Phase 06/Writing your own kernels/Beyond NVIDIA: TPU, Trainium, AMD and compilers
PHASE 06 · Writing your own kernels

Beyond NVIDIA: TPU, Trainium, AMD and compilers

0%
12 h7 subtopics3 lessons · 3 required
In plain English

NVIDIA GPUs are not the only chips that run large models. Google builds TPUs, Amazon builds Trainium and Inferentia, AMD sells the MI300 family, and several startups sell their own. Each has its own software stack, and the labs hiring inference engineers run more than one of them. Think of a touring band. The songs are the same, but every venue has a different sound system, and the crew's value is knowing how to plug the same show into each one. In this topic you learn the mental model of each platform and the compilers (XLA, torch.compile, MLIR, Triton) that act as universal adapters, so a model written once can be lowered to whatever hardware is cheapest that quarter. Everything is done on a laptop, by inspecting what the compilers produce rather than by renting exotic hardware.

Why it matters

Eighteen of the forty-six postings ask for non-NVIDIA accelerator experience and nine ask for compiler knowledge. Anthropic serves Claude across multiple accelerator families, OpenAI is bringing up its own silicon, and AMD MI300X is now a mainstream vLLM target. Engineers who can read HLO, Inductor output or a HIP diff can move between these platforms; the rest are stuck on one vendor.

Hiring signal

OpenAI's Accelerators team prototypes its software stack on new and exploratory accelerator platforms and develops kernels and sharding strategies for them; Anthropic's inference role integrates new AI accelerator platforms across clouds; CoreWeave lists HIP/ROCm, JAX/Pallas and TPU experience as preferred for its kernel engineers.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain the TPU execution model (systolic MXU, HBM, ICI, SPMD sharding) and why XLA's ahead-of-time compilation suits it.
  • Port a small PyTorch model to JAX, lower it with jax.jit and read the resulting HLO to identify fusions and dot operations.
  • Use torch.compile with Inductor, read the generated code and count graph breaks and fused kernels.
  • Describe the AWS Neuron and AMD ROCm stacks at the level of what maps to CUDA concepts (HIP, RCCL, hipBLASLt, Composable Kernel, rocprof).
  • Produce a HIPify port plan for a CUDA kernel you wrote, listing every warp-size and library assumption that changes.

Key concepts

XLA and HLO
Google's accelerator compiler and its intermediate representation; JAX and PyTorch/XLA lower whole programs to HLO, which XLA fuses and schedules for TPU, GPU or CPU.
TPU MXU and ICI
The systolic matrix unit that does the multiplies and the inter-chip interconnect that links TPUs into pods; both shape how models are sharded.
SPMD sharding
One program, many devices; the compiler inserts collectives from sharding annotations (jax.sharding, GSPMD) rather than the programmer writing them.
AWS Neuron
The SDK for Trainium and Inferentia, including the Neuron compiler, NKI kernel language and transformers-neuronx and vLLM integration for inference.
HIP and ROCm
AMD's CUDA-like programming layer and platform; HIPify converts CUDA source, RCCL mirrors NCCL, hipBLASLt and Composable Kernel replace cuBLAS and CUTLASS.
Wavefront
AMD's group of 64 threads executed together (versus NVIDIA's 32-thread warp); every warp-size assumption in a kernel changes.
torch.compile and Inductor
PyTorch's tracer (Dynamo) plus code-generating backend that emits Triton for GPU and C++ for CPU, fusing ops and removing Python overhead.
Graph break
A point where Dynamo cannot trace Python (data-dependent control flow, unsupported call) and falls back to eager, splitting the compiled graph.
MLIR
A compiler framework of composable dialects used by Triton, IREE, XLA and vendor toolchains to lower from framework graphs to hardware code.
Triton as portability layer
One tile-level kernel source compiled to NVIDIA, AMD and, with vendor backends, other targets; why engines write new kernels in Triton first.

Subtopics

  1. 1. TPU and JAX mental model

    MXU, VPU, HBM and ICI; jit, pmap and sharding; why static shapes and ahead-of-time compilation fit TPUs; TPU inference through JAX and vLLM TPU.

  2. 2. Reading HLO

    Lowered StableHLO versus compiled HLO, fusion ops, dot_general, all-reduce insertion from sharding; spotting unintended recompilation.

  3. 3. AWS Trainium and Inferentia

    NeuronCores, the Neuron compiler, NKI kernels, continuous batching support in the Neuron vLLM plugin; what is and is not supported.

  4. 4. AMD ROCm and MI300

    MI300X memory (192 GB HBM3), CDNA3 compute units, HIP, RCCL, rocprof, hipBLASLt, Composable Kernel and AITER; vLLM and SGLang on ROCm.

  5. 5. torch.compile and Inductor

    Dynamo tracing, guards, graph breaks, Inductor fusion and codegen (Triton or C++), modes, and what engines compile versus hand-write.

  6. 6. MLIR and kernel DSLs

    Dialects and lowering, how Triton uses MLIR, Pallas on TPU and GPU, Mojo and CuTe DSL; choosing between a DSL and a compiler.

  7. 7. Heterogeneous fleets

    Placing models by hardware fit, numerics differences across platforms, rollout and correctness gates per platform, cost per token comparisons.

Resources

article
documentation

Hands-on lessons

L1

Port a small transformer block to JAX and read the HLO

CPU · your Macnotebook150 minrequired

Goal · A PyTorch transformer block re-implemented in JAX with numerically matching outputs, its lowered and compiled HLO text saved, and the dot and fusion operations counted and explained.

  1. 1pip install jax (CPU); write a one-layer pre-norm transformer block (RMSNorm, 4-head attention, SwiGLU MLP) in PyTorch with fixed-seed weights and run it on an input of shape (2, 16, 256).
  2. 2Re-implement the same block in JAX with jax.numpy using the exported weights; compare outputs with the PyTorch block at atol 1e-5 in fp32.
  3. 3Call jax.jit(block).lower(x).as_text() and save the StableHLO; count dot_general operations and confirm the count matches the matmuls you wrote (q, k, v, o projections, scores, attention-value product, gate, up and down projections).
  4. 4Call .compile().as_text() and save the compiled HLO; count fusion ops and find which elementwise operations XLA fused into the matmuls or into the softmax.
  5. 5Add jax.sharding with a 2-device mesh (use XLA_FLAGS=--xla_force_host_platform_device_count=2) sharding the hidden dimension of the MLP; recompile and find the all-reduce or reduce-scatter XLA inserted.
  6. 6Change the input sequence length to 17 and observe recompilation; explain in a markdown cell why static shapes matter on TPUs.
  7. 7Time the jitted and the non-jitted JAX block and the PyTorch eager block for 100 iterations on CPU.
Deliverable
jax_block.ipynb with both HLO texts saved as files and a table of operation counts.
Check
Outputs match at atol 1e-5; the lowered StableHLO contains exactly 9 dot_general operations; the sharded compiled HLO contains at least one all-reduce or reduce-scatter; a sequence length change triggers a recompile (observable via a new compile log line or a jitted call time spike).
L2

torch.compile on CPU and read what Inductor generated

CPU · your Macnotebook120 minrequired

Goal · The same PyTorch block compiled with torch.compile on the Mac, with generated C++ inspected, graph breaks counted and fixed, and a before/after timing.

  1. 1Run the l1 PyTorch block under torch.compile(backend="inductor") with TORCH_LOGS="output_code,graph_breaks" and save the generated code to a file.
  2. 2Open the generated code; identify the fused kernel for RMSNorm and for the SwiGLU activation and list which eager ops were merged into each loop.
  3. 3Use torch._dynamo.explain(block)(x) to report the number of graphs and graph breaks; if there are breaks, read the reasons.
  4. 4Introduce a deliberate graph break (a Python print of a tensor value inside the block) and show it appears in explain; remove it.
  5. 5Compare eager and compiled latency over 200 iterations at batch 2 and batch 32 on CPU and report the speedup.
  6. 6Set dynamic=True and re-run with sequence lengths 16 and 17; confirm no recompilation by checking the compile counters.
  7. 7Write a short note comparing what Inductor fused with what XLA fused in l1 for the same block.
Deliverable
compile_block.ipynb, the saved generated code and a comparison note.
Check
explain reports exactly 1 graph and 0 graph breaks for the clean block and at least 1 break with the print inserted; the generated code contains a single loop that computes the RMSNorm (mean of squares, rsqrt and scale) rather than separate kernels; dynamic=True produces no recompile between lengths 16 and 17.
L3

HIPify your attention kernel and write the AMD port plan

CPU · your Macdesign120 minrequired

Goal · Your Phase 6 CUDA attention kernel converted with hipify-perl, with a diff and a port plan that lists every assumption that changes on MI300X and how you would validate correctness and performance there.

  1. 1git clone https://github.com/ROCm/HIPIFY and run bin/hipify-perl (a standalone Perl script) on the CUDA source of your p6-custom-attention-kernels l1 kernel; save the output and the diff.
  2. 2Read the hipify warnings and list every unconverted API or unsupported construct.
  3. 3Search your kernel for warp-size assumptions (32, __shfl_sync masks, warpSize-dependent reductions) and list each line with the change needed for a 64-wide wavefront.
  4. 4Map every library call in your PyTorch glue (cuBLAS, NCCL, nvcc flags, torch.cuda calls) to its ROCm equivalent (hipBLASLt or rocBLAS, RCCL, hipcc, the same torch.cuda API on ROCm builds).
  5. 5Write the validation plan with the exact correctness tests you would run on MI300X (the l1 asserts), the profiler you would use (rocprof), and the roofline numbers you would compare against (5.3 TB/s HBM3, 192 GB).
  6. 6Add a section on numerics differences to expect (fp16 accumulation order, transcendental implementations) and how your correctness gate would tolerate them.
Deliverable
attention_hip.cu, hipify.diff and amd-port-plan.md.
Check
hipify-perl runs to completion and the diff shows cuda prefixes replaced with hip prefixes; the plan lists every warp-size assumption with a line number and names rocprof and the MI300X bandwidth figure.

Build your own

Build your own portable kernel layer

PythonCPU · your Mac~8 h

One fused RMSNorm-plus-residual op implemented three ways, in Triton, in JAX/XLA and through torch.compile, behind one dispatch interface with a shared test suite and a per-backend benchmark harness.

The real thing: github.com/vllm-project/vllm/tree/main/vllm/platforms ↗

How you know a stage passes

Write tests/test_portable.py first. A pure-PyTorch fp32 reference of fused_rmsnorm_residual(x, residual, weight, eps) is the oracle; every backend is parametrized into the same tests with torch.testing.assert_close (atol 1e-5 fp32, 2e-2 bf16/fp16) at shapes (1, 4096), (32, 4096) and (7, 1023). A `--backend` flag on bench.py times each path. Run `pytest -q` on the Mac (Triton under TRITON_INTERPRET=1, JAX CPU, torch.compile inductor CPU) and optionally on a Colab GPU or TPU runtime; a stage passes when its backend's tests are green.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01interface and reference
    A portable_kernels package with register_backend(name, fn), set_backend(name) and a fused_rmsnorm_residual entry point, with the eager PyTorch reference registered as backend 'torch'.
    test · `pytest -q -k torch` passes; calling set_backend('nope') raises a KeyError listing the registered names.
  2. 02Triton backend
    A Triton kernel computing the residual add, mean of squares, rsqrt and scale in one pass per row, registered as backend 'triton'.
    test · `TRITON_INTERPRET=1 pytest -q -k triton` passes on the Mac; on a Colab T4 the same tests pass without the interpreter and bench.py reports at least 150 GB/s at (4096, 4096) fp16.
  3. 03JAX/XLA backend
    A jax.jit function with the same math registered as backend 'jax', with zero-copy conversion of CPU tensors through dlpack and the lowered StableHLO saved to disk.
    test · `pytest -q -k jax` passes; the saved HLO after compilation contains exactly one fusion for the op (count 'fusion' in the optimized HLO text) and a second call with the same shapes does not recompile (jit cache size unchanged).
  4. 04torch.compile backend
    The eager reference wrapped in torch.compile(fullgraph=True, dynamic=True) registered as backend 'inductor', with the generated C++ (or Triton on GPU) captured through TORCH_COMPILE_DEBUG.
    test · `pytest -q -k inductor` passes; torch._dynamo.explain reports 1 graph and 0 graph breaks; the generated code contains a single loop nest for the whole op; lengths 1023 and 1024 do not trigger a recompile.
  5. 05capability-based dispatch
    A select_backend() that inspects the device (cpu, cuda, mps, tpu via jax.devices) and installed packages and picks the fastest available backend from a priority table, overridable by an environment variable.
    test · On the Mac select_backend() returns 'inductor' (or 'triton' when TRITON_INTERPRET is set), on a Colab T4 it returns 'triton', and PORTABLE_BACKEND=jax forces 'jax'; a test asserts each case by monkeypatching the probes.
  6. 06cross-backend benchmark and parity report
    bench.py runs every available backend at four shapes, writes results.csv and a Markdown parity report with max abs error versus the reference per backend and dtype, and includes a Colab TPU note (run the jax backend on a TPU runtime and paste the numbers).
    test · The report lists every backend that passed tests with its latency and max error; all max errors are under the test tolerances; the TPU section is either filled with numbers or marked 'not run' with the reason.

Knowledge check

QWhy do TPUs and XLA favour static shapes?

XLA compiles the whole program ahead of time into a fixed schedule for the systolic MXU and inserts collectives at compile time; a new shape means a new compilation, so dynamic shapes cost recompiles or padding.

QWhat does a graph break in torch.compile cost you?

The compiled region is split, control returns to Python between the pieces, and any fusion or overhead removal across the break is lost.

QName three CUDA-to-ROCm equivalences a port must handle.

CUDA to HIP APIs via HIPify, NCCL to RCCL, cuBLAS or CUTLASS to hipBLASLt or Composable Kernel; and the 32-thread warp becomes a 64-thread wavefront.

QWhy do inference engines write new kernels in Triton before CUDA?

Triton lowers through MLIR to NVIDIA and AMD backends, so one source serves both fleets, and iteration is faster; hand-written CUDA or HIP is reserved for the few kernels where Triton leaves performance on the table.

QWhat does the compiler do with sharding annotations in JAX?

Under SPMD it partitions the program across devices and inserts the all-reduce, all-gather or reduce-scatter collectives needed, so the programmer never writes communication calls.

Completion

  • All 7 subtopics marked done
  • All 3 required lessons done
  • Lesson l1 HLO operation counts and sharded collectives recorded.
  • Lesson l2 generated code read and graph breaks explained.
  • Lesson l3 port plan complete with line-level warp-size findings.
  • Can give a two-minute comparison of TPU, Trainium and MI300X stacks relative to CUDA.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →