For the complete documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /get-started.md).
Steering resharding
A sharded computation can leave a tensor in a placement the next op can't use. A
matmul that contracts over a split axis, for example, leaves each device with
one term of a sum, a
Partial() result, and
relu()'s rule has no row for a partial sum. Before relu() can run, the
operand has to reshard: move to a placement the rule accepts, here by adding
the terms together.
By default, MAX refuses that move and raises
ShardingError.
To let MAX move the operand, run the op inside
auto_reshard().
Its policy sets which moves MAX may make and whether each move runs
silently, warns, or raises. Among the moves the policy allows, MAX takes the
cheapest and runs its collective before the op. On this page, you set the
policy, read the report MAX writes about a move, and make a move yourself with
to().
A reshard keeps the global value and changes how the devices split it.
Unknown shards have no
global value, so a move that involves them raises ShardingError.
Choose a resharding mode
auto_reshard() is a context manager. Its region is every op inside the
with block, and its mode applies to each of them. The region allows a set
of transitions. A transition names a kind of move as a (from, to) pair of
placement types, so (Partial, Replicated) is the allreduce that sums a
partial result. The transitions decide which moves an op may make, and the
mode decides what happens when it makes one. When no row on a mesh axis uses
only allowed transitions, the op raises ShardingError. For an allowed move,
mode sets one of these behaviors:
"silent": MAX moves the operand and emits no message."warn": MAX moves the operand and emits aUserWarningthat names the moved operand, the rule's rows, and thetransfer_to()call that makes the move explicit."raise": the op raisesShardingErrorbefore it runs.
Outside any region, the mode is "raise", and the allowed transitions are
DEFAULT_TRANSITIONS:
the transitions in
ALL_TRANSITIONS
except (Partial, Sharded). An argument you leave out keeps the enclosing
setting, including this default, so auto_reshard(mode="warn") changes the mode
and keeps DEFAULT_TRANSITIONS.
Read a reshard report
A reshard report describes each move an op needs. MAX puts it in the
UserWarning that "warn" emits, in the ShardingError that "raise"
raises, and in the ShardingError an op raises when no row uses only allowed
transitions. To see each mode, run the case from
the top of this page, relu() on a matmul that contracts over a split axis,
once in each mode:
import warnings
from max.driver import CPU
from max.functional import full, matmul, relu
from max.tensor.sharding import (
DeviceMapping,
DeviceMesh,
Sharded,
ShardingError,
auto_reshard,
)
mesh = DeviceMesh(devices=(CPU(), CPU()), mesh_shape=(2,), axis_names=("tp",))
# Contracting over the split axis leaves each device one term of the sum.
a = full([4, 8], 1.0, device=DeviceMapping(mesh, (Sharded(1),)))
b = full([8, 2], 1.0, device=DeviceMapping(mesh, (Sharded(0),)))
with auto_reshard(mode="silent"):
print("silent:", relu(matmul(a, b)).placements)
with warnings.catch_warnings(record=True) as caught, auto_reshard(mode="warn"):
warnings.simplefilter("always")
print("warn:", relu(matmul(a, b)).placements)
print("report:", str(caught[0].message).splitlines()[1])
try:
with auto_reshard(mode="raise"):
relu(matmul(a, b))
except ShardingError as error:
print("raise:", str(error).splitlines()[1])silent: (Replicated(),)
warn: (Replicated(),)
report: relu(x) reshards x
raise: relu(x) needs a resharding; this region does not reshard automaticallyEach device's term of the product holds 4.0 in every cell, and the allreduce
in the "warn" run sums the terms to 8.0:
y.local_shards
Partial()
[0](4, 2)[1](4, 2)Replicated()
[0](4, 2)[1](4, 2)y.to(DeviceMapping(mesh, (Replicated(),)))The report in the warning opens with a line naming the operand that moves, one line per operand layout, and a line for the region. Then it lists the rows the op's rule offered on each mesh axis:
decided per mesh axis
axis x -> out collective bytes status
"tp" x{P->S0} -> S0 reduce_scatter(x) 16 not allowed
x{P->S1} -> S1 reduce_scatter(x) 16 not allowed
x{P->R} -> R allreduce(x) 32 chosen, reshards x
result x{"tp":R} -> {"tp":R}R is Replicated(), P is Partial(), and S0 is Sharded(axis=0). Each
row is one way the rule offered to run the op: the placement the operand would
take, the placement the op would then produce, the collective the transition
implies, the bytes the collective sends as estimated by MAX's ring-collective
cost model, and the row's status. The rows are listed cheapest first. The
picker, the function an op's wrapper calls to choose one row per mesh axis,
takes the cheapest allowed row and marks it chosen. not allowed marks a row
whose transitions the region refuses, and any other row leaves the status empty.
Dispatch and rules
covers how the picker ranks rows.
The report then writes the call that makes the move explicit for each operand
it moves, here x = transfer_to(x, DeviceMapping(mesh, (Replicated(),))), with
transfer_to() imported from max.functional.
Next, the report lists the regions that would accept the move, and its last
line names the call site in your code. Here it also suggests
auto_reshard(ALL_TRANSITIONS, mode="silent"), because the region refused the
cheaper reduce-scatter rows.
Allow every transition with ALL_TRANSITIONS
Reach for ALL_TRANSITIONS when the ops after a contraction have rule rows for
a Sharded input, as relu() and the other elementwise ops do, so the result
can stay split across devices. Leave the default in place when the next op
needs the whole value.
DEFAULT_TRANSITIONS omits the Partial to Sharded move, so a partial sum
resolves to a replicated value by allreduce. Pass ALL_TRANSITIONS to allow
that move, and the result comes back sharded:
from max.tensor.sharding import ALL_TRANSITIONS
with auto_reshard(ALL_TRANSITIONS, mode="silent"):
print(relu(matmul(a, b)).placements)(Sharded(axis=0),)The picker takes the
reduce_scatter()
row because MAX's cost model puts it at 16 bytes against 32 for the allreduce.
reduce_scatter() reduces and splits the partial sum in one step. The
Sharded(axis=0) and Sharded(axis=1) rows cost the same, and the rule lists
Sharded(axis=0) first, so the result takes Sharded(axis=0).
transfer_to() also performs Replicated to Partial: the first device keeps
its copy and the others hold zeros, with no communication. ALL_TRANSITIONS
and DEFAULT_TRANSITIONS leave that step out. To let the picker use it, pass
ALL_TRANSITIONS | {(Replicated, Partial)} to auto_reshard(). Adding a
replicated bias to a Partial() sum then moves the bias to Partial() and
leaves the sum in place, so the add needs no allreduce and its result stays
Partial():
import numpy as np
from max.functional import add
from max.tensor.sharding import Partial, Replicated
product = matmul(a, b)
bias = full([2], 1.0, device=DeviceMapping(mesh, (Replicated(),)))
with auto_reshard(mode="silent"):
allreduced = add(product, bias)
print("default transitions:", allreduced.placements)
with auto_reshard(ALL_TRANSITIONS | {(Replicated, Partial)}, mode="silent"):
biased = add(product, bias)
print("with (Replicated, Partial):", biased.placements)
print("same value:", np.allclose(biased.to_numpy(), allreduced.to_numpy()))default transitions: (Replicated(),)
with (Replicated, Partial): (Partial(),)
same value: TrueAllow different moves on each mesh axis
A mesh with more than one axis can need different allowed transitions on each
axis. On a tensor-parallel axis, you can allow the reduce-scatter, so the result
stays split across that axis's devices. On a data-parallel axis, you can allow
only the allreduce, so every device on that axis holds the whole value. The
axes argument of auto_reshard() sets the allowed transitions for single mesh
axes, by axis name, and allowed_transitions applies to every axis that axes
doesn't name.
Build a 2 x 2 mesh with a dp axis and a tp axis, and split the
contraction axis of a matmul on each, so the product is a partial sum on each
axis. ALL_TRANSITIONS lets relu() reduce-scatter on each axis.
Naming dp in axes limits that axis to the allreduce:
from max.driver import CPU
from max.functional import full, matmul, relu
from max.tensor.sharding import (
ALL_TRANSITIONS,
DeviceMapping,
DeviceMesh,
Partial,
Replicated,
Sharded,
auto_reshard,
)
mesh = DeviceMesh(
devices=tuple(CPU() for _ in range(4)),
mesh_shape=(2, 2),
axis_names=("dp", "tp"),
)
# Both mesh axes split the contraction axis, so the product is a partial sum
# on each of them.
a = full([4, 8], 1.0, device=DeviceMapping(mesh, (Sharded(1), Sharded(1))))
b = full([8, 4], 1.0, device=DeviceMapping(mesh, (Sharded(0), Sharded(0))))
print("product:", matmul(a, b).placements)
with auto_reshard(ALL_TRANSITIONS, mode="silent"):
print("ALL_TRANSITIONS:", relu(matmul(a, b)).placements)
# Any move on tp, but only an allreduce for a partial sum on dp.
with auto_reshard(
ALL_TRANSITIONS, axes={"dp": {(Partial, Replicated)}}, mode="silent"
):
print("dp limited:", relu(matmul(a, b)).placements)product: (Partial(), Partial())
ALL_TRANSITIONS: (Sharded(axis=0), Sharded(axis=0))
dp limited: (Replicated(), Sharded(axis=0))On dp, the allreduce is the only move the region allows for a partial sum, so
the result is Replicated() there. tp keeps ALL_TRANSITIONS and takes the
reduce-scatter, as in the previous section. An inner auto_reshard() block
inherits these per-axis sets unless it names the same axis, and an axis name
the mesh doesn't have is ignored.
Reshard with to()
Use tensor.to(mapping) at a boundary where you know the placement
a value needs: placing weights and inputs before a model runs, or gathering a
sharded result into a replicated one at the end, as the
column and row parallel example does. to() calls transfer_to(),
the same function an op calls to move an operand, so it runs the same
collectives at the point where you call it. It returns the tensor unchanged when
the mapping already matches, and raises when the move would change an Unknown
placement or no supported collective performs it.
In the default "raise" mode, or inside an auto_reshard(mode="raise")
region, an op raises ShardingError whenever an operand would have to move.
An explicit to() before the op turns that expected move into code: the
operand arrives in a placement the op's rule accepts, so nothing has to move
and the op runs.
Next steps
- Dispatch and rules: the rule that offered the rows the report lists.
- Shard a model: choosing placements so each op runs without a reshard.
auto_reshard(): the full signature, includingallowed_transitionsandaxes.