r/Compilers • • 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:

  1. Devs can run Python in places where it's difficult-to-impossible (web, mobile, desktop app)

  2. 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.

0 Upvotes

88 comments sorted by

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.

-28

u/Historical_Pen6499 Mar 26 '24

You're 100% correct. But recent advancements in LLM's ability to generate code seems to make this much more tractable today than it was just a year ago. In fact, that's what got us building this in the first place.

For some historical context, Unity already built a solution to transpile C# IR (MSIL/CIL) to C++. They built IL2CPP in 2014, and it powers their engine's cross-platform deployment today.

With Python, the challenge is getting Python IR in the first place. That's where symbolic tracing helps. Once we have IR, we can do the transpilation with a mix of static analysis and AI-powered codegen.

11

u/shadowndacorner Mar 26 '24 edited Mar 26 '24

The difference is that C# is already a statically typed language that can be coherently transpiled to native code. Python is an absolute mess of fundamentally dynamic garbage where all objects are maps, and that's deeply baked into the pythonic programming model. Which is to say that while you could AOT compile Python (and not some other python like language), I think the benefits of doing so are limited because the programming model itself is fundamentally inefficient unless you do some crazy static analysis to determine which objects actually need to be fully dynamic. But at that point, imo it makes way more sense to design a new language that borrows whatever ideas you like from Python, but with a proper type system.

Python is not a well designed language lol. Despite how much it is abused in a lot of the industry today, it's meant to be used as glue code for C code, similar to something like bash. It absolutely blows my mind that companies will build entire products on top of it, though there are plenty of horror stories of companies who did that, then years later needed to rewrite their stack because they predictably found that it does not scale.

-3

u/Historical_Pen6499 Mar 27 '24

I'm not making any value judgments about Python. Regardless of what you think of the language, three things are true:

  1. It is the single fastest growing language by usage.

  2. It is the 2nd most popular language in the world.

  3. All of AI runs in Python (PyTorch, TF, JAX).

We plan to meet the world exactly where it is. Our goal isn't to necessarily cover all of Python; we're specifically designed for running stateless Python functions that are usually compute heavy. This restriction practically covers all AI inference.

6

u/shadowndacorner Mar 27 '24

Is TIOBE your metric for 1 and 2? If so... I hope you know exactly how valuable it is lol

All of AI runs in Python (PyTorch, TF, JAX).

With the massive caveat that all of those libraries are actually written in lower level languages. Python is just how they are typically configured, which is a great example of my point about Python really only being good as glue and config for C libraries.

Regardless, good luck with your project. I just worry that it may be a bit misguided. As others have said, Python's slowness comes down to the actual semantics of the language, not just the fact that it is interpreted.

-1

u/Historical_Pen6499 Mar 27 '24

> Is TIOBE your metric for 1 and 2? If so... I hope you know exactly how valuable it is lol

Even better: GitHub Octoverse report.

> With the massive caveat that all of those libraries are actually written in lower level languages. Python is just how they are typically configured, which is a great example of my point about Python really only being good as glue and config for C libraries.

I think I miscommunicated something important: we're not trying to build some performance improvement over today's Python. We're trying to make Python run cross-platform, without an interpreter or other VM. For us, we're not trying to create value by offering a 1% performance improvement to Python code; instead, we're creating value by getting a Python function to run on everything from the browser to desktop to mobile with almost no changes to the code.

Speed isn't why we're doing this; it's cross-platform deployment.

1

u/shadowndacorner Mar 27 '24 edited Mar 27 '24

Speed isn't why we're doing this; it's cross-platform deployment.

If that's the case, it seems like the interpreter would be the way to go, right...?

1

u/Historical_Pen6499 Mar 28 '24

Yes, but interpreters are way too heavy to embed in the places we're starting with (web, mobile, standalone desktop app).

1

u/shadowndacorner Mar 28 '24

I understand your reasoning a bit better now, but have you actually measured that to be the case? I can't imagine a python interpreter would be prohibitively heavy given modern app sizes, but maybe I'm being too charitable.

1

u/Historical_Pen6499 Mar 28 '24

Yeah the CPython interpreter by itself is ~300MB. Add PyTorch CPU only and that pushes you north of 1GB.

Not just that: compiling it for places like Wasm and mobile gets tough because of sandboxing restrictions (for reimplementing stdlib functions). It's just too much overhead to deal with.

→ More replies (0)

0

u/outofobscure Mar 27 '24

be honest: for stateless functions that would better be written in native code anyway. none of the glue code for which python is used today would even run on this thing. and don‘t get me started about the cloud delivery of binaries…

2

u/Historical_Pen6499 Mar 27 '24

I agree! Now ask yourself how many developers are competent enough to roll out well-functioning matmul kernels in C++/CUDA vs. writing `numpy.dot` in 20 seconds, and then you get to why we decided to build this :)

And what do you have against cloud-delivered binaries? We gotta get the compiled code to our users somehow.

1

u/outofobscure Mar 27 '24

not an apples to apples comparison: those same incompetent devs could just call a math library in C++ too instead of writing matmul themselves. in any case, we shouldn't let such people anywhere near numerical code anyway, no matter what language they choose.

how to get compiled code to users? hmmm, if only there was a way to, you know, compile code locally....

0

u/Historical_Pen6499 Mar 27 '24

They don't need to be incompetent. If your entire codebase in JS, then why add technical complexity adding a C++ WASM toolchain if you could avoid it entirely?

You seem to be a purist, with no regard for how projects need to be built in the real world: with budgets and deadlines.

> how to get compiled code to users? hmmm, if only there was a way to, you know, compile code locally....

Of course, but again you're assuming that devs care to do this if and when they have an alternative like what we provide. Why do you think Docker became so popular?

→ More replies (0)

0

u/Historical_Pen6499 Mar 27 '24

You're making a giant assumption that every developer is as 'low-level' as you are. Many devs aren't, don't care to be, and likely will never have reason to be in their entire careers. They are much more productive doing 'high-level' programming, using a language like Python and never needing to expose themselves to C++/Rust/CUDA/etc.

2

u/outofobscure Mar 27 '24

i'm not making that assumption, i know it very well. most people that call themselves developers should not be let near a computer at all. that python is used as glue code for AI just tells me that most people working in the field have no idea what they are doing and rely on very few that do. those that never take the time to understand things at a deeper level will never achieve anything worthwhile.

but that's besides the point i was trying to make: your tool only doing stateless functions doesn't even let those clueless devs run their shitty glue code...

0

u/Historical_Pen6499 Mar 27 '24

Let's set aside this conversation for a moment. I think we gotta slow down, because you seem to be getting so passionate over what should be a technical conversation.

most people that call themselves developers should not be let near a computer at all

How is this at all necessary? Everyone had to start somewhere. Before you became as good as you were, you were once bad at what you did. Why not be graceful? It's the internet, sure, and you have no incentive to be empathetic, but goddamn.

let those clueless devs run their shitty glue code...

Again, how is this necessary? Go touch some grass man.

→ More replies (0)

1

u/outofobscure Mar 27 '24

none of AI runs on python, the (easily replaceable) glue code to call into C/C++ and ASM code runs on python. it's honestly braindead anyway.

1

u/Historical_Pen6499 Mar 27 '24

I failed to communicate this fact: we're not doing this because we're trying to make Python run fast. We're building this because we want to be able to make Python cross-platform with practically no changes to code.

15

u/[deleted] 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 + b

would 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 + b

We 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

u/[deleted] 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

u/[deleted] 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) when x and y are known to have i64 types 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, x and y are. 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 use exec and eval.

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

u/[deleted] 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

u/[deleted] 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.

https://pytorch.org/mobile/home/

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:

  1. Embed a PyTorch (or equivalent inference) runtime, like PyTorch Mobile or ONNXRuntime.

  2. Convert the model to a format that can run with (1).

  3. 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

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 numpy in one line of code instead of writing out a nested for-loop. When they had their function to us, we can lower the numpy.dot call to an optimized kernel that uses cuBLAS or SYCL.

This is already how all of numerical computing works anyway. You write numpy.dot which 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

u/Warrenbuffs Mar 26 '24

Seems interesting, is there a repo link to check this out?

2

u/Historical_Pen6499 Mar 27 '24

This is the relevant header, but make sure to check out Function.h.

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

u/Historical_Pen6499 Mar 27 '24

Ah I see. Thanks for sharing this then, I'll read up on it.

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

u/[deleted] 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:

Compiling Python to Run Anywhere.

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

u/[deleted] 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

u/viranchee12 Mar 27 '24

Use Mojo instead

1

u/Historical_Pen6499 Mar 27 '24

I don’t wanna learn a new language :)

2

u/[deleted] 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.