Skip to main content

Compile PyTorch models into TensorFlow custom ops backed by Triton PTX kernels

Project description

Mirai

A compiler that converts PyTorch models into deployable TensorFlow custom ops backed by Triton PTX kernels.

Mirai takes a decorated PyTorch function, runs torch.compile to generate optimized Triton kernels, extracts the PTX, and wraps everything into a TensorFlow custom op — with a single function call.

Quick Start

import torch
import mirai

@mirai.op(name="Pffn")
def pffn(inputs, w_gate, b_gate, w_up, b_up, w_down, b_down):
    inputs_t = inputs.transpose(0, 1).contiguous()  # TF side cannot represent non-contiguous tensors
    gates = torch.bmm(inputs_t, w_gate) + b_gate.unsqueeze(1)
    gates = torch.nn.functional.silu(gates)
    vals = torch.bmm(inputs_t, w_up) + b_up.unsqueeze(1)
    outputs = torch.bmm(gates * vals, w_down) + b_down.unsqueeze(1)
    return outputs.transpose(0, 1)

# One call: torch.compile → PTX extraction → C++ codegen → build script
mirai.build(pffn, sample_inputs=[inputs, w_gate, b_gate, w_up, b_up, w_down, b_down])

Output in ./generated/:

generated/
├── PffnFwd.cc          # TF custom op C++ source (forward)
├── PffnBwd.cc          # TF custom op C++ source (backward)
├── build.sh            # g++ compilation script
├── pffn_api.py         # TF Python API wrapper
└── tf32/               # PTX kernels and metadata
    ├── PffnFwd/
    └── PffnBwd/

Build the op:

cd generated && bash build.sh

Dynamic Shapes

Use dynamic=True to generate shape-generic ops that accept variable batch sizes at runtime:

mirai.build(pffn, sample_inputs=sample_inputs, dynamic=True)

A single compiled op then handles any batch size — no recompilation needed:

# TF side: same op binary, different batch sizes
out = pffn_op(inputs_2000, ...)   # bs=2000
out = pffn_op(inputs_8000, ...)   # bs=8000

See examples/pffn_dynamic.py for a complete example.

Requirements

The pipeline spans two environments (typically on different machines):

Stage Dependencies
Code generation (mirai.build) PyTorch 2.x, CUDA
Op compilation (build.sh) TensorFlow 1.x, CUDA

Run mirai.build() in the PyTorch environment, copy generated/ to the TF environment, then bash build.sh.

Install

pip install mirai-compiler

How It Works

Mirai bridges two frameworks at the PTX level — it leverages PyTorch's compiler stack to produce hardware-optimized GPU kernels, then wraps them as native TensorFlow ops.

                        PyTorch environment                          TF environment
               ┌─────────────────────────────────────────┐    ┌──────────────────────┐
 @mirai.op  →  │ torch.compile  →  Triton  →  PTX/CUBIN  │ →  │  C++ TF custom op    │
   function    │    (max_autotune, fwd + bwd)            │    │  (.so, Python API)   │
               └─────────────────────────────────────────┘    └──────────────────────┘

Under the hood:

  1. Trace & Optimizetorch.compile with max_autotune explores kernel configurations across the search space. Both forward and backward graphs are traced and optimized independently.

  2. Intercept & Extract — Mirai rewrites the inductor-generated Python via AST transformers, injecting hooks that capture PTX binaries and tensor metadata at each kernel launch site. The patched code runs in an isolated subprocess.

  3. Codegen — Each captured kernel is rendered into a self-contained C++ TF op via Jinja2 templates, complete with shape inference, PTX loading, and CUDA launch logic. A Python API wrapper with tf.custom_gradient connects forward and backward ops seamlessly.

Project Structure

mirai/
├── build.py           # mirai.build() entry point
├── decorator.py       # @mirai.op decorator
├── pipeline.py        # Per-kernel: AST patch → PTX extraction → C++ render
├── codegen/           # AST transformers, C++ / build.sh / API renderers
└── templates/         # Jinja2 templates (kernel.cc, build.sh, api.py)
examples/
├── pffn.py            # Static shape example
└── pffn_dynamic.py    # Dynamic shape example

Development

pip install -e ".[dev]"
black --check mirai/ tests/ examples/
pytest tests/ -v

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mirai_compiler-0.2.2.tar.gz (31.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mirai_compiler-0.2.2-py3-none-any.whl (31.6 kB view details)

Uploaded Python 3

File details

Details for the file mirai_compiler-0.2.2.tar.gz.

File metadata

  • Download URL: mirai_compiler-0.2.2.tar.gz
  • Upload date:
  • Size: 31.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for mirai_compiler-0.2.2.tar.gz
Algorithm Hash digest
SHA256 6e4b49f500455c84445595d04355daf80494ec369301b6f3369cbaa6ddc7f09e
MD5 4f0368617b5c5b42f2f3a53134127a07
BLAKE2b-256 8713a209eb4283308f22988a045c45d9a77ee6ff2f5993ec4f02b878ed9e7bb0

See more details on using hashes here.

Provenance

The following attestation bundles were made for mirai_compiler-0.2.2.tar.gz:

Publisher: publish.yml on dawnop/mirai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file mirai_compiler-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: mirai_compiler-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 31.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for mirai_compiler-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 cc17bc463a3da91afc44b9d16e8323fcc090ed3fbc7f551b48d7905c5d50108e
MD5 10519959552b5ced655290357e68931e
BLAKE2b-256 b36791b1c954eda0fcbfcfb84770205e808745040d4d7b0be12acbdb7bf740fe

See more details on using hashes here.

Provenance

The following attestation bundles were made for mirai_compiler-0.2.2-py3-none-any.whl:

Publisher: publish.yml on dawnop/mirai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page