LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 192 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/9
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningBayesian Inference from EvidenceStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/15
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageStatistical Learning and GeneralizationConformal Prediction and UncertaintyClustering and PCAProbabilistic Generative ModelsCore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingCausal Inference and CounterfactualsPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/25
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernancePrivacy-Preserving Machine LearningData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/17
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningTraining Run OperationsReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/27
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceAccelerator Architecture Field GuideCorrect GPU Profiling and BenchmarkingGPU Kernel Performance Engineering LabGPU Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingDistributed Inference Data PlaneServing Benchmark EngineeringA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning Agent System Design
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnInference & Production ScaleAccelerator Architecture Field Guide
🚀HardInference Optimization

Accelerator Architecture Field Guide

Compare accelerator execution, memory, interconnect, and programming models through one LLM workload, then choose what must be remeasured when moving between NVIDIA, AMD, TPU, Trainium, and Apple silicon.

22 min read
Learning path
Step 144 of 192 in the full curriculum
Model Parallelism for LLM InferenceCorrect GPU Profiling and Benchmarking

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

An 8-billion-parameter code assistant receives eight repository prompts, each 4,096 tokens long. Its prompt pass is fast on one accelerator, yet token generation crawls. Move the same model graph to another accelerator and the slow operation changes. Nothing about “more peak FLOPS” explains either result.

The CUDA foundation introduced kernels, thread blocks, warps, device memory, and synchronized timing. The model-parallelism lesson then showed that a logical shard count isn't a physical route. Keep both ideas: an accelerator runs work through a concrete execution hierarchy, and every tensor or collective travels through a concrete memory path.

We follow one model projection across five programming stacks. The intent isn't to crown a winner. Instead, preserve the workload's meaning while execution groups, local memory, compiler boundaries, and interconnects change.

Snapshot boundary, checked August 29, 2026: Concrete targets here are NVIDIA H100 (Hopper) and B200-class Blackwell under CUDA, AMD MI300/CDNA 3 and MI350/CDNA 4 under the ROCm 7.14 documentation, Google TPU v6e with Pallas, AWS Trainium2 with Neuron 2.32 documentation, and Apple silicon through PyTorch MPS. Hardware availability, software support, and cloud shapes change. Recheck official compatibility pages before buying capacity or freezing a production image.[1]Reference 1NVIDIA Hopper Tuning Guidehttps://docs.nvidia.com/cuda/archive/13.0.0/hopper-tuning-guide/index.html[2]Reference 2Blackwell Tuning Guidehttps://docs.nvidia.com/cuda/archive/13.0.2/pdf/Blackwell_Tuning_Guide.pdf[3]Reference 3ROCm Core SDK 7.14.0 Release Noteshttps://rocm.docs.amd.com/en/docs-7.14.0/about/release-notes.html[4]Reference 4TPU v6ehttps://cloud.google.com/tpu/docs/v6e[5]Reference 5The Trainium Memory Hierarchyhttps://awsdocs-neuron.readthedocs-hosted.com/en/v2.32.0/nki/get-started/about/memory-hierarchy-overview.html[6]Reference 6Accelerated PyTorch training on Mac.https://developer.apple.com/metal/pytorch/

One projection, two different machines inside it

Take the first feed-forward projection from the running assistant. Each input row has K = 4,096 features, and the projection produces N = 11,008 features. Its simplified matrix multiplication is:

YM×N=XM×KWK×NY_{M \times N} = X_{M \times K} W_{K \times N}YM×N​=XM×K​WK×N​

M is the number of token rows processed together. BF16 stores each matrix element in 2 bytes. The weight matrix contains about 86 MiB, independent of phase.

During prefill, all prompt tokens are processed in parallel. Eight 4,096-token prompts give M = 32,768. During decode, each active sequence contributes one new token, so the same eight requests give M = 8. The weight shape hasn't changed. Reuse has.

For a matrix multiplication, the arithmetic work is approximately:

FLOPs=2MKN\text{FLOPs} = 2MKNFLOPs=2MKN

An idealized traffic floor that reads each input and weight once and writes each output once is:

bytes=2(MK+KN+MN)\text{bytes} = 2(MK + KN + MN)bytes=2(MK+KN+MN)

Dividing work by traffic gives arithmetic intensity, measured in floating-point operations per byte. The script computes both phases as a shape calculation, not a hardware benchmark.

projection-phase-intensity.py
1K = 4_096 2N = 11_008 3bytes_per_value = 2 # BF16 4 5phases = { 6 "prefill": 8 * 4_096, 7 "decode": 8, 8} 9 10weight_mib = K * N * bytes_per_value / 2**20 11print(f"weight matrix: {weight_mib:.0f} MiB") 12 13for phase, rows in phases.items(): 14 flops = 2 * rows * K * N 15 traffic = bytes_per_value * (rows * K + K * N + rows * N) 16 intensity = flops / traffic 17 print(f"{phase:7s}: M={rows:6,d}, ideal intensity={intensity:7.1f} FLOP/byte")
Output
1weight matrix: 86 MiB 2prefill: M=32,768, ideal intensity= 2736.0 FLOP/byte 3decode : M= 8, ideal intensity= 8.0 FLOP/byte
Two aligned bar charts for the same 86 MiB BF16 weight matrix. The first chart uses a base-2 logarithmic axis for token rows per weight sweep: prefill is 15 at 32,768 rows and decode is 3 at 8 rows. The second uses a base-2 logarithmic axis for ideal arithmetic intensity: prefill is about 11.4 at 2,736 FLOP per byte and decode is about 3 at 8 FLOP per byte. The row-count gap spans twelve powers of two, while the arithmetic-intensity gap spans about 8.4, showing that decode gets far less work from each weight read.
Both charts use a base-2 logarithmic axis. Prefill reuses the same 86 MiB weight matrix across 4,096 times as many token rows, so its ideal arithmetic intensity is about 343 times higher. Decode is the phase most likely to expose weight bandwidth and launch overhead.

Real kernels reread some data, cache some tiles, fuse operations, and may use quantized weights. Still, the phase split survives: prefill presents large matrix work, while low-concurrency decode repeatedly streams a large weight set for a few rows. Peak matrix throughput predicts prefill better than it predicts decode.

Why can the same projection be compute-heavy during prefill and memory-heavy during decode?

Answer

Prefill applies each loaded weight tile to 32,768 token rows in this workload, while decode applies it to only 8. The large prefill matrix gets far more arithmetic from each byte moved. Decode has much lower arithmetic intensity, so weight traffic and fixed dispatch costs can dominate.

The invariant behind every accelerator

Fast accelerator code keeps reused data close to compute, performs enough work before eviction, and overlaps the next transfer with current arithmetic. Vendor names differ, but four ownership questions don't:

  1. Which group executes one instruction together?
  2. Which memory can that group share at low latency?
  3. Who schedules movement between large memory and local memory?
  4. Which physical link carries bytes when work spans devices?

Time to first token (TTFT) covers prompt processing and scheduling. Time per output token (TPOT) exposes the serial decode loop. The running projection turns the ownership questions into a four-stage receipt:

Diagram showing 1. Map work group plus local memory, 2. Stage bytes large memory to reused tiles, 3. Route devices link plus collective, and 4. Verify TTFT, TPOT, output.
1. Map work group plus local memory, 2. Stage bytes large memory to reused tiles, 3. Route devices link plus collective, and 4. Verify TTFT, TPOT, output.

A platform port is incomplete until both clocks and an output-correctness check are attached to the same prompt distribution.

The local-memory vocabulary is different, but the job is recognizable:

Stack and dated targetExecution unit to reason aboutFast software-visible storageLarge-memory movementMulti-device boundaryFirst porting question
NVIDIA CUDA, Hopper H100 / Blackwell32-thread warp inside a thread block on an SMregisters, shared memory, and Hopper-era distributed shared memoryexplicit loads, libraries, compiler scheduling, and TMA for suitable multidimensional copiesNVLink/NVSwitch or PCIe under topology-aware collectives such as NCCLDoes the binary target the device, and does the tile overlap loads without exhausting registers or shared memory?
AMD ROCm/HIP, CDNA 3 / CDNA 464-thread wavefront inside a work-group on a compute unitvector registers and Local Data Share (LDS)HIP kernels, libraries, and explicit or compiler-managed copiesInfinity Fabric or PCIe under RCCLDid CUDA code assume a 32-lane warp, and is the exact gfx target supported by the pinned ROCm image?
Google TPU v6e, JAX/PallasPallas programs over TensorCore resources: matrix-multiply, vector, and scalar unitsvector memory (VMEM) plus scalar memory (SMEM)compiler-pipelined HBM blocks selected by BlockSpecinter-chip interconnect (ICI) across a declared slice topologyDo block shapes fit TPU constraints, and does grid order preserve useful VMEM reuse?
AWS Trainium2, Neuron/NKITensor, vector, scalar, or GPSIMD engine inside a NeuronCore-v3State Buffer (SBUF) and Partial Sum Buffer (PSUM)explicit direct-memory-access copies between HBM and SBUF, with PSUM accumulationNeuronLink-v3 and Neuron collectives across a declared rank groupWhich engine owns each operation, and will live tiles spill from SBUF or PSUM?
Apple silicon, PyTorch MPSMPS Graph or tuned MPS kernels submitted to the integrated GPUcaches and threadgroup resources behind the graph or kernel implementationunified physical memory, still mediated by MPS tensors and command schedulingnormally one Mac for this backend pathDoes every operation stay supported on MPS, and does model state leave enough system-memory headroom?

The table compares ownership, not speed. After a symptom appears, inspect the platform-specific owner in its row.

NVIDIA Hopper and Blackwell: preserve mapping, retune pressure

CUDA presents grids of thread blocks, blocks of threads, 32-thread warps, and streaming multiprocessors (SMs). Threads in one block share on-chip shared memory and can synchronize. Global device memory holds large tensors. Those boundaries from the CUDA prerequisite remain valid on Hopper and Blackwell.[7]Reference 7CUDA Programming Guide.https://docs.nvidia.com/cuda/cuda-programming-guide/

Hopper added the Tensor Memory Accelerator (TMA), which can move multidimensional tensor tiles between global and shared memory while thread blocks continue independent work. Hopper also added thread-block clusters and distributed shared memory across blocks in a cluster.[1]Reference 1NVIDIA Hopper Tuning Guidehttps://docs.nvidia.com/cuda/archive/13.0.0/hopper-tuning-guide/index.html Those features are useful only when a kernel has a tile worth reusing. Copying the decode projection's 86 MiB weight matrix through shared memory without enough rows to reuse each tile adds staging without changing the bandwidth problem.

Blackwell retains and extends the CUDA programming model. NVIDIA's Blackwell tuning guide still starts with coalesced global access, reduced redundant traffic, suitable launch configuration, and limited warp divergence. It also warns that occupancy limits differ across Blackwell compute capabilities, so “Blackwell” isn't one register-and-shared-memory budget.[2]Reference 2Blackwell Tuning Guidehttps://docs.nvidia.com/cuda/archive/13.0.2/pdf/Blackwell_Tuning_Guide.pdf

For the running workload, use the same algorithmic split on both generations:

  • Prefill: choose a matrix path whose tile shape keeps Tensor Core work dense, then overlap global-to-shared movement with current computation.
  • Decode: batch enough active rows to reuse weights, use a kernel specialized for small M, or reduce bytes through a verified quantization path.
  • Port from Hopper to Blackwell: ship native code for the target or forward-compatible PTX, then retune. A binary that launches is only a compatibility result.[2]Reference 2Blackwell Tuning Guidehttps://docs.nvidia.com/cuda/archive/13.0.2/pdf/Blackwell_Tuning_Guide.pdf

A CUDA failure that looks like architecture progress

Suppose a Hopper kernel uses more shared memory to stage a larger weight tile. One block now reuses more bytes, but fewer blocks remain resident on each SM. TPOT gets worse.

The symptom isn't proof that shared-memory tiling failed. Larger tiles improved reuse and reduced concurrency at the same time. Compare achieved occupancy, memory traffic, and eligible warps, then test smaller tiles. If decode still moves almost the same weight bytes per token, more staging can't create missing reuse.

A Hopper decode kernel gets slower after its shared-memory tile doubles. Which two effects must be separated?

Answer

The larger tile may reduce global-memory traffic per block, but its shared-memory and register footprint may lower occupancy. Measure both data movement and resident or eligible warps before deciding whether the tile helped.

AMD CDNA and ROCm: familiar syntax, different lane contract

HIP deliberately resembles CUDA: kernels launch grids of blocks, threads use threadIdx and blockIdx, and a work-group shares Local Data Share (LDS). That similarity helps source portability. It doesn't make wave-level assumptions portable.

On CDNA architectures, AMD's HIP programming-model documentation specifies a 64-thread wavefront. NVIDIA code commonly assumes a 32-thread warp. A reduction that hardcodes masks, lane counts, or “four warps per 128-thread block” can return wrong values or waste half a wave after a mechanical HIP conversion.[8]Reference 8Introduction to the HIP Programming Modelhttps://rocm.docs.amd.com/projects/HIP/en/develop/understand/programming_model.html

Repair the execution model before changing syntax:

  • derive lane behavior from warpSize or use library primitives with documented semantics;
  • recalculate work-group size as a number of 64-lane waves on CDNA;
  • remeasure vector-register and LDS pressure, because both limit resident waves;
  • compile for the exact LLVM gfx target in the pinned environment.

As of the snapshot date, ROCm 7.14 documentation lists MI300-series accelerators as CDNA 3 with gfx942 and MI350-series accelerators as CDNA 4 with gfx950.[3]Reference 3ROCm Core SDK 7.14.0 Release Noteshttps://rocm.docs.amd.com/en/docs-7.14.0/about/release-notes.html Keep those identifiers in build and benchmark records. “ROCm passed” without hardware target, ROCm version, and library versions isn't reproducible.

RCCL provides collective communication for ROCm stacks. Its current MI300X guidance describes eight-GPU systems where every accelerator pair has dedicated Infinity Fabric links. Using only part of that topology changes available collective routes, so a tensor-parallel result needs the selected ranks, not only TP=4.[9]Reference 9RCCL Documentationhttps://rocm.docs.amd.com/projects/rccl/en/docs-7.2.4/

For the projection, CDNA's decision remains phase-specific. Dense prefill can keep matrix units busy through large tiles. Decode needs enough concurrent rows, a small-M kernel, or fewer weight bytes. Replacing CUDA API names with HIP API names can't change M = 8.

A 128-thread CUDA reduction is ported to CDNA and keeps a hardcoded 32-lane shuffle mask. Why is this a correctness risk rather than only a tuning issue?

Answer

CDNA uses 64-thread wavefronts. A hardcoded 32-lane algorithm may combine only half of each wave or apply invalid lane assumptions, so output can be wrong. Replace the assumption with documented cross-lane primitives or a wave-size-aware algorithm, then test against a reference.

TPU and Pallas: map tiles, not CUDA threads

TPU v6e exposes a TensorCore with matrix-multiply units (MXUs), a vector unit, and a scalar unit. The MXUs handle dense matrix work, while vector and scalar operations have separate execution resources.[4]Reference 4TPU v6ehttps://cloud.google.com/tpu/docs/v6e A port that treats TPU as a GPU with different thread names misses that split.

Pallas is JAX's custom-kernel layer for GPU and TPU. On TPU, kernel inputs usually reside in high-bandwidth memory (HBM), while kernel-body references point into faster vector memory (VMEM) or scalar memory (SMEM). BlockSpec describes which input and output tile each program sees; the compiler can overlap HBM transfers with computation.[10]Reference 10Writing TPU Kernels with Pallashttps://docs.jax.dev/en/latest/pallas/tpu/details.html

Grid order carries extra meaning. Pallas TPU programs normally advance sequentially in lexicographic grid order. Consecutive programs that use the same input slice can reuse data already in VMEM and skip another HBM transfer.[10]Reference 10Writing TPU Kernels with Pallashttps://docs.jax.dev/en/latest/pallas/tpu/details.html Reordering grid axes can therefore change traffic without changing the mathematical output.

Map the running projection this way:

  1. Put the 86 MiB weights in HBM.
  2. Use BlockSpec to select weight and activation tiles that fit VMEM.
  3. Arrange the prefill grid so consecutive output tiles reuse one weight or input slice where possible.
  4. Accumulate matrix work on MXUs and keep softmax, normalization, or element-wise work on suitable vector paths.
  5. For M = 8 decode, test padded or batched shapes against real TPOT. A large MXU doesn't guarantee high use for a skinny matrix.

Pallas block shapes have backend constraints, including divisibility requirements on the trailing dimensions for TPU paths.[10]Reference 10Writing TPU Kernels with Pallashttps://docs.jax.dev/en/latest/pallas/tpu/details.html A shape rejection at compile time isn't an availability incident. The tile contract failed. Pad with correctness masking, choose a legal block, or keep the operation in compiled JAX when a custom kernel doesn't earn its maintenance cost.

A TPU failure caused by legal but poor grid order

Two Pallas kernels produce identical outputs. Kernel A varies the output-column tile fastest, so consecutive programs reuse the same input tile. Kernel B varies the input-row tile fastest and reloads that input tile more often. Kernel B reports more HBM traffic and worse prefill time.

The math can't distinguish them. The grid-to-block mapping can. Inspect BlockSpec, grid order, and HBM-to-VMEM transfers before changing model precision.

Trainium and NKI: assign work to engines and memories

Trainium2's NeuronCore-v3 contains tensor, vector, scalar, and general-purpose SIMD (GPSIMD) engines plus software-managed on-chip SRAM.[11]Reference 11NeuronCore-v3 Architecturehttps://awsdocs-neuron.readthedocs-hosted.com/en/v2.29.1/about-neuron/arch/neuron-hardware/neuron-core-v3.html Neural Kernel Interface (NKI) code makes that specialization visible.

NKI's memory path has three named levels for our projection:

  • HBM holds kernel inputs and outputs.
  • SBUF is the main software-managed on-chip buffer shared by compute engines.
  • PSUM holds partial matrix-multiply accumulations near the tensor engine.

An NKI kernel loads HBM tiles into SBUF, performs work from internal memory, accumulates matrix results in PSUM when appropriate, and stores completed outputs back through SBUF to HBM.[5]Reference 5The Trainium Memory Hierarchyhttps://awsdocs-neuron.readthedocs-hosted.com/en/v2.32.0/nki/get-started/about/memory-hierarchy-overview.html If live tiles exceed SBUF or PSUM capacity, the compiler inserts spills and refills. That can preserve correctness while quietly destroying the intended traffic pattern.

The running projection suggests an engine schedule: direct-memory-access engines prefetch the next X and W tiles, the tensor engine performs matrix multiplication, vector or scalar engines handle fused follow-up operations they support, and the current output tile accumulates in PSUM. NKI tile dimensions also distinguish partition and free dimensions, so a valid NumPy shape isn't yet a valid physical layout.

Trainium2 systems connect chips through NeuronLink-v3 in a 4-by-4 two-dimensional torus within a 16-chip instance.[12]Reference 12Amazon EC2 Trn2 Architecturehttps://awsdocs-neuron.readthedocs-hosted.com/en/v2.32.0/about-neuron/arch/neuron-hardware/trn2-arch.html Keep tensor-parallel ranks aligned with the actual topology. A rank count alone hides routing, exactly as it did for CUDA and ROCm.

An NKI failure that keeps answers correct

The prefill kernel grows its fused region to remove one HBM round trip. Live intermediates no longer fit SBUF, so the compiler adds spills. Latency increases and the trace shows extra DMA traffic.

Split the fusion or shrink tiles until the live set stays on chip. “More fusion” isn't a monotonic optimization when software-managed local memory is the limiting resource.

Why can a larger fused NKI kernel run slower even though it launches fewer kernels?

Answer

Fusion lengthens the lifetime of intermediate tiles. If that live set overflows SBUF or PSUM, spills add HBM traffic. Fewer launches can lose to more bytes moved.

Apple MPS: unified memory changes transfer, not capacity

PyTorch's Metal Performance Shaders (MPS) backend maps tensor operations to MPS Graph and tuned MPS kernels on Apple platforms.[6]Reference 6Accelerated PyTorch training on Mac.https://developer.apple.com/metal/pytorch/[13]Reference 13MPS backend.https://docs.pytorch.org/docs/stable/notes/mps MPS Graph represents operations and tensors as a symbolic compute graph that can be compiled into an executable.[14]Reference 14Metal Performance Shaders Graphhttps://developer.apple.com/documentation/metalperformanceshadersgraph

Apple silicon uses a unified physical memory pool. The CPU and GPU don't have the discrete host-RAM-to-VRAM boundary used by a typical data-center GPU. PyTorch still treats cpu and mps as different device targets, and unified memory is still finite.[15]Reference 15MLX: An array framework for Apple siliconhttps://github.com/ml-explore/mlx[13]Reference 13MPS backend.https://docs.pytorch.org/docs/stable/notes/mps

For the 8B BF16 model, weights alone need about 16 GB in decimal units. The machine also needs KV cache, temporary activations, allocator headroom, macOS, and other applications. A Mac advertised with enough total memory can still enter pressure or fail allocation once the full serving ledger is counted.

MPS is strongest in this field guide as a local path: validate graph behavior, test product logic, and measure an on-device latency envelope. Keep three questions separate:

  1. Is the operation implemented on MPS?
  2. Does the whole model fit within safe system-memory headroom?
  3. Does the graph execute fast enough after warmup and synchronization?

When PYTORCH_ENABLE_MPS_FALLBACK=1 is enabled, an unsupported MPS operation can fall back to the CPU and create a latency cliff.[16]Reference 16MPS Environment Variables.https://docs.pytorch.org/docs/stable/mps_environment_variables.html Unified memory makes the detour less visually obvious than a discrete device copy, but it doesn't make CPU and GPU execution equally fast. Profile for CPU operations and synchronization gaps before blaming GPU arithmetic.

Choose programming depth after the bottleneck

Most ports should stop at the highest layer that meets correctness and service-level objectives (SLOs). Each step downward gains control and creates a new maintenance surface:

LayerTypical toolsWhat you controlWhat you inheritMove lower when
Model graphPyTorch, JAX, framework backendshapes, batching, precision, graph breaksvendor libraries, compiler lowering, memory planningtrace shows one material unsupported or poorly lowered operation
Compiler and library configurationtorch.compile, XLA, cuBLAS, hipBLASLt, MPS Graph, Neuron compilerfusion boundaries, layouts, autotuning, capture, static shapestested kernels and many architecture detailsexisting kernels miss a stable workload shape or move avoidable bytes
Portable kernel DSLTriton or Pallas where supportedprogram grid, blocks, local tiles, pipeliningbackend code generation and some schedulingone hotspot has enough volume to repay backend testing
Native kernelCUDA C++, HIP, NKI, Metalengine, memory, synchronization, and launch choicesalmost nothing about portabilitya measured hotspot needs hardware-specific behavior the higher layer can't express

Portability is a test matrix, not a source-language property. A Triton kernel may support NVIDIA and AMD while using different legal tile sizes. A Pallas kernel may share BlockSpec vocabulary across GPU and TPU while requiring backend-specific memory and shape rules. NKI exposes Trainium's memory hierarchy directly. MPS Graph may compile a complete graph without offering the same custom-kernel surface as CUDA.

For our assistant, start with graph-level BF16 inference on each candidate. Preserve tokenization, weights, prompts, decoding settings, and output checks. Move down only after a trace identifies a stable projection, attention, normalization, or collective hotspot.

Read failures as ownership mistakes

The same symptom can point to a different owner on each platform. Use evidence in this order: output, phase, memory path, execution mapping, then topology.

SymptomLikely ownership errorDisambiguating evidenceFirst controlled change
Prefill is fast, TPOT is poortoo few decode rows reuse each weight loadsmall M, high weight traffic, low matrix-engine useincrease continuous-batch rows or test a small-M / quantized kernel
Port is wrong only on AMD32-lane warp assumption survived conversionfailing reduction test at wave boundaryuse wave-size-aware primitive and test 63, 64, and 65 elements
Pallas TPU compile rejects a tileBlockSpec violates backend shape rulescompiler error names block dimensionschoose legal trailing dimensions and mask padding
TPU output is correct but HBM traffic risesgrid order lost VMEM reusetransfer trace changes while operations don'treorder grid axes so repeated slices are consecutive
NKI fusion is correct but slowerlive tiles spill from SBUF or PSUMadded spill/refill DMA in traceshrink tile or split fusion
MPS latency jumps for one model revisionunsupported op fell back or graph brokeCPU activity and extra command gapsisolate operation, replace it, or keep explicit CPU baseline
Multi-device TPOT regresseslogical shards crossed a worse physical routecollective time and selected link topologyremap ranks within fast domain before changing model
New accelerator launches but isn't fastercompatibility passed; tuning didn'tsame output, different occupancy, tiling, or library pathrerun phase-specific trace and tune one proven hotspot

Don't change precision, batching, kernel code, and topology in one experiment. That destroys attribution. Keep one baseline and change one ownership boundary at a time.

Build an architecture decision receipt

Suppose the assistant must meet p95 TTFT below 450 ms and p95 TPOT below 45 ms for eight 4,096-token prompts. Those thresholds are exercise inputs, not published accelerator results.

For every candidate, record one row with:

  • exact accelerator and count;
  • host or instance shape and physical topology;
  • driver, runtime, framework, compiler, and library versions;
  • model revision, dtype, quantization, and kernel path;
  • prompt, output, concurrency, arrival, and warmup distributions;
  • weight, KV-cache, temporary, and safety-headroom memory;
  • p50, p95, and p99 TTFT and TPOT;
  • output tolerance plus task-level quality check;
  • profiler evidence for the largest compute, memory, and collective regions.

Then make a constrained decision:

  1. Reject any point that fails output or task quality.
  2. Reject any point that exceeds safe memory headroom.
  3. Reject any point that misses either latency SLO.
  4. Compare goodput and cost only among remaining points.

Architecture changes which knobs exist. It doesn't change that decision order. An accelerator with a higher unconstrained token rate still loses if its p95 TPOT misses the user's limit.

Two accelerators pass numerical checks. Candidate A has higher total tokens per second but misses the p95 TPOT limit. Candidate B meets TTFT and TPOT with lower total throughput. Which candidate is eligible?

Answer

Candidate B. Correctness, fit, and latency SLOs are gates. Throughput ranks only the candidates that pass all gates.

The field guide leaves one unresolved problem: each diagnosis above depends on trustworthy timing, traces, counters, and output comparisons. The next lesson turns those words into a repeatable benchmark and correctness workflow.

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.The running projection uses the same 86 MiB BF16 weight matrix for prefill with M=32,768 and decode with M=8. Which conclusion follows from the worked arithmetic-intensity model?

Correct answer: Prefill gets far more arithmetic from each weight byte, while decode is more exposed to weight traffic and fixed dispatch cost.

The worked lower bound is about 2,736 FLOP/byte for prefill and 8 FLOP/byte for decode. The same weights are reused across 4,096 times as many token rows during prefill, so decode exposes memory movement and launch overhead much more strongly.

2.A Hopper decode kernel doubles its shared-memory tile. Global-memory transactions fall, but TPOT increases. Which explanation should be tested first?

Correct answer: The larger tile may improve reuse while lowering occupancy through higher shared-memory or register pressure.

Tile size changes at least two mechanisms: bytes reused per block and resources consumed per block. Higher resource use can reduce resident blocks or eligible warps. Measure traffic and occupancy together.

3.A CUDA wave reduction hardcodes 32 lanes and is mechanically converted to HIP for a CDNA accelerator. Which review finding is most serious?

Correct answer: CDNA wavefronts have 64 lanes, so the reduction can omit half a wave and return incorrect values.

Lane count is part of the algorithm when cross-lane masks or shuffles are hardcoded. CDNA's 64-thread wavefront makes a 32-lane assumption a correctness bug, not merely a launch-tuning choice.

4.Two correct Pallas TPU kernels use the same tiles, but one reloads HBM data more often. Which difference can explain the traffic gap?

Correct answer: Grid order can stop consecutive programs from reusing the same input slice already resident in VMEM.

Pallas TPU grid order is normally sequential and lexicographic. Consecutive programs can reuse an input slice in VMEM. Changing which grid axis varies fastest can therefore change HBM transfers without changing outputs.

5.An NKI prefill kernel fuses matrix multiplication, bias, and activation. It stays numerically correct but adds HBM traffic. What is the most direct hypothesis?

Correct answer: The longer-lived intermediates overflow SBUF or PSUM, causing compiler-inserted spills and refills.

Fusion reduces boundaries but increases the live on-chip working set. NKI's SBUF and PSUM are finite software-visible resources. Overflow can preserve answers by spilling to HBM while losing the intended traffic reduction.

6.An 8B BF16 model has about 16 GB of weight data and runs on Apple silicon with unified memory. Which capacity statement is sound?

Correct answer: Weights, KV cache, temporaries, macOS, and other processes share finite memory, so weight-only sizing needs headroom.

Unified memory removes the usual discrete RAM-to-VRAM pool split, not the capacity limit. The model's full memory ledger competes with the operating system and other applications.

7.A tensor-parallel deployment has the same rank count on NVIDIA and AMD systems. Why isn't TP=4 enough to compare them?

Correct answer: Rank count omits physical placement, link type, collective library path, and achieved communication behavior.

Logical ownership doesn't reveal whether ranks cross NVLink, Infinity Fabric, PCIe, or a network boundary. Decode collectives can repeat inside every layer, so route and library behavior belong in the benchmark receipt.

8.A graph-level implementation is correct and meets memory and latency SLOs on all target accelerators. What is the best reason to add a native custom kernel?

Correct answer: A stable, measured hotspot needs a hardware behavior that compiler and library paths can't express efficiently.

Higher layers inherit mature libraries, compilers, and portability. Move lower only when evidence identifies a material hotspot and the extra control can repay implementation and backend-testing cost.

9.A new accelerator produces correct outputs and higher total token throughput, but p95 TPOT exceeds the service limit. How should it be classified?

Correct answer: Ineligible until TPOT meets the limit, because throughput ranks only candidates that pass correctness, fit, and latency gates.

The decision order treats correctness, memory safety, TTFT, and TPOT as gates. An unconstrained throughput win doesn't compensate for missing the user's p95 token-latency limit.

10.Which benchmark change most cleanly tests whether poor decode performance comes from missing weight reuse?

Correct answer: Sweep active decode rows while keeping model revision, precision, kernel path, topology, and output checks fixed.

Active rows directly change how many token rows reuse each weight sweep. Holding other boundaries fixed preserves attribution, while correctness checks make sure the apparent speedup hasn't changed model behavior.

10 questions remaining.

Next Step
Continue to Correct GPU Profiling and Benchmarking

Architecture vocabulary tells you where work could stall. Next you will collect synchronized timings, traces, counters, and correctness evidence that show where it actually stalls.

PreviousModel Parallelism for LLM Inference
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

NVIDIA Hopper Tuning Guide

NVIDIA · 2026 · Official documentation

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

Blackwell Tuning Guide

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/archive/13.0.2/pdf/Blackwell_Tuning_Guide.pdf

ROCm Core SDK 7.14.0 Release Notes

AMD · 2026 · Official documentation

https://rocm.docs.amd.com/en/docs-7.14.0/about/release-notes.html

TPU v6e

Google Cloud · 2026 · Official documentation

https://cloud.google.com/tpu/docs/v6e

The Trainium Memory Hierarchy

Amazon Web Services · 2026 · Official documentation

https://awsdocs-neuron.readthedocs-hosted.com/en/v2.32.0/nki/get-started/about/memory-hierarchy-overview.html

Accelerated PyTorch training on Mac.

Apple · 2026

https://developer.apple.com/metal/pytorch/

CUDA Programming Guide.

NVIDIA · 2026

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

Introduction to the HIP Programming Model

AMD · 2026 · Official documentation

https://rocm.docs.amd.com/projects/HIP/en/develop/understand/programming_model.html

RCCL Documentation

AMD · 2026 · Official documentation

https://rocm.docs.amd.com/projects/rccl/en/docs-7.2.4/

Writing TPU Kernels with Pallas

JAX Authors · 2026 · Official documentation

https://docs.jax.dev/en/latest/pallas/tpu/details.html

NeuronCore-v3 Architecture

Amazon Web Services · 2026 · Official documentation

https://awsdocs-neuron.readthedocs-hosted.com/en/v2.29.1/about-neuron/arch/neuron-hardware/neuron-core-v3.html

Amazon EC2 Trn2 Architecture

Amazon Web Services · 2026 · Official documentation

https://awsdocs-neuron.readthedocs-hosted.com/en/v2.32.0/about-neuron/arch/neuron-hardware/trn2-arch.html

MPS backend.

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/stable/notes/mps

Metal Performance Shaders Graph

Apple · 2026 · Official documentation

https://developer.apple.com/documentation/metalperformanceshadersgraph

MLX: An array framework for Apple silicon

Apple (ml-explore) · 2026

https://github.com/ml-explore/mlx

MPS Environment Variables.

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/stable/mps_environment_variables.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.