2026年11月16日
Google 从零开始设计 TPU,使其在机器学习工作负载中具备极高的效率,在总拥有成本(TCO)方面提供顶级性能。由于 TPU 用通用硬件调度换取了宽脉动阵列、专用 SparseCore 引擎和定制互连网络,遵循特定的架构最佳实践对于实现最大性能至关重要。为帮助开发者充分利用 TPU,我们发布了开源的 AI-Hypercomputer/tpu-codesign 指南。本文重点介绍了其核心原则——涵盖形状对齐、架构选择(如 LatentMoE)以及并行化策略——以加速 TPU 上的 LLMs、Mixture-of-Experts (MoE) 模型及其他硬件密集型工作负载。
性能调优始于模型定义。在第一个训练步骤之前做出的架构选择,将为 MFU (Model FLOP Utilization)、成本和服务延迟设定永久性上限。本指南为构建或适配 TPU 模型的团队提供了具体的、基于硬件的设计规则,分为三组:
- 形状规则(原则 1–2):硬件对齐的维度和静态形状;模型质量风险接近零。始终采用。
- 架构选择(原则 3–7):结构性设计选择;大多数涉及质量权衡。通过消融实验验证。
- 并行化表达(原则 8):并行化、内核和编译器调优;无需修改模型。
如何使用本指南。形状规则适用于任何设计新模型的人。如果你是在适配现有模型而非从头设计,则"表达并行性"部分适用,且无需修改 checkpoint。通用规则适用于任何大规模矩阵乘法架构(稠密 LLM、多模态和世界模型),配套的 AI-Hypercomputer/tpu-codesign 仓库将随时间推移增加面向特定模型和工作负载的章节。
第八代 TPU。这些原则延续至 TPU 8t 和 TPU 8i,以及新发布的 TPU 8tx 和 TPU 8i Max。推理逻辑不变,但阈值随硬件变化。TPU 8t 和 TPU 8i 均新增原生 FP4 支持。在训练方面,TPU 8t 还带来了更均衡的向量处理单元(VPU)扩展。在推理服务方面,TPU 8i 新增了 Boardfly 拓扑结构、集合通信加速引擎(CAE),以及 3 倍于前代的片上 SRAM。我们在原则 5–8 中以行内注释标明了相关影响,后续文章将深入介绍第八代设计。
实测证据。除已公开的资料外,标记为 Measured 的注释包含来自我们自身 Ironwood 性能剖析项目的结果:开源 20–30B MoE 模型(基于 Qwen3-30B 衍生的 LatentMoE 变体;GPT-OSS-20B)以及稠密对照模型,单 slice 配置(原则 4 中 512-chip TPU v7x 和 1,024-chip TPU v4 的消融实验除外),BF16 精度,训练序列长度最大至 32K,均以经过调优的系统为基线。请将其中的趋势和排名视为可迁移的结论,而将具体百分比视为与配置相关的结果。
TPUs 是专为定制的 ML ASIC,从底层架构设计出发,旨在以总拥有成本(TCO)为基准实现最优的前沿性能。虽然其架构设计——例如宽 256×256 脉动阵列、软件管理的 VMEM、专用 SparseCore 引擎以及直接多维 ICI 互连网络——带来了出色的效率,但它们也内在地产生了一系列特定的结构约束和编程模式,必须严格遵守才能释放最大性能。要达到峰值效率,需要将模型形状、路由和并行策略与这些底层硬件特性直接对齐:
并行方式缩写:DP = 数据并行,TP = 张量并行,EP = 专家并行,CP = 上下文并行,PP = 流水线并行;FSDP = 全分片数据并行。
将 d_model、FFN 及专家中间宽度(d_ff)、潜在宽度、注意力投影和填充后的词表大小(用作收缩维度或输出维度)设置为 256 的倍数,以匹配 256×256 MXU 脉动阵列。词元/批次轴以及头数、层数和专家数等计数不受此限制。最容易被忽略的维度是 head_dim:在 64 或 128 时,flash-attention 的 QK 乘积会导致 MXU 空闲率 ≥ 50%。将 head_dim 重塑为 256,并等比例减少 Q 和 KV 头数,保持总投影宽度和逻辑 KV 缓存字节数不变(在我们的消融实验中质量等价)。
实测:将 Qwen3-30B MoE 的注意力从 32 × 128 重塑为 16 × 256(参数和 FLOPs 完全相同)加速了端到端训练,且在更长上下文时收益进一步扩大:
这些规则同样适用于非二次复杂度注意力。值得注意的是,Yang et al. 2025 中关于 GDN 的消融实验也指出,其 Gated DeltaNet Attention 在头维度为 256 时质量持平或更优。
XLA 为每种精确的张量形状编译每个程序,因此每个缓冲区都有固定地址,每个循环都有已知的迭代次数,而新形状意味着重新编译和主机停顿。那动态形状呢?动态工作负载契合这一模型:关键在于将缓冲区的形状与其内部数据的长度分离开来。
- 分桶与掩码:在程序层面,将请求填充到一小组预编译的序列长度和批处理槽位桶中(在服务器启动时预热),用掩码替代数据依赖分支,并对训练序列进行打包(MaxText 中 packing=True),使填充永远不会到达 MXU。
- 标量预取:动态形状的另一种常见模式出现在无丢弃 MoE 层中,每个步骤将不同数量的令牌路由到每个专家;也出现在分页注意力中,其中每个序列拥有自己的 KV 长度、自己的一组散布在缓存中的页,以及在混合批次中自己的阶段(预填充或解码)。
与其填充到最大组或最长序列,我们保持缓冲区为固定形状(按专家排序的令牌仅在末尾填充,KV 缓存作为固定页池),并用几个小型整数数组(组大小和偏移量;KV 长度、页表、累积查询长度)来描述不规则结构。Pallas 在网格启动前将这些数据复制到 TensorCore 的标量内存中(PrefetchScalarGridSpec),内核读取它们来选择下一个图块并限定其循环,用掩码覆盖跨越组边界或仅部分填充的最后一页的图块。数据依赖变成了地址和迭代次数而非形状,因此编译后的程序对每种路由和每种批次组合都相同,内核以未填充的 FLOP 数运行。
标准 EP 以完整的 d_model 宽度分发每个路由 token,使其在 Ironwood 基准测试中,EP + FSDP 比纯 FSDP 更慢。LatentMoE 在分发之前将路由 token 从 d_model 投影到潜在宽度 ℓ(d/ℓ ≈ 2–4×),在潜在空间中执行专家,并在 combine 之后投影回原维度(由 Nemotron 3 引入,并被 962B MAI-Base-1 和 2.8T Kimi K3 采用):
- 同时缩减 MoE 的两个瓶颈并重新投入:当专家宽度 m = d_ff 时,潜在压缩将小批量专家权重读取(∝ d × m)和吞吐受限的 all-to-all 分发(∝ K × d)削减了 d/ℓ。将节省的带宽重新投入更多活跃专家中,同时保持 K_new × ℓ ≤ K_old × d_model,从而在恒定流量下提高非线性预算 K × m(例如,Nemotron 3 的 ℓ = 1024、N = 512、top-22 在匹配的活跃与总参数量下优于 d = 4096、N = 128、top-6)。
- TPU 规则:在压缩前先按完整 d_model 路由;保持 ℓ 为 256 的倍数;分发使用 FP8,同时保持轻量级上/下投影使用 BF16;并将 EP 放置在一条短 3D torus 轴上。
实测:在一个 30B / 128-expert MoE 上,ℓ = 768(2.67×)的 LatentMoE 将设备端 permute 时间缩短 2.8 倍,端到端训练吞吐量提升 +14% tokens/s(322 vs 270 TFLOP/s/chip,或 +19%,因为潜在投影每 token 增加约 5% FLOPs;token 在下投影之后保持 ℓ 宽度,因此设备端 permute 和 combine 随 EP all-to-all 一同缩减),当 remat 检查点锚定在压缩潜在空间时,释放了约 25 GB/device 的激活 HBM。虽然当前 tpu-recipes 中的 MoE 方案运行 FSDP(+ TP),但当每设备批大小不足以隐藏 FSDP 权重 all-gathers 时,LatentMoE + FP8 分发使 EP roofline 可行。在 FSDP 和 EP 下,避免过度碎片化专家:小 token × K / N 的组大小会使 MXU tile 得不到充分利用。
当候选 MoE 布局在质量上相当时,选择计算强度更高、活跃参数预算相近的那一个。更大的共享专家(更宽的 d_shared)会将计算转移到无通信开销的稠密 GEMM 中,使其在训练期间与 EP dispatch/combine 重叠,并跨解码批次摊薄权重读取。更少、更宽的路由专家(在固定稀疏度 K/N 下将 N 和 K 减半,同时将 d_ff 加倍)可将 dispatch 流量减半,并使单专家 GEMM 填充率翻倍。最优 (N, K) 随模型规模增大而增大,过度粗化则会损害路由多样性。应在目标规模上对专家粒度和共享/路由划分比例进行消融实验,而非照搬 GPU 协同设计模型,因为 TPU 的最优解更偏向共享专家。
实测:在 63B LatentMoE(ℓ = 768,K/N = 1/32,8K context,512 片 TPU v7x 芯片,EP = 128)上,将 (N, K) 从 (512, 16) 减半至 (256, 8),同时加倍 d_ff 和共享专家,训练吞吐量提升 +57% tok/s,且在 120.8B tokens 上保持更低损失:
低并发解码流每个 token 都需流式传输模型权重(稠密 FP8 下,每个权重分片约需 300 个并发 token 才能触及计算屋顶线)。将两项架构调节手段与显式并发规模设定相结合:
- 5.1 低直径横向扩展:在高连通性、低直径拓扑(例如 TPU 8i 上的 Boardfly)上进行解码扩展,可聚合多芯片 HBM 带宽,同时将集合通信延迟控制在足够低的水平,使其在延迟敏感场景下优于单芯片带宽扩展。TPU 8i 将 Boardfly 与集合加速引擎(Collectives Acceleration Engine,CAE)搭配使用,该引擎替代了 Ironwood 的四个 SparseCore,将片上集合通信延迟最多降低 5 倍。同时,片上 SRAM 容量提升至三倍,使更多 KV 缓存保留在芯片上。TPU 8i Max 使每封装的计算能力、SRAM 和 HBM 带宽均翻倍。以下容量规划规则仍适用于各系统自身的 HBM 参数。
- 5.2 设计时投机解码(MTP):以 BF16 保留的多 token 预测(MTP)头可提供更密集的训练信号,并内置一个草稿生成器,将每次权重读取的开销分摊到多个已验证 token 上(DeepSeek-V3 85–90% 接受率;Qwen3-Next;GLM-4.5;Nemotron 3 +2.4% 基准提升及约 97% 双 token 接受率)。在目标并发度下,测量投机解码完整的草稿生成、验证与回滚周期中的净提交 token/s。
- 按实际服务并发量和 MoE batch 占用来设计规模:每个 token 的解码延迟下界由每芯片权重字节数 ÷ HBM 带宽决定(例如,当 batch 触及所有专家时,Qwen3.5-397B 以 FP8 分布在 4 个芯片上,每芯片需流式传输 ~100 GB/chip,在 KV 读取之前设定了 ~13.5 ms 的权重读取下限),而最大 batch 受限于(剩余 HBM)÷(每条序列分配的 KV/state)。对于 MoE,权重流量随 batch 中触及的专家并集而增长(在均匀路由下为 E × [1 - (1 - K/E)^B]);分析最繁忙 rank 的偏斜度,当 HBM 允许时 replicate 热门专家(DeepSeek-V3)。如果实际并发量较小,应设计更少的激活字节数(更少的激活参数或更小的模型),而非围绕一个你根本不会用到的 batch 规模来规划。
归一化、激活函数、掩码、路由数学运算和量化 scale 应用均在 Vector Processing Unit (VPU) 上执行,其吞吐量比 MXU 低约两个数量级,且与矩阵乘法顺序执行,除非 XLA 将其融合到相邻的 GEMM 中,或将其移出 TensorCore。因此我们丢弃不影响质量的 reshape 和转置操作,统一使用可融合的 RMSNorm 和 SwiGLU,使逐元素运算折叠进相邻的 GEMM,并将 MoE 的 sort、gather 和 scatter 卸载到 SparseCore。
注意,融合的 VPU 工作只有在其周期数能容纳在所融合的 MXU 窗口内时才不产生额外开销。block-scaled fp8 GEMM 是这一概念的简要示例。
当沿收缩轴每 B 个元素一个 scale 时,MXU 输出
本文由 AI图鉴自动抓取并翻译,版权归原作者所有;如需查看原文请点下方链接。
NOV. 16, 2026
Google designed TPUs from the ground up to be exceptionally efficient for machine learning workloads, delivering top-tier performance per total cost of ownership (TCO). Because TPUs trade general-purpose hardware scheduling for wide systolic arrays, dedicated SparseCore engines, and custom interconnect fabrics, adhering to specific architectural best practices is essential to achieve maximum performance. To help developers get the most out of TPUs, we are launching the open-source AI-Hypercomputer/tpu-codesign guide. This post highlights its key principles—spanning shape alignment, architectural choices like LatentMoE, and parallelism strategies—to accelerate LLMs, Mixture-of-Experts (MoE) models, and other hardware-intensive workloads on TPUs.
Performance tuning starts with model definition. Architectural choices made before the first training step set permanent ceilings on MFU (Model FLOP Utilization), cost, and serving latency. This guide gives concrete, hardware-grounded design rules for teams building or adapting models for TPUs, organized into three groups:
- Shape rules (Principles 1–2): hardware-aligned dimensions and static shapes; near-zero model-quality risk. Adopt always.
- Architecture choices (Principles 3–7): structural design choices; most involve quality tradeoffs. Validate with ablations.
- Expressing parallelism (Principle 8): parallelism, kernel, and compiler tuning; no model changes required.
How to use this guide. The shape rules apply to anyone designing a new model. If you are adapting an existing model rather than designing one, the Expressing Parallelism section applies without touching the checkpoint. The general rules hold for any large-matmul architecture (dense LLMs, multimodal, and world models), and the companion AI-Hypercomputer/tpu-codesign repository grows model- and workload-specific sections over time.
Eighth-generation TPUs. These principles carry forward to TPU 8t and TPU 8i and to the newly announced TPU 8tx and TPU 8i Max. The reasoning stays the same and the thresholds move with the hardware. TPU 8t and TPU 8i both add native FP4. For training, TPU 8t also brings more balanced Vector Processing Unit (VPU) scaling. For serving, TPU 8i adds the Boardfly topology, a Collectives Acceleration Engine (CAE), and 3x more on-chip SRAM. We note the effects inline in Principles 5–8, and follow-up posts will cover eighth-generation designs in depth.
Measured evidence. Alongside the published sources, notes marked Measured carry results from our own Ironwood profiling program: open 20–30B MoEs (a Qwen3-30B-derived LatentMoE variant; GPT-OSS-20B) plus dense controls, single slice (except for the 512-chip TPU v7x and 1,024-chip TPU v4 ablations in Principle 4), BF16, training shapes up to 32K sequence, all against tuned-systems baselines. Treat the trends and rankings as transferable, the exact percentages as config-specific.
TPUs are purpose-built custom ML ASICs designed from the ground up to deliver state-of-the-art performance per total cost of ownership (TCO). While their architectural choices—such as wide 256×256 systolic arrays, software-managed VMEM, dedicated SparseCore engines, and direct multi-dimensional ICI fabrics—enable exceptional efficiency, they inherently create specific structural constraints and programming patterns that must be carefully followed to unlock maximal performance. Reaching peak efficiency requires aligning model shapes, routing, and parallelism directly with these underlying hardware characteristics:
Parallelism shorthand: DP = data, TP = tensor, EP = expert, CP = context, PP = pipeline parallelism; FSDP = fully sharded data parallel.
Make d_model, FFN and expert intermediate widths (d_ff), latent widths, attention projections, and padded vocabulary sizes (used as contracting or output dimensions) multiples of 256 to match the 256×256 MXU systolic array. Token/batch axes and counts such as heads, layers, and experts are exempt. The most frequently missed dimension is head_dim: at 64 or 128, flash-attention QK products leave the MXU ≥ 50% idle. Reshape to head_dim = 256 with proportionally fewer Q and KV heads, preserving total projection widths and logical KV cache bytes (iso-quality in our ablations).
Measured: Reshaping Qwen3-30B MoE attention from 32 × 128 to 16 × 256 (identical parameters and FLOPs) sped up end-to-end training, with gains widening at longer context:
These rules apply for non-quadratic attention as well, notably GDN ablations from Yang et al. 2025 also noted at par or better quality for head dimension 256 for their Gated DeltaNet Attention.
XLA compiles each program for exact tensor shapes, so every buffer has a fixed address and every loop a known trip count, and a new shape means a recompilation and a host stall. What about dynamic shapes? Dynamic workloads fit this model: the trick is to separate the shape of a buffer from the extent of the data inside it.
- Bucketing and masking: At the program level, pad requests to a small set of precompiled sequence-length and batch-slot buckets (warmed up at server startup), replace data-dependent branches with masks, and pack training sequences (packing=True in MaxText) so padding never reaches the MXU.
- Scalar Prefetch: Another common pattern of dynamic shapes appears in dropless MoE layers, which route a different number of tokens to each expert every step, and in paged attention, which gives every sequence its own KV length, its own set of pages scattered through the cache, and in a mixed batch its own phase (prefill or decode).
Instead of padding to the largest group or the longest sequence, we keep the buffers at fixed shapes (tokens sorted by expert and padded only at the tail, the KV cache as a fixed pool of pages) and describe the ragged structure with a few small integer arrays (group sizes and offsets; KV lengths, the page table, cumulative query lengths). Pallas copies these into the TensorCore's scalar memory before the grid starts (PrefetchScalarGridSpec), and the kernel reads them to choose the next tile and bound its loops, with a mask covering a tile that straddles a group boundary or a partly filled last page. The data dependence becomes an address and a trip count instead of a shape, so the compiled program is the same for every routing and every batch composition and the kernel runs at the unpadded FLOP count.
Standard EP dispatches every routed token at full d_model width, making EP + FSDP slower than plain FSDP in our Ironwood benchmarks. LatentMoE projects routed tokens from d_model down to latent width ℓ (d/ℓ ≈ 2–4×) before dispatch, executes experts in latent space, and projects back up after combine (introduced by Nemotron 3 and adopted by 962B MAI-Base-1 and 2.8T Kimi K3):
- Shrink both MoE bottlenecks and reinvest: With expert width m = d_ff, latent compression cuts small-batch expert weight reads (∝ d × m) and throughput-bound all-to-all dispatch (∝ K × d) by d/ℓ. Reinvest the saved bandwidth into more active experts while keeping K_new × ℓ ≤ K_old × d_model, raising the nonlinearity budget K × m at constant traffic (for example, Nemotron 3's ℓ = 1024, N = 512, top-22 beat d = 4096, N = 128, top-6 at matched active and total parameters).
- TPU rules: Route on full d_model before compressing; keep ℓ a multiple of 256; dispatch in FP8 while keeping lightweight up/down projections in BF16; and place EP on one short 3D torus axis.
Measured: On a 30B / 128-expert MoE, an ℓ = 768 (2.67×) LatentMoE cut on-device permute time 2.8×, lifted end-to-end training throughput +14% tokens/s (322 vs 270 TFLOP/s/chip, or +19%, since the latent projections add ~5% FLOPs per token; tokens stay ℓ-wide past the down-projection, so on-device permute and combine shrink alongside EP all-to-all), and freed ~25 GB/device of activation HBM when remat checkpoints were anchored on the compressed latent. While current MoE recipes in tpu-recipes run FSDP (+ TP), LatentMoE + FP8 dispatch makes EP roofline-viable when per-device batch is too small to hide FSDP weight all-gathers. Under both FSDP and EP, avoid over-fragmenting experts: small tokens × K / N group sizes starve MXU tiles.
When candidate MoE layouts match on quality, pick the one with higher compute intensity at a similar active-parameter budget. A larger shared expert (wider d_shared) shifts work into dense, communication-free GEMMs that overlap EP dispatch/combine in training and amortize weight reads across the decode batch. Fewer, wider routed experts (halving N and K while doubling d_ff at fixed sparsity K/N) cut dispatch traffic in half and double per-expert GEMM fill. Optimal (N, K) grows with model size, and over-coarsening hurts routing diversity. Ablate expert granularity and the shared-to-routed split at your target scale rather than copying GPU co-designed models, since the TPU optimum is more shared-heavy.
Measured: On a 63B LatentMoE (ℓ = 768, K/N = 1/32, 8K context, 512 TPU v7x chips at EP = 128), halving (N, K) from (512, 16) to (256, 8) while doubling d_ff and the shared expert lifted training throughput +57% tok/s and held lower loss across 120.8B tokens:
Low-concurrency decode streams model weights every token (~300 concurrent tokens per weight shard are needed in dense FP8 to reach compute roofline). Combine two architectural levers with explicit concurrency sizing:
- 5.1 Low-diameter scale-out: Scaling decode across high-connectivity, low-diameter topologies (such as Boardfly on TPU 8i) aggregates multi-chip HBM bandwidth while keeping collective latency low enough to beat single-chip bandwidth scaling in latency-sensitive regimes.TPU 8i pairs Boardfly with a Collectives Acceleration Engine (CAE), which replaces Ironwood's four SparseCores and cuts on-chip collective latency by up to 5x. It also triples on-chip SRAM, which keeps more of the KV cache on silicon. TPU 8i Max doubles compute, SRAM, and HBM bandwidth per package. The sizing rule below still applies with each system's own HBM numbers.
- 5.2 Design-time speculative decoding (MTP): Multi-token prediction (MTP) heads kept in BF16 provide a denser training signal and a built-in drafter that amortizes each weight read across multiple verified tokens (DeepSeek-V3 85–90% acceptance; Qwen3-Next; GLM-4.5; Nemotron 3 +2.4% benchmark gain and ~97% two-token acceptance). Measure net committed tokens/s across the full draft, verify, and rollback cycle of speculative decoding at target concurrency.
- Size to real serving concurrency and MoE batch occupancy: Per-token decode latency is bounded below by per-chip weight bytes ÷ HBM bandwidth (for example, when the batch touches all experts, Qwen3.5-397B in FP8 across 4 chips streams ~100 GB/chip, setting a ~13.5 ms weight-read floor before KV), while max batch is capped by (remaining HBM) ÷ (allocated KV/state per sequence). For MoEs, weight traffic scales with the union of experts touched across the batch (E × [1 - (1 - K/E)^B] under uniform routing); profile busiest-rank skew and replicate hot experts (DeepSeek-V3) when HBM permits. If real concurrency will be small, design fewer active bytes (fewer active parameters or a smaller model) rather than planning around a batch size you will not have.
Norms, activations, masking, routing math and quantization scale applies run on the Vector Processing Unit (VPU), which is roughly two orders of magnitude below the MXU in throughput and executes in sequence with the matmuls unless XLA fuses it into an adjacent GEMM or we move it off the TensorCore. Therefore we drop reshapes and transposes that carry no quality, standardize on fusable RMSNorm and SwiGLU so the elementwise work folds into the neighbouring GEMM, and offload the MoE sort, gather and scatter to the SparseCore.
Note that fused VPU work is free only while its cycle count fits inside the MXU window it is fused into. A quick illustration of this concept is block-scaled fp8 GEMM.
With a scale per block of B elements along the contraction axis, the MXU emits on
Auto-fetched and translated by AI Atlas. All rights belong to the original author.