343 points · by bobajeff · 5y ago · 345 comments
Performance doesn't come from any one quality, but from the holistic goals at each level of the language. I think some of the most frustrating aspects from the history of Python have been when the team lost focus on why and how people used the language (i.e. the 2 -> 3 transition, though I have always loved 3). I hope that this is a sensible optimization and not an over-extension.
At a higher level, Python is getting serious about performance. But this gives both flexibility and performance.
> The overall effect of this change, and a number of others with it, actually boosts single-threaded performance slightly—by around 10%
Then it sounds like having the cake and eating it too (optimism). Although my experience keeps nagging at me with, "there is not such thing as a free lunch" (skepticism).
https://lwn.net/Articles/872869/
The no-GIL version is actually about 8% slower on single-threaded performance than the GIL version, but the author bundled in some unrelated performance improvements that make the no-GIL version overall 10% faster than today's Python.
Well, yeah, someone had to make the changes. That's the cost that was paid.
You can get a mass-produced machete that is cheaper and higher-quality than a 7th-century sword. It's easy for one thing to be better than another thing across several dimensions simultaneously. That's why certain technologies go out of use -- they have negative value compared to other technologies. But that has nothing to do with the principle that there's no such thing as a free lunch.
When you carry a heavy suitcase filled with lead and you drop it, things get lighter for free. You paid for it by carrying the damn thing around with you for the whole time.
Can't see Python getting there unless we go to Python 4 which, given the fiasco that was Python 2->3 is probably never gonna happen.
Might as well wait for Julia to improve its TTFP then to hope for a Python 4.
The GraalPython implementation of Python 3 is built on the JVM, which is a fully thread safe high performance runtime, and Graal/Truffle provide support for speculation on many things. For pure Python it provides a 5-7x speedup already and the implementation is not really mature. Although at the moment they're working on compatibility, in future it might be possible to speculatively remove GIL locks because you have support for things like forcing JITd code to a safepoint and discarding it, if you want to change the basic semantics of the language.
Even if this will be a major breaking change to Python, it'll be worth it for us.
And it is also about flexibility. What I love about Python is the simplicity, and let's be honest, multiprocess anything but. Especially if you fall into one of the gotchas (unpickable data for example).
This can be a problem for a lot of treading use cases. If I'm working on an ETL app that parses large amounts of data, either the related CPU bound tasks need to either run sequentially, call out to C extensions, or use multiple processes which incurs an overhead.
It's a pain when you know threads would suit your use case well, but the threading implementation in the language you're working in isn't up to the task.
I see this as being a nice stopgap solution for those who are too big for single-threaded but not big enough to need Spark.
It starts to become an issue when you have built a few well-performing subsystems and now want them to run together and interact. With the GIL, your subsystems are suddenly not performing as well anymore. Without the GIL, you can still get good performance (within limits of course).
Performance referring here to throughput and/or latency (responsiveness).
I think a JIT would be the best possible improvement for CPython as far as speed is concerned. Though I can imagine there are plenty of people doing processor heavy stuff with c extensions that would benefit from sharing memory. So from their perspective removing the GIL would be a better improvement.
So basically a JIT would help every Python program, and removing the GIL would only help a small subset of Python programs. Though I'm just happy I get to make a living using Python.
Edit: This was in the back of my head, but I didn't mention it, and it would be unfair to dismiss. A JIT does slowdown startup time, so for short programs that are finished running quickly it may make things worse. Though I suspect it would be easy enough to have a value to turn off the JIT at the start of the program.
https://stackoverflow.com/questions/1050222/what-is-the-diff...
What if the "Global Interpreter Lock" needs to be removed for JIT? I put that in quotes to highlight it because AFAICT no compiled (or JITed) language has such a thing. I think it functions differently than regular stuff like critical sections.
It doesn't. PyPy has a JIT and a GIL. The JIT just compiles the byte code to native code before running, along with some tricks that are over my head.
Edit: Here is PyPy's FAQ about it
https://doc.pypy.org/en/latest/faq.html#does-pypy-have-a-gil...
The compiled code polls a global or per-thread variable as it runs (but in a very optimized way). When one thread tries to change something that might break another thread, the other threads are brought to a clean halt at specific points in the program where the full state of the abstract interpreter can be reconstructed from the stack and register state. Then the thread stacks are rewritten to force the thread back into the interpreter and the compiled code is deallocated.
The result is that if you need to change something that is in practice only changed very rarely, instead of constantly locking/unlocking a global lock (very, very slow) you replace it with a polling operation (can be very fast as the CPU will execute it speculatively).
However, this requires a lot of very sophisticated low level virtual machinery. The JVM has it. V8 has it. CLR has a limited form of it. Maybe PyPy does, I'm not sure? Most other runtimes do not. For the Python community, very likely the best way to upgrade performance would be to start treating CPython as stable/legacy, then support and encourage efforts like GraalPython. That way the community can re-use all the effort put into the JVM.
What does it mean? how is python different here than Java/C#?
Mypy and other static analysis tools are becoming more common in part because IMO they basically require you to stop and think about your "Pythonic" dynamic patterns (containers of mixed element types, duck typing of function arguments, mutable OOP etc.), and often realize that they are a bad idea.
So in some way we are hampering multithreading to support programming constructs that are mostly used to make python flavoured spaghetti, especially in the hands of beginners and non-programmers who are encouraged to learn Python...
I'm not sure Python is fixable at this point. Oh well.
Assuming now you have a big dictionary, which contains tens of millions of records to be filtered upon, another say TB of data. In current Python land, you either:
1. Using multi-processing, but each process needs to create its own dictionary
2. Or create an external DB, and using the DB's client to retrieve data in certain way.
This pattern has occurred again and again in my use case, and it is always messy to solve in Python. Had Python has true multi-threading, then sharing some big but read-only object among real threads would be a possibility, and believe me, a lot of people would be really happy.
In this market you really want to shuffle tons of data quickly, and that’s usually achieved through parallelism.
Python multiprocess library does a poor job at that.
The timing was critical, and although Python may be the Facebook of languages, one can't discount that it was extraordinarily lucky for Guido to be in the precise time and place to capitalize on good design choices.
I've had to rewrite my Python code in another language in 3 different projects already (multi-processing wasn't an option) and I'm not even a heavy user. Removing GIL would be very welcome.
That Python and other languages in its speed class are still used for new projects in production demonstrates that you can, often, get away with 100× slower code. But, sure, you can get away with 10× slower more often.
A lot of people learned Python and now want to use it for something more serious even if Python was not designed for it.
I work on high volume backends (like million TPS on a single node) and Python for me is just a toy language.
But I see no reason to purposefully inconvenience these people by keeping GIL if it can be removed.
Threads will allow you to split your I/O in multiple procedures, so you might start computations as soon as possible when the data is ready. They will also allow you to massively speed up aggregates without having to create a new process each time (which doesn't allow you to share memory). Threads are a BIG issue when you don't want to rely on asyncio[1].
Note [1]: Asyncio pools are single-threaded because of the GIL. This is already bad enough in practice, but they also perform very badly in CPU-bound contexts. This make them an absolute no-go when dealing with datascience code: a cpu-bounded core in an i/o-bounded wrapper.
like processing web requests?
Rust got it pretty good, but they designed a significant part of their language so that multithreading could be done well. Python did almost the opposite.
Basically I love peanut butter ice cream (Python) I’d just like it even more with sprinkles.
Could be that the impact of this change is far broader than just a few key libraries.
Most of the issues with multi-threading come from concurrency, not parallelism. The GIL allows concurrency, you just don’t get any of the advantages of parallelism, which is normally the reason for putting up with the complexity concurrency creates.
Thread1: a = 0xFFFFFFFF00000000
Thread2: a = 0x00000000FFFFFFFF
One might think that the two possible values of a if those are run concurrently are 0xFFFFFFFF00000000 and 0x00000000FFFFFFFF. But actually 0x0000000000000000 and 0xFFFFFFFFFFFFFFFF are also possible because the load itself isnt atomic.
The GIL (AFAICT) will prevent the latter two possibilities.
The compilers also take care to align most variables.
So while your scenario is not impossible, it would take some effort to force "a" to be not aligned, e.g. by being a member in a structure with inefficient layout.
Normally in a multithreaded program all shared variables should be aligned, which would guarantee atomic loads and stores.
That thread behavior is enough to reduce the likelihood of races and collisions; particularly if the critical sections are narrow.
Some more discussion here: https://stackoverflow.com/questions/1717393/is-the-operator-...
Porting the thing to a multi-core system revealed that there were a lot of nasty concurrency bugs, like dead-locks or crashes which happened after a day of operation. And this wasn't a toy system - it was in use for a long time in an industrial application, and the customer was not too happy about the intermittent dead-locks. I commiserated with the poor engineer who had the quite stressful task to debug this, equipped with a lot of dedication but an insufficient background.
Frankly, while it would be nice to be able to write parallel code in pure Python, I think that Clojure with its purely-functional approach has the better concepts for this. And moreover, actually improving performance by parallel computation (using several CPUs to work in parallel on the same thing) is damn hard and unsolved in many cases (just come up with an efficient parallel Fast Fourier Transform and you might get a Turing award). What is mostly needed (outside of massive data processing pipelines) is concurrency for event-driven systems. Python can handle that, Clojure does handle it in a much more elegant way.
with gil:
call_a_method()
print(some_debugging_info)
with all the sit-ups you’d have to do in a “real” concurrent language.It only protects the state of the Python interpreter and that of C/Cython extension modules. Though even there, you can have unexpected thread switches, e.g. in Cython `self.obj = None` can result in a thread switch if the value previously stored in `self.obj` had a `__del__` method implemented in Python.
And AFAIK pretty much any Python object allocation can trigger the cycle collector which can trigger `__del__` on (completely unrelated) objects in reference cycles, so it's pretty much impossible to rely on the GIL to keep any non-trivial code block atomic.
Maybe time to rethink? https://www.techrepublic.com/article/programming-languages-w...
If this is as promising as it sounds, it seems Python 4 now has its "thing" and is on the horizon. Or at least may become a serious thing to talk about
What struck me as most significant was the opportunistic breakage of things not related to the unicode transition. In the many years it took to win people over to v3, they could have marched over all the breaking changes a year at a time. Given that side-by-side installs of python3.x point versions are very functional, with or without venvs, this would have been much more palatable. Perhaps harder than it sounds though.
I attempted a couple of 2to3 translations of open source libraries over the years, with varying degrees of success. Every time I found that most of the changes were easy, but debugging the broken bits was hard due to the sheer volume of source changes. If instead I could have done conversions where there was only a single major semantic change at a time, it would be so much easier to figure out what was going wrong at any given step. Furthermore, I imagine that a single-breaking-change mentality would lead to better documentation on how to transition for each version.
For this reason, I have become rather suspicious of yearly release schedules. Swift is even more frustrating: the version changes are really just dictated by Apple's yearly PR calendar. Some big things get rushed out for WWDC before they are ready, and smaller fixes can get held back until the next year. I would much rather that the language teams just prioritize one thing at a time, release it when it is ready, and foster a community where staying up-to-date on the latest version is easy and desirable (a more complicated story for Apple than for Python I think, due to ABI, OS version, etc).
From past discussions on HN I've gathered that there is such a thing as release fatigue, where developers get irritated when libraries release breaking changes too often. Nevertheless I often wonder if languages and libraries could improve faster by making more breaking changes, one at a time, with robust side-by-side installs to facilitate testing across versions. I wish side-by-side library versions were possible in Python, just to facilitate regression testing.
Bringing this all back to the post, I sincerely hope that if Python 4 is a breaking change to the GIL, that it will be only that.
I'm curious what others think about all this. Thoughts?
This.
It makes absolutely no sense to claim that having to deal with a single non-backwards compatible release is somehow worse than having to deal with a sequence of non-backwards compatible releases.
Even though the migration from Python2 to Python3 faced some resistence, if anything the decision was totally vindicated.
I want the python that Guido promised me, with 2021 performance. I don't want some abhorrent committee-designed piece of middle-of-the-road shitware glue language that I must use because everyone uses it.
I want a language that doesn't spin it's single-threaded wheel in a sea of CPU cores, and I want a language that has one obvious way of doing things without needing to grok and parse dumb """clever""" hacks that will only be abused by midlevel programmers to show off hoe they saved typing a few lines of additional code.
To me, speed + simplicity = ergonomy = joy. I want a new python 4 to focus exclusively and intensely on performance improvements and ergonomy.
That was the point of the "from __future__" imports. You could get most of the way toward Python 3 so that 2to3 would be easier to work with and the new semantics could be gradually baked into the code prior to migration.
Python 3 had 25 years of cruft to clean up. They won't have to do that again.
Corporate developers, who have taken over Python and other people's work, like unnecessary changes, because they get many billable hours of seemingly complex work that can be done on autopilot.
Corporations might even take over more C extensions whose developers are no longer willing to put up with the churn and who have moved to C++ or Java.
In the long run, this is bad for Python. But many developers want to milk the snake until their retirement and don't care what happens afterwards.
In my 20+ year career I have never worked with a programmer that matches this description.
Maybe I've got lucky.
.. but. Let's not count our chickens until they are home. I'm wondering if the Python dev community will take on this challenge. I hope so, Sam seems to really have put in a lot of effort!
Python is there now, if you ask me. It should slow down and focus more on "maintenance" stuff with little to no impact on its interface. And maybe work on big projects like multithreading or stronger typing on the background and them when they're fully ready.
Please, don't. There are wonderful strongly types languages out there, so if one wants or needs a strongly types language, use that, and not Python.
Perhaps, without the GIL and with typing information included, additional performance gains with be on offer.
But the "have it your way" nature of Python is a bigger win than either end of the data typing spectrum.
TMTOWTDI - There's more than one way to do it - is Perl's motto :)
Zen of Python suggests there's just one correct way.
We won't get data race free guarantees but if built into pandas or Vaex we can have a near transparent API.
It'll really open things up for those apps running on 32 core machines. They're out there, I deploy these things frequently (Plotly Dash framework for large Enterprise customers).
IMO, removing the GIL is a major mistake. The GIL is what allows you easy concurrency and to keep the language's 'magic' while ensuring correctness. If you need parallelism, there's processes and probably other tactics (I'm not super up to date on Python things). If you simply remove the GIL you have a bunch of race conditions, so you need a bunch of new language constructs, and it just adds a bunch of complexity to solve problems that don't really need solving.
IMO they should just do what Ruby did with Ractors; basically a cheap alternative to spawning more processes. Rewriting absolutely everything that uses threads to be thread-safe is a waste of time.
if x in d:
del d[x]
else:
d[x] = True
Is a classic example -- if two threads execute that, you can't predict the outcome (but a KeyError is quite likely)The GIL only protects the CPython virtual machine; it doesn't protect user code. Concurrent code with shared mutable state already needs explicit mutexes.
I already have to be careful to only write to a shared object from one thread, since I have no guarantees on order of execution.
The main benefit of the GIL, from my recent reading is that it makes ref counting fast and thread safe. The meat of the proposal is changing ref counting so that it's almost as fast and atomic without the GIL.
In Java you would have to worry about safe publication to make the change visible to the other thread, but thanks to the GIL changes in Python are always (I think?) made visible to other threads.
current_boolean_value = global_cancelled
global_cancelled = new_boolean_value(current_boolean_value)
The nice thing about everything being single threaded is that nothing will break if you remove the GIL. It will still be single threaded. It's only when you actively start using multiple threads that things might break. So, you won't have race conditions until you do that and then only if you do things that you shouldn't be doing like sharing things across threads that you should not be sharing because they aren't thread safe.
Removing the GIL will simply enable people to start gradually fixing things and give them the option to use threads instead of forcing them to use completely different languages.
Ractor style asynchronous programming might be a good idea for python as well. One does not exclude the other.
The race conditions a Gil program and a no Gil program should have should be same. A Gil is not the only way to keep certain operations safe.
Only if you are writing multithreaded coded. Otherwise it is just a loss.
Interesting. When I write Python, and I write Python most of the time, I'm not chasing performance. But when it comes to speed, a 18x speedup gets Python up to par with currently much faster languages like Java. At least if you are willing to spam threads like your life depends on it.
conda install numba & conda install cudatoolkit comes to mind?
And you should data orientated, so all that remains from objects is arrays of structures with the index being the object indicator. Im honestly puzzled about the use-case..
But what would be nice currently, is to create map reduce API w/o shared data or just readonly data.
Something like ProcessPoolExecutor but instead of spawning new process and pickling input/output data, create threads w/o GIL w/o pickling input/output data.
<grumble> Please escape Discord links so people don't accidentally click a live one and thereby expose data to Hammer & Chisel, Inc. </grumble>
It's a constant slap-in-the-face how prevalent Discord is in the tech community. Need support with an obscure library? Discord. Want to talk to contributors for a project? Discord.
I honestly don't know why people so greatly prefer Discord to IRC. The interface? Network effects? Whatever it is, Discord and H&C are disgusting, and I pray the tech community finds a way to escape it.
can you fill me in? a couple google searches didn't turn up much.
Also, it's so disheartening to see people tout Discord's interface as its 'killer feature.' As far as I'm concerned, if I can't mold it into a decent TUI for my terminals, it's okay at best. If an app actively resists its interface being molded, however, that's just evil.
I am praying for CPython to become faster. But I need faster singlethreaded performance, so web applications benefit from it.
That was a really sad moment, and I've never felt good about python since.
I wanted "as you wait for the GPU to churn through this batch, start reading the next batch from disk & preprocessing it on the CPU"
Getting this to work turned out so ass backwards it made me sad
Also I pity the fool who tries to connect a debugger to code using multiprocessing.Pool()...
PyCharm works fine
I solved it by using python threads and C function (cv2.resize)
Like anything, it’s possible to split this work out to a separate process but the IPC overhead is a lot.
That said, many such databases are (or already have) rolled out connection pool proxies for reasons like this, so meh.
Friend: I saw this interesting tech article ...
Me: Site?
Friend: mumble corp IT site mumble
Me: Bye
Even if those changes are better for other ways of solving problems.
I assume that a change to relax the GIL will both allow you to opt-out of it, and allow you to use locking versions of primitive data-structures, anyway; it's not like it's going to just vanish overnight with no guardrails.
`dict.update()` will call methods like `__eq__`, and those methods (if implemented in Python) may temporarily release the GIL.
I'm probably biased because I think Python is a hacked together mess but I just don't see what the point is in dragging it around.
I think Go benefited a lot from that.
I think Python is shit but so is most everything else, I'm interested in whether people jump ship or just work around it's issues at scale. I work on a programming language designed to avoid messy python scripts internally, so I am sincerely interested in these decisions.