KernelLens: Deploying PyTorch @triton.jit Kernels to ONNX Runtime & TensorRT C++ Plugins
Category: Deployment / C++ / Compilers
Hi PyTorch Community!
When writing custom deep learning operators in PyTorch using OpenAI Triton (@triton.jit), models achieve high performance during eager execution and training. However, when transitioning these models to production C++ deployment pipelines (Microsoft ONNX Runtime or NVIDIA TensorRT 10.x), an architectural gap emerges:
- PyTorch ONNX Exporter Tracing Breakdown: Standard
torch.onnx.exportoperates on PyTorch C++ operator schemas. Imperative Python calls to@triton.jitfunctions are opaque to trace backends, leading to tracing failures or missing graph nodes. - C++ Engine Plugin Complexity: Executing custom Triton kernels inside standalone C++ engines requires manually implementing hundreds of lines of C++/CUDA plugin boilerplate (
OrtCustomOpfor ONNX Runtime andnvinfer1::IPluginV2DynamicExtfor TensorRT) to wrap PTX assembly and handle dynamic grid launches.
To solve this, we created Kernel Lens, an open-source compiler framework from Galiad Research that automatically compiles PyTorch models containing Python @triton.jit kernels into native C++ plugins for ONNX Runtime and TensorRT in 1 line of Python.
Minimal Runnable Example
1. Install Dependencies
pip install torch triton kernel-lens
2. Python Script (example.py)
Save the following code to example.py and run it on any CUDA GPU:
import torch
import torch.nn as nn
import triton
import triton.language as tl
import kernel_lens as kl
# 1. Define a custom Triton Kernel
@triton.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n_elements, BLOCK_SIZE: tl.constexpr):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(x_ptr + offsets, mask=mask)
y = tl.load(y_ptr + offsets, mask=mask)
output = x + y
tl.store(out_ptr + offsets, output, mask=mask)
# 2. Wrap the Triton Kernel inside a PyTorch nn.Module
class VectorAddModule(nn.Module):
def forward(self, x: torch.Tensor, y: torch.Tensor):
out = torch.empty_like(x)
n_elements = x.numel()
grid = lambda meta: (triton.cdiv(n_elements, meta['BLOCK_SIZE']),)
add_kernel[grid](<x, y, out, n_elements, BLOCK_SIZE=1024>)
return out
if __name__ == '__main__':
device = 'cuda' if torch.cuda.is_available() else 'cpu'
x = torch.randn(4096, device=device, dtype=torch.float32)
y = torch.randn(4096, device=device, dtype=torch.float32)
model = VectorAddModule().to(device)
print("Compiling PyTorch + Triton Model with KernelLens...")
# 3. Compile Model to ONNX & TensorRT C++ Plugins in 1 Line
compiled_model = kl.compile(
model,
(x, y),
name="simple_vector_add",
backends=["onnx", "tensorrt"]
)
print("Executing Zero-Copy Inference in ONNX Runtime...")
ort_output = compiled_model.run((x, y), backend="onnx")
print("Executing Zero-Copy Inference in TensorRT...")
trt_output = compiled_model.run((x, y), backend="tensorrt")
# 4. Verify Numerical Parity against Eager PyTorch Output
torch_expected = x + y
max_diff_ort = (ort_output - torch_expected).abs().max().item()
max_diff_trt = (trt_output - torch_expected).abs().max().item()
print("Verification Complete!")
print(f"ORT Max Floating-Point Difference: {max_diff_ort:.6e}")
print(f"TRT Max Floating-Point Difference: {max_diff_trt:.6e}")
print(f"Exact Numerical Match (ORT): {torch.allclose(ort_output, torch_expected)}")
print(f"Exact Numerical Match (TRT): {torch.allclose(trt_output, torch_expected)}")
3. Expected Terminal Output
Compiling PyTorch + Triton Model with KernelLens...
Executing Zero-Copy Inference in ONNX Runtime...
Executing Zero-Copy Inference in TensorRT...
Verification Complete!
ORT Max Floating-Point Difference: 0.000000e+00
TRT Max Floating-Point Difference: 0.000000e+00
Exact Numerical Match (ORT): True
Exact Numerical Match (TRT): True
How KernelLens Interoperates with PyTorch Under the Hood
- Dual-Pass Tracing & FX Proxy Interception: During
kl.compile(), KernelLens enters an FX proxy context that intercepts@triton.jitlaunches without modifying PyTorch model source code. - SymPy Grid Transpilation: Converts Python launch grid lambdas (e.g.,
grid = lambda META: (triton.cdiv(M, BLOCK_SIZE),)) into C++ AST integer arithmetic evaluated dynamically at runtime (< 0.5 μs CPU overhead). - Automated C++/CUDA Code Synthesis: Generates production C++ source files implementing
Ort::CustomOpandnvinfer1::IPluginV2DynamicExt, executing raw PTX assembly via CUDA Driver API (cuModuleLoadData&cuLaunchKernel). - Zero-Copy Memory Binding: Binds PyTorch GPU memory addresses (
data_ptr()) directly to ONNX RuntimeIOBindingand TensorRTsetTensorAddress(). - Toolchain Hardening: Injects dynamic 16-byte address check guards (preventing
LDG.128hardware alignment exceptions) and clamps PTX ISA versions (.version 9.0) for NVIDIA Blackwell (sm_120a) GPU driver compatibility.
Benchmarks & Evaluation
Evaluated across PyTorch research kernels (LLaMA 3 RMSNorm, SwiGLU, Qwen 2.5 RoPE, and Liger-Kernel Fused Cross-Entropy), KernelLens achieves 3.4x to 7.0x speedups over PyTorch eager execution while maintaining exact floating-point numerical parity (MaxDiff = 0.00e+00).
Open Source & Resources
GitHub Repository: Just1truc/kernel_lens
PyPI Package: pip install kernel-lens
Galiad Research: galiad-research.com
Lead Researcher: Justin Duc
We would welcome any feedback, questions, or community contributions!