KernelLens: Deploying Triton Kernels to C++ Inference Engines (TensorRT & ONNX)

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:

  1. PyTorch ONNX Exporter Tracing Breakdown: Standard torch.onnx.export operates on PyTorch C++ operator schemas. Imperative Python calls to @triton.jit functions are opaque to trace backends, leading to tracing failures or missing graph nodes.
  2. C++ Engine Plugin Complexity: Executing custom Triton kernels inside standalone C++ engines requires manually implementing hundreds of lines of C++/CUDA plugin boilerplate (OrtCustomOp for ONNX Runtime and nvinfer1::IPluginV2DynamicExt for 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

  1. Dual-Pass Tracing & FX Proxy Interception: During kl.compile(), KernelLens enters an FX proxy context that intercepts @triton.jit launches without modifying PyTorch model source code.
  2. 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).
  3. Automated C++/CUDA Code Synthesis: Generates production C++ source files implementing Ort::CustomOp and nvinfer1::IPluginV2DynamicExt, executing raw PTX assembly via CUDA Driver API (cuModuleLoadData & cuLaunchKernel).
  4. Zero-Copy Memory Binding: Binds PyTorch GPU memory addresses (data_ptr()) directly to ONNX Runtime IOBinding and TensorRT setTensorAddress().
  5. Toolchain Hardening: Injects dynamic 16-byte address check guards (preventing LDG.128 hardware 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

Lead Researcher: Justin Duc

We would welcome any feedback, questions, or community contributions!

We’re the editorial team at aicost.tools, and for us the real inference cost often sits in fused custom kernels like this once they leave Python. Wrapping them as plugins is a sensible way to keep latency down, but I’d worry about maintenance when TensorRT or ORT versions move. Have you checked how the generated plugins behave with dynamic batch sizes, not just fixed shapes?

Both are fair.

About Version drift: I handled it by limiting the package to fix versions. TensorRT 11 removed the legacy IPluginV2 interfaces the generator targets, so the package pins tensorrt>=8.6,<11 and refuses to build rather than emitting something that would crash. ONNX Runtime 1.30 can’t bind bfloat16 custom-op tensors, so bf16 is TensorRT-only. A future release will generate for TensorRT’s IPluginV3. The IPluginV2* interfaces we emit are deprecated in 10.x and removed in 11, so that’s the migration path I’m focusing on.

About Dynamic batch: It was actually a bug. kl.compile(…, dynamic_shapes=True) now produces one engine that serves any leading-dimension size in range, and we test it by compiling once and running every shape through that single engine: a build at batch 8 serves batches 1–16, bit-exact against native Triton on both ONNX Runtime and TensorRT, on Blackwell and Ampere. So yes, the engine can handle ranges like what tensorRT would normally do and the plugins handle dynamic shapes automatically through symint tracing.

Great Work ! Does it support any modules decorated with @triton.jit directly into the model graph, while the rest of the model is compiled using traditional Torch AOTInductor ?