advanced27 min studyLesson 554 in Engineering

Sequence-parallel normalization: shard tokens, retain their hidden features

Explain why tokenwise LayerNorm stays local under sequence sharding and why its replicated parameter gradients still combine.

On this page

What you’ll understand

  • Identify the axis over which LayerNorm computes statistics.
  • Distinguish sequence-sharded full-hidden activations from hidden-feature shards.
  • Compute global parameter gradients from token-shard contributions.

Sequence parallelism in the Megatron activation-saving design distributes token activations for operations such as LayerNorm and dropout that can act independently per token. It does not redefine LayerNorm to normalize over the sequence. Each local token still needs its complete normalized hidden dimension under this layout. This differs from context parallel attention, which must exchange information across token positions. The distinction prevents a shape-correct implementation from changing the model’s normalization function.

Normalize each token over the specified feature axes

For a token with H hidden coordinates, LayerNorm computes mean and variance over those coordinates, then applies learned per-feature scale and bias. If a rank owns whole token rows, it has the needed statistics locally. Splitting the sequence into token chunks therefore does not require a global reduction of means across different tokens. Combining token means would normalize a different object. RMSNorm has its own statistic and should not be silently substituted for LayerNorm in an equivalence test.

A hidden-feature-sharded token is different: no rank has the whole normalized axis, so a correct implementation needs the appropriate distributed statistics or a redistribution. Merely naming a tensor sequence-parallel does not establish its actual axes. Write the global shape, local shape, and placement at each boundary. With batch, sequence, and hidden dimensions, library defaults about which axis is sequence must match the program’s convention; a transpose can keep element counts unchanged while moving the wrong axis.

μt=1H∑hxth,vt=1H∑h(xth−μt)2,yth=γhxth−μtvt+ϵ+βh\mu_t=\frac1H\sum_h x_{th},\quad v_t=\frac1H\sum_h(x_{th}-\mu_t)^2,\quad y_{th}=\gamma_h\frac{x_{th}-\mu_t}{\sqrt{v_t+\epsilon}}+\beta_h
t labels a token, h a hidden coordinate, and H is the full normalized feature count. x, γ, β, and ε follow the layer’s numeric convention; ε must have variance-compatible units. Statistics are per token, not across t.↔ Scroll wide equations horizontally.

Replicated weights do not mean identical gradient contributions

LayerNorm scale and bias parameters are typically replicated across sequence-sharded ranks in this design. Each rank’s local tokens contribute different parameter gradients, so those contributions must be summed over the relevant group before the intended optimizer update. Whether a framework performs this in a particular mapping or gradient-finalization phase is an implementation boundary. Do not independently update replicated parameters from different local token gradients and expect them to remain equal. Loss averaging must be applied once according to the global valid-token convention.

Sequence-sharded activations can be gathered when a tensor-parallel linear layer needs more input tokens, and complete output contributions can be reduce-scattered back into token shards. Such transitions explain activation-memory savings without treating every layer as permanently sequence-sharded. Dropout adds a random-number mapping requirement: matching a seed on every rank can accidentally repeat masks rather than reproduce the intended global mask. Start equivalence checks without dropout, then test an explicit consistent global randomness policy.

dγh=∑r∑t∈Trdythx^th,dβh=∑r∑t∈Trdythd\gamma_h=\sum_r\sum_{t\in T_r}dy_{th}\widehat{x}_{th},\qquad d\beta_h=\sum_r\sum_{t\in T_r}dy_{th}
T_r are disjoint token partitions and x-hat is the token’s normalized value. These are sums for the stated upstream dy; any mean-loss scaling is already reflected in dy or must be applied consistently once.↔ Scroll wide equations horizontally.

Check padding and normalization conventions

A token that is padding may still pass through a normalization kernel, but its contribution to the training objective must follow the defined masking rule. Shard sizes that do not divide the sequence require a supported uneven or padded layout and correct global token identities. PyTorch 2.8 marks some uneven DTensor sharding behavior experimental, so do not assume every module supports it automatically. Verify ε, variance convention, dtype, learned parameters, and custom parameter initialization when comparing replicated normalization modules.

The function lab can illustrate sensitivity in one fixed map only. Reset, set a=1 and x=1, predict y=1 and tangent slope 2, then Step. Change x to 0.5 to predict y=0.25 and slope 1. This is not LayerNorm, a variance calculation, or a sequence-parallel kernel. It reminds you to name which input coordinates a statistic depends on; the lesson’s formula and token-by-token example supply the actual normalization semantics.

Two token owners share normalization parameters

Rank 0 owns token [1,3] and rank 1 owns [2,6], with H=2, γ=[1,1], β=[0,0]. For exact toy arithmetic take ε=0; both variances are positive. Their upstream gradients are [1,2] and [3,4].

  1. Token 0 has mean 2 and variance 1, so its normalized vector is[−1,1]. Token 1 has mean 4 and variance 4, giving the same normalized vector[−1,1]. No statistic was averaged across the two tokens.

  2. Rank 0 contributes dγ=[−1,2] and dβ=[1,2]. Rank 1 contributes dγ=[−3,4] and dβ=[3,4], using its own upstream gradient.

  3. Sum contributions for the shared parameters: dγ=[−4,6] and dβ=[4,6]. A real layer normally uses its configured positive ε, so a numerical reference must use the same ε rather than expect these simplified values unchanged.

The result

Forward normalization is local to a complete token row, while shared parameter gradients combine token contributions across owners.

Explore the model

Interactive lab

Interactive lab · function

Name the coordinates a computation depends on

Reset, set a=1 and x=1, predict y=1 and slope 2, then Step. Set x=0.5 to predict y=0.25 and slope 1. This quadratic does not implement LayerNorm, RMSNorm, statistics, or sequence sharding.

Name the coordinates a computation depends onThis lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forCorrect local computation depends on owning the full axis required by its actual formula.

Check your understanding

A token’s hidden vector is split across two ranks. Can each normalize its half independently and claim ordinary full-hidden LayerNorm equivalence?

Try it yourself

Two token shards contribute dβ vectors [2,1] and [5,3] to one replicated LayerNorm bias under a sum loss. What is the full gradient? If one shard has twice as many valid tokens, should local mean losses simply be averaged?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Sum the declared contributions; distinguish a sum from a valid-token weighted global mean.

Compare with the solution

The sum gradient is[7,4]. For a global mean with unequal valid-token counts, equal averaging of local means generally gives the wrong weighting. Combine appropriately scaled sums and divide by the total valid-token count, matching the reference objective and framework reduction semantics.

Take it with you

  • Sequence sharding can retain full hidden vectors for tokenwise normalization.
  • Hidden-axis sharding requires a different statistic or layout transition.
  • Replicated normalization parameters need correctly combined and scaled gradients.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.