From 82a75e68855f6943a8185c1ab888ed6912bf3198 Mon Sep 17 00:00:00 2001 From: NuojCheng Date: Thu, 26 Nov 2026 20:09:18 +0000 Subject: [PATCH] Add experimental MPMD pipeline parallelism on Shardy MPMD and Pathways Add src/maxtext/experimental/mpmd/partir/: pipeline parallelism in which every stage is its own XLA program on its own mesh. One training step, traced from MaxText's embedding, decoder layers and output head, is partitioned by Shardy MPMD (OSS PartIR:MPMD) into an IFRT IR program -- a fragment per stage, microbatch and pass plus the cross-mesh transfers, in the schedule's order (1F1B, GPipe, ZB-H1, ZB-H2, ...) -- which Pathways runs as one execute per step. Schedules: 1F1B (default), GPipe, and the zero-bubble ZB-H1 and ZB-H2, for which Shardy splits each backward fragment into its input- and weight-gradient halves; the last stage merges its forward with the input-gradient half. Entry points: train, train_compile, parity (MPMD against one SPMD program), spmd_baseline (MaxText's own pipeline at the same tokens per step) and launch (gcluster or xpk Pathways jobs); local_pathways.sh runs Pathways in docker on a TPU VM. Decoder blocks: simple_mlp, llama2, mistral, mixtral, qwen3, qwen3_moe and deepseek (with mHC). shardy-mpmd is an optional dependency, pinned to the Shardy commit of the installed jaxlib; the tests that need it skip without it. The package README covers setup, Pathways images, results and limitations. --- src/maxtext/experimental/mpmd/__init__.py | 15 + .../experimental/mpmd/partir/README.md | 262 +++ .../experimental/mpmd/partir/__init__.py | 15 + .../experimental/mpmd/partir/benchmark.py | 408 ++++ .../experimental/mpmd/partir/config.py | 331 +++ .../experimental/mpmd/partir/hparams.py | 1015 +++++++++ .../experimental/mpmd/partir/launch.py | 506 +++++ .../mpmd/partir/local_pathways.sh | 146 ++ .../experimental/mpmd/partir/mesh_utils.py | 700 +++++++ .../experimental/mpmd/partir/models.py | 1821 +++++++++++++++++ .../experimental/mpmd/partir/parity.py | 765 +++++++ .../experimental/mpmd/partir/pipeline.py | 520 +++++ .../experimental/mpmd/partir/runner.py | 380 ++++ .../mpmd/partir/sdy_mpmd_compat.py | 66 + .../mpmd/partir/sdy_mpmd_versions.py | 105 + .../experimental/mpmd/partir/spmd_baseline.py | 645 ++++++ src/maxtext/experimental/mpmd/partir/train.py | 400 ++++ .../experimental/mpmd/partir/train_compile.py | 394 ++++ .../experimental/mpmd/partir/train_step.py | 326 +++ tests/unit/mpmd_test/benchmark_test.py | 147 ++ tests/unit/mpmd_test/config_test.py | 160 ++ .../mpmd_test/documented_commands_test.py | 132 ++ tests/unit/mpmd_test/hparams_test.py | 223 ++ tests/unit/mpmd_test/launch_test.py | 319 +++ tests/unit/mpmd_test/local_pathways_test.py | 125 ++ tests/unit/mpmd_test/mesh_utils_test.py | 161 ++ tests/unit/mpmd_test/models_test.py | 506 +++++ tests/unit/mpmd_test/parity_test.py | 313 +++ tests/unit/mpmd_test/pathways_train_test.py | 71 + tests/unit/mpmd_test/pipeline_test.py | 416 ++++ tests/unit/mpmd_test/sdy_mpmd_compat_test.py | 78 + .../unit/mpmd_test/sdy_mpmd_versions_test.py | 77 + tests/unit/mpmd_test/spmd_baseline_test.py | 477 +++++ tests/unit/mpmd_test/train_test.py | 163 ++ 34 files changed, 12188 insertions(+) create mode 100644 src/maxtext/experimental/mpmd/__init__.py create mode 100644 src/maxtext/experimental/mpmd/partir/README.md create mode 100644 src/maxtext/experimental/mpmd/partir/__init__.py create mode 100644 src/maxtext/experimental/mpmd/partir/benchmark.py create mode 100644 src/maxtext/experimental/mpmd/partir/config.py create mode 100644 src/maxtext/experimental/mpmd/partir/hparams.py create mode 100644 src/maxtext/experimental/mpmd/partir/launch.py create mode 100755 src/maxtext/experimental/mpmd/partir/local_pathways.sh create mode 100644 src/maxtext/experimental/mpmd/partir/mesh_utils.py create mode 100644 src/maxtext/experimental/mpmd/partir/models.py create mode 100644 src/maxtext/experimental/mpmd/partir/parity.py create mode 100644 src/maxtext/experimental/mpmd/partir/pipeline.py create mode 100644 src/maxtext/experimental/mpmd/partir/runner.py create mode 100644 src/maxtext/experimental/mpmd/partir/sdy_mpmd_compat.py create mode 100644 src/maxtext/experimental/mpmd/partir/sdy_mpmd_versions.py create mode 100644 src/maxtext/experimental/mpmd/partir/spmd_baseline.py create mode 100644 src/maxtext/experimental/mpmd/partir/train.py create mode 100644 src/maxtext/experimental/mpmd/partir/train_compile.py create mode 100644 src/maxtext/experimental/mpmd/partir/train_step.py create mode 100644 tests/unit/mpmd_test/benchmark_test.py create mode 100644 tests/unit/mpmd_test/config_test.py create mode 100644 tests/unit/mpmd_test/documented_commands_test.py create mode 100644 tests/unit/mpmd_test/hparams_test.py create mode 100644 tests/unit/mpmd_test/launch_test.py create mode 100644 tests/unit/mpmd_test/local_pathways_test.py create mode 100644 tests/unit/mpmd_test/mesh_utils_test.py create mode 100644 tests/unit/mpmd_test/models_test.py create mode 100644 tests/unit/mpmd_test/parity_test.py create mode 100644 tests/unit/mpmd_test/pathways_train_test.py create mode 100644 tests/unit/mpmd_test/pipeline_test.py create mode 100644 tests/unit/mpmd_test/sdy_mpmd_compat_test.py create mode 100644 tests/unit/mpmd_test/sdy_mpmd_versions_test.py create mode 100644 tests/unit/mpmd_test/spmd_baseline_test.py create mode 100644 tests/unit/mpmd_test/train_test.py diff --git a/src/maxtext/experimental/mpmd/__init__.py b/src/maxtext/experimental/mpmd/__init__.py new file mode 100644 index 0000000000..3ebc99996f --- /dev/null +++ b/src/maxtext/experimental/mpmd/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""MPMD (multiple program, multiple data) pipeline parallelism, experimental.""" diff --git a/src/maxtext/experimental/mpmd/partir/README.md b/src/maxtext/experimental/mpmd/partir/README.md new file mode 100644 index 0000000000..7eb813666f --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/README.md @@ -0,0 +1,262 @@ + + +# MPMD pipeline parallelism on Shardy MPMD and Pathways (experimental) + +Pipeline parallelism in which every stage is its own XLA program on its own mesh. One training step, traced from +MaxText's embedding, decoder layers and output head, is partitioned by +[Shardy MPMD](https://github.com/openxla/shardy/tree/main/shardy/integrations/python/jax/mpmd) (OSS PartIR:MPMD) into +an IFRT IR program: a fragment per stage, microbatch and pass, plus the cross-mesh transfers, in the order of the +pipeline schedule (1F1B, GPipe, ZB-H1, ZB-H2, ...). Pathways runs it, one execute per step. The program compiles only +through Pathways' IFRT proxy; a CPU host lowers it without a TPU. **Status: experimental.** + +## Environment + +| Component | Tested with | Note | +|---|---|---| +| MaxText | `c034bc02f` (2026-11-25) | the 2026-11 results below were measured on `4b5b24c92` (2026-11-24); the October table states its own | +| Python | 3.12 | | +| jax, jaxlib | 0.12.0.1 | pin both: the Shardy MPMD frontend must match jaxlib (next table) | +| libtpu | 0.0.51, MaxText's minimum, from the install below; 0.0.50.1 also run, with the same losses | not loaded by a Pathways client (`JAX_PLATFORMS=proxy`) or on CPU: the Pathways servers compile | +| pathwaysutils | 0.1.14 | MaxText's minimum, from the install below | +| shardy-mpmd (Shardy MPMD's frontend) | Shardy `38ab99f4` | on neither PyPI nor the jax wheels; installed below | +| Pathways server and proxy images | `20261117-jax_0.12.0.1` | builds from 2026-11-18 on reject jaxlib 0.12.0.1's IFRT IR ("Failed to parse IFRT IR module string"); plain `jax.jit` runs on them too | +| GKE launcher | xpk | or a gcluster built from cluster-toolkit's `develop`: see [GKE](#pathways-on-gke) | + +| jaxlib | Shardy commit (`sdy_mpmd_versions.SHARDY_COMMITS`) | Run | +|---|---|---| +| 0.12.0.1 | `38ab99f4d252c59d491899a694fe8cbadfeccec3` | everything here from November 2026 | +| 0.12.1 | `57fffc23dfdf139b80013ad681701cee59c22f96` | not run | +| 0.11.1 | `2832731619ffb4bcc718faa4aa8054214a68c969` | the October results' implementation; MaxText now needs jax 0.12.0.1 or newer | + +Install MaxText from source as its [install guide](../../../../../docs/install_maxtext.md#from-source) describes, pin +jax, and add the frontend from the installed jaxlib's Shardy commit, without dependencies (`sdy_mpmd_compat.py` warns +when pip recorded another commit): + +```bash +uv pip install -e .[tpu] --resolution=lowest && install_tpu_pre_train_extra_deps +uv pip install jax==0.12.0.1 jaxlib==0.12.0.1 +uv pip install --no-deps "shardy-mpmd @ git+https://github.com/openxla/shardy@38ab99f4d252c59d491899a694fe8cbadfeccec3#subdirectory=shardy/integrations/python/jax/mpmd" +``` + +### Pathways in docker on a TPU VM + +[`local_pathways.sh`](local_pathways.sh) runs the resource manager, one worker (the VM's chips) and the IFRT proxy from +the public images `us-docker.pkg.dev/cloud-tpu-v2-images/pathways/{server,proxy_server}`, as a GKE Pathways job's pods +run them. It needs docker and a `gs://` scratch location the VM's service account can write. `--instance_type` is +`tpu7x:2x2x1` on a TPU7x VM with 4 chips (`tpu7x-8`), `tpuv6e:2x2` on a v6e-4; `--tag` picks the images; +`--xla_flags_file` (one `--key=value` a line) gives XLA / libtpu flags to all three servers. The worker holds the TPU +until `down`; it exits whenever a client disconnects and restarts, so each new client waits about 10 s. + +### Pathways on GKE + +Create a Pathways cluster and install Cluster Toolkit (`gcluster`) as MaxText's +[Pathways guide](../../../../../docs/run_maxtext/run_maxtext_via_pathways.md) describes, and build an image with this +MaxText tree ([Build MaxText](../../../../../docs/tutorials/build_maxtext.md)) and the `shardy-mpmd` install above. +[`launch.py`](launch.py) checks the decoder block, the stages and slices, the workload name and the microbatch split, +and prints `gcluster job config set` and `gcluster job submit --pathways`, whose head pod runs the entry point +(`--submit` runs them; `--launcher=xpk` prints `xpk workload create-pathways`). + +- **gcluster v1.108.0 and v1.109.0 rerun a finished Pathways job and end it `Failed`, and no release has the fix yet** + (v1.109.0 is the newest on 2026-11-26). They give the workers `restartPolicy: Never`, and a worker exits when its + client disconnects: when the entry point ends, even successfully, the JobSet restarts and runs it a second time. The + fix, cluster-toolkit [PR #6739](https://github.com/GoogleCloudPlatform/cluster-toolkit/pull/6739), was merged into + `develop` on 2026-11-25: use a gcluster built from `develop`, or `--launcher=xpk`. The launcher logs this warning. +- `--xla_flags_file` and `--extra_xla_flags=key=value` go to the proxy, which compiles the TPU programs, and to the + resource manager and the workers (gcluster's `--pathways-{proxy,server,worker}-args`, xpk's + `--custom-pathways-{proxy-server,server,worker}-args`). +- `--pathways_tag` (default `20261117-jax_0.12.0.1`) must match the image's jax. `--module=parity` or + `--module=train_compile` run the other entry points; arguments after `--` go to the entry point. + +## Quick start + +```bash +# CPU only: lower one step on 8 fake devices and write /tmp/pp4.{stablehlo,mpmd,ifrt}.mlir. +JAX_PLATFORMS=cpu python3 -m maxtext.experimental.mpmd.partir.train_compile --pp=4 --num_microbatches=4 \ + --per_device_batch_size=4 --model_name=deepseek3-tiny --pipeline_schedule=1F1B --ir_dump_path=/tmp/pp4 + +# A TPU VM: train, check MPMD against one SPMD program, and log each compiled fragment's memory and cost. +bash src/maxtext/experimental/mpmd/partir/local_pathways.sh up --gcs_scratch_location=gs:///pathways \ + --instance_type=tpu7x:2x2x1 +export JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000 +python3 -m maxtext.experimental.mpmd.partir.train --pp=4 --num_microbatches=4 --per_device_batch_size=4 \ + --model_name=simple +python3 -m maxtext.experimental.mpmd.partir.parity --pp=4 --num_microbatches=4 --per_device_batch_size=4 \ + --model_name=simple --steps=3 --maxtext_overrides=dtype=float32 +python3 -m maxtext.experimental.mpmd.partir.train_compile --compile_topology=local --pp=4 --num_microbatches=4 \ + --per_device_batch_size=4 --model_name=deepseek3-tiny +bash src/maxtext/experimental/mpmd/partir/local_pathways.sh down + +# GKE, 2 x tpu7x-4x4x4: the llama3.1-8b PP=4 run of the results. Prints the xpk command; --submit runs it. +python3 -m maxtext.experimental.mpmd.partir.launch --cluster= --project= --zone= \ + --docker_image= --pathways_gcs_location=gs:///pathways --device_type=tpu7x-4x4x4 --num_slices=2 \ + --workload=mpmd-llama-pp4 --pp=4 --num_microbatches=4 --per_device_batch_size=4 --model_name=llama3.1-8b \ + --max_target_length=1024 --learning_rate=1e-5 --warmup_steps=10 --steps=20 --launcher=xpk +# The same model and tokens a step on MaxText's own SPMD pipeline: prints its settings and trainer command. +python3 -m maxtext.experimental.mpmd.partir.spmd_baseline --device_type=tpu7x-4x4x4 --num_slices=2 --pp=4 \ + --num_microbatches=4 --per_device_batch_size=4 --model_name=llama3.1-8b --max_target_length=1024 --learning_rate=1e-5 +``` + +`train` logs one `MPMD_RESULT {json}` line (`--result_json` writes it), stops with exit 1 at a NaN loss, and traces +with `--enable_profile --profile_dir=gs://...`. Each stage's devices run FSDP unless `--fsdp` and `--expert` say +otherwise. `spmd_baseline` also prints pure FSDP (`--pure_fsdp`) and, with `--cluster`, the job. Decoder blocks: +`simple_mlp` (`--model_name=simple`), `llama2`, `mistral`, `mixtral`, `qwen3`, `qwen3_moe`, `deepseek` (e.g. +llama3.1-8b, mistral-7b, mixtral-8x7b, qwen3-8b, qwen3-30b-a3b, deepseek2-16b, deepseek3-tiny; qwen3-235b-a22b with +`--maxtext_overrides=load_balance_loss_weight=0`). `--num_layers` defaults to 8 for every model; named models keep +their dimensions, while `simple` and deepseek3-tiny take `--emb_dim`, `--mlp_dim` and `--vocab_size` (512, 2048, +16384). + +## Schedules + +`--pipeline_schedule` is `1F1B` by default, or `GPipe`, `GPipeBut1F1BForLastMesh`, or a zero-bubble schedule +([Qi et al.](https://arxiv.org/abs/2401.10241)): `ZB-H1`, or `ZB-H2` (`ZB-H2-ZERO`; `ZB-H2-HALF` and `ZB-H2-FULL` +assume a transfer takes half or all of a stage's compute, and start more forwards early). For the zero-bubble +schedules the port sets Shardy's `mpmd_split_bwd_fragments`: each backward fragment that sends an activation gradient +upstream becomes B_a, which computes that gradient, and B_w, which computes the weight gradients and runs where the +stage would otherwise wait. The first stage's backward stays whole (it sends nothing upstream); the last stage runs +B_a merged with its forward, as 1F1B's last stage runs the whole backward; MaxText's MoE layers compute the routed +experts' weight gradients in B_a. ZB-H1 runs as many forwards ahead as 1F1B and also holds B_w's inputs until B_w +runs; ZB-H2 runs up to 2(P - s) - 1 forwards ahead on stage s (1F1B: P - s) to also fill the warm-up, 1.75 times +1F1B's activations on the first of 4 stages. `train_compile --ir_dump_path` shows the fragments; `pipeline_test.py` +checks the split and how many forwards each zero-bubble schedule runs ahead. + +## Benchmark results + +jax 0.12.0.1, Shardy `38ab99f4`, Pathways `20261117-jax_0.12.0.1`, synthetic data, 1F1B, 4 microbatches, +`--per_device_batch_size=4`, FSDP over each stage; median step time of the timed steps; measured on 2026-11-25. The +quick-start commands reran on 2026-11-26, on MaxText `4b5b24c92` and `c034bc02f`, with the same losses and parity +figures, bit for bit. + +**One TPU7x VM** (tpu7x-8: 4 chips, 8 devices; Pathways in docker), PP=4 x FSDP=2, 2 warm-up steps: + +| Model (8 layers) | Sequence | Timed steps | Step time | TFLOP/s/device | Loss, first to last step | +|---|---|---|---|---|---| +| `simple` | 512 | 8 | 7.11 ms | (toy) | 10.217 to 2.772 | +| deepseek3-tiny | 512 | 8 | 17.72 ms | (toy) | 10.200 to 2.919 | +| deepseek3-tiny with mHC (`mhc_expansion_rate=4`) | 512 | 8 | 36.88 ms | (toy) | 10.190 to 2.718 | +| llama3.1-8b, `--learning_rate=1e-5` | 1024 | 10 | 70.19 ms | 201.7 | 12.27 to 0.27 | + +Through the proxy, tiny models' step times follow the host's load: `simple` and deepseek3-tiny reran at 8.07 and +15.06 ms on 2026-11-26, and the mHC program took 45.0 ms at a load average of 65 to 135. + +**2 x tpu7x-4x4x4** (256 devices; one xpk-rendered Pathways JobSet whose head ran `train.run_training` for the four +runs in one client session, not through `launch.py`), 10 warm-up and 20 timed steps, no stage straddling a slice: + +| Model (8 layers) | Stages | Devices a stage | Tokens a step | Step time | TFLOP/s/device | +|---|---|---|---|---|---| +| llama3.1-8b, sequence 1024, `--learning_rate=1e-5` | PP=4, 2 a slice | 64 | 262,144 | 159.0 ms | 89.0 | +| llama3.1-8b, sequence 1024, `--learning_rate=1e-5` | PP=2, 1 a slice | 128 | 524,288 | 231.8 ms | 122.1 | +| deepseek3-tiny, sequence 512 | PP=4, 2 a slice | 64 | 131,072 | 49.9 ms | (toy) | +| deepseek3-tiny, sequence 512 | PP=2, 1 a slice | 128 | 262,144 | 44.3 ms | (toy) | + +deepseek3-tiny took about 0.3 s a step until it settled by its 14th step. No MaxText SPMD step time was measured. + +**Schedules** (2026-11-26): llama3.1-8b cut to 8 layers, sequence 1024, `--learning_rate=1e-5`, 8 microbatches, +`--per_device_batch_size=8`; median step time (TFLOP/s/device). On the TPU7x VM PP=4 x FSDP=2 with 3 warm-up and 20 +timed steps, on 2 x tpu7x-4x4x4 as above: + +| Schedule | TPU7x VM | the VM, layers 2,2,3,1 | 2 x tpu7x-4x4x4, PP=4 | PP=4, layers 2,2,3,1 | PP=2 | +|---|---|---|---|---|---| +| 1F1B | 105.6 ms (268) | 103.4 ms (274) | 243.7 ms (116) | 248.9 ms (114) | 402.7 ms (141) | +| GPipe | 124.2 ms (228) | 108.0 ms (262) | not run | not run | not run | +| ZB-H1 | 96.6 ms (293) | 88.6 ms (320) | 217.4 ms (130) | 195.9 ms (145) | 326.3 ms (174) | +| ZB-H2 | 97.2 ms (291) | 82.8 ms (342) | 212.2 ms (133) | 194.6 ms (146) | 319.4 ms (177) | +| ZB-H2-HALF | 107.2 ms (264) | 94.0 ms (301) | 249.2 ms (114) | not run | 330.5 ms (171) | +| ZB-H2-FULL | 105.7 ms (268) | 91.9 ms (308) | not run | not run | not run | + +All schedules give llama the same losses (on the VM, 12.268 to 0.0235 over 23 steps). ZB-H1 and ZB-H2 save 8 to 13% +of 1F1B's step at PP=4 and 19 to 21% at PP=2. The output head, about 2.3 layers of FLOPs, makes the last stage the +slowest; with 2,2,3,1 layers (`--stage_layer_counts`) the stages are closer, and the saving grows to 14 to 22%. In a +trace of the VM, ZB-H1's B_a halves the middle stages' backward (2.0 against 4.1 ms), so each gradient reaches the +stage upstream sooner, and the last stage runs its last four B_w (14.5 ms) while the gradient drains back through the +other stages. On the VM `simple` and deepseek3-tiny run fragments of 0.1 to 0.3 ms, so their steps are bound by +dispatch and follow the host's load: the zero-bubble schedules ranged from 24% faster to 55% slower across sessions. +On 2 x tpu7x-4x4x4, deepseek3-tiny at PP=4 took 72.0 ms with 1F1B, 66.7 with ZB-H1, 55.6 with ZB-H2 and 54.6 with +ZB-H2-HALF. + +**Parity** (`parity.py`, float32, PP=4 x FSDP=2, 3 steps, on the TPU7x VM; the second row on 2026-11-26): MPMD +against one unsharded SPMD program from the same parameters and data. Each cell is the worst step or tensor / its +bound, max(tolerance, 4 x the noise floor), the floor being the SPMD program with another microbatch split: + +| Model and settings | Loss | Step-1 gradients (rel. L2) | Parameters (rel. L2) | +|---|---|---|---| +| `simple` (the quick start's command) | 1.7e-5 / 1e-4 | 7.4e-4 / 1.0e-2 | 1.3e-3 / 1.0e-2 | +| `simple`, `matmul_precision=highest`, `JAX_DEFAULT_MATMUL_PRECISION=highest` | 9.3e-8 / 1e-4 | 3.2e-7 / 1e-2 | 2.9e-6 / 1e-2 | +| deepseek3-tiny, every expert routed, `matmul_precision=highest` | 1.4e-4 / 1.1e-3 | 4.2e-3 / 1.1e-2 | 6.5e-3 / 2.4e-2 | +| the same with mHC (`mhc_expansion_rate=4`), floor at 8 microbatches | 3.1e-5 / 1.1e-4 | 3.3e-2 / 4.7e-2 | 8.7e-3 / 3.2e-2 | +| the second row with 8 microbatches, ZB-H1 and each ZB-H2 (2026-11-26) | 1.1e-7 / 1e-4 | 3.5e-7 / 1e-2 | 2.6e-6 / 1e-2 | +| the third row with 8 microbatches, ZB-H1 and ZB-H2, floor at 16 (2026-11-26) | 1.4e-4 / 5.5e-4 | 5.2e-3 / 1.4e-2 | 5.7e-3 / 2.2e-2 | + +All passed. The zero-bubble schedules give the same numbers as each other, and as 1F1B at the same settings to two +digits; the last row's default floor, 4 unsharded microbatches of 2,048 tokens, halts the TPU in MaxText's GMM kernel +(as 2,048-token microbatches with mHC do). With top-8 routing, deepseek3-tiny fails on its router gradients only +(10.5% against 1%): near-tied expert scores round to another expert. mHC's mixing scalars have near-zero step-1 +gradients that move with the microbatch split, so they pass only against a wide floor. + +**October 2026, the earlier, unpublished implementation** this package was ported from (jax 0.11.1, Shardy `2832731`, +Pathways `20261013-jax_0.11.1`, an October MaxText; v5p, MFU against 459 TFLOP/s; not repeated with this package): + +| Hardware | Configuration (1F1B unless noted) | Step time | TFLOP/s/device (MFU) | +|---|---|---|---| +| v5p-64 | llama3.1-8b (32 layers), PP=4 x FSDP=8, 8 microbatches of 8 x 2048 tokens; ZB-H1 | 1337 ms; 1113 ms | 142.9 (31.1%); 171.7 (37.4%) | +| v5p-32 | llama3.1-8b, PP=4 x FSDP=4, 8 microbatches of 4 x 2048: MPMD; MaxText's SPMD pipeline at the same tokens | 1351 ms; 1641 ms | 141 (30.8%); 116.4 | +| 2 x v5p-32 | the v5p-64 run with one stage boundary over DCN (one v5p-64: 1337 ms) | 1349 ms (+0.9%) | 141.6 (30.8%) | +| 4 x v5p-16 | the v5p-64 run with one stage a slice, 3 boundaries over DCN (one v5p-64: 1339 ms) | 1388 ms (+3.7%) | 137.6 (30.0%) | +| v5p-128 | llama3.1-70b (80 layers), PP=8 x FSDP=8, `--remat`, 16 microbatches of 8 x 2048 | 12.69 s | 137.2 (29.9%) | +| v5p-64 | mixtral-8x7b, PP=4 x FSDP=8, `--remat`; deepseek2-16b, 6/7/7/7 layers, `--expert=8 --ragged_buffer_factor=2` | 3258 ms; 996 ms | 98.2 (21.4%); 64.0 | + +## Tests + +```bash +# The package's tests are in tests/unit/mpmd_test/, beside the pure-JAX pipeline's: name them +T=tests/unit/mpmd_test +JAX_PLATFORMS=cpu XLA_FLAGS=--xla_force_host_platform_device_count=4 python3 -m pytest \ + $T/benchmark_test.py $T/config_test.py $T/documented_commands_test.py $T/hparams_test.py $T/launch_test.py \ + $T/local_pathways_test.py $T/mesh_utils_test.py $T/models_test.py $T/parity_test.py \ + $T/pathways_train_test.py $T/pipeline_test.py $T/sdy_mpmd_compat_test.py $T/sdy_mpmd_versions_test.py \ + $T/spmd_baseline_test.py $T/train_test.py +``` + +With 4 or 8 devices: 129 passed, 1 skipped with shardy-mpmd; 116 passed, 14 skipped without it (the lowering, merge-rule +and shim tests need the frontend); tests that need 4 devices skip below that. MaxText CI's `cpu-unit` job runs them with +4 devices, without shardy-mpmd and the marker `cpu_only and not post_training and not integration_test`: 116 passed, 13 +skipped. `pathways_train_test.py` (`tpu_only`) trains on Pathways and skips elsewhere: run it with shardy-mpmd and +`JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000` against `local_pathways.sh`. + +## Known limitations + +- **The MPMD step trains on the token cross-entropy alone**, with a constant-learning-rate `optax.adamw` + (`--learning_rate`, default 1e-3; llama3.1-8b needs 1e-5) on synthetic data: not MaxText's optimizer, schedule or + input pipeline. Settings that add to MaxText's model or loss are refused, each naming the override that turns it off: + an MTP block, a sinusoidal position embedding, the MoE load-balance loss, the z-loss, routing-bias updates and the + indexer loss. +- **Refused rather than trained as another model:** other decoder blocks, m3 models, tied embeddings (pass + `--maxtext_overrides=logits_via_embedding=false`), learned position embeddings, hyper-connections outside `deepseek`, + quantization, `shard_mode=explicit`, `prefetch_fsdp_weights`, the output-head variants `config._check_buildable` + lists, and remat policies that offload to the host. YaRN RoPE (DeepSeek, Kimi) becomes real RoPE, in `spmd_baseline` + too: Shardy MPMD asserts on its `complex64` table. +- **OSS Shardy MPMD lacks** five of its ten boolean partitioning options (jaxlib's driver ignores them), tying an + output's layout to an input's (the state's shardings are pinned on both sides of `mpmd.jit`), `lowered.ifrt_ir_module` + (`pipeline.pin_ifrt_transfers_to_producers` edits `lowered.partitioning_result`), AOT compilation for a TPU topology, + serialized programs and custom schedule rules. The wrap-around and circular schedules are refused: each stage holds + one contiguous chunk of layers. +- **Pathways:** `ifrt_ir_program_memory_stats` is unimplemented through the proxy, so `train_compile` logs each + fragment's memory instead of the program's; a worker's out-of-memory reaches the client as a lost connection; traces + need a `gs://` directory and about 1 s after the trace starts (`--profile_delay_s`). +- **MoE:** expert gradients under FSDP are reduce-scattered once a step by patching the private + `jax._src.shard_map._unmentioned2` (`models_test.py` fails if jax renames it); a large MoE needs + `--ragged_buffer_factor=2`, or its routed-token buffers are sized for the worst case. +- `launch.py`'s commands have not run on a cluster; shardy-mpmd is not in MaxText's requirements. diff --git a/src/maxtext/experimental/mpmd/partir/__init__.py b/src/maxtext/experimental/mpmd/partir/__init__.py new file mode 100644 index 0000000000..c082ee3565 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""MPMD pipeline parallelism on Shardy MPMD (OSS PartIR:MPMD), executed by Pathways.""" diff --git a/src/maxtext/experimental/mpmd/partir/benchmark.py b/src/maxtext/experimental/mpmd/partir/benchmark.py new file mode 100644 index 0000000000..c169a91dc5 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/benchmark.py @@ -0,0 +1,408 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Step timing, throughput accounting and XProf capture. + +Kept separate from the trainer so the measurement logic can be unit tested and +so the SPMD comparison reports exactly the same quantities as the MPMD run. + +The throughput numbers are deliberately reported in the same units MaxText +itself logs (``TFLOP/s/device`` and ``Tokens/s/device``, see +``maxtext/src/maxtext/common/metric_logger.py``) so that an MPMD run can be +compared against a MaxText SPMD pipeline run without any unit conversion. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +import contextlib +import dataclasses +import math +import statistics +import time +from typing import Any + +import jax + +from maxtext.utils import max_logging + +from maxtext.experimental.mpmd.partir import hparams as hparams_lib + + +class NonFiniteLossError(RuntimeError): + """A step returned a NaN or infinite loss (see :func:`run_steps`).""" + + def __init__(self, step: int, loss: float, losses: tuple[float, ...]): + # The losses end at `step` and may start after step 1 (first_step). + super().__init__( + f"step {step} returned a loss of {loss} (losses from step" + f" {step - len(losses) + 1}:" + f" {', '.join(f'{value:.6g}' for value in losses)})" + ) + self.step = step + self.loss = loss + self.losses = losses + + +@dataclasses.dataclass(frozen=True) +class StepStats: + """Timing statistics for a sequence of training steps. + + Attributes: + step_times_ms: Wall-clock duration of each timed step. + loss: Loss reported by the final step. + first_loss: Loss reported by the first step run (warm-up included). + """ + + step_times_ms: tuple[float, ...] + loss: float + first_loss: float = float("nan") + + @property + def num_steps(self) -> int: + """Returns the number of timed steps.""" + return len(self.step_times_ms) + + @property + def mean_ms(self) -> float: + """Returns the arithmetic mean step time in milliseconds.""" + return statistics.fmean(self.step_times_ms) if self.step_times_ms else 0.0 + + @property + def median_ms(self) -> float: + """Returns the median step time in milliseconds.""" + return statistics.median(self.step_times_ms) if self.step_times_ms else 0.0 + + @property + def min_ms(self) -> float: + """Returns the minimum step time in milliseconds.""" + return min(self.step_times_ms) if self.step_times_ms else 0.0 + + @property + def stdev_ms(self) -> float: + """Returns the sample standard deviation of step times in milliseconds.""" + if len(self.step_times_ms) < 2: + return 0.0 + return statistics.stdev(self.step_times_ms) + + +def loss_warning(stats: StepStats, learning_rate: float) -> list[str]: + """Returns a warning when the loss rose over the run or is not finite. + + Every step trains on the same synthetic batch, so a healthy run's loss falls; + a rise from the first step to the last means the optimizer diverged. + llama3.1-8b at the default learning rate of 1e-3 went from 24.8 to 675 in 7 + steps (and trained with 1e-5). The step times stay valid, but the run is not + training. + + Args: + stats: The timed steps' statistics. + learning_rate: The learning rate the steps ran with. + """ + if stats.num_steps and not math.isfinite(stats.loss): + return [ + f" ERROR : the loss is {stats.loss} after" + f" {stats.num_steps} timed steps (first {stats.first_loss:.4g}); the" + " run did not train, and its step times are not valid" + ] + if not stats.loss > stats.first_loss: # also False when either is NaN + return [] + return [ + f" WARNING : the loss rose from {stats.first_loss:.4g}" + f" to {stats.loss:.4g}: --learning_rate {learning_rate:g} is too high" + " for this model (llama3.1-8b diverges at 1e-3 and trains at 1e-5)" + ] + + +@dataclasses.dataclass(frozen=True) +class Throughput: + """Derived performance figures for one training step. + + Attributes: + step_time_s: Median step duration, in seconds. + tokens_per_step: Number of training tokens consumed per step. + num_devices: Total devices participating in the run. + tflops_per_step_per_device: Analytic model FLOPs per device per step. + peak_tflops_per_device: Hardware peak, or 0 when unknown. + """ + + step_time_s: float + tokens_per_step: int + num_devices: int + tflops_per_step_per_device: float + peak_tflops_per_device: float = 0.0 + + @property + def tokens_per_second(self) -> float: + """Returns global training throughput in tokens per second.""" + return self.tokens_per_step / self.step_time_s if self.step_time_s else 0.0 + + @property + def tokens_per_second_per_device(self) -> float: + """Returns per-device training throughput in tokens per second.""" + if not self.num_devices: + return 0.0 + return self.tokens_per_second / self.num_devices + + @property + def tflops_per_second_per_device(self) -> float: + """Returns achieved TFLOP/s per device.""" + if not self.step_time_s: + return 0.0 + return self.tflops_per_step_per_device / self.step_time_s + + @property + def mfu(self) -> float | None: + """Model FLOPs utilization, or None if the hardware peak is unknown.""" + if self.peak_tflops_per_device <= 0: + return None + return self.tflops_per_second_per_device / self.peak_tflops_per_device + + def report(self) -> str: + """Returns the figures as aligned ``key: value`` lines.""" + lines = [ + f"step_time_ms : {self.step_time_s * 1e3:.3f}", + f"tokens_per_step : {self.tokens_per_step}", + f"num_devices : {self.num_devices}", + f"Tokens/s : {self.tokens_per_second:,.1f}", + f"Tokens/s/device : {self.tokens_per_second_per_device:,.1f}", + f"TFLOP/s/device : {self.tflops_per_second_per_device:.3f}", + ] + mfu = self.mfu + if mfu is not None: + lines.append(f"MFU : {mfu * 100:.2f}%") + return "\n".join(f" {line}" for line in lines) + + +def compute_throughput( + *, + stats: StepStats, + maxtext_config: Any, + devices_per_stage: int, + num_devices: int, + peak_tflops_per_device: float = 0.0, +) -> Throughput: + """Derives throughput figures from `stats`. + + MaxText's analytic FLOP counter reports FLOPs for ``per_device_batch_size`` + tokens across every layer. In this pipeline the global batch is + ``per_device_batch_size * devices_per_stage`` (the batch is data-parallel + over one stage, not over the whole slice), so the whole-step model FLOPs are + the MaxText figure scaled by `devices_per_stage`. Dividing by the *total* + device count then charges the pipeline for the devices it is occupying, + including any that are idle in a bubble -- which is the honest way to + compare a pipeline against a non-pipelined baseline. + + The FLOPs are those of the model the MPMD step runs: MaxText also counts a + multi-token-prediction block's, which the MPMD model does not build + (``config.py`` refuses ``mtp_num_layers > 0``), so they are never charged. + + Args: + stats: Measured step times. + maxtext_config: The MaxText config the run used. + devices_per_stage: Number of devices backing one pipeline stage. + num_devices: Total number of devices in the run. + peak_tflops_per_device: Hardware peak TFLOP/s, 0 if unknown. + + Returns: + The derived :class:`Throughput`. + """ + # Imported here so that modules which only need the dataclasses above do not + # pay for MaxText's import graph. + from maxtext.utils import maxtext_utils # pylint: disable=import-outside-toplevel + + if maxtext_config.mtp_num_layers > 0: + maxtext_config = maxtext_config.replace(mtp_num_layers=0) + maxtext_tflops_per_device, _, _ = maxtext_utils.calculate_tflops_training_per_device(maxtext_config, log=False) + total_tflops_per_step = maxtext_tflops_per_device * devices_per_stage + tokens_per_step = int(maxtext_config.per_device_batch_size * devices_per_stage * maxtext_config.max_target_length) + return Throughput( + step_time_s=stats.median_ms / 1e3, + tokens_per_step=tokens_per_step, + num_devices=num_devices, + tflops_per_step_per_device=total_tflops_per_step / max(num_devices, 1), + peak_tflops_per_device=peak_tflops_per_device, + ) + + +def run_steps( + step_fn: Callable[..., Any], + state: Any, + batch: Any, + *, + num_steps: int, + warmup_steps: int = 0, + first_step: int = 0, + log_prefix: str = "", + abort_on_nonfinite: bool = False, +) -> tuple[Any, StepStats]: + """Runs `step_fn` repeatedly, timing the steps after the warm-up. + + Args: + step_fn: A compiled ``(state, batch) -> (state, loss)``. + state: Initial state, threaded through the steps. + batch: The (fixed) input batch. + num_steps: Number of timed steps. + warmup_steps: Number of untimed steps run first. The first execution pays + for dispatch-path warm-up and, on Pathways, for program distribution; + including it would dominate the mean. + first_step: Steps the state has been through in earlier calls, so that + :class:`NonFiniteLossError` numbers the step among all of them (it lists + this call's losses only): a NaN in train.py's second profiled step after + one warm-up and three timed steps is step 6, not "step 2". + log_prefix: Prefix for the per-step log lines. + abort_on_nonfinite: Raise :class:`NonFiniteLossError` at the first NaN or + infinite loss (warm-up included) instead of running on: every later step + is wasted, and its timing describes a degenerate run. + + Returns: + A tuple of the final state and the collected :class:`StepStats`. + + Raises: + NonFiniteLossError: See ``abort_on_nonfinite``. + """ + loss_value = first_loss = float("nan") + losses: list[float] = [] + + def check(step: int) -> None: + losses.append(loss_value) + if abort_on_nonfinite and not math.isfinite(loss_value): + raise NonFiniteLossError(first_step + step, loss_value, tuple(losses)) + + # Every step is wrapped in a `StepTraceAnnotation`. XProf uses these + # annotations -- and nothing else -- to segment a trace into training steps. + # Without them an XProf session reports `is_training: false` and a + # `steptime_ms_average` derived from the whole (mostly idle) profile window, + # which is not the step time of this trainer. MaxText emits the same + # annotation with the same "train" name, so keeping it identical here is what + # makes an MPMD XProf directly comparable to a MaxText SPMD one. + # `block_until_ready` must cover the updated state, not just the loss. The + # loss is produced part-way through the step, while the optimizer update + # finishes later; blocking on the loss alone would let the tail of step N + # overlap step N+1 and be attributed to it. + for index in range(warmup_steps): + with jax.profiler.StepTraceAnnotation("train", step_num=index): + state, loss = step_fn(state, batch) + jax.block_until_ready((state, loss)) + loss_value = float(loss) + if index == 0: + first_loss = loss_value + max_logging.log(f"{log_prefix}warmup step {index + 1}/{warmup_steps}" f" loss={loss_value:.6f}") + check(index + 1) + + step_times_ms = [] + for index in range(num_steps): + started = time.perf_counter() + with jax.profiler.StepTraceAnnotation("train", step_num=warmup_steps + index): + state, loss = step_fn(state, batch) + jax.block_until_ready((state, loss)) + elapsed_ms = (time.perf_counter() - started) * 1e3 + step_times_ms.append(elapsed_ms) + loss_value = float(loss) + if index == 0 and not warmup_steps: + first_loss = loss_value + max_logging.log( + f"{log_prefix}completed step: {index + 1}/{num_steps}," + f" seconds: {elapsed_ms / 1e3:.4f}, loss: {loss_value:.6f}" + ) + check(warmup_steps + index + 1) + + return state, StepStats( + step_times_ms=tuple(step_times_ms), + loss=loss_value, + first_loss=first_loss, + ) + + +@contextlib.contextmanager +def profile( + enabled: bool, + *, + tag: str, + profile_dir: str = "", + trace_delay_s: float = 1.0, +) -> Iterator[list[str]]: + """Captures an XProf trace around the enclosed block. + + On a Pathways backend ``pathwaysutils`` turns ``jax.profiler.start_trace`` + into a Pathways profile request: the workers write the trace themselves, so + `profile_dir` must be a ``gs://`` directory (a local one is rejected). On any + other backend the trace goes to `profile_dir` (default ``/tmp/xprof``). + Either way it lands in ``/``. + + Pathways workers start their TPU tracer late: device work issued right after + ``start_trace`` returns is missing from the trace (no ``/device:TPU`` planes). + The block therefore starts `trace_delay_s` after the trace does. + + The trace covers one TPU, one SparseCore and one SparseCore tile a traced + host (`profile_options`); a backend that refuses those options gets an + untrimmed trace instead of none. + + Args: + enabled: When False this is a no-op, and the yielded list stays empty. + tag: Name of the trace directory under `profile_dir`. + profile_dir: Output directory; must be ``gs://...`` under Pathways. + trace_delay_s: Seconds to wait after ``start_trace`` on Pathways. + + Yields: + A list that will contain the trace directory once the block has exited. + """ + urls: list[str] = [] + if not enabled: + yield urls + return + + # Imported lazily so CPU unit tests do not need pathwaysutils. + import pathwaysutils # pylint: disable=import-outside-toplevel + + on_pathways = bool(pathwaysutils.is_pathways_backend_used()) + root = profile_dir or ("" if on_pathways else "/tmp/xprof") + if on_pathways and not root.startswith("gs://"): + max_logging.warning( + "Skipping the XProf trace: under Pathways jax.profiler.start_trace" + f" accepts only gs:// directories, got --profile_dir={profile_dir!r}." + ) + yield urls + return + destination = f"{root.rstrip('/')}/{tag}" + max_logging.log(f"Starting JAX profiler trace to {destination}...") + try: + jax.profiler.start_trace(destination, profiler_options=profile_options()) + except Exception as error: # pylint: disable=broad-exception-caught + max_logging.warning(f"The trimmed trace was refused ({error}); tracing untrimmed.") + jax.profiler.start_trace(destination) + try: + if on_pathways and trace_delay_s > 0: + time.sleep(trace_delay_s) + yield urls + except BaseException: + with contextlib.suppress(Exception): + jax.profiler.stop_trace() + raise + # The measured steps have already run when the trace is written, so a trace + # that fails to write is reported, not raised: discarding a completed run + # because its profile could not be saved would be backwards. + try: + jax.profiler.stop_trace() + except Exception as error: # pylint: disable=broad-exception-caught + max_logging.warning(f"XProf trace could not be written: {error}") + return + urls.append(destination) + max_logging.log(f"JAX profiler trace written to {destination}.") + + +def profile_options() -> jax.profiler.ProfileOptions: + """`jax.profiler.ProfileOptions` for `hparams.TRACE_ADVANCED_CONFIGURATION`.""" + options = jax.profiler.ProfileOptions() + options.advanced_configuration = dict(hparams_lib.TRACE_ADVANCED_CONFIGURATION) + return options diff --git a/src/maxtext/experimental/mpmd/partir/config.py b/src/maxtext/experimental/mpmd/partir/config.py new file mode 100644 index 0000000000..3db462a8f8 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/config.py @@ -0,0 +1,331 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Builds MaxText configs from :class:`hparams.Hparams`. + +Every entry point in this package funnels through :func:`build_maxtext_config` +so that the trainer, the lowering check, the parity checker and the unit tests +all see byte-identical MaxText settings, and the MPMD and SPMD paths cannot +drift apart. +""" + +from __future__ import annotations + +from collections.abc import Mapping +import os +import types +from typing import Any + +from maxtext.common.common_types import DecoderBlockType +from maxtext.common.common_types import get_weight_dtype +from maxtext.common.common_types import ShardMode +from maxtext.configs import pyconfig +from maxtext.layers import quantizations +from maxtext.utils.globals import MAXTEXT_CONFIGS_DIR + +from maxtext.experimental.mpmd.partir import hparams as hparams_lib + +# Settings that make a run reproducible and self-contained. They are applied to +# every config this module produces, so an MPMD run and its SPMD reference can +# never disagree on, say, dropout. +_DETERMINISM_OVERRIDES = { + # Pipelining splits the model into separately traced computations; scanned + # layers would hide the per-layer boundaries PartIR needs to see. + "scan_layers": "false", + "enable_checkpointing": "false", + "enable_dropout": "false", + "dropout_rate": "0.0", + # Synthetic data: this package benchmarks the pipeline, not the input + # pipeline. + "dataset_type": "synthetic", + "enable_goodput_recording": "false", + "monitor_goodput": "false", + # `use_iota_embed` avoids a gather that would otherwise dominate the tiny + # embedding stage and distort the profile. + "use_iota_embed": "true", + # Required so that the `base_*` overrides below are honoured on top of a + # named model config. + "override_model_config": "true", +} + + +# What MaxText's model or trainer (trainers/pre_train/train.py) adds that the MPMD step leaves out, by setting: when it +# is on, what it adds, and the value that turns it off. The MPMD model builds neither an MTP block nor a sinusoidal +# position embedding, and its loss collects none of the auxiliary terms MaxText's layers record; spmd_baseline's run of +# MaxText's trainer applies all of them. Each condition is the one MaxText's trainer applies the term under. +_LEFT_OUT = types.MappingProxyType( + { + "mtp_num_layers": (lambda cfg: cfg.mtp_num_layers > 0, "a multi-token-prediction block and its loss", "0"), + "use_untrainable_positional_embedding": ( + lambda cfg: cfg.use_untrainable_positional_embedding, + "a sinusoidal position embedding", + "false", + ), + "load_balance_loss_weight": ( + lambda cfg: cfg.num_experts > 1 and cfg.load_balance_loss_weight > 0, + "the MoE load-balance loss", + "0", + ), + "z_loss_multiplier": (lambda cfg: cfg.z_loss_multiplier != 0, "the z-loss", "0"), + "routed_bias_update_rate": ( + lambda cfg: cfg.routed_bias and cfg.routed_bias_update_rate > 0, + "the routing-bias updates", + "0", + ), + "indexer_loss_scaling_factor": ( + lambda cfg: cfg.use_indexer and cfg.indexer_loss_scaling_factor > 0, + "the indexer loss", + "0", + ), + } +) + + +def build_maxtext_config( + hparams: hparams_lib.Hparams, + *, + overrides: Mapping[str, Any] | None = None, + base_config_path: str | None = None, +) -> Any: + """Materialises the MaxText config described by `hparams`. + + Args: + hparams: Hyperparameters to translate. + overrides: Extra ``key=value`` MaxText settings applied last, i.e. they win + over everything this function derives. Used by tests. + base_config_path: Base YAML to start from. Defaults to MaxText's + ``base.yml``. + + Returns: + The initialised MaxText config object (``pyconfig.HyperParameters``). + + Raises: + ValueError: If the model is not one the MPMD model builds as MaxText + describes it (see :func:`_check_buildable`). + """ + base_yaml = base_config_path or os.path.join(MAXTEXT_CONFIGS_DIR, "base.yml") + # `ici_pipeline_parallelism` below is only MaxText's bookkeeping (the stage + # count `models` reads back and `pipeline_parallel_layers`); MaxText's own + # pipeline never runs. MaxText refuses `remat_policy=none` together with + # pipeline parallelism, because its pipeline needs checkpointing, so it is + # handed a policy it accepts. The MPMD model's own choice, + # `hparams.mpmd_remat_policy`, goes to the model itself + # (`models.PipelineGraphDef.remat_policy`), not through this config. + maxtext_remat_policy = hparams.mpmd_remat_policy if hparams.mpmd_remat_policy != "none" else "full" + + # (`hparams` has checked that the model config exists: pyconfig would only + # log a warning without it and measure base.yml's model under its name.) + argv: list[str] = [ + # pyconfig treats argv[0] as the program name and ignores it. + "maxtext_mpmd_partir", + base_yaml, + f"model_name={hparams.maxtext_model_name}", + f"base_num_decoder_layers={hparams.num_layers}", + f"per_device_batch_size={hparams.per_device_batch_size}", + f"max_target_length={hparams.max_target_length}", + f"ici_pipeline_parallelism={hparams.num_stages}", + "dcn_pipeline_parallelism=1", + # NB: `gradient_accumulation_steps` is deliberately NOT set here. + # MaxText reads it as "replay this batch N times before applying the + # optimizer", so it multiplies both the global batch and the analytic + # FLOP count (`calculate_tflops_training_per_device`) by N. PartIR's + # microbatches are the opposite: they *split* one global batch across + # the pipeline. Setting it to `num_microbatches` therefore left + # tokens/s correct but inflated TFLOP/s by exactly `num_microbatches`. + f"remat_policy={maxtext_remat_policy}", + f"learning_rate={hparams.learning_rate}", + f"init_weights_seed={hparams.seed}", + ] + if hparams.emb_dim > 0: + argv.append(f"base_emb_dim={hparams.emb_dim}") + if hparams_lib.is_pure_moe_model(hparams.maxtext_model_name, hparams.first_num_dense_layers): + moe_dim = hparams.moe_mlp_dim if hparams.moe_mlp_dim > 0 else hparams.mlp_dim + if moe_dim > 0: + argv.append(f"base_mlp_dim={moe_dim}") + argv.append(f"base_moe_mlp_dim={moe_dim}") + else: + if hparams.mlp_dim > 0: + argv.append(f"base_mlp_dim={hparams.mlp_dim}") + if hparams.moe_mlp_dim > 0: + argv.append(f"base_moe_mlp_dim={hparams.moe_mlp_dim}") + if hparams.vocab_size > 0: + argv.append(f"vocab_size={hparams.vocab_size}") + + argv += [f"{key}={value}" for key, value in _DETERMINISM_OVERRIDES.items()] + + if hparams.fsdp > 0: + argv.append(f"ici_fsdp_parallelism={hparams.fsdp}") + # Expert parallelism and token dispatch: one table shared with + # `spmd_baseline` so both sides route tokens to experts identically. + argv += [f"{key}={value}" for key, value in hparams_lib.moe_dispatch_overrides(hparams).items()] + + decoder_block = hparams.decoder_block + if hparams.maxtext_model_name == "default": + # `simple` and `default` build the simple_mlp block, not base.yml's. A + # named model's config gives its block to pyconfig, and _check_buildable + # checks what pyconfig resolved. + argv.append(f"decoder_block={decoder_block}") + pipeline_layers = (hparams.num_layers // hparams.num_stages) * hparams.num_stages + if decoder_block not in ("simple", "simple_mlp") or pipeline_layers != hparams.num_layers: + # Tell MaxText that *all* layers (or the largest stage-divisible prefix + # when asymmetric stage_layer_counts has a sum not divisible by num_stages) + # participate in the pipeline; the MPMD layer-to-mesh assignment is what + # actually places all `hparams.num_layers` layers. + argv.append(f"pipeline_parallel_layers={pipeline_layers}") + + if decoder_block == "deepseek" or hparams_lib.uses_yarn_rope(hparams.maxtext_model_name): + # Several MaxText model configs (DeepSeek, Kimi-K2) ask for YaRN RoPE, + # which MaxText implements with complex + # arithmetic: it precomputes `freqs_cis = exp(i*theta)` as a `complex64` + # table and rotates by complex multiplication (`layers/embeddings.py`, + # `YarnRotaryEmbedding`). PartIR MPMD cannot partition that -- + # `MarkFragmentReservedMemoryPass::AddLiveValue` calls + # `mlir::Type::getIntOrFloatBitWidth()` on every live value and a + # `tensor<...xcomplex>` trips its assertion, crashing the compiler: + # + # assert.h assertion failed at mlir/lib/IR/Types.cpp:125 in + # getIntOrFloatBitWidth(): isIntOrFloat() && "only integers and floats + # have a bitwidth" + # + # `rope_pairwise` does not help: it avoids complex *multiplication* but + # still gathers from the complex table. So pin the standard real-valued + # sin/cos RoPE. It changes the positional encoding, but not the parameter + # count, the FLOP count, or anything else the pipeline benchmark measures + # -- and `spmd_baseline` pins exactly the same value, so both sides stay + # comparable. Revisit if PartIR learns to handle complex types. + argv.append("rope_type=default") + if decoder_block == "deepseek" and hparams.first_num_dense_layers >= 0: + argv.append(f"first_num_dense_layers={hparams.first_num_dense_layers}") + + argv += [f"{key}={value}" for key, value in hparams_lib.float32_gmm_tiles(hparams).items()] + argv += list(hparams.maxtext_overrides) + if overrides: + argv += [f"{key}={value}" for key, value in overrides.items()] + + cfg = pyconfig.initialize(argv) + _check_buildable(cfg, hparams) + return cfg + + +def _check_buildable(cfg: Any, hparams: hparams_lib.Hparams) -> None: + """Refuses configs that ``models`` would not build as MaxText describes them. + + ``models.PipelinedTransformer`` builds MaxText's token embedding, decoder + layers (of :data:`hparams.SUPPORTED_DECODER_BLOCKS`) and untied output head + (final norm, ``logits_dense``) in MaxText's default form, and + ``train_step.compute_loss`` trains them on the token cross-entropy alone. A + model or objective that needs more would otherwise train as something else, + silently, and ``spmd_baseline`` would compare it with the real one. + + Raises: + ValueError: For an unsupported decoder block (or one other than the + hyperparameters derived their settings for), a model MaxText builds with + its m3 backend, tied embeddings, a learned position embedding, + hyper-connections outside the deepseek block, quantization, explicit + sharding, an output-head setting the MPMD model does not mirror, or a + setting that adds to MaxText's model or loss what the MPMD step leaves + out (:data:`_LEFT_OUT`). + """ + name = hparams.model_name + unsupported = hparams_lib.unsupported_decoder_block(name, cfg.decoder_block.value) + if unsupported: + raise ValueError(unsupported) + if cfg.decoder_block.value != hparams.decoder_block: + raise ValueError( + f"{name}: MaxText resolved decoder_block={cfg.decoder_block.value}, but the settings config.py derives (and" + f" spmd_baseline prints) are for the model config's decoder_block={hparams.decoder_block}." + ) + if cfg.logits_via_embedding: + raise ValueError( + f"{name} ties its output projection to the embedding (logits_via_embedding), which the MPMD model does not" + " build: pass --maxtext_overrides=logits_via_embedding=false to run its untied variant (spmd_baseline then" + " runs the same one)." + ) + refused = { + # MaxText's create_model builds such a model with its separate m3 + # backend, not with NNXDecoder's layers. + "use_m3_model": cfg.use_m3_model, + # A learned position embedding (GPT-3). + "trainable_position_size": cfg.trainable_position_size > 0, + # Hyper-connection streams: `models.forward` expands and reduces them as + # MaxText's decoder does for the deepseek block, whose layers take them; + # the other supported layers do not. + "mhc_expansion_rate": cfg.mhc_expansion_rate > 1 and cfg.decoder_block != DecoderBlockType.DEEPSEEK, + # Every layer is built unquantized (`models._NNXDecoderLayerFactory`). + "quantization": bool(cfg.quantization), + # The stage meshes, the pre-gather and the deferred reduce-scatter assume + # MaxText's auto sharding mode. + "shard_mode": cfg.shard_mode != ShardMode.AUTO, + # The MPMD step pre-gathers FSDP weights its own way (`models.pregather_params`). + "prefetch_fsdp_weights": cfg.prefetch_fsdp_weights, + # The output head (`models.OutputHead`): `logits_dense` with ("embed", + # "vocab") kernel axes in the weight dtype, its logits cast to float32 by + # the loss, as MaxText's default head. + "lm_head_fsdp_as_vocab_tp": cfg.lm_head_fsdp_as_vocab_tp, + "lm_head_weight_grad_in_kernel_order": bool(cfg.lm_head_weight_grad_in_kernel_order), + "tie_lm_head_cotangents": cfg.tie_lm_head_cotangents, + "cast_logits_to_fp32": not cfg.cast_logits_to_fp32, + "weight_dtype": ( + get_weight_dtype(cfg, "logits_dense") != cfg.weight_dtype + or quantizations.get_weight_quant_config(cfg, "logits_dense") is not None + ), + } + settings = [key for key, is_refused in refused.items() if is_refused] + if settings: + raise ValueError( + f"{name}: the MPMD model does not build {', '.join(f'{key}={cfg.get_keys()[key]}' for key in settings)};" + " leave these settings at MaxText's defaults." + ) + left_out = [key for key, (is_set, _, _) in _LEFT_OUT.items() if is_set(cfg)] + if left_out: + # A model config can set them (qwen3-235b-a22b's load_balance_loss_weight), so the hint is an override. + *others, last = [f"{_LEFT_OUT[key][1]} ({key}={cfg.get_keys()[key]})" for key in left_out] + added = f"{', '.join(others)} and {last}" if others else last + hints = " ".join(f"--maxtext_overrides={key}={_LEFT_OUT[key][2]}" for key in left_out) + raise ValueError( + f"{name}: MaxText would add {added}, which the MPMD step leaves out: it trains the embedding, decoder layers and" + f" output head on the token cross-entropy alone. Pass {hints} to train without {'them' if others else 'it'}" + " (spmd_baseline then runs the same)." + ) + + +def describe(config: Any, hparams: hparams_lib.Hparams) -> str: + """Returns a multi-line summary of the run, for the logs.""" + if hparams.stage_layer_counts: + counts_str = ",".join(str(c) for c in hparams.stage_layer_counts) + stage_desc = f"{hparams.num_stages} (stage_layer_counts={counts_str})" + else: + stage_desc = f"{hparams.num_stages} ({hparams.layers_per_stage} layers/stage)" + lines = [ + (f"model_name : {hparams.model_name}" f" (maxtext: {hparams.maxtext_model_name})"), + f"decoder_block : {config.decoder_block.value}", + f"num_decoder_layers : {config.num_decoder_layers}", + f"emb_dim / mlp_dim : {config.emb_dim} / {config.mlp_dim}", + f"vocab_size : {config.vocab_size}", + f"max_target_length : {config.max_target_length}", + f"per_device_batch_size : {config.per_device_batch_size}", + f"pipeline stages : {stage_desc}", + f"fsdp per stage : {hparams.fsdp}", + f"expert per stage : {hparams.expert}", + ( + f"moe_dispatch : {hparams.moe_dispatch}" + f" (ragged_buffer_factor={hparams.ragged_buffer_factor}," + f" num_moe_token_chunks={hparams.num_moe_token_chunks})" + ), + f"num_microbatches : {hparams.num_microbatches}", + f"remat_policy (MPMD) : {hparams.mpmd_remat_policy}", + f"pipeline_schedule : {hparams.pipeline_schedule}", + ] + if hparams.maxtext_overrides: + lines.append(f"maxtext_overrides : {' '.join(hparams.maxtext_overrides)}") + return "\n".join(f" {line}" for line in lines) diff --git a/src/maxtext/experimental/mpmd/partir/hparams.py b/src/maxtext/experimental/mpmd/partir/hparams.py new file mode 100644 index 0000000000..0305f0c049 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/hparams.py @@ -0,0 +1,1015 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Single source of truth for the MPMD pipeline's hyperparameters. + +This module owns the ``absl`` flags that every entry point in this package shares (the trainer, the lowering check, +the parity checker, the SPMD baseline and the launcher). Keeping them here guarantees that: + + * a flag added once is understood by every entry point, and + * the launcher (``launch.py``) forwards *exactly* the flags the trainer accepts (see :func:`to_job_args`), so + launcher and trainer can never drift. + +The flags are registered by :func:`define_flags`, which each entry point calls before it parses its command line, and +never at import: MaxText's test process imports many modules that define absl flags of their own (``vocab_size``, +``seed``, ...), and a second definition of a name raises ``DuplicateFlagError``. + +The module depends only on ``absl``, ``omegaconf`` (for the model configs) and MaxText's path constants, so that the +launcher does not pull in JAX, Flax or MaxText's model code. +""" + +from __future__ import annotations + +from collections.abc import Sequence +import dataclasses +import functools +import os +import types +from typing import Any + +from absl import flags +import omegaconf + +from maxtext.utils.globals import MAXTEXT_CONFIGS_DIR + +# Pipeline schedules, spelled as PartIR's proto enum (the vocabulary of every +# flag, log line and report in this package). `OSS_SCHEDULE_NAMES` maps each +# onto the string Shardy MPMD's `mpmd_pipeline_schedule` takes. +PIPELINE_SCHEDULES = ( + "NONE", + "ONE_FWD_ONE_BWD", + "GPIPE", + "GPIPE_BUT_1F1B_FOR_LAST_MESH", + "ZERO_BUBBLE_H1", + "ZERO_BUBBLE_H2_ZERO_TX_LATENCY", + "ZERO_BUBBLE_H2_HALF_TX_LATENCY", + "ZERO_BUBBLE_H2_FULL_TX_LATENCY", + "PARALLEL_PIPELINES_WITH_WRAP_AROUND", + "CIRCULAR", + "CIRCULAR_WITH_REVERSED_BACKWARD", +) + +# `PIPELINE_SCHEDULES` -> Shardy MPMD's `mpmd_pipeline_schedule` value. +OSS_SCHEDULE_NAMES = types.MappingProxyType( + { + "NONE": "None", + "ONE_FWD_ONE_BWD": "1F1B", + "GPIPE": "GPipe", + "GPIPE_BUT_1F1B_FOR_LAST_MESH": "GPipeBut1F1BForLastMesh", + "ZERO_BUBBLE_H1": "ZeroBubbleH1", + "ZERO_BUBBLE_H2_ZERO_TX_LATENCY": "ZeroBubbleH2ZeroTxLatency", + "ZERO_BUBBLE_H2_HALF_TX_LATENCY": "ZeroBubbleH2HalfTxLatency", + "ZERO_BUBBLE_H2_FULL_TX_LATENCY": "ZeroBubbleH2FullTxLatency", + "PARALLEL_PIPELINES_WITH_WRAP_AROUND": "ParallelPipelinesWithWrapAround", + "CIRCULAR": "Circular", + "CIRCULAR_WITH_REVERSED_BACKWARD": "CircularWithReversedBackward", + } +) + +# Schedules a training step here cannot use, with the reason. Shardy's +# ParallelPipelinesWithWrapAround orders forward fragments only and aborts the +# process on a backward one (`SDY_CHECK(IsForwardFragment(...))` in +# pipeline_schedule.cc). The circular schedules order several logical stages +# per mesh, but the model places one contiguous chunk of layers on each stage +# (`models._unit_stages`), so they would run as GPipe under another name. +UNSUPPORTED_SCHEDULES = types.MappingProxyType( + { + "PARALLEL_PIPELINES_WITH_WRAP_AROUND": ( + "Shardy MPMD schedules only forward fragments with it, and aborts on a" " training step's backward fragments" + ), + "CIRCULAR": ( + "it needs several logical stages per mesh, and the model places one" + " contiguous chunk of layers per stage: it would run as GPipe" + ), + "CIRCULAR_WITH_REVERSED_BACKWARD": ( + "it needs several logical stages per mesh, and the model places one" + " contiguous chunk of layers per stage: it would run as GPipe" + ), + } +) + +# The schedules a training step here can use. +USABLE_SCHEDULES = tuple(name for name in PIPELINE_SCHEDULES if name not in UNSUPPORTED_SCHEDULES) + +# User-friendly aliases accepted on the command line. +_SCHEDULE_ALIASES = { + "1F1B": "ONE_FWD_ONE_BWD", + "1f1b": "ONE_FWD_ONE_BWD", + "GPIPE": "GPIPE", + "gpipe": "GPIPE", + "ZB_H1": "ZERO_BUBBLE_H1", + "ZB-H1": "ZERO_BUBBLE_H1", + "ZB_H2": "ZERO_BUBBLE_H2_ZERO_TX_LATENCY", + "ZB-H2": "ZERO_BUBBLE_H2_ZERO_TX_LATENCY", + "ZERO_BUBBLE_H2": "ZERO_BUBBLE_H2_ZERO_TX_LATENCY", + "ZB_H2_ZERO": "ZERO_BUBBLE_H2_ZERO_TX_LATENCY", + "ZB-H2-ZERO": "ZERO_BUBBLE_H2_ZERO_TX_LATENCY", + "ZB_H2_HALF": "ZERO_BUBBLE_H2_HALF_TX_LATENCY", + "ZB-H2-HALF": "ZERO_BUBBLE_H2_HALF_TX_LATENCY", + "ZB_H2_FULL": "ZERO_BUBBLE_H2_FULL_TX_LATENCY", + "ZB-H2-FULL": "ZERO_BUBBLE_H2_FULL_TX_LATENCY", + # Shardy MPMD's own spellings (`mpmd_pipeline_schedule` values), upper-cased. + "GPIPEBUT1F1BFORLASTMESH": "GPIPE_BUT_1F1B_FOR_LAST_MESH", + "ZEROBUBBLEH1": "ZERO_BUBBLE_H1", + "ZEROBUBBLEH2ZEROTXLATENCY": "ZERO_BUBBLE_H2_ZERO_TX_LATENCY", + "ZEROBUBBLEH2HALFTXLATENCY": "ZERO_BUBBLE_H2_HALF_TX_LATENCY", + "ZEROBUBBLEH2FULLTXLATENCY": "ZERO_BUBBLE_H2_FULL_TX_LATENCY", + "PARALLELPIPELINESWITHWRAPAROUND": "PARALLEL_PIPELINES_WITH_WRAP_AROUND", + "CIRCULARWITHREVERSEDBACKWARD": "CIRCULAR_WITH_REVERSED_BACKWARD", +} + + +def normalize_schedule(schedule: str) -> str: + """Maps a user-supplied schedule name onto a PartIR MPMD schedule. + + Args: + schedule: Schedule name or alias, case insensitive (e.g. ``1F1B``). + + Returns: + A schedule name guaranteed to be in :data:`PIPELINE_SCHEDULES`. + + Raises: + ValueError: If `schedule` is not a known schedule or alias. + """ + if schedule in _SCHEDULE_ALIASES: + return _SCHEDULE_ALIASES[schedule] + upper = schedule.upper() + if upper in _SCHEDULE_ALIASES: + return _SCHEDULE_ALIASES[upper] + if upper in PIPELINE_SCHEDULES: + return upper + raise ValueError( + f"Unknown pipeline schedule {schedule!r}. Expected one of" + f" {sorted(PIPELINE_SCHEDULES)} or an alias in" + f" {sorted(_SCHEDULE_ALIASES)}." + ) + + +@functools.lru_cache(maxsize=None) +def read_model_yaml_metadata(model_name: str) -> dict[str, Any]: + """Returns the settings in MaxText's ``configs/models/.yml``; ``{}`` for ``default`` and ``simple``. + + Read with ``omegaconf``, as pyconfig reads it, but without pyconfig, so that :mod:`hparams` and the launcher stay + free of JAX: the hyperparameters are checked against the model's decoder block, MoE layout and RoPE type before any + MaxText config is built. A key the model config leaves out takes base.yml's value in pyconfig, which is the default + each caller reads it with (``num_experts`` 1, ``first_num_dense_layers`` 0, ``interleave_moe_layer_step`` 1). + + Args: + model_name: MaxText model config name (e.g. ``llama3.1-8b``). + + Raises: + FileNotFoundError: If the model config does not exist. pyconfig would only log a warning and go on with base.yml's + defaults: the run would still *look* right (``model_name``, and the dimensions overridden explicitly), while + everything taken from the model config (``num_experts``, the MLA head counts and LoRA ranks, ``routed_bias``, + ``attention_type``) had quietly reverted; a ``deepseek3-test`` benchmark measured a generic 16-head dense model + and reported about 12x too few FLOPs. + """ + if model_name in ("simple", "default"): + return {} + yaml_path = os.path.join(MAXTEXT_CONFIGS_DIR, "models", f"{model_name}.yml") + if not os.path.exists(yaml_path): + raise FileNotFoundError( + f"MaxText model config {yaml_path!r} is missing, so model_name={model_name!r} would silently fall back to" + " base.yml defaults and measure a different model. Use a MaxText checkout that has this model, or a model name" + f" from {os.path.join(MAXTEXT_CONFIGS_DIR, 'models')}." + ) + return dict(omegaconf.OmegaConf.to_container(omegaconf.OmegaConf.load(yaml_path))) + + +def infer_decoder_block(model_name: str) -> str: + """Returns the ``decoder_block`` of MaxText's config of `model_name` (``simple_mlp`` for ``simple`` and ``default``). + + Args: + model_name: MaxText model config name (or the ``simple`` alias). + + Raises: + FileNotFoundError: If the model config does not exist (see :func:`read_model_yaml_metadata`). + ValueError: If the model config names no ``decoder_block``, as those of the models MaxText builds with its + separate m3 backend (``use_m3_model``) do. + """ + if model_name in ("simple", "default"): + return "simple_mlp" + block = read_model_yaml_metadata(model_name).get("decoder_block") + if not (isinstance(block, str) and block): + raise ValueError( + f"model_name={model_name}: its MaxText config names no decoder_block (those of the models MaxText builds" + " with its m3 backend, use_m3_model, name none), so the MPMD pipeline refuses it rather than train another" + f" architecture. Supported decoder blocks: {', '.join(SUPPORTED_DECODER_BLOCKS)}." + ) + return block + + +# The decoder blocks `models.PipelinedTransformer` builds and has been run with. +# Every other `DecoderBlockType` is refused rather than built: some need inputs +# or per-layer wiring the per-layer named computations do not pass (DeepSeek4's +# token inputs and hyper-connection head, Gemma4-Small's shared KV caches, GLM5's +# dense/MoE pair, Kimi-Linear's layer specs), and the rest have not run here. +# (`simple` and `default` model names build `simple_mlp`; no model config selects +# MaxText's `default` or `simple` blocks.) +SUPPORTED_DECODER_BLOCKS = ( + "simple_mlp", + "llama2", + "mistral", + "mixtral", + "qwen3", + "qwen3_moe", + "deepseek", +) + + +def unsupported_decoder_block(model_name: str, decoder_block: str) -> str | None: + """Returns why `decoder_block` cannot run here, or None if it is supported.""" + if decoder_block in SUPPORTED_DECODER_BLOCKS: + return None + return ( + f"model_name={model_name} uses decoder_block={decoder_block}, which the MPMD" + " pipeline does not build (it would train a different architecture than" + f" the one MaxText describes). Supported decoder blocks: {', '.join(SUPPORTED_DECODER_BLOCKS)}." + ) + + +def is_pure_moe_model(model_name: str, first_num_dense_layers: int = -1) -> bool: + """Returns whether every decoder layer of `model_name` uses an MoE MLP block. + + MaxText validates that ``base_mlp_dim == base_moe_mlp_dim`` when a model has + no dense MLP layers (or, for ``qwen3_moe``, overwrites ``base_mlp_dim`` with + ``base_moe_mlp_dim``). Keeping the two in sync when ``mlp_dim`` is overridden + without an explicit ``moe_mlp_dim`` ensures both MPMD and SPMD configure the + requested expert width. + + Args: + model_name: MaxText model config name, of a supported decoder block. + first_num_dense_layers: Number of leading dense layers override (-1 = + default from YAML). + """ + resolved_name = "default" if model_name == "simple" else model_name + if infer_decoder_block(resolved_name) in ("qwen3_moe", "mixtral"): + return True + meta = read_model_yaml_metadata(resolved_name) + if int(meta.get("num_experts", 1)) <= 1: + return False + dense_layers = first_num_dense_layers if first_num_dense_layers >= 0 else int(meta.get("first_num_dense_layers", 0)) + return dense_layers == 0 and int(meta.get("interleave_moe_layer_step", 1)) == 1 + + +# The `--remat_policy` values: the policies of MaxText's resolver +# (`NNXDecoder.get_remat_policy`, which `models` calls) that neither offload to +# host memory nor name quantization intermediates (every layer here is built +# unquantized). A literal, as this module stays free of JAX; models_test checks +# that MaxText's resolver accepts each. `none` is spelled by leaving --remat off. +REMAT_POLICIES = ( + "full", + "minimal", + "minimal_with_context", + "minimal_flash", + "save_dot_with_context_except_mlp", + "save_dot_except_mlpwi", + "save_dot_except_mlp", + "save_qkv_proj", + "save_out_proj", +) + + +# How routed tokens reach their expert shard when `expert > 1`: +# +# ragged_a2a : MaxText's default `jax.lax.ragged_all_to_all` over the +# `expert` axis (`sparse_matmul_with_all_to_all`), using +# megablox `gmm` on the received slice. +# ring_of_experts: `use_ring_of_experts` -- the tokens of the EP group are +# all-gathered first, each device sorts and runs only the +# tokens routed to its local experts with MaxText's +# SparseCore ragged-sort kernels (`use_ragged_sort`), and +# the expert outputs are reduce-scattered back. Moves +# `expert` x more activation bytes than `ragged_a2a`, +# but uses only all-gather / reduce-scatter. +# +# `ragged_a2a` is the default because it is MaxText's default. (In runs of the +# stack this was ported from, it halted the TPU on the first forward step on a +# TPU v7x 4x4x4 slice with `--expert=32` while `ring_of_experts` ran; not +# reproduced with this port.) +MOE_DISPATCH_MODES = ("ragged_a2a", "ring_of_experts") + + +def moe_dispatch_overrides(hparams: "Hparams") -> dict[str, Any]: + """MaxText config overrides implementing ``hparams.moe_dispatch``. + + Shared by ``config.build_maxtext_config`` (MPMD) and ``spmd_baseline`` so + both sides dispatch tokens to experts identically. Empty when + ``hparams.expert == 1``; ``ragged_a2a`` only forwards the expert degree and + the optional ``ragged_buffer_factor`` cap so it stays byte-identical to + MaxText's defaults. + + Args: + hparams: The run's hyperparameters. + + Returns: + ``{maxtext_key: value}`` overrides, with Python ``bool``/``int``/``float`` + values. + """ + if hparams.expert <= 1: + return {} + overrides: dict[str, Any] = {"ici_expert_parallelism": hparams.expert} + # `ragged_buffer_factor` sizes the routed-token buffer on every dispatch + # path; MaxText's own default is the worst case (-1.0), so only forward a + # cap. + if hparams.ragged_buffer_factor > 0: + overrides["ragged_buffer_factor"] = hparams.ragged_buffer_factor + if hparams.moe_dispatch == "ragged_a2a": + return overrides + # `use_ragged_sort` is valid on both paths (it restricts the local permute + # to the valid prefix of the buffer) but is only switched on with + # ring-of-experts. + overrides.update( + { + "use_ring_of_experts": True, + "use_ragged_sort": True, + "num_moe_token_chunks": hparams.num_moe_token_chunks, + } + ) + return overrides + + +# MaxText's MoE GMM tiles (base.yml: m x k x n = 512 x 1024 x 1024 for the +# forward, dlhs and drhs kernels alike) are sized for bfloat16. In float32 every +# buffer doubles and the kernel asks for 16.3 MiB of scoped VMEM, over v5p's +# 16 MiB default ("CompileTimeScopedVmemOom" when deepseek3-tiny's parity ran in +# float32). Halving the contracting and output tiles brings it back under the +# bfloat16 footprint; explicit `--maxtext_overrides` tiles still win. +_FLOAT32_GMM_TILES = { + f"{weight}_tile_{kernel}_{dim}": 512 + for weight in ("wi", "wo") + for kernel in ("fwd", "dlhs", "drhs") + for dim in ("embed_dim", "mlp_dim") +} + + +def override_value(hparams: "Hparams", key: str) -> str | None: + """Returns the last ``--maxtext_overrides`` value for `key`, or None.""" + value = None + for item in hparams.maxtext_overrides: + name, _, rhs = item.partition("=") + if name == key: + value = rhs + return value + + +def float32_gmm_tiles(hparams: "Hparams") -> dict[str, int]: + """Returns the GMM tile settings a float32 run needs (empty otherwise).""" + if override_value(hparams, "dtype") in ("float32", "fp32"): + return dict(_FLOAT32_GMM_TILES) + return {} + + +# What an XProf trace covers: one TPU, one SparseCore and one SparseCore tile a +# traced host, small enough to open. `benchmark.profile` hands it to +# jax.profiler, the SPMD baseline to MaxText's profiler +# (enable_tpu_profiling_options). +TRACE_ADVANCED_CONFIGURATION = types.MappingProxyType( + { + "tpu_num_chips_to_profile_per_task": 1, + "tpu_num_sparse_cores_to_trace": 1, + "tpu_num_sparse_core_tiles_to_trace": 1, + } +) + + +# MaxText settings that config.py derives from a hyperparameter (or must pin), +# with where to set them instead. A `--maxtext_overrides` of one of them would +# win in MaxText's config while the rest of the package (the optimizer's +# learning rate, the stage meshes, MPMD_RESULT, launch.py's checks) still used +# the hyperparameter. +OWNED_MAXTEXT_KEYS = types.MappingProxyType( + { + "model_name": "--model_name", + "base_num_decoder_layers": "--num_layers", + "per_device_batch_size": "--per_device_batch_size", + "max_target_length": "--max_target_length", + "ici_pipeline_parallelism": "--pp", + "dcn_pipeline_parallelism": "--pp", + "remat_policy": "--remat and --remat_policy", + "learning_rate": "--learning_rate", + "init_weights_seed": "--seed", + "base_emb_dim": "--emb_dim", + "base_mlp_dim": "--mlp_dim", + "base_moe_mlp_dim": "--moe_mlp_dim", + "vocab_size": "--vocab_size", + "ici_fsdp_parallelism": "--fsdp", + "ici_expert_parallelism": "--expert", + "use_ring_of_experts": "--moe_dispatch", + "ragged_buffer_factor": "--ragged_buffer_factor", + "num_moe_token_chunks": "--num_moe_token_chunks", + "first_num_dense_layers": "--first_num_dense_layers", + "decoder_block": "--model_name (it follows the model)", + "pipeline_parallel_layers": "--num_layers / --stage_layer_counts", + "scan_layers": "nothing: pipelining needs one computation per layer", + # MaxText replays the batch this many times and multiplies the analytic + # FLOP count (and so TFLOP/s and MFU) by it; microbatches here split it. + "gradient_accumulation_steps": "--num_microbatches", + "enable_dropout": "nothing: the MPMD model runs every layer deterministic", + "dropout_rate": "nothing: the MPMD model runs every layer deterministic", + } +) + + +def _rope_is_pinned(model_name: str) -> bool: + """Whether config.py pins `model_name`'s RoPE to ``rope_type=default``.""" + return infer_decoder_block(model_name) == "deepseek" or uses_yarn_rope(model_name) + + +def uses_yarn_rope(model_name: str) -> bool: + """Returns whether `model_name` configures complex-valued YaRN RoPE.""" + resolved_name = "default" if model_name == "simple" else model_name + return str(read_model_yaml_metadata(resolved_name).get("rope_type", "")).lower() == "yarn" + + +def parse_stage_layer_counts( + raw: str | Sequence[int], +) -> tuple[int, ...]: + """Parses a comma-separated string or integer sequence into stage counts. + + Args: + raw: Either a comma-separated string (e.g. ``"7,10,11,12"``) or a sequence + of integers. An empty string or empty sequence denotes uniform stage layer + counts. + + Returns: + A tuple of per-stage layer counts, or ``()`` when uniform. + + Raises: + ValueError: If any entry is not a valid integer. + """ + if isinstance(raw, str): + stripped = raw.strip() + if not stripped: + return () + parts = [p.strip() for p in stripped.split(",")] + if any(not p for p in parts): + raise ValueError(f"Invalid stage_layer_counts {raw!r}: expected comma-separated" " integers.") + try: + return tuple(int(p) for p in parts) + except ValueError as err: + raise ValueError(f"Invalid stage_layer_counts {raw!r}: expected comma-separated" " integers.") from err + return tuple(int(x) for x in raw) + + +@dataclasses.dataclass(frozen=True) +class Hparams: + """Model, parallelism and benchmarking hyperparameters. + + Attributes: + model_name: MaxText model config name (``deepseek3-tiny``, + ``deepseek2-16b``, ``llama3.1-8b``, ``mixtral-8x7b``, ``qwen3-30b-a3b``, + ``default``, ...) whose decoder block is in + :data:`SUPPORTED_DECODER_BLOCKS`. The alias ``simple`` is mapped onto + MaxText's ``default`` config. + num_layers: Total number of decoder layers spread across the pipeline. Its + default (8) applies to every model, real ones included. + emb_dim: Model (embedding) dimension. -1 keeps the model YAML value + (:func:`from_flags` passes -1 for a named model whose flag is not given). + mlp_dim: Feed-forward hidden dimension. -1 keeps the model YAML value. + moe_mlp_dim: MoE expert intermediate dimension. -1 keeps the model YAML + value (or matches ``mlp_dim`` on pure-MoE models). + per_device_batch_size: Batch size per device of a *single* stage mesh. + max_target_length: Sequence length. + vocab_size: Vocabulary size. -1 keeps the model YAML value. + num_stages: Pipeline depth, i.e. number of stage meshes. + fsdp: FSDP degree within each stage mesh; -1 means "use every device of the + stage mesh not taken by ``expert``". + expert: Expert-parallel degree within each stage mesh. MoE expert weights + are partitioned across this axis (each device owns ``num_experts / + expert`` whole experts) and tokens are routed to them with an all-to-all, + instead of every device all-gathering the full expert weights for every + microbatch. The batch is sharded over ``fsdp x expert`` devices either + way. 1 disables expert parallelism. + moe_dispatch: How routed tokens reach their expert shard when ``expert > + 1``; one of :data:`MOE_DISPATCH_MODES`. Ignored when ``expert == 1``. + ragged_buffer_factor: Capacity of the per-shard routed-token buffer as a + multiple of the perfectly balanced load. ``<= 0`` sizes it for the worst + case (never drops tokens, at ``min(expert, num_experts / top_k)`` x the + balanced size); ``> 0`` (e.g. ``2``) caps it and drops the overflow. + Ignored when ``expert == 1``. + num_moe_token_chunks: ``ring_of_experts`` only: split each microbatch's + routed tokens into this many chunks so one chunk's all-gather / + reduce-scatter overlaps the previous chunk's expert matmul. 1 disables. + num_microbatches: Number of microbatches per optimizer step. + pipeline_schedule: PartIR MPMD schedule name (already normalized). + first_num_dense_layers: For DeepSeek models, how many leading layers are + dense rather than MoE. -1 keeps the value from the model config. + remat: Whether to rematerialize (recompute) activations during the + backward pass, in both MPMD (a per-layer ``jax.checkpoint`` with + ``remat_policy``) and the SPMD baseline. + remat_policy: The MaxText rematerialisation policy each layer is + checkpointed with under ``remat``, one of :data:`REMAT_POLICIES`; the + SPMD baseline gets the same. Without ``remat`` no MPMD layer is + checkpointed, and MaxText's config, which refuses ``none`` with pipeline + parallelism, is handed ``full`` (``config.build_maxtext_config``). + steps: Number of timed training steps. + warmup_steps: Number of untimed warm-up steps run before timing. + learning_rate: AdamW learning rate. + seed: Seed for parameter initialisation and synthetic data. + stage_layer_counts: Optional per-stage decoder layer counts (e.g. ``(7, 10, + 11, 12)``). Empty tuple distributes ``num_layers`` uniformly across + ``num_stages``. + maxtext_overrides: ``key=value`` MaxText settings applied after everything + :mod:`config` derives, in order (e.g. ``("dtype=float32",)`` for a + float32 parity check). Both arms of ``parity.py`` get them. + """ + + model_name: str = "deepseek3-tiny" + num_layers: int = 8 + emb_dim: int = 512 + mlp_dim: int = 2048 + moe_mlp_dim: int = -1 + per_device_batch_size: float = 2.0 + max_target_length: int = 512 + vocab_size: int = 16384 + num_stages: int = 4 + fsdp: int = -1 + expert: int = 1 + moe_dispatch: str = "ragged_a2a" + ragged_buffer_factor: float = -1.0 + num_moe_token_chunks: int = 1 + num_microbatches: int = 4 + pipeline_schedule: str = "ONE_FWD_ONE_BWD" + first_num_dense_layers: int = -1 + remat: bool = False + remat_policy: str = "full" + steps: int = 5 + warmup_steps: int = 2 + learning_rate: float = 1e-3 + seed: int = 42 + stage_layer_counts: tuple[int, ...] | str = () + maxtext_overrides: tuple[str, ...] | str = () + + def __post_init__(self): + if self.num_stages <= 0: + raise ValueError(f"num_stages must be positive, got {self.num_stages}.") + if self.num_layers < self.num_stages: + raise ValueError( + f"num_layers ({self.num_layers}) must be >= num_stages" + f" ({self.num_stages}) so that every stage owns at least one layer." + ) + parsed_counts = parse_stage_layer_counts(self.stage_layer_counts) + object.__setattr__(self, "stage_layer_counts", parsed_counts) + if parsed_counts: + if len(parsed_counts) != self.num_stages: + raise ValueError( + f"stage_layer_counts ({parsed_counts}) must have length" + f" num_stages ({self.num_stages}), got {len(parsed_counts)}." + ) + if any(count <= 0 for count in parsed_counts): + raise ValueError(f"Every entry in stage_layer_counts ({parsed_counts}) must be" " positive.") + if sum(parsed_counts) != self.num_layers: + raise ValueError(f"sum(stage_layer_counts) ({sum(parsed_counts)}) must equal" f" num_layers ({self.num_layers}).") + elif self.num_layers % self.num_stages: + raise ValueError( + f"num_layers ({self.num_layers}) must be divisible by num_stages" + f" ({self.num_stages}) for a balanced pipeline." + ) + if self.num_microbatches <= 0: + raise ValueError(f"num_microbatches must be positive, got {self.num_microbatches}.") + if self.expert <= 0: + raise ValueError(f"expert must be positive, got {self.expert}.") + if self.moe_dispatch not in MOE_DISPATCH_MODES: + raise ValueError(f"moe_dispatch must be one of {MOE_DISPATCH_MODES}, got" f" {self.moe_dispatch!r}.") + if self.num_moe_token_chunks <= 0: + raise ValueError("num_moe_token_chunks must be positive, got" f" {self.num_moe_token_chunks}.") + # First, as the override checks below read the model config: a missing model config raises FileNotFoundError. + unsupported = unsupported_decoder_block(self.model_name, self.decoder_block) + if unsupported: + raise ValueError(unsupported) + overrides = self.maxtext_overrides + overrides = (overrides,) if isinstance(overrides, str) else tuple(overrides) + for item in overrides: + key, sep, _ = item.partition("=") + if not sep or not key or key != key.strip(): + raise ValueError(f"maxtext_overrides entry {item!r}: expected key=value.") + if key in OWNED_MAXTEXT_KEYS: + raise ValueError( + f"maxtext_overrides entry {item!r}: {key} is derived from the" + f" hyperparameters; set it with {OWNED_MAXTEXT_KEYS[key]}." + ) + if key == "rope_type" and _rope_is_pinned("default" if self.model_name == "simple" else self.model_name): + raise ValueError( + f"maxtext_overrides entry {item!r}: {self.model_name} asks for" + " YaRN RoPE, which config.py pins to rope_type=default (PartIR" + " MPMD asserts on its complex64 table)." + ) + if self.remat_policy not in REMAT_POLICIES: + raise ValueError( + f"remat_policy={self.remat_policy} is not one the MPMD model checkpoints its layers with:" + f" {', '.join(REMAT_POLICIES)} (MaxText's, except those that offload to host memory or save quantization" + " intermediates). Without --remat no layer is rematerialised." + ) + schedule = normalize_schedule(self.pipeline_schedule) + if schedule in UNSUPPORTED_SCHEDULES: + raise ValueError(f"pipeline_schedule {schedule} is not supported here:" f" {UNSUPPORTED_SCHEDULES[schedule]}.") + # `object.__setattr__` because the dataclass is frozen. + object.__setattr__(self, "maxtext_overrides", overrides) + object.__setattr__(self, "pipeline_schedule", schedule) + + @property + def layers_per_stage(self) -> int: + """Returns the nominal uniform number of decoder layers per stage.""" + return self.num_layers // self.num_stages + + @property + def mpmd_remat_policy(self) -> str: + """Returns the policy the MPMD model checkpoints each layer with: ``remat_policy`` under ``remat``, else none.""" + return self.remat_policy if self.remat else "none" + + @property + def maxtext_model_name(self) -> str: + """Returns the MaxText config name, resolving the ``simple`` alias.""" + return "default" if self.model_name == "simple" else self.model_name + + @property + def decoder_block(self) -> str: + """Returns the MaxText ``decoder_block`` name for ``model_name``.""" + return infer_decoder_block(self.maxtext_model_name) + + +def devices_in_device_type(device_type: str) -> int: + """Returns the JAX device count of an xpk device type, or 0 if unknown. + + ``v5p-N`` / ``v4-N`` count TensorCores (two per chip, one megacore JAX device + per chip), ``v5litepod-N`` / ``v6e-N`` count chips, and ``tpu7x-AxBxC`` + names the chip box (two JAX devices per chip). ``=`` + strings fall back to :func:`devices_in_platform`. + + Args: + device_type: For example ``v5p-32`` or ``tpu7x-4x4x4``. + """ + if "=" in device_type: + return devices_in_platform(device_type) + gen, _, size = device_type.partition("-") + if not size: + return 0 + if "x" in size: + chips = 1 + for dim in size.split("x"): + if not dim.isdigit(): + return 0 + chips *= int(dim) + return 2 * chips if gen.startswith("tpu7") else chips + if not size.isdigit(): + return 0 + count = int(size) + return count // 2 if gen in ("v5p", "v4") else count + + +def devices_in_platform(platform: str) -> int: + """Returns the chip count implied by a ``=`` string. + + This is the product of the topology dimensions, i.e. the number of *chips*. + On platforms that expose more than one core per chip it is not the number of + JAX devices; callers who need that must pass it explicitly. + + Args: + platform: A ``=`` string. + + Returns: + The product of the topology dimensions, or 0 if it cannot be parsed. + """ + if "=" not in platform: + return 0 + _, _, topology = platform.partition("=") + total = 1 + for dimension in topology.split("x"): + if not dimension.isdigit(): + return 0 + total *= int(dimension) + return total + + +def check_microbatch_split(hparams: Hparams, *, devices_per_stage: int, data_parallel_size: int) -> None: + """Raises unless every microbatch splits evenly over a stage's batch-sharding devices. + + MaxText's TPU flash attention asserts that the batch divides over the + ``fsdp`` x ``expert`` devices; a CPU lowering (dot-product attention) does + not, so without this check the mistake surfaces only once the TPUs run. The + deferred MoE expert-gradient reduce-scatter (``models.pregather_params``) also + needs it. + + Args: + hparams: The configuration to run. + devices_per_stage: Devices of one stage mesh (the batch is data-parallel over + one stage). + data_parallel_size: Devices of a stage the batch is sharded over (``fsdp`` x + ``expert``). + + Raises: + ValueError: If the global batch does not split into the microbatches, or a + microbatch not over the data-parallel devices. + """ + global_batch = int(hparams.per_device_batch_size * devices_per_stage) + micro = global_batch // hparams.num_microbatches + if global_batch % hparams.num_microbatches or micro % max(data_parallel_size, 1): + raise ValueError( + f"Global batch {global_batch} (per_device_batch_size {hparams.per_device_batch_size} x" + f" {devices_per_stage} devices per stage) in {hparams.num_microbatches} microbatches gives {micro} sequences" + f" per microbatch, which must be a multiple of the {data_parallel_size} devices its batch is sharded over" + " (MaxText's TPU attention asserts it)." + ) + + +def check_microbatch_split_on(hparams: Hparams, num_devices: int) -> None: + """:func:`check_microbatch_split` for `num_devices` split into stages as ``mesh_utils.create_stage_meshes`` does. + + Each stage gets ``num_devices / num_stages`` devices, and its batch is sharded over ``fsdp x expert`` of them + (``fsdp=-1``: every device not taken by ``expert``). + + Raises: + ValueError: See :func:`check_microbatch_split`. + """ + devices_per_stage = num_devices // hparams.num_stages + fsdp = hparams.fsdp if hparams.fsdp > 0 else devices_per_stage // hparams.expert + check_microbatch_split(hparams, devices_per_stage=devices_per_stage, data_parallel_size=fsdp * hparams.expert) + + +def ragged_buffer_note(hparams: Hparams) -> str | None: + """Returns a note when MoE dispatch buffers are sized for the worst case, else None.""" + if hparams.expert <= 1 or hparams.ragged_buffer_factor > 0: + return None + return ( + "--expert > 1 with --ragged_buffer_factor <= 0 sizes every MoE dispatch buffer for the worst case" + " (min(expert, experts / top_k) x the balanced load: 98304 rows per layer and microbatch for deepseek2-16b at" + " --expert=8, which filled stage 0's HBM on a v5p-64). For a large MoE, consider --ragged_buffer_factor=2 (it" + " drops tokens past twice the balanced load)." + ) + + +# Flags forwarded verbatim from the launcher (`launch.py`) to the trainer. +# `pp` is deliberately excluded: it is folded into `num_stages` below. +FORWARDED_FLAGS = ( + "model_name", + "num_layers", + "emb_dim", + "mlp_dim", + "moe_mlp_dim", + "per_device_batch_size", + "max_target_length", + "vocab_size", + "num_stages", + "fsdp", + "expert", + "moe_dispatch", + "ragged_buffer_factor", + "num_moe_token_chunks", + "num_microbatches", + "pipeline_schedule", + "first_num_dense_layers", + "remat", + "remat_policy", + "steps", + "warmup_steps", + "learning_rate", + "seed", + "stage_layer_counts", + "maxtext_overrides", +) + + +def define_flags(flag_values: flags.FlagValues = flags.FLAGS) -> None: + """Registers the hyperparameter flags on `flag_values`; a second call is a no-op. + + Entry points call it before parsing their command line; tests pass a fresh + ``flags.FlagValues()`` so that nothing is registered on the global + ``flags.FLAGS`` of a shared test process. + + Args: + flag_values: Where to register the flags. + """ + if "num_microbatches" in flag_values: + return + # The dataclass defaults are the flag defaults. + defaults = Hparams() + fv = {"flag_values": flag_values} + flags.DEFINE_string( + "model_name", + defaults.model_name, + "MaxText model config name (e.g. simple, deepseek3-tiny, deepseek2-16b, llama3.1-8b, mixtral-8x7b," + f" qwen3-30b-a3b); its decoder block must be one of {', '.join(SUPPORTED_DECODER_BLOCKS)}.", + **fv, + ) + flags.DEFINE_integer( + "num_layers", + defaults.num_layers, + "Total number of decoder layers, for every model: pass a model's own count (32 for llama3.1-8b) to train all" + " of it.", + **fv, + ) + # See from_flags: only the toy models take these flags' defaults. + toy = "The flag's default is for the toy models (simple, default, deepseek3-tiny); others keep their config's value" + flags.DEFINE_integer( + "emb_dim", defaults.emb_dim, f"Embedding (model) dimension. {toy} unless the flag is given (-1 keeps it).", **fv + ) + flags.DEFINE_integer( + "mlp_dim", defaults.mlp_dim, f"Feed-forward hidden dimension. {toy} unless the flag is given (-1 keeps it).", **fv + ) + flags.DEFINE_integer( + "moe_mlp_dim", defaults.moe_mlp_dim, "MoE expert hidden dimension (-1 keeps the model config value).", **fv + ) + flags.DEFINE_float( + "per_device_batch_size", defaults.per_device_batch_size, "Batch size per device of a single stage mesh.", **fv + ) + flags.DEFINE_integer("max_target_length", defaults.max_target_length, "Sequence length.", **fv) + flags.DEFINE_integer( + "vocab_size", defaults.vocab_size, f"Vocabulary size. {toy} unless the flag is given (-1 keeps it).", **fv + ) + flags.DEFINE_integer("num_stages", defaults.num_stages, "Pipeline depth (number of stages).", **fv) + flags.DEFINE_integer("pp", -1, "Alias for --num_stages. Takes precedence when > 0.", **fv) + flags.DEFINE_integer( + "fsdp", + defaults.fsdp, + "FSDP degree within each stage mesh (-1 = all devices of the stage not taken by --expert).", + **fv, + ) + flags.DEFINE_integer( + "expert", + defaults.expert, + "Expert-parallel degree within each stage mesh: MoE experts are partitioned across this many devices and tokens" + " are all-to-all'd to them, instead of FSDP-gathering the expert weights every microbatch. Must divide" + " num_experts; 1 disables expert parallelism.", + **fv, + ) + flags.DEFINE_enum( + "moe_dispatch", + defaults.moe_dispatch, + MOE_DISPATCH_MODES, + "How routed tokens reach their expert shard when --expert > 1. ragged_a2a: jax.lax.ragged_all_to_all (MaxText" + " default). ring_of_experts: all-gather the EP group's tokens, SparseCore ragged-sort the local experts' share," + " reduce-scatter the outputs.", + **fv, + ) + flags.DEFINE_float( + "ragged_buffer_factor", + defaults.ragged_buffer_factor, + "Routed-token buffer capacity per expert shard as a multiple of the balanced load. <= 0: worst case, never" + " drops. > 0 (e.g. 2): capped, drops overflow.", + **fv, + ) + flags.DEFINE_integer( + "num_moe_token_chunks", + defaults.num_moe_token_chunks, + "ring_of_experts only: chunks per microbatch so one chunk's all-gather / reduce-scatter overlaps the previous" + " chunk's expert matmul. 1 disables.", + **fv, + ) + flags.DEFINE_integer("num_microbatches", defaults.num_microbatches, "Number of microbatches per optimizer step.", **fv) + flags.DEFINE_string( + "pipeline_schedule", + defaults.pipeline_schedule, + f"Pipeline schedule. Accepts aliases such as 1F1B. One of: {', '.join(USABLE_SCHEDULES)} (the other OSS" + " schedules cannot run a training step here; see UNSUPPORTED_SCHEDULES).", + **fv, + ) + flags.DEFINE_integer( + "first_num_dense_layers", + defaults.first_num_dense_layers, + "DeepSeek only: number of leading dense (non-MoE) layers. -1 keeps the model config value.", + **fv, + ) + flags.DEFINE_boolean( + "remat", + defaults.remat, + "Rematerialize each layer's activations in the backward pass (jax.checkpoint with --remat_policy). Off by" + " default; without it stage 0 ran out of HBM for mixtral-8x7b on a v5p-64 and llama3.1-8b on a v6e-16" + " (per_device_batch_size 8, seq 2048).", + **fv, + ) + flags.DEFINE_string( + "remat_policy", + defaults.remat_policy, + "MaxText rematerialisation policy each layer is checkpointed with under --remat: one of" + f" {', '.join(REMAT_POLICIES)}.", + **fv, + ) + flags.DEFINE_integer("steps", defaults.steps, "Number of timed training steps.", **fv) + flags.DEFINE_integer("warmup_steps", defaults.warmup_steps, "Number of untimed warm-up steps run before timing.", **fv) + flags.DEFINE_float("learning_rate", defaults.learning_rate, "AdamW learning rate.", **fv) + flags.DEFINE_integer("seed", defaults.seed, "Seed for initialisation and synthetic data.", **fv) + flags.DEFINE_string( + "stage_layer_counts", + "", + "Optional comma-separated per-stage decoder layer counts (e.g. '7,10,11,12'). Empty distributes num_layers" + " uniformly across stages.", + **fv, + ) + flags.DEFINE_multi_string( + "maxtext_overrides", + [], + "key=value MaxText setting applied after everything config.py derives; repeatable, e.g." + " --maxtext_overrides=dtype=float32 for a float32 parity check (both arms get it).", + **fv, + ) + + +def from_flags(flag_values: flags.FlagValues = flags.FLAGS) -> Hparams: + """Builds an :class:`Hparams` from parsed flags registered by :func:`define_flags`.""" + fv = flag_values + num_stages = fv.pp if fv.pp > 0 else fv.num_stages + model_name = fv.model_name + # The toy models take the flags' small dimensions; a real model keeps its + # config's unless a dimension is passed explicitly. + is_toy_model = model_name in ("deepseek3-tiny", "simple", "default") + emb_dim = fv.emb_dim if (is_toy_model or fv["emb_dim"].present) else -1 + mlp_dim = fv.mlp_dim if (is_toy_model or fv["mlp_dim"].present) else -1 + vocab_size = fv.vocab_size if (is_toy_model or fv["vocab_size"].present) else -1 + return Hparams( + model_name=model_name, + num_layers=fv.num_layers, + emb_dim=emb_dim, + mlp_dim=mlp_dim, + moe_mlp_dim=fv.moe_mlp_dim, + per_device_batch_size=fv.per_device_batch_size, + max_target_length=fv.max_target_length, + vocab_size=vocab_size, + num_stages=num_stages, + fsdp=fv.fsdp, + expert=fv.expert, + moe_dispatch=fv.moe_dispatch, + ragged_buffer_factor=fv.ragged_buffer_factor, + num_moe_token_chunks=fv.num_moe_token_chunks, + num_microbatches=fv.num_microbatches, + pipeline_schedule=fv.pipeline_schedule, + first_num_dense_layers=fv.first_num_dense_layers, + remat=fv.remat, + remat_policy=fv.remat_policy, + steps=fv.steps, + warmup_steps=fv.warmup_steps, + learning_rate=fv.learning_rate, + seed=fv.seed, + stage_layer_counts=fv.stage_layer_counts, + maxtext_overrides=tuple(fv.maxtext_overrides), + ) + + +def to_job_args(hparams: Hparams) -> dict[str, object]: + """Returns the worker-binary command line for `hparams`. + + Used by the launcher (`launch.py`) so the flags sent to the Pathways job are + derived from the same dataclass the trainer parses them back into. + + Args: + hparams: Hyperparameters to serialise. + + Returns: + A mapping of flag name to value (``--name=value`` on the command line; a + list value is a repeated flag, one ``--name=item`` per item). + """ + as_dict = dataclasses.asdict(hparams) + as_dict["stage_layer_counts"] = ",".join(str(c) for c in hparams.stage_layer_counts) + as_dict["maxtext_overrides"] = list(hparams.maxtext_overrides) + return {name: as_dict[name] for name in FORWARDED_FLAGS} + + +def job_argv(args: dict[str, object]) -> list[str]: + """Renders :func:`to_job_args`-style ``{name: value}`` as ``--flags``.""" + out = [] + for name, value in args.items(): + if isinstance(value, bool): + out.append(f"--{name}" if value else f"--no{name}") + elif isinstance(value, (list, tuple)): + out += [f"--{name}={item}" for item in value] + else: + out.append(f"--{name}={value}") + return out + + +def read_xla_flags_file(path: str) -> dict[str, str]: + """Reads XLA / libtpu flags from `path`: one ``--key=value`` per line. + + Blank lines and ``#`` comment lines are skipped. No flag set is built in: a + run passes the one its slice needs with ``--xla_flags_file``. + + Args: + path: The flags file. + + Returns: + ``{key: value}`` in file order, keys without the leading dashes. + + Raises: + ValueError: If a line is not ``--key=value``. + """ + flags_by_key: dict[str, str] = {} + with open(path, encoding="utf-8") as handle: + for number, raw in enumerate(handle, 1): + line = raw.strip() + if not line or line.startswith("#"): + continue + key, sep, value = line[2:].partition("=") + if not line.startswith("--") or not sep or not key: + raise ValueError(f"{path}:{number}: expected --key=value, got {line!r}") + flags_by_key[key] = value + return flags_by_key diff --git a/src/maxtext/experimental/mpmd/partir/launch.py b/src/maxtext/experimental/mpmd/partir/launch.py new file mode 100644 index 0000000000..72981d9f11 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/launch.py @@ -0,0 +1,506 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +r"""Prints (or runs) the command that runs a partir entry point on GKE through Pathways. + +The command is ``gcluster job submit --pathways`` (Cluster Toolkit, MaxText's +launcher for GKE; ``--launcher=gcluster``, the default), after ``gcluster job +config set`` of the project, cluster and location, or ``xpk workload +create-pathways`` (``--launcher=xpk``; MaxText has deprecated XPK): one JobSet +whose head pod runs the Pathways resource manager, the IFRT proxy and the entry +point, while the TPU slices run Pathways workers. ``--device_type`` names each +slice; gcluster's ``--compute-type`` and ``--topology`` are each derived from it +(:func:`gcluster_slice`) unless ``--gcluster_compute_type`` or +``--gcluster_topology`` gives it. ``--module`` picks the entry point: +``train`` (the default), ``parity`` (MPMD vs SPMD) or ``train_compile`` (compile +on the slices' Pathways backend and log the memory report; +``--compile_topology=local`` is added). Arguments after ``--`` go to the entry +point verbatim, e.g. ``-- --loss_tolerance=1e-3`` for ``parity``. + +The image (``--docker_image``) must hold this MaxText tree and the Shardy MPMD +frontend that matches its jaxlib (``sdy_mpmd_compat.py``), and the Pathways +images (``--pathways_tag``) must match its jax. gcluster v1.108.0 and v1.109.0 +run a successful Pathways job twice and then mark it Failed +(:data:`GCLUSTER_RESTART_WARNING`, which the launcher logs). + +The model and pipeline flags are not redeclared here: :func:`hparams.define_flags` +registers them, and :func:`hparams.to_job_args` serialises them back out for the +entry point, so the launcher can never pass a flag the entry point does not +accept. The launcher checks what would otherwise fail only once the slices are +up: the workload name's length, how stages and slices divide, and whether each +microbatch splits over a stage's batch-sharding devices. + +Example (PP=4 x FSDP=2 on a v5p-16, i.e. 8 chips on 2 hosts):: + + python3 -m maxtext.experimental.mpmd.partir.launch \ + --cluster= --project= --zone= \ + --docker_image= --pathways_gcs_location=gs:///pathways \ + --device_type=v5p-16 --workload=mpmd-pp4 \ + --pp=4 --fsdp=2 --num_microbatches=8 --per_device_batch_size=8 \ + --model_name=deepseek3-tiny --num_layers=8 # prints the command + ... --submit # runs it + ... --module=parity --submit -- --loss_tolerance=1e-3 +""" + +from __future__ import annotations + +from collections.abc import Sequence +import math +import re +import shlex +import subprocess + +from absl import app +from absl import flags + +from maxtext.utils import accelerator_to_spec_map +from maxtext.utils import max_logging + +from maxtext.experimental.mpmd.partir import hparams as hparams_lib + +# The newest Pathways images known to compile Shardy MPMD's IFRT IR from a jax +# 0.12.0.1 client: the 20261118, 20261120 and 20261124 jax_0.12.0.1 images +# reject it ("Failed to parse IFRT IR module string"). +DEFAULT_PATHWAYS_TAG = "20261117-jax_0.12.0.1" +# Since cluster-toolkit #6528 (in v1.108.0 and v1.109.0), a Pathways batch job's workers have restartPolicy Never and +# backoffLimit 0. A Pathways worker exits when its client disconnects, so at the end of a successful run the worker Job +# fails before the head Job completes, and JobSet, which acts on a failed Job first, restarts the whole JobSet. +GCLUSTER_RESTART_WARNING = ( + "gcluster v1.108.0 and v1.109.0 give a Pathways job's workers restartPolicy Never, and a Pathways worker exits when" + " its client disconnects: when the entry point ends, even successfully, the worker Job fails, the JobSet restarts," + " the entry point runs a second time, and the JobSet ends Failed. cluster-toolkit PR #6739 (merged into develop on" + " 2026-11-25; not in v1.109.0) fixes it: use a gcluster built with it, or --launcher=xpk." +) +PATHWAYS_IMAGES = "us-docker.pkg.dev/cloud-tpu-v2-images/pathways" +# xpk's Pathways JobSet labels every pod `-pathways-head-0-0.`, a +# Kubernetes label of at most 63 characters: 2 * len(name) + 19 <= 63. +MAX_PATHWAYS_NAME = 22 +# A DNS-1035 label, which starts with a letter: xpk's workload names, and the +# Job names JobSet's admission webhook builds from the name (`--`). +_NAME = re.compile(r"[a-z]([a-z0-9-]*[a-z0-9])?") +# `gcluster job submit --compute-type` of each TPU generation (the GCE machine types MaxText's +# run_maxtext_via_pathways.md and run_maxtext_via_cluster_toolkit.md name), by --device_type prefix. +GCLUSTER_COMPUTE_TYPES = { + "tpu7x": "tpu7x-standard-4t", + "v6e": "ct6e-standard-4t", + "v5p": "ct5p-hightpu-4t", + "v5e": "ct5lp-hightpu-4t", + "v5litepod": "ct5lp-hightpu-4t", + "v4": "ct4p-hightpu-4t", +} +# Every compute type above is a host of 4 chips, in a chip box of 3 dimensions (TPU7x, v5p, v4) or 2 (v6e, v5e). +_GCLUSTER_CHIPS_PER_HOST = 4 +_TOPOLOGY_DIMENSIONS = {"tpu7x": 3, "v5p": 3, "v4": 3, "v6e": 2, "v5e": 2, "v5litepod": 2} +# The flags every launcher needs. +_REQUIRED = ("cluster", "project", "zone", "docker_image", "pathways_gcs_location", "device_type", "workload") +# The launcher's own flags: none of them may be passed after `--`. +_OWN_FLAGS = ( + "module", + "launcher", + "cluster", + "project", + "zone", + "docker_image", + "pathways_gcs_location", + "pathways_tag", + "device_type", + "num_slices", + "workload", + "gcluster_compute_type", + "gcluster_topology", + "extra_xla_flags", + "xla_flags_file", + "launcher_args", + "enable_profile", + "profile_steps", + "profile_dir", + "peak_tflops_per_device", + "submit", +) + + +def define_flags(flag_values: flags.FlagValues = flags.FLAGS) -> None: + """Registers the launcher's flags, the hyperparameters' included, on `flag_values`.""" + hparams_lib.define_flags(flag_values) + fv = {"flag_values": flag_values} + flags.DEFINE_enum( + "module", + "train", + ["train", "parity", "train_compile"], + "Entry point to run: maxtext.experimental.mpmd.partir..", + **fv, + ) + flags.DEFINE_enum( + "launcher", + "gcluster", + ["gcluster", "xpk"], + "gcluster: `gcluster job submit --pathways` (Cluster Toolkit), after `gcluster job config set` of the project," + " cluster and zone. xpk: `xpk workload create-pathways` (MaxText has deprecated XPK).", + **fv, + ) + flags.DEFINE_string("cluster", "", "GKE cluster (required).", **fv) + flags.DEFINE_string("project", "", "GCP project of the cluster (required).", **fv) + flags.DEFINE_string("zone", "", "Zone (or region) of the cluster (required).", **fv) + flags.DEFINE_string( + "docker_image", + "", + "Image of the head pod's user container (required): this MaxText tree, and the shardy-mpmd frontend that" + " matches its jaxlib.", + **fv, + ) + flags.DEFINE_string( + "pathways_gcs_location", + "", + "gs:// scratch location of the Pathways servers (required); it holds their persistent compilation cache.", + **fv, + ) + flags.DEFINE_string( + "pathways_tag", + DEFAULT_PATHWAYS_TAG, + f"Tag of the Pathways server and proxy_server images ({PATHWAYS_IMAGES}/...); it must match the jax version in" + " --docker_image.", + **fv, + ) + flags.DEFINE_string( + "device_type", + "", + "TPU type of each slice (required), e.g. v5p-16, v6e-16, tpu7x-128 or tpu7x-4x4x4: xpk's --tpu-type, and what" + " gcluster's --compute-type and --topology are derived from.", + **fv, + ) + flags.DEFINE_integer("num_slices", 1, "Number of TPU slices.", **fv) + flags.DEFINE_string( + "workload", + "", + f"Workload name (required): a lowercase letter, then lowercase letters, digits and '-', at most" + f" {MAX_PATHWAYS_NAME} characters for a Pathways JobSet; also the trainer's --run_name.", + **fv, + ) + flags.DEFINE_string( + "gcluster_compute_type", + "", + "--launcher=gcluster: the slices' --compute-type, e.g. ct5p-hightpu-4t; empty derives it from --device_type.", + **fv, + ) + flags.DEFINE_string( + "gcluster_topology", + "", + "--launcher=gcluster: the slices' --topology, e.g. 2x2x2; empty derives it from --device_type.", + **fv, + ) + flags.DEFINE_multi_string( + "extra_xla_flags", + [], + "key=value XLA flag for the Pathways proxy server (which compiles the TPU programs), resource manager and" + " workers; repeatable, applied after --xla_flags_file.", + **fv, + ) + flags.DEFINE_string( + "xla_flags_file", + "", + "File of --key=value XLA flags, one per line with # comments, for the Pathways proxy server, resource manager" + " and workers.", + **fv, + ) + flags.DEFINE_multi_string( + "launcher_args", [], "Argument appended verbatim to the xpk or gcluster command, e.g. --priority=low.", **fv + ) + flags.DEFINE_boolean("enable_profile", False, "train: capture an XProf trace (needs --profile_dir).", **fv) + flags.DEFINE_integer("profile_steps", 3, "train: extra steps run under the profiler (not timed).", **fv) + flags.DEFINE_string("profile_dir", "", "train: gs:// directory for the trace (/).", **fv) + flags.DEFINE_float( + "peak_tflops_per_device", + 0.0, + "train: hardware peak TFLOP/s per JAX device (on TPU7x, half a chip's), for MFU.", + **fv, + ) + flags.DEFINE_boolean("submit", False, "Run the command(s) instead of printing them.", **fv) + + +def xla_server_args(flag_values: flags.FlagValues) -> str: + """Returns the ``--key=value`` XLA flags for the Pathways servers, joined by single spaces.""" + xla_args: dict[str, str] = {} + if flag_values.xla_flags_file: + xla_args.update(hparams_lib.read_xla_flags_file(flag_values.xla_flags_file)) + for item in flag_values.extra_xla_flags: + key, sep, value = item.lstrip("-").partition("=") + if not sep or not key: + raise app.UsageError(f"Expected --extra_xla_flags entry of the form key=value, got {item!r}.") + xla_args[key] = value + return " ".join(f"--{key}={value}" for key, value in xla_args.items()) + + +def module_args(hparams: hparams_lib.Hparams, flag_values: flags.FlagValues, extra: Sequence[str] = ()) -> list[str]: + """Returns the command line of ``maxtext.experimental.mpmd.partir.`` for this run. + + Args: + hparams: The configuration to run. + flag_values: The launcher's parsed flags. + extra: Arguments passed after ``--``: flags only the entry point defines + (e.g. parity's ``--loss_tolerance``), as ``--flag=value``, appended + verbatim. + + Raises: + app.UsageError: If an extra argument is not a ``--flag``, or is a + hyperparameter or launcher flag. Those go before ``--``, where they are + validated; after it they would silently override the validated values. + """ + module = flag_values.module + args = dict(hparams_lib.to_job_args(hparams)) + if module == "train": + args.update( + enable_profile=flag_values.enable_profile, + profile_steps=flag_values.profile_steps, + profile_dir=flag_values.profile_dir, + peak_tflops_per_device=flag_values.peak_tflops_per_device, + run_name=flag_values.workload, + ) + elif module == "train_compile": + # The head pod's only backend is the Pathways proxy: no fake CPU devices. + args["compile_topology"] = "local" + reserved = set(hparams_lib.FORWARDED_FLAGS) | {"pp"} | set(_OWN_FLAGS) + for item in extra: + if not item.startswith("--"): + raise app.UsageError(f"Arguments after -- go to {module} and must be --flags, got {item!r}.") + name = item[2:].partition("=")[0] + if name in reserved or name.removeprefix("no") in reserved: + raise app.UsageError(f"{item!r} is a hyperparameter or launcher flag: pass it before --, where it is validated.") + return hparams_lib.job_argv(args) + list(extra) + + +def gcluster_topology(device_type: str) -> tuple[str, int]: + """Returns gcluster's ``--topology`` for a slice of `device_type`, and the number of chips on each of its hosts. + + The topology is the chip box: the name's own (``tpu7x-4x4x4``), or MaxText's for the type + (``accelerator_to_spec_map``: ``v5p-16`` is 2x2x2, ``v6e-16`` 4x4, ``tpu7x-128`` 4x4x4). + + Args: + device_type: A TPU type such as ``v5p-16`` or ``tpu7x-4x4x4``. + + Raises: + ValueError: If the slice is not known: a generation not in :data:`GCLUSTER_COMPUTE_TYPES`, a type MaxText does not + know (``v5p-12345``), or a topology with the wrong number of dimensions for its generation (``tpu7x-4x4``) or + with a dimension that is not a positive integer (``v5p-2x2x0``). + """ + generation, _, size = device_type.partition("-") + if generation not in GCLUSTER_COMPUTE_TYPES: + raise ValueError(f"{generation!r} is not one of the known TPU generations ({', '.join(GCLUSTER_COMPUTE_TYPES)})") + if "x" in size: + dimensions = size.split("x") + expected = _TOPOLOGY_DIMENSIONS[generation] + if len(dimensions) != expected: + raise ValueError(f"a {generation} topology has {expected} dimensions ({'x'.join('ABC'[:expected])}), not {size!r}") + for dimension in dimensions: + if not (dimension.isdecimal() and int(dimension) > 0): + raise ValueError(f"a topology's dimensions are positive integers, not {dimension!r} (in {size!r})") + return size, min(math.prod(map(int, dimensions)), _GCLUSTER_CHIPS_PER_HOST) + name = f"v5e-{size}" if generation == "v5litepod" else device_type + spec = accelerator_to_spec_map.UserFacingNameToSystemCharacteristics.get(name) + if spec is None or not spec.topology_name or not spec.chips_per_host_bounds: + raise ValueError(f"MaxText knows no {device_type} slice (maxtext.utils.accelerator_to_spec_map)") + return spec.topology_name.partition(":")[2], math.prod(spec.chips_per_host_bounds) + + +def gcluster_slice(device_type: str) -> tuple[str, str]: + """Returns gcluster's ``(--compute-type, --topology)`` for a slice of `device_type`. + + The compute type is the generation's host of 4 chips (:data:`GCLUSTER_COMPUTE_TYPES`); the topology is + :func:`gcluster_topology`'s. + + Args: + device_type: A TPU type such as ``v5p-16`` or ``tpu7x-4x4x4``. + + Raises: + ValueError: If the slice is not known (see :func:`gcluster_topology`), or its hosts do not have 4 chips + (``v6e-1``, ``tpu7x-2``). + """ + topology, chips_per_host = gcluster_topology(device_type) + compute_type = GCLUSTER_COMPUTE_TYPES[device_type.partition("-")[0]] + if chips_per_host != _GCLUSTER_CHIPS_PER_HOST: + raise ValueError( + f"a {topology} slice has {chips_per_host}-chip hosts, and {compute_type} is a host of" + f" {_GCLUSTER_CHIPS_PER_HOST} chips" + ) + return compute_type, topology + + +def gcluster_options(flag_values: flags.FlagValues) -> tuple[str, str]: + """Returns ``(--compute-type, --topology)`` for gcluster: each the flag's, else derived from ``--device_type``. + + Only a value no flag gives is derived: with ``--gcluster_compute_type`` alone, just the topology, so that compute + type is not checked against the slice's hosts. + + Raises: + app.UsageError: If a value no flag gives cannot be derived. The error names only the flags that are needed: just + ``--gcluster_compute_type`` when the slice is known but its hosts do not have 4 chips. + """ + fv = flag_values + compute_type, topology = fv.gcluster_compute_type, fv.gcluster_topology + if compute_type and topology: + return compute_type, topology + try: + derived_topology, _ = gcluster_topology(fv.device_type) + except ValueError as error: + # Neither value can be derived from a slice that is not known. + missing = [f"--{name}" for name in ("gcluster_compute_type", "gcluster_topology") if not fv[name].value] + raise app.UsageError(f"--device_type={fv.device_type}: {error}; pass {' and '.join(missing)}.") from error + if not compute_type: + try: + compute_type, _ = gcluster_slice(fv.device_type) + except ValueError as error: + raise app.UsageError(f"--device_type={fv.device_type}: {error}; pass --gcluster_compute_type.") from error + return compute_type, topology or derived_topology + + +def gcluster_config_commands(project: str, cluster: str, zone: str) -> list[list[str]]: + """Returns the ``gcluster job config set`` commands that point ``gcluster job submit`` at the cluster.""" + return [ + ["gcluster", "job", "config", "set", "project", project], + ["gcluster", "job", "config", "set", "cluster", cluster], + ["gcluster", "job", "config", "set", "location", zone], + ] + + +def check_workload_name(workload: str) -> None: + """Raises unless `workload` is a valid Pathways JobSet name (see :data:`MAX_PATHWAYS_NAME` and ``_NAME``).""" + if not _NAME.fullmatch(workload) or len(workload) > MAX_PATHWAYS_NAME: + raise app.UsageError( + f"--workload {workload!r}: a lowercase letter, then lowercase letters, digits and '-' (not last), at most" + f" {MAX_PATHWAYS_NAME} characters for a Pathways JobSet." + ) + + +def check_slices(hparams: hparams_lib.Hparams, device_type: str, num_slices: int) -> None: + """Fails fast when the slices cannot hold the stages, or a microbatch cannot be split. + + Args: + hparams: The configuration to launch. + device_type: TPU type of each slice, e.g. ``v5p-16``. + num_slices: Number of slices. + + Raises: + app.UsageError: If the device count, the slices or the microbatch do not + divide. + """ + devices = hparams_lib.devices_in_device_type(device_type) * num_slices + if devices <= 0 or devices % hparams.num_stages: + raise app.UsageError( + f"{device_type} x {num_slices} ({devices} devices) does not split into {hparams.num_stages} stages." + ) + if num_slices > 1 and hparams.num_stages % num_slices and num_slices % hparams.num_stages: + # mesh_utils never lets a stage straddle a slice. + raise app.UsageError( + f"{num_slices} slices and {hparams.num_stages} stages must divide one another: each slice holds whole stages," + " or each stage whole slices." + ) + try: + hparams_lib.check_microbatch_split_on(hparams, devices) + except ValueError as error: + raise app.UsageError(str(error)) from error + + +def entry_point_command(hparams: hparams_lib.Hparams, flag_values: flags.FlagValues, extra: Sequence[str] = ()) -> str: + """Returns the head pod's command: the entry point, as ``python3 -u -m``.""" + module = f"maxtext.experimental.mpmd.partir.{flag_values.module}" + return shlex.join(["python3", "-u", "-m", module, *module_args(hparams, flag_values, extra)]) + + +def launcher_commands( + hparams: hparams_lib.Hparams, flag_values: flags.FlagValues, extra: Sequence[str] = () +) -> list[list[str]]: + """Returns the argvs that launch the run, in order (config, then submit, for gcluster; one for xpk).""" + fv = flag_values + command = entry_point_command(hparams, fv, extra) + server_image = f"{PATHWAYS_IMAGES}/server:{fv.pathways_tag}" + proxy_image = f"{PATHWAYS_IMAGES}/proxy_server:{fv.pathways_tag}" + # The proxy server hosts the Pathways client, which compiles: a compiler flag + # given only to the resource manager and workers does not apply. + xla = xla_server_args(fv) + if fv.launcher == "gcluster": + compute_type, topology = gcluster_options(fv) + argv = ["gcluster", "job", "submit", "--pathways"] + [ + f"--name={fv.workload}", + f"--image={fv.docker_image}", + f"--compute-type={compute_type}", + f"--topology={topology}", + f"--num-slices={fv.num_slices}", + f"--pathways-gcs-location={fv.pathways_gcs_location}", + f"--pathways-server-image={server_image}", + f"--pathways-worker-image={server_image}", + f"--pathways-proxy-server-image={proxy_image}", + ] + if xla: + argv += [f"--pathways-proxy-args={xla}", f"--pathways-server-args={xla}", f"--pathways-worker-args={xla}"] + return gcluster_config_commands(fv.project, fv.cluster, fv.zone) + [ + argv + list(fv.launcher_args) + [f"--command={command}"] + ] + argv = ["xpk", "workload", "create-pathways"] + [ + f"--cluster={fv.cluster}", + f"--project={fv.project}", + f"--zone={fv.zone}", + f"--workload={fv.workload}", + f"--tpu-type={fv.device_type}", + f"--num-slices={fv.num_slices}", + f"--docker-image={fv.docker_image}", + f"--server-image={server_image}", + f"--proxy-server-image={proxy_image}", + f"--pathways-gcs-location={fv.pathways_gcs_location}", + ] + if xla: + argv += [ + f"--custom-pathways-proxy-server-args={xla}", + f"--custom-pathways-server-args={xla}", + f"--custom-pathways-worker-args={xla}", + ] + return [argv + list(fv.launcher_args) + [f"--command={command}"]] + + +def main(argv: Sequence[str], flag_values: flags.FlagValues = flags.FLAGS) -> None: + fv = flag_values + missing = [f"--{name}" for name in _REQUIRED if not fv[name].value] + if missing: + raise app.UsageError(f"Missing required flags: {', '.join(missing)}.") + if not fv.pathways_gcs_location.startswith("gs://"): + raise app.UsageError(f"--pathways_gcs_location must be gs://..., got {fv.pathways_gcs_location!r}.") + if fv.enable_profile and not fv.profile_dir.startswith("gs://"): + raise app.UsageError("--enable_profile needs a gs:// --profile_dir: Pathways writes traces only to GCS.") + # Validates the hyperparameters (layers divisible by stages, schedule name, + # decoder block, ...) here, so that a misconfiguration fails in a second + # rather than after the slices have been provisioned. + try: + hparams = hparams_lib.from_flags(fv) + except (ValueError, FileNotFoundError) as error: + raise app.UsageError(str(error)) from error + check_workload_name(fv.workload) + check_slices(hparams, fv.device_type, fv.num_slices) + note = hparams_lib.ragged_buffer_note(hparams) + if note: + max_logging.warning(f"launch: {note}") + if fv.launcher == "gcluster": + max_logging.warning(f"launch: {GCLUSTER_RESTART_WARNING}") + + commands = launcher_commands(hparams, fv, argv[1:]) + if not fv.submit: + for command in commands: + print(shlex.join(command)) + return + for command in commands: + returncode = subprocess.run(command, check=False).returncode + if returncode: + raise SystemExit(returncode) + + +if __name__ == "__main__": + define_flags() + app.run(main) diff --git a/src/maxtext/experimental/mpmd/partir/local_pathways.sh b/src/maxtext/experimental/mpmd/partir/local_pathways.sh new file mode 100755 index 0000000000..b4b1152c92 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/local_pathways.sh @@ -0,0 +1,146 @@ +#!/bin/bash +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Pathways on a single-host TPU VM's own chips, in docker: the resource manager, one worker (the VM's +# chips) and the IFRT proxy, run the way xpk's Pathways head and worker pods run them on GKE, all +# --net=host on 127.0.0.1. A local loop for programs that compile only on Pathways, such as Shardy +# MPMD's IFRT IR: +# +# bash local_pathways.sh up --gcs_scratch_location=gs://BUCKET/DIR --instance_type=tpu7x:2x2x1 +# JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000 \ +# python3 -m maxtext.experimental.mpmd.partir.train --pp=4 --fsdp=2 --num_microbatches=4 \ +# --per_device_batch_size=4 --model_name=simple +# bash local_pathways.sh status # containers, worker restarts, slice state +# bash local_pathways.sh down # frees the TPU again +# +# up's arguments: +# --gcs_scratch_location (required) gs:// location for Pathways' scratch files and its persistent +# compilation cache. The containers authenticate as the VM's service +# account, which needs write access to it. +# --instance_type (required) the VM's slice as the resource manager names it: tpu7x:2x2x1 +# on a TPU7x VM with 4 chips (tpu7x-8), tpuv6e:2x2 on a v6e-4. +# --tag Pathways image tag; it must match the client's jax (default +# 20261117-jax_0.12.0.1; the 20261118, 20261120 and 20261124 jax_0.12.0.1 +# images reject the IFRT IR of the Shardy MPMD programs jax 0.12.0.1 lowers). +# --xla_flags_file File of XLA / libtpu flags, one --key=value per line (# comments), for the +# proxy (which compiles), the resource manager and the worker: launch.py's +# --xla_flags_file. +# Environment: DOCKER, the docker command (default: sudo docker). +# +# While the worker is up it owns the TPU, so plain-JAX runs on this VM fail until 'down'. The worker +# exits on purpose each time a client disconnects, so it runs under --restart=on-failure (as xpk's +# Pathways JobSet restarts it on GKE; see the README about gcluster); the next client's first +# execution waits about 10 s for it to rejoin. Profiling: under Pathways, jax.profiler.start_trace +# accepts only gs:// directories, and the worker's TPU tracer starts late: work dispatched within +# about a second of start_trace is missing from the trace. +set -euo pipefail + +TAG=20261117-jax_0.12.0.1 +GCS= +INSTANCE_TYPE= +XLA_FLAGS_FILE= +IMG=us-docker.pkg.dev/cloud-tpu-v2-images/pathways +DOCKER=${DOCKER:-sudo docker} +PREFIX=maxtext-pathways +NAMES=("$PREFIX-rm" "$PREFIX-worker" "$PREFIX-proxy") +LOGS=(--log-opt max-size=50m --log-opt max-file=2) + +usage() { + echo "usage: $0 up --gcs_scratch_location=gs://BUCKET/DIR --instance_type=TYPE [--tag=TAG]" \ + "[--xla_flags_file=FILE] | down | status" + exit 2 +} + +# (not grep -q: under pipefail, grep -q exiting early fails 'docker logs' with SIGPIPE on a long log) +slice_state() { $DOCKER logs "$PREFIX-rm" 2>&1 | grep -o '[0-9]*/[0-9]* Pathways Slices Now Ready' | tail -1; } +proxy_ready() { $DOCKER logs "$PREFIX-proxy" 2>&1 | grep 'IFRT proxy server started with status OK' >/dev/null; } + +up() { + for arg in "$@"; do + case $arg in + --gcs_scratch_location=*) GCS=${arg#*=} ;; + --instance_type=*) INSTANCE_TYPE=${arg#*=} ;; + --tag=*) TAG=${arg#*=} ;; + --xla_flags_file=*) XLA_FLAGS_FILE=${arg#*=} ;; + *) echo "unknown argument: $arg"; usage ;; + esac + done + if [[ $GCS != gs://* ]]; then echo "--gcs_scratch_location=gs://... is required"; usage; fi + if [[ -z $INSTANCE_TYPE ]]; then echo "--instance_type is required"; usage; fi + local flags=() flag + if [[ -n $XLA_FLAGS_FILE ]]; then + if [[ ! -r $XLA_FLAGS_FILE ]]; then echo "cannot read --xla_flags_file=$XLA_FLAGS_FILE"; exit 1; fi + mapfile -t flags < <(sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^#/d' -e '/^$/d' "$XLA_FLAGS_FILE") + for flag in "${flags[@]}"; do + if [[ $flag != --?*=* || $flag == *[[:space:]]* ]]; then + echo "$XLA_FLAGS_FILE: expected one --key=value a line, got '$flag'"; exit 1 + fi + done + fi + if [[ -n "$($DOCKER ps -aq --filter name="^$PREFIX-")" ]]; then + echo "$PREFIX-* containers exist already: run '$0 down' first"; exit 1 + fi + if sudo lsof /dev/vfio/[0-9]* >/dev/null 2>&1; then + echo "the TPU is in use:"; sudo lsof /dev/vfio/[0-9]*; exit 1 + fi + $DOCKER run -d --name "$PREFIX-rm" --net=host "${LOGS[@]}" \ + -e TPU_SKIP_MDS_QUERY=true -e JOBSET_NAME="$PREFIX" -e REPLICATED_JOB_NAME=pathways-head \ + -e HOST_ADDRESS=127.0.0.1 \ + "$IMG/server:$TAG" --server_port=29001 --gcs_scratch_location="$GCS" \ + --node_type=resource_manager --instance_count=1 --instance_type="$INSTANCE_TYPE" "${flags[@]}" >/dev/null + $DOCKER run -d --name "$PREFIX-worker" --net=host --privileged --restart=on-failure "${LOGS[@]}" \ + -e TPU_MIN_LOG_LEVEL=0 -e TF_CPP_MIN_LOG_LEVEL=0 -e XCLOUD_ENVIRONMENT=GCP \ + -e MEGASCALE_GRPC_ENABLE_XOR_TRACER=false -e MEGASCALE_NUM_SLICES=1 -e MEGASCALE_SLICE_ID=0 \ + -e JOBSET_NAME="$PREFIX" -e REPLICATED_JOB_NAME=worker -e PATHWAYS_HEAD=127.0.0.1 \ + -e MEGASCALE_COORDINATOR_ADDRESS=127.0.0.1 \ + "$IMG/server:$TAG" --server_port=29005 --resource_manager_address=127.0.0.1:29001 \ + --gcs_scratch_location="$GCS" "${flags[@]}" >/dev/null + $DOCKER run -d --name "$PREFIX-proxy" --net=host "${LOGS[@]}" -e PATHWAYS_HEAD=127.0.0.1 \ + "$IMG/proxy_server:$TAG" --server_port=29000 --resource_manager_address=127.0.0.1:29001 \ + --gcs_scratch_location="$GCS" "${flags[@]}" >/dev/null + for _ in $(seq 90); do + if [[ "$(slice_state)" == "1/1 Pathways Slices Now Ready" ]] && proxy_ready; then + echo "Pathways up ($INSTANCE_TYPE, $TAG, ${#flags[@]} XLA flags):" \ + "JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000" + return + fi + if [[ "$($DOCKER inspect -f '{{.State.Running}}' "$PREFIX-rm" 2>/dev/null)" != true ]]; then + echo "the resource manager exited:"; status; $DOCKER logs --tail 30 "$PREFIX-rm" 2>&1; exit 1 + fi + sleep 2 + done + echo "not ready after 180 s:"; status; exit 1 +} + +down() { + for n in "${NAMES[@]}"; do $DOCKER rm -f "$n" >/dev/null 2>&1 && echo "removed $n" || true; done +} + +status() { + $DOCKER ps -a --filter name="^$PREFIX-" --format '{{.Names}}\t{{.Status}}' + if $DOCKER inspect "$PREFIX-worker" >/dev/null 2>&1; then + echo "worker restarts: $($DOCKER inspect "$PREFIX-worker" --format '{{.RestartCount}}')" + fi + if $DOCKER inspect "$PREFIX-rm" >/dev/null 2>&1; then echo "slices: $(slice_state)"; fi + if $DOCKER inspect "$PREFIX-proxy" >/dev/null 2>&1; then + if proxy_ready; then echo "proxy: ready"; else echo "proxy: not ready"; fi + fi +} + +case "${1:-}" in + up) shift; up "$@" ;; + down | status) "$1" ;; + *) usage ;; +esac diff --git a/src/maxtext/experimental/mpmd/partir/mesh_utils.py b/src/maxtext/experimental/mpmd/partir/mesh_utils.py new file mode 100644 index 0000000000..4c104e2c46 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/mesh_utils.py @@ -0,0 +1,700 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Mesh, topology and layer-placement helpers for MPMD pipeline parallelism. + +An MPMD pipeline is described by two pieces of data: + + * a *topology*: a mapping from mesh name (``m0``, ``m1``, ...) to a + :class:`jax.sharding.Mesh` holding the devices of that pipeline stage, and + * a *name-to-mesh assignment*: a mapping from the name of each + ``mpmd.named_computation`` (``embed``, ``layer0``, ..., ``unembed``) to the + mesh it must execute on. + +This module builds both, and nothing else: it has no JIT, model or MaxText +dependency, which keeps it cheap to unit test on CPU. +""" + +from __future__ import annotations + +from collections.abc import Sequence +import dataclasses +from typing import Any + +import jax +from jax.sharding import Mesh +import numpy as np + +# Mesh axis names used inside a single pipeline stage. They are deliberately +# the names MaxText's `logical_axis_rules` refer to (`fsdp`, `tensor`, +# `expert`), so MaxText's own layers resolve their activation and weight +# shardings against a stage mesh without any translation. +FSDP_AXIS = "fsdp" +TENSOR_AXIS = "tensor" +EXPERT_AXIS = "expert" + +# Mesh axes the (micro)batch dimension is sharded over. MaxText maps +# `activation_batch` onto `('data', 'fsdp', 'fsdp_transpose', 'expert')`: with +# expert parallelism the batch is still split over *every* non-tensor device +# of the stage, and the `expert` axis additionally partitions the MoE experts +# so that tokens are exchanged with an all-to-all instead of every device +# all-gathering the full expert weights. +DATA_PARALLEL_AXES = (FSDP_AXIS, EXPERT_AXIS) + +# Names of the non-layer named computations. +EMBED_NAME = "embed" +UNEMBED_NAME = "unembed" + + +def mesh_name(stage_index: int) -> str: + """Returns the canonical mesh name for `stage_index`.""" + return f"m{stage_index}" + + +def layer_name(layer_index: int) -> str: + """Returns the canonical named-computation name for `layer_index`.""" + return f"layer{layer_index}" + + +def pre_stage_name(stage_index: int) -> str: + """Returns the canonical pre-loop named-computation name for `stage_index`.""" + return f"pre_m{stage_index}" + + +def post_stage_name(stage_index: int) -> str: + """Returns the canonical post-loop named-computation name for `stage_index`.""" + return f"post_m{stage_index}" + + +def data_parallel_axes(mesh: Any) -> tuple[str, ...]: + """Returns the axes of `mesh` that the batch dimension is sharded over. + + Args: + mesh: A concrete or abstract mesh with ``axis_names``. + + Returns: + The subset of :data:`DATA_PARALLEL_AXES` present in `mesh`, in mesh order. + """ + names = tuple(getattr(mesh, "axis_names", ())) + return tuple(name for name in names if name in DATA_PARALLEL_AXES) + + +def data_parallel_size(mesh: Any) -> int: + """Returns the number of ways the batch dimension is sharded on `mesh`.""" + shape = dict(getattr(mesh, "shape", {})) + size = 1 + for name in data_parallel_axes(mesh): + size *= int(shape.get(name, 1)) + return size + + +@dataclasses.dataclass(frozen=True) +class StageTopology: + """A pipeline topology together with the metadata used to build it. + + Attributes: + meshes: Mapping from mesh name to the stage's device mesh. + num_stages: Number of pipeline stages. + devices_per_stage: Number of devices backing each stage. + fsdp_size: FSDP degree inside each stage. + tensor_size: Tensor-parallel degree inside each stage. + expert_size: Expert-parallel degree inside each stage. + """ + + meshes: dict[str, Mesh] + num_stages: int + devices_per_stage: int + fsdp_size: int + tensor_size: int + expert_size: int = 1 + + @property + def axis_names(self) -> tuple[str, ...]: + """Returns the mesh axis names common to every stage mesh.""" + return self.meshes[mesh_name(0)].axis_names + + @property + def data_parallel_size(self) -> int: + """Returns how many ways a microbatch is sharded inside a stage.""" + return self.fsdp_size * self.expert_size + + def describe(self) -> str: + """Returns a one-line human readable summary.""" + return ( + f"{self.num_stages} stages x {self.devices_per_stage} devices" + f" (fsdp={self.fsdp_size}, expert={self.expert_size}," + f" tensor={self.tensor_size}), axes={self.axis_names}" + ) + + +# The 3D TPU sub-cube shapes (in chip coordinates) that XLA:TPU's +# supported-slice-shape check accepts. +_SUPPORTED_3D_SUBSLICES = frozenset( + { + (1, 1, 1), + (1, 2, 1), + (2, 2, 1), + (2, 2, 2), + (2, 2, 4), + (2, 4, 4), + } +) + + +def _is_supported_3d_subslice(dx: int, dy: int, dz: int) -> bool: + """Returns whether ``(dx, dy, dz)`` is a valid XLA 3D TPU subslice shape. + + When ``grid_z > 1`` (3D TPU topologies such as TPU v7x ``tpu7x-4x4x4`` or + v5p), XLA:TPU's collective verification applies its supported-slice-shape + check to the bounding box of every stage's collective replica group. A + subslice is supported iff all dimensions are multiples of 4 (multi-cube + slice) or the ``(dx, dy, dz)`` chip bounds match one of the sub-cube + topologies above. + + Args: + dx: Sub-box chip extent along X. + dy: Sub-box chip extent along Y. + dz: Sub-box chip extent along Z. + """ + if dx <= 0 or dy <= 0 or dz <= 0: + return False + if dx % 4 == 0 and dy % 4 == 0 and dz % 4 == 0: + return True + return (dx, dy, dz) in _SUPPORTED_3D_SUBSLICES + + +def _order_subbox_coords(dx: int, dy: int, dz: int) -> list[tuple[int, int, int]]: + """Orders a ``(dx, dy, dz)`` sub-box in row-major ``(x, y, z)`` order. + + XLA:TPU's ring reordering for limited ICI routing constructs hardware + Hamiltonian cycles over 2D torus slices automatically, under the + precondition that every collective's ``replica_group`` -- including + power-of-2 contiguous or strided subgroups when a tensor's batch or sequence + dimension is smaller than ``fsdp`` -- forms a Cartesian product + ``X_subset x Y_subset``. Row-major ordering inside each stage's contiguous + rectangular ``(dx, dy, dz)`` sub-box guarantees that both the full stage and + every power-of-2 contiguous or strided subgroup form rectangular 2D slices. + + Args: + dx: Sub-box size along the X coordinate axis. + dy: Sub-box size along the Y coordinate axis. + dz: Sub-box size along the Z coordinate axis. + + Returns: + Row-major list of ``(x, y, z)`` coordinate offsets inside the sub-box. + """ + if dx <= 0 or dy <= 0 or dz <= 0: + return [] + coords: list[tuple[int, int, int]] = [] + for z in range(dz): + for x in range(dx): + for y in range(dy): + coords.append((x, y, z)) + return coords + + +def _snake_order_blocks(px: int, py: int, pz: int) -> list[tuple[int, int, int]]: + """Orders a ``(px, py, pz)`` grid of stage blocks as a boustrophedon path. + + Planes go along z, rows along x with the x direction reversed on every other + plane, and blocks along y with the y direction reversed on every other row, + so each block is a face neighbour of the one before it: consecutive pipeline + stages share a face of their sub-boxes (their nearest chips are one ICI hop + apart). Row-major order instead puts, e.g., stages 1 and 2 of a 4x4 grid cut + into 2x2 blocks only diagonally next to each other. + + Args: + px: Number of blocks along X. + py: Number of blocks along Y. + pz: Number of blocks along Z. + + Returns: + The ``(x, y, z)`` block coordinates in path order. + """ + coords: list[tuple[int, int, int]] = [] + row = 0 + for z in range(pz): + xs = range(px) if z % 2 == 0 else range(px - 1, -1, -1) + for x in xs: + ys = range(py) if row % 2 == 0 else range(py - 1, -1, -1) + coords.extend((x, y, z) for y in ys) + row += 1 + return coords + + +def _partition_grid_into_stages( + flat_devices: np.ndarray, + num_stages: int, +) -> list[np.ndarray] | None: + """Partitions a dense 3D TPU device grid into contiguous rectangular stages. + + JAX's default ``devices()`` list enumerates chips host-by-host (``2x2`` tiles + per host on v5e/v6e), so slicing ``flat_devices[s * n : (s + 1) * n]`` neither + guarantees rectangular sub-slices nor preserves rectangular 2D slices for + subgroup collectives. When the devices carry ``(x, y, z)`` coordinates that + tile a dense ``(X, Y, Z)`` box and ``num_stages`` factors into + ``(P_x, P_y, P_z)`` dividing ``(X, Y, Z)``, this function: + + 1. Picks a stage sub-box ``(dx, dy, dz)`` that passes XLA:TPU's + supported-slice-shape check on 3D topologies, preserves whole ``2x2`` + hosts whenever possible, and keeps each stage compact. + 2. Orders the ``(P_x, P_y, P_z)`` stage blocks as a snake + (:func:`_snake_order_blocks`), so adjacent pipeline stages ``m_s`` and + ``m_{s+1}`` are face neighbours on the ICI torus. + 3. Orders the devices inside each stage's ``(dx, dy, dz)`` sub-box using + :func:`_order_subbox_coords` so both full-stage and subgroup collectives + satisfy XLA's rectangular slice requirement for limited ICI routing. + + Args: + flat_devices: 1D array of JAX devices. + num_stages: Number of pipeline stages. + + Returns: + A list of ``num_stages`` 1D device arrays, or ``None`` if the devices do + not form a factorable 3D coordinate grid. + """ + coord_to_devices: dict[tuple[int, int, int], list[Any]] = {} + for dev in flat_devices: + coords = getattr(dev, "coords", None) + if coords is None or len(coords) != 3: + return None + key = (int(coords[0]), int(coords[1]), int(coords[2])) + coord_to_devices.setdefault(key, []).append(dev) + + if not coord_to_devices: + return None + + num_devices = flat_devices.size + num_chips = len(coord_to_devices) + if num_devices % num_chips != 0 or num_chips % num_stages != 0: + return None + cores_per_chip = num_devices // num_chips + for key, devs in coord_to_devices.items(): + if len(devs) != cores_per_chip: + return None + coord_to_devices[key] = sorted( + devs, + key=lambda d: (getattr(d, "core_on_chip", 0), getattr(d, "id", 0)), + ) + + xs = [c[0] for c in coord_to_devices] + ys = [c[1] for c in coord_to_devices] + zs = [c[2] for c in coord_to_devices] + if min(xs) != 0 or min(ys) != 0 or min(zs) != 0: + return None + grid_x, grid_y, grid_z = max(xs) + 1, max(ys) + 1, max(zs) + 1 + if grid_x * grid_y * grid_z != num_chips: + return None + + candidates: list[tuple[tuple[int, ...], tuple[int, int, int]]] = [] + for px in range(1, num_stages + 1): + if num_stages % px != 0 or grid_x % px != 0: + continue + rem_yz = num_stages // px + for py in range(1, rem_yz + 1): + if rem_yz % py != 0 or grid_y % py != 0: + continue + pz = rem_yz // py + if grid_z % pz != 0: + continue + dx, dy, dz = grid_x // px, grid_y // py, grid_z // pz + # First require 3D subslice bounds that XLA:TPU's supported-slice-shape + # check accepts, then prefer multiples of 2x2 hosts in (X, Y), the + # canonical sub-cube orientation (dx <= dy <= dz, e.g. 2x2x4 on 4x4x4), + # and compact sub-boxes. + supported_subslice = int(grid_z == 1 or _is_supported_3d_subslice(dx, dy, dz)) + whole_hosts = int((dx % 2 == 0 or grid_x < 2) and (dy % 2 == 0 or grid_y < 2)) + canonical_subcube_order = int(dx <= dy <= dz) if grid_z > 1 else 1 + is_2d_slice = int(sum(d > 1 for d in (dx, dy, dz)) <= 2) + has_cycle = int((dx >= 2 and dy >= 2 and (dx % 2 == 0 or dy % 2 == 0)) or dx * dy <= 2) + score = ( + -supported_subslice, + -whole_hosts, + -canonical_subcube_order, + -is_2d_slice, + -has_cycle, + max(dx, dy, dz), + dx + dy + dz, + -dz, + ) + candidates.append((score, (px, py, pz))) + + if not candidates: + return None + + candidates.sort(key=lambda item: item[0]) + px, py, pz = candidates[0][1] + dx, dy, dz = grid_x // px, grid_y // py, grid_z // pz + + stage_block_coords = _snake_order_blocks(px, py, pz) + intra_stage_coords = _order_subbox_coords(dx, dy, dz) + + stages: list[np.ndarray] = [] + for bx, by, bz in stage_block_coords: + base_x, base_y, base_z = bx * dx, by * dy, bz * dz + stage_devs = [] + for rx, ry, rz in intra_stage_coords: + stage_devs.extend(coord_to_devices[(base_x + rx, base_y + ry, base_z + rz)]) + stages.append(np.asarray(stage_devs, dtype=object)) + return stages + + +def _devices_by_slice(flat_devices: np.ndarray) -> list[np.ndarray]: + """Groups devices by ``slice_index``, in slice order. + + Returns one group holding every device when there is a single slice, or when + the devices carry no ``slice_index`` (CPU devices). + """ + slice_ids = [getattr(dev, "slice_index", None) for dev in flat_devices] + if any(sid is None for sid in slice_ids) or len(set(slice_ids)) <= 1: + return [flat_devices] + by_slice: dict[int, list[Any]] = {} + for dev, sid in zip(flat_devices, slice_ids): + by_slice.setdefault(int(sid), []).append(dev) + return [np.asarray(by_slice[sid], dtype=object) for sid in sorted(by_slice)] + + +def _partition_devices_into_stages(flat_devices: np.ndarray, num_stages: int) -> list[np.ndarray]: + """Splits one slice's devices into stages: grid sub-boxes, else contiguous.""" + stages = _partition_grid_into_stages(flat_devices, num_stages) + if stages is not None: + return stages + per_stage = flat_devices.size // num_stages + return [flat_devices[stage * per_stage : (stage + 1) * per_stage] for stage in range(num_stages)] + + +def _partition_slices_into_stages(slices: list[np.ndarray], num_stages: int) -> list[np.ndarray]: + """Splits a multi-slice device set into stages that never straddle slices. + + Every slice's chips have the same coordinates, so partitioning the devices of + all slices as one coordinate grid would put devices of every slice into every + stage: each stage's FSDP collectives would cross DCN while the stage-boundary + transfers stayed on ICI, the opposite of pipelining over DCN. Instead no stage + straddles a slice: each slice holds ``num_stages / num_slices`` consecutive + stages (cut as in a single slice), so only the boundaries between slices + cross DCN; or, with more slices than stages, each stage holds ``num_slices / + num_stages`` whole slices, slice-major, so the outermost axis of its mesh + (``fsdp``; ``tensor`` or ``expert`` with ``--fsdp=1``) runs over DCN. + + Args: + slices: Each slice's devices, in slice order. + num_stages: Number of pipeline stages. + + Returns: + ``num_stages`` 1D device arrays. + + Raises: + ValueError: If the slices differ in size, or if neither of ``num_stages`` + and the number of slices divides the other. + """ + num_slices = len(slices) + sizes = {group.size for group in slices} + if len(sizes) != 1: + raise ValueError(f"Slices hold different numbers of devices: {sorted(sizes)}.") + if num_stages % num_slices == 0: + stages: list[np.ndarray] = [] + for group in slices: + stages += _partition_devices_into_stages(group, num_stages // num_slices) + return stages + if num_slices % num_stages == 0: + per_stage = num_slices // num_stages + return [ + np.concatenate( + [_partition_devices_into_stages(group, 1)[0] for group in slices[stage * per_stage : (stage + 1) * per_stage]] + ) + for stage in range(num_stages) + ] + raise ValueError( + f"num_stages ({num_stages}) and the number of slices ({num_slices}) must" + " divide one another, so that no stage straddles a slice." + ) + + +def create_stage_meshes( + devices: Sequence[Any] | np.ndarray, + num_stages: int, + fsdp_size: int = -1, + expert_size: int = 1, +) -> StageTopology: + """Splits `devices` into one device mesh per pipeline stage. + + When `devices` carry 3D TPU chip coordinates forming a dense grid, the grid + is partitioned into contiguous rectangular stage sub-boxes (of whole ``2x2`` + hosts where the grid allows; a v5p-16 at four stages gets half a host each), + ordered in a snake across stages so consecutive stages are neighbours, + with each stage's devices in row-major order (rectangular collective + subgroups; see :func:`_partition_grid_into_stages`). Otherwise, devices are + partitioned contiguously in the order supplied by the caller: stage ``i`` + receives ``devices[i * n : (i + 1) * n]``. Devices of several slices + (``slice_index``) are grouped by slice first, so that no stage straddles a + slice: each slice holds whole stages, or each stage whole slices (see + :func:`_partition_slices_into_stages`). + + Each stage mesh is ``fsdp x tensor x expert`` (axes of size 1 are omitted, + except that a stage always keeps at least the ``fsdp`` axis so that shardings + can be expressed uniformly). The axis order mirrors MaxText's ``mesh_axes`` + (``fsdp`` before ``tensor`` before ``expert``), so a batch sharded over + ``('fsdp', 'expert')`` is laid out exactly like MaxText lays it out. + + Args: + devices: Devices to distribute, either a flat sequence or an ndarray. + num_stages: Number of pipeline stages to create. + fsdp_size: FSDP degree inside each stage. -1 (the default) uses every device + of the stage not already consumed by `expert_size`, i.e. no tensor + parallelism. + expert_size: Expert-parallel degree inside each stage. MoE expert weights + are partitioned (not replicated or FSDP-gathered) across this axis, and + the batch is additionally sharded over it. + + Returns: + The resulting :class:`StageTopology`. + + Raises: + ValueError: If the devices cannot be split evenly into the requested + stage/FSDP/expert shape. + """ + if num_stages <= 0: + raise ValueError(f"num_stages must be positive, got {num_stages}.") + if expert_size <= 0: + raise ValueError(f"expert_size must be positive, got {expert_size}.") + + flat_devices = np.asarray(devices).flatten() + num_devices = flat_devices.size + if num_devices < num_stages: + raise ValueError(f"Not enough devices ({num_devices}) for {num_stages} pipeline stages.") + if num_devices % num_stages: + raise ValueError(f"Number of devices ({num_devices}) must be divisible by num_stages" f" ({num_stages}).") + + devices_per_stage = num_devices // num_stages + if devices_per_stage % expert_size: + raise ValueError(f"devices_per_stage ({devices_per_stage}) must be divisible by" f" expert_size ({expert_size}).") + if fsdp_size <= 0: + fsdp_size = devices_per_stage // expert_size + if fsdp_size * expert_size > devices_per_stage: + raise ValueError( + f"fsdp_size x expert_size ({fsdp_size} x {expert_size}) exceeds the" + f" number of devices available per stage ({devices_per_stage})." + " Reduce --fsdp, --expert or --num_stages." + ) + if devices_per_stage % (fsdp_size * expert_size): + raise ValueError( + f"devices_per_stage ({devices_per_stage}) must be divisible by" + f" fsdp_size x expert_size ({fsdp_size} x {expert_size})." + ) + + tensor_size = devices_per_stage // (fsdp_size * expert_size) + mesh_shape: list[int] = [] + axis_names: list[str] = [] + for name, size in ( + (FSDP_AXIS, fsdp_size), + (TENSOR_AXIS, tensor_size), + (EXPERT_AXIS, expert_size), + ): + if size > 1: + mesh_shape.append(size) + axis_names.append(name) + if not axis_names: + mesh_shape, axis_names = [fsdp_size], [FSDP_AXIS] + + slices = _devices_by_slice(flat_devices) + if len(slices) > 1: + stage_device_lists = _partition_slices_into_stages(slices, num_stages) + else: + stage_device_lists = _partition_devices_into_stages(flat_devices, num_stages) + + meshes = {} + for stage, stage_devices in enumerate(stage_device_lists): + meshes[mesh_name(stage)] = Mesh(stage_devices.reshape(tuple(mesh_shape)), tuple(axis_names)) + + return StageTopology( + meshes=meshes, + num_stages=num_stages, + devices_per_stage=devices_per_stage, + fsdp_size=fsdp_size, + tensor_size=tensor_size, + expert_size=expert_size, + ) + + +def layer_stage_indices( + num_layers: int, + num_stages: int, + num_repeats: int = 1, + stage_layer_counts: Sequence[int] = (), +) -> list[int]: + """Returns the logical chunk index for each decoder layer ``0..num_layers-1``. + + Args: + num_layers: Total number of decoder layers. + num_stages: Number of pipeline stages. + num_repeats: Number of times the pipeline is traversed per forward pass. + stage_layer_counts: Optional per-chunk layer counts. When empty, layers are + divided uniformly into ``num_repeats * num_stages`` chunks. + + Returns: + A list of length ``num_layers`` mapping each layer index to its chunk index + in ``[0, num_repeats * num_stages)``. + + Raises: + ValueError: If the layer counts or stage counts are invalid. + """ + if num_stages <= 0: + raise ValueError(f"num_stages must be positive, got {num_stages}.") + if num_repeats <= 0: + raise ValueError(f"num_repeats must be positive, got {num_repeats}.") + + num_chunks = num_repeats * num_stages + if stage_layer_counts: + counts = tuple(int(c) for c in stage_layer_counts) + if len(counts) != num_chunks: + raise ValueError( + f"stage_layer_counts ({counts}) must have length" + f" num_repeats * num_stages ({num_chunks}), got {len(counts)}." + ) + if any(c <= 0 for c in counts): + raise ValueError(f"Every entry in stage_layer_counts ({counts}) must be positive.") + if sum(counts) != num_layers: + raise ValueError(f"sum(stage_layer_counts) ({sum(counts)}) must equal" f" num_layers ({num_layers}).") + assignments: list[int] = [] + for chunk_index, count in enumerate(counts): + assignments.extend([chunk_index] * count) + return assignments + + if num_layers < num_chunks or num_layers % num_chunks: + raise ValueError( + f"num_layers ({num_layers}) must be a positive multiple of" + f" num_repeats * num_stages ({num_repeats} * {num_stages} =" + f" {num_chunks})." + ) + layers_per_chunk = num_layers // num_chunks + return [layer_index // layers_per_chunk for layer_index in range(num_layers)] + + +def create_name_to_mesh_assignment( + num_layers: int, + num_stages: int, + num_repeats: int = 1, + stage_layer_counts: Sequence[int] = (), +) -> dict[str, str]: + """Assigns every named computation of the model to a stage mesh. + + With ``num_repeats == 1`` the assignment is contiguous: the first stage's + layers live on ``m0``, the next stage's on ``m1`` and so on. With + ``num_repeats > 1`` the assignment is *circular* (the layout + interleaved/looped pipelines need): the model is cut into + ``num_repeats * num_stages`` chunks which are dealt round-robin across the + stages, so stage ``i`` owns chunks ``i``, ``i + num_stages``, ... + + The embedding is pinned to the first stage and the unembedding to the last, + matching the data flow of the forward pass. + + Args: + num_layers: Total number of decoder layers. + num_stages: Number of pipeline stages. + num_repeats: Number of times the pipeline is traversed per forward pass. + stage_layer_counts: Optional per-stage (or per-chunk) layer counts. + + Returns: + Mapping from named-computation name to mesh name. + + Raises: + ValueError: If the layers cannot be divided into valid chunks. + """ + chunk_indices = layer_stage_indices( + num_layers=num_layers, + num_stages=num_stages, + num_repeats=num_repeats, + stage_layer_counts=stage_layer_counts, + ) + + name_to_mesh = {} + for layer_index, chunk_index in enumerate(chunk_indices): + stage_index = chunk_index % num_stages + name_to_mesh[layer_name(layer_index)] = mesh_name(stage_index) + + name_to_mesh[EMBED_NAME] = mesh_name(0) + name_to_mesh[UNEMBED_NAME] = mesh_name(num_stages - 1) + for stage_index in range(num_stages): + name_to_mesh[post_stage_name(stage_index)] = mesh_name(stage_index) + name_to_mesh[pre_stage_name(stage_index)] = mesh_name(stage_index) + return name_to_mesh + + +def create_name_to_stage_assignment( + num_layers: int, + num_stages: int, + num_repeats: int = 1, + stage_layer_counts: Sequence[int] = (), +) -> dict[str, int]: + """Assigns every named computation to a *pipeline stage index*. + + For circular schedules PartIR needs to know the position of a computation in + the logical pipeline, which is distinct from the mesh it runs on once a stage + is visited more than once. + + Args: + num_layers: Total number of decoder layers. + num_stages: Number of pipeline stages. + num_repeats: Number of times the pipeline is traversed per forward pass. + stage_layer_counts: Optional per-stage (or per-chunk) layer counts. + + Returns: + Mapping from named-computation name to its logical stage index. + """ + chunk_indices = layer_stage_indices( + num_layers=num_layers, + num_stages=num_stages, + num_repeats=num_repeats, + stage_layer_counts=stage_layer_counts, + ) + num_chunks = num_repeats * num_stages + + name_to_stage = {} + for layer_index, chunk_index in enumerate(chunk_indices): + name_to_stage[layer_name(layer_index)] = chunk_index + name_to_stage[EMBED_NAME] = 0 + name_to_stage[UNEMBED_NAME] = num_chunks - 1 + for stage_index in range(num_stages): + name_to_stage[post_stage_name(stage_index)] = num_chunks + stage_index + name_to_stage[pre_stage_name(stage_index)] = num_chunks + num_stages + stage_index + return name_to_stage + + +def resolve_devices( + topology_name: str = "", + num_slices: int = 1, +) -> Sequence[Any]: + """Returns the devices to build a topology from. + + Args: + topology_name: An AOT topology name such as ``v6e:4x4``. When empty (or + ``cpu``) the locally attached devices are returned instead, which is what + a real training run wants. + num_slices: Number of slices for the virtual topology. + + Returns: + A sequence of (possibly virtual) JAX devices. + """ + if not topology_name or topology_name == "cpu": + return jax.devices() + + # Imported lazily: pulling in the AOT topology machinery costs a non-trivial + # amount of start-up time and is useless during a real run. + from jax.experimental.topologies import get_topology_desc # pylint: disable=import-outside-toplevel + + topology = get_topology_desc( + platform="tpu", + topology_name=topology_name, + num_slices=num_slices, + ) + return topology.devices diff --git a/src/maxtext/experimental/mpmd/partir/models.py b/src/maxtext/experimental/mpmd/partir/models.py new file mode 100644 index 0000000000..e217389e08 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/models.py @@ -0,0 +1,1821 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""A pipelineable transformer assembled from native MaxText NNX layers. + +The model is deliberately split into one :func:`mpmd.named_computation` per +*stage-assignable unit* (``embed``, ``layer0`` ... ``layerN``, ``unembed``). +PartIR MPMD then maps those names onto meshes using the assignment produced by +:mod:`mesh_utils`, and derives the pipeline schedule from the data dependencies +between them. + +The single most important property of this module is that the forward pass is +written **once** and parameterised by a `wrap` strategy: + + * :data:`NAMED_COMPUTATION` wraps each unit in ``mpmd.named_computation``, + producing a pipelined MPMD program; + * :data:`UNWRAPPED` is the identity, producing an ordinary single-program + (SPMD) model. + +Both therefore execute *exactly* the same arithmetic, in the same order, on the +same parameters, which is what makes the numerical-parity check in +``parity.py`` meaningful rather than a comparison of two similar-looking but +independently written models. +""" + +from __future__ import annotations + +from collections.abc import Callable +import contextlib +import dataclasses +import functools +from typing import Any, TypeVar + +from flax import nnx +from flax.core import spmd as flax_spmd +import jax +import jax.numpy as jnp +from jax.sharding import Mesh +from jax.sharding import NamedSharding +from jax.sharding import PartitionSpec as P +from jax._src import shard_map as jax_shard_map # pylint: disable=protected-access +from maxtext.common.common_types import DecoderBlockType +from maxtext.common.common_types import MODEL_MODE_TRAIN +from maxtext.layers import mhc +from maxtext.layers import nnx_decoders +from maxtext.layers.embeddings import Embed +from maxtext.layers.linears import DenseGeneral +from maxtext.utils import max_logging +import numpy as np + +from maxtext.experimental.mpmd.partir import hparams as hparams_lib +from maxtext.experimental.mpmd.partir import mesh_utils + +_F = TypeVar("_F", bound=Callable[..., Any]) + +# The decoder blocks this model builds; `config.build_maxtext_config` refuses +# the others (see `hparams.SUPPORTED_DECODER_BLOCKS`). +SUPPORTED_DECODER_BLOCKS = frozenset(DecoderBlockType(block) for block in hparams_lib.SUPPORTED_DECODER_BLOCKS) + +# Default unsharded target-dtype parameter footprint budget (2 GiB on 16 GiB +# TPU v5e / CPU) for which FSDP weights are pre-cast and all-gathered once +# before the microbatch loop. Stages on higher-HBM accelerators (8 GiB on 32 GiB +# TPU v6e, 24 GiB on 95 GiB TPU v7x and v5p) scale this budget automatically via +# `_stage_pregather_budget_bytes`. A v5p gets its 24 GiB through Pathways, whose +# devices report "TPU v5p"; libtpu alone reports "TPU v5", which keeps 2 GiB. +_DEFAULT_UNIT_PREGATHER_BYTES = 2 * 1024**3 +_MAX_UNIT_PREGATHER_BYTES = _DEFAULT_UNIT_PREGATHER_BYTES +_V6E_STAGE_PREGATHER_BYTES = 8 * 1024**3 +_V7X_STAGE_PREGATHER_BYTES = 24 * 1024**3 + +# A `Wrapper` turns a stage's python function into the function that will +# actually be traced, given the stage's name. +Wrapper = Callable[[str], Callable[[_F], _F]] + + +def NAMED_COMPUTATION(name: str) -> Callable[[_F], _F]: # pylint: disable=invalid-name + """Wraps a stage in an MPMD named computation (pipelined execution).""" + # Imported here, so that the SPMD half of this module (and its tests) runs + # without Shardy MPMD installed. + from maxtext.experimental.mpmd.partir.sdy_mpmd_compat import mpmd # pylint: disable=import-outside-toplevel + + return mpmd.named_computation(name=name) + + +def UNWRAPPED(name: str) -> Callable[[_F], _F]: # pylint: disable=invalid-name,unused-argument + """Leaves a stage untouched (single-program / SPMD execution).""" + return lambda fn: fn + + +class _NNXDecoderLayerFactory: + """Adapter that delegates single-layer construction to ``NNXDecoder``. + + Calling ``NNXDecoder.get_decoder_layers`` and + ``NNXDecoder._init_sequential_generic`` directly instantiates every supported + ``DecoderBlockType`` with the exact per-layer arguments (attention types, + NoPE/MLA flags, MoE interleaving) that MaxText's own unscanned decoder uses, + while only allocating and drawing RNGs for the requested ``layer_index``. + ``NNXDecoder.get_remat_policy`` resolves the layers' remat policy, from + ``remat_policy_override``. Some of these are private ``NNXDecoder`` methods: + ``models_test`` builds every supported block, and resolves every + ``hparams.REMAT_POLICIES`` entry, through them, so a change of their protocol + fails there. + """ + + def __init__(self, config: Any, mesh: Mesh | None, layer_index: int, remat_policy_override: str | None = None): + self.config = config + self.mesh = mesh + self.quant = None + self.model_mode = MODEL_MODE_TRAIN + self.remat_policy_override = remat_policy_override + self._layer_index = layer_index + self.built_layer: nnx.Module | None = None + + def _effective_remat_policy(self) -> str | None: + return nnx_decoders.NNXDecoder._effective_remat_policy(self) # pylint: disable=protected-access + + def minimal_policy(self, with_context: bool = False, with_quantization: bool = False) -> Any: + return nnx_decoders.NNXDecoder.minimal_policy(self, with_context=with_context, with_quantization=with_quantization) + + def remat_policy(self) -> Any: + """Returns MaxText's ``jax.checkpoint`` policy for ``remat_policy_override`` (None for ``full``).""" + return nnx_decoders.NNXDecoder.get_remat_policy(self) + + def _create_single_layer( + self, + decoder_layer_class: type[nnx.Module], + rngs: nnx.Rngs, + **kwargs: Any, + ) -> nnx.Module: + return nnx_decoders.NNXDecoder._create_single_layer( # pylint: disable=protected-access + self, decoder_layer_class, rngs, **kwargs + ) + + def _create_and_register_layer( + self, + layer_cls: type[nnx.Module], + rngs: nnx.Rngs, + base_name: str, + i: int, + **layer_kwargs: Any, + ) -> nnx.Module | None: + """Instantiates only the requested layer index ``self._layer_index``.""" + del base_name + if i != self._layer_index: + return None + self.built_layer = self._create_single_layer(layer_cls, rngs, **layer_kwargs) + return self.built_layer + + def instantiate_layer( + self, + block_cls: type[nnx.Module], + rngs: nnx.Rngs, + **extra_kwargs: Any, + ) -> nnx.Module: + """Directly instantiates a single layer of ``block_cls``.""" + self.built_layer = self._create_single_layer(block_cls, rngs, **extra_kwargs) + return self.built_layer + + +@dataclasses.dataclass(frozen=True) +class PipelineGraphDef: + """The static (non-array) half of a split :class:`PipelinedTransformer`. + + ``nnx.split`` separates a module into a ``GraphDef`` (structure, closed-over + python values) and ``State`` (the arrays). Only the arrays may cross an MPMD + computation boundary, so the model is split once up front and the graphdefs + are captured as trace-time constants. + + Attributes: + config: The MaxText config the model was built from. + embed_def: GraphDef of the token embedder. + embed_rest: Non-parameter state of the token embedder. + layer_defs: Per-layer GraphDefs, ordered from input to output. + layer_rests: Per-layer non-parameter state. + unembed_def: GraphDef of the output head (final norm + projection). + unembed_rest: Non-parameter state of the output projection. + is_deepseek: Whether the decoder blocks are DeepSeek layers. + remat_policy: The policy each decoder layer is checkpointed with + (``Hparams.mpmd_remat_policy``: ``--remat_policy`` under ``--remat``, else + ``none``). Not MaxText's ``remat_policy``, which pipeline parallelism keeps + from being ``none`` (``config.build_maxtext_config``). + stage_layer_counts: Decoder layers per stage (``--stage_layer_counts``); + empty for a uniform split. + fsdp_size: Size of the stage mesh's ``fsdp`` axis. + mesh: Concrete stage mesh used to resolve parameter shardings inside stages. + """ + + config: Any + embed_def: nnx.GraphDef + embed_rest: nnx.State + layer_defs: tuple[nnx.GraphDef, ...] + layer_rests: tuple[nnx.State, ...] + unembed_def: nnx.GraphDef + unembed_rest: nnx.State + is_deepseek: bool + # Required, unlike the two below: a caller that forgot them would silently lose remat or uneven stages. + remat_policy: str + stage_layer_counts: tuple[int, ...] + fsdp_size: int = 1 + mesh: Mesh | None = None + + @property + def num_layers(self) -> int: + """Returns the number of decoder layers in the model.""" + return len(self.layer_defs) + + @property + def data_parallel_size(self) -> int: + """Returns how many ways a microbatch is sharded inside a stage. + + This is the product of the stage mesh's ``fsdp`` and ``expert`` axes (the + ``expert`` axis also shards the batch; see :mod:`mesh_utils`). + """ + if self.mesh is None: + return max(self.fsdp_size, 1) + return max(mesh_utils.data_parallel_size(self.mesh), 1) + + +class OutputHead(nnx.Module): + """MaxText's output head (``NNXDecoder.apply_output_head``) as one unit. + + The final norm (``decoder_norm``, the norm class MaxText's decoder picks for + the decoder block: RMSNorm for most) and then the vocabulary projection + (``logits_dense``). Without the norm the model was not MaxText's: its logits + were unnormalised, and initial losses on the fixed synthetic batch were 24.8 + for llama3.1-8b (MaxText's own trainer: 12.3) and 21 for deepseek2-16b, + against ln(vocab) of about 11.8. Dropout, which MaxText applies after the + norm, is off in every config here (``config._DETERMINISM_OVERRIDES``). + + Only the untied head: ``config.build_maxtext_config`` refuses models with + ``logits_via_embedding`` (tied embeddings, whose MaxText head also applies + ``normalize_embedding_logits`` and ``final_logits_soft_cap``) unless + ``--maxtext_overrides=logits_via_embedding=false`` asks for the untied + variant, which this is. MaxText's default ``cast_logits_to_fp32`` is the + loss's own float32 cast, and ``config._check_buildable`` refuses the head + settings this does not mirror (``lm_head_fsdp_as_vocab_tp``, fp8 weights, ...). + """ + + def __init__(self, config: Any, mesh: Mesh, *, rngs: nnx.Rngs): + norm_cls = nnx_decoders.NNXDecoder.get_norm_layer( + _NNXDecoderLayerFactory(config, mesh, layer_index=-1), + num_features=config.emb_dim, + rngs=rngs, + ) + self.decoder_norm = norm_cls( + dtype=config.dtype, + weight_dtype=config.weight_dtype, + epsilon=config.normalization_layer_epsilon, + kernel_axes=("norm",), + parameter_memory_host_offload=config.parameter_memory_host_offload, + ) + # As NNXDecoder builds it, except for the kernel's logical axes ("embed", + # not "embed_vocab": the FSDP sharding here keys on "embed"). + self.logits_dense = DenseGeneral( + in_features_shape=config.emb_dim, + out_features_shape=config.vocab_size, + kernel_axes=("embed", "vocab"), + dtype=_unembed_output_dtype(config), + weight_dtype=config.weight_dtype, + shard_mode=config.shard_mode, + matmul_precision=config.matmul_precision, + parameter_memory_host_offload=config.parameter_memory_host_offload, + use_bias=False, + mesh=mesh, + rngs=rngs, + ) + + def __call__(self, hidden_states: jax.Array) -> jax.Array: + return self.logits_dense(self.decoder_norm(hidden_states)) + + +class PipelinedTransformer(nnx.Module): + """A decoder-only transformer whose layers are individually addressable. + + Builds the decoder blocks in :data:`SUPPORTED_DECODER_BLOCKS` by delegating + per-layer class lookup and keyword-argument resolution to MaxText's + ``NNXDecoder``. + """ + + def __init__( + self, + config: Any, + mesh: Mesh, + *, + rngs: nnx.Rngs, + remat_policy: str, + stage_layer_counts: tuple[int, ...], + ): + """Builds the model. + + Args: + config: An initialised MaxText config (see :mod:`config`). + mesh: The mesh used to resolve MaxText's logical parameter shardings. This + is the *global* sharding mesh, not a per-stage mesh: PartIR re-shards + parameters onto their stage mesh when it partitions. + rngs: Initialisation RNGs. + remat_policy: See :attr:`PipelineGraphDef.remat_policy`. + stage_layer_counts: See :attr:`PipelineGraphDef.stage_layer_counts`. + """ + self.config = config + self.mesh = mesh + self.remat_policy = remat_policy + self.stage_layer_counts = tuple(stage_layer_counts) + + self.token_embedder = Embed( + num_embeddings=config.vocab_size, + num_features=config.emb_dim, + config=config, + mesh=mesh, + dtype=config.dtype, + rngs=rngs, + ) + + # `config.decoder_block` is a `DecoderBlockType`, not a string: pyconfig + # converts the YAML value with `DecoderBlockType(final_dict[...])`. And + # `DecoderBlockType` is a plain `enum.Enum`, not a `str` mixin, so + # `config.decoder_block == "deepseek"` is *always* False. Comparing against + # the string meant every `--model_name=deepseek3-*` run silently built + # eight dense `SimpleMlpDecoderLayer`s while MaxText -- which compares + # against the enum properly -- charged the run DeepSeek's analytic FLOP + # count, reporting an impossible 427 TFLOP/s/device. + self.is_deepseek = config.decoder_block == DecoderBlockType.DEEPSEEK + first_num_dense_layers = config.first_num_dense_layers + + # `nnx.List` (rather than a plain python list) so the layers are part of + # the module graph and are picked up by `nnx.split`. + self.layers = nnx.List() + for layer_index in range(config.num_decoder_layers): + self.layers.append(self._make_layer(config, mesh, rngs, layer_index, first_num_dense_layers)) + + self.unembed = OutputHead(config, mesh, rngs=rngs) + + @staticmethod + def _build_decoder_layer( + config: Any, + mesh: Mesh, + rngs: nnx.Rngs, + layer_index: int, + first_num_dense_layers: int, + ) -> nnx.Module: + """Instantiates the decoder block for `layer_index`. + + Delegates class lookup and per-layer kwarg resolution to MaxText's + :class:`nnx_decoders.NNXDecoder`. + + Raises: + ValueError: If `config.decoder_block` is not one of + :data:`SUPPORTED_DECODER_BLOCKS`. + """ + decoder_block = config.decoder_block + if decoder_block not in SUPPORTED_DECODER_BLOCKS: + raise ValueError( + f"Unsupported decoder_block {decoder_block!r}. Expected one of" + f" {sorted(b.value for b in SUPPORTED_DECODER_BLOCKS)}; anything else" + " would silently benchmark a different architecture than the one" + " MaxText charges FLOPs for." + ) + factory = _NNXDecoderLayerFactory(config, mesh, layer_index) + if decoder_block == DecoderBlockType.DEEPSEEK: + dense_cls, moe_cls = nnx_decoders.NNXDecoder.get_decoder_layers(factory) + layer_cls = dense_cls if layer_index < first_num_dense_layers else moe_cls + return factory.instantiate_layer(layer_cls, rngs, layer_idx=layer_index) + try: + decoder_block_classes = nnx_decoders.NNXDecoder.get_decoder_layers(factory) + except NotImplementedError as exc: + raise ValueError(f"Unsupported decoder_block {decoder_block!r}: {exc}") from exc + nnx_decoders.NNXDecoder._init_sequential_generic( # pylint: disable=protected-access + factory, decoder_block_classes, rngs + ) + if factory.built_layer is None: + return factory.instantiate_layer(decoder_block_classes[0], rngs, layer_idx=layer_index) + return factory.built_layer + + def _make_layer( + self, + config: Any, + mesh: Mesh, + rngs: nnx.Rngs, + layer_index: int, + first_num_dense_layers: int, + ) -> nnx.Module: + return self._build_decoder_layer(config, mesh, rngs, layer_index, first_num_dense_layers) + + def split(self) -> tuple[PipelineGraphDef, dict[str, nnx.State]]: + """Separates the model into a static graphdef and a per-unit param dict. + + Returns: + A tuple ``(graphdef, params)`` where `params` is keyed by the same names + used for the MPMD named computations (``embed``, ``layer0``, ..., + ``unembed``), so that ``params[name]`` is exactly the state the + computation called `name` consumes. + """ + embed_def, embed_params, embed_rest = nnx.split(self.token_embedder, nnx.Param, ...) + params: dict[str, nnx.State] = {mesh_utils.EMBED_NAME: embed_params} + + layer_defs = [] + layer_rests = [] + for layer_index, layer in enumerate(self.layers): + layer_def, layer_params, layer_rest = nnx.split(layer, nnx.Param, ...) + layer_defs.append(layer_def) + layer_rests.append(layer_rest) + params[mesh_utils.layer_name(layer_index)] = layer_params + + unembed_def, unembed_params, unembed_rest = nnx.split(self.unembed, nnx.Param, ...) + params[mesh_utils.UNEMBED_NAME] = unembed_params + + fsdp_size = int(self.mesh.shape.get(mesh_utils.FSDP_AXIS, 1)) + graphdef = PipelineGraphDef( + config=self.config, + embed_def=embed_def, + embed_rest=embed_rest, + layer_defs=tuple(layer_defs), + layer_rests=tuple(layer_rests), + unembed_def=unembed_def, + unembed_rest=unembed_rest, + is_deepseek=self.is_deepseek, + fsdp_size=fsdp_size, + mesh=self.mesh, + remat_policy=self.remat_policy, + stage_layer_counts=self.stage_layer_counts, + ) + return graphdef, params + + @classmethod + def init_split( + cls, + config: Any, + mesh: Mesh, + *, + rngs: nnx.Rngs, + unit_shard_fn: Callable[[str, nnx.State], nnx.State] | None = None, + remat_policy: str, + stage_layer_counts: tuple[int, ...], + ) -> tuple[PipelineGraphDef, dict[str, nnx.State]]: + """Builds and splits the model one unit at a time, optionally sharding each. + + Draws from `rngs` in the exact same sequence as ``PipelinedTransformer( + config, mesh, rngs=rngs, ...).split()``, while allowing `unit_shard_fn` to move + each layer's parameters onto its target stage mesh and FSDP sharding before + the next layer is allocated. This prevents OOMing ``device 0`` when + initialising multi-billion-parameter models across many pipeline stages. + + Args: + config: Initialised MaxText config. + mesh: Concrete stage mesh used to resolve logical axis rules. + rngs: Initialisation RNGs. + unit_shard_fn: Optional callback ``(unit_name, unit_params) -> + sharded_unit_params`` invoked immediately after each unit is split. + remat_policy: See :attr:`PipelineGraphDef.remat_policy`. + stage_layer_counts: See :attr:`PipelineGraphDef.stage_layer_counts`. + + Returns: + ``(graphdef, params)`` identical in structure and values to :meth:`split`. + """ + shard_fn = unit_shard_fn if unit_shard_fn is not None else (lambda _name, p: p) + + def shard_unit(name: str, module: nnx.Module, unit_params: nnx.State): + sharded = shard_fn(name, unit_params) + # The GraphDef can keep `module` alive: MaxText's Attention passes + # `kernel_init=query_init`, a closure over the module, and the GraphDef + # holds it as a static attribute. Pointing the module at the sharded + # arrays lets the unsharded ones go; they were left on device 0 (5 GiB + # for llama3.1-8b, 45 GiB for llama3.1-70b, on one stage-0 chip). + nnx.update(module, sharded) + return sharded + + token_embedder = Embed( + num_embeddings=config.vocab_size, + num_features=config.emb_dim, + config=config, + mesh=mesh, + dtype=config.dtype, + rngs=rngs, + ) + embed_def, embed_params, embed_rest = nnx.split(token_embedder, nnx.Param, ...) + params: dict[str, nnx.State] = { + mesh_utils.EMBED_NAME: shard_unit(mesh_utils.EMBED_NAME, token_embedder, embed_params) + } + del token_embedder, embed_params + + is_deepseek = config.decoder_block == DecoderBlockType.DEEPSEEK + first_num_dense_layers = config.first_num_dense_layers + + layer_defs = [] + layer_rests = [] + for layer_index in range(config.num_decoder_layers): + layer = cls._build_decoder_layer(config, mesh, rngs, layer_index, first_num_dense_layers) + layer_def, layer_params, layer_rest = nnx.split(layer, nnx.Param, ...) + layer_defs.append(layer_def) + layer_rests.append(layer_rest) + unit_name = mesh_utils.layer_name(layer_index) + params[unit_name] = shard_unit(unit_name, layer, layer_params) + del layer, layer_params + + unembed = OutputHead(config, mesh, rngs=rngs) + unembed_def, unembed_params, unembed_rest = nnx.split(unembed, nnx.Param, ...) + params[mesh_utils.UNEMBED_NAME] = shard_unit(mesh_utils.UNEMBED_NAME, unembed, unembed_params) + del unembed, unembed_params + + fsdp_size = int(mesh.shape.get(mesh_utils.FSDP_AXIS, 1)) + graphdef = PipelineGraphDef( + config=config, + embed_def=embed_def, + embed_rest=embed_rest, + layer_defs=tuple(layer_defs), + layer_rests=tuple(layer_rests), + unembed_def=unembed_def, + unembed_rest=unembed_rest, + is_deepseek=is_deepseek, + fsdp_size=fsdp_size, + mesh=mesh, + remat_policy=remat_policy, + stage_layer_counts=tuple(stage_layer_counts), + ) + return graphdef, params + + +def _is_nnx_variable(node: Any) -> bool: + """Whether `node` is an NNX variable (a parameter with its logical-axis metadata).""" + return isinstance(node, nnx.Variable) + + +def _unembed_output_dtype(config: Any) -> Any: + """Returns the vocabulary projection's dtype, as MaxText's ``logits_dense``.""" + if config.logits_dot_in_fp32: + return jnp.float32 + return config.dtype + + +def _is_embed_logical_axis(axis_entry: Any) -> bool: + """Returns whether a MaxText logical axis entry represents an FSDP embed dim.""" + if isinstance(axis_entry, str): + return axis_entry.startswith("embed") + if isinstance(axis_entry, (tuple, list)): + return any(isinstance(a, str) and a.startswith("embed") for a in axis_entry) + return False + + +# MaxText logical axis names that denote the *expert* dimension of a routed +# MoE weight (`RoutedMoE.wi_kernel_axes = ("exp", "embed_moe", "mlp_moe")`). +_EXPERT_LOGICAL_AXES = frozenset({"exp", "expert_only"}) + + +def _is_expert_logical_axis(axis_entry: Any) -> bool: + """Returns whether a MaxText logical axis entry is the MoE expert dim.""" + if isinstance(axis_entry, str): + return axis_entry in _EXPERT_LOGICAL_AXES + if isinstance(axis_entry, (tuple, list)): + return any(isinstance(a, str) and a in _EXPERT_LOGICAL_AXES for a in axis_entry) + return False + + +def _extract_logical_axes(node: Any) -> tuple[Any, ...] | None: + """Extracts MaxText logical axis names from an NNX Variable or VariableState.""" + metadata = node.get_metadata() if hasattr(node, "get_metadata") else {} + raw = ( + metadata.get("out_sharding") + or metadata.get("sharding_names") + or metadata.get("sharding") + or getattr(node, "out_sharding", None) + or getattr(node, "sharding", None) + ) + if raw is None or isinstance(raw, (NamedSharding, P)): + return None + if isinstance(raw, str): + return (raw,) + if isinstance(raw, (tuple, list)): + return tuple(raw) + return None + + +def _axes_entry(axes: tuple[str, ...]) -> Any: + """Returns a PartitionSpec entry for `axes` (a name, a tuple, or None).""" + if not axes: + return None + return axes[0] if len(axes) == 1 else tuple(axes) + + +@dataclasses.dataclass(frozen=True) +class LeafSharding: + """How one parameter leaf is laid out at rest and while it is being used. + + Attributes: + sharded: The at-rest sharding of the leaf (what the optimizer state holds). + ``embed*`` dims are split over the stage's FSDP axes, and the ``exp`` dim + of routed-MoE weights is split over the ``expert`` axis. + gathered: The sharding the forward pass consumes. FSDP axes are gathered + (every device sees the full ``embed`` dim), but the ``expert`` dim stays + partitioned: with expert parallelism each device only ever runs its own + experts, so there is nothing to gather. + expert_sharded: Whether the leaf's expert dimension is partitioned over the + ``expert`` mesh axis. + """ + + sharded: NamedSharding + gathered: NamedSharding + expert_sharded: bool = False + + @property + def needs_gather(self) -> bool: + """Returns whether using the leaf requires an FSDP all-gather.""" + return self.sharded.spec != self.gathered.spec + + +def leaf_shardings( + mesh: Mesh, + leaf: Any, + fsdp_size: int, + *, + logical_axes: tuple[Any, ...] | None = None, +) -> LeafSharding: + """Computes the at-rest and gathered shardings of `leaf` on a stage mesh. + + When `logical_axes` metadata from an :class:`nnx.Param` is available: + + * the dim annotated ``exp`` (the expert dim of ``RoutedMoE.wi_0`` / + ``wi_1`` / ``wo``) is partitioned over the mesh's ``expert`` axis, if + any. This is *expert parallelism*: each device owns whole experts and + tokens travel to them, so these weights are never gathered; + * the dim annotated ``embed*`` (such as axis 1 of ``MlpBlock.wo`` or + ``RoutedMoE.wi_0`` and axis 2 of ``Attention.out`` or ``RoutedMoE.wo``) + is FSDP-sharded over the data-parallel axes not already used by the + expert dim -- ``fsdp`` for expert weights, ``('fsdp', 'expert')`` for + everything else, exactly as MaxText's ``embed`` rule maps onto + ``['fsdp', ..., 'expert']``. Sharding axis 0 of output projections or + the expert dim of MoE tensors over FSDP devices would instead split + their contracting / expert dimension, forcing cross-device ``bfloat16`` + reductions or all-to-all weight reshards. + + When no ``logical_axes`` are present (e.g. batch tensors), axis 0 is sharded + over every data-parallel axis if divisible, else replicated. + + Args: + mesh: The (possibly abstract) stage mesh the sharding refers to. + leaf: The array (or ``ShapeDtypeStruct``) to shard. + fsdp_size: Number of FSDP shards (the size of the ``fsdp`` axis when the + mesh has one). + logical_axes: Optional MaxText logical axis tuple from ``nnx.Param``. + + Returns: + The :class:`LeafSharding` of the leaf. + """ + shape = tuple(getattr(leaf, "shape", ())) + if len(shape) < 2: + replicated = NamedSharding(mesh, P()) + return LeafSharding(sharded=replicated, gathered=replicated) + + mesh_shape = dict(getattr(mesh, "shape", {})) + dp_axes = mesh_utils.data_parallel_axes(mesh) + axis_size = { + name: (max(fsdp_size, 1) if name == mesh_utils.FSDP_AXIS else int(mesh_shape.get(name, 1))) for name in dp_axes + } + dp_axes = tuple(name for name in dp_axes if axis_size[name] > 1) + + if logical_axes: + spec: list[Any] = [None] * len(shape) + expert_size = axis_size.get(mesh_utils.EXPERT_AXIS, 1) + expert_dim = None + if expert_size > 1: + for dim_index, axis_entry in enumerate(logical_axes): + if dim_index < len(shape) and _is_expert_logical_axis(axis_entry) and shape[dim_index] % expert_size == 0: + spec[dim_index] = mesh_utils.EXPERT_AXIS + expert_dim = dim_index + break + gathered_spec = list(spec) + + gather_axes = tuple(name for name in dp_axes if name != mesh_utils.EXPERT_AXIS or expert_dim is None) + gather_size = int(np.prod([axis_size[name] for name in gather_axes])) + if gather_axes and gather_size > 1: + for dim_index, axis_entry in enumerate(logical_axes): + if ( + dim_index < len(shape) + and dim_index != expert_dim + and _is_embed_logical_axis(axis_entry) + and shape[dim_index] % gather_size == 0 + ): + spec[dim_index] = _axes_entry(gather_axes) + break + return LeafSharding( + sharded=NamedSharding(mesh, P(*spec)), + gathered=NamedSharding(mesh, P(*gathered_spec)), + expert_sharded=expert_dim is not None, + ) + + dp_size = int(np.prod([axis_size[name] for name in dp_axes])) if dp_axes else 1 + if dp_axes and shape[0] % dp_size == 0: + sharded = NamedSharding(mesh, P(_axes_entry(dp_axes))) + else: + sharded = NamedSharding(mesh, P()) + return LeafSharding(sharded=sharded, gathered=sharded) + + +def shard_leaf_on_fsdp( + mesh: Mesh, + leaf: Any, + fsdp_size: int, + *, + logical_axes: tuple[Any, ...] | None = None, +) -> NamedSharding: + """Returns the at-rest sharding of `leaf`; see :func:`leaf_shardings`.""" + return leaf_shardings(mesh, leaf, fsdp_size, logical_axes=logical_axes).sharded + + +def shard_tree_on_fsdp( + mesh: Mesh, + tree: Any, + fsdp_size: int, + *, + device_put: bool = False, +) -> Any: + """Computes (or applies) FSDP shardings across a pytree, preserving NNX axes.""" + + def _map_node(node: Any) -> Any: + logical_axes = _extract_logical_axes(node) if _is_nnx_variable(node) else None + + def _map_leaf(leaf: Any) -> Any: + sharding = shard_leaf_on_fsdp(mesh, leaf, fsdp_size, logical_axes=logical_axes) + return jax.device_put(leaf, sharding) if device_put else sharding + + return jax.tree.map(_map_leaf, node) + + return jax.tree.map(_map_node, tree, is_leaf=_is_nnx_variable) + + +def _has_fsdp_axis(spec: P) -> bool: + """Returns whether `spec` partitions any dimension over ``fsdp``.""" + for axis in spec: + if axis == mesh_utils.FSDP_AXIS: + return True + if isinstance(axis, tuple) and mesh_utils.FSDP_AXIS in axis: + return True + return False + + +def _remove_fsdp_from_spec(spec: P) -> P: + """Returns `spec` with ``fsdp`` replaced by replication (`None`).""" + new_axes = [] + for axis in spec: + if axis == mesh_utils.FSDP_AXIS: + new_axes.append(None) + elif isinstance(axis, tuple): + filtered = tuple(a for a in axis if a != mesh_utils.FSDP_AXIS) + new_axes.append(filtered if filtered else None) + else: + new_axes.append(axis) + return P(*new_axes) + + +def _target_param_dtype(config: Any) -> jnp.dtype: + """Returns the compute dtype a parameter leaf is cast to in forward (MaxText's ``dtype``).""" + return jnp.dtype(config.dtype) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0, 1)) +def _bind_pregathered( + sharding: NamedSharding, + sharded_dtype: Any, + w_sharded: jax.Array, + w_gathered: jax.Array, +) -> jax.Array: + """Substitutes pre-cast, FSDP-gathered weights in forward & remat passes. + + Forward and ``jax.checkpoint`` rematerialisation return `w_gathered` directly + with zero tensor residuals, avoiding repeated ``float32 -> bfloat16`` casts + and FSDP ``all-gather``s on every microbatch. In the backward pass, the + cotangent `g_gathered` (`bfloat16`) is constrained to `sharding` so XLA fuses + the gradient reduction into a ``bfloat16`` ``reduce-scatter`` before casting + only the FSDP shard back to `sharded_dtype` (`float32`). + """ + del sharding, sharded_dtype, w_sharded + return w_gathered + + +def _bind_pregathered_fwd( + sharding: NamedSharding, + sharded_dtype: Any, + w_sharded: jax.Array, + w_gathered: jax.Array, +) -> tuple[jax.Array, None]: + del sharding, sharded_dtype, w_sharded + return w_gathered, None + + +def _bind_pregathered_bwd( + sharding: NamedSharding, + sharded_dtype: Any, + unused_res: None, + g_gathered: jax.Array, +) -> tuple[jax.Array, None]: + g_sharded = jax.lax.with_sharding_constraint(g_gathered, sharding) + return (g_sharded.astype(sharded_dtype), None) + + +_bind_pregathered.defvjp(_bind_pregathered_fwd, _bind_pregathered_bwd) + + +def _pregather_candidate( + mesh: Mesh, + leaf: Any, + fsdp_size: int, + logical_axes: tuple[Any, ...] | None, + target_dtype: jnp.dtype, +) -> LeafSharding | None: + """Returns the leaf's shardings if it should be pre-cast / pre-gathered.""" + if getattr(leaf, "ndim", 0) < 2: + return None + shardings = leaf_shardings(mesh, leaf, fsdp_size, logical_axes=logical_axes) + if shardings.needs_gather or (shardings.expert_sharded and jnp.dtype(leaf.dtype) != target_dtype): + return shardings + return None + + +def _resident_bytes(mesh: Mesh, leaf: Any, sharding: NamedSharding, itemsize: int) -> int: + """Returns the per-device byte footprint of `leaf` laid out as `sharding`.""" + mesh_shape = dict(getattr(mesh, "shape", {})) + num_shards = 1 + for entry in sharding.spec: + axes = (entry,) if isinstance(entry, str) else tuple(entry or ()) + for axis in axes: + num_shards *= int(mesh_shape.get(axis, 1)) + return int(np.prod(leaf.shape)) * itemsize // max(num_shards, 1) + + +def _unit_pregather_bytes( + mesh: Mesh, + unit_params: nnx.State, + fsdp_size: int, + config: Any, +) -> int: + """Returns the per-device target-dtype footprint of pre-gathered weights.""" + total_bytes = 0 + + leaves_with_path, _ = jax.tree_util.tree_flatten_with_path(unit_params, is_leaf=_is_nnx_variable) + for _, node in leaves_with_path: + logical_axes = _extract_logical_axes(node) if _is_nnx_variable(node) else None + target_dtype = _target_param_dtype(config) + for leaf in jax.tree_util.tree_leaves(node): + shardings = _pregather_candidate(mesh, leaf, fsdp_size, logical_axes, target_dtype) + if shardings is not None: + total_bytes += _resident_bytes(mesh, leaf, shardings.gathered, target_dtype.itemsize) + + return total_bytes + + +def _stage_pregather_budget_bytes(mesh: Mesh | None) -> int: + """Returns the per-stage HBM budget in bytes for FSDP weight pregathering. + + Scales the budget with the target accelerator's HBM capacity (24 GiB on 95 GiB + TPU v7x and v5p, 8 GiB on 32 GiB TPU v6e, 2 GiB on 16 GiB TPU v5e / CPU), + unless a test sets :data:`_MAX_UNIT_PREGATHER_BYTES`. A v5p matches the + ``v5p`` tag through Pathways, whose devices report ``TPU v5p``; libtpu alone + reports ``TPU v5``. + + Args: + mesh: Optional JAX device mesh used to inspect accelerator `device_kind`. + """ + if _MAX_UNIT_PREGATHER_BYTES != _DEFAULT_UNIT_PREGATHER_BYTES: + return _MAX_UNIT_PREGATHER_BYTES + if mesh is not None and getattr(mesh, "devices", None) is not None: + flat_devices = np.asarray(mesh.devices).flat + if len(flat_devices) > 0: + kind = str(getattr(flat_devices[0], "device_kind", "")).lower() + if any(tag in kind for tag in ("v7", "tpu7", "v5p")): + return _V7X_STAGE_PREGATHER_BYTES + if any(tag in kind for tag in ("v6", "trillium")): + return _V6E_STAGE_PREGATHER_BYTES + return _MAX_UNIT_PREGATHER_BYTES + + +def pregather_params( + graphdef: PipelineGraphDef, + params: dict[str, nnx.State], + *, + microbatch_rows: int, + wrap: Wrapper = NAMED_COMPUTATION, +) -> dict[str, Any] | None: + """Pre-casts and all-gathers FSDP-sharded stage weights once per step. + + In PartIR MPMD, microbatches are unrolled across separate ``mpmd.call`` + invocations (`fwd_call0..N`, `bwd_call0..N`). Because XLA cannot hoist loop- + invariant weight casts or FSDP ``all-gather``s across ``mpmd.call`` or + ``jax.checkpoint`` boundaries, passing FSDP-sharded ``float32`` weights + directly into each microbatch causes XLA to execute ``convert(f32 -> bf16)`` + and ``all-gather(bf16)`` `2 * num_microbatches` times per step (once per + forward microbatch and once per rematerialised backward microbatch). + + Wrapping each stage's weight cast and FSDP all-gather in a dedicated pre-loop + ``@wrap(pre_stage{s})`` computation with a distinct ``stage_id`` prevents + Shardy's ``MergeUserDefinedFragmentsIntoSchedulingUnitsPass`` from merging + the weight all-gather into ``fwd_call0``. Because ``pre_stage{s}`` depends + only on stage ``s``'s own ``state.params``, IFRT dispatches all stages' + weight all-gathers in parallel at ``t = 0`` before ``fwd_call0`` begins, + eliminating the ``(num_stages - 1) * T_AG`` warmup serialization bubble while + reusing the gathered ``bfloat16`` weights across all forward and backward + microbatches. + + Applies to ``embed`` (stage 0), ``layer0..layer_{N-1}``, and ``unembed`` + (stage ``num_stages - 1``). Pre-gathering is enabled on stages whose + cumulative unsharded weight footprint fits within + :func:`_stage_pregather_budget_bytes`. + + Args: + graphdef: Static model structure. + params: Per-unit parameter state. + microbatch_rows: Rows of each microbatch. Unless the stage's data-parallel + devices share them (:func:`_microbatch_shards_in_stage`), no 3D expert + weight whose reduce-scatter would defer + (:func:`_should_defer_bwd_reduce_scatter`) is gathered, so none defers. + wrap: Stage wrapping strategy. + + Returns: + A dict mapping unit names to their pre-cast, FSDP-gathered parameter + trees, or ``None`` when FSDP pregathering is not applicable. + """ + if wrap is UNWRAPPED or graphdef.data_parallel_size <= 1 or graphdef.mesh is None: + return None + + num_stages = max(1, graphdef.config.ici_pipeline_parallelism) + stage_budget = _stage_pregather_budget_bytes(graphdef.mesh) + if stage_budget <= 0: + return None + + unit_stages = _unit_stages(graphdef, params) + + unit_bytes = { + name: _unit_pregather_bytes( + graphdef.mesh, + params[name], + graphdef.fsdp_size, + graphdef.config, + ) + for name, _ in unit_stages + } + stage_bytes = [0] * num_stages + for name, stage_idx in unit_stages: + nbytes = unit_bytes[name] + if 0 < nbytes <= stage_budget: + stage_bytes[stage_idx] += nbytes + + pregathered: dict[str, Any] = {name: None for name, _ in unit_stages} + any_pregathered = False + + # Which units fit the budget, decided before anything is gathered. + gathered_units = { + name + for name, stage_idx in unit_stages + if 0 < stage_bytes[stage_idx] <= stage_budget and 0 < unit_bytes[name] <= stage_budget + } + # `defer_fsdp_shard_map_psum` removes the per-microbatch FSDP psum of every + # 3D expert weight at once, and only gathered expert weights get the deferred + # psum_scatter that replaces it. So the expert weights are gathered (and + # their reduce-scatter deferred) for every unit holding them, or for none. + # The expert gradients of the units left out used to keep one device's + # tokens: mixtral-8x7b's 2.7 GiB MoE layers miss a 2 GiB budget while embed + # and unembed fit, and on a v5p (24 GiB) --stage_layer_counts=7,9,8,8 leaves + # out stage 1 (24.3 GiB) alone. Nor are they gathered for a microbatch the + # stage's data-parallel devices cannot share: MaxText's MoE shard_map then + # runs all of it on every device, each holds the whole expert gradient, and + # the deferred psum_scatter added up fsdp copies of it (4x at FSDP=4 with the + # default batch: 2-row microbatches); the shard_map's own psum is right then. + deferrable = _deferrable_units(graphdef, params) + gather_experts = ( + bool(deferrable) and deferrable <= gathered_units and _microbatch_shards_in_stage(graphdef, microbatch_rows) + ) + + def _gather_unit(lp): + def _gather_node(path, node): + logical_axes = _extract_logical_axes(node) if _is_nnx_variable(node) else None + target_dtype = _target_param_dtype(graphdef.config) + + def _gather_leaf(leaf): + if not gather_experts and _should_defer_bwd_reduce_scatter( + leaf, + shard_leaf_on_fsdp( + graphdef.mesh, + leaf, + graphdef.fsdp_size, + logical_axes=logical_axes, + ), + graphdef.config, + logical_axes=logical_axes, + ): + return None + shardings = _pregather_candidate( + graphdef.mesh, + leaf, + graphdef.fsdp_size, + logical_axes, + target_dtype, + ) + if shardings is None: + return None + return jax.lax.with_sharding_constraint(leaf.astype(target_dtype), shardings.gathered) + + return jax.tree.map(_gather_leaf, node) + + return jax.tree_util.tree_map_with_path(_gather_node, lp, is_leaf=_is_nnx_variable) + + for stage_idx in range(num_stages): + stage_unit_names = [name for name, s in unit_stages if s == stage_idx and name in gathered_units] + if not stage_unit_names: + continue + + any_pregathered = True + pre_name = mesh_utils.pre_stage_name(stage_idx) + stage_params = {uname: params[uname] for uname in stage_unit_names} + + def _pregather_stage(sp): + return {uname: _gather_unit(ulp) for uname, ulp in sp.items()} + + pregathered.update(wrap(pre_name)(_pregather_stage)(stage_params)) + + return pregathered if any_pregathered else None + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2)) +def _cast_sharded( + sharding: NamedSharding, + sharded_dtype: Any, + target_dtype: Any, + w_sharded: jax.Array, +) -> jax.Array: + """Casts an FSDP-sharded parameter to `target_dtype` before `all-gather`.""" + del sharded_dtype + return jax.lax.with_sharding_constraint(w_sharded.astype(target_dtype), sharding) + + +def _cast_sharded_fwd( + sharding: NamedSharding, + sharded_dtype: Any, + target_dtype: Any, + w_sharded: jax.Array, +) -> tuple[jax.Array, None]: + return ( + _cast_sharded(sharding, sharded_dtype, target_dtype, w_sharded), + None, + ) + + +def _cast_sharded_bwd( + sharding: NamedSharding, + sharded_dtype: Any, + target_dtype: Any, + unused_res: None, + g_target: jax.Array, +) -> tuple[jax.Array]: + g_sharded = jax.lax.with_sharding_constraint(g_target.astype(target_dtype), sharding) + return (g_sharded.astype(sharded_dtype),) + + +_cast_sharded.defvjp(_cast_sharded_fwd, _cast_sharded_bwd) + + +def _cast_sharded_layer_params( + layer_params: nnx.State, + mesh: Mesh | None, + fsdp_size: int, + config: Any, +) -> nnx.State: + """Casts FSDP-sharded parameters to compute dtype while keeping them sharded.""" + if mesh is None or mesh_utils.data_parallel_size(mesh) <= 1: + return layer_params + + def _cast_node(path: tuple[Any, ...], node: Any) -> Any: + logical_axes = _extract_logical_axes(node) if _is_nnx_variable(node) else None + target_dtype = _target_param_dtype(config) + + def _cast_leaf(leaf: Any) -> Any: + if getattr(leaf, "ndim", 0) < 2 or leaf.dtype == target_dtype: + return leaf + shardings = leaf_shardings(mesh, leaf, fsdp_size, logical_axes=logical_axes) + if not shardings.needs_gather: + return leaf + return _cast_sharded(shardings.sharded, leaf.dtype, target_dtype, leaf) + + return jax.tree.map(_cast_leaf, node) + + return jax.tree_util.tree_map_with_path(_cast_node, layer_params, is_leaf=_is_nnx_variable) + + +def _should_defer_bwd_reduce_scatter( + leaf: Any, + sharding: NamedSharding, + config: Any, + *, + logical_axes: tuple[Any, ...] | None = None, +) -> bool: + """Returns whether a pre-gathered weight should defer FSDP reduce-scatter. + + Never when this jax lacks the private function the deferral patches + (:func:`can_defer_moe_reduce_scatter`): every expert gradient is then reduced + inside its microbatch, as MaxText's shard_map transpose does by itself. + """ + is_moe_expert_3d = logical_axes is None or (len(logical_axes) == 3 and logical_axes[0] == "exp") + return ( + can_defer_moe_reduce_scatter() + and getattr(leaf, "ndim", 0) == 3 + and is_moe_expert_3d + and config.sparse_matmul + and not config.check_vma + and _has_fsdp_axis(sharding.spec) + ) + + +def _deferrable_units(graphdef: PipelineGraphDef, params: dict[str, nnx.State]) -> set[str]: + """Names of the units holding a 3D expert weight whose reduce-scatter defers. + + See :func:`_should_defer_bwd_reduce_scatter`; empty without FSDP, without + sparse_matmul, or with check_vma. + """ + if graphdef.mesh is None or graphdef.fsdp_size <= 1 or not graphdef.config.sparse_matmul or graphdef.config.check_vma: + return set() + names = set() + for name, unit_params in params.items(): + for node in jax.tree_util.tree_leaves(unit_params, is_leaf=_is_nnx_variable): + logical_axes = _extract_logical_axes(node) if _is_nnx_variable(node) else None + for leaf in jax.tree_util.tree_leaves(node): + sharding = shard_leaf_on_fsdp(graphdef.mesh, leaf, graphdef.fsdp_size, logical_axes=logical_axes) + if _should_defer_bwd_reduce_scatter(leaf, sharding, graphdef.config, logical_axes=logical_axes): + names.add(name) + return names + + +def _defers_moe_reduce_scatter( + graphdef: PipelineGraphDef, + params: dict[str, nnx.State], + pregathered_params: dict[str, Any] | None, +) -> bool: + """Whether this step defers 3D expert gradients' FSDP reduce-scatter. + + It does when the deferrable units' expert weights are pre-gathered: + :func:`pregather_params` gathers them for all such units or for none (see + there), because :func:`defer_fsdp_shard_map_psum` removes the per-microbatch + psum for every 3D expert weight at once. + """ + if pregathered_params is None: + return False + return any( + pregathered_params.get(name) is not None + and _build_unit_deferred_meta(graphdef, params[name], pregathered_params[name])[1] + for name in _deferrable_units(graphdef, params) + ) + + +def build_grad_carry( + graphdef: PipelineGraphDef, + params: dict[str, nnx.State], + pregathered_params: dict[str, Any] | None, +) -> dict[str, nnx.State]: + """Replaces deferred 3D MoE leaves with `pregathered_params` (`bfloat16`). + + For 3D MoE weights whose backward FSDP ``reduce-scatter`` is deferred to + :func:`reduce_scatter_deferred_grads`, the per-microbatch backward pass + produces unsharded ``bfloat16`` gradients (`15 GiB`/stage). Using the + already-gathered ``bfloat16`` weight leaves from `pregathered_params` as the + differentiation target and VJP carry keeps the microbatch gradient accumulator + in ``bfloat16`` (`15 GiB`/stage instead of `30 GiB`/stage in ``float32``), + avoiding a `15 GiB` zero-initialized accumulator on microbatch 0, per- + microbatch ``bfloat16 -> float32`` casts, and post-loop ``float32 -> + bfloat16`` truncation before ``psum_scatter``. + + Args: + graphdef: Static model structure. + params: Sharded model parameters tree. + pregathered_params: Pre-gathered parameter tree from + :func:`pregather_params`. + + Returns: + A parameter PyTree with deferred 3D MoE leaves replaced by their + ``bfloat16`` pre-gathered counterparts. + """ + if ( + pregathered_params is None + or graphdef.fsdp_size <= 1 + or graphdef.mesh is None + or not graphdef.config.sparse_matmul + or graphdef.config.check_vma + ): + return params + + out_carry: dict[str, nnx.State] = {} + + for name, unit_params in params.items(): + unit_preg = pregathered_params.get(name) + if unit_preg is None: + out_carry[name] = unit_params + continue + + def _select_node(param_node, preg_node): + if preg_node is None: + return param_node + logical_axes = _extract_logical_axes(param_node) if _is_nnx_variable(param_node) else None + + def _select_leaf(param_leaf, preg_leaf): + if preg_leaf is None: + return param_leaf + sharding = shard_leaf_on_fsdp( + graphdef.mesh, + param_leaf, + graphdef.fsdp_size, + logical_axes=logical_axes, + ) + if _should_defer_bwd_reduce_scatter( + param_leaf, + sharding, + graphdef.config, + logical_axes=logical_axes, + ): + return preg_leaf + return param_leaf + + return jax.tree.map( + _select_leaf, + param_node, + preg_node, + is_leaf=lambda x: x is None, + ) + + out_carry[name] = jax.tree.map( + _select_node, + unit_params, + unit_preg, + is_leaf=lambda x: _is_nnx_variable(x) or x is None, + ) + + return out_carry + + +def can_defer_moe_reduce_scatter() -> bool: + """Whether this jax has the private function :func:`suppress_fsdp_psum_of_3d_inputs` patches. + + The deferred expert-gradient reduce-scatter replaces + ``jax._src.shard_map._unmentioned2``, which the transpose of a + ``check_vma=False`` shard_map looks up at call time. Without it the step + reduces every expert gradient inside its microbatch (correct, but once per + microbatch), and ``models_test`` fails, so that a rename in jax is noticed. + """ + available = callable(getattr(jax_shard_map, "_unmentioned2", None)) + if not available: + _warn_no_deferral() + return available + + +@functools.cache +def _warn_no_deferral() -> None: + max_logging.warning( + "jax._src.shard_map._unmentioned2 is gone: MoE expert gradients are reduce-scattered once per microbatch" + " instead of once per step." + ) + + +@contextlib.contextmanager +def suppress_fsdp_psum_of_3d_inputs(): + """Drops the ``fsdp`` psum the transpose of a ``check_vma=False`` shard_map adds to 3D inputs. + + During VJP transposition, ``jax._src.shard_map._shard_map_transpose_fancy`` + psums the cotangent of every input whose ``in_specs`` entry does not mention a + manual mesh axis over that axis (``_unmentioned2``). Inside this context, a + 3D input (a routed-MoE expert weight) keeps its per-device partial gradient + over ``fsdp`` instead. This patches private JAX; see + :func:`can_defer_moe_reduce_scatter`. + + Yields: + Nothing; the patch is undone on exit. + """ + orig_unmentioned2 = jax_shard_map._unmentioned2 # pylint: disable=protected-access + + def _deferred_unmentioned2(mesh, spec, manual_axes): + axes = orig_unmentioned2(mesh, spec, manual_axes) + if len(spec) == 3 and mesh_utils.FSDP_AXIS in axes: + return [a for a in axes if a != mesh_utils.FSDP_AXIS] + return axes + + jax_shard_map._unmentioned2 = _deferred_unmentioned2 # pylint: disable=protected-access + try: + yield + finally: + jax_shard_map._unmentioned2 = orig_unmentioned2 # pylint: disable=protected-access + + +@contextlib.contextmanager +def defer_fsdp_shard_map_psum( + graphdef: PipelineGraphDef, + pregathered_params: dict[str, Any] | None, + params: dict[str, nnx.State], +): + """Suppresses per-microbatch FSDP psum on 3D MoE weights inside shard_map. + + MaxText's ``RoutedMoE.sparse_matmul_route_and_compute`` wraps each MoE layer + in ``@jax.shard_map(..., in_specs=(..., w0_pspec, w1_pspec, wo_pspec, ...), + check_vma=False)`` where ``w0_pspec`` is ``P(None, None, None)``. During VJP + transposition the shard_map inserts a defensive ``lax.psum(..., "fsdp")`` on + every microbatch for any input whose spec does not mention ``"fsdp"``, forcing + an N-microbatch redundant FSDP ``reduce-scatter`` inside the microbatch loop. + :func:`suppress_fsdp_psum_of_3d_inputs` keeps each device's partial expert + gradient unreduced during the microbatch loop so + :func:`reduce_scatter_deferred_grads` can execute a single ``psum_scatter`` + once per step after the microbatch loop. + + Only when the step defers (:func:`_defers_moe_reduce_scatter`): the patch + applies to every 3D expert weight's shard_map, so every one of them must be + reduced later by :func:`reduce_scatter_deferred_grads`. + + Args: + graphdef: Static model structure. + pregathered_params: Pre-gathered parameter tree from + :func:`pregather_params`. + params: The step's parameters (to see which expert weights were gathered). + + Yields: + Nothing; the patch, if any, is undone on exit. + """ + if ( + pregathered_params is None + or graphdef.fsdp_size <= 1 + or not graphdef.config.sparse_matmul + or graphdef.config.check_vma + or not _defers_moe_reduce_scatter(graphdef, params, pregathered_params) + ): + yield + return + with suppress_fsdp_psum_of_3d_inputs(): + yield + + +def _unit_stages( + graphdef: PipelineGraphDef, + units: dict[str, Any], +) -> list[tuple[str, int]]: + """Maps each model unit in ``units`` to its contiguous pipeline stage index.""" + num_stages = max(1, graphdef.config.ici_pipeline_parallelism) + stage_layer_counts = graphdef.stage_layer_counts + if stage_layer_counts or (graphdef.num_layers >= num_stages and graphdef.num_layers % num_stages == 0): + layer_stages = mesh_utils.layer_stage_indices( + num_layers=graphdef.num_layers, + num_stages=num_stages, + stage_layer_counts=stage_layer_counts, + ) + else: + layers_per_stage = max(1, graphdef.num_layers // num_stages) + layer_stages = [min(num_stages - 1, i // layers_per_stage) for i in range(graphdef.num_layers)] + unit_stages: list[tuple[str, int]] = [] + seen: set[str] = set() + if mesh_utils.EMBED_NAME in units: + unit_stages.append((mesh_utils.EMBED_NAME, 0)) + seen.add(mesh_utils.EMBED_NAME) + for i, stage_idx in enumerate(layer_stages): + name = mesh_utils.layer_name(i) + if name in units: + unit_stages.append((name, stage_idx)) + seen.add(name) + if mesh_utils.UNEMBED_NAME in units: + unit_stages.append((mesh_utils.UNEMBED_NAME, num_stages - 1)) + seen.add(mesh_utils.UNEMBED_NAME) + for name in units: + if name not in seen: + unit_stages.append((name, 0)) + return unit_stages + + +@dataclasses.dataclass(frozen=True) +class _DeferredGradMeta: + """Static metadata for deferred 3D MoE gradient reduce-scatter.""" + + sharding_spec: P + no_fsdp_spec: P + fsdp_dim: int + target_dtype: Any + out_dtype: Any + + +def _build_unit_deferred_meta( + graphdef: PipelineGraphDef, + unit_params: nnx.State | None, + unit_preg: Any, +) -> tuple[Any, bool]: + """Builds a static metadata tree (no JAX arrays) for deferred 3D MoE grads.""" + if ( + unit_params is None + or unit_preg is None + or graphdef.fsdp_size <= 1 + or graphdef.mesh is None + or not graphdef.config.sparse_matmul + or graphdef.config.check_vma + ): + return None, False + + found_deferred = False + + def _meta_node(path, param_node, preg_node): + nonlocal found_deferred + if preg_node is None: + return jax.tree.map(lambda _: None, param_node) + logical_axes = _extract_logical_axes(param_node) if _is_nnx_variable(param_node) else None + target_dtype = _target_param_dtype(graphdef.config) + + def _meta_leaf(param_leaf, preg_leaf): + nonlocal found_deferred + if preg_leaf is None: + return None + sharding = shard_leaf_on_fsdp( + graphdef.mesh, + param_leaf, + graphdef.fsdp_size, + logical_axes=logical_axes, + ) + if not _should_defer_bwd_reduce_scatter( + param_leaf, + sharding, + graphdef.config, + logical_axes=logical_axes, + ): + return None + fsdp_dim = next( + i + for i, a in enumerate(sharding.spec) + if a == mesh_utils.FSDP_AXIS or (isinstance(a, tuple) and mesh_utils.FSDP_AXIS in a) + ) + found_deferred = True + return _DeferredGradMeta( + sharding_spec=sharding.spec, + no_fsdp_spec=_remove_fsdp_from_spec(sharding.spec), + fsdp_dim=fsdp_dim, + target_dtype=target_dtype, + out_dtype=param_leaf.dtype, + ) + + return jax.tree.map( + _meta_leaf, + param_node, + preg_node, + is_leaf=lambda x: x is None, + ) + + meta_tree = jax.tree_util.tree_map_with_path( + _meta_node, + unit_params, + unit_preg, + is_leaf=lambda x: _is_nnx_variable(x) or x is None, + ) + return (meta_tree if found_deferred else None), found_deferred + + +def reduce_scatter_deferred_grads( + graphdef: PipelineGraphDef, + params: dict[str, nnx.State], + pregathered_params: dict[str, Any] | None, + grads: dict[str, nnx.State], + *, + num_microbatches: int = 1, + wrap: Wrapper = NAMED_COMPUTATION, +) -> dict[str, nnx.State]: + """Finalizes accumulated gradients once per step after the microbatch loop. + + Performs the deferred ``bfloat16`` FSDP ``psum_scatter`` on 3D MoE expert + weight gradients and scales all gradients by ``1 / num_microbatches``. + Under MPMD (`wrap is NAMED_COMPUTATION`), downstream stages (`stage_idx > 0`) + wrap their post-loop gradient finalization in a dedicated + ``@wrap(post_m{s})`` user fragment taking only that stage's accumulated + gradients as traced inputs (using precomputed static + :class:`_DeferredGradMeta` + leaves so ``params`` and ``pregathered_params`` are never captured as traced + arrays). This prevents Shardy's ``MergeInferredFragmentsPass`` from merging + post-loop gradient reduce-scatter and AdamW updates into the last microbatch's + backward fragment (``bwd_call_{M-1}``) on downstream stages, allowing them to + emit ``dX`` upstream immediately and execute ``reduce_scatter + AdamW`` in + parallel during cooldown. Because Stage 0 (`stage_idx == 0`) has no upstream + stage waiting on ``dX`` when ``num_stages > 1``, its gradient finalization is + left unwrapped when it has deferred reduce-scatters, so + ``MergeInferredFragmentsPass`` fuses Stage 0's ``psum_scatter`` and AdamW + updates into ``stage0_bwd_call_{M-1}``, allowing XLA's + ``LatencyHidingScheduler`` to overlap Stage 0's SparseCore reduce-scatters + with TensorCore backward compute across layers. Without one there is nothing + to overlap, and the fused update only raises that program's memory: on + deepseek2-16b with expert parallelism (no FSDP) on a v5p-64, stage 0's HBM + was full and ``stage0_bwd_call_7`` with the update failed to load every step + (``RuntimeProgramAllocationFailure``, 6.1 GB scoped), the runtime + defragmented HBM, and the loss went NaN. Stage 0 then gets ``post_m0`` like + the others. + + Args: + graphdef: Static structure produced by :meth:`PipelinedTransformer.split`. + params: Per-unit parameter state tree. + pregathered_params: Optional pre-gathered ``bfloat16`` parameter tree. + grads: Accumulated per-unit gradient state tree. + num_microbatches: Number of microbatches accumulated before scaling. + wrap: Stage wrapping strategy. + + Returns: + The finalized per-unit ``float32`` gradient tree. + """ + unit_metas: dict[str, Any] = {} + unit_has_deferred: dict[str, bool] = {} + for name in grads: + unit_preg = pregathered_params.get(name) if pregathered_params is not None else None + meta_tree, has_def = _build_unit_deferred_meta(graphdef, params.get(name), unit_preg) + unit_metas[name] = meta_tree + unit_has_deferred[name] = has_def + + def _finalize_unit_grads( + unit_grads: nnx.State, + unit_meta: Any, + ) -> nnx.State: + if unit_meta is None: + if num_microbatches != 1: + return jax.tree.map(lambda g: g / num_microbatches, unit_grads) + return unit_grads + + def _finalize_leaf(g_leaf: jax.Array, meta: _DeferredGradMeta | None): + if meta is not None: + + @functools.partial( + jax.shard_map, + mesh=graphdef.mesh, + in_specs=(meta.no_fsdp_spec,), + out_specs=meta.sharding_spec, + check_vma=False, + ) + def _psum_scatter(g): + return jax.lax.psum_scatter( + g.astype(meta.target_dtype), + mesh_utils.FSDP_AXIS, + scatter_dimension=meta.fsdp_dim, + tiled=True, + ).astype(meta.out_dtype) + + g_leaf = _psum_scatter(g_leaf) + if num_microbatches != 1: + g_leaf = g_leaf / num_microbatches + return g_leaf + + return jax.tree.map(_finalize_leaf, unit_grads, unit_meta) + + if wrap is UNWRAPPED: + return {name: _finalize_unit_grads(ug, unit_metas.get(name)) for name, ug in grads.items()} + + num_stages = max(1, graphdef.config.ici_pipeline_parallelism) + unit_stages = _unit_stages(graphdef, grads) + out_grads = dict(grads) + + for stage_idx in range(num_stages): + stage_names = [name for name, s in unit_stages if s == stage_idx] + if not stage_names: + continue + stage_has_deferred = any(unit_has_deferred.get(name, False) for name in stage_names) + if num_microbatches == 1 and not stage_has_deferred: + continue + if stage_idx == 0 and num_stages > 1 and stage_has_deferred: + for uname in stage_names: + out_grads[uname] = _finalize_unit_grads(grads[uname], unit_metas.get(uname)) + continue + post_name = mesh_utils.post_stage_name(stage_idx) + stage_grads = {name: grads[name] for name in stage_names} + stage_metas = {name: unit_metas.get(name) for name in stage_names} + + def _finalize_stage(sg, smetas=stage_metas): + return {uname: _finalize_unit_grads(ugrad, smetas[uname]) for uname, ugrad in sg.items()} + + out_grads.update(wrap(post_name)(_finalize_stage)(stage_grads)) + + return out_grads + + +def _bind_layer_params( + layer_params: nnx.State, + layer_pregathered: Any, + mesh: Mesh | None, + fsdp_size: int, + config: Any = None, +) -> nnx.State: + """Binds pre-gathered layer weights to `layer_params` via `_bind_pregathered`.""" + if layer_pregathered is None or mesh is None or mesh_utils.data_parallel_size(mesh) <= 1: + return layer_params + + def _bind_node(node: Any, preg_node: Any) -> Any: + if preg_node is None: + return node + logical_axes = _extract_logical_axes(node) if _is_nnx_variable(node) else None + + def _bind_leaf(leaf: Any, preg_leaf: Any) -> Any: + if preg_leaf is None: + return leaf + sharding = shard_leaf_on_fsdp(mesh, leaf, fsdp_size, logical_axes=logical_axes) + if config is not None and _should_defer_bwd_reduce_scatter(leaf, sharding, config, logical_axes=logical_axes): + bwd_sharding = NamedSharding(mesh, _remove_fsdp_from_spec(sharding.spec)) + else: + bwd_sharding = sharding + return _bind_pregathered(bwd_sharding, leaf.dtype, leaf, preg_leaf) + + return jax.tree.map(_bind_leaf, node, preg_node, is_leaf=lambda x: x is None) + + return jax.tree.map( + _bind_node, + layer_params, + layer_pregathered, + is_leaf=lambda x: _is_nnx_variable(x) or x is None, + ) + + +def _microbatch_shards_in_stage(graphdef: PipelineGraphDef, rows: int) -> bool: + """Whether a microbatch of `rows` rows is split over the stage's devices. + + It is when MaxText's logical axis rules apply (:func:`_logical_axis_context`): + the stage has several data-parallel devices (``fsdp`` x ``expert``) and + `rows` is a multiple of their number. Otherwise every device of the stage + runs the whole microbatch. + """ + dp_size = graphdef.data_parallel_size + return bool(graphdef.config.logical_axis_rules) and dp_size > 1 and rows > 0 and rows % dp_size == 0 + + +def _logical_axis_context( + graphdef: PipelineGraphDef, + tokens: Any, + wrap: Wrapper, +) -> contextlib.AbstractContextManager[None]: + """Enters MaxText's logical axis rules when the microbatch shards in-stage. + + MaxText's DeepSeek layers, Splash Attention and RoutedMoE read the active + Flax ``logical_axis_rules`` context to map logical batch axes + (``activation_batch``, ``activation_batch_attn``, ``activation_batch_moe``) + onto the stage mesh's ``fsdp`` / ``expert`` axes, and the ``exp`` weight axis + onto ``expert``. Without this context ``get_logical_axis_rules()`` returns + ``()``, causing every activation and every ``shard_map`` inside + ``AttentionOp`` and ``RoutedMoE`` to replicate the entire microbatch across + all devices in the stage. + + Args: + graphdef: Static structure produced by :meth:`PipelinedTransformer.split`. + tokens: The microbatch ``inputs`` tensor. + wrap: Stage wrapping strategy. + + Returns: + A context manager that activates ``config.logical_axis_rules`` when + pipelined across multiple data-parallel devices per stage and the + microbatch batch dimension is divisible by their number. + """ + batch_dim = tokens.shape[0] if getattr(tokens, "ndim", 0) > 0 else 0 + if wrap is UNWRAPPED or not _microbatch_shards_in_stage(graphdef, batch_dim): + return contextlib.nullcontext() + return flax_spmd.logical_axis_rules(graphdef.config.logical_axis_rules) + + +def _resolve_remat_policy(config: Any, policy_name: str) -> tuple[bool, Any]: + """Resolves the MPMD model's remat policy into ``(enabled, jax_policy)``. + + The policy is :attr:`PipelineGraphDef.remat_policy` (``--remat_policy``, or + ``none`` without ``--remat``), not MaxText's ``remat_policy``, which + ``config.build_maxtext_config`` must keep at a policy MaxText accepts with + pipeline parallelism. MaxText's own resolver (``NNXDecoder.get_remat_policy``) + turns it into the policy, so each layer saves exactly the named + intermediates MaxText's decoder saves under that name. + + Args: + config: The MaxText config the model was built from. + policy_name: One of ``hparams.REMAT_POLICIES``, or ``none``. + + Returns: + ``(use_remat, checkpoint_policy)`` where ``checkpoint_policy`` is passed to + :func:`jax.checkpoint`. + """ + if policy_name == "none": + return False, None + return True, _NNXDecoderLayerFactory(config, None, layer_index=-1, remat_policy_override=policy_name).remat_policy() + + +def _ensure_jax_rest(rest_tree: Any) -> Any: + """Converts abstract numpy array placeholders in `rest_tree` to JAX arrays.""" + + def _to_jax(leaf): + if isinstance(leaf, np.ndarray): + return jnp.zeros(leaf.shape, dtype=leaf.dtype) + return leaf + + return jax.tree.map(_to_jax, rest_tree) + + +def forward( + graphdef: PipelineGraphDef, + params: dict[str, nnx.State], + batch: dict[str, Any], + *, + wrap: Wrapper = NAMED_COMPUTATION, + pregathered_params: dict[str, Any] | None = None, +) -> Any: + """Runs the forward pass, returning logits. + + Args: + graphdef: Static structure produced by :meth:`PipelinedTransformer.split`. + params: Per-unit parameter state, keyed as in ``split()``. + batch: Must contain ``inputs``; may contain ``inputs_position`` and + ``inputs_segmentation``. + wrap: Stage wrapping strategy. :data:`NAMED_COMPUTATION` (the default) + produces a pipelined MPMD program; :data:`UNWRAPPED` produces the + equivalent single-program model. + pregathered_params: Optional pre-cast, FSDP-gathered layer parameter trees + produced by :func:`pregather_params`. + + Returns: + Logits of shape ``[batch, length, vocab_size]``. + """ + tokens = batch["inputs"] + positions = batch.get("inputs_position") + segmentation = batch.get("inputs_segmentation") + use_remat, _ = _resolve_remat_policy(graphdef.config, graphdef.remat_policy) + # DeepSeek's manifold-constrained hyper-connections (mHC): the layers carry + # `mhc_expansion_rate` residual streams, which MaxText's decoder expands from + # the embedding and sums back before the final norm (`NNXDecoder`); so do the + # embed and unembed computations here. + expand_streams, reduce_streams = mhc.get_functions(graphdef.config.mhc_expansion_rate) + uses_mhc = graphdef.config.mhc_expansion_rate > 1 + + with _logical_axis_context(graphdef, tokens, wrap): + + embed_pregathered = pregathered_params.get(mesh_utils.EMBED_NAME) if pregathered_params is not None else None + + @wrap(mesh_utils.EMBED_NAME) + def apply_embed(embed_params, embed_preg, token_ids): + bound_params = _bind_layer_params(embed_params, embed_preg, graphdef.mesh, graphdef.fsdp_size) + + def _embed_body(p, tok): + if wrap is not UNWRAPPED and embed_preg is None: + p = _cast_sharded_layer_params(p, graphdef.mesh, graphdef.fsdp_size, graphdef.config) + with _logical_axis_context(graphdef, tok, wrap): + module = nnx.merge(graphdef.embed_def, p, _ensure_jax_rest(graphdef.embed_rest)) + y = module(tok, model_mode=MODEL_MODE_TRAIN) + # [batch, length, emb] -> [batch, length, streams, emb] + return expand_streams(y) if uses_mhc else y + + # Always checkpoint iota embedding in MPMD so JAX AD never stashes + # the `[micro_batch, seq_len, vocab_size]` one-hot tensor in HBM. + if use_remat or (wrap is not UNWRAPPED and graphdef.config.use_iota_embed): + return jax.checkpoint(_embed_body)(bound_params, token_ids) + return _embed_body(bound_params, token_ids) + + hidden = apply_embed(params[mesh_utils.EMBED_NAME], embed_pregathered, tokens) + + def _run_layer(p, layer_preg, h, seg, pos, layer_def, layer_rest): + if wrap is not UNWRAPPED and layer_preg is None: + p = _cast_sharded_layer_params(p, graphdef.mesh, graphdef.fsdp_size, graphdef.config) + with _logical_axis_context(graphdef, h, wrap): + module = nnx.merge(layer_def, p, _ensure_jax_rest(layer_rest)) + if graphdef.config.decoder_block == DecoderBlockType.SIMPLE_MLP: + outputs = module(h, positions=pos, segmentation=seg, deterministic=True, model_mode=MODEL_MODE_TRAIN) + else: + outputs = module( + h, + decoder_segment_ids=seg, + decoder_positions=pos, + deterministic=True, + model_mode=MODEL_MODE_TRAIN, + ) + # Layers may return `(hidden_states, kv_cache)`. + return outputs[0] if isinstance(outputs, tuple) else outputs + + for layer_index in range(graphdef.num_layers): + name = mesh_utils.layer_name(layer_index) + layer_pregathered = pregathered_params.get(name) if pregathered_params is not None else None + # Resolved for each layer: a policy object shared by every layer's + # jax.checkpoint changes how jax numbers the saved residuals in the + # StableHLO (not the partitioned program). + layer_use_remat, layer_remat_policy = _resolve_remat_policy(graphdef.config, graphdef.remat_policy) + + # `layer_def`/`layer_rest` are bound as default arguments rather than + # captured, so each closure keeps its own layer instead of the last one. + def apply_layer( + layer_params, + layer_preg, + hidden_states, + segment_ids, + token_positions, + *, + layer_def=graphdef.layer_defs[layer_index], + layer_rest=graphdef.layer_rests[layer_index], + use_layer_ckpt=layer_use_remat, + layer_ckpt_policy=layer_remat_policy, + ): + bound_params = _bind_layer_params( + layer_params, + layer_preg, + graphdef.mesh, + graphdef.fsdp_size, + graphdef.config, + ) + + def _layer_body(p, h, seg, pos): + return _run_layer(p, layer_preg, h, seg, pos, layer_def, layer_rest) + + if use_layer_ckpt: + return jax.checkpoint(_layer_body, policy=layer_ckpt_policy)( + bound_params, hidden_states, segment_ids, token_positions + ) + return _layer_body(bound_params, hidden_states, segment_ids, token_positions) + + hidden = wrap(name)(apply_layer)(params[name], layer_pregathered, hidden, segmentation, positions) + + unembed_pregathered = pregathered_params.get(mesh_utils.UNEMBED_NAME) if pregathered_params is not None else None + + @wrap(mesh_utils.UNEMBED_NAME) + def apply_unembed(unembed_params, unembed_preg, hidden_states): + bound_params = _bind_layer_params(unembed_params, unembed_preg, graphdef.mesh, graphdef.fsdp_size) + if wrap is not UNWRAPPED and unembed_preg is None: + bound_params = _cast_sharded_layer_params(bound_params, graphdef.mesh, graphdef.fsdp_size, graphdef.config) + with _logical_axis_context(graphdef, hidden_states, wrap): + if uses_mhc: + # [batch, length, streams, emb] -> [batch, length, emb] + hidden_states = reduce_streams(hidden_states) + module = nnx.merge(graphdef.unembed_def, bound_params, graphdef.unembed_rest) + return module(hidden_states) + + return apply_unembed(params[mesh_utils.UNEMBED_NAME], unembed_pregathered, hidden) diff --git a/src/maxtext/experimental/mpmd/partir/parity.py b/src/maxtext/experimental/mpmd/partir/parity.py new file mode 100644 index 0000000000..d0d6661322 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/parity.py @@ -0,0 +1,765 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +r"""Numerical parity between the MPMD pipeline and its SPMD reference. + +Pipeline parallelism must not change what the model computes -- only where it +computes it. This binary runs the *same* training step (see +:mod:`train_step`) twice from the same initial parameters and the same data: + + 1. partitioned across stage meshes by PartIR MPMD, and + 2. as an ordinary single program. + +It then compares the per-step losses, the step-1 gradients and the full +post-update parameter tree. Both runs share the model and the loss code; the +MPMD step additionally pre-gathers each stage's weights once per step and, with +data parallelism, reduce-scatters their gradients in the compute dtype +(``models.pregather_params`` / ``build_grad_carry``), where the unsharded +reference accumulates float32. In float32 the remaining differences are +therefore the partitioning's own reassociation; in bfloat16 they also include +that precision change. + +How much reassociation moves the numbers depends on the hardware and the model, +so the SPMD reference also runs a second time with a different microbatch +split (the same arithmetic, summed in another order): the *noise floor*. Each +step's loss and each tensor passes within its fixed tolerance or within +``--noise_floor_factor`` times the floor at the same step or tensor. On TPU +even ``dtype=float32`` with ``matmul_precision=highest`` leaves MoE gradients +split-dependent at the percent level (SPMD with 8 vs 4 microbatches: 0.8-3.5% +on the router at step 1, against 5e-7 on CPU). Top-k routing adds jumps: where +two experts' scores nearly tie, MPMD's rounding can pick the other one, which +an SPMD floor need not do (the report notes it, with the override that routes +every token to all experts). A non-finite loss, gradient or parameter always +fails, and a floor that is not finite is ignored. + +The MPMD side compiles only on Pathways, so run it against a Pathways backend, +e.g. a TPU VM's Pathways in docker (``local_pathways.sh up``); this checks +float32 at the default matmul precision (see :func:`parity_notes` and the +README's Parity section):: + + JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000 \ + python3 -m maxtext.experimental.mpmd.partir.parity --pp=4 \ + --num_microbatches=4 --per_device_batch_size=4 --steps=3 \ + --model_name=simple --maxtext_overrides=dtype=float32 +""" + +from __future__ import annotations + +from collections.abc import Sequence +import dataclasses +import math +from typing import Any, NamedTuple + +from absl import app +from absl import flags +import jax +import jax.numpy as jnp +import numpy as np +import optax +import pathwaysutils + +from maxtext.common.common_types import DecoderBlockType +from maxtext.utils import max_logging + +from maxtext.experimental.mpmd.partir import hparams as hparams_lib +from maxtext.experimental.mpmd.partir import runner as runner_lib +from maxtext.experimental.mpmd.partir import train_step as train_step_lib + + +def define_flags(flag_values: flags.FlagValues = flags.FLAGS) -> None: + """Registers the parity check's flags, the hyperparameters' included, on `flag_values`.""" + hparams_lib.define_flags(flag_values) + fv = {"flag_values": flag_values} + flags.DEFINE_float( + "loss_tolerance", + 1e-4, + "Fixed tolerance on each step's relative MPMD-vs-SPMD loss difference (absolute below a loss of 1); a step also" + " passes within --noise_floor_factor times the floor's difference up to that step.", + **fv, + ) + flags.DEFINE_float( + "param_tolerance", + 1e-2, + "Fixed tolerance on each parameter tensor's relative L2 difference after the last step; a tensor also passes" + " within --noise_floor_factor times its own floor. Looser than the loss tolerance: AdamW divides by sqrt(v)," + " which amplifies the difference for weights whose gradient is near zero.", + **fv, + ) + flags.DEFINE_float( + "grad_tolerance", + 1e-2, + "Fixed tolerance on each step-1 gradient tensor's relative L2 difference (read from AdamW's first moment after" + " step 1, so before any update has amplified a difference); a tensor also passes within --noise_floor_factor" + " times its own floor.", + **fv, + ) + flags.DEFINE_integer( + "noise_floor_microbatches", + -1, + "Microbatches of the second SPMD run that measures the noise floor. -1: num_microbatches over its smallest" + " prime factor (8 -> 4, 9 -> 3, 5 -> 1); 0: no floor, only the fixed tolerances.", + **fv, + ) + flags.DEFINE_float( + "noise_floor_factor", + 4.0, + "A step or tensor also passes within this many times the noise floor at the same step (the floor's largest" + " difference up to it) or tensor. Once AdamW has changed an MoE model's routing, the later steps' losses" + " diverge chaotically, so the floor gives their scale, not their value. Top-k MoE routing can flip under" + " MPMD's rounding where an SPMD floor does not; see the report's note.", + **fv, + ) + + +# optax.adamw's default b1 (train_step.make_optimizer keeps the defaults): after +# one step its first moment is (1 - b1) * g. +_ADAM_B1 = 0.9 + + +def relative_difference(value: float, reference: float) -> float: + """Returns the loss difference relative to ``max(|reference|, 1)``. + + Absolute below a loss of 1: a model that memorizes its batch drives the loss + toward 0, where relative noise grows without bound (deepseek2-16b cut to two + layers went 10.87 -> 2.30 -> 0.031 at lr 1e-3, and a 1.3e-5 difference at + 0.031 read 4.3e-4). Inf if either value is not finite. + """ + if not (math.isfinite(value) and math.isfinite(reference)): + return math.inf + return abs(value - reference) / max(abs(reference), 1.0) + + +class TreeDiff(NamedTuple): + """What :func:`_compare_params` found; see its docstring.""" + + rel_l2: float + worst_l2_path: str + max_abs: float + max_rel: float + worst_path: str + # (rel_l2, path, reference_norm) of every leaf, worst first; rel_l2 is inf + # for a leaf with a non-finite value on either side. + leaves: tuple[tuple[float, str, float], ...] + + @property + def finite(self) -> bool: + """Whether every leaf's difference is finite.""" + return all(math.isfinite(rel) for rel, _, _ in self.leaves) + + +@dataclasses.dataclass(frozen=True) +class Comparison: + """How far one run is from the SPMD reference. + + Attributes: + losses: Per-step losses of the run. + reference_losses: Per-step losses of the SPMD reference. + grads: Step-1 gradients compared, recovered from AdamW's first moment + (``(1 - b1) * g`` after one step): unlike the parameters they have not + been through an update, so they compare the backward passes themselves. + params: Parameters after the last step compared. The relative L2 is gated, + not the elementwise maximum; see :func:`_compare_params`. + """ + + losses: tuple[float, ...] + reference_losses: tuple[float, ...] + grads: TreeDiff + params: TreeDiff + + @property + def loss_diffs(self) -> tuple[float, ...]: + """Per-step loss differences (see :func:`relative_difference`).""" + return tuple(relative_difference(loss, reference) for loss, reference in zip(self.losses, self.reference_losses)) + + @property + def max_rel_loss_diff(self) -> float: + """Largest per-step loss difference.""" + return max(self.loss_diffs, default=0.0) + + @property + def finite(self) -> bool: + """Whether every loss, gradient and parameter difference is finite.""" + return math.isfinite(self.max_rel_loss_diff) and self.grads.finite and self.params.finite + + +class Gate(NamedTuple): + """One gated metric at its worst step or tensor, relative to its bound. + + Attributes: + name: ``loss``, ``grads`` or ``params``. + value: The MPMD difference there. + bound: Its bound there: ``max(tolerance, factor * floor)``. + floor: The floor's difference there, or None without a usable floor. + where: The step or tensor. + """ + + name: str + value: float + bound: float + floor: float | None + where: str + + @property + def passed(self) -> bool: + """Whether the value is finite and within its bound.""" + return math.isfinite(self.value) and self.value <= self.bound + + @property + def excess(self) -> float: + """``value / bound``: above 1 fails; inf for a non-finite value.""" + if not math.isfinite(self.value): + return math.inf + if self.bound <= 0: + return math.inf if self.value > 0 else 0.0 + return self.value / self.bound + + +def _worst(candidates: list[Gate]) -> Gate: + """Returns the candidate furthest over (or least under) its bound.""" + return max(candidates, key=lambda gate: gate.excess) + + +@dataclasses.dataclass(frozen=True) +class ParityResult: + """Outcome of a parity comparison. + + Attributes: + mpmd: The MPMD run against the SPMD reference. + floor: The SPMD reference run with ``floor_microbatches`` microbatches + against the reference, or None when no floor was measured. + floor_microbatches: Microbatch count of the noise-floor run. + num_params: Number of parameter leaves compared. + notes: Caveats about this configuration, printed with the report. + """ + + mpmd: Comparison + floor: Comparison | None + floor_microbatches: int + num_params: int + notes: tuple[str, ...] = () + + @property + def usable_floor(self) -> Comparison | None: + """The floor, unless it is missing or has a non-finite difference.""" + return self.floor if self.floor is not None and self.floor.finite else None + + def gates( + self, + loss_tolerance: float, + param_tolerance: float, + grad_tolerance: float = math.inf, + floor_factor: float = 0.0, + ) -> tuple[Gate, Gate, Gate]: + """Returns the loss, gradient and parameter gates at their worst points. + + Each step's loss is bounded by ``max(loss_tolerance, floor_factor x the + floor's largest loss difference up to that step)``, so a chaotic late step + of the floor cannot loosen step 1. Each tensor is bounded by its own + tolerance or ``floor_factor`` x its own floor, so one noisy MoE router + cannot loosen the bound of every other tensor. + + Args: + loss_tolerance: Fixed tolerance on each step's loss difference (see + :func:`relative_difference`). + param_tolerance: Fixed tolerance on each parameter tensor's relative L2 + difference. + grad_tolerance: Fixed tolerance on each step-1 gradient tensor's relative + L2 difference. + floor_factor: A step or tensor also passes within this many times the + floor at the same step or tensor. + """ + floor = self.usable_floor + floor_losses = floor.loss_diffs if floor is not None else () + loss_gates = [] + running = 0.0 + for index, value in enumerate(self.mpmd.loss_diffs): + floor_value = None + if index < len(floor_losses): + running = max(running, floor_losses[index]) + floor_value = running + bound = loss_tolerance + if floor_value is not None: + bound = max(loss_tolerance, floor_factor * floor_value) + loss_gates.append(Gate("loss", value, bound, floor_value, f"step {index + 1}")) + + def tensor_gate(name, mine, theirs, tolerance): + floors = {path: rel for rel, path, _ in theirs.leaves} if theirs else {} + candidates = [] + for rel, path, _ in mine.leaves: + floor_value = floors.get(path) + bound = tolerance + if floor_value is not None: + bound = max(tolerance, floor_factor * floor_value) + candidates.append(Gate(name, rel, bound, floor_value, path)) + return _worst(candidates) if candidates else Gate(name, 0.0, tolerance, None, "") + + return ( + _worst(loss_gates) if loss_gates else Gate("loss", 0.0, loss_tolerance, None, ""), + tensor_gate( + "grads", + self.mpmd.grads, + floor.grads if floor is not None else None, + grad_tolerance, + ), + tensor_gate( + "params", + self.mpmd.params, + floor.params if floor is not None else None, + param_tolerance, + ), + ) + + def passed( + self, + loss_tolerance: float, + param_tolerance: float, + grad_tolerance: float = math.inf, + floor_factor: float = 0.0, + ) -> bool: + """Returns whether every step's loss and every tensor is within bounds. + + Args: + loss_tolerance: See :meth:`gates`. + param_tolerance: See :meth:`gates`. + grad_tolerance: See :meth:`gates`. + floor_factor: See :meth:`gates`. + """ + return all(gate.passed for gate in self.gates(loss_tolerance, param_tolerance, grad_tolerance, floor_factor)) + + def report( + self, + loss_tolerance: float, + param_tolerance: float, + grad_tolerance: float = math.inf, + floor_factor: float = 0.0, + ) -> str: + """Returns a human readable comparison table. + + Args: + loss_tolerance: See :meth:`gates`. + param_tolerance: See :meth:`gates`. + grad_tolerance: See :meth:`gates`. + floor_factor: See :meth:`gates`. + """ + floor = self.usable_floor + header = f"{'step':>6} {'MPMD loss':>16} {'SPMD loss':>16} {'diff':>12}" + if floor is not None: + header += f" {'floor diff':>14}" + lines = [header] + floor_losses = floor.loss_diffs if floor is not None else () + for index, (mpmd_loss, spmd_loss, difference) in enumerate( + zip(self.mpmd.losses, self.mpmd.reference_losses, self.mpmd.loss_diffs) + ): + line = f"{index + 1:>6} {mpmd_loss:>16.9f} {spmd_loss:>16.9f}" f" {difference:>12.3e}" + if index < len(floor_losses): + line += f" {floor_losses[index]:>14.3e}" + lines.append(line) + + tolerances = { + "loss": loss_tolerance, + "grads": grad_tolerance, + "params": param_tolerance, + } + lines += [ + "", + # Not "rel diff": absolute below a loss of 1 (relative_difference). + "loss diff : |MPMD - SPMD| / max(|SPMD|, 1)", + f"parameter leaves compared : {self.num_params}", + ] + if self.floor is not None and floor is None: + lines.append("noise floor : ignored, it has a non-finite difference") + elif floor is not None: + lines.append( + "noise floor : SPMD with" f" {self.floor_microbatches} microbatches against the SPMD reference" + ) + lines += ["", "gated (worst step or tensor, against its own bound):"] + for gate in self.gates(loss_tolerance, param_tolerance, grad_tolerance, floor_factor): + if gate.floor is None: + rule = "the tolerance" + else: + rule = f"max(tolerance {tolerances[gate.name]:.1e}," f" {floor_factor:g} x floor {gate.floor:.3e})" + lines.append( + f" {gate.name:<7}: {gate.value:.3e} at {gate.where} (bound" + f" {gate.bound:.3e} = {rule}) {'ok' if gate.passed else 'FAIL'}" + ) + floor_grads = {path: rel for rel, path, _ in floor.grads.leaves} if floor else {} + lines += [ + "", + "diagnostic (elementwise; see _compare_params):", + f" max abs param diff : {self.mpmd.params.max_abs:.3e}", + (f" max rel param diff : {self.mpmd.params.max_rel:.3e}" f" (at {self.mpmd.params.worst_path})"), + " step-1 grads, worst rel L2 (floor; reference ||g||):", + ] + for rel, path, norm in self.mpmd.grads.leaves[:5]: + floor_text = f"{floor_grads[path]:.3e}" if path in floor_grads else "n/a" + lines.append(f" {rel:.3e} {path} ({floor_text}; {norm:.3e})") + if self.notes: + lines += ["", "notes:", *(f" - {note}" for note in self.notes)] + return "\n".join(lines) + + +def noise_floor_microbatches(num_microbatches: int, flag_value: int) -> int: + """Returns the noise-floor run's microbatch count (0: none); see the flag.""" + if flag_value >= 0: + return flag_value + for factor in range(2, num_microbatches + 1): + if num_microbatches % factor == 0: + return num_microbatches // factor + return 0 + + +def _first_moment(opt_state): + """Returns AdamW's first moment (``mu``) from an optax state tree.""" + + def is_adam(node): + return isinstance(node, optax.ScaleByAdamState) + + for node in jax.tree_util.tree_leaves(opt_state, is_leaf=is_adam): + if is_adam(node): + return node.mu + raise ValueError("The optimizer state holds no ScaleByAdamState.") + + +def _step1_gradients(opt_state): + """Returns the step-1 gradients on the host, after exactly one step. + + In the leaves' own dtype: three runs' trees stay alive until they are + compared, and _compare_params widens one leaf at a time. + """ + return jax.tree.map( + lambda mu: np.asarray(jax.device_get(mu)) / (1 - _ADAM_B1), + _first_moment(opt_state), + ) + + +def _compare_params(mpmd_params, spmd_params, norm_floor=1.0) -> TreeDiff: + """Compares two parameter trees. + + The gating metric is the per-tensor relative L2 difference + ``||mpmd - spmd||_2 / ||spmd||_2`` rather than the largest elementwise + relative difference, because the latter is not a usable signal once the + parameters have been through AdamW. AdamW's update is + ``m / (sqrt(v) + eps)``, so for a weight whose gradient is near zero an + arbitrarily small perturbation of that gradient -- for instance the + reassociation of a bf16 reduction caused by sharding -- flips the update by + up to a full learning rate. A single such weight sends the elementwise + relative difference to O(1) while the tensor as a whole is unchanged. The + L2 ratio, in contrast, only grows if the difference is spread over the + tensor, which is what an actual partitioning bug produces. + + Args: + mpmd_params: Parameters after the MPMD run. + spmd_params: Parameters after the SPMD reference run. + norm_floor: Floor of the relative L2's denominator (see below); gradients, + whose norms are far below 1, use a small one. + + Returns: + A :class:`TreeDiff`. + + Raises: + ValueError: If the trees differ in size or in any leaf's shape. + """ + max_abs = 0.0 + max_rel = 0.0 + rel_l2 = 0.0 + worst_path = "" + worst_l2_path = "" + per_leaf: list[tuple[float, str, float]] = [] + + mpmd_leaves = jax.tree_util.tree_flatten_with_path(mpmd_params)[0] + spmd_leaves = jax.tree_util.tree_flatten_with_path(spmd_params)[0] + if len(mpmd_leaves) != len(spmd_leaves): + raise ValueError(f"Parameter trees differ in size: {len(mpmd_leaves)} (MPMD) vs" f" {len(spmd_leaves)} (SPMD).") + + for (path, mpmd_leaf), (_, spmd_leaf) in zip(mpmd_leaves, spmd_leaves): + mpmd_array = np.asarray(jax.device_get(mpmd_leaf), dtype=np.float64) + spmd_array = np.asarray(jax.device_get(spmd_leaf), dtype=np.float64) + if mpmd_array.shape != spmd_array.shape: + raise ValueError(f"Shape mismatch at {jax.tree_util.keystr(path)}:" f" {mpmd_array.shape} vs {spmd_array.shape}.") + finite = bool(np.isfinite(mpmd_array).all() and np.isfinite(spmd_array).all()) + absolute = np.abs(mpmd_array - spmd_array) + # A NaN compares as neither larger nor smaller, so a non-finite leaf is + # recorded as inf: it must fail every gate, never count as no difference. + leaf_max_abs = float(absolute.max(initial=0.0)) if finite else math.inf + max_abs = max(max_abs, leaf_max_abs) + + relative = absolute / np.maximum(np.abs(spmd_array), 1e-6) + leaf_max_rel = float(relative.max(initial=0.0)) if finite else math.inf + if leaf_max_rel > max_rel: + max_rel = leaf_max_rel + worst_path = jax.tree_util.keystr(path) + + # Floor the denominator at 1.0 so zero-initialised offset parameters (such + # as Qwen3NextRMSNorm.scale, which starts at 0.0 and is applied as + # `1.0 + scale`) do not divide a single-learning-rate AdamW step by ~0. + reference_norm = float(np.linalg.norm(spmd_array.ravel())) if finite else math.nan + leaf_rel_l2 = float(np.linalg.norm(absolute.ravel())) / max(reference_norm, norm_floor) if finite else math.inf + per_leaf.append((leaf_rel_l2, jax.tree_util.keystr(path), reference_norm)) + if leaf_rel_l2 > rel_l2: + rel_l2 = leaf_rel_l2 + worst_l2_path = jax.tree_util.keystr(path) + + per_leaf.sort(key=lambda leaf: leaf[0], reverse=True) + return TreeDiff(rel_l2, worst_l2_path, max_abs, max_rel, worst_path, tuple(per_leaf)) + + +def _run_reference(runnable, steps): + """Runs the unsharded SPMD step; returns (losses, step-1 grads, params).""" + # The reference is deliberately left unsharded: it exists to say what the + # arithmetic should produce, so the fewer transformations applied to it the + # better. Its inputs and outputs are committed to the one device it runs on: + # left uncommitted, a model that constrains shardings inside (DeepSeek's + # layers) returned step 1's state committed to another sharding, and step 2 + # compiled the program again (3.5 min for deepseek3-tiny with mHC on TPU7x). + device = jax.sharding.SingleDeviceSharding(runnable.plan.layer_mesh.devices.flat[0]) + step_fn = jax.jit(runnable.train_step, in_shardings=device, out_shardings=device) + state, batch = jax.device_put((runnable.state, runnable.batch), device) + losses, grads = [], None + for step in range(steps): + state, loss = step_fn(state, batch) + losses.append(float(loss)) + if step == 0: + grads = _step1_gradients(state.opt_state) + return tuple(losses), grads, state.params + + +def check_parity( + hparams: hparams_lib.Hparams, + *, + config_overrides: dict[str, object] | None = None, + floor_microbatches: int = 0, +) -> ParityResult: + """Runs both execution modes (and the noise-floor run) and compares them. + + Args: + hparams: Hyperparameters; ``steps`` controls how many optimizer steps are + compared. More steps make the check stricter for dense models, because + any divergence compounds through the optimizer; an MoE model's routing + turns it chaotic instead, which the noise floor measures. + config_overrides: Optional MaxText config overrides forwarded to + :func:`runner.build`. + floor_microbatches: Microbatches of the SPMD run that measures the noise + floor; 0 skips it. + + Returns: + The :class:`ParityResult`. + + Raises: + ValueError: If ``hparams.steps < 1`` (nothing would be compared) or + `floor_microbatches` does not divide the global batch. + """ + if hparams.steps < 1: + raise ValueError(f"steps must be at least 1, got {hparams.steps}.") + mpmd_runnable = runner_lib.build( + hparams, + mode=train_step_lib.ExecutionMode.MPMD, + config_overrides=config_overrides, + check_microbatches=True, + ) + spmd_runnable = runner_lib.build( + hparams, + mode=train_step_lib.ExecutionMode.SPMD, + config_overrides=config_overrides, + ) + + if floor_microbatches and mpmd_runnable.batch_size % floor_microbatches: + # Checked before anything compiles: runner.build would only reject it + # after the MPMD and SPMD runs. + raise ValueError( + f"--noise_floor_microbatches={floor_microbatches} does not divide the" + f" global batch of {mpmd_runnable.batch_size}." + ) + + max_logging.log("Configuration under test:") + max_logging.log(mpmd_runnable.describe()) + + max_logging.log("Compiling MPMD step...") + mpmd_lowered = mpmd_runnable.lower() + mpmd_step = mpmd_lowered.compile() + mpmd_state, mpmd_batch = runner_lib.place_on_stage_meshes( + (mpmd_runnable.state, mpmd_runnable.batch), + mpmd_lowered.function_named_shardings.input_specs, + ) + + mpmd_losses, mpmd_grads = [], None + for step in range(hparams.steps): + mpmd_state, mpmd_loss = mpmd_step(mpmd_state, mpmd_batch) + mpmd_losses.append(float(mpmd_loss)) + max_logging.log(f" MPMD step {step + 1}/{hparams.steps}: {mpmd_losses[-1]:.9f}") + if step == 0: + # Read before the next step donates the state. + mpmd_grads = _step1_gradients(mpmd_state.opt_state) + mpmd_params = jax.device_get(mpmd_state.params) + del mpmd_state + + max_logging.log("Running the SPMD reference...") + spmd_losses, spmd_grads, spmd_params = _run_reference(spmd_runnable, hparams.steps) + for step, loss in enumerate(spmd_losses): + max_logging.log(f" SPMD step {step + 1}/{hparams.steps}: {loss:.9f}") + spmd_params = jax.device_get(spmd_params) + del spmd_runnable + + floor = None + if floor_microbatches > 0: + max_logging.log(f"Running the SPMD reference with {floor_microbatches} microbatches" " (noise floor)...") + floor_runnable = runner_lib.build( + dataclasses.replace(hparams, num_microbatches=floor_microbatches), + mode=train_step_lib.ExecutionMode.SPMD, + config_overrides=config_overrides, + ) + floor_losses, floor_grads, floor_params = _run_reference(floor_runnable, hparams.steps) + for step, loss in enumerate(floor_losses): + max_logging.log(f" floor step {step + 1}/{hparams.steps}: {loss:.9f}") + floor = (floor_losses, floor_grads, jax.device_get(floor_params)) + + notes = parity_notes( + mpmd_runnable.maxtext_config, + mpmd_runnable.plan.topology.data_parallel_size, + platform=mpmd_runnable.plan.layer_mesh.devices.flat[0].platform, + ) + return assemble_result( + reference=(spmd_losses, spmd_grads, spmd_params), + mpmd_run=(mpmd_losses, mpmd_grads, mpmd_params), + floor=floor, + floor_microbatches=floor_microbatches, + notes=notes, + ) + + +def parity_notes(maxtext_config: Any, data_parallel_size: int, platform: str = "") -> list[str]: + """Returns the caveats a configuration's report should print (`platform`: the devices', e.g. ``tpu``).""" + notes = [] + compute_dtype = jnp.dtype(maxtext_config.dtype) + exact = ("highest", "float32") + missing = [] + if maxtext_config.matmul_precision not in exact: + # deepseek3-tiny in float32 with all 16 experts routed at PP=4 x FSDP=2 on + # TPU7x: step-2 loss 4.3e-4 from the reference against a floor of 1.6e-5, + # and attention-norm gradients 1.9%, at the default precision; 1.4e-4 + # (floor 2.7e-4) and 0.42% (bound 1.14%) at highest. + missing.append("--maxtext_overrides=matmul_precision=highest") + if maxtext_config.decoder_block == DecoderBlockType.SIMPLE_MLP and jax.config.jax_default_matmul_precision not in exact: + # matmul_precision reaches only the simple model's output head: its + # layers' jnp.dot take JAX's default precision (simple in float32 on + # TPU7x: step-1 gradients 1.15e-3 from the reference with + # matmul_precision=highest alone, 3.2e-7 with both). + missing.append("JAX_DEFAULT_MATMUL_PRECISION=highest (the simple model's layers take JAX's default precision)") + if platform == "tpu" and compute_dtype == jnp.float32 and missing: + notes.append( + "On TPU a float32 matmul at the default precision multiplies in bfloat16 passes, whose rounding the" + " differently fused MPMD fragments and the single program do not share: for a like-for-like check add" + f" {' and '.join(missing)}." + ) + if data_parallel_size > 1 and compute_dtype != jnp.float32: + # `models._bind_pregathered` / `_cast_sharded` reduce-scatter the gathered + # weights' gradients in the compute dtype, for speed; the unsharded + # reference accumulates float32 gradients. The floor run is unsharded too. + notes.append( + f"MPMD reduce-scatters gradients over the stage's devices in" + f" {compute_dtype.name}, the unsharded reference accumulates them in" + " float32, and the noise floor does not see that: for a like-for-like" + " check run with --maxtext_overrides=dtype=float32." + ) + num_experts = maxtext_config.num_experts + top_k = maxtext_config.num_experts_per_tok + if 1 < num_experts and top_k < num_experts: + # deepseek3-tiny in float32 at PP=4 x FSDP=2 (or --expert=2) on a v5p-16: + # step-1 loss 6.9e-6 from the reference (floor 3.7e-7), router gradients + # 4.4% (floor 0.8%); with all 16 experts routed, 1.6e-6 (floor 3.1e-6) + # and every gradient within 0.71%. + notes.append( + f"Each token goes to {top_k} of {num_experts} experts. Where two" + " experts' scores nearly tie, the MPMD program's rounding (its" + " fragments fuse differently from the single program) can pick the" + " other one, which moves the loss and the router and expert gradients" + " in a jump that the floor, an SPMD run, need not show. If only those" + " fail, check the MoE machinery without the discontinuity by" + " rerunning with" + f" --maxtext_overrides=num_experts_per_tok={num_experts}." + ) + return notes + + +def assemble_result( + *, + reference: tuple[Sequence[float], Any, Any], + mpmd_run: tuple[Sequence[float], Any, Any], + floor: tuple[Sequence[float], Any, Any] | None = None, + floor_microbatches: int = 0, + notes: Sequence[str] = (), +) -> ParityResult: + """Compares the runs' ``(losses, step-1 gradients, final params)``. + + Args: + reference: The SPMD reference run. + mpmd_run: The MPMD run. + floor: The noise-floor run (the reference with another microbatch split), + or None. + floor_microbatches: The floor run's microbatch count. + notes: Caveats printed with the report. + + Returns: + The :class:`ParityResult`. + """ + ref_losses, ref_grads, ref_params = reference + + def compare(run) -> Comparison: + losses, grads, params = run + return Comparison( + losses=tuple(losses), + reference_losses=tuple(ref_losses), + # Gradient norms are far below 1: floor the denominator at 1e-5. + grads=_compare_params(grads, ref_grads, norm_floor=1e-5), + params=_compare_params(params, ref_params), + ) + + return ParityResult( + mpmd=compare(mpmd_run), + floor=compare(floor) if floor is not None else None, + floor_microbatches=floor_microbatches if floor is not None else 0, + num_params=len(jax.tree_util.tree_leaves(ref_params)), + notes=tuple(notes), + ) + + +def main(argv: Sequence[str], flag_values: flags.FlagValues = flags.FLAGS) -> None: + if len(argv) > 1: + raise app.UsageError(f"Unexpected command line arguments: {argv[1:]}") + # Registers the Pathways proxy backend when JAX_PLATFORMS contains "proxy"; + # it must run before the backend is first used. + pathwaysutils.initialize() + + fv = flag_values + hparams = hparams_lib.from_flags(fv) + result = check_parity( + hparams, + floor_microbatches=noise_floor_microbatches(hparams.num_microbatches, fv.noise_floor_microbatches), + ) + + max_logging.log("=" * 72) + max_logging.log("MPMD vs SPMD numerical parity") + max_logging.log("=" * 72) + tolerances = (fv.loss_tolerance, fv.param_tolerance, fv.grad_tolerance, fv.noise_floor_factor) + max_logging.log(result.report(*tolerances)) + max_logging.log("=" * 72) + + if result.passed(*tolerances): + max_logging.log("PARITY PASSED") + return + raise SystemExit("PARITY FAILED: see the differences reported above.") + + +if __name__ == "__main__": + define_flags() + jax.config.config_with_absl() + app.run(main) diff --git a/src/maxtext/experimental/mpmd/partir/pipeline.py b/src/maxtext/experimental/mpmd/partir/pipeline.py new file mode 100644 index 0000000000..560c3f3211 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/pipeline.py @@ -0,0 +1,520 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Construction of the Shardy MPMD (OSS PartIR:MPMD) configuration. + +This is the one place that decides how a :class:`hparams.Hparams` becomes an +``mpmd.Config``, so that the trainer and the lowering check build the same +program: "it lowers" then says something about "it runs". + +Written for OSS Shardy MPMD as jaxlib 0.11.1 to 0.12.1 pin it (see +``sdy_mpmd_versions.SHARDY_COMMITS``), which shapes it: + + * options are a plain dict of ``mpmd_*`` keys, and the schedule is a string + (:data:`hparams.OSS_SCHEDULE_NAMES`); + * jaxlib's MPMD driver reads only five boolean options and the schedule + (``ParsePartitioningOptions`` in mpmd_program.cc); the others are accepted + by Python and then ignored, so they stay at their defaults; + * nothing ties an output's layout to an input's (``make_config`` has no + such argument); see :func:`build_plan`; + * the lowered IFRT IR lives at ``lowered.partitioning_result.ifrt_ir_module``, + a frozen dataclass, which :func:`pin_ifrt_transfers_to_producers` replaces. + +Shardy MPMD is an optional dependency (``sdy_mpmd_compat``): it is imported +when an ``mpmd.Config`` is first needed, so building a :class:`PipelinePlan` for +the SPMD reference, and the tests that only do that, run without it. +""" + +from __future__ import annotations + +from collections.abc import Sequence +import dataclasses +import functools +import re +from typing import TYPE_CHECKING, Any + +from maxtext.experimental.mpmd.partir import hparams as hparams_lib +from maxtext.experimental.mpmd.partir import mesh_utils + +if TYPE_CHECKING: + from maxtext.experimental.mpmd.partir.sdy_mpmd_compat import mpmd + from maxtext.experimental.mpmd.partir.sdy_mpmd_compat import shardy_pipeline + +# Partitioning options applied to every MPMD program built here. +# +# `infer_transfers` lets Shardy insert the cross-mesh transfers implied by the +# data dependencies between named computations, and +# `infer_cross_mesh_reductions` does the same for the gradient reductions that +# appear when a parameter is used on more than one mesh. Without them the user +# has to write every transfer by hand. +_BASE_PARTITIONING_OPTIONS = { + "mpmd_infer_cross_mesh_reductions": True, + "mpmd_infer_transfers": True, + # Ignored by jaxlib's driver (always False there); kept so the program + # asks for it once the driver reads it. + "mpmd_absorb_inferred_fragments_on_entry_point_function": True, + # Keep per-microbatch activation/gradient transfers independent: merging + # adjacent `ifrt.CopyArrays` across microbatches (e.g. `dX_2k` and + # `dX_{2k+1}` on stage 3 in 1F1B) creates a false cross-microbatch barrier + # that stalls upstream stages until both microbatches complete. Also + # ignored by jaxlib's driver, whose default is the same False. + "mpmd_apply_merge_transfers_pass": False, +} + + +def shardy_mpmd() -> Any: + """Returns Shardy MPMD's frontend (``mpmd``), importing it (``sdy_mpmd_compat``) on first use.""" + from maxtext.experimental.mpmd.partir import sdy_mpmd_compat # pylint: disable=import-outside-toplevel + + return sdy_mpmd_compat.mpmd + + +def _shardy_pipeline() -> Any: + """Returns Shardy MPMD's ``pipeline`` module (schedules and merge rules), importing it on first use.""" + from maxtext.experimental.mpmd.partir import sdy_mpmd_compat # pylint: disable=import-outside-toplevel + + return sdy_mpmd_compat.shardy_pipeline + + +@dataclasses.dataclass(frozen=True) +class PipelinePlan: + """Everything needed to lower and run one MPMD pipeline. + + Attributes: + topology: The stage meshes backing the pipeline. + name_to_mesh: Mapping from named computation to mesh name. + name_to_stage: Mapping from named computation to stage id. + schedule: The schedule in use (a :data:`hparams.PIPELINE_SCHEDULES` name). + num_repeats: Pipeline traversals per forward pass (see :func:`build_plan`). + """ + + topology: mesh_utils.StageTopology + name_to_mesh: dict[str, str] + name_to_stage: dict[str, int] + schedule: str + num_repeats: int = 1 + + @functools.cached_property + def mpmd_config(self) -> mpmd.Config: + """Returns the Shardy MPMD configuration, built (and Shardy imported) on first use. + + Raises: + ValueError: If Shardy's sharding mesh is not :attr:`sharding_mesh`, which + the shardings built from it assume. + """ + config = _make_mpmd_config(self) + if config.sharding_mesh != self.sharding_mesh: + raise ValueError( + f"Shardy MPMD's sharding mesh {config.sharding_mesh} is not stage 0's abstract mesh {self.sharding_mesh}." + ) + return config + + @property + def sharding_mesh(self) -> Any: + """Returns the abstract mesh logical parameter shardings resolve against. + + It is what ``mpmd.Config.sharding_mesh`` returns, stage 0's abstract mesh: + every stage mesh has the same shape and axis names, and Shardy re-shards each + parameter onto its own stage's mesh when it partitions. + """ + return self.topology.meshes[mesh_utils.mesh_name(0)].abstract_mesh + + @property + def layer_mesh(self) -> Any: + """Returns a concrete stage mesh, for *building* the model's layers. + + `sharding_mesh` is abstract. Under MPMD the parameters of different stages + live on different device meshes, so no single concrete mesh spans them. + That is fine for resolving logical shardings, but some MaxText layers + inspect the mesh's devices while tracing -- DeepSeek's MLA attention picks + its kernel with `self.mesh.devices[...].platform` (MaxText's + `layers/attention_op.py`) -- and an abstract mesh raises `ValueError: AbstractMesh does not implement + devices`. Stage 0's mesh, whose abstract mesh `sharding_mesh` is, stands in. + """ + return self.topology.meshes[mesh_utils.mesh_name(0)] + + @property + def num_devices(self) -> int: + """Returns the total number of devices across all stages.""" + return self.topology.num_stages * self.topology.devices_per_stage + + def describe(self) -> str: + """Returns a short human readable summary of the plan.""" + stage_counts: dict[str, int] = {} + for name, mesh in self.name_to_mesh.items(): + if name.startswith(("pre_m", "post_m")): + continue + stage_counts[mesh] = stage_counts.get(mesh, 0) + 1 + placement = ", ".join( + f"{mesh_utils.mesh_name(i)}:{stage_counts.get(mesh_utils.mesh_name(i), 0)}" + for i in range(self.topology.num_stages) + ) + return ( + f" schedule : {self.schedule}\n" + f" topology : {self.topology.describe()}\n" + f" total devices : {self.num_devices}\n" + f" computations : {placement}" + ) + + +def _merge_last_stage_fwd_bwd( + f1: shardy_pipeline.FragmentInfo, + f2: shardy_pipeline.FragmentInfo, + context: shardy_pipeline.PipelineContext, +) -> bool: + """Merges forward and backward fragments of the same microbatch on the last stage. + + A split backward (the Zero Bubble schedules) merges its activation-gradient + fragment B_a with the forward; the weight-gradient fragment B_w stays apart, for + the schedule to place. + """ + sdy_pipeline = _shardy_pipeline() + info = sdy_pipeline.get_staged_scheduling_info(f1, f2, "last-stage fwd-bwd merge") + if info is None: + return False + call_f1, transpose_f1, call_f2, transpose_f2 = info + return ( + f1.stage_id == context.num_meshes - 1 + and f2.stage_id == context.num_meshes - 1 + and call_f1 == call_f2 + and transpose_f1 != transpose_f2 + and sdy_pipeline.SplitFragmentType.DROP_TRANSFERRED not in (f1.split_type, f2.split_type) + ) + + +def build_plan( + hparams: hparams_lib.Hparams, + *, + devices: Sequence[Any] | None = None, + num_repeats: int = 1, +) -> PipelinePlan: + """Builds the MPMD pipeline described by `hparams`. + + Args: + hparams: Pipeline hyperparameters. + devices: Devices to build the stage meshes from. Defaults to + ``jax.devices()``; AOT callers pass virtual topology devices instead. + num_repeats: Number of pipeline traversals per forward pass. Values > 1 + produce a circular (interleaved) layer placement. + + Returns: + The resulting :class:`PipelinePlan`; its ``mpmd_config`` is built when it is + first read. + """ + if devices is None: + devices = mesh_utils.resolve_devices() + + topology = mesh_utils.create_stage_meshes( + devices=devices, + num_stages=hparams.num_stages, + fsdp_size=hparams.fsdp, + expert_size=hparams.expert, + ) + name_to_mesh = mesh_utils.create_name_to_mesh_assignment( + num_layers=hparams.num_layers, + num_stages=hparams.num_stages, + num_repeats=num_repeats, + stage_layer_counts=hparams.stage_layer_counts, + ) + name_to_stage = mesh_utils.create_name_to_stage_assignment( + num_layers=hparams.num_layers, + num_stages=hparams.num_stages, + num_repeats=num_repeats, + stage_layer_counts=hparams.stage_layer_counts, + ) + return PipelinePlan( + topology=topology, + name_to_mesh=name_to_mesh, + name_to_stage=name_to_stage, + schedule=hparams.pipeline_schedule, + num_repeats=num_repeats, + ) + + +def _make_mpmd_config(plan: PipelinePlan) -> mpmd.Config: + """Builds `plan`'s ``mpmd.Config``: schedule, partitioning options and merge rule.""" + sdy_pipeline = _shardy_pipeline() + partitioning_options: dict[str, bool | str] = dict(_BASE_PARTITIONING_OPTIONS) + partitioning_options["mpmd_pipeline_schedule"] = hparams_lib.OSS_SCHEDULE_NAMES[plan.schedule] + if plan.schedule.startswith("ZERO_BUBBLE_"): + # The Zero Bubble schedules order split backward fragments. With this option + # (one of the five options jaxlib's driver reads) Shardy's + # SplitBwdFragmentsPass cuts each backward fragment that transfers a result + # upstream into B_a, which computes the transferred activation gradient + # (split_keep_transferred), and B_w, which computes the rest -- the weight + # gradients -- from residuals B_a returns (split_drop_transferred); the + # schedule runs B_w in what would be a bubble. The first stage transfers + # nothing upstream, so its backward stays whole, and a weight gradient + # computed by the op that also gives the activation gradient (the routed + # experts' in MaxText's MoE shard_map) stays in B_a. pipeline_test checks + # the split. + partitioning_options["mpmd_split_bwd_fragments"] = True + + # Stage ids are passed explicitly: OSS does not fill them in from the mesh + # index for the 1F1B / GPipeBut1F1B / ZB schedules, and the predicate rules + # (`get_staged_scheduling_info`) raise on a fragment without one. + make_config_kwargs: dict[str, Any] = { + "partitioning_options": partitioning_options, + "name_to_stage_assignment": plan.name_to_stage, + } + if plan.num_repeats == 1 and (plan.schedule == "ONE_FWD_ONE_BWD" or plan.schedule.startswith("ZERO_BUBBLE_")): + # The last stage runs each microbatch's forward and backward -- under the + # Zero Bubble schedules, its B_a -- back to back; merged, the forward's + # residuals (the output head's logits among them) stay inside one program, + # and B_w stays a fragment of its own (_merge_last_stage_fwd_bwd). + # MergeForwardWithBackwardPass merges F_{S-1}(m) and B_{S-1}(m) at the + # consumer position B_{S-1}(m) (after F_{S-2}(m+1) -> T_{S-2,S-1}(m+1)), + # which places T_{S-2,S-1}(m) and T_{S-2,S-1}(m+1) adjacent before + # F_{S-1}B_{S-1}(m) and causes IfrtMergeCopiesAndReshardsPass to fuse them. + # RuleBasedMergePass instead merges F_{S-1}(m) and B_{S-1}(m) at the + # producer position F_{S-1}(m) (immediately after T_{S-2,S-1}(m) and before + # T_{S-2,S-1}(m+1)), keeping every forward and backward transfer unmerged. + # (OSS never runs MergeForwardWithBackwardPass, and it honours merge + # rules, so this rule is the only forward/backward merge.) + make_config_kwargs["pipeline_schedule"] = sdy_pipeline.PipelineSchedule( + schedule_merge_rule_builders=[ + functools.partial( + sdy_pipeline.build_merge_rules_from_predicate, + pred=_merge_last_stage_fwd_bwd, + ) + ] + ) + + # The new state (output 0) must be laid out exactly like the state that + # produced it (input 0), or the second call rejects its own predecessor's + # output with "Input signature does not match the signature of the compiled + # function". OSS `make_config` has no argument that ties the new state's + # layout to the old one, so the callers pin the state's shardings on both + # sides (`mpmd.jit(in_shardings=..., out_shardings=(state_shardings, + # None))`), and each parameter's update is computed on the mesh that holds + # it, so the meshes agree; `train.py` checks it by feeding step N's state to + # step N+1. + return shardy_mpmd().make_config(plan.topology.meshes, plan.name_to_mesh, **make_config_kwargs) + + +_SSA_TOKEN_RE = re.compile(r"(%[A-Za-z0-9_]+(?:#\d+)?)(?![A-Za-z0-9_#])") +_IFRT_CALL_RE = re.compile(r"^\s*(%[A-Za-z0-9_]+)(?::\d+)?,\s*(%[A-Za-z0-9_]+)\s*=\s*ifrt\.Call\b") +_COPY_HEADER_RE = re.compile( + r"^(\s*)(%[A-Za-z0-9_]+)(?::(\d+))?,\s*(%[A-Za-z0-9_]+)\s*=\s*" r"ifrt\.CopyArrays\(([^)]*)\)(.*)$" +) + + +def _split_top_level_comma(text: str) -> list[str]: + """Splits a comma-separated MLIR list at bracket depth 0.""" + parts: list[str] = [] + depth = 0 + start = 0 + for idx, ch in enumerate(text): + if ch in "<([{": + depth += 1 + elif ch in ">)]}": + depth = max(0, depth - 1) + elif ch == "," and depth == 0: + part = text[start:idx].strip() + if part: + parts.append(part) + start = idx + 1 + tail = text[start:].strip() + if tail: + parts.append(tail) + return parts + + +def _split_arrow_top_level(text: str) -> tuple[str, str] | None: + """Splits ``(in_types) -> out_types`` at bracket depth 0.""" + depth = 0 + for idx, ch in enumerate(text): + if ch in "<([{": + depth += 1 + elif ch in ">)]}": + depth = max(0, depth - 1) + elif depth == 0 and text.startswith(" -> ", idx): + return text[:idx].strip(), text[idx + 4 :].strip() + return None + + +def _replace_ssa_tokens(line: str, replacements: dict[str, str]) -> str: + """Replaces exact SSA token occurrences in an MLIR statement line.""" + if not replacements: + return line + return _SSA_TOKEN_RE.sub(lambda m: replacements.get(m.group(1), m.group(1)), line) + + +def pin_ifrt_transfers_to_producers(lowered: Any) -> Any: + """Un-merges cross-microbatch ``ifrt.CopyArrays`` and pins them to producers. + + Both MPMD's ``LowerToIfrt`` and IFRT's ``CompiledIfrtIrProgram::Create`` + (invoked inside ``lowered.compile()``) unconditionally run + ``IfrtMergeCopiesAndReshardsPass``, which batches any two ``ifrt.CopyArrays`` + in ``@main`` that share ``(source_devices, dst_devices, donated)`` and have + empty ``getControlInputs()``. In 1F1B steady state on the last stage, two + ``fwd_bwd`` calls execute between upstream ``bwd`` calls, so their activation + gradient transfers ``dX_{2k}`` and ``dX_{2k+1}`` get merged into a single + ``ifrt.CopyArrays`` scheduled after ``fwd_bwd_{2k+1}``, stalling upstream + ``bwd_{2k}`` for an entire extra ``fwd_bwd`` duration. + + This function: + 1. Splits any ``ifrt.CopyArrays`` whose inputs come from multiple distinct + ``ifrt.Call`` producers into one ``ifrt.CopyArrays`` per producer Call, + placed immediately after that producer Call. + 2. Attaches ``after %producer_control_output`` to every ``ifrt.CopyArrays`` + that depends on an ``ifrt.Call`` producer, which causes + ``IfrtMergeCopiesAndReshardsPass`` inside ``lowered.compile()`` to keep + each microbatch's transfer independent. + + The stall was measured with jax 0.11.1. With jax 0.12.0.1, Shardy 38ab99f4 + and Pathways 20261117 on TPU7x, deepseek3-tiny's 1F1B and GPipe programs (PP=4, + 8 microbatches) ran the same 51 transfers a step with and without the pins + (one ``TransferManager::Recv`` per copy and destination device in the trace), + at the same step time within noise: nothing was merged either way, and the + pins are a guard for the stacks and schedules that do merge. On that stack + ``LowerToIfrt`` does merge two producers' transfers for + GPipeBut1F1BForLastMesh, ZB-H1 and the ZB-H2 schedules, which step 1 splits + (``pipeline_test`` checks the rewrite on a synthetic program). + + Args: + lowered: The :class:`MpmdLowered` object returned by + ``mpmd.jit(...).lower``. + + Returns: + ``lowered`` with its IFRT IR module replaced in-place. OSS keeps the module + only in the frozen ``lowered.partitioning_result`` (there is no + ``lowered.ifrt_ir_module``); ``compile()`` and ``as_text("ifrt")`` read it + from there, so that is what gets replaced. + """ + result = lowered.partitioning_result + orig_module = result.ifrt_ir_module + + ir_text = str(orig_module) + func_pos = ir_text.find("func.func public @main(") + if func_pos < 0: + return lowered + sig_end = ir_text.find("\n", func_pos) + if sig_end < 0: + return lowered + body_start = sig_end + 1 + body_end = ir_text.find("\n }\n", body_start) + if body_end < 0: + return lowered + + body_text = ir_text[body_start:body_end] + body_lines = body_text.splitlines() + + # Count occurrences of every SSA token in @main so we never split a CopyArrays + # whose control output is explicitly referenced elsewhere. + token_counts: dict[str, int] = {} + for m in _SSA_TOKEN_RE.finditer(body_text): + tok = m.group(1) + token_counts[tok] = token_counts.get(tok, 0) + 1 + + blocks: list[list[str]] = [] + call_info: dict[str, tuple[int, str]] = {} + ssa_replacements: dict[str, str] = {} + changed = False + + # A line-by-line rewrite of @main's text: one statement per line, with nested matching. + # pylint: disable=too-many-nested-blocks + for raw_line in body_lines: + line = _replace_ssa_tokens(raw_line, ssa_replacements) + if line != raw_line: + changed = True + + m_call = _IFRT_CALL_RE.match(line) + if m_call: + out_base, ctrl_var = m_call.group(1), m_call.group(2) + block_idx = len(blocks) + blocks.append([line]) + call_info[out_base] = (block_idx, ctrl_var) + continue + + if "ifrt.CopyArrays(" in line and " : (!ifrt.array" in line: + header, type_rest = line.split(" : (!ifrt.array", 1) + m_copy = _COPY_HEADER_RE.match(header) + arrow_split = _split_arrow_top_level("(!ifrt.array" + type_rest) + if m_copy and arrow_split is not None: + indent, out_base, _, ctrl_out, inputs_str, tail = m_copy.groups() + in_types_raw, out_types_raw = arrow_split + if in_types_raw.startswith("(") and in_types_raw.endswith(")") and not re.search(r"\bafter\s+%", tail): + in_types = _split_top_level_comma(in_types_raw[1:-1]) + if out_types_raw.startswith("(") and out_types_raw.endswith(")"): + out_types = _split_top_level_comma(out_types_raw[1:-1]) + else: + out_types = [out_types_raw.strip()] + inputs = [x.strip() for x in inputs_str.split(",") if x.strip()] + + if len(inputs) == len(in_types) == len(out_types) and inputs: + input_producers = [call_info.get(inp.split("#", 1)[0]) for inp in inputs] + distinct_producers: list[tuple[int, str]] = [] + for prod in input_producers: + if prod is not None and prod not in distinct_producers: + distinct_producers.append(prod) + + if ( + len(distinct_producers) >= 2 + and all(p is not None for p in input_producers) + and token_counts.get(ctrl_out, 0) <= 1 + ): + groups: list[tuple[tuple[int, str], list[int]]] = [] + group_map: dict[tuple[int, str], list[int]] = {} + for idx, prod in enumerate(input_producers): + assert prod is not None + if prod not in group_map: + idxs: list[int] = [] + group_map[prod] = idxs + groups.append((prod, idxs)) + group_map[prod].append(idx) + + for g_idx, ((prod_block_idx, prod_ctrl), idxs) in enumerate(groups): + sub_out_base = f"{out_base}_pin{g_idx}" + sub_ctrl_out = f"{ctrl_out}_pin{g_idx}" + if len(idxs) == 1: + lhs = f"{sub_out_base}, {sub_ctrl_out}" + rhs_out_type = out_types[idxs[0]] + ssa_replacements[f"{out_base}#{idxs[0]}"] = sub_out_base + else: + lhs = f"{sub_out_base}:{len(idxs)}, {sub_ctrl_out}" + rhs_out_type = "(" + ", ".join(out_types[i] for i in idxs) + ")" + for j, orig_i in enumerate(idxs): + ssa_replacements[f"{out_base}#{orig_i}"] = f"{sub_out_base}#{j}" + rhs_in_type = "(" + ", ".join(in_types[i] for i in idxs) + ")" + sub_inputs = ", ".join(inputs[i] for i in idxs) + sub_line = ( + f"{indent}{lhs} = ifrt.CopyArrays({sub_inputs}) after" + f" {prod_ctrl}{tail} : {rhs_in_type} -> {rhs_out_type}" + ) + blocks[prod_block_idx].append(sub_line) + + blocks.append([]) + changed = True + continue + + if len(distinct_producers) == 1: + _, prod_ctrl = distinct_producers[0] + prefix = header[: len(header) - len(tail)] + pinned_line = f"{prefix} after {prod_ctrl}{tail} : (!ifrt.array{type_rest}" + blocks.append([pinned_line]) + changed = True + continue + + blocks.append([line]) + + if not changed: + return lowered + + new_body_lines: list[str] = [] + for block in blocks: + new_body_lines.extend(block) + new_ir_text = ir_text[:body_start] + "\n".join(new_body_lines) + ir_text[body_end:] + new_module = type(orig_module).parse(new_ir_text, context=orig_module.context) + lowered.partitioning_result = dataclasses.replace(result, ifrt_ir_module=new_module) + return lowered diff --git a/src/maxtext/experimental/mpmd/partir/runner.py b/src/maxtext/experimental/mpmd/partir/runner.py new file mode 100644 index 0000000000..029820a65f --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/runner.py @@ -0,0 +1,380 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Assembles a runnable MPMD pipeline from hyperparameters. + +``train.py``, ``train_compile.py``, ``parity.py`` and the unit tests all build +their model, data and training step through :func:`build`, and lower it with +:meth:`Runnable.lower`, so a lowering and the run it is supposed to predict +describe the same program. +""" + +from __future__ import annotations + +from collections.abc import Sequence +import dataclasses +from typing import Any + +from flax import nnx +from flax.training import train_state +import jax +import jax.numpy as jnp +import numpy as np + +from maxtext.experimental.mpmd.partir import config as config_lib +from maxtext.experimental.mpmd.partir import hparams as hparams_lib +from maxtext.experimental.mpmd.partir import models +from maxtext.experimental.mpmd.partir import pipeline as pipeline_lib +from maxtext.experimental.mpmd.partir import train_step as train_step_lib + + +def make_synthetic_batch( + *, + batch_size: int, + seq_len: int, + vocab_size: int, + seed: int, + abstract: bool = False, +) -> dict[str, Any]: + """Builds a deterministic synthetic training batch. + + The same `seed` always yields the same tokens, which is what allows the MPMD + run and the SPMD reference to be compared value-for-value. + + Args: + batch_size: Global batch size (across one stage mesh). + seq_len: Sequence length. + vocab_size: Vocabulary size to sample token ids from. + seed: Seed for the token sampler. + abstract: When True return ``jax.ShapeDtypeStruct`` placeholders instead of + concrete arrays, for ahead-of-time lowering. + + Returns: + A dict with the keys listed in :data:`train_step.BATCH_KEYS`. + """ + if abstract: + spec = jax.ShapeDtypeStruct((batch_size, seq_len), jnp.int32) + return {key: spec for key in train_step_lib.BATCH_KEYS} + + rng = np.random.default_rng(seed) + # `seq_len + 1` tokens so that targets are the inputs shifted by one. + tokens = rng.integers(0, vocab_size, size=(batch_size, seq_len + 1), dtype=np.int32) + positions = np.tile(np.arange(seq_len + 1, dtype=np.int32), (batch_size, 1)) + # Every position is a real token: segment id 1, no padding. + segmentation = np.ones((batch_size, seq_len), dtype=np.int32) + return { + "inputs": jnp.asarray(tokens[:, :-1]), + "inputs_position": jnp.asarray(positions[:, :-1]), + "inputs_segmentation": jnp.asarray(segmentation), + "targets": jnp.asarray(tokens[:, 1:]), + "targets_position": jnp.asarray(positions[:, 1:]), + "targets_segmentation": jnp.asarray(segmentation), + } + + +shard_tree_on_fsdp = models.shard_tree_on_fsdp + + +def place_on_stage_meshes(inputs: Any, input_specs: Any) -> Any: + """Commits `inputs` onto the meshes an MPMD executable expects. + + ``Lowered.function_named_shardings.input_specs`` is a *flat* sequence with + one :class:`jax.sharding.NamedSharding` per flattened argument leaf, and + different leaves generally live on different stage meshes. It is therefore + not a pytree prefix of the arguments: handing the pair + ``(state, batch)`` and the flat specs to :func:`jax.device_put` in one go + produces arrays the executable rejects with:: + + INVALID_ARGUMENT: Input signature does not match the signature of the + compiled function. + + Args: + inputs: The pytree of arguments, in the order they were lowered with. + input_specs: The flat shardings reported by the lowering. + + Returns: + `inputs` with every leaf committed to its mesh. + + Raises: + ValueError: If the number of leaves and shardings disagree, which means + the arguments are not the ones that were lowered. + """ + leaves, treedef = jax.tree_util.tree_flatten(inputs) + specs = jax.tree_util.tree_leaves(input_specs) + if len(leaves) != len(specs): + raise ValueError( + f"Lowering expects {len(specs)} input arrays but {len(leaves)} were" + " supplied; the arguments differ from the ones lowered." + ) + return jax.tree_util.tree_unflatten( + treedef, + [jax.device_put(leaf, spec) for leaf, spec in zip(leaves, specs)], + ) + + +@dataclasses.dataclass(frozen=True) +class Runnable: + """A fully assembled, not-yet-lowered MPMD training program. + + Attributes: + hparams: The hyperparameters this was built from. + maxtext_config: The materialised MaxText config. + plan: The MPMD pipeline plan (topology, schedule, mesh assignment). + graphdef: Static model structure. + state: Initial optimizer state (concrete, or abstract when ``abstract=True`` + was requested). + batch: A training batch (concrete or abstract). + train_step: The function to lower, ``(state, batch) -> (state, loss)``. + in_shardings: Input shardings for ``mpmd.jit``. + batch_size: Global batch size. + """ + + hparams: hparams_lib.Hparams + maxtext_config: Any + plan: pipeline_lib.PipelinePlan + graphdef: models.PipelineGraphDef + state: train_state.TrainState + batch: dict[str, Any] + train_step: Any + in_shardings: tuple[Any, Any] + batch_size: int + + @property + def out_shardings(self) -> tuple[Any, None]: + """Output shardings matching ``(new_state, loss)``.""" + return (self.in_shardings[0], None) + + def lower(self) -> Any: + """Lowers :attr:`train_step` with ``mpmd.jit`` and pins its transfers. + + The state is donated and its shardings are pinned on both sides, so that + step N's state is what step N+1 accepts (see ``pipeline._make_mpmd_config``); + :func:`pipeline.pin_ifrt_transfers_to_producers` keeps each microbatch's + transfers apart. + + Returns: + The ``MpmdLowered`` program, to compile on Pathways. + """ + lowered = ( + pipeline_lib.shardy_mpmd() + .jit( + self.train_step, + mpmd_config=self.plan.mpmd_config, + in_shardings=self.in_shardings, + out_shardings=self.out_shardings, + donate_argnums=(0,), + ) + .lower(self.state, self.batch) + ) + return pipeline_lib.pin_ifrt_transfers_to_producers(lowered) + + def describe(self) -> str: + """Returns a multi-line summary of model, pipeline and batch.""" + return "\n".join( + [ + "MaxText configuration:", + config_lib.describe(self.maxtext_config, self.hparams), + "Pipeline plan:", + self.plan.describe(), + ( + f" global batch : {self.batch_size}" + f" ({self.batch_size // self.hparams.num_microbatches} per" + " microbatch)" + ), + ] + ) + + +def build( + hparams: hparams_lib.Hparams, + *, + devices: Sequence[Any] | None = None, + mode: train_step_lib.ExecutionMode = train_step_lib.ExecutionMode.MPMD, + abstract: bool = False, + config_overrides: dict[str, Any] | None = None, + check_microbatches: bool = False, +) -> Runnable: + """Builds everything needed to lower or run one training step. + + Args: + hparams: Hyperparameters. + devices: Devices for the stage meshes. Defaults to ``jax.devices()``. + mode: Whether to build the MPMD (pipelined) or SPMD (reference) step. + abstract: Build abstract (shape-only) state and data, for AOT compilation on + a machine with no accelerators. + config_overrides: Extra MaxText settings, for tests. + check_microbatches: Refuse a microbatch that does not split over a stage's + batch-sharding devices (:func:`hparams.check_microbatch_split`), which only + the TPUs would otherwise reject. The entry points ask for it; tests build + such configurations on CPU. + + Returns: + The assembled :class:`Runnable`. + + Raises: + ValueError: If the global batch is not divisible by the microbatch count, + or (with `check_microbatches`) a microbatch not by the stage's + batch-sharding devices. + """ + maxtext_config = config_lib.build_maxtext_config(hparams, overrides=config_overrides) + plan = pipeline_lib.build_plan(hparams, devices=devices) + if mode is train_step_lib.ExecutionMode.MPMD: + # Builds the Shardy MPMD configuration now, so that a missing shardy-mpmd + # or a configuration Shardy refuses fails before the model is initialised. + _ = plan.mpmd_config + if check_microbatches: + # Before any parameter or optimizer state exists: a large model takes + # minutes to initialise. + hparams_lib.check_microbatch_split( + hparams, + devices_per_stage=plan.topology.devices_per_stage, + data_parallel_size=plan.topology.data_parallel_size, + ) + + # The batch is sharded across a *single* stage's devices: every microbatch + # traverses all stages, so the data-parallel width is the width of one stage, + # not of the whole slice. + batch_size = int(maxtext_config.per_device_batch_size * plan.topology.devices_per_stage) + if batch_size % hparams.num_microbatches: + raise ValueError( + f"Global batch size ({batch_size} = per_device_batch_size" + f" {maxtext_config.per_device_batch_size} x" + f" {plan.topology.devices_per_stage} devices per stage) must be" + f" divisible by num_microbatches ({hparams.num_microbatches})." + ) + + batch = make_synthetic_batch( + batch_size=batch_size, + seq_len=maxtext_config.max_target_length, + vocab_size=maxtext_config.vocab_size, + seed=hparams.seed, + abstract=abstract, + ) + + fsdp_size = plan.topology.fsdp_size + if abstract: + + def _init_abstract(): + model = models.PipelinedTransformer( + config=maxtext_config, + # `layer_mesh`, not `sharding_mesh`: building DeepSeek's MLA + # attention reads `mesh.devices` to choose an attention kernel, + # which an abstract mesh cannot answer. + mesh=plan.layer_mesh, + rngs=nnx.Rngs(hparams.seed), + remat_policy=hparams.mpmd_remat_policy, + stage_layer_counts=hparams.stage_layer_counts, + ) + gdef, params = model.split() + st = train_step_lib.create_train_state(params, hparams.learning_rate) + return ( + gdef.embed_def, + gdef.embed_rest, + gdef.layer_defs, + gdef.layer_rests, + gdef.unembed_def, + gdef.unembed_rest, + st, + ) + + ( + embed_def, + embed_rest, + layer_defs, + layer_rests, + unembed_def, + unembed_rest, + state, + ) = jax.eval_shape(_init_abstract) + + try: + cpu_device = jax.devices("cpu")[0] + except RuntimeError: + cpu_device = None + + def _materialize_rest(leaf): + if isinstance(leaf, jax.ShapeDtypeStruct): + if jax.dtypes.issubdtype(leaf.dtype, jax.dtypes.prng_key): + if cpu_device is not None: + with jax.default_device(cpu_device): + return jax.random.key(0) + return jax.random.key(0) + return np.zeros(leaf.shape, dtype=leaf.dtype) + return leaf + + is_deepseek = maxtext_config.decoder_block == models.DecoderBlockType.DEEPSEEK + graphdef = models.PipelineGraphDef( + config=maxtext_config, + embed_def=embed_def, + embed_rest=jax.tree.map(_materialize_rest, embed_rest), + layer_defs=tuple(layer_defs), + layer_rests=tuple(jax.tree.map(_materialize_rest, layer_rests)), + unembed_def=unembed_def, + unembed_rest=jax.tree.map(_materialize_rest, unembed_rest), + is_deepseek=is_deepseek, + fsdp_size=fsdp_size, + mesh=plan.layer_mesh, + remat_policy=hparams.mpmd_remat_policy, + stage_layer_counts=hparams.stage_layer_counts, + ) + else: + unit_shard_fn = None + init_mesh = plan.layer_mesh + if mode is train_step_lib.ExecutionMode.MPMD: + + def _shard_unit(unit_name: str, unit_params: nnx.State) -> nnx.State: + stage_mesh_name = plan.name_to_mesh[unit_name] + stage_mesh = plan.topology.meshes[stage_mesh_name] + return shard_tree_on_fsdp(stage_mesh, unit_params, fsdp_size, device_put=True) + + unit_shard_fn = _shard_unit + else: + # In SPMD reference mode (`parity.py`), `spmd_state` and `spmd_batch` are + # unsharded single-device arrays on device 0. Using a 1-device mesh with + # the same axis names ensures any internal `jax.shard_map(mesh=self.mesh)` + # (such as Qwen3.5 GatedDeltaNet or Splash Attention) executes on that + # same single device rather than demanding a multi-device stage mesh. + single_dev = np.asarray(plan.layer_mesh.devices).flat[:1].reshape((1,) * len(plan.layer_mesh.axis_names)) + init_mesh = jax.sharding.Mesh(single_dev, plan.layer_mesh.axis_names) + + graphdef, params = models.PipelinedTransformer.init_split( + config=maxtext_config, + mesh=init_mesh, + rngs=nnx.Rngs(hparams.seed), + unit_shard_fn=unit_shard_fn, + remat_policy=hparams.mpmd_remat_policy, + stage_layer_counts=hparams.stage_layer_counts, + ) + state = train_step_lib.create_train_state(params, hparams.learning_rate) + + state_shardings = shard_tree_on_fsdp(plan.sharding_mesh, state, fsdp_size, device_put=False) + batch_shardings = shard_tree_on_fsdp(plan.sharding_mesh, batch, fsdp_size, device_put=False) + + train_step = train_step_lib.make_train_step( + graphdef, + vocab_size=maxtext_config.vocab_size, + num_microbatches=hparams.num_microbatches, + mode=mode, + ) + + return Runnable( + hparams=hparams, + maxtext_config=maxtext_config, + plan=plan, + graphdef=graphdef, + state=state, + batch=batch, + train_step=train_step, + in_shardings=(state_shardings, batch_shardings), + batch_size=batch_size, + ) diff --git a/src/maxtext/experimental/mpmd/partir/sdy_mpmd_compat.py b/src/maxtext/experimental/mpmd/partir/sdy_mpmd_compat.py new file mode 100644 index 0000000000..4584350748 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/sdy_mpmd_compat.py @@ -0,0 +1,66 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Imports Shardy MPMD (OSS PartIR:MPMD) on top of the installed jaxlib wheel. + +Shardy MPMD's Python frontend (``shardy.integrations.python.jax.mpmd``) is an optional dependency: it is neither on +PyPI nor in the jax or jaxlib wheels, and it must come from the Shardy commit the installed jaxlib was built from +(``sdy_mpmd_versions.SHARDY_COMMITS``, whose ``install_command`` prints the pip line). Only the code that builds, +lowers or traces an MPMD program imports this module, so the rest of the package runs without it. + +Two Bazel-internal module names that the extension and the frontend import do not exist in the jaxlib wheel: + + * ``jaxlib._sdy_mpmd`` imports ``jax.jaxlib._jax``: the import fails with "No module named 'jax.jaxlib'", and aliasing + only the package makes Python load a second copy of ``_jax.so``, which aborts; + * the frontend's ``jit.py`` does ``from mlir import ir``; the wheel ships MLIR's Python bindings as ``jaxlib.mlir``. + +Each name is pointed at the module jax has already loaded, before the frontend is imported. +""" + +import sys + +import jax # pylint: disable=unused-import +import jaxlib +from jaxlib import _jax +from jaxlib import mlir as jaxlib_mlir +from jaxlib.mlir import ir as jaxlib_mlir_ir + +from maxtext.utils import max_logging + +from maxtext.experimental.mpmd.partir import sdy_mpmd_versions + +# The aliases must exist before `jaxlib._sdy_mpmd` or the frontend is imported. `setdefault` keeps a top-level +# `mlir` module that is already imported; an installed `mlir` package that nothing has imported yet is shadowed. +sys.modules.setdefault("jax.jaxlib", jaxlib) +sys.modules.setdefault("jax.jaxlib._jax", _jax) +sys.modules.setdefault("mlir", jaxlib_mlir) +sys.modules.setdefault("mlir.ir", jaxlib_mlir_ir) + +try: + # pylint: disable=wrong-import-position + from shardy.integrations.python.jax import mpmd + from shardy.integrations.python.jax.mpmd import pipeline as shardy_pipeline +except ModuleNotFoundError as error: + if not (error.name or "").startswith("shardy"): # one of the frontend's own dependencies is missing + raise + raise ModuleNotFoundError( + f"Shardy MPMD's Python frontend is not installed: {sdy_mpmd_versions.install_command(jaxlib.__version__)}.", + name=error.name, + ) from error + +_MISMATCH = sdy_mpmd_versions.version_mismatch(jaxlib.__version__, sdy_mpmd_versions.installed_commit()) +if _MISMATCH: + max_logging.warning(_MISMATCH) + +__all__ = ["mpmd", "shardy_pipeline"] diff --git a/src/maxtext/experimental/mpmd/partir/sdy_mpmd_versions.py b/src/maxtext/experimental/mpmd/partir/sdy_mpmd_versions.py new file mode 100644 index 0000000000..e3249e691c --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/sdy_mpmd_versions.py @@ -0,0 +1,105 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Which Shardy MPMD frontend matches which jaxlib, and how to install it. + +Shardy MPMD's Python frontend (``shardy.integrations.python.jax.mpmd``) is neither on PyPI nor in the jax or jaxlib +wheels, and it must come from the Shardy commit the installed jaxlib was built from, so that it matches the C++ +bindings in ``jaxlib._sdy_mpmd``. :data:`SHARDY_COMMITS` lists those commits; install the frontend with pip:: + + pip install --no-deps \ + "shardy-mpmd @ git+https://github.com/openxla/shardy@#subdirectory=shardy/integrations/python/jax/mpmd" + +(:func:`install_command` prints the line for a jaxlib version). A Shardy checkout on ``PYTHONPATH`` works too. + +This module imports neither jax nor Shardy, so the version table and its checks are usable (and tested) without +shardy-mpmd installed; ``sdy_mpmd_compat`` imports the frontend itself. +""" + +import importlib.metadata +import json +import re +import types + +SHARDY_MPMD_DISTRIBUTION = "shardy-mpmd" +SHARDY_MPMD_SUBDIRECTORY = "shardy/integrations/python/jax/mpmd" + +# The Shardy commit each jaxlib release was built from (XLA's third_party/shardy pin at that jaxlib). jaxlib records +# only its jax commit, so the matching Shardy commit cannot be discovered at run time. +SHARDY_COMMITS = types.MappingProxyType( + { + "0.11.1": "2832731619ffb4bcc718faa4aa8054214a68c969", + "0.12.0.1": "38ab99f4d252c59d491899a694fe8cbadfeccec3", + "0.12.1": "57fffc23dfdf139b80013ad681701cee59c22f96", + } +) + +_COMMIT_RE = re.compile(r"\b[0-9a-f]{40}\b") + + +def install_command(jaxlib_version: str) -> str: + """Returns the pip command that installs the Shardy MPMD frontend matching `jaxlib_version`.""" + commit = SHARDY_COMMITS.get(jaxlib_version) + if commit is None: + known = ", ".join(f"jaxlib {version}" for version in SHARDY_COMMITS) + return ( + f"no Shardy commit is known for jaxlib {jaxlib_version} (known: {known}); install the frontend from the Shardy" + " commit that XLA's third_party/shardy pins at the commit this jaxlib was built from, or install one of the" + " known jaxlib versions" + ) + return ( + f'pip install --no-deps "{SHARDY_MPMD_DISTRIBUTION} @ git+https://github.com/openxla/shardy@{commit}' + f'#subdirectory={SHARDY_MPMD_SUBDIRECTORY}"' + ) + + +def commit_from_direct_url(direct_url: str) -> str | None: + """Returns the Shardy commit recorded in a distribution's PEP 610 ``direct_url.json``, or None. + + pip records the resolved commit of a ``git+https://...@`` install under ``vcs_info``; an archive install + (``https://github.com/openxla/shardy/archive/.zip``) carries the commit in its URL. A local directory install + records neither. + """ + try: + record = json.loads(direct_url) + except ValueError: + return None + commit = record.get("vcs_info", {}).get("commit_id") + if commit: + return commit + match = _COMMIT_RE.search(record.get("url", "")) + return match.group(0) if match else None + + +def installed_commit() -> str | None: + """Returns the Shardy commit the installed ``shardy-mpmd`` distribution came from, or None if it is unknown.""" + try: + direct_url = importlib.metadata.distribution(SHARDY_MPMD_DISTRIBUTION).read_text("direct_url.json") + except importlib.metadata.PackageNotFoundError: # a Shardy checkout on PYTHONPATH + return None + return commit_from_direct_url(direct_url) if direct_url else None + + +def version_mismatch(jaxlib_version: str, commit: str | None) -> str | None: + """Returns why `commit` may not match `jaxlib_version`'s C++, or None when it matches or cannot be checked.""" + expected = SHARDY_COMMITS.get(jaxlib_version) + if expected is None: + return f"Shardy MPMD's Python must match the C++ in jaxlib: {install_command(jaxlib_version)}." + if commit is None or commit == expected: + return None + return ( + f"shardy-mpmd was installed from Shardy {commit[:12]}, but jaxlib {jaxlib_version} was built with Shardy" + f" {expected[:12]}, and its Python must match the C++ in jaxlib. Reinstall it: {install_command(jaxlib_version)}" + " --force-reinstall" + ) diff --git a/src/maxtext/experimental/mpmd/partir/spmd_baseline.py b/src/maxtext/experimental/mpmd/partir/spmd_baseline.py new file mode 100644 index 0000000000..d08906d849 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/spmd_baseline.py @@ -0,0 +1,645 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +r"""Derives the equivalent MaxText **SPMD** pipeline configuration. + +The point of comparison for this package is MaxText's own pipeline +(``maxtext/src/maxtext/layers/pipeline.py``), which implements pipelining +inside a single SPMD program: microbatches are circulated between stages with +``jax.lax.ppermute`` inside a ``shard_map`` over a ``stage`` mesh axis. + +Translating one configuration into the other is not a rename, because the two +define ``per_device_batch_size`` against different device sets: + + * **MPMD** shards the batch over one *stage* mesh, since every microbatch + traverses all stages. Global batch = ``pdbs x devices_per_stage``. + * **MaxText SPMD** shards the batch over *all* devices, the ``stage`` axis + included. Global batch = ``pdbs x total_devices``. + +Comparing the two at the same nominal ``per_device_batch_size`` would +therefore silently give the SPMD run ``num_stages`` times more work per step. +:func:`spmd_flags` performs the conversion so both runs consume the same +number of tokens per step, which is the only basis on which their step times +can be compared. + +Run this module to print the settings and the command that runs MaxText's own +trainer with them (multi-controller JAX, not Pathways); with ``--cluster`` it +wraps the command in a ``gcluster job submit`` (Cluster Toolkit; with +``--launcher=xpk``, the deprecated ``xpk workload create``):: + + python3 -m maxtext.experimental.mpmd.partir.spmd_baseline \ + --pp=4 --fsdp=4 --num_microbatches=4 --per_device_batch_size=4 --device_type=v5p-32 +""" + +from __future__ import annotations + +from collections.abc import Sequence +import shlex +import time + +from absl import app +from absl import flags + +from maxtext.utils import max_logging + +from maxtext.experimental.mpmd.partir import hparams as hparams_lib +from maxtext.experimental.mpmd.partir import launch + +# MaxText's trainer, run as a module from an image that has MaxText installed. +MAXTEXT_TRAIN_MODULE = "maxtext.trainers.pre_train.train" + +# Number of steady-state steps to capture in the xplane profile. Five steps is +# enough to average out per-step jitter while keeping the trace small enough to +# load in the XProf UI. +_PROFILER_STEPS = 5 + +# The flags a cluster command needs besides the device type. +_CLUSTER_FLAGS = ("cluster", "project", "zone", "docker_image") + + +def define_flags(flag_values: flags.FlagValues = flags.FLAGS) -> None: + """Registers the baseline's flags, the hyperparameters' included, on `flag_values`.""" + hparams_lib.define_flags(flag_values) + fv = {"flag_values": flag_values} + flags.DEFINE_string( + "device_type", "", "TPU type of the slice the baseline runs on, e.g. v5p-32, v6e-16, tpu7x-4x4x4.", **fv + ) + flags.DEFINE_integer( + "num_slices", + 1, + "Number of slices. The pipeline's stages go over them as the MPMD run places them (whole stages a slice, or whole" + " slices a stage); --pure_fsdp is data-parallel across them.", + **fv, + ) + flags.DEFINE_integer( + "total_devices", -1, "JAX devices of all the slices. -1 derives them from --device_type and --num_slices.", **fv + ) + flags.DEFINE_string( + "run_name", + "", + "MaxText run_name, and by default the cluster workload's name; empty: spmd-baseline-, so that" + " repeated runs do not collide.", + **fv, + ) + flags.DEFINE_string( + "output_dir", + "", + "MaxText base_output_directory (gs://...), where the xplane profile and TensorBoard files land; empty leaves" + " MaxText's default.", + **fv, + ) + flags.DEFINE_boolean( + "pure_fsdp", + False, + "Emit a Pure FSDP (ici_pipeline_parallelism=1) MaxText configuration with the same global batch size as the MPMD" + " pipeline configuration.", + **fv, + ) + flags.DEFINE_string( + "xla_flags_file", + "", + "File of --key=value XLA flags, one per line with # comments, put in LIBTPU_INIT_ARGS.", + **fv, + ) + flags.DEFINE_string("cluster", "", "GKE cluster: also print the command that runs the baseline on it.", **fv) + flags.DEFINE_enum( + "launcher", + "gcluster", + ["gcluster", "xpk"], + "With --cluster: `gcluster job submit` (Cluster Toolkit), or `xpk workload create` (MaxText has deprecated XPK).", + **fv, + ) + flags.DEFINE_string("project", "", "GCP project of --cluster.", **fv) + flags.DEFINE_string("zone", "", "Zone (or region) of --cluster.", **fv) + flags.DEFINE_string("docker_image", "", "Image with MaxText installed, for --cluster.", **fv) + flags.DEFINE_string("workload", "", "Workload name for --cluster (default: --run_name).", **fv) + flags.DEFINE_string( + "gcluster_compute_type", "", "--launcher=gcluster: --compute-type; empty derives it from --device_type.", **fv + ) + flags.DEFINE_string( + "gcluster_topology", "", "--launcher=gcluster: --topology; empty derives it from --device_type.", **fv + ) + + +devices_in_device_type = hparams_lib.devices_in_device_type +devices_in_platform = hparams_lib.devices_in_platform + + +def deepseek_dense_layers(hparams: hparams_lib.Hparams) -> int: + """Returns a DeepSeek model's leading dense layers: ``--first_num_dense_layers``, else its model config's.""" + if hparams.first_num_dense_layers >= 0: + return hparams.first_num_dense_layers + return int(hparams_lib.read_model_yaml_metadata(hparams.maxtext_model_name).get("first_num_dense_layers", 0)) + + +def pipelined_layers(hparams: hparams_lib.Hparams) -> int: + """Returns how many decoder layers MaxText's pipeline holds in the baseline; the others run before it. + + The MPMD model pipelines all ``num_layers`` layers. MaxText's pipeline holds + ``pipeline_parallel_layers`` of them, and for DeepSeek only MoE layers: its + dense layers, and the MoE layers past the last multiple of the stage count, run + before the pipeline, data-parallel over every device (``nnx_decoders``: + ``_init_pipeline_deepseek``). Setting ``pipeline_parallel_layers`` to + ``num_layers`` there would build the dense layers *and* ``num_layers`` MoE + layers, a larger model than the MPMD side's. + + Raises: + ValueError: If the layers cannot fill a balanced MaxText pipeline. + """ + if hparams.decoder_block != "deepseek": + if hparams.num_layers % hparams.num_stages: + raise ValueError( + f"MaxText's pipeline needs the {hparams.num_layers} layers to divide into the {hparams.num_stages} stages" + f" (--stage_layer_counts={','.join(map(str, hparams.stage_layer_counts))} has no MaxText equivalent)." + ) + return hparams.num_layers + moe_layers = hparams.num_layers - deepseek_dense_layers(hparams) + pipelined = moe_layers // hparams.num_stages * hparams.num_stages + if pipelined <= 0: + raise ValueError( + f"{hparams.model_name} has {moe_layers} MoE layers in {hparams.num_layers}, fewer than the" + f" {hparams.num_stages} stages: MaxText's pipeline holds only DeepSeek's MoE layers." + ) + return pipelined + + +def unscanned_layers_outside_pipeline(hparams: hparams_lib.Hparams) -> bool: + """Returns whether the baseline runs the layers outside MaxText's pipeline unscanned (``scan_layers=False``). + + MaxText wraps the *scanned* layers it runs outside its pipeline in + ``jax.checkpoint`` (``remat_policy`` cannot be ``none`` with pipeline + parallelism) and the unscanned ones not, so an MPMD run without ``--remat`` + is matched unscanned. But ``scan_layers=False`` changes MaxText's pipeline + too: it then passes each stage's output on as the stage returns it, where it + otherwise unwraps DeepSeek's ``(output, cache)`` tuple (``layers/pipeline.py``). + A stage of several layers unwraps the tuple itself + (``NNXSequentialPipelineStage``); a stage of one layer is the bare layer, + whose tuple then fails the pipeline's shift (``zeros_like`` of a tuple). So + the layers run unscanned only without ``--remat``, when there are any + (DeepSeek's) and every stage holds more than one layer; otherwise MaxText's + default (scanned) applies. + """ + if hparams.decoder_block != "deepseek" or hparams.remat: + return False + pipelined = pipelined_layers(hparams) + return hparams.num_layers > pipelined and pipelined // hparams.num_stages > 1 + + +def _layers(count: int, kind: str) -> str: + return f"{count} {kind} layer{'' if count == 1 else 's'}" + + +def baseline_notes(hparams: hparams_lib.Hparams, *, pure_fsdp: bool = False) -> list[str]: + """Returns how the baseline's program differs from the MPMD run's beyond the pipeline itself.""" + if pure_fsdp: + return [] + notes = [] + if len(set(hparams.stage_layer_counts)) > 1: + notes.append( + f"MaxText's pipeline gives every stage the same number of layers; the MPMD run's" + f" --stage_layer_counts={','.join(map(str, hparams.stage_layer_counts))} has no MaxText equivalent." + ) + if hparams.decoder_block != "deepseek": + return notes + pipelined = pipelined_layers(hparams) + outside = hparams.num_layers - pipelined + if not outside: # MaxText's pipeline holds every layer, as the MPMD run does. + return notes + dense = deepseek_dense_layers(hparams) + which = [f"DeepSeek's {_layers(dense, 'dense')}"] if dense else [] + if outside > dense: + which.append(f"the {_layers(outside - dense, 'MoE')} past a multiple of the {hparams.num_stages} stages") + notes.append( + f"MaxText's pipeline holds {pipelined} of the {hparams.num_layers} layers, all MoE; {' and '.join(which)}" + f" {'runs' if outside == 1 else 'run'} before it, data-parallel over all devices, where the MPMD run pipelines" + " every layer." + ) + if hparams.remat: + return notes + if unscanned_layers_outside_pipeline(hparams): + how = ( + "Without --remat those layers run unscanned (scan_layers=False), the only MaxText path that does not" + " rematerialise them under pipeline parallelism (remat_policy=none is refused there)" + ) + else: + how = ( + "Without --remat MaxText still rematerialises those layers (remat_policy=full, as MaxText refuses none under" + " pipeline parallelism): it skips that only for unscanned layers, which its pipeline cannot run with one" + " DeepSeek layer per stage" + ) + notes.append( + f"{how}; for a step-time comparison of DeepSeek, --remat on both sides checkpoints every layer with the same" + " policy." + ) + return notes + + +def spmd_flags( + hparams: hparams_lib.Hparams, + *, + total_devices: int, + num_slices: int = 1, + pure_fsdp: bool = False, +) -> dict[str, str]: + """Returns the MaxText settings reproducing `hparams` with SPMD. + + MaxText's ``ici_*`` degrees describe one slice and its ``dcn_*`` degrees the + slices (``create_device_mesh`` checks their products). Over several slices + the stages go where the MPMD run puts them (``mesh_utils``: no stage + straddles a slice): each slice holds whole stages, so the stage axis is split + over DCN (``dcn_pipeline_parallelism``) and ICI; or each stage holds whole + slices, the outermost axis of its mesh, ``fsdp``, over DCN + (``dcn_fsdp_parallelism``). Pure FSDP is data-parallel across the slices + (``dcn_data_parallelism``), MaxText's recommended DCN axis. + + Args: + hparams: The MPMD configuration to match. + total_devices: Number of JAX devices of all the slices, needed to convert + the per-device batch size between the two conventions. + num_slices: Number of slices the devices are in. + pure_fsdp: When True, emit a Pure FSDP (`ici_pipeline_parallelism=1`) + configuration matching the MPMD run's global batch size instead of a + pipelined SPMD configuration. + + Returns: + An ordered mapping of MaxText config key to value. + + Raises: + ValueError: If the configuration cannot be expressed as a balanced MaxText + pipeline, if `total_devices` is not a multiple of the stage count or of + the slice count, or if neither of the stage and slice counts divides the + other. + """ + if total_devices <= 0: + raise ValueError(f"total_devices must be positive, got {total_devices}.") + if num_slices <= 0 or total_devices % num_slices: + raise ValueError(f"total_devices ({total_devices}) must split evenly over num_slices ({num_slices}).") + if total_devices % hparams.num_stages: + raise ValueError(f"total_devices ({total_devices}) must be divisible by num_stages" f" ({hparams.num_stages}).") + if not pure_fsdp and hparams.num_stages % num_slices and num_slices % hparams.num_stages: + raise ValueError( + f"{num_slices} slices and {hparams.num_stages} stages must divide one another: the MPMD run puts whole stages" + " on a slice, or whole slices in a stage." + ) + if not pure_fsdp and hparams.num_microbatches % hparams.num_stages: + raise ValueError( + "MaxText requires num_pipeline_microbatches to be a multiple of the" + f" stage count; got {hparams.num_microbatches} microbatches for" + f" {hparams.num_stages} stages." + ) + + devices_per_slice = total_devices // num_slices + devices_per_stage = total_devices // hparams.num_stages + # The stage axis's share of the slices (DCN), and how many slices a stage holds. + dcn_stages = min(num_slices, hparams.num_stages) + stage_slices = num_slices // dcn_stages + # Same tokens per step on both sides; see the module docstring. + global_batch = hparams.per_device_batch_size * devices_per_stage + spmd_per_device_batch_size = global_batch / total_devices + + if not pure_fsdp and global_batch % hparams.num_microbatches: + raise ValueError( + f"Global batch ({global_batch}) is not divisible by" f" num_microbatches ({hparams.num_microbatches})." + ) + + settings: dict[str, object] = { + "model_name": hparams.maxtext_model_name, + "base_num_decoder_layers": hparams.num_layers, + } + if hparams.emb_dim > 0: + settings["base_emb_dim"] = hparams.emb_dim + if hparams_lib.is_pure_moe_model(hparams.maxtext_model_name, hparams.first_num_dense_layers): + moe_dim = hparams.moe_mlp_dim if hparams.moe_mlp_dim > 0 else hparams.mlp_dim + if moe_dim > 0: + settings["base_mlp_dim"] = moe_dim + settings["base_moe_mlp_dim"] = moe_dim + else: + if hparams.mlp_dim > 0: + settings["base_mlp_dim"] = hparams.mlp_dim + if hparams.moe_mlp_dim > 0: + settings["base_moe_mlp_dim"] = hparams.moe_mlp_dim + if hparams.vocab_size > 0: + settings["vocab_size"] = hparams.vocab_size + settings.update( + { + "max_target_length": hparams.max_target_length, + "per_device_batch_size": spmd_per_device_batch_size, + } + ) + if pure_fsdp: + settings.update( + { + "ici_pipeline_parallelism": 1, + "dcn_pipeline_parallelism": 1, + "scan_layers": True, + "allow_split_physical_axes": True, + } + ) + else: + settings.update( + { + # --- pipeline --- + "ici_pipeline_parallelism": hparams.num_stages // dcn_stages, + "dcn_pipeline_parallelism": dcn_stages, + **({"dcn_fsdp_parallelism": stage_slices} if stage_slices > 1 else {}), + "num_pipeline_microbatches": hparams.num_microbatches, + "num_layers_per_pipeline_stage": pipelined_layers(hparams) // hparams.num_stages, + "num_pipeline_repeats": 1, + "pipeline_parallel_layers": pipelined_layers(hparams), + # MaxText's own recommendation: scan the pipeline iterations, not the + # layers within a stage. + "scan_layers_per_stage": False, + "scan_pipeline_iterations": True, + # 2D torus slices such as v6e-64 (physical [8, 8, 1]) and v6e-128 + # (physical [8, 16, 1]) cannot factor into (stage=4, fsdp=16) or + # (stage=4, fsdp=32) without splitting a physical axis of size 8 into + # 4 x 2. MPMD slices flat stage submeshes directly, so the SPMD baseline + # must allow physical axis splitting to run on the same topologies. + "allow_split_physical_axes": True, + } + ) + settings.update( + { + # --- match the MPMD determinism settings --- + "dataset_type": "synthetic", + "enable_checkpointing": False, + "enable_goodput_recording": False, + "monitor_goodput": False, + "enable_dropout": False, + "use_iota_embed": True, + "override_model_config": True, + # Rematerialization: the MPMD model checkpoints its layers only under + # --remat (per layer, with --remat_policy). MaxText checkpoints its + # pipeline's scan iterations when + # `set_remat_policy_on_pipeline_iterations` is true, so that switch + # follows --remat. `remat_policy` itself cannot be "none" with + # pipeline parallelism (MaxText refuses it), so without --remat a + # pipelined baseline names "full": the pipeline's own stage layers + # are then not checkpointed (neither switch is on), but MaxText wraps + # the *scanned* layers it runs outside the pipeline (DeepSeek's dense + # and remaining MoE layers, `pipelined_layers`) in `jax.checkpoint` + # whenever remat_policy is not "none"; see `scan_layers` below. + "set_remat_policy_on_pipeline_iterations": hparams.remat, + "set_remat_policy_on_layers_per_stage": False, + "remat_policy": hparams.remat_policy if hparams.remat else ("none" if pure_fsdp else "full"), + "learning_rate": hparams.learning_rate, + "init_weights_seed": hparams.seed, + # --- steps and profiling --- + # Like train.py: warm-up steps, then the timed steps, then extra steps + # under the profiler, so the profiler never slows a timed step (with the + # profiler over the timed steps, its start made one 3.4 s and the next + # 12 ms). MaxText writes the xplane profile under `tensorboard_dir`, + # derived from `base_output_directory` (--output_dir) and `run_name`. + "steps": hparams.warmup_steps + hparams.steps + _PROFILER_STEPS, + "profiler": "xplane", + "skip_first_n_steps_for_profiler": hparams.warmup_steps + hparams.steps, + "profiler_steps": _PROFILER_STEPS, + # The MPMD side's trace (benchmark.profile): one TPU, one SparseCore and + # one SparseCore tile a traced host. + "enable_tpu_profiling_options": True, + **hparams_lib.TRACE_ADVANCED_CONFIGURATION, + } + ) + expert = max(hparams.expert, 1) + # Mirrors `config.build_maxtext_config`: both sides must dispatch tokens to + # experts the same way for the comparison to be about the pipeline. + settings.update(hparams_lib.moe_dispatch_overrides(hparams)) + if pure_fsdp: + if devices_per_slice % expert: + raise ValueError(f"Devices per slice ({devices_per_slice}) is not divisible by the expert degree ({expert}).") + fsdp_deg = hparams.fsdp * hparams.num_stages if hparams.fsdp > 0 else total_devices // expert + # Each slice holds its share of the FSDP degree; the slices are data-parallel. + if fsdp_deg % num_slices or devices_per_slice % (fsdp_deg // num_slices * expert): + raise ValueError( + f"total_devices ({total_devices}) in {num_slices} slice(s) does not split into Pure FSDP" + f" degree x expert degree ({fsdp_deg} x {expert})." + ) + settings["ici_fsdp_parallelism"] = fsdp_deg // num_slices + tensor = devices_per_slice // (fsdp_deg // num_slices * expert) + if tensor > 1: + settings["ici_tensor_parallelism"] = tensor + if num_slices > 1: + settings["dcn_data_parallelism"] = num_slices + elif hparams.fsdp > 0 or expert > 1: + fsdp_deg = hparams.fsdp if hparams.fsdp > 0 else devices_per_stage // expert + # A stage mesh is `fsdp x expert x tensor`; the tensor axis is whatever is + # left over. It is normally 1, but not on platforms with more than one core + # per chip (a TPU v7x 4x4x4 slice reports 128 devices for its 64 chips). + # MaxText validates that the product of the ICI dimensions equals the + # device count of a slice, so this axis has to be reproduced or the + # baseline will not start. + if devices_per_stage % (fsdp_deg * expert): + raise ValueError( + f"Devices per stage ({devices_per_stage}) is not divisible by the" + f" FSDP x expert degree ({fsdp_deg} x {expert})." + ) + if fsdp_deg % stage_slices: + raise ValueError( + f"Each stage holds {stage_slices} slices, over which its outermost axis, fsdp, runs: its FSDP degree" + f" ({fsdp_deg}) must be a multiple of {stage_slices}." + ) + settings["ici_fsdp_parallelism"] = fsdp_deg // stage_slices + tensor = devices_per_stage // (fsdp_deg * expert) + if tensor > 1: + settings["ici_tensor_parallelism"] = tensor + # As `config.build_maxtext_config`: `simple` and `default` build the + # simple_mlp block, where MaxText's `default` config resolves to base.yml's + # (llama2), so the baseline pins it; a named model's config gives its block + # to both sides. + decoder_block = hparams.decoder_block + if hparams.maxtext_model_name == "default": + settings["decoder_block"] = decoder_block + if decoder_block == "deepseek" or hparams_lib.uses_yarn_rope(hparams.maxtext_model_name): + # Mirrors `config.build_maxtext_config`. MPMD cannot run YaRN RoPE at all + # (PartIR's MarkFragmentReservedMemoryPass asserts on the complex tensors + # it produces -- see the comment there), so the MPMD side pins the standard + # real-valued RoPE. The baseline has to pin it too, or the two sides stop + # being the same model (nothing here tests the two sides' FLOPs for this + # drift). + settings["rope_type"] = "default" + if decoder_block == "deepseek" and hparams.first_num_dense_layers >= 0: + settings["first_num_dense_layers"] = hparams.first_num_dense_layers + if not pure_fsdp and unscanned_layers_outside_pipeline(hparams): + # MaxText runs the layers outside its pipeline unscanned without + # `jax.checkpoint`, scanned with it; otherwise MaxText's default (scanned). + settings["scan_layers"] = False + # Mirrors `config.build_maxtext_config`: float32 GMM tiles, then the + # overrides, applied last. + settings.update(hparams_lib.float32_gmm_tiles(hparams)) + for item in hparams.maxtext_overrides: + key, _, value = item.partition("=") + settings[key] = value + + return {key: str(value) for key, value in settings.items()} + + +def trainer_command( + hparams: hparams_lib.Hparams, + *, + total_devices: int, + run_name: str, + num_slices: int = 1, + output_dir: str = "", + pure_fsdp: bool = False, + xla_flags: dict[str, str] | None = None, +) -> str: + """Returns the shell command that runs MaxText's trainer with :func:`spmd_flags`. + + Args: + hparams: The MPMD configuration to match. + total_devices: Number of JAX devices in the run, of all its slices. + run_name: MaxText ``run_name``; the profile lands under it. + num_slices: Number of slices the devices are in. + output_dir: MaxText ``base_output_directory`` (``gs://...``); empty omits it. + pure_fsdp: Emit Pure FSDP (`ici_pipeline_parallelism=1`) flags. + xla_flags: ``{key: value}`` XLA flags for ``LIBTPU_INIT_ARGS`` (see + :func:`hparams.read_xla_flags_file`); None or empty sets none. + + Returns: + A one-line shell command. + """ + settings = spmd_flags(hparams, total_devices=total_devices, num_slices=num_slices, pure_fsdp=pure_fsdp) + settings["run_name"] = run_name + if output_dir: + settings["base_output_directory"] = output_dir + args = " ".join(shlex.quote(f"{key}={value}") for key, value in settings.items()) + env = "" + if xla_flags: + xla = " ".join(f"--{key}={value}" for key, value in xla_flags.items()) + env = f"export LIBTPU_INIT_ARGS={shlex.quote(xla)}; " + return f"{env}python3 -u -m {MAXTEXT_TRAIN_MODULE} {args}" + + +def xpk_command( + command: str, + *, + cluster: str, + project: str, + zone: str, + device_type: str, + num_slices: int, + workload: str, + docker_image: str, +) -> str: + """Returns the ``xpk workload create`` command that runs `command` on every host of the slice(s).""" + argv = [ + ("--cluster", cluster), + ("--project", project), + ("--zone", zone), + ("--tpu-type", device_type), + ("--num-slices", str(num_slices)), + ("--workload", workload), + ("--docker-image", docker_image), + ("--command", command), + ] + return " \\\n".join(["xpk workload create", *(f" {name} {shlex.quote(value)}" for name, value in argv)]) + + +def gcluster_command( + command: str, + *, + cluster: str, + project: str, + zone: str, + compute_type: str, + topology: str, + num_slices: int, + workload: str, + docker_image: str, +) -> str: + """Returns the ``gcluster job config set`` lines and the ``gcluster job submit`` that runs `command` on every host.""" + config = "\n".join(shlex.join(argv) for argv in launch.gcluster_config_commands(project, cluster, zone)) + argv = [ + ("--name", workload), + ("--image", docker_image), + ("--compute-type", compute_type), + ("--topology", topology), + ("--num-slices", str(num_slices)), + ("--command", command), + ] + return ( + config + "\n" + " \\\n".join(["gcluster job submit", *(f" {name}={shlex.quote(value)}" for name, value in argv)]) + ) + + +def main(argv: Sequence[str], flag_values: flags.FlagValues = flags.FLAGS) -> None: + if len(argv) > 1: + raise app.UsageError(f"Unexpected command line arguments: {argv[1:]}") + + fv = flag_values + try: + hparams = hparams_lib.from_flags(fv) + except (ValueError, FileNotFoundError) as error: + raise app.UsageError(str(error)) from error + total_devices = fv.total_devices + if total_devices <= 0: + total_devices = devices_in_device_type(fv.device_type) * fv.num_slices + if total_devices <= 0: + raise app.UsageError( + f"Could not derive the device count from --device_type={fv.device_type!r}; pass --total_devices." + ) + run_name = fv.run_name or f"spmd-baseline-{time.strftime('%m%d%H%M%S')}" + if fv.cluster: + missing = [f"--{name}" for name in _CLUSTER_FLAGS if not fv[name].value] + if not fv.device_type: + missing.append("--device_type") + if missing: + raise app.UsageError(f"--cluster needs {', '.join(missing)}.") + + # Before anything is printed: a configuration MaxText's pipeline cannot run is a usage error, not a traceback. + try: + settings = spmd_flags(hparams, total_devices=total_devices, num_slices=fv.num_slices, pure_fsdp=fv.pure_fsdp) + except ValueError as error: + raise app.UsageError(str(error)) from error + mode_desc = "Pure FSDP" if fv.pure_fsdp else f"SPMD pipeline ({hparams.num_stages} stages)" + for note in baseline_notes(hparams, pure_fsdp=fv.pure_fsdp): + max_logging.warning(f"spmd_baseline: {note}") + slices_desc = f" in {fv.num_slices} slices" if fv.num_slices > 1 else "" + print(f"Equivalent MaxText {mode_desc} configuration ({total_devices} devices{slices_desc}):") + for key, value in settings.items(): + print(f" {key}={value}") + command = trainer_command( + hparams, + total_devices=total_devices, + run_name=run_name, + num_slices=fv.num_slices, + output_dir=fv.output_dir, + pure_fsdp=fv.pure_fsdp, + xla_flags=hparams_lib.read_xla_flags_file(fv.xla_flags_file) if fv.xla_flags_file else None, + ) + print("\nRun MaxText's trainer with:\n") + print(command) + if not fv.cluster: + return + cluster = {"cluster": fv.cluster, "project": fv.project, "zone": fv.zone, "docker_image": fv.docker_image} + workload = fv.workload or run_name + print("\nOn the cluster:\n") + if fv.launcher == "xpk": + print(xpk_command(command, device_type=fv.device_type, num_slices=fv.num_slices, workload=workload, **cluster)) + return + compute_type, topology = launch.gcluster_options(fv) + print( + gcluster_command( + command, + compute_type=compute_type, + topology=topology, + num_slices=fv.num_slices, + workload=workload, + **cluster, + ) + ) + + +if __name__ == "__main__": + define_flags() + app.run(main) diff --git a/src/maxtext/experimental/mpmd/partir/train.py b/src/maxtext/experimental/mpmd/partir/train.py new file mode 100644 index 0000000000..5e09692be8 --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/train.py @@ -0,0 +1,400 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +r"""End-to-end training benchmark of the MPMD pipeline on Shardy MPMD and Pathways. + +Lowers and compiles a microbatched training step partitioned across TPU stage +meshes by Shardy MPMD (OSS PartIR:MPMD), runs it on a Pathways backend, and +reports step time, throughput and, optionally, an XProf trace. The program +compiles only through Pathways' IFRT proxy (``JAX_PLATFORMS=proxy``), e.g. on a +TPU VM with Pathways in docker (``local_pathways.sh``):: + + JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000 \ + python3 -m maxtext.experimental.mpmd.partir.train --pp=4 \ + --num_microbatches=4 --per_device_batch_size=4 --model_name=simple + +or on a GKE cluster, as the workload ``launch.py`` prints. +""" + +from __future__ import annotations + +from collections.abc import Sequence +import dataclasses +import json + +from absl import app +from absl import flags +import jax +import pathwaysutils + +from maxtext.utils import max_logging + +from maxtext.experimental.mpmd.partir import benchmark +from maxtext.experimental.mpmd.partir import hparams as hparams_lib +from maxtext.experimental.mpmd.partir import runner as runner_lib +from maxtext.experimental.mpmd.partir import train_step as train_step_lib + + +def define_flags(flag_values: flags.FlagValues = flags.FLAGS) -> None: + """Registers the trainer's flags, the hyperparameters' included, on `flag_values`.""" + hparams_lib.define_flags(flag_values) + fv = {"flag_values": flag_values} + flags.DEFINE_boolean( + "enable_profile", + False, + "Capture an XProf / JAX profiler trace over --profile_steps extra steps run after the timed steps, so it does" + " not affect the reported step times.", + **fv, + ) + flags.DEFINE_integer("profile_steps", 3, "Number of extra steps to run under the profiler once timing is done.", **fv) + flags.DEFINE_string( + "profile_dir", + "", + "Trace directory; the trace goes to /. Under Pathways it must be gs://..." + " (pathwaysutils rejects local paths); empty skips the trace there. Elsewhere it defaults to /tmp/xprof.", + **fv, + ) + flags.DEFINE_float( + "profile_delay_s", + 1.0, + "Seconds between starting the trace and the profiled steps. Pathways workers start their TPU tracer late;" + " without a delay the trace has no TPU device planes.", + **fv, + ) + flags.DEFINE_float( + "peak_tflops_per_device", + 0.0, + "Hardware peak TFLOP/s per JAX device (on TPU7x, half a chip's peak: a chip is two devices). When > 0 an MFU" + " figure is reported.", + **fv, + ) + flags.DEFINE_string( + "run_name", "mpmd-partir", "Name of the run: the trace directory and the label of the results.", **fv + ) + flags.DEFINE_string("result_json", "", "If set, also write the MPMD_RESULT record (JSON) to this local path.", **fv) + + +def _publish_results(urls: Sequence[str]) -> None: + """Logs where the trace went and how to open it. + + The record of a run is its ``MPMD_RESULT`` line (logged to stderr; its JSON + also in ``--result_json``) plus the trace directory. + + Args: + urls: Trace directories returned by :func:`benchmark.profile`. + """ + if not urls: + max_logging.warning("No trace was captured.") + return + for url in urls: + max_logging.log(f"Trace directory : {url}") + if urls[0].startswith("gs://"): + # XProf aborts on a gs:// logdir; copy the session locally first. + max_logging.log( + f"Open with: gcloud storage cp -r {urls[0]} /tmp/ && xprof --logdir" + f" /tmp/{urls[0].rstrip('/').rsplit('/', 1)[-1]}" + ) + + +@dataclasses.dataclass(frozen=True) +class TrainingResult: + """Everything one end-to-end MPMD training run produced. + + Attributes: + stats: Measured step times and the final loss. + throughput: Derived tokens/s and TFLOP/s figures. + xprof_urls: Trace directories, empty when profiling was disabled. + description: Human readable summary of the configuration that ran. + num_devices: Total devices the run occupied. + devices_per_stage: Devices backing a single pipeline stage. + num_stages: Pipeline depth. + num_microbatches: Microbatches per optimizer step. + learning_rate: The AdamW learning rate the steps ran with. + """ + + stats: benchmark.StepStats + throughput: benchmark.Throughput + xprof_urls: tuple[str, ...] + description: str + num_devices: int + devices_per_stage: int + num_stages: int + num_microbatches: int + learning_rate: float = 0.0 + + @property + def analytic_bubble_fraction(self) -> float: + """Bubble fraction a non-circular schedule cannot avoid. + + For a GPipe-style schedule the warm-up and cool-down phases leave + ``stages - 1`` slots idle out of ``stages - 1 + microbatches``. Measured + TensorCore idle time well above this points at transfer stalls rather than + the schedule itself. + + Returns: + The analytic bubble fraction, or 0.0 when it is not defined. + """ + return analytic_bubble_fraction(self.num_stages, self.num_microbatches) + + def summary(self, label: str, schedule: str) -> str: + """Returns the human readable results block for this run. + + The exact same text is logged and, with ``--result_json``, + summarised in the result file. + + Args: + label: Run label, e.g. ``mpmd-partir``. + schedule: The pipeline schedule that ran. + + Returns: + A multi-line summary. + """ + stats = self.stats + return "\n".join( + ( + f"Results for {label} ({schedule}):", + (f" devices / stages / microbatches: {self.num_devices} /" f" {self.num_stages} / {self.num_microbatches}"), + f" steps timed : {stats.num_steps}", + (f" step time mean / median : {stats.mean_ms:.3f} /" f" {stats.median_ms:.3f} ms"), + (f" step time min / stdev : {stats.min_ms:.3f} /" f" {stats.stdev_ms:.3f} ms"), + (f" first / final loss : {stats.first_loss:.6f} /" f" {stats.loss:.6f}"), + *benchmark.loss_warning(stats, self.learning_rate), + (" analytic bubble :" f" {self.analytic_bubble_fraction * 100:.1f}%"), + self.throughput.report(), + ) + ) + + +def analytic_bubble_fraction(num_stages: int, num_microbatches: int) -> float: + """Returns ``(P - 1) / (P - 1 + M)`` for P stages and M microbatches. + + Args: + num_stages: Pipeline depth. + num_microbatches: Microbatches per optimizer step. + + Returns: + The analytic bubble fraction, or 0.0 when it is not defined. + """ + if num_stages <= 1 or num_microbatches <= 0: + return 0.0 + return (num_stages - 1) / (num_stages - 1 + num_microbatches) + + +def run_training( + hparams: hparams_lib.Hparams, + *, + enable_profile: bool = False, + profile_dir: str = "", + peak_tflops_per_device: float = 0.0, + profile_tag: str = "mpmd-partir", + profile_steps: int = 3, + profile_delay_s: float = 1.0, +) -> TrainingResult: + """Lowers, compiles and runs the MPMD training step, timing the steps. + + This is the whole experiment, minus flag parsing and artifact publishing, so + that it can also be driven from a test on real accelerators. + + Args: + hparams: The configuration to run. + enable_profile: Whether to capture an XProf / JAX profiler trace. + profile_dir: Trace directory (``gs://...`` under Pathways). + peak_tflops_per_device: Hardware peak TFLOP/s per JAX device, enabling an MFU figure. + profile_tag: Tag attached to the captured trace. + profile_steps: Number of extra steps to run under the profiler, after the + timed steps have finished. These are excluded from the reported timings so + that enabling profiling cannot change the measured numbers. + profile_delay_s: Seconds between starting the trace and the profiled steps. + + Returns: + The :class:`TrainingResult`. + """ + runnable = runner_lib.build(hparams, mode=train_step_lib.ExecutionMode.MPMD, check_microbatches=True) + note = hparams_lib.ragged_buffer_note(hparams) + if note: + max_logging.log(f"Note: {note}") + + description = runnable.describe() + max_logging.log("=" * 72) + max_logging.log(description) + max_logging.log("=" * 72) + + max_logging.log("Lowering MPMD training step...") + lowered = runnable.lower() + + max_logging.log("Compiling MPMD training step...") + compiled = lowered.compile() + max_logging.log("Compilation complete.") + + # `function_named_shardings` reports where Shardy decided each input must + # live once the program is partitioned; committing the arrays there avoids a + # silent host round-trip on the first step. + state, batch = runner_lib.place_on_stage_meshes( + (runnable.state, runnable.batch), + lowered.function_named_shardings.input_specs, + ) + + # The profiler is deliberately NOT wrapped around the timed steps. XProf adds + # per-executable tracing overhead, so profiling the measured window would + # inflate every number this run reports -- and silently, because the result + # still looks plausible. Instead the timed steps run clean, and the trace is + # captured afterwards from a short extra window that nothing is derived from. + # MaxText does the equivalent with `skip_first_n_steps_for_profiler`. + state, stats = benchmark.run_steps( + compiled, + state, + batch, + num_steps=hparams.steps, + warmup_steps=hparams.warmup_steps, + abort_on_nonfinite=True, + ) + + urls: list[str] = [] + if enable_profile: + max_logging.log( + f"Capturing XProf over {profile_steps} extra step(s); these are not" " included in the reported timings." + ) + with benchmark.profile( + True, + tag=profile_tag, + profile_dir=profile_dir, + trace_delay_s=profile_delay_s, + ) as captured: + benchmark.run_steps( + compiled, + state, + batch, + num_steps=profile_steps, + warmup_steps=0, + first_step=hparams.warmup_steps + hparams.steps, + log_prefix="[profiled] ", + abort_on_nonfinite=True, + ) + urls = list(captured) + + throughput = benchmark.compute_throughput( + stats=stats, + maxtext_config=runnable.maxtext_config, + devices_per_stage=runnable.plan.topology.devices_per_stage, + num_devices=runnable.plan.num_devices, + peak_tflops_per_device=peak_tflops_per_device, + ) + + return TrainingResult( + stats=stats, + throughput=throughput, + xprof_urls=tuple(urls), + description=description, + num_devices=runnable.plan.num_devices, + devices_per_stage=runnable.plan.topology.devices_per_stage, + num_stages=hparams.num_stages, + num_microbatches=hparams.num_microbatches, + learning_rate=hparams.learning_rate, + ) + + +def result_line(hparams: hparams_lib.Hparams, result: TrainingResult, run_name: str = "") -> str: + """Returns the one-line ``MPMD_RESULT {json}`` record of a finished run. + + One JSON object per run, so results can be collected from logs without + scraping the human-readable summary. + + Args: + hparams: The configuration that ran. + result: What the run measured. + run_name: The run's name (``--run_name``), or "" for none. + + Returns: + ``"MPMD_RESULT "`` followed by a single-line JSON object. + """ + throughput = result.throughput + record = { + "backend": "partir", + "model": hparams.model_name, + "layers": hparams.num_layers, + "stages": result.num_stages, + "microbatches": result.num_microbatches, + "schedule": hparams.pipeline_schedule, + "fsdp": hparams.fsdp, + "expert": hparams.expert, + "per_device_batch_size": hparams.per_device_batch_size, + "seq": hparams.max_target_length, + "remat": hparams.remat, + "devices": result.num_devices, + "devices_per_stage": result.devices_per_stage, + "step_ms": throughput.step_time_s * 1e3, + "step_ms_mean": result.stats.mean_ms, + "tokens_per_step": throughput.tokens_per_step, + "tokens_per_s_per_device": throughput.tokens_per_second_per_device, + "tflops_per_device": throughput.tflops_per_second_per_device, + "mfu": throughput.mfu, + "loss": result.stats.loss, + "loss_first": result.stats.first_loss, + "learning_rate": hparams.learning_rate, + } + if hparams.maxtext_overrides: + record["maxtext_overrides"] = list(hparams.maxtext_overrides) + if run_name: + record["run"] = run_name + return "MPMD_RESULT " + json.dumps(record, sort_keys=True, default=str) + + +def _write_result(line: str, path: str) -> None: + """Logs the ``MPMD_RESULT`` line, and writes its JSON to `path` if set.""" + max_logging.log(line) + if path: + with open(path, "w", encoding="utf-8") as handle: + handle.write(line.removeprefix("MPMD_RESULT ") + "\n") + + +def main(argv: Sequence[str], flag_values: flags.FlagValues = flags.FLAGS) -> None: + if len(argv) > 1: + raise app.UsageError(f"Unexpected command line arguments: {argv[1:]}") + # Registers the Pathways proxy backend when JAX_PLATFORMS contains "proxy"; + # it must run before the backend is first used. + pathwaysutils.initialize() + + fv = flag_values + hparams = hparams_lib.from_flags(fv) + try: + result = run_training( + hparams, + enable_profile=fv.enable_profile, + profile_dir=fv.profile_dir, + peak_tflops_per_device=fv.peak_tflops_per_device, + profile_tag=fv.run_name, + profile_steps=fv.profile_steps, + profile_delay_s=fv.profile_delay_s, + ) + except benchmark.NonFiniteLossError as error: + # Without this a NaN loss ended in "Execution finished successfully" with + # exit 0, after steps whose times described degenerate routing. + record = {"backend": "partir", "model": hparams.model_name, "error": f"non-finite loss: {error}"} + if fv.run_name: + record["run"] = fv.run_name + _write_result("MPMD_RESULT " + json.dumps(record, sort_keys=True), fv.result_json) + raise SystemExit(f"MPMD training failed: {error}") from error + summary = result.summary(fv.run_name, hparams.pipeline_schedule) + + max_logging.log("=" * 72) + max_logging.log(summary) + max_logging.log("=" * 72) + _write_result(result_line(hparams, result, fv.run_name), fv.result_json) + _publish_results(result.xprof_urls) + max_logging.log("Execution finished successfully.") + + +if __name__ == "__main__": + define_flags() + jax.config.config_with_absl() + app.run(main) diff --git a/src/maxtext/experimental/mpmd/partir/train_compile.py b/src/maxtext/experimental/mpmd/partir/train_compile.py new file mode 100644 index 0000000000..9eaf4ea5fa --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/train_compile.py @@ -0,0 +1,394 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +r"""Lowers the MPMD training step without TPUs, and compiles it on Pathways. + +Lets a pipeline configuration be checked before spending an allocation. +Because the program is assembled by :func:`runner.build` -- the same function +``train.py`` uses -- a successful lowering here is evidence about the program +that will actually run, not about a similar-looking one. + +OSS has no AOT cross-compilation against a TPU topology on a CPU host and no +serialization of the compiled program, and Shardy MPMD's IFRT IR program +compiles only through a Pathways IFRT client (plain PJRT fails with +"PjRtCompiler requires an HloProgram"). +This binary therefore: + + * lowers (StableHLO -> MPMD -> IFRT IR) on fake CPU devices (default), on an + OSS AOT topology's devices (``--compile_topology=v6e:4x4``), or on the + attached backend's devices (``--compile_topology=local``); + * pins the transfers as ``train.py`` does and logs the program's shape + (fragments and transfers per mesh), optionally dumping the IR; + * compiles and logs the memory / cost report when the backend is Pathways + (``JAX_PLATFORMS=proxy``, e.g. a TPU VM's Pathways in docker, + ``local_pathways.sh``). + +It also checks what only the TPUs would otherwise reject: that each microbatch +splits over a stage's batch-sharding devices. + +Example (8 fake CPU devices by default, ``--num_cpu_devices``):: + + JAX_PLATFORMS=cpu python3 -m maxtext.experimental.mpmd.partir.train_compile \ + --pp=4 --fsdp=2 --num_microbatches=4 --per_device_batch_size=4 \ + --pipeline_schedule=1F1B --model_name=deepseek3-tiny --ir_dump_path=/tmp/mpmd_pp4 +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +import collections +import dataclasses +import os +import re +from typing import Any + +from absl import app +from absl import flags +import jax +import pathwaysutils + +from maxtext.utils import max_logging + +from maxtext.experimental.mpmd.partir import hparams as hparams_lib +from maxtext.experimental.mpmd.partir import runner as runner_lib +from maxtext.experimental.mpmd.partir import train_step as train_step_lib + + +def define_flags(flag_values: flags.FlagValues = flags.FLAGS) -> None: + """Registers the lowering check's flags, the hyperparameters' included, on `flag_values`.""" + hparams_lib.define_flags(flag_values) + fv = {"flag_values": flag_values} + flags.DEFINE_string( + "compile_topology", + "cpu", + "Devices to lower against: 'cpu' (fake CPU devices, the default), 'local' (the attached backend, e.g." + " Pathways), or an OSS AOT topology such as 'v6e:4x4' or 'v5p:2x2x2' (needs libtpu, which only one process per" + " TPU VM can load).", + **fv, + ) + flags.DEFINE_integer( + "num_cpu_devices", + 8, + "Fake CPU devices for --compile_topology=cpu, unless XLA_FLAGS sets --xla_force_host_platform_device_count.", + **fv, + ) + flags.DEFINE_integer("compile_topology_num_slices", 1, "Number of slices in the topology.", **fv) + flags.DEFINE_string("chip_config", "default", "chip_config_name for an AOT topology.", **fv) + flags.DEFINE_string( + "ir_dump_path", + "", + "If set, write .{stablehlo,mpmd,ifrt}.mlir (the IFRT IR after transfer pinning).", + **fv, + ) + flags.DEFINE_enum( + "skip_compile", + "auto", + ["auto", "true", "false"], + "auto: compile only on a Pathways backend (nothing else can compile an IFRT IR program). false: always try," + " and fail off Pathways.", + **fv, + ) + + +_CALL_RE = re.compile(r"ifrt\.Call @([A-Za-z0-9_.$]+)") +_MESH_RE = re.compile(r"ifrt\.mesh_name\s*=\s*\"([^\"]+)\"") + + +@dataclasses.dataclass(frozen=True) +class CompilationReport: + """Memory and cost analysis of a compiled whole-program MPMD executable. + + Attributes: + peak_memory_bytes: Peak HBM bytes required on the most-loaded device across + the entire MPMD program schedule. + argument_size_bytes: Whole-program input buffer footprint in bytes. + output_size_bytes: Whole-program output buffer footprint in bytes. + device_to_peak_bytes_used: Per-device peak HBM usage map from the IFRT IR + program memory stats. + fragment_memory_stats: Mapping from outlined stage fragment name to its XLA + ``CompiledMemoryStats`` (temp, argument, output, alias, generated code + bytes). + fragment_cost_analysis: Mapping from outlined stage fragment name to its XLA + cost analysis dictionary (FLOPs, bytes accessed, etc.). + unavailable: Statistics the executable could not provide, with the first + line of the error each one raised. + """ + + peak_memory_bytes: int + argument_size_bytes: int + output_size_bytes: int + device_to_peak_bytes_used: dict[int, int] + fragment_memory_stats: dict[str, Any] + fragment_cost_analysis: dict[str, dict[str, Any]] + unavailable: dict[str, str] = dataclasses.field(default_factory=dict) + + @property + def peak_memory_gib(self) -> float: + """Returns the peak per-device HBM usage in GiB.""" + return self.peak_memory_bytes / (1024.0**3) + + def format_summary(self) -> str: + """Returns a human-readable summary of whole-program and fragment stats.""" + lines = ["MPMD Whole-Program Compilation Report:"] + if "ifrt_ir_program_memory_stats" not in self.unavailable: + lines += [ + (f" peak HBM per device : {self.peak_memory_gib:.3f} GiB" f" ({self.peak_memory_bytes:,} B)"), + (" program inputs :" f" {self.argument_size_bytes / (1024**2):.2f} MiB"), + (" program outputs :" f" {self.output_size_bytes / (1024**2):.2f} MiB"), + ] + lines.append(" outlined XLA fragments:" f" {len(self.fragment_memory_stats or self.fragment_cost_analysis)}") + lines += [f" unavailable : {name} ({error})" for name, error in self.unavailable.items()] + names = sorted(set(self.fragment_memory_stats) | set(self.fragment_cost_analysis)) + for name in names: + mem = self.fragment_memory_stats.get(name) + temp_mib = getattr(mem, "temp_size_in_bytes", 0) / (1024.0**2) + arg_mib = getattr(mem, "argument_size_in_bytes", 0) / (1024.0**2) + out_mib = getattr(mem, "output_size_in_bytes", 0) / (1024.0**2) + alias_mib = getattr(mem, "alias_size_in_bytes", 0) / (1024.0**2) + cost = self.fragment_cost_analysis.get(name) or {} + flops = float(cost.get("flops", 0.0)) if isinstance(cost, Mapping) else 0.0 + lines.append( + f" {name:32s}: temp={temp_mib:8.2f} MiB, args={arg_mib:8.2f} MiB," + f" out={out_mib:7.2f} MiB, alias={alias_mib:8.2f} MiB," + f" GFLOPs={flops / 1e9:8.2f}" + ) + return "\n".join(lines) + + +def build_compilation_report(compiled: Any) -> CompilationReport: + """Extracts a :class:`CompilationReport` from a compiled ``MpmdCompiled``. + + Each statistic is read on its own: through the IFRT proxy (any GKE Pathways + run) the program-level memory stats raise ``UNIMPLEMENTED: + GetIfrtIrProgramMemoryStats only supported on MpmdLoadedExecutable``, and + that must not hide the per-fragment analyses. What could not be read is + listed in :attr:`CompilationReport.unavailable`. + """ + unavailable: dict[str, str] = {} + + def _read(name: str, fn: Any, default: Any) -> Any: + try: + return fn() + except Exception as error: # pylint: disable=broad-exception-caught + unavailable[name] = (str(error).splitlines() or [repr(error)])[0][:200] + return default + + prog_stats = _read( + "ifrt_ir_program_memory_stats", + lambda: compiled.ifrt_ir_program_memory_stats, + None, + ) + frag_mem = dict(_read("memory_analysis", compiled.memory_analysis, None) or {}) + raw_cost = _read("cost_analysis", compiled.cost_analysis, None) or {} + frag_cost: dict[str, dict[str, Any]] = { + str(name): dict(stats) if isinstance(stats, Mapping) else {} for name, stats in raw_cost.items() + } + device_peaks = dict(getattr(prog_stats, "device_to_peak_bytes_used", {}) or {}) + return CompilationReport( + peak_memory_bytes=max(device_peaks.values(), default=0), + argument_size_bytes=int(getattr(prog_stats, "argument_size_in_bytes", 0)), + output_size_bytes=int(getattr(prog_stats, "output_size_in_bytes", 0)), + device_to_peak_bytes_used=device_peaks, + fragment_memory_stats=frag_mem, + fragment_cost_analysis=frag_cost, + unavailable=unavailable, + ) + + +@dataclasses.dataclass(frozen=True) +class ProgramSummary: + """The shape of a lowered IFRT IR program. + + Attributes: + calls: Number of ``ifrt.Call`` ops (fragment executions) in ``@main``. + copies: Number of ``ifrt.CopyArrays`` ops (cross-mesh transfers). + pinned_copies: Copies with an ``after`` control dependency. + programs: Number of distinct fragment programs called. + calls_per_mesh: Fragment executions per mesh name. + """ + + calls: int + copies: int + pinned_copies: int + programs: int + calls_per_mesh: dict[str, int] + + def format_summary(self) -> str: + """Returns the summary as aligned lines.""" + per_mesh = ", ".join(f"{mesh}:{count}" for mesh, count in sorted(self.calls_per_mesh.items())) + return "\n".join( + [ + "Lowered IFRT IR program:", + f" fragment executions : {self.calls} ({self.programs} programs)", + f" per mesh : {per_mesh}", + (f" cross-mesh copies : {self.copies}" f" ({self.pinned_copies} pinned to their producer)"), + ] + ) + + +def summarize_ifrt(ifrt_text: str) -> ProgramSummary: + """Counts the fragment executions and transfers of an IFRT IR program.""" + calls = 0 + copies = 0 + pinned = 0 + programs: set[str] = set() + per_mesh: dict[str, int] = collections.Counter() + for line in ifrt_text.splitlines(): + if "ifrt.Call " in line or "ifrt.Call @" in line: + match = _CALL_RE.search(line) + if match: + calls += 1 + programs.add(match.group(1)) + mesh = _MESH_RE.search(line) + per_mesh[mesh.group(1) if mesh else "?"] += 1 + elif "ifrt.CopyArrays(" in line: + copies += 1 + pinned += bool(re.search(r"\)\s*after\s+%", line)) + return ProgramSummary( + calls=calls, + copies=copies, + pinned_copies=pinned, + programs=len(programs), + calls_per_mesh=dict(per_mesh), + ) + + +def resolve_compile_devices(compile_topology: str, num_slices: int = 1, chip_config: str = "default") -> Sequence[Any]: + """Returns the devices to lower against; see ``--compile_topology``.""" + if compile_topology in ("", "cpu"): + return jax.devices("cpu") + if compile_topology == "local": + return jax.devices() + # Imported lazily: the AOT topology machinery loads libtpu. + from jax.experimental import topologies # pylint: disable=import-outside-toplevel + + return topologies.get_topology_desc( + platform="tpu", + topology_name=compile_topology, + chip_config_name=chip_config, + chips_per_host_bounds=(2, 2, 1), + num_slices=num_slices, + ).devices + + +def run_compile( + hparams: hparams_lib.Hparams, + *, + compile_topology: str = "cpu", + num_slices: int = 1, + chip_config: str = "default", + ir_dump_path: str = "", + skip_compile: str = "auto", + config_overrides: dict[str, Any] | None = None, +) -> tuple[Any, Any, ProgramSummary]: + """Lowers, and on Pathways compiles, the whole MPMD training step. + + Args: + hparams: Pipeline hyperparameters. + compile_topology: See ``--compile_topology``. + num_slices: Number of slices in an AOT topology. + chip_config: ``chip_config_name`` for an AOT topology. + ir_dump_path: Optional path prefix for the lowered IR dumps. + skip_compile: ``auto``, ``true`` or ``false``; see ``--skip_compile``. + config_overrides: Extra MaxText settings, for tests. + + Returns: + A tuple ``(lowered, compiled, summary)``; `compiled` is None when + compilation was skipped. + """ + devices = resolve_compile_devices(compile_topology, num_slices, chip_config) + max_logging.log( + f"Targeting {len(devices)} devices ({compile_topology}," f" {devices[0].platform}, {num_slices} slice(s))." + ) + + runnable = runner_lib.build( + hparams, + devices=devices, + mode=train_step_lib.ExecutionMode.MPMD, + abstract=True, + config_overrides=config_overrides, + check_microbatches=True, + ) + note = hparams_lib.ragged_buffer_note(hparams) + if note: + max_logging.log(f"Note: {note}") + max_logging.log(runnable.describe()) + + max_logging.log("Lowering MPMD training step to IFRT IR...") + lowered = runnable.lower() + max_logging.log("Lowering succeeded.") + + ifrt_text = lowered.as_text(dialect="ifrt") + summary = summarize_ifrt(ifrt_text) + max_logging.log(summary.format_summary()) + + if ir_dump_path: + for dialect in ("stablehlo", "mpmd", "ifrt"): + path = f"{ir_dump_path}.{dialect}.mlir" + with open(path, "w", encoding="utf-8") as handle: + handle.write(ifrt_text if dialect == "ifrt" else lowered.as_text(dialect=dialect)) + max_logging.log(f"Wrote {path}.") + + on_pathways = bool(pathwaysutils.is_pathways_backend_used()) + if skip_compile == "true" or (skip_compile == "auto" and not on_pathways): + if not on_pathways: + max_logging.log( + "Not compiling: Shardy MPMD's IFRT IR program compiles only through a" + " Pathways backend (JAX_PLATFORMS=proxy)." + ) + return lowered, None, summary + + max_logging.log("Compiling whole MPMD pipeline program...") + compiled = lowered.compile() + max_logging.log("Compilation succeeded.") + + try: + report = build_compilation_report(compiled) + except Exception as error: # pylint: disable=broad-exception-caught + max_logging.warning(f"Compilation report unavailable: {error}") + else: + max_logging.log("=" * 72) + max_logging.log(report.format_summary()) + max_logging.log("=" * 72) + + return lowered, compiled, summary + + +def main(argv: Sequence[str], flag_values: flags.FlagValues = flags.FLAGS) -> None: + if len(argv) > 1: + raise app.UsageError(f"Unexpected command line arguments: {argv[1:]}") + # Registers the Pathways proxy backend when JAX_PLATFORMS contains "proxy"; + # it must run before the backend is first used. + pathwaysutils.initialize() + + fv = flag_values + if fv.compile_topology in ("", "cpu"): + if not jax.config.jax_platforms: + # Fake CPU devices only: on a TPU VM, JAX would otherwise take the TPU. + jax.config.update("jax_platforms", "cpu") + if "xla_force_host_platform_device_count" not in os.environ.get("XLA_FLAGS", ""): + jax.config.update("jax_num_cpu_devices", fv.num_cpu_devices) + run_compile( + hparams_lib.from_flags(fv), + compile_topology=fv.compile_topology, + num_slices=fv.compile_topology_num_slices, + chip_config=fv.chip_config, + ir_dump_path=fv.ir_dump_path, + skip_compile=fv.skip_compile, + ) + + +if __name__ == "__main__": + define_flags() + jax.config.config_with_absl() + app.run(main) diff --git a/src/maxtext/experimental/mpmd/partir/train_step.py b/src/maxtext/experimental/mpmd/partir/train_step.py new file mode 100644 index 0000000000..0c2cd56b0f --- /dev/null +++ b/src/maxtext/experimental/mpmd/partir/train_step.py @@ -0,0 +1,326 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The training step, shared by every execution mode. + +There is exactly one implementation of the loss and of the microbatched +optimizer step here. The MPMD (pipelined) and SPMD (single-program) modes +differ only in two substitutions: + + ================== ========================== ======================== + mode stage wrapper microbatch wrapper + ================== ========================== ======================== + ``MPMD`` ``mpmd.named_computation`` ``mpmd.call`` + ``SPMD`` reference identity identity + ================== ========================== ======================== + +Because the arithmetic is literally the same code, any numerical difference +observed between the two modes is attributable to the MPMD partitioning +itself, which is exactly the property ``parity.py`` asserts. The trainer and +the lowering check share it too, so they cannot optimise different objectives. + +The optimizer is a constant-learning-rate ``optax.adamw`` +(:func:`make_optimizer`), not MaxText's optimizer and schedule. +""" + +from __future__ import annotations + +from collections.abc import Callable +import enum +from typing import Any + +from flax.training import train_state +import jax +import jax.numpy as jnp +import optax + +from maxtext.experimental.mpmd.partir import mesh_utils +from maxtext.experimental.mpmd.partir import models + +# The batch keys the model and loss consume. +BATCH_KEYS = ( + "inputs", + "inputs_position", + "inputs_segmentation", + "targets", + "targets_position", + "targets_segmentation", +) + + +class ExecutionMode(enum.Enum): + """How the training step should be traced.""" + + # Pipelined across meshes by PartIR MPMD. + MPMD = "mpmd" + # A single program; the numerical reference. + SPMD = "spmd" + + @property + def stage_wrapper(self) -> models.Wrapper: + return models.NAMED_COMPUTATION if self is ExecutionMode.MPMD else models.UNWRAPPED + + +def microbatch_call(fn: Callable[..., Any], call_counter: int) -> Callable[..., Any]: + """Wraps one microbatch's step in ``mpmd.call``, the pipeline slot `call_counter`.""" + # Imported here, so that the SPMD step (and its tests) runs without Shardy + # MPMD installed. + from maxtext.experimental.mpmd.partir.sdy_mpmd_compat import mpmd # pylint: disable=import-outside-toplevel + + return mpmd.call(fn, call_counter=call_counter) + + +@jax.custom_vjp +def _sparse_cross_entropy_with_logits( + logits: jax.Array, + targets: jax.Array, +) -> jax.Array: + """Computes per-token sparse cross-entropy without a full-vocab one_hot.""" + logits_f32 = logits.astype(jnp.float32) + max_logit = jax.lax.stop_gradient(jnp.max(logits_f32, axis=-1, keepdims=True)) + shifted = logits_f32 - max_logit + log_z = jnp.log(jnp.sum(jnp.exp(shifted), axis=-1)) + target_logit = jnp.squeeze(jnp.take_along_axis(shifted, targets[..., None], axis=-1), axis=-1) + return log_z - target_logit + + +def _sparse_ce_fwd( + logits: jax.Array, + targets: jax.Array, +) -> tuple[jax.Array, tuple[jax.Array, jax.Array, jax.Array, jax.Array]]: + """Forward pass for custom-VJP sparse cross-entropy.""" + logits_f32 = logits.astype(jnp.float32) + max_logit = jax.lax.stop_gradient(jnp.max(logits_f32, axis=-1, keepdims=True)) + shifted = logits_f32 - max_logit + sum_exp = jnp.sum(jnp.exp(shifted), axis=-1, keepdims=True) + log_z = jnp.squeeze(jnp.log(sum_exp), axis=-1) + target_logit = jnp.squeeze(jnp.take_along_axis(shifted, targets[..., None], axis=-1), axis=-1) + return log_z - target_logit, (logits, targets, max_logit, sum_exp) + + +def _sparse_ce_bwd( + res: tuple[jax.Array, jax.Array, jax.Array, jax.Array], + g: jax.Array, +) -> tuple[jax.Array, None]: + """Backward pass for custom-VJP sparse cross-entropy.""" + logits, targets, max_logit, sum_exp = res + vocab_size = logits.shape[-1] + probs = jnp.exp(logits.astype(jnp.float32) - max_logit) / sum_exp + one_hot = jax.nn.one_hot(targets, vocab_size, dtype=jnp.float32) + d_logits = (probs - one_hot) * g[..., None].astype(jnp.float32) + return d_logits.astype(logits.dtype), None + + +_sparse_cross_entropy_with_logits.defvjp(_sparse_ce_fwd, _sparse_ce_bwd) + + +def compute_loss( + graphdef: models.PipelineGraphDef, + params: dict[str, Any], + batch: dict[str, Any], + *, + vocab_size: int, + wrap: models.Wrapper, + pregathered_params: dict[str, Any] | None = None, +) -> jax.Array: + """Returns the mean cross-entropy over the unpadded tokens of `batch`. + + Args: + graphdef: Static model structure. + params: Per-unit parameters. + batch: A single microbatch. + vocab_size: Number of classes for the one-hot targets. + wrap: Stage wrapping strategy, see :mod:`models`. + pregathered_params: Optional pre-cast, FSDP-gathered layer parameters. + + Returns: + A scalar loss. + """ + del vocab_size + logits = models.forward( + graphdef, + params, + batch, + wrap=wrap, + pregathered_params=pregathered_params, + ) + targets = batch["targets"] + segmentation = batch.get("targets_segmentation") + + @wrap(mesh_utils.UNEMBED_NAME) + def _loss_head(logits_arr, targets_arr, seg_arr): + with models._logical_axis_context(graphdef, logits_arr, wrap): # pylint: disable=protected-access + token_loss = _sparse_cross_entropy_with_logits(logits_arr, targets_arr) + if seg_arr is None: + return jnp.mean(token_loss) + # Padding is encoded as segment id 0; excluding it keeps the loss (and + # hence the gradients) independent of how the batch happens to be padded. + mask = (seg_arr != 0).astype(token_loss.dtype) + num_tokens = jnp.sum(mask) + return jnp.where(num_tokens > 0, jnp.sum(token_loss * mask) / num_tokens, 0.0) + + return _loss_head(logits, targets, segmentation) + + +def make_train_step( + graphdef: models.PipelineGraphDef, + *, + vocab_size: int, + num_microbatches: int, + mode: ExecutionMode, +) -> Callable[[train_state.TrainState, dict[str, Any]], Any]: + """Builds a microbatched training step. + + The global batch (sharded along axis 0 over ``fsdp``) is reshaped to + ``[micro_size, num_microbatches, ...]`` and sliced along axis 1 so that every + microbatch keeps its leading ``micro_size`` dimension evenly sharded across + all FSDP devices in the stage without cross-device resharding. In MPMD mode + every microbatch is wrapped in ``mpmd.call`` with a distinct + ``call_counter``; that is what lets PartIR identify the individual pipeline + "slots" and interleave them according to the configured schedule. + + Args: + graphdef: Static model structure. + vocab_size: Number of classes for the one-hot targets. + num_microbatches: Number of microbatches per optimizer step. + mode: MPMD (pipelined) or SPMD (reference). + + Returns: + A function ``(state, batch) -> (new_state, loss)``. + """ + wrap = mode.stage_wrapper + + def train_step(state: train_state.TrainState, batch: dict[str, Any]) -> tuple[train_state.TrainState, jax.Array]: + def to_microbatches(array): + micro_size = array.shape[0] // num_microbatches + return array.reshape((micro_size, num_microbatches) + array.shape[1:]) + + def loss_fn(params, pregathered, microbatch): + return compute_loss( + graphdef, + params, + microbatch, + vocab_size=vocab_size, + wrap=wrap, + pregathered_params=pregathered, + ) + + def fwd_with_carry_passthrough(params, pregathered, microbatch): + return loss_fn(params, pregathered, microbatch), params + + def accumulate(carry, params, pregathered, microbatch): + loss, grads = jax.value_and_grad(loss_fn)(params, pregathered, microbatch) + return jax.tree.map(jax.lax.add, carry, (loss, grads)) + + microbatched = jax.tree.map(to_microbatches, batch) + params = state.params + pregathered_params = None + if mode is ExecutionMode.MPMD and graphdef.data_parallel_size > 1: + pregathered_params = models.pregather_params( + graphdef, + params, + microbatch_rows=microbatched["inputs"].shape[0], + wrap=wrap, + ) + + with models.defer_fsdp_shard_map_psum(graphdef, pregathered_params, params): + if mode is ExecutionMode.MPMD: + # Trace all forward microbatches before backward microbatches so that in + # the unscheduled MPMD block every forward computation F_s(m+1) precedes + # B_s(m). In 1F1B wavefront passes, mlir::sortTopologically then + # schedules each consumer F_{s+1}(m) and B_s(m) immediately after its + # incoming stage transfer before the next microbatch's transfer is + # emitted, preventing IfrtMergeCopiesAndReshardsPass from fusing + # transfers across consecutive microbatches. Passing `grad_carry` + # through `fwd_with_carry_passthrough` on microbatches 1..N-1 causes + # JAX's VJP transpose to accumulate `total_grads + mb_grads` inside + # each `bwd_call` fragment without allocating a zero-init accumulator on + # microbatch 0. + grad_carry = models.build_grad_carry(graphdef, params, pregathered_params) + vjp_steps = [] + for index in range(num_microbatches): + microbatch = jax.tree.map(lambda x: x[:, index], microbatched) # pylint: disable=cell-var-from-loop + if index == 0: + step_fn = microbatch_call(loss_fn, call_counter=index) + mb_loss, vjp_fn = jax.vjp(step_fn, grad_carry, pregathered_params, microbatch) + else: + step_fn = microbatch_call(fwd_with_carry_passthrough, call_counter=index) + (mb_loss, _), vjp_fn = jax.vjp(step_fn, grad_carry, pregathered_params, microbatch) + vjp_steps.append((index, mb_loss, vjp_fn)) + + total_loss = jnp.zeros(()) + total_grads = None + for index, mb_loss, vjp_fn in vjp_steps: + total_loss = total_loss + mb_loss + if index == 0: + total_grads, _, _ = vjp_fn(jnp.ones_like(mb_loss)) + else: + total_grads, _, _ = vjp_fn((jnp.ones_like(mb_loss), total_grads)) + else: + carry = (jnp.zeros(()), jax.tree.map(jnp.zeros_like, params)) + for index in range(num_microbatches): + microbatch = jax.tree.map(lambda x: x[:, index], microbatched) # pylint: disable=cell-var-from-loop + carry = accumulate(carry, params, pregathered_params, microbatch) + total_loss, total_grads = carry + + grads = models.reduce_scatter_deferred_grads( + graphdef, + params, + pregathered_params, + total_grads, + num_microbatches=num_microbatches, + wrap=wrap, + ) + loss = total_loss / num_microbatches + return state.apply_gradients(grads=grads), loss + + return train_step + + +def make_optimizer(learning_rate: float) -> optax.GradientTransformation: + """Returns the optimizer used by every mode. + + Kept here so the MPMD run and its SPMD reference cannot accidentally use + different optimizers or hyperparameters. + + Args: + learning_rate: Peak (constant) learning rate. + """ + return optax.adamw(learning_rate=learning_rate) + + +def create_train_state(params: dict[str, Any], learning_rate: float) -> train_state.TrainState: + """Creates the optimizer state for `params`. + + Args: + params: The model parameters. + learning_rate: Peak (constant) learning rate. + + Returns: + A :class:`flax.training.train_state.TrainState` whose every leaf is an + array. + """ + state = train_state.TrainState.create( + # This model is applied through `models.forward`, not through + # `state.apply_fn`; TrainState nonetheless requires the field. + apply_fn=lambda *args, **kwargs: None, + params=params, + tx=make_optimizer(learning_rate), + ) + # `TrainState.create` sets `step` to the Python `int` 0, but + # `apply_gradients` returns `step + 1` as a traced array. The state therefore + # changes type after one step, which breaks both PartIR's input/output + # constraint checking ("'int' object has no attribute 'shape'") and the + # requirement that a compiled step accept its own output. Pinning the dtype + # up front keeps the state a fixed point of the step function. + return state.replace(step=jnp.asarray(state.step, jnp.int32)) diff --git a/tests/unit/mpmd_test/benchmark_test.py b/tests/unit/mpmd_test/benchmark_test.py new file mode 100644 index 0000000000..22b233a86b --- /dev/null +++ b/tests/unit/mpmd_test/benchmark_test.py @@ -0,0 +1,147 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the MPMD pipeline's step statistics, throughput and trace (benchmark.py, CPU only).""" + +import sys +import types +import unittest +from unittest import mock + +import jax.numpy as jnp + +from maxtext.experimental.mpmd.partir import benchmark +from maxtext.experimental.mpmd.partir import config +from maxtext.experimental.mpmd.partir import hparams as hp +from maxtext.utils import maxtext_utils + + +def loss_step(losses): + """A step function that returns the next of `losses` and leaves the state alone.""" + + def step(state, batch): + del batch + return state, jnp.float32(next(losses)) + + return step + + +class StepStatsTest(unittest.TestCase): + + def test_first_and_final_loss(self): + _, stats = benchmark.run_steps(loss_step(iter([5.0, 4.0, 3.0, 2.0])), 0, None, num_steps=2, warmup_steps=2) + self.assertEqual((stats.first_loss, stats.loss, stats.num_steps), (5.0, 2.0, 2)) + _, stats = benchmark.run_steps(loss_step(iter([3.0, 1.0])), 0, None, num_steps=2) + self.assertEqual((stats.first_loss, stats.loss), (3.0, 1.0)) + + def test_abort_on_the_first_non_finite_loss(self): + step = loss_step(iter([5.0, 4.0, float("nan"), 2.0])) + with self.assertRaises(benchmark.NonFiniteLossError) as raised: + benchmark.run_steps(step, 0, None, num_steps=3, warmup_steps=1, abort_on_nonfinite=True) + self.assertEqual((raised.exception.step, raised.exception.losses[:2]), (3, (5.0, 4.0))) + self.assertIn("(losses from step 1: 5, 4, nan)", str(raised.exception)) + # without the flag it runs on + _, stats = benchmark.run_steps(loss_step(iter([5.0, float("inf")])), 0, None, num_steps=2) + self.assertEqual(stats.loss, float("inf")) + + def test_steps_numbered_after_an_earlier_call(self): + """train.py's profiled steps after 1 warm-up and 3 timed steps: a NaN in the second is step 6.""" + step = loss_step(iter([4.47, float("nan")])) + with self.assertRaises(benchmark.NonFiniteLossError) as raised: + benchmark.run_steps(step, 0, None, num_steps=2, first_step=4, abort_on_nonfinite=True) + self.assertEqual(raised.exception.step, 6) + self.assertIn("step 6 returned a loss of nan (losses from step 5: 4.47, nan)", str(raised.exception)) + + def test_loss_warning_only_when_the_loss_rose(self): + falling = benchmark.StepStats(step_times_ms=(1.0,), loss=1.2, first_loss=24.8) + self.assertEqual(benchmark.loss_warning(falling, 1e-5), []) + rising = benchmark.StepStats(step_times_ms=(1.0,), loss=675.0, first_loss=24.8) + (line,) = benchmark.loss_warning(rising, 1e-3) + self.assertIn("rose from 24.8 to 675", line) + self.assertIn("--learning_rate 0.001", line) + self.assertEqual(benchmark.loss_warning(benchmark.StepStats(step_times_ms=(), loss=1.0), 1e-3), []) + (nan_line,) = benchmark.loss_warning( + benchmark.StepStats(step_times_ms=(1.0, 1.0), loss=float("nan"), first_loss=20.99), 1e-5 + ) + self.assertIn("ERROR", nan_line) + self.assertIn("nan after 2 timed steps", nan_line) + + +class ThroughputTest(unittest.TestCase): + + def test_tokens_and_flops_of_the_mpmd_model(self): + """A step's tokens and FLOPs are one stage's batch's, over every device; the MPMD model has no MTP block.""" + cfg = config.build_maxtext_config(hp.Hparams(model_name="deepseek3-tiny", num_layers=2, num_stages=1)) + stats = benchmark.StepStats(step_times_ms=(400.0, 500.0, 900.0), loss=1.0) # median 0.5 s + + def throughput(maxtext_config): + return benchmark.compute_throughput( + stats=stats, maxtext_config=maxtext_config, devices_per_stage=2, num_devices=8, peak_tflops_per_device=10.0 + ) + + tflops, _, _ = maxtext_utils.calculate_tflops_training_per_device(cfg, log=False) + result = throughput(cfg) + self.assertEqual(result.tokens_per_step, 2 * 2 * 512) # per_device_batch_size x devices per stage x sequence + self.assertAlmostEqual(result.tflops_per_step_per_device, tflops * 2 / 8) + self.assertAlmostEqual(result.tflops_per_second_per_device, tflops * 2 / 8 / 0.5) + self.assertAlmostEqual(result.mfu, tflops * 2 / 8 / 0.5 / 10.0) + self.assertAlmostEqual(result.tokens_per_second_per_device, 2048 / 0.5 / 8) + # MaxText counts an MTP block's FLOPs (config.py refuses the setting; replace() bypasses it): none are charged. + mtp = cfg.replace(mtp_num_layers=1) + self.assertGreater(maxtext_utils.calculate_tflops_training_per_device(mtp, log=False)[0], tflops * 1.05) + self.assertEqual(throughput(mtp), result) + + +class ProfileTest(unittest.TestCase): + + def _profile(self, start_trace): + """benchmark.profile around nothing, off Pathways, with jax's tracer replaced by `start_trace`.""" + fake = types.SimpleNamespace(is_pathways_backend_used=lambda: False) + with ( + mock.patch.dict(sys.modules, {"pathwaysutils": fake}), + mock.patch("jax.profiler.start_trace", side_effect=start_trace) as start, + mock.patch("jax.profiler.stop_trace"), + self.assertLogs("absl", level="INFO") as logs, + ): + with benchmark.profile(True, tag="t", profile_dir="/tmp/xprof_test") as urls: + pass + return start.call_args_list, urls, "\n".join(logs.output) + + def test_one_tpu_one_sparsecore_one_tile(self): + calls, urls, _ = self._profile(lambda *a, **k: None) + (call,) = calls + self.assertEqual(call.args, ("/tmp/xprof_test/t",)) + self.assertEqual( + call.kwargs["profiler_options"].advanced_configuration, + { + "tpu_num_chips_to_profile_per_task": 1, + "tpu_num_sparse_cores_to_trace": 1, + "tpu_num_sparse_core_tiles_to_trace": 1, + }, + ) + self.assertEqual(urls, ["/tmp/xprof_test/t"]) + + def test_refused_options_trace_untrimmed(self): + def start_trace(*args, profiler_options=None): + if profiler_options is not None: + raise RuntimeError("Bad PluginProgram") + + calls, urls, out = self._profile(start_trace) + self.assertEqual([sorted(c.kwargs) for c in calls], [["profiler_options"], []]) + self.assertIn("The trimmed trace was refused (Bad PluginProgram); tracing untrimmed.", out) + self.assertEqual(urls, ["/tmp/xprof_test/t"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/config_test.py b/tests/unit/mpmd_test/config_test.py new file mode 100644 index 0000000000..58833db3a6 --- /dev/null +++ b/tests/unit/mpmd_test/config_test.py @@ -0,0 +1,160 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the MaxText settings the MPMD pipeline derives (config.py).""" + +import unittest + +import jax + +from maxtext.common.common_types import DecoderBlockType +from maxtext.experimental.mpmd.partir import config +from maxtext.experimental.mpmd.partir import hparams as hp + +BASE = {"model_name": "deepseek3-tiny", "num_layers": 8, "num_stages": 4} + + +def setUpModule(): + # MaxText checks its own pipeline's batch against the devices: 4 stages need 4 (per_device_batch_size 2 x 1 device + # is not divisible into 4 pipeline microbatches). + if len(jax.devices()) < 4: + raise unittest.SkipTest("needs 4 devices (XLA_FLAGS=--xla_force_host_platform_device_count=4)") + + +class RematTest(unittest.TestCase): + + def test_pipeline_parallelism_without_remat(self): + """MaxText refuses remat_policy=none with ici_pipeline_parallelism > 1; the MPMD model keeps its own choice.""" + hparams = hp.Hparams(**BASE) + cfg = config.build_maxtext_config(hparams) + self.assertEqual(cfg.ici_pipeline_parallelism, 4) + self.assertEqual((cfg.remat_policy, hparams.mpmd_remat_policy), ("full", "none")) + hparams = hp.Hparams(**BASE, remat=True, remat_policy="minimal") + cfg = config.build_maxtext_config(hparams) + self.assertEqual((cfg.remat_policy, hparams.mpmd_remat_policy), ("minimal", "minimal")) + # Only MaxText's own (typed) fields: a key added to get_keys() would not survive cfg.replace(). + self.assertFalse([key for key in cfg.get_keys() if key.startswith("mpmd_")]) + + +class Float32TilesTest(unittest.TestCase): + + def test_float32_halves_the_gmm_tiles_and_overrides_still_win(self): + bf16 = config.build_maxtext_config(hp.Hparams(**BASE)) + self.assertEqual((bf16.wi_tile_fwd_embed_dim, bf16.wo_tile_drhs_mlp_dim), (1024, 1024)) + f32 = config.build_maxtext_config(hp.Hparams(**BASE, maxtext_overrides=("dtype=float32",))) + self.assertEqual(str(f32.dtype), "float32") + for weight in ("wi", "wo"): + for kernel in ("fwd", "dlhs", "drhs"): + self.assertEqual(getattr(f32, f"{weight}_tile_{kernel}_embed_dim"), 512) + self.assertEqual(getattr(f32, f"{weight}_tile_{kernel}_mlp_dim"), 512) + self.assertEqual(getattr(f32, f"{weight}_tile_{kernel}_batch_seq"), 512) + mine = config.build_maxtext_config( + hp.Hparams(**BASE, maxtext_overrides=("dtype=float32", "wi_tile_fwd_embed_dim=256")) + ) + self.assertEqual((mine.wi_tile_fwd_embed_dim, mine.wo_tile_fwd_embed_dim), (256, 512)) + + +class BuildableTest(unittest.TestCase): + + def test_every_supported_decoder_block_builds_its_config(self): + for model_name, block in ( + ("simple", DecoderBlockType.SIMPLE_MLP), + ("deepseek3-tiny", DecoderBlockType.DEEPSEEK), + ("llama3.1-8b", DecoderBlockType.LLAMA2), + ("mistral-7b", DecoderBlockType.MISTRAL), + ("mixtral-8x7b", DecoderBlockType.MIXTRAL), + ("qwen3-30b-a3b", DecoderBlockType.QWEN3_MOE), + ): + cfg = config.build_maxtext_config(hp.Hparams(model_name=model_name, num_layers=4, num_stages=2)) + self.assertEqual(cfg.decoder_block, block, model_name) + + def test_refuses_what_the_mpmd_model_does_not_build(self): + tied = {"model_name": "qwen3-0.6b", "num_layers": 4, "num_stages": 4} + with self.assertRaisesRegex(ValueError, "logits_via_embedding=false"): + config.build_maxtext_config(hp.Hparams(**tied)) + untied = config.build_maxtext_config(hp.Hparams(**tied, maxtext_overrides=("logits_via_embedding=false",))) + self.assertFalse(untied.logits_via_embedding) + self.assertEqual(untied.decoder_block, DecoderBlockType.QWEN3) + # Each of _check_buildable's refusals: one setting each, the first's key named in the error. + for overrides in ( + ("use_m3_model=true",), + ("trainable_position_size=16",), + ("mhc_expansion_rate=2",), + # The layers are built unquantized, while spmd_baseline's MaxText run would be quantized. + ("quantization=int8",), + ("shard_mode=explicit",), + ("prefetch_fsdp_weights=true",), + ("lm_head_fsdp_as_vocab_tp=true",), + ("lm_head_weight_grad_in_kernel_order=true",), + ("tie_lm_head_cotangents=true",), + ("cast_logits_to_fp32=false",), + # fp8 weights: logits_dense quantized, or left in the compute dtype while the rest is fp8. + ("weight_dtype=float8_e4m3fn",), + ("weight_dtype=float8_e4m3fn", "unquantized_modules=[logits_dense]"), + ): + key = overrides[0].partition("=")[0] + with self.assertRaisesRegex(ValueError, f"does not build {key}=", msg=overrides): + config.build_maxtext_config( + hp.Hparams(model_name="simple", num_layers=4, num_stages=2, maxtext_overrides=overrides) + ) + + def test_refuses_what_the_mpmd_step_leaves_out(self): + """The MPMD step trains on the token cross-entropy alone, without an MTP block or a sinusoidal embedding.""" + + def build(model_name, overrides): + return config.build_maxtext_config( + hp.Hparams(model_name=model_name, num_layers=4, num_stages=2, maxtext_overrides=overrides) + ) + + # deepseek3-tiny's MLA with the sparse indexer, small enough for a sequence of 512 (and for MaxText's checks). + indexer = ("use_indexer=true", "attention=dot_product", "indexer_topk=256", "indexer_n_heads=4") + for model_name, overrides, key, off in ( + ("deepseek3-tiny", ("mtp_num_layers=1",), "mtp_num_layers", "0"), + ("simple", ("use_untrainable_positional_embedding=true",), "use_untrainable_positional_embedding", "false"), + ("deepseek3-tiny", ("load_balance_loss_weight=0.01",), "load_balance_loss_weight", "0"), + ("simple", ("z_loss_multiplier=1e-4",), "z_loss_multiplier", "0"), + ("deepseek3-tiny", ("routed_bias_update_rate=0.001",), "routed_bias_update_rate", "0"), + ("deepseek3-tiny", indexer + ("indexer_loss_scaling_factor=0.01",), "indexer_loss_scaling_factor", "0"), + ): + with self.subTest(key=key): + with self.assertRaisesRegex( + ValueError, rf"\({key}=[^)]*\), which the MPMD step leaves out.* Pass --maxtext_overrides={key}={off} to" + ): + build(model_name, overrides) + build(model_name, overrides + (f"{key}={off}",)) # the hint's override builds + # The load-balance loss is in qwen3-235b-a22b's own config. + with self.assertRaisesRegex(ValueError, r"MoE load-balance loss \(load_balance_loss_weight=0.001\)"): + build("qwen3-235b-a22b", ()) + self.assertEqual(build("qwen3-235b-a22b", ("load_balance_loss_weight=0",)).decoder_block, DecoderBlockType.QWEN3_MOE) + with self.assertRaisesRegex(ValueError, r"\(mtp_num_layers=1\) and the z-loss .* to train without them"): + build("deepseek3-tiny", ("mtp_num_layers=1", "z_loss_multiplier=1e-4")) + # max_utils.cross_entropy_with_logits adds z_loss_multiplier * log(z)^2 whatever its sign. + with self.assertRaisesRegex(ValueError, r"the z-loss \(z_loss_multiplier=-0\.0001\), which"): + build("simple", ("z_loss_multiplier=-1e-4",)) + # Only where MaxText's trainer adds the term: a dense model has no MoE loss, a fixed routing bias no updates, and + # the indexer's loss needs the indexer. + build("llama3.1-8b", ("load_balance_loss_weight=0.01",)) + build("deepseek3-tiny", ("routed_bias=false", "routed_bias_update_rate=0.001")) + build("deepseek3-tiny", ("indexer_loss_scaling_factor=0.01",)) + + def test_the_decoder_block_is_maxtexts(self): + """A named model's block is the one pyconfig resolves from its config; config.py names only simple_mlp's.""" + mistral = hp.Hparams(model_name="mistral-7b", num_layers=4, num_stages=2) + with self.assertRaisesRegex(ValueError, "MaxText resolved decoder_block=llama2, but"): + config.build_maxtext_config(mistral, overrides={"decoder_block": "llama2"}) + self.assertEqual(config.build_maxtext_config(mistral).decoder_block, DecoderBlockType.MISTRAL) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/documented_commands_test.py b/tests/unit/mpmd_test/documented_commands_test.py new file mode 100644 index 0000000000..7245d0bec7 --- /dev/null +++ b/tests/unit/mpmd_test/documented_commands_test.py @@ -0,0 +1,132 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""The command lines the partir package documents parse, and pass the checks the TPUs would otherwise make.""" + +import contextlib +import io +import os +import re +import shlex +import unittest + +from absl import flags + +from maxtext.experimental.mpmd.partir import hparams as hp +from maxtext.experimental.mpmd.partir import launch +from maxtext.experimental.mpmd.partir import parity +from maxtext.experimental.mpmd.partir import spmd_baseline +from maxtext.experimental.mpmd.partir import train +from maxtext.experimental.mpmd.partir import train_compile + +_PACKAGE = os.path.dirname(hp.__file__) +# Where commands are documented: module docstrings, the README and local_pathways.sh's usage. +_DOCUMENTS = ( + "README.md", + "local_pathways.sh", + "launch.py", + "parity.py", + "spmd_baseline.py", + "train.py", + "train_compile.py", +) +_DEFINE_FLAGS = { + "launch": launch.define_flags, + "parity": parity.define_flags, + "spmd_baseline": spmd_baseline.define_flags, + "train": train.define_flags, + "train_compile": train_compile.define_flags, +} +# A command's arguments run to the end of its line, or to the backticks closing inline code. +_COMMAND = re.compile(r"-m maxtext\.experimental\.mpmd\.partir\.(\w+)([^\n`]*)") +# A shell operator or redirection ends the arguments. +_SHELL_END = re.compile(r"(;|&&?|\|\|?|\d*>>?(&\d+)?|<)") +# Commands that name no TPU type run on 8 devices: train_compile's fake CPU devices (--num_cpu_devices), or the 4-chip +# TPU7x VM (tpu7x:2x2x1) of local_pathways.sh and the README. +_LOCAL_DEVICES = 8 + + +def documented_commands(text): + """Returns ``(module, argv)`` for each ``python3 -m maxtext.experimental.mpmd.partir. ...`` in `text`. + + Lines continued with a backslash are joined first, also inside shell comments. The arguments are split as the + shell splits them (``--flag=value``, ``--flag value`` and quoted values alike) and end at a comment, a shell operator + or redirection, or the end of the command. + """ + commands = [] + for match in _COMMAND.finditer(re.sub(r"\\\n[\s#]*", " ", text)): + argv = [] + for word in shlex.split(match.group(2), comments=True): + if _SHELL_END.fullmatch(word): + break + argv.append(word) + commands.append((match.group(1), argv)) + return commands + + +class DocumentedCommandsTest(unittest.TestCase): + + def test_every_documented_command(self): + found = [] + for document in _DOCUMENTS: + with open(os.path.join(_PACKAGE, document), encoding="utf-8") as handle: + found += [(document, module, argv) for module, argv in documented_commands(handle.read())] + # The README documents train, parity, train_compile, launch and spmd_baseline runs; every module docstring one. + self.assertGreaterEqual(len(found), 12, found) + self.assertEqual({module for _, module, _ in found}, set(_DEFINE_FLAGS)) + for document, module, argv in found: + with self.subTest(document=document, command=" ".join([module, *argv])): + flag_values = flags.FlagValues() + _DEFINE_FLAGS[module](flag_values) + flag_values([module, *argv]) + if module == "launch": + # The launcher's own checks: required flags, the workload name, slices and stages, the microbatch split. + with contextlib.redirect_stdout(io.StringIO()): + launch.main([module], flag_values=flag_values) + continue + hparams = hp.from_flags(flag_values) + if module == "spmd_baseline": + devices = hp.devices_in_device_type(flag_values.device_type) * flag_values.num_slices + with contextlib.redirect_stdout(io.StringIO()): + spmd_baseline.main([module], flag_values=flag_values) # MaxText's pipeline constraints + elif module == "train_compile" and flag_values.compile_topology == "cpu": + devices = flag_values.num_cpu_devices + else: + devices = _LOCAL_DEVICES + # The MPMD run of the same flags must split each microbatch over its stage's batch-sharding devices. + hp.check_microbatch_split_on(hparams, devices) + + def test_the_extraction(self): + text = ( + " python3 -m maxtext.experimental.mpmd.partir.train --pp=4 \\\n" + " --num_microbatches=4 # a comment\n" + "# python3 -m maxtext.experimental.mpmd.partir.parity --pp=2 \\\n" + "# --steps=3\n" + "python3 -m maxtext.experimental.mpmd.partir.train --num_microbatches 8 --run_name 'a b' \\\n" + ' --maxtext_overrides="dtype=float32" > /tmp/train.log 2>&1\n' + "Run `python3 -m maxtext.experimental.mpmd.partir.launch --cluster=` first.\n" + ) + self.assertEqual( + documented_commands(text), + [ + ("train", ["--pp=4", "--num_microbatches=4"]), + ("parity", ["--pp=2", "--steps=3"]), + ("train", ["--num_microbatches", "8", "--run_name", "a b", "--maxtext_overrides=dtype=float32"]), + ("launch", ["--cluster="]), + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/hparams_test.py b/tests/unit/mpmd_test/hparams_test.py new file mode 100644 index 0000000000..d4a015aa8e --- /dev/null +++ b/tests/unit/mpmd_test/hparams_test.py @@ -0,0 +1,223 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the MPMD pipeline's hyperparameters and their flags (no JAX).""" + +import dataclasses +import os +import tempfile +import unittest + +from absl import flags + +from maxtext.experimental.mpmd.partir import hparams as hp + + +def parse(argv): + """Parses `argv` with the hyperparameter flags registered on a fresh FlagValues.""" + flag_values = flags.FlagValues() + hp.define_flags(flag_values) + flag_values(["prog", *argv]) + return flag_values + + +class ScheduleTest(unittest.TestCase): + + def test_aliases_and_oss_spellings(self): + for raw, want in [ + ("1F1B", "ONE_FWD_ONE_BWD"), + ("gpipe", "GPIPE"), + ("GPipe", "GPIPE"), + ("ZB-H1", "ZERO_BUBBLE_H1"), + ("ZeroBubbleH1", "ZERO_BUBBLE_H1"), + ("ZeroBubbleH2HalfTxLatency", "ZERO_BUBBLE_H2_HALF_TX_LATENCY"), + ("GPipeBut1F1BForLastMesh", "GPIPE_BUT_1F1B_FOR_LAST_MESH"), + ("Circular", "CIRCULAR"), + ("None", "NONE"), + ]: + self.assertEqual(hp.normalize_schedule(raw), want, raw) + with self.assertRaisesRegex(ValueError, "Unknown pipeline schedule"): + hp.normalize_schedule("2F2B") + + def test_schedule_help_lists_only_usable_schedules(self): + text = parse([])["pipeline_schedule"].help + self.assertIn("ONE_FWD_ONE_BWD", text) + for name in hp.UNSUPPORTED_SCHEDULES: + self.assertNotIn(f"{name},", text) + self.assertNotIn(f"{name} (", text) + + def test_every_schedule_has_an_oss_name(self): + self.assertEqual(set(hp.OSS_SCHEDULE_NAMES), set(hp.PIPELINE_SCHEDULES)) + # The OSS spellings round-trip through normalize_schedule. + for name, oss in hp.OSS_SCHEDULE_NAMES.items(): + self.assertEqual(hp.normalize_schedule(oss), name) + + +class HparamsTest(unittest.TestCase): + + def test_validation(self): + with self.assertRaisesRegex(ValueError, "divisible by num_stages"): + hp.Hparams(num_layers=6, num_stages=4) + with self.assertRaisesRegex(ValueError, "must have length"): + hp.Hparams(num_layers=8, num_stages=4, stage_layer_counts="1,2,3") + with self.assertRaisesRegex(ValueError, "must equal"): + hp.Hparams(num_layers=8, num_stages=2, stage_layer_counts="3,4") + self.assertEqual(hp.Hparams(num_layers=8, num_stages=2, stage_layer_counts="3,5").stage_layer_counts, (3, 5)) + with self.assertRaisesRegex(ValueError, "moe_dispatch"): + hp.Hparams(expert=2, moe_dispatch="all_to_all") + for bad in ("dtype", "=float32", " dtype=float32"): + with self.assertRaisesRegex(ValueError, "key=value"): + hp.Hparams(maxtext_overrides=(bad,)) + self.assertEqual(hp.Hparams(maxtext_overrides="dtype=float32").maxtext_overrides, ("dtype=float32",)) + # A MaxText key a hyperparameter owns must be set through that flag. + for owned, flag in ( + ("learning_rate=1e-5", "--learning_rate"), + ("per_device_batch_size=4", "--per_device_batch_size"), + ("ici_fsdp_parallelism=2", "--fsdp"), + ("scan_layers=true", "one computation per layer"), + ("remat_policy=full", "--remat and --remat_policy"), + ): + with self.assertRaisesRegex(ValueError, flag): + hp.Hparams(maxtext_overrides=(owned,)) + with self.assertRaisesRegex(ValueError, "--num_microbatches"): + hp.Hparams(maxtext_overrides=("gradient_accumulation_steps=4",)) + with self.assertRaisesRegex(ValueError, "YaRN"): + hp.Hparams(model_name="deepseek3-tiny", maxtext_overrides=("rope_type=yarn",)) + self.assertEqual( + hp.Hparams(model_name="simple", maxtext_overrides=("rope_type=llama3.1",)).maxtext_overrides, + ("rope_type=llama3.1",), + ) + for schedule in ("ParallelPipelinesWithWrapAround", "Circular", "CIRCULAR_WITH_REVERSED_BACKWARD"): + with self.assertRaisesRegex(ValueError, "not supported"): + hp.Hparams(pipeline_schedule=schedule) + + def test_only_the_supported_decoder_blocks(self): + for model_name, block in ( + ("simple", "simple_mlp"), + ("deepseek3-tiny", "deepseek"), + ("llama3.1-8b", "llama2"), + ("mistral-7b", "mistral"), + ("mixtral-8x7b", "mixtral"), + ("qwen3-0.6b", "qwen3"), + ("qwen3-30b-a3b", "qwen3_moe"), + ): + self.assertEqual(hp.Hparams(model_name=model_name).decoder_block, block) + for model_name, block in (("gpt3-52k", "gpt3"), ("deepseek4-tiny", "deepseek4"), ("gemma4-e2b", "gemma4_small")): + with self.assertRaisesRegex(ValueError, f"decoder_block={block}, which the MPMD pipeline does not build"): + hp.Hparams(model_name=model_name) + + def test_a_model_config_without_a_decoder_block_is_refused(self): + """MaxText builds these with its m3 backend; they were once built as the toy simple_mlp block under their name.""" + for model_name in ("granite-3.0-1b-a400m", "glm5.3-flash"): + with self.assertRaisesRegex(ValueError, f"model_name={model_name}: its MaxText config names no decoder_block"): + hp.Hparams(model_name=model_name, maxtext_overrides=("logits_via_embedding=false", "mhc_expansion_rate=1")) + + def test_a_missing_model_config_is_refused(self): + """pyconfig would go on with base.yml's model under the name; the launcher refuses it before any slice is up.""" + for overrides in ((), ("rope_type=yarn",)): # the override check reads the model config too + with self.assertRaisesRegex(FileNotFoundError, "would silently fall back"): + hp.Hparams(model_name="llama3.1-8b-does-not-exist", maxtext_overrides=overrides) + + def test_remat_policies(self): + """MaxText's resolver takes each (models_test checks it); any other name fails before a model is built.""" + for policy in hp.REMAT_POLICIES: + self.assertEqual(hp.Hparams(remat=True, remat_policy=policy).mpmd_remat_policy, policy) + # MaxText's offloading and quantization policies, names only the MPMD model knew, none, and a typo. + for policy in ("qkv_proj_offloaded", "custom", "minimal_with_quantization", "alternate", "dots", "none", "minimum"): + with self.assertRaisesRegex(ValueError, f"remat_policy={policy} is not one the MPMD model checkpoints"): + hp.Hparams(remat=True, remat_policy=policy) + + def test_job_args_cover_every_field(self): + """The launcher can forward every hyperparameter.""" + fields = {f.name for f in dataclasses.fields(hp.Hparams)} + self.assertEqual(fields, set(hp.FORWARDED_FLAGS)) + + def test_job_args_round_trip(self): + want = hp.Hparams( + model_name="deepseek3-tiny", + num_layers=12, + num_stages=3, + fsdp=2, + num_microbatches=6, + pipeline_schedule="ZB-H1", + remat=True, + stage_layer_counts="3,4,5", + per_device_batch_size=1.5, + maxtext_overrides=("dtype=float32", "attention=dot_product"), + ) + self.assertEqual(hp.from_flags(parse(hp.job_argv(hp.to_job_args(want)))), want) + + def test_flags_are_defined_once_where_asked(self): + flag_values = flags.FlagValues() + hp.define_flags(flag_values) + hp.define_flags(flag_values) # a second call is a no-op + self.assertIn("num_microbatches", flag_values) + + def test_real_models_keep_their_dimensions_unless_given(self): + self.assertEqual(hp.from_flags(parse(["--model_name=llama3.1-8b"])).emb_dim, -1) + self.assertEqual(hp.from_flags(parse(["--model_name=llama3.1-8b", "--emb_dim=256"])).emb_dim, 256) + self.assertEqual(hp.from_flags(parse(["--model_name=simple"])).emb_dim, hp.Hparams().emb_dim) + self.assertEqual(hp.from_flags(parse(["--pp=2", "--num_layers=4"])).num_stages, 2) + + def test_float32_gmm_tiles(self): + self.assertEqual(hp.float32_gmm_tiles(hp.Hparams()), {}) + tiles = hp.float32_gmm_tiles(hp.Hparams(maxtext_overrides=("dtype=float32",))) + self.assertEqual(len(tiles), 12) + self.assertEqual(set(tiles.values()), {512}) + self.assertEqual(hp.float32_gmm_tiles(hp.Hparams(maxtext_overrides=("dtype=float32", "dtype=bfloat16"))), {}) + self.assertEqual(hp.override_value(hp.Hparams(maxtext_overrides=("a=1", "b=2", "a=3")), "a"), "3") + + def test_moe_dispatch_overrides(self): + self.assertEqual(hp.moe_dispatch_overrides(hp.Hparams()), {}) + ring = hp.moe_dispatch_overrides(hp.Hparams(expert=4, moe_dispatch="ring_of_experts")) + self.assertTrue(ring["use_ring_of_experts"]) + self.assertEqual(ring["ici_expert_parallelism"], 4) + self.assertEqual( + set(ring), {"ici_expert_parallelism", "use_ring_of_experts", "use_ragged_sort", "num_moe_token_chunks"} + ) + + def test_microbatch_split(self): + h = hp.Hparams(num_microbatches=4, per_device_batch_size=2.0) + hp.check_microbatch_split(h, devices_per_stage=4, data_parallel_size=2) # 8 rows, microbatches of 2 over 2 + with self.assertRaisesRegex(ValueError, "2 sequences per microbatch, which must be a multiple of the 4 devices"): + hp.check_microbatch_split(h, devices_per_stage=4, data_parallel_size=4) + with self.assertRaisesRegex(ValueError, "Global batch 6"): + hp.check_microbatch_split(h, devices_per_stage=3, data_parallel_size=1) # 6 rows in 4 microbatches + + def test_ragged_buffer_note(self): + self.assertIsNone(hp.ragged_buffer_note(hp.Hparams())) + self.assertIn("--ragged_buffer_factor=2", hp.ragged_buffer_note(hp.Hparams(expert=2))) + self.assertIsNone(hp.ragged_buffer_note(hp.Hparams(expert=2, ragged_buffer_factor=2.0))) + + def test_device_counts(self): + self.assertEqual( + [hp.devices_in_device_type(t) for t in ("v5p-16", "v6e-16", "tpu7x-4x4x4", "tpu7x-2x2x1", "v5p", "x-y")], + [8, 16, 128, 8, 0, 0], + ) + + def test_read_xla_flags_file(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "x.flags") + with open(path, "w", encoding="utf-8") as f: + f.write("# comment\n\n--xla_a=true\n --xla_b=65536 \n--xla_c=x=y\n") + self.assertEqual(hp.read_xla_flags_file(path), {"xla_a": "true", "xla_b": "65536", "xla_c": "x=y"}) + for bad in ("xla_a=true", "--xla_a", "--=1"): + with open(path, "w", encoding="utf-8") as f: + f.write(bad + "\n") + with self.assertRaisesRegex(ValueError, "expected --key=value"): + hp.read_xla_flags_file(path) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/launch_test.py b/tests/unit/mpmd_test/launch_test.py new file mode 100644 index 0000000000..6caef4ed1a --- /dev/null +++ b/tests/unit/mpmd_test/launch_test.py @@ -0,0 +1,319 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the Pathways launcher's command lines (no JAX, no cluster).""" + +import contextlib +import io +import os +import shlex +import tempfile +import unittest + +from absl import app +from absl import flags + +from maxtext.experimental.mpmd.partir import hparams as hp +from maxtext.experimental.mpmd.partir import launch + +REQUIRED = [ + "--cluster=my-cluster", + "--project=my-project", + "--zone=us-east5-b", + "--docker_image=example.com/maxtext:latest", + "--pathways_gcs_location=gs://bucket/pathways", + "--device_type=v5p-16", + "--workload=mpmd-pp4", +] +MODEL = ["--pp=4", "--fsdp=2", "--num_microbatches=8", "--per_device_batch_size=8", "--model_name=deepseek3-tiny"] + + +def parse(*argv): + flag_values = flags.FlagValues() + launch.define_flags(flag_values) + flag_values(["launch", *argv]) + return flag_values + + +def printed(*argv, extra=()): + """The commands main prints for `argv` (flags) and `extra` (the arguments after --).""" + out = io.StringIO() + with contextlib.redirect_stdout(out): + launch.main(["launch", *extra], flag_values=parse(*argv)) + return [shlex.split(line) for line in out.getvalue().splitlines()] + + +def command_of(argv): + """The entry point's command inside an xpk or gcluster argv.""" + (command,) = [a.partition("=")[2] for a in argv if a.startswith("--command=")] + return shlex.split(command) + + +class ModuleArgsTest(unittest.TestCase): + + def test_only_the_trainer_gets_its_flags(self): + hparams = hp.Hparams(maxtext_overrides=("dtype=float32",)) + train = launch.module_args(hparams, parse(*REQUIRED)) + self.assertIn("--noenable_profile", train) + self.assertIn("--run_name=mpmd-pp4", train) + self.assertIn("--maxtext_overrides=dtype=float32", train) + parity = launch.module_args(hparams, parse(*REQUIRED, "--module=parity"), ["--loss_tolerance=1e-3"]) + self.assertFalse([a for a in parity if a.startswith(("--enable_profile", "--profile_", "--run_name"))]) + self.assertEqual(parity[-1], "--loss_tolerance=1e-3") + self.assertIn("--compile_topology=local", launch.module_args(hparams, parse(*REQUIRED, "--module=train_compile"))) + # What the launcher sends parses back into the same hyperparameters. + flag_values = flags.FlagValues() + hp.define_flags(flag_values) + flag_values(["parity", *[a for a in parity if not a.startswith("--loss_tolerance")]]) + self.assertEqual(hp.from_flags(flag_values), hparams) + + def test_extra_arguments_must_be_entry_point_flags(self): + flag_values = parse(*REQUIRED, "--module=parity") + with self.assertRaisesRegex(app.UsageError, "must be --flags"): + launch.module_args(hp.Hparams(), flag_values, ["stray"]) + # Hyperparameter and launcher flags after -- would bypass main()'s validation. + for item in ( + "--num_microbatches=3", + "--pp=2", + "--noremat", + "--pipeline_schedule=Circular", + "--maxtext_overrides=dtype=float32", + "--enable_profile", + "--cluster=x", + ): + with self.assertRaisesRegex(app.UsageError, "before --", msg=item): + launch.module_args(hp.Hparams(), flag_values, [item]) + self.assertEqual( + launch.module_args(hp.Hparams(), flag_values, ["--noise_floor_factor=3"])[-1], "--noise_floor_factor=3" + ) + + +class ChecksTest(unittest.TestCase): + + def test_slices_and_stages_divide(self): + hparams = hp.Hparams(num_stages=4, num_microbatches=8, per_device_batch_size=8) + launch.check_slices(hparams, "v5p-16", 2) # 2 stages per slice + launch.check_slices(hp.Hparams(num_stages=2, num_microbatches=8, per_device_batch_size=8), "v5p-16", 4) + with self.assertRaisesRegex(app.UsageError, "divide one another"): + launch.check_slices(hparams, "v5p-16", 3) # 24 devices split in 4, but not by slice + with self.assertRaisesRegex(app.UsageError, "does not split into 4 stages"): + launch.check_slices(hparams, "v5p-unknown", 1) + + def test_microbatches_split_over_the_stage(self): + # v5p-16 at PP=4: 2 devices a stage; 8 rows in 8 microbatches is 1 row a microbatch, over 2 devices. + with self.assertRaisesRegex(app.UsageError, "must be a multiple of the 2 devices"): + launch.check_slices(hp.Hparams(num_stages=4, num_microbatches=8, per_device_batch_size=4), "v5p-16", 1) + + def test_workload_names(self): + launch.check_workload_name("mpmd-pp4") + launch.check_workload_name("a" * launch.MAX_PATHWAYS_NAME) + launch.check_workload_name("a") + # A leading digit passed, but xpk and JobSet's webhook want a DNS-1035 label, which starts with a letter. + for bad in ("a" * (launch.MAX_PATHWAYS_NAME + 1), "Upper", "under_score", "-dash", "dash-", "1mpmd", "4"): + with self.assertRaisesRegex(app.UsageError, "at most 22 characters", msg=bad): + launch.check_workload_name(bad) + + +class CommandTest(unittest.TestCase): + + def test_xpk_create_pathways(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "x.flags") + with open(path, "w", encoding="utf-8") as f: + f.write("# comment\n--xla_a=true\n--xla_b=1\n") + (argv,) = printed( + *REQUIRED, + *MODEL, + "--launcher=xpk", + f"--xla_flags_file={path}", + "--extra_xla_flags=xla_b=2", + "--launcher_args=--priority=low", + ) + self.assertEqual(argv[:3], ["xpk", "workload", "create-pathways"]) + for want in ( + "--cluster=my-cluster", + "--project=my-project", + "--zone=us-east5-b", + "--workload=mpmd-pp4", + "--tpu-type=v5p-16", + "--num-slices=1", + "--docker-image=example.com/maxtext:latest", + f"--server-image={launch.PATHWAYS_IMAGES}/server:{launch.DEFAULT_PATHWAYS_TAG}", + f"--proxy-server-image={launch.PATHWAYS_IMAGES}/proxy_server:{launch.DEFAULT_PATHWAYS_TAG}", + "--pathways-gcs-location=gs://bucket/pathways", + "--priority=low", + ): + self.assertIn(want, argv) + # The XLA flags reach the proxy server, which compiles, as well as the resource manager and the workers. + for component in ("proxy-server", "server", "worker"): + self.assertIn(f"--custom-pathways-{component}-args=--xla_a=true --xla_b=2", argv) + command = command_of(argv) + self.assertEqual(command[:4], ["python3", "-u", "-m", "maxtext.experimental.mpmd.partir.train"]) + self.assertIn("--num_stages=4", command) + + def test_gcluster_is_the_default(self): + """Cluster Toolkit, which MaxText uses in place of the deprecated XPK; the slice is derived from --device_type.""" + commands = printed(*REQUIRED, *MODEL, "--extra_xla_flags=xla_a=1") + self.assertEqual( + commands[:3], + [ + ["gcluster", "job", "config", "set", "project", "my-project"], + ["gcluster", "job", "config", "set", "cluster", "my-cluster"], + ["gcluster", "job", "config", "set", "location", "us-east5-b"], + ], + ) + submit = commands[3] + self.assertEqual(submit[:4], ["gcluster", "job", "submit", "--pathways"]) + for want in ( + "--name=mpmd-pp4", + "--image=example.com/maxtext:latest", + "--compute-type=ct5p-hightpu-4t", + "--topology=2x2x2", + "--num-slices=1", + "--pathways-gcs-location=gs://bucket/pathways", + f"--pathways-server-image={launch.PATHWAYS_IMAGES}/server:{launch.DEFAULT_PATHWAYS_TAG}", + f"--pathways-proxy-server-image={launch.PATHWAYS_IMAGES}/proxy_server:{launch.DEFAULT_PATHWAYS_TAG}", + "--pathways-proxy-args=--xla_a=1", + ): + self.assertIn(want, submit) + self.assertEqual(command_of(submit)[3], "maxtext.experimental.mpmd.partir.train") + + def test_gcluster_warns_that_it_reruns_a_finished_job(self): + """gcluster v1.108.0 and v1.109.0 restart a Pathways JobSet whose entry point ended (cluster-toolkit PR #6739).""" + with self.assertLogs("absl", level="WARNING") as logs: + printed(*REQUIRED, *MODEL) + (warning,) = [line for line in logs.output if "PR #6739" in line] + self.assertIn("gcluster v1.108.0 and v1.109.0", warning) + self.assertIn("--launcher=xpk", warning) + with self.assertNoLogs("absl", level="WARNING"): + printed(*REQUIRED, *MODEL, "--launcher=xpk") + + def test_gcluster_slices(self): + self.assertEqual(launch.gcluster_slice("v5p-16"), ("ct5p-hightpu-4t", "2x2x2")) + self.assertEqual(launch.gcluster_slice("v6e-16"), ("ct6e-standard-4t", "4x4")) + self.assertEqual(launch.gcluster_slice("tpu7x-128"), ("tpu7x-standard-4t", "4x4x4")) + self.assertEqual(launch.gcluster_slice("tpu7x-4x4x4"), ("tpu7x-standard-4t", "4x4x4")) + self.assertEqual(launch.gcluster_slice("v5litepod-8"), ("ct5lp-hightpu-4t", "2x4")) + self.assertEqual(launch.gcluster_slice("v6e-2x2"), ("ct6e-standard-4t", "2x2")) + for device_type, error in ( + ("v5p-12345", "MaxText knows no v5p-12345 slice"), + ("gpu-8", r"'gpu' is not one of the known TPU generations \(tpu7x, v6e, v5p, v5e, v5litepod, v4\)"), + # The compute types are 4-chip hosts: a 1-chip slice needs another (e.g. ct6e-standard-1t). + ("v6e-1", "a 1x1 slice has 1-chip hosts, and ct6e-standard-4t is a host of 4 chips"), + ("tpu7x-2", "a 1x1x1 slice has 1-chip hosts"), + ("v5litepod-1", "a 1x1 slice has 1-chip hosts"), + ("tpu7x-1x1x1", "a 1x1x1 slice has 1-chip hosts"), + ("tpu7x-4x4", r"a tpu7x topology has 3 dimensions \(AxBxC\), not '4x4'"), + ("v6e-4x4x4", r"a v6e topology has 2 dimensions \(AxB\), not '4x4x4'"), + # The right number of dimensions, one of them not a number of chips. + ("v5p-2x2x0", r"^a topology's dimensions are positive integers, not '0' \(in '2x2x0'\)$"), + ("tpu7x-4x4x", r"^a topology's dimensions are positive integers, not '' \(in '4x4x'\)$"), + ("v6e-2xa", r"^a topology's dimensions are positive integers, not 'a' \(in '2xa'\)$"), + ): + with self.subTest(device_type=device_type), self.assertRaisesRegex(ValueError, error): + launch.gcluster_slice(device_type) + + def test_gcluster_topologies(self): + """The slice's chip box, and the chips on each of its hosts: all of them for a slice smaller than a host.""" + self.assertEqual(launch.gcluster_topology("v5p-16"), ("2x2x2", 4)) + self.assertEqual(launch.gcluster_topology("tpu7x-4x4x4"), ("4x4x4", 4)) + self.assertEqual(launch.gcluster_topology("tpu7x-2"), ("1x1x1", 1)) + self.assertEqual(launch.gcluster_topology("v6e-2x2"), ("2x2", 4)) + self.assertEqual(launch.gcluster_topology("v6e-1x1"), ("1x1", 1)) + self.assertEqual(launch.gcluster_topology("v5litepod-8"), ("2x4", 4)) + for device_type, error in ( + ("v5p-12345", "MaxText knows no v5p-12345 slice"), + ("gpu-2x2", "'gpu' is not one of the known TPU generations"), + ("tpu7x-4x4", r"a tpu7x topology has 3 dimensions \(AxBxC\), not '4x4'"), + ("v5p-2x0x2", r"a topology's dimensions are positive integers, not '0' \(in '2x0x2'\)"), + ): + with self.subTest(device_type=device_type), self.assertRaisesRegex(ValueError, error): + launch.gcluster_topology(device_type) + + def test_gcluster_derives_only_what_no_flag_gives(self): + """An explicit compute type or topology is never blamed: an error names only the flags still needed.""" + # tpu7x-2 is one chip, so its 1-chip hosts fit no 4-chip compute type; 2 devices hold PP=2. + small = ["--pp=2", "--fsdp=1", "--num_microbatches=4", "--per_device_batch_size=4", "--model_name=deepseek3-tiny"] + + def slice_flags(*argv): + submit = printed(*REQUIRED, *small, *argv)[-1] + return [a for a in submit if a.startswith(("--compute-type=", "--topology="))] + + self.assertEqual( + slice_flags("--device_type=tpu7x-2", "--gcluster_compute_type=tpu7x-standard-1t"), + ["--compute-type=tpu7x-standard-1t", "--topology=1x1x1"], + ) + self.assertEqual( + slice_flags("--device_type=v5p-16", "--gcluster_topology=4x2x1"), + ["--compute-type=ct5p-hightpu-4t", "--topology=4x2x1"], + ) + hosts = r"--device_type=tpu7x-2: a 1x1x1 slice has 1-chip hosts, and tpu7x-standard-4t is a host of 4 chips" + unknown = r"--device_type=v5p-16384: MaxText knows no v5p-16384 slice \(maxtext.utils.accelerator_to_spec_map\)" + for argv, error in ( + # The slice is known: only the compute type is in question, with or without an explicit topology. + (["--device_type=tpu7x-2"], rf"^{hosts}; pass --gcluster_compute_type\.$"), + (["--device_type=tpu7x-2", "--gcluster_topology=1x1x1"], rf"^{hosts}; pass --gcluster_compute_type\.$"), + # No value is derived from a slice that is not known: the error names the flags not given. + (["--device_type=v5p-16384"], rf"^{unknown}; pass --gcluster_compute_type and --gcluster_topology\.$"), + ( + ["--device_type=v5p-16384", "--gcluster_compute_type=ct5p-hightpu-4t"], + rf"^{unknown}; pass --gcluster_topology\.$", + ), + (["--device_type=v5p-16384", "--gcluster_topology=16x16x32"], rf"^{unknown}; pass --gcluster_compute_type\.$"), + ): + with self.subTest(argv=argv), self.assertRaisesRegex(app.UsageError, error): + printed(*REQUIRED, *small, *argv) + + def test_gcluster_explicit_slice(self): + commands = printed( + *REQUIRED, *MODEL, "--launcher=gcluster", "--gcluster_compute_type=ct5p-hightpu-4t", "--gcluster_topology=2x2x2" + ) + self.assertEqual( + commands[:3], + [ + ["gcluster", "job", "config", "set", "project", "my-project"], + ["gcluster", "job", "config", "set", "cluster", "my-cluster"], + ["gcluster", "job", "config", "set", "location", "us-east5-b"], + ], + ) + submit = commands[3] + self.assertEqual(submit[:4], ["gcluster", "job", "submit", "--pathways"]) + for want in ("--name=mpmd-pp4", "--compute-type=ct5p-hightpu-4t", "--topology=2x2x2"): + self.assertIn(want, submit) + self.assertFalse([a for a in submit if a.startswith("--pathways-proxy-args")]) # no XLA flags given + self.assertEqual(command_of(submit)[3], "maxtext.experimental.mpmd.partir.train") + + def test_refuses_what_would_fail_on_the_cluster(self): + with self.assertRaisesRegex(app.UsageError, "Missing required flags: --cluster, --project"): + printed(*REQUIRED[2:], *MODEL) + with self.assertRaisesRegex(app.UsageError, "pass --gcluster_compute_type and --gcluster_topology"): + printed(*REQUIRED, *MODEL, "--device_type=v5p-16384") + with self.assertRaisesRegex(app.UsageError, "--device_type=tpu7x-4x4: a tpu7x topology has 3 dimensions"): + printed(*REQUIRED, *MODEL, "--device_type=tpu7x-4x4") + with self.assertRaisesRegex(app.UsageError, "gs://"): + printed(*REQUIRED, *MODEL, "--pathways_gcs_location=/tmp/x") + with self.assertRaisesRegex(app.UsageError, "gs:// --profile_dir"): + printed(*REQUIRED, *MODEL, "--enable_profile") + # The hyperparameters' refusals are usage errors, not tracebacks. + with self.assertRaisesRegex(app.UsageError, "decoder_block=gpt3"): + printed(*REQUIRED, "--pp=4", "--model_name=gpt3-52k") + with self.assertRaisesRegex(app.UsageError, "MaxText model config .*no-such-model.yml' is missing"): + printed(*REQUIRED, *MODEL, "--model_name=no-such-model") + # Once accepted, it failed only when the trainer traced its first step on the cluster. + with self.assertRaisesRegex(app.UsageError, "remat_policy=qkv_proj_offloaded is not one"): + printed(*REQUIRED, *MODEL, "--remat", "--remat_policy=qkv_proj_offloaded") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/local_pathways_test.py b/tests/unit/mpmd_test/local_pathways_test.py new file mode 100644 index 0000000000..ef2da01d7b --- /dev/null +++ b/tests/unit/mpmd_test/local_pathways_test.py @@ -0,0 +1,125 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for local_pathways.sh's arguments and XLA flags file, with docker stood in for (no container starts).""" + +import os +import shlex +import shutil +import subprocess +import tempfile +import unittest + +from maxtext.experimental.mpmd import partir + +SCRIPT = os.path.join(os.path.dirname(partir.__file__), "local_pathways.sh") +GCS = "--gcs_scratch_location=gs://bucket/pathways" +INSTANCE = "--instance_type=tpu7x:2x2x1" +UP = ("up", GCS, INSTANCE) +IMAGES = "us-docker.pkg.dev/cloud-tpu-v2-images/pathways" +FLAGS_FILE = "# a comment\n--xla_a=1\n\n --xla_b=true \n" +# up's first docker call asks for existing containers: under DOCKER=echo the answer is echo's own output, so up stops. +EXISTING = "containers exist already" +# A docker that records its calls, has no containers, and whose logs say the slice and the proxy are ready. +FAKE_DOCKER = """#!/usr/bin/env bash +printf '%q ' "$@" >> {calls}; echo >> {calls} +case $1 in + logs) echo '1/1 Pathways Slices Now Ready'; echo 'IFRT proxy server started with status OK' ;; + inspect) echo true ;; +esac +""" + + +@unittest.skipUnless(shutil.which("bash"), "needs bash") +class LocalPathwaysTest(unittest.TestCase): + + def setUp(self): + super().setUp() + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp) + + def write(self, name, text, mode=0o644): + path = os.path.join(self.tmp, name) + with open(path, "w", encoding="utf-8") as handle: + handle.write(text) + os.chmod(path, mode) + return path + + def run_script(self, *args, docker="echo", bin_dir=None): + env = dict(os.environ, DOCKER=docker) + if bin_dir: + env["PATH"] = bin_dir + os.pathsep + env["PATH"] + result = subprocess.run(["bash", SCRIPT, *args], env=env, capture_output=True, text=True, timeout=60, check=False) + return result.returncode, result.stdout + result.stderr + + def test_refusals_come_before_any_docker_call(self): + """Under DOCKER=echo any docker call would stop up as if containers existed: each refusal comes first.""" + good = self.write("good.flags", FLAGS_FILE) + cases = [ + ((), 2, "usage:"), + (("start",), 2, "usage:"), + ((*UP, "--bogus"), 2, "unknown argument: --bogus"), + (("up", INSTANCE), 2, "--gcs_scratch_location=gs://... is required"), + (("up", "--gcs_scratch_location=/tmp/pathways", INSTANCE), 2, "--gcs_scratch_location=gs://... is required"), + (("up", GCS), 2, "--instance_type is required"), + ((*UP, f"--xla_flags_file={self.tmp}/missing.flags"), 1, "cannot read --xla_flags_file="), + ] + for i, line in enumerate(("xla_b=2", "--xla_a=1 --xla_b=2", "--xla_a", "--=1")): + bad = self.write(f"bad{i}.flags", f"--xla_ok=1\n{line}\n") + cases.append(((*UP, f"--xla_flags_file={bad}"), 1, f"expected one --key=value a line, got '{line}'")) + for args, returncode, message in cases: + with self.subTest(args=args): + got, out = self.run_script(*args) + self.assertEqual(got, returncode, out) + self.assertIn(message, out) + self.assertNotIn(EXISTING, out) + # Accepted arguments reach docker, which echo answers as if containers existed. + for args in (UP, (*UP, "--tag=my-tag", f"--xla_flags_file={good}")): + with self.subTest(args=args): + returncode, out = self.run_script(*args) + self.assertEqual(returncode, 1, out) + self.assertIn(EXISTING, out) + + def test_the_flags_reach_the_resource_manager_worker_and_proxy(self): + """The flags file's flags end each server's arguments, after the scratch location and the instance type.""" + calls = os.path.join(self.tmp, "calls") + docker = self.write("docker", FAKE_DOCKER.format(calls=shlex.quote(calls)), 0o755) + os.mkdir(os.path.join(self.tmp, "bin")) + self.write("bin/sudo", "#!/bin/sh\nexit 1\n", 0o755) # sudo lsof /dev/vfio/*: nothing holds the TPU + good = self.write("good.flags", FLAGS_FILE) + for extra, flags in (((), []), ((f"--xla_flags_file={good}",), ["--xla_a=1", "--xla_b=true"])): + with self.subTest(flags=flags): + if os.path.exists(calls): + os.remove(calls) + returncode, out = self.run_script( + *UP, "--tag=my-tag", *extra, docker=docker, bin_dir=os.path.join(self.tmp, "bin") + ) + self.assertEqual(returncode, 0, out) + self.assertIn(f"Pathways up (tpu7x:2x2x1, my-tag, {len(flags)} XLA flags)", out) + with open(calls, encoding="utf-8") as handle: + runs = [argv for argv in map(shlex.split, handle) if argv[0] == "run"] + self.assertEqual( + [argv[argv.index("--name") + 1] for argv in runs], + [f"maxtext-pathways-{n}" for n in ("rm", "worker", "proxy")], + ) + for argv, image in zip(runs, ("server", "server", "proxy_server")): + server_args = argv[argv.index(f"{IMAGES}/{image}:my-tag") + 1 :] + self.assertIn(GCS, server_args) + self.assertEqual(server_args[len(server_args) - len(flags) :], flags) + self.assertEqual(len([a for a in server_args if a.startswith("--xla_")]), len(flags)) + self.assertIn(INSTANCE, runs[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/mesh_utils_test.py b/tests/unit/mpmd_test/mesh_utils_test.py new file mode 100644 index 0000000000..43f565ed4d --- /dev/null +++ b/tests/unit/mpmd_test/mesh_utils_test.py @@ -0,0 +1,161 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the MPMD pipeline's stage meshes, on CPU devices and fake TPU coordinates.""" + +# pylint: disable=protected-access + +import dataclasses +import unittest + +import jax +import numpy as np + +from maxtext.experimental.mpmd.partir import mesh_utils as mu + + +def cpu_devices(count): + """The first `count` CPU devices, or a skip when there are fewer.""" + devices = jax.devices("cpu") + if len(devices) < count: + raise unittest.SkipTest(f"needs {count} CPU devices (XLA_FLAGS=--xla_force_host_platform_device_count={count})") + return devices[:count] + + +@dataclasses.dataclass(frozen=True) +class FakeTpu: + id: int + coords: tuple[int, int, int] + core_on_chip: int = 0 + slice_index: int = 0 + + +def grid(x, y, z, slice_index=0): + """Fake chips of an x*y*z box, host by host (2x2 tiles), like jax.devices() lists them.""" + devs = [] + for hz in range(z): + for hy in range(0, y, 2): + for hx in range(0, x, 2): + for dy in range(min(2, y)): + for dx in range(min(2, x)): + devs.append(FakeTpu(100_000 * (slice_index + 1) + len(devs), (hx + dx, hy + dy, hz), slice_index=slice_index)) + return devs + + +class StageMeshTest(unittest.TestCase): + + def test_cpu_devices_split_contiguously(self): + devices = cpu_devices(4) + topo = mu.create_stage_meshes(devices, num_stages=2) + self.assertEqual(topo.devices_per_stage, 2) + self.assertEqual(topo.fsdp_size, 2) + self.assertEqual(list(topo.meshes), ["m0", "m1"]) + self.assertEqual(topo.meshes["m0"].axis_names, ("fsdp",)) + self.assertEqual([d.id for d in topo.meshes["m0"].devices.flat], [d.id for d in devices[:2]]) + flat = [d for m in topo.meshes.values() for d in m.devices.flat] + self.assertEqual(sorted(d.id for d in flat), sorted(d.id for d in devices)) + + def test_expert_axis(self): + devices = cpu_devices(4) + topo = mu.create_stage_meshes(devices, num_stages=1, expert_size=2) + self.assertEqual(topo.meshes["m0"].axis_names, ("fsdp", "expert")) + self.assertEqual(dict(topo.meshes["m0"].shape), {"fsdp": 2, "expert": 2}) + self.assertEqual(topo.data_parallel_size, 4) + with self.assertRaisesRegex(ValueError, "divisible by num_stages"): + mu.create_stage_meshes(devices, num_stages=3) + with self.assertRaisesRegex(ValueError, "exceeds"): + mu.create_stage_meshes(devices, num_stages=2, fsdp_size=2, expert_size=2) + + def test_4x4x4_stages_are_whole_host_subcubes(self): + """64 chips into 4 stages: each a 2x2x4 sub-cube (an XLA-supported 3D subslice).""" + stages = mu._partition_grid_into_stages(np.asarray(grid(4, 4, 4), dtype=object), 4) + self.assertEqual(len(stages), 4) + for stage in stages: + xs, ys, zs = zip(*(d.coords for d in stage)) + box = (max(xs) - min(xs) + 1, max(ys) - min(ys) + 1, max(zs) - min(zs) + 1) + self.assertEqual(box, (2, 2, 4)) + self.assertEqual(min(xs) % 2, 0) + self.assertEqual(min(ys) % 2, 0) + + def test_2x2x2_v5p16_two_stages_per_host(self): + """The v5p-16 run on 2026-10-15 (pathways demo): stages 0-1 on host z=0, 2-3 on z=1.""" + stages = mu._partition_grid_into_stages(np.asarray(grid(2, 2, 2), dtype=object), 4) + for index, stage in enumerate(stages): + self.assertEqual({d.coords[2] for d in stage}, {index // 2}) + + def test_consecutive_stages_are_neighbours(self): + """The stage blocks follow a snake: each stage's box touches the next one's (a 4x4 v6e-16 in four + 2x2 hosts, a 4x4x4 cube in eight 2x2x2 blocks, 2x2x2 in four 1x2x1 halves).""" + + def box(stage): + xs, ys, zs = zip(*(d.coords for d in stage)) + return (min(xs), max(xs)), (min(ys), max(ys)), (min(zs), max(zs)) + + def touching(a, b): # boxes share a face: adjacent (gap 1) along one axis, overlapping along the others + gaps = [max(lo2 - hi1, lo1 - hi2) for (lo1, hi1), (lo2, hi2) in zip(a, b)] + return gaps.count(1) == 1 and all(g <= 0 for g in gaps if g != 1) + + for shape, num_stages in (((4, 4, 1), 4), ((4, 4, 4), 8), ((2, 2, 2), 4), ((4, 4, 4), 4)): + stages = mu._partition_grid_into_stages(np.asarray(grid(*shape), dtype=object), num_stages) + boxes = [box(stage) for stage in stages] + for s in range(num_stages - 1): + self.assertTrue(touching(boxes[s], boxes[s + 1]), (shape, num_stages, s, boxes[s], boxes[s + 1])) + self.assertEqual( + mu._snake_order_blocks(2, 2, 2), + [(0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0), (1, 0, 1), (1, 1, 1), (0, 1, 1), (0, 0, 1)], + ) + + def test_stages_never_straddle_slices(self): + """Every slice's chips share coordinates: two v5p-16 slices into 4 stages put stages 0-1 on + slice 0 and 2-3 on slice 1, each a whole host as on one slice, instead of mixing both + slices into every stage.""" + devices = grid(2, 2, 2, slice_index=0) + grid(2, 2, 2, slice_index=1) + topo = mu.create_stage_meshes(devices, num_stages=4) + for index, mesh in enumerate(topo.meshes.values()): + self.assertEqual({d.slice_index for d in mesh.devices.flat}, {index // 2}) + self.assertEqual({d.coords[2] for d in mesh.devices.flat}, {index % 2}) + # More slices than stages: each stage holds whole slices. + devices = [d for i in range(4) for d in grid(2, 2, 2, slice_index=i)] + topo = mu.create_stage_meshes(devices, num_stages=2) + self.assertEqual([sorted({d.slice_index for d in m.devices.flat}) for m in topo.meshes.values()], [[0, 1], [2, 3]]) + with self.assertRaisesRegex(ValueError, "straddles"): + mu.create_stage_meshes([d for i in range(3) for d in grid(2, 2, 2, slice_index=i)], num_stages=4) + + def test_supported_subslices(self): + self.assertTrue(mu._is_supported_3d_subslice(2, 2, 4)) + self.assertTrue(mu._is_supported_3d_subslice(4, 4, 8)) + self.assertFalse(mu._is_supported_3d_subslice(1, 4, 4)) + + +class AssignmentTest(unittest.TestCase): + + def test_uniform_and_asymmetric(self): + a = mu.create_name_to_mesh_assignment(num_layers=8, num_stages=4) + self.assertEqual([a[mu.layer_name(i)] for i in range(8)], ["m0", "m0", "m1", "m1", "m2", "m2", "m3", "m3"]) + self.assertEqual((a["embed"], a["unembed"]), ("m0", "m3")) + self.assertEqual((a["pre_m2"], a["post_m2"]), ("m2", "m2")) + b = mu.create_name_to_mesh_assignment(num_layers=8, num_stages=2, stage_layer_counts=(3, 5)) + self.assertEqual([b[mu.layer_name(i)] for i in range(8)], ["m0"] * 3 + ["m1"] * 5) + + def test_circular(self): + a = mu.create_name_to_mesh_assignment(num_layers=8, num_stages=2, num_repeats=2) + self.assertEqual([a[mu.layer_name(i)] for i in range(8)], ["m0", "m0", "m1", "m1", "m0", "m0", "m1", "m1"]) + s = mu.create_name_to_stage_assignment(num_layers=8, num_stages=2, num_repeats=2) + self.assertEqual([s[mu.layer_name(i)] for i in range(8)], [0, 0, 1, 1, 2, 2, 3, 3]) + # pre/post computations get their own stage ids, so Shardy does not merge them into a call. + self.assertEqual(len({s["pre_m0"], s["post_m0"], s["embed"]}), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/models_test.py b/tests/unit/mpmd_test/models_test.py new file mode 100644 index 0000000000..a1e1082164 --- /dev/null +++ b/tests/unit/mpmd_test/models_test.py @@ -0,0 +1,506 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the MPMD pipeline's model (models.py) on CPU devices. + +These run the MPMD-only code paths (pre-gather, deferred expert-gradient reduce-scatter) without ``mpmd.jit``, so they +need neither Shardy MPMD nor Pathways. +""" + +import dataclasses +import gc +import re +import unittest +from unittest import mock + +from flax import nnx +from flax.linen import partitioning as nn_partitioning +import jax +import jax.numpy as jnp +from jax.sharding import Mesh +from jax.sharding import NamedSharding +from jax.sharding import PartitionSpec as P +import numpy as np + +from maxtext.common.common_types import DecoderBlockType +from maxtext.common.common_types import MODEL_MODE_TRAIN +from maxtext.utils import model_creation_utils + +from maxtext.experimental.mpmd.partir import config as config_lib +from maxtext.experimental.mpmd.partir import hparams as hp +from maxtext.experimental.mpmd.partir import mesh_utils +from maxtext.experimental.mpmd.partir import models +from maxtext.experimental.mpmd.partir import train_step as ts + + +def IDENTITY(name): # pylint: disable=invalid-name + """A stage wrapper that leaves the stage as it is: the MPMD-only code paths, without mpmd.jit.""" + del name + return lambda fn: fn + + +def cpu_devices(count): + """The first `count` CPU devices, or a skip when there are fewer.""" + devices = jax.devices("cpu") + if len(devices) < count: + raise unittest.SkipTest(f"needs {count} CPU devices (XLA_FLAGS=--xla_force_host_platform_device_count={count})") + return devices[:count] + + +def rel_l2(mine, theirs): + mine, theirs = np.asarray(mine, np.float64), np.asarray(theirs, np.float64) + return np.linalg.norm(mine - theirs) / max(np.linalg.norm(theirs), 1e-30) + + +def batch_of(rows, seq_len, vocab_size, seed=0): + """A synthetic batch: random tokens, targets shifted by one, no padding.""" + tokens = np.random.default_rng(seed).integers(0, vocab_size, size=(rows, seq_len + 1), dtype=np.int32) + positions = np.tile(np.arange(seq_len + 1, dtype=np.int32), (rows, 1)) + segmentation = np.ones((rows, seq_len), dtype=np.int32) + return { + "inputs": tokens[:, :-1], + "inputs_position": positions[:, :-1], + "inputs_segmentation": segmentation, + "targets": tokens[:, 1:], + "targets_position": positions[:, 1:], + "targets_segmentation": segmentation, + } + + +def build(hparams, devices, unit_shard_fn=None): + """The MaxText config, stage topology, graphdef and parameters `runner.build` would make, without Shardy.""" + cfg = config_lib.build_maxtext_config(hparams) + topology = mesh_utils.create_stage_meshes(devices, hparams.num_stages, hparams.fsdp, hparams.expert) + graphdef, params = models.PipelinedTransformer.init_split( + config=cfg, + mesh=topology.meshes["m0"], + rngs=nnx.Rngs(hparams.seed), + unit_shard_fn=unit_shard_fn, + remat_policy=hparams.mpmd_remat_policy, + stage_layer_counts=hparams.stage_layer_counts, + ) + return cfg, topology, graphdef, params + + +def deepseek3_tiny(**kw): + return hp.Hparams( + model_name="deepseek3-tiny", + max_target_length=16, + emb_dim=128, + mlp_dim=256, + vocab_size=512, + first_num_dense_layers=1, + maxtext_overrides=("dtype=float32",), + **kw, + ) + + +# A model of each supported decoder block (hparams.SUPPORTED_DECODER_BLOCKS). +MODELS_BY_BLOCK = { + "simple_mlp": "simple", + "deepseek": "deepseek3-tiny", + "llama2": "llama3.1-8b", + "mistral": "mistral-7b", + "mixtral": "mixtral-8x7b", + "qwen3": "qwen3-8b", + "qwen3_moe": "qwen3-30b-a3b", +} + + +class SupportedBlocksTest(unittest.TestCase): + """Every supported decoder block builds through MaxText's private NNXDecoder helpers and runs forward.""" + + def test_every_supported_block_builds_and_runs(self): + devices = cpu_devices(1) + small = {"num_layers": 2, "num_stages": 1, "max_target_length": 8, "emb_dim": 64, "mlp_dim": 128, "vocab_size": 128} + self.assertEqual(set(MODELS_BY_BLOCK), set(hp.SUPPORTED_DECODER_BLOCKS)) + for block, model_name in MODELS_BY_BLOCK.items(): + with self.subTest(block=block): + h = hp.Hparams(model_name=model_name, **small) + cfg, _, graphdef, params = build(h, devices) + self.assertEqual(cfg.decoder_block.value, block) + self.assertEqual(graphdef.num_layers, 2) + batch = batch_of(2, 8, 128) + logits = jax.jit(lambda p, b, g=graphdef: models.forward(g, p, b, wrap=models.UNWRAPPED))(params, batch) + self.assertEqual(logits.shape, (2, 8, 128)) + self.assertTrue(bool(jnp.isfinite(logits).all())) + + def test_refuses_an_unsupported_block_at_build_time(self): + cfg = config_lib.build_maxtext_config(hp.Hparams(model_name="simple", num_layers=2, num_stages=1)) + with self.assertRaisesRegex(ValueError, "Unsupported decoder_block"): + models.PipelinedTransformer( + cfg.replace(decoder_block=DecoderBlockType.GPT3), + Mesh(np.asarray(cpu_devices(1)), ("fsdp",)), + rngs=nnx.Rngs(0), + remat_policy="none", + stage_layer_counts=(), + ) + + +class MaxTextTransformerTest(unittest.TestCase): + """The model computes MaxText's: from the parameters of MaxText's own (unscanned) NNX Transformer, the same logits. + + Parity compares MPMD against this same model unpipelined, so it cannot see the model drift from MaxText's. The + output head once had no final norm (llama3.1-8b's first loss 24.8, MaxText's 12.3). simple_mlp is left out: MaxText's + own unscanned NNX decoder returns logits of shape [vocab] for it. + """ + + SMALL = {"num_layers": 2, "num_stages": 1, "max_target_length": 8, "emb_dim": 64, "mlp_dim": 128, "vocab_size": 128} + + def assert_logits_match(self, hparams): + """Builds both models, copies MaxText's parameters into the per-unit dict, and compares float32 logits.""" + devices = cpu_devices(1) + cfg, _, graphdef, params = build(hparams, devices) + with nn_partitioning.axis_rules(cfg.logical_axis_rules): + reference = model_creation_utils.from_config(cfg, devices=devices, rngs=nnx.Rngs(1)) + reference_def, reference_state = nnx.split(reference) + leaves = { + jax.tree_util.keystr(path): leaf + for path, leaf in jax.tree_util.tree_flatten_with_path(nnx.state(reference, nnx.Param))[0] + } + decoder = nnx.state(reference, nnx.Param)["decoder"] + + def index(prefix): + return [key for _, key in sorted((int(k[len(prefix) :]), k) for k in decoder if re.fullmatch(prefix + r"\d+", k))] + + # MaxText's decoder layers from input to output (DeepSeek: its dense layers, then its MoE layers). + layer_keys = index("dense_layers_") + index("moe_layers_") + index("layers_") + self.assertEqual(len(layer_keys), graphdef.num_layers) + + def maxtext_path(path): + unit, rest = re.fullmatch(r"\['(\w+)'\](.*)", path).groups() + if unit == mesh_utils.EMBED_NAME: + return "['token_embedder']" + rest + if unit == mesh_utils.UNEMBED_NAME: # decoder_norm and logits_dense + return "['decoder']" + rest + return f"['decoder']['{layer_keys[int(unit[len('layer'):])]}']" + rest + + flat, treedef = jax.tree_util.tree_flatten_with_path(params) + paths = [maxtext_path(jax.tree_util.keystr(path)) for path, _ in flat] + self.assertEqual(sorted(paths), sorted(leaves)) # every parameter of MaxText's model, each once + for (_, leaf), path in zip(flat, paths): + self.assertEqual(leaf.shape, leaves[path].shape, path) + params = jax.tree_util.tree_unflatten(treedef, [leaves[path] for path in paths]) + + batch = batch_of(2, hparams.max_target_length, hparams.vocab_size) + mine = jax.jit(lambda p, b: models.forward(graphdef, p, b, wrap=models.UNWRAPPED))(params, batch) + + def run_reference(state, b): + logits = nnx.merge(reference_def, state)( + b["inputs"], + b["inputs_position"], + decoder_segment_ids=b["inputs_segmentation"], + enable_dropout=False, + model_mode=MODEL_MODE_TRAIN, + ) + return logits[0] if isinstance(logits, tuple) else logits + + with nn_partitioning.axis_rules(cfg.logical_axis_rules): + theirs = jax.jit(run_reference)(reference_state, batch) + self.assertEqual(mine.shape, theirs.shape) + self.assertLess(rel_l2(mine, theirs), 1e-5) + + def test_same_logits_as_maxtexts_transformer(self): + float32 = ("dtype=float32", "weight_dtype=float32", "matmul_precision=highest") + for block, model_name in MODELS_BY_BLOCK.items(): + if block == "simple_mlp": + continue + with self.subTest(block=block): + dense = {"first_num_dense_layers": 1} if block == "deepseek" else {} + self.assert_logits_match(hp.Hparams(model_name=model_name, maxtext_overrides=float32, **dense, **self.SMALL)) + with self.subTest(block="deepseek with hyper-connections"): + self.assert_logits_match( + hp.Hparams( + model_name="deepseek3-tiny", + first_num_dense_layers=1, + maxtext_overrides=(*float32, "mhc_expansion_rate=4"), + **self.SMALL, + ) + ) + + +class ModelSettingsTest(unittest.TestCase): + """The MPMD-only settings travel with the model, not as extra keys of MaxText's config.""" + + def test_graphdef_carries_the_remat_policy_and_stage_layer_counts(self): + h = hp.Hparams( + model_name="simple", + num_layers=4, + num_stages=2, + emb_dim=64, + mlp_dim=128, + vocab_size=128, + max_target_length=8, + remat=True, + remat_policy="minimal", + stage_layer_counts=(1, 3), + ) + cfg, _, graphdef, params = build(h, cpu_devices(2)) + self.assertEqual((graphdef.remat_policy, graphdef.stage_layer_counts), ("minimal", (1, 3))) + self.assertEqual( + models._unit_stages(graphdef, params), # pylint: disable=protected-access + [("embed", 0), ("layer0", 0), ("layer1", 1), ("layer2", 1), ("layer3", 1), ("unembed", 1)], + ) + # Required: a caller that forgot them would silently lose remat or uneven stages. + with self.assertRaisesRegex(TypeError, "missing 2 required keyword-only arguments: 'remat_policy' and"): + models.PipelinedTransformer.init_split(cfg, graphdef.mesh, rngs=nnx.Rngs(0)) # pylint: disable=missing-kwoa + fields = {f.name: getattr(graphdef, f.name) for f in dataclasses.fields(graphdef) if f.name != "remat_policy"} + with self.assertRaisesRegex(TypeError, "missing 1 required positional argument: 'remat_policy'"): + models.PipelineGraphDef(**fields) + # A copy of MaxText's config (replace() rebuilds it from its typed fields) still describes the same model. + self.assertEqual(cfg.replace(learning_rate=0.5).remat_policy, cfg.remat_policy) + + +def checkpoint_policies(jaxpr): + """The policy of every jax.checkpoint in `jaxpr` and the jaxprs it calls, in order (None: save nothing).""" + found = [] + for eqn in jaxpr.eqns: + if eqn.primitive.name in ("checkpoint", "remat2"): + found.append(eqn.params["policy"]) + for value in eqn.params.values(): + inner = getattr(value, "jaxpr", value) + if hasattr(inner, "eqns"): + found += checkpoint_policies(inner) + return found + + +class RematPolicyTest(unittest.TestCase): + """Each layer is checkpointed with the policy MaxText's own resolver (NNXDecoder.get_remat_policy) gives the name.""" + + def test_maxtexts_resolver_takes_every_policy(self): + """hparams.REMAT_POLICIES is a literal: each must be a name MaxText's resolver (and so its trainer) accepts.""" + cfg = config_lib.build_maxtext_config(hp.Hparams(model_name="simple", num_layers=2, num_stages=1)) + for policy in hp.REMAT_POLICIES: + enabled, jax_policy = models._resolve_remat_policy(cfg, policy) # pylint: disable=protected-access + self.assertEqual((enabled, jax_policy is None), (True, policy == "full"), policy) + self.assertEqual(models._resolve_remat_policy(cfg, "none"), (False, None)) # pylint: disable=protected-access + + def test_every_layer_is_checkpointed_with_it(self): + devices = cpu_devices(1) + small = {"num_layers": 3, "num_stages": 1, "max_target_length": 8, "emb_dim": 64, "mlp_dim": 128, "vocab_size": 128} + for remat, policy in ((False, "full"), (True, "full"), (True, "save_dot_except_mlp")): + _, _, graphdef, params = build(hp.Hparams(model_name="simple", remat=remat, remat_policy=policy, **small), devices) + jaxpr = jax.make_jaxpr(lambda p, b, g=graphdef: models.forward(g, p, b, wrap=models.UNWRAPPED))( + params, batch_of(2, 8, 128) + ) + found = checkpoint_policies(jaxpr.jaxpr) + if not remat: + self.assertEqual(found, []) + continue + # The embedding, then each of the 3 layers with the policy. + self.assertEqual([p is None for p in found], [True] + [policy == "full"] * 3, policy) + + +class HyperConnectionsTest(unittest.TestCase): + """DeepSeek's mHC streams, expanded after the embedding and summed before the output head as MaxText's decoder does.""" + + SMALL = {"num_layers": 2, "num_stages": 1, "max_target_length": 8, "emb_dim": 64, "mlp_dim": 128, "vocab_size": 128} + + def test_deepseek_builds_and_runs_with_hyper_connections(self): + devices = cpu_devices(1) + plain = hp.Hparams(model_name="deepseek3-tiny", **self.SMALL) + counts = {} + for name, hparams in ( + ("plain", plain), + ("mhc", dataclasses.replace(plain, maxtext_overrides="mhc_expansion_rate=4")), + ): + cfg, _, graphdef, params = build(hparams, devices) + counts[name] = sum(leaf.size for leaf in jax.tree.leaves(params)) + logits = jax.jit(lambda p, b, g=graphdef: models.forward(g, p, b, wrap=models.UNWRAPPED))( + params, batch_of(2, 8, 128) + ) + self.assertEqual(logits.shape, (2, 8, 128)) + self.assertTrue(bool(jnp.isfinite(logits).all()), name) + self.assertEqual(cfg.mhc_expansion_rate, 4) + self.assertGreater(counts["mhc"], counts["plain"]) # each layer's attention and MLP hyper-connections + + def test_refused_for_layers_without_streams(self): + hparams = hp.Hparams(model_name="simple", maxtext_overrides="mhc_expansion_rate=4", **self.SMALL) + with self.assertRaisesRegex(ValueError, "does not build mhc_expansion_rate=4"): + config_lib.build_maxtext_config(hparams) + + +class SuppressFsdpPsumTest(unittest.TestCase): + """The private JAX function the deferred expert-gradient reduce-scatter patches.""" + + def test_jax_still_has_it(self): + # A rename in jax would turn the deferral off (correct, but one reduce-scatter per microbatch). + self.assertTrue(models.can_defer_moe_reduce_scatter()) + + def test_3d_inputs_keep_their_partial_gradients(self): + """Without the patch the transpose of a check_vma=False shard_map psums a 3D input's gradient over fsdp.""" + mesh = Mesh(np.asarray(cpu_devices(2)), ("fsdp",)) + weight = jnp.ones((2, 3, 4), jnp.float32) + x = jax.device_put(jnp.arange(2 * 3 * 4, dtype=jnp.float32).reshape(2, 3, 4) + 1, NamedSharding(mesh, P("fsdp"))) + body = jax.shard_map( + lambda w, v: jnp.sum(w * v, keepdims=True), + mesh=mesh, + in_specs=(P(None, None, None), P("fsdp")), + out_specs=P("fsdp"), + check_vma=False, + ) + grad_fn = jax.jit(jax.grad(lambda w, v: jnp.sum(body(w, v)), argnums=0)) + halves = np.asarray(x).reshape(2, 1, 3, 4) + summed = grad_fn(weight, x) + for shard in summed.addressable_shards: + np.testing.assert_allclose(np.asarray(shard.data), np.broadcast_to(halves.sum(axis=0), (2, 3, 4))) + with models.suppress_fsdp_psum_of_3d_inputs(): + jax.clear_caches() + partial = jax.jit(jax.grad(lambda w, v: jnp.sum(body(w, v)), argnums=0))(weight, x) + jax.clear_caches() + shards = sorted(partial.addressable_shards, key=lambda shard: mesh.devices.tolist().index(shard.device)) + for index, shard in enumerate(shards): + np.testing.assert_allclose(np.asarray(shard.data), np.broadcast_to(halves[index], (2, 3, 4))) + + +class DeferredExpertGradTest(unittest.TestCase): + """MoE expert gradients under FSDP must match the unwrapped step whatever pre-gathering covers.""" + + def check_expert_grads(self, h, budgets): + """Every MoE unit's expert gradients against the unwrapped step's, at each of budgets(unit bytes).""" + _, _, graphdef, params = build(h, cpu_devices(h.num_stages * h.fsdp)) + # Every stage's units on the one mesh a plain jit runs on. + params = models.shard_tree_on_fsdp(graphdef.mesh, params, graphdef.fsdp_size, device_put=True) + rows = int(h.per_device_batch_size * h.fsdp) + batch = jax.device_put(batch_of(rows, h.max_target_length, 512), NamedSharding(graphdef.mesh, P("fsdp"))) + + def step(params, batch): + preg = models.pregather_params(graphdef, params, microbatch_rows=batch["inputs"].shape[0], wrap=IDENTITY) + with models.defer_fsdp_shard_map_psum(graphdef, preg, params): + carry = models.build_grad_carry(graphdef, params, preg) + grads = jax.grad( + lambda p: ts.compute_loss(graphdef, p, batch, vocab_size=512, wrap=IDENTITY, pregathered_params=preg) + )(carry) + return models.reduce_scatter_deferred_grads(graphdef, params, preg, grads, num_microbatches=1, wrap=IDENTITY) + + reference = jax.jit(jax.grad(lambda p, b: ts.compute_loss(graphdef, p, b, vocab_size=512, wrap=models.UNWRAPPED)))( + params, batch + ) + moe_units = [name for name in params if "DeepSeekMoeBlock_0" in params[name]] + self.assertTrue(moe_units) # a renamed MoE block must not pass vacuously + unit_bytes = { + name: models._unit_pregather_bytes( # pylint: disable=protected-access + graphdef.mesh, params[name], graphdef.fsdp_size, graphdef.config + ) + for name in params + } + saved = models._MAX_UNIT_PREGATHER_BYTES # pylint: disable=protected-access + self.addCleanup(setattr, models, "_MAX_UNIT_PREGATHER_BYTES", saved) + for budget in budgets(unit_bytes): + models._MAX_UNIT_PREGATHER_BYTES = budget # pylint: disable=protected-access + # The budget is read while tracing, and jit(step) would replay the first budget's trace. + grads = jax.jit(lambda p, b: step(p, b))(params, batch) # pylint: disable=unnecessary-lambda + for unit in moe_units: + mine, theirs = (tree[unit]["DeepSeekMoeBlock_0"]["MoeBlock_0"] for tree in (grads, reference)) + for name in ("wi_0", "wi_1", "wo"): + self.assertLess(rel_l2(mine[name].get_value(), theirs[name].get_value()), 1e-4, (budget, unit, name)) + + def test_expert_grads_whatever_is_pregathered(self): + # Every unit; only embed and unembed (the MoE layer over budget: the case that dropped the FSDP + # reduction of the expert gradients); nothing. + self.check_expert_grads( + deepseek3_tiny(num_layers=2, num_stages=1, fsdp=4, num_microbatches=1, per_device_batch_size=1.0), + lambda b: (1 << 30, b["embed"] + b["unembed"], 1), + ) + + def test_one_moe_unit_pregathered_and_another_not(self): + """Two stages: every unit, then a budget only stage 0 (embed, layer0, MoE layer1) fits, so that stage 1 (MoE + layer2 and layer3, unembed) is not gathered. Gathering layer1's experts deferred the psum of every expert weight, + so layer2's and layer3's were never reduced.""" + self.check_expert_grads( + deepseek3_tiny( + num_layers=4, num_stages=2, fsdp=2, num_microbatches=1, per_device_batch_size=1.0, stage_layer_counts=(2, 2) + ), + lambda b: (1 << 30, b["embed"] + b["layer0"] + b["layer1"]), + ) + + def test_expert_grads_without_the_private_jax_function(self): + """If jax renames the function the deferral patches, every expert gradient is reduced in its microbatch.""" + with mock.patch.object(models, "can_defer_moe_reduce_scatter", lambda: False): + self.check_expert_grads( + deepseek3_tiny(num_layers=2, num_stages=1, fsdp=4, num_microbatches=1, per_device_batch_size=1.0), + lambda b: (1 << 30,), + ) + + def test_microbatch_the_stage_cannot_split(self): + """2-row microbatches on 4 devices: MaxText's MoE runs all of a microbatch on every device, and the deferred + reduce-scatter added up 4 copies of the expert gradients. make_train_step's MPMD branch against its SPMD branch, + on the step-1 gradients in AdamW's first moment.""" + h = deepseek3_tiny(num_layers=2, num_stages=1, fsdp=4, num_microbatches=4, per_device_batch_size=2.0) + _, _, graphdef, params = build(h, cpu_devices(4)) + params = models.shard_tree_on_fsdp(graphdef.mesh, params, graphdef.fsdp_size, device_put=True) + state = ts.create_train_state(params, h.learning_rate) + batch = jax.device_put(batch_of(8, h.max_target_length, 512), NamedSharding(graphdef.mesh, P("fsdp"))) + with ( + mock.patch.object(models, "NAMED_COMPUTATION", IDENTITY), + mock.patch.object(ts, "microbatch_call", lambda fn, call_counter: fn), + ): + mpmd, spmd = ( + jax.jit(ts.make_train_step(graphdef, vocab_size=512, num_microbatches=4, mode=mode))(state, batch)[0] + .opt_state[0] + .mu + for mode in (ts.ExecutionMode.MPMD, ts.ExecutionMode.SPMD) + ) + theirs = dict(jax.tree_util.tree_flatten_with_path(spmd)[0]) + for path, mine in jax.tree_util.tree_flatten_with_path(mpmd)[0]: + self.assertLess(rel_l2(mine, theirs[path]), 1e-4, jax.tree_util.keystr(path)) + + # Still deferred for microbatches of 4 rows. + def defers(rows): + pregathered = jax.eval_shape( + lambda p: models.pregather_params(graphdef, p, microbatch_rows=rows, wrap=IDENTITY), params + ) + return models._defers_moe_reduce_scatter(graphdef, params, pregathered) # pylint: disable=protected-access + + self.assertEqual((defers(2), defers(4)), (False, True)) + + +class InitSplitTest(unittest.TestCase): + + def test_no_unsharded_weights_left_on_device_0(self): + """MaxText's Attention outlives the split (its query_init closure is in the GraphDef): each layer used to leave + its unsharded float32 q/k/v/o kernels on device 0, 5 GiB for llama3.1-8b.""" + h = hp.Hparams( + model_name="llama3.1-8b", + num_layers=2, + num_stages=2, + fsdp=2, + num_microbatches=2, + per_device_batch_size=1.0, + max_target_length=16, + emb_dim=128, + mlp_dim=256, + vocab_size=512, + ) + devices = cpu_devices(4) + topology = mesh_utils.create_stage_meshes(devices, h.num_stages, h.fsdp) + name_to_mesh = mesh_utils.create_name_to_mesh_assignment(num_layers=h.num_layers, num_stages=h.num_stages) + + def shard_unit(name, unit_params): # as runner.build places each unit on its stage's mesh + return models.shard_tree_on_fsdp(topology.meshes[name_to_mesh[name]], unit_params, h.fsdp, device_put=True) + + before = {id(a) for a in jax.live_arrays()} + _, _, _, params = build(h, devices, unit_shard_fn=shard_unit) + gc.collect() + held = {id(a) for a in jax.tree_util.tree_leaves(params)} + left = [ + (a.shape, str(a.dtype)) + for a in jax.live_arrays() + if id(a) not in before | held and devices[0] in a.devices() and a.nbytes >= 1024 + ] + self.assertEqual(left, []) # RNG keys and scalars stay; no weights + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/parity_test.py b/tests/unit/mpmd_test/parity_test.py new file mode 100644 index 0000000000..8f208bc724 --- /dev/null +++ b/tests/unit/mpmd_test/parity_test.py @@ -0,0 +1,313 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the MPMD-vs-SPMD parity check's comparison and gating (no MPMD run, no Shardy).""" + +# pylint: disable=protected-access + +import dataclasses +import math +import types +import unittest +from unittest import mock + +import jax +import numpy as np +import optax + +from maxtext.common.common_types import DecoderBlockType +from maxtext.experimental.mpmd.partir import hparams as hp +from maxtext.experimental.mpmd.partir import parity +from maxtext.experimental.mpmd.partir import train_step + +TOLERANCES = (1e-4, 1e-2, 1e-2) # loss, param, grad: parity's flag defaults + + +def tree_diff(errors, norm_floor=1e-6): + """A TreeDiff over tensors 'router' and 'dense' that differ by the given relative amounts.""" + reference = {"router": np.ones((4, 4)), "dense": np.arange(1.0, 17.0).reshape(4, 4)} + run = {name: value * (1 + errors.get(name, 0.0)) for name, value in reference.items()} + return parity._compare_params(run, reference, norm_floor=norm_floor) + + +def comparison(losses, reference, grads=None, params=None): + return parity.Comparison( + losses=tuple(losses), + reference_losses=tuple(reference), + grads=tree_diff(grads or {}), + params=tree_diff(params or {}, norm_floor=1.0), + ) + + +def result(mpmd, floor=None): + return parity.ParityResult(mpmd=mpmd, floor=floor, floor_microbatches=4 if floor else 0, num_params=2) + + +class GateTest(unittest.TestCase): + + def test_floor_microbatches(self): + self.assertEqual([parity.noise_floor_microbatches(n, -1) for n in (1, 2, 4, 5, 8, 9)], [0, 1, 2, 1, 4, 3]) + self.assertEqual(parity.noise_floor_microbatches(8, 0), 0) + self.assertEqual(parity.noise_floor_microbatches(8, 2), 2) + + def test_fixed_tolerances_without_a_floor(self): + self.assertTrue( + result(comparison([2.0, 1.0], [2.0, 1.00005], {"dense": 1e-3}, {"dense": 1e-3})).passed(*TOLERANCES, 4.0) + ) + bad = result(comparison([2.0, 1.0], [2.0, 1.001], {"dense": 1e-3}, {"dense": 1e-3})) + self.assertFalse(bad.passed(*TOLERANCES, 4.0)) + self.assertIn("bound 1.000e-04 = the tolerance", bad.report(*TOLERANCES, 4.0)) + + def test_floor_widens_each_bound_and_only_its_own(self): + """MoE on TPU: MPMD as far from the reference as the floor run is passes on the floor.""" + floor = comparison( + [12.36, 10.985], [12.36, 10.99], {"router": 0.035, "dense": 0.005}, {"router": 0.015, "dense": 0.001} + ) + mpmd = comparison([12.36, 10.98], [12.36, 10.99], {"router": 0.04, "dense": 0.006}, {"router": 0.017, "dense": 0.002}) + self.assertTrue(result(mpmd, floor).passed(*TOLERANCES, 4.0)) + self.assertFalse(result(mpmd).passed(*TOLERANCES, 4.0)) + self.assertIn("4 x floor", result(mpmd, floor).report(*TOLERANCES, 4.0)) + + def test_grad_gate_on_its_own(self): + """Loss and parameters sit at their floor; only the gradients exceed theirs at factor 1.""" + floor = comparison([12.36, 10.985], [12.36, 10.99], {"router": 0.035}, {"router": 0.015}) + mpmd = comparison([12.36, 10.985], [12.36, 10.99], {"router": 0.04}, {"router": 0.015}) + loss, grads, params = result(mpmd, floor).gates(*TOLERANCES, 1.0) + self.assertEqual((loss.passed, grads.passed, params.passed), (True, False, True)) + self.assertEqual(grads.where, "['router']") + # Parameter differences far above the parameter floor fail even when the gradient floor is wide. + lopsided = comparison([12.36, 10.985], [12.36, 10.99], {"router": 0.04}, {"router": 0.05}) + self.assertFalse(result(lopsided, floor).passed(*TOLERANCES, 3.0)) + + def test_each_tensor_against_its_own_floor(self): + """A noisy router floor (3.5%) must not license a 12% error on another tensor (floor 0.5%).""" + floor = comparison([1.0], [1.0], {"router": 0.035, "dense": 0.005}) + mpmd = comparison([1.0], [1.0], {"router": 0.03, "dense": 0.12}) + _, grads, _ = result(mpmd, floor).gates(*TOLERANCES, 4.0) + self.assertFalse(grads.passed) + self.assertEqual((grads.where, round(grads.bound, 6)), ("['dense']", 0.02)) + + def test_step1_loss_against_the_floor_up_to_step1(self): + """A chaotic late step of the floor (2e-4) must not loosen step 1 (floor 1e-6).""" + floor = comparison([1.000001, 1.00001, 1.0002], [1.0, 1.0, 1.0]) + mpmd = parity.Comparison( + losses=(1.0005, 1.0, 1.0), reference_losses=(1.0, 1.0, 1.0), grads=floor.grads, params=floor.params + ) + loss, _, _ = result(mpmd, floor).gates(*TOLERANCES, 4.0) + self.assertFalse(loss.passed) + self.assertEqual(loss.where, "step 1") + late = parity.Comparison( + losses=(1.0, 1.0, 1.0005), reference_losses=(1.0, 1.0, 1.0), grads=floor.grads, params=floor.params + ) + self.assertTrue(result(late, floor).passed(*TOLERANCES, 4.0)) # 5e-4 <= 4 x 2e-4 + + def test_running_maximum_of_the_floor(self): + """Step 2 is bounded by the floor's largest difference up to step 2, not by its own smaller one.""" + floor = comparison([1.0003, 1.00001], [1.0, 1.0]) # floor 3e-4 at step 1, 1e-5 at step 2 + mpmd = comparison([1.0, 1.001], [1.0, 1.0]) # 1e-3 at step 2 <= 4 x 3e-4 + loss, _, _ = result(mpmd, floor).gates(*TOLERANCES, 4.0) + self.assertTrue(loss.passed) + self.assertAlmostEqual(loss.floor, 3e-4, places=9) + + def test_losses_below_1_compared_absolutely(self): + """A 1.3e-5 difference at a memorized loss of 0.031 once read 4.3e-4 and failed (deepseek2-16b cut to 2 layers).""" + reference = [10.868768692, 2.304498196, 0.030810289] + floor = comparison([10.868770600, 2.304684, 0.030811244], reference) + mpmd = comparison([10.868772507, 2.304545879, 0.030823506], reference) + self.assertAlmostEqual(mpmd.loss_diffs[2], 1.3217e-05, places=8) + self.assertTrue(result(mpmd, floor).passed(*TOLERANCES, 4.0)) + report = result(mpmd, floor).report(*TOLERANCES, 4.0) # its columns once read 'rel diff' + self.assertIn("|MPMD - SPMD| / max(|SPMD|, 1)", report) + self.assertNotIn("rel diff", report) + self.assertAlmostEqual(parity.relative_difference(10.001, 10.0), 1e-4, places=12) # relative above 1 + self.assertFalse(result(comparison([2.0, 0.5], [2.0, 0.4998])).passed(*TOLERANCES, 4.0)) # 2e-4 + + def test_non_finite_values_fail_and_a_non_finite_floor_is_ignored(self): + good = comparison([2.0, 1.0], [2.0, 1.0]) + for mpmd in ( + comparison([2.0, math.nan], [2.0, 1.0]), # MPMD loss NaN + comparison([2.0, 1.0], [2.0, math.inf]), # reference loss inf + comparison([2.0, 1.0], [2.0, 1.0], {"dense": math.nan}), # NaN gradients + comparison([2.0, 1.0], [2.0, 1.0], params={"router": math.inf}), + ): + self.assertFalse(result(mpmd, good).passed(*TOLERANCES, 4.0)) + self.assertFalse(result(mpmd).passed(*TOLERANCES, 4.0)) + diverged_floor = comparison([2.0, math.inf], [2.0, 1.0], {"dense": math.nan}) + five_percent = comparison([2.0, 1.05], [2.0, 1.0], {"dense": 0.5}, {"dense": 0.5}) + self.assertIsNone(result(five_percent, diverged_floor).usable_floor) + self.assertFalse(result(five_percent, diverged_floor).passed(*TOLERANCES, 4.0)) + self.assertIn("ignored", result(five_percent, diverged_floor).report(*TOLERANCES, 4.0)) + self.assertEqual(tree_diff({"dense": math.nan}).rel_l2, math.inf) + + def test_assemble_result_from_the_three_runs(self): + """The comparison of the three runs on host trees (CheckParityTest runs check_parity itself).""" + reference = {"router": np.ones((4, 4)), "dense": np.arange(1.0, 17.0).reshape(4, 4)} + nudged = {name: value * 1.001 for name, value in reference.items()} + outcome = parity.assemble_result( + reference=([2.0, 1.0], reference, reference), + mpmd_run=([2.0, 1.00005], nudged, nudged), + floor=([2.0, 1.00004], reference, reference), + floor_microbatches=4, + notes=["a note"], + ) + self.assertEqual((outcome.num_params, outcome.floor_microbatches, outcome.notes), (2, 4, ("a note",))) + self.assertAlmostEqual(outcome.mpmd.grads.rel_l2, 1e-3, places=6) + self.assertTrue(outcome.passed(*TOLERANCES, 4.0)) + self.assertIn("notes:", outcome.report(*TOLERANCES, 4.0)) + alone = parity.assemble_result(reference=([2.0], reference, reference), mpmd_run=([2.0], nudged, nudged)) + self.assertIsNone(alone.floor) + + def test_gradients_far_below_1_against_their_own_norm(self): + """Step-1 gradient norms are far below 1 (deepseek3-tiny's router about 2e-3 on CPU): assemble_result floors the + gradients' denominator at 1e-5, not at the parameters' 1.0, under which a 50% error on such a tensor read 3.2e-4.""" + params = {"w": np.ones((4, 4))} + reference = {"router": np.full((64, 64), 1e-5), "tiny": np.full((4, 4), 1e-7)} # norms 6.4e-4 and 4e-7 + off = {name: grad * 1.5 for name, grad in reference.items()} + outcome = parity.assemble_result(reference=([2.0], reference, params), mpmd_run=([2.0], off, params)) + loss, grads, params_gate = outcome.gates(*TOLERANCES, 4.0) + self.assertEqual((loss.passed, grads.passed, params_gate.passed), (True, False, True)) + self.assertFalse(outcome.passed(*TOLERANCES, 4.0)) + rel = {path: value for value, path, _ in outcome.mpmd.grads.leaves} + self.assertAlmostEqual(rel["['router']"], 0.5, places=9) + self.assertAlmostEqual(rel["['tiny']"], 2e-7 / 1e-5, places=9) # a norm below the floor: divided by 1e-5 + + def test_notes(self): + def config(**kw): + return types.SimpleNamespace( + **{ + "dtype": "bfloat16", + "num_experts": 1, + "num_experts_per_tok": 1, + "matmul_precision": "default", + "decoder_block": DecoderBlockType.DEEPSEEK, + **kw, + } + ) + + self.assertEqual(parity.parity_notes(config(dtype="float32"), 2), []) + notes = parity.parity_notes(config(), 2) + self.assertEqual(len(notes), 1) + bf16 = notes[0] + self.assertIn("bfloat16", bf16) + self.assertEqual(parity.parity_notes(config(), 1), []) # no data parallelism + notes = parity.parity_notes(config(dtype="float32", num_experts=16, num_experts_per_tok=8), 1) + self.assertEqual(len(notes), 1) + moe = notes[0] + self.assertIn("--maxtext_overrides=num_experts_per_tok=16", moe) + self.assertEqual(parity.parity_notes(config(dtype="float32", num_experts=16, num_experts_per_tok=16), 2), []) + # On TPU a float32 matmul at the default precision runs in bfloat16 passes. + notes = parity.parity_notes(config(dtype="float32"), 2, platform="tpu") + self.assertEqual(len(notes), 1) + self.assertIn("--maxtext_overrides=matmul_precision=highest", notes[0]) + self.assertEqual(parity.parity_notes(config(dtype="float32", matmul_precision="highest"), 2, platform="tpu"), []) + # matmul_precision reaches only the simple model's output head; its layers take JAX's default precision. + simple = config(dtype="float32", matmul_precision="highest", decoder_block=DecoderBlockType.SIMPLE_MLP) + notes = parity.parity_notes(simple, 2, platform="tpu") + self.assertEqual(len(notes), 1) + self.assertIn("add JAX_DEFAULT_MATMUL_PRECISION=highest", notes[0]) + self.assertNotIn("matmul_precision=highest and", notes[0]) + with jax.default_matmul_precision("highest"): + self.assertEqual(parity.parity_notes(simple, 2, platform="tpu"), []) + self.assertIn("matmul_precision=highest.", parity.parity_notes(config(dtype="float32"), 2, platform="tpu")[0]) + + def test_step1_gradients_from_the_first_moment(self): + params = {"w": np.ones((2,), np.float32)} + tx = optax.adamw(1e-3) + _, state = tx.update({"w": np.full((2,), 3.0, np.float32)}, tx.init(params), params) + np.testing.assert_allclose(parity._first_moment(state)["w"], [0.3, 0.3], rtol=1e-6) + np.testing.assert_allclose(parity._step1_gradients(state)["w"], [3.0, 3.0], rtol=1e-6) + + +class CheckParityTest(unittest.TestCase): + + def test_check_parity_end_to_end_on_cpu(self): + """check_parity's whole path on CPU, with the Pathways-only MPMD compile swapped for the SPMD step. + + Both arms then run the same program, so they agree exactly; what this checks is the code around + them (a renamed variable there once crashed every parity run after its compute). + """ + if len(jax.devices("cpu")) < 4: + self.skipTest("needs 4 CPU devices (XLA_FLAGS=--xla_force_host_platform_device_count=4)") + real_build = parity.runner_lib.build + + def build(hparams, *, mode, **kw): + del mode # the "MPMD" arm runs the SPMD step too + return real_build(hparams, mode=train_step.ExecutionMode.SPMD, **kw) + + class Lowered: + + def __init__(self, fn): + self.fn, self.function_named_shardings = fn, types.SimpleNamespace(input_specs=None) + + def compile(self): + return jax.jit(self.fn) + + hparams = hp.Hparams( + model_name="simple", + num_layers=2, + num_stages=2, + emb_dim=64, + mlp_dim=128, + vocab_size=256, + max_target_length=16, + per_device_batch_size=2, + num_microbatches=2, + steps=2, + ) + with ( + mock.patch.object(parity.runner_lib, "build", build), + mock.patch.object(parity.runner_lib.Runnable, "lower", lambda runnable: Lowered(runnable.train_step)), + mock.patch.object(parity.runner_lib, "place_on_stage_meshes", lambda inputs, specs: inputs), + ): + outcome = parity.check_parity(hparams, floor_microbatches=1) + self.assertEqual(outcome.mpmd.max_rel_loss_diff, 0.0) + self.assertEqual((outcome.floor_microbatches, len(outcome.mpmd.losses)), (1, 2)) + self.assertTrue(outcome.passed(*TOLERANCES, 4.0)) + with self.assertRaisesRegex(ValueError, "at least 1"): + parity.check_parity(dataclasses.replace(hparams, steps=0)) + + def test_the_reference_compiles_once(self): + """Pinned to its device: DeepSeek's layers once returned step 1's state committed to another sharding, and the + step compiled again for step 2 (3.5 min for deepseek3-tiny with mHC on TPU7x).""" + if len(jax.devices("cpu")) < 2: + self.skipTest("needs 2 CPU devices (XLA_FLAGS=--xla_force_host_platform_device_count=2)") + hparams = hp.Hparams( + model_name="deepseek3-tiny", + num_layers=2, + first_num_dense_layers=1, + num_stages=2, + emb_dim=64, + mlp_dim=128, + vocab_size=128, + max_target_length=16, + per_device_batch_size=2, + num_microbatches=2, + ) + runnable = parity.runner_lib.build(hparams, mode=train_step.ExecutionMode.SPMD) + real_jit, steps = jax.jit, [] + + def jit(fun, *args, **kwargs): + jitted = real_jit(fun, *args, **kwargs) + if fun is runnable.train_step: + steps.append(jitted) + return jitted + + with mock.patch.object(parity.jax, "jit", jit): + losses, _, _ = parity._run_reference(runnable, 3) + self.assertEqual(len(losses), 3) + self.assertEqual([step._cache_size() for step in steps], [1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/pathways_train_test.py b/tests/unit/mpmd_test/pathways_train_test.py new file mode 100644 index 0000000000..47f118cad6 --- /dev/null +++ b/tests/unit/mpmd_test/pathways_train_test.py @@ -0,0 +1,71 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Trains the Shardy MPMD pipeline on Pathways: compile, and feed each step's state to the next. + +Shardy MPMD's IFRT IR program compiles only through Pathways' IFRT proxy, so this runs only with JAX_PLATFORMS=proxy +against a Pathways backend of 4 or more TPU devices (e.g. local_pathways.sh on a TPU VM), with shardy-mpmd installed. +""" + +import unittest + +import jax +import pathwaysutils +import pytest + +from maxtext.experimental.mpmd.partir import hparams as hp +from maxtext.experimental.mpmd.partir import train + +try: + from maxtext.experimental.mpmd.partir import sdy_mpmd_compat # pylint: disable=unused-import + + _SKIP = "" +except ModuleNotFoundError as error: # shardy-mpmd is an optional dependency + if not (error.name or "").startswith("shardy"): + raise + _SKIP = f"needs shardy-mpmd: {error}" + + +@pytest.mark.tpu_only +@unittest.skipIf(bool(_SKIP), _SKIP) +class PathwaysTrainTest(unittest.TestCase): + + def setUp(self): + super().setUp() + if not pathwaysutils.is_pathways_backend_used(): + self.skipTest("needs a Pathways backend (JAX_PLATFORMS=proxy): Shardy MPMD programs compile only there") + if len(jax.devices()) < 4: + self.skipTest("needs 4 devices") + + def test_steps_run_and_the_loss_falls(self): + hparams = hp.Hparams( + model_name="simple", + num_layers=4, + num_stages=2, + fsdp=2, + num_microbatches=4, + per_device_batch_size=4, + max_target_length=128, + steps=3, + warmup_steps=1, + ) + # A step that rejected its predecessor's output ("Input signature does not match") would raise here. + result = train.run_training(hparams) + self.assertEqual(result.stats.num_steps, 3) + self.assertLess(result.stats.loss, result.stats.first_loss) + self.assertGreater(result.throughput.tokens_per_second, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/pipeline_test.py b/tests/unit/mpmd_test/pipeline_test.py new file mode 100644 index 0000000000..60bd7ac4f1 --- /dev/null +++ b/tests/unit/mpmd_test/pipeline_test.py @@ -0,0 +1,416 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Lowering tests of the Shardy MPMD pipeline on 4 CPU devices, and tests of the last-stage merge rule on made-up +fragment infos and of the IFRT IR rewrite on a synthetic program. + +Shardy MPMD's IFRT IR program compiles only on Pathways, so these stop at the lowered program. The lowering and +merge-rule tests need the shardy-mpmd frontend (see sdy_mpmd_compat.py) and skip without it. +""" + +import dataclasses +import re +from typing import Any +import unittest + +import jax + +from maxtext.experimental.mpmd.partir import hparams as hp +from maxtext.experimental.mpmd.partir import pipeline as pl + +try: + from maxtext.experimental.mpmd.partir import runner + from maxtext.experimental.mpmd.partir import train_compile + from maxtext.experimental.mpmd.partir.sdy_mpmd_compat import mpmd + from maxtext.experimental.mpmd.partir.sdy_mpmd_compat import shardy_pipeline + + _SKIP = "" +except ModuleNotFoundError as error: # shardy-mpmd is an optional dependency + if not (error.name or "").startswith("shardy"): + raise + _SKIP = f"needs shardy-mpmd: {error}" + + +def cpu_devices(count): + """The first `count` CPU devices, or a skip when there are fewer.""" + devices = jax.devices("cpu") + if len(devices) < count: + raise unittest.SkipTest(f"needs {count} CPU devices (XLA_FLAGS=--xla_force_host_platform_device_count={count})") + return devices[:count] + + +def lower(split_bwd_fragments=None, **kw): + """Lowers the simple model's training step, at PP=2 x FSDP=2 unless `kw` says otherwise; returns (lowered, runnable). + + `split_bwd_fragments`, when not None, overrides the plan's `mpmd_split_bwd_fragments` partitioning option. + """ + hparams = hp.Hparams( + **{ + "model_name": "simple", + "num_layers": 4, + "num_stages": 2, + "num_microbatches": 4, + "per_device_batch_size": 2.0, + "max_target_length": 64, + **kw, + } + ) + run = runner.build(hparams, devices=cpu_devices(4), abstract=True) + config = run.plan.mpmd_config + if split_bwd_fragments is not None: + options = {**config.partitioning_options, "mpmd_split_bwd_fragments": split_bwd_fragments} + config = dataclasses.replace(config, partitioning_options=options) + lowered = mpmd.jit( + run.train_step, + mpmd_config=config, + in_shardings=run.in_shardings, + out_shardings=run.out_shardings, + donate_argnums=(0,), + ).lower(run.state, run.batch) + return lowered, run + + +_FRAGMENT_CALL_RE = re.compile( + r'^\s*(%\w+)(?::\d+)? = mpmd\.fragment_call @([\w.$]+)\(' +) +_TRANSFER_RE = re.compile(r"mpmd\.transfer (%\w+)") +_CONTRACTING_DIMS_RE = re.compile(r"stablehlo\.dot_general .*contracting_dims = \[([\d, ]*)\] x") + + +@dataclasses.dataclass(frozen=True, order=True) +class Fragment: + """A fragment call of the partitioned MPMD module's @main. + + Attributes: + kind: "F" (every origin a forward), "B" (every origin a backward, transpose count 1) or "FB" (merged). + transferred: Whether one of its results goes to another mesh. + weight_dots: dot_generals that contract two dimensions of each operand: the rows and positions of the simple + model's [rows, positions, features] activations, dW = X^T dY. + other_dots: The other dot_generals (forward, dX = dY W^T), which contract one dimension or none. + """ + + kind: str + transferred: bool + weight_dots: int + other_dots: int + + +def fragments(lowered): + """Each mesh's fragment calls (no pre_m / post_m), in program order, as `Fragment`s.""" + text = lowered.as_text(dialect="mpmd") + main = text[text.index("func.func public @main(") :] + main = main[: main.index("\n }\n")] + transferred = set(_TRANSFER_RE.findall(main)) + calls = {} + for line in main.splitlines(): + match = _FRAGMENT_CALL_RE.match(line) + if not match or re.search(r'"(pre|post)_m\d+"', match.group(3)): + continue + result, mesh, origins, callee = match.groups() + backward = re.findall(r'"\w+"(\(1\))?', origins) + kind = "B" if all(backward) else "FB" if any(backward) else "F" + start = text.index(f"func.func @{callee}(") + body = text[start : text.index("\n }\n", start)] + contracted = [len([d for d in dims.split(",") if d.strip()]) for dims in _CONTRACTING_DIMS_RE.findall(body)] + weight = contracted.count(2) + calls.setdefault(mesh, []).append(Fragment(kind, result in transferred, weight, len(contracted) - weight)) + return calls + + +# PP=4 on the 4 CPU devices, one a stage: 4 microbatches of 2 sequences. +_PP4 = {"num_stages": 4, "per_device_batch_size": 8.0} + + +def dot_totals(mesh_fragments): + """(weight-gradient dots, other dots) over a mesh's fragments.""" + return sum(f.weight_dots for f in mesh_fragments), sum(f.other_dots for f in mesh_fragments) + + +def leading_forwards(mesh_fragments): + """The forwards a mesh runs before its first fragment with a backward in it.""" + return next((i for i, f in enumerate(mesh_fragments) if f.kind != "F"), len(mesh_fragments)) + + +# A synthetic @main: call @a's outputs 0 and 2 and call @b's output go to the other mesh in one merged CopyArrays, +# whose outputs @c and the return use; @c's output comes back in a copy of its own. +_A = "!ifrt.array, #sp, [0, 1]>" +_B = "!ifrt.array, #sp, [2, 3]>" +_HEADER = f"""module @jit_f attributes {{ifrt.num_devices = 4 : i32}} {{ + func.func public @main(%arg0: {_A}) -> ({_B}, {_B}, {_B}, {_A}) attributes {{ifrt.function}} {{ +""" +_FOOTER = """ } +} +""" +_MERGED = f""" %a:3, %ca = ifrt.Call @a::@main(%arg0) on devices [0, 1] : ({_A}) -> ({_A}, {_A}, {_A}) + %b, %cb = ifrt.Call @b::@main(%arg0) after %ca on devices [0, 1] : ({_A}) -> {_A} + %t:3, %ct = ifrt.CopyArrays(%a#0, %b, %a#2) : ({_A}, {_A}, {_A}) -> ({_B}, {_B}, {_B}) + %c, %cc = ifrt.Call @c::@main(%t#0, %t#1) on devices [2, 3] : ({_B}, {_B}) -> {_B} + %u, %cu = ifrt.CopyArrays(%c) : ({_B}) -> {_A} + return %c, %t#2, %t#1, %u : {_B}, {_B}, {_B}, {_A} +""" +# Each producer's inputs in a copy of their own, right after it and pinned to it, and every use of the merged copy's +# outputs renamed to the split copies' (#0 and #2 to the first one's #0 and #1, #1 to the second one). +_PINNED = f""" %a:3, %ca = ifrt.Call @a::@main(%arg0) on devices [0, 1] : ({_A}) -> ({_A}, {_A}, {_A}) + %t_pin0:2, %ct_pin0 = ifrt.CopyArrays(%a#0, %a#2) after %ca : ({_A}, {_A}) -> ({_B}, {_B}) + %b, %cb = ifrt.Call @b::@main(%arg0) after %ca on devices [0, 1] : ({_A}) -> {_A} + %t_pin1, %ct_pin1 = ifrt.CopyArrays(%b) after %cb : ({_A}) -> {_B} + %c, %cc = ifrt.Call @c::@main(%t_pin0#0, %t_pin1) on devices [2, 3] : ({_B}, {_B}) -> {_B} + %u, %cu = ifrt.CopyArrays(%c) after %cc : ({_B}) -> {_A} + return %c, %t_pin0#1, %t_pin1, %u : {_B}, {_B}, {_B}, {_A} +""" + + +class _TextModule: + """Stands in for the IFRT IR module: its text, parsed back as it is.""" + + context = None + + def __init__(self, text): + self.text = text + + def __str__(self): + return self.text + + @classmethod + def parse(cls, text, context=None): + del context + return cls(text) + + +@dataclasses.dataclass(frozen=True) +class _PartitioningResult: + ifrt_ir_module: Any + + +class PinTransfersTest(unittest.TestCase): + """pin_ifrt_transfers_to_producers on a synthetic program: no Shardy needed. + + With jax 0.12.0.1 and Shardy 38ab99f4, LowerToIfrt merges two producers' transfers into one CopyArrays for ZB-H1, + the ZB-H2 schedules and GPipeBut1F1BForLastMesh (not for 1F1B or GPipe), and the rewrite splits it and renames every + use of its outputs: a use renamed to another value of the same type would still parse, and compute something else. + """ + + def test_a_merged_copy_is_split_per_producer(self): + lowered = types_namespace(partitioning_result=_PartitioningResult(_TextModule(_HEADER + _MERGED + _FOOTER))) + self.assertIs(pl.pin_ifrt_transfers_to_producers(lowered), lowered) + self.assertEqual(str(lowered.partitioning_result.ifrt_ir_module), _HEADER + _PINNED + _FOOTER) + + def test_a_program_already_pinned_is_left_alone(self): + module = _TextModule(_HEADER + _PINNED + _FOOTER) + lowered = types_namespace(partitioning_result=_PartitioningResult(module)) + pl.pin_ifrt_transfers_to_producers(lowered) + self.assertIs(lowered.partitioning_result.ifrt_ir_module, module) + + +def types_namespace(**kwargs): + """A mutable stand-in for MpmdLowered.""" + return type("Lowered", (), kwargs)() + + +def fragment_info(transpose_count, split_type=None, call_counter=0, stage=3): + """Microbatch `call_counter`'s fragment of `stage`, as Shardy describes it to the merge rule at PP=4 with 4 layers. + + `transpose_count` is 0 for the forward and 1 for the backward; `split_type` marks B_a (KEEP_TRANSFERRED) and B_w + (DROP_TRANSFERRED) of a split backward. The last stage's fragments also hold the output head. + """ + names = (f"layer{stage}", "unembed") if stage == 3 else (f"layer{stage}",) + return shardy_pipeline.FragmentInfo( + origins=tuple(shardy_pipeline.FragmentOrigin(name, transpose_count) for name in names), + stage_id=stage, + call_counter=call_counter, + split_type=split_type, + mesh_name=f"m{stage}", + ) + + +@unittest.skipIf(bool(_SKIP), _SKIP) +class LastStageMergeRuleTest(unittest.TestCase): + """pipeline._merge_last_stage_fwd_bwd on made-up fragment infos: nothing is lowered. + + A rule that also matched B_w would put the forward in two merge rules, on which Shardy aborts the whole process (a + CHECK in rule_based_merge.cc) instead of failing a lowering test. + """ + + def test_the_forward_merges_with_b_a_not_b_w(self): + merge = pl._merge_last_stage_fwd_bwd # pylint: disable=protected-access + keep = shardy_pipeline.SplitFragmentType.KEEP_TRANSFERRED + drop = shardy_pipeline.SplitFragmentType.DROP_TRANSFERRED + forward = fragment_info(0) + cases = { + "F + B_a": (forward, fragment_info(1, keep), True), + "F + B_w": (forward, fragment_info(1, drop), False), + "B_a + B_w": (fragment_info(1, keep), fragment_info(1, drop), False), + "F + the whole backward (1F1B)": (forward, fragment_info(1), True), + "F + the next microbatch's B_a": (forward, fragment_info(1, keep, call_counter=1), False), + "F + B_a on stage 2": (fragment_info(0, stage=2), fragment_info(1, keep, stage=2), False), + } + context = shardy_pipeline.PipelineContext(num_meshes=4) + for case, (f1, f2, merged) in cases.items(): + for swapped in (False, True): + with self.subTest(case, swapped=swapped): + self.assertEqual(merge(*((f2, f1) if swapped else (f1, f2)), context), merged) + + +@unittest.skipIf(bool(_SKIP), _SKIP) +class LoweringTest(unittest.TestCase): + + def test_schedule_option_and_stage_ids(self): + for schedule, option in ( + ("ZB-H1", "ZeroBubbleH1"), + ("ZB-H2-ZERO", "ZeroBubbleH2ZeroTxLatency"), + ("ZB-H2-HALF", "ZeroBubbleH2HalfTxLatency"), + ("ZB-H2-FULL", "ZeroBubbleH2FullTxLatency"), + ): + with self.subTest(schedule=schedule): + plan = pl.build_plan( + hp.Hparams(model_name="simple", num_layers=8, num_stages=4, pipeline_schedule=schedule), + devices=cpu_devices(4), + ) + opts = plan.mpmd_config.partitioning_options + self.assertEqual(opts["mpmd_pipeline_schedule"], option) + self.assertTrue(opts["mpmd_split_bwd_fragments"]) + self.assertEqual(plan.mpmd_config.name_to_stage_assignment["layer7"], 3) + + def test_1f1b_merges_the_last_stage(self): + """The last-stage forward/backward merge rule removes one fragment per microbatch.""" + gpipe, _ = lower(pipeline_schedule="GPIPE") + one_f_one_b, _ = lower(pipeline_schedule="1F1B") + n_gpipe = train_compile.summarize_ifrt(gpipe.as_text(dialect="ifrt")).calls + n_1f1b = train_compile.summarize_ifrt(one_f_one_b.as_text(dialect="ifrt")).calls + self.assertEqual(n_gpipe - n_1f1b, 4) + + def test_pin_transfers_to_producers(self): + lowered, run = lower(pipeline_schedule="1F1B") + before = train_compile.summarize_ifrt(lowered.as_text(dialect="ifrt")) + self.assertEqual(before.pinned_copies, 0) + pl.pin_ifrt_transfers_to_producers(lowered) + after = train_compile.summarize_ifrt(lowered.as_text(dialect="ifrt")) + self.assertGreater(after.pinned_copies, 0) + self.assertEqual(after.calls, before.calls) + # The pinned module is what compile() would read. + self.assertIn("after %", str(lowered.partitioning_result.ifrt_ir_module)) + # Every stage holds its own layers (2 per stage), embed on m0, unembed on m1. + self.assertEqual( + [run.plan.name_to_mesh[name] for name in ("embed", "layer1", "layer2", "unembed")], ["m0", "m0", "m1", "m1"] + ) + + def test_split_and_pinned_transfers_with_zero_bubble(self): + """ZB-H1: LowerToIfrt merges two microbatches' stage-0 transfers; each goes after its own producer again.""" + lowered, _ = lower(pipeline_schedule="ZB-H1") + before = train_compile.summarize_ifrt(lowered.as_text(dialect="ifrt")) + pl.pin_ifrt_transfers_to_producers(lowered) + text = lowered.as_text(dialect="ifrt") + after = train_compile.summarize_ifrt(text) + self.assertGreater(after.copies, before.copies) # a merged copy was split + self.assertEqual(after.pinned_copies, after.copies) + self.assertEqual(after.calls, before.calls) + + def test_zero_bubble_splits_the_backward_fragments(self): + """ZB-H1 / ZB-H2 at PP=4: each backward that sends an activation gradient upstream becomes two fragments. + + B_a (Shardy's split_keep_transferred) computes the transferred activation gradient; B_w (split_drop_transferred) + computes the weight gradients, which stay on the mesh, so the schedule can run it in a bubble. The first stage + sends nothing upstream: its backward stays whole. On the last stage the forward merges with B_a, as 1F1B's does + with the whole backward. + + Each schedule keeps its own order: before stage s's first backward, ZB-H1 runs 1F1B's P - s forwards, and ZB-H2 + runs 2(P - s) - 1, plus 2(P - s - 1) times a transfer's share of a stage's compute: 0, 1/2 or 1 for ZERO, HALF and + FULL (Shardy's pipeline_schedule.cc); at most the 4 microbatches. + """ + gpipe = fragments(lower(pipeline_schedule="GPIPE", **_PP4)[0]) + self.assertEqual([len(gpipe[mesh]) for mesh in ("m0", "m1", "m2", "m3")], [8, 8, 8, 8]) + # The forwards before the first backward on m1 and m2. + expected_leading_forwards = {"ZB-H1": [3, 2], "ZB-H2-ZERO": [4, 3], "ZB-H2-HALF": [4, 4], "ZB-H2-FULL": [4, 4]} + for schedule, expected in expected_leading_forwards.items(): + with self.subTest(schedule=schedule): + zero_bubble = fragments(lower(pipeline_schedule=schedule, **_PP4)[0]) + self.assertEqual(sorted(zero_bubble["m0"]), sorted(gpipe["m0"])) + for mesh in ("m1", "m2", "m3"): + b_a = [f for f in zero_bubble[mesh] if f.kind != "F" and f.transferred] + b_w = [f for f in zero_bubble[mesh] if f.kind == "B" and not f.transferred] + self.assertEqual([len(b_a), len(b_w)], [4, 4], zero_bubble[mesh]) + self.assertTrue(all(f.weight_dots == 0 for f in b_a), b_a) + self.assertTrue(all(f.weight_dots > 0 and f.other_dots == 0 for f in b_w), b_w) + # Every dot_general of GPipe's forward and backward, in exactly one fragment: nothing is recomputed. + self.assertEqual(dot_totals(zero_bubble[mesh]), dot_totals(gpipe[mesh])) + self.assertEqual({f.kind for f in zero_bubble["m3"]}, {"FB", "B"}) + order = {mesh: " ".join(f.kind for f in zero_bubble[mesh]) for mesh in ("m1", "m2")} + self.assertEqual([leading_forwards(zero_bubble[mesh]) for mesh in ("m1", "m2")], expected, order) + + def test_zero_bubble_without_the_split_option_runs_the_1f1b_fragments(self): + """The split is pipeline._make_mpmd_config's mpmd_split_bwd_fragments: without it ZB-H1 runs 1F1B's fragments.""" + one_f_one_b = fragments(lower(pipeline_schedule="1F1B", **_PP4)[0]) + unsplit = fragments(lower(pipeline_schedule="ZB-H1", split_bwd_fragments=False, **_PP4)[0]) + self.assertEqual( + {mesh: sorted(f) for mesh, f in unsplit.items()}, {mesh: sorted(f) for mesh, f in one_f_one_b.items()} + ) + + def test_fsdp_pregather_fragments(self): + """FSDP=2 stages pre-gather their weights in their own pre_m{s} computation.""" + lowered, _ = lower(pipeline_schedule="1F1B") + self.assertIn("pre_m", lowered.as_text(dialect="mpmd")) + + def test_deepseek3_tiny_lowers_to_ifrt_ir(self): + """train_compile's CPU path on an MoE model with the deferred expert-gradient reduce-scatter.""" + hparams = hp.Hparams( + model_name="deepseek3-tiny", + num_layers=4, + num_stages=2, + fsdp=2, + num_microbatches=2, + per_device_batch_size=2.0, + max_target_length=32, + emb_dim=128, + mlp_dim=256, + vocab_size=512, + ) + cpu_devices(4) + lowered, compiled, summary = train_compile.run_compile(hparams, compile_topology="cpu") + self.assertIsNone(compiled) # compiles only on Pathways + self.assertEqual(set(summary.calls_per_mesh), {"m0", "m1"}) + self.assertGreater(summary.copies, 0) + self.assertGreater(summary.pinned_copies, 0) + self.assertIn("post_m1", lowered.as_text(dialect="mpmd")) + + def test_deepseek_hyper_connections_cross_the_stage_boundary(self): + """With mHC the activations between the stages carry the 4 residual streams: [rows, seq, streams, emb].""" + hparams = hp.Hparams( + model_name="deepseek3-tiny", + num_layers=4, + num_stages=2, + fsdp=2, + num_microbatches=2, + per_device_batch_size=2.0, + max_target_length=32, + emb_dim=128, + mlp_dim=256, + vocab_size=512, + maxtext_overrides="mhc_expansion_rate=4", + ) + cpu_devices(4) + lowered, _, summary = train_compile.run_compile(hparams, compile_topology="cpu") + self.assertEqual(set(summary.calls_per_mesh), {"m0", "m1"}) + copies = [line for line in lowered.as_text(dialect="ifrt").splitlines() if "ifrt.CopyArrays(" in line] + # [microbatch rows (2 on 4 devices, 4 on 8), 32 positions, 4 streams, 128] + self.assertTrue([line for line in copies if re.search(r"tensor<\d+x32x4x128xbf16>", line)], copies) + + def test_train_compile_refuses_a_microbatch_the_stage_cannot_split(self): + cpu_devices(4) + hparams = hp.Hparams(model_name="simple", num_layers=4, num_stages=2, num_microbatches=4, per_device_batch_size=2.0) + with self.assertRaisesRegex(ValueError, r"sequences per microbatch, which must be a multiple of the \d+ devices"): + train_compile.run_compile(hparams, compile_topology="cpu") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/sdy_mpmd_compat_test.py b/tests/unit/mpmd_test/sdy_mpmd_compat_test.py new file mode 100644 index 0000000000..c006030486 --- /dev/null +++ b/tests/unit/mpmd_test/sdy_mpmd_compat_test.py @@ -0,0 +1,78 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the Shardy MPMD import shim (the frontend's import needs shardy-mpmd).""" + +import importlib +import logging +import sys +import unittest +from unittest import mock + +import jaxlib + +from maxtext.experimental.mpmd.partir import sdy_mpmd_versions + +_COMPAT = "maxtext.experimental.mpmd.partir.sdy_mpmd_compat" + +try: + from maxtext.experimental.mpmd.partir import sdy_mpmd_compat as compat + + _SKIP = "" +except ModuleNotFoundError as error: # shardy-mpmd is an optional dependency + if not (error.name or "").startswith("shardy"): + raise + _SKIP = f"needs shardy-mpmd: {error}" + + +class ShimTest(unittest.TestCase): + + @unittest.skipIf(bool(_SKIP), _SKIP) + def test_imports_the_frontend_through_the_aliases(self): + self.assertTrue(callable(compat.mpmd.jit)) + self.assertTrue(callable(compat.shardy_pipeline.build_merge_rules_from_predicate)) + self.assertIs(sys.modules["jax.jaxlib"], jaxlib) + self.assertIn("mlir.ir", sys.modules) + + @unittest.skipIf(bool(_SKIP), _SKIP) + def test_a_mismatched_frontend_warns(self): + """pip recorded another Shardy commit than the installed jaxlib's: importing the shim warns, with the fix.""" + for commit, warns in (("0" * 40, True), (sdy_mpmd_versions.SHARDY_COMMITS.get(jaxlib.__version__), False)): + with ( + mock.patch.dict(sys.modules), + mock.patch.object(sdy_mpmd_versions, "installed_commit", return_value=commit), + self.assertLogs("absl", level="WARNING") as logs, + ): + del sys.modules[_COMPAT] + importlib.import_module(_COMPAT) + logging.getLogger("absl").warning("end of the import") # assertLogs needs one record + mismatch = [line for line in logs.output if "shardy-mpmd was installed from Shardy 000000000000" in line] + self.assertEqual(bool(mismatch), warns, logs.output) + if warns: + self.assertIn(sdy_mpmd_versions.install_command(jaxlib.__version__), mismatch[0]) + + def test_a_missing_frontend_names_the_install_command(self): + """Without shardy-mpmd, the MPMD paths stop with the pip command for the installed jaxlib.""" + with mock.patch.dict(sys.modules): + for name in [name for name in sys.modules if name == "shardy" or name.startswith(("shardy.", _COMPAT))]: + del sys.modules[name] + sys.modules["shardy"] = None # makes `import shardy...` raise ModuleNotFoundError + with self.assertRaises(ModuleNotFoundError) as raised: + importlib.import_module(_COMPAT) + self.assertIn(sdy_mpmd_versions.install_command(jaxlib.__version__), str(raised.exception)) + self.assertTrue(raised.exception.name.startswith("shardy"), raised.exception.name) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/sdy_mpmd_versions_test.py b/tests/unit/mpmd_test/sdy_mpmd_versions_test.py new file mode 100644 index 0000000000..84c3468733 --- /dev/null +++ b/tests/unit/mpmd_test/sdy_mpmd_versions_test.py @@ -0,0 +1,77 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the jaxlib/Shardy MPMD version table and its install hints (no Shardy needed).""" + +import importlib.metadata +import json +import types +import unittest +from unittest import mock + +from maxtext.experimental.mpmd.partir import sdy_mpmd_versions as versions + +COMMIT = "38ab99f4d252c59d491899a694fe8cbadfeccec3" +# PEP 610 direct_url.json records of a git install, an archive install and a local directory install. +VCS = {"url": "https://github.com/openxla/shardy", "vcs_info": {"vcs": "git", "commit_id": COMMIT}} +ARCHIVE = {"url": f"https://github.com/openxla/shardy/archive/{COMMIT}.zip", "archive_info": {}} +LOCAL = {"url": "file:///src/shardy/integrations/python/jax/mpmd", "dir_info": {}} + + +class VersionsTest(unittest.TestCase): + + def test_install_command(self): + self.assertEqual( + versions.install_command("0.12.0.1"), + f'pip install --no-deps "shardy-mpmd @ git+https://github.com/openxla/shardy@{COMMIT}' + '#subdirectory=shardy/integrations/python/jax/mpmd"', + ) + self.assertIn("no Shardy commit is known for jaxlib 9.9.9", versions.install_command("9.9.9")) + self.assertEqual(set(versions.SHARDY_COMMITS), {"0.11.1", "0.12.0.1", "0.12.1"}) + + def test_commit_from_direct_url(self): + self.assertEqual(versions.commit_from_direct_url(json.dumps(VCS)), COMMIT) + self.assertEqual(versions.commit_from_direct_url(json.dumps(ARCHIVE)), COMMIT) + self.assertIsNone(versions.commit_from_direct_url(json.dumps(LOCAL))) + self.assertIsNone(versions.commit_from_direct_url("not json")) + + def test_installed_commit(self): + """The commit pip recorded for the shardy-mpmd distribution, or None when there is no record or no distribution.""" + + def distribution(record): + """A distribution whose direct_url.json is `record` (None: the file is missing).""" + return types.SimpleNamespace( + read_text=lambda name: json.dumps(record) if name == "direct_url.json" and record is not None else None + ) + + for record, want in ((VCS, COMMIT), (ARCHIVE, COMMIT), (LOCAL, None), (None, None)): + with mock.patch.object(importlib.metadata, "distribution", return_value=distribution(record)) as found: + self.assertEqual(versions.installed_commit(), want, record) + found.assert_called_once_with("shardy-mpmd") + # A Shardy checkout on PYTHONPATH: no distribution at all. + missing = importlib.metadata.PackageNotFoundError("shardy-mpmd") + with mock.patch.object(importlib.metadata, "distribution", side_effect=missing): + self.assertIsNone(versions.installed_commit()) + + def test_version_mismatch(self): + self.assertIsNone(versions.version_mismatch("0.12.0.1", COMMIT)) + self.assertIsNone(versions.version_mismatch("0.12.0.1", None)) # a checkout on PYTHONPATH: cannot be checked + mismatch = versions.version_mismatch("0.12.1", COMMIT) + self.assertIn("jaxlib 0.12.1 was built with Shardy 57fffc23dfdf", mismatch) + self.assertIn("--force-reinstall", mismatch) + self.assertIn("no Shardy commit is known", versions.version_mismatch("9.9.9", None)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/spmd_baseline_test.py b/tests/unit/mpmd_test/spmd_baseline_test.py new file mode 100644 index 0000000000..8051f7f0b8 --- /dev/null +++ b/tests/unit/mpmd_test/spmd_baseline_test.py @@ -0,0 +1,477 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the equivalent MaxText SPMD baseline's settings and command, and that MaxText traces them (no cluster).""" + +import contextlib +import dataclasses +import io +import os +import re +import shlex +import unittest + +from absl import app +from absl import flags + +from flax import nnx +from flax.linen import partitioning as nn_partitioning +import jax +from maxtext.configs import pyconfig +from maxtext.trainers.pre_train import train +from maxtext.trainers.pre_train import train_compile +from maxtext.utils import max_utils +from maxtext.utils import maxtext_utils +from maxtext.utils import model_creation_utils +from maxtext.utils import sharding +from maxtext.utils.globals import MAXTEXT_CONFIGS_DIR + +from maxtext.experimental.mpmd.partir import hparams as hp +from maxtext.experimental.mpmd.partir import runner +from maxtext.experimental.mpmd.partir import spmd_baseline +from maxtext.experimental.mpmd.partir import train_step + +FLAGS = [ + "--device_type=v5p-32", + "--pp=4", + "--fsdp=4", + "--num_microbatches=8", + "--per_device_batch_size=8", + "--model_name=llama3.1-8b", + "--num_layers=32", + "--max_target_length=2048", + "--steps=5", + "--warmup_steps=2", + "--run_name=sb-run", + "--output_dir=gs://bucket/out", +] +# The README's spmd_baseline example: its GKE llama3.1-8b run on two slices, two layers a stage. +README_EXAMPLE = ( + "--device_type=tpu7x-4x4x4", + "--num_slices=2", + "--pp=4", + "--num_microbatches=4", + "--per_device_batch_size=4", + "--model_name=llama3.1-8b", + "--max_target_length=1024", + "--learning_rate=1e-5", +) +# One DeepSeek layer a pipeline stage, on a v5p-16. +ONE_DEEPSEEK_LAYER_A_STAGE = ( + "--device_type=v5p-16", + "--pp=4", + "--fsdp=2", + "--num_microbatches=8", + "--per_device_batch_size=8", + "--model_name=deepseek3-tiny", + "--num_layers=8", + "--max_target_length=256", +) + + +def run(*extra): + flag_values = flags.FlagValues() + spmd_baseline.define_flags(flag_values) + flag_values(["spmd_baseline", *FLAGS, *extra]) + out = io.StringIO() + with contextlib.redirect_stdout(out): + spmd_baseline.main(["spmd_baseline"], flag_values=flag_values) + return out.getvalue() + + +def settings_of(out): + return dict( + line.strip().split("=", 1) + for line in out.split("Run MaxText's trainer with:")[0].splitlines() + if line.startswith(" ") and "=" in line + ) + + +class SpmdFlagsTest(unittest.TestCase): + + def test_same_tokens_per_step(self): + """MPMD's batch is per stage, MaxText's per device of the whole slice: the baseline divides by the stages.""" + hparams = hp.Hparams(model_name="simple", num_layers=8, num_stages=4, num_microbatches=4, per_device_batch_size=8) + settings = spmd_baseline.spmd_flags(hparams, total_devices=16) + self.assertEqual(settings["per_device_batch_size"], "2.0") # 8 x 4 devices per stage, over 16 devices + self.assertEqual(settings["ici_pipeline_parallelism"], "4") + self.assertEqual(settings["num_pipeline_microbatches"], "4") + with self.assertRaisesRegex(ValueError, "multiple of the stage count"): + spmd_baseline.spmd_flags(dataclasses.replace(hparams, num_microbatches=6), total_devices=16) + + def test_remat_policy(self): + """MaxText refuses remat_policy=none with pipeline parallelism; the pipeline iterations checkpoint only with remat.""" + hparams = hp.Hparams(model_name="simple", num_layers=8, num_stages=4, num_microbatches=4, per_device_batch_size=8) + pipelined = spmd_baseline.spmd_flags(hparams, total_devices=16) + self.assertEqual((pipelined["remat_policy"], pipelined["set_remat_policy_on_pipeline_iterations"]), ("full", "False")) + self.assertEqual(spmd_baseline.spmd_flags(hparams, total_devices=16, pure_fsdp=True)["remat_policy"], "none") + remat = spmd_baseline.spmd_flags(dataclasses.replace(hparams, remat=True, remat_policy="minimal"), total_devices=16) + self.assertEqual((remat["remat_policy"], remat["set_remat_policy_on_pipeline_iterations"]), ("minimal", "True")) + + +class MultiSliceTest(unittest.TestCase): + """Over several slices MaxText's ici_* degrees describe one slice and its dcn_* degrees the slices. + + The baseline once put every stage on ICI: on two slices its ICI degrees multiplied to the devices of both, and + MaxText's mesh check (create_device_mesh) stopped the printed command at start-up. + """ + + def mesh(self, hparams, device_type, num_slices, pure_fsdp=False): + """{mesh axis: (ICI degree, DCN degree)} of the baseline on `num_slices` slices of `device_type`, axes above 1. + + pyconfig resolves the settings for that topology (compile_topology, as MaxText's AOT compilation takes it), and + the degrees are filled in and checked as MaxText's create_device_mesh does. + """ + devices = hp.devices_in_device_type(device_type) + settings = spmd_baseline.spmd_flags( + hparams, total_devices=devices * num_slices, num_slices=num_slices, pure_fsdp=pure_fsdp + ) + cfg = pyconfig.initialize( + [ + "spmd_baseline", + os.path.join(MAXTEXT_CONFIGS_DIR, "base.yml"), + *(f"{k}={v}" for k, v in settings.items()), + f"compile_topology={device_type}", + f"compile_topology_num_slices={num_slices}", + ] + ) + self.assertEqual(cfg.num_slices, num_slices) + ici = max_utils.fill_unspecified_mesh_axes(list(cfg.ici_parallelism), devices, "ICI") + dcn = max_utils.fill_unspecified_mesh_axes(list(cfg.dcn_parallelism), num_slices, "DCN") + return {axis: (i, d) for axis, i, d in zip(cfg.mesh_axes, ici, dcn) if i * d > 1} + + def test_whole_stages_on_each_slice(self): + """deepseek3-tiny on two v5p-16 slices: two stages a slice, the stage boundary between them over DCN.""" + tiny = hp.Hparams( + model_name="deepseek3-tiny", num_layers=8, num_stages=4, fsdp=2, num_microbatches=8, per_device_batch_size=8 + ) + self.assertEqual(self.mesh(tiny, "v5p-16", 1), {"stage": (4, 1), "fsdp": (2, 1)}) + # 4 devices a stage: FSDP 2 x tensor 2, as the MPMD run's stage meshes. + self.assertEqual(self.mesh(tiny, "v5p-16", 2), {"stage": (2, 2), "fsdp": (2, 1), "tensor": (2, 1)}) + expert = dataclasses.replace(tiny, fsdp=-1, expert=2) + self.assertEqual(self.mesh(expert, "v5p-16", 2), {"stage": (2, 2), "fsdp": (2, 1), "expert": (2, 1)}) + # MaxText fills in the FSDP degree of each slice's stages. + self.assertEqual(self.mesh(dataclasses.replace(tiny, fsdp=-1), "v5p-16", 2), {"stage": (2, 2), "fsdp": (4, 1)}) + # The README's example: 2 x tpu7x-4x4x4 (MaxText's compile_topology calls it tpu7x-128), two stages a slice. + flag_values = flags.FlagValues() + spmd_baseline.define_flags(flag_values) + flag_values(["spmd_baseline", *README_EXAMPLE]) + self.assertEqual(self.mesh(hp.from_flags(flag_values), "tpu7x-128", 2), {"stage": (2, 2), "fsdp": (64, 1)}) + llama = hp.Hparams(model_name="llama3.1-8b", num_layers=8, num_stages=4, fsdp=4, num_microbatches=4) + self.assertEqual(self.mesh(llama, "v5p-32", 2), {"stage": (2, 2), "fsdp": (4, 1), "tensor": (2, 1)}) + + def test_whole_slices_in_each_stage(self): + """Two stages on four slices: each stage holds two, with its outermost axis, fsdp, over DCN as in the MPMD run.""" + hparams = hp.Hparams(model_name="llama3.1-8b", num_layers=8, num_stages=2, num_microbatches=4) + self.assertEqual(self.mesh(hparams, "v5p-16", 4), {"stage": (1, 2), "fsdp": (8, 2)}) + # 16 devices a stage at FSDP 8: tensor 2 within each slice, as in the MPMD run's stage mesh (fsdp outermost). + self.assertEqual( + self.mesh(dataclasses.replace(hparams, fsdp=8), "v5p-16", 4), {"stage": (1, 2), "fsdp": (4, 2), "tensor": (2, 1)} + ) + with self.assertRaisesRegex(ValueError, "FSDP degree \\(1\\) must be a multiple of 2"): + spmd_baseline.spmd_flags(dataclasses.replace(hparams, fsdp=1), total_devices=32, num_slices=4) + + def test_pure_fsdp_data_parallel_across_slices(self): + hparams = hp.Hparams(model_name="llama3.1-8b", num_layers=8, num_stages=4, fsdp=4, num_microbatches=4) + self.assertEqual(self.mesh(hparams, "v5p-32", 1, pure_fsdp=True), {"fsdp": (16, 1)}) + # FSDP 4 x 4 stages over the 32 devices, 2-way tensor parallel as the MPMD run's stages. + self.assertEqual(self.mesh(hparams, "v5p-32", 2, pure_fsdp=True), {"data": (1, 2), "fsdp": (8, 1), "tensor": (2, 1)}) + self.assertEqual( + self.mesh(dataclasses.replace(hparams, fsdp=-1), "v5p-32", 2, pure_fsdp=True), {"data": (1, 2), "fsdp": (16, 1)} + ) + + def test_refuses_stages_that_would_straddle_slices(self): + hparams = hp.Hparams(model_name="simple", num_layers=8, num_stages=4, num_microbatches=4) + with self.assertRaisesRegex(ValueError, "3 slices and 4 stages must divide one another"): + spmd_baseline.spmd_flags(hparams, total_devices=24, num_slices=3) + with self.assertRaisesRegex(ValueError, "must split evenly over num_slices"): + spmd_baseline.spmd_flags(hparams, total_devices=16, num_slices=3) + + def test_command_on_two_slices(self): + out = run("--num_slices=2", "--cluster=my-cluster", "--project=my-project", "--zone=us-east5-b", "--docker_image=img") + self.assertIn("(32 devices in 2 slices)", out) + settings = settings_of(out) + self.assertEqual( + {k: settings[k] for k in ("ici_pipeline_parallelism", "dcn_pipeline_parallelism", "per_device_batch_size")}, + {"ici_pipeline_parallelism": "2", "dcn_pipeline_parallelism": "2", "per_device_batch_size": "2.0"}, + ) + self.assertIn("--num-slices=2", out) + + +class DeepSeekBaselineTest(unittest.TestCase): + + HPARAMS = hp.Hparams( + model_name="deepseek3-tiny", + num_layers=8, + num_stages=4, + num_microbatches=4, + per_device_batch_size=4, + emb_dim=64, + mlp_dim=128, + vocab_size=256, + max_target_length=32, + ) + + def test_pipeline_holds_only_moe_layers(self): + """deepseek3-tiny's 3 dense layers run before MaxText's pipeline, which holds 4 of its 5 MoE layers.""" + settings = spmd_baseline.spmd_flags(self.HPARAMS, total_devices=16) + self.assertEqual((settings["pipeline_parallel_layers"], settings["num_layers_per_pipeline_stage"]), ("4", "1")) + self.assertIn( + "4 of the 8 layers, all MoE; DeepSeek's 3 dense layers and the 1 MoE layer past a multiple of the 4 stages run" + " before it", + spmd_baseline.baseline_notes(self.HPARAMS)[0], + ) + all_moe = dataclasses.replace(self.HPARAMS, first_num_dense_layers=0) + self.assertEqual(spmd_baseline.spmd_flags(all_moe, total_devices=16)["pipeline_parallel_layers"], "8") + # Every layer is in MaxText's pipeline, as in the MPMD run: nothing to note. + self.assertEqual(spmd_baseline.baseline_notes(all_moe), []) + uneven = dataclasses.replace(all_moe, num_layers=9, stage_layer_counts="2,2,2,3") + self.assertIn( + "8 of the 9 layers, all MoE; the 1 MoE layer past a multiple of the 4 stages runs before it", + spmd_baseline.baseline_notes(uneven)[1], + ) + with self.assertRaisesRegex(ValueError, "fewer than the 4 stages"): + spmd_baseline.spmd_flags( + dataclasses.replace(self.HPARAMS, num_layers=4, first_num_dense_layers=1), total_devices=16 + ) + + def test_scan_layers(self): + """Without --remat the layers outside MaxText's pipeline run unscanned, unless a stage holds one DeepSeek layer. + + Unscanned they are not rematerialised, as in the MPMD run; but with one layer per stage scan_layers=False makes + MaxText's pipeline shift the layer's output tuple and fail, as the README's example did (see + MaxTextTrainStepTest). + """ + one_per_stage = spmd_baseline.spmd_flags(self.HPARAMS, total_devices=16) + self.assertNotIn("scan_layers", one_per_stage) # MaxText's default: scanned + self.assertIn("MaxText still rematerialises those layers", spmd_baseline.baseline_notes(self.HPARAMS)[1]) + self.assertIn("--remat on both sides", spmd_baseline.baseline_notes(self.HPARAMS)[1]) + two_per_stage = dataclasses.replace(self.HPARAMS, num_stages=2, num_microbatches=2) + settings = spmd_baseline.spmd_flags(two_per_stage, total_devices=16) + self.assertEqual((settings["num_layers_per_pipeline_stage"], settings["scan_layers"]), ("2", "False")) + notes = spmd_baseline.baseline_notes(two_per_stage) + self.assertIn("those layers run unscanned (scan_layers=False)", notes[1]) + self.assertIn("--remat on both sides", notes[1]) + for remat in (dataclasses.replace(two_per_stage, remat=True), dataclasses.replace(self.HPARAMS, remat=True)): + self.assertNotIn("scan_layers", spmd_baseline.spmd_flags(remat, total_devices=16)) + self.assertEqual(len(spmd_baseline.baseline_notes(remat)), 1) + all_moe = dataclasses.replace(two_per_stage, first_num_dense_layers=0) # nothing outside the pipeline + self.assertNotIn("scan_layers", spmd_baseline.spmd_flags(all_moe, total_devices=16)) + self.assertEqual(spmd_baseline.spmd_flags(self.HPARAMS, total_devices=16, pure_fsdp=True)["scan_layers"], "True") + + def test_uneven_stage_layer_counts(self): + """MaxText's pipeline splits the layers evenly: uneven counts are noted, and indivisible ones refused.""" + simple = hp.Hparams(model_name="simple", num_layers=6, num_stages=2, num_microbatches=2, stage_layer_counts="2,4") + self.assertIn("--stage_layer_counts=2,4 has no MaxText equivalent", spmd_baseline.baseline_notes(simple)[0]) + self.assertEqual(spmd_baseline.spmd_flags(simple, total_devices=4)["num_layers_per_pipeline_stage"], "3") + with self.assertRaisesRegex(ValueError, "layers to divide into the 2 stages"): + spmd_baseline.spmd_flags(dataclasses.replace(simple, num_layers=5, stage_layer_counts="2,3"), total_devices=4) + + def test_same_model_as_the_mpmd_run(self): + """MaxText builds the baseline with exactly the MPMD model's parameters (it once built 3 dense + 8 MoE layers).""" + if len(jax.devices("cpu")) < 4: + self.skipTest("needs 4 CPU devices (XLA_FLAGS=--xla_force_host_platform_device_count=4)") + settings = spmd_baseline.spmd_flags(self.HPARAMS, total_devices=4) + cfg = pyconfig.initialize( + ["spmd_baseline", os.path.join(MAXTEXT_CONFIGS_DIR, "base.yml"), *(f"{k}={v}" for k, v in settings.items())] + ) + baseline = nnx.eval_shape(lambda: model_creation_utils.from_config(cfg, rngs=nnx.Rngs(0))) + _, baseline_params, _ = nnx.split(baseline, nnx.Param, ...) + mpmd = runner.build(self.HPARAMS, devices=jax.devices("cpu")[:4], mode=train_step.ExecutionMode.SPMD, abstract=True) + + def count(tree): + return sum(int(leaf.size) for leaf in jax.tree.leaves(tree)) + + self.assertEqual(count(baseline_params), count(mpmd.state.params)) + + +class MaxTextTrainStepTest(unittest.TestCase): + """MaxText's own training step traces with the settings the baseline prints, on the CPU devices. + + It once did not: with one DeepSeek layer per pipeline stage, ``scan_layers=False`` made MaxText's pipeline shift + the layer's output tuple (``TypeError: zeros_like requires ndarray or scalar arguments, got ``). + """ + + def hparams_of(self, argv, **changes): + flag_values = flags.FlagValues() + spmd_baseline.define_flags(flag_values) + flag_values(["spmd_baseline", *argv]) + return dataclasses.replace(hp.from_flags(flag_values), **changes) + + def trace_train_step(self, hparams): + """Traces MaxText's `train_step` with the baseline of `hparams` on every CPU device, its FSDP filling each stage. + + As MaxText's ahead-of-time compilation (`train_compile`) lowers it, from abstract state and data; returns the + settings. + """ + devices = len(jax.devices()) + if devices % hparams.num_stages: + self.skipTest(f"needs a multiple of {hparams.num_stages} CPU devices, has {devices}") + hparams = dataclasses.replace(hparams, fsdp=devices // hparams.num_stages) + settings = spmd_baseline.spmd_flags(hparams, total_devices=devices) + cfg = pyconfig.initialize( + ["spmd_baseline", os.path.join(MAXTEXT_CONFIGS_DIR, "base.yml"), *(f"{k}={v}" for k, v in settings.items())] + ) + mesh = maxtext_utils.get_mesh_from_config(cfg) + shaped_args, shaped_kwargs, state_mesh_shardings, _, model = train_compile.get_shaped_inputs(mesh, cfg) + params_shardings, state_mesh_shardings = sharding.maybe_update_params_sharding_with_opt(cfg, state_mesh_shardings) + step, in_shardings, out_shardings, static_argnums, donate_argnums = maxtext_utils.get_functional_train_with_signature( + train.train_step, + sharding.get_input_data_sharding(cfg, mesh), + sharding.build_zero1_input_state_mesh_shardings(cfg, state_mesh_shardings, params_shardings), + model, + cfg, + params_shardings, + ) + with jax.set_mesh(mesh), nn_partitioning.axis_rules(cfg.logical_axis_rules): + jax.jit( + step, + in_shardings=in_shardings, + out_shardings=out_shardings, + static_argnums=static_argnums, + donate_argnums=donate_argnums, + ).trace(*shaped_args, **shaped_kwargs) + return settings + + def test_readme_example(self): + """The README's example on one slice of the CPU devices, its FSDP scaled to them: 2 layers a stage.""" + with open(os.path.join(os.path.dirname(spmd_baseline.__file__), "README.md"), encoding="utf-8") as readme: + self.assertIn("spmd_baseline " + " ".join(README_EXAMPLE), re.sub(r"\s*\\\n\s*", " ", readme.read())) + settings = self.trace_train_step(self.hparams_of(README_EXAMPLE)) + self.assertEqual(settings["num_layers_per_pipeline_stage"], "2") + + def test_one_deepseek_layer_a_stage(self): + """deepseek3-tiny at PP=4 x FSDP=2 on a v5p-16, its FSDP scaled to the CPU devices: 1 layer a stage.""" + settings = self.trace_train_step(self.hparams_of(ONE_DEEPSEEK_LAYER_A_STAGE)) + self.assertEqual(settings["num_layers_per_pipeline_stage"], "1") + + def test_unscanned_layers_outside_the_pipeline(self): + """Two layers a stage: the dense and remaining MoE layers run unscanned before MaxText's pipeline.""" + settings = self.trace_train_step(self.hparams_of(ONE_DEEPSEEK_LAYER_A_STAGE, num_stages=2)) + self.assertEqual((settings["num_layers_per_pipeline_stage"], settings["scan_layers"]), ("2", "False")) + + +class LaunchCommandTest(unittest.TestCase): + + def test_trainer_command(self): + out = run() + command = out.split("Run MaxText's trainer with:", 1)[1].strip().splitlines()[0] + argv = shlex.split(command) + self.assertEqual(argv[:4], ["python3", "-u", "-m", "maxtext.trainers.pre_train.train"]) + self.assertIn("run_name=sb-run", argv) + self.assertIn("base_output_directory=gs://bucket/out", argv) + self.assertNotIn("On the cluster", out) + + def test_profiler_after_the_timed_steps(self): + settings = settings_of(run()) + self.assertEqual(settings["steps"], "12") # 2 warm-up + 5 timed + 5 profiled + self.assertEqual(settings["skip_first_n_steps_for_profiler"], "7") + self.assertEqual(settings["profiler_steps"], "5") + # one TPU, one SparseCore and one SparseCore tile, as the MPMD side traces + self.assertEqual( + { + k: settings[k] + for k in ( + "enable_tpu_profiling_options", + "tpu_num_chips_to_profile_per_task", + "tpu_num_sparse_cores_to_trace", + "tpu_num_sparse_core_tiles_to_trace", + ) + }, + { + "enable_tpu_profiling_options": "True", + "tpu_num_chips_to_profile_per_task": "1", + "tpu_num_sparse_cores_to_trace": "1", + "tpu_num_sparse_core_tiles_to_trace": "1", + }, + ) + + def test_gcluster_command(self): + out = run("--cluster=my-cluster", "--project=my-project", "--zone=us-east5-b", "--docker_image=example.com/mt") + lines = out.split("On the cluster:", 1)[1].strip().splitlines() + self.assertEqual( + lines[:3], + [ + "gcluster job config set project my-project", + "gcluster job config set cluster my-cluster", + "gcluster job config set location us-east5-b", + ], + ) + argv = shlex.split("\n".join(lines[3:]).replace("\\\n", " ")) + self.assertEqual(argv[:3], ["gcluster", "job", "submit"]) + options = dict(arg[2:].split("=", 1) for arg in argv[3:]) + self.assertEqual( + {k: options[k] for k in ("name", "image", "compute-type", "topology", "num-slices")}, + { + "name": "sb-run", + "image": "example.com/mt", + "compute-type": "ct5p-hightpu-4t", + "topology": "2x2x4", + "num-slices": "1", + }, + ) + self.assertTrue(options["command"].startswith("python3 -u -m maxtext.trainers.pre_train.train ")) + + def test_default_run_names_differ(self): + """A fixed default made every repeated run (and its workload) collide; the default carries a timestamp.""" + flag_values = flags.FlagValues() + spmd_baseline.define_flags(flag_values) + flag_values(["spmd_baseline", *[f for f in FLAGS if not f.startswith("--run_name")]]) + out = io.StringIO() + with contextlib.redirect_stdout(out): + spmd_baseline.main(["spmd_baseline"], flag_values=flag_values) + self.assertRegex(out.getvalue(), r"run_name=spmd-baseline-\d{10}\b") + + def test_xpk_command(self): + out = run( + "--cluster=my-cluster", + "--project=my-project", + "--zone=us-east5-b", + "--docker_image=example.com/mt", + "--launcher=xpk", + ) + argv = shlex.split(out.split("On the cluster:", 1)[1].replace("\\\n", " ")) + self.assertEqual(argv[:3], ["xpk", "workload", "create"]) + pairs = dict(zip(argv[3::2], argv[4::2])) + self.assertEqual( + {k: pairs[k] for k in ("--cluster", "--project", "--zone", "--tpu-type", "--workload", "--docker-image")}, + { + "--cluster": "my-cluster", + "--project": "my-project", + "--zone": "us-east5-b", + "--tpu-type": "v5p-32", + "--workload": "sb-run", + "--docker-image": "example.com/mt", + }, + ) + self.assertTrue(pairs["--command"].startswith("python3 -u -m maxtext.trainers.pre_train.train ")) + with self.assertRaisesRegex(app.UsageError, "--cluster needs --project, --zone, --docker_image"): + run("--cluster=my-cluster") + + def test_refusals_are_usage_errors_before_any_output(self): + out = io.StringIO() + for extra, error in ( + (("--num_slices=3", "--total_devices=48"), "3 slices and 4 stages must divide one another"), + (("--model_name=no-such-model",), "MaxText model config .*no-such-model.yml' is missing"), + ): + flag_values = flags.FlagValues() + spmd_baseline.define_flags(flag_values) + flag_values(["spmd_baseline", *FLAGS, *extra]) + with self.subTest(extra=extra), self.assertRaisesRegex(app.UsageError, error), contextlib.redirect_stdout(out): + spmd_baseline.main(["spmd_baseline"], flag_values=flag_values) + self.assertEqual(out.getvalue(), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/mpmd_test/train_test.py b/tests/unit/mpmd_test/train_test.py new file mode 100644 index 0000000000..f36f2854a4 --- /dev/null +++ b/tests/unit/mpmd_test/train_test.py @@ -0,0 +1,163 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the trainer's main loop and its NaN stop, end to end on CPU (no Shardy). + +train.main runs with the Pathways-only pieces swapped for the SPMD step: Shardy MPMD's program compiles only on +Pathways. +""" + +import json +import logging +import os +import tempfile +import types +import unittest +from unittest import mock + +from absl import flags +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.partir import train +from maxtext.experimental.mpmd.partir import train_step + +ARGV = [ + "train", + "--model_name=simple", + "--num_layers=2", + "--num_stages=2", + "--emb_dim=64", + "--mlp_dim=128", + "--vocab_size=256", + "--max_target_length=16", + "--per_device_batch_size=2", + "--num_microbatches=2", + "--warmup_steps=1", + "--steps=3", + "--run_name=nan-test", +] + + +def run_main(argv, nan_at=0): + """Runs train.main on `argv` with the compiled step's call `nan_at` (1-based; 0: none) returning a NaN loss. + + Returns: + (what main raised or None, what it logged). + """ + flag_values = flags.FlagValues() + train.define_flags(flag_values) + flag_values(argv) + calls = [0] + real_build = train.runner_lib.build + + def build(hparams, *, mode, **kw): + del mode # the MPMD program compiles only on Pathways: run the SPMD step instead + return real_build(hparams, mode=train_step.ExecutionMode.SPMD, **kw) + + class Lowered: + """Stands in for the lowered MPMD program: compiles the SPMD step instead.""" + + function_named_shardings = types.SimpleNamespace(input_specs=None) + + def __init__(self, fn): + self.fn = fn + + def compile(self): + jitted = jax.jit(self.fn) + + def step(state, batch): + calls[0] += 1 + state, loss = jitted(state, batch) + return state, (jnp.float32(float("nan")) if calls[0] == nan_at else loss) + + return step + + logged = _Collect() + absl_logger = logging.getLogger("absl") + level = absl_logger.level + absl_logger.addHandler(logged) + absl_logger.setLevel(logging.INFO) + raised = None + with ( + mock.patch.object(train.runner_lib, "build", build), + mock.patch.object(train.runner_lib.Runnable, "lower", lambda runnable: Lowered(runnable.train_step)), + mock.patch.object(train.runner_lib, "place_on_stage_meshes", lambda inputs, specs: inputs), + ): + try: + train.main(["train"], flag_values=flag_values) + except SystemExit as error: + raised = error + finally: + absl_logger.removeHandler(logged) + absl_logger.setLevel(level) + return raised, "\n".join(logged.messages) + + +class _Collect(logging.Handler): + """Keeps the messages logged through absl (max_logging).""" + + def __init__(self): + super().__init__(level=logging.INFO) + self.messages = [] + + def emit(self, record): + self.messages.append(record.getMessage()) + + +class TrainMainTest(unittest.TestCase): + + def setUp(self): + super().setUp() + if len(jax.devices("cpu")) < 4: + self.skipTest("needs 4 CPU devices (XLA_FLAGS=--xla_force_host_platform_device_count=4)") + + def test_a_finished_run_prints_its_record(self): + with tempfile.TemporaryDirectory() as tmp: + out_path = os.path.join(tmp, "run.json") + raised, logged = run_main([*ARGV, f"--result_json={out_path}"]) + self.assertIsNone(raised) + with open(out_path, encoding="utf-8") as f: + record = json.load(f) + self.assertEqual((record["run"], record["stages"], record["microbatches"]), ("nan-test", 2, 2)) + self.assertLess(record["loss"], record["loss_first"]) + self.assertIn("Results for nan-test", logged) + self.assertIn("Execution finished successfully.", logged) + + def test_a_nan_in_a_profiled_step_is_numbered_among_all_steps(self): + """1 warm-up and 3 timed steps, then a NaN in the second profiled step: the error record calls it step 6, lists + the losses from step 5, exits with an error, and writes --result_json.""" + with tempfile.TemporaryDirectory() as tmp: + out_path = os.path.join(tmp, "run.json") + argv = [ + *ARGV, + "--enable_profile", + "--profile_steps=2", + f"--profile_dir={os.path.join(tmp, 'xprof')}", + f"--result_json={out_path}", + ] + raised, logged = run_main(argv, nan_at=6) + self.assertIsInstance(raised, SystemExit) + self.assertIn("MPMD training failed", str(raised)) + with open(out_path, encoding="utf-8") as f: + record = json.load(f) + self.assertRegex( + record["error"], r"^non-finite loss: step 6 returned a loss of nan \(losses from step 5: [0-9.e+-]+, nan\)$" + ) + self.assertEqual(record["run"], "nan-test") + self.assertIn("MPMD_RESULT ", logged) + + +if __name__ == "__main__": + unittest.main()