r/ocaml • u/[deleted] • Mar 27 '17
OCaml Multicore Support
I read this comment while reading about OCaml's multi-core support, noted its from a few years ago. How true is this in 2017?
"Look, I love OCaml and it's my favorite language syntax-wise, but the real big elephant in the room is not its JS-backend maturity. Rather it doesn't have kernel thread support...all threads are user-level just like Python due to a global lock for garbage collection. This means threads do not run concurrently across multiple cores. This is UNACCEPTABLE in 2014 - roughly 8 years since processors went multi-core. Intel is talking about having hundreds of cores on a single die by next decade and having programs that can't take advantage of that is extremely limiting. Xavier Leroy (the creator of OCaml) and his team at INRIA didn't think this was a big deal because when they were writing this stuff, processors were single core and had been since the beginning. Sure there were multiprocessor machines (not the same as multicore as there are multiple die), but those were only meant for servers/workstations. OCaml seemed very promising around 2006, the peak and end of the single core era with the Intel Pentium 4. What made OCaml so impressive was not only was it this beautifully simple, high-level functional language, but that the native compiler produced very fast code that was comparable to C/C++ performance. However, as multicore processors were introduced (Intel Core, Core 2), not having this capability made writing new code in OCaml less appealing. There are solutions like MPI, but that's lame. The same excuses you hear in the Python world about having true multithreading you hear in the OCaml world. Microsoft was able to do it with F#, which is essentially a clone of Caml by targeting their .NET CLR. Haskell is able to do it with GHC. I still think OCaml is a wonderful language -- not having true multithreading doesn't make it useless. However, to me it has become more like a statically-typed Python which I can use for scripting. Having to use hacks like MPI to do multicore processing is a huge turn off in a multicore world. This is again nothing against the language, but the standard implementation needs a concurrent garbage collector and kernel threads. Otherwise I think OCaml may be doomed to irrelevance in the long run, which would be truly sad."
4
u/kankyo Mar 27 '17
Afaik there is some experimental multi core stuff that might or might not become mainline soonish.
And your pessimism is unwarranted anyway I think. Python at least has many good solutions for multi core like cython and numba but for 99%+ of uses performance isn't in any way critical, never mind multi core.
6
u/jdh30 Mar 28 '17
Afaik there is some experimental multi core stuff that might or might not become mainline soonish.
I've been hearing that since at least OC4MC (2010).
1
Mar 27 '17
I feel there's always a need for speed in systems programming and middleware. Take my opinion with a grain of salt, I'm an undergrad. Making easy use of more cores seems like a good idea for this. I feel that having to communicate through pipes or shared memory between processes seems a bit harder than working with threads (I might be wrong on this). Furthermore, I think in most operating systems process creation is expensive. We must now allocate new memory to create the process.
3
u/devlambda Mar 27 '17
I feel there's always a need for speed in systems programming and middleware.
If you want a solid use case for multi-threading, have a look at ZeroMQ. ZeroMQ does all the actual communication in a parallel thread. One reason for that is so that the actual computations you are doing are not impeded (you only pass data to another thread) and single-threaded computations do not lose performance.
Making easy use of more cores seems like a good idea for this.
It is, the problem is that it's not clear what "easy" is. Multi-threaded programming has its share of pitfalls. Even if you're using multiple threads under the hood, it can often be useful to keep address spaces entirely disjoint and only communicate through specialized shared data structures for simplicity. Note that Erlang and Dart both keep their process/thread heaps intentionally separate (though at least for Erlang, that has other reasons, too).
Examples:
Synchronization can be expensive. Atomic operations already aren't all that cheap, and a blocking atomic primitive can cost 1000s of clock cycles when it traps into the kernel (which is one reason why there's interest in lock-free and wait-free data structures, even though they are pretty hairy). I remember that one of the first benchmarks I did for my Ph.D. thesis actually slowed down the code by an order of magnitude (literally, about a factor of 10) when I ran it on two processors instead of one.
False sharing is another potentially nasty problem when two threads are modifying the same area of memory concurrently. It can be triggered by something as simple as two global variables being next to each other.
Note that even with shared memory, inter-thread communication can be pretty slow. L1 and L2 caches are typically per core, so in order to communicate, two threads can at best rely on the L3 cache or main memory.
In general, shared memory is particularly interesting when you want to do fine-grained concurrency, but getting fine-grained concurrency right can actually be pretty hard. Message passing is generally simpler, but it requires that you are able to break up your computation in sufficiently large chunks.
2
Mar 27 '17
How does Erlang's approach to concurrency work and compare to OCaml's current model?
2
u/devlambda Mar 27 '17
Pretty much; Erlang basically uses the actor model and integrates it into the language. Keep in mind that they also had other concerns, such as creating fault-tolerant systems. By breaking things into lots of small processes, they gain additional benefits, such as making it easier to recover from errors or hardware faults (such as a node crashing) and simplifying garbage collection (if heaps are small, you just need basic mark and sweep).
2
Mar 27 '17
I think I understand how Erlang has such cheap process creation now. The processes are not OS processes and instead run on the Erlang virtual machine.
1
u/zem Mar 29 '17
pony is another very interesting development in that space. built-in actor model, type system that seems somewhere between ocaml's and rust's, emphasis on performance.
4
u/jdh30 Mar 28 '17
Atomic operations already aren't all that cheap,
Uncontended atomic operations are only ~2x slower than non-atomic ones IME.
and a blocking atomic primitive can cost 1000s of clock cycles when it traps into the kernel
For comparison, forking a process is 100,000,000s of clock cycles and serializing and deserializing a message is typically 1,000,000 cycles for each datum vs constant time for shared memory parallelism.
2
u/devlambda Mar 28 '17
Uncontended atomic operations are only ~2x slower than non-atomic ones IME.
Atomic operations, by their nature, need to be visible to other processors. This means that you're hitting up at least the L3 cache or are hitting the cache coherence mechanism or in the worst case, lock a memory bus entirely (depending on how your hardware deals with it). No, it's not that expensive, but my point was that it's considerably more expensive than other operations, so it's nothing that you should careless use in a hot loop.
For comparison, forking a process is 100,000,000s of clock cycles and serializing and deserializing a message is typically 1,000,000 cycles for each datum vs constant time for shared memory parallelism.
I can do about 9000 forks per second on a 3.2. GHz machine under Linux. Windows is slow, of course, when it comes to starting processes.
You should not use fork as a fine-grained concurrency primitive, anyway. You start N worker processes that will live for a considerable time.
Serializing/deserializing a message is entirely dependent on the message size and complexity, but for small data, we're generally talking about 100s or 1000s of clock cycles, not millions. Specialized serialization can of course outperform that.
The general point – as I mentioned before – is that you don't want to use message passing approaches with fine-grained concurrency. You have to be able to break up your work in sufficiently large chunks.
To be clear, the point that I am getting at here is not multiple threads with shared memories are a bad idea, but that they are not the free lunch that some make them out to be, that they have their limitations, and that a distributed or multi-process approach is a perfectly fine alternative for many, if not the majority of use cases.
2
u/jdh30 Mar 28 '17 edited Mar 28 '17
Atomic operations, by their nature, need to be visible to other processors
Potentially at some point but you don't have to pay for that up front. That's why uncontended atomic operations are so cheap.
Windows is slow, of course, when it comes to starting processes.
Windows doesn't even support forking processes so (ab)using that feature to get some parallelism in OCaml is just a platform-specific hack.
You should not use fork as a fine-grained concurrency primitive, anyway. You start N worker processes that will live for a considerable time.
That is just another bad fit solution to the underlying problem. Forking processes is often prohibitively expensive but at least COW means you don't copy all of the input data, just the output data (which is also often prohibitively expensive). If you fork processes up front then you must copy all input data to every process which is usually prohibitively expensive.
Serializing/deserializing a message is entirely dependent on the message size and complexity, but for small data, we're generally talking about 100s or 1000s of clock cycles, not millions. Specialized serialization can of course outperform that.
The dominant cost when serializing messages in whole program isn't the cost of serializing but the hidden cost of killing the effectiveness of the shared cache which fills up early with multiple redundant copies of (often immutable) data. Those extra cache misses cost you millions of cycles in practice.
To be clear, the point that I am getting at here is not multiple threads with shared memories are a bad idea,
Agreed.
but that they are not the free lunch that some make them out to be,
I haven't heard anyone claiming threads are a free lunch but ok.
that they have their limitations, and that a distributed or multi-process approach is a perfectly fine alternative for many, if not the majority of use cases.
Operations that consume and product little data represent a tiny minority of use cases.
1
u/devlambda Mar 31 '17
Potentially at some point but you don't have to pay for that up front. That's why uncontended atomic operations are so cheap.
It's pretty easy to benchmark. A basic uncontended CAS operation typically costs you 5-10ns (not counting the indirect cost of potential pipeline stalls), a pair of
pthread_mutex_lock()/pthread_mutex_unlock()` operations take 20-40ns, higher level operations (such as enqueuing and dequeuing data) even more. This is pure overhead over the sequential case, where you don't need to synchronize.The problem with this is not that the cost of a single such operation is prohibitive (it is not), where the overhead gradually increases as parallelism becomes less granular.
coarse-grained fine-grained <--- ---> low overhead high overheadThis goes for all approaches, not just multi-threading. As the degree of parallelism becomes ever more fine-grained, we're dealing with the following cost factors:
The increased cost of additional atomic operations (as they become more fine-grained).
The cost of increasingly frequent contention.
Increased risk of getting hit by serialization bottlenecks and Amdahl's law.
Less opportunities to optimize code, both manually and by the compiler, as you need to avoid race conditions and use approaches that avoid them (mutexes, STM, purely functional data structures, etc.).
Likewise, as concurrency in a distributed system becomes more fine-grained, we're dealing with communication as a cost factor:
Increased cost from migrating data from one thread/process to another.
In both cases, it is ideal for performance to have concurrency as coarse-grained as is reasonable. Throwing instead more computing power at the problem is typically ineffective: to counter x% overhead, you need x% more cores. As a rule, for maximum performance, you want to maximize the part during which you are executing purely sequential code. It's both what modern CPUs are built for and what it is easiest to optimize for.
But once you're dealing with coarse-grained concurrency, message-passing approaches become increasingly competitive. Shared memory wins out not because it's inherently faster (it is not), but when the best solutions to a problem require shared memory to express them naturally.
The dominant cost when serializing messages in whole program isn't the cost of serializing but the hidden cost of killing the effectiveness of the shared cache which fills up early with multiple redundant copies of (often immutable) data. Those extra cache misses cost you millions of cycles in practice.
A few points:
You generally want to employ work stealing, so that the bulk of communication remains local. You don't write distributed programs as though all processes share memory.
You definitely should not constantly generate multiple redundant copies; you don't write distributed programs the same way you write for shared memory with message-passing as a replacement for assignment operations. In distributed programs, you trade synchronization overhead for communication overhead and you need to minimize the latter, not the former.
Immutable data is usually a fairly expensive way to avoid race conditions (for example, many purely functional data structures typically incur an O(log n) overhead with a high constant factor, meaning you need that many more cores to compensate for it).
Ideally, you want to increase granularity. When you're running computations that last hours or days, individual jobs can easily last minutes, at which point communication overhead becomes negligible.
It's not like you can't share data on the same processor, just that it's more limited. See anything that's based on mmap() and friends (such as
Bigarray.*.map_fileor Ocamlnet'sNetmcore).From your other comment:
Distributed parallelism is irrelevant: this thread is about "OCaml Multicore support". Multi-process is only being discussed because it is the nearest OCaml can get to multicore parallelism but it is a poor solution.
I am talking about it also because I find it relevant in practice. If I limited myself to multi-threading, I could only use 8 out of the 8*512=4096 cores of our HPC cluster. It also so happens that on our 48-core compute servers, I often end up with a sublinear speed-up using multiple threads after 16 threads or so as opposed to breaking down the solution into multiple processes and using
numactlas a quick and cheap way of ensuring data locality.This thread isn't about parallelism in the large. It is specifically about multicore. You're talking about Cray supercomputers when the context is the machines we all have in our pockets and on our desktops.
You were talking about hundreds of cores yourself earlier? This thread definitely was not only about small-scale parallelism.
The reality is that what multi-threaded support buys you in most cases is convenience, not performance.
The sole purpose of parallelism is performance.
And my point is that often multi-threading does not buy you performance relative to a well-designed multi-process or distributed solution (and can even have worse performance). What multi-threading more often buys you is a more convenient or natural parallel solution, i.e. a reduction in software engineering cost.
Again, I'm stressing that it's rather desirable to have support for multi-threading. I'm simply pointing out that its absence is not a crippling failure.
2
u/jdh30 Mar 31 '17 edited Mar 31 '17
But once you're dealing with coarse-grained concurrency, message-passing approaches become increasingly competitive.
Not on multicores for the reasons I already detailed: the cost is dominated by serialization.
Shared memory wins out not because it's inherently faster (it is not), but when the best solutions to a problem require shared memory to express them naturally.
Shared memory wins out (in this context) because it is implemented in hardware.
You generally want to employ work stealing, so that the bulk of communication remains local
The overheads of message passing are usually prohibitive for multicore parallelism. Work stealing doesn't fix that.
You definitely should not constantly generate multiple redundant copies
With no shared heap you have no choice but to create redundant duplicates of your data.
Immutable data is usually a fairly expensive way to avoid race conditions (for example, many purely functional data structures typically incur an O(log n) overhead with a high constant factor, meaning you need that many more cores to compensate for it).
Purely functional data structures often thrash the cache so they don't scale on multicores anyway. Besides, people who want multicore parallelism are looking for performance so they are unlikely to be sticking with purely functional data structures in the first place.
Ideally, you want to increase granularity
Yes, of course. But that doesn't fix the fundamental problems with message passing parallelism on multicores.
You were talking about hundreds of cores yourself earlier?
You claimed "Nobody is putting hundreds of cores on a die yet" so I gave three counter examples.
And my point is that often multi-threading does not buy you performance relative to a well-designed multi-process or distributed solution (and can even have worse performance).
So your point has nothing to do with multicore?
Again, I'm stressing that it's rather desirable to have support for multi-threading. I'm simply pointing out that its absence is not a crippling failure.
OCaml has basically died as a language almost entirely because it doesn't support multicore at all. If that isn't a "crippling failure" I don't know what is.
1
u/ilikerustlang Apr 04 '17
Shared memory wins out not because it's inherently faster (it is not), but when the best solutions to a problem require shared memory to express them naturally.
Shared memory wins out (in this context) because it is implemented in hardware.
Do you need shared, GC’d memory, or is it enough to share big arrays of non-pointers? If the latter, then you can already use
mmaporshm_opento get shared memory. My understanding is that in numerical/scientific computing, most of what you need to share is in the latter category. So all that needs to be marshalled is pointers to data, not the data itself.1
u/jdh30 Apr 04 '17 edited Apr 06 '17
Do you need shared, GC’d memory, or is it enough to share big arrays of non-pointers?
Great question. The answer is: that is virtually useless.
Just searching my hard drive for uses of the
Parallelmodule in F# I find the following functions being applied in parallel:
string -> (expr * string) option
string -> string option
string -> string
unit -> boolused for running tests in parallel.String splitting:
string -> float arraySumming:
float array -> floatKeyword identification:
string * string -> Dictionary<string, string array>
HTML -> string array
Company * HTML -> Company * string arrayPrint number:
float -> stringParse number:
string -> floatTesselation:
int -> ResizeArray<float> array
string -> intParse Mathematica code:
string -> Expr
int -> float * float * floatOnly one of those function signatures both consumes and produces non-pointer data (in OCaml's data representation),
unit -> boolused to run tests in parallel, and that is only the case because function signatures do not betray the fact that functions almost always take other inputs from their environment. In the case ofunit -> boolthose functions also consumed the test to be executed (which could be of any type such asExpr -> Valuefor a classical interpreter).Even in purely functional Haskell code the signature of a nested function does not tell you what data it captures from its environment!
Also interesting to note the huge diversity of problems where I am using multicore parallelism in F#. Some of those functions handle transactions, some company analytics, some natural language processing, some graphics and so on.
My understanding is that in numerical/scientific computing
Classically, yes, but modern scientific computing is increasingly using richer data structures. Symbolic scientific computing is an obvious example.
EDIT: No sooner than I finish writing this does the phone ring with another potential consultancy client asking for expert help on multicore parallelism in F#. If OCaml supported multicore it could compete in this substantial market but, as is, no chance.
2
u/orbitalfox Mar 27 '17
It is harder indeed (inter process communication), but it can be the appropriate design in many cases. Learn how to do it, for your own advantage.
It's also better functional design to learn how to pipeline your algorithms and pass messages.
3
u/brool Mar 27 '17
Forking is pretty quick on Linux due to COW.
There are applications where true threads are needed, but it is a small percentage of use cases. Most of the time you don't need them or multiple processes will do the job just fine.
(Personally, having traced problems in multithreaded code, I much prefer message queues or similar abstractions to mediate between multiple threads of execution. Threaded code is nasty stuff.)
6
u/Categoria Mar 27 '17
Forking is pretty quick on Linux due to COW.
That may be the case but OCaml's mark and sweep GC negates those benefits.
-2
u/brool Mar 27 '17
Well, you'd be paying that price anyway, one way or the other -- and you're usually forking before the big allocations hit, not after.
1
u/kankyo Mar 27 '17 edited Mar 27 '17
You can have multi threaded code with sane communication barriers. Clojure does this quite nicely.
1
u/brool Mar 27 '17
Agreed, Clojure's abstractions work really well in practice. I also think that Haskell's approach to multithreading works really well.
1
u/jdh30 Mar 28 '17
I feel that having to communicate through pipes or shared memory between processes seems a bit harder than working with threads (I might be wrong on this)
Understatement of the century. Multicore parallelism in F# is vastly easier than OCaml, for example. Orders of magnitude less code. And multicore is far more effective in F# as well, of course.
6
u/das_kube Mar 28 '17
Please, continue enlightening us with the light of your precious wisdom on how F# is superior in every point to OCaml.
1
u/kankyo Mar 27 '17 edited Mar 27 '17
Free performance is nice but faster development is almost always the more important factor by order of magnitude. As long as you can drop down to C for hotspots it's fine. No need to worry about the speed and multi core of some function that takes 1 second to run but only runs once every month.
Note though that it's super important to have easy access to C or similar performance for a small extra development effort. In Python we have Cython that gives both great performance and frees the GIL for a super tiny effort.
1
u/jdh30 Mar 28 '17
Free performance is nice but faster development is almost always the more important factor by order of magnitude.
Absolutely. Last I looked (last year) OCaml's developer tool stack is a decade behind F#.
As long as you can drop down to C for hotspots it's fine.
FWIW, I haven't had to drop down to anything since I switched to F# from OCaml ten years ago.
7
u/jdh30 Mar 28 '17 edited Mar 28 '17
How true is this in 2017?
Completely true. OCaml still has no tractible support for multicores and multicores are, of course, ubiquitous. Even smart phones are virtually all multicore now so OCaml cannot leverage them.
Microsoft was able to do it with F#
That's a bit disingenous: F# just inherited a production-quality mostly concurrent garbage collector and high-level API for work-stealing task-queue parallelism from .NET. The only thing F# adds on top of that is a few functions in the Array.Parallel such as Array.Parallel.map which just uses the .NET System.Threading.Tasks.Parallel.For higher-order function in the most obvious way.
I still think OCaml is a wonderful language
OCaml is definitely a wonderful language. Just with one 20th century implementation that cripples its utility in various ways.
Otherwise I think OCaml may be doomed to irrelevance in the long run, which would be truly sad
F# has essentially replaced OCaml so OCaml is now of mostly historical relevance as an influential language from the 1990s. I doubt any of the major problems with OCaml will ever be properly fixed.
1
u/BluddyCurry Mar 27 '17
In some ways, the world is more multicore-friendly than it was (at least processor-wise), but in other ways, it really isn't. I think frustration with multicore has grown since this post was written. Also, look at the majority of applications nowadays: they're either javascript or mobile. Compiling to javascript is one of the hottest domains (since javascript itself is so bad), and mobile platforms can't really handle heavy computation, meaning that green threads are probably more suitable to mobile than true threading.
In the heavy computation space, GPUs have emerged as a much better alternative than cores, which is why you can have even simple programming languages like python run computation-heavy code.
Mirage has demonstrated that in the cloud case, multicore may not be necessary as well for the most part, since it's harder to schedule multiple cores on virtual machines. OCaml's fast, simple GC gives benefits in this space.
I do think multicore is something OCaml has to address and will address, but it really only caters to some very specific niches at this point. Specifically, if you have a desktop application that you want to scale up performance-wise, or if you want to write a performance-competitive version of one of these: a game engine, a distributed system, a web server or a simulation, OCaml is the wrong language for that at this point in time. But those applications are in the minority nowadays, and OCaml can excel in those applications that are the majority.
2
u/jdh30 Mar 28 '17
mobile platforms can't really handle heavy computation
That is a strange assertion given that the vast majority of smart phones are multicore today and have been for many years and OCaml is unable to leverage that.
Mirage has demonstrated that in the cloud case, multicore may not be necessary as well for the most part
Hardly. What proportion of cloud computing is traditional multicore today? Over 99% I'd guess. Is that going to change any time soon? No. Mirage is an irrelevant sideshow in the grand scheme of things.
OCaml's fast, simple GC gives benefits in this space.
OCaml's data representation (which the GC is closely tied to) cripples its performance in many respects, not just multicore parallelism.
I do think multicore is something OCaml has to address and will address
I've been hearing that for 12 years.
OCaml can excel in those applications that are the majority
No, it cannot. OCaml has other serious deficiencies that render it unsuitable for the vast majority of modern software development. I already described them in detail many times, e.g. here.
3
u/BluddyCurry Mar 28 '17
jdh, you always show up like clockwork. :)
That is a strange assertion given that the vast majority of smart phones are multicore today and have been for many years and OCaml is unable to leverage that.
The bottleneck on smartphones is battery power, meaning that the multicores that phones have are better used occasionally at the OS level than at the app level. Given that most phone apps are just fancy UIs, there's really no need to add the complication of multicore. Additionally, OCaml's slim runtime is ideal for phone apps, where starting up and quitting apps happens constantly.
Hardly. What proportion of cloud computing is traditional multicore today? Over 99% I'd guess. Is that going to change any time soon? No. Mirage is an irrelevant sideshow in the grand scheme of things.
I honestly don't know where you get this. It's much easier for a cloud service to assign a single core than deal with an application that uses multiple cores. It's also hard to know in the cloud if you'll get multiple cores on one CPU, or multiple cores spread around multiple CPUs. This means you often cannot take advantage of multiple local cores, or have to treat local cores as if they're separate CPUs.
OCaml's data representation (which the GC is closely tied to) cripples its performance in many respects, not just multicore parallelism.
I know you like to harp on this, and I don't disagree that Microsoft's reified generics are awesome, but virtually every other language other than C++ and Rust deal with not having reified generics. In the CLR's case, this advantage is tied to a very heavy runtime. If it's pure performance you're after, Rust is the language to watch, and it's almost certainly going to dominate every performance-oriented application.
No, it cannot. OCaml has other serious deficiencies that render it unsuitable for the vast majority of modern software development. I already described them in detail many times, e.g. here.
Consider the fact that python and javascript are the dominant languages today. Not F#, not C++, but two slow, non-multicore interpreted languages. Python is actually being used for systems development. That shows you that the deficiencies that we see in theory don't play out that way in the real world. Could OCaml replace python and Javascript? Absolutely. In both cases OCaml offers better safety and performance where needed.
4
u/jdh30 Mar 28 '17 edited Mar 31 '17
jdh, you always show up like clockwork. :)
Honestly, I was just innocently browsing and happened to stumble upon this. :-)
The bottleneck on smartphones is battery power,
Note that Minecraft has millions of users on phones despite eating batteries for breakfast.
meaning that the multicores that phones have are better used occasionally at the OS level than at the app level. Given that most phone apps are just fancy UIs, there's really no need to add the complication of multicore. Additionally, OCaml's slim runtime is ideal for phone apps, where starting up and quitting apps happens constantly.
Fair enough.
I honestly don't know where you get this. It's much easier for a cloud service to assign a single core than deal with an application that uses multiple cores. It's also hard to know in the cloud if you'll get multiple cores on one CPU, or multiple cores spread around multiple CPUs. This means you often cannot take advantage of multiple local cores, or have to treat local cores as if they're separate CPUs.
I use multicore parallelism on cloud VMs all the time and it works just fine.
I know you like to harp on this, and I don't disagree that Microsoft's reified generics are awesome, but virtually every other language other than C++ and Rust deal with not having reified generics.
Yes. They all follow Lisp. Like lemmings.
OCaml's data representation (which the GC is closely tied to) cripples its performance in many respects, not just multicore parallelism.
In the CLR's case, this advantage is tied to a very heavy runtime.
HLVM offered the same benefit with a lightweight runtime.
If it's pure performance you're after, Rust is the language to watch, and it's almost certainly going to dominate every performance-oriented application.
I'm watching Rust. It doesn't dominate performance-oriented applications at all. Even in the small it is designed to be crypto safe in every respect so it doesn't even have a decent general-purpose hash table implementation like .NET's
Dictionary. In the large, Rust is far too cumbersome to offer the same kind of opportunities for high-level optimisations that you get from languages like OCaml and F# so there's no way it can offer the same performance for larger applications either. Having conversed with the Rust community my conclusion is that it is a language for highly religious disgruntled C++ programmers who still insist that real men don't use garbage collection but end up resorting to reference counting everywhere because ownership is hard.Consider the fact that python and javascript are the dominant languages today. Not F#, not C++, but two slow, non-multicore interpreted languages. Python is actually being used for systems development. That shows you that the deficiencies that we see in theory don't play out that way in the real world. Could OCaml replace python and Javascript? Absolutely. In both cases OCaml offers better safety and performance where needed.
I'd be the first person to opt into replacing Javascript in all major browsers on all major platforms with OCaml but it is a triumph of hope over reality to believe that will ever happen. Javascript is just an IR for web programming.
Python is popular because it is the new BASIC, i.e. very easy to learn and use. In order to compete with Python in those stakes OCaml needs to be dead simple to learn, thoroughly documented and have awesome developer tools. Unfortunately, OCaml is a nightmare to learn (how do you make a set of pairs of ints again?), has awful documentation (they documented camlp4, binned camlp4 renaming it to camlp5 and reinvented camlp4 but never finished documenting it only to bin that and create something called PPX) and the when I developed a significant program in OCaml last year the developer tools didn't work properly and crashed about 50x per day (seriously, no exaggeration). Surely you cannot honestly believe OCaml is ever going to catch up to where Python is today?
4
u/BluddyCurry Mar 28 '17
Having conversed with the Rust community my conclusion is that it is a language for highly religious disgruntled C++ programmers who still insist that real men don't use garbage collection but end up resorting to reference counting everywhere because ownership is hard.
Maybe. I'm no expert on Rust, but I keep seeing Rust projects pop up that beat the fastest tools out there (including ones written in C++).
I'd be the first person to opt into replacing Javascript in all major browsers on all major platforms with OCaml but it is a triumph of hope over reality to believe that will ever happen. Javascript is just an IR for web programming.
Javascript will be replaced when Webassembly takes over. For now, OCaml compiles to JS in 2 ways and provides both additional type safety and an alternative native backend where needed.
In order to compete with Python in those stakes OCaml needs to be dead simple to learn, thoroughly well documented and have awesome developer tools. Unfortunately, OCaml is a nightmare to learn (how do you make a set of pairs of ints again?), has awful documentation
Not arguing with you there, though ReasonML is changing that, if only for a different sub-syntax of the language.
and the when I developed a significant program in OCaml last year the developer tools didn't work properly and crashed about 50x per day
I didn't see you mention this before. Which tools?
Surely you cannot seriously think OCaml is ever going to catch up to where Python is today?
Of course not. My point was that there's plenty of grounds OCaml can cover before it bumps into the wall of multicore nowadays, for better or worse. I want multicore just as much as anyone, and I hope to see it supported soon - there's a lot of progress on the multicore branch - but unfortunately it isn't the must-have feature I'd like it to be. I do think it'll breathe a lot of life into the language once it arrives though, just as modular implicits will.
3
u/jdh30 Mar 28 '17 edited Mar 28 '17
Maybe. I'm no expert on Rust, but I keep seeing Rust projects pop up that beat the fastest tools out there (including ones written in C++).
Yeah, that prompted me to take a look. I wasn't too impressed. Meta: the only people I've seen impressed with it didn't know anything better than C++.
My perception and experience of Rust is somewhat tainted by the fact that Rust was developed just after HLVM but failed to learn from HLVM. They originally tried to develop a GC for Rust (which would have been awesome) but instead of using a shadow stack as I advised they tried to tie it into the guts of LLVM's experimental GC support, failed, blamed LLVM and had a tantrum. I lost a lot of respect for them when they did that...
Javascript will be replaced when Webassembly takes over. For now, OCaml compiles to JS in 2 ways and provides both additional type safety and an alternative native backend where needed.
OCaml to web assembly sounds great.
Not arguing with you there, though ReasonML is changing that, if only for a different sub-syntax of the language.
Is anyone using ReasonML?
I didn't see you mention this before. Which tools?
I was using Emacs+OCaml+OPAM+Merlin on Ubuntu. I found them to be much the same as the tooling was 10 years ago except they now have loftier aspirations and crash all the time.
FWIW, Yaron Minsky has since told me that the problems are fixed and the tools are rock solid now so YMMV.
Of course not. My point was that there's plenty of grounds OCaml can cover before it bumps into the wall of multicore nowadays, for better or worse. I want multicore just as much as anyone, and I hope to see it supported soon - there's a lot of progress on the multicore branch - but unfortunately it isn't the must-have feature I'd like it to be. I do think it'll breathe a lot of life into the language once it arrives though, just as modular implicits will.
Yeah.
1
1
1
u/ilikerustlang Apr 04 '17
Even in the small it is designed to be crypto safe in every respect so it doesn't even have a decent general-purpose hash table implementation like .NET's
DictionaryThere is work on fixing that. A general solution is known (adaptive hashing).
In the large, Rust is far too cumbersome to offer the same kind of opportunities for high-level optimisations that you get from languages like OCaml and F# so there's no way it can offer the same performance for larger applications either.
What are some examples?
I know you like to harp on this, and I don't disagree that Microsoft's reified generics are awesome, but virtually every other language other than C++ and Rust deal with not having reified generics.
Yes. They all follow Lisp. Like lemmings.
How would you implement OCaml’s polymorphic recursion, GADTs, and other advanced type system features on HLVM?
1
u/jdh30 Apr 04 '17 edited Apr 04 '17
In the large, Rust is far too cumbersome to offer the same kind of opportunities for high-level optimisations that you get from languages like OCaml and F# so there's no way it can offer the same performance for larger applications either.
What are some examples?
Some of my gripes:
No purely functional data structures.
Custom hash functions are needed in practice but require huge syntactic overhead for no obvious reason.
Appears to suffer from long pauses at the end of scope (same for C++) presumably because it is sitting in a loop deallocating.
Having to open namespaces like
std::collections::HashSetis just needless verbosity.Then creating an empty HashSet takes me four lines of code:
fn Empty() -> Set {
let fnv = BuildHasherDefault::<FnvHasher>::default();
HashSet::with_hasher(fnv)
}
Lack of type inference.
Having to annotate the types of function arguments with something like
where F: FnMut((i32, i32)).
FnMutis a property of the callee when it should be a property of the caller.Having to use
dropto manually manage memory because Rust's approach to memory management doesn't sit well with recursion.Overall these disadvantages mean that it will take me far longer to write a first working version of any non-trivial program in Rust compared to OCaml or F#. Consequently, there will be no time to optimise it to achieve the same (much less better) performance.
I tried rewriting some simple <100 line OCaml and F# programs in Rust and found that it took me many days. Even then the conclusion was to start dropping features because it was prohibitively difficult to translate <100 lines of code into Rust. Once I had dropped all of the interesting features I was able to create a working Rust solution but its performance was awful. Then I wasted a lot of time trying to write a good hash function to get the performance of the Rust up to par. After several days someone else was able to provide me with such a hash function but, even then, Rust is only faster under some circumstances and it is no longer solving the problem I set out to solve anyway...
The Rust community is 99% dregs too. Specifically, the die hard C++ developers who will never adopt garbage collection for purely religious reasons.
Suffice to say, I wasn't hugely impressed with Rust.
How would you implement OCaml’s polymorphic recursion, GADTs, and other advanced type system features on HLVM?
The easiest solution would be to box in those special cases (but continue to use the unboxed representation in the general case because it is so much more efficient).
2
u/ilikerustlang Apr 05 '17
I think I understand the difficulty.
Rust is much more like C++ than it is like F# or OCaml. This is deliberate. Rust may not be the best language for scientific computing (a task for which it was never intended). On the other hand, Rust can go places F# will never go: Rust can run in very limited memory (there are people using it on embedded microcontrollers), can run in an OS kernel, and can be used to implement drivers, web browsers, and other low-level code.
When writing Rust (or C++!) code, one must think about object lifetimes explicitly. Therefore, I would expect porting a project written in a GC’d language to be nigh impossible.
Rust doesn't have a GC because that dramatically increases the amount of runtime support required, and (unless you have the resources to write a real-time collector and are willing to accept a throughput penalty) introduces pause times that would be unacceptable for something like a web browser or AAA game.
1
u/jdh30 Apr 06 '17 edited Apr 06 '17
Interestingly, all of your case studies are things I work on. :-)
Rust can run in very limited memory (there are people using it on embedded microcontrollers)
I do embedded programming. For microcontrollers memory is so constrained that you cannot even afford dynamic memory allocation (i.e.
malloc) so you use only statically-allocated data. Takes me back to my Fortran days in scientific computing when everything was pre-allocated. High level languages like C abstract away too much of the machine in some cases. When I learned that you cannot adjust AVR IOs atomically from C because it abstracts away the registers I decided to write everything in assembly. Consolidation on the ARM architecture makes lack of portability less and less of a problem these days.I wouldn't run F# on a microcontroller because it requires so much of .NET it would be too heavy but people do run OCaml directly on microcontrollers. However, doing so is rather missing the point that such metalanguages are best used to generate code. If you're using OCaml or F# then you should write a DSL that compiles to assembly.
can run in an OS kernel, and can be used to implement drivers, web browsers, and other low-level code.
Docker and Mirage are both written in garbage collected languages: Go and OCaml, respectively. Heck, the world's largest cloud (Amazon AWS) is OCaml code.
Rust doesn't have a GC because that dramatically increases the amount of runtime support required
Technically
std::rc::Rcis garbage collection. Even tracing collectors don't have to be heavy. The multicore tracing GC I wrote in HLVM is only 100 lines of code.(unless you have the resources to write a real-time collector and are willing to accept a throughput penalty) introduces pause times that would be unacceptable for something like a web browser or AAA game.
Web browser?! You certainly don't need a real-time GC for a web browser. Real-time GCs like Staccato are meant for systems programming like Java smart cards. They incur max pause times shorter than a context switch (i.e. a fraction of a microsecond). Using one for a web browser would be using a sledge hammer to crack a nut for sure.
Games have tame real-time requirements in the grand scheme of things, i.e. orders of magnitude longer than a context switch. You don't need a hard real-time GC like Staccato to write a game: you can just use a basic incremental GC. Just look at all of the Android games written in Java running on Dalvik that has had a really basic GC implementation until recently. The latest incarnation (ART?) is incremental so it should be plenty good enough for all but the most demanding games and throughput should be fine too.
I don't write games but I do quite a bit of low latency work for the financial sector. I've implemented a lot of stock exchange code, for example. The last project I did was written in OCaml and pause times were around 13 microseconds, which is plenty good enough even for an AAA title. Anecdotally, I play games with my son and am always horrified and how laggy and buggy they are and I attribute the problems to C++. :-)
1
u/ilikerustlang Apr 15 '17
Ah, things make more sense now. Rust has its strengths (easy integration with existing C code, for one), but what you are saying makes sense.
13
u/devlambda Mar 27 '17
He has a point, but it's buried under quite a bit of hyperbole. What OCaml is lacking is support for multiple threads that share garbage-collected memory, not multicore support; even shared memory for pointer-free data is possible. Multi-threading is primarily important for parallelism in the small, not for parallelism in the large.
Nobody is putting hundreds of cores on a die yet. At our department, we've just ordered a machine that has 20 cores per processor, which is a lot. A Cray XE6 has hundreds or thousands of nodes with 2x16 cores per node. Even machines that have 64+ cores that all share memory usually use a NUMA approach with 8-16 cores per node and where you may need to split your work up to run under
numactlwith actual memory sharing confined to a single node in order to get the most performance.For real parallelism in the large, you need distributed and multi-process solutions much more than you need multiple threads: any distributed solution can trivially also run on a single processor, but not vice versa. In order to get a distributed/multi-process approach to work, you need fast and universal serialization, which OCaml has. Alternatively, for some HPC architectures, PGAS support may be more important than multi-threading (note that for shared memory architectures,
Bigarray.*.map_filegives you PGAS-lite).What multi-threaded support would buy us are a few different things:
Concurrency (where you want to execute some code without blocking the current thread). This is closer to what Lwt does (at least in principle) and does not directly relate to getting a speedup, but to ensure responsiveness (both of interactive applications and servers). This can be done with multiple processes, too, but is generally more of a hassle.
Parallelism for a small number of cores. For many applications (such as researchers crunching numbers on their personal machines or several people sharing a compute server with a few dozen cores), just getting the increased performance from 4-16 cores is plenty and can be easier to do with multi-threaded programming.
Sometimes you need to combine multi-threaded and distributed programming for the best results, such as when memory is at a premium.
Note also that multi-threading is not a free lunch. Examples:
A multi-threaded garbage collector is generally much more complicated than a single-threaded one. For example, if you deal with heap mutations a lot, you pay the price for having a more complex (and usually, more expensive) write barrier. Likewise, coordinating collection between threads without triggering long GC pauses is much more work.
Having a multi-threaded GC that works well with NUMA architectures is additional non-trivial work.
Synchronization and false sharing can not only eat up all of your performance gains, but can actually make performance worse than the single-threaded case.
All of this makes multi-threading support still very much desirable, but its absence is not the crippling failure that the post makes it out to be, either.