470 points · by freediver · 2y ago · 247 comments
[0] Multithreaded Python without the GIL https://docs.google.com/document/d/18CXhDb1ygxg-YXNBJNzfzZsD...
[1] Github repo https://github.com/colesbury/nogil
There are so many different attempts at solving this problem that that the last time I wanted to try one of them, I found myself overwhelmed with options. I chose taichi which is pretty fun and easy to use, although somewhat limited in scope.
Taichi is really underrated, it works across all platforms (including Metal), has tons of examples and the code is easy to write. And lastly, it integrates with the ecosystem and doesn't displace it.
great demo reel of what Taichi can do, https://www.youtube.com/watch?v=oXRJoQGCYFg
https://gigamonkeys.wordpress.com/2009/10/16/coders-c-plus-p...
This depends on how they license it going forward, and whether they make it open, or use being a superset as a way to capture then trap python users in their ecosystem, and I don't think we have a certain answer which path they'll take yet.
The way they let you mix python compatible code with their similar but more performant code [1] looks interesting and provides a nice path for gradual migration and performance improvements. It looks like one of the ways they do this is by letting you define functions that only use typed variables which is something I would like to see make its way back to CPython someday (that is optionally enforcing typing in modules and getting some performance gains out of it).
[1] https://en.wikipedia.org/wiki/Mojo_(programming_language)#Pr...
C++ predates on C in a similar way to how Mojo predates on Python. At least C++ has extern C.
https://docs.modular.com/mojo/manual/python/#call-mojo-from-...
> As shown above, you can call out to Python modules from Mojo. However, there's currently no way to do the reverse—import Mojo modules from Python or call Mojo functions from Python.
One way street. Classic commons harvesting.
Mojo explicitly does the opposite, allowing Mojo to use Python but requiring Mojo to be in control, while making it hard/impossible for code written in Mojo to benefit code written in Python:
> Our long-term goal is to make Mojo a superset of Python (that is, to make Mojo compatible with existing Python programs). […] Mojo lets you import Python modules, call Python functions and interact with Python objects from Mojo code. […]
> As shown above, you can call out to Python modules from Mojo. However, there's currently no way to do the reverse—import Mojo modules from Python or call Mojo functions from Python. […]
> This pattern doesn't work because you can't pass Mojo callbacks to a Python module.
> Since Python can't call back into Mojo, one alternative is to have the Mojo application drive the event loop and poll for updates.
No comment on whether this should be viewed as an attack.
A superset of pure .py code, not the numpy, cython, ctypes and stuff.
But once you get "superset" of CPython's C bindings, congratulations, you get GIL.
https://www.researchgate.net/publication/337118128_Taichi_a_...
I think the performance benefit would also be small. Many objects are only accessed by a single thread, some objects are accessed by many threads, but few objects are exclusively accessed by one thread and then exclusively accessed by a different thread.
I was a bit disheartened when the Unladen Swallow project [1] fizzled out. Great to see Python back on the core optimization track.
"tranced bread" is a fun name for some sort of library that breaks up files into pieces for better resilience for sending, like over BitTorrent.
I get in concept what the GIL is.
But what's the impact of this change?
Packages will now break, for the hope of better overall performance?
Even outside of high-intensity CPU work, this can be useful. A problem lately is that a lot of code is written using Python's native asyncio language features. These run single-threaded with async/await to yield execution, much like in NodeJS, and can achieve pretty good throughput even with a single thread (thousands of reqs/second).
However, a big problem is that any time you do _any_ CPU work, you block all other coroutines, which causes all kinds of obscure issues and ruins your reqs/second. For example, you might see random IO timeouts in one coroutine which are actually caused by a totally different coroutine hogging the CPU for a bit. It can be very hard to get observability into why this is happening. asyncio provides a `asyncio.to_thread()` function [1] which can help to take blocking work off the main thread, but because of the GIL it doesn't truly allow the CPU-bound to avoid interfering with other coroutines.
[1] https://docs.python.org/3/library/asyncio-task.html#asyncio....
I'm asking because I encountered a weird phenomenon before.
I use a simple Python lib called "schedule" which is to run some tasks periodically (not precise). And I often run a script multiple times (with different arguments) to monitor something say, every 30 seconds. So they're in three separate Python Interpreter processes.
What I've noticed is that while when I initiated them, they were something like 5 seconds apart, they eventually will end up running in sync. Probably not related to GIL at all, but I guess do no harm to ask.
The GIL only really kicks in if you use threads in a single process. Then, the GIL will only let one single thread do actual work at a time, and will trade off which thread gets to do work. The other threads can wait on IO stuff (web requests, the file system, etc) but they can't do number crunching or data processing at the same time.
That's a really interesting observation though, I wonder what _is_ causing your separate processes to sync up?
Edit: https://peps.python.org/pep-0703/ suggests it will support multiple cores, unless the current work does not yet achieve that.
They assume they can "take the GIL", and then go and look at the various Python datastructures you passed them without worrying about them changing as they are being read.
The later, when writing out their answer (which might involve editing something they were given), they can assume they are not changing. For example, you could write code which extends the length of a list to 100, then fill in all the members, not worrying half way through your loop another thread shrinks the list back down.
Intent to approve PEP 703: making the GIL optional - https://news.ycombinator.com/item?id=36913328 - July 2023 (499 comments)
Once the Python ecosystem supports either subinterpreters or nogil, we'll happily migrate to those and get rid of our hacky interprocess code.
Subinterpreters with independent GILs, released with 3.12, theoretically solve our problems but practically are not yet usable, as none of Cython/pybind11/nanobind support them yet. In comparison, nogil feels like it'll be easier to support.
apart from go (maybe java) those are all "scary" languages that require a bunch of engineering to get to the point that you can prototype.
even then you can normally pybind the bits that are compute bound.
If Microsoft had been better back in the say, then c# should have been the goto language of choice. It has the best tradeoff of speed/handholding/rapid prototyping. Its also statically typed, unless you tell it to not be.
I think Python is a terrible language that exemplifies the maxim "worse is better".
[1] https://docs.ray.io/en/latest/ray-core/walkthrough.html#call...
[2] https://docs.python.org/3/library/multiprocessing.html#manag...
Of course, getting threads to be actually useful for concurrency (GIL removed) adds another very useful tool to the performance toolkit, so that is great.
Not if you use Windows, then it's a mess. I have a suspicion that people who say that the multiprocessing works just fine never had to seriously use Python on Windows.
Something that tripped me up when I last did `multiprocessing` was that communication between the processes requires marshaling all the data into a binary format to be unmarshaled on the other side; if you're dealing with 100s of MB of data or more, that can be quite some significant expense.
I work on low-latency stuff and we routinely get server-side latencies in the order of single to low double-digit microseconds of latency.
If python ever becomes fully concurrent (python threads being free of any kind of GIL) we'll see the "python slow" meme for a number of years... Also doesn't help that python gets updated very very slowly in the industry (although things are getting better).
Of course, if you have a simple fastpath you can make it fast in any language with a JIT, latency is also generally not an issue anymore, credit where credit is due - java GCs are light years ahead of everything else.
Regarding jlink - my main complaint is that everything requires java.base which already is 175M. And thats not counting the VM, etc. But I don't actively work with java anymore so please correct me if there is a way to get smaller images.
Probably the right design though.
AFAIK we're just talking about removing the global interpreter lock. I'm pretty sure the threading library uses system threads. So running without the GIL means actual parallelism across system threads with shared memory access.
Working with threads is a pain in Python. If you want to spawn +10-20 threads in a process, it can quickly become way slower than running a single thread.
Removing the GIL and refactoring some of the core will unlock levels of concurrency that are currently not feasible with Python. And that's a great deal, in my opinion. Well worth the trouble they're going through.
That said - I think it's fair to be irritated by people who write Python off as entirely useless because it is not _the fastest_ language. As you rightly say - it's fast enough for many purposes. It does bother me to see Python immediately counted out of discussions because of its speed when the app in question is extremely insensitive to speed.
This topic is an example: a detail of one particular implementation, since GIL is definitely not inherent to the language. Just the usual worry about looseness of types?
Async I/O and threads are two different things, and either can be present in real code without the other.
I have ran a lot of programs containing race conditions successfully many times until I ran into an issue.
At any rate, test_asyncio contains a lot of tests that involve threads and specifically thread safety between coroutines and those tests fail. As far as async I/O and threads being distinct, I mean sure that is true of a lot of features but people mix features together and mixing asyncio with threads will not work with this particular release.
> When we found out about the “nogil” fork of Python it took a single person less than half a working day to adjust the codebase to use this fork and the results were astonishing. Now we can focus on data acquisition system development rather than fine-tuning data exchange algorithms.
You're not supposed to drive a car that hasn't got out of the research and development laboratory either, so there's that.
EDIT:
> [the test synchronous programs] all seem to run fine, and very basic threaded programs work, sometimes
Perhaps this is closer to removing the oil pan
Only as long at it’s as easy to put back in
I also want types, so Elixir is not in the picture. I dabbled in Rust a bit. Although I was able to get the hang of things and build a CLI tool pretty quickly, I'm worried I'll have to deal with numerous quirks later if I keep using Rust (like numerous string types). Is that something to be worried about if all I want from Rust is Python+Types+Concurrency?
But once you get over it, you realize Golang has a good type system, concurrency model, package manager that's not pip, fast compile times, and static binaries. For most cases it will also offer great performance.
It has everything you need to build APIs, CLI tools, web servers, microservices - pieces which will form the building blocks of your software infrastructure. I have heard numerous stories of people being productive in Go in a few days, sometimes even hours.
If Python is 0 quality of life and Rust is a 100, Golang gets you all they way up to 80-90. That last bit is something you might never need.
Rust is a great language and something I hope to be in proficient someday, but I ll save it for where I actually need that last microsecond of performance.
You can even run Python from Julia, so that alleviates the problem with a lack of libraries somewhat.
If you're not a fan of GoLang's spartan syntax and are cool with async/await, C#/dotnet core is a great experience on all platforms. IMO it has the best async/await implementation (it originated there) on top of a multi-threaded event loop. ASP.NET is a great web framework and it has great library support for everything else. As someone who avoids "traditional" ORMs (Hybernate, Django) I really like Dapper.
Nim is a statically-typed compiled language with very pythonic syntax. It's easy to learn, especially if you already know Python, because Nim's stdlib is heavily inspired by it.
For multithreading in Nim see:
Weave - https://github.com/mratsim/weave
Malebolgia - https://github.com/Araq/malebolgia
[0] - https://nim-lang.org
I migrated a couple of projects from Java, TS and Go to Rust and honesly, I couldn't be happier.
Sounds like Groovy. But I wouldn't recommend it. Also the career padding hype is gone.
Learn golang or rust instead. Impressive that they are managing this though!
Bad take. Learn golang and rust and python.
You should use the language which is suited to the task, sometimes that's golang sometimes that's python and sometimes it's rust.
It's impressive that the python team as a whole continues to improve in such big ways after more than 30 years of development. It's more impressive that the python team managed to navigate 2to3 and come out stronger.
Instead, pick C#/F#, Kotlin/Clojure or Rust depending on the use case.
I definitely agree that libraries can and should drive your language decisions. A 20,000 line golang program might be 10 lines of python because there is a library to do what you need. Similarly a complicated-to-reason-about python program may be made far simpler by using go channels/routines.
Having to "if err != nil" every single function call is a big put off - imagine having to "try catch" everything in a language like C#!
func Must(err error) {
if err != nil {
panic(err)
}
}
func Panic[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}It forces me to think about how my programs can fail and what I should do when they fail.
Also Rust became a quite popular tool for python extensions, where you can offload performance to rust and business logic to python.
Yes it is, in every way. When the first job of choosing to use types is choosing which of the five or so type checkers, each deficient in their own way and incapable of dealing with the poor idioms the language encourages to proliferate, you know you're on the wrong path.
With tools like pyright now + the work on nogil everyone benefits from this using Python.
>> 99% of my compute is offloaded to compiled BLAS or CUDA.
types are enough.
and memory and type safety are not terribly relevant for my use cases.