Why Python is Slow: Antonio Cuni on SPy and Statically Compiled Python
Mia Bajić talks with Antonio Cuni about why Python is slow and SPy, a statically compiled variant of Python.
Antonio Cuni is a principal engineer at Anaconda, the author of SPy, a developer of PyScript and PyPy, and co-founder of the HPy project. SPy aims to be as fast as C while staying Pythonic. They discuss the trade-off between dynamic features and performance, SPy's red and blue code model, the SPy compilation pipeline, why PyPy struggles with C extensions, garbage collection in SPy, and what "Pythonic" means.
About the guest
Antonio Cuni
Principal engineer at Anaconda, author of SPy, developer of PyScript and PyPy, co-founder of the HPy project, and creator of PDB++, Fancy Completer and VMProf.
Chapters
- 00:00 Episode highlights and introduction
- 00:40 Why is Python so slow?
- 01:31 Would a static Python be fast?
- 02:13 What is SPy?
- 02:28 What motivated you to create SPy? (Spoiler: frustration)
- 03:52 Which ideas from PyPy and HPy went into SPy?
- 06:36 Biggest challenges of building SPy
- 07:49 What does "Pythonic" actually mean?
- 10:39 Current roadmap and the two-level language idea
- 12:24 Walking through the SPy compilation pipeline
- 13:57 Red-shifting and the blue/red AST nodes
- 14:40 Why blue and red? (No, it's not from The Matrix)
- 15:52 PyPy vs SPy: when to use which
- 19:34 C extensions and the C API problem
- 20:04 How to actually make your Python code faster
- 23:34 Memory management and garbage collection in SPy
- 24:44 When will SPy be production-ready?
- 25:44 How to contribute to SPy
- 26:26 Where does the name "SPy" come from?
Links & Resources
Full Transcript
You said Python is slow. Why is Python so slow? >> Python is slow because many reasons. But >> motivated you to create it. >> That's a good question. I think that
ultimately is like frustration. >> Why did you name them Red and Blue? Is it from Matrix? >> No, I didn't think about that. >> Everyone, have you ever wondered why SPy
so slow? If so, this is the right episode for you. In this episode, I talked to Antonio Cuni. Antonio is a principal engineer at Anaconda and author of SPy. a core developer of
PyScript and PyPy and one of the founders of the HPy project. He is also a creator, maintainer, contributor of numerous other open source projects such as PTB++, fantasy completer and VM
We talked at Pyon US about Python performance. I asked you what do you think about it and you said Python is slow. Why is Python so slow? >> Oh, that's exactly the talk which I just
gave. [laughter] No, why why Python is slow? Python is slow because uh many reasons but it's very dynamic language and uh
the re the fact that it's so dynam dynamic makes it very very hard for implementation to make it fast. >> Mhm. But at the same time a lot of this dynamicity is what makes Python a nice
language and uh so there is this like tradeoff and tension and uh that's like they they are part >> so if the only problem is the fact that Python is dynamic does it mean that if
you have a static Python where you use type annotations and everything is static that means that it will be fast. Yes, that that these languages already exist like uh Rust or Java or C++ uh
like uh static statically typed languages exist but uh they tend to be harder to use or less ergonomics or well just non-Pyonic like from the point of view of what we like in Python these
languages like lack some features or they just feel different. So the challenge is to make something which is like fast but pythonic. >> SPy is a variant of Python. It's
relatively new and it's designed to be statically compiled but at the same time it's very familiar to Python users because it uses uh the same or very similar syntax and it provides you with
the same developer experience. What motivated you to create it? >> That's a good question. I think that ultimately is like frustration. No. Okay. So uh my my like history in
the Python community roots back to like 20 years ago. I started doing PyPy and PyPy is like advanced implementation of Python with a JIT compiler which aim to be fast and it actually is it has other
problems but that's not that's not the the the topic. Um but the problem is that somehow it feels like we are playing a puzzle game. So there are a lot of features in in Python
which makes it very hard to optimize. What I was saying earlier >> they are very interesting to solve and as a language implementtor you need to work around all this strange uh crazy
stuff but then you realize that in practice they are not used a lot. And so we are in this strange situation in which you you have to take them into account but then they are not used and
so like your language is more like your implementation is very complex and not as fast as it could be but at the same time you cannot avoid them because if you do then 0.01% of existing program
stop working and that's not what you want. So you have this. >> Yeah. So you mentioned PyPy and you were also in the past involved with HPy. Are there some ideas that you took from
those languages or variants and you decide to implement in SPy or you decide to take a very different approach and to build something very different from scratch? Um it it so SPy can feel very
different than PyPy somehow but actually a lot of the ideas come from PyPy like from from the experience which I had with it in particular the fact that when you okay let's do a step back you are a
python interpreter that you want to make python fast uh but python is super dynamic and uh in theory there is a lot of computation that you need to do again and again and
again and and and that's what like a um easy interpreter does and and it loses a lot of time redoing the same computation. So for example, if you have a loop which is doing additions on
numbers on a list on numbers, you need to do the lookup for the plus implementation every time at every loop. >> What what a JIT compiler does both pipi but also the new uh um CPython jet
compiler is to realize that a lot of this computation you you redo again and again. So you you think okay if this thing doesn't change I can premp compute it earlier and then uh and then save the
results later >> and that's basically the bulk of it. That's how you make >> so uses the same approach that those operations which are used often that
they are pre-ompiled so they don't have to be interpreted line by line but you have those templates you can reuse. Yes, the the the big difference is that in any JIT compiler which aims to implement
full Python semantics is okay I think this thing is constant is uh um how can I say uh best effort >> we hope it works if it doesn't then we fall back to be slow and then for the
user it becomes very hard because depending if if your program doesn't um is not fully understandable by the the VM then the VM is not able to optimize but it still works. It's slow
and you don't know why and and then you have to spend hours trying to understand why the G compile didn't kick in. >> And with SPy the approach is different is if the rules of the lang the rules of
the language are designed in such a way that if you cannot make it fast then you get a nice error. So if this thing which the J compiler hopes it's constant in inspire you try to change it then you
get an error say okay you cannot change it because there's >> and you know why >> yes that's that's the core of the idea >> and what are some biggest challenges you
faced while developing SPy is it only Python's dynamic nature or are there more things under the hood that we don't see that are very challenging to be implementing in spy
>> so the hardest part in SPy so far so SPy is a very new is a very new project I mean I've been working couple of years but at the beginning not full-time and then I started doing other stuff in the
last 6 months or so I'm doing it The hardest part is basically language design because you can think of it as a variant of Python or a subset of Python or
something like that statically typed version of Python but in reality is a different language with different rules and you need to design them and they design them in a way that are ergonomic
to the end users. The the the hard part is to design something which feels like Python. So I really want that people coming from the Python community should should find it very obvious what it does
even without knowing all the details of the semantics >> and uh there isn't this tension between okay maybe I should do this but I don't want to do things too differently so
let's let's try to find a >> so it was very hard to make it static but also very pythonic >> and what does it mean pythonic to you because you described SPy to aim to be
fast as c pythonic as python What does it mean Pythonic to you and what are some features or some qualities of Python that you that are important that you prioritize?
>> That's a that's an unanswerable question like Pythonic is a very very like uh not it's not well defined. Yeah. But >> I it's it's easier to say what is unpyonic. So like if you use other
languages there are a a number of patterns that in Python comes very naturally and in other languages you cannot do decorator. So in Python it it's it's very easy to add a decorator
to a function and then you do automatic logging or of exceptions something like >> and uh if you want to do it in C++ well it's impossible you need to do strange and um in Java I think that you have
something like similar but like it really feels not as nice and as uh um natural as it does in Pythons. And can you use decorators in spy? >> Not yet because it's work in progress,
but it's it will be. Yes. >> And um >> I would say that Python is a very expressive language and it's but this expressiveness is not used by most
>> Mh. So like the vast majority of like normal Python users use pre-built libraries and then they you have like Jupyter notebook or data processing script and or AI and use these libraries
made by others and the libraries have an incredibly nice API which is user >> And that's why I think it's one of good reason why Python became so popular because it's very natural. You can write
libraries which are very natural >> very easy to learn. >> But if you look into these libraries they use advanced features to make this API as natural as possible. advanced
advanced features like meta classes, uh import time premputation, um descriptors and uh the the idea of SPy is to make sure that all these patterns are still
>> and that's like in in this sense they must be pyonic. Um even if you might need to change a bit of of what you used to do but like for from the point of view of power users
yes you need to learn new rules of the language but from the point of view of let's say end users using libraries you should shouldn't find a lot of >> So you would like to make all those
possible but they're not there yet because it's work in progress. What is the current road map of spy? So um another thing that I I'll answer another question before which is like
spy also aims to be a two-level >> Mhm. in the sense that currently in Python you have this high level uh language which is relatively slow but then if you want to implement numpy or
pytorch you need to go to a lower level language and so you numpy is written in C pytor is written in C++ other stuff are written in rust or in Syon and uh you have to to do the jump and change
>> uh SPy wants to be a two-level language so it has a low-level core which is super fast and on On top of it, you can build high level abstractions without paying extra cost. So what I have so far
is that this low-level core is mostly done or very in a very good shape and now I can start building my own abstractions which means for example that I don't have list type in spy. So
it's it's very work in progress but why because list will be implemented in SPy itself and it's actually what I'm going to do next. So next I want to have like more built-in types like list,
dictionary, arrays. >> Mhm. And um I also plan to have a initial kind of integration with uh CPython so that from a SPy module you can generate a CPython extension which
is fast and usable in Python programs and and I want to mod like it generally improve ergonomics of the language because right now it's like sometimes get just a crash in the interpreter and
>> So you mentioned that SPy has two levels. Can you walk us through the compilation pipeline? So let's say I create a file with the extension.spy. I write there I create there an array or
something and I have some for loop. What happens under the hood? >> Okay. So from from a high level point of view what SPy does is pretty textbook. Uh so to start
with we have two modality. SPy is both an interpreter and a compiler which is super important because as a developer for developer experience you want to have an interpreter which is nicer to
debug and uh get better except exceptions fast development cycle all the thing that we like in Python >> and that's the concept of the red and blue code right
>> yes so the the the pipeline is that you start with source code you parse it and you get an a >> and then in the interpreter what you have is a pretty standard uh asbased uh
uh interpreter which works along the a and evaluate all the nodes. The innovative part is how you go you go from interpreter to the compiler and the idea is that what I was saying before a
lot of stuff can be precomputed and instead of be a best effort and hoping that stuff doesn't change inspire the type system in design in such a way that a lot of the stuff is actually
provable as constant. >> Mhm. and uh and then can be optimized that way before the compilation and uh the visualization of this is this blue and red uh nodes. So you imagine to have
the A which is a tree >> and then you have a step in which you color the A and you see that some mod some nodes are blue which means that they are safe to be premputeed because
they are guaranteed to give the same result again and again and and so there's this process of red shifting which basically takes its color a find the blue parts premputee them and
substitute this big tree with just a single node which is the And the the what what's left is a much smaller tree which is easy to compile and faster to execute.
>> Right. And I wonder why did you name them red and blue? Is it from matrix? >> No, I didn't think about that. Actually, it comes from pi. You asked before. So in PyPy we have similar concepts. Um in
the PyPy jet you have concept of green and red variables and that's very similar to to to to the concept in spy. Um so at the beginning I actually called them green and red but then someone pointed
out that is not uh blind color friendly and and so I checked and um yeah seems that blue and red is a good combination that's why is that way >> but I think it actually having color I
mean it could be like a color A and B like they they need to be two categories don't need to color but having like a colors I think it will be important later because I plan to have like
visualizations or IDI ID plugins pretty printers in which you can see like you type your code and you see some code is in blue some code is in red it's immediately obvious what is like free
and will not cause computation at at runtime and what will be the actual computation so I think it will be an important part of the ergonomics of the >> and when you mentioned PyPy let's talk
about the difference between those on a practical level when should I use which one Let's say I'm starting a new project. I want to use Python because I'm a Python developer. So I don't want
to learn Rust or C++ for example. But at the same time, Python is too slow for my needs. I need some scientific computing or something like that. And except of those two, there are also lots of other
variants. So when should I use which >> That's a that's a a kind of a pain point. Uh because PyPy historically has been the most advanced Python implementation around and the fastest.
Um the problem is that as soon as you execute pure Python code then PyPy works as a breeze. Um the pain point comes when you want to interact with extensions which are written in other
languages usually C or C++ and they talk to the interpreter using the C API. And uh for reasons which are too long to explain, I can go go out for hours on this topic. Uh the C API of CPython is
designed in such a way which is very tight to internal implementation. >> So if you're C Python, it's very easy to expose this API. But if you are any other uh implementation,
the thing just don't match. It's like trying to to put like a a US plug into European socket. doesn't work. So you need to work >> oil and water
>> same mix. >> Yes, exactly. And so you need a kind of an adapter but which we de developed in PyPy but it's very expensive at runtime because you need to emulate a lot of
stuff that you don't have >> and and this means that in PyPy as long as you are in pure python everything is super fast but as as soon as you cross the border to see it um it's very very
slow and it becomes like slower than c python or without a jet >> right so that means that if you if I use Python and I do for example data science where I use some libraries which are
written in C PyPy should not be the best by default is not a safe choice. >> You can use it in ways if if you can restrict your code in such a way that like is border crossing is not too often
but you need to be become very very expert in the field. I I that's why PyPy is less relevant than it was before because in the last latest years Python like data science and numerical
computation became an incredibly important part of the Python world and uh for that you need C extensions and then they don't work well in pip >> right and SPy works with C extensions
>> not yet but the idea yes is that I want that's one of the problem that I want to solve like SPy I will be able to integrate with CPython ecosystem uh in an easier way. Although probably a spy
only program will always be faster than a SPy plus extension program but it would not be as bad as a pipe. >> And are there any other projects or initiatives that I can also use
>> for what? For to make your code faster >> to make my code faster. Yes. it really depends on the code. There is no silver bullet. Um the the usual suggestion is so the usual suggestion is
first first of all profile you don't know why your py your code is low and if you think you know you're probably wrong and that's by experience like every time I look at some code and yeah it's
obviously there then your profile is not >> so do you have any similar stories like when you thought that you knew why it was slow but then you realize that it's something different
>> yes um So >> what do you think is the most common reason like why or the most common misconception where people think what people think that is slow but it
actually it's not slow as they think they is. >> Uh I think that a very good expl uh candidate is memory memory copy. >> Uh copying memory on modern computer is
actually fast especially compared to all the stuff that you do when executing Python code. So very often and it's a mistake which I made you you elaborate complicated data structure. So you can
have something which you don't do copy and then you need to do caching and uh you you you have references and etc. And uh and then it turns out that if you just copy the whole thing and then you
have a simple data structure for attribute access later it's faster. Uh back in the days I was working for a company um I don't want to enter into details but we had kind of a a a server
which uh produced jobs to solve and then a lot of workers. >> Mhm. And but passing the job to the to the workers was like potentially heavy like lot of memory. And so I tried with
a scheme in which you had shared memory and put the job there and so the the worker could like read into the shared memory and was very complicated and it turned out that
didn't work so well. So later the second try was okay let's just write things in a way that they can be be copied as a bulk to the uh to the worker
>> and that work very very well so the actually memory copying was not the bottleneck at all there were other things so that's >> and how does memory management work in
spy does it work the same like in Python that you have a garbage collector and reference count or do you have a different system >> so that's currently SPy is a garbage
uncollected language So [laughter] no. Okay. So SPy will have a garbage collector. Uh right now it's just not implemented. So uh for it's for demo purposes it works very it works well
enough but it's not usable for anything >> Uh the idea is that depending on the target you should be able to plug into different memory management system. In particular, if you have a SPy only um
program, I plan to have uh like advanced garbage collectors like moving generational garbage collector which usually they they are faster than other >> If you want to integrate with CPython
ecosystem then you are forced to use CPython memory management which means reference counting and uh and then the generational uh sorry the cycle detector of CPython.
That's that that's one reason why is not full developed. I I need to understand exactly where to how to wire up things. >> Yeah. And if someone would like to try SPy or would like to use it in their
projects, when do you think that it will be mature enough to be used in production? Is it a matter of months, years, many years? >> So depends depends really strongly
depends on the use case. Um so okay if for something which imagine that you want to do a numerical kernel something that you can use number nowadays so like uh uh you have
a single function which does numeric uh uh computation and get arrays as input and outputs I don't think we are very far from that so months >> months okay
>> uh if you want but the point of SPy is that we I want to be like much to support much more features than than number. So for that well it's at least one year but it's very hard to give any
estimate. It's very research R&D project >> and if the community would like to get involved with it, it's an open source project, right? So, how can I get >> So, yeah, like the best way is uh GitHub
spy. Um I am the point in which contributions are welcome. Uh I I I have some issues which I label as good for the issue and uh uh help wanted on GitHub and I think they're like easy
enough for external people to to start getting a a grasp of both the language and implementation is not a super easy project. You need to have some experience with compilers and
interpreters and language implementation at the moment. when the language mature probably it should be possible to contribute even without knowing something about
compilers because you can just write standard library in SPy like that there will be a lot of uh work to be done on that field so that's also a a good opportunity but at the moment I feel
that we're not at so advanced yet and uh so yes github.com is >> and is everything written in C or can I contribute with Python only or for example do you need help with code
reviews use or documentation as well. >> Uh documentation yes the documentation is inexistent. So [laughter] >> if someone would like to try and create >> uh I plan to write a series of blog post
to explain uh motivation and technicalities of SPy also because like everything is very in flux and and changing. So blog post at the moment is a better way because it doesn't need to
be it can be more colloquial let's say but eventually I need to write down a real do documentation system and even even just setting up the CI and everything uh uh publishing uh I can do
it I prefer to spend my time on something else. So this is the kind of uh contribution which are very >> contributions are are welcome. >> Yeah totally. Um you you I think you ask
a different another question which I >> I asked about code reviews for example because that's a good way how to start for example. >> Yes right now like I don't have I mean
to get I need I need a contributors first. So >> yes [laughter] [snorts] and my last question is what is the significance of the name spy? Does
it officially stand for static python or is there any story about this? >> So there is a small story like it it does nothing to do with spies. uh like the S is for static Python but as we
said earlier the roots are in PyPy world and in PyPy we added this implementation language which was called is still called air python for restricted python and so a SPy takes a lot of inspiration
from that is from some of the view air python 2.0 zero and so SPy is the s after the earth. So it's this kind of >> Thank you for coming.
Behind the Commit is a podcast hosted by Mia Bajić. All episodes.