codon README

The project's README from github.com/exaloop/codon. As one markdown file: README.md.

Codon banner

Docs  ·  FAQ  ·  Blog  ·  Discord  ·  Roadmap  ·  Benchmarks

Build Status

What is Codon?

Codon is a high-performance Python implementation that compiles to native machine code without any runtime overhead. Typical speedups over vanilla Python are on the order of 10-100x or more, on a single thread. Codon's performance is typically on par with (and sometimes better than) that of C/C++. Unlike Python, Codon supports native multithreading, which can lead to speedups many times higher still.

Think of Codon as Python reimagined for static, ahead-of-time compilation, built from the ground up with best possible performance in mind.

Goals

Non-goals

How it works

Codon figure

Quick start

Download and install Codon with this command:

/bin/bash -c "$(curl -fsSL https://exaloop.io/install.sh)"

After following the prompts, the codon command will be available to use. For example:

Many more options are available and described in the docs.

Alternatively, you can build from source.

Examples

Basics

Codon supports much of Python, and many Python programs will work with few if any modifications. Here's a simple script fib.py that computes the 40th Fibonacci number...

from time import time

def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

t0 = time()
ans = fib(40)
t1 = time()
print(f'Computed fib(40) = {ans} in {t1 - t0} seconds.')

... run through Python and Codon:

$ python3 fib.py
Computed fib(40) = 102334155 in 17.979357957839966 seconds.
$ codon run -release fib.py
Computed fib(40) = 102334155 in 0.275645 seconds.

Using Python libraries

You can import and use any Python package from Codon via from python import. For example:

from python import matplotlib.pyplot as plt
data = [x**2 for x in range(10)]
plt.plot(data)
plt.show()

(Just remember to set the CODON_PYTHON environment variable to the CPython shared library, as explained in the the Python interoperability docs.)

Parallelism

Codon supports native multithreading via OpenMP. The @par annotation in the code below tells the compiler to parallelize the following for-loop, in this case using a dynamic schedule, chunk size of 100, and 16 threads.

from sys import argv

def is_prime(n):
    factors = 0
    for i in range(2, n):
        if n % i == 0:
            factors += 1
    return factors == 0

limit = int(argv[1])
total = 0

@par(schedule='dynamic', chunk_size=100, num_threads=16)
for i in range(2, limit):
    if is_prime(i):
        total += 1

print(total)

Note that Codon automatically turns the total += 1 statement in the loop body into an atomic reduction to avoid race conditions. Learn more in the multithreading docs.

Codon also supports writing and executing GPU kernels. Here's an example that computes the Mandelbrot set:

import gpu

MAX    = 1000  # maximum Mandelbrot iterations
N      = 4096  # width and height of image
pixels = [0 for _ in range(N * N)]

def scale(x, a, b):
    return a + (x/N)*(b - a)

@gpu.kernel
def mandelbrot(pixels):
    idx = (gpu.block.x * gpu.block.dim.x) + gpu.thread.x
    i, j = divmod(idx, N)
    c = complex(scale(j, -2.00, 0.47), scale(i, -1.12, 1.12))
    z = 0j
    iteration = 0

    while abs(z) <= 2 and iteration < MAX:
        z = z**2 + c
        iteration += 1

    pixels[idx] = int(255 * iteration/MAX)

mandelbrot(pixels, grid=(N*N)//1024, block=1024)

GPU programming can also be done using the @par syntax with @par(gpu=True). See the GPU programming docs for more details.

NumPy support

Codon includes a feature-complete, fully-compiled native NumPy implementation. It uses the same API as NumPy, but re-implements everything in Codon itself, allowing for a range of optimizations and performance improvements.

Here's an example NumPy program that approximates $\pi$ using random numbers...

import time
import numpy as np

rng = np.random.default_rng(seed=0)
x = rng.random(500_000_000)
y = rng.random(500_000_000)

t0 = time.time()
# pi ~= 4 x (fraction of points in circle)
pi = ((x-1)**2 + (y-1)**2 < 1).sum() * (4 / len(x))
t1 = time.time()

print(f'Computed pi~={pi:.4f} in {t1 - t0:.2f} sec')

... run through Python and Codon:

$ python3 pi.py
Computed pi~=3.1417 in 2.25 sec
$ codon run -release pi.py
Computed pi~=3.1417 in 0.43 sec

Codon can speed up NumPy code through general-purpose and NumPy-specific compiler optimizations, including inlining, fusion, memory allocation elision and more. Furthermore, Codon's NumPy implementation works with its multithreading and GPU capabilities, and can even integrate with PyTorch. Learn more in the Codon-NumPy docs.

Documentation

Please see docs.exaloop.io for in-depth documentation.

Acknowledgements

This project would not be possible without:

codon (exaloop/codon)

Searching Database…

16.9K ·GitHub
What is this?Codon is a high-performance Python implementation that compiles your code straight to native machine code — typically 10-100x faster than vanilla Python on a single thread, on par with C/C++.
So is it a different language I have to learn, or do I write regular Python?You write regular Python: Codon compiles it ahead of time, and many Python programs run with few or no modifications. It avoids adding new syntax, except in a couple of spots like expressing parallelism.
How do I get it running?Install with the one-line command from the Quick start section; that gives you a codon command. Run scripts with codon run file.py (add -release for optimizations) or compile a standalone executable with codon build -release file.py.
What about my existing Python packages — do they work?Yes, via 'from python import'. Set the CODON_PYTHON environment variable to the CPython shared library, and those modules run on real CPython while the rest of your code compiles natively.
Can any Python program run on it, or are there gaps?It's not a drop-in CPython replacement: Python features that don't suit static compilation aren't supported (see 'Differences with Python' in the docs). For larger codebases there's a JIT decorator, a Python extension backend, and full Python interop.
Can it run code on a GPU?Yes — Codon supports writing and executing GPU kernels, including through the same @par annotation with @par(gpu=True). The README demos a Mandelbrot kernel, and the NumPy implementation works with GPU and multithreading too.
Does it really include its own NumPy?Yes — a feature-complete, fully compiled native NumPy re-implementation with the same API. Since it lives inside the compiler, Codon can apply optimizations like inlining, fusion and memory allocation elision, and it even integrates with PyTorch.
How does parallelism work — do I manage threads myself?No. Codon has native multithreading over OpenMP with no GIL: annotate a for-loop with @par (schedule, chunk size, thread count are options) and the compiler parallelizes it, automatically turning accumulations in the loop body into atomic reductions to avoid race conditions.
When would I pick Codon over just running CPython?For compute-heavy work: number crunching, large NumPy array code, or loops you'd otherwise hand-optimize. Anywhere vanilla Python is too slow but rewriting in C/C++ or Rust feels too heavy — Codon keeps Python syntax and delivers low-level-language speed, more still with threads or GPU.
What are similar projects?numba, spinel, taskflow, cython, CalcKernel, cupy, wasmtime, TornadoVM
Creator
exaloop
Size
13.1 MB
Stars
16.9K
Age
5y
Commits · 90 Days