2026年11月9日
长上下文训练——包括预训练和post-training,已成为前沿AI模型的基础。更长的原生序列长度赋予大语言模型(LLMs)工作记忆能力,可阅读整个代码仓库、摄入数小时的视频内容,并完成多步骤agentic任务的推理。三年内,context windows从128K–200K tokens增长至1M–2M,面向10M tokens训练的模式正在到来。在这些长度上进行训练(而不仅仅是推理),是系统瓶颈显现的地方。
具体而言,在数百万token序列长度下的有效训练面临以下瓶颈:
- Attention Compute:在长上下文中,attention FLOPs随序列长度二次方增长,且attention主导训练步骤的开销。吞吐量取决于attention kernel。
- Memory and Communication:activations(包括每个token的keys和values的总用量)随序列长度增长。如果在每个chip上复制这些数据——naive all-gather的做法——会耗尽高带宽内存(HBM),并触发OOM故障。此外,与内存相关的约束会强制引入通信和recompute操作,可能对MFU造成负面影响。此处的解决方案是context parallelism(CP),通过流式传输keys和values而非完整物化它们来解决问题。
今天,我们很高兴宣布在 MaxText 中支持长上下文训练。MaxText 是 Google Cloud 的开源 JAX 训练框架。MaxText 通过在 Cloud TPU 上支持四种上下文并行策略来实现这一功能:All-gather、A2A(DeepSpeed Ulysses)、P2P(Ring Attention)以及 A2A + P2P 混合策略(Unified Sequence Parallelism,简称 USP),并结合负载均衡和序列打包。这四种策略均采用 Tokamax Splash Attention 内核。结合 3D 片间互联(ICI)(在 TPU 5p 或 TPU 7 (Ironwood) 等 TPU 上得到支持),这使得单个序列能够跨越整个切片,同时通信与计算重叠,且每个芯片的显存保持平稳。在我们的基准测试中,Llama 3.1 8B(25 head dim,16 query heads)展现了卓越的长上下文效率,在 TPU 5p 上对高达 400 万 token 的序列长度实现了 70% 的模型浮点运算利用率(MFU)。在 TPU 5p 和 TPU 7 上,上下文均可无缝扩展至 1400 万 token——TPU 7 在低于 600 万 token 的所有序列规模下均能稳定保持 50% MFU。
此功能现已在 MaxText v0.2.4(doc) 中提供。
上下文并行将一个长序列跨芯片拆分,因此没有哪个芯片会持有完整序列的激活值。上下文并行可以与数据并行和张量并行结合使用,而适合你序列且最小的上下文并行尺寸通常是最优选择。对于更稀疏的注意力变体同样适用,它们可以减少注意力计算,但无法减少其他每一层的激活值。
注意力是一种全局操作,每个 token 都需要关注所有前置 token 的 keys 和 values,因此每种上下文并行策略都必须将这些 keys 和 values 聚合回来。每种策略在显存(单个芯片存储多少 KV)、通信量(每层传输多少数据,以及是否与计算重叠)和模型形状(分割多少注意力头)之间做出不同的权衡。
All-gather:每个芯片保留序列的一块分片,并在每一层从其他所有芯片收集 keys 和 values。这是最简单的方案。然而,由于因果掩码导致后续 token 需要关注更大的前缀,All-gather 需要在设备间平衡计算负载。
图1. All-gather,一个序列分布在四个设备(TPU芯片)上。每个设备收集所有的 keys 和 values,然后进行本地注意力计算。轮廓方块标记正在计算的注意力区域;小型轮廓方块表示正在传输的数据。
All-to-All(Ulysses):收集键和值会使每个芯片持有完整序列,因此无论添加多少芯片,注意力内存都不会缩减。All-to-All 改变的是每个芯片所持有的数据维度。注意力在 heads 之间是独立的,但在 tokens 之间并非如此,因此 head 轴可以自由切分,而 token 轴不行。在注意力计算前执行一次 All-to-All,将切分方式从一个轴切换到另一个轴:每个芯片放弃其不负责的 heads,并接收其保留的 heads 所缺失的 tokens,最终在每个 head 上持有完整序列,而非在所有 head 上只持有少量 tokens。这也正是 Ulysses 不需要 token 负载均衡的原因。随后,注意力通过标准内核以普通单芯片注意力的方式运行,第二次 All-to-All 将输出旋转回去。每个芯片的 KV 会随 context-parallel 因子缩减,但你无法在超过模型 head 数量的芯片上进行切分——而 tensor parallelism 切分的也是同一维度,因此 TP × CP 的上限受 head 数量限制(在 GQA 下受 KV heads 限制:Llama 3 8B 为八)。然而,all-to-all 本身无法与计算重叠——由于注意力无法在部分序列上启动,因此在任何芯片开始计算之前,每个芯片都必须等待来自其他所有芯片的数据。
图 2. All-to-All(Ulysses)。all-to-all 用 token 块换取注意力 heads(行)。每个设备为其对应的 head 在整个序列上执行注意力计算,输出再通过第二次 all-to-all 返回。
P2P(环形注意力):Ulysses 的上限是头数;环形注意力通过从不脱离 token 轴来消除这一限制。Keys 和 values 从不完全物化。KV 块沿芯片环逐跳传递,一站一站地移动。每个芯片在下一块传输的过程中,让其查询针对自己持有的块进行注意力计算,并在过程中合并局部结果。每个芯片只持有自己的那块和一块途经的块,永远不会持有完整的序列,通信与计算重叠。然而,将注意力计算拆分为更小的块可能会降低局部 kernel 的效率,并且与 All-to-All Ulysses 不同,环形注意力需要显式的负载平衡。
图3. P2P(环形注意力)。KV 块每次沿环传递一跳。每个设备在处理当前持有的块的同时对到达的下一个块执行注意力计算,且同一时间只持有一块途经块。
A2A + P2P(USP):A2A + P2P(USP):两种策略单独都无法扩展——All-to-All 止步于头数,而长环累加跳跃次数,同时削弱使其有效的工作的重叠。统一序列并行在芯片网格的两个轴上组合它们,因此上下文并行度为两者的乘积:沿着一个轴执行 All-to-All,大小为等于或低于 KV 头数;沿着另一个轴执行环形传播以超越该限制。由于每个 All-to-All 组已经聚合了它们的 token,环形步现在携带的块比 All-to-All 因子大,环相应地更短——每跳有更多计算量来掩盖传输延迟,并减少累积延迟和因果不平衡的跳数。在 Cloud TPU 上,这两个映射到切片芯片网格的两个轴。
图4. A2A + P2P(USP)。All-to-all 在每个设备对内部运行,P2P 环跨这些对运行,因此每个设备以更少的跳跃次数对更长的块执行注意力计算。
这些策略涵盖了当今主流模型中的注意力变体,从多头注意力和分组查询注意力到DeepSeek风格的多头潜在注意力。
只有当每个芯片上的注意力计算保持高效时,序列分割才有意义。这四种策略均在Splash Attention上运行——这是Tokamax推出的、来自Google的TPU内核开源库的块稀疏flash注意力核。它跳过完全被掩码的块,并处理无需填充的紧凑序列。P2P在每个环步中调用一次,作用于本地查询和刚刚到达的KV chunk,而下一步的传输则在底层(前向和后向传播皆然)进行。每个芯片执行相同的融合式块级工作,与无上下文并行时相同,通信被隐藏在其后方。
P2P(Ring Attention)是超长上下文训练的主要主力,而All-Gather则是KV可以容纳时的标准基线。它们是实践中应使用的核心CP策略。我们在一个固定的64芯片TPU 5p切片上,使用Llama 3.1 8B(256头维度,16个查询头)对比了两种策略各自能推进到的上下文长度,并测量其MFU。在理想设置下,即两种策略都能拥有足够大的chunk(S/CP)和本地batch size——这两个是影响TPU 5p上MFU的主要变量——我们观察到:在64K到14M token的几乎整个上下文长度范围内,得益于通过Ring循环传输调度大部分隐藏了通信开销,P2P的表现优于All-Gather。
TPU v7x(Ironwood)沿用了相同的方案并进一步优化。每芯片配备双倍的HBM后,64颗TPU 7芯片上14M token的点对点训练达到了48.7%的模型FLOPS利用率(MFU),而TPU 5p仅为37.1%。我们观察到在TPU 7芯片上,环注意力机制的效果优于其他上下文并行策略——例如Ulysses和USP。
上下文并行策略的选择主要取决于累积的KV缓存是否能装入HBM,以及模型的KV头数量:
- 当累积的KV能放入HBM时:使用带负载均衡的全聚集(All-gather)。其显存随整个序列增长,因此最先耗尽,但在可用时是最简单的选项,在我们的实验中速度最快或接近最快。对于分组查询模型来说,收集操作的成本较低,因为其KV大小仅占激活值的一小部分。
- 对于少量芯片(最多等于KV头数):仅用A2A(全到全)。一次入站全到全加上一次出站全到全,无需环形结构,但不支持多查询注意力。
- 当累积的KV无法放入HBM时:采用环形系列方法,其显存随每个芯片分配的块大小增长而非整个序列长度。我们建议在KV头数允许A2A因子达到2或以上时使用混合模式(USP)。较长的区块和更少的跳数使其在许多场景下比点对点方式更快,并且能与全聚集保持同等性能(在全聚集仍可行的情况下)。序列跨越的芯片越多,这一优势越显著。对于DeepSeek等MLA模型,或当头数无法整除时,点对点方式仍是首选。
对于所有 CP 策略,当内存不足时:在重新计算之前先卸载。MaxText 可以逐张量将被保存的激活值、优化器状态和参数卸载到主机内存。在长上下文长度下,这些传输被计算隐藏,使得卸载实际上相当于免费。首先卸载注意力输出,其次是优化器状态、层输入、参数,最后将 remat 作为最后手段。在整个卸载过程中 MFU 保持稳定,而 all-gather 会下降并最终不再适用。更多细节请参考 remat 调优指南。
展望未来,我们看到两个自然的扩展方向。首先是更广泛的模型覆盖。混合使用滑动窗口层和全局层的模型(如 Gemma)将在相邻芯片之间使用短交换运行窗口层,而全局层则使用 ring。我们还计划支持线性注意力机制,例如 Gated Delta Net (GDN) 和 Kimi Delta Attention (KDA)。第二个方向是性能,通过进一步调优 Tokamax 算子和 P2P 反向传播,缩小与 short context 下 all-gather 之间的差距,并为 TPU 5p 和 7 芯片提供按模型和上下文长度的配方。
上下文并行目前已在 PyPI 上的 MaxText v0.2.4、相应的 Docker 镜像以及 GitHub main 分支上可用。TPU 7 和 TPU 5p 的示例配方可在[此处]获取。通过 `context_parallel_strategy`(ring、ulysses 或 usp)选择一种策略,设置 context-parallel 大小,其余运行配置保持不变即可。分片指南包含了每种策略的标志位和约束条件,版本说明链接到此次工作背后的 pull requests。我们迫不及待想看到你们的训练成果。
本文由 AI图鉴自动抓取并翻译,版权归原作者所有;如需查看原文请点下方链接。
NOV. 9, 2026
Long-context training — including pretraining and post-training, has become a foundation of frontier AI models. Longer native sequence lengths give large language models (LLMs) the working memory to read a whole code repository or ingest hours of video, and reason through multi-step agentic tasks. In three years, context windows have grown from 128K–200K tokens to 1M–2M, and models trained toward 10M tokens are arriving. Training at those lengths, not just serving them, is where the system limits show up.
In particular, efficient training at multi-million-token sequence lengths runs into the following bottlenecks:
- Attention Compute: At long context, attention FLOPs grow quadratically with sequence length and attention dominates the training step. Throughput depends on the attention kernel.
- Memory and Communication: Activations, including the aggregate volume of keys and values for every token, grow with sequence length. Replicating them on every chip, as a naive all-gather does, exhausts high-bandwidth memory (HBM) and triggers out-of-memory failures. In addition, memory-related constraints force communication and recomputation which could negatively impact Model FLOPs Utilization (MFU). The fix here is context parallelism (CP) that streams keys and values instead of materializing them in full.
Today, we are excited to announce long-context training support in MaxText, Google Cloud's open-source JAX training framework. MaxText enables this by supporting four context-parallel strategies on Cloud TPU: All-gather, A2A (DeepSpeed Ulysses), P2P (Ring Attention), and the A2A + P2P hybrid (Unified Sequence Parallelism, or USP), combined with load balancing and sequence packing. All four use the Tokamax Splash Attention kernel. Combined with the 3D inter-chip interconnect (ICI) ( supported on TPUs such as TPU 5p or TPU 7 (Ironwood) ), this lets one sequence span an entire slice while communication overlaps compute and memory per chip stays flat. In our benchmarks, Llama 3.1 8B (25 head dim, 16 query heads) demonstrates exceptional long-context efficiency, achieving 70% Model FLOPs Utilization (MFU) on TPU 5p for sequence lengths up to 4 million tokens. Across both TPU 5p and TPU 7, context can be seamlessly extended to 14 million tokens—with TPU 7 consistently maintaining 50% MFU across all sequence scales below 6 million tokens.
This functionality is available today in MaxText v0.2.4(doc).
Context parallelism splits a long sequence across chips, so no chip holds the activations of the whole sequence. Context parallelism can be combined with data and tensor parallelism, and the smallest context-parallel size that fits your sequence in HBM is usually the right one. This also holds for sparser attention variants which cut attention compute but not the activations of every other layer.
Attention is the one global operation where every token needs the keys and values of every preceding token, so each context parallel strategy has to bring those keys and values back together. Each makes a different tradeoff between memory (how much KV a chip holds), communication (how much moves per layer, and whether it overlaps compute), and model shape (how many attention heads to split).
All-gather: Each chip keeps its chunk of the sequence and, at every layer, gathers the keys and values from every other chip. It is the simplest option. However, because causal masking causes later tokens to attend to larger prefixes, All-gather requires balancing compute load across devices.
Figure 1. All-gather, for one sequence split across four devices (TPU chips). Every device collects all keys and values, then attends locally. Outlined blocks mark attention being computed; small outlined blocks are data in flight.
All-to-All (Ulysses): Gathering keys and values makes every chip hold the whole sequence, so attention memory never shrinks no matter how many chips you add. All-to-All changes what each chip owns instead. Attention is independent across heads but not across tokens, so the head axis is free to shard and the token axis is not. An All-to-All before attention rotates the sharding from one onto the other: each chip gives up the heads it is not responsible for and receives the tokens it was missing for the heads it keeps, ending up with the full sequence for a few heads instead of a few tokens for all heads. This is also why Ulysses does not need token load balancing. Attention then runs as ordinary single-chip attention with standard kernels, and a second All-to-All rotates the output back. KV per chip shrinks by the context-parallel factor, but you cannot split across more chips than the model has heads — and tensor parallelism shards that same dimension, so TP × CP is capped by the head count (under GQA, by the KV heads: eight for Llama 3 8B). The all-to-all itself, though, does not overlap with compute — attention cannot start on a partial sequence, so every chip waits for data from every other chip before any of them begins.
Figure 2. All-to-All (Ulysses). An all-to-all trades token chunks for attention heads (the rows). Each device attends over the full sequence for its head, and the outputs return with a second all-to-all.
P2P (ring attention): Ulysses' ceiling is the head count; ring attention removes it by never leaving the token axis. Keys and values never materialize in full. KV chunks travel around a ring of chips one hop at a time, neighbor to neighbor. Each chip attends its queries to the chunk it holds while the next one is in flight, and merges the partial results as it goes. A chip holds its own chunk and one visiting chunk, never the full sequence, and the communication overlaps compute. However, dividing attention computation into smaller chunks can reduce local kernel efficiency, and unlike All-to-All Ulysses, ring attention requires explicit load balancing.
Figure 3. P2P (ring attention). KV chunks rotate one hop at a time. Each device attends to the chunk it holds while the next one arrives, and holds only one visiting chunk at a time.
A2A + P2P (USP): A2A + P2P (USP): Neither strategy scales on its own — All-to-All stops at the head count, and a long ring accumulates hops while thinning the overlap that makes it work. Unified sequence parallelism composes them on two axes of the chip mesh, so the context-parallel degree becomes the product of the two: All-to-All along one axis, sized at or below the KV-head count, and a ring along the other to extend past it. Because each All-to-All group has already pooled its tokens, a ring step now carries a chunk larger by the All-to-All factor, and the ring is correspondingly shorter — more compute per hop to hide the transfer behind, and fewer hops to accumulate latency and causal imbalance. On Cloud TPU the two map onto two axes of the slice's chip mesh.
Figure 4. A2A + P2P (USP). The all-to-all runs within each pair of devices and the P2P ring across the pairs, so each device attends over longer chunks with fewer hops.
These strategies cover the attention variants in today's major models, from multi-head and grouped-query attention to DeepSeek-style multi-head latent attention.
Splitting the sequence only pays off if the attention compute on each chip stays efficient. All four strategies run on Splash Attention, the block-sparse flash attention kernel from Tokamax, Google's open-source library of TPU kernels. It skips fully masked blocks and handles packed sequences without padding. P2P calls it once per ring step, on the local queries and the KV chunk that has just arrived, while the transfer for the next step runs underneath, in the forward and backward pass alike. Each chip does the same fused, block-level work it would do without context parallelism, with the communication hidden behind it.
P2P (Ring Attention) is the primary workhorse for very long-context training, whereas All-Gather is the standard baseline for most other cases where the KV can fit. These are the primary CP strategies to use in practice. We compare how far each can push context length on a fixed 64-chip TPU 5p slice with Llama 3.1 8B (256 head dim, 16 query heads) , and measure their MFUs. In ideal settings where both strategies can have large enough chunks (S/CP) and local batch size - the two major variables driving MFU on TPU 5p, we observe that P2P can outperform All-Gather almost every context length from 64K to 14M tokens, where communication becomes mostly hidden with the Ring circular transport schedule.
TPU v7x (Ironwood) takes the same recipe further. With twice the HBM per chip, P2P training of 14M tokens on 64 TPU 7 chips reached 48.7% Model FLOPs Utilization (MFU) compared to 37.1% on TPU 5p. We observed that ring attention performs better than other context parallelism strategies -- e.g. Ulysses and USP –- on TPU 7 chips.
The choice of context parallelism strategy depends mostly on whether the gathered KV fits in HBM, and on how many KV heads the model has:
- When the gathered KV fits in HBM: All-gather, with load balancing on. Its memory grows with the whole sequence, so it is the first to run out, but when it fits, it is the simplest option and was the fastest or near fastest in our runs. The gather can be cheap for grouped-query models, whose KV size is a small fraction of the activations.
- On a few chips, up to the number of KV heads: A2A alone. One all-to-all in, one out, no ring; it does not support multi-query attention.
- When the gathered KV no longer fits: The ring family, whose memory grows with each chip's chunk instead of the whole sequence. We recommend the hybrid (USP) whenever the KV heads allow an A2A factor of 2 or more. Its longer chunks and fewer hops can make it faster than P2P in many settings, keeping pace with all-gather for as long as all-gather fit; the more chips a sequence spans, the more this becomes important. P2P alone remains the choice for MLA models such as DeepSeek, or when the head count doesn't divide.
For all CP strategies, when you run low on memory: Offload before you recompute. MaxText can move saved activations, optimizer states, and parameters to host memory tensor by tensor. At long context lengths, these transfers are hidden behind compute, making offloading effectively free. Offload attention outputs first, followed by optimizer states, layer inputs, parameters, and finally remat as a last resort. MFU stays flat through the offload steps while all-gather falls off and eventually stops fitting. For more details, see the remat tuning guide.
Looking ahead, we see two natural extensions. The first is broader model coverage. Models that mix sliding-window and global layers, such as Gemma, would run the window layers with a short exchange between neighboring chips while the global layers use the ring. We also plan to support linear attention mechanisms such as Gated Delta Net (GDN) and Kimi Delta Attention (KDA). The second is performance, with further tuning of the Tokamax kernels and the P2P backward pass to narrow the remaining gap to all-gather at short context, and recipes by model and context length for TPU 5p and 7 chips.
Context parallelism is available today in MaxText v0.2.4 on PyPI, the corresponding Docker images and on GitHub main. Sample recipes are available here for TPU 7 and TPU 5p. Pick a strategy with context_parallel_strategy (ring, ulysses, or usp), set the context-parallel size, and keep the rest of your run the same. The sharding guide has the flags and constraints for each strategy, and the release notes link to the pull requests behind this work. We can't wait to see what you train.
Auto-fetched and translated by AI Atlas. All rights belong to the original author.