advanced27 min studyLesson 553 in Engineering

Attention head partitions: keep each head’s dependencies intact

Track query and key/value head ownership, grouped-query constraints, and the output projection reduction.

On this page

What you’ll understand

  • Derive local query-head and key/value-head counts for an even partition.
  • Explain why GQA can require a different KV placement than Q.
  • Connect concatenated head outputs to a row-parallel output projection.

Multi-head attention exposes independent per-head computations once the required queries, keys, values, and masks are available. That makes head partitioning useful, but the heads are not interchangeable tensor chunks. Grouped-query attention gives several query heads a shared key/value head, so ownership must preserve that grouping. The output projection then mixes head features and needs the correct sum or layout transition. We use explicit counts rather than assume every head count divides every parallel degree.

Partition whole head computations when possible

For ordinary multi-head attention, each head compares its queries with the permitted keys, normalizes scores over those keys, and combines the corresponding values. Different heads can be evaluated on different tensor-parallel ranks while retaining their full head-dimension calculations. The attention scaling uses the key/query head dimension, not the number of devices. Position encodings and masks must use the same global token positions as the reference. A rank owning only some heads does not justify ignoring keys from other token positions.

Projecting hidden states into Q, K, and V can be organized with output-feature partitions aligned to head boundaries. Each rank then holds its head outputs as a feature shard. A compatible output projection partitions its input rows along those concatenated head features and sums partial contributions to the final hidden output. A gather of all head outputs is one possible implementation boundary, but it is not universally necessary before that row-parallel projection.

Attn⁡h(Qh,Kh,Vh)=softmax⁡ ⁣(QhKhTdh+M)Vh\operatorname{Attn}_h(Q_h,K_h,V_h)=\operatorname{softmax}\!\left(\frac{Q_hK_h^{\mathsf T}}{\sqrt{d_h}}+M\right)V_h
Q_h is S_q×d_h, K_h is S_k×d_h, V_h is S_k×d_v, and M is a compatible mask of dimensionless score offsets. Softmax is over permitted keys for each query. This describes a head mathematically, not a communication schedule.↔ Scroll wide equations horizontally.

Grouped-query head counts constrain the layout

With H_q query heads and H_kv key/value heads, a regular GQA layout groups H_q/H_kv query heads per KV head when that ratio is integral. A simple even partition over P ranks can assign H_q/P query heads and H_kv/P KV heads per rank only when the counts and grouping support it. If P exceeds the KV-head count, an implementation may replicate KV heads or use another supported arrangement. Dividing to obtain half a head is not a valid execution plan.

Replicated KV changes memory and gradient bookkeeping. Its storage is not reduced by the same factor as evenly sharded query features, and contributions to shared parameters must be combined across the actual replica groups. Multi-query attention, with one KV head, makes this difference especially visible. Frameworks impose configuration constraints that can be stricter than the mathematical possibility. Check the selected version’s supported head mapping rather than claiming that every GQA configuration supports an arbitrary tensor-parallel size.

Hq,local=Hq/P,Hkv,local=Hkv/P,g=Hq/HkvH_{q,\rm local}=H_q/P,\qquad H_{kv,\rm local}=H_{kv}/P,\qquad g=H_q/H_{kv}
These local counts apply only to an evenly divisible, grouping-compatible sharded-head layout. H values and g count heads; if a quotient is nonintegral or KV is replicated, this formula is not the placement used.↔ Scroll wide equations horizontally.

Compare the correct global head order

Test each head with distinguishable inputs so an accidental permutation cannot hide behind identical values. Preserve the mapping from global query heads to their KV group, then reconstruct or project the output in the documented order. Compare forward attention, output projection, and gradients to shared KV parameters. Include a causal mask and a nontrivial sequence length; a single-token test cannot reveal a missing-key or future-token visibility bug. Disable dropout initially before testing the intended random-stream mapping.

The matrix lab illustrates an inspectable map without implementing attention. Reset, set a=1 and b=0, predict the identity transform and determinant 1, then Step. This exposes what an unchanged coordinate map means; head reordering in the worked layout must likewise preserve its declared correspondence. The triangular 2D family cannot represent arbitrary head permutations, attention scores, GQA sharing, or distributed projection. Use the explicit head-count and global-ID table to establish the actual partition.

Four query heads per rank, one KV head per rank

A model has Hq=8 query heads, Hkv=2 KV heads, query/key head dimension 4, and tensor-parallel size P=2. Use an even grouping-compatible head split.

  1. Each KV head serves 8/2=4 query heads. Rank 0 can own query heads 0–3 with KV head 0, and rank 1 query heads 4–7 with KV head 1.

  2. Each rank owns four query heads, so its query projection output width is 4×4=16 features per token. Its key projection width is 1×4=4, and a matching value head of dimension 4 also has width 4.

  3. If P changes to 4, Hkv/P=0.5 is invalid for this simple split. A supported replicated-KV or other layout is needed, with its own storage and gradient rules. The existing even-KV-shard formula cannot simply be reused.

The result

Head grouping determines which tensors can be local. A query-head partition does not automatically imply the same KV sharding factor.

Explore the model

Interactive lab

Interactive lab · matrix

Preserve a declared coordinate correspondence

Reset, set a=1 and b=0, predict the identity transform, then Step. This 2D triangular family does not model attention, head permutations, GQA sharing, or projection collectives. Use it only to inspect an explicit map while tracing head IDs separately.

Preserve a declared coordinate correspondenceThe selected matrix is A = [[a,b],[0,1]]. Playback interpolates geometry between the identity and A; readouts always describe A. Its determinant is a and its singular values come from AᵀA. Positive a makes every supported matrix invertible. This two-dimensional family is not a general eigensolver or a learned network. Current readings: Area scale · det A: 1.4; Singular values · σmax, σmin: 1.597, 0.876; Condition number · κ₂(A): 1.823. All parameters are adjustable with the labeled controls below.Matrix A with first row 1.4, 0.6 and second row zero, one; display interpolates between identity and A while final determinant remains 1.4.−4−2024−2−1012x · equal geometric scaleyA = [ 1.4 0.6 ; 0 1 ]Display blend: 0% · final values below
Interpolated geometryOriginal unit squareSelected final transform
Area scale · det A
1.4
Singular values · σmax, σmin
1.597, 0.876
Condition number · κ₂(A)
1.823
t = 0 s

The selected matrix is A = [[a,b],[0,1]]. Playback interpolates geometry between the identity and A; readouts always describe A. Its determinant is a and its singular values come from AᵀA. Positive a makes every supported matrix invertible. This two-dimensional family is not a general eigensolver or a learned network. 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 forA partition must preserve which global feature or head each local value represents.

Check your understanding

A GQA model has one KV head and eight query heads. Four ranks each own two query heads. What can you conclude about KV placement?

Try it yourself

Hq=12, Hkv=4, P=2, with grouping-compatible even splits and head dimension 8. Compute local query heads, local KV heads, group size, and local Q width.

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

Give me a hint

Divide head counts by ranks and keep query-per-KV grouping separate.

Compare with the solution

Each rank has six query heads and two KV heads. Each KV head serves three query heads globally, and local Q width is 6×8=48 features per token. The K width is 2×8=16. These counts assume the stated supported mapping, not arbitrary framework support for every configuration.

Take it with you

  • Attention heads can be partitioned only with their required Q/K/V dependencies.
  • GQA sharing can make KV placement differ from query-head placement.
  • The output projection and shared-parameter gradients must preserve global head identity.

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.