Skip to content
mlmentorship

Sharded matrix multiplication

Predict which collective communication a distributed matrix multiplication needs from its sharded axes.

Published · 9 min read ·Role-specific ·Advanced

Visual quick review

See why sharding both non-contracting output axes over the same two-device mesh axis computes only C[0,0] and C[1,1], and why an input must be gathered or resharded before the missing cross-index blocks can be formed.

Gather an input before computing the missing cross-index blocks

Gather an input before computing the missing cross-index blocksA is [[1,2],[3,4]] and B is [[5,6],[7,8]]. Each rank retains one A row. Gathering both B columns enables complete output rows: retain diagonal 19 and 50, compute previously absent 22 and 43. Adding diagonal outputs alone cannot create them.Keep A rows; gather B columns beforedot productsR0: A row 0R1: A row 11234B column 0B column 15768Gather both BcolumnsA0 reads fullBA1 reads fullB1922435022 and 43 are new cross-products
A is [[1,2],[3,4]] and B is [[5,6],[7,8]]. Each rank retains one A row. Gathering both B columns enables complete output rows: retain diagonal 19 and 50, compute previously absent 22 and 43. Adding diagonal outputs alone cannot create them.
Full explanation 9 min read

Summary

A sharded matrix multiplication splits matrix data across devices. The required communication follows from which matrix axes are split and which axis is summed during the multiplication.

Why AI labs care

Transformer training is mostly matrix multiplication. Data, tensor, fully sharded, context, and expert parallelism all change where matrix pieces live.

A useful systems skill is predicting:

  • which local multiplication each device can perform;
  • whether the result is complete or only a partial sum;
  • which collective communication completes the operation;
  • how much data moves;
  • whether compute can hide that communication.

Global and local shapes

Suppose:

is the contracting axis because it appears in both inputs and is summed away. and are output axes.

A global shape describes the full matrix. A local shape describes the piece held by one device.

If is split across four devices, each device holds about one quarter of the rows of and .

A simple sharding notation

Write when the axis is split across device-mesh axis .

Examples:

  • : replicated on ;
  • : rows split across ;
  • : columns split across .

The notation is framework-neutral. A device mesh is only a named grid of devices.

Case 1: the contracting axis is not split

Each device has all values needed for its output block. It performs a local matrix multiplication. No communication is needed if this output layout is acceptable.

Communication may still be needed if the next operation requires a different layout.

Case 2: one input is split on the contracting axis

One device has only part of the values from .

Two common choices are:

  1. All-gather along , then perform the full local multiplication.
  2. Multiply local pieces, then reduce the partial outputs.

Choose by comparing the bytes in the gathered input with the bytes in the output reduction. The next operation’s required layout also affects the choice.

Case 3: both inputs share the split contracting axis

Each device can multiply matching local pieces. Its result is only a partial sum over .

Finish with:

  • all-reduce if every device needs the full output;
  • reduce-scatter if the output should remain split.

Keeping the output split often saves memory and avoids a later reshard.

Case 4: two output axes use the same mesh axis

This output layout is invalid. One mesh axis cannot independently select both output axes. The devices would hold only diagonal blocks of the full output.

With two devices, device 0 would compute the first row block with the first column block, while device 1 would compute the second row block with the second column block. No device computes the two off-diagonal blocks.

Adding diagonal blocks cannot create cross-block products that were never computed

Diagonal products cannot manufacture the missing cross-block termsComputing A0B0 and A1B1 omits A0B1 and A1B0. Adding the two available blocks cannot reconstruct terms that were never computed.Four block slots require fourcomputed productsA0B0computedA0B1missingA1B0missingA1B1computedAdding diagonal results does not fillthe empty slots.
Read it this way: Computing A0B0 and A1B1 omits A0B1 and A1B0. Adding the two available blocks cannot reconstruct terms that were never computed. Can adding the two diagonal products create A0B1?
Reference drawing

Adding diagonal blocks cannot create cross-block products that were never computed

Diagonal products cannot manufacture the missing cross-block termsComputing A0B0 and A1B1 omits A0B1 and A1B0. Adding the two available blocks cannot reconstruct terms that were never computed.Four block slots require fourcomputed productsA0B0computedA0B1missingA1B0missingA1B1computedAdding diagonal results does not fillthe empty slots.
Derivation
A reduction cannot invent the two products that no device computedIn a declared two-by-two toy, A has rows one-two and three-four, and B has columns five-seven and six-eight. Device zero initially owns only A row zero and B column zero, producing nineteen. Device one owns only A row one and B column one, producing fifty. The same-scale output grid leaves off-diagonal cells uncomputed, not zero. All-gather of B columns gives each device the missing input. New local dot products produce twenty-two and forty-three; a second grid fills those exact gaps while retaining nineteen and fifty.Toy 2x2 matrices; each output block is onenumberD0 ownsA row 0 [1,2]B col 0 [5,7]D1 ownsA row 1 [3,4]B col 1 [6,8]LOCAL WORK: TWO MISSING PRODUCTScol 0col 1r019D0?not computedr1?not computed50D1NEW PAIRS: ALL FOUR PRODUCTS EXISTcol 0col 1r019D022D0r143D150D1ALL-REDUCE ADDS; IT CANNOT CREATE THE ? CELLSREPAIR: GATHER B, THEN MULTIPLYD0 gains [6,8]; D1 gains [5,7].D0: [1,2] dot [6,8] = 6 + 16 = 22D1: [3,4] dot [5,7] = 15 + 28 = 43Gather inputs first. New multiplication, notreduction, fills the gaps.
Compare the same output positions before and after the gather. The new input pairs produce 22 and 43; the existing 19 and 50 do not change. All-reduce alone cannot manufacture the absent cross-index multiplications.
Check: Why can reducing the two computed diagonal blocks not create C0,1 or C1,0?
Read it this way: Computing A0B0 and A1B1 omits A0B1 and A1B0. Adding the two available blocks cannot reconstruct terms that were never computed. Can adding the two diagonal products create A0B1?

All-gather or reshard one input before multiplying. Pick the smaller movement or the layout needed by the next operation.

Collective operations

CollectiveLayout change
All-gatherremove a split and replicate the full axis
Reduce-scattersum partial values and keep a chosen output axis split
All-reducesum partial values and replicate the result
All-to-allmove a split from one tensor axis to another

All-reduce can often be implemented as reduce-scatter followed by all-gather.

For large messages, a first communication estimate is:

For small messages, fixed launch and hop latency also matters.

Backpropagation

The backward pass uses more matrix multiplications:

Apply the same sharding rules to these operations.

An all-gather in the forward computation often corresponds to a reduce-scatter for its gradient. This is why fully sharded training naturally pairs those two collectives.

Overlap communication with compute

A blocking all-gather moves all data before any multiplication begins. A collective matrix multiplication moves one block while computing another block.

Overlap helps when:

  • the multiplication has enough independent work;
  • blocks are large enough for efficient compute and communication;
  • dependencies allow a pipeline;
  • the implementation and hardware can run both at once.

Always compare with a simple blocking baseline. More complex overlap code is useful only when measured time improves.

Small example

A transformer feed-forward projection uses activations and weights .

If is split across devices in both and , each device produces a partial output. Use all-reduce for a replicated output or reduce-scatter to keep split.

If only is split, each device processes different tokens with replicated weights. The forward multiplication needs no communication. Gradients must be combined later.

In an interview

Use this order:

  1. Name input, contracting, and output axes.
  2. State global and local shapes.
  3. Mark each split on the device mesh.
  4. Decide whether local outputs are complete or partial.
  5. Select all-gather, reduce-scatter, all-reduce, or all-to-all.
  6. Estimate bytes and effective bandwidth.
  7. Check the layout required by the next operation.
  8. Discuss overlap only after the blocking plan is correct.

Common mistakes

  • Looking only at tensor size and not at the contracting axis.
  • Treating a partial sum as a complete result.
  • Replicating an output that could remain split.
  • Assigning one mesh axis to two output axes.
  • Ignoring the next operation’s layout.
  • Counting aggregate cluster bandwidth instead of the limiting link.
  • Assuming communication always overlaps with compute.

Related: all-reduce and other collectives, tensor parallelism, and FSDP and ZeRO. Further practice: sharded matrices in the JAX Scaling Book.