KatInterview

Tensor-Parallel Linear Layer: Forward, Backward, and Collectives

Machine LearningModel answer
MediumModel answerMachine Learningtensor-parallelismbackpropagationdistributed-training

Last updated

Work out the forward and backward passes of a linear layer whose weight columns are split across devices, pinpoint the required collective, and design tests for sharding bugs.

A bias-free linear layer computes Y = X @ W, where X is (B, D) and W is (D, H). The layer is trained with tensor parallelism on P devices. H is divisible by P, and the weight matrix is split along its output columns: device p holds W_p of shape (D, H/P). Every device starts with the complete X, and during the backward pass device p receives only its own slice dY_p of the upstream gradient, with shape (B, H/P).

Your task

  1. Derive the forward computation. State the local tensor shape for every expression, and say how (or whether) the full Y is assembled.
  2. Derive the backward formulas for dW and dX from the differential of the loss.
  3. Name each collective needed so that the full dX ends up replicated on all devices while dW stays column-sharded. Explain why each is required and what it costs in communication volume.
  4. Write NumPy-style pseudocode for one device's forward and backward step, treating collectives as abstract calls such as all_gather and all_reduce.
  5. Describe a debugging plan covering shape errors, numerical errors, and collective mistakes.
  6. Briefly discuss, without implementing it, how things change if X or the contraction dimension D is sharded instead.

Assumptions

  • Plain dense matmul, no bias.
  • Devices run synchronously with identical floating-point dtype.
  • Local matmul is available, and collectives are treated as black-box primitives.
  • The scalar loss provides dY with the same logical shape as Y.

Points worth clarifying up front

  • Which tensors must be replicated and which sharded after each phase?
  • Are you optimizing for communication volume, peak memory, or latency?
  • Are gradients also averaged across data-parallel replicas?
  • What reference implementation and tolerances exist for testing?

Hints

Hint 1

Annotate every expression with its local shape. For example, `X @ W_p` is `(B, D) @ (D, H/P) = (B, H/P)`.

Hint 2

Start from `dL = <dY, dX_in @ W + X @ dW_in>` and read off the gradients. Then ask which of them involves a sum over the sharded dimension `H`.

Hint 3

`dX = dY @ W^T = sum_p dY_p @ W_p^T`. Each device can only compute one term of that sum, so think about which collective combines them.

Hint 4

Check the implementation by simulating `P` devices in one process on tiny shapes and comparing against the unsharded computation.