Shard flattened parameters across ranks
Why it matters PyTorch FSDP's FlatParameter does exactly this bookkeeping for every wrapped module.
FSDP flattens all parameters into one buffer, pads it to a multiple of the world size and gives each rank an equal slice.
Write shard_flat(shapes, world, rank). shapes is a list of parameter shapes. Total = sum of sizes; padded = ceil(total / world) * world; shard size s = padded // world. Return (start, end, pieces) where [start, end) is this rank's slice of the padded buffer and pieces lists (param_index, offset_in_param, length) for every parameter overlapping the slice, in order. Padding contributes no pieces.
def shard_flat(shapes, world, rank)Example
shapes [(3,), (2,)], world 2, rank 1: total 5, padded 6, s 3, slice [3, 6) holds param 1 elements 0..1, so pieces [(1, 0, 2)].
Understand the idea
FSDP joins all parameters end to end into one flat buffer, pads it so its length divides evenly by the number of ranks, and gives each rank one equal, contiguous slice. A parameter can therefore be split across two ranks. Each rank needs to know which parameter pieces fall in its slice. Worked example: shapes [(2, 2), (3,)], world 3. Sizes are 4 and 3, total 7, padded = ceil(7 / 3) * 3 = 9, shard size 3. Parameter 0 covers flat [0, 4) and parameter 1 covers [4, 7). Rank 1 owns [3, 6): the last element of parameter 0 (offset 3, length 1) and the first two of parameter 1 (offset 0, length 2), so pieces [(0, 3, 1), (1, 0, 2)]. Rank 2 owns [6, 9): one element of parameter 1 at offset 2, then padding, so [(1, 2, 1)]. Rule: s = padded // world; start = rank * s, end = start + s; for each parameter spanning [p0, p1), the overlap is [max(start, p0), min(end, p1)); if it is non-empty, record (index, overlap_start - p0, overlap_length). Offsets are measured from the parameter's start. Used in: PyTorch FSDP and ZeRO sharding.
Shapes and data flow
params [6, 4] -> flat 10 -> padded 12 -> 4 shards of 3 rank 1 = [3, 6): param 0 elements 3..5