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).
Dispatch and rules
A sharding rule is a function that lists, for one op, the placements its
operands may have and the placement each result gets. With a rule attached, an
op's results on distributed tensors get a known placement. Use this page to give
your own graph op a rule, or to change the rule on an op in max.functional. To
choose whether MAX may move data between devices for an op that already has a
rule, see Steering resharding.
Attach a rule to an opβ
functional(graph_op, rule=rule),
from max.functional, returns a callable that takes
Tensor values and calls graph_op
on them. When any tensor argument is distributed, the wrapper runs these steps:
- Calls its rule with the op's arguments and gets back the placement combinations the op can run with.
- Chooses one combination for each mesh axis.
- Moves each operand whose placement differs from the chosen one.
- Runs
graph_oponce per device, on that device's shard.
To see these steps, wrap ops.relu with a rule that offers one combination,
a replicated operand and a replicated result:
from max import functional as F
from max.graph import ops
from max.tensor.sharding import AxisAssignment, Replicated, TensorLayout
def replicated_relu(x: TensorLayout) -> list[AxisAssignment]:
return [AxisAssignment((Replicated(),), (Replicated(),))]
relu = F.functional(ops.relu, rule=replicated_relu)The wrapper holds both arguments as attributes: relu.graph_op is ops.relu
and relu.rule is the rule. Each call with a distributed argument looks up
rule on the wrapper, so pointing relu.rule at another rule changes the
placements the next call may use and the placements its results take.
A wrapper built without a rule still runs on distributed tensors: graph_op
executes on each device's own shard, and the result's placement is
Unknown, the placement
that claims no relation between the per-device values. No collective can move an
Unknown value, so an op whose rule names no Unknown row, such as relu(),
raises ShardingError on an Unknown operand. When you know how the per-device
values relate,
rebind_mapping(mapping)
returns the same shards under the mapping you supply, without moving data.
rebind_mapping() checks the mapping against the tensor's mesh and nothing
else, so a mapping that doesn't match the shards produces wrong results with no
error.
Most elementwise and matmul ops in max.functional are wrappers built the same
way, and F.relu.graph_op and F.relu.rule hold the two arguments its wrapper
was built with. A few add a second function around the wrapper: the ops that
accept a Python scalar, such as add() and the comparisons, promote the scalar
to a tensor first, and the reductions, such as sum() and max(), translate
axis=None. The outer function carries neither graph_op nor rule, so attach
a rule to one of these ops by building its wrapper with F.functional().
Read the rows a rule returnsβ
A rule reaches the wrapper through F.functional() and takes the op's
signature. Before calling it, the wrapper fills in the op's defaults and
replaces every tensor argument, at any depth, with its
TensorLayout. The
other arguments arrive unchanged. No tensor's data reaches the rule: it works
from the shapes and placements in those layouts.
A rule returns a list of
AxisAssignment
values, called rows. Each row is one way the op could run on a single mesh
axis, and MAX picks one row on each mesh axis. On a mesh with dp and tp
axes, the op can run with one row on dp and another on tp. An
AxisAssignment has two fields, each a tuple:
needed_inputsholds one placement per tensor argument, in the order the op takes them.outputsholds one placement per tensor the op returns, in the order it returns them.
replicated_relu above writes one row: AxisAssignment((Replicated(),), (Replicated(),)), one tensor argument that must be replicated and one result
that comes back replicated.
The picker is the function the wrapper calls to choose one row per mesh axis.
It decides the mesh axes in order, and each axis starts from the placements the
axes before it chose, so the row picked on dp changes what a row costs on
tp. On each axis, it drops the rows that can't run, such as a row that names
Sharded for an operand on a single device. It ranks the rest by the cost of
the moves they need, then by how many operands move. A tie keeps the rule's
order, so the row listed first wins. It takes the first ranked row whose moves
the policy allows, and the wrapper moves each operand to that row's placement.
The policy is the mode and the transitions that auto_reshard() sets, which
Steering resharding covers.
A rule refuses a combination by leaving it out of its rows. The picker raises
ShardingError
before the op runs in cases including these:
- The rule returns an empty list.
- A row's
needed_inputsdoesn't have one placement per tensor argument. - No row can run on some mesh axis.
- The row the picker would take needs a move the policy refuses.
Write a ruleβ
A rule is an ordinary function of layouts, so you can call one yourself and
print the rows it offers before you attach it. Build a layout by hand, print
the row a rule for an add offers, and then wrap ops.add with that rule and
call it on sharded tensors:
from max.driver import CPU
from max.dtype import DType
from max.functional import full
from max.tensor.sharding import (
DeviceMapping,
DeviceMesh,
Sharded,
ShardingError,
auto_reshard,
)
mesh = DeviceMesh(devices=(CPU(), CPU()), mesh_shape=(2,), axis_names=("tp",))
split = DeviceMapping(mesh, (Sharded(1),))
layout = TensorLayout(DType.float32, [4, 8], split)
def replicated_add(
lhs: TensorLayout, rhs: TensorLayout
) -> list[AxisAssignment]:
return [AxisAssignment((Replicated(), Replicated()), (Replicated(),))]
print(replicated_add(layout, layout))
add = F.functional(ops.add, rule=replicated_add)
a = full([4, 8], 1.0, device=split)
b = full([4, 8], 1.0, device=split)
try:
add(a, b)
except ShardingError as error:
print("refused:", str(error).splitlines()[1])
with auto_reshard(mode="silent"):
print("silent:", add(a, b).placements)[AxisAssignment(needed_inputs=(Replicated(), Replicated()), outputs=(Replicated(),))]
refused: add(lhs, rhs) needs a resharding; this region does not reshard automatically
silent: (Replicated(),)The printed list is what every rule returns: one AxisAssignment per row. Its
one row names Replicated() on both operands and a replicated result. a and
b are Sharded(1), so every call of add has to gather both operands first.
Under the default policy, the call raises ShardingError. Inside
auto_reshard(mode="silent"), the wrapper gathers both operands, runs ops.add
on each device, and returns a tensor whose placements are (Replicated(),).
max.tensor.sharding also exports functions that build common rules and rows.
replicated_rows(*args, output_count=1) returns the one row
of an op that runs only on whole tensors: Replicated() for every tensor
operand and every result. replicated_add could return
replicated_rows(lhs, rhs) and print the same list.
match_operand_placement(graph_op, name) returns a whole rule
to pass as rule= when you wrap graph_op. On each mesh axis, that rule's row
names each operand's current placement, so no operand moves, and gives each
result the placement of the tensor argument for parameter name.
Next stepsβ
- Steering resharding: the policy and the report.
- Custom ops: writing a Mojo kernel to call from a model.
AxisAssignment: the row type a rule returns.