Lecture 16 · AWS Inferentia and Trainium AI Accelerators (guest lecture)

Hardware Accelerators for Machine Learning · Lecture 16。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: Stanford CS 217 Hardware Accelerators for Machine Learning (Winter 2026), Lecture 16 · Thu 03/05/2026 · AWS Inferentia and Trainium AI Accelerators, guest lecture by Nafea Bshara. Reading: none listed on the schedule.

Basis: The talk and its slides are not public. This lecture is written only from AWS’s public material:

  • the AWS Neuron documentation: hardware pages for Inferentia2, Trainium, Trainium2 and Trainium3, the NeuronCore-v2/v3/v4 pages, the NKI architecture guides for Trainium/Inferentia2 and Trainium2, and the Trn2 system page;
  • AWS’s Trn2 launch blog.

Engine clocks, data-path widths, SRAM sizes, chip and system numbers are published and labelled as such. The experiments use a model written for these notes (neuron.py):

  • engine-level cost rules taken from the NKI documentation;
  • a multi-engine list scheduler for one shard of a transformer layer;
  • collective-communication models.

The model’s overheads, latencies and the cost example of §1 are assumed and labelled. Nothing here reflects what was said in class or AWS-internal information. Code: code/lecture16/ (4 scripts + 1 module; ~3 s in total) Reading time: 2.5 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain why a cloud provider designs its own accelerators, in terms of cost per token, supply and integration.
  2. Place Inferentia2, Trainium, Trainium2 and Trainium3 next to NVIDIA GPUs: compute, memory, ridge points, on-chip SRAM, links.
  3. Describe a NeuronCore:
    • its four engines (tensor, vector, scalar, GpSimd);
    • its software-managed SRAM (SBUF, PSUM);
    • how DMA and semaphores tie them together.
  4. Schedule a transformer layer across the engines, and explain what software pipelining over tiles buys, why decode is a DMA problem, and when the scalar engine’s exps approach the critical path.
  5. Use the tensor engine’s cost rule (max(N, 64) cycles per instruction, FP8 modes that deepen the contraction) to predict utilization.
  6. Relate SBUF size to off-chip traffic for GEMMs and attention.
  7. Estimate collectives on a 2D torus, an UltraServer and over EFA, and explain why tensor-parallel decoding is latency-bound.
  8. Explain stochastic rounding and configurable FP8, and why low-precision training needs them.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 5: systolic arrays, stationary operandsthe NeuronCore’s four engines; SBUF/PSUMNVIDIA’s view of the same trends (L17)
Lecture 6: vector units, function approximation; Amdahl for non-GEMM workthe matmul cost rule; FP8 contraction depthrack-scale systems; a decade of speedups (L17)
Lecture 7: tiling, the √S lawmulti-engine scheduling, software pipelining
Lecture 10: FlashAttention, fusion2D-torus and hierarchical all-reduce
Lecture 4: BF16, FP8, MX formatsstochastic rounding, configurable FP8 bias

0.3 Map

§1  why build your own accelerator                                ← code 01 (Part 1)
§2  the chips and the systems                                     ← code 01 (Part 2)
§3  inside a NeuronCore: four engines and a scratchpad             ← code 01 (Parts 3-5)
§4  scheduling a transformer layer across the engines             ← code 02
§5  what the SRAM size buys                                       ← code 03
§6  scale-out: NeuronLink, UltraServers, EFA                       ← code 04 (Parts 1-3)
§7  numerics for training                                         ← code 04 (Parts 4-5)
§8  the software stack
§9  summary   §10 pitfalls   §11 exercises   §12 further reading   §13 next lecture

0.4 Notation

SymbolMeaning
NC-v2/v3/v4NeuronCore generations (Inferentia2/Trainium; Trainium2; Trainium3)
SBUFstate buffer: the core’s software-managed SRAM, 128 partitions
PSUMpartial-sum buffer: the tensor engine’s accumulators, 8 banks
stationary / movingthe matmul operand held in the array / streamed through it
partition / free axisSBUF’s first dimension (≤ 128, one per lane) / the rest
tptensor-parallel ways (a layer’s heads and FFN columns split tp ways)
αlatency of one collective step
SR, RNEstochastic rounding; round to nearest even

1. Why build your own accelerator

1.1 The economics of a token

A cloud provider sells accelerator time, and its customers buy tokens: trained models, served requests. The cost of a token is

cost per token=capital per hour+energy per hourtokens per hour.\text{cost per token} = \frac{\text{capital per hour} + \text{energy per hour}}{\text{tokens per hour}} .

A merchant accelerator’s price includes its vendor’s margin. A chip designed in-house is bought at cost plus the amortized design effort, but the provider must design it, build its software and keep up with the vendor’s roadmap.

Script 01, Part 1 makes the structure concrete with assumed, illustrative prices:

  • a $6,000 build cost;
  • +25% for the in-house design effort;
  • 700 W, PUE 1.2, $0.08/kWh;
  • a 4-year life.
merchant gross marginmerchant pricemerchant $/hourin-house cost per token at 0.5× speedat 0.75×break-even speed
50%$12,000$0.411.370.920.69×
65%$17,143$0.561.010.670.51×
75%$24,000$0.750.750.500.37×

When the margin dominates the price, an in-house chip can be substantially slower per chip and still cheaper per token. With a 75% margin it breaks even at 0.37× the speed.

AWS’s own published claim is that Trn2 instances offer 30–40% better price performance than its GPU-based P5e/P5en instances.

1.2 What the formula leaves out

  • Supply. Owning a design means not waiting for a vendor’s allocation.
  • Integration. AWS designs the servers, the network (EFA), the virtualization layer (Nitro) and the software stack together with the chip, and can co-design across them.
  • Specialization. An in-house chip only has to serve the provider’s workloads: training and serving transformers at scale. It can leave out what a general-purpose GPU must support (graphics and its pipeline, among others).
  • Risk. The in-house chip must succeed generation after generation. Its software stack is what customers see, and a weaker stack can erase a hardware advantage.

The product line reflects the split of the market:

  • Inferentia (2019) and Inferentia2 (instances from 2023) for inference;
  • Trainium (instances from 2022), Trainium2 (2024) and Trainium3 (2025) for training and, increasingly, inference.

2. The chips and the systems

Script 01, Part 2 (published, dense):

chipyearcoresBF16 TFLOPSFP8 TFLOPSHBMTB/sridge BF16ridge FP8on-chip SRAMlinks TB/s
Inferentia220232 × NC-v219019032 GiB0.8223223248 MiB—
Trainium20222 × NC-v219119132 GiB0.8223323348 MiB0.38
Trainium220248 × NC-v36671,29996 GiB2.90230448224 MiB1.28
Trainium320258 × NC-v46712,517 (MXFP8)144 GiB4.90137514256 MiB2.56
H1002022SMs9891,97980 GB3.3529559150 MB L20.90
B2002024SMs2,2504,500192 GB8.00281562—1.80

Three things stand out:

  1. The ridge points are GPU-like. Prefill is compute-bound and decode bandwidth-bound on all of them, so the lessons of Lectures 1, 10 and 14 carry over unchanged.
  2. The on-chip SRAM is large and software-managed. A Trainium2 carries 224 MiB of SBUF, several times an H100’s L2. There is no cache: every byte arrives because a DMA instruction moved it.
  3. The chips scale out through dedicated links. NeuronLink on Trainium2 provides 1.28 TB/s per chip (published).

Systems (published, Neuron docs):

  • A Trn2 instance has 16 Trainium2 chips in a 4 × 4 2D torus: 1,024 GiB/s of NeuronLink per chip, 1.5 TiB of HBM and 20.8 dense FP8 PFLOPS.
  • A Trn2 UltraServer joins 4 instances (64 chips). Chips with the same coordinates in the 4 instances form rings, at 256 GiB/s per chip. That gives 83.2 dense FP8 PFLOPS and 6 TiB of HBM.
  • Between instances, the EFA network provides 3.2 Tbps per instance.

Trainium3 (published):

  • 8 NeuronCore-v4, 144 GiB at 4.9 TB/s;
  • 2,517 TFLOPS in MXFP8/MXFP4;
  • NeuronLink 2.56 TB/s per chip.

The docs’ tables differ slightly between versions: 4.7 vs 4.9 TB/s, and 16 vs 20 collective cores.


3. Inside a NeuronCore: four engines and a scratchpad

3.1 The engines

A NeuronCore is not one kind of core but four engines that run asynchronously and in parallel, synchronized by hardware semaphores. They share the SBUF.

enginewhat it is (published)what it does
Tensor128 × 128 systolic array; NC-v2 2.8 GHz, v3/v4 2.4 GHz; reads SBUF, writes PSUM; FP32 accumulationmatrix multiplication; also transposes (identity matmul)
Vector128 lanes (v3: 512 BF16 / 256 other elements per cycle at 0.96 GHz)element-wise math, reductions along the free axis, small cross-partition shuffles
Scalar128 lanes (v3: 1.2 GHz) with hardware for non-linear functions, computing func(in × scale + bias) with a reduction afteractivations (GELU, SiLU, exp, rsqrt), fused scale/bias
GpSimd8 programmable 512-bit SIMD processors with local memoryanything else, as C/C++ code
DMA16 engines per core (27 GiB/s each on v2)all movement between HBM and SBUF (and across chips)

Why separate engines? Lecture 6 showed that non-GEMM operators become the bottleneck once matrix units are fast (Amdahl). A transformer layer is mostly matmuls, but every matmul is surrounded by element-wise and non-linear work: norms, RoPE, softmax, SiLU, residual adds, the eviction of results from PSUM.

If one core did both in sequence, the tensor engine would idle during that work. Separate engines let it run in the shadow of the matmuls. Each engine is built for its work: the scalar engine’s function hardware does an exp per lane per cycle, and the GpSimd cores give flexibility without slowing the common path.

3.2 The scratchpad

SBUFPSUM
size (v2 / v3 / v4)24 / 28 / 32 MiB2 MiB
organization128 partitions (192 / 224 / 256 KiB each)128 partitions × 8 banks of 2 KiB (512 FP32)
roleeverything: weights, activations, KV blocksthe tensor engine’s accumulators

A tensor in SBUF is laid out as [partition × free]. The partition axis (≤ 128) is the one the engines process in parallel, one lane per partition; the free axis is streamed.

A matmul instruction (published limits):

  • its stationary operand is at most 128 partitions × 128;
  • its moving operand is at most 128 partitions × 512;
  • its output is 128 × 512 FP32, exactly one PSUM bank.

PSUM holds at most 8 such accumulation groups. The output must be evicted to SBUF by the vector or scalar engine, often fused with the next operation (a cast, an activation).

3.3 The cost rule of the tensor engine

The NKI documentation gives a simple rule. Back-to-back matmul instructions take about

max⁡(N,64) cycles\max(N, 64) \text{ cycles}

where N is the moving operand’s free size (≤ 512) and 64 is the instruction’s start-up. Loading the next stationary tile is up to 4× faster and overlaps the current matmul.

So the array streams one 128-element column per cycle and does 128 × 128 MACs: 2 × 128² × 2.4 GHz = 78.6 TFLOPS (BF16, NC-v3), as published.

Script 01, Part 5 (NC-v3, BF16):

tokens MM × 4096 by 4096 × 4096M × 64 by 64 × 4096
11.6%0.8%
812.5%6.2%
3250%25%
≥ 64100%50%

The weights are stationary and the tokens stream through.

  • Below 64 tokens the array idles for the rest of each instruction’s 64 cycles, which is why decode batches waste it.
  • A contraction of 64 (a small head dimension) fills only half the rows.

FP8 deepens the contraction.

  • NC-v3’s FP8 “double-row” mode presents a logical 256 × 128 array (published): twice the contraction depth per pass, so twice the FLOPs.
  • NC-v4’s MXFP8 path reads 8 × 128 inputs per cycle: a contraction of 512.

A matmul gains only if its contraction is that long. The linear layers (contraction 4,096 or 14,336) and P·V (contraction = number of keys) speed up. Q·Kᵀ (contraction = head dimension = 128) and the transposes of P do not. This detail decides §3.4.

3.4 The engine budget of a transformer

Script 01, Part 3 gives the per-core rates:

  • NC-v3: tensor 78.6 TFLOPS BF16, 157 FP8; vector 246 G elements/s (492 BF16); scalar 154 G/s;
  • NC-v4: tensor 315 TFLOPS MXFP8. Its vector and scalar rates are not published, so we ASSUME v3’s.

The ratio that matters is ~512 BF16 FLOPs per scalar-engine element on v3 (1,024 FP8; 2,048 MXFP8 on v4). A workload with fewer matrix FLOPs per non-linear element waits for the scalar engine.

Script 01, Part 4. One prefill token of a Llama 3 8B layer, on one chip at peak rates, with the shape rules of §3.3:

core, matmulscontextmatmul FLOPs per exptensor ns (linear + attention)scalar nsscalar / tensor
v3 BF162,04813,824693 + 40450.06
v3 BF1632,7681,344693 + 6404450.33
v3 FP8131,072720347 + 2,1331,7250.70
v4 MXFP832,7681,344173 + 4804450.68
v4 MXFP8131,072720173 + 1,9201,7250.82

Engine budget

Attention’s FLOPs per exp are fixed (4 × head_dim = 512), while the linear layers’ FLOPs per token are not. So as the context grows, the exps grow toward the matrix work.

  • FP8 and MXFP8 shrink the linear layers 2–4×, but not Q·Kᵀ or the transposes.
  • At 32K–128K the exps reach 68–82% of the tensor engine’s time. They are close to a co-bottleneck, not past it.

This is the same pressure that led FlashAttention on recent GPUs to compute part of the exps with polynomials on FMA units (Lecture 6’s function approximation).


4. Scheduling a transformer layer across the engines

4.1 The task graph

neuron.layer_tasks turns one 1/8 shard of a Llama 3 8B layer into engine tasks:

  • the shard holds 4 query heads, 1 KV head and 1/8 of the FFN, as with tensor parallelism over the 8 cores of a Trainium2;
  • the tokens are split into tiles of 128.

Per tile, the chain is:

  • RMSNorm: vector (sum of squares) → scalar (rsqrt and scale);
  • QKV matmul (tensor) → PSUM eviction (vector) → RoPE (vector);
  • Q·Kᵀ (tensor) → row max (vector) → exp with fused row sum (scalar) → transpose of P (tensor) → P·V (tensor) → divide by the sum (vector);
  • O matmul → residual add → RMSNorm → gate/up matmul → SiLU (scalar) → × up (vector) → down matmul → residual add.

Weights and, in decode, the KV cache arrive by DMA.

Each engine executes its tasks in program order, each as soon as its dependencies are done: this is what the compiler’s semaphores enforce. The program order is software-pipelined: stage j of tile i is issued at step i + j, so while tile i is in the vector engine, tile i + 1 can use the tensor engine.

The first version of the model issued tiles one after another. Every engine then waited for the previous tile’s whole chain, and the layer took the sum of all latencies. Program order is part of the design.

4.2 Prefill

Script 02, Part 1 (2,048 tokens, BF16, one NC-v3):

enginework (µs)busy during the layer
tensor1,51097%
vector15810%
scalar19513%
DMA23715%
  • The layer takes 1,551 µs, against 2,099 µs if the engines ran one after another (1.35×). That is the value of four engines for this workload: everything except the matmuls hides.
  • Per chip (8 cores, 32 layers, no all-reduce): ~330,000 prefill tokens/s in the model.

Schedule

The first ~40 µs show the prologue: the tensor engine waits for the first weights.

4.3 Decode

Script 02, Part 2 (4,096 tokens of context):

batchlayer step (µs)DMA worktensor workDMA busytensor busytokens/s per chip
118016847.993%27%1,387
822120947.995%22%9,049
6454753454.798%10%29,240
2561,7541,65121994%12%36,482

Decode is a DMA problem.

  • Every step streams the shard’s 55 MB of weights, plus each sequence’s KV cache, from HBM.
  • Batching shares the weights, but the KV cache grows with the batch. Batch 64 gives 21× the tokens/s of batch 1, not 64×.

This is Lecture 10’s and Lecture 14’s story on another machine.

4.4 Engine balance

Script 02, Part 3 (prefill; layer time in ms; the last two columns relative to the four-engine schedule):

core, matmulscontexttensor workscalar workvector worklayerone merged vector engineexps on the vector engine
v3 BF162,0481.510.190.161.551.00×1.00×
v3 BF1632,76843.816.26.6343.91.00×1.00×
v3 FP832,76829.016.26.6329.01.00×1.00×
v4 MXFP82,0480.440.190.160.471.05×1.00×
v4 MXFP832,76821.816.26.6321.81.06×1.00×

The tensor engine stays the busiest, for the reason of §3.3. But with MXFP8, vector and scalar work together exceed the tensor work (22.85 vs 21.75 ms at 32K). A core with one general vector engine instead of two specialized ones would then be ~6% slower.

As matmuls get cheaper, the engines around them must keep up. The balance between engines is a design parameter that each generation re-tunes.

4.5 Data layout

Script 02, Part 4. If element-wise work puts tokens on partitions, a decode batch of 1 uses 1 of 128 lanes, and the element-wise work grows 20× (1.1 → 21.7 µs). Packing features onto all 128 partitions avoids that, at the price of an extra tensor-engine pass for reductions across partitions.

In decode the difference hides under the DMA time (+1% step time). It would not if the weights stopped being the bottleneck. Layout is the compiler’s job on this machine, and it matters.


5. What the SRAM size buys

5.1 GEMMs

Script 03, Part 2. The gate/up shard GEMM of prefill (2,048 tokens × 4,096 → 3,584), with the best tiling that fits a budget (Lecture 7’s √S law):

dtypeSBUF budgetHBM trafficFLOP/bytecore ridgebound
BF160.25 MiB954 MB63217memory
BF162 MiB367 MB164217memory
BF164 MiB250 MB241217compute
BF1628 MiB90 MB667217compute
FP82 MiB184 MB328434memory
FP84 MiB125 MB482434compute

A few MiB of SBUF make the GEMM compute-bound. FP8 halves the bytes and doubles the speed, so the intensity and the ridge both double, and the same 4 MiB budget suffices.

5.2 Attention

Script 03, Part 3 (one head, head_dim 128, causal; HBM traffic):

contextunfusedFlashAttention paper’s blocks, 28 MiBlarge query blocks, 1 MiB4 MiB16 MiB28 MiB
8,192545 MB273 MB20.2 MB12.3 MB8.4 MB (KV resident)8.4 MB
32,7688.62 GB4.24 GB215 MB72.9 MB50.1 MB33.6 MB (KV resident)
131,072138 GB42.3 GB3.01 GB736 MB300 MB222 MB

SBUF

Rules tuned for one machine do not transfer.

  • The paper’s rule fails with large SRAM. The FlashAttention paper’s block rule (query block ≤ head_dim, key block = M/4d) was designed for GPU shared memories of ~100 KB. With 28 MiB it keeps 128-row query blocks and re-reads K and V for every one of them.
  • Large query blocks fix it. As many query rows as fit, with 512-key blocks, cut K/V re-reads to N/B_r. At 128K that is ~190× less traffic.
  • Up to ~57K tokens, a head’s K and V simply stay resident in one core’s SBUF.

5.3 What if the weights lived in SBUF?

Script 03, Part 4 is a what-if, not an AWS deployment. It spreads a model’s weights over enough chips that they fit in SBUF and pipelines the layers. Batch 1, KV and attention ignored.

modelchipweightschips (SBUF)tokens/s per userchips (HBM)tokens/s per user (HBM)
Llama 3 8BTrainium2BF16925501181
Llama 3 8BTrainium2FP8465791361
Llama 3 70BTrainium2FP840166141

The HBM stream disappears, but the tensor engine becomes the limit. At batch 1 it consumes one 128 × 128 weight tile per 64-cycle instruction: 4.9 T weights/s per chip, only 1.7× an FP8 HBM stream.

  • Pipelining layers over chips does not shorten a token’s path.
  • Splitting every layer over the chips would add collectives (§6).

SRAM-centric machines (SambaNova’s 520-MiB tier in Lecture 13) pair the SRAM with datapaths and links built for that regime. A balanced design has no single fix.


6.1 All-reduce

An all-reduce sums a tensor across p chips and gives everyone the result. The ring algorithm takes 2(p − 1) steps, each moving 1/p of the data:

t=2(p−1)pnB+2(p−1) α.t = \frac{2(p-1)}{p}\frac{n}{B} + 2(p-1)\,\alpha .

A 2D torus does a reduce-scatter along X, an all-reduce along Y on 1/p_x of the data, and an all-gather along X. On 4 × 4 chips that is 12 latency steps instead of 30 for a 16-chip ring.

Script 04, Part 1. Published bandwidths; ASSUMED α = 2 µs on NeuronLink and 10 µs on EFA; a ring along one torus dimension gets half of a chip’s links.

message16 chips, ring4 × 4 torusUltraServer (64)4 instances over EFA64 instances over EFA
16 kB60.1 µs24.1 µs36.1 µs84.1 µs1.28 ms
64 MB278 µs242 µs276 µs542 µs1.82 ms
16 GB54.6 ms54.6 ms60.1 ms115 ms135 ms
  • Small messages are latency-bound, so topology (number of steps) decides.
  • Large messages are bandwidth-bound. A chip’s 1 TiB/s of NeuronLink is ~44× its 1/16 share of the instance’s EFA. Hierarchical algorithms send only 1/16 of the data over EFA, so 4 instances take ~2× one instance.

6.2 Tensor-parallel decode

Script 04, Part 2. Llama 3 70B in BF16, 4,096-token context. Each layer needs two all-reduces of batch × 8,192 × 2 bytes.

chipsbatchαHBM time per tokenall-reducescollective sharetokens/s per user
16 (torus)10.5 µs2.98 ms0.97 ms25%253
16 (torus)12 µs2.98 ms3.85 ms56%146
64 (UltraServer)10.5 µs0.74 ms1.45 ms66%456
64 (UltraServer)12 µs0.74 ms5.77 ms89%153
64 (UltraServer)322 µs0.97 ms6.07 ms86%142 (4,543 total)

With 2 µs steps, four times the chips buy no per-user speed (146 → 153 tokens/s). The HBM time falls 4×, but the collectives, a few KB each, are pure latency.

This is Ma and Patterson’s “low-latency interconnect” direction (Lecture 14), measured. It is also why chips that serve one model sit in one tightly coupled domain.

6.3 Data-parallel training

Script 04, Part 3. Llama 3 8B, 4M-token global batch, BF16 gradients (16 GB), 40% MFU (ASSUMED):

instanceschipscompute per stepgradient all-reduceratio
46411.3 s115 ms0.01
641,024705 ms135 ms0.19
2564,096176 ms140 ms0.79
1,02416,38444.1 ms155 ms3.53

Compute per step falls with the number of chips; the gradient all-reduce does not. Large-scale training therefore:

  • shards optimizer state and gradients (ZeRO/FSDP);
  • overlaps communication with the backward pass;
  • keeps the chattiest parallelism (tensor, pipeline) inside the fast NeuronLink domain.

That is the reason for UltraServers.


7. Numerics for training

7.1 BF16 and stochastic rounding

BF16 has 8 significant bits. Its spacing at 1.0 is 2⁻⁷ = 0.0078. With round to nearest, an update smaller than half a spacing is simply lost.

Script 04, Part 4. Adding 10⁻³ to w = 1.0, 1,000 times:

storagefinal w
exact2.0000
BF16, round to nearest even1.0000
BF16, stochastic rounding (5 seeds)1.9969 ± 0.0153

Stochastic rounding rounds up with probability equal to the discarded fraction, so the expected result is exact.

The same effect in least-squares training (512 × 64, 3,000 steps):

weights kept infinal loss
FP321.07 × 10⁻²
BF16, nearest21.0 (stalled)
BF16, stochastic1.19 × 10⁻²
BF16 + FP32 master copy1.10 × 10⁻²

The NeuronCore-v3 tensor engine supports stochastic rounding in hardware (published). It replaces the FP32 master copy and its 2 extra bytes per parameter (more with the optimizer’s state).

7.2 Configurable FP8

FP8 E4M3 covers magnitudes from 2 × 10⁻³ to 448. Gradients are often far smaller.

Script 04, Part 5 (gradient-like values ~10⁻⁵, log-normal spread):

formatrepresentable magnitudesflushed to zeroSQNR
E4M3, bias 7 (standard)2.0e-3 .. 4.5e2100%0.0 dB
E4M3, bias 157.6e-6 .. 1.837.5%21.6 dB
E4M3, bias 194.8e-7 .. 0.113.1%31.5 dB
E4M3, bias 7 + per-tensor scale(scaled)0%31.6 dB

Trainium’s configurable FP8 (cFP8, “adjustable exponent biasing”, published) slides the format’s binades onto the data. It is a power-of-two scale built into the format, equivalent to the per-tensor scales of Lecture 4.

Trainium3 adds MXFP8 and MXFP4: block scaling in hardware, at 4× the BF16 rate.


8. The software stack

A NeuronCore has no caches and no hardware scheduler between its engines. Everything the GPU does dynamically, the software does statically:

  • The Neuron compiler takes framework graphs (PyTorch through torch-neuronx, JAX) and produces per-engine instruction streams. It fuses operators, tiles them for SBUF and PSUM, chooses layouts, inserts DMA, and synchronizes the engines with semaphores. §4.1’s software pipelining and §4.5’s layout choice are its decisions.
  • NKI (Neuron Kernel Interface) lets programmers write kernels directly, close to the ISA. They choose tiles, the partition axis, which engine runs which operation, and how matmuls accumulate in PSUM. It plays the role CUDA/Triton kernels play on GPUs; FlashAttention-style kernels are written in it.
  • Collective libraries map all-reduces onto the torus, the UltraServer rings and EFA (§6). The collective-communication cores on the chip run them alongside the compute.

The lesson of the course since Lecture 2 applies with full force: the hardware’s efficiency is only as good as the schedule the software finds. A static, software-managed design trades the GPU’s dynamic tolerance for predictability and efficiency, and pays for it in compiler effort.


9. Summary

  1. Why in-house: cost per token is (capital + energy) / throughput. Removing a merchant margin lets a slower chip win on price; supply and system integration matter as much. AWS reports 30–40% better price performance for Trn2 than its GPU instances.
  2. The chips:
    • Trainium2 has 667 BF16 / 1,299 FP8 TFLOPS, 96 GiB at 2.9 TB/s and 224 MiB of SBUF; Trainium3 has 2,517 MXFP8 TFLOPS and 144 GiB at 4.9 TB/s.
    • The ridge points are GPU-like.
    • The systems are a 16-chip 4 × 4 torus per instance and 64 chips per UltraServer.
  3. A NeuronCore has four engines (tensor 128 × 128, vector, scalar, GpSimd) around a software-managed SBUF (128 partitions) and PSUM (8 banks). DMA moves everything.
  4. The tensor engine costs max(N, 64) cycles per instruction: full rate from 64 streamed tokens, 1.6% at one. FP8 modes deepen the contraction, so Q·Kᵀ and transposes do not speed up.
  5. Scheduling: software pipelining keeps the tensor engine 97% busy in prefill (1.35× over serial engines). Decode is DMA-bound (93–98%). With MXFP8 at long context, vector and scalar work together exceed the tensor work, and the exps reach 68–82% of it.
  6. SRAM: 4 MiB makes a prefill GEMM compute-bound, in BF16 and FP8. Large query blocks, not GPU-era block rules, minimize attention traffic. SBUF-resident weights would trade chips for per-user speed and hit the tensor engine’s batch-1 rate.
  7. Scale-out: small all-reduces are latency-bound. 70B decode gains nothing from 16 → 64 chips at 2 µs per step. Data-parallel gradient sync over EFA exceeds compute beyond ~250 instances.
  8. Numerics: BF16 training needs stochastic rounding or FP32 master weights. A configurable FP8 bias (or a scale) keeps gradients out of the underflow.

10. Common pitfalls

  • “FP8 doubles every matmul.” Only those whose contraction fills the deeper array (§3.3).
  • “More engines are always better.” They help only when the program interleaves work. Our first, unpipelined schedule gained nothing from them (§4.1).
  • “Decode needs a faster tensor engine.” It needs bytes: the DMA queue is the bottleneck (§4.3).
  • “Copy the GPU kernel’s tile sizes.” FlashAttention’s block rule wastes a large scratchpad (§5.2).
  • “More chips, faster tokens.” Not when each layer’s collectives are latency-bound (§6.2).
  • “BF16 is enough for weights.” Not with round-to-nearest and small learning rates (§7.1).
  • “Price per chip is what matters.” Cost per token is what matters, and margin, power and utilization all enter it (§1).

11. Exercises

Exercise 1 (peak from structure). Derive NC-v3’s published 79 TFLOPS BF16 and 158 TFLOPS FP8 from the array size and clock. Then derive Trainium3’s 2,517 MXFP8 TFLOPS.

Answer

NC-v3, BF16: 2 FLOPs × 128 × 128 MACs × 2.4 GHz = 78.6 TFLOPS.

NC-v3, FP8 (double-row): the 256-deep contraction gives 2× = 157 TFLOPS.

Trainium3: MXFP8 reads 8 × 128 inputs per cycle, a 512-deep contraction, so 4 × 78.6 = 315 TFLOPS per core, and × 8 cores = 2,517 TFLOPS.

Exercise 2 (utilization). Using max(N, 64), what fraction of the array does a decode step with 16 tokens use on a 4096 × 4096 weight matrix? What about a prefill tile of 300 tokens?

Answer

16 tokens: 16 / 64 = 25%.

300 tokens: a single chunk of 300 ≤ 512, so max(300, 64) = 300 cycles for 300 columns: 100% (moving chunks of up to 512 cost max(n, 64)).

Exercise 3 (FP8 and attention). Why does FP8’s double-row mode not speed up Q·Kᵀ for head_dim 128? What would a head_dim of 256 change?

Answer

head_dim 128. The mode doubles the contraction rows from 128 to 256. Q·Kᵀ contracts over head_dim = 128, so it fills only half the deeper array, and its time is unchanged.

head_dim 256. The contraction would fill the 256 rows, and Q·Kᵀ would run at the FP8 rate. (It would also double the KV cache per head.)

Exercise 4 (engine budget). At what context length does the scalar engine’s exp work equal the tensor engine’s attention matmul work on NC-v3 in BF16 (ignoring linear layers)?

Answer

Per score, the tensor engine does:

  • Q·Kᵀ and P·V: 4 × 128 = 512 FLOPs;
  • the transpose of P: 256 FLOP-equivalents.

That is ~768 FLOPs at 78.6 TFLOPS = 9.8 ps.

One exp at 154 G/s takes 6.5 ps.

So the exps never reach attention’s matmul time in BF16 (ratio 0.66), whatever the context. They approach it only when the linear layers are small and the matmuls faster.

Exercise 5 (pipelining). A tile’s chain has 25 stages: 7 on the tensor engine (total 60 µs), 18 elsewhere (total 30 µs, never more than 10 µs at a time on one engine). Estimate a 16-tile layer’s time without and with software pipelining.

Answer

Without pipelining: 16 × (60 + 30) = 1,440 µs.

With pipelining: the tensor engine is the bottleneck, ~16 × 60 = 960 µs plus a prologue/epilogue of about one tile’s non-tensor latency (~30 µs). That is ~990 µs, 1.45× faster.

Exercise 6 (decode bytes). A Trainium2 core holds 1/8 of Llama 3 8B in BF16 and decodes a batch of 64 at 4,096 tokens of context. Compute the weight and KV bytes per step per core, and the time at 362 GB/s.

Answer
  • Weights: 218 M/8 parameters × 2 bytes = 54.5 MB.
  • KV: 64 × 4,096 × 2 × 1 KV head × 128 × 2 bytes = 134 MB.
  • Time: 188.5 MB / 362 GB/s = 521 µs (the model’s DMA work: 534 µs, including latencies).

Exercise 7 (SBUF and the √S law). From Part 2’s table, how does the HBM traffic scale between 1 MiB (484 MB) and 4 MiB (250 MB)? Compare with 1/√S.

Answer

The ratio is 484 / 250 = 1.94, against √4 = 2. The √S law (Lecture 7) holds closely until the compulsory traffic (each matrix read once) starts to dominate at larger budgets.

Exercise 8 (attention block sizes). With 28 MiB (14.7 M BF16 elements) and head_dim 128, how many query rows fit with 512-key blocks? How many times are K and V read for a 131,072-token context?

Answer

B_r = (14.7 M − 2 × 512 × 128) / (2 × 128) ≈ 56,832 (a multiple of 128).

K and V are read ⌈131,072 / 56,832⌉ = 3 times (fewer with the causal mask).

Exercise 9 (all-reduce latency). On a 4 × 4 torus with α = 2 µs, how many latency steps does an all-reduce take, and what is its latency floor? For Llama 3 70B (80 layers, 2 all-reduces each), what is the per-token collective floor?

Answer
  • Steps: 2 × 3 (reduce-scatter and all-gather along X) + 2 × 3 (all-reduce along Y) = 12 steps, a floor of 24 µs.
  • Per token: 160 all-reduces × 24 µs = 3.84 ms, matching the model’s 3.85 ms.

The floor alone caps decoding at ~260 tokens/s per user, whatever the HBM.

Exercise 10 (data parallelism). Why does the gradient all-reduce time barely change from 64 to 1,024 instances, while compute falls 16×?

Answer

The bandwidth term of a ring all-reduce is 2(p − 1)/p × n / B, which tends to 2n/B and is independent of p for large p. The latency term grows with p, but slowly at these sizes.

Each chip must still send and receive about twice its shard, whatever the number of instances. Compute, by contrast, is divided among all chips.

Exercise 11 (stochastic rounding). A BF16 weight is 1.0 and receives an update of +0.002 per step. What is the probability that SR rounds up at each step, and the expected weight after 1,000 steps? What does RNE give?

Answer

SR. The spacing above 1.0 is 2⁻⁷ = 0.0078125, so 1.002 lies 0.256 of a spacing above 1.0 and rounds up with probability 0.256.

The expected increment per step is exactly 0.002, so after 1,000 steps the expected weight is ≈ 3.0. Above 2.0 the spacing doubles, but the expectation stays unbiased.

RNE. 0.002 < 0.0039 (half a spacing), so the weight stays 1.0 forever.

Exercise 12 (design). You must serve Llama 3 70B at ≥ 300 tokens/s per user. Using §5.3 and §6.2, list which levers help, and estimate what α would be needed on 16 chips.

Answer

What the per-token time is made of. At batch 1 on 16 chips:

  • HBM: 2.98 ms per token;
  • collectives: 80 × 2 × (12 α + bandwidth terms).

For 300 tokens/s the total must be ≤ 3.33 ms. That leaves ≤ 0.35 ms for 160 all-reduces, about 2.2 µs each, so α ≲ 0.18 µs: unrealistic.

The levers:

  • FP8 weights halve the HBM time (1.49 ms), allowing α ≈ 0.9 µs;
  • fewer, larger collectives (fusing the two all-reduces of a layer);
  • speculative decoding (several tokens per weight pass);
  • more HBM bandwidth per chip (Trainium3’s 4.9 TB/s).

More chips alone do not help (§6.2).


12. Further reading

  • AWS Neuron documentation: Trainium2 and Trainium3 architecture pages; NeuronCore-v2/v3/v4; “Trainium/Inferentia2 Architecture Guide for NKI” and “Trainium2 Architecture Guide for NKI”; Trn2 system architecture (awsdocs-neuron.readthedocs-hosted.com).
  • AWS News Blog, “Amazon EC2 Trn2 instances and Trn2 UltraServers for AI/ML training and inference are now available” (December 2024).
  • N. P. Jouppi et al., “In-datacenter performance analysis of a tensor processing unit”, ISCA 2017: the other cloud provider’s first in-house accelerator (Lecture 5).
  • S. Gupta et al., “Deep learning with limited numerical precision”, ICML 2015: stochastic rounding for low-precision training.
  • P. Micikevicius et al., “FP8 formats for deep learning”, 2022 (arXiv:2209.05433).
  • S. Rajbhandari et al., “ZeRO: memory optimizations toward training trillion parameter models”, SC 2020.
  • J. Shah et al., “FlashAttention-3”, 2024, and the FlashAttention-4 discussions of exp throughput on Blackwell: the same engine-balance pressure on GPUs.

13. Next lecture

Lecture 17 is the course’s last: a guest lecture on NVIDIA’s GPU architecture for AI and a course review. We will:

  • decompose a decade of GPU speedups into process, number formats, specialized instructions and sparsity;
  • model rack-scale systems (NVLink domains of 72 GPUs) for training and serving with tensor, pipeline and data parallelism;
  • go back through every lever of Lecture 1, to see where each later lecture used it.
← 返回课程目录