Skip to content
Projekte

Über uns

Runtime compiler for numerical Python

Wissenschaft und Technik

So werden diese Zahlen gemessen

What you can do

  • Scalar arithmetic, bitwise, and comparison operations (math, uint8–uint64, int8–int64, float32, float64, complex64, complex128, bool, bfloat16 conversions, popcount/clz/ctz)
  • Control flow (if/elif/else, for, while, for/while ... else, break, continue, early return, scalar match/case)
  • Nested functions, lambdas, and closures; default, keyword, and *args/**kwargs arguments
  • Nested tuples, NamedTuples, fixed string-key dicts, @dataclasses, par.nn.Module (normal __init__, pure methods, @property, __call__), par.nn & par.optim helpers, par.Alphabet / par.Vocab ASCII categorical LUTs, RaggedArray, SortedIndex, FrozenHashTable, and BlockMask

Gemessener Sternzuwachs

in 24h
0
in 7 days
0
in 15 days
0
in 1 month
Verlauf wird gesammelt

Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.

README.md

Original

Parakeet

CI Docs

Parakeet is a runtime compiler for an array-oriented subset of Python. It generates a native specialization of a function for each distinct set of input types, fuses and tiles array operations algebraically before lowering them to loops, and runs those loops across CPU cores or on Apple Metal and NVIDIA CUDA GPUs.

The compiler started as a research project at New York University, first presented in a 2012 paper at the USENIX Workshop on Hot Topics in Parallelism (Parakeet: A Just-In-Time Parallel Accelerator for Python, HotPar '12) and in PyData '13 talks, and later formalized in the NYU PhD theses of Eric Hielscher (2013) and Alex Rubinsteyn (2014).

Underneath, ordinary NumPy expressions, comprehensions, explicit loops, and Parakeet's data-parallel operators (parakeet.map, imap, ireduce, reduce, fold, scan, filter, scatter_add, allpairs, flatmap, wavefront) all lower to the same seven index-space primitives (plus optimizer-emitted IndexTile). Keeping that algebraic structure alive until code generation lets fusion, cache/GPU tiling, and reverse-mode differentiation (parakeet.grad) all run on one IR.

Parakeet is not a general-purpose compiler for all of Python. It compiles the numerical subset and reports a source-located compile error whenever you step outside it.

Example

Wrap a function with @parakeet.jit, or call data-parallel operators like parakeet.map and parakeet.imap directly from Python (their callable arguments are JIT-compiled automatically). Throughout the docs and examples, four recurring styles (_numpy, _comp, _loop, _par) show how different Python idioms compile:

import numpy as np
import parakeet as par


@par.jit
def tanh_rescale_numpy(x, alpha=0.5, beta=0.3):
  return np.tanh(x * alpha) + beta


@par.jit
def tanh_rescale_comp(x, alpha=0.5, beta=0.3):
  return np.array([np.tanh(xi * alpha) + beta for xi in x])


@par.jit
def tanh_rescale_loop(x, alpha=0.5, beta=0.3):
  y = np.empty_like(x)
  for i in range(len(x)):
    y[i] = np.tanh(x[i] * alpha) + beta
  return y


@par.jit
def tanh_rescale_par(x, alpha=0.5, beta=0.3):
  return par.map(lambda xi: np.tanh(xi * alpha) + beta, x)


x = np.array([1.0, 2.0, 3.0])
expected = np.tanh(x * 0.5) + 0.3
for fn in (tanh_rescale_numpy, tanh_rescale_comp, tanh_rescale_loop, tanh_rescale_par):
  assert np.allclose(fn(x), expected)

_numpy, _comp, and _par compile to the exact same single-pass parallel loop with zero temporary arrays; _loop compiles to a single sequential C loop.

Install

Parakeet requires Python 3.11 or later and a C compiler.

pip install parakeet                 # CPU backends
pip install "parakeet[metal]"        # + Apple GPUs
pip install "parakeet[cuda12]"       # + NVIDIA GPUs

Dependencies

Parakeet is written for Python 3.11+ and depends on:

  • NumPy 2.0 or newer
  • a C compiler: clang from the Xcode command line tools on macOS, gcc or clang on Linux, MinGW-w64 or LLVM on Windows

That's the whole list. If Parakeet can't find a compiler it says so and tells you how to get one.

For Apple Metal you need a Mac and the PyObjC Metal bindings. For NVIDIA CUDA you need an NVIDIA GPU and CuPy.

How does it work?

Your untyped function acts as a template from which Parakeet generates one type specialization for each distinct combination of argument dtypes, array ranks, layouts, and container structure.

During elaboration, helper calls are inlined, closures and tuples disappear, and array expressions stay delayed until something consumes them, so np.tanh(x * alpha) + beta becomes a single loop with no temporary arrays. What comes out is a small core operator IR (IndexMap, IndexReduce, IndexScan, IndexFilter, IndexExpand, IndexScatter, IndexWavefront, and IndexTile). Middle-end passes apply algebraic rewrites (vertical and sibling fusion, filter fusion, contraction reassociation, rescaled-monoid and pairwise fold tiling, chunkwise scans, and cache/GPU blocking) before lowering to loops, emitting C (plus Metal or CUDA kernels for eligible parallel loops), compiling with your system C compiler, and caching the result on disk.

Every stage is inspectable:

  • par.typed_repr(f, [x]) prints the typed IR,
  • par.show_rewrite(f, x) summarizes which algebraic laws fired, and
  • f.specialize(x).source prints the generated C, Metal, or CUDA source.

Supported language features

Parakeet compiles a static-type numerical subset of Python:

  • Scalar arithmetic, bitwise, and comparison operations (math, uint8–uint64, int8–int64, float32, float64, complex64, complex128, bool, bfloat16 conversions, popcount/clz/ctz)
  • Control flow (if/elif/else, for, while, for/while ... else, break, continue, early return, scalar match/case)
  • Nested functions, lambdas, and closures; default, keyword, and *args/**kwargs arguments
  • Nested tuples, NamedTuples, fixed string-key dicts, @dataclasses, par.nn.Module (normal __init__, pure methods, @property, __call__), par.nn & par.optim helpers, par.Alphabet / par.Vocab ASCII categorical LUTs, RaggedArray, SortedIndex, FrozenHashTable, and BlockMask
  • Slices, range, zip, enumerate, itertools
  • NumPy array expressions (x[1:, :] + 2 * y[:-1, ::2]), with broadcasting, boolean masks, integer-array indexing, and in-place updates
  • Over 210 NumPy functions, ufuncs, and methods (np.ones, np.sin, x.sum(axis=0), np.einsum, np.bincount, np.sort, np.argsort, np.searchsorted, np.linalg, np.random, and the usual builtins: see the full list)
  • Explicit data-parallel operators (par.map, par.imap, par.ireduce, par.reduce, par.fold, par.scan, par.filter, par.filter_reduce, par.flatmap, par.filter_pairs, par.allpairs, par.outer_map, par.parfor, par.scatter_add, par.wavefront, par.batched_wavefront, par.soft_align)
  • Composable reverse-mode, forward-mode, and higher-order automatic differentiation (par.grad, par.value_and_grad, par.jvp, par.vjp, par.linearize, par.linear_transpose, par.hvp, par.jacfwd, par.jacrev, par.hessian, par.stop_gradient, @par.checkpoint, @par.custom_vjp, @par.custom_jvp) with checkpointed for/while loops and algebraic rematerialization for attention, cross-entropy, norms, and soft sequence alignment

Unsupported constructs fail loudly at compile time with the exact source line:

parakeet.errors.UnsupportedError: numpy.fft.fft is not supported in compiled code
  File "demo.py", line 7, in spectrum
    return np.fft.fft(x)
           ^^^^^^^^^^^^^

Runtime failures raise the exception NumPy would have raised (IndexError, ValueError, ZeroDivisionError) instead of crashing the interpreter, even from inside a parallel loop or GPU kernel.

Backends

Parakeet compiles to sequential C, multi-core C, Metal, or CUDA. Switch backends with parakeet.config.backend:

  • "auto": the best multi-core strategy available on your machine (default)
  • "c": lowers all parallel operators to sequential loops
  • "threads" / "multicore": runs parallel operators on Parakeet's own thread pool
  • "openmp": multi-core via OpenMP
  • "gcd": multi-core via Grand Central Dispatch (macOS)
  • "metal" (or "mps"): runs eligible parallel operations on an Apple GPU
  • "cuda": runs eligible parallel operations on an NVIDIA GPU
  • "python": runs your original function uncompiled, handy for checking whether a bug is in your code or the compiler

You can also pick a backend per function (@par.jit(backend="metal")), per call (f(x, _backend="c")), or for a block (with par.options(backend="c"): ...). par.available_backends() reports which backends work on your machine and what is missing for any that don't.

Apple GPUs support float32. Requesting Metal for a loop that uses float64 raises BackendUnavailable at compile time. To run unsupported loops on the CPU with a warning, use with par.options(device_fallback="warn"): ....

Benchmarks

Parakeet is strongest where NumPy or CuPy allocates large intermediates (pairwise distances, attention scores, chained elementwise expressions) or where Python loops replace vectorization. Hand-tuned libraries (Faiss, cuDNN SDPA, cuBLAS, XGBoost, LightGBM) and LLVM/XLA compilers (Numba, JAX, torch.compile) still lead on many workloads; every benchmark reports both where Parakeet leads and where other tools are faster.

Exact 1-NN search on A100 and 32-core CPU

The v1.28.6 release report includes warmed timings, first-call costs, and individual measurements for every suite on the NVIDIA A100 and 32-core CPU tiers. It also covers CPU-only workloads and compares direct PTX, NVRTC and nvcc for nanoGPT. Benchmarks report · Performance guide.

More information

History

Parakeet began as an OCaml compiler modeling the array language Q, shifted to modeling Python, and was reimplemented in Python at New York University (Courant Institute) by co-creators Alex Rubinsteyn (@iskandr) and Eric Hielscher (@hielscher), with Nathaniel Weinman, advised by Dennis Shasha, and with early advice from Russell Power (@rjpower). That Python 2 / NumPy 1 compiler lowered numerical Python to a typed SSA IR of data-parallel adverbs (Map, Reduce, Scan, OuterMap, Filter), fusing and tiling algebraically before emitting C, OpenMP, or CUDA.

The original research is documented in:

Parakeet 1.x is a rewrite for Python 3.11+ and NumPy 2 that keeps @jit NumPy and explicit data-parallel operators together, adds scatter reductions, multi-state folds, ragged compaction, wavefront DP, chunkwise scans, rescaled-monoid GPU tiling, and composable AD, and targets multi-core CPUs, Apple Metal, and NVIDIA CUDA. The older Python 2 codebase remains in Git history.

BSD 3-clause licensed; see LICENSE.

Ähnliche Projekte entdecken

Wird geladen…