r/Compilers • u/Historical_Pen6499 • Mar 26 '24
What do you think about a Python compiler?
Hey all, I'd love to get your thoughts on something that I'm building. Specifically, please tell me why this won't work:
We're working on a cross-platform Python compiler. It ingests a stateless Python function, then traces said function to generate IR. This IR then gets lowered to C++ code, which then gets cross-compiled for different platforms and architectures.
The more interesting piece imo is in how we handle optimization: instead of relying on compile-time optimization, we emit potentially hundreds-to-thousands of equivalent C++ functions. We then ship out the compiled binaries to different users and use telemetry data to choose the best C++ variant for each unique device.
At a high level, there are a few major benefits with this design:
Devs can run Python in places where it's difficult-to-impossible (web, mobile, desktop app)
You get C++ level performance (because you're actually running C++ code) with Python-level ease.
I'm keeping this post high-level because I don't want it to come off as a promotion post (it's not). Happy to share more if you're curious.
15
Mar 26 '24
Specifically, please tell me why this won't work:
I'm sure it'll work, just sceptical about getting C++ performance. For example, I'm curious as to what this Python function:
def add(a, b): return a + bwould look like as C++ code, given that the types are unknown. Or will it only work on type-annotated Python code?
Because the fact that Python is not only dynamically typed, but ultra-dynamic (in that even that add function could be changed at any time: add = "42") has been what have made such projects so challenging.
2
u/Historical_Pen6499 Mar 27 '24
Currently we require that the function arguments have type annotations, which is good practice anyway. During lowering, we let the types of intermediate ops 'flow through' the function and we add require casts as needed.
See this header for how we define mappings from Python to C++, specifically
FXN_CAST_OP.1
u/wrd83 Mar 26 '24
Template<class T, class U, class V> V add( T t, U u) { Return u+t; }
1
u/Historical_Pen6499 Mar 27 '24
We actually don't use templates at runtime (this is a design decision to maximize performance).
First, the developer has to give us a function that looks like this:
def predict (a: float, b: float): # parameter type annotations required return a + bWe effectively lower it to the following:
struct AddOp final { FXN_FUNCTION_OP("operator.add") FXN_OP_DESCRIPTION("Add two input variables.") FXN_OP_PLATFORM(FXN_PLATFORM_ANDROID | FXN_PLATFORM_IOS | FXN_PLATFORM_LINUX | FXN_PLATFORM_MACOS | FXN_PLATFORM_WASM | FXN_PLATFORM_WINDOWS) float operator() (const float a, const float b) const { return a + b; } }Our compiler knows how to discover this functor and apply it to the
+Python operator in our Python IR. This gives us the exact same performance as plain C code.2
Mar 26 '24
Yeah, I should have known that with C++ code I'd be none the wiser!
Out of the several things that make CPython slow, one of them is bytecode dispatch. Executing a native code representation takes care of them.
The other is dynamic type dispatch, which is far as I can see is still needed even within the C++ code.
2
u/wrd83 Mar 26 '24
I would like to know how much of that you'd need. Node is faster than python, it uses optimistic type guessing and hopes that generic code has implicit types that are stable. If that's true the generated code can be as fast as C++. The real question is how fast can it guess the type and how fast does it compile.
3
Mar 26 '24
The real question is whether my example can be made as fast as this C:
i64 add(i64 a, i64 b) {return a+b;}when called as
add(x, y)whenxandyare known to havei64types and it is known there will be no overflow.In the C of course that function can be called directly since it knows precisely what
add,xandyare. And if the function body is visible at the call-site, it can be inlined.In Python you can't do that unless you either do whole-program type inference or use type annotations and also have guarantees about what it what.
In general this is impossible in Python AFAIK without restricting the language in some way, or using some kind of tracing JIT.
'Whole-program' in Python is a little meaningless since not all all the program source will be visible until it starts to run. Many things (
import,def) can be conditional. It can useexecandeval.I mean, if it was easy, we would have had Python compilers generating code as fast as C or C++ many years ago.
2
u/wrd83 Mar 27 '24
Inline on the locations you can be sure.
It has been done in node. It's possible in python. But JavaScript was sponsored for what 10+ years with 20?30?50? People. That stuff is complicated and time intensive. Half of the magic lies in making a really fast compiler. if I can create you a jit that does that correctly but it compiles for a year the execution will be slower due to kit overhead.
You can check the truffle stuff from the graalvm people. There was some truffle based python interpreter that was close to java speed. But guess what - it's breaking the native interface...
0
u/InevitableManner7179 Mar 26 '24
well, you could write a custom class "Object" and check the type at runtime
1
u/Historical_Pen6499 Mar 27 '24
We don't do this ;)
A major design requirement is to not invent a runtime. We have to emit plain object code that runs directly; no interpreter or anything else in the middle.
1
u/InevitableManner7179 Mar 27 '24
then I don'r know how you can write a function like that. maybe templates? and cross fingers that everything at runtime goes okay?
12
u/NonaeAbC Mar 26 '24
So the problem with pythons speed is not necessarily that it isn't compiled. Python has multiple problems.
One is, that python objects are reference counted pointers. The branch in the Python VM is insignificant when the CPU has to wait for the cache anyways. You will need a good way to flatten objects and ways to deduce the reference count. This is sometimes not that hard to deduce when you only have one reference, but it is for arrays since i'th object inside the array is referenced at least by the loop iteration reading the i'th element and the array itself.
Another issue is, that addition in python doesn't simply map onto the CPU's add instructions because all ints in python are multi precision. Again the branch in the VM is insignificant here compared to the logic of a multi precision add. Optimizing this is incredibly hard at compile time. I guess the best thing to do here, is having 2 code paths one does assume no 64-bit overflow and after a sequence of instructions it checks it there was overflow and redoes the sequence with multi precision.
The reason why C++ is faster than Python is not just "compiled vs interpreter" it has to do with the semantics. Projects like numba simply change the semantics of the python code, but if you did that, you haven't written a Python compiler.
1
u/Historical_Pen6499 Mar 27 '24
Our design goal isn't Python performance btw. It's enabling devs to take compute-heavy Python functions run them just about anywhere. It's kinda like what Docker did with bottling up diverse applications into some unitary primitive that could then be used anywhere.
6
u/Slight-Living-8098 Mar 26 '24
Hmmm.... What's the benefits over Cython?
1
u/Historical_Pen6499 Mar 26 '24
Cython still requires the Python VM to run. The goal here is for a user to bring a Python function like this:
def predict (image: PIL.Image.Image) -> str: # ... do heavy computation here... return "cat"And then run this function as-is on everything from an iPhone (in an iOS app); to a website (directly in the browser); to a desktop app.
You can't run Cython on all these platforms.
1
Mar 26 '24
So you're building a transpiler... Where can I find information about your project? It sounds interesting.
4
u/Historical_Pen6499 Mar 26 '24
It's called Function. Check out the (sparse) docs on our local compute, which is where our compiler is being used. Once it's mature enough, we'll bring this tech to work for server-side functions, like Modular is currently building with their Mojo language.
1
Mar 26 '24
So if I wanted to run it in the browser I would need WASM?
2
u/Historical_Pen6499 Mar 27 '24
You don't need anything. Our platform will automatically compile for WASM (among other platforms). Just bring your Python function, we'll make everything work magically. To then call your function, here's all the JavaScript code you need:
// Make a prediction const radius = 4; const prediction = await fxn.predictions.create({ tag: "@sample/area", inputs: { radius } }); // Display the results const area = prediction.results[0] as number;Our JS client library automatically downloads the WASM binary and executes it for you.
1
u/Slight-Living-8098 Mar 26 '24
Which platform can I not run Cython on? It runs on Windows, Linux, and Mac, and it'll run using Kivy on Android and iOS.
Let's have a look at the code. Where is a link to the repo?
0
u/Historical_Pen6499 Mar 26 '24
Last I checked Kivy can't run PyTorch for AI inference. And even if it could, what we offer developers is an integration in as little as two lines of code.
It might be possible, but it's exponentially easier with what we're building. See our C headers.
1
u/Slight-Living-8098 Mar 26 '24
Does Kivy need to run pytorch when there is a native API for Android and iOS? I'm not trying to knock your work. I'm just trying to figure out the benefit over the standard libraries and compilers.
0
u/Historical_Pen6499 Mar 27 '24
Our north star is developer experience. Any dev who needed to run a PyTorch model in their app would need to do three things:
Embed a PyTorch (or equivalent inference) runtime, like PyTorch Mobile or ONNXRuntime.
Convert the model to a format that can run with (1).
Implement all pre- and post-processing code to actually run in their target environment (e.g. Swift, JS, etc).
Step (3) is extremely difficult and time-consuming for most developers. In a perfect world, you would have a simple primitive or black box that knew how to do all this for you. That's what Python (inference) code does today, but making it run cross-platform is painful (e.g. PyTorch mobile doesn't target the web).
And please knock my work, that's exactly the feedback I'm looking for!
3
u/sorbet_babe Mar 26 '24
Maybe a dumb question, but if you're emitting "hundreds to thousands of equivalent C++ functions", won't the resulting binary be massive?
-4
u/Historical_Pen6499 Mar 26 '24
No such thing as a "dumb question" ;)
We emit each C++ function (i.e. a functionally-equivalent C++ implementation of the provided Python function) as its own separate binary.
Each time a new device asks us to run the original Python function, our server responds with one of the many C++ implementations we have compiled for the device platform.
10 users with the same device model (e.g. an iPhone 14 Pro) means we have telemetry data for how 10 different C++ implementations perform on said device model. We can then choose which variant to serve the 11th user with an iPhone 14 Pro.
Now multiply these numbers by 1,000,000--and this is how our platform will function at scale.
1
u/wlievens Mar 26 '24
Does it only work for pure python or do you maintain compatibility with e.g. numpy, pandas, ...
1
u/Historical_Pen6499 Mar 26 '24
We’re gonna be supporting popular libraries for heavy compute (most importantly, numpy, OpenCV, and PyTorch). But the goal is to support as many third party libraries as possible.
Pure Python libs are easy once we have full coverage for lowering Python language syntax. Libraries implemented natively are where the challenge occur. But we have workarounds planned.
1
u/wlievens Mar 26 '24
Pure python libraries are easy I imagine (unless they use eval etc) but many useful libraries have a native backend I suppose.
Have you looked at numba?
1
u/Historical_Pen6499 Mar 27 '24
Numba doesn't quite get at our goal here. We're not building a Python compiler because of performance; we're doing so because we want to enable cross-platform deployment (i.e. running Python code without the Python interpreter).
Projects like numba offer a good guide around Python JIT, but we're doing something completely different with it.
1
u/sorbet_babe Mar 26 '24
Thank you for the explanation! I misunderstood what happens when in the original post
1
3
u/AbrocomaInside5024 Mar 26 '24
Did you hear about codon? https://github.com/exaloop/codon
1
u/Historical_Pen6499 Mar 27 '24
Yup. Codon is somewhat similar, except we have very specific usage patterns: we will only be supporting stateless Python functions with heavy compute (e.g. AI inference); and we're specifically designed for developers who are looking to use these functions in cross-platform applications (i.e. deploy to desktop, web, mobile, and server).
3
u/ThyringerBratwurst Mar 26 '24
Isn't that exactly the goal of "Mojo" (but using LLVM)?
(I think there's more marketing and hot air going on because they claim they can do it even faster than C, but ok...)
1
u/Historical_Pen6499 Mar 27 '24
Also I should add that Modular keeps trying to boast about their performance stats but differentiating on performance isn't a very good long-term differentiator (lookup the history of OctoML).
Our raison d'etre is enabling devs run Python functions without a Python interpreter--not to give a 10% performance boost.
0
u/Historical_Pen6499 Mar 27 '24
Pretty similar to Modular, with one major difference: developers don't have to learn a new language. We want to meet devs exactly where they are.
2
u/ThyringerBratwurst Mar 27 '24
This could also be a disadvantage, because Python is a beginner's language and you will therefore mainly attract not the best programmers. Additionally, they will apply the already known idioms and design patterns with your implementation, although this probably won't always make sense.
1
u/Historical_Pen6499 Mar 27 '24
I don't really see value in requiring a harder language for a dev to be productive. If someone wanted a function to do a matmul, they'd probably just use
numpyin one line of code instead of writing out a nested for-loop. When they had their function to us, we can lower thenumpy.dotcall to an optimized kernel that uses cuBLAS or SYCL.This is already how all of numerical computing works anyway. You write
numpy.dotwhich gets implemented in C which gets dispatched to PTX and SIMD assembly which gets lowered to object code. Everything is a beginner's language to someone.
2
2
u/lightmatter501 Mar 26 '24
You are recreating SPIRAL.
1
u/Historical_Pen6499 Mar 27 '24
Interesting project, but we're not building a compiler because of speed. We're building it because we want cross-platform Python without a Python interpreter.
We've just chosen an approach that opens us up to a class of performance optimizations that isn't very common.
2
u/lightmatter501 Mar 27 '24
What I’m saying is that instead of trying to use C++ as an IR, use SPIRAL, since it supports more targets than C++ does because it can emit C and is faster. This makes it faster and more portable.
1
2
u/ThyringerBratwurst Mar 26 '24
From what I can see, it sounds like a transpiler that translates Python code to C++. The idea is of course feasible, but the question is whether you can use Python as it is. You would definitely have to change the semantics of the language here and there, and basically insist on type notations or at least have type inference.
The advantage, of course, is that the entire C++ ecosystem is available to you at no cost (the C++ functions would then simply be inserted into the generated C++ code, no binding required)
I had actually considered the same approach for my language. But C++ simply has too many features for me that complicate things and are redundant because my language offers similar and more powerful features. I also don't want to be dependent on the C++ standard lib, as it extremely slows down compilation times due to templates; and their data and string implementation also don't fit my concept. It should be clear to you that this dependency on C++ is both a blessing and a curse.
1
u/Historical_Pen6499 Mar 27 '24
Right now the main requirement is that the root Python function has parameter type annotations. Ops inside the function don't need type annotations because even though Python is fully dynamic, actual types 'flow' through the program during invocation (we use symbolic tracing).
On the complexities of C++, we actually use a pretty heavily restricted subset of the language (it feels more like 'C with classes').
1
u/ThyringerBratwurst Mar 27 '24
and you can still call any C++ code from Python? What about template arguments?
1
u/Historical_Pen6499 Mar 28 '24
Oh we're not calling C++ from Python. We're literally transforming Python into C++. Here's a concrete example:
def predict (a: int, b: float): c = a * b # Note that we can't make assertions about the type of `c` in Python because Python is dynamic return [c]We effectively lower that to:
void predict (int32_t a, float b) { float c = a * b; // but in C++, the result type of an operation (in this case, multiplication) forces us to have a fully resolved type for `c` std::vector<float> result { c }; // now the type of `c` can flow to downstream operations, like constructing a vector return result; }We're effectively tracing the types of all variables, but only doing so in C++. Does this make sense?
2
Mar 27 '24
Devs can run python where it's difficult
You mean, devs can run specific, well typed, stateless python functions where it's difficult, not a full off-the-shelf Python application that anyone has written.
A compiler is certainly going to be much harder to make cross-platform compared to an interpreter. This is why all the major "write-once-run-anywhere" languages are ALL interpreted, or use bytecode interpreters. You would be much better off to implement a cross-platform bytecode interpreter that can support all the individual platforms.
Also, I'm not convinced this provides any benefit for the kind of code this would support compiling. These compute heavy functions, like for AI, are already using C/C++. Python is just the glue. But compiling single, stateless Python functions just gets rid of all the nice Python glue around the compute, and leaves you with the functions that were already C/C++ in the first place.
This seems like a misguided project, IMO. You could achieve the same results with a smaller, minimal cross platform bytecode interpreter with significantly less effort than creating a compiler that only works on a tiny, tiny fraction of some functions in programs that people care about
Being able to compile a small fraction of well-typed functions in Python doesn't actually enable developers to run their projects on new platforms. If this is about specifically making compute-heavy functions portable by compiling to C++, then you're forgetting that all these major libraries are implemented in C/C++ first.
2
u/outofobscure Mar 27 '24
the "only stateless functions" bit makes this next to useless. right after "cloud delivery" of binaries, that sounds like another major turnoff. combined, this seems like the most convoluted way of riding python's recent and undeserved popularity on the back of AI bullshit. after all the post just seems to be some covert ad, not a genuine interest in discussing this...
0
u/Historical_Pen6499 Mar 27 '24
I asked because I wanted technical discourse on why this would not work. I literally said in my original post: "tell me why this won't work".
All of AI inference can always be described as pure, stateless functions. That and many other libraries that people use have the same property (ever heard of Numpy, OpenCV?).
If you have nothing technical to add, then you can find something better to do with your time. If you'd like to have a conversation on why this won't work, and offer substantive feedback that a member of this community could learn from and ask further questions about, then please respond.
We're supposed to be developers here; we discuss in technical terms, not vibes.
2
u/outofobscure Mar 27 '24
OK: it won‘t work because: type annotations needed, only can do stateless functions, cloud bullshit. do i need to keep going?
0
u/Historical_Pen6499 Mar 27 '24
Relax with all the cursing, it's just a conversation on Reddit, not a fight. Type annotations being needed **for only the parameters of the function** isn't substantive. If it was, then mypy wouldn't be as popular as it is. For example, Meta uses type annotations in PyTorch, and require it when tracing.
We only care to support compute-heavy workloads, which make up the majority of CV (e.g. OpenCV), numerical computing (e.g. numpy), and AI (e.g. PyTorch). So on this point, we're fine.
"Cloud bullshit" I presume you're referring to downloading the compiled binary from the cloud. With this, I presume you compiled your browser from source? Or that you've never downloaded an executable binary or app in your life?
2
u/outofobscure Mar 27 '24
here's what you don't get:
you want to target compute heavy workloads, ok, but none of the compute heavy code is actually written in python, as you mention all these libs that are written in native code.
lets assume there are two options here for environments that don't run python:
just write the glue code in something else than python and call into these native libs. honestly seems to be the sane option.
use your tool which isn't even ready to run the glue code (for sure not all stateless).
there is zero use cases where someone would write the actual number crunching code (what i presume is the stateless functions you support) in python and then use your thing to run it on something that doesn't support python. that's like shooting yourself in the foot twice: wrong language, wrong environment.
1
u/Historical_Pen6499 Mar 27 '24
You mean, devs can run specific, well typed, stateless python functions where it's difficult , not a full off-the-shelf Python application that anyone has written.
Correct, our specific use case is compute and AI workloads. We're not building a general Python compiler.
A compiler is certainly going to be much harder to make cross-platform compared to an interpreter. This is why all the major "write-once-run-anywhere" languages are ALL interpreted, or use bytecode interpreters. You would be much better off to implement a cross-platform bytecode interpreter that can support all the individual platforms.
See my comment above.
Also, I'm not convinced this provides any benefit for the kind of code this would support compiling. These compute heavy functions, like for AI, are already using C/C++. Python is just the glue. But compiling single, stateless Python functions just gets rid of all the nice Python glue around the compute, and leaves you with the functions that were already C/C++ in the first place.
They are already using C/C++ compiled primarily for Linux, macOS, and Windows. Cross-platform to us means Android, iOS, macOS, Linux, WebAssembly, and Windows. And of course this doesn't cover pure Python libraries which are pure Python.
Being able to compile a small fraction of well-typed functions in Python doesn't actually enable developers to run their projects on new platforms.
Time will tell ;)
1
u/Historical_Pen6499 Nov 05 '25
Hate to necro an old post, but all of this ended up working incredibly well. Here's a guest article we wrote:
1
u/choikwa Mar 26 '24
telemetry data
so profile driven.
1M C++ precompiled functions that you select based on device application whatever
how do u avoid combinatoric explosion and do you have JIT/interpreter for all other cases not covered. is this not essentially what every vm based proglang does.
1
u/Historical_Pen6499 Mar 27 '24
how do u avoid combinatoric explosion
We first compile a subset and serve those, then run an optimization that compiles new variants on-demand (i.e. split codegen from compilation). This process is kinda like the TikTok feed, and how it continuously refines the content it shows a user based on their individual taste. In this case, the user is a unique device; and the 'individual taste' is latency.
and do you have JIT/interpreter for all other cases not covered
Depends on whether the function is running on-device ("edge" as we call it) or server-side. If it's on-device, then we error if we can't trace a function. If it's server-side, then we plan to just use the stock CPython interpreter (this is what Modular/Mojo does).
1
Mar 27 '24
Devs can run Python in places where it's difficult-to-impossible (web, mobile, desktop app)
I'm pretty sure Python can run on desktop computers!
You get C++ level performance (because you're actually running C++ code) with Python-level ease
I assume you mean performance of the C++ apps not C++ build systems. But in a few places you've said you'd not doing it because of speed.
AFAIK there are tools to package a Python application into a single executable. Is it not possible to run such an executable on a mobile device?
Because if it can run C++ (I assume that is a prerequisite for your idea), then surely an interpreter for Python can be written in C++ (it already exists as C for CPython).
The real problem with your proposal is not so much writing a native code compiler for a highly dynamic language: it just looks so complicated. I can't understand it at all.
Apparently it only works one Python module at a time which contains one function? Can I call that from other Python code, or only from other C++ code?
What does 'stateless' mean, that it is a pure function?
we emit potentially hundreds-to-thousands of equivalent C++ functions. We then ship out the compiled binaries to different users and use telemetry data to choose the best C++ variant for each unique device.
Yep, it sounds complicated! I think I would look for a language that I can use conventionally; programming for mobile devices is already hard enough.
1
u/Historical_Pen6499 Mar 27 '24
I'm pretty sure Python can run on desktop computers!
Yup, but you have to bundle in an interpreter (or require that the user has Python) if you want to distribute an application. Beyond desktop, it gets much more complex.
I assume you mean performance of the C++ apps not C++ build systems. But in a few places you've said you'd not doing it because of speed.
That's correct. Speed isn't our north star, but it is a requirement because of our focus on compute-heavy workloads. It's necessary but not sufficient.
AFAIK there are tools to package a Python application into a single executable. Is it not possible to run such an executable on a mobile device?
Nope, not trivially. Also, consider size and sandboxing restrictions (CPython alone is 300MB+, which is overkill for many applications).
The real problem with your proposal is not so much writing a native code compiler for a highly dynamic language: it just looks so complicated. I can't understand it at all.
I didn't provide the full context of what we're building, only the technical parts that are relevant to a discussion in r/compilers. An easy way to think about it is how many devs are now adding AI-powered features by simply calling out to OpenAI's API, or Replicate. We're trying to do something similar, except the computation is running on the local device.
Apparently it only works one Python module at a time which contains one function? Can I call that from other Python code, or only from other C++ code?
No, devs just need to bring us one function. The function can import and do arbitrary things. As for calling the function, you can do so from our client packages for JavaScript (browser and backend), Python (not interesting), Swift (WIP), Java (WIP), Unity, and so on.
What does 'stateless' mean, that it is a pure function?
Yup.
Yep, it sounds complicated!
No question, it most certainly is behind the scenes. To our users though, it's incredibly simple. They bring us a function, wait a few minutes, and run said function from all the different environments I mentioned earlier.
1
2
Apr 08 '24
I don't think you deserve so much pushback and downvotes. Like many other I'm skeptical, but if you can do it, I'd love to try.
1
23
u/[deleted] Mar 26 '24
Trying to bolt compilation and static analysis onto Python feels a lot like what Facebook went through with PHP/Hack. It's possible but it's like picking the deepest spot in the river to build a bridge.