9 ms·
Optimization Without Derivatives: Prima Fortran Version and Inclusion in SciPy
- enriquto 3y agoI'm gradually moving to (modern) Fortran, and it's just lovely to see all this activity. Fortran really reaches a sweet spot if all you want to do is write straightforward numerical algorithms that run reasonably fast.
- m_mueller 3y agoreasonably fast is a bit of an understatement IMO. I don't know another language that is as machine friendly AND at the same time allows for reasonably high productivity and can be understood by (non-Computer-) scientists.
- wiz21c 3y agoHow fast ? I gather, for example, that Intel's Fortran is a frontend to LLVM. So the speed of that Fortran can't be much different than anything compiled by LLVM such as rust or C. Correct ?
- cscheid 3y agoThe language semantics matter greatly. GHC with `-fllvm` is not going make Haskell any easier to compile just because it's targeting LLVM. Fortran is (relatively!) easy to make fast because the language semantics allow it to. Lack of pointer aliasing is one of the canonical examples; C's pointer aliasing makes systems programming easier, but high-performance code harder.
- pklausler 3y agoPointers in Fortran can alias with each other and with valid pointer targets. What makes Fortran potentially easier to optimize are its rules against dummy argument aliasing in most (but not all) cases. (See https://github.com/llvm/llvm-project/blob/main/flang/docs/Aliasing.md https://github.com/llvm/llvm-project/blob/main/flang/docs/Al... for the full story.)
- cscheid 3y ago> dummy argument aliasing Thanks for the precise Fortran terminology; that's what I meant to say in my head but you're correct. From the linked website for everyone else: "Fortran famously passes actual arguments by reference, and forbids callers from associating multiple arguments on a call to conflicting storage when doing so would cause the called subprogram to write to a bit of that storage by means of one dummy argument and read or write that same bit by means of another."
- m_mueller 3y agothe main question is: how fast after how much learnings and optimizations that went into the 'naive' version of the application. Just an example on how to declaring a couple of input float pointers in a fully optimized way, avoiding aliases and declaring it readonly (if I remember correctly, it's been a few years: Fortran: real(32), intent(in) :: foo, bar, baz C: const float *const restrict foo const float *const restrict bar const float *const restrict baz of course what happens then is that people will do a typedef and hide it away... and then every application invents its own standards and becomes harder to interoperate on a common basis. in Fortran it's just baked in. Another example: multidimensional arrays. In C/C++ it either doesn't exist, is not flat memory space (and thus for grid applications very slow), or is an external library (again restricting your interop with other scientific applications). In Fortran: integer, parameter :: n = 10, m = 5 real(32), dimension(n, m) :: foo, bar, baz Again, reasonably simple to understand, and it's already reasonably close to what you want - there are still ways to make it better like memory alignment, but I'd claim you're already at 80% of optimal as long as you understand memory layout and its impact on caching when accessing it (which is usually a very low hanging fruit, you just have to know which order to loop it over).
- messe 3y ago> Another example: multidimensional arrays. In C/C++ it [...] is not flat memory space (and thus for grid applications very slow) Can you clarify what you mean by this? A naively defined multidimensional array, float foo[32][32] = ... is stored in sizeof(float) * 32 * 32 = 4096 consecutive bytes of memory. There's no in-built support for array copies or broadcasting, I'll give you that, but I'm still trying to understand what you mean by "not flat memory space".
- int_19h 3y agoI think they meant dynamically sized multidimensional arrays (and arrays of pointers often used to emulate those). However, even then it's not quite true given C99 VLA.
- 3y ago
- GeompMankle 3y agoNegative. Fortran is in a better position to guarantee certain facts about sequential access in arrays and solid information about pointer aliasing that is generally not available in C or C++ unless the author of the C/C++ is extremely aware for compiler quirks and pragma. Fortran has a "just works" attitude to high speed array processing where as other languages are focused on edge cases that are good for PhD thesis on general computing optimization but rarely work in the easiest case without extensive pragmas. See also CUDA. Sure you can write a C to CUDA converter auto-vectorizer but its likely to have all sorts of bugs and usually never work right except in rare hand-tune cases. May as well just write CUDA from scratch if it is to be performant. Same for array processing, wanna array process? Use compiler for array processing like Fortran or ISPC.
- bee_rider 3y agoYou have to caveat “faster than C.” It is basically impossible to beat C with sprinkled in assembly or intrinsics as appropriate. Most people, even good C programmers, don’t write that kind of C, though. The point of Fortran is that you can write Fortran code that is almost as fast as that nightmare C, but you can do it and still get your degree on time.
- enriquto 3y ago> reasonably fast is a bit of an understatement IMO. I mean that a naive loop that traverses your data does not take several minutes like in Python. But there's a guy in my lab who takes my stupid loops, avxs the fuck out of them, and they become 8 times faster. Now, that's what you would call unreasonably fast (short of rewriting the whole thing for the GPU).
- m_mueller 3y agoFair enough. Btw. IMO rewriting for GPU (if you do have the hardware) can be quite a bit simpler than doing vector optimisations for CPU, depending on the codebase. Back in my research days I actually created a framework for doing just that with Fortran: https://github.com/muellermichel/Hybrid-Fortran https://github.com/muellermichel/Hybrid-Fortran.
- archermarks 3y agoI use fortran in my day to day work and most of my work has been modernizing and refactoring an oldish code. Its amazing how nice it can be to work in once you've removed and reorganized the legacy cruft.
- tpoacher 3y agoHow have you found the experience so far? I kinda tried this a few years back, but found the documentation/lack of modern tutorials appalling ... but there's been a nice explosion of activity over the last few years (e.g. fpm, lFortran), which makes me think this may have changed considerably. Also, any tips on nice ways/resources that helped you get (back) into it?
- sampo 3y ago> found the documentation/lack of modern tutorials appalling There isn't good modern Fortran textbooks/courses on the web. But there are some textbooks that cover the language well. Especially: Metcalf, Reid, Cohen: Modern Fortran Explained, 2018.
- zaikunzhang 3y ago1. The following recent book is a good reference: Milan Curcic, Modern Fortran: Building efficient parallel applications, Manning, 2020, https://www.manning.com/books/modern-fortran https://www.manning.com/books/modern-fortran 2. More references, online courses, and tutorials can be found at https://fortran-lang.org/en/learn/ https://fortran-lang.org/en/learn/ 3. If you have questions, Fortran Discourse is a good place to ask: https://fortran-lang.discourse.group/ https://fortran-lang.discourse.group/ People there are gurus of modern Fortran and are very willing to help.
- whinvik 3y agoGoing to the Github issue page and reading the exchange is fascinating. Most of the discussion is about licensing and through the thread you see it getting resolved! Also the author's dedication to Prof. Powell seems amazing. I know nothing about Prof. Powell but I am sure he would have much appreciated it.
- certik 3y agoThis is a very important effort: if SciPy accepts this modern Fortran codebase, then I think the tide for Fortran will change. My own focus is to compile all of SciPy with LFortran, we can already fully compile the Minpack package, here is our recent status update: https://lfortran.org/blog/2023/05/lfortran-breakthrough-now-building-legacy-and-modern-minpack/ https://lfortran.org/blog/2023/05/lfortran-breakthrough-now-... And we have funding to compile all of SciPy. If anyone here is interested to help out, please get in touch with me. Once LFortran can compile SciPy, it will greatly help with maintenance, such as on Windows, WASM, Python wrappers, even modernization later on.
- kergonath 3y agoI can’t really contribute, but it’s great to see developments around LFortran!
- ggraphilia 3y agoLFortran sounds to be a genenius project. The interactivity is a critical block that is missing from FORTRAN ecosystem. Hope things will get better with LFortran!
- zaikunzhang 3y agoThank you @certik for your encouragement! I cherish the following comment from you: > if SciPy accepts this modern Fortran codebase, then I think the tide for Fortran will change. I believe that you and the LFortran project are truly turning the tide on Fortran. I wish to see the production release of LFortran as soon as possible. If PRIMA can also contribute to “turning the tide on Fortran”, I will feel honored. All the pain, depression, and frustration that I have experienced in the past three years will then be partially compensated. Let us the community work together to get PRIMA included in SciPy and see whether the tide on Fortran will improve. Many thanks.
- Loic 3y agoI contacted you on your email address from your personal website.
- quickthrower2 3y agoWhy might it be goos to not use derivatives? Is it faster, easier? Are there some functions whose derivatives are not known or are too complicated?
- efavdb 3y agoYes sometimes it’s hard to measure a derivative. Eg when doing hyperparameter tuning in ML, you can read out a metric at a given choice of parameters, but it’s generally not easy to get a gradient. Shameless plug: I happen to have recently written a package for the opposite limit! It finds roots when you can only measure the derivative. https://github.com/EFavDB/inchwormrf https://github.com/EFavDB/inchwormrf
- quickthrower2 3y agoI assume backprop is still most efficient for the neural net itself, rather than one of these algorithms? I am doing a course and I am aware that there are other algorithms than gradient descent but haven’t seen the details yet on that. I know things like cross entropy loss are designed to be easy to differentiate and probably more efficient to do that than something that approximates it.
- efavdb 3y agoYeah, backprop gives efficient gradient calcs to train at a given net architecture. To find the best architecture though people try various other methods, eg random search or Gaussian processes, which don’t evaluate derivatives wrt architecture Params.
- imurray 3y agoYou might be interested in David MacKay's old conjugate gradient implementation in C that also only uses derivatives: https://www.inference.org.uk/mackay/c/macopt.html https://www.inference.org.uk/mackay/c/macopt.html (It was written in another time, don't expect it to be nice. My 20-year-old Octave/Matlab wrappers on that page have almost certainly bit-rotted, don't expect them to work.)
- RockyMcNuts 3y agoI think there are a few derivative-free global optimizers, curious what sets this one apart? see e.g. https://www.microprediction.com/blog/optimize https://www.microprediction.com/blog/optimize . If the current scipy-native one is unmaintained and this one is superior it certainly makes sense to update.
- icegreentea2 3y agoThe proposal isn't a "new" algorithm, rather a rewrite (plus bug fixes) of the existing scipy implementation of "COBYLA" (which I don't think it tested in your linked comparison).
- ckmiller 3y agoThese algorithms work best on smooth functions with mid-to-low 100's of variables. They are very sample efficient, often obtaining superlinear convergence using just a linear number of evaluations of the objective function.
- djoldman 3y agoPapers for the algos: [50] M. J. D. Powell. A direct search optimization method that models the objective and constraint functions by linear interpolation. In S. Gomez and J. P. Hennart, editors, Advances in Optimization and Numerical Analysis, pages 51–67, Dordrecht, NL, 1994. [53] M. J. D. Powell. UOBYQA: unconstrained optimization by quadratic approximation. Math. Program., 92:555–582, 2002. [56] M. J. D. Powell. The NEWUOA software for unconstrained optimization without derivatives. In G. Di Pillo and M. Roma, editors, Large-Scale Nonlinear Optimization, volume 83 of Nonconvex Optimization and Its Applications, pages 255–297, Boston, MA, USA, 2006. [58] M. J. D. Powell. The BOBYQA algorithm for bound constrained optimization without derivatives. Technical Report DAMTP 2009/NA06, Department of Applied Mathematics and Theoretical Physics, University of Cambridge, Cambridge, UK, 2009.
- domcoltd 3y agoGood coffee is needed to understand Powell’s papers on these algorithms. If you don’t have, section 3 of the following paper is a good place to start with: https://arxiv.org/pdf/2302.13246.pdf https://arxiv.org/pdf/2302.13246.pdf
- EVa5I7bHFq9mnYK 3y agoI remember using a program to find a function maximum using parabolic approximation on my programmable calculator in the 80s. Everything new is well forgotten old.
- V1ndaar 3y agoI'm surprised not to see a single mention of NLopt [0] in the discussion. I was under the impression most algorithms implemented in NLopt are in C and not using any Fortran77. But I'm sure the author knows something I don't (I've never really looked at NLopt's sources, but I've been using it for years). Anyhow, the more alternatives the merrier I suppose! [0]: https://nlopt.readthedocs.io/en/latest/ https://nlopt.readthedocs.io/en/latest/
- zaikunzhang 3y agoExtraction from https://github.com/libprima/prima https://github.com/libprima/prima “There do exist "translations" of Powell's Fortran 77 code into other languages. For example, NLopt contains a C version of COBYLA, NEWUOA, and BOBYQA, but the C code in NLopt is translated from the Fortran 77 code straightforwardly, if not automatically by f2c, and hence inherits the style, structure, and probably bugs of the original Fortran 77 implementation.” See also https://github.com/stevengj/nlopt/issues/501 https://github.com/stevengj/nlopt/issues/501 , where the author of NLopt talks.
- V1ndaar 3y agoAh, thanks!
- ckmiller 3y agoI'm very glad to see these algorithms get the maintenance they deserve. I pulled them apart and used lots of their pieces and theory for my PhD; MJD Powell's original code was subtle and difficult to understand. Hats off to those doing to the hard work of keeping them alive. These algorithms are the absolute best in their domain, and should be more widely known.
- domcoltd 3y agoGitHub repo of the project: https://github.com/libprima/prima https://github.com/libprima/prima
- genphy1976 3y agoThis is truly impressive! While I'm not well-versed in these specific techniques, I do recall learning about Powell during a mathematics course in the past. It's reassuring to know that capable individuals are maintaining his work. Some time ago, I attempted to update an antiquated FORTRAN program for a particular project, but regrettably, I had to abandon the effort. Navigating the labyrinth of countless GOTO statements was both challenging and disheartening. I became genuinely concerned about the potential impact on my mental well-being. That being said, I have a profound admiration for the individual who successfully modernized such a complex FORTRAN project. Their achievement is undoubtedly commendable!
- ZeroCool2u 3y agoWow, just a few weeks ago I wanted an optimization function in Python and was already using SciPy, so I reached for scipy.optimize and ran into quite a few of the bugs described first hand, which had me kind of rattled. I just assumed whatever optimizer SciPy uses would be reliable even if it's not completely optimal or cutting edge. I love the dedication these folks have to their old colleague too. They took a great deal of care in relicensing, so that SciPy could use their derived code even though the original author had passed. Nothing but admiration for them! Anyways, I was lucky enough that I could restrict my search space on some assumptions and just brute force the problem in very reasonable time, but this is quite timely for me and great to see!
- whimsicalism 3y agoFrom my experience with this (in 2018), scipys non-gradient optimizers are not very good/
- domcoltd 3y agoIndeed, the author mentions many bugs of the SciPy gradient-free solvers in the readme of the repo of Prima.
- NwtnsMthd 3y agoThe optimization libraries in SciPy are surprisingly bad. I've found Mystic to be a great alternative. https://github.com/uqfoundation/mystic https://github.com/uqfoundation/mystic
- nunuvit 3y ago> I just assumed whatever optimizer SciPy uses would be reliable That's usually a bad assumption for wrapped math libraries outside of the foundational ones like numpy. They tend to have a pretty low ratio of "mileage" to complexity in the first place, it's easy for the project to become a zombie without users realizing, and the layers of challenges to fixing issues leave many of them unresolved. If you need reliability, you'll have to deliberately choose software that's mature and actively maintained.
- zaikunzhang 3y agoWho was Powell? Michael James David Powell FRS was “a British numerical analyst who was among the pioneers of computational mathematics” [1]. He was the inventor/early contributor of Quasi-Newton method, Trust-Region method, Augmented Lagrangian method, and SQP method [1,2]. Each of them is a pillar of modern numerical optimization. He also made significant contributions to approximation theory and methods [1,2,3]. Among numerous honors, Powell was one of the first two recipients of the Dantzig Prize [4] from the Mathematical Programming Society/Society for Industrial and Applied Mathematics (SIAM). This is considered the highest award in optimization. See also his Google Scholar profile [5] and the memorial page at [6]. [1] https://royalsocietypublishing.org/doi/full/10.1098/rsbm.2017.0023 https://royalsocietypublishing.org/doi/full/10.1098/rsbm.201... [2] https://en.wikipedia.org/wiki/Michael_J._D._Powell https://en.wikipedia.org/wiki/Michael_J._D._Powell [3] https://www.cambridge.org/highereducation/books/approximation-theory-and-methods/66FD8CD6F18FE1ED499A8CA9A05F2A5A https://www.cambridge.org/highereducation/books/approximatio... [4] https://en.wikipedia.org/wiki/Dantzig_Prize https://en.wikipedia.org/wiki/Dantzig_Prize [5] https://scholar.google.com/citations?user=p3kDmy0AAAAJ&hl https://scholar.google.com/citations?user=p3kDmy0AAAAJ&hl [6] https://www.zhangzk.net/powell.html https://www.zhangzk.net/powell.html
- onos 3y agoCool, thanks so much for this info. I only knew the name from scipy, where one of the optimization method options carries his name. Good to learn more … and wow what a contribution.
- domcoltd 3y agoThe extensive tests made by GitHub actions are simply amazing.
- zaikunzhang 3y agoThe extensive tests are vital in this project. The tests do not only verify the faithfulness of the implementation but also check that the solvers behave properly even if they are invoked with improper inputs or encounter failures of function evaluations.
- genphy1976 3y agoThese people https://arxiv.org/pdf/1307.5867.pdf https://arxiv.org/pdf/1307.5867.pdf use Powell's derivative-free optimization method (newuoa) in the study of the galaxy cluster MACS J1206.2-0847 ( https://it.wikipedia.org/wiki/MACS_J1206.2-0847 https://it.wikipedia.org/wiki/MACS_J1206.2-0847 ). This is so cool!
- ggraphilia 3y ago“Renowned for their robustness and efficiency, these solvers are used in a wide spectrum of applications, for instance, aeronautical engineering [25], astronomy [39], computer vision [33], robotics [40], and statistics [5].” These algorithms seem truly used in science and engineering. [5] D. M. Bates, M. Mächler, B. Bolker, and S. Walker. Fitting linear mixed-effects models using lme4. J. Stat. Softw., 67:1–48, 2015. [25] F. Gallard et al. GEMS: a Python library for automation of multidisciplinary design optimization process generation. In 2018 AIAA/ASCE/AHS/ASC Structures, Structural Dynamics, and Materials Conference, Kissimmee, FL, USA, 2018. AIAA. [33] H. Izadinia, Q. Shan, and S. M. Seitz. IM2CAD. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 5134–5143, San Juan, PR, USA, 2017. IEEE. [40] K. Mombaur, A. Truong, and J. P. Laumond. From human to humanoid locomotion—an inverse optimal control approach. Auton. Robot., 28:369–383, 2010. [39] G. A. Mamon, A. Biviano, and G. Boué. MAMPOSSt: modelling anisotropy and mass profiles of observed spherical systems I. Gaussian 3D velocities. Mon. Not. R. Astron. Soc., 429:3079–3098, 2013.
- zaikunzhang 3y agoI have some funding available if someone here would like to undertake the project of getting PRIMA into SciPy, although the person must come to work at my university in Hong Kong, as the funding cannot be used online/abroad. I can open a research assistant or postdoc position for the project. My contact can be found at https://github.com/libprima/prima https://github.com/libprima/prima . Thanks.
- blt 3y agoIt sounds like this was a difficult task. The motivation to fulfill Prof. Powell's request and help the community of derivative-free optimization users must have been strong. Congratulations on your achievement! From the GitHub README: > In the past years, while working on PRIMA, I have spotted a dozen of bugs in reputable Fortran compilers and two bugs in MATLAB. Each of them represents days of bitter debugging, which finally led to the conclusion that it was not a problem in my code but a flaw in the Fortran compilers or in MATLAB. From a very unusual angle, this reflects how intensive the coding has been. > The bitterness behind this "fun" fact is exactly why I work on PRIMA: I hope that all the frustrations that I have experienced will not happen to any user of Powell's methods anymore. I hope I am the last one in the world to decode a maze of 244 GOTOs in 7939 lines of Fortran 77 code — I have been doing this for three years and I do not want anyone else to do it again. https://github.com/libprima/prima#a-fun-fact https://github.com/libprima/prima#a-fun-fact
- genphy1976 3y agoNo, it is not difficult. It is way more than that. It is frustrating and depressing according to my experience attempting to modernize a FORTRAN 77 codebase (I gave up finally). Navigating through a quagmire of GOTO statements felt like a desperate endeavor. It's hard to fathom how someone could work on such a project for three years, especially if it appears to be a solo effort. Upon examining the original FORTRAN code and accompanying papers, I realized that the complexity of the task was far from trivial. Working alone for three years, especially on such a complex codebase, requires a significant amount of dedication and perseverance.
- domcoltd 3y agoComment from Reddit: https://www.reddit.com/r/programming/comments/13k74ro/optimization_without_using_derivatives_the_prima/ https://www.reddit.com/r/programming/comments/13k74ro/optimi... “Finally, a fortran package not written in Fortran77 but one trying to be approachable and maintainable rather than the product of unhappy PhD students spending many months to eke out a little more in an incomprehensible, Oracle-comparable mess.”
- zaikunzhang 3y agoSee also SciPy: Interested in adopting PRIMA, but little appetite for more Fortran code, https://news.ycombinator.com/item?id=35986906 https://news.ycombinator.com/item?id=35986906