Skip to content
Skip to lesson
Back to Topics
LearnGPU Systems & LLM InferenceGPU Compilers and Kernel Languages
HardInference Optimization12 min read

GPU Compilers and Kernel Languages

A correct kernel can still stall on its first call or fail because no image matches the GPU. The evidence is in the compiler artifacts.

On this page

Your vector-add kernel passed every test yesterday, yet today its first call stalls for 300 ms or crashes on a newer GPU with "no kernel image is available". Reading the source again won't explain either failure. A never executes C++ or Python directly; both symptoms live in the compiler artifacts between source and silicon.

One addition, several representations

To compute out[i] = x[i] + y[i] for n=1,000n = 1{,}000 floats with 256 threads per block, CUDA launches four blocks (1,024 threads) and guards the 24 tail threads. Notice the size_t index widening and overflow-safe block calculation (n / threads + (n % threads != 0) instead of (n + threads - 1) / threads, which overflows signed int near INT_MAX):

vector_add.cu
__global__ void add_kernel(const float* x, const float* y, float* out, int n) {
    std::size_t i = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
    if (i < static_cast<std::size_t>(n)) out[i] = x[i] + y[i];
}

void launch_add(const float* x, const float* y, float* out, int n) {
    if (n <= 0) return;  // Zero-block launches are invalid.
    constexpr int threads = 256;
    int blocks = n / threads + (n % threads != 0);
    add_kernel<<<blocks, threads>>>(x, y, out, n);
}

At source level you see the bounds check, not the emitted instructions or physical registers. For SIMT kernels, nvcc lowers device code through four distinct artifacts:[1][2][3][4][5]

source→LLVM/NVVM IR→PTX→ptxas→cubin (SASS)\text{source} \rightarrow \text{LLVM/NVVM IR} \rightarrow \text{PTX} \rightarrow \text{ptxas} \rightarrow \text{cubin (SASS)}
  • PTX (Parallel Thread Execution): Versioned virtual ISA using virtual registers (%f1, %f2, %rd3). Portable forward to compatible newer GPUs only when the driver supports that PTX ISA version.
  • ptxas -> cubin: Optimizing assembler allocates physical registers, schedules instructions, inserts spills if needed, and writes target-specific machine code into an ELF cubin (e.g. sm_90).
  • SASS: Human-readable disassembly of native machine code inside a cubin (nvdisasm), not an executable source format.
CUDA block 0 thread 1 lowers through NVVM IR and LLVM IR while Triton pid 0 offset 1 mask 1 lowers through TTIR, TTGIR, and LLVM IR into PTX. PTX loads x[1]=0.25 into %f1 and y[1]=-2 into %f2, adds to %f3=-1.75, and stores out[1]=-1.75. Toolkit ptxas allocates physical registers to build a target ELF cubin for GPU driver execution or nvdisasm SASS disassembly.
CUDA and Triton both lower to PTX virtual registers (`%f1`, `%f2`, `%f3`), which `ptxas` assembles into a target cubin with physical registers; `nvdisasm` renders that machine code as SASS.

nvcc packages host code with architecture-specific device images

nvcc separates host C++ from device code and embeds one or more device images inside a fatbinary (fatbin).[1] The flags distinguish virtual vs. native intent:

Target spellingArtifact embeddedRuntime effect
compute_90PTX for virtual compute capability 9.0Driver can JIT-compile forward for compatible newer GPUs
sm_90Native cubin for 9.0 siliconLoads natively without PTX JIT
Suffixes (compute_90a, compute_100f)Architecture- or family-restricted PTXDisables general forward compatibility across major architectures

At load time, the CUDA driver prefers a compatible native cubin; only a cubin miss triggers PTX driver JIT (which still requires a driver supporting the emitted PTX ISA version).

Loader flow for a fatbin containing sm_90 cubin and compute_90 PTX. A compatible cubin jumps straight to native GPU load, which stays lazy by default. A cubin miss checks embedded PTX against the driver max ISA, running driver JIT and compute cache write before native load, or failing load if neither matches. Right column lists CUDA_FORCE_PTX_JIT=1, CUDA_CACHE_DISABLE=1, and CUDA_DISABLE_PTX_JIT=1.
The loader takes native cubin first and falls back to PTX JIT only on a cubin miss. Test both paths explicitly via `CUDA_FORCE_PTX_JIT=1` and `CUDA_DISABLE_PTX_JIT=1`.

Produce artifacts you can inspect

Compile both a native cubin and forward-compatible PTX, then inspect the fatbin with cuobjdump (works on host executables and fatbins) and standalone cubins with nvdisasm (adds source-line and register-liveness views):[3]

build-and-inspect.sh
nvcc -O3 -lineinfo -Xptxas -v \
  --generate-code arch=compute_90,code=sm_90 \
  --generate-code arch=compute_90,code=compute_90 \
  vector_add.cu -o build/vector_add

cuobjdump --list-elf --list-ptx --dump-resource-usage build/vector_add
nvcc -O3 -lineinfo --cubin --generate-code arch=compute_90,code=sm_90 \
  vector_add.cu -o build/vector_add.sm_90.cubin
nvdisasm --print-code --print-line-info --print-life-ranges \
  build/vector_add.sm_90.cubin > build/vector_add.liveness.sass

Register pressure, occupancy cliffs, and spilling

Every SM holds 65,536 32-bit registers (64 max warps on Hopper sm_90 and Blackwell sm_100; 48 max warps on Ada sm_89 and Blackwell sm_120).[6][7][8] Because hardware allocates registers per warp in 256-register granules, a single extra register per thread (32 to 33) rounds each 32-lane warp from 1,024 to 1,280 registers, dropping an 8-warp block from 8 resident blocks (64 warps, 100%) to 6 blocks (48 warps, 75%)!

resource_puzzle.py
import math

def resident_warps(regs, *, warp_limit=64, shared_per_block=0):
    warps_per_block = 8
    regs_per_warp = math.ceil(32 * regs / 256) * 256
    blocks = min(65536 // (warps_per_block * regs_per_warp), warp_limit // warps_per_block)
    if shared_per_block:
        blocks = min(blocks, (96 * 1024) // shared_per_block)
    return blocks * warps_per_block

for r in (32, 33, 41, 65, 129):
    w = resident_warps(r)
    print(f"R={r:3d}: {w:2d} warps ({100 * w / 64:5.1f}% of 64)")
print(f"R=33 on 48-warp SM: {resident_warps(33, warp_limit=48)} warps (100%)")
print(f"R=32 + 32 KiB shared (96 KiB SM): {resident_warps(32, shared_per_block=32768)} warps (37.5%)")
Output
R= 32: 64 warps (100.0% of 64)
R= 33: 48 warps ( 75.0% of 64)
R= 41: 40 warps ( 62.5% of 64)
R= 65: 24 warps ( 37.5% of 64)
R=129:  8 warps ( 12.5% of 64)
R=33 on 48-warp SM: 48 warps (100%)
R=32 + 32 KiB shared (96 KiB SM): 24 warps (37.5%)
Bar chart and register-pool breakdown for 256-thread (8-warp) blocks on a 65,536-register SM with 256-register warp allocation granules. Active warps drop from 64 at R32 (8 blocks, 65,536 used) to 48 at R33 (6 blocks, 61,440 used, 4,096 free), 40 at R41, 24 at R65, and 8 at R129. Right notes show why rounding 1,056 to 1,280 strands 4,096 registers, how R33 reaches 100% under a 48-warp cap, and how 96 KiB shared memory at 32 KiB per block caps R32 at 24 warps.
Warp-granule rounding turns 32 -> 33 registers/thread into a 25% occupancy cliff on a 64-warp SM, while shared-memory budgets can cap residency independently.

Spills, ptxas -v, and artifact identity

When registers run out, ptxas spills values to .local memory (device-backed and cached, not automatically an HBM stall; CUDA 13.0 also adds opt-in shared-memory spilling in whole-program mode[9]). Control limits with --maxrregcount=N or __launch_bounds__(maxThreadsPerBlock, minBlocksPerMultiprocessor) (launching more than maxThreadsPerBlock fails at runtime) and always compare -Xptxas -v logs alongside warm timings.[1][10]

For reproducible JIT caches, hash the complete compilation recipe: source plus transitive headers, compiler version, ordered flags, target architecture (note sm_90a for WGMMA vs. sm_90), shape, strides, dtype, block size, num_warps, and num_stages. Hashing only the top-level source file silently reuses stale binaries when an included header or tensor stride changes:[11]

compilation_identity.py
from dataclasses import asdict, dataclass, replace
import hashlib, json

@dataclass(frozen=True)
class Recipe:
    source_sha256: str
    toolchain: str
    target: str
    flags: tuple[str, ...]
    shape: tuple[int, ...]
    strides: tuple[int, ...]
    dtype: str
    block: int

    def key(self, headers=None):
        deps = sorted((k, hashlib.sha256(v).hexdigest()) for k, v in (headers or {}).items())
        return hashlib.sha256(json.dumps([asdict(self), deps], sort_keys=True).encode()).hexdigest()

base = Recipe(hashlib.sha256(b"v1").hexdigest(), "nvcc-12.8", "sm_90", ("-O3",), (1000,), (1,), "fp32", 256)
k_v1 = base.key({"scale.cuh": b"#define SCALE 1\n"})
k_v2 = base.key({"scale.cuh": b"#define SCALE 2\n"})
k_stride2 = replace(base, strides=(2,)).key({"scale.cuh": b"#define SCALE 1\n"})
assert len({k_v1, k_v2, k_stride2}) == 3
print("header edit and stride-2 view both produce distinct cache keys")
Output
header edit and stride-2 view both produce distinct cache keys
Left side shows vector_add.cu unchanged while scale.cuh changes SCALE from 1 to 2 for inputs 4 and 5: a source-only key returns stale hit 9, whereas a dependency-aware key misses and rebuilds 18; below, identical shape 1000 misses when stride changes from 1 to 2. Right side flows four key groups (source plus transitive headers, toolchain plus ordered flags and target, shape plus stride and dtype, block plus warps and stages) into a SHA-256 recipe digest.
Include transitive headers, flags, target, and tensor strides in every JIT cache key so edits to `scale.cuh` or stride-2 views never hit a stale binary.

JIT is part of request latency

Runtime compilers (NVRTC, nvJitLink, driver PTX JIT, and Triton) shift compilation latency onto the first request.[11][12][13] Moreover, CUDA module loading is lazy by default, so even a native cubin can pay first-call load latency unless warmed up outside the request path.[14] Test both branches in fresh processes:

test-fatbin-branches.sh
CUDA_FORCE_PTX_JIT=1 CUDA_CACHE_DISABLE=1 ./build/vector_add
CUDA_DISABLE_PTX_JIT=1 ./build/vector_add
A log10-scale horizontal latency bar chart spanning 1 microsecond to 1 second compares four GPU kernel execution paths: cold PTX or Triton JIT compilation takes roughly 300 ms (300,000 us), cold compatible cubin lazy loading takes roughly 15 ms (15,000 us), warm cache-hit kernel launch takes roughly 40 us, and CUDA Graph replay takes roughly 12 us. A dimension bracket highlights the 7,500x to 25,000x latency gap between cold JIT compilation and steady-state warm execution.
On a logarithmic scale, cold PTX/Triton JIT (~300 ms) and lazy cubin loading (~15 ms) sit three to four orders of magnitude above warm kernel launches (~40 µs) and CUDA Graph replay (~12 µs).

Eight ranks, two different cache questions

When eight workers miss the same cache entry concurrently, separate atomic visibility from duplicate work: Triton stages into a unique temp path and publishes via os.replace so readers never observe partial files (without guaranteeing cross-file group atomicity or power-loss durability), while an optional cooperating-writer lock with exact-key recheck prevents eight redundant compiles.[15] A rank-0 warmup helps other ranks only when both shared cache storage and exact target/recipe identity match.

Top graph shows Writer A and Writer B each writing and closing a complete temporary file before executing atomic replace on key K. A reader opening K before the swap sees the complete old file; opening after sees the complete new file. Bottom pipeline shows an optional lock protocol: acquire lock, recheck exact key K, compile on miss, and publish before unlocking.
Atomic rename (`os.replace`) protects readers from partial files; a lock plus exact-key recheck avoids duplicate compilation across ranks.
Graph of rank-0 warmup: Rank 0 compiles sm_90 and populates key K(sm_90) in the shared cache before an MPI barrier. Post-barrier, a rank querying K(sm_90) in the shared cache hits, Rank 1 requesting sm_100 builds key K(sm_100) and misses, and a worker using an empty private cache misses even for the identical sm_90 recipe.
Rank-0 warmup hits only when another rank shares the physical cache directory and requests the exact same recipe and target.

Same kernel, different unit of thought

CUDA C++ describes one scalar thread; describes one blocked program instance over a vector of offsets:[16][17]

vector_add_triton.py
import triton, triton.language as tl

@triton.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr):
    offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
    mask = offsets < n
    x = tl.load(x_ptr + offsets, mask=mask, other=0.0)
    y = tl.load(y_ptr + offsets, mask=mask, other=0.0)
    tl.store(out_ptr + offsets, x + y, mask=mask)

How Triton compiles: the MLIR lowering pipeline

On NVIDIA GPUs, Triton lowers through five MLIR/backend stages: TTIR (target-agnostic block ops) -> TTGIR (distributed lane/warp layouts, coalescing, swizzles, software pipelining) -> LLVM IR (shared-memory allocation, zero for plain vector add) -> PTX -> ptxas cubin (invoked directly by Triton's backend).[18]

Top row traces Triton MLIR lowering across TTIR, TTGIR layout, LLVM IR, PTX, and cubin. Bottom left shows a 4x4 TritonGPU tile assigning rows 0-3, 4-7, 8-11, and 12-15 to lanes L0 through L3, with zero shared memory for plain vector add. Bottom right uses lifetime bars to show nonoverlapping virtual values A and B sharing physical register r0, while overlapping lifetimes occupy r0 and r1 concurrently.
Triton assigns warp/lane ownership at TTGIR and allocates shared memory during LLVM lowering, while register liveness decides whether values share or split physical registers.

Check ownership without a GPU

Always test edge lengths (0, 1, 255, 256, 257) and INT_MAX arithmetic so off-by-one <= masks and 32-bit offset wraps get caught before touching hardware:

check_index_coverage.py
def covered(n, block=256, include_equal=False):
    blocks = n // block + (n % block != 0)
    idx = [p * block + l for p in range(blocks) for l in range(block)
           if p * block + l < n or (include_equal and p * block + l == n)]
    return blocks, idx

for n in (0, 1, 255, 256, 257, 1000):
    b, idx = covered(n)
    assert idx == list(range(n))
    print(f"n={n:4d}: blocks={b}, masked={b * 256 - n}")
assert covered(256, include_equal=True)[1] == list(range(256))  # Full block hides <= bug!
assert covered(257, include_equal=True)[1][-1] == 257           # n=257 exposes it.

n_max = (1 << 31) - 1
blocks = n_max // 256 + (n_max % 256 != 0)
print(f"INT_MAX: {blocks} blocks, {blocks * 256 - n_max} masked lane (no int32 overflow)")
Output
n=   0: blocks=0, masked=0
n=   1: blocks=1, masked=255
n= 255: blocks=1, masked=1
n= 256: blocks=1, masked=0
n= 257: blocks=2, masked=255
n=1000: blocks=4, masked=24
INT_MAX: 8388608 blocks, 1 masked lane (no int32 overflow)
Stacked bar of n=1,000 split across four 256-lane blocks (CUDA blocks B0 to B3 and Triton pid 0 to 3): blocks 0 to 2 are full, while block 3 holds 232 valid lanes (768 to 999) and 24 masked lanes (1000 to 1023), with sums x[0]+y[0]=-3 and x[1]+y[1]=-1.75. Below left, a lane grid contrasts n=256 hiding <= against n=257 exposing lane 257 out of bounds. Below right, quotient-plus-remainder arithmetic for INT_MAX computes 8,388,608 blocks and 1 masked lane without 32-bit overflow.
Full blocks (`n=256`) conceal an `i <= n` off-by-one bug that `n=257` immediately exposes, while quotient-plus-remainder avoids `int32` launch overflow at `INT_MAX`.

Six authoring surfaces, six control contracts

Kernel languages are not a ranking from "easy" to "fast"; each picks which decisions belong to the author vs. the compiler:

SurfaceMain authoring unitWhat you control explicitlyTarget scope
CUDA C++[13]Scalar thread, warp, blockThread geometry, sync, intrinsics, memory spacesNVIDIA GPUs
Triton[16][19]Blocked programTile shapes, masked loads/stores, launch meta-paramsNVIDIA & AMD GPUs
/ CuTe[20]Hierarchical layouts & hardware atomsExact layout algebra, copy/MMA atoms, C++ or Python CuTe-DSLNVIDIA GPUs
CUDA Tile[21]Block-level immutable tilesPower-of-two tile ops; compiler owns intra-block threadsCUDA Tile-capable NVIDIA stack
Pallas[22][23]Grid program over Refs & BlockSpecHBM/VMEM or SMEM transfers and JAX compositionJAX GPU & TPU
NKI[24]Tile over Neuron engines & SBUFExplicit HBM ↔\leftrightarrow SBUF DMA and nki.isa opsAWS Inferentia2 & Trainium

Diagnose the first failing boundary

Isolate compiler bugs by finding the last stage that produced valid output:

SymptomFailing stageFirst evidence to inspect
Type/intrinsic compile errorSource -> Frontend IRCompiler log + minimal reproducer + pinned API version
ptxas rejects instructionPTX -> cubinPTX .target / .version, toolkit version, sm suffix (sm_90a)
"No kernel image" at launchFatbin loaderGPU compute capability vs. cuobjdump --list-elf --list-ptx
Forced PTX JIT fails, cubin worksDriver PTX JITEmbedded PTX ISA version vs. installed driver floor
Slow first call, fast warm callsJIT or lazy module loadFresh-process trace, cache state, warm exact shapes ahead of traffic
Registers jump & speed dropsIR / ptxas allocationDiff -Xptxas -v logs, SASS liveness, occupancy & stall counters
Edge shape or strided view wrongMask or JIT cache keyTest n=255, 257 and stride-2; check specialization key fields

Choose by the decision you must own

Start with framework ops and vendor libraries (cuBLAS, cuDNN, FlashAttention). Drop to Triton for custom block fusion, Pallas for JAX GPU/TPU integration, NKI for AWS Neuron SBUF control, CUDA Tile when compiler-owned threads suffice, CUTLASS/CuTe for custom MMA/layout pipelines, and CUDA C++ when irregular per-thread control or custom intrinsics are required.

Mastery check

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.A kernel's PTX shows separate multiply and add instructions, while its disassembled cubin encodes one FFMA. How many native arithmetic instructions run, and how should you compare it against a non-fused build?
2.On a compute capability 8.6 GPU whose driver supports PTX ISA <= 8.0, CUDA_DISABLE_PTX_JIT=1 fails while CUDA_FORCE_PTX_JIT=1 succeeds. Which fatbin inventory matches?
3.With 8 warps/block, 65,536 registers/SM, 64-warp cap, and 256-register warp granules, registers/thread rise from 37 to 40. What happens to theoretical occupancy?
4.A writer atomically replaces kernel.cubin with artifact B, then crashes before replacing its metadata file (still describing artifact A). What does this prove about multi-file caches?
5.For n = 515 and block = 128 guarded by i < n, how many total lanes launch and how many lanes in the final block are valid vs. masked?

5 questions remaining.

References

NVIDIA CUDA Compiler Driver NVCC

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/

Parallel Thread Execution ISA

NVIDIA · 2026

https://docs.nvidia.com/cuda/parallel-thread-execution/

CUDA Binary Utilities

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/cuda-binary-utilities/

NVVM IR Specification

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/nvvm-ir-spec/

libNVVM API

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/libnvvm-api/

NVIDIA Hopper Tuning Guide

NVIDIA · 2026

https://docs.nvidia.com/cuda/hopper-tuning-guide/index.html

NVIDIA Ada Tuning Guide

NVIDIA · 2026

https://docs.nvidia.com/cuda/ada-tuning-guide/index.html

NVIDIA Blackwell Tuning Guide

NVIDIA · 2026

https://docs.nvidia.com/cuda/blackwell-tuning-guide/index.html

How to Improve CUDA Kernel Performance with Shared Memory Register Spilling

Shanmughan, D. · 2025

https://developer.nvidia.com/blog/how-to-improve-cuda-kernel-performance-with-shared-memory-register-spilling/

C/C++ Language Extensions

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/cpp-language-extensions.html

NVRTC

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/nvrtc/

nvJitLink

NVIDIA · 2026

https://docs.nvidia.com/cuda/nvjitlink/

CUDA Programming Guide

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/

CUDA Environment Variables

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/environment-variables.html

Triton File Cache Source

Triton Project · 2026

https://github.com/triton-lang/triton/blob/ee07f7ff302740dbb858b84c7c1ea9f1d1ffc782/python/triton/runtime/cache.py

Triton Programming Guide: Introduction

Triton Project · 2026 · Official documentation

https://triton-lang.org/main/programming-guide/chapter-1/introduction.html

Vector Addition

Triton Project · 2026

https://triton-lang.org/main/getting-started/tutorials/01-vector-add.html

Triton NVIDIA Backend Compiler Source

Triton Project · 2026

https://github.com/triton-lang/triton/blob/ee07f7ff302740dbb858b84c7c1ea9f1d1ffc782/third_party/nvidia/backend/compiler.py

Triton Language and Compiler

Triton Project · 2026 · Official repository

https://github.com/triton-lang/triton

CUTLASS and CuTe Documentation

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cutlass/latest/overview.html

Writing Tile Kernels

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/cuda-programming-guide/02-basics/writing-tile-kernels.html

Pallas: a JAX Kernel Language

JAX Authors · 2026 · Official documentation

https://docs.jax.dev/en/latest/pallas/

Pallas Changelog

JAX Authors · 2026

https://docs.jax.dev/en/latest/pallas/CHANGELOG.html

About Neuron Kernel Interface

Amazon Web Services · 2026 · Official documentation

https://awsdocs-neuron.readthedocs-hosted.com/en/latest/nki/get-started/about/index.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.