From daf5b955f1b4e882bb2580cbf6ce3c2ec2a2c15d Mon Sep 17 00:00:00 2001 From: NuojCheng Date: Thu, 26 Nov 2026 16:08:52 +0000 Subject: [PATCH] Add an experimental pure-JAX MPMD pipeline with a Pathways mode Add src/maxtext/experimental/mpmd/jax/: MPMD pipeline parallelism for DeepSeek-V3 and the Qwen3.5 family in plain JAX. Each stage is its own set of jitted shard_map programs on its own sub-mesh (FSDP x EP), a stage boundary is a device-to-device copy, and one Python thread replays a fixed schedule. It runs in one process, as multi-controller JAX across hosts and slices, as one Pathways client (each boundary one IFRT CopyArrays, across slices too), and on NVIDIA GPUs. The multi-controller code runs only where jax.process_count() > 1, so never under Pathways, which refuses its flags up front. Schedules: breadth / circular (the default), GPipe, 1F1B, interleaved, and the zero-bubble ZB-H1 and ZB-H2 (--schedule zbh1 / zbh2). These cut each middle chunk's backward program by data dependence into its input-gradient half and its weight-gradient half, which runs later, in the bubbles; --zb-split-last on (off by default) cuts the fused last chunk's program too. On CPU without YNNPACK fusions they give 1F1B's gradients bit for bit; on a TPU, within a measured tolerance. It is a training harness with its own command line (ds_ep_pipeline), not a MaxText trainer. The layer math is a pure-JAX port of each model that the tests hold to MaxText's; the kernels are MaxText's (megablox, ragged sort, Lineage's layers for DeepSeek-V3's batch split) and tokamax's. The package README covers setup, Pathways in docker and on GKE, benchmark results and the tests, which use MaxText's markers and skip on the jaxlib 0.12 XLA:CPU bugs they would trip. pylint skips the two new directories. --- .pre-commit-config.yaml | 2 +- src/maxtext/experimental/mpmd/__init__.py | 15 + src/maxtext/experimental/mpmd/jax/README.md | 327 + src/maxtext/experimental/mpmd/jax/__init__.py | 29 + .../mpmd/jax/deepseek/__init__.py | 15 + .../mpmd/jax/deepseek/attention.py | 396 + .../experimental/mpmd/jax/deepseek/config.py | 341 + .../experimental/mpmd/jax/deepseek/convert.py | 156 + .../experimental/mpmd/jax/deepseek/init.py | 94 + .../experimental/mpmd/jax/deepseek/layers.py | 226 + .../mpmd/jax/deepseek/maxtext_reference.py | 448 + .../experimental/mpmd/jax/deepseek/model.py | 314 + .../experimental/mpmd/jax/deepseek/moe.py | 419 + .../experimental/mpmd/jax/deepseek/rope.py | 143 + .../experimental/mpmd/jax/deepseek/train.py | 350 + src/maxtext/experimental/mpmd/jax/ds_ep.py | 6524 ++++++++++++ .../experimental/mpmd/jax/ds_ep_aot.py | 956 ++ .../experimental/mpmd/jax/ds_ep_aot.sh | 78 + .../experimental/mpmd/jax/ds_ep_lineage.py | 1130 ++ .../experimental/mpmd/jax/ds_ep_multihost.sh | 278 + .../experimental/mpmd/jax/ds_ep_parity.py | 1103 ++ .../experimental/mpmd/jax/ds_ep_pipeline.py | 7137 +++++++++++++ .../experimental/mpmd/jax/ds_ep_progbench.py | 404 + .../experimental/mpmd/jax/ds_ep_run.sh | 91 + .../experimental/mpmd/jax/gpu.xla_flags | 23 + .../experimental/mpmd/jax/gpu_kernels.py | 785 ++ .../mpmd/jax/libtpu_flags/tpu7x.flags | 48 + .../mpmd/jax/libtpu_flags/v5p.flags | 47 + .../jax/libtpu_flags/v5p_fsdp_extra.flags | 14 + .../experimental/mpmd/jax/maxtext_parity.py | 779 ++ .../experimental/mpmd/jax/mem_probe.py | 138 + src/maxtext/experimental/mpmd/jax/pathways.py | 450 + .../experimental/mpmd/jax/profiling.py | 98 + .../experimental/mpmd/jax/qwen35/__init__.py | 61 + .../experimental/mpmd/jax/qwen35/_ops.py | 285 + .../experimental/mpmd/jax/qwen35/attention.py | 153 + .../experimental/mpmd/jax/qwen35/config.py | 610 ++ .../experimental/mpmd/jax/qwen35/convert.py | 138 + .../experimental/mpmd/jax/qwen35/gdn.py | 563 + .../mpmd/jax/qwen35/gdn_triton.py | 978 ++ .../experimental/mpmd/jax/qwen35/init.py | 177 + .../experimental/mpmd/jax/qwen35/layers.py | 59 + .../experimental/mpmd/jax/qwen35/model.py | 251 + .../experimental/mpmd/jax/qwen35/moe.py | 66 + .../experimental/mpmd/jax/qwen35/train.py | 91 + src/maxtext/experimental/mpmd/jax/schedule.py | 1962 ++++ .../experimental/mpmd/jax/sharding_mode.py | 436 + src/maxtext/experimental/mpmd/jax/stage_ad.py | 422 + src/maxtext/experimental/mpmd/jax/testing.py | 522 + src/maxtext/experimental/mpmd/jax/transfer.py | 2653 +++++ src/maxtext/experimental/mpmd/jax/xprof.py | 2162 ++++ .../experimental/mpmd/jax/xprof_align.py | 337 + tests/unit/mpmd_test/cp_test.py | 440 + .../mpmd_test/deepseek_maxtext_parity_test.py | 292 + tests/unit/mpmd_test/deepseek_model_test.py | 509 + tests/unit/mpmd_test/ds_ep_aot_test.py | 1947 ++++ .../mpmd_test/ds_ep_lineage_pipeline_test.py | 319 + tests/unit/mpmd_test/ds_ep_lineage_test.py | 1934 ++++ tests/unit/mpmd_test/ds_ep_qwen_test.py | 2256 ++++ tests/unit/mpmd_test/ds_ep_test.py | 9046 +++++++++++++++++ tests/unit/mpmd_test/exact_dsv3_test.py | 932 ++ tests/unit/mpmd_test/gdn_kernels_test.py | 534 + tests/unit/mpmd_test/gpu_kernels_test.py | 541 + tests/unit/mpmd_test/gpu_port_test.py | 3848 +++++++ tests/unit/mpmd_test/maxtext_parity_test.py | 1341 +++ tests/unit/mpmd_test/multihost_test.py | 1072 ++ tests/unit/mpmd_test/pathways_test.py | 1873 ++++ tests/unit/mpmd_test/profiling_test.py | 96 + tests/unit/mpmd_test/qwen35_explicit_test.py | 439 + .../mpmd_test/qwen35_maxtext_parity_test.py | 825 ++ tests/unit/mpmd_test/qwen35_model_test.py | 1466 +++ tests/unit/mpmd_test/ragged_buffer_test.py | 304 + tests/unit/mpmd_test/relay_test.py | 1405 +++ tests/unit/mpmd_test/schedule_test.py | 1528 +++ tests/unit/mpmd_test/sharding_mode_test.py | 468 + tests/unit/mpmd_test/slices_layout_test.py | 1762 ++++ tests/unit/mpmd_test/stage_ad_test.py | 398 + tests/unit/mpmd_test/testing_test.py | 379 + .../unit/mpmd_test/transfer_channels_test.py | 350 + tests/unit/mpmd_test/transfer_test.py | 583 ++ tests/unit/mpmd_test/xprof_align_test.py | 324 + tests/unit/mpmd_test/xprof_gpu_test.py | 616 ++ tests/unit/mpmd_test/xprof_pb_test.py | 234 + tests/unit/mpmd_test/xprof_test.py | 1453 +++ 84 files changed, 74797 insertions(+), 1 deletion(-) create mode 100644 src/maxtext/experimental/mpmd/__init__.py create mode 100644 src/maxtext/experimental/mpmd/jax/README.md create mode 100644 src/maxtext/experimental/mpmd/jax/__init__.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/__init__.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/attention.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/config.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/convert.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/init.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/layers.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/maxtext_reference.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/model.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/moe.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/rope.py create mode 100644 src/maxtext/experimental/mpmd/jax/deepseek/train.py create mode 100644 src/maxtext/experimental/mpmd/jax/ds_ep.py create mode 100644 src/maxtext/experimental/mpmd/jax/ds_ep_aot.py create mode 100755 src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh create mode 100644 src/maxtext/experimental/mpmd/jax/ds_ep_lineage.py create mode 100755 src/maxtext/experimental/mpmd/jax/ds_ep_multihost.sh create mode 100644 src/maxtext/experimental/mpmd/jax/ds_ep_parity.py create mode 100644 src/maxtext/experimental/mpmd/jax/ds_ep_pipeline.py create mode 100644 src/maxtext/experimental/mpmd/jax/ds_ep_progbench.py create mode 100755 src/maxtext/experimental/mpmd/jax/ds_ep_run.sh create mode 100644 src/maxtext/experimental/mpmd/jax/gpu.xla_flags create mode 100644 src/maxtext/experimental/mpmd/jax/gpu_kernels.py create mode 100644 src/maxtext/experimental/mpmd/jax/libtpu_flags/tpu7x.flags create mode 100644 src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p.flags create mode 100644 src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p_fsdp_extra.flags create mode 100644 src/maxtext/experimental/mpmd/jax/maxtext_parity.py create mode 100644 src/maxtext/experimental/mpmd/jax/mem_probe.py create mode 100644 src/maxtext/experimental/mpmd/jax/pathways.py create mode 100644 src/maxtext/experimental/mpmd/jax/profiling.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/__init__.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/_ops.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/attention.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/config.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/convert.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/gdn.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/gdn_triton.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/init.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/layers.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/model.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/moe.py create mode 100644 src/maxtext/experimental/mpmd/jax/qwen35/train.py create mode 100644 src/maxtext/experimental/mpmd/jax/schedule.py create mode 100644 src/maxtext/experimental/mpmd/jax/sharding_mode.py create mode 100644 src/maxtext/experimental/mpmd/jax/stage_ad.py create mode 100644 src/maxtext/experimental/mpmd/jax/testing.py create mode 100644 src/maxtext/experimental/mpmd/jax/transfer.py create mode 100644 src/maxtext/experimental/mpmd/jax/xprof.py create mode 100644 src/maxtext/experimental/mpmd/jax/xprof_align.py create mode 100644 tests/unit/mpmd_test/cp_test.py create mode 100644 tests/unit/mpmd_test/deepseek_maxtext_parity_test.py create mode 100644 tests/unit/mpmd_test/deepseek_model_test.py create mode 100644 tests/unit/mpmd_test/ds_ep_aot_test.py create mode 100644 tests/unit/mpmd_test/ds_ep_lineage_pipeline_test.py create mode 100644 tests/unit/mpmd_test/ds_ep_lineage_test.py create mode 100644 tests/unit/mpmd_test/ds_ep_qwen_test.py create mode 100644 tests/unit/mpmd_test/ds_ep_test.py create mode 100644 tests/unit/mpmd_test/exact_dsv3_test.py create mode 100644 tests/unit/mpmd_test/gdn_kernels_test.py create mode 100644 tests/unit/mpmd_test/gpu_kernels_test.py create mode 100644 tests/unit/mpmd_test/gpu_port_test.py create mode 100644 tests/unit/mpmd_test/maxtext_parity_test.py create mode 100644 tests/unit/mpmd_test/multihost_test.py create mode 100644 tests/unit/mpmd_test/pathways_test.py create mode 100644 tests/unit/mpmd_test/profiling_test.py create mode 100644 tests/unit/mpmd_test/qwen35_explicit_test.py create mode 100644 tests/unit/mpmd_test/qwen35_maxtext_parity_test.py create mode 100644 tests/unit/mpmd_test/qwen35_model_test.py create mode 100644 tests/unit/mpmd_test/ragged_buffer_test.py create mode 100644 tests/unit/mpmd_test/relay_test.py create mode 100644 tests/unit/mpmd_test/schedule_test.py create mode 100644 tests/unit/mpmd_test/sharding_mode_test.py create mode 100644 tests/unit/mpmd_test/slices_layout_test.py create mode 100644 tests/unit/mpmd_test/stage_ad_test.py create mode 100644 tests/unit/mpmd_test/testing_test.py create mode 100644 tests/unit/mpmd_test/transfer_channels_test.py create mode 100644 tests/unit/mpmd_test/transfer_test.py create mode 100644 tests/unit/mpmd_test/xprof_align_test.py create mode 100644 tests/unit/mpmd_test/xprof_gpu_test.py create mode 100644 tests/unit/mpmd_test/xprof_pb_test.py create mode 100644 tests/unit/mpmd_test/xprof_test.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b1c4a52c34..8b55b925db 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,7 +30,7 @@ repos: args: - '--disable=R0401,R0917,W0201,W0613' - "--ignore-patterns='.pytype,.*pyi$'" - - '--ignore-paths=src/maxtext/input_pipeline/protos|src/maxtext/eval/simple_evals_template|src/maxtext/experimental/lineage' + - '--ignore-paths=src/maxtext/input_pipeline/protos|src/maxtext/eval/simple_evals_template|src/maxtext/experimental/lineage|src/maxtext/experimental/mpmd/jax|tests/unit/mpmd_test/(cp|deepseek_maxtext_parity|deepseek_model|ds_ep_aot|ds_ep_lineage_pipeline|ds_ep_lineage|ds_ep_qwen|ds_ep|exact_dsv3|gdn_kernels|gpu_kernels|gpu_port|maxtext_parity|multihost|pathways|profiling|qwen35_explicit|qwen35_maxtext_parity|qwen35_model|ragged_buffer|relay|schedule|sharding_mode|slices_layout|stage_ad|testing|transfer_channels|transfer|xprof_align|xprof_gpu|xprof_pb|xprof)_test.py' # - repo: https://github.com/google/pytype # rev: 2024.10.11 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/jax/README.md b/src/maxtext/experimental/mpmd/jax/README.md new file mode 100644 index 0000000000..c68c76c9f6 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/README.md @@ -0,0 +1,327 @@ + + +# MPMD pipeline parallelism in pure JAX (experimental) + +MPMD pipeline parallelism for mixture-of-experts decoders (DeepSeek-V3; the Qwen3.5 family, Qwen3.8-2.4T-A95B +included) in plain JAX, with no MPMD partitioner: each stage is its own set of jitted `shard_map` programs on its +own sub-mesh (FSDP x EP, the FSDP collectives folded into the microbatch programs), a stage boundary is a +device-to-device copy, and one Python thread replays a fixed schedule without blocking. It runs on TPU in one +process, as multi-controller JAX across hosts and slices (`--distributed`), or as one Pathways client +(`JAX_PLATFORMS=proxy`), and on NVIDIA GPUs (`--platform gpu`, one process a host). + +**Status: experimental.** A training harness with its own command line (`ds_ep_pipeline --help`), not a MaxText +trainer: synthetic data (its own, or MaxText's with `--data maxtext`) or a token file (`--data npy:PATH`), a constant +learning rate, no checkpointing. Its layer math is a pure-JAX port of each model that the tests hold to MaxText's; its +kernels are MaxText's (megablox, the ring of experts, Lineage's layers for DeepSeek-V3's batch split) and tokamax's +splash attention. Run its modules as `python3 -m maxtext.experimental.mpmd.jax.`, never by file path (the +package is named `jax`). + +## Environment setup + +| component | version | notes | +|---|---|---| +| MaxText | `c034bc02f` (main, 2026-11-25) plus this package | from source, `.[tpu]` | +| Python | 3.12 | | +| jax / jaxlib | 0.12.0.1 | | +| libtpu | 0.0.51 | MaxText's lowest; the benchmarks below ran on 0.0.50.1 (jax 0.12.0.1's own pin), and the TPU-topology (AOT) tests have the same outcomes on both | +| tokamax | 0.0.18 | the benchmarks' version, pinned below (MaxText's lowest, 0.0.17, is what its CI runs: the CPU tests pass on both) | +| pathwaysutils | 0.1.14 | Pathways only | +| Pathways server, proxy | `20261124-jax_0.12.0.1` (GKE), `20261117-jax_0.12.0.1` (local) | the image's jax must be the client's; plain `jax.jit`, which this is, also runs on builds after 2026-11-17 (Shardy MPMD does not) | +| typeguard | 2.13.3 | only for DeepSeek-V3's batch split on Lineage's layers (not in MaxText's requirements; 4.6.1 fails to import Lineage) | +| triton, jax-triton | 3.9.0, 0.5.0 | only for the GPU Triton kernels | + +```bash +git clone https://github.com/AI-Hypercomputer/maxtext.git && cd maxtext # a checkout with this package +uv venv --python 3.12 --seed venv && source venv/bin/activate +uv pip install -e .[tpu] tokamax==0.0.18 --resolution=lowest && install_tpu_pre_train_extra_deps +uv pip install typeguard==2.13.3 # optional: DeepSeek-V3's batch split on Lineage's layers +``` + +Commands run from the repository root. The launchers (`ds_ep_run.sh`, `ds_ep_multihost.sh`, `ds_ep_aot.sh`) build +`LIBTPU_INIT_ARGS` from `libtpu_flags/$MPMD_FLAG_SET.flags` (`tpu7x`, the default: 30 flags, among them the 64 MiB +scoped VMEM limit the megablox tiles need; `v5p`; `none`) plus `--xla_max_concurrent_async_collective_permutes=64` +and `EXTRA_LIBTPU_INIT_ARGS`; `LIBTPU_INIT_ARGS_OVERRIDE` replaces the set. + +### Pathways + +One client process drives every TPU through the IFRT proxy, so the pipeline takes its one-process path: every stage +is local and each boundary is one IFRT `CopyArrays`, across slices too; `--layout slices` puts one stage on each +slice, or k as strips of whole chips at k times the slices (two stages a TPU7x-4x4x4 are its z-halves). The +Pathways servers compile, so the libtpu flags (`python3 -m maxtext.experimental.mpmd.jax.pathways flags tpu7x` +prints the set's 31 on one line) go to the proxy, the resource manager and the workers, and the same set to the +client's `LIBTPU_INIT_ARGS`, which the planner reads. + +The multi-controller code (one process a host, `--distributed`) runs only where `jax.process_count() > 1` +(`pathways.multi_controller()`), so never under Pathways, whose one client is the only process. (A one-host run skips it +too, but for what it asks for: `--distributed` still starts `jax.distributed`, and `ds_ep_aot` still checks a multi-host +target's hosts, unless `--pathways` plans one Pathways client's run.) Under Pathways there is no walk over other +processes' boundary copies, no key-value agreement or barrier, no relay, xfer or cross-process copy, no per-process +record or trace. Its flags are refused there before the backend starts, each naming what to use instead: +`--distributed`, `--transport relay` and `xfer`, `--json-procs` and `--profile-procs` other than `leaders` (Pathways +traces `--profile-hosts` worker hosts), and `--norm-reduce allreduce`; `ds_ep_multihost.sh` starts nothing. Its +environment variables are not refused, since a cluster may set them for every job. `--max-ahead` defaults to 2 there, +since nothing else bounds how far the client runs ahead; the wait for finished steps runs beside the dispatch, so the +bound does not slow it. + +**In docker on one TPU VM** (as a GKE Pathways job's pods run them; a TPU7x-8 is `tpu7x:2x2x1`, a v6e-4 +`tpuv6e:2x2`). One client may hold the proxy at a time, and the worker restarts after each one disconnects: + +```bash +IMG=us-docker.pkg.dev/cloud-tpu-v2-images/pathways TAG=20261117-jax_0.12.0.1 GCS=gs:///pathways-scratch +FLAGS=$(python3 -m maxtext.experimental.mpmd.jax.pathways flags tpu7x) # unquoted below: one argument a flag +sudo docker run -d --name pw-rm --net=host -e TPU_SKIP_MDS_QUERY=true -e JOBSET_NAME=pw \ + -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=tpu7x:2x2x1 $FLAGS +sudo docker run -d --name pw-worker --net=host --privileged --restart=on-failure -e XCLOUD_ENVIRONMENT=GCP \ + -e MEGASCALE_GRPC_ENABLE_XOR_TRACER=false -e MEGASCALE_NUM_SLICES=1 -e MEGASCALE_SLICE_ID=0 -e JOBSET_NAME=pw \ + -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 +sudo docker run -d --name pw-proxy --net=host -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 +# ready when the resource manager logs "1/1 Pathways Slices Now Ready" and the proxy "IFRT proxy server started" +sudo docker rm -f pw-rm pw-worker pw-proxy # when done: frees the chips +``` + +**On GKE**, follow [MaxText's Pathways guide](../../../../../docs/run_maxtext/run_maxtext_via_pathways.md) (Cluster +Toolkit, an image holding this tree, `gcluster job submit --pathways`), with the flag set on the three Pathways +containers (`"$FLAGS"`, quoted: one argument an option) and their images at the client's jax. The run under +[Benchmark results](#benchmark-results) went through xpk 1.16.0 as the last command does; the `gcluster` one has not +been submitted, and gcluster v1.108.0 and v1.109.0 rerun a finished Pathways job and end it Failed (cluster-toolkit +PR #6739, merged to its develop branch on 2026-11-25): use a gcluster built with that fix, or xpk. Expect a cold +compile of 25-30 minutes with no client output (Pathways then caches the programs under `--pathways-gcs-location`); +`--profile` takes only a `gs://` directory. + +```bash +PW=us-docker.pkg.dev/cloud-tpu-v2-images/pathways TAG=20261124-jax_0.12.0.1 +FLAGS="$(python3 -m maxtext.experimental.mpmd.jax.pathways flags tpu7x)" +CMD="JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000 MPMD_PATHWAYS_IMAGE=$TAG LIBTPU_INIT_ARGS='$FLAGS' \ + python3 -m maxtext.experimental.mpmd.jax.ds_ep_pipeline --layout slices --stages 2 --vv 2 --fsdp 16 --ep 8 \ + --layers 8 --experts 256 --vocab 129280 --gbs 1024 --mb 8 --embed gather --acc-dtype bfloat16 --remat-last \ + --ragged-buffer-factor 2 --expert-weights sliced --bench --steps 20 --json gs:///run.json" +gcluster job submit --pathways --name=${RUN_NAME?} --image=${DOCKER_IMAGE?} --compute-type=tpu7x-standard-4t \ + --topology=4x4x4 --num-slices=2 --pathways-gcs-location=gs:///pathways-scratch --command="$CMD" \ + --pathways-server-image=$PW/server:$TAG --pathways-server-args="$FLAGS" --pathways-worker-image=$PW/server:$TAG \ + --pathways-worker-args="$FLAGS" --pathways-proxy-server-image=$PW/proxy_server:$TAG --pathways-proxy-args="$FLAGS" +xpk workload create-pathways --cluster=${CLUSTER?} --workload=${RUN_NAME?} --docker-image=${DOCKER_IMAGE?} \ + --tpu-type=tpu7x-4x4x4 --num-slices=2 --pathways-gcs-location=gs:///pathways-scratch --command="$CMD" \ + --server-image=$PW/server:$TAG --custom-pathways-server-args="$FLAGS" --custom-pathways-worker-args="$FLAGS" \ + --proxy-server-image=$PW/proxy_server:$TAG --custom-pathways-proxy-server-args="$FLAGS" +``` + +## Quick start + +```bash +# 1. CPU dry run: build the pipeline and print its plan, compiling nothing (seconds) +JAX_PLATFORMS=cpu XLA_FLAGS=--xla_force_host_platform_device_count=8 \ + bash src/maxtext/experimental/mpmd/jax/ds_ep_run.sh --stages 2 --vv 2 --fsdp 1 --ep 2 --layers 4 --experts 16 \ + --gbs 16 --mb 8 --dry-run + +# 2. One TPU7x-8 (McJAX): 4 MoE layers at DeepSeek-V3's per-layer dimensions, 128 experts, PP=2 x FSDP 2 x EP 2 +bash src/maxtext/experimental/mpmd/jax/ds_ep_run.sh --bench + +# 3. Pathways, the local proxy above: two stages on two fake slices of one TPU7x-8 +TAG=20261117-jax_0.12.0.1 FLAGS="$(python3 -m maxtext.experimental.mpmd.jax.pathways flags tpu7x)" +JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000 MPMD_PATHWAYS_IMAGE=$TAG LIBTPU_INIT_ARGS="$FLAGS" \ + MPMD_FAKE_SLICES=2 python3 -m maxtext.experimental.mpmd.jax.ds_ep_pipeline --layout slices --stages 2 --vv 2 \ + --fsdp 2 --ep 2 --layers 4 --experts 16 --vocab 129280 --gbs 16 --mb 4 --embed gather --acc-dtype bfloat16 \ + --remat-last --ragged-buffer-factor 2 --bench --steps 20 --json gs:///run.json + +# 4. Multi-controller JAX on every host of a 2 x TPU7x-4x4x4 job: across slices the relay (or ppermute), as jax's +# native cross-slice copy hangs +RUN_DIR=gs:///run bash src/maxtext/experimental/mpmd/jax/ds_ep_multihost.sh --layout slices --stages 2 \ + --vv 2 --fsdp 16 --ep 8 --layers 8 --experts 256 --vocab 129280 --gbs 1024 --mb 8 --embed gather \ + --acc-dtype bfloat16 --remat-last --ragged-buffer-factor 2 --expert-weights sliced --transport relay --bench +# --model qwen3.8-2.4t-a95b switches to that model's dimensions; --layers 61 --dense-layers 3 --mlp 18432 +# --experts 256 --vocab 129280 is the whole DeepSeek-V3 +``` + +## Zero-bubble schedules (ZB-H1 / ZB-H2) + +`--schedule zbh1` / `zbh2` (at `--vv 1`) run the zero-bubble schedules of Qi et al.: each middle chunk's backward is +cut into I, the input gradient with the recompute it needs, and W, the weight gradients, which run later, in the +bubbles. The cut is the chunk's own backward program split by data dependence (`stage_ad.split_jaxpr`), so no model +code changes. Chunk 0's backward stays whole, and so does the fused last chunk unless `--zb-split-last on` (off by +default) cuts it too: its F runs the forward, the head, the loss and the input gradient (AI), its W its layers' weight +gradients. Turn it on at two stages, where nothing else splits (without it zbh1 is 1F1B's order). On one TPU7x-8 it +was faster in all 22 pairs measured (0.7-3.3%, mean 1.5%), but at G4 below slower: zbh2 3448.8 ms against 3332.4 +without it (+3.5%). ZB-H1 keeps 1F1B's residual sets and ZB-H2 about twice them, and each split stage holds up to +`--zb-wbuf-cap` (default 1; 0 for no cap) pending W buffers on top: a microbatch's crossing set and what its W reads, +7.25 GiB a device for two DeepSeek-V3 MoE layers at 4096 tokens a device (a run's is in the summary's `split backward` +line). Each schedule is the fastest of its candidates in simulation under the program costs (`--costs`); the run warns +where its order simulates slower than 1F1B's. + +```bash +# L4 below, zbh2 on one TPU7x-8 (McJAX); through the local Pathways proxy, the same flags with quick start 3's env +bash src/maxtext/experimental/mpmd/jax/ds_ep_run.sh --stages 4 --vv 1 --fsdp 1 --ep 2 --layers 8 --experts 64 \ + --gbs 16 --mb 8 --schedule zbh2 --zb-split-last on --bench # --zb-wbuf-cap 2: two W buffers a stage +``` + +**Correctness.** On CPU (XLA:CPU's YNNPACK fusions off) zbh1 and zbh2 give 1F1B's losses, gradients and updates bit +for bit: the halves run the fused programs' operations, and each chunk's W's add its gradients in microbatch order. +MaxText's CPU CI runs with the fusions on, which compile some halves otherwise: there those pipeline checks skip, the +three-stage fp32 ones hold zbh1 / zbh2 to a few ulps, and the split checks allow fp32 leaves 4 ulps (its runners gave +fp32 experts' gradients on XLA's ops up to 2 ulps apart, fusions off). On a TPU they do not, as XLA:TPU compiles +each half by itself. The tests hold it to a contract measured on a TPU7x-8 (McJAX and local Pathways): every leaf +of a split chunk within 3% of the fused program's (bit for bit with excess precision off, but MLA's `q_norm` / +`kv_norm` scales); warmup losses within 2e-3 and gradient norms within 2e-2 of 1F1B's (seen: 4.0e-4 and 6.8e-3 on +the tests' TINY, 3.4e-5 and 8.2e-4 at the widths below); zbh2 zbh1's bit for bit. + +**Results**, ms a step (run-ahead mean of 20; against 1F1B on the same backend). DeepSeek-V3 per-layer widths, +megablox, bf16, one 4096-token row a device a microbatch: +- L4 `--stages 4 --vv 1 --fsdp 1 --ep 2 --layers 8 --experts 64`, L2 `--stages 2 --vv 1 --fsdp 2 --ep 2 --layers 4`, + Qwen: L4 at Qwen3.8-2.4T-A95B's widths with 32 experts; one TPU7x-8 (2026-11-27; jax 0.12.0.1, libtpu 0.0.50.1), + McJAX on this tree, local Pathways (image `20261117-jax_0.12.0.1`) on it before the McJAX pacing below, which + Pathways does not use, and before Pathways' default of at most 2 steps ahead (this tree's L4 at M=8 came within + 0.1%). +- G4 and G2: 2 x TPU7x-4x4x4 on GKE, Pathways image `20261124-jax_0.12.0.1`, the widths of the GKE run under + [Benchmark results](#benchmark-results) with `--layout slices --gbs 1024`; G4 `--stages 4 --vv 1 --fsdp 8 --ep 8 + --mb 16` (2026-11-28; one job, evicted twice: 1F1B ran in its first client session, breadth and zbh2 with the split + in its second, the rest in its third; zbh2 without it repeats an earlier job's 3338.6 within 0.2%), G2 + `--stages 2 --vv 1 --fsdp 16 --ep 8 --mb 8` (2026-11-27). +- `--vv 2` breadth: the fastest schedule without the split on the TPU7x-8 (G2's: the GKE run under Benchmark results). +- split last: `--zb-split-last` in the zero-bubble columns (G2 ran before it existed). + +| run | M | split last | 1F1B | zbh1 | zbh2 | zbh2 `--zb-wbuf-cap 2` | `--vv 2` breadth | +|---|---|---|---|---|---|---|---| +| L4, McJAX | 8 | on | 1337.5 | 1262.0 (−5.6%) | 1230.6 (−8.0%) | 1205.4 (−9.9%) | 1157.3 (−13.5%) | +| L4, Pathways | 8 | on | 1441.2 | 1369.9 (−4.9%) | 1332.9 (−7.5%) | 1306.7 (−9.3%) | 1254.9 (−12.9%) | +| L4, McJAX | 16 | on | 2329.1 | 2248.4 (−3.5%) | 2216.7 (−4.8%) | 2200.3 (−5.5%) | 2118.2 (−9.1%) | +| L4, Pathways | 16 | on | 2501.4 | 2444.7 (−2.3%) | 2405.9 (−3.8%) | 2379.6 (−4.9%) | | +| L2, McJAX | 8 | on | 1388.3 | 1342.4 (−3.3%) | 1302.2 (−6.2%) | | 1332.2 (−4.0%) | +| L2, Pathways | 8 | on | 1459.4 | 1410.8 (−3.3%) | 1367.2 (−6.3%) | 1367.6 (−6.3%) | 1422.5 (−2.5%) | +| Qwen, McJAX | 8 | on | 2492.3 | 2340.6 (−6.1%) | 2228.4 (−10.6%) | | | +| Qwen, Pathways | 8 | on | 2569.1 | 2419.4 (−5.8%) | 2368.2 (−7.8%) | | | +| G4, GKE | 16 | on | 3621.7 | 3477.9 (−4.0%) | 3448.8 (−4.8%) | 3422.4 (−5.5%) | 3626.9 (+0.1%) | +| G4, GKE | 16 | off | | | 3332.4 (−8.0%) | | | +| G2, GKE | 8 | off | 3227.6 | 3257.6 (+0.9%: 1F1B's order) | | | 2943.2 (−8.8%) | + +On the TPU7x-8 at four stages `--vv 2` breadth stays ahead of every zero-bubble order; at two, zbh2 passes it. At G4 +breadth gains nothing over 1F1B, and zbh2 without `--zb-split-last` is the fastest run measured there. The split last +chunk puts W buffers on the last stage too (L4 McJAX: its peak 66.1 GiB, 51.7 without it, 79.9 under 1F1B; ahead of +time G4 41.1 GiB on its last stage, 33.7 without it). +Measured (`xprof costs`), a split chunk's I + W is 3.6-4.5% above its B at DeepSeek-V3 widths and the split last +chunk's AI + W 4.5-6.3% above its A (Qwen: within 1%), so with enough microbatches the split's overhead outgrows the +bubble it fills. + +**On a TPU VM's own client (McJAX)** a program's outputs are allocated when the one dispatch thread issues it, and the +loop runs ahead of the chips. Unpaced, the W buffers of I's issued early filled the split stages' HBM whatever +`--zb-wbuf-cap` said (87.5 of 94.7 GiB at L4), and a split stage's last W sent libtpu into defragmenting, holding +every stage's dispatch 0.6-0.7 s a step: L4's zbh1 / zbh2 ran about 2% / 4.5% under 1F1B, against the 4.0% / 6.3% +they simulate. So the loop issues an I (and a split last chunk's AI) only once its chunk's previous one has +finished, and each stage's trailing W's last; Pathways, whose client issues asynchronously, is not paced. Dispatch is +still one thread: where a stage's own working set leaves its HBM short, its waits hold up every stage, so leave the +split stages headroom (fewer layers a stage, shorter microbatches) or run on Pathways. + +## Benchmark results + +Step times are the mean of run-ahead steps after warm-up; TFLOP/s per device by MaxText's accounting. This port's +numbers below were measured on MaxText `4b5b24c92`; on `c034bc02f` quick start 2 gives the same losses bit for bit +and the same step time (1333 ms). + +**Pathways against multi-controller JAX, 2 x TPU7x-4x4x4 on GKE** (2026-11-26). 8 DeepSeek-V3 MoE layers (256 +experts top-8, random routing), vocab 129280, seq 4096, GBS 1024 in 8 microbatches; PP=2 with one stage a slice, +FSDP 16 x EP 8, V=2 circular, bf16 weights / accumulation / reduce-scatters; 93.9B parameters (the GKE command +above). Pathways: this port, image `20261124-jax_0.12.0.1` with the 31 `tpu7x` flags (client jax 0.12.0.1, libtpu +0.0.50.1, tokamax 0.0.18). McJAX: the pre-port implementation (unpublished), 2026-10-22, one process a host with the +host relay (jax 0.11.1, libtpu 0.0.46, tokamax 0.0.12). + +| | Pathways, `--transport native` | McJAX, `--transport relay` (pre-port) | +|---|---|---| +| step, run-ahead mean of 20 | **2943.2 ms** (2.9% longer), 209.8 TFLOP/s/device | **2859 ms**, 216.0 TFLOP/s/device | +| step, blocked median of 20 | 2947.2 ms | 2861 ms | +| a boundary crossing, 58.7 MB a device | 41-51 ms (isolated copy: 44.6 slice 0 to 1, 40.7 back, 51.4 both at once) | 50 ms (trace median) | +| warm-up losses | 13.2037582 / 13.1034050 / 13.0033779 | 13.2037678 / 13.1033659 / 13.0034189 | +| compile; init | 40 programs in 509 s, ~25 cached (cold ~25-30 min, at the head pod's 8-thread compile service); 114.8 s | 19 programs (stage 1) in 99 s; 52.4 s | + +**Cross-slice copies under Pathways, 2 x TPU7x-4x4x4** (image `20261124-jax_0.12.0.1`, 2026-11-25 and 26): one client +moved 128 devices' shards to the other slice exactly, device to device, and programs on the two slices overlapped. A +small crossing in a dependent chain took ~1.5 ms (0.26 ms of it dispatch); 1 GiB (8 MiB a device) 14.7 ms blocked and +139 GB/s back to back by the batched copy (`device_put`: 17.4 ms, 119 GB/s); the run above's 7.5 GB boundary +40.7-44.6 ms blocked (median), 211-254 GB/s back to back; 1 GiB inside one slice (64 to 64 devices) 344-381 GB/s back +to back. + +**One TPU7x-8**, this port (2026-11-26; jax 0.12.0.1, libtpu 0.0.50.1, tokamax 0.0.18): quick start 2 (McJAX) ran at +1334 ms a step, 214.3 TFLOP/s/device, peak HBM 77.0-79.5 GiB (23.95B parameters; 40 programs compiled in 161 s); quick +start 3 (local Pathways, image `20261117-jax_0.12.0.1`, flags on the servers) at 734 ms, 240.9 TFLOP/s/device, and +with `--expert-weights sliced` at 732 ms native against 1145 ms with `--transport ppermute`, the same losses. On the +tests' TINY pipelines (precompiled, `--bench --steps 20`; 2026-11-25, the pre-port implementation, whose programs this +port reproduces bit for bit) a Pathways step (image `20261124`) took 10.03 ms against McJAX's 11.75 at S=2 (two fake +slices of FSDP 2 x EP 2) and 21.20 against 27.62 ms at S=4 (FSDP 2). Such steps are dispatch-bound (a call costs +~80-140 us through the proxy whatever its devices, ~50 us a device on McJAX), so at S=8 Pathways trailed, 75-100 +against 49-53 ms a step (measured on the code before its Pathways mode). + +**Numerics.** Pathways does not reproduce McJAX bit for bit: the client lowers the same programs (every hash +matches), but the servers compile them with their own XLA and libtpu, a few ulps apart. Over TINY's three warm-up +steps the losses differ by up to 5.5e-4 relative at S=2 and 2.0e-3 at S=4 (gradient norms 1.6e-2 and 2.8e-2); at the +GKE size above, against the McJAX relay run, losses 3.2e-6 and gradient norms 3.3e-5. Each image repeats itself bit +for bit, `native` and `ppermute` boundaries alike. + +**Earlier results**, from the pre-port implementation (unpublished): + +| result | hardware | date | +|---|---|---| +| Against MaxText's SPMD pipeline, 4 DeepSeek-V3 MoE layers, PP=2 x FSDP 2 x EP 2: 1603 against 2668 ms a step (1.66x; 1.52x at equal FLOPs) | 1 x TPU7x-8 | 2026-09 | +| The whole DeepSeek-V3 (671B), PP=8 one stage a slice, against MaxText's DP over DCN: 1.43x at GBS 1024 (8515 against 12150 ms), 1.17x at 2048 | 8 x TPU7x-4x4x4 | 2026-10-25 | +| With 1024 devices a slice the order reverses: MaxText's DP over DCN beat PP=4 over DCN on the whole DeepSeek-V3 (6746 against 8076 ms, 1.20x) and Qwen3.8-2.4T-A95B (20069 against 26499 ms, 1.32x), one 4096-token sequence a device | 4 x TPU7x-8x8x8 | 2026-11-17 | +| Qwen3.8-2.4T-A95B, PP=8: all 92 layers fit (AOT, 56.6-78.8 GiB of 94.74); 8 layers trained at 5054 ms a step | 8 x TPU7x-4x4x4 | 2026-10-25 | +| Batch split, interleaved 1F1B, PP over RDMA: whole DeepSeek-V3 2374 tokens/s/device (1.19x DP on the same nodes), whole Qwen3.8-2.4T 869 | 64 / 188 GB200 | 2026-11-09 to 11 | + +## Tests + +The tests are in `tests/unit/mpmd_test/` (beside the partir package's, which the commands below also run where +that package is in the tree) and use MaxText's markers only. MaxText's `tests/conftest.py` +marks every test without `tpu_only` / `gpu_only` as `cpu_only`, skipped on accelerators: on a TPU VM run those with +`JAX_PLATFORMS=cpu`. A test that needs more devices than jax has skips, naming the count. + +```bash +# What MaxText's cpu-unit job runs on this pull request (4 fake CPU devices, scheduled_only tests included) +XLA_FLAGS=--xla_force_host_platform_device_count=4 python3 -m pytest -n 8 \ + -m 'cpu_only and not post_training and not integration_test' tests/unit/mpmd_test +# The fast tier on 8 devices, 4-7 minutes on a 32-core machine +JAX_PLATFORMS=cpu XLA_FLAGS=--xla_force_host_platform_device_count=8 python3 -m pytest -n 8 --dist loadfile \ + -m 'not scheduled_only and not tpu_only and not gpu_only' tests/unit/mpmd_test +# By hand, what no CI job runs on CPU: the 8-device tests, the slow checks (those alone ~2 h of test time) and the +# tests that start several JAX processes (multi-controller JAX over local CPU processes) +JAX_PLATFORMS=cpu XLA_FLAGS=--xla_force_host_platform_device_count=8 MAXTEXT_MPMD_SLOW_TESTS=1 \ + MAXTEXT_MPMD_MULTIHOST_TESTS=1 \ + python3 -m pytest -n 8 -m 'not tpu_only and not gpu_only' tests/unit/mpmd_test +# On TPUs, a TPU VM's own client; on Pathways JAX_PLATFORMS=proxy JAX_BACKEND_TARGET=grpc://127.0.0.1:29000 instead +# (a pytest process of its own: one client per proxy) +JAX_PLATFORMS=tpu MAXTEXT_MPMD_REQUIRE_TPU=1 \ + python3 -m pytest tests/unit/mpmd_test/pathways_test.py -k OnTpu +``` + +| MaxText CI job | what runs here | +|---|---| +| cpu-unit: 4 CPU devices, libtpu installed, `JAX_PLATFORMS` unset | every test but the `tpu_only` and `gpu_only` ones; `scheduled_only` ones nightly, and on a pull request that adds or changes them (this one: all 1190, of which 934 pass and 256 skip, in 24-29 minutes with 8 workers on a replica of its 32-core runner; the tests that start several JAX processes skip unless `MAXTEXT_MPMD_MULTIHOST_TESTS=1`, as they need more memory than a CI worker running other test modules has) | +| tpu-unit (v6e-4); tpu7x-unit (tpu7x-8, on a pull request only the tests it touches); TPU Pathways unit (v6e-4 through the proxy) | the 18 `tpu_only` tests: `pathways_test.OnTpu` runs (one slice of 4n devices: two stages of FSDP n x EP 2, and a skip on a job of several slices; its four-stage zero-bubble test needs 8), its two-stage split-last test and `SplitBackwardOnTpu` (`scheduled_only`) nightly; the 12 Lineage checks skip, as MaxText's TPU images have no typeguard (with typeguard 2.13.3, `MAXTEXT_MPMD_REQUIRE_LINEAGE=1 JAX_PLATFORMS=tpu python3 -m pytest -m tpu_only tests/unit/mpmd_test/ds_ep_lineage_test.py tests/unit/mpmd_test/ds_ep_lineage_pipeline_test.py` runs them on a TPU7x-8, over an hour; some are McJAX-only and skip on Pathways) | +| gpu-unit (A100) | the 13 `gpu_only` kernel checks; those needing Triton / jax-triton or an sm_100 GPU skip | + +## Known limitations + +- Multi-controller JAX across TPU slices: jax's native copy hangs and `jax.experimental.transfer`'s receiver crashes + (jax 0.11.1, libtpu 0.0.46): use `--transport relay` or `ppermute` (the run warns), or Pathways. Across v6e or v5p + hosts the native receive aborts. +- Pathways: one client per proxy, no peak HBM, no host callbacks, last-bit differences from McJAX, slow cold compiles. +- On a TPU VM's own client, libtpu keeps a sub-mesh's collectives on the TensorCore when it holds chip (0,0,0) but + not the whole slice (Pathways offloads them): `--layout slices` or `physical_origin_last` avoids it. +- MaxText's SparseCore unsort caps EP x tokens a device x top-k (Qwen3.8 at 4096 tokens a device: EP 16, not 32); + `--prefetch-pin auto` is calibrated on v5p and v6e only. +- The zero-bubble schedules: one chunk a stage only; not on Lineage's batch split, with stash modes or under + `--fsdp-scope repeat`; on a TPU VM's own client one dispatch thread paces every stage (see above). +- Not run since the port: multi-host multi-controller jobs, the `gcluster` Pathways command, `OnTpu`'s 4-device + form (MaxText CI's v6e-4), and the zero-bubble schedules on any TPU but a TPU7x. diff --git a/src/maxtext/experimental/mpmd/jax/__init__.py b/src/maxtext/experimental/mpmd/jax/__init__.py new file mode 100644 index 0000000000..2d4e2f005e --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/__init__.py @@ -0,0 +1,29 @@ +# 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. + +"""Pure-JAX MPMD pipeline: one jitted program set per pipeline stage, driven from Python.""" + +import os +import sys + +# A module of this package run by file path (`python3 src/maxtext/experimental/mpmd/jax/ds_ep_pipeline.py`), or a +# Python started in this directory, has this directory on sys.path, where the package's modules shadow top-level ones +# of the same name: xprof.py hides the `xprof` package, which `import tokamax` imports (tokamax 0.0.17). The +# package's modules import one another by their full names and need no such entry: take it off before any of them +# imports tokamax. +_here = globals().get("__file__") # a loader may set none (frozen, in-memory): it has no directory on sys.path then +if _here: + _here = os.path.dirname(os.path.realpath(_here)) + sys.path[:] = [p for p in sys.path if not (isinstance(p, str) and os.path.realpath(p or os.curdir) == _here)] +del os, sys, _here diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/__init__.py b/src/maxtext/experimental/mpmd/jax/deepseek/__init__.py new file mode 100644 index 0000000000..45067ebbb4 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/__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. + +"""A pure-JAX DeepSeek-V3 port: the layer math the MPMD pipeline's stage programs run.""" diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/attention.py b/src/maxtext/experimental/mpmd/jax/deepseek/attention.py new file mode 100644 index 0000000000..28b4d795d3 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/attention.py @@ -0,0 +1,396 @@ +# 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. + +"""Multi-head Latent Attention (MLA), matching MaxText's `attention_mla.MLA`. + +Query/key/value are produced by low-rank (LoRA) projections with a partial +RoPE, and the softmax scale -- including the squared YaRN `mscale` -- is folded +into the query before the attention kernel runs (`MLA.mla_query_projection`). The +kernel itself therefore sees a scale of 1.0. +""" + +import functools + +import jax +import jax.numpy as jnp +from jax.experimental.pallas.ops.tpu.splash_attention import splash_attention_kernel +from jax.experimental.pallas.ops.tpu.splash_attention import splash_attention_mask + +from maxtext.experimental.mpmd.jax.deepseek import layers +from maxtext.experimental.mpmd.jax.deepseek import rope +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig + +# common_types.DEFAULT_MASK_VALUE +DEFAULT_MASK_VALUE = -0.7 * float(jnp.finfo(jnp.float32).max) + + +def _causal_segment_mask(query_len, kv_len, segment_ids, kv_segment_ids=None, offset=0): + """`attention_op.AttentionOp.generate_attention_mask`, train mode. + + `offset` shifts the queries along the keys (query i is at key position + i + offset, splash's CausalMask offset); `kv_segment_ids` are the keys' own + segment ids where they are not the queries' (`segment_ids` serves both by + default).""" + causal = ( + jax.lax.broadcasted_iota(jnp.int32, (query_len, kv_len), 1) + <= jax.lax.broadcasted_iota(jnp.int32, (query_len, kv_len), 0) + offset + ) + keep = causal[jnp.newaxis, :, :] + if segment_ids is not None: + kv_seg = segment_ids if kv_segment_ids is None else kv_segment_ids + same = (segment_ids[:, :, jnp.newaxis] == kv_seg[:, jnp.newaxis, :]) & (kv_seg[:, jnp.newaxis, :] >= 0) + keep = keep & same + return keep + + +def dot_product_attention(query, key, value, segment_ids, config: DeepSeekConfig, kv_segment_ids=None, offset=0): + """`attention_op.AttentionOp.apply_attention_dot`, train mode. + + Everything -- the QK product, the mask fill, the softmax and the PV product -- + stays in bf16, because `float32_qk_product` and `float32_logits` are both + false. This is *not* the same arithmetic as the splash kernel, which does the + softmax in fp32; use it only when comparing against a MaxText run that also + took this branch (`attention=dot_product`, or `max_target_length < 128`). + """ + precision = layers.precision_of(config) + b, t, n, _ = query.shape + n_kv = key.shape[2] + g = n // n_kv + + grouped_q = jnp.reshape(query, (b, t, n_kv, g, query.shape[-1])) + attn_weights = jnp.einsum("btkgd,bskd->bkgts", grouped_q, key, precision=precision) + + keep = _causal_segment_mask(t, key.shape[1], segment_ids, kv_segment_ids, offset)[:, jnp.newaxis, jnp.newaxis, :, :] + attn_weights = jnp.where(keep, attn_weights, DEFAULT_MASK_VALUE) + + logits = jnp.reshape(attn_weights, (b, n, t, key.shape[1])) + local_max = jnp.max(logits, axis=-1, keepdims=True) + local_exps = jnp.exp(logits - local_max) + local_sum = jnp.sum(local_exps, axis=-1, keepdims=True) + local_sum = jnp.transpose(local_sum, (0, 2, 1, 3)) # [b, t, n, 1] + + local_exps = jnp.reshape(local_exps, (b, n_kv, g, t, key.shape[1])) + out = jnp.einsum("bkgts,bskd->btkgd", local_exps, value, precision=precision) + out = jnp.reshape(out, (b, t, n, out.shape[-1])) + return out / local_sum + + +def reference_attention(query, key, value, segment_ids, precision=None, kv_segment_ids=None, offset=0): + """A readable fp32 stand-in for the splash kernel (softmax and PV in fp32). + + `precision` is the QK product's (`layers.precision_or_none`). With bf16 + operands any precision is exact, but an fp32 model's QK product at DEFAULT + is a bf16 pass on TPU. The PV product is always HIGHEST: its probabilities + are fp32 whatever the model's dtype. `offset` / `kv_segment_ids`: see + `_causal_segment_mask`. + """ + t, s = query.shape[1], key.shape[1] + logits = jnp.einsum("bqhd,bkhd->bhqk", query, key, precision=precision, preferred_element_type=jnp.float32) + keep = _causal_segment_mask(t, s, segment_ids, kv_segment_ids, offset)[:, jnp.newaxis, :, :] + logits = jnp.where(keep, logits, DEFAULT_MASK_VALUE) + + m = jnp.max(logits, axis=-1, keepdims=True) + p = jnp.exp(logits - m) + p = p * (1.0 / jnp.sum(p, axis=-1, keepdims=True)) + out = jnp.einsum("bhqk,bkhd->bqhd", p, value.astype(jnp.float32), precision=jax.lax.Precision.HIGHEST) + return out.astype(query.dtype) + + +@functools.partial(jax.jit, static_argnums=(4, 5, 6, 7), static_argnames=("offset",)) +def splash_attention( + query, key, value, segment_ids, num_heads, block_q, block_kv, block_kv_compute, kv_segment_ids=None, offset=0 +): + """The TPU Pallas kernel MaxText autoselects, called the same way (`offset` / + `kv_segment_ids`: see `_causal_segment_mask`).""" + query = jnp.transpose(query, axes=(0, 2, 1, 3)) + key = jnp.transpose(key, axes=(0, 2, 1, 3)) + value = jnp.transpose(value, axes=(0, 2, 1, 3)) + + q_len, kv_len = query.shape[2], key.shape[2] + mask = splash_attention_mask.CausalMask(shape=(q_len, kv_len), offset=offset) + multi_head_mask = splash_attention_mask.MultiHeadMask(masks=(mask,) * num_heads) + block_sizes = splash_attention_kernel.BlockSizes( + block_q=min(block_q, q_len), + block_kv=min(block_kv, kv_len), + block_kv_compute=min(block_kv_compute, kv_len), + block_q_dkv=min(block_q, q_len), + block_kv_dkv=min(block_kv, kv_len), + block_kv_dkv_compute=min(block_kv_compute, kv_len), + block_q_dq=min(block_q, q_len), + block_kv_dq=min(block_kv, kv_len), + use_fused_bwd_kernel=False, + ) + kernel = splash_attention_kernel.make_splash_mha( + mask=multi_head_mask, + head_shards=1, + q_seq_shards=1, + block_sizes=block_sizes, + attn_logits_soft_cap=None, + residual_checkpoint_name="context", + interpret=jax.default_backend() != "tpu", + ) + segments = None + if segment_ids is not None: + segments = splash_attention_kernel.SegmentIds(segment_ids, segment_ids if kv_segment_ids is None else kv_segment_ids) + out = jax.vmap(kernel, in_axes=(0, 0, 0, 0, None))(query, key, value, segments, None) + return jnp.transpose(out, axes=(0, 2, 1, 3)) + + +@functools.cache +def _tokamax_splash_package(): + """Where tokamax keeps its splash attention: tokamax._src.ops.splash_attention after 0.0.17, else + tokamax._src.ops.experimental.tpu.splash_attention -- looked up in that order, as MaxText's attention_op and lineage + kernel do, and once, so that the kernel and its masks always come from one tree.""" + import importlib + + err = None + for pkg in ("tokamax._src.ops.splash_attention", "tokamax._src.ops.experimental.tpu.splash_attention"): + try: + importlib.import_module(pkg) + return pkg + except ModuleNotFoundError as e: + if not e.name or not pkg.startswith(e.name): # a dependency the tree imports is missing: say which + raise + err = e + raise err + + +def tokamax_splash_module(name): + """tokamax's splash-attention module `name` (splash_attention_kernel, splash_attention_mask, ...), from the tree + `_tokamax_splash_package` finds.""" + import importlib + + return importlib.import_module(f"{_tokamax_splash_package()}.{name}") + + +def tokamax_splash_attention(query, key, value, segment_ids, config: DeepSeekConfig, kv_segment_ids=None, offset=0): + """MaxText `use_tokamax_splash=true` (`AttentionOp._create_sa_config`, `AttentionOp.tpu_flash_attention`). + + Tokamax splash always runs the fused backward. On TPU, like the jax splash + kernel, it cannot be auto-partitioned: call it on device-local arrays, e.g. + inside a `shard_map`. Off TPU it runs in interpret mode, plain JAX that + partitions like any other op. + """ + from jax.experimental import pallas as pl + + tsk, tsm = tokamax_splash_module("splash_attention_kernel"), tokamax_splash_module("splash_attention_mask") + + query = jnp.transpose(query, axes=(0, 2, 1, 3)) + key = jnp.transpose(key, axes=(0, 2, 1, 3)) + value = jnp.transpose(value, axes=(0, 2, 1, 3)) + q_len, kv_len = query.shape[2], key.shape[2] + + def cost(flops): + return pl.CostEstimate(flops=flops, transcendentals=0, bytes_accessed=0) if flops >= 0 else None + + sa_config = tsk.SplashConfig( + block_q=min(config.sa_block_q, q_len), + block_kv=min(config.sa_block_kv, kv_len), + block_kv_compute=min(config.sa_block_kv_compute, kv_len), + block_q_dkv=min(config.sa_block_q_dkv or config.sa_block_q, q_len), + block_kv_dkv=min(config.sa_block_kv_dkv or config.sa_block_kv, kv_len), + block_kv_dkv_compute=min(config.sa_block_kv_dkv_compute or config.sa_block_kv_compute, kv_len), + use_fused_bwd_kernel=True, + fuse_reciprocal=True, + # MaxText's sa_use_base2_exp, on by default; DeepSeekConfig says what it does to the softmax + use_base2_exp=config.sa_use_base2_exp, + residual_checkpoint_name="context", + fwd_cost_estimate=cost(config.sa_cost_estimate_flops_fwd), + bwd_cost_estimate=cost(config.sa_cost_estimate_flops_bwd), + interpret=jax.default_backend() != "tpu", + ) + kernel = tsk.make_splash_mha(tsm.CausalMask(shape=(q_len, kv_len), offset=offset), config=sa_config, q_seq_shards=1) + segments = None + if segment_ids is not None: + segments = tsk.SegmentIds(segment_ids, segment_ids if kv_segment_ids is None else kv_segment_ids) + out = jax.vmap(lambda q, k, v, s: kernel(q, k, v, s))(query, key, value, segments) + return jnp.transpose(out, axes=(0, 2, 1, 3)) + + +def attention_op(query, key, value, segment_ids, config: DeepSeekConfig, kv_segment_ids=None, offset=0): + """The attention kernel `config.attention_kernel` names: causal attention of + `query` [b, t, n, d] over `key` / `value` [b, s, n, .], query i at key + position i + `offset`; `kv_segment_ids` are the keys' segment ids where they + differ from the queries' `segment_ids` (context parallelism) -- given + without them, against queries of one segment, 1: the keys' ids alone mask. + + A Pallas kernel (splash, tokamax) runs on device-local arrays: on TPU it is + a Mosaic custom call, which XLA cannot partition, so on a sub-mesh of more + than one Auto device it does not even compile, and off TPU tokamax's + interpret mode does not trace at the top level of an explicit program. + ds_ep calls `mla` from inside its own `shard_map`, where both run. + """ + if segment_ids is None and kv_segment_ids is not None: + # every kernel reads kv_segment_ids only beside segment_ids + segment_ids = jnp.ones(query.shape[:2], kv_segment_ids.dtype) + return _attention_kernel(query, key, value, segment_ids, config, kv_segment_ids, offset) + + +def cudnn_attention(query, key, value, segment_ids, config: DeepSeekConfig, kv_segment_ids=None, offset=0): + """cuDNN's fused flash attention (GPU), causal, through jax's cuDNN API + (`jax._src.cudnn.fused_attention_stablehlo`, what MaxText's `cudnn_flash_jax` + calls): [b, t, n, d] operands as they are (BTNH), GQA natively, the softmax + in fp32, scale 1.0 (MLA and Qwen fold it into the query). The query / key + head dim may differ from the value's (MLA's 192 / 128) and go up to 256 + (Qwen's) on sm90 and later with cuDNN >= 9.10; sm80 takes <= 128 and equal + dims. `jax.nn.dot_product_attention` would refuse MLA's value shape. + + Unpacked sequences only: the segment ids are taken as one segment a row + (ds_ep's are all ones), and a query offset or separate key segment ids + (context parallelism) are refused.""" + if offset or kv_segment_ids is not None: + raise NotImplementedError( + "attention_kernel 'cudnn': no query offset / key segment ids (context " "parallelism); use cp 1" + ) + del segment_ids # one segment a row: the causal mask is the whole mask + from jax._src.cudnn import fused_attention_stablehlo as cudnn_fa + + return cudnn_fa.dot_product_attention( + query, key, value, scale=1.0, mask_type=cudnn_fa.MaskType.CAUSAL, qkv_layout="BTNH" + ) + + +def _attention_kernel(query, key, value, segment_ids, config: DeepSeekConfig, kv_segment_ids=None, offset=0): + if config.attention_kernel == "cudnn": + return cudnn_attention(query, key, value, segment_ids, config, kv_segment_ids, offset) + if config.attention_kernel == "tokamax_splash": + return tokamax_splash_attention(query, key, value, segment_ids, config, kv_segment_ids, offset) + if config.attention_kernel == "splash": + return splash_attention( + query, + key, + value, + segment_ids, + config.num_query_heads, + config.sa_block_q, + config.sa_block_kv, + config.sa_block_kv_compute, + kv_segment_ids, + offset=offset, + ) + if config.attention_kernel == "dot_product": + return dot_product_attention(query, key, value, segment_ids, config, kv_segment_ids, offset) + if config.attention_kernel == "reference": + return reference_attention(query, key, value, segment_ids, layers.precision_or_none(config), kv_segment_ids, offset) + raise ValueError(f"unknown attention_kernel: {config.attention_kernel}") + + +def mla(params, inputs, positions, segment_ids, freqs_cis, config: DeepSeekConfig, kv_context=None, norm=None): + """`MLA.__call__` for MODEL_MODE_TRAIN. + + `kv_context`, for a sequence split over devices (context parallelism): + `(kv latent [b, s, kv_lora], roped key [b, s, 1, rope], segment_ids) -> (the + same over the keys these queries attend, their segment ids against + `segment_ids` -- or, with None, against queries of one segment, 1 --, the + queries' key offset)`, e.g. ds_ep's, which gathers the other chunks of the + sequence. The keys and values are then projected from the gathered latent. + + `norm`: the pre-attention RMSNorm's params, which `inputs` -- the residual + stream, then -- go through first. Under lean residuals + (`layers.lean_residuals`) the norm and the two projections that read its + output run in one checkpoint (`layers.rms_norm_read`), so that a VJP keeps + the stream rather than the normalised activation; outside them this is the + norm applied first. Likewise the query's norm and its up-projection, and, + without `kv_context`, the key / value latent's norm and its up-projection + (with it the gathered latent comes between the two). + + Args: + params: `wq_a`, `q_norm`, `wq_b` (or `query` when `q_lora_rank == 0`), + `wkv_a`, `kv_norm`, `wkv_b`, `out`. + inputs: `[b, s, emb_dim]`. + positions: `[b, s]` token positions for RoPE. + segment_ids: `[b, s]` packing segment ids, or None. + freqs_cis: YaRN rotation table. + config: model config. + kv_context: see above, or None. + norm: see above, or None. + """ + b = inputs.shape[0] + heads = config.num_query_heads + + def q_down(x): + return layers.dense_general(params["query" if config.q_lora_rank == 0 else "wq_a"], x, config) + + def kv_down(x): + return layers.dense_general(params["wkv_a"], x, config) + + if norm is not None and layers.lean(): + q_in, kv_in = layers.rms_norm_read(norm, inputs, config, lambda x: (q_down(x), kv_down(x))) + else: + if norm is not None: + inputs = layers.rms_norm(norm, inputs, config) + q_in, kv_in = q_down(inputs), None # the key / value latent's projection where MaxText runs it, below + + # --- query: LoRA down -> RMSNorm -> LoRA up -> partial RoPE -> scale ------- + # `q_lora_rank == 0` is a plain projection, not a rank-0 LoRA + # (`MLA._init_projections`, `MLA.mla_query_projection`). Running the LoRA path at rank 0 would make + # `wq_a` `[emb, 0]` and every query identically zero -- uniform attention, + # silently -- so the two are different parameter trees, as in MaxText. + if config.q_lora_rank == 0: + q = q_in + else: + low_rank_q = jax.ad_checkpoint.checkpoint_name(q_in, "query_wa_proj") + q = layers.rms_norm_read( + params["q_norm"], + low_rank_q, + config, + lambda lq: layers.dense_general(params["wq_b"], jax.ad_checkpoint.checkpoint_name(lq, "mla_q"), config), + ) + q_nope, q_pe = jnp.split(q, [config.qk_nope_head_dim], axis=-1) + q_pe = rope.apply_yarn(q_pe, positions, freqs_cis, config) + query = jnp.concatenate([q_nope, q_pe], axis=-1) * config.softmax_scale + + # --- key/value: shared LoRA latent, rope on the shared 1-head slice ------- + low_rank = kv_down(inputs) if kv_in is None else kv_in + low_rank = jax.ad_checkpoint.checkpoint_name(low_rank, "kv_wa_proj") + low_rank_main, low_rank_rope = jnp.split(low_rank, [config.kv_lora_rank], axis=-1) + + def kv_up(lk): + return layers.dense_general(params["wkv_b"], lk, config) + + kv_out = None + if kv_context is None and layers.lean(): + # the latent's norm and its up-projection in one checkpoint, as the query's: no VJP keeps the norm's output + kv_out = layers.rms_norm_read( + params["kv_norm"], low_rank_main, config, lambda lk: kv_up(jax.ad_checkpoint.checkpoint_name(lk, "mla_kv")) + ) + else: + # outside lean residuals the norm, then the projection below, where MaxText runs it; under context + # parallelism the gathered latent comes between the two, and wkv_b's VJP keeps that + low_rank_main = layers.rms_norm(params["kv_norm"], low_rank_main, config) + low_rank_main = jax.ad_checkpoint.checkpoint_name(low_rank_main, "mla_kv") + key_rope = jnp.expand_dims(low_rank_rope, axis=2) + key_rope = rope.apply_yarn(key_rope, positions, freqs_cis, config) + kv_segment_ids, offset = None, 0 + if kv_context is not None: + low_rank_main, key_rope, kv_segment_ids, offset = kv_context(low_rank_main, key_rope, segment_ids) + + if kv_out is None: + kv_out = kv_up(low_rank_main) + key_nope, value = jnp.split(kv_out, [config.qk_nope_head_dim], axis=-1) + key_rope = jnp.broadcast_to(key_rope, (b, key_rope.shape[1], heads, config.qk_rope_head_dim)) + key = jnp.concatenate([key_nope, key_rope], axis=-1) + + query = jax.ad_checkpoint.checkpoint_name(query, "query_proj") + key = jax.ad_checkpoint.checkpoint_name(key, "key_proj") + value = jax.ad_checkpoint.checkpoint_name(value, "value_proj") + + out = attention_op(query, key, value, segment_ids, config, kv_segment_ids, offset) + # Under lean residuals the output takes no name: the out projection's VJP then keeps the very array the kernel's + # VJP keeps (cuDNN's keeps its output), where the name, an array of its own, would be a second copy of it. Only + # remat policies read the name, and a saved-residual forward applies none. + if not layers.lean(): + out = jax.ad_checkpoint.checkpoint_name(out, "attention_out") + out = layers.dense_general(params["out"], out, config, axis=(-2, -1)) + return jax.ad_checkpoint.checkpoint_name(out, "out_proj") diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/config.py b/src/maxtext/experimental/mpmd/jax/deepseek/config.py new file mode 100644 index 0000000000..7ae585ed9b --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/config.py @@ -0,0 +1,341 @@ +# 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. + +"""Config for the pure-JAX DeepSeek-V3 model. + +Field names and defaults mirror MaxText's resolved config so that a MaxText +`pyconfig` object can be translated 1:1 (see `from_maxtext`). Only the +knobs that the DeepSeek-V3 training forward pass actually reads are kept; +everything that MaxText leaves off by default (quantization, pipeline +parallelism, attention sinks, soft caps, indexer/DSA, ...) is simply absent. + +How the model shards is one more field, `shard` (a `ShardPolicy`): the +default policy, the program this port has always traced. `SharedLayerConfig` +names the fields that the functions other models borrow from this package +read. +""" + +import dataclasses +import math +import typing +from typing import Any, Protocol + +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.sharding_mode import ShardPolicy + + +@dataclasses.dataclass(frozen=True) +class DeepSeekConfig: + """Resolved DeepSeek-V3 hyperparameters.""" + + # --- vocabulary / shape --------------------------------------------------- + vocab_size: int = 129280 + emb_dim: int = 64 + num_decoder_layers: int = 61 + first_num_dense_layers: int = 3 + + # --- MLA ------------------------------------------------------------------ + num_query_heads: int = 4 + num_kv_heads: int = 4 + q_lora_rank: int = 32 + kv_lora_rank: int = 16 + qk_nope_head_dim: int = 128 + qk_rope_head_dim: int = 64 + v_head_dim: int = 128 + + # --- MLP / MoE ------------------------------------------------------------ + mlp_dim: int = 64 + moe_mlp_dim: int = 64 + mlp_activations: tuple[str, ...] = ("silu", "linear") + num_experts: int = 16 + num_experts_per_tok: int = 8 + shared_experts: int = 1 + routed_score_func: str = "sigmoid" + routed_bias: bool = True + routed_scaling_factor: float = 2.5 + routed_bias_update_rate: float = 0.0 + # Group-limited routing (moe.expert_group_mask): the experts are cut into + # n_routing_groups groups, each scored by its two best post-bias scores, and + # a token picks its top-k among the topk_routing_group best groups. -1: off. + n_routing_groups: int = -1 + topk_routing_group: int = -1 + # Multi-token prediction (multi_token_prediction.py): mtp_num_layers extra + # MoE layers after the decoder, each predicting one token further, their + # mean cross entropy scaled by mtp_loss_scaling_factor into the loss. + mtp_num_layers: int = 0 + mtp_loss_scaling_factor: float = 0.1 + load_balance_loss_weight: float = 0.0 + # The aux loss of a sigmoid router as Megatron-LM's seq_aux_loss + # (moe.megatron_seq_aux_loss, DeepSeek-V3 eqs 17-20): per sequence, summed + # over the MoE layers (MTP's too); else MaxText's Switch-style loss. + moe_use_megatron_seq_aux_loss: bool = False + # `dense` reproduces moe.dense_matmul (einsum over every expert); + # `ragged` reproduces moe.sparse_matmul (sort + grouped matmul). + moe_impl: str = "ragged" + # MaxText's default grouped matmul is the megablox Pallas kernel, which + # accumulates every tile in fp32 and rounds to bf16 once, on the way out. Its + # `jax_ragged_dot_gmm` fallback (`megablox=false use_tokamax_gmm=false`) hands + # `preferred_element_type=bf16` to XLA instead. The two differ by up to one + # bf16 ulp per grouped matmul, so the port has to follow whichever is active. + gmm_fp32_accum: bool = True + # Reproduce megablox's `tgmm` weight gradient exactly, at `num_experts` times + # the FLOPs -- see `moe._grouped_matmul`. For parity runs, not for training. + gmm_exact_drhs: bool = False + moe_use_direct_token_gather: bool = False + float32_weight_sum: bool = True + float32_gate_logits: bool = False + + # --- normalization -------------------------------------------------------- + normalization_layer_epsilon: float = 1.0e-6 + + # --- YaRN RoPE ------------------------------------------------------------ + rope_max_timescale: float = 10_000.0 + max_position_embeddings: int = 163840 + original_max_position_embeddings: int = 4096 + rope_factor: float = 40.0 + beta_fast: float = 32.0 + beta_slow: float = 1.0 + mscale: float = 1.0 + rope_interleave: bool = True + rope_truncate: bool = True + rope_attention_scaling: bool = False + + # --- numerics ------------------------------------------------------------- + dtype: jnp.dtype = jnp.bfloat16 + weight_dtype: jnp.dtype = jnp.float32 + matmul_precision: str = "default" + cast_logits_to_fp32: bool = True + logits_dot_in_fp32: bool = False + dense_init_scale: float = 1.0 + + # --- attention kernel ----------------------------------------------------- + # 'splash' -- the TPU Pallas kernel MaxText autoselects (fp32 softmax); + # 'dot_product' -- MaxText's `apply_attention_dot` (bf16 softmax), which is + # what MaxText itself falls back to below 128 tokens; + # 'reference' -- a portable fp32 stand-in for the splash kernel; + # 'tokamax_splash' -- tokamax's splash kernel with the fused backward + # (MaxText `use_tokamax_splash=true`), which the MPMD + # ds_ep pipeline runs; + # 'cudnn' -- cuDNN's fused flash attention (GPU; unpacked rows, no + # context parallelism): ds_ep_pipeline's GPU default. + attention_kernel: str = "splash" + sa_block_q: int = 512 + sa_block_kv: int = 512 + sa_block_kv_compute: int = 512 + # 'tokamax_splash' only (MaxText `use_tokamax_splash=true`, fused bwd). + # 0 means "same as the forward block"; -1 cost estimates mean "unset". + sa_block_q_dkv: int = 0 + sa_block_kv_dkv: int = 0 + sa_block_kv_dkv_compute: int = 0 + sa_cost_estimate_flops_fwd: int = -1 + sa_cost_estimate_flops_bwd: int = -1 + # 'tokamax_splash' only: tokamax's base-2 softmax (MaxText `sa_use_base2_exp`, + # true in its base.yml, as here; tokamax always ran it before the field). Not + # the exact softmax: with a bf16 query the kernels scale it by the Python + # float log2(e), which JAX rounds to bf16 1.4453125, so the softmax runs at + # 1.0018x its logits while the fused backward's dq and dk both leave that + # factor out (DeepSeek-V3's layer 0 at init: the output and dv ~0.3%, dq and + # dk ~0.25% larger than the exact softmax's). False computes the exact one, + # ~1.2% slower in the kernel (fwd + bwd, DeepSeek-V3 attention at 4096 tokens + # x 128 heads on one TPU7x device: 11.49 vs 11.34 ms). `from_maxtext` + # carries MaxText's setting, but its kernel resolution maps MaxText's flash + # attention to 'splash' (the exact softmax): it matters where a caller picks + # 'tokamax_splash', e.g. ds_ep_pipeline. + sa_use_base2_exp: bool = True + + # --- training ------------------------------------------------------------- + per_device_batch_size: int = 1 + max_target_length: int = 2048 + scan_layers: bool = True + remat_policy: str = "full" + + # --- sharding ------------------------------------------------------------- + # How the model shards (`src/maxtext/experimental/mpmd/jax/sharding_mode.py`): the default + # policy, today's program, the only one there is. It is frozen like this + # class, which therefore stays hashable. + shard: ShardPolicy = ShardPolicy() + + # --- derived -------------------------------------------------------------- + @property + def qk_head_dim(self) -> int: + return self.qk_nope_head_dim + self.qk_rope_head_dim + + @property + def num_moe_layers(self) -> int: + return self.num_decoder_layers - self.first_num_dense_layers + + @property + def softmax_scale(self) -> float: + """MLA softmax scale, folded into the query (`attention_mla.MLA.mla_query_projection`).""" + scale = self.qk_head_dim**-0.5 + if self.max_position_embeddings > self.original_max_position_embeddings: + mscale = 0.1 * self.mscale * math.log(self.rope_factor) + 1.0 + scale = scale * mscale * mscale + return scale + + @property + def shared_expert_mlp_dim(self) -> int: + """`moe.get_shared_expert_mlp_dim` -- moe_mlp_dim unless overridden.""" + return self.moe_mlp_dim + + def replace(self, **kwargs) -> "DeepSeekConfig": + return dataclasses.replace(self, **kwargs) + + +@typing.runtime_checkable +class SharedLayerConfig(Protocol): + """The config fields read by the functions of this package other models call. + + The Qwen3.5 port calls a handful of these whose arithmetic is the same for + both models, so any config handed to them needs exactly these fields: + `DeepSeekConfig` has them, and so must every other model's config. + `deepseek_model_test` collects every `config.` the functions' + sources mention and checks the set equals this one, and it traces them + with an object that has these fields and nothing else. + + layers.precision_of matmul_precision + layers.precision_or_none (precision_of) + layers.rms_norm dtype, normalization_layer_epsilon + (+ precision_or_none) + layers.dense_general dtype (+ precision_of) + layers.embed_lookup dtype + layers.mlp_block mlp_activations, dtype + moe.routed_experts moe_impl + moe._experts_dense dtype, num_experts, + float32_weight_sum + moe._experts_ragged dtype, num_experts, + num_experts_per_tok, + moe_use_direct_token_gather, + gmm_fp32_accum, gmm_exact_drhs, + float32_weight_sum (+ precision_of, + precision_or_none) + attention.attention_op attention_kernel; splash + reads num_query_heads and + sa_block_{q,kv,kv_compute}; + reference (+ precision_or_none) + attention.dot_product_attention (precision_of) + attention.tokamax_splash_attention sa_block_* incl. the *_dkv blocks, + sa_cost_estimate_flops_{fwd,bwd}, + sa_use_base2_exp + model.remat_policy_for remat_policy + """ + + dtype: Any + matmul_precision: str + normalization_layer_epsilon: float + mlp_activations: tuple + moe_impl: str + num_experts: int + num_experts_per_tok: int + moe_use_direct_token_gather: bool + gmm_fp32_accum: bool + gmm_exact_drhs: bool + float32_weight_sum: bool + attention_kernel: str + num_query_heads: int + sa_block_q: int + sa_block_kv: int + sa_block_kv_compute: int + sa_block_q_dkv: int + sa_block_kv_dkv: int + sa_block_kv_dkv_compute: int + sa_cost_estimate_flops_fwd: int + sa_cost_estimate_flops_bwd: int + sa_use_base2_exp: bool + remat_policy: str + + +SHARED_LAYER_FIELDS = frozenset(SharedLayerConfig.__annotations__) + + +def resolve_attention_kernel(cfg) -> str: + """`attention_op.AttentionOp.apply_attention` dispatch, train. + + `autoselected` picks the TPU splash kernel unless the sequence is shorter than + 128 tokens, in which case MaxText silently drops to the bf16 dot-product path. + """ + kernel = cfg.attention + if kernel == "dot_product": + return "dot_product" + if kernel in ("autoselected", "flash"): + if int(cfg.max_target_length) < 128: + return "dot_product" + return "splash" + raise ValueError(f"unsupported attention kernel for this port: {kernel}") + + +def from_maxtext(cfg) -> DeepSeekConfig: + """Builds a DeepSeekConfig from an initialized MaxText pyconfig.""" + activations = tuple(cfg.mlp_activations) + return DeepSeekConfig( + attention_kernel=resolve_attention_kernel(cfg), + sa_block_q=cfg.sa_block_q, + sa_block_kv=cfg.sa_block_kv, + sa_block_kv_compute=cfg.sa_block_kv_compute, + sa_use_base2_exp=bool(cfg.sa_use_base2_exp), + scan_layers=cfg.scan_layers, + remat_policy=cfg.remat_policy, + vocab_size=cfg.vocab_size, + emb_dim=cfg.emb_dim, + num_decoder_layers=cfg.num_decoder_layers, + first_num_dense_layers=cfg.first_num_dense_layers, + num_query_heads=cfg.num_query_heads, + num_kv_heads=cfg.num_kv_heads, + q_lora_rank=cfg.q_lora_rank, + kv_lora_rank=cfg.kv_lora_rank, + qk_nope_head_dim=cfg.qk_nope_head_dim, + qk_rope_head_dim=cfg.qk_rope_head_dim, + v_head_dim=cfg.v_head_dim, + mlp_dim=cfg.mlp_dim, + moe_mlp_dim=cfg.moe_mlp_dim, + mlp_activations=activations, + num_experts=cfg.num_experts, + num_experts_per_tok=cfg.num_experts_per_tok, + shared_experts=cfg.shared_experts, + routed_score_func=cfg.routed_score_func, + routed_bias=cfg.routed_bias, + routed_scaling_factor=cfg.routed_scaling_factor, + routed_bias_update_rate=cfg.routed_bias_update_rate, + n_routing_groups=cfg.n_routing_groups, + topk_routing_group=cfg.topk_routing_group, + mtp_num_layers=cfg.mtp_num_layers, + mtp_loss_scaling_factor=cfg.mtp_loss_scaling_factor, + load_balance_loss_weight=cfg.load_balance_loss_weight, + moe_use_megatron_seq_aux_loss=bool(cfg.moe_use_megatron_seq_aux_loss), + moe_impl="ragged" if cfg.sparse_matmul else "dense", + gmm_fp32_accum=bool(cfg.megablox or cfg.use_tokamax_gmm), + moe_use_direct_token_gather=cfg.moe_use_direct_token_gather, + float32_weight_sum=cfg.float32_weight_sum, + float32_gate_logits=cfg.float32_gate_logits, + normalization_layer_epsilon=cfg.normalization_layer_epsilon, + rope_max_timescale=cfg.rope_max_timescale, + max_position_embeddings=cfg.max_position_embeddings, + original_max_position_embeddings=cfg.original_max_position_embeddings, + rope_factor=cfg.rope_factor, + beta_fast=cfg.beta_fast, + beta_slow=cfg.beta_slow, + mscale=cfg.mscale, + rope_interleave=cfg.rope_interleave, + rope_truncate=cfg.rope_truncate, + rope_attention_scaling=cfg.rope_attention_scaling, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + matmul_precision=cfg.matmul_precision, + cast_logits_to_fp32=cfg.cast_logits_to_fp32, + logits_dot_in_fp32=cfg.logits_dot_in_fp32, + dense_init_scale=cfg.dense_init_scale, + per_device_batch_size=int(cfg.per_device_batch_size), + max_target_length=cfg.max_target_length, + ) diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/convert.py b/src/maxtext/experimental/mpmd/jax/deepseek/convert.py new file mode 100644 index 0000000000..baa5f9dcbb --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/convert.py @@ -0,0 +1,156 @@ +# 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. + +"""Bridge between MaxText's NNX state and this model's parameter pytrees. + +Two differences have to be reconciled: + + * MaxText stacks scanned `nnx.Param` leaves at `param_scan_axis` (1 by + default) while non-`Param` variables stay at axis 0; we always stack at + axis 0 so `jax.lax.scan` can consume the tree directly. + * MaxText's router bias is a `MoEBiasVar`, which the trainer deliberately + excludes from the gradient. We keep it in a separate `aux` tree so that + `jax.grad` cannot reach it either. + +Flax is imported inside the functions that use it: the port itself does not +depend on it. +""" + +import jax +import jax.numpy as jnp + +_SCAN_STACKS = ("dense_layers", "moe_layers") +_SKIP = ("rngs",) + + +def _set(tree, path, value): + node = tree + for key in path[:-1]: + node = node.setdefault(key, {}) + node[path[-1]] = value + + +def _get(tree, path): + node = tree + for key in path: + node = node[key] + return node + + +def _flat_state(state): + """`(path, variable)` pairs of an `nnx.State` (`State.flat_state` is deprecated).""" + from flax import nnx # pylint: disable=g-import-not-at-top + + return nnx.to_flat_state(state) + + +def _value(var): + """The array a variable holds, or `var` itself when it is already one. + + `get_value()` rather than `.value`, which flax deprecates. + """ + get_value = getattr(var, "get_value", None) + return get_value() if callable(get_value) else var + + +def from_nnx_state(state, param_scan_axis: int = 1): + """Converts a `nnx.State` (from `nnx.split(model)`) into `(params, aux)`. + + Args: + state: the NNX state of a MaxText `Transformer`. + param_scan_axis: `config.param_scan_axis` used to build the model. + + Returns: + `(params, aux)` -- nested dicts of `jax.Array`, with scanned stacks at + axis 0. + """ + params: dict = {} + aux: dict = {} + for path, var in _flat_state(state): + parts = [str(p) for p in path] + if any(skip in parts for skip in _SKIP): + continue + kind = type(var).__name__ + if kind not in ("Param", "MoEBiasVar"): + continue + value = jnp.asarray(_value(var)) + scanned = any(stack in parts for stack in _SCAN_STACKS) + if scanned and kind == "Param" and param_scan_axis != 0: + value = jnp.moveaxis(value, param_scan_axis, 0) + _set(params if kind == "Param" else aux, parts, value) + return params, aux + + +def tree_from_nnx_state(state, param_scan_axis: int = 1): + """Converts a single-collection `nnx.State` (e.g. gradients) into one dict. + + Unlike `from_nnx_state` this does not look at variable types -- after + `jax.grad` the leaves need not be typed variables -- so every leaf lands in + one tree and every scanned stack is moved to axis 0. + """ + out: dict = {} + for path, var in _flat_state(state): + parts = [str(p) for p in path] + if any(skip in parts for skip in _SKIP): + continue + value = _value(var) + if not hasattr(value, "shape"): + continue + value = jnp.asarray(value) + if any(stack in parts for stack in _SCAN_STACKS) and param_scan_axis != 0: + value = jnp.moveaxis(value, param_scan_axis, 0) + _set(out, parts, value) + return out + + +def from_nnx_model(model, param_scan_axis: int = 1): + from flax import nnx # pylint: disable=g-import-not-at-top + + _, state = nnx.split(model) + return from_nnx_state(state, param_scan_axis) + + +def to_nnx_state(model, params, aux, param_scan_axis: int = 1): + """Writes `(params, aux)` back into a live NNX model, in place.""" + from flax import nnx # pylint: disable=g-import-not-at-top + + _, state = nnx.split(model) + updates = [] + for path, var in _flat_state(state): + parts = [str(p) for p in path] + if any(skip in parts for skip in _SKIP): + continue + kind = type(var).__name__ + if kind not in ("Param", "MoEBiasVar"): + continue + value = _get(params if kind == "Param" else aux, parts) + scanned = any(stack in parts for stack in _SCAN_STACKS) + if scanned and kind == "Param" and param_scan_axis != 0: + value = jnp.moveaxis(value, 0, param_scan_axis) + updates.append((path, value)) + for path, value in updates: + node = model + for key in path[:-1]: + node = node[int(key)] if str(key).isdigit() else getattr(node, key) + getattr(node, path[-1]).set_value(value) + return model + + +def tree_report(params, aux): + """`path -> (shape, dtype)` for eyeballing a converted tree.""" + rows = {} + for path, leaf in jax.tree_util.tree_flatten_with_path({"params": params, "aux": aux})[0]: + name = "/".join(str(k.key) for k in path) + rows[name] = (tuple(leaf.shape), str(leaf.dtype)) + return rows diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/init.py b/src/maxtext/experimental/mpmd/jax/deepseek/init.py new file mode 100644 index 0000000000..847b3b6307 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/init.py @@ -0,0 +1,94 @@ +# 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 test init for the DeepSeek-V3 port's parameter trees. + +`init_params` draws a tree -- the full model's `model.param_avals(config)`, or +any subtree of it -- from its aval tree, straight onto the devices +`shardings` names, so the full model never has to exist on one host. It is a +*test* init, not MaxText's: `normal / sqrt(fan_in)` with the norm scales at +one. MaxText's own weights come through `convert.py`. +""" + +import jax +import jax.numpy as jnp +import numpy as np + + +def _fan_in(path, shape): + """Elements contracted by the kernel at `path` -- not simply `shape[-2]`. + + `shape[-2]` is right for an `[in, out]` kernel and wrong for MLA's 3-D ones: + `query`, `wq_b` and `wkv_b` are `[in, heads, head_dim]`, so `shape[-2]` is the + head count, and `out` is `[heads, v_head_dim, emb]`, which contracts two axes. + Taking `heads` as the fan-in made queries 4x and attention logits ~16x too + large at test widths, and a model that sharp amplifies fp32 rounding by + three orders of magnitude -- enough to swamp every reassociation floor the + correctness tests are built on. + """ + if "token_embedder" in path: + return 1 # embeddings are unit-scale + if len(shape) < 2: + return shape[-1] + name = path[-2] if len(path) >= 2 else "" + if name in ("query", "wq_b", "wkv_b"): + return shape[-3] + if name == "out" and "self_attention" in path: + return shape[-3] * shape[-2] + return shape[-2] + + +def _init_leaf(path, shape, dtype, key): + """One leaf: `normal / sqrt(fan_in)`, norm scales at one. + + Biases and zero-sized leaves start at zero. What a test init has to get + right is activations that stay O(1) through the model, because a model with + logits orders of magnitude too sharp amplifies fp32 rounding past the + reassociation floors the correctness tests are built on (see `_fan_in`). + """ + if int(np.prod(shape)) == 0: + return jnp.zeros(shape, dtype) + name = path[-1] if path else "" + if name == "scale": # RMSNorm gains start at one + return jnp.ones(shape, dtype) + if name == "bias": + return jnp.zeros(shape, dtype) + v = jax.random.normal(key, shape, jnp.float32) * (_fan_in(path, shape) ** -0.5) + return v.astype(dtype) + + +def _dict_path(path): + """A jax key path -> the tuple of its dict keys.""" + return tuple(k.key for k in path if isinstance(k, jax.tree_util.DictKey)) + + +def init_params(avals, key, shardings=None): + """Materialise the parameter tree `avals` describes (`model.param_avals`, or + a subtree of it) straight onto `shardings` (None: jit's default placement). + + Driven by the aval tree, so the full model never exists anywhere. Each + leaf draws from its own key, split off `key` by the leaf's position in the + tree, so the result is deterministic in `key` and the tree. + """ + leaves, treedef = jax.tree_util.tree_flatten_with_path(avals) + keys = jax.random.split(key, max(1, len(leaves))) + + def build(): + out = [] + for i, (path, a) in enumerate(leaves): + shape, dt = tuple(int(d) for d in a.shape), a.dtype + out.append(_init_leaf(_dict_path(path), shape, dt, keys[i])) + return jax.tree.unflatten(treedef, out) + + return jax.jit(build, out_shardings=shardings)() diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/layers.py b/src/maxtext/experimental/mpmd/jax/deepseek/layers.py new file mode 100644 index 0000000000..383bc0001b --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/layers.py @@ -0,0 +1,226 @@ +# 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. + +"""Primitive layers, as plain functions over explicit parameter pytrees. + +Every function here reproduces the corresponding MaxText NNX module's forward +pass exactly, including where activations are rounded to bf16. The rule +throughout MaxText is: weights are stored in `weight_dtype` (fp32) and cast to +`dtype` (bf16) immediately before every matmul; RMSNorm is the only place that +promotes activations to fp32, and it drops back to bf16 *before* applying the +scale. + +Every op whose result type explicit sharding cannot infer goes through +`maxtext.experimental.mpmd.jax.sharding_mode` (see its docstring), which reads the mode +off the mesh in context. Under auto each helper is the expression this file +used to write inline, so that program is unchanged. +Activations are batch-major throughout, so a result's spec is always +`mode.act_spec(ndim)`: the batch on the stage's axes, nothing else sharded. +""" + +import contextlib +import contextvars + +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig +from maxtext.experimental.mpmd.jax import sharding_mode as mode + + +def precision_of(config: DeepSeekConfig): + return jax.lax.Precision(config.matmul_precision) + + +def precision_or_none(config: DeepSeekConfig): + """`precision_of`, but None at the default precision. + + For the matmuls that ignored `matmul_precision` until a TPU parity check at + 'highest' tripped on them: the grouped expert matmuls, RMSNorm's scale and + the reference attention's QK product. The grouped matmuls and the QK + product were lowered at DEFAULT, which on TPU means one bf16 pass, so an + fp32 model at 'highest' still rounded them, and that noise was enough to + flip the router's top-k choices. (RMSNorm's scale product contracts + nothing: XLA:TPU makes it an elementwise multiply at any precision.) They + used to pass None, and still do at the default: an explicit DEFAULT would + lower the same, but it would also override `jax_default_matmul_precision`, + which governs a None. + + MaxText leaves its own grouped matmuls at the default whatever + `matmul_precision` says (moe.py: megablox's Pallas dot and the + `jax.lax.ragged_dot` fallback pass none, tokamax passes DEFAULT -- on TPU + each is one bf16-rounding pass over fp32 operands), so at a non-default + precision the port's grouped matmuls are more precise than the MaxText + they mirror. The CPU parity tests cannot show it: XLA:CPU computes an + fp32 dot in fp32 at any precision. + """ + precision = precision_of(config) + return None if precision == jax.lax.Precision.DEFAULT else precision + + +# Lean residuals (`lean_residuals()`, which the pipeline's saved-residual forwards trace under): RMSNorm, its +# scale's product included, and the gated MLPs' activation product run under jax.checkpoint, so a VJP saves their +# bf16 inputs (and the matmuls' operands) instead of the f32 and bf16 normalised activations and the silu / sigmoid / +# product intermediates -- Transformer Engine's RMSNorm and Megatron's fused SwiGLU keep about as little. Where a +# norm's output is a matmul's lhs, `rms_norm_read` takes the matmul into the norm's checkpoint, so that its VJP does +# not keep the output either (Megatron's layernorm recompute). The recomputation is elementwise. attention.mla and +# rope.apply_yarn read the mode too. +# (The pipeline's routed experts go further under it: their grouped matmuls keep what their operand is recomputed +# from, the gated product's inputs or the dispatched tokens, instead of the operand -- mpmd/jax/ds_ep.Recompute.) +_LEAN = contextvars.ContextVar("lean_residuals", default=False) + + +@contextlib.contextmanager +def lean_residuals(on=True): + token = _LEAN.set(on) + try: + yield + finally: + _LEAN.reset(token) + + +def lean(): + return _LEAN.get() + + +def gated_product(h0, h1, act, dtype): + """act(h0) * h1 in `dtype` -- under jax.checkpoint when lean (its VJP then keeps h0 and h1 only).""" + f = lambda a, b: (activation_fn(act)(a) * b).astype(dtype) + return (jax.checkpoint(f) if lean() else f)(h0, h1) + + +def rms_norm(params, x, config: DeepSeekConfig): + """`normalizations.RMSNorm.__call__`. + + The scale is FSDP-sharded on its only axis, the feature axis the batch- + sharded activation leaves whole. Under explicit their product would put + the same mesh axis on the batch and on the features, which is illegal, so + the result is typed like the activation and XLA aligns the scale (MaxText + reshards it to the activation's last-dim spec, `normalizations.align_scale_with_normalized_axis`). + The product is an einsum, i.e. a dot_general, so it takes the precision. + + Under lean residuals the whole norm runs under jax.checkpoint: its VJP + keeps x and the scale, and its backward recomputes the bf16 normalised + activation the scale's gradient reads (a VJP of the product alone would + keep it, beside x). + """ + + def norm(x, scale): + x = jnp.asarray(x, jnp.float32) + mean2 = jnp.mean(jax.lax.square(x), axis=-1, keepdims=True) + y = jnp.asarray(x * jax.lax.rsqrt(mean2 + config.normalization_layer_epsilon), config.dtype) + scale = jnp.asarray(scale, config.dtype) + return mode.einsum("...k,k->...k", y, scale, out_spec=mode.act_spec(y.ndim), precision=precision_or_none(config)) + + return (jax.checkpoint(norm) if lean() else norm)(x, params["scale"]) + + +def rms_norm_read(params, x, config: DeepSeekConfig, read): + """`read(rms_norm(params, x, config))`, `read` being what reads the norm's + output: the projections that take it as their lhs, then anything + elementwise. + + Under lean residuals one jax.checkpoint runs both, saving only dot + products without batch dims -- the projections' outputs, where read's + backward needs them. A projection's VJP would keep its lhs, the norm's + output, beside the norm's own input; here the backward recomputes it from + that input (Megatron's layernorm recompute), and read's elementwise values + with it, but no projection. (The scale's product has a batch dim, the + feature axis: it is recomputed, elementwise as it is.) So `read` holds + matmuls and elementwise ops only: a collective or a custom-VJP kernel's + outputs would be recomputed too. Inside, the norm and `read` trace + without lean residuals: the checkpoint's policy, not theirs, decides what + nested checkpoints keep, and theirs would only recompute the same values a + second time. Outside lean residuals this is the plain composition. + """ + if not lean(): + return read(rms_norm(params, x, config)) + + def f(x, params): + with lean_residuals(False): + return read(rms_norm(params, x, config)) + + return jax.checkpoint(f, policy=jax.checkpoint_policies.dots_with_no_batch_dims_saveable)(x, params) + + +def dense_general(params, inputs, config: DeepSeekConfig, axis=(-1,)): + """`linears.DenseGeneral.__call__`. + + The kernel is `in_features_shape + out_features_shape`; `axis` names the + input axes contracted against the leading kernel axes. + + FSDP stores the kernel sharded on its biggest axis. That is an OUTPUT + axis for MLA's `out`, the head, the dense layers' `wi_*` and, at DS-S and + DeepSeek-V3 sizes, the shared expert's `wo` (at some test sizes `wq_b` / + `wkv_b` too). Under explicit an output-split matmul has no legal result + type of its own, so it is typed like the activation: the kernel stays + sharded and XLA gathers it. + """ + kernel = jnp.asarray(params["kernel"], config.dtype) + inputs = jnp.asarray(inputs, config.dtype) + norm_axis = tuple(a % inputs.ndim for a in axis) + contract_ind = tuple(range(len(axis))) + out_ndim = inputs.ndim + kernel.ndim - 2 * len(axis) + out = mode.dot_general( + inputs, + kernel, + ((norm_axis, contract_ind), ((), ())), + out_spec=mode.act_spec(out_ndim), + precision=precision_of(config), + ) + if "bias" in params: + out += jnp.asarray(params["bias"], config.dtype) + return out + + +def embed_lookup(params, tokens, config: DeepSeekConfig): + """`embeddings.Embed.__call__` -- cast the table to bf16 first, then gather. + + The table is never gathered: a row lookup in a vocab-sharded table is a + local masked gather plus a reduction of the `[B, L, emb]` result, and + gathering a 129k-row table to replicated per lookup would cost far more + (MaxText's explicit lookup leaves it sharded too). + + Under explicit the table is looked up with `.at[].get(out_sharding=)`, + which jax runs as an auto_axes island (`mode.take`). + """ + table = jnp.asarray(params["embedding"], config.dtype) + ids = tokens.astype(jnp.int32) + return mode.take(table, ids, out_spec=mode.act_spec(ids.ndim + 1)) + + +_ACTIVATIONS = { + "silu": jax.nn.silu, + "swish": jax.nn.silu, + "gelu": jax.nn.gelu, + "relu": jax.nn.relu, + "sigmoid": jax.nn.sigmoid, + "tanh": jnp.tanh, + "linear": lambda x: x, +} + + +def activation_fn(name: str): + return _ACTIVATIONS[name] + + +def mlp_block(params, inputs, config: DeepSeekConfig): + """`linears.MlpBlock.__call__` -- gated MLP with `wi_0`/`wi_1`/`wo`.""" + activated = None + for idx, act in enumerate(config.mlp_activations): + y = dense_general(params[f"wi_{idx}"], inputs, config) + y = activation_fn(act)(y) + activated = y if activated is None else activated * y + activated = jnp.asarray(activated, config.dtype) + return dense_general(params["wo"], activated, config) diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/maxtext_reference.py b/src/maxtext/experimental/mpmd/jax/deepseek/maxtext_reference.py new file mode 100644 index 0000000000..1c434398a5 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/maxtext_reference.py @@ -0,0 +1,448 @@ +# 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. + +"""MaxText's own DeepSeek-V3 (NNX), built and driven as the reference this port is held to. + +`build` resolves a MaxText config and builds MaxText's NNX DeepSeek-V3 on one device; `convert.from_nnx_model` +copies its weights into this port's parameter tree. The pairs below run the same computation on both sides: + + * `maxtext_logits` / `port_logits`: the forward pass over one batch. + * `moe_block` + `maxtext_moe_vjp` / `port_moe_vjp`: one MoE layer's routed-and-shared block, unscanned, forward + and backward on the same activations and output cotangent, with the block's load-balance loss and routed-bias + update. + * `maxtext_train` / `port_train`: optimizer steps. The MaxText side is assembled out of MaxText's and optax's + own pieces (`max_utils.cross_entropy_with_logits`, `optax.clip_by_global_norm`, `optax.adamw`, + `maxtext_utils.create_learning_rate_schedule`), driven the way `trainers/pre_train/train.py` drives them on the + NNX path; the port side is `deepseek/train.py`, which has no optax and no Flax. + +Every computation is jitted with `numerics()` as its XLA compile options. Then whatever the two programs compute +with the same ops comes out bit-identical. What they compute differently: + + * The norms. MaxText stacks the scanned layers' weights at `param_scan_axis` (1), the port at axis 0, so a + global norm sums the same squares in another order: the gradient norm, and through the clip every update after + the first (AdamW's first update divides the gradient by its own magnitude), agree to fp32 rounding. + * The routed experts under megablox, MaxText's default. Off TPU MaxText interprets megablox's Pallas kernels; + the port runs `jax.lax.ragged_dot` with fp32 accumulation. The weight gradients differ by design: megablox's + `tgmm` sums each expert's rows in a tile order no XLA-level op reproduces. The expert outputs and input + gradients agree but for a rare bf16 rounding, which in the whole model spreads: attention carries it to every + later token, the backward to every layer below. With `megablox=False` MaxText runs `jax.lax.ragged_dot` too, + and `config.from_maxtext` drops the port's fp32 accumulation to match. But MaxText pads a grouped matmul's + rows (tokens x top-k) with zeros to a multiple of `wi_tile_fwd_batch_seq`, 512 by default, and the port does + not; on CPU a matmul over the padded rows can round differently, most often the expert weight gradients, which + sum over the rows. A tile that divides the rows pads none. + +On one CPU device at `TINY`, over init seeds 0-23: with `megablox=False` and the rows unpadded, the logits, every +gradient leaf and the loss of three steps are bit-exact at every seed, the norms within 1.2e-6 and the parameters +within 1.1e-7 (relative to each leaf's largest magnitude). Padded to 512 rows, on jax 0.11.1, the first gradients +differed at 16 of the seeds (up to 2.2e-2) and the later losses at 9. With megablox, an isolated MoE block's +output, input gradient and non-expert parameter gradients are bit-exact at every seed and the expert weight +gradients within 7.4e-4; the whole model's logits differ at seeds 19 and 20 (from one token on, up to 7.5e-3), and +its first gradients at 2 of seeds 0-8 (up to 1.8e-2). + +One device is deliberate: on more than one, MaxText shards its activations through `with_logical_constraint` while +the port lets XLA choose, so the two sum weight gradients over a different partition of the batch. + +Measured before the port, against an older MaxText, on one v6e chip with MaxText's defaults (megablox, the splash +kernel) and excess precision off, at DeepSeek-V3's 61-layer shapes with vocabulary 2048 and 64 tokens (3 steps) and +at deepseek3-tiny with 2048 tokens (2 steps): the loss, the gradient norm and the parameter norm bit-exact at every +step, and every gradient leaf but the three stacked expert weights bit-exact (at 2048 tokens those within 2.4e-7 +absolute; with `gmm_exact_drhs`, which reproduces `tgmm`'s order at num_experts times the FLOPs, all 31 leaves at +the 61-layer shapes). +""" + +import os + +import jax +import jax.numpy as jnp +import numpy as np +import optax +from flax import linen as nn +from flax import nnx + +from maxtext.common.common_types import MODEL_MODE_TRAIN +from maxtext.configs import pyconfig +from maxtext.utils import max_utils +from maxtext.utils import maxtext_utils +from maxtext.utils import model_creation_utils +from maxtext.utils.globals import MAXTEXT_CONFIGS_DIR + +from maxtext.experimental.mpmd.jax.deepseek import convert +from maxtext.experimental.mpmd.jax.deepseek import model as ds_model +from maxtext.experimental.mpmd.jax.deepseek import moe as ds_moe +from maxtext.experimental.mpmd.jax.deepseek import train as ds_train + +BASE_OVERRIDES = { + "run_name": "parity", + "enable_checkpointing": False, + "dataset_type": "synthetic", + "skip_jax_distributed_system": True, + "override_model_config": True, +} + +# deepseek3-tiny cut down to build and run on CPU in seconds: 1 dense and 3 MoE layers of 8 experts (top 2). +# max_target_length < 128 makes MaxText autoselect the bf16 dot-product attention, which the port mirrors. +TINY = { + "base_num_decoder_layers": 4, + "first_num_dense_layers": 1, + "base_emb_dim": 64, + "base_mlp_dim": 128, + "base_moe_mlp_dim": 64, + "num_experts": 8, + "num_experts_per_tok": 2, + "vocab_size": 256, + "max_target_length": 64, + "max_prefill_predict_length": 16, + "per_device_batch_size": 1.0, +} + +# The stacked expert weights of an MoE layer (`MoeBlock_0/`), whose gradients megablox computes with `tgmm`. +EXPERT_WEIGHTS = ("wi_0", "wi_1", "wo") + +METRICS = ("loss", "total_weights", "raw_grad_norm", "grad_norm", "param_norm") + + +def numerics(backend=None): + """The XLA compile options every computation here is jitted with. + + * `xla_allow_excess_precision=False`. The option (on by default) lets XLA drop an intermediate bf16 rounding + when it fuses the producer into its consumer. Which roundings survive then depends on fusion decisions, and + MaxText's graph and this one fuse differently -- MaxText carries extra `with_logical_constraint` and + `out_sharding` nodes -- so two op-for-op identical programs come out apart. On TPU that is up to a bf16 ulp + per layer (every MLA and MoE sub-block compared alone is bit-exact either way; only the fused whole diverges); + on CPU, 3 of the 31 gradient leaves of `TINY` with `megablox=False`. A measurement knob, not a training one. + * On CPU, `xla_cpu_experimental_ynn_fusion_type=""`: no YNNPACK fusions, so every bf16 matmul accumulates in fp32 + through XLA's own emitters, the same on any thread count. With them on (the default since jax 0.11.2) a bf16 + weight gradient's contraction depends on the thread count. + + Passed per compile rather than through XLA_FLAGS, they apply whatever flags the process was started with, and + change nothing else in it. + """ + options = {"xla_allow_excess_precision": False} + if (backend or jax.default_backend()) == "cpu": + options["xla_cpu_experimental_ynn_fusion_type"] = "" + return options + + +def _jit(fn, compiler_options): + return jax.jit(fn, compiler_options=numerics() if compiler_options is None else compiler_options) + + +def build(preset=None, *, devices=None, config_path=None, **overrides): + """Resolves a MaxText config and builds its NNX DeepSeek-V3, on `devices` (the first device by default). + + Args: + preset: config overrides on top of `BASE_OVERRIDES`; `TINY` when None. + devices: the devices of the model's mesh. One keeps the comparison exact (see the module docstring). + config_path: the base config; MaxText's `configs/base.yml` when None. + **overrides: more config overrides, applied last. `model_name` (default `deepseek3-tiny`) picks the model. + + Returns: + `(config, model)`. The config's global batch sizes count every device of the process; `batch_size` counts the + model's. + """ + merged = {**BASE_OVERRIDES, **(TINY if preset is None else preset), **overrides} + # `model_name` selects a yml under configs/models and so has to travel in argv, not as a keyword override. + model_name = merged.pop("model_name", "deepseek3-tiny") + config_path = config_path or os.path.join(MAXTEXT_CONFIGS_DIR, "base.yml") + cfg = pyconfig.initialize([None, config_path, f"model_name={model_name}"], **merged) + devices = list(devices) if devices is not None else jax.devices()[:1] + with nn.logical_axis_rules(cfg.logical_axis_rules): + create = model_creation_utils.get_nnx_create_model_fn( + cfg, + mesh=None, + devices=devices, + model_mode=MODEL_MODE_TRAIN, + rng_key=jax.random.PRNGKey(cfg.init_weights_seed), + ) + model = create() + return cfg, model + + +def batch_size(cfg, model): + """The global batch over the model's own mesh: `per_device_batch_size` rows a device.""" + return int(cfg.per_device_batch_size * model.mesh.size) + + +def forward_batch(cfg, rows): + """A plain non-packed forward batch of `rows` sequences: `(tokens, positions, segment_ids)`.""" + length = int(cfg.max_target_length) + rng = np.random.default_rng(1234) + tokens = jnp.asarray(rng.integers(0, cfg.vocab_size, size=(rows, length)), jnp.int32) + positions = jnp.broadcast_to(jnp.arange(length, dtype=jnp.int32), (rows, length)) + segment_ids = jnp.ones((rows, length), jnp.int32) + return tokens, positions, segment_ids + + +def train_batch(cfg, rows): + """MaxText's synthetic training batch (`SyntheticDataIterator`) of `rows` sequences.""" + return ds_train.synthetic_batch( + vocab_size=cfg.vocab_size, + batch_size=rows, + seq_len=int(cfg.max_target_length), + packing=bool(cfg.packing), + max_segments_per_seq=int(cfg.max_segments_per_seq), + ) + + +# --------------------------------------------------------------------------- # +# Forward +# --------------------------------------------------------------------------- # + + +def maxtext_logits(cfg, model, batch, *, compiler_options=None): + """MaxText's logits for a `forward_batch`.""" + graphdef, state = nnx.split(model) + + def forward(state, tokens, positions, segment_ids): + return nnx.merge(graphdef, state)( + decoder_input_tokens=tokens, + decoder_positions=positions, + decoder_segment_ids=segment_ids, + enable_dropout=False, + model_mode=MODEL_MODE_TRAIN, + ) + + with nn.logical_axis_rules(cfg.logical_axis_rules): + return jax.block_until_ready(_jit(forward, compiler_options)(state, *batch)) + + +def port_logits(port_cfg, params, aux, batch, *, compiler_options=None): + """The port's logits for a `forward_batch`, from `convert.from_nnx_model`'s `(params, aux)`.""" + + def forward(params, aux, tokens, positions, segment_ids): + return ds_model.forward(params, aux, tokens, positions, segment_ids, port_cfg) + + return jax.block_until_ready(_jit(forward, compiler_options)(params, aux, *batch)) + + +# --------------------------------------------------------------------------- # +# One MoE block +# --------------------------------------------------------------------------- # + + +def moe_block(model, cfg, layer=0): + """Returns `decoder.moe_layers.DeepSeekMoeBlock_0` with MoE layer `layer` sliced out. + + The NNX decoder keeps the MoE layers as one module whose parameters carry an extra scan axis at + `cfg.param_scan_axis`; the module body itself is scan-agnostic, so dropping that axis makes it directly callable. + """ + block = model.decoder.moe_layers.DeepSeekMoeBlock_0 + graphdef, params, rest = nnx.split(block, nnx.Param, ...) + n_layers = cfg.num_decoder_layers - cfg.first_num_dense_layers + + def slicer(axis): + # `nnx.Param` is stacked at `param_scan_axis`; everything else (the `MoEBiasVar` routing bias) at axis 0. + def slice_leaf(x): + x = jnp.asarray(x) + if x.ndim > axis and x.shape[axis] == n_layers: + return jnp.take(x, layer, axis=axis) + return x + + return slice_leaf + + return nnx.merge(graphdef, jax.tree.map(slicer(cfg.param_scan_axis), params), jax.tree.map(slicer(0), rest)) + + +def moe_block_params(block): + """The port's `moe.routed_and_shared_moe` parameters of one unscanned `moe_block`, the routing bias included.""" + routed = block.MoeBlock_0 + shared = block.shared_experts + return { + "MoeBlock_0": { + "gate": { + "kernel": jnp.asarray(routed.gate.kernel.get_value()), + "bias": jnp.asarray(routed.gate.bias.get_value()), + }, + **{name: jnp.asarray(getattr(routed, name).get_value()) for name in EXPERT_WEIGHTS}, + }, + "shared_experts": { + name: {"kernel": jnp.asarray(getattr(shared, name).kernel.get_value())} for name in EXPERT_WEIGHTS + }, + } + + +def _vjp(fn, params, x, ct, compiler_options): + """`(out, d_params, d_x, extras)` of `fn(params, x) -> (out, extras)`, `out` pulled back from the cotangent `ct`.""" + out, vjp, extras = _jit(lambda p, x: jax.vjp(fn, p, x, has_aux=True), compiler_options)(params, x) + d_params, d_x = _jit(lambda f, c: f(c), compiler_options)(vjp, ct) + return out, d_params, d_x, extras + + +def maxtext_moe_vjp(cfg, block, x, ct, *, compiler_options=None): + """`(out, d_params, d_x, (lb_loss, bias_updates))` of MaxText's block, `d_params` in the port's layout (none for + the routing bias). + + `lb_loss` and `bias_updates` are the block's other two outputs, its load-balance loss and its routed bias's update + (each None when its weight is zero), as computed and not differentiated. + """ + graphdef, params, rest = nnx.split(block, nnx.Param, ...) + + def fn(p, x): + out, lb_loss, bias_updates = nnx.merge(graphdef, p, rest, copy=True)(x) + return out, (lb_loss, bias_updates) + + with nn.logical_axis_rules(cfg.logical_axis_rules): + out, d_params, d_x, extras = _vjp(fn, params, x, ct, compiler_options) + return out, convert.tree_from_nnx_state(d_params, param_scan_axis=0), d_x, extras + + +def port_moe_vjp(port_cfg, params, x, ct, *, compiler_options=None): + """`(out, d_params, d_x, (lb_loss, bias_updates))` of `moe.routed_and_shared_moe`, `d_params` without the routing + bias's entry; the last two as `maxtext_moe_vjp`'s. + + The bias has to stay inside the traced parameter tree on this side: hoisting it into a jit constant lets XLA fold + the `+ bias` away, which perturbs the bf16 gate logits enough to flip a few top-k selections. MaxText produces no + cotangent for it (a `MoEBiasVar`), so its entry is dropped from the gradient. + + `lb_loss` is MaxText's Switch-style loss even under `moe_use_megatron_seq_aux_loss`: the sequence-wise one + DeepSeek-V3 trains with is ds_ep's `seq_aux_loss`. + """ + + def fn(p, x): + out, lb_loss, bias_updates = ds_moe.routed_and_shared_moe(p, x, port_cfg) + return out, (lb_loss, bias_updates) + + out, d_params, d_x, extras = _vjp(fn, params, x, ct, compiler_options) + d_params["MoeBlock_0"]["gate"].pop("bias") + return out, d_params, d_x, extras + + +# --------------------------------------------------------------------------- # +# Optimizer steps +# --------------------------------------------------------------------------- # + + +def train_config(cfg, steps): + """The port's `TrainConfig` from MaxText's resolved config.""" + return ds_train.TrainConfig( + steps=steps, + learning_rate=cfg.learning_rate, + learning_rate_final_fraction=cfg.learning_rate_final_fraction, + learning_rate_schedule_steps=cfg.learning_rate_schedule_steps, + warmup_steps_fraction=cfg.warmup_steps_fraction, + lr_schedule_type=cfg.lr_schedule_type, + adam_b1=cfg.adam_b1, + adam_b2=cfg.adam_b2, + adam_eps=cfg.adam_eps, + adam_eps_root=cfg.adam_eps_root, + adam_weight_decay=cfg.adam_weight_decay, + gradient_clipping_threshold=cfg.gradient_clipping_threshold, + z_loss_multiplier=cfg.z_loss_multiplier, + ) + + +def maxtext_loss(model, cfg, batch): + """`train.py::loss_fn`, NNX branch, stripped to what this config reaches.""" + logits = model( + decoder_input_tokens=batch["inputs"], + decoder_positions=batch["inputs_position"], + decoder_segment_ids=batch["inputs_segmentation"], + enable_dropout=False, + model_mode=MODEL_MODE_TRAIN, + ) + one_hot_targets = jax.nn.one_hot(batch["targets"], cfg.vocab_size) + xent, z_loss = max_utils.cross_entropy_with_logits(logits, one_hot_targets, z_loss=cfg.z_loss_multiplier) + xent = xent * (batch["targets_segmentation"] != 0) + z_loss = z_loss * (batch["targets_segmentation"] != 0) + xent_sum = jnp.sum(xent) + total_weights = jnp.sum(batch["targets_segmentation"] != 0) + loss = xent_sum / (total_weights + 1e-8) + aux = {"total_weights": total_weights, "z_loss": jnp.sum(z_loss) / (total_weights + 1e-8)} + return loss, aux + + +def maxtext_train(cfg, model, batch, steps, *, compiler_options=None): + """`steps` MaxText optimizer steps from the model's weights (the model itself is left as it is). + + Returns: + `(history, params, raw_grads)`: each step's `METRICS` as float64 numpy scalars, the final parameters and the + first step's unclipped gradients, both in the port's layout. + """ + graphdef, params_state, rest = nnx.split(model, nnx.Param, ...) + schedule = maxtext_utils.create_learning_rate_schedule(cfg) + tx = optax.adamw( + learning_rate=schedule, + b1=cfg.adam_b1, + b2=cfg.adam_b2, + eps=cfg.adam_eps, + eps_root=cfg.adam_eps_root, + weight_decay=cfg.adam_weight_decay, + mu_dtype="float32", + ) + clip = optax.clip_by_global_norm(cfg.gradient_clipping_threshold) + opt_state = tx.init(params_state) + + def diff_wrapper(curr_params, rest_state): + local_model = nnx.merge(graphdef, curr_params, rest_state, copy=True) + return maxtext_loss(local_model, cfg, batch) + + def step(params_state, rest_state, opt_state): + (loss, aux), raw_grads = jax.value_and_grad(diff_wrapper, argnums=0, has_aux=True)(params_state, rest_state) + grads, _ = clip.update(raw_grads, None, None) + updates, opt_state = tx.update(grads, opt_state, params_state) + params_state = optax.apply_updates(params_state, updates) + metrics = { + "loss": loss, + "total_weights": aux["total_weights"], + "raw_grad_norm": max_utils.l2norm_pytree(raw_grads), + "grad_norm": max_utils.l2norm_pytree(grads), + "param_norm": max_utils.l2norm_pytree(params_state), + } + return params_state, opt_state, raw_grads, metrics + + history = [] + raw_grads0 = None + with nn.logical_axis_rules(cfg.logical_axis_rules): + step = _jit(step, compiler_options) + for _ in range(steps): + params_state, opt_state, raw_grads, metrics = step(params_state, rest, opt_state) + if raw_grads0 is None: + raw_grads0 = raw_grads + history.append(jax.tree.map(lambda x: np.asarray(x, np.float64), metrics)) + return ( + history, + convert.tree_from_nnx_state(params_state, param_scan_axis=cfg.param_scan_axis), + convert.tree_from_nnx_state(raw_grads0, param_scan_axis=cfg.param_scan_axis), + ) + + +def port_train(port_cfg, params, aux, batch, train_cfg, *, compiler_options=None): + """`train_cfg.steps` optimizer steps of the port, returning what `maxtext_train` does.""" + schedule = ds_train.learning_rate_schedule(train_cfg) + opt_state = ds_train.adamw_init(params, train_cfg) + + def step(params, opt_state): + grad_fn = jax.value_and_grad(ds_train.compute_loss, has_aux=True) + (loss, metrics), raw_grads = grad_fn(params, aux, batch, port_cfg, train_cfg) + grads = ds_train.clip_by_global_norm(raw_grads, train_cfg.gradient_clipping_threshold) + updates, opt_state = ds_train.adamw_update(grads, opt_state, params, train_cfg, schedule) + params = ds_train.apply_updates(params, updates) + out = { + "loss": loss, + "total_weights": metrics["total_weights"], + "raw_grad_norm": ds_train.global_norm(raw_grads), + "grad_norm": ds_train.global_norm(grads), + "param_norm": ds_train.global_norm(params), + } + return params, opt_state, raw_grads, out + + step = _jit(step, compiler_options) + history = [] + raw_grads0 = None + for _ in range(train_cfg.steps): + params, opt_state, raw_grads, metrics = step(params, opt_state) + if raw_grads0 is None: + raw_grads0 = raw_grads + history.append(jax.tree.map(lambda x: np.asarray(x, np.float64), metrics)) + return history, params, raw_grads0 diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/model.py b/src/maxtext/experimental/mpmd/jax/deepseek/model.py new file mode 100644 index 0000000000..80838ab9fc --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/model.py @@ -0,0 +1,314 @@ +# 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 DeepSeek-V3 decoder stack, as plain functions over parameter pytrees. + +Mirrors MaxText's `models.models.Transformer` + `layers.nnx_decoders.NNXDecoder` + +`models.deepseek` for `MODEL_MODE_TRAIN`. + +Parameter layout differs from MaxText in exactly one way: scanned layers are +stacked at **axis 0** (natural for `jax.lax.scan`), whereas MaxText moves +`nnx.Param` leaves to `param_scan_axis = 1`. `convert.py` bridges the two. + +The router bias (`gate.bias`) lives in a separate `aux` pytree rather than in +`params`, because MaxText stores it as a `MoEBiasVar` -- not an `nnx.Param` -- +and therefore never differentiates it. + +The model code imports jax and numpy (and, for the 'tokamax_splash' kernel, +tokamax) and never MaxText; only the reference it is held to imports MaxText +(`maxtext_reference.py`, which deepseek_maxtext_parity_test drives), which is +what lets MaxText run next to it as a reference. + +Nothing in this file shards: the ops that need a sharding under explicit +(embedding and RoPE gathers, FSDP matmuls, norm scales, the MoE dispatch) +live in `layers` / `rope` / `moe` and go through +`maxtext.experimental.mpmd.jax.sharding_mode`, which reads the mode off the mesh in +context. The same `forward` runs on one device, under auto and under +explicit. +""" + +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.deepseek import attention +from maxtext.experimental.mpmd.jax.deepseek import layers +from maxtext.experimental.mpmd.jax.deepseek import moe +from maxtext.experimental.mpmd.jax.deepseek import rope +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig + + +# The remat policies by MaxText name +# (`nnx_decoders.NNXDecoder.get_remat_policy`), as data: the +# `checkpoint_name`s each one saves HERE (`save_only_these_names`). Two +# differ from MaxText's: its 'minimal' also saves the MLP / MoE outputs +# (`mlpwi_0`, `mlpwi_1`, `mlpwi`, `mlpwo`), which neither port emits, and its +# 'save_dot_except_mlp' saves no `context` (that is its +# 'save_dot_with_context_except_mlp'). (MaxText's lists also hold `kv_proj`, +# which no port here emits.) 'none' and 'full' save nothing, i.e. recompute +# everything (`NNXDecoder.get_remat_policy`). The one table: `remat_policy_for` builds +# the policy from it, for this port and for the Qwen3.5 port alike. +REMAT_POLICIES = { + "none": (), + "full": (), + "save_out_proj": ("out_proj",), + "minimal": ("query_proj", "value_proj", "key_proj", "qkv_proj", "out_proj"), + "save_dot_except_mlp": ("query_proj", "value_proj", "key_proj", "qkv_proj", "context", "out_proj"), + "save_qkv_proj": ("query_proj", "value_proj", "key_proj", "qkv_proj"), +} + + +def remat_policy_for(config: DeepSeekConfig): + """`nnx_decoders.NNXDecoder.get_remat_policy`.""" + name = config.remat_policy or "none" + if name not in REMAT_POLICIES: + raise ValueError(f"unsupported remat_policy: {name}") + names = REMAT_POLICIES[name] + return jax.checkpoint_policies.save_only_these_names(*names) if names else None + + +def _merge(base, extra): + """Shallow-recursive dict merge; `extra` wins. Used to splice `aux` in.""" + if not extra: + return base + out = dict(base) + for key, value in extra.items(): + if isinstance(out.get(key), dict) and isinstance(value, dict): + out[key] = _merge(out[key], value) + else: + out[key] = value + return out + + +def decoder_layer(params, x, positions, segment_ids, freqs_cis, config, is_moe): + """`DeepSeekGenericLayer.self_attention_with_norm_op` + the MLP/MoE branch. + + `deepseek.DeepSeekGenericLayer` (shared body), `DeepSeekDenseLayer.__call__` + (dense), `DeepSeekMoELayer.__call__` (MoE). + The residual stream stays bf16 end to end; nothing here promotes to fp32. + """ + x = jax.ad_checkpoint.checkpoint_name(x, "decoder_layer_input") + + lnx = layers.rms_norm(params["pre_self_attention_layer_norm"], x, config) + attention_lnx = attention.mla(params["self_attention"], lnx, positions, segment_ids, freqs_cis, config) + intermediate_inputs = x + attention_lnx # residual #1: adds `x`, not `lnx`. + + hidden_states = layers.rms_norm(params["post_self_attention_layer_norm"], intermediate_inputs, config) + if is_moe: + mlp_lnx, lb_loss, updates = moe.routed_and_shared_moe(params["DeepSeekMoeBlock_0"], hidden_states, config) + # Neither is plumbed out of the layer stack: there is no aux-loss term in + # `train.compute_loss` and no router-bias update after the step. Dropping + # them would train a different model from MaxText without a word, so a + # config that asks for either is refused until they are. + if lb_loss is not None or updates is not None: + raise NotImplementedError( + "load_balance_loss_weight > 0 and routed_bias_update_rate > 0 are not " + "supported: the aux loss and the bias update are computed per layer but " + "never reach the loss or the optimizer" + ) + else: + mlp_lnx = layers.mlp_block(params["mlp"], hidden_states, config) + + return mlp_lnx + intermediate_inputs # residual #2: adds the post-attention residual. + + +def _apply_stack(stack_params, stack_aux, x, positions, segment_ids, freqs_cis, config, is_moe): + """`nnx_decoders.NNXDecoder._apply_layers_sequentially`. + + `jax.lax.scan` + `jax.checkpoint` are forward-identity; this is a plain + sequential loop over the layers. + """ + + def body(carry, layer): + layer_params, layer_aux = layer + y = decoder_layer( + _merge(layer_params, layer_aux), + carry, + positions, + segment_ids, + freqs_cis, + config, + is_moe, + ) + return y, None + + if config.scan_layers: + fn = jax.checkpoint(body, policy=remat_policy_for(config), prevent_cse=False) + out, _ = jax.lax.scan(fn, x, (stack_params, stack_aux), unroll=1) + return out + + num_layers = jax.tree.leaves(stack_params)[0].shape[0] + for i in range(num_layers): + sliced = jax.tree.map(lambda leaf, i=i: leaf[i], (stack_params, stack_aux)) + x, _ = body(x, sliced) + return x + + +def forward(params, aux, tokens, positions, segment_ids, config: DeepSeekConfig, freqs_cis=None): + """`Transformer.__call__` for training. Returns `[B, L, vocab]` logits. + + Args: + params: differentiable parameter pytree, structured as `param_avals` + (`init.init_params` draws one, `convert.py` reads one off MaxText). + aux: non-differentiable state -- the MoE router biases. + tokens: `[B, L]` int32 input token ids. + positions: `[B, L]` int32 token positions. + segment_ids: `[B, L]` int32 packing segment ids (all ones when not packing). + config: model config. + freqs_cis: optional precomputed YaRN table; built here if omitted. + + MaxText rebuilds the (163840, 32) YaRN table inside every attention call; we + build the `max_target_length` prefix once, which is numerically identical and + avoids 42 MB of redundant work per layer. + + That one is worth spelling out, because it is the single largest term in the + step-time gap. XLA does not fold the table build into the position gather: + the optimized HLO materialises both `f32[163840, 32]` halves of + `exp(1j * outer(arange(163840), freqs))` and only then gathers the 2048 rows + the batch actually uses, which takes MLA's HBM traffic from 109 MB to 275 MB. + Slicing the table afterwards does not help -- it has to be built short. On + one v6e chip at MaxText's deepseek3-tiny shapes (seq 2048, 61 layers, + remat 'full', batch 1) that is 0.39 ms per layer, bit-identical output + either way: 23 ms per forward pass, doubled to 47 ms per step by full + remat, out of a 74 ms total step-time gap to MaxText. + """ + if freqs_cis is None: + freqs_cis = rope.freqs_cis_for(config, config.max_target_length) + + y = layers.embed_lookup(params["token_embedder"], tokens, config) + y = y.astype(config.dtype) # NNXDecoder._apply_embedding + + decoder = params["decoder"] + aux_decoder = (aux or {}).get("decoder", {}) + + # `first_num_dense_layers=0` is a legal MaxText config (a fully-MoE model); + # the converter then emits no `dense_layers` key at all. + if "dense_layers" in decoder: + y = _apply_stack( + decoder["dense_layers"], + aux_decoder.get("dense_layers", {}), + y, + positions, + segment_ids, + freqs_cis, + config, + is_moe=False, + ) + y = _apply_stack( + decoder["moe_layers"], + aux_decoder.get("moe_layers", {}), + y, + positions, + segment_ids, + freqs_cis, + config, + is_moe=True, + ) + + y = layers.rms_norm(decoder["decoder_norm"], y, config) + logits = layers.dense_general(decoder["logits_dense"], y, config) + if config.cast_logits_to_fp32: + logits = logits.astype(jnp.float32) # NNXDecoder.apply_output_head + return logits + + +# ------------------------------------------------------------- param avals +# The two layer stacks under `decoder`, each with the layer axis at 0. +DENSE = "dense_layers" +MOE = "moe_layers" + + +def _sds(shape, dtype): + """`jax.ShapeDtypeStruct` with plain-int dims.""" + return jax.ShapeDtypeStruct(tuple(int(d) for d in shape), dtype) + + +def _layer_avals(config: DeepSeekConfig, n: int, is_moe: bool): + """One stacked layer group, `[n, ...]`, matching `convert.from_nnx_state`.""" + wd, emb, heads = config.weight_dtype, config.emb_dim, config.num_query_heads + tree = { + "pre_self_attention_layer_norm": {"scale": _sds((n, emb), wd)}, + "post_self_attention_layer_norm": {"scale": _sds((n, emb), wd)}, + "self_attention": { + "wkv_a": {"kernel": _sds((n, emb, config.kv_lora_rank + config.qk_rope_head_dim), wd)}, + "kv_norm": {"scale": _sds((n, config.kv_lora_rank), wd)}, + "wkv_b": {"kernel": _sds((n, config.kv_lora_rank, heads, config.qk_nope_head_dim + config.v_head_dim), wd)}, + "out": {"kernel": _sds((n, heads, config.v_head_dim, emb), wd)}, + }, + } + att = tree["self_attention"] + if config.q_lora_rank == 0: # a plain projection, see `attention.mla` + att["query"] = {"kernel": _sds((n, emb, heads, config.qk_head_dim), wd)} + else: + att["wq_a"] = {"kernel": _sds((n, emb, config.q_lora_rank), wd)} + att["q_norm"] = {"scale": _sds((n, config.q_lora_rank), wd)} + att["wq_b"] = {"kernel": _sds((n, config.q_lora_rank, heads, config.qk_head_dim), wd)} + if not is_moe: + tree["mlp"] = { + "wi_0": {"kernel": _sds((n, emb, config.mlp_dim), wd)}, + "wi_1": {"kernel": _sds((n, emb, config.mlp_dim), wd)}, + "wo": {"kernel": _sds((n, config.mlp_dim, emb), wd)}, + } + return tree + n_exp, fm = config.num_experts, config.moe_mlp_dim + shared = config.shared_experts * config.shared_expert_mlp_dim + tree["DeepSeekMoeBlock_0"] = { + "MoeBlock_0": { + "gate": {"kernel": _sds((n, emb, n_exp), wd)}, + "wi_0": _sds((n, n_exp, emb, fm), wd), + "wi_1": _sds((n, n_exp, emb, fm), wd), + "wo": _sds((n, n_exp, fm, emb), wd), + }, + "shared_experts": { + "wi_0": {"kernel": _sds((n, emb, shared), wd)}, + "wi_1": {"kernel": _sds((n, emb, shared), wd)}, + "wo": {"kernel": _sds((n, shared, emb), wd)}, + }, + } + return tree + + +def param_avals(config: DeepSeekConfig): + """`jax.ShapeDtypeStruct` tree for the FULL model parameters (`forward`'s + `params`). + + Never materialized; this is the thing that lets a 671B model be described + on a host that could not hold one copy of it. + """ + dec = { + "decoder_norm": {"scale": _sds((config.emb_dim,), config.weight_dtype)}, + "logits_dense": {"kernel": _sds((config.emb_dim, config.vocab_size), config.weight_dtype)}, + MOE: _layer_avals(config, config.num_moe_layers, True), + } + if config.first_num_dense_layers: + dec[DENSE] = _layer_avals(config, config.first_num_dense_layers, False) + return { + "token_embedder": {"embedding": _sds((config.vocab_size, config.emb_dim), config.weight_dtype)}, + "decoder": dec, + } + + +def aux_avals(config: DeepSeekConfig): + """Router-bias tree (`forward`'s `aux`): `[n_moe_layers, num_experts]`, + layer axis at 0.""" + if not config.routed_bias: + return {} + return { + "decoder": { + MOE: { + "DeepSeekMoeBlock_0": { + "MoeBlock_0": {"gate": {"bias": _sds((config.num_moe_layers, config.num_experts), config.weight_dtype)}} + } + } + } + } diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/moe.py b/src/maxtext/experimental/mpmd/jax/deepseek/moe.py new file mode 100644 index 0000000000..f732972b2a --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/moe.py @@ -0,0 +1,419 @@ +# 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. + +"""DeepSeek-V3 MoE block: sigmoid router + routed experts + one shared expert. + +Mirrors MaxText's `layers/moe.py` for `decoder_block: deepseek` and +`model_name: deepseek3*`. The two facts that are easy to get wrong: + + * top-k *selects* on the post-bias scores but *weighs* with the pre-bias + scores (`moe.deepseek_routing`), and + * the renormalisation `w / (sum(w) + 1e-20) * routed_scaling_factor` runs + entirely in bf16 (`moe.deepseek_scale_weights`) -- there is no softmax. + +The routed experts are dispatched by one argsort over every token of the +stage (`routed_experts`; `src/maxtext/experimental/mpmd/jax/sharding_mode.py` for the modes). +Under auto XLA implements it by all-gathering the routing to every device and +running a weight-stationary MoE. Under explicit the tokens are made +replicated first, since a sort over a sharded axis has no type: a correctness +path. +""" + +import functools + +import jax +import jax.numpy as jnp +from jax.sharding import PartitionSpec as P + +from maxtext.experimental.mpmd.jax.deepseek import layers +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig +from maxtext.experimental.mpmd.jax import sharding_mode as mode + + +def route(params, inputs, config: DeepSeekConfig): + """`GateLogit.__call__` + `get_topk` for DeepSeek-V3. + + Returns `(weights, indices)` with shapes `[b, s, k]`. + """ + gate_dtype = jnp.float32 if config.float32_gate_logits else config.dtype + x = jnp.asarray(inputs, gate_dtype) + kernel = jnp.asarray(params["kernel"], gate_dtype) + logits = _gate_logits(x, kernel, config) + pre_bias_logits = layers.activation_fn(config.routed_score_func)(logits) + + gate_logits = pre_bias_logits + if config.routed_bias: + gate_logits = gate_logits + jnp.asarray(params["bias"], gate_dtype) + indices = select_experts(gate_logits, config) + weights = jnp.take_along_axis(pre_bias_logits, indices, axis=-1) + + # deepseek_scale_weights -- bf16 throughout, epsilon outside the sum. + if config.routed_score_func in ("sigmoid", "sqrtsoftplus"): + weights = weights / (weights.sum(-1, keepdims=True) + 1e-20) + weights = weights * config.routed_scaling_factor + return weights, indices + + +def _top_2_in_group_sum(scores_grouped): + """`moe._top_2_in_group_sum`: the two largest scores of each group, summed in + fp32 -- two masked maxima, not a top-k sort (the lowest index of a tie is + the one masked, so a tied pair sums to twice the maximum, as top_k's).""" + max_1 = jnp.max(scores_grouped, axis=-1) + argmax_1 = jnp.argmax(scores_grouped, axis=-1)[..., None] + lane = jax.lax.broadcasted_iota(argmax_1.dtype, scores_grouped.shape, scores_grouped.ndim - 1) + max_2 = jnp.max(jnp.where(lane == argmax_1, -jnp.inf, scores_grouped), axis=-1) + return max_1.astype(jnp.float32) + max_2.astype(jnp.float32) + + +def expert_group_mask(gate_logits, config: DeepSeekConfig): + """`RoutedMoE.expert_group_mask`: 1 for the experts of each token's + `topk_routing_group` best groups (a group scored by its two best post-bias + scores), 0 elsewhere; `[..., num_experts]` float32.""" + g = config.n_routing_groups + grouped = jnp.reshape(gate_logits, gate_logits.shape[:-1] + (g, -1)) + _, group_idx = jax.lax.top_k(_top_2_in_group_sum(grouped), k=config.topk_routing_group) + group_mask = jnp.sum(jax.nn.one_hot(group_idx, num_classes=g, dtype=jnp.float32), axis=-2) + mask = jnp.broadcast_to(group_mask[..., None], group_mask.shape + (config.num_experts // g,)) + return jnp.reshape(mask, mask.shape[:-2] + (config.num_experts,)) + + +def select_experts(gate_logits, config: DeepSeekConfig): + """`RoutedMoE.deepseek_routing`'s choice: the top-k experts of the post-bias + `gate_logits`, among each token's best groups when `n_routing_groups` is + set (> 0).""" + if config.n_routing_groups > 0: + gate_logits = jnp.where(expert_group_mask(gate_logits, config) > 0, gate_logits, -jnp.inf) + _, indices = jax.lax.top_k(gate_logits, config.num_experts_per_tok) + return indices + + +def _gate_logits(x, kernel, config: DeepSeekConfig): + """`x @ gate.kernel`, typed like the activation: the kernel is FSDP-sharded + on whichever of `[emb, num_experts]` is bigger, an output dim when it is + the expert count.""" + return mode.dot_general( + x, kernel, (((x.ndim - 1,), (0,)), ((), ())), out_spec=mode.act_spec(x.ndim), precision=layers.precision_of(config) + ) + + +def load_balance_loss(indices, probs, config: DeepSeekConfig): + """`moe.RoutedMoE.load_balance_loss`.""" + expert_mask = jax.nn.one_hot(indices, num_classes=config.num_experts, dtype=jnp.int32) + summed = jnp.sum(expert_mask, axis=2) + density = jnp.mean(summed, axis=1) / config.num_experts_per_tok + density_prob = jnp.mean(probs, axis=1) + return jnp.mean(density * density_prob) * (config.num_experts**2) * config.load_balance_loss_weight + + +def bias_update(indices, config: DeepSeekConfig): + """`moe.calculate_load_balance_updates` -- sign rule, no lr.""" + flat = indices.ravel() + counts = jnp.sum(jax.nn.one_hot(flat, config.num_experts, dtype=jnp.int32), axis=0) + average_load = jnp.sum(counts) / config.num_experts + return jnp.sign(average_load - counts) * config.routed_bias_update_rate + + +def _experts_dense(params, inputs, weights, indices, config: DeepSeekConfig): + """`moe.RoutedMoE.dense_matmul` with `capacity_factor <= 0`. + + Every expert on every token, so nothing here crosses the batch shards and + each op is simply typed like the activation: the expert kernels can be + FSDP-sharded on an output dim, and the routing-weight scatter writes at + batch-sharded indices. + """ + b, s, _ = inputs.shape + w0 = jnp.asarray(params["wi_0"], config.dtype) + w1 = jnp.asarray(params["wi_1"], config.dtype) + wo = jnp.asarray(params["wo"], config.dtype) + precision = layers.precision_of(config) + act3, act4 = mode.act_spec(3), mode.act_spec(4) + + layer_w0 = mode.einsum("BSM,EMH->BSEH", inputs, w0, out_spec=act4, precision=precision) + layer_w1 = mode.einsum("BSM,EMH->BSEH", inputs, w1, out_spec=act4, precision=precision) + hidden = (jax.nn.silu(layer_w0) * layer_w1).astype(config.dtype) + intermediate = mode.einsum("BSEH,EHM->BSEM", hidden, wo, out_spec=act4, precision=precision) + + # RoutedMoE.reshape_and_update_weights + dense_weights = jnp.zeros((b, s, config.num_experts), dtype=config.dtype) + batch_idx = jnp.arange(b)[:, None, None] + seq_idx = jnp.arange(s)[None, :, None] + dense_weights = mode.set_at(dense_weights, (batch_idx, seq_idx, indices), weights, out_spec=act3) + + if config.float32_weight_sum: + intermediate = intermediate.astype(jnp.float32) + dense_weights = dense_weights.astype(jnp.float32) + out = mode.einsum("BSEM,BSE->BSM", intermediate, dense_weights, out_spec=act3, precision=precision) + return out.astype(config.dtype) + + +@jax.custom_vjp +def _sort_activations(inputs, sort_indices): + """`moe._sort_activations_custom`. + + The custom VJP matters numerically as well as for speed: the backward pass is + the inverse *permutation* rather than a scatter-add, so no summation happens + where the compiler-generated transpose would have summed. + + Under explicit sharding with rows sharded (the dispatches never hand it + such rows, but a custom VJP must hold for any typed primal) the gather is + typed like `inputs`, so the cotangent comes back typed like `inputs` too, + and the backward undoes the permutation with a scatter rather than with an + argsort, which cannot sort over a sharded axis. Both are pure data + movement, so the values are bit-for-bit those of the gather by the inverse. + """ + sharding = mode.sharding_of(inputs) + if sharding is None: + return inputs[sort_indices, ...] + return inputs.at[sort_indices, ...].get(out_sharding=sharding) + + +def _sort_activations_fwd(inputs, sort_indices): + return _sort_activations(inputs, sort_indices), sort_indices + + +def _sort_activations_bwd(sort_indices, grads): + # `inputs`' cotangent is typed like `grads`, the cotangent of a result + # typed like `inputs` (above). + sharding = mode.sharding_of(grads) + if sharding is None: + return _sort_activations(grads, jnp.argsort(sort_indices)), None + # A permutation writes every row exactly once, so `set` sums nothing. + return jnp.zeros_like(grads).at[sort_indices, ...].set(grads, out_sharding=sharding), None + + +_sort_activations.defvjp(_sort_activations_fwd, _sort_activations_bwd) + + +# `lhs[m, k] * dout[m, n] -> out[g, k, n]`, contracting over the *ragged* axis: +# `megablox`'s `tgmm`, and the only grouped-matmul mode XLA exposes that does +# not cost `num_experts` times the work. +_RAGGED_CONTRACTING = jax.lax.RaggedDotDimensionNumbers( + dot_dimension_numbers=(((0,), (0,)), ((), ())), + lhs_ragged_dimensions=[0], + rhs_group_dimensions=[], +) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(3, 4, 5)) +def _grouped_matmul(lhs, rhs, group_sizes, fp32_accum, exact_drhs, precision=None): + """`kernels/megablox/ops.py:gmm`, expressed with `jax.lax.ragged_dot`. + + megablox is a `jax.custom_vjp` around three Pallas kernels -- `gmm` forward, + `gmm` again for `dlhs`, `tgmm` for `drhs` -- so its three matmuls round + independently and each has to be matched independently. What reproduces + MaxText, measured leaf by leaf against MaxText's `RoutedMoE` (one MoE + layer, both fed the same activations and the same output cotangent): + + * forward: accumulate in fp32 and round once. The kernel accumulates a + tile in fp32 and stores through `preferred_element_type`, so with a + single contraction tile that is exactly an fp32 `ragged_dot` rounded to + bf16. Asking XLA for a bf16 `ragged_dot` instead is off by up to a bf16 + ulp per layer, which the 58-layer stack turns into a visible loss delta. + * `dlhs`: XLA's plain bf16 `ragged_dot` transpose. Deriving it from the + fp32 forward costs ~1.5 orders of magnitude of accuracy against MaxText + (2/31 leaves bit-exact end to end rather than 27/31), so the asymmetry + with the forward is deliberate. + * `drhs`: fp32 `ragged_dot_general` over the ragged axis leaves only `wo` + inexact, and by 2e-5. A masked bf16 `einsum` is bit-exact on every leaf + but contracts `num_experts` slices instead of one, so it is opt-in via + `exact_drhs` (`DeepSeekConfig.gmm_exact_drhs`) -- a parity check turns + it on, training leaves it off. + + `fp32_accum=False` recovers MaxText's `jax_ragged_dot_gmm` fallback + (`megablox=false use_tokamax_gmm=false`), which is bit-exact in both + directions without any of the above. + + `precision` (`layers.precision_or_none`) goes to all three matmuls, the + hand-written transposes included: on TPU a DEFAULT-precision matmul of + fp32 operands is a bf16 pass, which an fp32 parity run at 'highest' would + otherwise inherit from these three alone. + + Under explicit sharding (only the global dispatch reaches it, with the rows + replicated) `ragged_dot` has no sharding rule at all, so the result is + typed like `lhs`; and its transpose would call `ragged_dot_general` without + one, which is why the backward spells the two transposes out. The ragged + (row) axis of `lhs` must not be sharded: XLA's ragged-dot lowering on CPU + rejects it. + """ + accum = jnp.float32 if fp32_accum else lhs.dtype + out = jax.lax.ragged_dot( + lhs, rhs, group_sizes, precision=precision, preferred_element_type=accum, out_sharding=mode.sharding_of(lhs) + ) + return out.astype(lhs.dtype) + + +def _grouped_matmul_fwd(lhs, rhs, group_sizes, fp32_accum, exact_drhs, precision): + out = _grouped_matmul(lhs, rhs, group_sizes, fp32_accum, exact_drhs, precision) + return out, (lhs, rhs, group_sizes) + + +def _grouped_matmul_bwd(fp32_accum, exact_drhs, precision, res, dout): + lhs, rhs, group_sizes = res + # Under explicit, `jax.vjp` of `ragged_dot` fails (its transpose has no + # out_sharding to give the rule-less op), so both transposes are written + # out, typed like the primals: the same products, bit for bit. + lhs_sh, rhs_sh = mode.bwd_out_sharding(lhs), mode.bwd_out_sharding(rhs) + if lhs_sh is None: + dlhs = jax.vjp( + lambda l: jax.lax.ragged_dot(l, rhs, group_sizes, precision=precision, preferred_element_type=lhs.dtype), + lhs, + )[1](dout)[0] + else: + dlhs = jax.lax.ragged_dot( + dout, + jnp.swapaxes(rhs, 1, 2), + group_sizes, + precision=precision, + preferred_element_type=lhs.dtype, + out_sharding=lhs_sh, + ) + + if not fp32_accum and rhs_sh is None: + drhs = jax.vjp( + lambda r: jax.lax.ragged_dot(lhs, r, group_sizes, precision=precision, preferred_element_type=lhs.dtype), + rhs, + )[1](dout)[0] + elif not fp32_accum: + drhs = jax.lax.ragged_dot_general( + lhs, + dout, + group_sizes, + _RAGGED_CONTRACTING, + precision=precision, + preferred_element_type=lhs.dtype, + out_sharding=rhs_sh, + ) + elif exact_drhs: + bounds = jnp.cumsum(group_sizes) + starts = jnp.concatenate([jnp.zeros((1,), bounds.dtype), bounds[:-1]]) + rows = jnp.arange(lhs.shape[0])[:, None] + mask = ((rows >= starts) & (rows < bounds)).astype(lhs.dtype) + drhs = jnp.einsum( + "mk,mn,mg->gkn", lhs, dout, mask, precision=precision, preferred_element_type=lhs.dtype, out_sharding=rhs_sh + ) + else: + drhs = jax.lax.ragged_dot_general( + lhs, + dout, + group_sizes, + _RAGGED_CONTRACTING, + precision=precision, + preferred_element_type=jnp.float32, + out_sharding=rhs_sh, + ) + return dlhs.astype(lhs.dtype), drhs.astype(rhs.dtype), None + + +_grouped_matmul.defvjp(_grouped_matmul_fwd, _grouped_matmul_bwd) + + +def _experts_ragged(params, inputs, weights, indices, config: DeepSeekConfig): + """`moe.RoutedMoE.sparse_matmul` with EP=TP=1. + + Sort tokens by expert, run three grouped matmuls (`_grouped_matmul`), unsort, + then combine in fp32. + + Numerics note: MaxText casts the expert kernels to bf16 *inside* `gmm`, so + their cotangents are bf16 too and every grouped-matmul implementation rounds + them to the same 8-bit mantissa. The forward and every other cotangent match + MaxText bit-for-bit; `wi_0`, `wi_1` and `wo` land on the adjacent bf16 value + for a fraction of their entries because the Pallas `tgmm` sums each group in + a different order -- worst relative 1 ulp (~2.5e-3) in the leaf-by-leaf + comparison against MaxText's `RoutedMoE` (see `_grouped_matmul`), and the + floor for anything that is not that kernel. + """ + b, s, d = inputs.shape + tokens = b * s + k = config.num_experts_per_tok + w0 = jnp.asarray(params["wi_0"], config.dtype) + w1 = jnp.asarray(params["wi_1"], config.dtype) + wo = jnp.asarray(params["wo"], config.dtype) + + # The argsort below is over EVERY token of the stage. Under explicit a sort + # over a batch-sharded axis has no type, so the tokens are made replicated + # first and the result is handed back batch-sharded: the global dispatch, + # spelled out. Under auto XLA makes the same choice by itself (it gathers + # the routing to every device), so this is a type obligation and emits + # nothing there; inside a caller's shard_map it is not explicit either. + out_spec = mode.act_spec(inputs.ndim) + inputs, weights, indices = (mode.retype(t, P()) for t in (inputs, weights, indices)) + + inputs_2d = inputs.reshape(tokens, d) + flat_experts = indices.reshape(-1) + sort_indices = jnp.argsort(flat_experts) + if config.moe_use_direct_token_gather: + # `_route_activations` -- gathers straight into expert order, so the + # backward pass sums the k copies of each token. + sorted_inputs = inputs_2d[sort_indices // k].astype(config.dtype) + else: + replicated_inputs_2d = jnp.repeat(inputs_2d, k, axis=0) + sorted_inputs = _sort_activations(replicated_inputs_2d, sort_indices).astype(config.dtype) + group_sizes = mode.bincount(flat_experts, length=config.num_experts) + + def gmm(lhs, rhs): + return _grouped_matmul( + lhs, rhs, group_sizes, config.gmm_fp32_accum, config.gmm_exact_drhs, layers.precision_or_none(config) + ) + + hidden = (jax.nn.silu(gmm(sorted_inputs, w0)) * gmm(sorted_inputs, w1)).astype(config.dtype) + expert_out = gmm(hidden, wo) + + unsorted = _sort_activations(expert_out, jnp.argsort(sort_indices)) + reshaped_intermediate = unsorted.reshape(tokens, k, -1) + reshaped_weights = weights.reshape(tokens, k) + if config.float32_weight_sum: + reshaped_intermediate = reshaped_intermediate.astype(jnp.float32) + reshaped_weights = reshaped_weights.astype(jnp.float32) + out = jnp.einsum("BKE,BK->BE", reshaped_intermediate, reshaped_weights, precision=layers.precision_of(config)) + return mode.retype(out.reshape(b, s, -1).astype(config.dtype), out_spec) + + +def routed_experts(params, inputs, weights, indices, config: DeepSeekConfig): + """The routed experts of one MoE layer (see the module docstring). + + `params` is `MoeBlock_0`; `inputs` is `[b, s, emb]`, `weights` and + `indices` the router's `[b, s, k]`. `config.moe_impl` picks the kernel: + `_experts_ragged` (sort + grouped matmuls) or `_experts_dense`. + """ + experts = _experts_dense if config.moe_impl == "dense" else _experts_ragged + return experts(params, inputs, weights, indices, config) + + +def routed_and_shared_moe(params, inputs, config: DeepSeekConfig): + """`moe.RoutedAndSharedMoE.__call__`. + + Returns `(output, lb_loss, bias_updates)`; the latter two are `None` when the + corresponding weights are zero, matching MaxText. + """ + inputs = inputs.astype(config.dtype) + routed = params["MoeBlock_0"] + weights, indices = route(routed["gate"], inputs, config) + + lb_loss = None + if config.load_balance_loss_weight > 0.0: + gate_dtype = jnp.float32 if config.float32_gate_logits else config.dtype + kernel = jnp.asarray(routed["gate"]["kernel"], gate_dtype) + logits = _gate_logits(jnp.asarray(inputs, gate_dtype), kernel, config) + pre_bias_logits = layers.activation_fn(config.routed_score_func)(logits) + probs = jax.nn.softmax(pre_bias_logits.astype(jnp.float32), axis=-1).astype(config.dtype) + lb_loss = load_balance_loss(indices, probs, config) + + updates = None + if config.routed_bias and config.routed_bias_update_rate > 0.0: + updates = bias_update(indices, config) + + routed_out = routed_experts(routed, inputs, weights, indices, config) + + shared_out = layers.mlp_block(params["shared_experts"], inputs, config) + return routed_out + shared_out, lb_loss, updates diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/rope.py b/src/maxtext/experimental/mpmd/jax/deepseek/rope.py new file mode 100644 index 0000000000..f62fb6f339 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/rope.py @@ -0,0 +1,143 @@ +# 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. + +"""YaRN rotary embeddings, bit-matching MaxText's `YarnRotaryEmbedding`. + +Reference: MaxText's `embeddings.YarnRotaryEmbedding`. +The table is a complex64 `exp(i*theta)` array, and the output layout is always +`[real..., imag...]` even though the input layout is interleaved. +""" + +import functools +import math + +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.deepseek import layers +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig +from maxtext.experimental.mpmd.jax import sharding_mode as mode + + +def _find_correction_dim(num_rotations, dim, base, max_position_embeddings): + """`YarnRotaryEmbedding._find_correction_dim` -- pure python float64.""" + return dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi)) / (2 * math.log(base)) + + +def _find_correction_range(beta_fast, beta_slow, dim, base, max_position_embeddings, truncate): + """`YarnRotaryEmbedding._find_correction_range`.""" + low = _find_correction_dim(beta_fast, dim, base, max_position_embeddings) + high = _find_correction_dim(beta_slow, dim, base, max_position_embeddings) + if truncate: + low = math.floor(low) + high = math.ceil(high) + low = max(low, 0) + high = min(high, dim - 1) # dim - 1, not half_dim - 1 + return low, high + + +def _linear_ramp_factor(min_val, max_val, dim): + """`YarnRotaryEmbedding._linear_ramp_factor`.""" + if min_val == max_val: + max_val += 0.001 + linear_func = (jnp.arange(dim, dtype=jnp.float32) - min_val) / (max_val - min_val) + return jnp.clip(linear_func, 0, 1) + + +@functools.partial(jax.jit, static_argnums=(0, 1, 2, 3, 4, 5, 6, 7)) +def yarn_freqs_cis( + embedding_dims, + rope_theta, + rope_factor, + beta_fast, + beta_slow, + original_max_position_embeddings, + max_position_embeddings, + truncate, +): + """Complex64 `[max_position_embeddings, embedding_dims // 2]` rotation table.""" + half_dim = embedding_dims // 2 + freqs = 1.0 / (rope_theta ** (2.0 * jnp.arange(0, half_dim, dtype=jnp.float32) / embedding_dims)) + low, high = _find_correction_range( + beta_fast, beta_slow, embedding_dims, rope_theta, original_max_position_embeddings, truncate + ) + smooth = 1 - _linear_ramp_factor(low, high, half_dim) + freqs = freqs / rope_factor * (1 - smooth) + freqs * smooth + t = jnp.arange(max_position_embeddings, dtype=jnp.float32) + freqs = jnp.outer(t, freqs) + return jnp.exp(1j * freqs) + + +def freqs_cis_for(config: DeepSeekConfig, max_len: int | None = None): + """Builds the table. `max_len` trims the (huge) 163840-row default.""" + return yarn_freqs_cis( + config.qk_rope_head_dim, + float(config.rope_max_timescale), + float(config.rope_factor), + float(config.beta_fast), + float(config.beta_slow), + int(config.original_max_position_embeddings), + int(max_len or config.max_position_embeddings), + bool(config.rope_truncate), + ) + + +def apply_yarn(inputs, positions, freqs_cis, config: DeepSeekConfig): + """`YarnRotaryEmbedding.__call__`. + + Args: + inputs: `[b, s, n, qk_rope_head_dim]`, bf16. + positions: `[b, s]` integer positions. + freqs_cis: complex64 table from `freqs_cis_for`. + config: model config. + + Returns: + `[b, s, n, qk_rope_head_dim]` in `config.dtype`. + + The table is replicated but the positions are batch-sharded, and a gather + with sharded indices has no inferable result type under explicit, so the + rows are typed like the activation (`mode.take`). Unlike the embedding + lookup this needs no remat: the table is not differentiated, so nothing + inside the gather is needed by the backward -- at most its typed output is. + + The rotation is linear in `inputs`: its VJP keeps the rows it multiplies + by. Under lean residuals (`layers.lean_residuals`) they enter the product + as `[b, s, 1, half]`, which the multiply broadcasts over the heads itself, + so the VJP keeps them so -- not the `[b, s, n, half]` complex64 broadcast + (128 MiB a layer at DeepSeek-V3's 128 heads and 4096 tokens a sequence). + The products are the same either way. + """ + b, s, n, h = inputs.shape + half = h // 2 + ids = positions.astype(jnp.int32) + freqs = mode.take(freqs_cis, ids, out_spec=mode.act_spec(ids.ndim + 1)) # [b, s, half] complex64 + freqs = freqs[:, :, jnp.newaxis, :] + + if config.rope_interleave: + reshaped = inputs.reshape(b, s, n, half, 2) + first_half, second_half = reshaped[..., 0], reshaped[..., 1] + else: + first_half, second_half = jnp.split(inputs, 2, axis=-1) + + # bf16 against a weak-typed python 1j promotes to complex64. + inputs_complex = first_half + 1j * second_half + if not layers.lean(): + freqs = jnp.broadcast_to(freqs, inputs_complex.shape) + rotated = inputs_complex * freqs + output = jnp.concatenate([jnp.real(rotated), jnp.imag(rotated)], axis=-1) + + if config.rope_attention_scaling: + scaling = 1.0 if config.rope_factor <= 1.0 else (0.1 * math.log(config.rope_factor) + 1.0) + output = output * scaling + return output.astype(config.dtype) diff --git a/src/maxtext/experimental/mpmd/jax/deepseek/train.py b/src/maxtext/experimental/mpmd/jax/deepseek/train.py new file mode 100644 index 0000000000..da4ac4ee20 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/deepseek/train.py @@ -0,0 +1,350 @@ +# 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. + +"""Loss, learning-rate schedule, AdamW and the train step -- all in raw JAX. + +Everything here reproduces MaxText's `trainers/pre_train/train.py` + +`optimizers/optimizers.py` + `maxtext_utils.create_learning_rate_schedule` +for the DeepSeek-V3 target config, without optax or Flax: + + * the loss is the T5X custom-VJP cross entropy (`max_utils.cross_entropy_with_logits`), + * the optimizer is `optax.adamw`'s exact update rule, hand-written, + * gradients are clipped by `optax.clip_by_global_norm(1.0)`'s exact rule. +""" + +import dataclasses + +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.deepseek import model as ds_model +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig +from maxtext.experimental.mpmd.jax import sharding_mode as mode + +EPS = 1e-8 # MaxText's globals.EPS + + +# --------------------------------------------------------------------------- # +# Loss +# --------------------------------------------------------------------------- # + + +@jax.custom_vjp +def cross_entropy_with_logits(logits, targets, z_loss=0.0): + """`max_utils.cross_entropy_with_logits`, the T5X kernel. + + This un-differentiated primal is mathematically the same as `_fwd` below but + can round differently in the last ulp; under `value_and_grad` -- which is how + the train step always calls it -- only `_fwd` runs. + """ + logits_sum = jax.scipy.special.logsumexp(logits, axis=-1, keepdims=True) + log_softmax = logits - logits_sum + loss = -jnp.sum(targets * log_softmax, axis=-1) + log_z = jnp.squeeze(logits_sum, axis=-1) + total_z_loss = z_loss * jax.lax.square(log_z) + loss += total_z_loss + return loss, total_z_loss + + +def _cross_entropy_fwd(logits, targets, z_loss=0.0): + """`max_utils._cross_entropy_with_logits_fwd` -- max-subtracted, and `loss` includes the z-loss.""" + max_logit = logits.max(axis=-1, keepdims=True) + shifted = logits - max_logit + exp_shifted = jnp.exp(shifted) + sum_exp = jnp.sum(exp_shifted, axis=-1, keepdims=True) + log_softmax = shifted - jnp.log(sum_exp) + loss = -jnp.sum(targets * log_softmax, axis=-1) + log_z = jnp.squeeze(jnp.log(sum_exp) + max_logit, axis=-1) + total_z_loss = z_loss * jax.lax.square(log_z) + loss += total_z_loss + return (loss, total_z_loss), (logits, targets, z_loss, exp_shifted, sum_exp, log_z) + + +def _cross_entropy_bwd(res, g): + """`max_utils._cross_entropy_with_logits_bwd` -- the z-loss cotangent is discarded. + + Under explicit sharding the cotangent must be typed exactly like `logits`. + Everything here is elementwise, so it comes out typed by its operands, and + those can disagree with `logits`: replicated logits against batch-sharded + targets give a batch-sharded `deriv`, and jax refuses the rule. So it is + retyped from `logits`' own aval (`mode.retype_like`), which costs nothing + when the types already agree and emits nothing under auto. + """ + g = g[0] + logits, targets, z_loss, exp_shifted, sum_exp, log_z = res + deriv = jnp.expand_dims(1 + 2 * z_loss * log_z, -1) * exp_shifted / sum_exp - targets + g_logits = jnp.expand_dims(g, axis=-1) * deriv + return mode.retype_like(jnp.asarray(g_logits, logits.dtype), logits), None, None + + +cross_entropy_with_logits.defvjp(_cross_entropy_fwd, _cross_entropy_bwd) + + +def loss_from_logits(logits, targets, targets_segmentation, vocab_size, z_loss_multiplier=0.0): + """The loss of MaxText's `train.loss_fn` (trainers/pre_train/train.py). Returns `(loss, metrics)`.""" + one_hot_targets = jax.nn.one_hot(targets, vocab_size) # float32 + xent, z_loss = cross_entropy_with_logits(logits, one_hot_targets, z_loss_multiplier) + + weights = targets_segmentation != 0 + xent = xent * weights + z_loss = z_loss * weights + + xent_sum = jnp.sum(xent) + total_weights = jnp.sum(weights) + loss = xent_sum / (total_weights + EPS) + metrics = { + "lm_loss": loss, + "z_loss": jnp.sum(z_loss) / (total_weights + EPS), + "total_weights": total_weights, + } + return loss, metrics + + +# --------------------------------------------------------------------------- # +# Learning-rate schedule +# --------------------------------------------------------------------------- # + + +@dataclasses.dataclass(frozen=True) +class TrainConfig: + """MaxText's optimizer/schedule knobs (base.yml defaults for deepseek3).""" + + steps: int = 1 + learning_rate: float = 3.0e-5 + learning_rate_final_fraction: float = 0.1 + learning_rate_schedule_steps: int = -1 # -1 -> steps + warmup_steps_fraction: float = 0.1 + lr_schedule_type: str = "cosine" + adam_b1: float = 0.9 + adam_b2: float = 0.95 + adam_eps: float = 1.0e-8 + adam_eps_root: float = 0.0 + adam_weight_decay: float = 0.1 + mu_dtype: jnp.dtype = jnp.float32 + gradient_clipping_threshold: float = 1.0 + z_loss_multiplier: float = 0.0 + + @property + def schedule_steps(self) -> int: + return self.steps if self.learning_rate_schedule_steps < 0 else self.learning_rate_schedule_steps + + +def _linear_schedule(init_value, end_value, transition_steps): + """`optax.linear_schedule` == `polynomial_schedule(..., power=1)`.""" + + def schedule(step): + count = jnp.clip(step, 0, transition_steps) + frac = 1 - count / transition_steps + return (init_value - end_value) * frac + end_value + + return schedule + + +def _cosine_schedule(init_lr, final_lr, len_steps): + """`maxtext_utils.create_learning_rate_schedule`'s `make_cos_schedule` -- note the `len_steps - 1` denominator.""" + + def schedule(step): + pct = step / (len_steps - 1) if len_steps > 1 else 1.0 + a = 0.5 * (jnp.cos(jnp.pi * pct) + 1) + return init_lr * a + final_lr * (1 - a) + + return schedule + + +def learning_rate_schedule(cfg: TrainConfig): + """`maxtext_utils.create_learning_rate_schedule` + `optax.join_schedules`.""" + lr = cfg.learning_rate + final_lr = lr * cfg.learning_rate_final_fraction + sched_steps = cfg.schedule_steps + warmup_steps = int(sched_steps * cfg.warmup_steps_fraction) + constant_zero_steps = cfg.steps - sched_steps + + pieces, boundaries = [], [] + if warmup_steps > 0: + pieces.append(_linear_schedule(0.0, lr, warmup_steps)) + boundaries.append(warmup_steps) + + if cfg.lr_schedule_type == "cosine": + cos_steps = sched_steps - warmup_steps + if cos_steps > 0: + pieces.append(_cosine_schedule(lr, final_lr, cos_steps)) + boundaries.append(warmup_steps + cos_steps) + else: + raise ValueError(f"unsupported lr_schedule_type: {cfg.lr_schedule_type}") + + if constant_zero_steps > 0: + pieces.append(lambda _: jnp.asarray(0.0, jnp.float32)) + boundaries.append(sched_steps) + + def schedule(step): + out = pieces[0](step) + for boundary, piece in zip(boundaries, pieces[1:]): + out = jnp.where(step < boundary, out, piece(step - boundary)) + return out + + return schedule + + +# --------------------------------------------------------------------------- # +# AdamW (optax.adamw's update rule, written out) +# --------------------------------------------------------------------------- # + + +def adamw_init(params, cfg: TrainConfig): + return { + "count": jnp.zeros([], jnp.int32), # scale_by_adam + "sched_count": jnp.zeros([], jnp.int32), # scale_by_schedule + "mu": jax.tree.map(lambda p: jnp.zeros_like(p, cfg.mu_dtype), params), + "nu": jax.tree.map(jnp.zeros_like, params), + } + + +def adamw_update(grads, state, params, cfg: TrainConfig, schedule): + """`chain(scale_by_adam, add_decayed_weights, scale_by_learning_rate)`.""" + b1, b2 = cfg.adam_b1, cfg.adam_b2 + count = state["count"] + 1 + + mu = jax.tree.map(lambda g, m: (1 - b1) * g + b1 * m, grads, state["mu"]) + nu = jax.tree.map(lambda g, n: (1 - b2) * (g**2) + b2 * n, grads, state["nu"]) + + mu_correction = 1 - b1**count + nu_correction = 1 - b2**count + mu_hat = jax.tree.map(lambda t: t / mu_correction.astype(t.dtype), mu) + nu_hat = jax.tree.map(lambda t: t / nu_correction.astype(t.dtype), nu) + + updates = jax.tree.map(lambda m, v: m / (jnp.sqrt(v + cfg.adam_eps_root) + cfg.adam_eps), mu_hat, nu_hat) + mu = jax.tree.map(lambda t: t.astype(cfg.mu_dtype), mu) + + # add_decayed_weights (decoupled weight decay, applied before the LR scale). + updates = jax.tree.map(lambda u, p: u + cfg.adam_weight_decay * p, updates, params) + + # scale_by_learning_rate(schedule, flip_sign=True) -- its own count, from 0. + step_size = -1 * schedule(state["sched_count"]) + updates = jax.tree.map(lambda u: jnp.array(step_size, dtype=u.dtype) * u, updates) + + new_state = { + "count": count, + "sched_count": state["sched_count"] + 1, + "mu": mu, + "nu": nu, + } + return updates, new_state + + +def global_norm(tree): + """`optax.tree.norm` / `max_utils.l2norm_pytree`.""" + return jnp.sqrt(sum(jnp.sum(jnp.square(leaf)) for leaf in jax.tree.leaves(tree))) + + +def clip_by_global_norm(grads, max_norm): + """`optax.clip_by_global_norm` -- a `lax.select` identity below the threshold.""" + g_norm = global_norm(grads) + trigger = jnp.squeeze(g_norm < max_norm) + + def clip(t): + return jax.lax.select(trigger, t, (t / g_norm.astype(t.dtype)) * max_norm) + + return jax.tree.map(clip, grads) + + +def apply_updates(params, updates): + return jax.tree.map(lambda p, u: (p + u).astype(p.dtype), params, updates) + + +# --------------------------------------------------------------------------- # +# Train step +# --------------------------------------------------------------------------- # + + +def compute_loss(params, aux, batch, config: DeepSeekConfig, train_cfg: TrainConfig, freqs_cis=None): + # MaxText's loss adds the MTP layers' (multi_token_prediction.py), which this port does not build (ds_ep_pipeline + # --mtp does): refused, as model.decoder_layer refuses the aux loss and the bias update, not trained without. + if config.mtp_num_layers > 0: + raise NotImplementedError( + f"mtp_num_layers={config.mtp_num_layers} is not supported: MaxText's loss adds the MTP " + "layers' cross entropy, which this port does not compute" + ) + logits = ds_model.forward( + params, + aux, + batch["inputs"], + batch["inputs_position"], + batch["inputs_segmentation"], + config, + freqs_cis=freqs_cis, + ) + loss, metrics = loss_from_logits( + logits, + batch["targets"], + batch["targets_segmentation"], + config.vocab_size, + train_cfg.z_loss_multiplier, + ) + return loss, metrics + + +def train_step(params, aux, opt_state, batch, config, train_cfg, schedule, freqs_cis=None): + """One MaxText training step: loss -> grads -> clip -> AdamW -> apply.""" + grad_fn = jax.value_and_grad(compute_loss, has_aux=True) + (loss, metrics), raw_grads = grad_fn(params, aux, batch, config, train_cfg, freqs_cis) + + grads = clip_by_global_norm(raw_grads, train_cfg.gradient_clipping_threshold) + updates, opt_state = adamw_update(grads, opt_state, params, train_cfg, schedule) + params = apply_updates(params, updates) + + metrics = dict(metrics) + metrics["loss"] = loss + metrics["raw_grad_norm"] = global_norm(raw_grads) + metrics["grad_norm"] = global_norm(grads) + metrics["param_norm"] = global_norm(params) + return params, opt_state, metrics + + +def packed_segment_ids(batch_size, seq_len, max_segments_per_seq): + """`synthetic_data_processing._make_packed_segment_ids`.""" + if max_segments_per_seq < 2 or seq_len < 2: + return jnp.ones((batch_size, seq_len), jnp.int32) + + max_segs = min(max_segments_per_seq, seq_len) + k1, k2 = jax.random.split(jax.random.PRNGKey(42), 2) + n_segs = jax.random.randint(k1, (batch_size, 1), minval=2, maxval=max_segs + 1) + num_splits = n_segs - 1 + scores = jax.random.uniform(k2, (batch_size, seq_len - 1)) + ranks = jnp.argsort(jnp.argsort(scores, axis=-1), axis=-1) + split_mask = ranks < num_splits + first_pos = jnp.ones((batch_size, 1), jnp.bool_) + is_boundary = jnp.concatenate([first_pos, split_mask], axis=-1) + return jnp.cumsum(is_boundary, axis=-1, dtype=jnp.int32) + + +def synthetic_batch(vocab_size, batch_size, seq_len, seed=0, packing=True, max_segments_per_seq=-1): + """`synthetic_data_processing.SyntheticDataIterator.raw_generate_synthetic_data`. + + Note the hardcoded `PRNGKey(0)` and that targets are already next-token + shifted -- neither the model nor the loss shifts anything. + """ + tokens = jax.random.randint(jax.random.PRNGKey(seed), (batch_size, seq_len + 1), 0, vocab_size, dtype=jnp.int32) + positions = jnp.broadcast_to(jnp.arange(0, seq_len + 1, dtype=jnp.int32), (batch_size, seq_len + 1)) + if packing: + segmentation = packed_segment_ids(batch_size, seq_len, max_segments_per_seq) + else: + segmentation = jnp.ones((batch_size, seq_len), jnp.int32) + return { + "inputs": tokens[:, :-1], + "inputs_position": positions[:, :-1], + "inputs_segmentation": segmentation, + "targets": tokens[:, 1:], + "targets_position": positions[:, 1:], + "targets_segmentation": segmentation, + } diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep.py b/src/maxtext/experimental/mpmd/jax/ds_ep.py new file mode 100644 index 0000000000..b677af31c9 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep.py @@ -0,0 +1,6524 @@ +# 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. + +"""DeepSeek-V3 sparse layers on one MPMD stage: FSDP x EP on a 2-D sub-mesh. + +A pipeline stage owns a sub-mesh with axes `('fsdp', 'expert')`. Weights live +in two layouts: + + storage fp32 master weights, sharded like MaxText's `pipeline-large-moe` + rules: non-routed weights shard their embed axis over + ('fsdp', 'expert') (the LoRA ranks over 'fsdp'); routed experts + shard the expert axis over 'expert' and the embed axis over 'fsdp'. + compute bf16, all-gathered once per step ahead of every microbatch: + non-routed weights are replicated on the stage, routed experts keep + [E / EP] experts per device. This is MaxText's layout after its + pipeline's per-repeat FSDP all-gather (`pipeline_fsdp_ag_per_repeat`), + cast to bf16 *before* the gather instead of after it. + +Every per-microbatch program is one `shard_map` over the stage mesh, so the +only collectives in the hot loop are ring-of-experts' token all-gather and +output reduce-scatter over 'expert' (MaxText `use_ring_of_experts=true` +`use_ragged_sort=true`, `RoutedMoE.sparse_matmul`). Weight gradients are +accumulated per device, unreduced, in a layout with a leading "partial" axis, +and reduce-scattered back to the storage layout once per step. Under +`shard_mode='explicit'` the stage meshes' axes are Explicit and the types say +so instead: the gathered weights are `reduced` over the axes their gradients +are partial over, the accumulators `unreduced` over them (StageConfig). + +The expert and attention kernels are MaxText's own -- `ring_ragged_sort` / +`ring_ragged_unsort` (SparseCore ragged gather / gather-reduce), the megablox +`gmm`, and tokamax splash with the fused backward -- called with the argument +values MaxText derives from the reference flags, so both sides of the +comparison execute the same kernels. MaxText is imported only where one of +its kernels runs: unsplit or under batch_split_impl 'native', with +`gmm_impl='ragged_dot'` and `use_ragged_sort=False` the stage programs are +pure JAX (plus tokamax for the tokamax_splash attention kernel); a batch +split on Lineage's layers (DeepSeek-V3's default, below) imports MaxText's +Lineage whatever those knobs are. + +A second layer family runs on the same machinery: the Qwen3.5 family +(Qwen3.5-397B-A17B, Qwen3.8-2.4T-A95B; MaxText `decoder_block: qwen3_5`), when +`StageConfig.model` is a `maxtext.experimental.mpmd.jax.qwen35.config.Qwen35Config`. Its layers +are MoE layers too, with one of two mixers in front of the experts: Gated +DeltaNet linear attention, or gated full attention on every +`inhomogeneous_layer_cycle_interval`-th layer. The mixers and norms are the +`maxtext.experimental.mpmd.jax.qwen35` port's (as DeepSeek's are `maxtext.experimental.mpmd.jax.deepseek`'s), the routed +experts are this module's ring of experts with Qwen's router (top-k of the raw +logits, softmax over the k, renormalised), and the shared expert has its +sigmoid gate. A chunk records each layer's kind (`ChunkSpec.kinds`), and its +weights are one subtree a layer, each leaf with a leading layer axis of one +(`chunk_shapes`): DeepSeek's [n, ...] stacks cost a Qwen3.8 chunk's backward +a copy of every layer's weight slice and every layer's weight gradient live at +once (a 2-layer chunk: 33.2 GiB of temporaries against 24.5). Every leaf keeps +one leading layer axis, so the gathers, reduce-scatters, accumulators and plans +are the same code for both families. + +Batch split (StageConfig.batch_split) runs a DeepSeek-V3 chunk's decoder +layers on MaxText's Lineage layers by default (ds_ep_lineage; the chunk's +programs are then global-view jits, ChunkPrograms), or on this module's +`split_layers` over the kernels above (batch_split_impl 'native'), where +Lineage's TPU kernels do not run (GPU, CPU: ds_ep_pipeline refuses 'native' +for DeepSeek-V3 on TPU). Lineage builds DeepSeek-V3's layers only, so a +Qwen3.5-family chunk always batch-splits on `split_layers`, its mixer in +attention's place: 'native' is that family's default and only impl. +""" + +from __future__ import annotations + +import contextlib +import contextvars +import dataclasses +import functools +import inspect +import math +import numbers +import threading +import warnings + +import jax +import jax.numpy as jnp +from jax import lax +from jax.ad_checkpoint import checkpoint_name +from jax.sharding import NamedSharding, PartitionSpec as P + +from maxtext.experimental.mpmd.jax.deepseek import attention +from maxtext.experimental.mpmd.jax.deepseek import layers +from maxtext.experimental.mpmd.jax.deepseek import rope +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig +from maxtext.experimental.mpmd.jax import stage_ad +from maxtext.experimental.mpmd.jax.qwen35 import attention as q_attention +from maxtext.experimental.mpmd.jax.qwen35 import gdn as q_gdn +from maxtext.experimental.mpmd.jax.qwen35 import layers as q_layers +from maxtext.experimental.mpmd.jax.qwen35.config import Qwen35Config + +FE = ("fsdp", "expert") +EP_AXIS = "expert" +GMM_IMPLS = ("megablox", "ragged_dot", "tokamax") +# The grouped-matmul backends gmm_impl 'tokamax' runs (StageConfig.tokamax_gmm): +# 'mosaic' -- Mosaic GPU for the forward and dlhs products, which skips the rows past the groups: on sm100 +# gpu_kernels.grouped_matmul (tokamax's Blackwell kernel reading the weight as it lies, tuned tiles), elsewhere +# (and for dtypes it does not take) tokamax's own; tokamax has no Mosaic dW kernel on sm80 / sm100, so dW runs on +# Triton -- but a dW with a starting value (in-place accumulation, an fp32 accumulator's too, or mb0's under +# split_dw 'acc': _ragged_dw) on sm100 on gpu_kernels.ragged_dw's tcgen05 kernel where it takes the shapes. +# 'tokamax_mosaic' -- tokamax's Mosaic kernels everywhere (its heuristic tiles; its forward transposes the weight), +# dW on Triton: none of gpu_kernels' Mosaic kernels (a dW with a starting value on ragged_dw's Triton one). +# 'triton' -- every product on Triton (sm80 and later; a dW with a starting value on ragged_dw's). +# 'xla' -- lax throughout: tokamax's own lax.ragged_dot, and ragged_dw's lax form for a dW with a starting value +# (CPU tests). +# On a GB200 at DeepSeek-V3's EP 4 shapes (64 local experts, 32768 rows routed to them in a buffer of 65536) the +# forward products run 0.82 ms (1150 TFLOP/s) on 'mosaic', 1.59 ms on tokamax's Mosaic (0.66 of it the weight's +# transposed copy), 1.8 / 3.9 ms on Triton (k=7168 / n=2048, k=2048 / n=7168); dlhs 0.85 / 1.0 ms; Triton's dW 1.2 ms +# (785 TFLOP/s). Qwen3.8's (128 experts, 40960 rows): forward 1.25-1.32 ms against tokamax's 2.7-3.0. +TOKAMAX_GMM = ("mosaic", "tokamax_mosaic", "triton", "xla") +# Stage programs take 'ppermute' / 'xla'; 'auto' (EP) is a pipeline-level +# choice that ds_ep_pipeline.Pipeline resolves per stage. +FSDP_COLLECTIVES = ("ppermute", "xla") +EP_COLLECTIVES = ("xla", "ppermute", "auto") +SHARD_MODES = ("auto", "explicit") +RS_AXES = ("joint", "each") +GATHER_AXES = ("joint", "each") +SPLIT_DW = ("acc", "sum") +EXPERT_WEIGHTS = ("stacked", "sliced") +# Whose code a batch-split chunk's decoder layers run (StageConfig.batch_split_impl): 'lineage', MaxText's Lineage +# layers (ds_ep_lineage), DeepSeek-V3's only; 'native', this module's own split_layers over its layer ports and +# MaxText's ring-of-experts / megablox kernels -- DeepSeek-V3's off TPU (ds_ep_pipeline.native_split_refusal), or +# the Qwen3.5 family's, its only batch split. +BATCH_SPLIT_IMPLS = ("lineage", "native") +# Where the routing weights multiply the routed experts' output (StageConfig.route_weights). +ROUTE_WEIGHTS = ("combine", "experts") +# A layer's routed-expert weight leaves (moe_experts' stacked). +EXPERT_LEAVES = ("wi_0", "wi_1", "wo") + + +def _is_spec(x): + return isinstance(x, P) + + +# --------------------------------------------------------- megablox tilings +# A tiling is a megablox 9-tuple (fwd tm,tk,tn, dlhs tm,tk,tn, drhs tm,tk,tn), +# as MaxText builds it from the wi_tile_* / wo_tile_* flags (`RoutedMoE.sparse_matmul`'s +# get_wi_gmm_params / get_wo_gmm_params). +# The three kernels of one weight tile different k dims (D = emb_dim, +# F = moe_mlp_dim; the gmm tk is a contraction tile, the tgmm tk tiles dW's k): +# +# fwd gmm dlhs gmm (_dx) drhs tgmm (_dw) +# wi k = D k = F k = D +# wo k = F k = D k = F +# +# megablox does not clamp a tk larger than its k: it rounds the tile count up +# (`_calculate_irregular_num_tiles`) and masks the tail, but the MXU still runs +# the dot on the whole [tm, tk] block -- tk=7168 on k=2048 is 3.5x the work, +# for bit-identical outputs. Padded tiles, one (512, D, 512) x3 for both +# weights, do that in four of the nine kernels (gmm_wo, gmm_wi_{0,1}_dx, +# gmm_wo_dw). In a TPU7x-8 capture (TPU:0 of the 2026-09-25 runs of +# DeepSeek-V3 layers against MaxText's SPMD pipeline), where all nine kernels +# do the same FLOPs: gmm_wo 6.42 ms vs gmm_wi_0 1.90 ms, gmm_wi_*_dx 6.50 vs +# gmm_wo_dx 1.88, gmm_wo_dw 7.86 vs gmm_wi_*_dw 2.60 -- ~376 ms/step of +# padding; the MaxText baseline, run with the same 7168 tiles, pads ~377 +# ms/step. On v6e the wo forward takes 8.42 ms at tk=7168 and 5.85 ms at +# tk=2048. +# +# clamped tk = the k it tiles, tm = tn = 512. The default. +# v6e swept on TPU v6e-4 at D=7168, F=2048. At PP2 x FSDP1 x EP2, 4 +# layers, 16 experts, gbs 16, M 8: 1607 ms/step with the padded +# tiles -> 1328 ms/step (clamped: 1447; MaxText on the same kernels +# and tiles: 1.91 -> 1.64 s/step, clamped 1.75). Fixed numbers: +# other shapes may pad. +TILES = { + "clamped": lambda cfg: ( + (512, cfg.emb_dim, 512, 512, cfg.moe_mlp_dim, 512, 512, cfg.emb_dim, 512), + (512, cfg.moe_mlp_dim, 512, 512, cfg.emb_dim, 512, 512, cfg.moe_mlp_dim, 512), + ), + "v6e": lambda cfg: ( + (1024, 3584, 2048, 1024, 2048, 2048, 256, 3584, 2048), + (1024, 2048, 2048, 1024, 3584, 2048, 1024, 2048, 2048), + ), +} + + +def split_acc_wi_tiling(wi): + """The wi tiling a batch-split chunk (impl 'native') runs under split_dw + 'acc' where none is given: the drhs (dW) tm capped at 256. Its dW kernel + then also holds existing_out, a second [tk, tn] window double-buffered like + the output: at the clamped (512, D, 512) and DeepSeek-V3's D that is 69.1 of + TPU7x's 63.9 MiB of VMEM, at tm 256 it fits (megablox tgmm compiled for one + TPU7x device, libtpu 0.0.46; tk D/2 or tn 256 fit too). wo's dW kernel (tk + F) fits either way.""" + wi = tuple(wi) + return wi[:6] + (min(wi[6], 256),) + wi[7:] + + +# How StageConfig's warning about such a tiling starts (to filter it by). +TILING_WARNING = "megablox tile larger than the k it tiles" + + +def tiling_problems(cfg: DeepSeekConfig, wi_tiling, wo_tiling): + """Every tk larger than the k it tiles (see TILES), as readable strings.""" + D, F = cfg.emb_dim, cfg.moe_mlp_dim + out = [] + for w, tiling, ks in (("wi_{0,1}", wi_tiling, (D, F, D)), ("wo", wo_tiling, (F, D, F))): + for kernel, i, k in zip(("", "_dx", "_dw"), (1, 4, 7), ks): + if tiling[i] > k: + out.append(f"gmm_{w}{kernel}: tk={tiling[i]} > k={k} ({tiling[i] / k:.2g}x the MXU work)") + return out + + +def _tiling9(name, t): + t = tuple(t) + if len(t) != 9 or not all(isinstance(x, numbers.Integral) and x > 0 for x in t): + raise ValueError(f"{name} must be 9 positive ints (fwd tm,tk,tn, dlhs tm,tk,tn, drhs tm,tk,tn), " f"got {t!r}") + return tuple(int(x) for x in t) + + +# ---------------------------------------------------------------- the config +@dataclasses.dataclass(frozen=True) +class StageConfig: + """Model + the knobs that belong to the stage programs, not the model. + + `model` is a DeepSeek-V3 config or a Qwen3.5-family one (`is_qwen`).""" + + model: DeepSeekConfig | Qwen35Config + fsdp: int = 2 + ep: int = 2 + # megablox 9-tuples (see TILES). None: TILES['clamped'] for `model` + # (wi's under batch_split_impl 'native' with split_dw 'acc': + # split_acc_wi_tiling; Lineage's layers run no megablox kernel), resolved + # in __post_init__ (so dataclasses.replace(..., model=...) keeps the + # tiling of the old model). + wi_tiling: tuple | None = None + wo_tiling: tuple | None = None + # A tk larger than the k it tiles pads the MXU work (see TILES): warn, or + # raise ValueError when True. + strict_tiling: bool = False + # The routed experts' grouped matmuls: 'megablox' (MaxText's kernels, with + # the tilings above) or 'ragged_dot' (pure JAX, jax.lax.ragged_dot; the + # tilings are unused). Same math, same group_offset semantics. + gmm_impl: str = "megablox" + # gmm_impl 'tokamax': the backend of the forward and dlhs products (TOKAMAX_GMM); the dW product runs on + # Triton unless this is 'xla' -- but under 'mosaic' on sm100 one with a starting value (inplace_dw and + # inplace_dw_any_dtype, or mb0's under split_dw 'acc') on gpu_kernels.ragged_dw's tcgen05 kernel (_ragged_dw). + # tokamax has no group_offset, so gmm_impl 'tokamax' runs the ring's experts on a compact buffer of this device's + # rows only (`_local_plan`): no ragged sort, and a row of another shard's experts is never in a kernel's input. + tokamax_gmm: str = "mosaic" + # gmm_impl 'tokamax': accumulate the routed experts' weight gradients into the step's accumulator inside the dW + # kernel (gpu_kernels.ragged_dw; ChunkPrograms' inplace_dw says where it applies) rather than writing each dW to + # a buffer of its own and adding it in a pass of its own. + inplace_dw: bool = True + # ... also into an accumulator of a dtype other than the compute dtype (an fp32 one: Megatron's main_grad), on + # every chunk but the last: the accumulated value leaves through the start's cotangent (tokamax_gmm's dw32), the + # starts being primals of the backward's VJP (the saved-residual forward's, or bwd_core_recompute's). Off by + # default. On sm_100 under tokamax_gmm 'mosaic' the kernel is gpu_kernels.ragged_dw's tcgen05 one (DW_MOSAIC_F32: + # 1.77 ms at DeepSeek-V3's EP 8 shapes, a 2-node B200 step 1.6% faster than the dW plus an add); elsewhere, and + # under 'tokamax_mosaic' / 'triton', its Triton one, slower than tokamax's dW plus an add pass (A100, dsv3-mini + # expert shapes: 5.66 ms against 4.21 + ~1.5; a step 1% slower); under 'xla' lax's form (_ragged_dw). + inplace_dw_any_dtype: bool = False + # Zero the compact buffer's rows past its groups (_masked): after the dispatch, every grouped matmul's output and + # each gradient entering one. Every reader of those rows is bounded by the group sizes (the grouped-matmul + # kernels) or indexes valid rows only (the combine's and the dispatch gradient's gathers by `pos`), so the masks + # change no result; False skips their buffer-wide passes (the kernels leave the rows past the groups unwritten, + # and nothing reads them). At EP 1 with a dropless buffer every row is valid and they are skipped regardless. + buffer_masks: bool = True + # The per-token sums over a token's K choices -- the combine's weighted sum of its rows, and the dispatch's + # gradient (the sum of its rows' gradients): 'xla', a fill-gather of T x K rows reduced over K (at EP 8 seven choices + # in eight have no row here, and it still walks them), or 'triton', gpu_kernels.gather_sum, which loads only the + # rows that exist (GPU; elsewhere it is the XLA sum). + combine_impl: str = "xla" + # Where the routing weights multiply the routed experts' output (ROUTE_WEIGHTS). 'combine': the combine's weighted + # sum of a token's rows (MaxText's), whose backward reads the expert output rows for the weights' gradient, so a + # saved-residual forward keeps them: [rows, emb], 896 MiB a DeepSeek-V3 layer at one sequence a device, EP 8 and + # ragged_buffer_factor 2. 'experts': each row of the gated activation, before the wo product (Megatron-LM's, which + # scales the activation by the probs), and the combine an unweighted sum -- a weight's gradient is then its row of + # the activation dotted with that row's gradient, [rows, moe_mlp] arrays the wo product's backward has anyway, and no + # expert output row is kept. The same sums, rounded otherwise: the weighted activation is rounded to the compute + # dtype before wo, as Megatron-LM rounds it. It needs each buffer row's (token, choice) pair: gmm_impl 'tokamax' + # (its compact buffer) or the argsort dispatch (use_ragged_sort False); MaxText's ring_ragged_sort keeps them inside + # its kernels. + route_weights: str = "combine" + # Under lean residuals (saved residuals), whether the routed experts' grouped matmuls keep what their lhs is + # recomputed from instead of the lhs (`Recompute`): the gathered tokens [T, emb] instead of the buffer rows + # [rows, emb], and the gated product's inputs instead of the product. True keeps the fewest bytes (a DeepSeek-V3 + # layer at one sequence a device, EP 8, ragged_buffer_factor 2: 0.7 GiB less) for a row gather and an elementwise + # product more in each backward; False keeps the lhs, where the memory is there. + lean_experts: bool = True + # A DeepSeek chunk's layers' weights, its MoE layers' and its dense layers' alike: 'stacked' ([n, ...] leaves, + # TPU's: megablox reads a layer's experts in place in the stack) or 'per_layer' (one subtree a layer, a layer axis + # of one, as a Qwen chunk's). Per layer, no layer's gradient is stacked into the accumulator in every backward (on + # GB200, three [n, E / EP, D, F] concatenations a MoE chunk's backward, ~9% of a stage's step; chunk 0's three + # DeepSeek-V3 dense layers' [3, D, mlp] ones ~0.6 s of the 64-B200 recipe's stage 0 step), each layer's dW + # accumulating in its own GEMM instead; each accumulator block is a whole buffer, which in-place dW accumulation + # needs; and a layer's weights are whole buffers, not slices of a stack, which the lean residuals' checkpoints + # (layers.rms_norm_read) would copy through their optimization barriers in every backward. Qwen3.5-family chunks + # are per layer either way. + layer_tree: str = "stacked" + use_ragged_sort: bool = True + random_routing: bool = True + iota_embed: bool = True + # dtype of the once-per-step gradient reduce-scatter. (MaxText reduce-scatters + # its compute copies' gradients whatever its grad_dtype: bf16, but for the + # fp32 ones' -- with fp32 weights, an fp32 router's under float32_gate_logits + # and a Qwen3.5-family model's norm scales under norm_numerics 'fp32' + # (leaf_dtypes).) + rs_dtype: jnp.dtype = jnp.bfloat16 + # The dtype the reduced gradient enters AdamW (and the clip) in, cast from + # rs_dtype at the top of StagePrograms' update: MaxText grad_dtype, which its + # trainer applies after the reduction -- rs_dtype bf16 with grad_dtype fp32 + # is MaxText's weight_dtype=float32 grad_dtype=float32, but for the routers' + # kernels and a Qwen model's norm scales: MaxText reduces the gradients of + # their fp32 compute copies in fp32, this pipeline in rs_dtype. None: under + # adam_math 'optax' each weight's dtype (MaxText's gradients take their + # parameter's, so with fp32 weights that is the cast above), under 'fp32' + # rs_dtype, no cast. adam_math 'fp32' computes in fp32 whatever this is + # (float32 changes nothing there; bfloat16 rounds the gradient first). The + # global norm stays the reduce-scatter's output's (its fp32 partial sums) + # and the count leaves (count_leaves) keep their fp32. + # MaxText casts fp32 gradients only: with bf16 weights its gradients stay + # bf16 whatever its grad_dtype (keep None). + grad_dtype: jnp.dtype | None = None + # Accumulate weight gradients across microbatches in this dtype. + acc_dtype: jnp.dtype = jnp.float32 + # Every chunk but the last saves only each layer's INPUT and recomputes the + # layer inside its backward program (MaxText's remat 'full'): its + # activations would otherwise have to outlive the forward program. The + # last chunk runs forward and backward in ONE program, so recomputing there + # buys no memory: False skips it (same gradients, less compute), True keeps + # MaxText's remat-everything FLOP count for a like-for-like comparison. + remat_fused_last: bool = False + # Every chunk but the last keeps its backward's residuals instead (Megatron-LM's default, no recompute): its + # forward program runs the layers under jax.vjp and returns the VJP's residuals -- every array the backward + # reads but the chunk's input and its compute weights, which the backward takes as arguments anyway -- and its + # backward program evaluates that VJP on them. No forward is computed twice (the structural recompute above + # is about a quarter of a step's FLOPs), for the residuals' memory until the backward (ChunkPrograms.res_avals). + save_residuals: bool = False + # How the once-per-step FSDP all-gather / reduce-scatter are expressed. + # 'ppermute': as collective-permutes over each size-2 mesh axis, which TPU + # runs as async DMAs that overlap compute in the same program on EVERY + # sub-mesh. (libtpu only offloads all-gather / reduce-scatter to + # SparseCore -- the other way they become async -- when the program's + # chips are the whole slice or a solid rectangle without chip (0,0,0): it + # compiles any other device set against the whole slice's topology, and + # skips the offload when the program uses fewer devices than that ("does + # not use all devices"), so on a sub-mesh holding chip (0,0) they run + # synchronously and serialize with compute. See sparsecore_offload_available.) + # 'xla': lax.all_gather / psum_scatter. + fsdp_collectives: str = "ppermute" + # Ring-of-experts token all-gather / output reduce-scatter over 'expert': + # 'xla' (lax collectives; SparseCore-offloaded and async where libtpu allows) + # or 'ppermute' (async collective-permutes, for sub-meshes without offload). + ep_collectives: str = "xla" + # When weight gradients are reduced over FSDP: + # 'step' accumulate per-device partials unreduced across microbatches + # and reduce-scatter once per step (folded into later programs); + # 'microbatch' reduce-scatter every microbatch's gradient inside its own + # backward program and accumulate the sharded result -- the + # cadence MaxText's pipeline_fsdp_ag_per_repeat compiles to. + grad_reduce: str = "step" + # The AdamW update's arithmetic. 'fp32': in fp32 whatever the storage + # dtype, stored back in it. 'optax': optax's chain as MaxText runs it -- + # clip_by_global_norm, scale_by_adam, add_decayed_weights, + # scale_by_learning_rate, apply_updates -- every op in its leaf's dtype: with + # bf16 weights the moments' decay, the bias correction and the learning rate + # are bf16 (maxtext.experimental.mpmd.jax.deepseek.train holds that chain bit-exact against + # MaxText). For parity runs against MaxText with bf16 weights and gradients + # (mu is always bf16 here; nu keeps its storage dtype); the global norm + # still comes from this pipeline's fp32 partial sums, where MaxText's optax + # reduces it in bf16 -- so the update is MaxText's bit for bit only while + # the norm stays below the clip (or both norms round to one bf16 value). + adam_math: str = "fp32" + # The global-norm clip's threshold, MaxText's gradient_clipping_threshold; 0 + # does not clip (a parity run with bf16 gradients turns it off on both sides, + # since MaxText rounds its norm to bf16 and this pipeline does not). + grad_clip: float = 1.0 + # The ring of experts' dispatch buffer (MaxText ragged_buffer_factor, + # RoutedMoE.get_ragged_buffer_size): <= 0 the worst case, every token of the + # EP group x top-k rows a device (dropless; [EP x tokens x top-k, emb] bf16 + # is 7.5 GB at EP 16 and one 4k sequence a device); > 0 that many times the + # balanced load, a device's own tokens x top-k. A shard routed more than its + # buffer drops the excess, as MaxText's truncated buffer does + # (`_truncate_matrix` of the shard's group sizes). Any factor: megablox gets + # the buffer padded to its row tile (`gmm_row_tile`). Needs use_ragged_sort + # (the ring's SparseCore sort holds the buffer). + ragged_buffer_factor: float = -1.0 + # Context parallelism: a microbatch's sequences cut into `cp` chunks, one + # row of seq / cp tokens a device. Rows shard fsdp-major over FE, so the cp + # rows of a sequence sit on cp consecutive devices of one 'expert' ring: + # device e holds chunk e % cp (`cp_chunk`). Attention collects the other + # chunks' kv latents from those devices (`cp_kv_context`); everything else + # is per token. 1, 2 or 4, dividing ep. + cp: int = 1 + # How the stage meshes type the step's weight copies and gradient + # accumulators (jax's sharding in types): + # 'auto' Auto mesh axes, nothing typed; an accumulator carries a leading + # axis over the mesh axes its per-device partial sums are still + # to be reduced over (chunk_gacc_specs). + # 'explicit' Explicit mesh axes. The gathered compute weights are typed + # P(*compute spec, reduced=) -- one copy on every + # device of those axes -- and an accumulator P(*compute spec, + # unreduced=): each device's partial sum, no leading + # axis, the gradient their sum over those axes. The types sit on + # the programs' arguments and outputs; their bodies, collectives + # and folding are 'auto''s (check_vma=False). Needs + # grad_reduce='step'. + shard_mode: str = "auto" + # How fsdp_collectives 'xla' reduce-scatters a gradient leaf stored over + # both mesh axes (P(.., ('fsdp', 'expert'), ..): wq_a, wkv_a, out, the + # shared experts, the embedding and the head): 'joint', one psum_scatter + # over both; 'each', one a mesh axis, 'fsdp' first. Compiled for a v5p + # slice as one stage (v5p-128: fsdp 4 x expert 16; v5p-64: 2 x 16; libtpu + # 0.0.46, the v5p recipe's flags) the joint one is a full-size all-reduce + # over the stage and a slice -- twice a reduce-scatter's bytes, through a + # full-size buffer -- where 'each' is two reduce-scatters, both on the + # SparseCore; but for the embedding and the head, whose per-axis pair + # libtpu runs on the TensorCore, synchronously: those keep the joint one + # (_rs_joint_only). Not timed on v5p: the joint all-reduce may use every + # link of the torus, the 'fsdp' step of 'each' runs over a ring of 4 + # chips. On v6e stages (2x2, 4x4) the joint one is one reduce-scatter, and + # 'each' only adds a collective (on the v6e-4 four of the five DS-V3 layer + # leaves took 9-63% longer, wkv_a 2.1 -> 0.9 ms); on a TPU7x-128 stage + # (8 x 16) it is one too, but for wkv_a's. So opt-in (ds_ep_pipeline + # --rs-axes; a 2 x v5p-128 study's runs with --rs-axes each, 2026-10-14). + # 'each' rounds the first axis's sum to rs_dtype before the second's is + # added: within 2 bf16 ulps of 'joint' (measured). Leaves stored over one + # axis, and 'ppermute' (axis by axis anyway), reduce alike either way. + rs_axes: str = "joint" + # The gather side's counterpart: how fsdp_collectives 'xla' all-gathers a + # leaf stored over both mesh axes -- 'joint', one lax.all_gather over both; + # 'each', one a mesh axis, the minor ('expert') first, tiled, so the second + # gathers whole blocks of the first and the result is the joint gather's, + # bit for bit (a gather is a copy). A v5p-128 stage of a 2-slice program + # (2 x v5p-128 PP over DCN, libtpu 0.0.46, the v5p recipe's flags) compiles the + # joint 64-way gather to a zero buffer, a dynamic-update-slice and a + # full-size all-reduce over the stage (libtpu's all-gather decomposer, which + # runs on multi-slice compiles only): about twice the bytes of a gather, + # through a buffer the size of the result (12.6 ms on the SparseCore for the + # [7168, 129280] head, measured). 'each' compiles to two native SparseCore + # all-gathers there, over 16 and 4 devices (AOT of the runs' programs), and + # the 2 x v5p-128 A/B timed them: 5.3 / 5.1 ms off update_s0_ag0 (the R2 / + # R1 runs of PinModel; 2026-10). On one slice the joint gather is native + # already, as in a 2-slice v6e program (NATIVE_JOINT_GATHER_KINDS), where the + # 2 x v6e-128 A/B timed 'each' slower on R2v (update_s0_ag0 18.3 -> 28.8 ms) + # and neutral on R1v. Leaves stored over one axis, and 'ppermute' (axis by + # axis anyway), gather alike either way. Opt-in: ds_ep_pipeline + # --gather-axes. + gather_axes: str = "joint" + # Batch split, Lineage's: a microbatch's rows on each device run as two + # halves, mb0 and mb1, through a chunk's MoE layers in phases: one half's + # EP all-gather or reduce-scatter beside the other half's attention or + # experts, so each EP collective has compute to run behind. The backward + # is the VJP of the chunk's whole split forward, recomputed from the + # chunk's input, so a chunk keeps one residual, its input. Two + # neighbouring microbatches of the unsplit pipeline make one microbatch + # here: it needs an even number of rows a device, cp 1 and no stash mode + # (ds_ep_pipeline --batch-split), and, as neither implementation keeps + # expert counts or an aux loss, no routed-bias update, sequence-wise aux + # loss or MTP. A chunk without a MoE layer (the embedding's or the + # head's alone, or dense layers only) has nothing to split and runs the + # plain path (ChunkPrograms.split), but not on Lineage's layers, which + # refuse it. + batch_split: bool = False + # Whose code runs a batch-split chunk's decoder layers (BATCH_SPLIT_IMPLS). + # None, the default, is the model's, resolved in __post_init__ (so a built + # config names its impl): 'lineage' for DeepSeek-V3, 'native' for the + # Qwen3.5 family, whose layers Lineage does not build (`is_qwen`). (A + # dataclasses.replace(..., model=...) across the families keeps the old + # model's impl: pass batch_split_impl=None with it.) + # 'lineage' MaxText's Lineage layers (src/maxtext/experimental/lineage, the + # MLPerf DeepSeek-V3 batch-split stack) through ds_ep_lineage: + # its MLA and splash attention, router, SparseCore dispatch and + # combine and gmmv2 expert kernels, chained over the chunk's MoE + # layers as its driver chains them (the dense layers first, + # Lineage's dense layer each), and its own backward. Lineage's + # code is global-view code that reads layouts from sharding + # types, so the chunk's programs are jits at global view on + # Explicit stage meshes (ChunkPrograms: the embedding, the head + # and every gather / reduce-scatter folded in run in shard_maps of + # their own): it needs shard_mode 'explicit' (so grad_reduce + # 'step'), top-k routing (Lineage draws no random experts), a + # dropless dispatch (ragged_buffer_factor <= 0) and a model + # Lineage builds (ds_ep_lineage.check), and its forwards take no + # prefetch pin (Lineage's layers have no point to tie). gmm_impl, + # the tilings, use_ragged_sort, ep_collectives, split_dw, + # expert_weights and route_weights mean nothing to its layers + # (ds_ep_lineage.IGNORED_STAGE_KNOBS). DeepSeek-V3 only. + # 'native' `split_layers`: this module's own layers -- DeepSeek-V3's, or the + # Qwen3.5 family's with its mixer in attention's place -- with + # MaxText's ring-of-experts and megablox kernels in Lineage's four + # phases a layer, an optimization barrier closing each. + # DeepSeek-V3's where Lineage's TPU kernels do not run (GPU, + # CPU; ds_ep_pipeline refuses it on TPU), and the Qwen3.5 + # family's only batch split. + batch_split_impl: str | None = None + # impl 'lineage': Lineage's MoE chunk size relative to a device's balanced + # load of routed slots (ds_ep_lineage.CAPACITY_FACTOR; MaxText's DeepSeek-V3 + # Lineage recipe runs 3.0). Dropless at any value: it sets how many trips + # Lineage's expert loop takes. + lineage_capacity_factor: float = 2.0 + # How a batch-split layer's backward combines the halves' routed-expert + # weight gradients (impl 'native'). 'acc': mb0's grouped matmuls hand + # their weights on to mb1's (moe_experts pass_weights), so mb0's dW kernel + # starts from mb1's dW and adds into it (megablox tgmm existing_out, in + # place; Lineage's grad_w_acc). 'sum': each half's VJP gives its own dW and + # XLA adds the two copies, an add fusion over every [E / EP, D, F] leaf + # (ds_ep_pipeline --split-dw). The other weights' halves are summed either + # way. + split_dw: str = "acc" + # How the routed experts' megablox kernels read a layer's weights, which a + # chunk's programs get stacked ([layers, ...] a leaf). 'stacked': in place, + # the group sizes moved onto the layer's block (moe_experts' stacked). + # 'sliced': from a slice, which XLA copies into a buffer of its own first, + # because a custom call takes whole buffers: on TPU7x 4.8 ms of a 39 ms + # forward at M=8, in every program, and the fused last chunk lays the slices + # out once more (2 x TPU7x-4x4x4, 2026-10). The same products either way, bit + # for bit; stash modes read slices (ds_ep_pipeline --expert-weights). Not + # under batch_split_impl 'lineage', whose layers run no megablox kernel. + expert_weights: str = "stacked" + + @property + def lineage_split(self): + """Do the batch-split chunks run Lineage's layers (batch_split, impl 'lineage')?""" + return self.batch_split and self.batch_split_impl == "lineage" + + def __post_init__(self): + if self.batch_split_impl is None: # the model's: Lineage builds DeepSeek-V3's layers only + object.__setattr__(self, "batch_split_impl", "native" if is_qwen(self.model) else "lineage") + wi, wo = TILES["clamped"](self.model) + if self.batch_split and self.batch_split_impl == "native" and self.split_dw == "acc": + wi = split_acc_wi_tiling(wi) + wi = _tiling9("wi_tiling", wi if self.wi_tiling is None else self.wi_tiling) + wo = _tiling9("wo_tiling", wo if self.wo_tiling is None else self.wo_tiling) + object.__setattr__(self, "wi_tiling", wi) + object.__setattr__(self, "wo_tiling", wo) + if self.batch_split_impl not in BATCH_SPLIT_IMPLS: + raise ValueError(f"batch_split_impl must be one of {BATCH_SPLIT_IMPLS}, got {self.batch_split_impl!r}") + if not (isinstance(self.lineage_capacity_factor, numbers.Real) and self.lineage_capacity_factor > 0): + raise ValueError(f"lineage_capacity_factor must be a number > 0, got {self.lineage_capacity_factor!r}") + if self.lineage_split: + self._check_lineage() + if self.gmm_impl not in GMM_IMPLS: + raise ValueError(f"gmm_impl must be one of {GMM_IMPLS}, got {self.gmm_impl!r}") + if self.fsdp_collectives not in FSDP_COLLECTIVES: + raise ValueError(f"fsdp_collectives must be 'ppermute' or 'xla', got {self.fsdp_collectives!r}") + if self.ep_collectives not in EP_COLLECTIVES: + raise ValueError( + f"ep_collectives must be 'xla' or 'ppermute' (or 'auto', which Pipeline " + f"resolves per stage), got {self.ep_collectives!r}" + ) + if self.ragged_buffer_factor > 0 and not self.use_ragged_sort and self.gmm_impl != "tokamax": + raise ValueError( + f"ragged_buffer_factor {self.ragged_buffer_factor} caps the ring's ragged-sort buffer: " + "it needs use_ragged_sort (or gmm_impl 'tokamax', whose compact local buffer it caps)" + ) + if self.gmm_impl == "tokamax" and self.use_ragged_sort: + raise ValueError( + "gmm_impl='tokamax' sorts this device's rows into a compact buffer of its own " + "(_local_plan); MaxText's ring_ragged_sort is megablox's: use use_ragged_sort=False" + ) + if self.tokamax_gmm not in TOKAMAX_GMM: + raise ValueError(f"tokamax_gmm must be one of {TOKAMAX_GMM}, got {self.tokamax_gmm!r}") + if self.route_weights not in ROUTE_WEIGHTS: + raise ValueError(f"route_weights must be one of {ROUTE_WEIGHTS}, got {self.route_weights!r}") + # (Lineage's layers weigh their experts' outputs in their own combine: under its batch split the knob is moot.) + if self.route_weights == "experts" and self.use_ragged_sort and not self.lineage_split: + raise ValueError( + "route_weights 'experts' scales each buffer row by its (token, choice) pair's routing weight, " + "and MaxText's ring_ragged_sort keeps the rows' pairs inside its kernels: use " + "use_ragged_sort=False (the argsort dispatch, or gmm_impl 'tokamax''s compact buffer)" + ) + if self.layer_tree not in LAYER_TREES: + raise ValueError(f"layer_tree must be one of {LAYER_TREES}, got {self.layer_tree!r}") + if self.cp not in (1, 2, 4) or self.ep % self.cp: + raise ValueError( + f"cp {self.cp!r}: want 1, 2 or 4 dividing ep={self.ep} (a sequence's chunks share an " "'expert' ring)" + ) + # (Lineage's layers run no megablox kernel: under its batch split no tiling is ever used.) + bad = tiling_problems(self.model, wi, wo) if self.gmm_impl == "megablox" and not self.lineage_split else [] + if bad: + msg = ( + TILING_WARNING + " -- megablox rounds the tile count up and masks the tail, so the " + "MXU runs the whole padded block (same outputs, more time; see ds_ep.TILES): " + "; ".join(bad) + ) + if self.strict_tiling: + raise ValueError(msg) + warnings.warn(msg, stacklevel=3) + # _ag2 / _rs2 exchange with ONE peer: exact only on mesh axes of size 1 or 2. + if self.fsdp_collectives == "ppermute" and (self.fsdp not in (1, 2) or self.ep not in (1, 2)): + raise ValueError("fsdp_collectives='ppermute' needs fsdp, ep in (1, 2); use 'xla' otherwise") + if self.ep_collectives == "ppermute" and self.ep != 2: + raise ValueError("ep_collectives='ppermute' needs ep == 2; use 'xla' otherwise") + if self.grad_reduce not in ("step", "microbatch"): + raise ValueError(f"grad_reduce must be step or microbatch, got {self.grad_reduce!r}") + if self.adam_math not in ("fp32", "optax"): + raise ValueError(f"adam_math must be 'fp32' or 'optax', got {self.adam_math!r}") + if self.grad_dtype is not None and not jnp.issubdtype(self.grad_dtype, jnp.floating): + raise ValueError(f"grad_dtype must be None or a floating dtype, got {self.grad_dtype!r}") + if not (isinstance(self.grad_clip, (int, float)) and self.grad_clip >= 0): + raise ValueError(f"grad_clip must be a number >= 0 (0: no clip), got {self.grad_clip!r}") + if self.rs_axes not in RS_AXES: + raise ValueError(f"rs_axes must be one of {RS_AXES}, got {self.rs_axes!r}") + if self.gather_axes not in GATHER_AXES: + raise ValueError(f"gather_axes must be one of {GATHER_AXES}, got {self.gather_axes!r}") + if self.shard_mode not in SHARD_MODES: + raise ValueError(f"shard_mode must be one of {SHARD_MODES}, got {self.shard_mode!r}") + if self.shard_mode == "explicit" and self.grad_reduce != "step": + raise ValueError( + "shard_mode='explicit' types the accumulator of a step's per-device partial gradients " + "unreduced: it needs grad_reduce='step'" + ) + if self.batch_split and self.cp > 1: + raise ValueError( + f"batch_split halves the rows a device holds; context parallelism (cp={self.cp}) holds " "one: use cp 1" + ) + if self.split_dw not in SPLIT_DW: + raise ValueError(f"split_dw must be one of {SPLIT_DW}, got {self.split_dw!r}") + if self.expert_weights not in EXPERT_WEIGHTS: + raise ValueError(f"expert_weights must be one of {EXPERT_WEIGHTS}, got {self.expert_weights!r}") + if self.shard_mode == "explicit" and self.fsdp * self.ep == 1: + # jax 0.11.1 lowers a shard_map whose manual axes all have size 1 inline, + # and its lowering then refuses an unreduced-typed output that is not a + # sharding constraint (mlir.check_unreduced_constraint). + raise ValueError( + "shard_mode='explicit' needs a stage of more than one device (fsdp x ep > 1): a one-device " + "stage has nothing to reduce, and jax lowers its shard_maps inline, which refuses their " + "unreduced outputs" + ) + if is_qwen(self.model): + _check_qwen(self) + + def _check_lineage(self): + """batch_split_impl 'lineage': ValueError naming everything Lineage's layers cannot run, all at once -- this + stage's settings here, the model's by ds_ep_lineage.check(model). Pure config: ds_ep_lineage imports this + module (so it is imported here, lazily) but no Lineage, and check reads fields only, so a StageConfig validates + on a MaxText without Lineage. (ds_ep_lineage.Region runs the whole check, its stage part too, when a chunk's + programs first trace.) A Qwen3.5-family model is refused alone: Lineage has none of its layers, so the stage's + settings are moot.""" + from maxtext.experimental.mpmd.jax import ds_ep_lineage + + qwen, bad = is_qwen(self.model), [] + if not qwen: + if self.shard_mode != "explicit": + bad.append( + f"shard_mode {self.shard_mode!r}, want 'explicit': Lineage's code is global-view code that reads " + "its layouts from sharding types, so a chunk's programs run at global view on Explicit stage " + "meshes" + ) + if self.grad_reduce != "step": + bad.append( + f"grad_reduce {self.grad_reduce!r}, want 'step': the programs add Lineage's per-device partial " + "weight gradients into unreduced accumulators, reduce-scattered once a step" + ) + if self.random_routing: + bad.append( + "random routing: Lineage routes top-k only, it draws no random experts (there is no RNG in it): " + "random_routing=False (ds_ep_pipeline --routing topk)" + ) + if self.ragged_buffer_factor > 0: + bad.append( + f"ragged_buffer_factor {self.ragged_buffer_factor}: Lineage is dropless, and > 0 drops the " + "tokens past the ring's capped dispatch buffer, which it has no counterpart of (want <= 0)" + ) + if self.cp > 1: + bad.append( + f"cp {self.cp}: the batch split halves the rows a device holds, context parallelism holds one " + "(and Lineage's splash attention shards heads, never the sequence)" + ) + if self.model.num_experts % self.ep: + bad.append(f"num_experts {self.model.num_experts} is not a multiple of ep {self.ep}") + try: + ds_ep_lineage.check(self.model) + except ValueError as e: + bad.append(str(e)) + if bad: + raise ValueError( + "batch_split_impl 'lineage' cannot run this: " + + "; ".join(bad) + + ( + " (batch_split_impl 'native' -- the Qwen3.5 family's default, None -- runs its split_layers)" + if qwen + else " (off TPU, batch_split_impl 'native' runs split_layers instead)" + ) + ) + + +def is_qwen(cfg) -> bool: + """Is `cfg` a Qwen3.5-family model (maxtext.experimental.mpmd.jax.qwen35: Qwen3.5, Qwen3.8), rather than DeepSeek-V3?""" + return isinstance(cfg, Qwen35Config) + + +def _check_qwen(scfg: StageConfig): + """What the Qwen3.5-family stage programs do not implement, refused here rather than traced wrong.""" + cfg = scfg.model + if scfg.cp != 1: + # The GDN's recurrent state and conv window would have to pass from one + # chunk of a sequence to the next (MaxText's gdn_cp.py); cp_kv_context is MLA's. + raise ValueError( + f"cp={scfg.cp}: context parallelism is not implemented for the Qwen3.5 family " "(Gated DeltaNet state passing)" + ) + if cfg.shared_experts != 1: + raise ValueError( + f"shared_experts={cfg.shared_experts}: the Qwen3.5-family stage programs build the one " + "sigmoid-gated shared expert every Qwen3.5 / Qwen3.8 MoE layer has" + ) + if cfg.moe_impl != "ragged": + raise ValueError( + f"moe_impl={cfg.moe_impl!r}: the routed experts are the ring of experts (sort + grouped " + "matmuls), MaxText's sparse_matmul; there is no dense MoE here" + ) + # These flags choose the port's (and MaxText's) MoE and head numerics, which the stage programs fix: moe_experts + # sums the top k in fp32, named_gmm accumulates in fp32, head_loss casts the logits to fp32. MaxText's + # sparse_matmul reads float32_weight_sum and moe_use_direct_token_gather on its argsort dispatch only + # (layers/moe.py) -- this one's counterpart, and what it runs at EP 1, where it refuses the ring and the ragged + # sort -- and its ring + ragged-sort path ignores them, as use_ragged_sort's does here. So float32_weight_sum=False + # is refused wherever MaxText's dispatch is the argsort one: with use_ragged_sort off, or at ep 1. The direct + # gather only where this pipeline runs its argsort dispatch, with use_ragged_sort off: that one repeats and sorts + # the tokens, so dx sums a token's k copies in the compute dtype, as MaxText's does without the flag. The ragged + # sort's backward (ring_ragged_sort's ragged_gather_reduce, at ep 1 as on the ring) sums them in fp32 and rounds + # once, as MaxText's direct gather does (bit for bit on CPU: ds_ep_qwen_test.QwenDispatchVsMaxText), so at ep 1 + # it computes MaxText's float32_weight_sum=true moe_use_direct_token_gather=true. The reverse is let through: a + # flag-off model at ep 1 with the ragged sort gets that fp32 dx, where MaxText's EP-1 argsort dispatch sums in the + # compute dtype (--ragged-sort auto turns the sort off at ep 1). + if (not scfg.use_ragged_sort or scfg.ep == 1) and not cfg.float32_weight_sum: + raise ValueError( + "float32_weight_sum=False: MaxText's argsort dispatch (the counterpart with use_ragged_sort off, " + "and at ep 1) then sums the top k in the compute dtype; the stage programs sum them in fp32 (only " + "the ring + ragged-sort path ignores the flag, here as in MaxText)" + ) + if not scfg.use_ragged_sort and cfg.moe_use_direct_token_gather: + raise ValueError( + "moe_use_direct_token_gather: MaxText's argsort dispatch (the counterpart with use_ragged_sort " + "off) then sums dx over a token's k copies in fp32 (sort_activations.route); the argsort " + "dispatch here repeats and sorts the tokens, and sums them in the compute dtype, as MaxText's " + "does without the flag (the ragged sort's backward sums them in fp32, at ep 1 as on the ring, " + "as the direct gather does)" + ) + if not cfg.gmm_fp32_accum: + raise ValueError( + "gmm_fp32_accum=False (MaxText's ragged_dot fallback, megablox=false use_tokamax_gmm=false): " + "both gmm_impl settings accumulate the grouped matmuls in fp32 (named_gmm)" + ) + if cfg.gmm_exact_drhs and scfg.gmm_impl != "megablox": + raise ValueError( + "gmm_exact_drhs reproduces megablox's dW kernel (tgmm), which gmm_impl='megablox' runs; " + "gmm_impl='ragged_dot' computes dW with an fp32 ragged_dot_general" + ) + if not cfg.cast_logits_to_fp32: + raise ValueError("cast_logits_to_fp32=False: the head casts the logits to fp32 (head_loss)") + n = scfg.fsdp * scfg.ep + if cfg.emb_dim % n or cfg.num_experts % scfg.ep: + raise ValueError( + f"emb_dim={cfg.emb_dim} must divide by fsdp*ep={n} and num_experts={cfg.num_experts} by " + f"ep={scfg.ep} (the storage layout shards them so)" + ) + + +# ------------------------------------------------------------ the param tree +def layer_shapes(cfg: DeepSeekConfig, bias=False): + """Shapes of one MoE decoder layer, in ds_ep's leaf names (MaxText's NNX tree, see deepseek/convert.py); `bias`: + its router's routed bias (DeepSeekConfig.routed_bias), which picks the experts and is not trained (`count_leaves`).""" + D, H, E = cfg.emb_dim, cfg.num_query_heads, cfg.num_experts + F, Fs = cfg.moe_mlp_dim, cfg.shared_expert_mlp_dim * cfg.shared_experts + return { + "pre_self_attention_layer_norm": {"scale": (D,)}, + "post_self_attention_layer_norm": {"scale": (D,)}, + "self_attention": { + "wq_a": {"kernel": (D, cfg.q_lora_rank)}, + "q_norm": {"scale": (cfg.q_lora_rank,)}, + "wq_b": {"kernel": (cfg.q_lora_rank, H, cfg.qk_head_dim)}, + "wkv_a": {"kernel": (D, cfg.kv_lora_rank + cfg.qk_rope_head_dim)}, + "kv_norm": {"scale": (cfg.kv_lora_rank,)}, + "wkv_b": {"kernel": (cfg.kv_lora_rank, H, cfg.qk_nope_head_dim + cfg.v_head_dim)}, + "out": {"kernel": (H, cfg.v_head_dim, D)}, + }, + "moe": { + "gate": {"kernel": (D, E), **({"bias": (E,)} if bias else {})}, + "wi_0": (E, D, F), + "wi_1": (E, D, F), + "wo": (E, F, D), + "shared_experts": { + "wi_0": {"kernel": (D, Fs)}, + "wi_1": {"kernel": (D, Fs)}, + "wo": {"kernel": (Fs, D)}, + }, + }, + } + + +def dense_layer_shapes(cfg: DeepSeekConfig): + """Shapes of one dense decoder layer, DeepSeek-V3's first `first_num_dense_layers`: layer_shapes' attention and + norms, and a dense MLP of width `mlp_dim` (MaxText's `mlp`) in place of the experts.""" + D, F = cfg.emb_dim, cfg.mlp_dim + shapes = {k: v for k, v in layer_shapes(cfg).items() if k != "moe"} + shapes["mlp"] = {"wi_0": {"kernel": (D, F)}, "wi_1": {"kernel": (D, F)}, "wo": {"kernel": (F, D)}} + return shapes + + +def dense_layer_storage_specs(): + """layer_storage_specs' attention and norms; the dense MLP stored as the shared expert is.""" + specs = {k: v for k, v in layer_storage_specs().items() if k != "moe"} + specs["mlp"] = {"wi_0": {"kernel": P(FE, None)}, "wi_1": {"kernel": P(FE, None)}, "wo": {"kernel": P(None, FE)}} + return specs + + +def layer_storage_specs(bias=False): + """MaxText's pipeline-large-moe sharding rules on a ('fsdp','expert') stage.""" + return { + "pre_self_attention_layer_norm": {"scale": P(None)}, + "post_self_attention_layer_norm": {"scale": P(None)}, + "self_attention": { + "wq_a": {"kernel": P(FE, None)}, + "q_norm": {"scale": P(None)}, + "wq_b": {"kernel": P("fsdp", None, None)}, + "wkv_a": {"kernel": P(FE, None)}, + "kv_norm": {"scale": P(None)}, + "wkv_b": {"kernel": P("fsdp", None, None)}, + "out": {"kernel": P(None, None, FE)}, + }, + "moe": { + "gate": {"kernel": P("fsdp", None), **({"bias": P(None)} if bias else {})}, + "wi_0": P("expert", "fsdp", None), + "wi_1": P("expert", "fsdp", None), + "wo": P("expert", None, "fsdp"), + "shared_experts": { + "wi_0": {"kernel": P(FE, None)}, + "wi_1": {"kernel": P(FE, None)}, + "wo": {"kernel": P(None, FE)}, + }, + }, + } + + +def mtp_shapes(cfg: DeepSeekConfig, bias=False): + """One multi-token-prediction layer (multi_token_prediction.py, MultiTokenPredictionLayer): the norms of the main + hidden state and of the next token's embedding, their [2 x emb -> emb] projection, an MoE decoder layer and its + final norm -- and a copy of the token embedding, which MaxText shares with the decoder's input (the last chunk's + copy and chunk 0's table get one gradient, their sum: ds_ep_pipeline.Pipeline). The copy is never gathered: it + computes in its storage blocks (`chunk_compute_specs`, `_sharded_embed`).""" + D = cfg.emb_dim + return { + "embedding_norm": {"scale": (D,)}, + "hidden_state_norm": {"scale": (D,)}, + "projection": {"kernel": (2 * D, D)}, + "layer": layer_shapes(cfg, bias), + "final_norm": {"scale": (D,)}, + "token_embedder": {"embedding": (cfg.vocab_size, D)}, + } + + +def mtp_storage_specs(bias=False): + return { + "embedding_norm": {"scale": P(None)}, + "hidden_state_norm": {"scale": P(None)}, + "projection": {"kernel": P(FE, None)}, + "layer": layer_storage_specs(bias), + "final_norm": {"scale": P(None)}, + "token_embedder": {"embedding": P(None, FE)}, + } + + +# The Qwen3.5 family's two mixers, one entry a layer in `ChunkSpec.kinds`; each +# is also the key of that mixer's subtree inside a layer's subtree of a chunk's +# 'layers' tree (`_qwen_layers_tree`). +QWEN_KINDS = ("gdn", "attn") +# A DeepSeek-V3 layer's kind, MoE or dense, under StageConfig.layer_tree 'per_layer': +# the chunk's 'layers' (and 'dense_layers') are then one subtree a layer, as a Qwen +# chunk's (`_qwen_layers_tree`), with no mixer subtree of its own (MLA is in the +# common parts). +DEEPSEEK_KIND = "mla" +LAYER_TREES = ("stacked", "per_layer") + + +def layer_kinds(cfg, layers, per_layer=False): + """`ChunkSpec.kinds` of the global layer ids `layers`: for DeepSeek () (its + layers stacked) or, `per_layer` (StageConfig.layer_tree), DEEPSEEK_KIND a + layer; for a Qwen3.5-family model 'attn' for a gated full-attention layer + (`Qwen35Config.is_attention_layer`, every cycle-th) and 'gdn' for a Gated + DeltaNet one.""" + if not is_qwen(cfg): + return (DEEPSEEK_KIND,) * len(layers) if per_layer else () + return tuple("attn" if cfg.is_attention_layer(l) else "gdn" for l in layers) + + +def dense_layer_kinds(n, per_layer=False): + """`ChunkSpec.dense_kinds` of a chunk's `n` dense layers: () (stacked) or, + `per_layer` (StageConfig.layer_tree), DEEPSEEK_KIND a layer.""" + return (DEEPSEEK_KIND,) * n if per_layer else () + + +def qwen_layer_shapes(cfg: Qwen35Config): + """One Qwen3.5-family layer in parts: `common`, what every layer has (its two + zero-centred norms and the MoE: router, routed experts, shared expert and its + gate), and each mixer, `gdn` and `attn` (a layer has one of them). The leaf names + are `maxtext.experimental.mpmd.jax.qwen35`'s (MaxText's NNX tree), so the port's functions take the + subtrees as they are.""" + D, X, F, Fs = cfg.emb_dim, cfg.num_experts, cfg.moe_mlp_dim, cfg.shared_expert_mlp_dim + hv, hd = cfg.gdn_num_value_heads, cfg.head_dim + return { + "common": { + "input_layernorm": {"scale": (D,)}, + "post_attention_layernorm": {"scale": (D,)}, + "mlp": { + "routed_experts": {"gate": {"kernel": (D, X)}, "wi_0": (X, D, F), "wi_1": (X, D, F), "wo": (X, F, D)}, + "shared_expert": {"wi_0": {"kernel": (D, Fs)}, "wi_1": {"kernel": (D, Fs)}, "wo": {"kernel": (Fs, D)}}, + "shared_expert_gate": {"kernel": (D, 1)}, + }, + }, + "gdn": { + "in_proj_qkvz": {"kernel": (D, cfg.gdn_qkvz_dim)}, + "in_proj_ba": {"kernel": (D, 2 * hv)}, + "conv1d": {"kernel": (cfg.gdn_conv_kernel_dim, 1, cfg.gdn_conv_dim)}, + "A_log": (hv,), + "dt_bias": (hv,), + "norm": {"rms_norm": {"scale": (cfg.gdn_value_head_dim,)}}, + "out_proj": {"kernel": (cfg.gdn_value_dim, D)}, + }, + "attn": { + "query": {"kernel": (D, cfg.num_query_heads, 2 * hd)}, + "key": {"kernel": (D, cfg.num_kv_heads, hd)}, + "value": {"kernel": (D, cfg.num_kv_heads, hd)}, + "query_norm": {"scale": (hd,)}, + "key_norm": {"scale": (hd,)}, + "out": {"kernel": (cfg.num_query_heads * hd, D)}, + }, + } + + +def qwen_layer_storage_specs(): + """`qwen_layer_shapes`' storage specs, by DeepSeek's rules (`layer_storage_specs`): + projections shard their embed axis over ('fsdp', 'expert'), the router over + 'fsdp', the routed experts their expert axis over 'expert' and their embed + axis over 'fsdp'; what is used elementwise (norm scales, the depthwise conv + kernel, A_log, dt_bias) is replicated.""" + return { + "common": { + "input_layernorm": {"scale": P(None)}, + "post_attention_layernorm": {"scale": P(None)}, + "mlp": { + "routed_experts": { + "gate": {"kernel": P("fsdp", None)}, + "wi_0": P("expert", "fsdp", None), + "wi_1": P("expert", "fsdp", None), + "wo": P("expert", None, "fsdp"), + }, + "shared_expert": { + "wi_0": {"kernel": P(FE, None)}, + "wi_1": {"kernel": P(FE, None)}, + "wo": {"kernel": P(None, FE)}, + }, + "shared_expert_gate": {"kernel": P(FE, None)}, + }, + }, + "gdn": { + "in_proj_qkvz": {"kernel": P(FE, None)}, + "in_proj_ba": {"kernel": P(FE, None)}, + "conv1d": {"kernel": P(None, None, None)}, + "A_log": P(None), + "dt_bias": P(None), + "norm": {"rms_norm": {"scale": P(None)}}, + "out_proj": {"kernel": P(None, FE)}, + }, + "attn": { + "query": {"kernel": P(FE, None, None)}, + "key": {"kernel": P(FE, None, None)}, + "value": {"kernel": P(FE, None, None)}, + "query_norm": {"scale": P(None)}, + "key_norm": {"scale": P(None)}, + "out": {"kernel": P(None, FE)}, + }, + } + + +def _qwen_layers_tree(kinds, parts, stack): + """A Qwen chunk's 'layers' tree from `parts` (`qwen_layer_shapes` or + `qwen_layer_storage_specs`): one subtree a layer, keyed by its place in the + chunk (`qwen_layer_key`), with the common parts and its own mixer's, every + leaf with a leading layer axis of one (`stack(leaf, 1)`).""" + out = {} + for l, kind in enumerate(kinds): + t = {k: jax.tree.map(lambda x: stack(x, 1), v, is_leaf=_is_part_leaf) for k, v in parts["common"].items()} + if kind in parts: # a DeepSeek layer's MLA is in its common parts + t[kind] = jax.tree.map(lambda x: stack(x, 1), parts[kind], is_leaf=_is_part_leaf) + out[qwen_layer_key(l)] = t + return out + + +def qwen_layer_key(l): + """The key of a Qwen chunk's l-th layer in its 'layers' tree: '00', '01', ...""" + return f"{l:02d}" + + +def _is_part_leaf(x): + return _is_spec(x) or _is_shape(x) + + +def _compute_of(spec): + """Storage spec -> compute spec: drop every axis but 'expert' on routed leaves.""" + if spec and spec[0] == "expert": # routed experts [E, ., .] + return P("expert", *([None] * (len(spec) - 1))) + return P(*([None] * len(spec))) + + +@dataclasses.dataclass(frozen=True) +class ChunkSpec: + """One pipeline chunk: a contiguous run of decoder layers on one stage -- + `dense` dense layers, then the MoE layers `layers` -- whose weights stack as + 'dense_layers' and 'layers'. The dense layers are the model's first: all in + chunk 0, or, under a layer split that counts every layer, spread over the + first chunks (ds_ep_pipeline.Pipeline). + + `kinds`: each MoE layer's mixer for a Qwen3.5-family model ('gdn' / 'attn', + `layer_kinds`), for DeepSeek DEEPSEEK_KIND a layer under StageConfig.layer_tree + 'per_layer' and () stacked. Non-empty, the chunk's 'layers' are one subtree a + layer (`_qwen_layers_tree`) rather than stacks. `dense_kinds` says the same of + its 'dense_layers' (`dense_layer_kinds`: DEEPSEEK_KIND a layer under + 'per_layer').""" + + index: int + layers: tuple # global MoE layer ids (the routing keys'), dense layers not counted + first: bool + last: bool + stage: int + dense: int = 0 # dense layers run before the MoE layers (chunk 0: first_num_dense_layers) + routed_bias: bool = False # the MoE routers carry a routed bias (DeepSeekConfig.routed_bias) + mtp: int = 0 # multi-token-prediction layers after the head (the last chunk: mtp_num_layers) + kinds: tuple = () # each MoE layer's mixer ('gdn' / 'attn'; DEEPSEEK_KIND), () for stacked DeepSeek layers + dense_kinds: tuple = () # each dense layer's (DEEPSEEK_KIND), () for stacked ones + + @property + def n_moe(self): + return len(self.layers) + + +def chunk_shapes(scfg: StageConfig, ch: ChunkSpec): + cfg = scfg.model + stack = lambda tree, n: jax.tree.map(lambda s: (n,) + s, tree, is_leaf=_is_shape) + tree = {} + if ch.kinds: + parts = qwen_layer_shapes(cfg) if is_qwen(cfg) else {"common": layer_shapes(cfg, ch.routed_bias)} + tree["layers"] = _qwen_layers_tree(ch.kinds, parts, lambda s, k: (k,) + s) + elif ch.n_moe: + tree["layers"] = stack(layer_shapes(cfg, ch.routed_bias), ch.n_moe) + if ch.dense_kinds: + tree["dense_layers"] = _qwen_layers_tree(ch.dense_kinds, {"common": dense_layer_shapes(cfg)}, lambda s, k: (k,) + s) + elif ch.dense: + tree["dense_layers"] = stack(dense_layer_shapes(cfg), ch.dense) + if ch.first: + tree["token_embedder"] = {"embedding": (cfg.vocab_size, cfg.emb_dim)} + if ch.last: + tree["decoder_norm"] = {"scale": (cfg.emb_dim,)} + tree["logits_dense"] = {"kernel": (cfg.emb_dim, cfg.vocab_size)} + if ch.mtp: + tree["mtp"] = mtp_shapes(cfg, ch.routed_bias) + return tree + + +def _is_shape(x): + return isinstance(x, tuple) and all(isinstance(i, int) for i in x) + + +def chunk_storage_specs(ch: ChunkSpec): + stack = lambda tree: jax.tree.map(lambda s: P(None, *s), tree, is_leaf=_is_spec) + tree = {} + if ch.kinds: + parts = ( + {"common": layer_storage_specs(ch.routed_bias)} if ch.kinds[0] == DEEPSEEK_KIND else qwen_layer_storage_specs() + ) + tree["layers"] = _qwen_layers_tree(ch.kinds, parts, lambda s, k: P(None, *s)) + elif ch.n_moe: + tree["layers"] = stack(layer_storage_specs(ch.routed_bias)) + if ch.dense_kinds: + tree["dense_layers"] = _qwen_layers_tree( + ch.dense_kinds, {"common": dense_layer_storage_specs()}, lambda s, k: P(None, *s) + ) + elif ch.dense: + tree["dense_layers"] = stack(dense_layer_storage_specs()) + if ch.first: + tree["token_embedder"] = {"embedding": P(None, FE)} + if ch.last: + tree["decoder_norm"] = {"scale": P(None)} + tree["logits_dense"] = {"kernel": P(FE, None)} + if ch.mtp: + tree["mtp"] = mtp_storage_specs(ch.routed_bias) + return tree + + +# The stacked subtrees of a chunk: a leading layer axis, no mesh axis on it. +STACKS = ("layers", "dense_layers") + + +def count_leaves(ch: ChunkSpec): + """Per leaf of the chunk's weights (jax.tree.leaves order): is it a router's + routed bias? Those are not trained: their gradient slot carries their + layers' expert counts instead -- kept in fp32 through the reduce-scatter and + out of the gradient norm (`scatter_tree`) -- and the update adds + routed_bias_update_rate x sign(mean load - load) (StagePrograms.update), as + MaxText's loss-free balancing does (moe.load_balance_updates_from_counts).""" + flat, _ = jax.tree_util.tree_flatten_with_path(chunk_storage_specs(ch), is_leaf=_is_spec) + return tuple(getattr(path[-1], "key", None) == "bias" for path, _ in flat) + + +def count_mask(ch: ChunkSpec): + """count_leaves as a tree shaped like the chunk's weights.""" + return jax.tree.unflatten(jax.tree.structure(chunk_storage_specs(ch), is_leaf=_is_spec), list(count_leaves(ch))) + + +def deferred_leaves(ch: ChunkSpec): + """Per leaf of the chunk's weights (jax.tree.leaves order, the accumulator's too): does a split last chunk's W + write its gradient (ChunkPrograms.build_split_last)? Its layers' leaves -- under 'layers' and 'dense_layers' -- + but the routers' bias slots, which carry their layers' expert counts (count_leaves): the forward computes those, + and they stay in its F (AI) with the head's, the decoder norm's, MTP's (and a first chunk's embedding's).""" + flat, _ = jax.tree_util.tree_flatten_with_path(chunk_storage_specs(ch), is_leaf=_is_spec) + return tuple( + getattr(path[0], "key", None) in STACKS and not cnt for (path, _), cnt in zip(flat, count_leaves(ch), strict=True) + ) + + +def router_kernel_leaves(ch: ChunkSpec): + """Per leaf of the chunk's weights (jax.tree.leaves order): is it a router's kernel (moe.gate.kernel)?""" + flat, _ = jax.tree_util.tree_flatten_with_path(chunk_storage_specs(ch), is_leaf=_is_spec) + return tuple([getattr(k, "key", None) for k in path[-2:]] == ["gate", "kernel"] for path, _ in flat) + + +def norm_scale_leaves(ch: ChunkSpec): + """Per leaf of the chunk's weights (jax.tree.leaves order): is it a norm's scale?""" + flat, _ = jax.tree_util.tree_flatten_with_path(chunk_storage_specs(ch), is_leaf=_is_spec) + return tuple(getattr(path[-1], "key", None) == "scale" for path, _ in flat) + + +def leaf_dtypes(scfg: StageConfig, ch: ChunkSpec, kind): + """Per leaf of the chunk's weights (jax.tree.leaves order), its dtype as + `kind` -- 'storage' cfg.weight_dtype, 'compute' cfg.dtype -- but under + float32_gate_logits a router's routed bias in fp32 for both, as MaxText + keeps it (GateLogit's bias_dtype: in bf16 its 0.001 steps would round + away), and its kernel's compute copy in fp32: GateLogit (and moe.route) + casts the stored kernel to fp32, so with fp32 weights the router reads the + master's values, not a bf16 copy's. And a Qwen3.5-family model's norm + scales compute in fp32 under norm_numerics 'fp32': MaxText's RMSNorm casts + the stored scale to fp32, in the zero-centred norms (scale_offset) and in + the GDN gated norm's (dtype float32) alike, so they too read the master's + values.""" + cfg = scfg.model + base = jnp.dtype(cfg.weight_dtype if kind == "storage" else cfg.dtype) + f32 = jnp.dtype(jnp.float32) + fp32_scales = kind == "compute" and is_qwen(cfg) and cfg.norm_numerics == "fp32" + scales = norm_scale_leaves(ch) if fp32_scales else (False,) * len(count_leaves(ch)) + if not cfg.float32_gate_logits: + return tuple(f32 if scale else base for scale in scales) + return tuple( + f32 if bias or scale or (kernel and kind == "compute") else base + for bias, kernel, scale in zip(count_leaves(ch), router_kernel_leaves(ch), scales) + ) + + +def leaf_dtype_tree(scfg: StageConfig, ch: ChunkSpec, kind): + """leaf_dtypes as a tree shaped like the chunk's weights.""" + return jax.tree.unflatten( + jax.tree.structure(chunk_storage_specs(ch), is_leaf=_is_spec), list(leaf_dtypes(scfg, ch, kind)) + ) + + +def _layer_compute(spec): + # stacked layer leaves carry a leading None for the layer axis + inner = P(*spec[1:]) + return P(None, *_compute_of(inner)) + + +def chunk_compute_specs(ch: ChunkSpec): + st = chunk_storage_specs(ch) + out = {k: jax.tree.map(_layer_compute if k in STACKS else _compute_of, v, is_leaf=_is_spec) for k, v in st.items()} + if ch.mtp: + # MTP's embedding copy stays in its column blocks (no gather, no full-size gradient: _sharded_embed) + out["mtp"]["token_embedder"] = dict(st["mtp"]["token_embedder"]) + return out + + +def _partial_axes(compute_spec): + """Mesh axes over which a per-device weight gradient is still a partial sum.""" + used = {a for d in compute_spec if d is not None for a in ((d,) if isinstance(d, str) else d)} + rest = tuple(a for a in FE if a not in used) + return rest + + +def typed_spec(cs, kind): + """A plain compute spec -> the same spec typed `kind` ('reduced' or + 'unreduced') over its partial axes (`_partial_axes`). A typed spec refuses + iteration and indexing, so only the programs' in / out specs and shardings + take one: the bodies' helpers (_gather_leaf, _scatter_leaf) read the plain.""" + return P(*cs, **{kind: frozenset(_partial_axes(cs))}) + + +def chunk_wc_specs(scfg: StageConfig, ch: ChunkSpec): + """The gathered compute weights' specs as the programs take and return them: + the compute specs, typed reduced over each leaf's partial axes under + shard_mode 'explicit' (non-routed leaves over both mesh axes, routed experts + over 'fsdp').""" + cs = chunk_compute_specs(ch) + if scfg.shard_mode != "explicit": + return cs + return jax.tree.map(lambda c: typed_spec(c, "reduced"), cs, is_leaf=_is_spec) + + +def chunk_gacc_specs(ch: ChunkSpec, explicit=False): + """Per-device partial gradients: a leading axis over the not-yet-reduced + axes -- or, `explicit`, the compute spec typed unreduced over them.""" + + def one(cs): + return typed_spec(cs, "unreduced") if explicit else P(_partial_axes(cs), *cs) + + return jax.tree.map(one, chunk_compute_specs(ch), is_leaf=_is_spec) + + +def acc_specs(scfg: StageConfig, ch: ChunkSpec): + """Layout of the cross-microbatch gradient accumulator.""" + if scfg.grad_reduce == "microbatch": + return chunk_storage_specs(ch) + return chunk_gacc_specs(ch, scfg.shard_mode == "explicit") + + +def acc_shapes(scfg: StageConfig, ch: ChunkSpec): + return chunk_shapes(scfg, ch) if scfg.grad_reduce == "microbatch" else chunk_gacc_shapes(scfg, ch) + + +def chunk_gacc_shapes(scfg: StageConfig, ch: ChunkSpec): + """Global shapes of the per-device partials (chunk_gacc_specs): a leading + axis of one block per device of the partial axes; under shard_mode + 'explicit' the chunk's own shapes (each device holds a compute-layout block, + the same bytes).""" + if scfg.shard_mode == "explicit": + return chunk_shapes(scfg, ch) + sizes = {"fsdp": scfg.fsdp, "expert": scfg.ep} + + def one(shape, cs): + n = math.prod(sizes[a] for a in _partial_axes(cs)) + return (n,) + shape + + return jax.tree.map(one, chunk_shapes(scfg, ch), chunk_compute_specs(ch), is_leaf=_is_shape) + + +def num_params(scfg: StageConfig, chunks): + tot = 0 + for ch in chunks: + tot += sum(math.prod(s) for s in jax.tree.leaves(chunk_shapes(scfg, ch), is_leaf=_is_shape)) + return tot + + +# ------------------------------------------------------------ per-device math +def ragged_buffer_rows(scfg: StageConfig, tokens): + """Rows of the ring's dispatch buffer a device for `tokens` all-gathered + tokens (the EP group's), as MaxText sizes it (RoutedMoE.get_ragged_buffer_size + of the balanced size (tokens // ep) x top-k): None for the worst case + (dropless, every token x top-k: a buffer that large, or ragged_buffer_factor + <= 0), else ragged_buffer_factor x a device's balanced load.""" + f, K, ep = scfg.ragged_buffer_factor, scfg.model.num_experts_per_tok, scfg.ep + if f <= 0: + return None + rows = int((tokens // ep) * K * f) + return None if rows >= tokens * K else rows + + +def truncate_group_sizes(gs, rows): + """One shard's group sizes `gs` (its rows sorted by group) clamped to a + buffer of `rows` rows: the groups past the buffer's end lose their rows, + from the last row back -- MaxText's `_truncate_matrix` of the shard's + column.""" + return jnp.diff(jnp.minimum(jnp.cumsum(gs), rows), prepend=0).astype(gs.dtype) + + +def gmm_row_tile(scfg: StageConfig): + """The row count megablox needs a grouped matmul's lhs to be a multiple of: + every tm of both tilings -- forward, dlhs and drhs, each of which tiles the + rows -- so their least common multiple (512 for the clamped tiles).""" + return math.lcm(*(t[i] for t in (scfg.wi_tiling, scfg.wo_tiling) for i in (0, 3, 6))) + + +@jax.custom_vjp +def _with_aux_loss(y, aux): + """`y`, with the scalar loss term `aux` riding its backward: wherever `y` is + differentiated, `aux` is too, with cotangent 1 -- its gradient joins the + layer's without any loss output (Megatron-LM's MoEAuxLossAutoScaler).""" + del aux + return y + + +def _with_aux_loss_fwd(y, aux): + return y, aux + + +def _with_aux_loss_bwd(aux, dy): + return dy, jnp.ones_like(aux) + + +_with_aux_loss.defvjp(_with_aux_loss_fwd, _with_aux_loss_bwd) + + +def seq_aux_loss(scores, cfg: DeepSeekConfig): + """Megatron-LM's sequence-wise aux loss of a sigmoid router, per sequence + (moe.megatron_aux_loss_inputs + RoutedMoE.load_balance_loss): the fp32 + pre-bias scores normalized per token, the token fractions from a plain top-k + of them (no bias, no groups) -> load_balance_loss_weight x E x sum over the + experts of fraction x mean probability, [b] for scores [b, S, E].""" + b, S, E = scores.shape + K = cfg.num_experts_per_tok + sc = scores.astype(jnp.float32) + probs = sc / (jnp.sum(sc, axis=-1, keepdims=True) + 1e-20) + _, idx = lax.top_k(sc, K) + rows = jnp.broadcast_to(jnp.arange(b)[:, None, None], idx.shape) + density = jnp.zeros((b, E), jnp.float32).at[rows, idx].add(1.0) / (S * K) + return jnp.sum(density * jnp.mean(probs, axis=1), axis=-1) * E * cfg.load_balance_loss_weight + + +# In-place weight-gradient accumulation (gmm_impl 'tokamax'): while a backward that accumulates into the step's +# gradient accumulator is traced, {MoE layer index in the chunk: {expert leaf: its accumulator block}} of the chunk +# (`ChunkPrograms`' bwd_acc), and in the unsplit layer loops the layer being traced. The routed experts' grouped +# matmul whose dW runs first in the layer's backward starts its dW kernel from that block (tokamax_gmm's dw0, +# gpu_kernels.ragged_dw), so the dW is added into the accumulator where it lies, as megablox's tgmm adds existing_out: +# no [E / EP, D, F] dW buffer of its own a weight and no pass that adds it. +_DW0 = contextvars.ContextVar("mpmd_dw0", default=None) +_DW0_LAYER = contextvars.ContextVar("mpmd_dw0_layer", default=None) + + +@contextlib.contextmanager +def _context(var, value): + tok = var.set(value) + try: + yield + finally: + var.reset(tok) + + +def _dw0_for(l): + """The accumulator blocks for MoE layer `l` of the chunk traced, or None.""" + by_layer = _DW0.get() + return None if by_layer is None or l is None else by_layer.get(l) + + +def _ring_moe(w, x, key, scfg: StageConfig, stacked=None, aux_seqs=0, scores=None): + """Routed experts, ring of experts, on device-local tokens `x [b, S, D]` + -> (output, expert counts [E] int32 of the EP group's tokens' choices). + With `aux_seqs` (the global batch's sequences; load_balance_loss_weight > + 0) the output carries this device's share of the sequence-wise aux loss + (`seq_aux_loss` of its own sequences / aux_seqs, `_with_aux_loss`). + + MaxText's `RoutedMoE.sparse_matmul` under use_ring_of_experts: the all-gather + and route, `RoutedMoE.permute` (ring_ragged_sort), the megablox gmm with + group_offset, `RoutedMoE.unpermute` (ring_ragged_unsort) and the + psum_scatter. In four parts -- the router's scores, the + dispatch (the tokens' all-gather), the experts and the combine (the + reduce-scatter) -- which a batch-split layer (`split_layers`) runs in + phases of their own; composed here they trace as one function. `stacked`: + moe_experts'. `scores`: x's router scores (moe_scores), where the caller + has them already (layer_fwd_counts under lean residuals). + """ + scores = moe_scores(w, x, scfg) if scores is None else scores + aux = jnp.sum(seq_aux_loss(scores, scfg.model)) / aux_seqs if aux_seqs else None + xg, sg = moe_dispatch(x, scores, scfg) + y, counts = moe_experts(w, xg, sg, key, scfg, stacked=stacked, with_counts=True, dw0=_dw0_for(_DW0_LAYER.get())) + y = moe_combine(y, scfg) + return (y if aux is None else _with_aux_loss(y, aux)), counts + + +def moe_scores(w, x, scfg: StageConfig): + """The router's scores of device-local tokens `x [b, S, D]` -> [b, S, E]: + its kernel alone (the routed bias joins after the score function, in + moe_experts: GateLogit), in fp32 under float32_gate_logits (GateLogit's + dtype, on the kernel's fp32 compute copy: leaf_dtypes). A Qwen3.5-family + router's scores are its raw logits.""" + cfg = scfg.model + gcfg = cfg.replace(dtype=jnp.float32) if cfg.float32_gate_logits else cfg + gate = layers.dense_general({"kernel": w["gate"]["kernel"]}, x, gcfg) + if is_qwen(cfg): + # Qwen routes on the raw logits: no score function, a softmax over the + # top k only (qwen35/moe.py:route; moe_experts) + return gate + return layers.activation_fn(cfg.routed_score_func)(gate) + + +def moe_dispatch(x, scores, scfg: StageConfig, tag=None): + """The ring of experts' dispatch: the tokens and their scores all-gathered + over 'expert' -> (xg [EP b, S, D], sg [EP b, S, E]). `tag`: a named scope + inside ep_all_gather (a batch-split half's, mb0 / mb1), where a transform + around the call still wraps ep_all_gather (xprof.scope_of reads it).""" + with jax.named_scope("ep_all_gather"), _scope(tag): + if scfg.ep_collectives == "ppermute" and scfg.ep == 2: + xg = _ag2(x, EP_AXIS, 0) + sg = _ag2(scores, EP_AXIS, 0) + else: + xg = lax.all_gather(x, EP_AXIS, axis=0, tiled=True) + sg = lax.all_gather(scores, EP_AXIS, axis=0, tiled=True) + # checkpoint_name is an identity (no HLO); only a stash forward's policy + # reads the names (STASH_POLICIES). + return checkpoint_name(xg, "moe_xg"), checkpoint_name(sg, "moe_sg") + + +def moe_combine(y, scfg: StageConfig, tag=None): + """The ring of experts' combine: the gathered tokens' expert outputs + reduce-scattered over 'expert' back to this device's tokens (`tag` as in + moe_dispatch).""" + with jax.named_scope("ep_reduce_scatter"), _scope(tag): + if scfg.ep_collectives == "ppermute" and scfg.ep == 2: + return _rs2(y, EP_AXIS, 0) + return lax.psum_scatter(y, EP_AXIS, scatter_dimension=0, tiled=True) + + +def _scope(name): + return jax.named_scope(name) if name else contextlib.nullcontext() + + +def moe_experts(w, xg, sg, key, scfg: StageConfig, pass_weights=False, stacked=None, with_counts=False, dw0=None): + """This shard's routed experts over the gathered tokens `xg [EP b, S, D]` + (scores `sg`): route, sort, the three grouped matmuls, unsort and the + top-k weighted sum -> [EP b, S, D], this shard's part of every gathered + token's output (moe_combine sums the shards'). Routing is MaxText's + get_topk. DeepSeek-V3's is RoutedMoE.deepseek_routing: the experts are + picked on the scores plus the router's routed bias (if it has one), among + each token's best groups (n_routing_groups), and weighed by the scores + without the bias, sum-normalised and scaled by routed_scaling_factor + (deepseek_scale_weights). A Qwen3.5-family model's takes the top k of + the raw logits (no groups, no routed bias), weighed by a softmax over + those k in fp32, rounded to the compute dtype and renormalised under + norm_topk_prob (qwen35/moe.py:route). Under random_routing either family + draws its k experts uniformly with replacement and weighs them by the raw + scores (a Qwen model's raw logits), with no softmax or scaling, as + get_topk returns early. `with_counts`: -> (that, the expert counts [E] + int32 of the gathered tokens' choices). + + `pass_weights`: also hand on the three expert weights as the grouped + matmuls took them (cast to the compute dtype) -> (y, {'wi_0', 'wi_1', + 'wo'}). A later moe_experts that runs on them in place of w's (a + batch-split layer's mb1: split_layers) adds its weight gradients into this + call's inside the dW kernel (named_gmm's acc) instead of beside it. + + `stacked` = (the chunk's stacked expert weights {'wi_0', 'wi_1', 'wo'}, + this layer's index in them): megablox reads the weights there, not from + w's slices of them (named_gmm's stacked), where their dtype is the compute + dtype. + + Under route_weights 'experts' the weights scale the rows of the gated + activation before wo, and the unsort's sum over a token's choices is + unweighted (the argsort dispatch's, or _tokamax_experts'). Under lean + residuals wo's VJP keeps the gated product's inputs, not the product + (`_wo_lhs`), and the wi products of the argsort dispatch keep the gathered + tokens and the order, not the T x K sorted rows of them (`Recompute`).""" + cfg, ep = scfg.model, scfg.ep + _, S, D = xg.shape + E, K = cfg.num_experts, cfg.num_experts_per_tok + dt = cfg.dtype + T = xg.shape[0] * S + sg = sg.reshape(T, E) + if scfg.random_routing: + # moe.random_routing: uniform with replacement, weights are the raw scores and + # deepseek_scale_weights is skipped (get_topk returns early) -- for Qwen the + # raw logits, with no softmax. + idx = jax.random.randint(key, (T * K,), 0, E, dtype=jnp.int32).reshape(T, K) + wts = jnp.take_along_axis(sg, idx, axis=-1) + else: + from maxtext.experimental.mpmd.jax.deepseek import moe as ds_moe + + sel = sg + if "bias" in w["gate"]: + sel = sel + jnp.asarray(w["gate"]["bias"], sel.dtype) # GateLogit: in the activation dtype + # Qwen: the top k of the raw logits (get_topk; no groups, no routed bias) + idx = lax.top_k(sel, K)[1] if is_qwen(cfg) else ds_moe.select_experts(sel, cfg) + wts = jnp.take_along_axis(sg, idx, axis=-1) + if is_qwen(cfg): + # qwen35/moe.py:route (MaxText's get_topk for qwen3_5): a softmax over + # the k selected logits in fp32, rounded, then renormalised in `dt` + wts = jax.nn.softmax(wts.astype(jnp.float32), axis=-1).astype(dt) + if cfg.norm_topk_prob: + wts = wts / wts.sum(-1, keepdims=True) + else: + wts = wts / (wts.sum(-1, keepdims=True) + 1e-20) * cfg.routed_scaling_factor + counts = jnp.zeros((E,), jnp.int32).at[idx.reshape(-1)].add(1) + xf = xg.reshape(T, D) + shard = lax.axis_index(EP_AXIS) + if scfg.gmm_impl == "tokamax": + y, passed = _tokamax_experts(w, xf, idx, wts, shard, scfg, pass_weights, stacked, dw0) + y = y.reshape(-1, S, D) + out = (y, passed) if pass_weights else y + return (out, counts) if with_counts else out + interpret = jax.default_backend() != "tpu" + if scfg.use_ragged_sort: + # RoutedMoE.permute: SparseCore ragged sort in global expert order; this + # shard's experts start at group_offset. + from maxtext.kernels.ragged import ragged_sort + + rows = ragged_buffer_rows(scfg, T) + # (x, group sizes, revert indices, argsort indices): ring_ragged_unsort takes the last optionally + # (topk_argsort_indices, to skip an argsort in its backward: the same permutation, the same values). Unsorted + # without them, as MaxText's own default routing-maps policy (moe_routing_maps=remat) unsorts. + xs, gs, rev, _ = ragged_sort.ring_ragged_sort(xf, idx, E, K, EP_AXIS, ep, buffer_size=rows) + if rows is None: + off, mm_gs = (shard * (E // ep)).astype(jnp.int32), gs + else: + # MaxText's truncated buffer (RoutedMoE.permute, use_truncated_buffer): + # the buffer holds this shard's rows packed from row 0; its groups' + # sizes, clamped to the buffer, and group_offset 0. The unsort takes + # the global sizes, as MaxText's. + off = jnp.int32(0) + mm_gs = truncate_group_sizes(lax.dynamic_slice_in_dim(gs, shard * (E // ep), E // ep), rows) + else: + # RoutedMoE.permute without ragged sort (MaxText requires it at EP=1): roll the expert + # ids so this shard's experts are groups 0..E/EP-1, argsort, repeat + + # custom-VJP gather; megablox then computes only the local groups. + from maxtext.experimental.mpmd.jax.deepseek import moe as ds_moe + + rolled = ((idx - shard * (E // ep)) % E).reshape(-1) + order = jnp.argsort(rolled) + xs = ds_moe._sort_activations(jnp.repeat(xf, K, axis=0), order) + gs = jnp.bincount(rolled, length=E).astype(jnp.int32) + off, mm_gs = jnp.int32(0), gs + + passed = {} + + def mm(name, lhs, wname, tiling, keep=None): + st = (stacked[0][wname], stacked[1]) if stacked is not None and stacked[0][wname].dtype == dt else None + out = named_gmm( + name, + tiling, + interpret, + lhs, + w[wname].astype(dt), + mm_gs, + off, + impl=scfg.gmm_impl, + acc=pass_weights, + stacked=st, + keep=keep, + ) + if pass_weights: + out, passed[wname] = out + return out + + # megablox needs the rows a multiple of every tm (`gmm_row_tile`), which a + # capped buffer -- int(balanced load x ragged_buffer_factor) rows -- rarely + # is: zero rows past every group pad it, and the output is cut back (MaxText + # pads its gmm input with max_utils.maybe_pad and slices the output alike). + m = xs.shape[0] + pad = -m % gmm_row_tile(scfg) if scfg.gmm_impl == "megablox" else 0 + if pad: + xs = jnp.pad(xs, ((0, pad), (0, 0))) + # (MaxText's ring_ragged_sort is a kernel of its own: its rows are kept as they are) + keep_xs = ( + Recompute(functools.partial(_argsort_rows, K=K, pad=pad), (xf, order)) + if layers.lean() and scfg.lean_experts and not scfg.use_ragged_sort + else None + ) + xs = _tie("xs", xs) # prefetch pins (an identity unless a pinned forward traces) + h0 = checkpoint_name(mm("gmm_wi_0", xs, "wi_0", scfg.wi_tiling, keep_xs), "moe_h0") + h1 = checkpoint_name(mm("gmm_wi_1", xs, "wi_1", scfg.wi_tiling, keep_xs), "moe_h1") + # route_weights 'experts': each sorted row's weight (StageConfig refuses it with the ragged sort), the padding's 0 + w_row = ( + jnp.pad(jnp.take(wts.reshape(-1), order, axis=0).astype(jnp.float32), (0, pad)) + if scfg.route_weights == "experts" + else None + ) + act, keep_act = _wo_lhs(h0, h1, w_row, cfg.mlp_activations[0], dt, scfg.lean_experts) + y = mm("gmm_wo", act, "wo", scfg.wo_tiling, keep_act) + y = checkpoint_name(y[:m] if pad else y, "moe_y") + y = _tie("y", y) + if scfg.use_ragged_sort: + y = ragged_sort.ring_ragged_unsort(y, gs, rev, K, E // ep, EP_AXIS, topk_weights=jnp.ravel(wts).astype(jnp.float32)) + else: + # RoutedMoE.unpermute: inverse gather, then the fp32 weighted sum over top-k (its rows weighted already under + # route_weights 'experts': the plain sum) + y = ds_moe._sort_activations(y, jnp.argsort(order)).reshape(T, K, D).astype(jnp.float32) + y = (y.sum(axis=1) if w_row is not None else jnp.einsum("tkd,tk->td", y, wts.astype(jnp.float32))).astype(dt) + y = y.reshape(-1, S, D) + out = (y, passed) if pass_weights else y + return (out, counts) if with_counts else out + + +def _argsort_rows(xf, order, K, pad): + """The argsort dispatch's sorted rows (moe_experts): token order[r] // K of `xf [T, D]` in row r -- the gather + that sorting xf repeated K times is -- and `pad` zero rows after them (megablox's row tile).""" + return jnp.pad(jnp.take(xf, order // K, axis=0), ((0, pad), (0, 0))) + + +@jax.tree_util.register_pytree_node_class +class Recompute: + """A grouped matmul's lhs as its VJP keeps it under lean residuals (`keep` of named_gmm / tokamax_gmm): the arrays + `args` it is recomputed from in the backward, `fn(*args)`, in place of the lhs itself. The wi products' buffer + rows [rows, emb] are kept as the gathered tokens [tokens, emb] they were gathered from (and the dispatch plan): + fewer bytes wherever the buffer has more rows than there are tokens -- a DeepSeek-V3 layer at EP 8, one sequence a + device and ragged_buffer_factor 2 keeps 448 MiB instead of 896 -- for a row gather more in the backward. wo's + gated activation is kept as the gated product's inputs, which the product's own VJP keeps anyway (it runs under + jax.checkpoint), so its [rows, moe_mlp] costs nothing more. `fn(*args)` must be the lhs bit for bit, since the + backward's dW reads it in the lhs's place, and the lhs's gradient reaches `args` through the lhs's own producer (the + dispatch's VJP, the gated product's): the grouped matmul gives `args` none. A pytree, `args` its children and `fn` + static, so that a custom VJP keeps it among its residuals.""" + + def __init__(self, fn, args): + self.fn, self.args = fn, tuple(args) + + def __call__(self): + return self.fn(*self.args) + + def tree_flatten(self): + return self.args, self.fn + + @classmethod + def tree_unflatten(cls, fn, args): + return cls(fn, args) + + +def _kept(lhs): + """A grouped matmul's lhs from its residuals: the lhs, or recomputed from what was kept of it (`Recompute`).""" + return lhs() if isinstance(lhs, Recompute) else lhs + + +def named_gmm(name, tiling, interpret, lhs, rhs, gs, off, impl="megablox", acc=False, stacked=None, keep=None): + """The routed experts' grouped matmul, `lhs[r] @ rhs[g - off]` for every row + r of a group g in [off, off + rhs.shape[0]) (rows sorted by group, `gs` the + sizes of ALL groups; rows of other groups come out zero), with the kernels + named for xprof: `name` forward, `name_dx` / `name_dw` backward. + + acc=True -> (out, rhs): `rhs` handed on, for another grouped matmul of the + same weight to run on. That one's weight gradient, the cotangent of the + handed-on copy, is this call's dW kernel's starting value: megablox tgmm + adds it as it stores each tile (existing_out, aliased to the output), so + the two gradients make one buffer and no add follows. + + stacked=(w, l): `rhs` is block l of the chunk's stacked weight w [L, + rhs.shape...], and the forward and dlhs kernels read it there -- w as one [L + x rhs.shape[0], ...] array (a bitcast), the group sizes padded with empty + groups so that this layer's land on its block (`_stacked_groups`) -- instead + of from `rhs`, a slice of w that XLA copies into a buffer of its own before + a megablox kernel (a custom call takes whole buffers: on TPU7x 4.8 ms of a + 39 ms forward at M=8). `rhs` then carries only the weight gradient, the + drhs kernel's output: its value is never read, so XLA drops the slice. The + same tiles, the same products: bit for bit on every row of the groups and in + dW (ds_ep_test.Kernels). megablox only: ragged_dot reads `rhs` (XLA lowers + its dot itself, and with more groups it rounds differently). + + impl='megablox': megablox `ops.gmm` (its unquantized megablox path, bit for + bit) with the 9-tuple `tiling`. megablox's `backend.gmm` / `tgmm` are + jitted, and the jit boundary drops the caller's name scope, so XLA named one + layer's three kernels after whatever enclosed them (`gmm.1`, `shard_map.147`, + `shard_map.148`). A Pallas kernel's HLO instruction name -- its op name in + the trace -- is the innermost named scope, so call the unjitted bodies under + one. + + impl='ragged_dot': the same three products in pure JAX (`jax.lax.ragged_dot` + / `ragged_dot_general`, fp32 accumulation like megablox); `tiling` and + `interpret` are unused and MaxText is not imported. + + keep (a Recompute of `lhs`): what the VJP keeps of the lhs for the dW + kernel, recomputed in the backward, instead of the lhs. + """ + ws, layer = (None, None) if stacked is None else stacked + if ws is not None and (tuple(ws.shape[1:]) != tuple(rhs.shape) or ws.dtype != rhs.dtype): + raise ValueError( + f"named_gmm stacked: block {layer} of a {ws.dtype}{list(ws.shape)} weight is not the " + f"{rhs.dtype}{list(rhs.shape)} rhs" + ) + if impl == "megablox": + f = _megablox_gmm_acc if acc else _megablox_gmm + return f(name, tiling, interpret, layer, lhs, rhs, gs, off, ws, keep) + if impl == "ragged_dot": + return (_ragged_gmm_acc if acc else _ragged_gmm)(name, lhs, rhs, gs, off, keep) + if impl == "tokamax": + raise ValueError( + "named_gmm: gmm_impl 'tokamax' runs on a compact local buffer, through tokamax_gmm " + "(moe_experts' _tokamax_experts), not on the ring's sorted rows" + ) + raise ValueError(f"named_gmm impl must be one of {GMM_IMPLS}, got {impl!r}") + + +def _stacked_groups(gs, off, n_local, layer, n_layers): + """Group sizes and an offset that put groups [off, off + n_local) of `gs` + on block `layer` of a stacked [n_layers x n_local, ...] rhs: the other + layers' blocks get empty groups. When `gs` holds just those groups (the + truncated ring buffer: off 0), offset 0 and n_layers x n_local groups, as + many as the rhs has, so megablox zeroes no rows it did not before; else one + leading group of the rows before them (those of the groups < off), offset + 1, and megablox zeroes the rows outside the rhs's groups, as it did.""" + pad = lambda k: jnp.zeros((k,), gs.dtype) + before, after = pad(layer * n_local), pad((n_layers - 1 - layer) * n_local) + if gs.shape[0] == n_local: + return jnp.concatenate([before, gs, after]), jnp.int32(0) + lead = jnp.sum(jnp.where(jnp.arange(gs.shape[0]) < off, gs, 0)).astype(gs.dtype) + local = lax.dynamic_slice_in_dim(gs, off, n_local) + return jnp.concatenate([lead[None], before, local, after]), jnp.int32(1) + + +def _gmm_operands(rhs, gs, off, ws, layer): + """(the rhs the forward and dlhs kernels read, its group sizes, its group + offset): `rhs`, `gs`, `off` themselves, or under named_gmm's stacked the + stacked weight `ws` as one [L x E_local, ...] array (`_stacked_groups`).""" + if ws is None: + return rhs, gs, off + n_layers, n_local = ws.shape[:2] + sizes, offset = _stacked_groups(gs, off, n_local, layer, n_layers) + return ws.reshape(n_layers * n_local, *ws.shape[2:]), sizes, offset + + +@contextlib.contextmanager +def _kernel_scope(name, impl="megablox"): + """`megablox/name` (`ragged_dot/name`): a transform wraps only the scope + right after it, so `megablox` takes the backward's `transpose(jvp(...))` and + the kernel keeps its name instead of becoming `transpose_jvp_gmm_wo_dx__`.""" + with jax.named_scope(impl), jax.named_scope(name): + yield + + +# The keywords named_gmm passes to megablox's unjitted gmm / tgmm (private +# MaxText internals: checked once, on first use, by _megablox). +_MEGABLOX_KWARGS = { + "gmm": ( + "lhs", + "rhs", + "group_sizes", + "preferred_element_type", + "tiling", + "group_offset", + "transpose_rhs", + "interpret", + ), + "tgmm": ( + "lhs", + "rhs", + "group_sizes", + "preferred_element_type", + "tiling", + "group_offset", + "num_actual_groups", + "existing_out", + "interpret", + ), +} + + +@functools.cache +def _megablox(): + """(gmm, tgmm): megablox's unjitted bodies, imported on first use, their + signatures checked against the keywords named_gmm passes.""" + from maxtext.kernels.megablox import backend # pylint: disable=import-outside-toplevel + + kw_ok = (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY) + out = [] + for fn_name, kws in _MEGABLOX_KWARGS.items(): + fn = getattr(getattr(backend, fn_name, None), "__wrapped__", None) + if fn is None: + raise RuntimeError( + f"MaxText changed megablox: {backend.__name__}.{fn_name} ({backend.__file__}) " + "is no longer a jitted function with an unjitted __wrapped__ body, which " + "ds_ep.named_gmm calls" + ) + params = inspect.signature(fn).parameters + bad = [k for k in kws if k not in params or params[k].kind not in kw_ok] + if bad: + raise RuntimeError( + f"MaxText changed megablox: {backend.__name__}.{fn_name}{inspect.signature(fn)} " + f"({backend.__file__}) does not take {bad} by keyword, which " + "ds_ep.named_gmm passes" + ) + out.append(fn) + return tuple(out) + + +# named_gmm's kernels. `layer` and `ws` are its stacked=(ws, layer), (None, +# None) without; `ws` gets no gradient (its block's comes out as rhs's), so +# the backward returns None for it. Under stacked the residuals hold `ws`, +# not `rhs`, whose shape and dtype are ws's block's (`_rhs_type`). `keep`: +# named_gmm's, held in the lhs's place among the residuals (None: the lhs); +# it gets no gradient either. +@functools.partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2, 3)) +def _megablox_gmm(name, tiling, interpret, layer, lhs, rhs, gs, off, ws, keep): + return _megablox_gmm_fwd(name, tiling, interpret, layer, lhs, rhs, gs, off, ws, keep)[0] + + +def _megablox_gmm_fwd(name, tiling, interpret, layer, lhs, rhs, gs, off, ws, keep): + gmm, _ = _megablox() + rk, gk, ok = _gmm_operands(rhs, gs, off, ws, layer) + with _kernel_scope(name): + out = gmm( + lhs=lhs, + rhs=rk, + group_sizes=gk, + preferred_element_type=lhs.dtype, + tiling=tiling[:3], + group_offset=ok, + interpret=interpret, + ) + return out, (lhs if keep is None else keep, rhs if ws is None else None, gs, off, ws) + + +def _rhs_type(rhs, ws): + """(shape, dtype) of named_gmm's rhs from its residuals.""" + return (rhs.shape, rhs.dtype) if ws is None else (ws.shape[1:], ws.dtype) + + +def _megablox_gmm_bwd(name, tiling, interpret, layer, res, g, dw_in=None): + """ops._gmm_bwd: dlhs = gmm(g, rhs^T), drhs = tgmm(lhs^T, g) (+ dw_in, + inside the kernel: named_gmm's acc).""" + gmm, tgmm = _megablox() + lhs, rhs, gs, off, ws = res + lhs = _kept(lhs) + shape, dtype = _rhs_type(rhs, ws) + rk, gk, ok = _gmm_operands(rhs, gs, off, ws, layer) + with _kernel_scope(name + "_dx"): + dx = gmm( + lhs=g, + rhs=rk, + group_sizes=gk, + preferred_element_type=lhs.dtype, + tiling=tiling[3:6], + group_offset=ok, + transpose_rhs=True, + interpret=interpret, + ) + with _kernel_scope(name + "_dw"): + dw = tgmm( + lhs=lhs.swapaxes(0, 1), + rhs=g, + group_sizes=gs, + preferred_element_type=dtype, + tiling=tiling[-3:], + group_offset=off, + num_actual_groups=shape[0], + existing_out=dw_in, + interpret=interpret, + ) + return dx, dw, None, None, None, None + + +_megablox_gmm.defvjp(_megablox_gmm_fwd, _megablox_gmm_bwd) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2, 3)) +def _megablox_gmm_acc(name, tiling, interpret, layer, lhs, rhs, gs, off, ws, keep): + return _megablox_gmm_fwd(name, tiling, interpret, layer, lhs, rhs, gs, off, ws, keep)[0], rhs + + +def _megablox_gmm_acc_fwd(name, tiling, interpret, layer, lhs, rhs, gs, off, ws, keep): + out, res = _megablox_gmm_fwd(name, tiling, interpret, layer, lhs, rhs, gs, off, ws, keep) + return (out, rhs), res + + +def _megablox_gmm_acc_bwd(name, tiling, interpret, layer, res, cts): + g, dw_in = cts # dw_in: the gradient of the handed-on rhs + return _megablox_gmm_bwd(name, tiling, interpret, layer, res, g, dw_in) + + +_megablox_gmm_acc.defvjp(_megablox_gmm_acc_fwd, _megablox_gmm_acc_bwd) + + +def _local_groups(gs, off, n_local, m): + """The rows of groups [off, off + n_local) in an m-row buffer sorted by + group (sum(gs) <= m, as for megablox), as an [m, 1] mask, and group sizes + that make ragged_dot visit exactly those groups: the local sizes, with the + rows before them folded into the first and the rows after into the last + (masked to zero, so they add nothing).""" + ends = jnp.cumsum(gs) + lo = (ends - gs)[off] + hi = ends[off + n_local - 1] + rows = lax.broadcasted_iota(jnp.int32, (m, 1), 0) + mask = (rows >= lo) & (rows < hi) + sizes = lax.dynamic_slice_in_dim(gs, off, n_local) + return mask, sizes.at[0].add(lo).at[n_local - 1].add(m - hi) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0,)) +def _ragged_gmm(name, lhs, rhs, gs, off, keep): + return _ragged_gmm_fwd(name, lhs, rhs, gs, off, keep)[0] + + +def _ragged_gmm_fwd(name, lhs, rhs, gs, off, keep): + mask, sizes = _local_groups(gs, off, rhs.shape[0], lhs.shape[0]) + with _kernel_scope(name, "ragged_dot"): + out = lax.ragged_dot(jnp.where(mask, lhs, 0), rhs, sizes, preferred_element_type=jnp.float32) + return jnp.where(mask, out, 0).astype(lhs.dtype), (lhs if keep is None else keep, rhs, gs, off) + + +def _ragged_gmm_bwd(name, res, g, dw_in=None): + """dlhs = g @ rhs^T per group, drhs = lhs^T @ g per group (ragged + contraction), + dw_in in fp32 before the rounding (named_gmm's acc, as + megablox's tgmm adds existing_out).""" + lhs, rhs, gs, off = res + lhs = _kept(lhs) + mask, sizes = _local_groups(gs, off, rhs.shape[0], lhs.shape[0]) + g = jnp.where(mask, g, 0) + with _kernel_scope(name + "_dx", "ragged_dot"): + dx = lax.ragged_dot(g, rhs.swapaxes(1, 2), sizes, preferred_element_type=jnp.float32) + with _kernel_scope(name + "_dw", "ragged_dot"): + dn = lax.RaggedDotDimensionNumbers( + dot_dimension_numbers=(((0,), (0,)), ((), ())), lhs_ragged_dimensions=[0], rhs_group_dimensions=[] + ) + dw = lax.ragged_dot_general(jnp.where(mask, lhs, 0), g, sizes, dn, preferred_element_type=jnp.float32) + if dw_in is not None: + dw = dw + dw_in.astype(jnp.float32) + return jnp.where(mask, dx, 0).astype(lhs.dtype), dw.astype(rhs.dtype), None, None, None + + +_ragged_gmm.defvjp(_ragged_gmm_fwd, _ragged_gmm_bwd) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0,)) +def _ragged_gmm_acc(name, lhs, rhs, gs, off, keep): + return _ragged_gmm_fwd(name, lhs, rhs, gs, off, keep)[0], rhs + + +def _ragged_gmm_acc_fwd(name, lhs, rhs, gs, off, keep): + out, res = _ragged_gmm_fwd(name, lhs, rhs, gs, off, keep) + return (out, rhs), res + + +def _ragged_gmm_acc_bwd(name, res, cts): + g, dw_in = cts + return _ragged_gmm_bwd(name, res, g, dw_in) + + +_ragged_gmm_acc.defvjp(_ragged_gmm_acc_fwd, _ragged_gmm_acc_bwd) + + +# ------------------------------------------------- gmm_impl 'tokamax' (GPU) +# tokamax's grouped matmuls take no group_offset, so this device's rows of the +# ring's gathered tokens go into a compact buffer of their own -- the rows of +# its E / EP experts only, sorted by expert, other shards' rows never in it -- +# instead of the ring's T x K sorted rows (`_local_plan`). Dispatch into it +# and combine out of it are gathers both ways (`_dispatch_rows`, +# `_combine_rows`): each buffer row is one (token, choice) pair, so every +# backward is a gather too, and no scatter-add (atomics on GPU, an order that +# changes run to run) is left in the programs. + + +def _local_plan(idx, shard, n_local, rows): + """This shard's part of the routing `idx [T, K]` (global expert ids; its + experts are [shard x n_local, (shard + 1) x n_local)) -> (src [R] int32, the + token each buffer row takes; gs [n_local] int32, the local experts' group + sizes, clamped to the buffer; valid [R, 1] bool, rows inside a group; pos + [T x K] int32, each (token, choice) pair's row, R for a pair of another + shard's expert or one past the buffer; order [R] int32, the flat (token, + choice) index of each row). R = `rows`, or T x K (dropless) when None. A + stable argsort with other shards' experts keyed last puts the local pairs + first, by expert, and in token order within an expert, as the ring's sort + orders them.""" + T, K = idx.shape + R = T * K if rows is None else min(rows, T * K) + le = idx.reshape(-1) - shard * n_local + local = (le >= 0) & (le < n_local) + key = jnp.where(local, le, n_local).astype(jnp.int32) + order = jnp.argsort(key, stable=True).astype(jnp.int32) + cnt = jnp.bincount(key, length=n_local + 1)[:n_local].astype(jnp.int32) + gs = truncate_group_sizes(cnt, R) + n_valid = jnp.sum(gs) + inv = jnp.zeros((T * K,), jnp.int32).at[order].set(jnp.arange(T * K, dtype=jnp.int32), unique_indices=True) + pos = jnp.where(local & (inv < n_valid), inv, R) + order = order[:R] + valid = (jnp.arange(R, dtype=jnp.int32) < n_valid)[:, None] + return (order // K).astype(jnp.int32), gs, valid, pos, order + + +def _take_rows(a, pos): + """a[pos] over a's rows, zero for pos == len(a) (a gather; the fill keeps it + in bounds without a padded copy of `a`).""" + return jnp.take(a, pos, axis=0, mode="fill", fill_value=0) + + +def _masked(valid, x, fill): + """jnp.where(valid, x, fill) -- or x itself where `valid` is None: a compact buffer every row of which is inside a + group (EP 1 and a dropless buffer: _tokamax_experts' `full`), where the kernels write every row.""" + return x if valid is None else jnp.where(valid, x, fill) + + +def _token_sum(y, pos, w, T, K, dtype, impl): + """sum_k w[t, k] y[pos[t, k]] for each token t (w None: unweighted) in fp32, cast to `dtype`; pos [T x K] is R + (y's length) for a choice with no row. `impl` StageConfig.combine_impl.""" + if impl == "triton": + from maxtext.experimental.mpmd.jax import gpu_kernels + + return gpu_kernels.gather_sum(y, pos.reshape(T, K), w, out_dtype=dtype) + yk = _take_rows(y, pos).reshape(T, K, y.shape[-1]).astype(jnp.float32) + if w is None: + return yk.sum(axis=1).astype(dtype) + return jnp.einsum("tkd,tk->td", yk, w.astype(jnp.float32)).astype(dtype) + + +def _gather_rows(xf, src, valid): + """Token src[r] of `xf [T, D]` in row r of the compact buffer, zero past the groups (`valid`).""" + return _masked(valid, jnp.take(xf, src, axis=0), 0).astype(xf.dtype) + + +def _to_pairs(d_row, pos, order, T, K): + """Per-row values `d_row [R]` placed at their rows' (token, choice) pairs -> [T, K] fp32, zero for a pair with no + row inside the groups. The rows inside the groups are those whose pair points back at them (pos), each at a pair + of its own; the others' values go to distinct indices past the end, which drop them -- so the indices stay unique, + no scatter-add is needed, and what the rows past the groups hold (other pairs', or the garbage an unmasked buffer + leaves there) reaches no pair.""" + rows = jnp.arange(order.shape[0], dtype=order.dtype) + here = jnp.take(pos, order, axis=0) == rows.astype(pos.dtype) + return ( + jnp.zeros((T * K,), jnp.float32) + .at[jnp.where(here, order, T * K + rows)] + .set(d_row, mode="drop", unique_indices=True) + .reshape(T, K) + ) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(4, 5)) +def _dispatch_rows(xf, src, pos, valid, K, impl="xla"): + """The compact buffer's rows: token src[r] of `xf [T, D]` in row r, zero past + the groups. Backward: a token's gradient is the sum of its rows' (pos), + gathered, in fp32 -- not the scatter-add autodiff would emit (`impl`: + StageConfig.combine_impl). pos indexes the rows inside the groups only, so + the gradient's rows past them are never read (and need no mask).""" + return _gather_rows(xf, src, valid) + + +def _dispatch_rows_fwd(xf, src, pos, valid, K, impl="xla"): + return _dispatch_rows(xf, src, pos, valid, K, impl), (src, pos, valid, xf.shape[0]) + + +def _dispatch_rows_bwd(K, impl, res, g): + src, pos, valid, T = res + return _token_sum(g, pos, None, T, K, g.dtype, impl), None, None, None + + +_dispatch_rows.defvjp(_dispatch_rows_fwd, _dispatch_rows_bwd) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(6, 7)) +def _combine_rows(y, wts, src, pos, valid, order, dtype, impl="xla"): + """Each token's output from the buffer: sum over its choices k of wts[t, k] x + y[pos[t, k]] in fp32 (a choice of another shard's expert reads zero), cast + to `dtype` -- the ring's unsort and weighted sum (`impl`: + StageConfig.combine_impl). Backward: a row's gradient is its token's, times + its weight (src, gathered); a weight's, its token's gradient dotted with its + row -- under 'triton' computed for the R rows and placed at their (token, + choice) by `order` rather than for all T x K choices (zero but for the rows + here; the same dots, reduced in another order).""" + T, K = wts.shape + return _token_sum(y, pos, wts, T, K, dtype, impl) + + +def _combine_rows_fwd(y, wts, src, pos, valid, order, dtype, impl="xla"): + return _combine_rows(y, wts, src, pos, valid, order, dtype, impl), (y, wts, src, pos, valid, order) + + +def _combine_rows_bwd(dtype, impl, res, g): + y, wts, src, pos, valid, order = res + T, K = wts.shape + w_row = jnp.take(wts.reshape(-1), order, axis=0).astype(jnp.float32) + g_row = jnp.take(g, src, axis=0) + dy = _masked(valid, g_row.astype(jnp.float32) * w_row[:, None], 0).astype(y.dtype) + if impl == "triton": + dw = _to_pairs(jnp.einsum("rd,rd->r", y, g_row, preferred_element_type=jnp.float32), pos, order, T, K) + else: + yk = _take_rows(y, pos).reshape(T, K, y.shape[-1]).astype(jnp.float32) + dw = jnp.einsum("tkd,td->tk", yk, g.astype(jnp.float32)) + return dy, dw.astype(wts.dtype), None, None, None, None + + +_combine_rows.defvjp(_combine_rows_fwd, _combine_rows_bwd) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(4, 5)) +def _sum_rows(y, src, pos, valid, K, impl="xla"): + """Each token's output from the buffer, unweighted: sum over its choices k of + y[pos[t, k]] in fp32 (a choice with no row here adds nothing), rounded once + to y's dtype -- the combine under route_weights 'experts', whose rows carry + their weights already (`impl`: StageConfig.combine_impl). _dispatch_rows' + transpose: a row's gradient is its token's (src, gathered; zero past the + groups), so the backward reads no row of `y` and the VJP keeps none.""" + return _token_sum(y, pos, None, pos.shape[0] // K, K, y.dtype, impl) + + +def _sum_rows_fwd(y, src, pos, valid, K, impl="xla"): + return _sum_rows(y, src, pos, valid, K, impl), (src, valid) + + +def _sum_rows_bwd(K, impl, res, g): + src, valid = res + return _gather_rows(g, src, valid), None, None, None + + +_sum_rows.defvjp(_sum_rows_fwd, _sum_rows_bwd) + + +@jax.custom_vjp +def _row_weights(wts, pos, order): + """Each buffer row's routing weight, wts[t, k] of its (token, choice) pair + order[r] (wts [T, K] fp32): what route_weights 'experts' scales the rows of + the gated activation by. Backward: a weight's gradient is its row's, + placed by `_to_pairs` -- zero for a pair with no row inside the groups -- + rather than autodiff's scatter-add, which would add the rows past the + groups' (other pairs' weights, or garbage in an unmasked buffer) into their + pairs.""" + return jnp.take(wts.reshape(-1), order, axis=0) + + +def _row_weights_fwd(wts, pos, order): + return _row_weights(wts, pos, order), (pos, order, wts.shape[0], wts.shape[1]) + + +def _row_weights_bwd(res, g): + pos, order, T, K = res + return _to_pairs(g, pos, order, T, K), None, None + + +_row_weights.defvjp(_row_weights_fwd, _row_weights_bwd) + + +def _tokamax(): + try: + import tokamax + except ImportError as e: + raise ImportError( + "gmm_impl='tokamax' needs tokamax (pip install tokamax; on GPU also jax-triton and " + "triton for its Triton kernels)" + ) from e + return tokamax + + +def _tokamax_impls(impl): + """(forward / dlhs backends, dW backends) for tokamax.ragged_dot_general: + Mosaic GPU has no dW kernel on sm80 / sm100, so dW runs on Triton there.""" + if impl == "xla": + return ("xla",), ("xla",) + if impl in ("mosaic", "tokamax_mosaic"): + return ("mosaic", "triton"), ("triton",) + return ("triton",), ("triton",) + + +def _own_mosaic(impl, lhs, rhs): + """Do this product's forward and dlhs run on gpu_kernels.grouped_matmul: tokamax_gmm 'mosaic' where it takes + them (an sm100 GPU, bf16 both sides, weight dims multiples of 64) -- else on tokamax's backends (_tokamax_impls).""" + if impl != "mosaic": + return False + from maxtext.experimental.mpmd.jax import gpu_kernels + + return gpu_kernels.grouped_matmul_supported(lhs, rhs) + + +def _ragged_dw(impl, lhs, g, gs, start): + """start + lhs^T @ g per group, accumulated in place in start's dtype (gpu_kernels.ragged_dw, one rounding), on + the kernel tokamax_gmm `impl` picks: ragged_dw's tcgen05 one under 'mosaic' only, as grouped_matmul (_own_mosaic; + on sm100 where it takes the shapes, an fp32 start too), its Triton one under 'tokamax_mosaic' and 'triton', lax's + form under 'xla'. Every dW with a starting value runs here: _tokamax_gmm_bwd's (dw0, the handed-on copy's) and + _dw32_backward's (an accumulator of its own dtype).""" + from maxtext.experimental.mpmd.jax import gpu_kernels + + return gpu_kernels.ragged_dw(lhs, g, gs, start, mosaic=None if impl == "mosaic" else False, xla=impl == "xla") + + +def _tokamax_dot(lhs, rhs, gs, dims, out_dtype, impls): + tk = _tokamax() + return tk.ragged_dot_general( + lhs, rhs, gs, ragged_dot_dimension_numbers=dims, preferred_element_type=out_dtype, implementation=impls + ) + + +_DEFAULT_DIMS = lax.RaggedDotDimensionNumbers( + dot_dimension_numbers=(((1,), (1,)), ((), ())), lhs_ragged_dimensions=[0], rhs_group_dimensions=[0] +) +_CONTRACTING_DIMS = lax.RaggedDotDimensionNumbers( + dot_dimension_numbers=(((0,), (0,)), ((), ())), lhs_ragged_dimensions=[0], rhs_group_dimensions=[] +) + + +def tokamax_gmm(name, impl, lhs, rhs, gs, valid, acc=False, stacked=None, dw0=None, keep=None): + """`lhs[r] @ rhs[g]` for each row r of local group g of a compact buffer + (`_local_plan`: rows sorted by group from row 0, `gs` the local groups' + sizes, rows past them `valid` False, which come out zero), on tokamax's + kernels (`impl`: StageConfig.tokamax_gmm), bf16 out of fp32 accumulation + like megablox. Named for xprof as named_gmm's (`tokamax/name`, `_dx`, `_dw`). + + acc=True -> (out, rhs), named_gmm's: the handed-on copy's weight gradient is + added to this call's dW, in fp32, before the rounding. stacked=(w, l): the + forward reads block l of the chunk's stacked weight w in place (the group + sizes padded with the other blocks' empty groups, named_gmm's trick), where + a slice would be a copy the kernel's custom call needs; dlhs reads a + transposed copy of the block either way (tokamax transposes rhs for it). + + dw0 (rhs's shape and dtype): the dW kernel's starting value -- the step + accumulator's block for this weight (`_DW0`) -- so rhs's cotangent is dw0 + + this call's dW, accumulated in place (gpu_kernels.ragged_dw), as is a + handed-on copy's (acc), which starts from that copy's cotangent. + + keep (a Recompute of `lhs`): named_gmm's -- what the VJP keeps of the lhs + for the dW kernel, recomputed in the backward.""" + if dw0 is not None and dw0.shape != rhs.shape: + raise ValueError(f"tokamax_gmm dw0: a {dw0.dtype}{list(dw0.shape)} start for a {rhs.dtype}{list(rhs.shape)} rhs") + if dw0 is not None and dw0.dtype != rhs.dtype: + # An accumulator in a dtype of its own (an fp32 one): a cotangent takes its primal's dtype, so the accumulated + # value leaves as dw0's cotangent instead -- dw0 is then a primal of the caller's VJP (ChunkPrograms' saved + # residuals, bwd_core_recompute) and rhs's cotangent is zero. acc=True hands dw0 itself on, (out, dw0), in + # place of the weight copy: the half that takes it (batch split's mb1) starts its dW from it, and this call's + # dW kernel then starts from that half's accumulated value -- one chain, in place, no add pass. + if stacked is not None: + raise ValueError("tokamax_gmm: an accumulator start of its own dtype takes no stacked reads") + return (_tokamax_gmm_dw32_pass if acc else _tokamax_gmm_dw32)(name, impl, None, lhs, rhs, gs, valid, dw0, keep) + ws, layer = (None, None) if stacked is None else stacked + if ws is not None and (tuple(ws.shape[1:]) != tuple(rhs.shape) or ws.dtype != rhs.dtype): + raise ValueError( + f"tokamax_gmm stacked: block {layer} of a {ws.dtype}{list(ws.shape)} weight is not the " + f"{rhs.dtype}{list(rhs.shape)} rhs" + ) + return (_tokamax_gmm_acc if acc else _tokamax_gmm)(name, impl, layer, lhs, rhs, gs, valid, ws, dw0, keep) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2)) +def _tokamax_gmm(name, impl, layer, lhs, rhs, gs, valid, ws, dw0, keep): + return _tokamax_gmm_fwd(name, impl, layer, lhs, rhs, gs, valid, ws, dw0, keep)[0] + + +def _tokamax_gmm_fwd(name, impl, layer, lhs, rhs, gs, valid, ws, dw0, keep): + fwd, _ = _tokamax_impls(impl) + rk, gk, _ = _gmm_operands(rhs, gs, jnp.int32(0), ws, layer) + with _kernel_scope(name, "tokamax"): + if _own_mosaic(impl, lhs, rk): + from maxtext.experimental.mpmd.jax import gpu_kernels + # tiles for this block's groups, not the stacked view's (whose other blocks' groups are empty) + cfg = gpu_kernels.mosaic_config(**gpu_kernels.mosaic_tiles(lhs.shape[0], rhs.shape[0])) + out = gpu_kernels.grouped_matmul(lhs, rk, gk, out_dtype=lhs.dtype, config=cfg) + else: + out = _tokamax_dot(lhs, rk, gk, _DEFAULT_DIMS, lhs.dtype, fwd) + # rows past the groups are left unwritten by the kernels: select them away + # before anything multiplies them (garbage x 0 can be NaN) + out = _masked(valid, out, 0).astype(lhs.dtype) + return out, (lhs if keep is None else keep, rhs if ws is None else None, gs, valid, ws, dw0) + + +def _tokamax_gmm_bwd(name, impl, layer, res, g, dw_in=None): + """dlhs = g @ rhs^T per group, dW = lhs^T @ g per group (ragged + contraction). With a starting value -- dw0 (the step accumulator's block), + dw_in (acc: the handed-on copy's cotangent), or both, added first in fp32 -- + the dW kernel adds into it in place (_ragged_dw: gpu_kernels.ragged_dw on + the kernel `impl` picks, one rounding); without, tokamax's dW kernel writes + it fresh, in the weight's dtype.""" + fwd, dw_impls = _tokamax_impls(impl) + lhs, rhs, gs, valid, ws, dw0 = res + lhs = _kept(lhs) + shape, dtype = _rhs_type(rhs, ws) + rk = rhs if ws is None else ws[layer] + g = _masked(valid, g, 0).astype(lhs.dtype) + with _kernel_scope(name + "_dx", "tokamax"): + if _own_mosaic(impl, g, rk): # the weight as it lies, contracted on its last dim: no transposed copy + from maxtext.experimental.mpmd.jax import gpu_kernels + + dx = gpu_kernels.grouped_matmul(g, rk, gs, transpose_rhs=True, out_dtype=lhs.dtype) + else: + dx = _tokamax_dot(g, rk.swapaxes(1, 2), gs, _DEFAULT_DIMS, lhs.dtype, fwd) + start = ( + dw_in + if dw0 is None + else dw0 + if dw_in is None + else (dw0.astype(jnp.float32) + dw_in.astype(jnp.float32)).astype(dtype) + ) + with _kernel_scope(name + "_dw", "tokamax"): + if start is None: + dw = _tokamax_dot(lhs, g, gs, _CONTRACTING_DIMS, dtype, dw_impls) + else: + dw = _ragged_dw(impl, lhs, g, gs, start.astype(dtype)) + return _masked(valid, dx, 0).astype(lhs.dtype), dw.astype(dtype), None, None, None, None, None + + +_tokamax_gmm.defvjp(_tokamax_gmm_fwd, _tokamax_gmm_bwd) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2)) +def _tokamax_gmm_acc(name, impl, layer, lhs, rhs, gs, valid, ws, dw0, keep): + return _tokamax_gmm_fwd(name, impl, layer, lhs, rhs, gs, valid, ws, dw0, keep)[0], rhs + + +def _tokamax_gmm_acc_fwd(name, impl, layer, lhs, rhs, gs, valid, ws, dw0, keep): + out, res = _tokamax_gmm_fwd(name, impl, layer, lhs, rhs, gs, valid, ws, dw0, keep) + return (out, rhs), res + + +def _tokamax_gmm_acc_bwd(name, impl, layer, res, cts): + g, dw_in = cts + return _tokamax_gmm_bwd(name, impl, layer, res, g, dw_in) + + +_tokamax_gmm_acc.defvjp(_tokamax_gmm_acc_fwd, _tokamax_gmm_acc_bwd) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2)) +def _tokamax_gmm_dw32(name, impl, layer, lhs, rhs, gs, valid, acc, keep): + """tokamax_gmm with the weight gradient accumulated in place into `acc` (its own dtype, e.g. fp32 -- Megatron's + gradient-accumulation fusion into main_grad), which leaves as acc's cotangent; rhs's is zero.""" + return _tokamax_gmm_fwd(name, impl, layer, lhs, rhs, gs, valid, None, None, keep)[0] + + +def _tokamax_gmm_dw32_fwd(name, impl, layer, lhs, rhs, gs, valid, acc, keep): + out, res = _tokamax_gmm_fwd(name, impl, layer, lhs, rhs, gs, valid, None, None, keep) + return out, (res, acc) + + +def _dw32_backward(name, impl, res, g, start): + """dlhs, and `start` + this call's dW accumulated in place in start's dtype (_ragged_dw: gpu_kernels.ragged_dw on + the kernel `impl` picks) -> (dx, rhs's zero cotangent, the accumulated value).""" + lhs, rhs, gs, valid, _, _ = res + lhs = _kept(lhs) + fwd, _ = _tokamax_impls(impl) + g = _masked(valid, g, 0).astype(lhs.dtype) + with _kernel_scope(name + "_dx", "tokamax"): + if _own_mosaic(impl, g, rhs): + from maxtext.experimental.mpmd.jax import gpu_kernels + + dx = gpu_kernels.grouped_matmul(g, rhs, gs, transpose_rhs=True, out_dtype=lhs.dtype) + else: + dx = _tokamax_dot(g, rhs.swapaxes(1, 2), gs, _DEFAULT_DIMS, lhs.dtype, fwd) + with _kernel_scope(name + "_dw", "tokamax"): + new_acc = _ragged_dw(impl, lhs, g, gs, start) + return _masked(valid, dx, 0).astype(lhs.dtype), jnp.zeros_like(rhs), new_acc + + +def _tokamax_gmm_dw32_bwd(name, impl, layer, res_acc, g): + res, acc = res_acc + dx, drhs, new_acc = _dw32_backward(name, impl, res, g, acc) + return dx, drhs, None, None, new_acc, None + + +_tokamax_gmm_dw32.defvjp(_tokamax_gmm_dw32_fwd, _tokamax_gmm_dw32_bwd) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(0, 1, 2)) +def _tokamax_gmm_dw32_pass(name, impl, layer, lhs, rhs, gs, valid, acc, keep): + """_tokamax_gmm_dw32 that hands its accumulator start on -> (out, acc): the start's cotangent comes back + holding the receiving call's accumulated value, which this call's dW kernel continues (tokamax_gmm's acc=True + with an own-dtype dw0).""" + return _tokamax_gmm_fwd(name, impl, layer, lhs, rhs, gs, valid, None, None, keep)[0], acc + + +def _tokamax_gmm_dw32_pass_fwd(name, impl, layer, lhs, rhs, gs, valid, acc, keep): + out, res = _tokamax_gmm_fwd(name, impl, layer, lhs, rhs, gs, valid, None, None, keep) + return (out, acc), res + + +def _tokamax_gmm_dw32_pass_bwd(name, impl, layer, res, cts): + g, acc_ct = cts # acc_ct: the receiver's start + its dW + dx, drhs, new_acc = _dw32_backward(name, impl, res, g, acc_ct) + return dx, drhs, None, None, new_acc, None + + +_tokamax_gmm_dw32_pass.defvjp(_tokamax_gmm_dw32_pass_fwd, _tokamax_gmm_dw32_pass_bwd) + + +def _expert_act(h0, h1, w_row, act, dtype): + """The routed experts' gated activation act(h0) * h1 in `dtype` (layers.gated_product's), each row then scaled by + its routing weight `w_row [rows]` (fp32) and rounded again under route_weights 'experts'; w_row None: unscaled.""" + a = (layers.activation_fn(act)(h0) * h1).astype(dtype) + return a if w_row is None else (a.astype(jnp.float32) * w_row[:, None]).astype(dtype) + + +def _wo_lhs(h0, h1, w_row, act, dtype, recompute=True): + """wo's lhs, the gated activation (`_expert_act`), and what its grouped matmul's VJP keeps of it (`keep`). Under + lean residuals the activation runs under jax.checkpoint and the matmul keeps a Recompute of it, so neither VJP + keeps more than h0, h1 and w_row (the [rows, moe_mlp] product is recomputed in the backward, elementwise) -- or, + with `recompute` False (StageConfig.lean_experts), keeps the product itself beside them; else the plain product, + kept as it is.""" + f = functools.partial(_expert_act, act=act, dtype=dtype) + if not layers.lean(): + return f(h0, h1, w_row), None + return jax.checkpoint(f)(h0, h1, w_row), (Recompute(f, (h0, h1, w_row)) if recompute else None) + + +def _tokamax_experts(w, xf, idx, wts, shard, scfg: StageConfig, pass_weights=False, stacked=None, dw0=None): + """moe_experts' routed experts under gmm_impl 'tokamax': this shard's rows + of the gathered tokens `xf [T, D]` (routing `idx`, `wts` [T, K]) in a + compact buffer (`_local_plan`, ragged_buffer_rows of them; dropless by + default), the three grouped matmuls on tokamax, and the fp32 sum of each + token's rows back to [T, D], weighted by `wts` in the combine or, under + route_weights 'experts', in wo's input rows (`_row_weights`) -> (y, the + handed-on weights under pass_weights, else {}). `dw0`: {expert leaf: the + step accumulator's block}, the dW kernels' starting values (tokamax_gmm's + dw0; `_DW0`). + + Under lean residuals the wi products keep the gathered tokens (and the + plan) instead of the buffer's rows wherever these outnumber them, and gather + the rows again in the backward (`Recompute`).""" + cfg = scfg.model + E, K = cfg.num_experts, cfg.num_experts_per_tok + dt = cfg.dtype + T = xf.shape[0] + n_local = E // scfg.ep + rows = ragged_buffer_rows(scfg, T) + src, gs, valid, pos, order = _local_plan(idx, shard, n_local, rows) + if (n_local == E and rows is None) or not scfg.buffer_masks: + # EP 1, dropless: every (token, choice) pair is this shard's and has a row -- the buffer is exactly full, the + # kernels write every row, and the masks below are the identity (one pass each spared); or masks off + # (StageConfig.buffer_masks): nothing reads the rows past the groups + valid = None + xs = _dispatch_rows(xf, src, pos, valid, K, scfg.combine_impl) + passed = {} + + def mm(name, lhs, wname, keep=None): + st = (stacked[0][wname], stacked[1]) if stacked is not None and stacked[0][wname].dtype == dt else None + out = tokamax_gmm( + name, + scfg.tokamax_gmm, + lhs, + w[wname].astype(dt), + gs, + valid, + acc=pass_weights, + stacked=st, + dw0=None if dw0 is None else dw0[wname], + keep=keep, + ) + if pass_weights: + out, passed[wname] = out + return out + + keep_xs = Recompute(_gather_rows, (xf, src, valid)) if layers.lean() and scfg.lean_experts and xs.shape[0] > T else None + xs = _tie("xs", xs) # prefetch pins (an identity unless a pinned forward traces) + h0 = checkpoint_name(mm("gmm_wi_0", xs, "wi_0", keep_xs), "moe_h0") + h1 = checkpoint_name(mm("gmm_wi_1", xs, "wi_1", keep_xs), "moe_h1") + w_row = _row_weights(wts.astype(jnp.float32), pos, order) if scfg.route_weights == "experts" else None + act, keep_act = _wo_lhs(h0, h1, w_row, cfg.mlp_activations[0], dt, scfg.lean_experts) + y = checkpoint_name(mm("gmm_wo", act, "wo", keep_act), "moe_y") + y = _tie("y", y) + if w_row is not None: + return _sum_rows(y, src, pos, valid, K, scfg.combine_impl), passed + return _combine_rows(y, wts, src, pos, valid, order, dt, scfg.combine_impl), passed + + +def sparsecore_offload_available(mesh, axes=None) -> bool: + """Does libtpu offload (and so run async) an all-gather over `axes` (a mesh + axis name or a tuple of them; None = all of them) on this sub-mesh? + + It offloads only when the program's chips are the whole slice or a solid + rectangle whose minimum corner is not chip (0,0,0), in any device order: + libtpu (0.0.46 and 0.0.48) compiles a program for a smaller subslice + topology only for such a rectangle (TpuTopologyDescription:: + ComputeSubsliceForAssignment), and its SparseCore offload pass skips any + program with fewer devices than its compile topology ("Skipping offloading + collectives to SparseCore because the device assignment does not use all + devices"). So a sub-mesh holding chip (0,0) -- stage 0 of + ds_ep_pipeline's 'physical' layout on a v6e-256, any stage on chip (0,0) of + a tpu7x-8 -- and any non-rectangular set run these collectives + synchronously on the TensorCore; no flag changes it + (ds_ep_pipeline.sync_collective_stages, layout 'physical_origin_last'). + Probe the axes the collective in question runs over: size-1 axes are + dropped (a gather over them is a no-op, never offloaded), and with none left + the answer is False. The mesh's own devices decide, not the host's backend: + a compile-only TPU topology's (AOT) answer is the same from any host. + """ + if mesh.devices.flat[0].platform != "tpu": + return False + axes = mesh.axis_names if axes is None else (axes,) if isinstance(axes, str) else tuple(axes) + axes = tuple(a for a in axes if mesh.shape[a] > 1) + if not axes: + return False + ax = axes[0] if len(axes) == 1 else axes + sm = jax.shard_map( + lambda a: lax.all_gather(a, ax, axis=0, tiled=True), mesh=mesh, in_specs=P(ax), out_specs=P(), check_vma=False + ) + n = math.prod(mesh.shape[a] for a in axes) + a = jax.ShapeDtypeStruct((n * 1024, 1024), jnp.bfloat16, sharding=NamedSharding(mesh, P(ax))) + return 'async_execution_thread="sparsecore"' in jax.jit(sm).lower(a).compile().as_text() + + +def _shared_mlp(params, inputs, cfg: DeepSeekConfig, name="shared"): + """`deepseek/layers.py:mlp_block`, verbatim, plus the inert names + `_h0` / `_h1` on its input projections (STASH_POLICIES). A + copy, so the independent port the parity tests check against stays as is. + A dense layer's MLP is the same block (name 'mlp').""" + hs = [ + checkpoint_name(layers.dense_general(params[f"wi_{idx}"], inputs, cfg), f"{name}_h{idx}") + for idx in range(len(cfg.mlp_activations)) + ] + if layers.lean() and tuple(cfg.mlp_activations[1:]) == ("linear",): + activated = layers.gated_product(hs[0], hs[1], cfg.mlp_activations[0], cfg.dtype) + else: + activated = None + for y, act in zip(hs, cfg.mlp_activations): + y = layers.activation_fn(act)(y) + activated = y if activated is None else activated * y + activated = jnp.asarray(activated, cfg.dtype) + return layers.dense_general(params["wo"], activated, cfg) + + +def cp_chunk(scfg: StageConfig): + """Which chunk of its sequence this device's row is under context + parallelism (0 without): its index on the 'expert' axis mod cp.""" + return lax.axis_index(EP_AXIS) % scfg.cp if scfg.cp > 1 else 0 + + +def cp_kv_context(scfg: StageConfig): + """attention.mla's kv_context under context parallelism: this row is chunk + r of its sequence (`cp_chunk`); the sequence's other cp - 1 chunks sit on + the neighbouring devices of its 'expert' ring. Slots [chunk r+1, ..., + chunk r+cp-1 (mod cp), own chunk r] of kv latents and roped keys: one + static causal mask with offset (cp - 1) x s then holds for every device -- + the own chunk causal, every other slot wholly visible -- and the keys' + segment ids take out the slots of the chunks after r (slot j's chunk + precedes r iff r + j >= cp). Only the chunks before r come in, latent and + roped key as one payload (a collective-permute a slot, half of its pairs; + autodiff sends their gradients back the same way); a slot taken out holds + zeros. Against the queries' segment ids (packed sequences) each slot's + keys carry their chunk's own, permuted along, and -1 where it is taken out; + without, the queries are one segment, 1 (attention.attention_op), and a + slot's keys 1 or 0.""" + cp, ep = scfg.cp, scfg.ep + + def ctx(main, krope, seg=None): + b, s, lora = main.shape + r = cp_chunk(scfg) + both = jnp.concatenate([main, krope.reshape(b, s, -1).astype(main.dtype)], axis=-1) + slots, segs = [], [] + for j in range(1, cp): + # chunk (q + j) % cp of each sequence -> the device holding its chunk q, where it comes first (q + j >= cp) + perm = [(g * cp + (q + j) % cp, g * cp + q) for g in range(ep // cp) for q in range(cp) if q + j >= cp] + slots.append(lax.ppermute(both, EP_AXIS, perm)) + seen = r + j >= cp + segs.append( + jnp.broadcast_to(seen.astype(jnp.int32), (b, s)) + if seg is None + else jnp.where(seen, lax.ppermute(seg, EP_AXIS, perm), -1) + ) + slots.append(both) + segs.append(jnp.ones((b, s), jnp.int32) if seg is None else seg) + kv = jnp.concatenate(slots, axis=1) + return ( + kv[..., :lora], + kv[..., lora:].reshape(b, cp * s, *krope.shape[2:]).astype(krope.dtype), + jnp.concatenate(segs, axis=1), + (cp - 1) * s, + ) + + return ctx + + +def layer_fwd_counts(w, x, key, scfg: StageConfig, stacked=None, aux_seqs=0): + """One DeepSeek MoE decoder layer (`deepseek.DeepSeekMoELayer.__call__`) -- or a + Qwen3.5-family one, its mixer in attention's place (`qwen_mixer_part`) -- + local -> (output, its router's expert counts [E] over the EP group's + tokens). + + Under context parallelism (scfg.cp > 1) `x` is one row of seq / cp tokens, + chunk `cp_chunk` of its sequence: its positions start at that chunk's, and + attention reaches the sequence's other chunks (`cp_kv_context`). + `stacked`: moe_experts'; `aux_seqs`: its aux loss rides the output + (`_ring_moe`). + + Under lean residuals (a saved-residual forward) a DeepSeek layer computes + the router's scores and the shared expert with its post-attention norm + (attention_part's `read`), the projections that read hn: the VJP keeps h, + not hn as their lhs.""" + wr = routed_tree(w, scfg) + if layers.lean() and not is_qwen(scfg.model): + h, hn, (scores, shared) = attention_part( + w, x, scfg, read=lambda hn: (moe_scores(wr, hn, scfg), shared_part(w, hn, scfg)) + ) + routed, counts = _ring_moe(wr, hn, key, scfg, stacked, aux_seqs, scores=scores) + return (routed + shared) + h, counts + h, hn = attention_part(w, x, scfg) + routed, counts = _ring_moe(wr, hn, key, scfg, stacked, aux_seqs) + return (routed + shared_part(w, hn, scfg)) + h, counts + + +def layer_fwd(w, x, key, scfg: StageConfig, stacked=None, aux_seqs=0): + """One MoE decoder layer, local (`layer_fwd_counts` without the counts).""" + return layer_fwd_counts(w, x, key, scfg, stacked, aux_seqs)[0] + + +def routed_tree(w, scfg: StageConfig): + """A MoE layer's router and routed experts, {'gate', 'wi_0', 'wi_1', 'wo'} + -- what moe_scores and moe_experts read: DeepSeek's 'moe' subtree, a + Qwen3.5-family layer's 'mlp' / 'routed_experts'.""" + return w["mlp"]["routed_experts"] if is_qwen(scfg.model) else w["moe"] + + +def shared_part(w, hn, scfg: StageConfig): + """A MoE layer's shared expert on the experts' input `hn`: DeepSeek's + (`_shared_mlp`), or a Qwen3.5-family layer's behind its sigmoid gate + (qwen35/moe.py:sparse_moe_block).""" + cfg = scfg.model + if not is_qwen(cfg): + return _shared_mlp(w["moe"]["shared_experts"], hn, cfg) + moe = w["mlp"] + gate = layers.dense_general(moe["shared_expert_gate"], hn, cfg) + return jax.nn.sigmoid(gate) * _shared_mlp(moe["shared_expert"], hn, cfg) + + +def dense_layer_fwd(w, x, scfg: StageConfig): + """One dense decoder layer (DeepSeek-V3's first ones, deepseek.py's dense + branch): attention_part, then a dense MLP of width mlp_dim (`_shared_mlp`, + MaxText's MlpBlock) in place of the experts. It has no EP collective, so a + batch-split chunk runs it on the whole microbatch, and its post-attention + point ties no prefetch pin (pins count MoE layers). Under lean residuals + the MLP runs with the post-attention norm (attention_part's `read`).""" + mlp = lambda hn: _shared_mlp(w["mlp"], hn, scfg.model, name="mlp") + with _untied(): + if layers.lean() and not is_qwen(scfg.model): + h, _, out = attention_part(w, x, scfg, read=mlp) + return out + h + h, hn = attention_part(w, x, scfg) + return mlp(hn) + h + + +def attention_part(w, x, scfg: StageConfig, read=None): + """layer_fwd up to the experts -> (h, hn): the residual stream after + attention, and its post-attention norm, the experts' input -- a + Qwen3.5-family layer's mixer instead (`qwen_mixer_part`). + + `read(hn)` (DeepSeek, under lean residuals): what else the layer computes + from hn than the dispatch, i.e. the projections that read it and what + follows them elementwise -> (h, hn, read(hn)), the norm and `read` in one + checkpoint (layers.rms_norm_read), so that the VJP keeps h and recomputes + hn for the projections' weight gradients. hn's other reader, the + dispatch's all-gather, needs nothing of it in the backward. The prefetch + pins' tie (`_tie`) then holds hn for the dispatch alone: it must stay out of + the checkpoint, whose backward would recompute it, pinned weights and all.""" + if is_qwen(scfg.model): + return qwen_mixer_part(w, x, scfg) + cfg = scfg.model + b, S, _ = x.shape + positions = jnp.broadcast_to(cp_chunk(scfg) * S + jnp.arange(S, dtype=jnp.int32), (b, S)) + # Synthetic data: no packing, all ones -- under context parallelism none, + # attention_op's then (cp_kv_context would permute these with the latents). + segment_ids = None if scfg.cp > 1 else jnp.ones((b, S), jnp.int32) + freqs = rope.freqs_cis_for(cfg, S * scfg.cp) + attn = attention.mla( + w["self_attention"], + x, + positions, + segment_ids, + freqs, + cfg, + kv_context=cp_kv_context(scfg) if scfg.cp > 1 else None, + norm=w["pre_self_attention_layer_norm"], + ) + h = x + attn + if read is not None: + hn, got = layers.rms_norm_read(w["post_self_attention_layer_norm"], h, cfg, lambda hn: (hn, read(hn))) + return h, _tie("hn", hn), got + hn = layers.rms_norm(w["post_self_attention_layer_norm"], h, cfg) + hn = _tie("hn", hn) # prefetch pins (an identity unless a pinned forward traces) + return h, hn + + +def _sharded_embed(table, ids, scfg: StageConfig): + """`embed` of this device's token ids `ids` [b, S] from the table's own column block (storage P(None, FE): [V, + emb / devices]): every device looks up every device's tokens in its columns, and an all-to-all hands each device + its rows' columns. The same values as the gathered table's lookup, without the table's full-size copy and + gradient on every device.""" + cfg = scfg.model + t = table.astype(cfg.dtype) + every = lax.all_gather(ids, FE, axis=0, tiled=True) + cols = jnp.dot(jax.nn.one_hot(every, cfg.vocab_size, dtype=cfg.dtype), t) if scfg.iota_embed else t.at[every].get() + return lax.all_to_all(cols, FE, 0, 2, tiled=True) + + +def mtp_loss(w, y, tokens, targets, denom, key, scfg: StageConfig, aux_seqs=0): + """The multi-token-prediction loss of one microbatch (MultiTokenPredictionBlock + at mtp_num_layers=1, mtp_reuse_input_embedding) and the MTP layer's expert + counts: position t combines the main decoder's last hidden state `y` (before + the decoder norm) with the embedding of token t + 1, runs the MTP layer and + predicts token t + 2 through the shared head; the last position, which has + no such token, is masked. -> (mtp_loss_scaling_factor x the masked cross + entropy summed / `denom`, counts). `w` is the last chunk's weights (its + 'mtp' subtree and the head); tokens / targets [b, S]; `aux_seqs`: the MTP + layer's aux loss rides its output, as the decoder's do.""" + cfg = scfg.model + m = w["mtp"] + b, S = tokens.shape + shift = lambda a: jnp.concatenate([a[:, 1:], jnp.zeros((b, 1), a.dtype)], axis=1) # roll_and_mask + e = _sharded_embed(m["token_embedder"]["embedding"], shift(tokens), scfg) + hin = jnp.concatenate( + [layers.rms_norm(m["embedding_norm"], e, cfg), layers.rms_norm(m["hidden_state_norm"], y, cfg)], axis=-1 + ) + h, counts = layer_fwd_counts(m["layer"], layers.dense_general(m["projection"], hin, cfg), key, scfg, aux_seqs=aux_seqs) + logits = layers.dense_general(w["logits_dense"], layers.rms_norm(m["final_norm"], h, cfg), cfg) + logits = logits.astype(jnp.float32) + lse = jax.nn.logsumexp(logits, axis=-1) + tl = jnp.take_along_axis(logits, shift(targets)[..., None], axis=-1)[..., 0] + valid = (jnp.arange(S) < S - 1).astype(jnp.float32) + return cfg.mtp_loss_scaling_factor * jnp.sum((lse - tl) * valid) / denom, counts + + +def split_layers(ws, xa, xb, keys, scfg: StageConfig, stacked=None): + """The layers `ws` (one weight tree each) over the two halves of a + microbatch's rows, mb0 `xa` and mb1 `xb`, in Lineage's batch-split phase + order, mb0 one attention block ahead: + + prologue A0(0) + layer l P1: dispatch(mb0) || A1(l) P2: experts(mb0) || dispatch(mb1) + P3: combine(mb0) || experts(mb1) P4: A0(l+1) || combine(mb1) + + A is attention_part and the router's scores -- a Qwen3.5-family layer's + mixer, Gated DeltaNet or gated attention, in attention's place + (qwen_mixer_part); dispatch and combine are the ring of experts' all-gather + and reduce-scatter over 'expert'; experts are the routed experts + (moe_experts) and the shared one (shared_part: a Qwen layer's behind its + sigmoid gate). An optimization + barrier closes every phase, so one half's collective has the other half's + compute to run behind. The last layer's P4 has no attention of mb0 left: + its combine of mb1 runs alone. Each half's EP collectives carry its name + (ep_all_gather/mb0, ...). Prefetch pins tie mb0's points, which lead; mb1 + traces untied, so `_pinned` counts each point once a layer. `keys[l]`: + layer l's routing keys, one a half. Under split_dw 'acc' mb0's experts + hand their weights on to mb1's (moe_experts pass_weights) outside the + barriers, so in the backward mb0's dW kernels add into mb1's dW, and no + barrier holds that dW. `stacked`: the stacked expert weights `ws` were + taken from, layer l at index l (moe_experts'). -> (ya, yb).""" + bar = lax.optimization_barrier + half = lambda i: contextlib.nullcontext() if i == 0 else _untied() + acc = scfg.split_dw == "acc" + + def attn(i, w, x): + with half(i): + h, hn = attention_part(w, x, scfg) + return h, hn, moe_scores(routed_tree(w, scfg), hn, scfg) + + def dispatch(i, hn, scores): + return moe_dispatch(hn, scores, scfg, f"mb{i}") + + def experts(i, l, xg, sg, key, hn, passed=None): + """-> ((routed, shared), mb0's handed-on expert weights under 'acc', else + {}); mb1 runs on `passed` where given.""" + w = ws[l] + st = None if stacked is None else (stacked, l) + with half(i): + wr = routed_tree(w, scfg) + d0 = _dw0_for(l) + # an accumulator of its own dtype (fp32; bwd_core_recompute's acc_own): under 'acc' mb0 hands its start on + # in place of the weight copies (tokamax_gmm's dw32 pass-through) + own = d0 is not None and any(jnp.dtype(d0[k].dtype) != jnp.dtype(wr[k].dtype) for k in d0) + wm = {**wr, **passed} if passed and not own else wr + # mb1's experts run first in the layer's backward: their dW kernels start + # from the accumulator's blocks (_DW0), and under 'acc' mb0's from mb1's + if acc and i == 0: + routed, out = moe_experts(wm, xg, sg, key, scfg, pass_weights=True, stacked=st, dw0=d0 if own else None) + else: + start = passed if own and acc and passed else (d0 if i == 1 else None) + routed, out = moe_experts(wm, xg, sg, key, scfg, stacked=st, dw0=start), {} + return (routed, shared_part(w, hn, scfg)), out + + def combine(i, y): + return moe_combine(y, scfg, f"mb{i}") + + n = len(ws) + # No pipeline chunk comes here without a layer: ChunkPrograms runs a chunk with no MoE layer on the plain path + # (split = batch_split and n > 0). A direct call with none gets its two halves back. + if not n: + return xa, xb + ha, hna, sa = attn(0, ws[0], xa) + for l in range(n): + w, (ka, kb) = ws[l], keys[l] + (ga, gsa), (hb, hnb, sb) = bar((dispatch(0, hna, sa), attn(1, w, xb))) + ea_sha, passed = experts(0, l, ga, gsa, ka, hna) + (ea, sha), (gb, gsb) = bar((ea_sha, dispatch(1, hnb, sb))) + ca, (eb, shb) = bar((combine(0, ea), experts(1, l, gb, gsb, kb, hnb, passed)[0])) + xa = (ca + sha) + ha + if l + 1 < n: + (ha, hna, sa), cb = bar((attn(0, ws[l + 1], xa), combine(1, eb))) + else: + cb = bar(combine(1, eb)) + xb = (cb + shb) + hb + return xa, xb + + +def qwen_mixer_part(w, x, scfg: StageConfig): + """A Qwen3.5-family layer (`maxtext.experimental.mpmd.jax.qwen35.model.decoder_layer`, MaxText's + Qwen3_5DecoderLayer) up to the experts -> (h, hn), as attention_part: its + mixer -- Gated DeltaNet, or gated full attention when `w` holds 'attn' -- + after a zero-centred RMSNorm, with its residual, then the post-attention + zero-centred norm, the experts' input. No packing: positions are 0..S-1, + the attention's segment ids all one, and the GDN's none -- MaxText's GDN + under packing=false. Under its default packing MaxText runs its packed GDN + on the batch's all-one segment ids, the same math in other roundings: fp32's + in fp32 (maxtext_parity_test.AgainstMaxText.test_qwen_trains_as_maxtext_fp32), + bf16's in a bf16 compute dtype, where the packed rule's fp32 differences round + to other bf16 values and, with fp32 weights, the packed conv keeps the fp32 + kernel this one rounds to bf16. So the parity protocol runs MaxText's + trainer with packing=false (maxtext_parity's docstring).""" + cfg = scfg.model + b, S, _ = x.shape + hx = q_layers.rms_norm(w["input_layernorm"], x, cfg) + if "attn" in w: + positions = jnp.broadcast_to(jnp.arange(S, dtype=jnp.int32), (b, S)) + a = q_attention.gated_attention(w["attn"], hx, positions, jnp.ones((b, S), jnp.int32), cfg) + else: + a = q_gdn.gated_delta_net(w["gdn"], hx, None, cfg) + h = x + a + hn = q_layers.rms_norm(w["post_attention_layernorm"], h, cfg) + hn = _tie("hn", hn) # prefetch pins (an identity unless a pinned forward traces) + return h, hn + + +def embed(w, tokens, scfg: StageConfig): + cfg = scfg.model + table = w["token_embedder"]["embedding"].astype(cfg.dtype) + if scfg.iota_embed: # Embed.__call__ under use_iota_embed + return jnp.dot(jax.nn.one_hot(tokens, cfg.vocab_size, dtype=cfg.dtype), table) + return table.at[tokens].get() + + +class TableRows: + """A table's weight gradient as the rows it adds: `values` [n, ...] to the rows `ids` [n] of a table of `shape` (a + repeated id adds each of its rows) -- the gathered embedding's (`embed_grad`). Its dense form, autodiff's, + zero-fills the whole table to scatter n rows into it, and an accumulator then adds every row of that: at + DeepSeek-V3's vocabulary a [129280, 7168] table a device for a microbatch's 4096 rows. The accumulating programs + (`ChunkPrograms`' add_acc / new_acc) add the rows into the accumulator instead (`into`): into an fp32 one with a + scatter-add of the rows as they come, into a bf16 one with a scatter-add of each id's rows summed in fp32 first (a + sort of the n ids and a segment sum of the rows: nothing the table's size). On an A100 the scatter-add of the rows + as they come into a donated bf16 accumulator took 0.65 ms against the table's 5.4; the fp32 sums first are not + timed on a GPU. A leaf of the gradient tree, not a pytree: built and consumed in one trace, by the programs' own + accumulate.""" + + def __init__(self, ids, values, shape): + self.ids, self.values, self.shape = ids, values, tuple(shape) + + def into(self, acc): + """`acc` -- a table of `shape`, or an accumulator's block of one (leading axes of one) -- plus the rows, added in + its dtype (where `acc` is donated, in place). In fp32 (or wider) the rows scatter-add as they come, a repeated + id's one after the other. Below fp32 each id's rows are summed in fp32 and the sum added once: one add a row of + the table a microbatch, as autodiff's table was added. Added one by one, a bf16 sum rounds a row away once it is + ~256 times the row (bf16's 8 significand bits), and at grad_reduce 'step' the accumulator takes a frequent token's + rows from every microbatch of the step.""" + table = acc.reshape(self.shape) + if jnp.finfo(acc.dtype).bits >= 32: + return table.at[self.ids].add(self.values.astype(acc.dtype)).reshape(acc.shape) + # each distinct id once, ascending, with the fp32 sum of its rows; the slots past them hold ids past the table, V + # plus the slot (so no index repeats), whose zero sums the scatter drops + n, V = self.ids.shape[0], self.shape[0] + ids, inv = jnp.unique(self.ids, size=n, fill_value=V, return_inverse=True) + ids = jnp.where(ids == V, V + jnp.arange(n, dtype=ids.dtype), ids) + sums = jax.ops.segment_sum(self.values.astype(jnp.float32), inv.reshape(-1), num_segments=n) + return ( + table.at[ids] + .add(sums.astype(acc.dtype), mode="drop", indices_are_sorted=True, unique_indices=True) + .reshape(acc.shape) + ) + + def dense(self, dtype=None): + """A zero table of `dtype` (default the rows') with the rows added (`into`): in fp32 autodiff's table, by the same + scatter; below fp32 with a repeated id's rows summed in fp32 first, where autodiff's scatter adds them one by one + in `dtype`.""" + return self.into(jnp.zeros(self.shape, self.values.dtype if dtype is None else dtype)) + + +def embed_grad(w, tokens, dh, scfg: StageConfig): + """`embed`'s weight gradient for the cotangent `dh` of its output -> {'token_embedder': {'embedding': ...}}: the + one-hot product's VJP (iota_embed), or, for the gather, its rows as they come (`TableRows`), in the table's dtype + as the gather's VJP gives them. Into an fp32 accumulator the gather's sums are the VJP's where no token repeats on + a device: a repeated token's rows add into the accumulator one after the other, not summed first. Into one below + fp32 (bf16) a token's rows are summed in fp32 and added once a microbatch (`TableRows.into`).""" + if scfg.iota_embed: + _, vjp = jax.vjp(lambda we: embed(we, tokens, scfg), {"token_embedder": w["token_embedder"]}) + return vjp(dh)[0] + table = w["token_embedder"]["embedding"] + rows = TableRows(tokens.reshape(-1), dh.reshape(-1, dh.shape[-1]).astype(table.dtype), table.shape) + return {"token_embedder": {"embedding": rows}} + + +def head_loss(w, h, targets, denom, scfg: StageConfig): + cfg = scfg.model + # Qwen's final norm is zero-centred (qwen35/model.py:head), DeepSeek's plain + hn = (q_layers.rms_norm if is_qwen(cfg) else layers.rms_norm)(w["decoder_norm"], h, cfg) + logits = layers.dense_general(w["logits_dense"], hn, cfg).astype(jnp.float32) + lse = jax.nn.logsumexp(logits, axis=-1) + tl = jnp.take_along_axis(logits, targets[..., None], axis=-1)[..., 0] + return jnp.sum(lse - tl) / denom + + +def _require_resolved(scfg: StageConfig): + """Stage programs run concrete collectives: EP's 'auto' is only meaningful + to Pipeline, which resolves it per stage.""" + if scfg.fsdp_collectives not in ("ppermute", "xla") or scfg.ep_collectives not in ("xla", "ppermute"): + raise ValueError( + f"stage programs need fsdp_collectives and ep_collectives in (ppermute, xla), got " + f"{scfg.fsdp_collectives!r} / {scfg.ep_collectives!r}: resolve auto per stage " + "(ds_ep_pipeline.Pipeline does)" + ) + + +def _layer_key(layer, seed): + return jax.random.fold_in(jax.random.fold_in(jax.random.key(0), layer), seed) + + +def _take(tree, i): + return jax.tree.map(lambda a: a[i], tree) + + +def layer_weights(wl, l, kinds=()): + """Layer l's weights out of a chunk's 'layers' (or 'dense_layers') tree `wl`: + every leaf of its [n, ...] stacks at l (DeepSeek's stacked layers); for one + subtree a layer (non-empty `kinds`: `ChunkSpec.kinds` / `dense_kinds`, a + Qwen3.5-family chunk's or a DeepSeek one's under layer_tree 'per_layer') its + subtree `wl[qwen_layer_key(l)]` without the layer axis of one -- the common + leaves and its own mixer's.""" + if not kinds: + return _take(wl, l) + return _take(wl[qwen_layer_key(l)], 0) + + +def stack_layers(per_layer, kinds=()): + """`layer_weights`' inverse: one tree a layer (each layer's dW, say) back into + a chunk's 'layers' (or 'dense_layers') tree -- stacked on a leading axis, or, + with `kinds`, each under its key with a layer axis of one.""" + if not kinds: + return jax.tree.map(lambda *a: jnp.stack(a), *per_layer) + return {qwen_layer_key(l): jax.tree.map(lambda a: a[None], t) for l, t in enumerate(per_layer)} + + +def _named(f, name): + """Give a program a readable XLA module name (`jit_`) for the profiler.""" + + @functools.wraps(f) + def g(*a, **k): + return f(*a, **k) + + g.__name__ = g.__qualname__ = name + return g + + +# ------------------------------------------------------------ stash policies +# What a stash forward keeps of each layer for its backward; everything else +# is recomputed there from the layer input, as today's backward recomputes +# all of it. The names are the inert `checkpoint_name` tags: attention's in +# deepseek/attention.py:mla, the experts' in `_ring_moe` and `_shared_mlp`, +# and 'context', the name both splash kernels give their own residuals (the +# attention output and its logsumexp: attention.py passes it as +# residual_checkpoint_name), so no stash backward re-runs the splash forward +# (ds_ep_test.test_stash_recompute_set). attention_out, context transposed, +# is not kept: the backward redoes the transpose. (The dot_product and +# reference kernels name nothing; under them attention is recomputed from the +# kept q, k, v.) +# GiB per device per (layer, microbatch) at the v6e config (PP2 x FSDP1 x +# EP2, 16 experts, mbs 2, seq 4096; ds_ep_test.test_stash_bytes_v6e_dims), on +# top of the layer input (0.055) every mode keeps: attn 0.713 (q, k 192 MiB +# each, v 128, splash out 128 + logsumexp 2, out_proj 56, LoRA 32), attn_min +# 0.659, lite 1.354 (+ the expert up-projections' outputs h0, h1 256 MiB each, +# the gathered tokens 112, the shared expert's 16 each), lite_y 2.229 (+ +# gmm_wo's [T*K, D] output 896), all 4.973. Under all but 'all' whatever is +# not named is recomputed. +ATTN_NAMES = ( + "query_wa_proj", + "mla_q", + "kv_wa_proj", + "mla_kv", + "query_proj", + "key_proj", + "value_proj", + "context", + "out_proj", +) +MOE_NAMES = ("moe_xg", "moe_sg", "moe_h0", "moe_h1", "shared_h0", "shared_h1") +STASH_POLICIES = { + "none": (), # nothing: full remat (today) + "attn": ATTN_NAMES, + "attn_min": ATTN_NAMES[:-1], # not out_proj + "lite": ATTN_NAMES + MOE_NAMES, # re-runs gmm_wo of the experts + "lite_y": ATTN_NAMES + MOE_NAMES + ("moe_y",), # re-runs no expert matmul + "all": None, # no recompute (diagnostics) +} + + +def stash_policy(name): + """STASH_POLICIES[name] as a `jax.checkpoint` policy (None: save everything).""" + names = STASH_POLICIES[name] + return None if names is None else jax.checkpoint_policies.save_only_these_names(*names) + + +# ------------------------------------------------------- parts and composer +@dataclasses.dataclass(frozen=True) +class Part: + """One piece of a per-microbatch program: `body(*args)` returns a tuple of + outputs inside the stage's shard_map, with a spec and a sharding for each + argument and output, and the positions of the arguments it donates. A + gather part ('G') lists the leaves it returns as `gathers`, ((chunk, leaf + id), ...); a forward part with prefetch pins carries its program's pin plan + as `pins`, ((point, layer, chunk, leaf id), ...) (`compose`). A + `global_view` part's body runs at global view instead, in the program's jit + outside any shard_map (a Lineage chunk's F / B / A: ChunkPrograms), taking + and returning arrays of its specs' types. A forward part (`forward`) + returns its chunk's output y, then its residuals -- the saved set, under + saved residuals -- and in stash mode its stash; a backward part (`backward`) + donates the dy, saved set and stash it reads (`fwd_like`, among `donate`), + arrays of those outputs' shapes. Side by side, an F&B pair, `compose` lists + the backward's outputs first and keeps those donations off + (`composed_order`, `composed_donations`).""" + + name: str + body: object + in_specs: tuple + out_specs: tuple + in_sh: tuple + out_sh: tuple + donate: tuple = () + gathers: tuple = () + pins: tuple = () + global_view: bool = False + forward: bool = False + backward: bool = False + fwd_like: tuple = () + + +# ------------------------------------------------------------ prefetch pins +# A gather folded into a forward -- a prefetch part's, or the self-prefetch's +# -- has no data dependence on the forward's compute, so XLA's scheduler alone +# decides where it runs. On a v5p stage the SparseCore runs every offloaded +# collective and kernel of a program as one in-order chain, one at a time, and +# the scheduler put most folded gathers behind the forward's EP collectives, +# the large ones at the program's end (2 x v5p-128, 2026-10). A pin ties a +# gathered leaf to a point of the forward: the leaf and the forward's value +# there pass one lax.optimization_barrier, so the gather must be done before +# the forward goes on, and the program returns the barrier's output. A +# barrier is an identity: the values are the same either way. The points, in +# each layer of the forward: +# hn the MoE input, after attention (layer_fwd) +# xs the sorted tokens, before the expert gmms (_ring_moe) +# y gmm_wo's output, before the unsort (_ring_moe) +PIN_POINTS = ("hn", "xs", "y") +# The v5p recipe's libtpu flags set --xla_tpu_aggressive_opt_barrier_removal=ENABLED, +# which removes every optimization barrier, these too: a program with pins is +# compiled with it DISABLED, per program (jax.jit's compiler_options), so the +# others keep their schedules. Globally it would also keep the barriers XLA's +# own rematerialization leaves in the fused last chunk (fb_c3 / fba_c3: +2.4-2.6 +# ms each in the AOT replay). +PIN_COMPILER_OPTIONS = {"xla_tpu_aggressive_opt_barrier_removal": "DISABLED"} + + +def pin_compiler_options(mesh): + """The compiler options of a program with pins on `mesh`'s devices: + PIN_COMPILER_OPTIONS for TPU devices (a compile-only topology's too), None + elsewhere -- other backends keep optimization barriers anyway, and refuse + libtpu's option.""" + return dict(PIN_COMPILER_OPTIONS) if mesh.devices.flat[0].platform == "tpu" else None + + +class _PinTrace(threading.local): + """The pins of the forward this thread is tracing (precompile traces + programs in threads): `regs` {(point, layer): [[(chunk, leaf id), value], + ...]}, the values each point's barrier takes and hands back; how often each + point was reached (`seen`), and the points that were (`hit`).""" + + def __init__(self): + self.regs = self.seen = self.hit = None + + +_PINS = _PinTrace() + + +def _tie(point, v): + """Pin point `point` of the layer being traced: `v` and the gathered leaves + pinned there pass one optimization barrier, and the registered leaves are + replaced by its outputs. `v` alone outside a pinned forward: no op.""" + st = _PINS + if st.regs is None: + return v + layer = st.seen.get(point, 0) + st.seen[point] = layer + 1 + regs = st.regs.get((point, layer)) + if not regs: + return v + out = lax.optimization_barrier((v, *[r[1] for r in regs])) + for r, o in zip(regs, out[1:]): + r[1] = o + st.hit.add((point, layer)) + return out[0] + + +@contextlib.contextmanager +def _untied(): + """Trace with `_tie` an identity inside, whatever pinned forward is being + traced (a batch-split layer's mb1: `split_layers`).""" + st = _PINS + regs, st.regs = st.regs, None + try: + yield + finally: + st.regs = regs + + +@contextlib.contextmanager +def _pinned(regs, plan=None): + """Trace a forward inside with `regs` ({(point, layer): [[(chunk, leaf id), + value], ...]}) pinned at its points (`_tie`; the lists are updated in + place). Inside another pinned trace -- a composed program's forward that + gathers some of its own leaves -- they join that one's. The outermost + checks on exit that every point with a pin was reached, and that every pin + of `plan` ((point, layer, chunk, leaf id), ...), if given, was registered.""" + st = _PINS + if st.regs is not None: + for k, lst in regs.items(): + st.regs.setdefault(k, []).extend(lst) + yield + return + st.regs, st.seen, st.hit = {k: list(v) for k, v in regs.items()}, {}, set() + try: + yield + missing = sorted(set(k for k, v in st.regs.items() if v) - st.hit) + if missing: + raise ValueError(f"prefetch pins at points the forward never reached (point, layer): {missing}") + got = {key for lst in st.regs.values() for key, _ in lst} + lost = sorted((c, i) for _, _, c, i in plan or () if (c, i) not in got) + if lost: + raise ValueError(f"prefetch pins of leaves no part of the program gathers (chunk, leaf): {lost}") + finally: + st.regs = st.seen = st.hit = None + + +def _pinned_body(parts, spans): + """`compose`'s body for a program with pins: the gather parts first, their + leaves registered at the points the forward part pins them to; the forward + traced with them pinned (it registers its own gathered leaves, if any, + itself); the gather parts' outputs are the barriers'. Any other part is + traced after, outside the pins.""" + pinned = [k for k, p in enumerate(parts) if p.pins] + if len(pinned) != 1: + raise ValueError( + f"a program pins the gathers of one forward part, not {len(pinned)}: " f"{[parts[k].name for k in pinned]}" + ) + f = pinned[0] + plan = parts[f].pins + where = {(c, i): (pt, layer) for pt, layer, c, i in plan} + outs, regs, slot = [None] * len(parts), {}, {} + for k, (p, a) in enumerate(zip(parts, spans)): + if p.gathers: + (got,) = p.body(*a) + outs[k] = list(got) + for i, key in enumerate(p.gathers): + if key in where: + regs.setdefault(where[key], []).append([key, outs[k][i]]) + slot[key] = (k, i) + with _pinned(regs, plan): + outs[f] = tuple(parts[f].body(*spans[f])) + for lst in regs.values(): # the entries the barriers updated in place + for key, v in lst: + k, i = slot[key] + outs[k][i] = v + res = [] + for k, (p, a) in enumerate(zip(parts, spans)): + if outs[k] is None: + outs[k] = tuple(p.body(*a)) + res.extend((outs[k],) if p.gathers else outs[k]) + return tuple(res) + + +def compose(mesh, parts, name, keep_barriers=False, compiler_options=None): + """ONE shard_map and ONE jit running `parts` side by side. + + The arguments and outputs are the parts', concatenated in order, and each + part's donations shift to its arguments' positions -- but an F&B pair (a + forward beside a backward) returns its backward's outputs first + (`composed_order`), and its backward donates no more than its accumulator + (`composed_donations`). The parts share no + values, so XLA is free to interleave them: a forward with another chunk's + gather (= fwd_prefetch), a backward with a reduce-scatter (= bwd_reduce), + or the forward of one chunk with the backward of another (an F&B pair). + A forward part with prefetch pins (`Part.pins`) ties the gathered leaves to + its points instead (`_pinned_body`), and the program compiles with + `pin_compiler_options` -- so on TPU a pinned program is a top-level jit + only: jax refuses to stage a jit with compiler options inside another jit + or jax.make_jaxpr (trace it with `.trace(...)`, compile it with + `.lower(...)`). `keep_barriers`: compile with those options whatever the + parts (a batch-split chunk's phases are optimization barriers too); + `compiler_options`: more of them, over those (a Lineage chunk's, + ds_ep_lineage.compiler_options). + + A program with a `global_view` part (a Lineage chunk's F, B or A) is a + mixed one: ONE jit at global view. It calls every global_view part's body + as it is (in an F&B pair the other chunk's part is one too: a stage runs + Lineage's layers for all its chunks or for none) and runs each other part + (a G or an R) in a shard_map of its own over the stage mesh -- the + per-device body it would run in the one shard_map -- side by side, sharing + no values as ever. No pins there: Lineage's layers have no point to tie a + gather to. + """ + parts = tuple(parts) + n_in = [len(p.in_specs) for p in parts] + pins = any(p.pins for p in parts) + mixed = any(p.global_view for p in parts) + if mixed and pins: + raise ValueError( + f"{name}: prefetch pins tie points of ds_ep's own layers, not of a global-view part's " + f"({[p.name for p in parts if p.global_view]}: Lineage's layers)" + ) + order = composed_order(parts) + if pins and order != tuple(range(len(parts))): + raise ValueError( + f"{name}: an F&B pair folds in no gather, so it pins none " + f"({[p.name for p in parts if p.pins]}: prefetch pins)" + ) + + def body(*args): + if pins: + starts = [sum(n_in[:k]) for k in range(len(parts))] + return _pinned_body(parts, [args[s : s + n] for s, n in zip(starts, n_in)]) + outs, i = [], 0 + for p, n in zip(parts, n_in): # traced in the parts' order, whatever the outputs' + f = p.body + if mixed and not p.global_view: + f = jax.shard_map(f, mesh=mesh, in_specs=p.in_specs, out_specs=p.out_specs, check_vma=False) + outs.append(tuple(f(*args[i : i + n]))) + i += n + return tuple(o for k in order for o in outs[k]) + + donate = composed_donations(parts) + cat = lambda field: tuple(x for p in parts for x in getattr(p, field)) + cat_out = lambda field: tuple(x for k in order for x in getattr(parts[k], field)) + opts = pin_compiler_options(mesh) if pins or keep_barriers else None + if compiler_options: + opts = {**(opts or {}), **compiler_options} + prog = ( + body + if mixed + else jax.shard_map(body, mesh=mesh, in_specs=cat("in_specs"), out_specs=cat_out("out_specs"), check_vma=False) + ) + return jax.jit( + _named(prog, name), + in_shardings=cat("in_sh"), + out_shardings=cat_out("out_sh"), + donate_argnums=donate, + compiler_options=opts, + ) + + +def composed_order(parts): + """The order of the parts whose outputs `compose`'s program returns, one part's after another: the parts' own, but + in an F&B pair -- a backward (`Part.backward`) beside a forward (`Part.forward`) -- the backward's first, so the + accumulator leaves it donates go to its own outputs before a forward output of their shape and dtype can take them + (`composed_donations`).""" + if not (any(p.forward for p in parts) and any(p.backward for p in parts)): + return tuple(range(len(parts))) + return tuple(sorted(range(len(parts)), key=lambda k: not parts[k].backward)) + + +def composed_donations(parts): + """The argument positions `compose`'s program donates: each part's `donate`, shifted to its arguments' place -- + but none of a backward's dy, saved set and stash (`Part.fwd_like`) beside a forward (`Part.forward`): an F&B pair. + jit hands each output, in order, the buffer of the first donated argument of its shape and dtype on a device; the + forward's y has dy's shape, and its saved set and stash have the backward's where the two chunks have the same + layers. With the forward's outputs listed first, jit aliased those buffers to them, and as XLA interleaves the two + parts, it copied each buffer the backward still read before the forward overwrote it (A100, dsv3-mini, 16 + microbatches: ~1700 device copies a step, 85 ms, for the saved sets). Undonated, they are freed when the program + ends: one set's bytes, and dy's, held a program longer. (Donated, dy would now go to the backward's own dx, but at + gpu_port_test.InterleavedPairs' dims that costs XLA:CPU one copy more a pair.) The accumulator stays donated, to be + added to in place, and `compose` lists an F&B pair's backward outputs first (`composed_order`): the accumulator + leaves go to the backward's own outputs before a forward output of their shape and dtype (a saved activation or a + stash leaf of a weight's shape, as in fp32 at InterleavedPairs' dims) can take them. The fused last chunk's part + ('A') is no forward here: an A&B pair keeps the parts' order, and the A's dx takes the buffer of the x it donates, + ahead of the backward's dy.""" + fwd = any(p.forward for p in parts) + donate, i = [], 0 + for p in parts: + donate.extend(i + d for d in p.donate if not (fwd and d in p.fwd_like)) + i += len(p.in_specs) + return tuple(donate) + + +def pdesc(kind, **kw): + """Hashable descriptor of one part (`ChunkPrograms.part(kind, **kw)`), for + `ChunkPrograms.program`. Defaults are dropped, so equal parts share a key; + `peer=` takes the part from another chunk on the same mesh.""" + kw = { + k: tuple(v) if isinstance(v, list) else v for k, v in kw.items() if v is not None and v is not False and v != "none" + } + return (kind, tuple(sorted(kw.items()))) + + +@dataclasses.dataclass +class Stash: + """One chunk's stash programs for one policy (`ChunkPrograms.build_stash`). + + fwd(w, x, seed) -> y, res, stash + bwd(w, x, res, stash, dy, seed) -> dx?, gacc (stash, dy donated) + bwda(w, x, res, stash, dy, gacc, seed) -> dx?, gacc + dW (and gacc) + + `stash` is a flat tuple, per layer in order, of the residuals the policy + keeps, each with a leading per-device axis (spec P(FE, None, ...)). + """ + + policy: str + specs: tuple # PartitionSpec per stash array + avals: tuple # global ShapeDtypeStructs with shardings (precompile) + layer_bytes: tuple # per device and microbatch, per layer + bytes: int # their sum + plans: tuple # per layer: where each vjp constant comes from + fwd_body: object + bwd_core: object + fwd: object = None + bwd: object = None + bwda: object = None + + +@dataclasses.dataclass +class Split: + """One middle chunk's backward cut into I and W, for the zero-bubble schedules (`ChunkPrograms.build_split`): bwd's + body -- the B part of the chunk's first gradient write -- traced to one flat per-device jaxpr and cut by data + dependence (stage_ad.split_jaxpr). I computes dx, the remat recompute of the forward included; W every + accumulator leaf, from the values of I it reads (the crossing set) and the arguments of I it reads too (`kept`). + One I feeds either W: + + I(w, x, res, dy, seed) -> dx, crossing part('I'): bwdi_c{c} + W(crossing, kept) -> gacc part('W'): bwdw_c{c} (acc False) + W(crossing, kept, gacc) -> gacc + dW part('W', acc=True): bwdwa_c{c} (gacc donated) + W(crossing, kept, gacc, sqs) -> grads, stage sumsq rs_self=n: bwdwa_c{c}_rsself (gacc donated) + + Or the fused last chunk's program cut so (`last`, `ChunkPrograms.build_split_last`): fb's body, I its forward, + head, loss and input gradient with the weight gradients of every accumulator leaf but its layers' (`i_leaves`: the + head's, the decoder norm's, MTP's, the routers' bias slots, which hold their expert counts), W its layers' (the + rest, `w_leaves`). The chunk's accumulator is then two disjoint parts, each a flat tuple of its leaves in leaf + order -- I's, written by its F (AI), and W's -- which the step merges once both are whole: + + AI(w, x, tgt[, tok], seed) -> dx?, gk, loss, crossing part('AI'): fbi_c{c} (x donated) + AI(w, x, tgt[, tok], gk, lacc, seed) -> dx?, gk + dWk, lacc + loss, crossing part('AI', acc=True): fbai_c{c} + W(crossing, kept) -> gw part('W'): bwdw_c{c} + W(crossing, kept, gw) -> gw + dWw part('W', acc=True): bwdwa_c{c} + + `acc`: the W this split's is, the chunk's first gradient write (False) or an accumulating one (True) -- the last + chunk's AI too. The accumulating halves are the first write's with the accumulator added to their outputs, leaf by + leaf (`w_adds`; and the last chunk's loss to the loss accumulator): bwda's accumulate is bwd's plus the accumulator + -- add_acc(g, dW) = g + new_acc(dW) on every leaf of a middle chunk and of the last chunk (the embedding's rows, + TableRows, which add otherwise, are chunk 0's B's alone) -- so one trace makes both. Not where the chunk accumulates + its routed experts' dW in place (ChunkPrograms.inplace_dw: tokamax's dW kernels starting from the accumulator's + blocks): there the accumulating W is cut from bwda's (fba's) own trace, and a middle chunk's reads the first write's + I where that trace cuts the same I -- the same program, crossing set and kept arguments -- else its own (`i_acc` + True: part('I', acc=True)); the last chunk's AI reads the accumulator's kept part, its own for each `acc`. + + `crossing`: a flat tuple, in the order W first reads them, each with a leading per-device axis (spec P(FE, None, + ...)), as a stash: `crossing_local` the per-device ShapeDtypeStructs, `crossing_avals` the global ones with their + shardings (precompile). `kept`: ((group, leaf), ...), the leaves of I's arguments W reads -- group one of + `groups` (I's arguments: 'w', 'x', 'res', 'dy', 'seed', or the last chunk's 'w', 'x', 'tgt'[, 'tok'], 'seed'), + leaf the index among that argument's leaves -- which I does not donate (a step keeps them until W instead: + `kept_of`); `kept_specs` / `kept_avals` theirs. `i_src`: per invar of `i_jaxpr`, its position among the leaves of + I's arguments, or the stage_ad.Const it is; `w_src`: per invar of `w_jaxpr` after the crossing set, ('kept', j), + ('gacc', j) (the j-th leaf of the accumulator W writes: an in-place W's) or a Const. `i_donate`: what I donates -- + what the B (or A) donates, but an argument W reads. `bytes`: the crossing set's bytes per device; `kept_bytes` + those of the kept x / res / dy leaves, which the fused backward would have freed (a step holds w, the seed and the + batch anyway): one microbatch's W buffer, from its I to its W, is their sum. `stats`: split_jaxpr's. + """ + + acc: bool + i_acc: bool + w_adds: bool + i_jaxpr: object + w_jaxpr: object + i_src: tuple + w_src: tuple + crossing_local: tuple + crossing_specs: tuple + crossing_avals: tuple + kept: tuple + kept_specs: tuple + kept_avals: tuple + i_donate: tuple + bytes: int + kept_bytes: int + stats: dict + groups: tuple = ("w", "x", "res", "dy", "seed") + last: bool = False + i_leaves: tuple = () # the accumulator leaves I writes (the last chunk's AI), their positions in leaf order + w_leaves: tuple | None = None # ... those W writes: None, every one (a middle chunk's) + + def kept_of(self, i_args): + """The values `kept` names, from I's arguments in `groups` order (w, x, res, dy, seed; the last chunk's w, x, tgt[, + tok], seed): the arrays themselves (a step keeps the references, no copy).""" + groups = {g: jax.tree.leaves(a) for g, a in zip(self.groups, i_args, strict=True)} + return tuple(groups[g][i] for g, i in self.kept) + + +# `A_log = log A`, A ~ U(A_LOG_RANGE): MaxText's qwen3.py draws A ~ U(0, 16], kept off 0 here. +A_LOG_RANGE = (1e-9, 16.0) + + +def qwen_init_rule(path): + """How `StagePrograms.init` draws a Qwen3.5-family leaf, by MaxText's rules + where they shape the math: 'zeros' for the zero-centred norm scales (input, + post-attention, final, q / k norms: applied as 1 + scale, so a one would + double the gain), 'ones' for the GDN's gated output norm and dt_bias, + 'a_log' for A_log, else 'normal' (the kernels and the embedding, N(0, + scale^2) as every DeepSeek leaf). The zeros / ones / a_log choice is a + copy of qwen35.init.leaf_rule's, and A_LOG_RANGE of its constant + (ds_ep_qwen_test.QwenInit holds them to each other); leaf_rule's 'normal' + draws by fan_in instead.""" + keys = tuple(str(getattr(k, "key", k)) for k in path) + name = keys[-1] + if name == "scale": + return "ones" if keys[-3:-1] == ("norm", "rms_norm") else "zeros" + if name == "A_log": + return "a_log" + if name == "dt_bias": + return "ones" + return "normal" + + +# ------------------------------------------------------------ stage programs +class ChunkPrograms: + """The jitted programs of one chunk on its stage mesh. + + fwd(w, x, seed) -> y, res + bwd(w, x, res, dy, seed) -> dx, gacc (first microbatch) + bwda(w, x, res, dy, gacc, seed) -> dx, gacc + dW (gacc donated) + fb / fba (last chunk) -> dx, gacc, loss (fused fwd + bwd) + + `x` is the chunk input (tokens for chunk 0), `res` the extra residuals (the + inputs of layers 1..n-1, plus layer 0's for chunk 0). Chunk 0 returns no dx. + + Those programs are fixed. Everything else is composed from `part`s, by + descriptor (`program`): the stash forward / backward of a policy + (`build_stash`), a middle chunk's backward cut into I and W for the + zero-bubble schedules (`build_split`) -- and the fused last chunk's program + cut into AI and W (`build_split_last`) -- and any of them with another + chunk's FSDP gather or reduce-scatter folded in, or paired with another + chunk's forward. + + A batch-split chunk on Lineage's layers (StageConfig.lineage_split) has the + same programs -- signatures, donations, residuals (chunk 0 keeps its + embedding's output, the others nothing) -- but each is a jit at global view + over the Explicit stage mesh, not a shard_map: Lineage's code opens its own + shard_maps and reads layouts from the arrays' types (ds_ep_lineage). The + decoder layers are the chunk's ds_ep_lineage.Region, a custom_vjp whose + primal and two rules are nested jits that every program of the chunk's + structure shares, each traced once (so a structure with F and B programs + traces its forward twice: at the primal's activation-bank size and the + forward rule's); the embedding and the head are ds_ep's own per-device + code, each in a shard_map of its own. A backward is the VJP of the region, + recomputed from the chunk's input inside the one program -- ds_ep's + contract keeps one residual a chunk, its input; carrying Lineage's + residuals from F to B instead would hold about 3.4-5.8 GiB per in-flight + chunk per device at DeepSeek-V3 scale (estimated: a 128-device stage, 4096 + tokens a half a device) -- and the + region's weight gradients come out typed as the accumulators are: each + device's partial, unreduced, no leading axis. Its composed programs are + mixed (`compose`): the gathers and reduce-scatters folded in run in + shard_maps of their own beside the global-view part. + """ + + def __init__( + self, + scfg: StageConfig, + ch: ChunkSpec, + mesh, + mbs: int, + seq: int, + denom: float, + lineage_sparsecore: bool | None = None, + ): + _require_resolved(scfg) + self.scfg, self.ch, self.mesh = scfg, ch, mesh + cfg = scfg.model + self.n = len(ch.layers) + # Dense layers -- the model's first: chunk 0's, or under a layer split + # that counts every layer the first chunks' -- run before the MoE layers. + self.nd = ch.dense + # A batch-split chunk on Lineage's layers: global-view programs (above). + # `lineage_sparsecore`: does its Region run Lineage's SparseCore regions + # -- does libtpu offload the stage's collectives? The pipeline's answer + # (ds_ep_pipeline.Pipeline asks it as it asks the FSDP one, over the + # whole stage, ahead of time too: libtpu's probe, agreed across + # processes; the device rule only where the probe fails; or its + # stage_lineage_sparsecore, which ds_ep_aot --transfers-only sets to the + # rule's); None: ds_ep_lineage.region probes the mesh itself when a + # program first traces. + self.lineage = scfg.lineage_split + self.lineage_sc = None if lineage_sparsecore is None else bool(lineage_sparsecore) + # A batch-split chunk's phases are optimization barriers: on TPU its + # programs compile with them kept, as a pinned one (pin_compiler_options). + self._copts = pin_compiler_options(mesh) if scfg.batch_split else None + if self.lineage: + # Lineage orders its phases with program_order's barriers, which its + # backward depends on; and its splash dkv kernel wants the scoped-VMEM + # limit of its recipe (ds_ep_lineage.compiler_options: None off TPU). + from maxtext.experimental.mpmd.jax import ds_ep_lineage # lazily: it imports this module + + self._copts = {**(self._copts or {}), **(ds_ep_lineage.compiler_options(mesh) or {})} or None + # The routed-bias update: each MoE layer's expert counts take its router + # bias's gradient slot (count_leaves). Without an update rate the bias + # stays where it starts, and its slot keeps autodiff's zeros. + self.counting = ch.routed_bias and cfg.routed_bias_update_rate > 0 + if self.counting and ch.kinds and not is_qwen(cfg): + raise ValueError( + "the routed-bias update (routed_bias_update_rate > 0) files a stacked DeepSeek chunk's expert " + "counts (put_counts): use layer_tree 'stacked'" + ) + # MTP: the fused last chunk also takes the microbatch's input tokens. + self.mtp = ch.mtp + # The sequence-wise aux loss: each MoE layer's output carries its share + # (`_ring_moe`), the global batch's sequences its denominator. + self.aux_seqs = 0 + if cfg.load_balance_loss_weight > 0: + if not cfg.moe_use_megatron_seq_aux_loss or scfg.cp > 1: + raise ValueError( + "load_balance_loss_weight > 0: the pipeline runs Megatron-LM's sequence-wise aux loss " + "(moe_use_megatron_seq_aux_loss), without context parallelism (a sequence on one device)" + ) + self.aux_seqs = int(round(denom / seq)) + if ch.mtp and (ch.mtp != 1 or not ch.last or scfg.cp > 1): + raise ValueError( + f"chunk {ch.index}: one MTP layer (mtp_num_layers=1), on the last chunk, without context " + f"parallelism, not mtp={ch.mtp} (last={ch.last}, cp={scfg.cp})" + ) + # A chunk of no layer at all -- the embedding's or the head's alone (a layer split's 0 at an end) -- or of + # dense layers only (chunk 0's, a layer split's 0 there) has no MoE layer to split: it runs the plain path even + # under batch split (no expert collective to hide behind the other half) -- an empty one with no residual for + # its backward (its embedding's VJP reads the tokens alone), where the split path would save its output for + # nothing. + self.empty = not self.n and not self.nd + self.split = scfg.batch_split and self.n > 0 + if self.lineage and (self.counting or self.aux_seqs or self.mtp or not self.n): + # ds_ep_lineage.Region hands back neither Lineage's expert counts nor its router logits (aux.group_sizes / + # aux.logits would carry them), runs no MTP layer, and batch-splits MoE layers: say which of these it is + why = [ + w + for w, bad in ( + ( + "a chunk without a MoE layer (Lineage batch-splits MoE layers, so every chunk needs one: a layer split " + "that counts every layer must not give a chunk dense layers only)", + not self.n, + ), + ("the routed-bias update (Lineage's expert counts are not wired up)", self.counting), + ("the sequence-wise aux loss (Lineage's router logits are not wired up)", self.aux_seqs), + (f"MTP (mtp {self.mtp}: no MTP layer on Lineage's layers)", self.mtp), + ) + if bad + ] + raise NotImplementedError( + f"chunk {ch.index}: batch_split on Lineage's layers (batch_split_impl 'lineage') " + "cannot run " + "; ".join(why) + ) + if scfg.batch_split and (self.counting or self.aux_seqs or self.mtp): + # split_layers runs moe_experts on each half with neither counts nor an aux loss riding its output + raise NotImplementedError( + f"chunk {ch.index}: batch_split runs MoE layers without the routed-bias update, the " + f"sequence-wise aux loss and MTP ({self.n} MoE layer(s), counting {self.counting}, " + f"aux loss {bool(self.aux_seqs)}, mtp {self.mtp})" + ) + ns = lambda spec: NamedSharding(mesh, spec) + self.cspec = chunk_compute_specs(ch) + # The weights' spec at the programs' boundaries (cspec typed reduced under + # shard_mode 'explicit'); the bodies read cspec. + self.wspec = chunk_wc_specs(scfg, ch) + self.gspec = acc_specs(scfg, ch) + # How the reduce-scatters read an accumulator and split their collectives + # (_scatter_leaf): 'auto''s carries a leading partial axis, a + # [1, *compute_local] block a device. + self._rs = dict(lead=scfg.shard_mode != "explicit", per_axis=scfg.rs_axes == "each") + # How the gathers split their collectives (_gather_leaf's per_axis). + self._ag = scfg.gather_axes == "each" + act = P(FE, None, None) + tok = P(FE, None) + self.act_spec, self.tok_spec = act, tok + x_spec = tok if ch.first else act + # The residuals a backward reads besides x: the inputs of its layers but + # the first, dense and MoE (and chunk 0's first, its embedding); under + # batch split only chunk 0's embedding, the backward recomputing the whole + # split chunk. + if scfg.batch_split: + n_dev = math.prod(mesh.shape[a] for a in FE) + if mbs % n_dev or (mbs // n_dev) % 2: + raise ValueError( + f"batch_split runs each device's rows as two halves: a microbatch of {mbs} rows over " + f"{n_dev} devices is {mbs / n_dev:g} a device, want an even number" + ) + n_res = (1 if ch.first else 0) if self.split else max(0, self.nd + self.n - (0 if ch.first else 1)) + self.n_res = n_res + res_spec = (act,) * n_res + self.res_spec = res_spec + self.act_aval = jax.ShapeDtypeStruct((mbs, seq, cfg.emb_dim), cfg.dtype) + self.tok_aval = jax.ShapeDtypeStruct((mbs, seq), jnp.int32) + self.res_avals = tuple(jax.ShapeDtypeStruct(self.act_aval.shape, cfg.dtype, sharding=ns(act)) for _ in range(n_res)) + # one residual set's bytes a device (save_residuals: the VJP's residuals instead, set below) + self.res_bytes = ( + n_res * (mbs // math.prod(mesh.shape[a] for a in FE)) * seq * cfg.emb_dim * jnp.dtype(cfg.dtype).itemsize + ) + self._parts, self._programs, self._stash = {}, {}, {} + self._splits = {} # per acc (build_split) + self.stash_avals, self.stash_bytes = {}, {} # per policy (build_stash) + loss_spec = P(FE) + self.loss_spec = loss_spec + if self.lineage: + if scfg.save_residuals: + raise ValueError( + "save_residuals: not on Lineage's layers (batch_split_impl 'lineage'), whose region keeps " + "residuals of its own" + ) + self._init_lineage(x_spec, denom) + return + scalar = P() + sm = functools.partial(jax.shard_map, mesh=mesh, check_vma=False) + acc_dt = scfg.acc_dtype + layer_ids = ch.layers + + def stack_dw(dws, dwd): + """The MoE and the dense layers' weight gradients, in layer order -> the chunk's layer trees (stacks, or one + subtree a layer: `kinds`, `dense_kinds`).""" + dw = {} + if self.n: + dw["layers"] = stack_layers(dws, ch.kinds) + if self.nd: + dw["dense_layers"] = stack_layers(dwd, ch.dense_kinds) + return dw + + def dense_weights(w): + """The chunk's dense layers' weights, one tree each, from its 'dense_layers' tree.""" + return [layer_weights(w["dense_layers"], l, ch.dense_kinds) for l in range(self.nd)] + + def with_counts(dwl, counts): + """A MoE layer's gradient with its router bias's slot holding the layer's expert counts (fp32: exact).""" + gate = dict(dwl["moe"]["gate"], bias=counts.astype(jnp.float32)) + return {**dwl, "moe": {**dwl["moe"], "gate": gate}} + + # A Qwen3.5-family chunk's layers are subtrees of their own (a layer axis + # of one): a layer's expert leaf is already a whole buffer, read in place. + stacked_reads = scfg.expert_weights == "stacked" and not ch.kinds and self.n > 0 + + def experts_of(wls): + """The chunk's stacked expert weights from its layer tree `wls`, for + moe_experts' stacked; None under expert_weights 'sliced'.""" + return {k: wls["moe"][k] for k in EXPERT_LEAVES} if stacked_reads else None + + def at(st, l): + return None if st is None else (st, l) + + def dense_run(wd, h): + """The chunk's dense layers `wd` (one tree each) over all of h.""" + for wl in wd: + h = dense_layer_fwd(wl, h, scfg) + return h + + def split_run(wl, h, seed, stacked=None, wd=()): + """The chunk's dense layers `wd` over all of h, then its MoE layers + `wl` (one tree each) over h's rows on this device as two halves + (split_layers), each layer's halves routed with keys of their own.""" + h = dense_run(wd, h) + keys = [tuple(jax.random.fold_in(_layer_key(lid, seed), i) for i in (0, 1)) for lid in layer_ids] + half = h.shape[0] // 2 + ya, yb = split_layers(wl, h[:half], h[half:], keys, scfg, stacked) + return jnp.concatenate([ya, yb], axis=0) + + def run_layers(w, h, seed, save, remat=False, counts=False): + """The chunk's dense layers, then its MoE layers, over h -> (the chunk's + output, each layer's input if `save`, and with `counts` the expert + counts of its MoE layers, in order).""" + # Under stacked reads a layer's slices are taken inside the (remat) + # function, which gets the stacked tree: its expert slices are then + # never read (megablox reads the stacked leaves), and XLA drops them -- + # under remat too, whose barriers would otherwise take them. + wd = dense_weights(w) + if self.split: # (no counts: refused above) + if stacked_reads: + + def f(wls, h, wd): + return split_run([_take(wls, l) for l in range(self.n)], h, seed, experts_of(wls), wd) + + args = (w["layers"], h, wd) + else: + + def f(wl, h, wd): + return split_run(wl, h, seed, wd=wd) + + args = ([layer_weights(w["layers"], l, ch.kinds) for l in range(self.n)], h, wd) + if remat: + f = jax.checkpoint(f) + return f(*args), [h] if save else [] + hs, cnts = [], [] + for l in range(self.nd): + if save: + hs.append(h) + f = functools.partial(dense_layer_fwd, scfg=scfg) + if remat: + f = jax.checkpoint(f) + h = f(wd[l], h) + fwd = layer_fwd_counts if counts else layer_fwd + for l in range(self.n): + if save: + hs.append(h) + if stacked_reads: + + def moe_f(wls, h, l=l): + return fwd(_take(wls, l), h, _layer_key(layer_ids[l], seed), scfg, at(experts_of(wls), l), self.aux_seqs) + + args = (w["layers"], h) + else: + moe_f = functools.partial(fwd, key=_layer_key(layer_ids[l], seed), scfg=scfg, aux_seqs=self.aux_seqs) + args = (layer_weights(w["layers"], l, ch.kinds), h) + if remat: + moe_f = jax.checkpoint(moe_f) + with _context(_DW0_LAYER, l): # in-place dW accumulation (_DW0): this layer's blocks + if counts: + h, cnt = moe_f(*args) + cnts.append(cnt) + else: + h = moe_f(*args) + return (h, hs, cnts) if counts else (h, hs) + + if scfg.grad_reduce == "microbatch": + # Reduce-scatter this microbatch's partial gradient to the storage layout + # right here (XLA overlaps the early-finished MoE part with the rest of + # the backward) and accumulate the sharded, reduced result. + ss_, cs_, cm_ = chunk_storage_specs(ch), self.cspec, count_mask(ch) + # (the embedding's rows, TableRows, as their table: the reduce-scatter takes whole leaves) + whole = lambda d: d.dense() if isinstance(d, TableRows) else d + + def reduced(dw): + return jax.tree.map( + lambda d, s_, c_, k_: _scatter_leaf( + whole(d)[None], + s_, + c_, + jnp.float32 if k_ else scfg.rs_dtype, + scfg.fsdp_collectives, + per_axis=self._rs["per_axis"], + ).astype(acc_dt), + dw, + ss_, + cs_, + cm_, + is_leaf=_arr_leaf, + ) + + # (add_acc(g, dw) is g + new_acc(dw) on every leaf, as below too: Split.w_adds builds an accumulating W so) + def add_acc(gacc, dw): + return jax.tree.map(lambda g, d: g + d, gacc, reduced(dw)) + + def new_acc(dw): + return reduced(dw) + + else: + # A device's partial dW: its block of the leading partial axis ('auto'), + # or the block of the unreduced-typed accumulator itself ('explicit'). + lift = (lambda d: d[None]) if self._rs["lead"] else (lambda d: d) + + def add_leaf(g, d): + """g + a device's partial dW `d`: the embedding's rows (TableRows) scatter-added into g where it lies, any + other dW added whole.""" + return d.into(g) if isinstance(d, TableRows) else g + lift(d).astype(acc_dt) + + # (add_acc(g, dw) is g + new_acc(dw) on every leaf but the embedding's rows, which only chunk 0 has: + # Split.w_adds builds a middle chunk's accumulating W so) + def add_acc(gacc, dw): + return jax.tree.map(add_leaf, gacc, dw) + + def new_acc(dw): + return jax.tree.map(lambda d: lift(d.dense(acc_dt) if isinstance(d, TableRows) else d).astype(acc_dt), dw) + + # In-place dW accumulation (gmm_impl 'tokamax', `_DW0`): a backward that + # accumulates hands the accumulator's routed-expert blocks to the layers' + # grouped matmuls, whose dW kernels add into them -- so those leaves of its + # dW already hold the accumulator's value and are not added again. Where + # the accumulator's dtype is the compute weights' (a cotangent takes its + # primal's dtype), under auto sharding at the step cadence, without + # routed-bias counting (whose gate leaves carry counts). + # Only where each layer's accumulator block is a whole buffer: a Qwen3.5-family + # chunk's layer subtrees, or a DeepSeek chunk of one MoE layer. Blocks of one + # [n, ...] stack (a DeepSeek chunk of several layers) handed to the in-place + # kernel came out wrong on GB200 (jax 0.12.0.1, jax-triton 0.5.0): the kernels' + # aliased outputs land on views into the stack, inf / garbage even without + # donation (gpu_port_test.InplaceDwStacked holds the minimal case and pins the guard). + saved_chunk = scfg.save_residuals and not ch.last + inplace_dw = ( + scfg.gmm_impl == "tokamax" + and scfg.inplace_dw + and scfg.shard_mode == "auto" + and (bool(ch.kinds) or self.n == 1) + and scfg.grad_reduce == "step" + and not self.counting + and self.n > 0 + and ( + jnp.dtype(acc_dt) == jnp.dtype(cfg.dtype) + or ( + scfg.inplace_dw_any_dtype + and not stacked_reads + and not ch.last + and (not self.split or scfg.split_dw == "acc") + ) + ) + and (not saved_chunk or bool(ch.kinds) and not self.split) + ) + # An accumulator of its own dtype (fp32): the accumulated value leaves as the start's cotangent, so the starts + # are primals of the backward's VJP (tokamax_gmm's dw32, which takes no stacked reads) -- in the saved path's + # forward and in bwd_core_recompute; not in the last chunk's fused loss-and-backward. Under batch split the + # halves chain it (split_dw 'acc': mb0 hands its start on to mb1, whose accumulated value mb0's dW continues). + acc_own = inplace_dw and jnp.dtype(acc_dt) != jnp.dtype(cfg.dtype) + self.inplace_dw = inplace_dw + unlift = (lambda g: g[0]) if self._rs["lead"] else (lambda g: g) + + def routed_path(path): + keys = [getattr(k, "key", getattr(k, "idx", None)) for k in path] + return ( + len(keys) >= 3 and keys[0] == "layers" and keys[-1] in EXPERT_LEAVES and keys[-2] in ("moe", "routed_experts") + ) + + def dw0_blocks(gacc): + """{MoE layer: {expert leaf: its block of `gacc`}} (`_DW0`), or None.""" + if not inplace_dw or gacc is None: + return None + gl = jax.tree.map(unlift, gacc["layers"]) + out = {} + for l in range(self.n): + r = routed_tree(layer_weights(gl, l, ch.kinds), scfg) + out[l] = {k: r[k] for k in EXPERT_LEAVES} + return out + + def add_acc_inplace(gacc, dw): + return jax.tree_util.tree_map_with_path( + lambda path, g, d: lift(d).astype(acc_dt) if routed_path(path) else add_leaf(g, d), gacc, dw + ) + + def with_dw0(core): + """`core(*args, seed)` (a backward) traced with `gacc`'s blocks as its dW + kernels' starting values -> (dx, gacc + dW).""" + + def acc_core(*args, gacc): + blocks = dw0_blocks(gacc) + with _context(_DW0, blocks): + dx, dw = core(*args) + return dx, (add_acc_inplace(gacc, dw) if blocks is not None else add_acc(gacc, dw)) + + return acc_core + + def acc_starts(wl, blocks=None): + """{MoE layer: {expert leaf: its accumulator start}}: `blocks` (the step accumulator's), else zeros.""" + if not inplace_dw: + return None + if blocks is not None: + return blocks + return {l: {k: jnp.zeros(routed_tree(wl[l], scfg)[k].shape, acc_dt) for k in EXPERT_LEAVES} for l in range(self.n)} + + def put_routed(t, blk): + """Layer tree `t` with its routed experts' leaves replaced by `blk`.""" + if is_qwen(cfg): + mlp = dict(t["mlp"]) + mlp["routed_experts"] = {**mlp["routed_experts"], **blk} + return {**t, "mlp": mlp} + return {**t, "moe": {**t["moe"], **blk}} + + if not ch.last and scfg.save_residuals: + # Saved residuals (StageConfig.save_residuals): the forward runs the chunk's layers under jax.vjp and returns + # the VJP's residual leaves -- the VJP is a pytree (a CustomNode over its residuals, a jaxpr in its treedef), + # so its leaves cross the program boundary and the backward rebuilds it from them. Leaves that ARE the + # function's primals -- the layers' compute weights, the chunk's input -- are not outputs (the backward has + # them as arguments: no copy of a weight a microbatch); every other leaf is, with a leading device axis so + # that one spec, P(FE), places any local shape. The structure comes from tracing the forward (_saved_meta, + # filled by every trace: the probe below, then the lowerings). + if self.counting or stacked_reads or self.aux_seqs: + # say each setting it does not take, and what to set instead + why = [ + w + for w, bad in ( + ( + "stacked expert reads -- the routed experts' weights read in place from the chunk's stacked " + "layer leaves, expert_weights 'stacked' (the default) on layer_tree 'stacked': set " + "expert_weights 'sliced' (--expert-weights sliced) or layer_tree 'per_layer' (--layer-tree " + "per_layer)", + stacked_reads, + ), + ( + "the routed-bias update's expert counts (routed_bias_update_rate > 0): set it to 0 " + "(--bias-update-rate 0)", + self.counting, + ), + ( + "the sequence-wise aux loss (load_balance_loss_weight > 0): set it to 0 (--lb-loss-weight 0)", + self.aux_seqs, + ), + ) + if bad + ] + raise ValueError(f"chunk {ch.index}: save_residuals (--save-residuals on) does not support " + "; nor ".join(why)) + saved = {} + self._saved_meta = saved + + def layers_fn(seed): + def f(wl, h, wd, accs=None): + # accs (inplace_dw): fp32-or-whatever accumulator starts for each MoE layer's routed experts, primals of + # the VJP whose cotangents are the accumulated values (tokamax_gmm's dw0 of its own dtype); placeholders + # here, the step accumulator's blocks in the backward + with _context(_DW0, accs): + if self.split: + return split_run(wl, h, seed, None, wd) + for l in range(self.nd): + h = dense_layer_fwd(wd[l], h, scfg) + for l in range(self.n): + with _context(_DW0_LAYER, l): + h = layer_fwd(wl[l], h, _layer_key(layer_ids[l], seed), scfg, None, self.aux_seqs) + return h + + return f + + def primals_of(w, x): + h = embed(w, x, scfg) if ch.first else x + wl = [layer_weights(w["layers"], l, ch.kinds) for l in range(self.n)] + wd = dense_weights(w) + return wl, h, wd + + def fwd_body(w, x, seed): + wl, h, wd = primals_of(w, x) + accs = acc_starts(wl) + with layers.lean_residuals(): + y, vjp = jax.vjp(layers_fn(seed), wl, h, wd, accs) + leaves, treedef = jax.tree_util.tree_flatten(vjp) + prim = jax.tree_util.tree_leaves((wl, wd)) + accl = jax.tree_util.tree_leaves(accs) + src, res = [], [] + for v in leaves: + k = next((i for i, q in enumerate(prim) if v is q), None) + r = next((i for i, q in enumerate(res) if v is q), None) + a = next((i for i, q in enumerate(accl) if v is q), None) + if k is not None: + src.append(("w", k)) + elif a is not None: # an accumulator start: the backward's own blocks + src.append(("acc", a)) + elif v is h: + src.append(("h",)) + elif v is x: + src.append(("x",)) + elif v is seed: + src.append(("seed",)) + elif r is not None: # the same array twice in the VJP: one output + src.append(("r", r)) + else: + src.append(("r", len(res))) + res.append(v) + # (Under batch split a chunk without dense layers slices its input inside split_run, so the input's two + # halves are residuals of their own beside x: one activation more a microbatch in flight. Recognising them + # would take split_run's halves as primals -- not done: saved residuals and batch split do not meet where + # memory is short, at scale.) + local = tuple(jax.ShapeDtypeStruct(r.shape, r.dtype) for r in res) + if "treedef" not in saved: # the probe's trace: the layout every later trace must reproduce + saved.update(treedef=treedef, src=tuple(src), local=local) + elif (saved["src"], saved["local"]) != (tuple(src), local): + raise ValueError( + f"chunk {ch.index}: save_residuals: a forward variant (folded collectives, pins) traced a " + "residual layout other than the probe's; its backward would misread it" + ) + return y, tuple(r[None] for r in res) + + # The probe: trace the forward once (abstractly) for the residuals' structure -> res_spec / res_avals. + n_dev = math.prod(mesh.shape[a] for a in FE) + w_av = jax.tree.map( + lambda sh, sp, d: jax.ShapeDtypeStruct(sh, d, sharding=ns(sp)), + chunk_shapes(scfg, ch), + self.wspec, + leaf_dtype_tree(scfg, ch, "compute"), + is_leaf=_is_shape, + ) + x_av = jax.ShapeDtypeStruct( + self.tok_aval.shape if ch.first else self.act_aval.shape, + jnp.int32 if ch.first else cfg.dtype, + sharding=ns(x_spec), + ) + seed_av = jax.ShapeDtypeStruct((), jnp.int32, sharding=ns(scalar)) + jax.eval_shape( + jax.shard_map( + fwd_body, mesh=mesh, in_specs=(self.wspec, x_spec, scalar), out_specs=(act, P(FE)), check_vma=False + ), + w_av, + x_av, + seed_av, + ) + res_spec = tuple(P(FE, *([None] * len(r.shape))) for r in saved["local"]) + self.res_spec, self.n_res = res_spec, len(res_spec) + self.res_avals = tuple( + jax.ShapeDtypeStruct((n_dev, *r.shape), r.dtype, sharding=ns(sp)) for r, sp in zip(saved["local"], res_spec) + ) + self.res_bytes = sum(math.prod(r.shape) * jnp.dtype(r.dtype).itemsize for r in saved["local"]) + + def bwd_core(w, x, res, dy, seed): + wl, h, wd = primals_of(w, x) + prim = jax.tree_util.tree_leaves((wl, wd)) + # the accumulating backwards (with_dw0) hand the step accumulator's blocks in through _DW0; the first + # backward starts from zeros + accl = jax.tree_util.tree_leaves(acc_starts(wl, _DW0.get())) + leaves = [] + for s_ in saved["src"]: + leaves.append( + { + "w": lambda: prim[s_[1]], + "h": lambda: h, + "x": lambda: x, + "seed": lambda: seed, + "acc": lambda: accl[s_[1]], + "r": lambda: res[s_[1]][0], + }[s_[0]]() + ) + vjp = jax.tree_util.tree_unflatten(saved["treedef"], leaves) + dwl, dh, dwd, daccs = vjp(dy) + dwl = list(dwl) + if acc_own: + # the routed experts' accumulated dW left through the starts' cotangents (an accumulator of its own + # dtype: tokamax_gmm's dw32); in the compute dtype it is rhs's cotangent already + dwl = [put_routed(dwl[l], daccs[l]) for l in range(self.n)] + dw = stack_dw(dwl, list(dwd)) + if ch.first: + dw.update(embed_grad(w, x, dh, scfg)) + return None, dw + return dh, dw + + elif not ch.last: + + def fwd_body(w, x, seed): + h = embed(w, x, scfg) if ch.first else x + y, hs = run_layers(w, h, seed, save=True) + hs = hs if ch.first else hs[1:] + return y, tuple(hs) + + if not ch.last: + self._fwd_body = fwd_body + self.fwd = jax.jit( + _named(sm(fwd_body, in_specs=(self.wspec, x_spec, scalar), out_specs=(act, res_spec)), f"fwd_c{ch.index}"), + in_shardings=(jax.tree.map(ns, self.wspec, is_leaf=_is_spec), ns(x_spec), ns(scalar)), + out_shardings=(ns(act), tuple(ns(r) for r in res_spec)), + compiler_options=self._copts, + ) + + def bwd_core_recompute(w, x, res, dy, seed): + hs = list(res) if ch.first else [x] + list(res) + # The stacked expert weights are closed over, not differentiated: each + # layer's gradient comes out as its slice's (named_gmm's stacked). + st = experts_of(w["layers"]) if self.n else None + wd = dense_weights(w) + if self.split and acc_own: + # the accumulator starts are primals (tokamax_gmm's dw32): the step accumulator's blocks (with_dw0's + # _DW0) or zeros, traced here so their cotangents -- both halves' dW accumulated -- come out of the VJP + wl0 = [layer_weights(w["layers"], l, ch.kinds) for l in range(self.n)] + + def run_acc(wl, h, wd, accs): + with _context(_DW0, accs): + return split_run(wl, h, seed, st, wd) + + _, vjp = jax.vjp(run_acc, wl0, hs[0], wd, acc_starts(wl0, _DW0.get())) + dws, dy, dwd, daccs = vjp(dy) + dws = [put_routed(dws[l], daccs[l]) for l in range(self.n)] + elif self.split: + _, vjp = jax.vjp( + lambda wl, h, wd: split_run(wl, h, seed, st, wd), + [layer_weights(w["layers"], l, ch.kinds) for l in range(self.n)], + hs[0], + wd, + ) + dws, dy, dwd = vjp(dy) + else: + # MoE layers' inputs follow the dense layers' in hs + dws, dwd = [None] * self.n, [None] * self.nd + for l in reversed(range(self.n)): + f = functools.partial( + layer_fwd_counts if self.counting else layer_fwd, + key=_layer_key(layer_ids[l], seed), + scfg=scfg, + stacked=at(st, l), + aux_seqs=self.aux_seqs, + ) + if self.counting: + _, vjp, cnt = jax.vjp(f, layer_weights(w["layers"], l, ch.kinds), hs[self.nd + l], has_aux=True) + dwl, dy = vjp(dy) + dws[l] = with_counts(dwl, cnt) + elif acc_own: + # the accumulator starts are primals (tokamax_gmm's dw32): the step accumulator's blocks (with_dw0's + # _DW0) or zeros, traced here so their cotangents -- the accumulated values -- come out of the VJP + wl_l = layer_weights(w["layers"], l, ch.kinds) + blocks = _DW0.get() + start = (acc_starts([wl_l] * self.n) if blocks is None else blocks)[l] + + def f_acc(wl_, h_, acc_l, f=f, l=l): + with _context(_DW0, {l: acc_l}), _context(_DW0_LAYER, l): + return f(wl_, h_) + + _, vjp = jax.vjp(f_acc, wl_l, hs[self.nd + l], start) + dwl, dy, dacc = vjp(dy) + dws[l] = put_routed(dwl, dacc) + else: + with _context(_DW0_LAYER, l): # in-place dW accumulation (_DW0): this layer's blocks + _, vjp = jax.vjp(f, layer_weights(w["layers"], l, ch.kinds), hs[self.nd + l]) + dws[l], dy = vjp(dy) + for l in reversed(range(self.nd)): + _, vjp = jax.vjp(functools.partial(dense_layer_fwd, scfg=scfg), wd[l], hs[l]) + dwd[l], dy = vjp(dy) + dw = stack_dw(dws, dwd) + if ch.first: + dw.update(embed_grad(w, x, dy, scfg)) + return None, dw + return dy, dw + + if not scfg.save_residuals: + bwd_core = bwd_core_recompute + out_dx = () if ch.first else (act,) + self._bwd_core, self._new_acc, self._add_acc = bwd_core, new_acc, add_acc + # (w, x, res, dy, seed, gacc=) -> (dx, gacc + dW), in place where inplace_dw + self._bwd_acc = bwd_acc = with_dw0(bwd_core) + + def bwd_body(w, x, res, dy, seed): + dx, dw = bwd_core(w, x, res, dy, seed) + return (*(() if ch.first else (dx,)), new_acc(dw)) + + def bwda_body(w, x, res, dy, gacc, seed): + dx, acc = bwd_acc(w, x, res, dy, seed, gacc=gacc) + return (*(() if ch.first else (dx,)), acc) + + w_sh = jax.tree.map(ns, self.wspec, is_leaf=_is_spec) + g_sh = jax.tree.map(ns, self.gspec, is_leaf=_is_spec) + self._w_sh, self._g_sh, self._x_spec = w_sh, g_sh, x_spec + in_b = (self.wspec, x_spec, res_spec, act, scalar) + in_b_sh = (w_sh, ns(x_spec), tuple(ns(r) for r in res_spec), ns(act), ns(scalar)) + out_b = (*out_dx, self.gspec) + out_b_sh = (*(ns(s) for s in out_dx), g_sh) + dy_don = (() if ch.first else (3,)) + ((2,) if scfg.save_residuals else ()) + self.bwd = jax.jit( + _named(sm(bwd_body, in_specs=in_b, out_specs=out_b), f"bwd_c{ch.index}"), + in_shardings=in_b_sh, + out_shardings=out_b_sh, + donate_argnums=dy_don, + compiler_options=self._copts, + ) + self.bwda = jax.jit( + _named(sm(bwda_body, in_specs=in_b[:4] + (self.gspec, scalar), out_specs=out_b), f"bwda_c{ch.index}"), + in_shardings=in_b_sh[:4] + (g_sh, ns(scalar)), + out_shardings=out_b_sh, + donate_argnums=dy_don + (4,), + compiler_options=self._copts, + ) + else: + # MTP's positions with a token two ahead: all but each sequence's last. + mtp_denom = denom * (seq - 1) / seq + + def loss_fn(w, x, tgt, tok, seed): + h = embed(w, x, scfg) if ch.first else x + if self.counting: + y, _, counts = run_layers(w, h, seed, save=False, remat=scfg.remat_fused_last, counts=True) + else: + (y, _), counts = run_layers(w, h, seed, save=False, remat=scfg.remat_fused_last), [] + loss = head_loss(w, y, tgt, denom, scfg) + if self.mtp: + extra, cnt = mtp_loss(w, y, tok, tgt, mtp_denom, _layer_key(cfg.num_decoder_layers, seed), scfg, self.aux_seqs) + loss, counts = loss + extra, counts + [cnt] + return loss, counts + + def put_counts(dw, counts): + """The routers' bias slots of the fused chunk's gradient <- its layers' expert counts (fp32).""" + dw = dict(dw) + if self.n: + moe = dict( + dw["layers"]["moe"], + gate=dict(dw["layers"]["moe"]["gate"], bias=jnp.stack(counts[: self.n]).astype(jnp.float32)), + ) + dw["layers"] = dict(dw["layers"], moe=moe) + if self.mtp: + dw["mtp"] = dict(dw["mtp"], layer=with_counts(dw["mtp"]["layer"], counts[-1])) + return dw + + def fb_core(w, x, tgt, tok, seed): + if ch.first: + (loss, counts), dw = jax.value_and_grad(loss_fn, has_aux=True)(w, x, tgt, tok, seed) + dx = None + else: + (loss, counts), (dw, dx) = jax.value_and_grad(loss_fn, argnums=(0, 1), has_aux=True)(w, x, tgt, tok, seed) + return dx, put_counts(dw, counts) if self.counting else dw, loss + + out_dx = () if ch.first else (act,) + + def fb_with(w, x, tgt, tok, seed): + dx, dw, loss = fb_core(w, x, tgt, tok, seed) + return (*(() if ch.first else (dx,)), new_acc(dw), loss[None]) + + def fb_dx_dw(w, x, tgt, tok, seed): + dx, dw, loss = fb_core(w, x, tgt, tok, seed) + return (dx, loss), dw + + fb_acc = with_dw0(fb_dx_dw) + + def fba_with(w, x, tgt, tok, gacc, lacc, seed): + (dx, loss), acc = fb_acc(w, x, tgt, tok, seed, gacc=gacc) + return (*(() if ch.first else (dx,)), acc, lacc + loss[None]) + + # With MTP the fused programs take the tokens after the targets. + if self.mtp: + fb_body, fba_body = fb_with, fba_with + else: + + def fb_body(w, x, tgt, seed): + return fb_with(w, x, tgt, None, seed) + + def fba_body(w, x, tgt, gacc, lacc, seed): + return fba_with(w, x, tgt, None, gacc, lacc, seed) + + w_sh = jax.tree.map(ns, self.wspec, is_leaf=_is_spec) + g_sh = jax.tree.map(ns, self.gspec, is_leaf=_is_spec) + self._w_sh, self._g_sh, self._x_spec = w_sh, g_sh, x_spec + self._fb_body, self._fba_body = fb_body, fba_body + out_f = (*out_dx, self.gspec, loss_spec) + out_f_sh = (*(ns(s) for s in out_dx), g_sh, ns(loss_spec)) + tk = (tok,) * (1 + bool(self.mtp)) # the targets [, the tokens] + nt = len(tk) - 1 + self.fb = jax.jit( + _named(sm(fb_body, in_specs=(self.wspec, x_spec, *tk, scalar), out_specs=out_f), f"fb_c{ch.index}"), + in_shardings=(w_sh, ns(x_spec), *(ns(t) for t in tk), ns(scalar)), + out_shardings=out_f_sh, + donate_argnums=(1,) if not ch.first else (), + compiler_options=self._copts, + ) + self.fba = jax.jit( + _named( + sm(fba_body, in_specs=(self.wspec, x_spec, *tk, self.gspec, loss_spec, scalar), out_specs=out_f), + f"fba_c{ch.index}", + ), + in_shardings=(w_sh, ns(x_spec), *(ns(t) for t in tk), g_sh, ns(loss_spec), ns(scalar)), + out_shardings=out_f_sh, + donate_argnums=((1, 3 + nt, 4 + nt) if not ch.first else (3 + nt, 4 + nt)), + compiler_options=self._copts, + ) + + def _init_lineage(self, x_spec, denom): + """__init__'s programs for a batch-split chunk on Lineage's layers (the class docstring): global-view bodies over + the Explicit stage mesh, the decoder layers the chunk's ds_ep_lineage.Region, the embedding and the head + ds_ep's per-device code in shard_maps of their own -- with the signatures, shardings and donations of the + other chunks' fwd / bwd / bwda / fb / fba.""" + from maxtext.experimental.mpmd.jax import ds_ep_lineage # lazily: it imports this module + + ch, mesh, scfg = self.ch, self.mesh, self.scfg + ns = lambda spec: NamedSharding(mesh, spec) + sm = functools.partial(jax.shard_map, mesh=mesh, check_vma=False) + act, tok, scalar, loss_spec, res_spec = self.act_spec, self.tok_spec, P(), self.loss_spec, self.res_spec + acc_dt, c = scfg.acc_dtype, ch.index + + def region(): + """The chunk's Region, looked up when a program traces: ds_ep_lineage.region builds one per chunk structure, + mesh, capacity factor and SparseCore answer (`lineage_sc`), and with it the nested jits all its programs + share, importing Lineage then -- so a pipeline builds, and refuses what it refuses, on a MaxText without + Lineage.""" + return ds_ep_lineage.region( + scfg, ch, mesh, capacity_factor=scfg.lineage_capacity_factor, sparsecore=self.lineage_sc + ) + + def layers_vjp(w, h, remat=False): + """The chunk's decoder layers on h -> (y, their VJP: dy -> (dW 'layers', dW 'dense_layers' or None, dh)). + The routing the region hands back (its aux) is not used: no counts, no aux loss (refused above).""" + f = jax.checkpoint(region()) if remat else region() + y, vjp, _ = jax.vjp(f, w["layers"], w.get("dense_layers"), h, has_aux=True) + return y, vjp + + def with_layers(dw, dwl, dwd): + return {**dw, "layers": dwl, **({"dense_layers": dwd} if self.nd else {})} + + # At global view an accumulator is typed unreduced like the region's gradients (each device's partial, no + # leading axis), so these add each device's partial to its partial. Never jnp.stack an unreduced value here: + # at jit level jax 0.11.1 multiplies it by the unreduced axes' size product (the region concatenates its per-layer + # gradients inside a shard_map). + def new_acc(dw): + return jax.tree.map(lambda d: d.astype(acc_dt), dw) + + def add_acc(gacc, dw): + return jax.tree.map(lambda g, d: g + d.astype(acc_dt), gacc, dw) + + if ch.first: + w_e = {"token_embedder": self.wspec["token_embedder"]} + of_e = lambda w: {"token_embedder": w["token_embedder"]} + embed_sm = sm(lambda we, x: embed(we, x, scfg), in_specs=(w_e, tok), out_specs=act) + + def embed_dw(we, x, dh): + """This device's partial gradient of the embedding table (bwd_core's embedding VJP).""" + _, vjp = jax.vjp(lambda we: embed(we, x, scfg), we) + return vjp(dh)[0] + + embed_dw_sm = sm(embed_dw, in_specs=(w_e, tok, act), out_specs={"token_embedder": self.gspec["token_embedder"]}) + + w_sh = jax.tree.map(ns, self.wspec, is_leaf=_is_spec) + g_sh = jax.tree.map(ns, self.gspec, is_leaf=_is_spec) + self._w_sh, self._g_sh, self._x_spec = w_sh, g_sh, x_spec + self._new_acc, self._add_acc = new_acc, add_acc + self._bwd_acc = None # no in-place dW on Lineage's layers: the parts accumulate as core + add_acc + out_dx = () if ch.first else (act,) + if not ch.last: + + def fwd_body(w, x, seed): + del seed # Lineage routes top-k: no key + h = embed_sm(of_e(w), x) if ch.first else x + y = region()(w["layers"], w.get("dense_layers"), h)[0] + return y, ((h,) if ch.first else ()) + + def bwd_core(w, x, res, dy, seed): + del seed + _, vjp = layers_vjp(w, res[0] if ch.first else x) + dwl, dwd, dh = vjp(dy) + dw = with_layers({}, dwl, dwd) + if ch.first: + return None, {**dw, **embed_dw_sm(of_e(w), x, dh)} + return dh, dw + + def bwd_body(w, x, res, dy, seed): + dx, dw = bwd_core(w, x, res, dy, seed) + return (*(() if ch.first else (dx,)), new_acc(dw)) + + def bwda_body(w, x, res, dy, gacc, seed): + dx, dw = bwd_core(w, x, res, dy, seed) + return (*(() if ch.first else (dx,)), add_acc(gacc, dw)) + + self._fwd_body, self._bwd_core = fwd_body, bwd_core + self.fwd = jax.jit( + _named(fwd_body, f"fwd_c{c}"), + in_shardings=(w_sh, ns(x_spec), ns(scalar)), + out_shardings=(ns(act), tuple(ns(r) for r in res_spec)), + compiler_options=self._copts, + ) + in_b_sh = (w_sh, ns(x_spec), tuple(ns(r) for r in res_spec), ns(act), ns(scalar)) + out_b_sh = (*(ns(s) for s in out_dx), g_sh) + dy_don = () if ch.first else (3,) + self.bwd = jax.jit( + _named(bwd_body, f"bwd_c{c}"), + in_shardings=in_b_sh, + out_shardings=out_b_sh, + donate_argnums=dy_don, + compiler_options=self._copts, + ) + self.bwda = jax.jit( + _named(bwda_body, f"bwda_c{c}"), + in_shardings=in_b_sh[:4] + (g_sh, ns(scalar)), + out_shardings=out_b_sh, + donate_argnums=dy_don + (4,), + compiler_options=self._copts, + ) + return + head_keys = ("decoder_norm", "logits_dense") + + def head(wh, y, tgt): + """This device's loss partial (head_loss), its partial gradient of the head and the loss's dy of its rows.""" + loss, vjp = jax.vjp(lambda wh, y: head_loss(wh, y, tgt, denom, scfg), wh, y) + dwh, dy = vjp(jnp.ones_like(loss)) + return loss[None], dwh, dy + + head_sm = sm( + head, + in_specs=({k: self.wspec[k] for k in head_keys}, act, tok), + out_specs=(loss_spec, {k: self.gspec[k] for k in head_keys}, act), + ) + + def fb_core(w, x, tgt, seed): + """The fused last chunk: the layers' forward (recomputed in their backward under remat_fused_last, as + run_layers' remat), the head, then the layers' VJP of the head's dy.""" + del seed + h = embed_sm(of_e(w), x) if ch.first else x + y, vjp = layers_vjp(w, h, remat=scfg.remat_fused_last) + loss, dwh, dy = head_sm({k: w[k] for k in head_keys}, y, tgt) + dwl, dwd, dh = vjp(dy) + dw = with_layers(dwh, dwl, dwd) + if ch.first: + return None, {**dw, **embed_dw_sm(of_e(w), x, dh)}, loss + return dh, dw, loss + + def fb_body(w, x, tgt, seed): + dx, dw, loss = fb_core(w, x, tgt, seed) + return (*(() if ch.first else (dx,)), new_acc(dw), loss) + + def fba_body(w, x, tgt, gacc, lacc, seed): + dx, dw, loss = fb_core(w, x, tgt, seed) + return (*(() if ch.first else (dx,)), add_acc(gacc, dw), lacc + loss) + + self._fb_body, self._fba_body = fb_body, fba_body + out_f_sh = (*(ns(s) for s in out_dx), g_sh, ns(loss_spec)) + self.fb = jax.jit( + _named(fb_body, f"fb_c{c}"), + in_shardings=(w_sh, ns(x_spec), ns(tok), ns(scalar)), + out_shardings=out_f_sh, + donate_argnums=(1,) if not ch.first else (), + compiler_options=self._copts, + ) + self.fba = jax.jit( + _named(fba_body, f"fba_c{c}"), + in_shardings=(w_sh, ns(x_spec), ns(tok), g_sh, ns(loss_spec), ns(scalar)), + out_shardings=out_f_sh, + donate_argnums=(1, 3, 4) if not ch.first else (3, 4), + compiler_options=self._copts, + ) + + # ---------------------------------------------- parts and the composer + def part(self, kind, *, stash=None, acc=False, other=None, leaves=None, rs_self=None, self_leaves=None, pin=None): + """One `Part` of this chunk's work on its stage (cached), for `compose`: + + 'F' forward (w, x, seed) -> (y, res[, stash]) + self_leaves: the chunk's first forward with part of its own + gather folded in, as fwd_self_prefetch: + (w_rest, x, seed, storage_leaves) -> (y, res[, stash], compute_leaves) + pin: prefetch pins, ((point, layer, chunk, leaf id), ...): the + leaves this forward gathers (self_leaves) or a gather part of its + program gathers, tied to points of its layers (PIN_POINTS; a remat + forward only: a stash forward runs its layers inside jax.vjp, and + every other kind refuses a pin) + 'B' backward (w, x, res[, stash], dy[, gacc], seed) -> (dx?, gacc) + rs_self=n (with acc): the chunk's last backward with its own + reduce-scatter, as bwda_reduce_self: + (..., gacc, seed, n other sumsqs) -> (dx?, grads, stage sumsq) + 'A' fused last chunk (w, x, tgt[, gacc, lacc], seed) -> (dx?, gacc, loss) + 'I' a middle chunk's split backward, its input gradient (`build_split`): + (w, x, res, dy, seed) -> (dx, crossing), feeding either W; acc: + the accumulating trace's own I, where in-place dW cuts another + (Split.i_acc; else the same part as acc False's) + 'W' ... its weight gradients (crossing, kept[, gacc]) -> (gacc,) + rs_self=n (with acc), as 'B''s: (..., gacc, n other sumsqs) -> (grads, stage sumsq) + -- the last chunk's, of its layers' leaves (`build_split_last`): + (crossing, kept[, gw]) -> (gw,), gw a tuple of those leaves + 'AI' the fused last chunk split (`build_split_last`): its forward, + head, loss and input gradient, the weight gradients of its other + leaves (gk, a tuple of them) -- (w, x, tgt[, tok][, gk, lacc], + seed) -> (dx?, gk, loss, crossing) + 'G' all-gather `leaves` of chunk `other` (storage leaves,) -> (compute leaves,) + 'R' reduce-scatter `leaves` of `other` (gacc leaves,) -> (grads, sumsq) + + `stash` is a STASH_POLICIES name (None or 'none': recompute -- the bodies + of the fixed programs); `acc` accumulates into a donated gacc (bwda / + fba); `leaves=None` is all of them. Donations are the fixed programs': + dy (but chunk 0's), gacc, lacc, the last chunk's x, the stash, the saved + set (saved residuals), the gacc leaves reduced -- never a forward's x, + which its backward still needs; beside a forward, in an F&B pair, a + backward's dy, stash and saved set are not (`composed_donations`), and + its outputs come first (`composed_order`). An I donates what its B does + but an argument W reads (Split.i_donate), a W the accumulator only; an AI + what its A does (x, gk, lacc), but an argument W reads. + + A Lineage chunk's F, B and A parts are `global_view` (the class + docstring), with no stash and no pin; the gather its self_leaves forward + folds in and the reduce-scatter of its rs_self backward run in shard_maps + inside their bodies. + """ + stash = None if stash == "none" else stash + key = ( + kind, + stash, + acc, + other, + None if leaves is None else tuple(leaves), + rs_self, + None if self_leaves is None else tuple(self_leaves), + tuple(map(tuple, pin)) if pin else None, + ) + if key not in self._parts: + self._parts[key] = self._make_part(*key) + return self._parts[key] + + def _make_part(self, kind, stash, acc, other, leaves, rs_self, self_leaves, pin=None): + if pin and self.lineage: + raise ValueError( + f"chunk {self.ch.index}: prefetch pins tie points of ds_ep's own layers (hn / xs / y), and a " + "batch-split chunk on Lineage's layers (batch_split_impl 'lineage') has none: no pin " + "(ds_ep_pipeline --prefetch-pin off)" + ) + if pin and kind != "F": + raise ValueError(f"prefetch pins tie points of a forward ('F'), not of a {kind!r} part") + if pin and stash is not None: + raise ValueError( + f"prefetch pins tie points of a remat forward (its layers traced as they run), not of one in " + f"stash mode {stash!r}: a stash forward runs each layer inside jax.vjp" + ) + ch, mesh, scfg = self.ch, self.mesh, self.scfg + ns = lambda spec: NamedSharding(mesh, spec) + lv = lambda t: jax.tree.leaves(t, is_leaf=_is_spec) + act, first, c = self.act_spec, ch.first, ch.index + dt, mode = scfg.model.dtype, scfg.fsdp_collectives + sizes = {"fsdp": scfg.fsdp, "expert": scfg.ep} + out_dx = () if first else (act,) + with_dx = lambda d: () if first else (d,) + if kind in ("G", "R"): + # oc: the plain compute specs the bodies read; ow, og: the gathered + # leaves' and the gacc leaves' boundary specs (typed under 'explicit') + os_, oc, ow, og = ( + lv(f(other)) + for f in ( + chunk_storage_specs, + chunk_compute_specs, + lambda o: chunk_wc_specs(scfg, o), + lambda o: acc_specs(scfg, o), + ) + ) + idx = tuple(range(len(os_))) if leaves is None else leaves + os_, oc, ow, og = ([x[i] for i in idx] for x in (os_, oc, ow, og)) + ok = [count_leaves(other)[i] for i in idx] + tag = "" if leaves is None else f"p{idx[0]}" + if kind == "G": + odt = leaf_dtypes(scfg, other, "compute") + odt = [odt[i] for i in idx] + + def gather(st): + return ([_gather_leaf(a, s_, c_, d_, mode, self._ag) for a, s_, c_, d_ in zip(st, os_, oc, odt)],) + + return Part( + f"_ag{other.index}{tag}", + gather, + (os_,), + (ow,), + ([ns(x) for x in os_],), + ([ns(x) for x in ow],), + gathers=tuple((other.index, i) for i in idx), + ) + + def reduce(go): + return scatter_tree(list(go), os_, oc, scfg.rs_dtype, sizes, mode, counts=ok, **self._rs) + + return Part( + f"_rs{other.index}{tag}", + reduce, + (og,), + (os_, P()), + ([ns(x) for x in og],), + ([ns(x) for x in os_], ns(P())), + donate=(0,), + ) + if kind == "A": + if not ch.last or stash is not None: + raise ValueError(f"'A' is the last chunk's fused forward + backward (chunk {c}, stash {stash})") + nt = int(bool(self.mtp)) # MTP: the tokens after the targets + in_specs = (self.wspec, self._x_spec) + (self.tok_spec,) * (1 + nt) + in_sh = (self._w_sh, ns(self._x_spec)) + (ns(self.tok_spec),) * (1 + nt) + out = (*out_dx, self.gspec, self.loss_spec) + out_sh = (*(ns(s) for s in out_dx), self._g_sh, ns(self.loss_spec)) + x_don = () if first else (1,) + if not acc: + return Part( + f"fb_c{c}", self._fb_body, in_specs + (P(),), out, in_sh + (ns(P()),), out_sh, x_don, global_view=self.lineage + ) + return Part( + f"fba_c{c}", + self._fba_body, + in_specs + (self.gspec, self.loss_spec, P()), + out, + in_sh + (self._g_sh, ns(self.loss_spec), ns(P())), + out_sh, + x_don + (3 + nt, 4 + nt), + global_view=self.lineage, + ) + if kind in ("I", "W", "AI"): + extra = [n for n, v in (("other", other), ("leaves", leaves), ("self_leaves", self_leaves)) if v is not None] + if kind == "AI" or (kind == "W" and ch.last): + return self._split_last_part(kind, stash, acc, rs_self=rs_self, extra=extra) + return self._split_part(kind, stash, acc, rs_self=rs_self, extra=extra) + if ch.last: + raise ValueError(f"chunk {c} is the last: its forward and backward are one part, 'A'") + st = None if stash is None else self.build_stash(stash) + sfx = "" if st is None else "_st" + st_in = () if st is None else (st.specs,) + st_sh = () if st is None else (tuple(ns(s) for s in st.specs),) + pin = tuple(pin or ()) + if any(pt not in PIN_POINTS or not 0 <= layer < self.n for pt, layer, _, _ in pin): + raise ValueError( + f"chunk {c} ({self.n} MoE layer(s)): prefetch pins want a point of {PIN_POINTS} in one of " + f"its MoE layers (a dense layer has none), got {pin}" + ) + if kind == "F": + body = self._fwd_body if st is None else st.fwd_body + out = (act, self.res_spec) + st_in + out_sh = (ns(act), tuple(ns(r) for r in self.res_spec)) + st_sh + if self_leaves is None: + return Part( + f"fwd_c{c}{sfx}", + body, + (self.wspec, self._x_spec, P()), + out, + (self._w_sh, ns(self._x_spec), ns(P())), + out_sh, + pins=pin, + global_view=self.lineage, + forward=True, + ) + ss, cs, ws = lv(chunk_storage_specs(ch)), lv(self.cspec), lv(self.wspec) + tdef = jax.tree.structure(self.cspec, is_leaf=_is_spec) + idx = self_leaves + rest = tuple(i for i in range(len(cs)) if i not in idx) + # the pins of this forward's own gathered leaves (the rest are its program's gather parts') + mine = {(cc, i): (pt, layer) for pt, layer, cc, i in pin if cc == c and i in idx} + + cdt = leaf_dtypes(scfg, ch, "compute") + + def gather_own(stl): + return [_gather_leaf(a, ss[i], cs[i], cdt[i], mode, self._ag) for a, i in zip(stl, idx)] + + if self.lineage: # a global-view body: the gather, per-device code, in a shard_map of its own + gather_own = jax.shard_map( + gather_own, mesh=mesh, in_specs=([ss[i] for i in idx],), out_specs=[ws[i] for i in idx], check_vma=False + ) + + def self_pf(w_rest, x, seed, stl): + got = gather_own(stl) + full = [None] * len(cs) + for i, v in zip(rest, w_rest): + full[i] = v + for i, v in zip(idx, got): + full[i] = v + if not mine: + return (*body(jax.tree.unflatten(tdef, full), x, seed), got) + regs = {} + for k, i in enumerate(idx): + if (c, i) in mine: + regs.setdefault(mine[(c, i)], []).append([(c, i), got[k]]) + with _pinned(regs, pin): + ys = body(jax.tree.unflatten(tdef, full), x, seed) + for lst in regs.values(): # the entries the barriers updated in place + for (_, i), v in lst: + got[idx.index(i)] = v + return (*ys, got) + + return Part( + f"fwd_c{c}{sfx}_agself", + self_pf, + ([ws[i] for i in rest], self._x_spec, P(), [ss[i] for i in idx]), + out + ([ws[i] for i in idx],), + ([ns(ws[i]) for i in rest], ns(self._x_spec), ns(P()), [ns(ss[i]) for i in idx]), + out_sh + ([ns(ws[i]) for i in idx],), + pins=pin, + global_view=self.lineage, + forward=True, + ) + if kind != "B": + raise ValueError(f"unknown part kind {kind!r}") + core = self._bwd_core if st is None else st.bwd_core + k = 4 + len(st_in) # w, x, res, [stash,] dy + in_specs = (self.wspec, self._x_spec, self.res_spec) + st_in + (act,) + in_sh = (self._w_sh, ns(self._x_spec), tuple(ns(r) for r in self.res_spec)) + st_sh + (ns(act),) + # the saved set, the stash and dy (but chunk 0's): what a forward returns too, arrays of its outputs' shapes + # (Part.fwd_like; gacc, where the part takes one, is donated after them) + donate = ((2,) if scfg.save_residuals else ()) + tuple(range(3, k - 1)) + (() if first else (k - 1,)) + out = (*out_dx, self.gspec) + out_sh = (*(ns(s) for s in out_dx), self._g_sh) + if not acc: + if rs_self is not None: + raise ValueError("rs_self folds into an accumulating backward (acc=True)") + + def bwd(*a): + dx, dw = core(*a[:k], a[k]) + return (*with_dx(dx), self._new_acc(dw)) + + return Part( + f"bwd_c{c}{sfx}", + bwd, + in_specs + (P(),), + out, + in_sh + (ns(P()),), + out_sh, + donate, + global_view=self.lineage, + backward=True, + fwd_like=donate, + ) + acc_core = self._bwd_acc if st is None else None + + def core_acc(a): + """(dx, gacc + dW) of the part's arguments: in place where inplace_dw (not + a stash backward's core).""" + if acc_core is not None: + return acc_core(*a[:k], a[k + 1], gacc=a[k]) + dx, dw = core(*a[:k], a[k + 1]) + return dx, self._add_acc(a[k], dw) + + if rs_self is None: + + def bwda(*a): + dx, acc = core_acc(a) + return (*with_dx(dx), acc) + + return Part( + f"bwda_c{c}{sfx}", + bwda, + in_specs + (self.gspec, P()), + out, + in_sh + (self._g_sh, ns(P())), + out_sh, + donate + (k,), + global_view=self.lineage, + backward=True, + fwd_like=donate, + ) + ss, cs = chunk_storage_specs(ch), chunk_compute_specs(ch) + if not self.lineage: + + def bwda_rs(*a): + dx, acc = core_acc(a) + g, sq = scatter_tree(acc, ss, cs, scfg.rs_dtype, sizes, mode, counts=count_mask(ch), **self._rs) + return (*with_dx(dx), g, sq + sum(a[k + 2])) + + else: + # A global-view body: the accumulate at global view (typed unreduced), the reduce-scatter -- per-device + # code, as the R parts' -- in a shard_map of its own. + def scatter(gacc, sqs): + g, sq = scatter_tree(gacc, ss, cs, scfg.rs_dtype, sizes, mode, counts=count_mask(ch), **self._rs) + return g, sq + sum(sqs) + + scatter = jax.shard_map( + scatter, mesh=mesh, in_specs=(self.gspec, [P()] * rs_self), out_specs=(ss, P()), check_vma=False + ) + + def bwda_rs(*a): + dx, acc = core_acc(a) + return (*with_dx(dx), *scatter(acc, list(a[k + 2]))) + + return Part( + f"bwda_c{c}{sfx}_rsself", + bwda_rs, + in_specs + (self.gspec, P(), [P()] * rs_self), + (*out_dx, ss, P()), + in_sh + (self._g_sh, ns(P()), [ns(P())] * rs_self), + (*(ns(s) for s in out_dx), jax.tree.map(ns, ss, is_leaf=_is_spec), ns(P())), + donate + (k,), + global_view=self.lineage, + backward=True, + fwd_like=donate, + ) + + def _split_part(self, kind, stash, acc, *, rs_self=None, extra=()): + """`_make_part`'s 'I' and 'W': the halves of `build_split(acc)` as parts. I evaluates the split's I jaxpr on + its arguments' leaves and returns dx and the crossing set, each value with a leading per-device axis -- one part + for both W's, unless in-place dW cut another I for the accumulating one (Split.i_acc); W evaluates its W jaxpr + on the crossing set, the kept leaves (and an in-place W the accumulator's), adds the accumulator where it + accumulates (Split.w_adds), and returns the accumulator -- with rs_self, reduce-scattered as bwda_reduce_self's. + Each evaluates its jaxpr's equations as they are, under the part's shard_map (stage_ad.inline_eval), and closes + over the constants it reads (stage_ad.Const).""" + c, mesh, scfg, ch = self.ch.index, self.mesh, self.scfg, self.ch + if stash is not None: + raise ValueError( + f"chunk {c}: the split backward ({kind!r}) cuts the recompute backward, not one in stash mode {stash!r}: a " + "split chunk's microbatches run without a stash" + ) + if extra: + raise ValueError(f"part {kind!r} takes acc (and a W's rs_self) only, not {extra}") + if rs_self is not None and (kind == "I" or not acc): + raise ValueError(f"rs_self folds into an accumulating W (acc=True), not {'an I' if kind == 'I' else 'a first W'}") + sp = self.build_split(acc) + if kind == "I" and acc and not sp.i_acc: + return self.part("I") # the accumulating W reads the first write's I + + def ns(spec): + return NamedSharding(mesh, spec) + + act = self.act_spec + cross_sh = tuple(ns(s) for s in sp.crossing_specs) + if kind == "I": + i_jaxpr, i_src = sp.i_jaxpr, sp.i_src + i_consts = list(getattr(i_jaxpr, "consts", ())) + + def bwdi(*a): + flat = jax.tree.leaves(a) + outs = stage_ad.inline_eval(i_jaxpr, i_consts, *[flat[s] if isinstance(s, int) else s.value for s in i_src]) + return outs[0], tuple(v[None] for v in outs[1:]) + + return Part( + f"bwdi_c{c}", + bwdi, + (self.wspec, self._x_spec, self.res_spec, act, P()), + (act, sp.crossing_specs), + (self._w_sh, ns(self._x_spec), tuple(ns(r) for r in self.res_spec), ns(act), ns(P())), + (ns(act), cross_sh), + sp.i_donate, + backward=True, + fwd_like=sp.i_donate, + ) + w_jaxpr, w_src = sp.w_jaxpr, sp.w_src + w_consts = list(getattr(w_jaxpr, "consts", ())) + gtree = jax.tree.structure(self.gspec, is_leaf=_is_spec) + + def w_core(cross, kept, gacc=None): + """The accumulator, from the crossing set, the kept leaves and (acc) the accumulator: the first write's W plus + the accumulator, leaf by leaf, as bwda's add_acc adds it to new_acc's (w_adds), or in-place dW's own W.""" + vals = {"kept": kept, "gacc": jax.tree.leaves(gacc)} + ins = [v[0] for v in cross] + [s.value if isinstance(s, stage_ad.Const) else vals[s[0]][s[1]] for s in w_src] + out = jax.tree.unflatten(gtree, stage_ad.inline_eval(w_jaxpr, w_consts, *ins)) + return jax.tree.map(lambda g, d: g + d, gacc, out) if sp.w_adds else out + + in_specs = (sp.crossing_specs, sp.kept_specs) + in_sh = (cross_sh, tuple(ns(s) for s in sp.kept_specs)) + # (the crossing set is not donated: no output of W has a crossing value's shape to alias, and a step drops it + # once W is enqueued, so it is freed when W ends either way) + if not acc: + + def bwdw(cross, kept): + return (w_core(cross, kept),) + + return Part(f"bwdw_c{c}", bwdw, in_specs, (self.gspec,), in_sh, (self._g_sh,), backward=True) + if rs_self is None: + + def bwdwa(cross, kept, gacc): + return (w_core(cross, kept, gacc),) + + return Part( + f"bwdwa_c{c}", + bwdwa, + in_specs + (self.gspec,), + (self.gspec,), + in_sh + (self._g_sh,), + (self._g_sh,), + (2,), + backward=True, + ) + ss, cs = chunk_storage_specs(ch), chunk_compute_specs(ch) + sizes = {"fsdp": scfg.fsdp, "expert": scfg.ep} + + def bwdwa_rs(cross, kept, gacc, sqs): + g, sq = scatter_tree( + w_core(cross, kept, gacc), + ss, + cs, + scfg.rs_dtype, + sizes, + scfg.fsdp_collectives, + counts=count_mask(ch), + **self._rs, + ) + return g, sq + sum(sqs) + + return Part( + f"bwdwa_c{c}_rsself", + bwdwa_rs, + in_specs + (self.gspec, [P()] * rs_self), + (ss, P()), + in_sh + (self._g_sh, [ns(P())] * rs_self), + (jax.tree.map(ns, ss, is_leaf=_is_spec), ns(P())), + (2,), + backward=True, + ) + + def _split_last_part(self, kind, stash, acc, *, rs_self=None, extra=()): + """`_make_part`'s 'AI' and the last chunk's 'W': the halves of `build_split_last(acc)` as parts. AI evaluates the + split's I jaxpr on its arguments' leaves and returns dx (but a first chunk's), the accumulator's kept part (gk, a + tuple of its leaves in leaf order), the loss and the crossing set, each crossing value with a leading per-device + axis -- accumulating, with gk and the loss accumulator added to its outputs where the split adds them + (Split.w_adds), else read by the jaxpr itself (in-place dW: the cut of fba's own trace). W evaluates its W jaxpr + on the crossing set, the kept arguments (and an in-place W the accumulator's deferred part, gw, a tuple of those + leaves), adds gw where the split adds it, and returns gw. Each closes over the constants it reads + (stage_ad.Const). Neither folds a reduce-scatter in: the two parts merge before the stage's reduce.""" + c, mesh, ch = self.ch.index, self.mesh, self.ch + if stash is not None: + raise ValueError(f"chunk {c}: the fused last chunk keeps nothing, so no stash mode ({kind!r}, {stash!r})") + if extra: + raise ValueError(f"part {kind!r} of the last chunk takes acc only, not {extra}") + if rs_self is not None: + raise ValueError( + f"chunk {c}: the split last chunk's {kind!r} folds no reduce-scatter (rs_self): its accumulator's two " + "parts merge before the stage's reduce" + ) + sp = self.build_split_last(acc) + + def ns(spec): + return NamedSharding(mesh, spec) + + gl = jax.tree.leaves(self.gspec, is_leaf=_is_spec) + gk_specs, gw_specs = tuple(gl[i] for i in sp.i_leaves), tuple(gl[i] for i in sp.w_leaves) + gk_sh, gw_sh = tuple(ns(x) for x in gk_specs), tuple(ns(x) for x in gw_specs) + cross_sh = tuple(ns(x) for x in sp.crossing_specs) + if kind == "AI": + nt, nk, n_dx = int(bool(self.mtp)), len(sp.i_leaves), 0 if ch.first else 1 + i_jaxpr, i_src = sp.i_jaxpr, sp.i_src + i_consts = list(getattr(i_jaxpr, "consts", ())) + adds = acc and sp.w_adds + + def fbi(*a): + flat = jax.tree.leaves(a[: 3 + nt] + a[-1:] if adds else a) # (w, x, tgt[, tok], seed): the first write's + outs = stage_ad.inline_eval(i_jaxpr, i_consts, *[flat[s] if isinstance(s, int) else s.value for s in i_src]) + dx, gk, loss, cross = outs[:n_dx], outs[n_dx : n_dx + nk], outs[n_dx + nk], outs[n_dx + nk + 1 :] + if adds: + gk, loss = [g + d for g, d in zip(a[3 + nt], gk, strict=True)], a[4 + nt] + loss + return (*dx, tuple(gk), loss, tuple(v[None] for v in cross)) + + tk = (self.tok_spec,) * (1 + nt) + out_dx = () if ch.first else (self.act_spec,) + return Part( + f"fb{'a' if acc else ''}i_c{c}", + fbi, + (self.wspec, self._x_spec, *tk) + ((gk_specs, self.loss_spec) if acc else ()) + (P(),), + (*out_dx, gk_specs, self.loss_spec, sp.crossing_specs), + (self._w_sh, ns(self._x_spec), *(ns(t) for t in tk)) + + ((gk_sh, ns(self.loss_spec)) if acc else ()) + + (ns(P()),), + (*(ns(x) for x in out_dx), gk_sh, ns(self.loss_spec), cross_sh), + sp.i_donate, + ) + w_jaxpr, w_src = sp.w_jaxpr, sp.w_src + w_consts = list(getattr(w_jaxpr, "consts", ())) + + def w_core(cross, kept, gw=None): + """The accumulator's deferred part, from the crossing set, the kept leaves and (acc) that part: the first + write's W plus it, leaf by leaf (w_adds), or in-place dW's own W.""" + vals = {"kept": kept, "gacc": gw} + ins = [v[0] for v in cross] + [s.value if isinstance(s, stage_ad.Const) else vals[s[0]][s[1]] for s in w_src] + out = stage_ad.inline_eval(w_jaxpr, w_consts, *ins) + return tuple(g + d for g, d in zip(gw, out, strict=True)) if gw is not None and sp.w_adds else tuple(out) + + in_specs = (sp.crossing_specs, sp.kept_specs) + in_sh = (cross_sh, tuple(ns(x) for x in sp.kept_specs)) + if not acc: + + def bwdw(cross, kept): + return (w_core(cross, kept),) + + return Part(f"bwdw_c{c}", bwdw, in_specs, (gw_specs,), in_sh, (gw_sh,), backward=True) + + def bwdwa(cross, kept, gw): + return (w_core(cross, kept, gw),) + + return Part( + f"bwdwa_c{c}", bwdwa, in_specs + (gw_specs,), (gw_specs,), in_sh + (gw_sh,), (gw_sh,), (2,), backward=True + ) + + def program(self, desc): + """The jitted program composing the parts `desc` names (cached by desc). + + `desc` is a tuple of `pdesc(kind, **part kwargs)`. The program is named + after its first part, with gather / reduce-scatter parts appended as the + fixed programs name them (fwd_c0_ag1p3, bwda_c1_st_rs3) and any other part + joined by '__' (an F&B pair: fwd_c2__bwda_c0_st). + + A remat backward hosting a reduce-scatter (B + R) is the fixed program + `bwd_reduce`: the same values either way, but that one traces the + reduce-scatter between the backward and its accumulate where compose + traces it after, so only it lowers to that program byte for byte. + Every other remat descriptor composes to its fixed program's text. A + Lineage chunk's B + R composes (a mixed program: `compose`), and so do its + fixed fused programs (fwd_prefetch, ...), from the same parts. + """ + if desc not in self._programs and self._is_bwd_reduce(desc) and not self.lineage: + (_, b), (_, r) = desc + r = dict(r) + self._programs[desc] = self.bwd_reduce(r["other"], accumulate=dict(b).get("acc", False), leaves=r.get("leaves")) + if desc not in self._programs: + parts = [] + for kind, kw in desc: + kw = dict(kw) + pr = kw.pop("peer", self) + if pr.mesh != self.mesh: + raise ValueError(f"chunks {self.ch.index} and {pr.ch.index} are on different meshes") + parts.append(pr.part(kind, **kw)) + name = parts[0].name + "".join(p.name if p.name.startswith("_") else "__" + p.name for p in parts[1:]) + self._programs[desc] = compose( + self.mesh, + parts, + name, + keep_barriers=self.scfg.batch_split, + compiler_options=self._copts if self.lineage else None, + ) + return self._programs[desc] + + @staticmethod + def _is_bwd_reduce(desc): + """Is `desc` a remat backward of this chunk (bwd / bwda) + a reduce-scatter?""" + return ( + len(desc) == 2 + and desc[0][0] == "B" + and desc[1][0] == "R" + and {k for k, _ in desc[0][1]} <= {"acc"} + and {k for k, _ in desc[1][1]} <= {"other", "leaves"} + ) + + # ------------------------------------------------------------- stash + def build_stash(self, policy): + """The `Stash` programs of `policy`, a STASH_POLICIES name (cached). + + Per layer, the forward takes `jax.vjp` of `jax.checkpoint(layer_fwd, + policy)` and closure-converts the vjp (stage_ad.closure_convert_all), so + everything its backward reads is an explicit constant. Constants that + are the layer's weights, its input or the seed are supplied again by the + backward from its own arguments, and those that are not traced (the + splash mask tables) are kept as they are; the rest -- exactly the named + values the policy saves, or under 'all' every residual -- leave the + shard_map as the stash. The backward evaluates the converted vjps in + reverse layer order (recomputing only what the policy did not save), then + chunk 0's embedding vjp, as `bwd_core` does: dx and every dW are today's. + + Bit for bit so (ds_ep_test.StashAndCompose) for one-layer chunks as XLA + compiles them by default, but for a chunk of two or more layers only with + xla_allow_excess_precision off: by default XLA may keep a fused bf16 + intermediate in f32, and it fuses the stash and the recompute backward of + such a chunk differently -- on CPU every dW leaf and dx then differ in + about the last bf16 bit. A pipeline test that wants stash and remat + bitwise equal uses one-layer chunks, or compiles both with that option. + ('all' is within one bf16 rounding, not bitwise: see the test.) + + The constants' layout and the converted vjps come from ONE eager + `jax.eval_shape` of the forward, here, before anything is jitted: the + backward can then be traced on its own (precompile traces in threads), + and every later trace of the forward only checks the layout is the same. + """ + if policy in self._stash: + return self._stash[policy] + if policy not in STASH_POLICIES or policy == "none": + raise ValueError( + f"stash policy must be one of {[k for k in STASH_POLICIES if k != 'none']}, " + f"got {policy!r} (none: the recompute programs)" + ) + if self.lineage: + raise ValueError( + f"stash policy {policy!r}: a batch-split chunk on Lineage's layers (batch_split_impl " + "'lineage') runs them in one custom VJP whose residuals are Lineage's own, which a stash " + "policy cannot name (batch_split takes the recompute programs only)" + ) + if self.scfg.batch_split: + raise ValueError( + f"stash policy {policy!r}: a stash forward runs each layer inside jax.vjp, a batch-split " + "chunk interleaves its layers' halves (batch_split takes the recompute programs only)" + ) + if self.scfg.save_residuals: + raise ValueError( + f"stash policy {policy!r}: save_residuals already keeps every residual of the chunk's " + "forward (its programs return the VJP's leaves, not the stash's layer inputs)" + ) + if self.nd: + raise ValueError( + f"stash policy {policy!r}: chunk {self.ch.index} holds dense layers, which the stash programs " + "do not build (they take MoE layers only: a pipeline with dense layers runs no stash policy)" + ) + ch, mesh, scfg, n = self.ch, self.mesh, self.scfg, self.n + if ch.last: + raise ValueError(f"chunk {ch.index} is the last: its forward and backward are one program") + if self.counting or self.aux_seqs: + # its layers below run layer_fwd without the counts and without the aux loss riding their outputs + raise NotImplementedError( + f"chunk {ch.index}: stash mode runs MoE layers without the routed-bias update and " + f"the sequence-wise aux loss only (counting {self.counting}, aux loss " + f"{bool(self.aux_seqs)}): use the recompute programs (a schedule without a stash)" + ) + ns = lambda spec: NamedSharding(mesh, spec) + pol = stash_policy(policy) + known = [None] * n # per layer: (plan, converted vjp, literals, stash avals) + + def layer(l, wl, h, seed): + lid = ch.layers[l] + f = lambda wl_, h_: layer_fwd(wl_, h_, _layer_key(lid, seed), scfg) + if pol is not None: + f = jax.checkpoint(f, policy=pol, prevent_cse=False) + y, vjp = jax.vjp(f, wl, h) + conv, consts = stage_ad.closure_convert_all(vjp, jnp.zeros_like(y)) + wflat = jax.tree.leaves(wl) + plan, res, literals = [], [], [] + for cst in consts: + i = next((i for i, p in enumerate(wflat) if cst is p), None) + if i is not None: + hit = ("p", i) + elif cst is h: + hit = ("x", 0) + elif cst is seed: + hit = ("s", 0) + elif not isinstance(cst, jax.core.Tracer): # a constant of the trace itself + hit = ("c", len(literals)) + literals.append(cst) + else: + j = next((j for j, r in enumerate(res) if r is cst), None) + if j is None: + j = len(res) + res.append(cst) + hit = ("r", j) + plan.append(hit) + avals = tuple((tuple(r.shape), jnp.dtype(r.dtype)) for r in res) + if known[l] is None: # the eager trace below + known[l] = (tuple(plan), conv, literals, avals) + elif (known[l][0], known[l][3]) != (tuple(plan), avals): + raise RuntimeError(f"chunk {ch.index} layer {lid}: the {policy!r} stash layout changed " "on re-trace") + return y, res + + def fwd_body(w, x, seed): + h = embed(w, x, scfg) if ch.first else x + hs, stash = [], [] + for l in range(n): + hs.append(h) + h, res = layer(l, layer_weights(w["layers"], l, ch.kinds), h, seed) + stash.extend(r[None] for r in res) + return h, tuple(hs if ch.first else hs[1:]), tuple(stash) + + def bwd_core(w, x, res, stash, dy, seed): + hs = list(res) if ch.first else [x] + list(res) + dws = [None] * n + for l in reversed(range(n)): + plan, conv, literals, _ = known[l] + src = { + "p": jax.tree.leaves(layer_weights(w["layers"], l, ch.kinds)), + "x": (hs[l],), + "s": (seed,), + "c": literals, + "r": [r[0] for r in stash[offs[l] : offs[l + 1]]], + } + dws[l], dy = conv(dy, *(src[kind][i] for kind, i in plan)) + dw = {"layers": stack_layers(dws, ch.kinds)} if n else {} # an empty chunk 0: its embedding's alone + if ch.first: + dw.update(embed_grad(w, x, dy, scfg)) + return None, dw + return dy, dw + + sds = lambda shape, dt, spec: jax.ShapeDtypeStruct(shape, dt, sharding=ns(spec)) + # the compute weights as the programs get them: cfg.dtype, but leaf_dtypes' fp32 ones (an fp32 router under + # float32_gate_logits, a Qwen model's norm scales under norm_numerics 'fp32') + w_av = jax.tree.map( + lambda s, sp, d: sds(s, d, sp), + chunk_shapes(scfg, ch), + self.wspec, + leaf_dtype_tree(scfg, ch, "compute"), + is_leaf=_is_shape, + ) + x_av = ( + sds(self.tok_aval.shape, jnp.int32, self.tok_spec) + if ch.first + else sds(self.act_aval.shape, self.act_aval.dtype, self.act_spec) + ) + jax.eval_shape( + jax.shard_map( + lambda w, x, seed: fwd_body(w, x, seed)[:2], + mesh=mesh, + in_specs=(self.wspec, self._x_spec, P()), + out_specs=(self.act_spec, self.res_spec), + check_vma=False, + ), + w_av, + x_av, + sds((), jnp.int32, P()), + ) + offs = [0] + for kn in known: + offs.append(offs[-1] + len(kn[3])) + avals = [a for kn in known for a in kn[3]] + specs = tuple(P(FE, *([None] * len(s))) for s, _ in avals) + n_dev = math.prod(mesh.shape[a] for a in FE) + nbytes = lambda avs: sum(math.prod(s) * d.itemsize for s, d in avs) + layer_bytes = tuple(nbytes(kn[3]) for kn in known) + st = Stash( + policy=policy, + specs=specs, + avals=tuple(sds((n_dev,) + s, d, sp) for (s, d), sp in zip(avals, specs)), + layer_bytes=layer_bytes, + bytes=sum(layer_bytes), + plans=tuple(kn[0] for kn in known), + fwd_body=fwd_body, + bwd_core=bwd_core, + ) + self._stash[policy] = st + self.stash_avals[policy], self.stash_bytes[policy] = st.avals, st.bytes + st.fwd = self.program((pdesc("F", stash=policy),)) + st.bwd = self.program((pdesc("B", stash=policy),)) + st.bwda = self.program((pdesc("B", stash=policy, acc=True),)) + return st + + # ------------------------------------------------------- split backward + def _part_avals(self, kind, acc=False): + """The abstract arguments of `part(kind, acc=acc)`, a tuple in its argument order of pytrees of + ShapeDtypeStructs with this chunk's shardings: 'B' (recompute: no stash) (w, x, res, dy[, gacc], seed), 'A' + (w, x, tgt[, tok][, gacc, lacc], seed) -- the weights in their compute dtypes (leaf_dtypes), the accumulator in + acc_dtype.""" + mesh, scfg, ch = self.mesh, self.scfg, self.ch + + def sds(shape, dt, spec): + return jax.ShapeDtypeStruct(shape, dt, sharding=NamedSharding(mesh, spec)) + + w = jax.tree.map( + lambda s, sp, d: sds(s, d, sp), + chunk_shapes(scfg, ch), + self.wspec, + leaf_dtype_tree(scfg, ch, "compute"), + is_leaf=_is_shape, + ) + act = sds(self.act_aval.shape, self.act_aval.dtype, self.act_spec) + tok = sds(self.tok_aval.shape, jnp.int32, self.tok_spec) + x = tok if ch.first else act + gacc = jax.tree.map(lambda s, sp: sds(s, scfg.acc_dtype, sp), acc_shapes(scfg, ch), self.gspec, is_leaf=_is_shape) + seed = sds((), jnp.int32, P()) + if kind == "B" and not ch.last: + return (w, x, tuple(self.res_avals), act) + ((gacc,) if acc else ()) + (seed,) + if kind == "A" and ch.last: + lacc = sds((scfg.fsdp * scfg.ep,), jnp.float32, self.loss_spec) + return (w, x, tok) + ((tok,) if self.mtp else ()) + ((gacc, lacc) if acc else ()) + (seed,) + raise ValueError(f"no abstract arguments for part {kind!r} of chunk {ch.index} (last {ch.last})") + + def build_split(self, acc=False): + """The `Split` of this chunk's backward for the zero-bubble schedules: its I, and the W of `acc` -- the chunk's + first gradient write (acc False) or an accumulating one (acc True) (cached). + + Traces `part('B')`, bwd's body, at its abstract arguments (`_part_avals`) to one flat per-device jaxpr + (stage_ad.trace_body: jit and remat bodies evaluated in place, an inlined remat's operands behind its + optimization barrier) and cuts it (stage_ad.split_jaxpr): I keeps dx, W computes every accumulator leaf. So I + is the forward's recompute and the input gradient -- every EP collective of the dx chain -- and W the weight + gradients' matmuls beyond them, and, under grad_reduce 'microbatch', the reduce-scatter (new_acc's); under saved + residuals the B is the VJP of the saved set (no recompute). The halves run the fused backward's equations, each + once, on the same operands: dx and every accumulator leaf are bwd's bit for bit wherever XLA compiles each + operation as it does in the fused program -- not everywhere: XLA may rewrite a division into a multiplication by + the reciprocal in one program and not in the other (ds_ep_test.SplitBackward, test_float32_gate_logits). + + The accumulating W is that W plus the accumulator (Split.w_adds), with no second trace: bwda's body is bwd's with + add_acc(gacc, dW) for new_acc(dW), and on a middle chunk add_acc(g, dW) is g + new_acc(dW) on every leaf -- so + one I feeds both W's, bwda's values bit for bit as above. Under in-place dW accumulation (`inplace_dw`) bwda's + dW kernels start from the accumulator's blocks: acc True traces and cuts `part('B', acc=True)` as well, its W + reading those blocks, and takes acc False's I where the two cuts' I are one program -- the same jaxpr, inputs, + crossing set, kept arguments and donations (Split.i_acc False) -- else its own. + + A middle chunk's only. Refuses (ValueError) chunk 0, whose B the schedules keep whole (no input gradient to + split off: it is all weight gradient to them); the last chunk, one fused program ('A'); a batch-split chunk on + Lineage's layers, one custom VJP of Lineage's whole region; a chunk without layers; and a cut whose I would + read the accumulator.""" + acc = bool(acc) + if acc in self._splits: + return self._splits[acc] + ch = self.ch + why = [ + w + for w, bad in ( + ("chunk 0 (no input gradient to split off: the schedules keep its B whole)", ch.first), + ("the last chunk (its forward and backward are one fused program, 'A')", ch.last), + ( + "a batch-split chunk on Lineage's layers (batch_split_impl 'lineage': one custom VJP of Lineage's " + "whole region)", + self.lineage, + ), + ("a chunk without layers (nothing to split)", self.empty), + ) + if bad + ] + if why: + raise ValueError(f"chunk {ch.index}: no split backward (I / W) for " + "; ".join(why)) + if acc and not self.inplace_dw: + sp = dataclasses.replace(self.build_split(False), acc=True, w_adds=True) + else: + sp = self._cut_backward(acc) + if acc: # in-place dW: bwda's own cut, on the first write's I where it is the same program + first = self.build_split(False) + if ( + (sp.kept, sp.i_donate, sp.crossing_local) == (first.kept, first.i_donate, first.crossing_local) + and len(sp.i_src) == len(first.i_src) + and all( + s == t if isinstance(s, int) or isinstance(t, int) else stage_ad.same_values(s.value, t.value) + for s, t in zip(sp.i_src, first.i_src) + ) + and stage_ad.same_jaxpr(sp.i_jaxpr, first.i_jaxpr) + ): + sp = dataclasses.replace(sp, i_acc=False, i_jaxpr=first.i_jaxpr, i_src=first.i_src) + self._splits[acc] = sp + return sp + + def _cut_backward(self, acc): + """`build_split`'s trace and cut of `part('B', acc=acc)` -> its Split (i_acc = acc, no w_adds).""" + ch, mesh = self.ch, self.mesh + avals = self._part_avals("B", acc) + part = self.part("B", acc=acc) + body = stage_ad.trace_body(part.body, avals, mesh, part.in_specs, part.out_specs) + cut = stage_ad.split_jaxpr(body.jaxpr, 1) # I keeps dx (the B's first output), W every accumulator leaf + names = ("w", "x", "res", "dy") + (("gacc",) if acc else ()) + ("seed",) + where, flat_av = [], [] # per leaf of the B's arguments: (group, its index there), its aval + for n, a in zip(names, avals): + for i, leaf in enumerate(jax.tree.leaves(a)): + where.append((n, i)) + flat_av.append(leaf) + flat_specs = jax.tree.leaves(part.in_specs, is_leaf=_is_spec) + i_srcs = [body.src[k] for k in cut.i_inputs] + read = sorted(where[s][1] for s in i_srcs if isinstance(s, int) and where[s][0] == "gacc") + if read: + raise ValueError( + f"chunk {ch.index}: the cut's I reads accumulator leaves {read}: it would compute a value from the " + "accumulator before its W, out of the order the accumulation keeps" + ) + i_pos = {b: i for i, b in enumerate(b for b, (g, _) in enumerate(where) if g != "gacc")} + i_src = tuple(i_pos[s] if isinstance(s, int) else s for s in i_srcs) + i_jaxpr = cut.i_jaxpr.replace(invars=[body.jaxpr.invars[k] for k in cut.i_inputs]) + w_srcs = [body.src[k] for k in cut.w_inputs] + kept = sorted({s for s in w_srcs if isinstance(s, int) and where[s][0] != "gacc"}) # B positions, in order + w_src = tuple( + s + if isinstance(s, stage_ad.Const) + else (("gacc", where[s][1]) if where[s][0] == "gacc" else ("kept", kept.index(s))) + for s in w_srcs + ) + kept_groups = {where[s][0] for s in kept} + # I donates what the B donates of its arguments (dy; the saved set under saved residuals) but what W reads + i_donate = tuple(d for d in part.donate if names[d] in ("res", "dy") and names[d] not in kept_groups) + n_dev = math.prod(mesh.shape[a] for a in FE) + local = tuple(jax.ShapeDtypeStruct(v.aval.shape, v.aval.dtype) for v in cut.crossing) + specs = tuple(P(FE, *([None] * len(a.shape))) for a in local) + kept_avals = tuple(flat_av[s] for s in kept) + + def dev_bytes(a): + return math.prod(a.sharding.shard_shape(a.shape)) * jnp.dtype(a.dtype).itemsize + + return Split( + acc=acc, + i_acc=acc, + w_adds=False, + i_jaxpr=i_jaxpr, + w_jaxpr=cut.w_jaxpr, + i_src=i_src, + w_src=w_src, + crossing_local=local, + crossing_specs=specs, + crossing_avals=tuple( + jax.ShapeDtypeStruct((n_dev, *a.shape), a.dtype, sharding=NamedSharding(mesh, s)) + for a, s in zip(local, specs) + ), + kept=tuple(where[s] for s in kept), + kept_specs=tuple(flat_specs[s] for s in kept), + kept_avals=kept_avals, + i_donate=i_donate, + bytes=cut.stats["crossing_bytes"], + kept_bytes=sum(dev_bytes(a) for s, a in zip(kept, kept_avals) if where[s][0] in ("x", "res", "dy")), + stats=dict(cut.stats), + ) + + def build_split_last(self, acc=False): + """The `Split` of the fused last chunk's program for the zero-bubble schedules that split it too (--zb-split-last): + its AI -- the forward, the head, the loss and the input gradient, with the weight gradients of the leaves it keeps + -- and the W of `acc`, its layers' weight gradients: the chunk's first gradient write (acc False) or an + accumulating one (acc True) (cached). + + Traces `part('A')`, fb's body, at its abstract arguments (`_part_avals`) to one flat per-device jaxpr + (stage_ad.trace_body, as `build_split`) and cuts it (stage_ad.split_jaxpr): I keeps dx, the loss and every + accumulator leaf but the layers' (`deferred_leaves`: the head's, the decoder norm's, MTP's, the routers' bias + slots, which carry their expert counts, and a first chunk's embedding's stay), W computes the layers' -- so the + head's T x vocab logits and their cotangent never cross, and W is the layers' weight-gradient matmuls. The halves + run the fused program's equations, each once, on the same operands (an inlined remat -- remat_fused_last -- behind + its optimization barrier): fb's values bit for bit wherever XLA compiles each operation as it does in the fused + program. + + The accumulating halves add the accumulator's two parts (and the loss accumulator) to the first write's outputs, + leaf by leaf (Split.w_adds), with no second trace: fba's body is fb's with add_acc(gacc, dW) for new_acc(dW) and + lacc + loss, and add_acc(g, dW) is g + new_acc(dW) on every leaf of the last chunk. Under in-place dW accumulation + (`inplace_dw`) fba's dW kernels start from the accumulator's blocks: acc True traces and cuts `part('A', + acc=True)` as well, its AI reading the accumulator's kept part and the loss accumulator, its W the deferred part. + + The last chunk's only. Refuses (ValueError) any other chunk (its backward is `build_split`'s); a batch-split + chunk on Lineage's layers, one custom VJP of Lineage's whole region; a chunk without layers -- its weight + gradients, the head's and the norm's, are all AI's, with nothing to defer; and a cut whose AI would read the + accumulator's deferred part, or whose W its kept part or the loss accumulator.""" + acc = bool(acc) + if acc in self._splits: + return self._splits[acc] + ch = self.ch + why = [ + w + for w, bad in ( + ("not the last chunk (a middle chunk's backward is build_split's)", not ch.last), + ( + "a batch-split chunk on Lineage's layers (batch_split_impl 'lineage': one custom VJP of Lineage's " + "whole region)", + self.lineage, + ), + ( + "a chunk without layers (the head's and the norm's weight gradients stay in AI: nothing to defer)", + self.empty, + ), + ) + if bad + ] + if why: + raise ValueError(f"chunk {ch.index}: no split last chunk (AI / W) for " + "; ".join(why)) + if acc and not self.inplace_dw: + first = self.build_split_last(False) + sp = dataclasses.replace(first, acc=True, i_acc=True, w_adds=True, i_donate=self._ai_donate(first.kept, True)) + else: + sp = self._cut_last(acc) + self._splits[acc] = sp + return sp + + def _ai_donate(self, kept, acc): + """What an AI part donates: the A part's x (but a first chunk's tokens), unless its W reads it (`kept`), and, + accumulating, the accumulator's kept part and the loss accumulator it adds to.""" + nt = int(bool(self.mtp)) + x = () if self.ch.first or any(g == "x" for g, _ in kept) else (1,) + return x + ((3 + nt, 4 + nt) if acc else ()) + + def _cut_last(self, acc): + """`build_split_last`'s trace and cut of `part('A', acc=acc)` -> its Split (last, i_acc = acc, no w_adds).""" + ch, mesh = self.ch, self.mesh + avals = self._part_avals("A", acc) + part = self.part("A", acc=acc) + body = stage_ad.trace_body(part.body, avals, mesh, part.in_specs, part.out_specs) + defer = deferred_leaves(ch) + w_leaves = tuple(i for i, d in enumerate(defer) if d) + i_leaves = tuple(i for i, d in enumerate(defer) if not d) + n_dx = 0 if ch.first else 1 + # A's outputs: dx (but a first chunk's), the accumulator's leaves, the loss. I keeps all but the deferred leaves. + if len(body.jaxpr.outvars) != n_dx + len(defer) + 1: + raise AssertionError(f"chunk {ch.index}: A has {len(body.jaxpr.outvars)} outputs, want {n_dx + len(defer) + 1}") + cut = stage_ad.split_jaxpr(body.jaxpr, [k for k in range(len(body.jaxpr.outvars)) if k - n_dx not in w_leaves]) + names = ("w", "x", "tgt") + (("tok",) if self.mtp else ()) + (("gacc", "lacc") if acc else ()) + ("seed",) + where, flat_av = [], [] # per leaf of A's arguments: (group, its index there), its aval + for n, a in zip(names, avals): + for i, leaf in enumerate(jax.tree.leaves(a)): + where.append((n, i)) + flat_av.append(leaf) + flat_specs = jax.tree.leaves(part.in_specs, is_leaf=_is_spec) + wset = set(w_leaves) + i_srcs = [body.src[k] for k in cut.i_inputs] + w_srcs = [body.src[k] for k in cut.w_inputs] + bad = [ + f"AI reads the deferred accumulator leaf {where[s][1]}" + for s in i_srcs + if isinstance(s, int) and where[s][0] == "gacc" and where[s][1] in wset + ] + bad += [ + f"W reads {'the loss accumulator' if where[s][0] == 'lacc' else f'the kept accumulator leaf {where[s][1]}'}" + for s in w_srcs + if isinstance(s, int) and (where[s][0] == "lacc" or (where[s][0] == "gacc" and where[s][1] not in wset)) + ] + if bad: + raise ValueError( + f"chunk {ch.index}: the cut of the fused last chunk crosses the accumulator's parts ({'; '.join(bad)}): each " + "part has one writer, AI the kept leaves and W the deferred ones" + ) + # AI's arguments: A's, but of the accumulator its kept part only, in leaf order (a tuple of its leaves) + ai_pos = {wh: k for k, wh in enumerate(wh for wh in where if wh[0] != "gacc" or wh[1] not in wset)} + i_src = tuple(ai_pos[where[s]] if isinstance(s, int) else s for s in i_srcs) + i_jaxpr = cut.i_jaxpr.replace(invars=[body.jaxpr.invars[k] for k in cut.i_inputs]) + kept = sorted({s for s in w_srcs if isinstance(s, int) and where[s][0] != "gacc"}) # A positions, in order + w_src = tuple( + s + if isinstance(s, stage_ad.Const) + else (("gacc", w_leaves.index(where[s][1])) if where[s][0] == "gacc" else ("kept", kept.index(s))) + for s in w_srcs + ) + n_dev = math.prod(mesh.shape[a] for a in FE) + local = tuple(jax.ShapeDtypeStruct(v.aval.shape, v.aval.dtype) for v in cut.crossing) + specs = tuple(P(FE, *([None] * len(a.shape))) for a in local) + kept_avals = tuple(flat_av[s] for s in kept) + + def dev_bytes(a): + return math.prod(a.sharding.shard_shape(a.shape)) * jnp.dtype(a.dtype).itemsize + + kept_wh = tuple(where[s] for s in kept) + return Split( + acc=acc, + i_acc=acc, + w_adds=False, + i_jaxpr=i_jaxpr, + w_jaxpr=cut.w_jaxpr, + i_src=i_src, + w_src=w_src, + crossing_local=local, + crossing_specs=specs, + crossing_avals=tuple( + jax.ShapeDtypeStruct((n_dev, *a.shape), a.dtype, sharding=NamedSharding(mesh, s)) + for a, s in zip(local, specs) + ), + kept=kept_wh, + kept_specs=tuple(flat_specs[s] for s in kept), + kept_avals=kept_avals, + i_donate=self._ai_donate(kept_wh, acc), + bytes=cut.stats["crossing_bytes"], + kept_bytes=sum(dev_bytes(a) for s, a in zip(kept, kept_avals) if where[s][0] == "x"), + stats=dict(cut.stats), + groups=tuple(n for n in names if n not in ("gacc", "lacc")), + last=True, + i_leaves=i_leaves, + w_leaves=w_leaves, + ) + + # ---------------------------------------------------- fused variants + def fwd_prefetch(self, other: ChunkSpec, leaves=None): + """fwd(w, x, seed, storage_leaves_other) -> y, res, compute_leaves_other. + + The forward of this chunk with the FSDP all-gather of (a subset of) + another chunk's weights folded in, so the gather overlaps this chunk's + compute instead of running as its own program. `leaves` indexes the + other chunk's flattened weight tree (None = all). A Lineage chunk's (its + forward a global-view body) is composed of the same parts, F + G. + """ + if self.lineage: + return self.program((pdesc("F"), pdesc("G", other=other, leaves=None if leaves is None else tuple(leaves)))) + ch, mesh, scfg = self.ch, self.mesh, self.scfg + ns = lambda spec: NamedSharding(mesh, spec) + sm = functools.partial(jax.shard_map, mesh=mesh, check_vma=False) + os_ = jax.tree.leaves(chunk_storage_specs(other), is_leaf=_is_spec) + oc = jax.tree.leaves(chunk_compute_specs(other), is_leaf=_is_spec) + ow = jax.tree.leaves(chunk_wc_specs(scfg, other), is_leaf=_is_spec) + idx = tuple(range(len(os_))) if leaves is None else tuple(leaves) + os_, oc, ow = [os_[i] for i in idx], [oc[i] for i in idx], [ow[i] for i in idx] + odt = leaf_dtypes(scfg, other, "compute") + odt = [odt[i] for i in idx] + fwd_body = self._fwd_body + mode = scfg.fsdp_collectives + + def body(w, x, seed, st): + y, res = fwd_body(w, x, seed) + return y, res, [_gather_leaf(a, s_, c_, d_, mode, self._ag) for a, s_, c_, d_ in zip(st, os_, oc, odt)] + + tag = "" if leaves is None else "_" + ".".join(map(str, idx)) + return jax.jit( + _named( + sm(body, in_specs=(self.wspec, self._x_spec, P(), os_), out_specs=(self.act_spec, self.res_spec, ow)), + f"fwd_c{ch.index}_ag{other.index}" + ("" if leaves is None else f"p{idx[0]}"), + ), + in_shardings=(self._w_sh, ns(self._x_spec), ns(P()), [ns(x) for x in os_]), + out_shardings=(ns(self.act_spec), tuple(ns(r) for r in self.res_spec), [ns(x) for x in ow]), + compiler_options=self._copts, + ) + + def fwd_self_prefetch(self, leaves): + """This chunk's FIRST forward with part of its OWN all-gather folded in. + + (w_leaves_rest, x, seed, storage_leaves) -> (y, res, compute_leaves) + + `leaves` index the chunk's flattened weight tree (the routed experts, in + practice): they are not needed until the MoE half of the layer, so their + gather overlaps the embedding + attention compute instead of delaying the + program's start. The other leaves arrive already gathered. A Lineage + chunk's is its F part with these self_leaves, as the pipeline composes it. + """ + if self.lineage: + return self.program((pdesc("F", self_leaves=tuple(leaves)),)) + ch, mesh, scfg = self.ch, self.mesh, self.scfg + ns = lambda spec: NamedSharding(mesh, spec) + sm = functools.partial(jax.shard_map, mesh=mesh, check_vma=False) + lv = lambda t: jax.tree.leaves(t, is_leaf=_is_spec) + ss, cs, ws = lv(chunk_storage_specs(ch)), lv(self.cspec), lv(self.wspec) + tdef = jax.tree.structure(self.cspec, is_leaf=_is_spec) + idx = tuple(leaves) + rest = tuple(i for i in range(len(cs)) if i not in idx) + cdt = leaf_dtypes(scfg, ch, "compute") + mode = scfg.fsdp_collectives + fwd_body = self._fwd_body + + def body(w_rest, x, seed, st): + got = [_gather_leaf(a, ss[i], cs[i], cdt[i], mode, self._ag) for a, i in zip(st, idx)] + full = [None] * len(cs) + for i, v in zip(rest, w_rest): + full[i] = v + for i, v in zip(idx, got): + full[i] = v + y, res = fwd_body(jax.tree.unflatten(tdef, full), x, seed) + return y, res, got + + return jax.jit( + _named( + sm( + body, + in_specs=([ws[i] for i in rest], self._x_spec, P(), [ss[i] for i in idx]), + out_specs=(self.act_spec, self.res_spec, [ws[i] for i in idx]), + ), + f"fwd_c{ch.index}_agself", + ), + in_shardings=([ns(ws[i]) for i in rest], ns(self._x_spec), ns(P()), [ns(ss[i]) for i in idx]), + out_shardings=(ns(self.act_spec), tuple(ns(r) for r in self.res_spec), [ns(ws[i]) for i in idx]), + compiler_options=self._copts, + ) + + def bwd_reduce(self, other: ChunkSpec, accumulate: bool, leaves=None): + """bwd / bwda with (a subset of) another chunk's once-per-step gradient + reduce-scatter folded in: (..., gacc_leaves_other) -> + (..., grads_leaves_other, sumsq_of_those). A Lineage chunk's is + composed of the same parts, B + R (`program`).""" + if self.lineage: + return self.program( + (pdesc("B", acc=accumulate), pdesc("R", other=other, leaves=None if leaves is None else tuple(leaves))) + ) + ch, mesh, scfg = self.ch, self.mesh, self.scfg + ns = lambda spec: NamedSharding(mesh, spec) + sm = functools.partial(jax.shard_map, mesh=mesh, check_vma=False) + lv = lambda t: jax.tree.leaves(t, is_leaf=_is_spec) + os_, oc, og = lv(chunk_storage_specs(other)), lv(chunk_compute_specs(other)), lv(acc_specs(scfg, other)) + idx = tuple(range(len(os_))) if leaves is None else tuple(leaves) + os_, oc, og = [os_[i] for i in idx], [oc[i] for i in idx], [og[i] for i in idx] + sizes = {"fsdp": scfg.fsdp, "expert": scfg.ep} + rs_dt = scfg.rs_dtype + mode = scfg.fsdp_collectives + bwd_core, new_acc, add_acc = self._bwd_core, self._new_acc, self._add_acc + first = ch.first + act = self.act_spec + + ok = [count_leaves(other)[i] for i in idx] + + def reduce(go): + g, sq = scatter_tree(list(go), os_, oc, rs_dt, sizes, mode, counts=ok, **self._rs) + return g, sq + + if accumulate: + + def body(w, x, res, dy, gacc, seed, go): + if self.inplace_dw: + dx, acc = self._bwd_acc(w, x, res, dy, seed, gacc=gacc) + g, sq = reduce(go) + else: # the program as it always traced: the reduce before the accumulate + dx, dw = bwd_core(w, x, res, dy, seed) + g, sq = reduce(go) + acc = add_acc(gacc, dw) + return (*(() if first else (dx,)), acc, g, sq) + + in_specs = (self.wspec, self._x_spec, self.res_spec, act, self.gspec, P(), og) + in_sh = ( + self._w_sh, + ns(self._x_spec), + tuple(ns(r) for r in self.res_spec), + ns(act), + self._g_sh, + ns(P()), + [ns(x) for x in og], + ) + donate = (() if first else (3,)) + (4, 6) + ((2,) if self.scfg.save_residuals else ()) # the saved set + else: + + def body(w, x, res, dy, seed, go): + dx, dw = bwd_core(w, x, res, dy, seed) + g, sq = reduce(go) + return (*(() if first else (dx,)), new_acc(dw), g, sq) + + in_specs = (self.wspec, self._x_spec, self.res_spec, act, P(), og) + in_sh = (self._w_sh, ns(self._x_spec), tuple(ns(r) for r in self.res_spec), ns(act), ns(P()), [ns(x) for x in og]) + donate = (() if first else (3,)) + (5,) + ((2,) if self.scfg.save_residuals else ()) + out_specs = (*(() if first else (act,)), self.gspec, os_, P()) + out_sh = (*(() if first else (ns(act),)), self._g_sh, [ns(x) for x in os_], ns(P())) + kind = "bwda" if accumulate else "bwd" + return jax.jit( + _named( + sm(body, in_specs=in_specs, out_specs=out_specs), + f"{kind}_c{ch.index}_rs{other.index}" + ("" if leaves is None else f"p{idx[0]}"), + ), + in_shardings=in_sh, + out_shardings=out_sh, + donate_argnums=donate, + compiler_options=self._copts, + ) + + def bwda_reduce_self(self, n_other_sq): + """The chunk's LAST backward with its own once-per-step reduce-scatter + folded in (overlapping the backward's tail instead of trailing it): + (w, x, res, dy, gacc, seed, other_sqs) -> (dx?, grads, stage_sumsq). + `other_sqs` are the stage's other partial sums of squares, so the output + is the stage total the optimizer's global-norm clip needs. A Lineage + chunk's is its B part with rs_self, as the pipeline composes it. + """ + if self.lineage: + return self.program((pdesc("B", acc=True, rs_self=n_other_sq),)) + ch, mesh, scfg = self.ch, self.mesh, self.scfg + ns = lambda spec: NamedSharding(mesh, spec) + sm = functools.partial(jax.shard_map, mesh=mesh, check_vma=False) + ss, cs = chunk_storage_specs(ch), chunk_compute_specs(ch) + sizes = {"fsdp": scfg.fsdp, "expert": scfg.ep} + bwd_core, add_acc = self._bwd_core, self._add_acc + first, act = ch.first, self.act_spec + + def body(w, x, res, dy, gacc, seed, sqs): + dx, acc = self._bwd_acc(w, x, res, dy, seed, gacc=gacc) + g, sq = scatter_tree(acc, ss, cs, scfg.rs_dtype, sizes, scfg.fsdp_collectives, counts=count_mask(ch), **self._rs) + return (*(() if first else (dx,)), g, sq + sum(sqs)) + + in_specs = (self.wspec, self._x_spec, self.res_spec, act, self.gspec, P(), [P()] * n_other_sq) + in_sh = ( + self._w_sh, + ns(self._x_spec), + tuple(ns(r) for r in self.res_spec), + ns(act), + self._g_sh, + ns(P()), + [ns(P())] * n_other_sq, + ) + out_specs = (*(() if first else (act,)), ss, P()) + out_sh = (*(() if first else (ns(act),)), jax.tree.map(ns, ss, is_leaf=_is_spec), ns(P())) + return jax.jit( + _named(sm(body, in_specs=in_specs, out_specs=out_specs), f"bwda_c{ch.index}_rsself"), + in_shardings=in_sh, + out_shardings=out_sh, + donate_argnums=(() if first else (3,)) + (4,), + compiler_options=self._copts, + ) + + +# ------------------------------------------------- once-per-step programs +def _axes_of(d): + return () if d is None else ((d,) if isinstance(d, str) else tuple(d)) + + +def _unsharded(spec, dim): + """`spec` shards no mesh axis over dimension `dim` (a dim past its end + included).""" + return dim >= len(spec) or not _axes_of(spec[dim]) + + +def _swap2(x, axis): + """The other device's copy of `x` along a size-2 mesh axis (one async DMA).""" + return lax.ppermute(x, axis, [(0, 1), (1, 0)]) + + +def _trivial(axis): + return lax.axis_size(axis) == 1 + + +def _ag2(x, axis, dim): + """all_gather(tiled) over a size-2 mesh axis, as one collective-permute.""" + if _trivial(axis): + return x + other = _swap2(x, axis) + i = lax.axis_index(axis) + # place both halves by dynamic offset -- no control flow, one write each + n = x.shape[dim] + full = list(x.shape) + full[dim] = 2 * n + out = jnp.zeros(full, x.dtype) + out = lax.dynamic_update_slice_in_dim(out, x, i * n, dim) + return lax.dynamic_update_slice_in_dim(out, other, (1 - i) * n, dim) + + +def _rs2(g, axis, dim): + """psum_scatter(tiled) over a size-2 mesh axis: keep my half, add theirs.""" + if _trivial(axis): + return g + n = g.shape[dim] // 2 + i = lax.axis_index(axis) + mine = lax.dynamic_slice_in_dim(g, i * n, n, dim) + theirs = lax.dynamic_slice_in_dim(g, (1 - i) * n, n, dim) + return mine + _swap2(theirs, axis) + + +# FSDP traffic runs under these scopes wherever it is folded (forward +# prefetch, update, backward): the collectives' op_name carries them, and +# xprof's "Framework Name Scope" row shows each as a labelled block. +@jax.named_scope("fsdp_all_gather") +def _gather_leaf(x, storage_spec, compute_spec, dtype, mode="xla", per_axis=False): + """fp32 storage shard -> bf16 compute layout. `per_axis` + (StageConfig.gather_axes 'each'): a dimension stored over several mesh + axes gathers one axis at a time under 'xla', as 'ppermute' does.""" + x = x.astype(dtype) + for dim, (s, c) in enumerate(zip(storage_spec, compute_spec)): + if s is not None and s != c: + axes = _axes_of(s) + if mode == "ppermute": + # P(('fsdp','expert')) tiles fsdp-major: gather the minor axis first, + # so each step is a plain two-block concatenation. (Major-first would + # halve the cross-chip bytes of these leaves, but its [2, 2, n] view + # puts tiny dims into TPU's tiled layout: measured 45% slower.) + for a in reversed(axes): + x = _ag2(x, a, dim) + elif per_axis and len(axes) > 1: + # The minor axis first, tiled: P(('fsdp', 'expert')) tiles fsdp-major, + # so the 'expert' gather leaves each device its fsdp row's blocks in + # order, and the 'fsdp' gather puts the rows in order -- the joint + # gather's result (why: StageConfig.gather_axes). + for a in reversed(axes): + if not _trivial(a): + x = lax.all_gather(x, a, axis=dim, tiled=True) + else: + x = lax.all_gather(x, s, axis=dim, tiled=True) + return x + + +# rs_axes 'each' on a v5p stage of 2 x v5p-128 PP (v5p-128 as fsdp 4 x expert 16, +# libtpu 0.0.46, its flags): libtpu offloads a reduce-scatter of a large leaf +# to the SparseCore (async) only if its extents suit it. The vocab leaves +# ([129280, 7168] and its transpose; 129280 = 256 x 505) compiled to +# synchronous TensorCore reduce-scatters, both steps, in either orientation; +# at 129024 or 129536 rows (multiples of 512) both steps offloaded. Of other +# unaligned row counts (x 7168), 8448-16640 offloaded as they were, 24832, +# 32512 and 49408 made the 'expert' step a full-size all-reduce, 98560 ran on +# the TensorCore (33024 offloaded). Padding the vocab to 129536 buys nothing +# over the joint psum_scatter, whose all-reduce offloads at any size: XLA +# pads in a full-size pass of its own after the bf16 convert, so the padded +# pair holds the joint one's temporaries (one vocab leaf alone: 3.46 GiB, +# joint 3.45, unpadded 2.16) and adds that pass (3.1 ms a leaf on the +# v6e-4). So 'each' leaves a leaf with an unsharded dim of 16384 or more +# that is no multiple of 512 to the joint psum_scatter (_rs_joint_only). +_RS_ALIGN, _RS_ALIGN_FROM = 512, 16384 + + +def _rs_joint_only(shape, dim, storage_spec, compute_spec): + """A leaf whose per-axis reduce-scatters along `dim` libtpu would run on + the TensorCore: one of its unsharded dims is large and unaligned (the vocab: + _RS_ALIGN).""" + return any( + d != dim and n >= _RS_ALIGN_FROM and n % _RS_ALIGN and _unsharded(storage_spec, d) and _unsharded(compute_spec, d) + for d, n in enumerate(shape) + ) + + +@jax.named_scope("fsdp_reduce_scatter") +def _scatter_leaf(g, storage_spec, compute_spec, dtype, mode="xla", lead=True, per_axis=False): + """Per-device partial [1, *compute_local] -> summed storage-local shard + (`lead` False: the partial is [*compute_local], a device's block of an + unreduced-typed accumulator). `per_axis` (StageConfig.rs_axes 'each'): a + dimension stored over both mesh axes reduce-scatters one axis at a time, + but for the vocab leaves (_rs_joint_only).""" + g = (g[0] if lead else g).astype(dtype) + pa = _partial_axes(compute_spec) + done = set() + for dim, (s, c) in enumerate(zip(storage_spec, compute_spec)): + if s is not None and s != c: + axes = _axes_of(s) + if mode == "ppermute": + axes = tuple(a for a in axes if not _trivial(a)) # size-1 axes: nothing to reduce + if mode == "ppermute" and not axes: + pass + elif mode == "ppermute" and len(axes) == 1: + g = _rs2(g, axes[0], dim) + elif mode == "ppermute": + # Mirror of the gather: reduce the intra-chip MINOR axis first while + # the array is big, so only the quarter crosses chips. + shp = g.shape + n = shp[dim] // 4 + y = g.reshape(shp[:dim] + (2, 2, n) + shp[dim + 1 :]) + y = _rs2(y, axes[1], dim + 1) + y = _rs2(y, axes[0], dim) + g = y.reshape(shp[:dim] + (n,) + shp[dim + 1 :]) + elif per_axis and len(axes) > 1 and not _rs_joint_only(g.shape, dim, storage_spec, compute_spec): + # One psum_scatter a mesh axis, the major one first: P(('fsdp', + # 'expert')) tiles fsdp-major, so the first leaves each device the + # block the second splits (why: StageConfig.rs_axes). + for a in axes: + if not _trivial(a): + g = lax.psum_scatter(g, a, scatter_dimension=dim, tiled=True) + else: + g = lax.psum_scatter(g, s, scatter_dimension=dim, tiled=True) + done.update(_axes_of(s)) + rest = tuple(a for a in pa if a not in done) + if rest: + if mode == "ppermute": + for a in rest: + if not _trivial(a): + g = g + _swap2(g, a) + else: + g = lax.psum(g, rest) + return g + + +def _replication(storage_spec, sizes): + used = {a for d in storage_spec if d is not None for a in ((d,) if isinstance(d, str) else d)} + return math.prod(v for k, v in sizes.items() if k not in used) + + +def _arr_leaf(x): + return not isinstance(x, (dict, list)) + + +def leaf_groups(shapes_tree, n_groups, skip=()): + """Partition a tree's leaves into `n_groups` sets of roughly equal bytes (indices in jax.tree.leaves order), + leaving the leaves `skip` names out of every set.""" + sizes = [math.prod(s) for s in jax.tree.leaves(shapes_tree, is_leaf=_is_shape)] + groups = [[] for _ in range(max(1, n_groups))] + load = [0] * len(groups) + skip = frozenset(skip) + for i in sorted((i for i in range(len(sizes)) if i not in skip), key=lambda i: -sizes[i]): + g = load.index(min(load)) + groups[g].append(i) + load[g] += sizes[i] + return [tuple(sorted(g)) for g in groups if g] + + +def routed_leaf_ids(ch: ChunkSpec): + """The chunk's routed-expert leaves (jax.tree.leaves order of its weights): the leaves stored over 'expert' on + their experts' axis -- the first, or the one after a stack's layer axis (the shared experts' leaves are stored + over both mesh axes together, `FE`, not over 'expert' alone).""" + specs = jax.tree.leaves(chunk_storage_specs(ch), is_leaf=_is_spec) + return tuple(i for i, sp in enumerate(specs) if (len(sp) and sp[0] == "expert") or (len(sp) > 1 and sp[1] == "expert")) + + +def leaf_names(ch: ChunkSpec): + """Readable names of chunk `ch`'s flat weight leaves (jax.tree.leaves + order): each leaf's path in the parameter tree without the stacked layers' + 'layers' and a last 'kernel' / 'scale' -- 'moe.wi_0' (the routed experts), + 'moe.gate', 'moe.shared_experts.wo', 'self_attention.wq_a', + 'self_attention.out', 'post_self_attention_layer_norm', 'logits_dense', + 'decoder_norm', 'token_embedder.embedding'. A DeepSeek layer leaf stacks + the chunk's layers: one name, one gather, for all of them; a dense layer's + leaves are 'dense.'-prefixed ('dense.mlp.wi_0', 'dense.self_attention.wq_a'), + the MTP layer's 'mtp.' ('mtp.layer.moe.wi_0', 'mtp.projection'). A + Qwen3.5-family chunk's leaves are a layer's each, named with its key in the + chunk (`qwen_layer_key`): '00.mlp.routed_experts.wi_0', '01.gdn.in_proj_qkvz', + '01.attn.query', '00.input_layernorm', ...; so are a DeepSeek chunk's under + layer_tree 'per_layer' ('01.moe.wi_0', 'dense.00.mlp.wi_0').""" + flat, _ = jax.tree_util.tree_flatten_with_path(chunk_storage_specs(ch), is_leaf=_is_spec) + out = [] + for path, _ in flat: + keys = [str(getattr(k, "key", k)) for k in path] + keys = keys[1:] if keys[0] == "layers" else ["dense"] + keys[1:] if keys[0] == "dense_layers" else keys + out.append(".".join(keys[:-1] if len(keys) > 1 and keys[-1] in ("kernel", "scale") else keys)) + return out + + +# ------------------------------------ prefetch pins: SPECs and the 'auto' plan +def parse_prefetch_pin(spec): + """--prefetch-pin -> 'off', 'auto', or a SPEC's ((point, layer, name), ...). + + SPEC: `point[@layer]=name,name;...`, e.g. 'hn=moe.gate,moe.wi_0;xs=moe.wo, + self_attention.out;y=logits_dense': the gathered leaves a name selects + (`leaf_names`: the leaf of that name, or every leaf under it -- + 'moe.shared_experts' its three, 'self_attention' all seven -- of every + chunk, or with a chunk prefix of that chunk only: 'c3.moe.wi_0', 'c3' all + of chunk 3) are pinned at that point (PIN_POINTS) of that layer of the + host's forward (default 0, its first). A leaf two names select takes the + longer one's point (two of one length must agree: `pin_of`); a leaf none + selects is left to XLA, and so is one with nothing to gather (a norm + scale). ValueError on anything else.""" + s = "off" if spec is None else str(spec).strip() + if s in ("off", "auto"): + return s + out, seen = [], set() + for item in filter(None, (x.strip() for x in s.split(";"))): + where, eq, names = item.partition("=") + point, at, layer = where.strip().partition("@") + if not eq or point not in PIN_POINTS or (at and not layer.strip().isdigit()): + raise ValueError( + f"--prefetch-pin {spec!r}: {item!r} is not point[@layer]=name,... (points: " + f'{", ".join(PIN_POINTS)}; e.g. hn=moe.wi_0;y=logits_dense)' + ) + for n in (x.strip() for x in names.split(",")): + if not n: + raise ValueError(f"--prefetch-pin {spec!r}: an empty leaf name in {item!r}") + if n in seen: + raise ValueError(f"--prefetch-pin {spec!r}: {n!r} is pinned twice") + seen.add(n) + out.append((point, int(layer) if at else 0, n)) + if not out: + raise ValueError(f"--prefetch-pin {spec!r}: off, auto, or point[@layer]=name,... (e.g. hn=moe.wi_0)") + return tuple(out) + + +def pin_selects(n, name, chunk): + """Does SPEC name `n` select leaf `name` of chunk `chunk` (parse_prefetch_pin)?""" + return any(full == n or full.startswith(n + ".") for full in (name, f"c{chunk}.{name}")) + + +def pin_of(entries, name, chunk): + """The (point, layer) the SPEC `entries` (parse_prefetch_pin) pin leaf + `name` of chunk `chunk` at -- the longest name selecting it decides -- or + None. Two names of one length select a leaf only as a path and a + chunk-qualified one ('moe.wo', 'c3.moe'): a ValueError where they pin it at + different points, which neither length nor order could settle.""" + hits = [(len(n), n, (pt, layer)) for pt, layer, n in entries if pin_selects(n, name, chunk)] + if not hits: + return None + top = max(k for k, _, _ in hits) + at = {w for k, _, w in hits if k == top} + if len(at) > 1: + raise ValueError( + f"--prefetch-pin: {sorted(n for k, n, _ in hits if k == top)}, names of one length, pin " + f"{name} of chunk {chunk} at different points {sorted(at)}: lengthen the one that should decide" + ) + return at.pop() + + +def has_gather(ch: ChunkSpec, i): + """Does leaf i of chunk `ch` gather anything (its storage layout is not its + compute layout)? A norm scale is only cast: no pin.""" + ss = jax.tree.leaves(chunk_storage_specs(ch), is_leaf=_is_spec)[i] + cs = jax.tree.leaves(chunk_compute_specs(ch), is_leaf=_is_spec)[i] + return any(_axes_of(s) != _axes_of(c) for s, c in zip(ss, cs)) + + +@dataclasses.dataclass(frozen=True) +class PinModel: + """The costs `plan_pins` ('auto' prefetch pins) estimates a host forward's + windows and its gathers with. The defaults (PIN_MODEL) are calibrated on + two profiled runs of PP over DCN on 2 x v5p-128 (fsdp 4 x expert 16 stages, + libtpu 0.0.46, the v5p recipe's flags; 2026-10): R1 = E576, M=2, one + 4096-token row a device; R2 = E1024, M=4, cp 2. PIN_MODEL_V6E is v6e's + (PIN_MODELS: the model a device kind plans with). + + ring_gbps a SparseCore all-gather over at most ring_max devices (v5p's + 4-way 'fsdp', a ring of chips): GB/s received a chip (the + routed experts' 4-way gathers: 793 MB in 4.3 ms (R1), 1409 MB + in 7.6 (R2)) + plane_gbps over ring_max + 1 to plane_max (the 16-way 'expert', a 4x4 + plane; the EP token gathers: 881 MB in 2.84 ms) + ring_max, plane_max the buckets' largest group sizes (4 and 16 on v5p-128, + whose axes are 4, 16 and 64 devices) + wide_gbps over more: a native gather over a whole v5p-128 stage (64 + devices), where libtpu does not make it an all-reduce -- with + prefag (--xla_tpu_prefer_async_allgather_to_allreduce), or in + a one-slice program. Not measured (no run has timed one): + plane_gbps stands in, and 'auto''s plans under prefag rest on + it -- if such a gather is no faster than the all-reduce, + prefag + auto replays slower than auto without prefag + allreduce_gbps the all-reduce a multi-slice compile makes of a gather over + both axes (ds_ep.StageConfig.gather_axes), bytes on the wire a + chip (the [7168, 129280] head: 2 x 1.82 GB in 12.6 ms) + attn_tflops, attn_ms attention up to the MoE input ('hn'): MLA's matmul + and causal attention FLOPs a device at attn_tflops, plus + attn_ms of everything else (norms, rope, layout copies, the + cp permutes; 9.7 ms in R1, 5.9 in R2) + topk_tokens_per_ms the router's TopK over the EP group's tokens, up to + 'xs' (4.22 ms for 65536 tokens in R1, 2.18 for 32768 in R2) + gmm_tflops the three expert gmms, up to 'y': megablox's FLOPs over the + tiles it visits -- a device's routed rows / tm plus one a + local expert (11.5 ms in R1, 10.2 in R2) + safety how far past its estimated compute a window may be filled: a + window's gathers run one at a time on the SparseCore and should + fit it, but a routed expert's gather in a window it overruns + a little beats leaving it -- or the head's -- to the end (R2: + a 7.6 ms gather in 5.9 ms of attention; 1.3 to 1.5 give the + same plans for both runs) + overflow where a gather no window holds goes: 'xla', left to XLA (no + gather of the v5p runs' plans was), or 'last', pinned at the + last window it may take -- the last layer's 'y', a forward's + own leaf its first layer's 'xs' -- after the windows are + filled. The gathers v6e's costs leave out on R2v -- the second + routed expert of 0F1, the head of 0F2 -- XLA issues after the + gmms and waits for at once (AOT): the unpinned runs expose 5.9 + of that 7.1 ms routed gather and 17.4 of the 19.5 ms per-axis + head (9.3 of 10.1 native), the A/B's pins at 'y' 1.8 and 10.4 + (R2v's 0F2: 45.6 ms pinned, 53.8 unpinned) + """ + + ring_gbps: float = 185.0 + plane_gbps: float = 310.0 + wide_gbps: float = 310.0 + allreduce_gbps: float = 290.0 + attn_tflops: float = 292.0 + attn_ms: float = 2.1 + topk_tokens_per_ms: float = 15_200.0 + gmm_tflops: float = 408.0 + safety: float = 1.4 + ring_max: int = 4 + plane_max: int = 16 + overflow: str = "xla" + + def __post_init__(self): + if self.overflow not in ("xla", "last"): + raise ValueError(f"PinModel.overflow must be 'xla' or 'last', got {self.overflow!r}") + + +PIN_MODEL = PinModel() +# v6e's costs, measured the way PIN_MODEL's were (the same ops, medians over 4 chips x 3 profiled steps of the stage-0 +# leader's trace) on the FSDP-overlap A/B on 2 x v6e-128 (2026-10-19, libtpu 0.0.46, the 'v6e' flag set, one stage a +# slice): R2v = E384, M=4, cp 2, fsdp 8 x expert 16; R1v = E128, M=2, one +# 4096-token row a device, fsdp 16 x expert 8. A stage's mesh is v6e-128's 8 x 16 chips: its 8-device axis (R2v's +# 'fsdp', R1v's 'expert') gathers at half the rate of its 16-device one, whatever it moves, so the ring bucket is 8 +# devices. +# ring_gbps 88 8-way: the routed experts 617 MB in 6.97-7.05 ms (R2v), the EP tokens 411 MB in 4.63 (R1v), +# the head's per-axis 1622 MB in 18.3 (R2v, --gather-axes each) +# plane_gbps 178 16-way: the EP tokens 440 MB in 2.38-2.44 ms (R2v), the routed experts 440 MB in 2.40-2.58 +# (R1v), the head's per-axis 1738 MB in 9.5 (R1v, each) +# wide_gbps 175 the native 128-way gathers of the vocab leaves (NATIVE_JOINT_GATHER_KINDS): 1839 MB in 10.1 ms +# (the head, R2v and R1v), 10.5-11.2 (the embedding, over its minor dim); out 233 MB in 1.32-1.38 +# allreduce_gbps 160 the 128-way all-reduces of the vocab leaves' gradients, 2 x 1.84 GB in 21.0-24.4 ms (no +# v6e forward gathers through one: Pipeline.joint_gather_allreduce) +# attn 2.94 ms + FLOPs at 330 TFLOP/s: attention up to 'hn' 6.30 ms (R2v), 9.66 (R1v) +# topk 87,700 tokens/ms: the TopK is XLA's sort of [EP x T, E] on v6e (no TopK custom call), 0.374 ms for 32768 +# tokens x 384 experts (R2v), 0.072 x 128 (R1v); the larger stands for both +# gmm 512 TFLOP/s: the three gmms and the activation product between them, 4.91-4.99 ms (R2v), 7.02-7.03 (R1v) +# overflow 'last': R2v's 8-way routed gathers (7.0 ms) and its head (10.5 ms native, 19.6 per axis) outgrow the +# windows; left to XLA they are exposed (PinModel.overflow) +PIN_MODEL_V6E = PinModel( + ring_gbps=88.0, + plane_gbps=178.0, + wide_gbps=175.0, + allreduce_gbps=160.0, + attn_tflops=330.0, + attn_ms=2.94, + topk_tokens_per_ms=87_700.0, + gmm_tflops=512.0, + ring_max=8, + overflow="last", +) +# The PinModel each device kind's stages plan with (a v5p device reports 'TPU v5', a v6e one 'TPU v6 lite'); 'auto' +# plans any other kind with v5p's and warns (ds_ep_pipeline.Pipeline.pin_model). +PIN_MODELS = {"TPU v5": PIN_MODEL, "TPU v5p": PIN_MODEL, "TPU v6 lite": PIN_MODEL_V6E, "TPU v6e": PIN_MODEL_V6E} +# The device kinds whose multi-slice programs gather a leaf stored over both stage axes natively, with no +# all-reduce (ds_ep_pipeline.Pipeline.joint_gather_allreduce): a 2 x v6e-128 AOT (libtpu 0.0.46, the v5p recipe's +# flags) compiled the 128-way gathers of the vocab leaves, out, wq_a and the shared experts to native SparseCore +# all-gathers -- but wkv_a's, [7168, 576], 8 MB a layer -- where 2 x v5p-128 decomposes every one of them. +NATIVE_JOINT_GATHER_KINDS = ("TPU v6 lite", "TPU v6e") + + +def pin_windows(scfg: StageConfig, ch: ChunkSpec, tokens, model=PIN_MODEL, seq=None): + """The compute windows of a forward of chunk `ch` with `tokens` tokens a + device, as `plan_pins` fills them: [(point, layer, ms)] in the order the + forward reaches the points -- per layer its attention (until 'hn'), the + router's TopK (until 'xs') and the expert gmms (until 'y'), estimated with + `model` (PinModel). `seq`: the sequence length -- a device's tokens are + rows of seq / cp, each attending within its own sequence -- by default + tokens x cp (one row a device).""" + cfg, t = scfg.model, tokens + if is_qwen(cfg): + raise ValueError( + "prefetch pins 'auto' price each window from MLA's FLOPs and DeepSeek's measured rates: a " + "Qwen3.5-family stage has no window model; pin by SPEC, or not at all (off)" + ) + seq = t * scfg.cp if seq is None else seq + D, H, F = cfg.emb_dim, cfg.num_query_heads, cfg.moe_mlp_dim + qk = cfg.qk_nope_head_dim + cfg.qk_rope_head_dim + q = D * cfg.q_lora_rank + cfg.q_lora_rank * H * qk if cfg.q_lora_rank else D * H * qk + kv = D * (cfg.kv_lora_rank + cfg.qk_rope_head_dim) + cfg.kv_lora_rank * H * (cfg.qk_nope_head_dim + cfg.v_head_dim) + proj = 2 * t * (q + kv + H * cfg.v_head_dim * D) + core = t * seq * H * (qk + cfg.v_head_dim) # causal, per sequence: on average seq / 2 keys a query + attn = model.attn_ms + (proj + core) / (model.attn_tflops * 1e9) + topk = scfg.ep * t / model.topk_tokens_per_ms + tiles_rows = t * cfg.num_experts_per_tok + cfg.num_experts // scfg.ep * scfg.wi_tiling[0] + gmm = 3 * 2 * D * F * tiles_rows / (model.gmm_tflops * 1e9) + return [(pt, layer, ms) for layer in range(ch.n_moe) for pt, ms in (("hn", attn), ("xs", topk), ("y", gmm))] + + +def pin_gather_ms( + scfg: StageConfig, shape, storage_spec, compute_spec, joint_allreduce=False, model=PIN_MODEL, itemsize=2 +): + """The estimated SparseCore time (ms) of gathering one leaf into its + compute copy of `itemsize` bytes an element (bf16; an fp32 router's 4), + 0 for one with nothing to gather. Over one mesh axis a native all-gather; over + both, under gather_axes 'joint', the all-reduce libtpu makes of it in a + multi-slice program (`joint_allreduce`) or a native gather over all of + them (over more than plane_max devices at PinModel.wide_gbps: measured on + v6e, unmeasured on v5p), and under 'each' a native gather an axis, the + minor first.""" + sizes = {"fsdp": scfg.fsdp, "expert": scfg.ep} + out = itemsize * math.prod( + n // math.prod(sizes[a] for a in _axes_of(c)) + for n, c in zip(shape, tuple(compute_spec) + (None,) * (len(shape) - len(compute_spec))) + ) + + def native(k, nbytes): + gbps = model.ring_gbps if k <= model.ring_max else model.plane_gbps if k <= model.plane_max else model.wide_gbps + return (k - 1) / k * nbytes / (gbps * 1e6) + + ms = 0.0 + for s, c in zip(storage_spec, compute_spec): + axes = tuple(a for a in _axes_of(s) if a not in _axes_of(c) and sizes[a] > 1) + n = math.prod(sizes[a] for a in axes) + if not axes: + continue + if len(axes) == 1: + ms += native(n, out) + elif scfg.gather_axes == "each": + cur = out / n + for a in reversed(axes): + cur *= sizes[a] + ms += native(sizes[a], cur) + elif joint_allreduce: + ms += 2 * (n - 1) / n * out / (model.allreduce_gbps * 1e6) + else: + ms += native(n, out) + return ms + + +def plan_pins( + scfg: StageConfig, host: ChunkSpec, leaves, tokens, joint_allreduce=False, own=(), model=PIN_MODEL, seq=None +): + """'auto' prefetch pins of one forward of chunk `host` that gathers `leaves` + ([(ChunkSpec, leaf id)]: a prefetch part's, or the self-prefetch's) -> + ((point, layer, chunk, leaf id), ...). + + The forward's windows (`pin_windows`: attention, the router, the gmms, + layer by layer) are filled with the gathers (`pin_gather_ms`), largest + first, each into the window it loads least -- the lowest (load + gather) / + window -- among the windows it keeps within their compute times + model.safety, the earlier window on a tie; a gather no window holds is left + to XLA (model.overflow 'xla') or, once the windows are filled, pinned at + the last window it may take ('last'); one with nothing to gather (a norm + scale) is left to XLA. Filling the + windows in order instead, each with the largest gathers that fit, put R1's + 12.6 ms head gather into its 9.7 ms attention rather than its 11.5 ms of + gmms (replayed: 65.5 ms against 58.3 for this plan). `own` ((chunk, leaf + id)s): leaves the forward itself uses (the self-prefetch's routed experts): + at most one of them is pinned, in a window of the first layer before its + gmms -- the rest are bound by their own gmms, and with the first one under + way early XLA puts them in time (pinning a second into R1's attention + replayed 51.2 ms against 48.9). The windows and the gathers are estimates + (PinModel; `tokens` and `seq` as pin_windows').""" + cost = [] + for ch, i in leaves: + shape = jax.tree.leaves(chunk_shapes(scfg, ch), is_leaf=_is_shape)[i] + ss = jax.tree.leaves(chunk_storage_specs(ch), is_leaf=_is_spec)[i] + cs = jax.tree.leaves(chunk_compute_specs(ch), is_leaf=_is_spec)[i] + ms = pin_gather_ms(scfg, shape, ss, cs, joint_allreduce, model, itemsize=leaf_dtypes(scfg, ch, "compute")[i].itemsize) + if ms > 0: + cost.append((-ms, ch.index, i)) + windows = pin_windows(scfg, host, tokens, model, seq) + if not windows: # a chunk of dense layers: no point to pin at + return () + load = [0.0] * len(windows) + plan, n_own = [], 0 + for neg, c, i in sorted(cost): # largest first; ties by (chunk, leaf) + ms, mine = -neg, (c, i) in own + if mine and n_own: + continue + fits = [ + ((load[k] + ms) / w, k) + for k, (pt, layer, w) in enumerate(windows) + if load[k] + ms <= w * model.safety and not (mine and (layer or pt == "y")) + ] + if fits: + k = min(fits)[1] + load[k] += ms + plan.append((windows[k][0], windows[k][1], c, i)) + n_own += mine + if model.overflow == "last": + done = {(c, i) for _, _, c, i in plan} + for neg, c, i in sorted(cost): + mine = (c, i) in own + if (c, i) in done or (mine and n_own): + continue + k = max(k for k, (pt, layer, _) in enumerate(windows) if not (mine and (layer or pt == "y"))) + load[k] -= neg + plan.append((windows[k][0], windows[k][1], c, i)) + n_own += mine + return tuple(sorted(plan)) + + +def gather_tree(storage, sspec, cspec, dtype, mode="xla", per_axis=False): + """Inside shard_map: fp32 storage shards -> bf16 compute layout (all-gather; + `per_axis` as _gather_leaf's). `dtype`: one for every leaf, or a tree of + them (leaf_dtype_tree).""" + if not isinstance(dtype, (dict, list)): + dtype = jax.tree.map(lambda _: dtype, sspec, is_leaf=_is_spec) + return jax.tree.map( + lambda x, s, c, d: _gather_leaf(x, s, c, d, mode, per_axis), storage, sspec, cspec, dtype, is_leaf=_arr_leaf + ) + + +@jax.named_scope("grad_norm_all_reduce") +def _stage_sumsq(sq): + """The stage's gradient sum of squares, summed over its devices (for the + global-norm clip; the other stages' come in as arguments).""" + return lax.psum(sum(jax.tree.leaves(sq)), FE) + + +def _leaf_sumsq(g, storage_spec, sizes, counts=False): + """A reduced gradient leaf's share of the stage's sum of squares (none for + an expert-count leaf: no gradient, count_leaves).""" + if counts: + return jnp.zeros((), jnp.float32) + return jnp.sum(jnp.square(g.astype(jnp.float32))) / _replication(storage_spec, sizes) + + +def scatter_tree(gacc, sspec, cspec, dtype, sizes, mode="xla", lead=True, per_axis=False, counts=None): + """Inside shard_map: per-device partials -> summed storage shards, plus the + stage-wide sum of squares of the result (already psum'd). `lead`, + `per_axis`: as _scatter_leaf's. `counts` (shaped like `gacc`, default + none): the leaves holding expert counts (count_leaves), reduced in fp32 and + left out of the sum of squares.""" + if counts is None: + counts = jax.tree.map(lambda _: False, sspec, is_leaf=_is_spec) + grads = jax.tree.map( + lambda g, s, c, k: _scatter_leaf(g, s, c, jnp.float32 if k else dtype, mode, lead, per_axis), + gacc, + sspec, + cspec, + counts, + is_leaf=_arr_leaf, + ) + sq = jax.tree.map(lambda g, s, k: _leaf_sumsq(g, s, sizes, k), grads, sspec, counts, is_leaf=_arr_leaf) + return grads, _stage_sumsq(sq) + + +class StagePrograms: + """Once-per-step programs of one stage, over all of its chunks at once. + + gather(storage) -> compute (bf16, all-gathered) + reduce(gaccs) -> grads, sumsq (reduce-scatter) + update(params, opt, grads, gsq_all, lr) -> params, opt (AdamW + clip) + """ + + def __init__( + self, scfg: StageConfig, chunks, mesh, adam=None, n_stages=2, gather_slots=(0,), first_leaves=None, skip_leaves=None + ): + _require_resolved(scfg) + self.scfg, self.chunks, self.mesh = scfg, chunks, mesh + ns = lambda spec: NamedSharding(mesh, spec) + sm = functools.partial(jax.shard_map, mesh=mesh, check_vma=False) + sspec = [chunk_storage_specs(c) for c in chunks] + cspec = [chunk_compute_specs(c) for c in chunks] + wspec = [chunk_wc_specs(scfg, c) for c in chunks] # cspec as the programs return it (typed: 'explicit') + gspec = [acc_specs(scfg, c) for c in chunks] + cmask = [count_mask(c) for c in chunks] # the routers' biases (count_leaves) + self.cmask = cmask + rs = dict(lead=scfg.shard_mode != "explicit", per_axis=scfg.rs_axes == "each") # as ChunkPrograms._rs + self.sspec, self.cspec, self.wspec, self.gspec, self._rs = sspec, cspec, wspec, gspec, rs + s_sh = jax.tree.map(ns, sspec, is_leaf=_is_spec) + c_sh = jax.tree.map(ns, wspec, is_leaf=_is_spec) + g_sh = jax.tree.map(ns, gspec, is_leaf=_is_spec) + self.s_sh, self.c_sh, self.g_sh = s_sh, c_sh, g_sh + dt = [leaf_dtype_tree(scfg, c, "compute") for c in chunks] # cfg.dtype, but leaf_dtypes' fp32 ones + ag = scfg.gather_axes == "each" # _gather_leaf's per_axis, as ChunkPrograms._ag + + def gather_body(storage): + return jax.tree.map( + lambda x, s, c, d: _gather_leaf(x, s, c, d, scfg.fsdp_collectives, ag), + storage, + sspec, + cspec, + dt, + is_leaf=lambda x: not isinstance(x, (dict, list)), + ) + + sid = chunks[0].stage + self.gather = jax.jit( + _named(sm(gather_body, in_specs=(sspec,), out_specs=wspec), f"gather_s{sid}"), + in_shardings=(s_sh,), + out_shardings=c_sh, + ) + + sizes = {"fsdp": scfg.fsdp, "expert": scfg.ep} + rs_dt = scfg.rs_dtype + + def reduce_body(gaccs): + if scfg.grad_reduce == "microbatch": + grads = jax.tree.map(lambda x, k: x.astype(jnp.float32 if k else rs_dt), gaccs, cmask) + else: + grads = jax.tree.map( + lambda g, s, c, k: _scatter_leaf(g, s, c, jnp.float32 if k else rs_dt, scfg.fsdp_collectives, **rs), + gaccs, + sspec, + cspec, + cmask, + is_leaf=_arr_leaf, + ) + sq = jax.tree.map(lambda g, s, k: _leaf_sumsq(g, s, sizes, k), grads, sspec, cmask, is_leaf=_arr_leaf) + sumsq = _stage_sumsq(sq) + return grads, sumsq + + self.reduce = jax.jit( + _named(sm(reduce_body, in_specs=(gspec,), out_specs=(sspec, P())), f"reduce_s{sid}"), + in_shardings=(g_sh,), + out_shardings=(s_sh, ns(P())), + donate_argnums=(0,), + ) + + mode = scfg.fsdp_collectives + gs0 = tuple(gather_slots) + # first_leaves: gather only these leaves of slot 0 here (as a flat list); + # the rest of slot 0 is gathered by its first forward (fwd_self_prefetch). + # skip_leaves: per slot, leaves never gathered -- the stage reads them in + # place (Pipeline's `direct`: at fsdp 1 the routed experts, whose compute + # copy would be their storage's bytes again). `keep[i]`: the leaves of + # slot i gathered here, as a flat list, where either applies; else None, + # the whole tree. + lv = lambda t: jax.tree.leaves(t, is_leaf=_is_spec) + fl = None if first_leaves is None else tuple(first_leaves) + self.first_leaves = fl + sk = [frozenset(skip_leaves[i] if skip_leaves else ()) for i in range(len(chunks))] + + def keep_of(i): + if (i != 0 or fl is None) and not sk[i]: + return None + base = fl if (i == 0 and fl is not None) else range(len(lv(sspec[i]))) + return tuple(j for j in base if j not in sk[i]) + + keep = [keep_of(i) for i in range(len(chunks))] + self.keep, self.skip_leaves = keep, [tuple(sorted(x)) for x in sk] + + def gather_slots_of(ps): + out = [] + for i in gs0: + if keep[i] is not None: + st, ss_, cs_, ds_ = jax.tree.leaves(ps[i]), lv(sspec[i]), lv(cspec[i]), jax.tree.leaves(dt[i]) + out.append([_gather_leaf(st[j], ss_[j], cs_[j], ds_[j], mode, ag) for j in keep[i]]) + else: + out.append(gather_tree(ps[i], sspec[i], cspec[i], dt[i], mode, ag)) + return out + + def gathered_specs(tree_of): + return [[lv(tree_of[i])[j] for j in keep[i]] if keep[i] is not None else tree_of[i] for i in gs0] + + self._gather_slots_of, self._gathered_specs = gather_slots_of, gathered_specs + self.gather_first = jax.jit( + _named(sm(gather_slots_of, in_specs=(sspec,), out_specs=gathered_specs(wspec)), f"gather_s{sid}_init"), + in_shardings=(s_sh,), + out_shardings=gathered_specs(c_sh), + ) + self._sm, self._ns, self._sizes, self._sid = sm, ns, sizes, sid + self._final = {} + + a = dict(b1=0.9, b2=0.95, eps=1e-8, wd=0.1, clip=scfg.grad_clip, mu_dtype=jnp.bfloat16) + a.update(adam or {}) + self.adam = a + rate = getattr(scfg.model, "routed_bias_update_rate", 0.0) # a Qwen3.5-family config has no routed bias + flags = [k for c in chunks for k in count_leaves(c)] # jax.tree.flatten order of the params list + + def bias_step(p, counts): + """A router bias, from its layers' expert counts (stacked [.., E]): + MaxText's load_balance_updates_from_counts, rate x sign(mean - load) -- + the counts' scale (the EP replicas' copies all summed) cancels.""" + c = counts.astype(jnp.float32) + return (p.astype(jnp.float32) + rate * jnp.sign(jnp.mean(c, axis=-1, keepdims=True) - c)).astype(p.dtype) + + # StageConfig.grad_dtype: the reduced gradient (rs_dtype) enters AdamW in + # it, cast ahead of the clip as MaxText casts after its reduction; the + # count leaves never pass through it. + gdt = scfg.grad_dtype + + def enter(g, p): + """A reduced gradient as AdamW takes it: in grad_dtype; else under + adam_math 'optax' in its weight's dtype, as MaxText's gradients take + their parameter's (a bf16 reduce-scatter into an fp32 weight cast up, an + fp32 --rs-dtype into a bf16 weight down); else as reduced.""" + if gdt is not None: + return g.astype(gdt) + return g.astype(p.dtype) if scfg.adam_math == "optax" else g + + def update(params, opt, grads, sumsqs, lr): + gnorm = jnp.sqrt(sum(sumsqs)) + scale = jnp.minimum(1.0, a["clip"] / (gnorm + 1e-6)) if a["clip"] else 1.0 + count = opt["count"] + 1 + c1 = 1 - a["b1"] ** count.astype(jnp.float32) + c2 = 1 - a["b2"] ** count.astype(jnp.float32) + ps, tdef = jax.tree.flatten(params) + ms, vs, gs = (tdef.flatten_up_to(t) for t in (opt["mu"], opt["nu"], grads)) + new_p, new_m, new_v = [], [], [] + if scfg.adam_math == "optax": + # maxtext.experimental.mpmd.jax.deepseek.train's clip_by_global_norm / adamw_update / apply_updates, op for op. + clip = gnorm < a["clip"] + c1, c2 = 1 - a["b1"] ** count, 1 - a["b2"] ** count + for p, m, v, g, k in zip(ps, ms, vs, gs, flags): + if k: + new_p.append(bias_step(p, g)) + new_m.append(m) + new_v.append(v) + continue + g = enter(g, p) + if a["clip"]: + g = lax.select(clip, g, (g / gnorm.astype(g.dtype)) * a["clip"]) + nu_dtype = v.dtype + m = (1 - a["b1"]) * g + a["b1"] * m + v = (1 - a["b2"]) * (g**2) + a["b2"] * v + u = (m / c1.astype(m.dtype)) / (jnp.sqrt(v / c2.astype(v.dtype)) + a["eps"]) + u = u + a["wd"] * p + new_p.append((p + jnp.asarray(-lr, u.dtype) * u).astype(p.dtype)) + new_m.append(m.astype(a["mu_dtype"])) + new_v.append(v.astype(nu_dtype)) # a wider gradient dtype would promote it; the programs fix its dtype + un = lambda xs: jax.tree.unflatten(tdef, xs) + return un(new_p), {"mu": un(new_m), "nu": un(new_v), "count": count}, gnorm + # In fp32 whatever the storage dtype (cfg.weight_dtype), stored back in it. + for p, m, v, g, k in zip(ps, ms, vs, gs, flags): + if k: + new_p.append(bias_step(p, g)) + new_m.append(m) + new_v.append(v) + continue + g = enter(g, p).astype(jnp.float32) * scale + m = a["b1"] * m.astype(jnp.float32) + (1 - a["b1"]) * g + v32 = a["b2"] * v.astype(jnp.float32) + (1 - a["b2"]) * g * g + p32 = p.astype(jnp.float32) + upd = (m / c1) / (jnp.sqrt(v32 / c2) + a["eps"]) + a["wd"] * p32 + new_p.append((p32 - lr * upd).astype(p.dtype)) + new_m.append(m.astype(a["mu_dtype"])) + new_v.append(v32.astype(v.dtype)) + un = lambda xs: jax.tree.unflatten(tdef, xs) + return un(new_p), {"mu": un(new_m), "nu": un(new_v), "count": count}, gnorm + + opt_sh = {"mu": s_sh, "nu": s_sh, "count": ns(P())} + self.opt_sh = opt_sh + + gs = tuple(gather_slots) + self.gather_slots = gs + + def update_gather(params, opt, grads, sumsqs, lr): + new_p, new_o, gnorm = update(params, opt, grads, sumsqs, lr) + return new_p, new_o, gnorm, gather_slots_of(new_p) + + # AdamW is elementwise, so the whole update runs per device inside a + # shard_map; the next step's all-gather of the chunks in `gather_slots` + # rides in the same program and overlaps the (memory-bound) update. On + # the stage that starts the forward that is just its first chunk; a + # stage with slack before its first forward can gather everything here. + opt_spec = {"mu": sspec, "nu": sspec, "count": P()} + self.update_gather = jax.jit( + _named( + sm( + update_gather, + in_specs=(sspec, opt_spec, sspec, [P()] * n_stages, P()), + out_specs=(sspec, opt_spec, P(), gathered_specs(wspec)), + ), + f"update_s{sid}_ag" + ".".join(str(chunks[i].index) for i in gs), + ), + out_shardings=(s_sh, opt_sh, ns(P()), gathered_specs(c_sh)), + donate_argnums=(0, 1, 2), + ) + self.update = jax.jit( + _named(update, f"update_s{sid}"), out_shardings=(s_sh, opt_sh, ns(P())), donate_argnums=(0, 1, 2) + ) + + def reduce_final(self, slots, n_other=None): + """(gaccs of `slots`, partial sumsqs of the rest) -> (grads of `slots`, stage sumsq).""" + slots = tuple(slots) + if n_other is None: + n_other = len(self.chunks) - len(slots) + key = (slots, n_other) + if key not in self._final: + sm, ns, sizes, scfg = self._sm, self._ns, self._sizes, self.scfg + ss = [self.sspec[i] for i in slots] + cs = [self.cspec[i] for i in slots] + gs = [self.gspec[i] for i in slots] + + cm = [self.cmask[i] for i in slots] + + def body(gaccs, sqs): + if scfg.grad_reduce == "microbatch": # already reduced: just the norm + g = jax.tree.map(lambda x, k: x.astype(jnp.float32 if k else scfg.rs_dtype), gaccs, cm) + sq_ = jax.tree.map(lambda x, s_, k: _leaf_sumsq(x, s_, sizes, k), g, ss, cm, is_leaf=_arr_leaf) + sq = _stage_sumsq(sq_) + else: + g, sq = scatter_tree(gaccs, ss, cs, scfg.rs_dtype, sizes, scfg.fsdp_collectives, counts=cm, **self._rs) + return g, sq + sum(sqs) + + self._final[key] = jax.jit( + _named( + sm(body, in_specs=(gs, [P()] * n_other), out_specs=(ss, P())), + f"reduce_s{self._sid}_" + "_".join(str(self.chunks[i].index) for i in slots), + ), + in_shardings=(jax.tree.map(ns, gs, is_leaf=_is_spec), [ns(P())] * n_other), + out_shardings=(jax.tree.map(ns, ss, is_leaf=_is_spec), ns(P())), + donate_argnums=(0,), + ) + return self._final[key] + + def init(self, key, scale=0.02, embed_key=None): + """Random master weights in `cfg.weight_dtype`, created directly in the + storage layout. AdamW's `nu` takes the same dtype, as optax's does. + + Norm scales start at one, routed biases at zero, everything else + ~N(0, scale^2) -- a Qwen3.5-family model's leaves by `qwen_init_rule`. + `embed_key` (an MTP model's: chunk 0's table and the last chunk's copy + must start equal, `mtp_shapes`): every token embedding from it, whichever + chunk and stage holds it. + """ + chunks, scfg = self.chunks, self.scfg + qwen = is_qwen(scfg.model) + + def make(key, embed_key): + out = [] + for ch in chunks: + flat, tdef = jax.tree_util.tree_flatten_with_path(chunk_shapes(scfg, ch), is_leaf=_is_shape) + ks = jax.random.split(jax.random.fold_in(key, ch.index), len(flat)) + vals = [] + for k, (path, s), wdt in zip(ks, flat, leaf_dtypes(scfg, ch, "storage")): + name = getattr(path[-1], "key", None) + rule = qwen_init_rule(path) if qwen else "ones" if name == "scale" else "zeros" if name == "bias" else "normal" + if rule == "zeros": + vals.append(jnp.zeros(s, wdt)) + elif rule == "ones": + vals.append(jnp.ones(s, wdt)) + elif rule == "a_log": + lo, hi = A_LOG_RANGE + vals.append(jnp.log(jax.random.uniform(k, s, jnp.float32, minval=lo, maxval=hi)).astype(wdt)) + else: + if embed_key is not None and name == "embedding": + k = embed_key + vals.append((scale * jax.random.normal(k, s, jnp.float32)).astype(wdt)) + out.append(jax.tree.unflatten(tdef, vals)) + return out + + return jax.jit(make, out_shardings=self.s_sh)(key, embed_key) + + def init_opt(self, params): + zeros = jax.jit( + lambda p: { + "mu": jax.tree.map(lambda x: jnp.zeros(x.shape, self.adam["mu_dtype"]), p), + "nu": jax.tree.map(jnp.zeros_like, p), + "count": jnp.zeros((), jnp.int32), + }, + out_shardings=self.opt_sh, + ) + return zeros(params) diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep_aot.py b/src/maxtext/experimental/mpmd/jax/ds_ep_aot.py new file mode 100644 index 0000000000..69b6792d79 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep_aot.py @@ -0,0 +1,956 @@ +# 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. + +"""Ahead-of-time compile of the MPMD DeepSeek pipeline for a TPU slice this +host does not have, before submitting it: every program of every stage, +lowered and compiled against the slice's topology, and what it needs in HBM. + + bash src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh --topology v6e-256 --stages 4 --fsdp 64 --ep 1 \ + --layout physical --layers 8 --experts 16 --mb 8 --gbs 512 [any ds_ep_pipeline flag] + +ds_ep_aot.sh runs this module under the run's libtpu flags, which change what +compiles; `python3 -m maxtext.experimental.mpmd.jax.ds_ep_aot` alone compiles under whatever +LIBTPU_INIT_ARGS holds, with a warning when that is not the run's set. + +The pipeline is built as `ds_ep_pipeline --distributed` builds it on the +slice -- the same flags, plan and stage meshes, here over the topology's +devices (`jax.experimental.topologies`) -- and `Pipeline.precompile` compiles +each stage's programs as that stage's processes would. What the +multi-controller run refuses at startup is checked first, on the topology's +hosts (`multihost_problems`). The report, per stage and per device: the +estimated peak -- `hbm_walk`'s, what the step holds when the stage's +heaviest program runs (the persistent state, the compute weights, the +gradient accumulators and reduced gradients, the live residuals and stash +sets, that program's temporaries and new outputs), plus the generated code +of every program the stage loads -- against the device's HBM, with the +totals of each kind for scale. The exit status is non-zero if a compiled +stage's estimate does not leave `--headroom` of HBM free (HEADROOM, 10%: +what the walk leaves out). + +It needs a TPU backend in this process (any TPU VM, e.g. a v6e-4): the +Pallas kernels pick interpret mode from `jax.default_backend()`, and a CPU +backend would compile those, not the TPU ones. `--batch-split` on Lineage's +layers (ds_ep_pipeline's default impl for DeepSeek-V3; a Qwen3.5-family +model's batch split is ds_ep.split_layers) needs Lineage importable +(ds_ep_lineage.import_lineage; checked first): its programs import it when they +trace -- but for `--transfers-only`, which compiles none of them. + +`--num-slices N` compiles for N slices of the topology (MaxText's +compile_topology_num_slices), e.g. one stage per slice on 2 x v5p-128 under +the v5p flags (the v5p set, and v5p_fsdp_extra's two flags added to it): + + F=src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p_fsdp_extra.flags + MPMD_FLAG_SET=v5p EXTRA_LIBTPU_INIT_ARGS="$(grep -v '^#' $F | tr '\n' ' ')" \ + bash src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh --topology v5p-128 --num-slices 2 --stages 2 --fsdp 4 --ep 16 \ + --layout slices --transport ppermute ... + +The boundary copies between slices compile as send / recv over DCN. +libtpu's compile-only multi-slice topology compiles no program without a +device on its first slice, so such a program compiles moved down until its +lowest slice is the first, each device to the one at the same chip +coordinates (`shift_to_first_slice`): a stage on another slice onto the +first slice's alike devices (`first_slice_meshes`), a copy between two +other slices with its lower one onto the first, a copy within another slice +onto the first (`first_slice_channel`) -- the same programs but for the +device assignment. A stage over devices of several slices does not compile +there: its collectives span part of the slices, where an all-gather failed +a RET_CHECK and a reduce-scatter crashed the process (SIGILL; libtpu +0.0.46), so main refuses it unless --transfers-only. + +`--pathways` compiles for a Pathways run instead -- one client driving every +stage (ds_ep_pipeline under JAX_PLATFORMS=proxy), not one process per host: +stages may share hosts, and what main checks first is what such a run +refuses (`pathways_problems`: --transport relay or xfer, a stage over part of +a chip's TensorCores) rather than what multi-controller JAX does +(`multihost_problems`); the plan is the one the Pathways client makes, no +stage's collectives synchronous (the Pathways servers' compiler offloads them +on chip (0,0,0)'s sub-meshes too; ds_ep_pipeline.Pipeline's `proxy`), and +under --transport ppermute no gradient-norm hop to compile (the client's are +jax.device_puts). Here libtpu compiles, not the Pathways servers' image: + + bash src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh --pathways --topology tpu7x-4x4x4 --num-slices 2 \ + --layout slices --stages 4 --vv 1 --fsdp 8 --ep 8 ... +""" + +from __future__ import annotations + +import argparse +import collections +import json +import math +import os +import sys +import time +import warnings + +import jax +import jax.numpy as jnp +import numpy as np +from jax.sharding import Mesh, NamedSharding, PartitionSpec as P + +from maxtext.experimental.mpmd.jax import ds_ep +from maxtext.experimental.mpmd.jax import ds_ep_pipeline as dsp +from maxtext.experimental.mpmd.jax import pathways +from maxtext.experimental.mpmd.jax import transfer + +# name -> (topology, chip_config, chips_per_host_bounds, wrap, HBM bytes per device) +# (MaxText accelerator_to_spec_map.py; HBM: the device's bytes_limit) +TOPOLOGIES = { + "v6e-16": ("v6e:4x4", "default", (2, 2, 1), (False, False, False), 33546041344), + "v6e-32": ("v6e:4x8", "default", (2, 2, 1), (False, False, False), 33546041344), + "v6e-64": ("v6e:8x8", "default", (2, 2, 1), (False, False, False), 33546041344), + "v6e-128": ("v6e:8x16", "default", (2, 2, 1), (False, True, False), 33546041344), + "v6e-256": ("v6e:16x16", "default", (2, 2, 1), (True, True, False), 33546041344), + # v5p (megacore: one device per chip). HBM: what XLA compiles a program for the slice against on libtpu 0.0.46, + # "available HBM (95.73G)" (G = GiB, as v6e's 31.24G = 33546041344, a v6e-4's): 96 GiB less 279 MiB and 512 B a + # chip of the slice, exactly (from the bytes its compile OOMs exceed by). + "v5p-8": ("v5:2x2x1", "megacore", (2, 2, 1), (False, False, False), 102_786_660_352), + "v5p-16": ("v5:2x2x2", "megacore", (2, 2, 1), (False, False, False), 102_786_658_304), + "v5p-32": ("v5:2x2x4", "megacore", (2, 2, 1), (False, False, False), 102_786_654_208), + "v5p-64": ("v5:2x4x4", "megacore", (2, 2, 1), (False, False, False), 102_786_646_016), + "v5p-128": ("v5:4x4x4", "megacore", (2, 2, 1), (True, True, True), 102_786_629_632), + "v5p-256": ("v5:4x4x8", "megacore", (2, 2, 1), (True, True, True), 102_786_596_864), + # TPU7x: two TensorCores a chip, each a device (8 a host). HBM: the largest one-device program the + # compile-only 4 x 8x8x8 topology compiles on libtpu 0.0.46, temporaries + code + arguments + outputs, + # bisected to 4 KiB ("Used 94.74G of 94.74G hbm" one step above). + "tpu7x-8x8x8": ("tpu7x:8x8x8", "default", (2, 2, 1), (True, True, True), 101_722_758_976), + # 64 chips, 128 devices on 16 hosts (MaxText's tpu7x-128). HBM: the largest one-device program (an int8 + # argument and its sum) the compile-only 1 x and 8 x 4x4x4 topologies compile on libtpu 0.0.46, arguments + + # outputs + code, bisected to 4 KiB (the same probe gives 101_723_929_088 on 4 x 8x8x8, 1.1 MB above that + # entry's figure). + "tpu7x-4x4x4": ("tpu7x:4x4x4", "default", (2, 2, 1), (True, True, True), 101_724_389_376), + # Two cubes, 128 chips, 32 hosts (MaxText's tpu7x-256); HBM as the 8x8x8's. + "tpu7x-4x4x8": ("tpu7x:4x4x8", "default", (2, 2, 1), (True, True, True), 101_722_758_976), +} +G = 2**30 + + +def topology_devices(name, num_slices=1): + """The compile-only devices of `num_slices` slices of topology `name`. + + With jax 0.11.1 and libtpu 0.0.46 the devices of slice k carry + slice_index k, ids (k + 1) * 100000 + i and processes of their own (16 a + slice on a v5p-128), and every slice repeats the chip coordinates; one + slice's devices carry no slice_index at all.""" + from jax.experimental import topologies + + topo, chip, hosts, wrap, _ = TOPOLOGIES[name] + return topologies.get_topology_desc( + platform="tpu", + topology_name=topo, + chip_config_name=chip, + chips_per_host_bounds=hosts, + num_slices=num_slices, + wrap=wrap, + ).devices + + +def shift_to_first_slice(meshes, devices): + """The meshes of one program -- a stage's, or a boundary copy's two -- + where libtpu's compile-only multi-slice topology compiles it -> (meshes, + moved?). `devices`: all of the topology's. + + That topology (libtpu 0.0.46, under jax 0.11.1) compiles no program + without a device on its first slice -- an elementwise one no more than a + stage's, or a copy between two other slices: "INVALID_ARGUMENT: Slice is + empty". One device there is enough: a copy between the first slice and + another compiles, as does a program over part of the first slice. The + slices of a topology are alike, so such a program moves k slices down, k + putting the lowest slice it touches on the first: each device to the one + at the same chip coordinates and core on the slice k below its own, the + meshes in the same order. It compiles to the same program but for the + device assignment -- a copy between slices s and t to one between s - k and + t - k; two stages on one slice stay disjoint. The meshes come back as + they are (the same objects) when they touch the first slice already, or + the devices are of one slice.""" + ks = {dsp.slice_index(d) for d in devices} + if len(ks) < 2 or None in ks: + return list(meshes), False + k = min(dsp.slice_index(d) for m in meshes for d in m.devices.flat) - min(ks) + if not k: + return list(meshes), False + where = lambda d, k=0: (dsp.slice_index(d) - k, tuple(d.coords), getattr(d, "core_on_chip", 0)) + at = {where(d): d for d in devices} + return [ + Mesh(np.array([at[where(d, k)] for d in m.devices.flat], dtype=object).reshape(m.devices.shape), m.axis_names) + for m in meshes + ], True + + +def first_slice_meshes(meshes, devices): + """`meshes` with each stage on one slice other than the first moved onto + the first slice's devices at the same chip coordinates + (`shift_to_first_slice`) -> (meshes, [the stages moved]). A stage over + devices of several slices stays where it is: its collectives, over part of + the slices, do not compile on the compile-only topology anyway (an + all-gather failed a RET_CHECK, a reduce-scatter crashed the process with + SIGILL; libtpu 0.0.46).""" + out, moved = [], [] + for s, m in enumerate(meshes): + if len({dsp.slice_index(d) for d in m.devices.flat}) == 1: + (m2,), shifted = shift_to_first_slice([m], devices) + if shifted: + m = m2 + moved.append(s) + out.append(m) + return out, moved + + +def first_slice_channel(ch, devices): + """A boundary copy's PermuteChannel `ch` where the compile-only topology + compiles it -> (channel, moved?): its two stages' meshes moved together + (`shift_to_first_slice`), a channel of the same name, avals and specs + over them when they move, else `ch` itself.""" + (a, b), moved = shift_to_first_slice([ch.src[0].mesh, ch.dst[0].mesh], devices) + if not moved: + return ch, False + on = lambda m, shardings: ch.treedef.unflatten([NamedSharding(m, s.spec) for s in shardings]) + return transfer.PermuteChannel(ch.treedef.unflatten(ch.avals), on(a, ch.src), on(b, ch.dst), name=ch.name), True + + +def compile_boundaries(p, devices): + """Compile `p`'s boundary-copy programs (--transport ppermute: each runs + on both its stages' devices) that touch a stage `p` compiles (`p.local`), + each where the compile-only topology of `devices` compiles it + (`first_slice_channel`) -> [((a, b), channel compiled, Compiled, lowering + s, compile s, moved?)].""" + out = [] + for (s, t), ch in [*p.channels.items(), *p.sq_channels.items()]: + if s in p.local or t in p.local: + ch, moved = first_slice_channel(ch, devices) + t0 = time.perf_counter() + lo = ch.prog.lower(*ch.lower_args()) + t1 = time.perf_counter() + out.append(((s, t), ch, lo.compile(), t1 - t0, time.perf_counter() - t1, moved)) + return out + + +def print_moved_copies(done): + """Say which of `compile_boundaries`' copies compiled moved -> [their names].""" + names = [ch.name for _, ch, _, _, _, moved in done if moved] + if names: + print( + f' copies {", ".join(names)}: compiled moved down until their lower slice is the first, at the same ' + "chip coordinates (libtpu's compile-only topology compiles no program without a device on its first " + 'slice: "Slice is empty")', + flush=True, + ) + return names + + +def dump_hlo(d, compiled, compiled_stage): + """Each compiled program's HLO text into directory d, as + s_.hlo.txt (s-_...: a copy over stages a and b).""" + os.makedirs(d, exist_ok=True) + for (name, c), s in zip(compiled, compiled_stage): + tag = "-".join(map(str, s)) if isinstance(s, tuple) else s + with open(os.path.join(d, f"s{tag}_{name}.hlo.txt"), "w") as f: + f.write(c.as_text()) + + +def _shard_bytes(aval): + """Bytes of one device's shard of a ShapeDtypeStruct with a sharding.""" + shape = aval.sharding.shard_shape(tuple(aval.shape)) + return math.prod(shape) * jnp.dtype(aval.dtype).itemsize + + +def _tree_bytes(tree): + return sum(_shard_bytes(a) for a in jax.tree.leaves(tree)) + + +# Default share of a device's HBM `report` keeps free past the estimated peak: +# the estimate leaves out run-ahead (the next step's first programs enqueued +# while this one's last run) and, unless asked (`hbm_walk`'s `inputs`), the +# activations in flight between stages. +# Above the largest excess measured so far: 4 x v5p-128's stash plan at M=16 +# peaked 3.3-6.3 GiB (3.5-6.6% of 95.7) over the estimate of the time, which +# summed every buffer. +HEADROOM = 0.1 + + +def residual_set_bytes(p, s): + """{chunk: bytes per device of one (chunk, microbatch) residual set on + stage s}: its input (chunk 0's tokens, else an activation) and the + residuals its forward returns (`ChunkPrograms.res_bytes`): its `n_res` + layer inputs, from which the backward recomputes the chunk, or under + --save-residuals the VJP's residual leaves (`res_avals`), on which the + backward evaluates the VJP instead.""" + act, tok = _shard_bytes(p._avals(s, "act")), _shard_bytes(p._avals(s, "tok")) + return { + c.index: (tok if c.first else act) + getattr(p.progs[c.index], "res_bytes", p.progs[c.index].n_res * act) + for c in p.stage_chunks[s] + } + + +def state_bytes(p, s): + """(storage, mu): bytes per device of stage s's params and of AdamW's mu + (its nu takes the params' dtype: storage again).""" + mu_dtype = p.stages[s].adam["mu_dtype"] + storage = mu = 0 + for c in p.stage_chunks[s]: + tree = p._avals(s, "storage", c) + storage += _tree_bytes(tree) + mu += _tree_bytes(jax.tree.map(lambda a: jax.ShapeDtypeStruct(a.shape, mu_dtype, sharding=a.sharding), tree)) + return storage, mu + + +def live_residuals(p): + """Per stage, the peak of (chunk, microbatch) residual sets alive at once + in program order -- a forward's input and residuals live until its + backward, or a split backward's I (the fused last chunk keeps none) -> + [(peak sets, peak bytes per device)], of sets of `residual_set_bytes`. + What a W reads of them is its W buffer's (`hbm_walk`).""" + out = [] + for s in range(p.S): + size = residual_set_bytes(p, s) + sets = live = peak_sets = peak = 0 + for c, k, m in p.order: + if p.place[c] != s or c == p.C - 1 or k == "W": + continue + sign = 1 if k == "F" else -1 + sets, live = sets + sign, live + sign * size[c] + peak_sets, peak = max(peak_sets, sets), max(peak, live) + out.append((peak_sets, peak)) + return out + + +def _program_memory(exe): + """(temporaries, outputs not aliased to a donated argument) of a compiled + program, in bytes; (0, 0) for one not compiled (a jitted function).""" + m = exe.memory_analysis() if hasattr(exe, "memory_analysis") else None + if m is None: + return 0, 0 + return m.temp_size_in_bytes, max(0, m.output_size_in_bytes - m.alias_size_in_bytes) + + +def hbm_walk(p, s, trace=False, inputs=False): + """Stage s's HBM per device through one step, program by program, from the + plan: what is live when each of its programs runs -> dict(peak (bytes), + at (the program at the peak), parts (bytes by kind at the peak), + uncompiled (the programs it priced without temporaries: no compiled + executable), loop_end_weights (the gathered weights the plan still held + when the microbatch loop ended, which the loop then drops)), and with + `trace` the (program, parts) of every program in turn. + + Live throughout: the storage params, AdamW's nu (their dtype) and mu. + Then, as the step loop holds them (`Pipeline._run`): + weights the gathered compute weights: the update's gather_slots from + the step's start (every chunk without the fusion plan: the + loop gathers them first), a prefetch host's leaf group from its + program on, until fsdp_scope 'repeat' releases the chunk + (`release_at`) or the loop ends -- `step` consumes wc0, so they + are gone by the update; + gacc a chunk's accumulator, from its first gradient write until its + reduce-scatter takes it (a host's leaf group at a time, its own + last backward under rs_self, the stage's final reduce) -- a + split last chunk's in its two parts, the leaves its F (AI) + keeps from its first F, its layers' from its first W; + grads the reduced gradients those produce, until the update; + residuals each (chunk, microbatch)'s input and residuals from its + forward to its backward, or its split backward's I + (`residual_set_bytes`: its layers' inputs, or under + --save-residuals the VJP's residuals; `live_residuals`), stash + sets too; + wbuf a split backward's W buffer (`Pipeline.wbuf_bytes`: the + crossing set and the arguments of I its W reads, a residual or + the cotangent among them) from its I to its W -- a split last + chunk's from its F (AI) to its W; + inputs with `inputs` (else 0), the boundary inputs filed for the + stage, a microbatch's activation shard each: an activation from + the forward that sends it until the forward that takes it, a + cotangent from the backward (or fused last chunk) that sends it + until the backward that takes it (`Pipeline._file`, + `_Box.pop`), the running program's own included. + A program adds, while it runs, its temporaries and the outputs it does not + write into a donated argument (`memory_analysis`, where `precompile` + compiled it; nothing otherwise). An I is a backward to all of this but the + accumulator: its W is the chunk's gradient writer, and hosts what a + backward hosts (reduce-scatters, rs_self; a split last chunk's W hosts + nothing). The update program closes the + step: persistent state, the reduced gradients (donated to it), its + temporaries and the next step's gathered weights. Left out: the boundary inputs + unless `inputs` -- tens of MiB each on the TPU targets here (4096 tokens a + device: 56 MiB at DeepSeek-V3's width, 64 MiB at Qwen3.8's, half that + under CP 2), up to M - 1 of them at once + on a stage under breadth or gpipe (the fused last chunk's cotangents, + piling up on the previous chunk's stage through its forwards): under 1 GiB + at M = 16, inside `HEADROOM`; but 256 MiB a device for a 16-sequence + Qwen3.8 microbatch at fsdp 1 x EP 4, and under --interleave-group G > S + about G - S more of them wait at the first and the last stage + (`schedule.megatron_interleaved`), as they do at a stage fed by a much + cheaper chunk -- and the programs' generated code (`report` adds it).""" + A, chs = p._avals, p.stage_chunks[s] + st = p.stages[s] + leaf_bytes = lambda kind, c: [_shard_bytes(x) for x in jax.tree.leaves(A(s, kind, c))] + w_leaf = {c.index: leaf_bytes("compute", c) for c in chs} + g_leaf = {c.index: leaf_bytes("gacc", c) for c in chs} + r_leaf = {c.index: leaf_bytes("grads", c) for c in chs} + storage, mu = state_bytes(p, s) + res_size = residual_set_bytes(p, s) + # --offload-residuals: a set lives in pinned host memory between its forward and its backward, and on the device + # only while that backward runs (Pipeline._restore brings it back for it) + offload = getattr(p, "offload_residuals", False) + running_res = dict(res_size) + if offload: + res_size = {c: 0 for c in res_size} + persistent = 2 * storage + mu + act = _shard_bytes(A(s, "act")) # one boundary input on the stage: an activation or its cotangent + weights = {} # chunk -> live bytes of its gathered weights + gacc, grads = {}, 0 + live = dict(residuals=0, stash=0, wbuf=0, inputs=0) + wbuf = getattr(p, "wbuf_bytes", {}) + # a split last chunk's accumulator: AI writes the leaves it keeps, the chunk's first W the deferred ones (its layers') + last = p.C - 1 if getattr(p, "split_last", False) else None + deferred = ds_ep.deferred_leaves(p.chunks[last]) if last is not None else () + last_w0 = next((j for j, (c, k, _) in enumerate(p.order) if c == last and k == "W"), None) + if p.overlap: + # what the update gathers for the next step, as the stage's programs say (with self-prefetch only the first + # chunk's leaves besides its routed experts, which 0F0 gathers) + for i, tree in zip(p.gather_slots[s], st._gathered_specs([A(s, "compute", c) for c in chs])): + weights[chs[i].index] = _tree_bytes(tree) + else: + for c in chs: + weights[c.index] = sum(w_leaf[c.index]) + best = dict(peak=-1, at=None, parts=None, uncompiled=[], loop_end_weights=None) + if trace: + best["trace"] = [] + + def priced(at, exe): + """`_program_memory` of program `at`, noting it when nothing compiled it.""" + if not hasattr(exe, "memory_analysis"): + best["uncompiled"].append(at) + return _program_memory(exe) + + def check(at, temp=0, out=0): + parts = dict( + persistent=persistent, + weights=sum(weights.values()), + gacc=sum(gacc.values()), + grads=grads, + residuals=live["residuals"], + stash=live["stash"], + wbuf=live["wbuf"], + inputs=live["inputs"], + temp=temp, + new_outputs=out, + ) + total = sum(parts.values()) + if total > best["peak"]: + best.update(peak=total, at=at, parts=parts) + if trace: + best["trace"].append((at, parts)) + + def boundary(o): + """With `inputs`, op o's change to the inputs waiting on stage s, as the step loop takes and files them + (`Pipeline._take_*` / `_put_*`): a forward of chunk c > 0 takes its activation on its own stage, and files chunk + c + 1's on place[c + 1] (the fused last chunk: chunk c - 1's cotangent on place[c - 1]); a backward, or a split + one's I, takes its cotangent and files chunk c - 1's (chunk 0's files none; a W neither: what it reads of the + cotangent is its W buffer's).""" + if not inputs: + return + c, C = o.c, p.C + if o.kind == "F": + took, to = c > 0, (p.place[c + 1] if c != C - 1 else p.place[c - 1] if c > 0 else None) + elif o.kind in ("B", "I") and c != C - 1: + took, to = True, (p.place[c - 1] if c > 0 else None) + else: # the fused last chunk's no-op backward, a W + return + live["inputs"] += act * ((to == s) - (took and o.s == s)) + + check("step start") + if not p.overlap: # the loop gathers every chunk first: its outputs are the weights above + check(f"gather_s{s}", priced(f"gather_s{s}", st.gather)[0]) + for op in p.ops(): + if op.s != s: # another stage's: only the inputs it files for this one + boundary(op) + continue + if op.desc is None or op.j - 1 in p.fuse: # a no-op, a pair's second half + continue + pair = [op] + ([p.ops()[op.j + 1]] if op.j in p.fuse else []) + back = sum(running_res[o.c] for o in pair if o.kind in ("B", "I")) if offload else 0 + live["residuals"] += back + check(p.op_name(op.j), *priced(p.op_name(op.j), p._exe.get((op.c, op.pair or op.desc)))) + live["residuals"] -= back + for o in pair: + boundary(o) + c = o.c + if o.kind == "F" and c != p.C - 1: + live["residuals"] += res_size[c] + if o.stash: + live["stash"] += p.stash_bytes[o.stash][c] + elif o.kind == "F" and getattr(p, "split_last", False): # the split last chunk's AI: its W buffer + live["wbuf"] += wbuf[c] + elif o.kind in ("B", "I"): + live["residuals"] -= res_size[c] + if o.stash: + live["stash"] -= p.stash_bytes[o.stash][c] + if o.kind == "I": + live["wbuf"] += wbuf[c] + elif o.kind == "W": + live["wbuf"] -= wbuf[c] + if p._writes(c, o.kind) and o.j == p.first_writer[c]: + gacc[c] = sum(b for b, d in zip(g_leaf[c], deferred, strict=True) if not d) if c == last else sum(g_leaf[c]) + if o.j == last_w0: # the split last chunk's first W: its accumulator's other part + gacc[c] += sum(b for b, d in zip(g_leaf[c], deferred, strict=True) if d) + if o.rs: + b, g = o.rs + gacc[b] -= sum(g_leaf[b][i] for i in g) + grads += sum(r_leaf[b][i] for i in g) + if o.rs_self is not None: + gacc.pop(c) + grads += sum(r_leaf[c]) + if o.self_pf: + weights[c] += sum(w_leaf[c][i] for i in p.routed_leaves) + if o.pf: + b, g = o.pf + weights[b] = weights.get(b, 0) + sum(w_leaf[b][i] for i in g) + for b in p.release_at.get(o.j, ()): + weights.pop(b, None) + best["loop_end_weights"] = sum(weights.values()) + weights.clear() # the loop drops its weights before the final reduces (`step` consumes wc0) + fs = p.final_slots[s] if p.overlap else tuple(range(len(chs))) + if fs: + red = st._final.get((fs, p.n_partial_sq[s])) if p.overlap else st.reduce + check(f"reduce_s{s}", *priced(f"reduce_s{s}", red)) + for i in fs: + gacc.pop(chs[i].index, None) + grads += sum(r_leaf[chs[i].index]) + check(f"update_s{s}", *priced(f"update_s{s}", st.update_gather if p.overlap else st.update)) + return best + + +def stage_programs(p): + """{stage: [(program name, its memory analysis)]} of what `precompile` + compiled; a boundary copy's program (compiled_stage (a, b)) runs on both + its stages' devices and counts on both.""" + out = collections.defaultdict(list) + for (name, c), s in zip(getattr(p, "compiled", ()), getattr(p, "compiled_stage", ())): + m = c.memory_analysis() + for t in s if isinstance(s, tuple) else (s,): + out[t].append((name, m)) + return out + + +def report(p, hbm, headroom=HEADROOM, inputs=False): + """Per stage this process compiles (`p.local`): what it holds in HBM per + device at the step's peak, estimated, against `hbm` bytes -> [row]. + + The estimate is `hbm_walk`'s peak -- what is live when the stage's + heaviest program runs, the program's own temporaries and new outputs + included, and with `inputs` the boundary inputs waiting on the stage + (`live_inputs_gib`; 0 without) -- plus the generated code of every program + the stage loads. It fits when it leaves `headroom` of `hbm` free + (HEADROOM: what the walk leaves out). The other fields are totals for + scale -- every chunk's compute weights, accumulators and gradients (the + walk's `live_*` are what the plan holds of them at the peak), the peak + residual sets, a split backward's peak W buffers (`wbuf_gib`: + Pipeline.peak_wbuf_gib), the largest temporaries of any one program -- and + `est_total_gib`, all of those summed: the estimate before the walk. + `uncompiled`: the programs the walk priced without temporaries, none where + `precompile` compiled the stage.""" + if not 0 <= headroom < 1: + raise ValueError(f"headroom is a share of HBM in [0, 1), not {headroom}") + A = p._avals + rows = [] + res = live_residuals(p) + stash = p.peak_stash_gib() if p.modes else [0.0] * p.S + wbufs = p.peak_wbuf_gib() if getattr(p, "split_chunks", None) else [0.0] * p.S + by_stage = stage_programs(p) + for s in sorted(p.local) if p.multi or p.aot else range(p.S): # one controller (mem_probe's) prices every stage + chs = p.stage_chunks[s] + storage, mu = state_bytes(p, s) + compute = sum(_tree_bytes(A(s, "compute", c)) for c in chs) + gacc = sum(_tree_bytes(A(s, "gacc", c)) for c in chs) + grads = sum(_tree_bytes(A(s, "grads", c)) for c in chs) + sets, resid = res[s] + temps = sorted(((m.temp_size_in_bytes, n) for n, m in by_stage[s] if m is not None), reverse=True) + code = sum(m.generated_code_size_in_bytes for _, m in by_stage[s] if m is not None) + walk = hbm_walk(p, s, inputs=inputs) + peak = walk["peak"] + code + total = storage * 2 + mu + compute + gacc + grads + resid + (stash[s] + wbufs[s]) * G + (temps[0][0] if temps else 0) + lv = {k: v / G for k, v in walk["parts"].items()} + rows.append( + dict( + stage=s, + storage_gib=storage / G, + adam_gib=(storage + mu) / G, + compute_gib=compute / G, + gacc_gib=gacc / G, + grads_gib=grads / G, + residual_sets=sets, + residuals_gib=resid / G, + stash_gib=stash[s], + wbuf_gib=wbufs[s], + max_temp_gib=(temps[0][0] / G if temps else 0), + max_temp_program=(temps[0][1] if temps else None), + code_gib=code / G, + peak_at=walk["at"], + live_weights_gib=lv["weights"], + live_gacc_gib=lv["gacc"], + live_grads_gib=lv["grads"], + live_residuals_gib=lv["residuals"], + live_stash_gib=lv["stash"], + live_wbuf_gib=lv["wbuf"], + live_inputs_gib=lv["inputs"], + live_temp_gib=lv["temp"] + lv["new_outputs"], + persistent_gib=lv["persistent"], + est_peak_gib=peak / G, + est_total_gib=total / G, + hbm_gib=hbm / G, + headroom_gib=headroom * hbm / G, + fits=peak < (1 - headroom) * hbm, + uncompiled=walk["uncompiled"], + top_temps=[(n, round(t / G, 3)) for t, n in temps[:6]], + ) + ) + return rows + + +def exit_unless_fits(rows, hbm): + """Exit non-zero, naming them, if any stage of the report does not fit: + its estimated peak leaves less than its headroom of `hbm` bytes per + device free.""" + bad = [r["stage"] for r in rows if not r["fits"]] + if bad: + room = max(r["headroom_gib"] for r in rows) + sys.exit( + f"ds_ep_aot: stages {bad} do not fit: estimated peak over the {hbm / G:.2f} GiB of HBM per device " + f"less {room:.2f} GiB of headroom" + ) + + +def multihost_problems(meshes, transport): + """What `ds_ep_pipeline --distributed` refuses at startup on these stage + meshes, and a Pipeline built ahead of time never checks (one process, no + runtime channels) -> [message]: stages sharing processes; else, under + transport 'xfer', each boundary and process `transfer.xfer_peers` rejects + (one pulling from, or giving to, more than one peer host), over every two + stages (the gradient norm's scalar copies link them all).""" + out = [f"stages {a} and {b} share processes {procs}" for a, b, procs in dsp.shared_stage_hosts(meshes)] + if transport == "xfer" and not out: + pids = sorted({d.process_index for m in meshes for d in m.devices.flat}) + for a in range(len(meshes)): + for b in range(len(meshes)): + if a == b: + continue + for pid in pids: + try: + transfer.xfer_peers(meshes[a], meshes[b], pid) + except ValueError as e: + out.append(f"s{a}->s{b}: {e}") + return out + + +def pathways_problems(meshes, transport): + """What a Pathways run of these stage meshes refuses -- one client process driving every device (ds_ep_pipeline + under JAX_PLATFORMS=proxy) -> [message]: --transport relay or xfer (main refuses them there, they move arrays between + processes: pathways.check_transport's message, as main and mem_probe give it), and each stage over part of a chip's + TensorCores (`dsp.split_chip_stages`: the Pathways servers refuse it, "a subslice must use all logical devices of + each chip"). Stages sharing hosts are no problem there.""" + out = [] + try: + pathways.check_transport(transport) + except ValueError as e: + out.append(str(e)) + split = collections.defaultdict(list) + for s, (k, coords), held, of in dsp.split_chip_stages(meshes): + split[s].append((k, coords, held, of)) + for s, chips in split.items(): + k, coords, held, of = chips[0] + on = "" if k is None else f" of slice {k}" + out.append( + f"stage {s} holds {held} of the {of} TensorCores of chip {','.join(map(str, coords))}{on}" + + (f" (and part of {len(chips) - 1} more chips)" if len(chips) > 1 else "") + + ": a subslice must use all logical devices of each chip" + ) + return out + + +def stage_extent(m, devs): + """Where stage mesh `m` sits on the slice of `devs`: its hosts and chip coordinates, with the z range on a slice + more than one chip deep (v5p-16 up; every TPU device has 3 coords, z 0 throughout a v6e or a v5p-8).""" + procs = sorted({d.process_index for d in m.devices.flat}) + xs = sorted({d.coords[0] for d in m.devices.flat}) + ys = sorted({d.coords[1] for d in m.devices.flat}) + zs = sorted({d.coords[2] for d in m.devices.flat}) + z = f" z {zs[0]}..{zs[-1]}" if any(d.coords[2] for d in devs) else "" + return f"hosts {procs[0]}..{procs[-1]} ({len(procs)}), chips x {xs[0]}..{xs[-1]} y {ys[0]}..{ys[-1]}{z}" + + +def main(argv=None): + ap = dsp.make_parser() + ap.add_argument("--topology", default="v6e-256", choices=sorted(TOPOLOGIES)) + ap.add_argument("--threads", type=int, default=32, help="compile threads") + ap.add_argument( + "--stages-to-compile", default="all", help="'all' or a comma list: the stages whose programs to compile" + ) + ap.add_argument("--hlo-dir", default="", help="dump every compiled program's HLO text here") + ap.add_argument( + "--headroom", + type=float, + default=HEADROOM, + help="share of HBM the estimated peak must leave free to fit (what the estimate leaves out: " + "run-ahead, activations in flight between stages); default %(default)s", + ) + ap.add_argument( + "--transfers-only", action="store_true", help="compile only the boundary-copy programs (--transport ppermute)" + ) + ap.add_argument( + "--num-slices", + type=int, + default=1, + help="slices of --topology (MaxText's compile_topology_num_slices): one stage per slice with " + "--layout slices (a stage over devices of several slices does not compile on libtpu " + "0.0.46's compile-only topology), and with --transport ppermute the boundary copies " + "between slices compile too (send / recv over DCN)", + ) + ap.add_argument( + "--pathways", + action="store_true", + help="compile for a Pathways run -- one client driving every stage (JAX_PLATFORMS=proxy) -- not for " + "multi-controller JAX: stages may share hosts but not chips (a stage over part of a chip's TensorCores is " + "refused there), --transport native or ppermute, and the plan the Pathways client makes (no stage's " + "collectives synchronous: the Pathways servers' compiler offloads them on chip (0,0,0)'s sub-meshes too)", + ) + a = ap.parse_args(argv) + if a.num_slices < 1: + sys.exit(f"--num-slices must be at least 1, not {a.num_slices}") + if not 0 <= a.headroom < 1: + sys.exit(f"--headroom is a share of HBM in [0, 1), not {a.headroom}") + if a.pathways and (bad := pathways_problems([], a.transport)): # before anything builds, as main says it there + sys.exit(f"ds_ep_aot --pathways: {bad[0]}") + # No persistent compile cache: jax cannot load an executable compiled for + # compile-only topology devices (every read fails, "PjRtCompiler must be + # constructed with a Client", and recompiles), so it would only grow. + jax.config.update("jax_enable_compilation_cache", False) + if jax.default_backend() != "tpu": + sys.exit( + f"ds_ep_aot needs a TPU backend in this process (Pallas kernels choose interpret mode from " + f"jax.default_backend(), here {jax.default_backend()!r}); run it on a TPU VM" + ) + # --batch-split on Lineage's layers: its programs import it (--transfers-only compiles none of them) + if not a.transfers_only and (why := dsp.lineage_missing(a)) is not None: + sys.exit(f"ds_ep_aot: --batch-split: {why}") + devs = topology_devices(a.topology, a.num_slices) + where = a.topology if a.num_slices == 1 else f"{a.num_slices} x {a.topology}" + if a.num_slices > 1 and len({dsp.slice_index(d) for d in devs} - {None}) != a.num_slices: + sys.exit( + f"ds_ep_aot: jax.experimental.topologies built no {where} topology here: its devices are on " + f"slices {sorted({str(dsp.slice_index(d)) for d in devs})}" + ) + hbm = TOPOLOGIES[a.topology][4] + if a.stages * a.fsdp * a.ep != len(devs): + sys.exit(f"{a.stages} stages x fsdp {a.fsdp} x ep {a.ep} != the {len(devs)} devices of {where}") + meshes = dsp.stage_meshes(a.stages, a.fsdp, a.ep, devices=devs, layout=a.layout) + if span := dsp.slice_spanning_stages(meshes): + # Before anything compiles (the pipeline's build may probe a stage's + # collectives): over part of the topology's slices they do not compile. + on = lambda s: sorted({dsp.slice_index(d) for d in meshes[s].devices.flat}) + why = ( + ", ".join(f"stage {s} spans slices {on(s)}" for s in span) + f" of {a.num_slices}: their FSDP and EP " + "collectives cross DCN (one stage per slice is --layout slices)" + ) + if not a.transfers_only and any(len(on(s)) < a.num_slices for s in span): + sys.exit( + f"ds_ep_aot: {why}; libtpu 0.0.46's compile-only topology compiles no collective over part of its " + "slices (an all-gather failed a RET_CHECK, a reduce-scatter crashed the process: SIGILL). " + "--transfers-only compiles the boundary copies alone" + ) + warnings.warn(why, RuntimeWarning) + if a.transfers_only and a.ep_collectives == "auto": + # Only the boundary copies compile, so the stages' collective flavours do not matter: pin the choice the + # pipeline's build asks libtpu (sparsecore_offload_available compiles an all-gather over each stage, which + # over part of the slices does not compile -- the refusal above). + a = argparse.Namespace(**{**vars(a), "ep_collectives": "xla"}) + print("--transfers-only: the stages' collectives taken as xla, unprobed (no stage program compiles)", flush=True) + lineage_sc = None + if a.transfers_only and dsp.uses_lineage(a): + # the same for Lineage's SparseCore regions (the pipeline's build asks libtpu over each whole stage): the device + # rule's answers, unprobed + sync = frozenset() if a.pathways else None # a Pathways run: no stage synchronous (sync_collective_stages) + lineage_sc = tuple(bool(dsp.rule_offloads(meshes, s, ds_ep.FE, sync)) for s in range(len(meshes))) + proxy = True if a.pathways else None # None: the pipeline asks the devices (a compile-only topology's: not Pathways) + t0 = time.perf_counter() + cmeshes, moved = first_slice_meshes(meshes, devs) + if moved: + # The programs of the stages on other slices than the first are built on + # the first slice's alike devices (q), with no boundary copies (two stages + # may share devices there). The pipeline over the real stages (p: the + # plan, the summary, the copies between slices) takes q's per-stage EP + # collective flavours, and under --batch-split on Lineage's layers q's + # answers for their SparseCore regions: libtpu's probe + # (sparsecore_offload_available) cannot compile on those slices either. + # The FSDP flavour is one for every stage, which p's build resolves from + # the same flags as q's. + q = dsp.build( + argparse.Namespace(**{**vars(a), "transport": "native"}), + meshes=cmeshes, + aot=True, + stage_lineage_sparsecore=lineage_sc, + proxy=proxy, + ) + p = dsp.build( + argparse.Namespace(**{**vars(a), "ep_collectives": ",".join(c.ep_collectives for c in q.stage_scfg)}), + meshes=meshes, + aot=True, + stage_lineage_sparsecore=q.lineage_sc, + proxy=proxy, + ) + else: + p = q = dsp.build(a, meshes=meshes, aot=True, stage_lineage_sparsecore=lineage_sc, proxy=proxy) + flags = os.environ.get("LIBTPU_INIT_ARGS", "").strip() + print( + f"AOT for {where} ({len(devs)} x {devs[0].device_kind}, " + f"{len({d.process_index for d in devs})} hosts); built in {time.perf_counter() - t0:.1f}s", + flush=True, + ) + print(f"LIBTPU_INIT_ARGS={flags!r}", flush=True) + if "--xla_max_concurrent_async_collective_permutes=" not in flags: # the one every launcher adds + warnings.warn( + "LIBTPU_INIT_ARGS is not the run's flag set, which changes what compiles (run " + "src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh: the libtpu flag set MPMD_FLAG_SET names, plus the MPMD one)", + RuntimeWarning, + ) + # multi-controller JAX's warning (its native copy hangs between slices); not asked when planned for one Pathways + # client (--pathways), whose boundary copies the Pathways servers carry (the note) + if not a.pathways and (msg := dsp.cross_slice_warning(meshes, a.transport)): + warnings.warn(msg, RuntimeWarning) + elif note := dsp.cross_slice_note(meshes, a.transport, proxy=proxy): + print(f" boundary copies: {note}", flush=True) + elif a.transport == "relay" and len({dsp.slice_index(d) for m in meshes for d in m.devices.flat} - {None}) > 1: + # it crosses them, on the hosts: the boundaries are no programs (ppermute's are, and compile below) + print( + " boundary copies: --transport relay moves them between the slices on the hosts at run time, so none " + "compiles here", + flush=True, + ) + print(p.summary(), flush=True) + for s, m in enumerate(meshes): + on = sorted({str(dsp.slice_index(d)) for d in m.devices.flat}) + sl = f'slice {",".join(on)}, ' if a.num_slices > 1 else "" + print(f" stage {s}: {sl}{stage_extent(m, devs)}", flush=True) + if moved: + print( + f" stages {moved}: their programs compile on slice {min(map(dsp.slice_index, devs))}'s devices at the " + "same chip coordinates (libtpu's compile-only topology compiles no program without a device on its " + 'first slice: "Slice is empty")', + flush=True, + ) + if a.pathways: + bad, who = pathways_problems(meshes, a.transport), "a Pathways run (one client driving every stage)" + print( + " planned for one Pathways client (--pathways): stages may share hosts, no stage's collectives synchronous", + flush=True, + ) + else: + bad, who = multihost_problems(meshes, a.transport), "`ds_ep_pipeline --distributed`" + if bad: + sys.exit( + f"ds_ep_aot: {who} refuses this on {where} at startup:\n " + + "\n ".join(bad[:8]) + + (f"\n ... ({len(bad)} in all)" if len(bad) > 8 else "") + ) + if a.stages_to_compile != "all": + p.local = q.local = frozenset(int(x) for x in a.stages_to_compile.split(",")) + if not p.local <= set(range(p.S)): + sys.exit(f"--stages-to-compile {a.stages_to_compile}: the stages are 0..{p.S - 1}") + if a.transfers_only: + if not any(s in p.local or t in p.local for s, t in [*p.channels, *p.sq_channels]): + sys.exit( + f"--transfers-only: no boundary-copy programs on stages {sorted(p.local)} (they exist with " + "--transport ppermute)" + ) + t0 = time.perf_counter() + done = compile_boundaries(p, devs) + for _, ch, c, _, _, _ in done: + m = c.memory_analysis() + print( + f" {ch.name}: compiled over {dict(ch.union.shape)}; temp {m.temp_size_in_bytes / 2**20:.1f} MiB, " + f"args {m.argument_size_in_bytes / 2**20:.1f} MiB, out {m.output_size_in_bytes / 2**20:.1f} MiB", + flush=True, + ) + print(f"compiled {len(done)} boundary-copy programs in {time.perf_counter() - t0:.1f}s", flush=True) + print_moved_copies(done) + if a.hlo_dir: + dump_hlo(a.hlo_dir, [(getattr(ch.prog, "__name__", "?"), c) for _, ch, c, *_ in done], [st for st, *_ in done]) + return [] + n, dt = q.precompile(threads=a.threads) + copies_moved = [] + if q is not p: + # the copies between the real stages, which q has none of: they count on both their stages + t0 = time.perf_counter() + done = compile_boundaries(p, devs) + for st, ch, c, tl, tc, _ in done: + q.compiled.append((getattr(ch.prog, "__name__", "?"), c)) + q.compiled_stage.append(st) + q.compile_times.append((tl, tc)) + n += 1 + dt += time.perf_counter() - t0 + copies_moved = print_moved_copies(done) + tl = sum(x for x, _ in q.compile_times) + tc = sum(y for _, y in q.compile_times) + print( + f"compiled {n} programs for stages {sorted(q.local)} in {dt:.1f}s (summed over threads: lowering " + f"{tl:.0f}s, XLA compile {tc:.0f}s)", + flush=True, + ) + if a.hlo_dir: + dump_hlo(a.hlo_dir, q.compiled, q.compiled_stage) + rows = report(q, hbm, a.headroom) + for r in rows: + print( + f" stage {r['stage']}: per device GiB -- storage {r['storage_gib']:.2f} (x2 with nu), mu " + f"{r['adam_gib'] - r['storage_gib']:.2f}; at the peak ({r['peak_at']}): compute weights " + f"{r['live_weights_gib']:.2f} (of {r['compute_gib']:.2f}), grad acc {r['live_gacc_gib']:.2f} (of " + f"{r['gacc_gib']:.2f}), grads {r['live_grads_gib']:.2f}, residuals {r['live_residuals_gib']:.2f}, stash " + f"{r['live_stash_gib']:.2f}, " + + (f"W buffers {r['live_wbuf_gib']:.2f} (peak {r['wbuf_gib']:.2f}), " if r["wbuf_gib"] else "") + + f"the program's temporaries + new outputs {r['live_temp_gib']:.2f}; code " + f"{r['code_gib']:.2f} => est. peak {r['est_peak_gib']:.2f} of {r['hbm_gib']:.2f} less " + f"{r['headroom_gib']:.2f} headroom {'OK' if r['fits'] else 'DOES NOT FIT'} (every buffer summed: " + f"{r['est_total_gib']:.2f})", + flush=True, + ) + print(f" largest temporaries: {r['top_temps']}", flush=True) + if r["uncompiled"]: + u = r["uncompiled"] + print( + f" WARNING: {len(u)} programs priced without temporaries (not compiled): " + f"{', '.join(u[:8])}{' ...' if len(u) > 8 else ''}", + flush=True, + ) + if a.json: + dsp.resolved_config(a, p) + with open(a.json, "w") as f: + json.dump( + { + "config": vars(a), + "libtpu_init_args": flags, + "summary": p.summary(), + "programs": n, + "compile_s": dt, + "stages": rows, + "compiled_on_first_slice": moved, + "copies_moved": copies_moved, + }, + f, + indent=1, + default=str, + ) + exit_unless_fits(rows, hbm) + return rows + + +if __name__ == "__main__": + main() diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh b/src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh new file mode 100755 index 0000000000..9d0a5c8ff0 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh @@ -0,0 +1,78 @@ +#!/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. + +# AOT-compile the multi-host MPMD DeepSeek pipeline for a slice (ds_ep_aot.py) under +# the libtpu flags the run itself gets (ds_ep_multihost.sh / ds_ep_run.sh): they +# change what compiles -- e.g. the scoped VMEM limit the megablox tiles need. So +# give it the run's MPMD_FLAG_SET, LIBTPU_INIT_ARGS_OVERRIDE and EXTRA_LIBTPU_INIT_ARGS. +# +# bash src/maxtext/experimental/mpmd/jax/ds_ep_aot.sh --topology v6e-256 --stages 4 --fsdp 64 --ep 1 --layout physical ... +# +# Environment: PYTHON (default python3); MAXTEXT_DIR as in ds_ep_run.sh (that checkout's +# src/ first on PYTHONPATH, so the programs compile the MaxText kernels -- ragged sort, +# megablox -- a run with the same MAXTEXT_DIR calls; stops if `maxtext` resolves anywhere +# else); MPMD_FLAG_SET (default tpu7x), LIBTPU_INIT_ARGS_OVERRIDE / EXTRA_LIBTPU_INIT_ARGS +# as in ds_ep_run.sh, and so is LIBTPU_INIT_ARGS. +set -euo pipefail +# This script's directory and the directory the package imports from, every symlink resolved, without `cd` (as in +# ds_ep_run.sh). +SELF="$(readlink -f "${BASH_SOURCE[0]}")" +HERE="${SELF%/*}" +# The package, and ROOT, the directory it imports from: HERE one level up for each component of the package's name. +PKG=maxtext.experimental.mpmd.jax +ROOT=$HERE +for _ in ${PKG//./ }; do ROOT=${ROOT%/*}; done +ROOT=${ROOT:-/} +PYTHON=${PYTHON:-python3} +if [[ -n "${MAXTEXT_DIR:-}" ]]; then + MAXTEXT_DIR="$(CDPATH='' cd "$MAXTEXT_DIR" && pwd)" + export PYTHONPATH="$MAXTEXT_DIR/src${PYTHONPATH:+:$PYTHONPATH}" +fi +# LIBTPU_INIT_ARGS, as every launcher builds it (ds_ep_run.sh and ds_ep_multihost.sh hold the same lines). +FLAG_SET=${MPMD_FLAG_SET:-tpu7x} +SET_FLAGS="" +if [[ $FLAG_SET != none ]]; then + SET_FILE="$HERE/libtpu_flags/$FLAG_SET.flags" + if [[ $FLAG_SET == */* || ! -f $SET_FILE ]]; then + SETS="none" + for f in "$HERE"/libtpu_flags/*.flags; do + if [[ -f $f ]]; then f=${f##*/}; SETS+=", ${f%.flags}"; fi + done + echo "ds_ep_aot.sh: MPMD_FLAG_SET=$FLAG_SET: no such libtpu flag set ($SETS; the files of $HERE/libtpu_flags)" >&2 + exit 1 + fi + SET_TEXT="$(sed -e 's/#.*//' "$SET_FILE")" || exit 1 # '#' starts a comment + read -r -d '' -a SET <<< "$SET_TEXT" || true # one flag a word, unglobbed + SET_FLAGS="${SET[*]-}" # joined by single spaces +fi +MPMD_LIBTPU_INIT_ARGS="--xla_max_concurrent_async_collective_permutes=64" +export LIBTPU_INIT_ARGS="${LIBTPU_INIT_ARGS_OVERRIDE-$SET_FLAGS} $MPMD_LIBTPU_INIT_ARGS ${EXTRA_LIBTPU_INIT_ARGS:-}" +export PYTHONHASHSEED=0 +cd "$ROOT" +if [[ -n "${MAXTEXT_DIR:-}" ]]; then + # Found, not imported (cheap), from the directory the AOT runs in. + "$PYTHON" - "$MAXTEXT_DIR/src" <<'EOF' +import importlib.util +import os +import sys + +spec = importlib.util.find_spec('maxtext') +path = spec and (spec.origin or next(iter(spec.submodule_search_locations or ()), None)) +if not path or not os.path.realpath(path).startswith(os.path.realpath(sys.argv[1]) + os.sep): + sys.exit(f'ds_ep_aot.sh: `maxtext` resolves to {path}, not under {sys.argv[1]}') +EOF +fi +exec "$PYTHON" -m "$PKG.ds_ep_aot" "$@" diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep_lineage.py b/src/maxtext/experimental/mpmd/jax/ds_ep_lineage.py new file mode 100644 index 0000000000..10fefb8fa3 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep_lineage.py @@ -0,0 +1,1130 @@ +# 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. + +"""ds_ep's batch-split chunks on Lineage's code: the adapter to MaxText's Lineage DeepSeek-V3 layers. + +Lineage (MaxText src/maxtext/experimental/lineage, the MLPerf DeepSeek-V3 batch-split stack) runs a decoder layer +as two half-microbatches, mb0 and mb1, in eight program_order phases whose EP all-gathers / reduce-scatters run on +SparseCore beside the other half's attention or experts. This module runs a ds_ep chunk's decoder layers on those +layer functions -- the router, dispatch and combine (dsv3_router), the gmmv2 expert kernels, Lineage's MLA and +splash attention, ops.rms_norm -- chained the way Lineage's driver chains them, but without its per-layer weight +collect / gradient reduce hooks: ds_ep gathers the weights once per step (or visit) and reduce-scatters the +accumulated gradients once per step. ds_ep's storage, optimizer, init and checkpoints stay in MaxText's layout; +`Region` converts the gathered compute copies to Lineage's collected layout inside the program and the gradients +back (`sparse_from_maxtext` / `sparse_to_maxtext`), shard-locally. Besides those hooks and its DeepSeek-V3 recipe's +other XLA flags (`COMPILER_OPTIONS`), two parts of MaxText's Lineage setup do not run here: its post-scheduler XLA +pass, which its use_lineage path always registers and which moves every async start as early and every done as late +as the schedule allows (`import_lineage`: XLA's own schedule stands), and the fp8 quantization that recipe sets +(lineage_quantization fp8_full; MaxText's default, none, is bf16 as here) -- the layers run unquantized, in bf16 +(`layer_kwargs`). + +Execution context. Lineage's functions are global-view code over an all-Explicit mesh that open their own +shard_maps and read layouts from the arrays' sharding types: they cannot run inside ds_ep's per-program shard_map, +only in a jit at global view over the stage mesh (shard_mode 'explicit'). They run on a VIEW of ds_ep's stage mesh +m2 ('fsdp', 'expert') with a trailing size-1 axis, m3 = ('fsdp', 'expert', 'attn') over the same devices +(`a3_mesh`), under the logical-axis mapping `AXIS_MAPPING` ("A3"): every device runs all heads of its own rows -- +ds_ep's own compute layout, MLA's collectives over the size-1 'attn' axis are no-ops -- experts over 'expert', FSDP +over 'fsdp'. The activation P(('fsdp','expert'),'attn',None) on m3 is ds_ep's P(FE,None,None) on m2 device for +device, and every m2 <-> m3 hand-off is a jax.reshard that moves nothing. The gathered weights are typed `reduced` +over the axes Lineage collects them along (dsv3_sparse_layer._w_ici_axes), so Lineage's own AD gives `unreduced` +gradients with no collective in the layer -- ds_ep's explicit accumulator types (ds_ep.chunk_gacc_specs). + +The driver. `Region` is a jax.custom_vjp: its forward chains dsv3_sparse_layer's prologue(w0) -> +scan_body(w_l, w_l+1) for l < n-1 -> epilogue(w_n-1) for ANY n >= 1 MoE layers (Lineage's own driver, +ops.w_collect_pipelined_scan_prologue_epilogue, asserts n >= 3), its backward Lineage's explicit backward functions +in reverse; its primal, what a program without AD runs (ds_ep's F), is that forward without residuals and with +Lineage's activation bank sized for no layer -- the bank only spares the backward recomputing the gate GMM, so a +forward-only program would fill it and never read it (`_chain_fwd`). All three run under +jax.sharding.use_abstract_mesh(m3.abstract_mesh) themselves, so ds_ep can take a jax.vjp of the region from the m2 +context (an AD transpose of Lineage's code outside that context raises ShardingTypeError). Each is a nested jax.jit +with a stable identity, so the F / B / A / FB programs of one chunk structure trace each once: on the TPU7x a second +B program of one region lowered in 17.0 s against the first's 45.8 s, retracing nothing (one-host TPU7x 2x2x1, +2026-11; the region's lowering, not its tracing, is per program). + +jax 0.11.1 trap: jnp.stack (lax.stack_p) of `unreduced`-typed values multiplies them by the product of the +unreduced axes' sizes (the type is right, the value is not; also in 0.11.2 and 0.12.0.dev). Lineage's own driver +stacks its scanned layers' gradients that way (ops._interleave_arrays): fed gathered weights typed reduced, its +hooks leave them unreduced, and at n=5 on the local TPU7x its layers 3 and 4 come out 4x (the routed experts' 2x). +This module never stacks an unreduced value at jit level: the per-layer gradients are concatenated inside a +shard_map, on device-local arrays. + +Lineage is imported lazily (`import_lineage`): this module imports where Lineage does not (its modules import +typeguard and jaxtyping, which MaxText's TPU requirements do not bring), and its tests that need Lineage skip there +-- MAXTEXT_MPMD_REQUIRE_LINEAGE=1 makes that a failure instead (ds_ep_lineage_test). +""" + +from __future__ import annotations + +import collections +import contextlib +import dataclasses +import functools +import importlib +import os +import sys +import threading +import types +import weakref + +import jax +import jax.numpy as jnp +from jax.sharding import AxisType, Mesh, NamedSharding, PartitionSpec as P + +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig +from maxtext.experimental.mpmd.jax import ds_ep + +FE = ds_ep.FE +ATTN = "attn" +# Lineage's logical axes (dsv3_sharding.LOGICAL_AXES) on the A3 view m3. Lineage's typing rule (traced on CPU at +# DeepSeek-V3 sizes, run here on TPU): the token axes fsdp_attention + attention must equal expert + fsdp_moe, with +# expert and fsdp_moe disjoint -- transposing a dot against a weight `reduced` over R needs the contraction (token) +# dims sharded over exactly R, and the router / shared experts are collected over (expert, fsdp_moe), the pre- and +# post-attention norms and the q / kv down-projections over (fsdp_attention, attention), the q / kv norms over +# fsdp_attention alone (dsv3_sparse_layer._w_ici_axes). 'attention' must name a real mesh axis (MLA all-gathers its +# latents over it, dsv3_mla.q_down_projection: `()` fails with "unbound axis name"), so the size-1 'attn'; and a +# physical axis may carry a Lineage logical name only where the mapping is the identity (ops.physical_pspec re-maps +# known names, init_activation_bank's spec collides otherwise) -- 'expert' is. +AXIS_MAPPING = {"dcn": (), "attention": ATTN, "fsdp_attention": FE, "expert": "expert", "fsdp_moe": ("fsdp", ATTN)} +ACT2 = P(FE, None, None) # ds_ep's activation on m2 +ACT3 = P(FE, ATTN, None) # Lineage's (dsv3_sharding.activation_sharding) on m3: the same blocks +_NO_MESH = jax.sharding.AbstractMesh((), ()) # the empty abstract mesh (Region's trace context) +# Lineage's MoE chunk size relative to a device's balanced load of routed slots (dropless whatever it is; the +# number of chunk-loop trips depends on it, and with more than one chunk the partial sums add in bf16, +# dsv3_sparse_layer._routed_experts_chunked_impl). MaxText's DeepSeek-V3 Lineage recipe runs 3.0 +# (deepseek3-671b-lineage.yml's capacity_factor). +CAPACITY_FACTOR = 2.0 +# Lineage's cross-layer activation bank: rows for this many times the balanced gating activations of a call's +# layers (dsv3_sparse_layer.init_activation_bank); a chunk that overflows them goes to scratch rows and the +# backward recomputes its gate GMM -- a memory-for-recompute knob, bitwise neutral. Not ds_ep's +# ragged_buffer_factor (the ring's token-dropping dispatch buffer), which Lineage has no counterpart of. A +# forward-only program sizes the bank for no layer (Region's primal: `_chain_fwd`), whatever this is. +BANK_FACTOR = 1.2 +# Per-program compiler options of a Lineage program on TPU (`compiler_options`). The scoped-VMEM limit is +# deepseek3-671b-lineage.yml's (compile_xla_flags): at the default 32 MiB the splash dkv kernel at 2048 blocks fails +# to compile (CompileTimeScopedVmemOom, 33.46M > 32.00M); ds_ep's TPU7x production LIBTPU flags carry it, runs without +# them do not. Lineage's other recipe flags (e.g. --xla_tpu_enable_offloading_copy_to_sparsecore=false) are not +# adopted, nor is its post-scheduler overlap pass, which is no flag (`import_lineage`). +COMPILER_OPTIONS = {"xla_tpu_scoped_vmem_limit_kib": "65536"} + + +# --------------------------------------------------------------- Lineage, lazily +_PKG = "maxtext.experimental.lineage" +_LIN = None +_LIN_LOCK = threading.Lock() + + +def import_lineage(): + """Lineage's modules this adapter calls, as a namespace (imported once). ImportError where Lineage does not + import: a module it imports is missing (typeguard or jaxtyping, which MaxText's TPU requirements do not bring). + + The sparse / dense layer chain imports no tensorflow: only lineage/dsv3.py, dsv3_model.py and + interop/maxtext_layout.py reach xla_transforms' hlo_pb2 import, and none of them is loaded here. So Lineage's + post-scheduler XLA pass (xla_transforms/max_async_overlap_transform.py: every async start as early, every done as + late as the schedule allows) is not registered either: only Lineage's whole-model entry point registers it + (dsv3.dsv3; MaxText's use_lineage path always has it do so, lineage_adapter.dsv3_config_from_maxtext), and this + adapter calls the layer functions instead. Registered as dsv3.dsv3 registers it -- jax.extend.xla's + register_hlo_module_transformation, POST_SCHEDULER, every platform -- it would rewrite every program the process + compiles after it, ds_ep's own too. Not tried: no time measured with this adapter has it.""" + global _LIN + with _LIN_LOCK: + if _LIN is None: + try: + mods = { + name: importlib.import_module(f"{_PKG}.{name}") + for name in ( + "ops", + "dsv3_config", + "dsv3_mla", + "dsv3_router", + "dsv3_types", + "dsv3_sparse_layer", + "dsv3_dense_layer", + ) + } + mods["expert_mlp"] = importlib.import_module(f"{_PKG}.gmmv2.expert_mlp") + except ImportError as e: + raise ImportError( + f"ds_ep_lineage could not import MaxText's Lineage stack ({_PKG}): {e} -- a module it imports is " + "missing (typeguard and jaxtyping are not among MaxText's TPU requirements)" + ) from e + _install_sparsecore_switch(mods) + _LIN = types.SimpleNamespace(**mods) + return _LIN + + +def available(): + """Is Lineage importable here?""" + try: + import_lineage() + except ImportError: + return False + return True + + +def provenance(): + """Where Lineage comes from (path and git state) -> dict; {'lineage': None, 'error': ...} without it.""" + from maxtext.experimental.mpmd.jax import ds_ep_pipeline + + try: + lin = import_lineage() + except ImportError as e: + return {"lineage": None, "error": str(e)} + path = os.path.dirname(os.path.abspath(lin.ops.__file__)) + return {"lineage": {"path": path, **ds_ep_pipeline._git(path)}} + + +# --------------------------------------------------------------- SparseCore switch +# libtpu offloads collectives to SparseCore only when a program's chips are the whole slice or a solid rectangle +# away from chip (0,0,0) (ds_ep.sparsecore_offload_available); on any other stage Lineage's forced +# compute_on('tpu_sparsecore') regions abort libtpu 0.0.46's compiler (`Check failed: collective_offload_config != +# std::nullopt`, SIGABRT). `no_sparsecore()` traces those regions as plain (TensorCore) code: Lineage's modules +# call compute_on at trace time -- dsv3_router / dsv3_mla through their module aliases (dsv3_router.compute_on, +# dsv3_mla.compute_on), ops.py through jax.experimental.compute_on.compute_on -- so wrappers installed there (and on any +# other alias of jax's compute_on a Lineage module imported by then keeps, whatever its name: a later Lineage's) return +# an identity decorator for compute_type 'tpu_sparsecore' while the switch is on in this thread. compute_on('device') +# regions (MLA's TensorCore collectives) are untouched, and nothing changes outside the context. The flag is +# thread-local: ds_ep traces one program at a time on one thread (ds_ep_pipeline.Pipeline.precompile), and a trace +# on another thread keeps its own setting. The wrappers hold the flag object itself, which a reloaded copy of this +# module adopts (its own new one would switch nothing). +_SC = threading.local() + + +def _sc_compute_on(orig, flag): + def compute_on(f=None, *, compute_type, **kwargs): # jax's signature: (f=None, *, compute_type, ...) + if compute_type == "tpu_sparsecore" and getattr(flag, "off", False): + return (lambda g: g) if f is None else f + return orig(f, compute_type=compute_type, **kwargs) + + compute_on.mpmd_sparsecore_switch = orig + compute_on.mpmd_sparsecore_flag = flag + return compute_on + + +def _jax_compute_on(v): + """`v` with the switch taken off (its original), or `v`.""" + try: + return getattr(v, "mpmd_sparsecore_switch", v) + except Exception: # (an attribute that answers getattr oddly is no alias) + return v + + +def _install_sparsecore_switch(mods): + """Wrap jax.experimental.compute_on.compute_on and every alias of it the Lineage modules hold -- `mods`' and any + other module of the package imported by now, under any attribute name -- in the switch, once: where a wrapper is + there already, adopt its flag.""" + global _SC + import jax.experimental.compute_on as jco + + own = _jax_compute_on(jco.compute_on) + modules = { + id(m): m + for m in ( + *mods.values(), + *(m for n, m in sorted(sys.modules.items()) if m is not None and (n == _PKG or n.startswith(_PKG + "."))), + ) + } + owners = [(jco, "compute_on")] + [ + (m, a) for m in modules.values() for a, v in sorted(vars(m).items()) if _jax_compute_on(v) is own + ] + for owner, attr in owners: + f = getattr(owner, attr) + if hasattr(f, "mpmd_sparsecore_switch"): + _SC = f.mpmd_sparsecore_flag + else: + setattr(owner, attr, _sc_compute_on(f, _SC)) + + +@contextlib.contextmanager +def no_sparsecore(off=True): + """While active (and `off`), Lineage's compute_on('tpu_sparsecore') regions trace as plain code in this thread. + Takes effect at trace time: wrap the tracing / lowering of a program, not its execution.""" + import_lineage() + prev = getattr(_SC, "off", False) + _SC.off = bool(off) + try: + yield + finally: + _SC.off = prev + + +def compiler_options(mesh): + """The compiler options of a program running Lineage's layers on `mesh` -> dict on TPU (a compile-only topology's + devices too), None elsewhere (other backends refuse libtpu options): COMPILER_OPTIONS plus ds_ep's + barrier-keeping option (ds_ep.PIN_COMPILER_OPTIONS) -- Lineage orders its phases with program_order's + optimization barriers and its backward depends on them, which the v5p recipe's + --xla_tpu_aggressive_opt_barrier_removal=ENABLED would remove (deepseek3-671b-lineage.yml says so above its + compile_xla_flags).""" + pin = ds_ep.pin_compiler_options(mesh) + return None if pin is None else {**pin, **COMPILER_OPTIONS} + + +# --------------------------------------------------------------- config +def check(cfg: DeepSeekConfig | None = None, scfg: ds_ep.StageConfig | None = None): + """Raise ValueError naming every setting Lineage's layers cannot run (all of them, at once). + + Lineage routes DeepSeek-V3's way only: top-k (no RNG anywhere: ds_ep's default --routing random has no counterpart), + sigmoid scores, among each token's best groups when n_routing_groups is set (a group scored by its two best + post-bias scores, as ds_ep's: `routing`), dropless (ds_ep's ragged_buffer_factor > 0 drops tokens), one shared + expert, num_kv_heads == num_query_heads (dsv3_config.DSv3Config.validate). Its expert kernels take bf16 tokens as + [N, D / 128, 128] tiles with D / 128 even (gmmv2.relayout.check_tile_d0, gmmv2.expert_mlp._check_3d), the routed + weights in [rows / 8, 8, cols] tiles; experts split evenly over EP. Its rope is split-half with always-truncated + YaRN frequencies, its activations SiLU-gated. No context parallelism (splash shards heads, never the sequence). It + returns no expert counts or aux loss through this adapter (aux.group_sizes / logits would carry them: a follow-up), + and runs no MTP layer. The stage needs Explicit mesh axes (shard_mode 'explicit', so grad_reduce 'step'). What + only picks among ds_ep's own kernels is not refused but ignored (IGNORED_MODEL_FIELDS). A Qwen3.5-family model + (ds_ep.is_qwen) is refused alone: Lineage has none of its layers (its batch split is ds_ep.split_layers, + batch_split_impl 'native'). + """ + cfg = scfg.model if cfg is None else cfg + if ds_ep.is_qwen(cfg): + # (none of the fields below is a Qwen35Config's: not a list of problems but a model Lineage does not build) + raise ValueError( + "Lineage's batch-split layers cannot run this: a Qwen3.5-family model -- Lineage builds " + "DeepSeek-V3's layers only (MLA, a sigmoid-scored router, one ungated shared expert), and no " + "Gated DeltaNet, gated attention or sigmoid-gated shared expert" + ) + bad = [] + if jnp.dtype(cfg.dtype) != jnp.bfloat16: + bad.append(f"dtype {jnp.dtype(cfg.dtype).name}: Lineage's expert kernels take bf16 activations only") + if cfg.routed_score_func != "sigmoid": + bad.append(f"routed_score_func {cfg.routed_score_func!r}: Lineage scores with a sigmoid only") + g, tg, E, k = cfg.n_routing_groups, cfg.topk_routing_group, cfg.num_experts, cfg.num_experts_per_tok + if (g > 0) != (tg > 0): + bad.append(f"n_routing_groups {g} / topk_routing_group {tg}: set both or neither") + elif g > 0: + if E % g: + bad.append(f"num_experts {E} is not a multiple of n_routing_groups {g}") + elif E // g < 2: + bad.append(f"{E // g} expert(s) a routing group: a group is scored by its two best experts") + if tg > g: + bad.append(f"topk_routing_group {tg} > n_routing_groups {g}") + elif E % g == 0 and k > tg * (E // g): + bad.append(f"num_experts_per_tok {k} > the {tg} x {E // g} experts of the chosen groups") + if cfg.shared_experts != 1: + bad.append(f"shared_experts {cfg.shared_experts}: want 1") + if cfg.num_kv_heads != cfg.num_query_heads: + bad.append(f"num_kv_heads {cfg.num_kv_heads} != num_query_heads {cfg.num_query_heads}") + if cfg.emb_dim % 256: + bad.append(f"emb_dim {cfg.emb_dim}: Lineage's expert kernels want a multiple of 256 (D / 128 even)") + if cfg.moe_mlp_dim % 128: + bad.append( + f"moe_mlp_dim {cfg.moe_mlp_dim}: want a multiple of 128 (the routed weights' 8-row tiles, the " "gmmv2 lanes)" + ) + if cfg.q_lora_rank <= 0: + bad.append("q_lora_rank 0: Lineage's MLA always has the query LoRA") + if tuple(cfg.mlp_activations) != ("silu", "linear"): + bad.append(f"mlp_activations {tuple(cfg.mlp_activations)}: Lineage hard-codes silu x linear") + if not cfg.rope_interleave: + bad.append("rope_interleave False: the weight conversion de-interleaves MaxText's interleaved rope channels") + if not cfg.rope_truncate or cfg.rope_attention_scaling: + bad.append("rope_truncate False / rope_attention_scaling True: Lineage's YaRN always truncates, never scales") + for name in ("rope_factor", "rope_max_timescale", "beta_fast", "beta_slow"): + v = getattr(cfg, name) + if float(v) != int(v) or int(v) <= 0: + bad.append(f"{name} {v}: Lineage takes a positive integer") + if cfg.routed_bias_update_rate: + bad.append( + f"routed_bias_update_rate {cfg.routed_bias_update_rate}: the expert counts (Lineage's " + "aux.group_sizes) are not wired up" + ) + if cfg.load_balance_loss_weight: + bad.append( + f"load_balance_loss_weight {cfg.load_balance_loss_weight}: the aux loss (Lineage's aux.logits) is " "not wired up" + ) + if cfg.mtp_num_layers: + bad.append(f"mtp_num_layers {cfg.mtp_num_layers}: no MTP layer on Lineage here") + if scfg is not None: + if scfg.random_routing: + bad.append("random routing: Lineage routes top-k only (--routing topk)") + if scfg.ragged_buffer_factor > 0: + bad.append( + f"ragged_buffer_factor {scfg.ragged_buffer_factor}: Lineage is dropless (its bank factor is " + f"fixed at {BANK_FACTOR})" + ) + if scfg.cp > 1: + bad.append(f"cp {scfg.cp}: no context parallelism") + if scfg.shard_mode != "explicit": + bad.append(f"shard_mode {scfg.shard_mode!r}: Lineage reads layouts from sharding types: want 'explicit'") + if cfg.num_experts % scfg.ep: + bad.append(f"num_experts {cfg.num_experts} is not a multiple of ep {scfg.ep}") + if bad: + raise ValueError("Lineage's batch-split layers cannot run this: " + "; ".join(bad)) + + +# What ds_ep's knobs of its own layers mean nothing to Lineage's (for help texts and run summaries): the experts' +# kernels and dispatch (gmmv2 with Lineage's tiles, its own SparseCore all-gather / reduce-scatter, dW accumulated in +# place across the halves and chunks: dsv3_experts.dsv3_routed_experts_bwd_impl), where the routing weights apply (its +# combine weighs the expert outputs), ds_ep's attention kernel and its softmax, and MoE numerics. Lineage's splash is +# base-2 always (its kernel config's use_base2_exp default, splash_attention_kernel.SplashConfig, which +# dsv3_mla.init_splash_kernel never sets; DeepSeekConfig.sa_use_base2_exp says what that does), whichever softmax +# ds_ep's own kernel would compute -- the exact one under attention_kernel 'splash' or sa_use_base2_exp False: a known +# numerics difference, like the bf16 rope tables. +# (matmul_precision is not among them: the same programs' head -- ds_ep's own, head_loss -- reads it.) +IGNORED_STAGE_KNOBS = ( + "gmm_impl", + "wi_tiling", + "wo_tiling", + "use_ragged_sort", + "ep_collectives", + "split_dw", + "expert_weights", + "route_weights", +) +IGNORED_MODEL_FIELDS = ( + "attention_kernel", + "sa_use_base2_exp", + "moe_impl", + "gmm_fp32_accum", + "gmm_exact_drhs", + "float32_weight_sum", + "moe_use_direct_token_gather", + "sa_cost_estimate_flops_fwd", + "sa_cost_estimate_flops_bwd", +) + + +def routing(cfg: DeepSeekConfig): + """(n_routing_groups, topk_routing_group, topk_in_group) for Lineage's router. It scores a group by the sum of + its `topk_in_group` best scores, an argument (dsv3_router.expert_group_mask; only Lineage's own config derives + it, as k / topk_routing_group, dsv3_config.DSv3ModelConfig.topk_in_group), and ds_ep by its two best post-bias + scores, summed in fp32 (deepseek.moe._top_2_in_group_sum, MaxText's): 2, for any k (DeepSeek-V3's k / g is 8 / 4 = + 2 too). Groups off (ds_ep's n_routing_groups -1) is one group of every expert, topk_in_group k: exactly plain + top-k (Lineage has no off switch, dsv3_router.expert_indices_and_coeffs).""" + if cfg.n_routing_groups <= 0: + return 1, 1, cfg.num_experts_per_tok + return cfg.n_routing_groups, cfg.topk_routing_group, 2 + + +def sa_blocks(cfg: DeepSeekConfig): + """Splash's six blocks from ds_ep's config: q, kv, kv compute, then the fused backward's q, kv, kv compute, where 0 + means the forward's (as deepseek.attention.tokamax_splash_attention reads them).""" + return ( + cfg.sa_block_q, + cfg.sa_block_kv, + cfg.sa_block_kv_compute, + cfg.sa_block_q_dkv or cfg.sa_block_q, + cfg.sa_block_kv_dkv or cfg.sa_block_kv, + cfg.sa_block_kv_dkv_compute or cfg.sa_block_kv_compute, + ) + + +# --------------------------------------------------------------- the A3 view +def a3_mesh(mesh: Mesh): + """ds_ep's stage mesh ('fsdp', 'expert'), Explicit -> the same devices, same order, with a trailing size-1 'attn' + axis: the mesh Lineage's code runs on (AXIS_MAPPING).""" + if tuple(mesh.axis_names) != FE or any(t != AxisType.Explicit for t in mesh.axis_types): + raise ValueError( + f"Lineage's layers run on an Explicit ('fsdp', 'expert') stage mesh (shard_mode 'explicit'), " + f"got axes {mesh.axis_names} of types {mesh.axis_types}" + ) + if jax.config.jax_remove_size_one_mesh_axis_from_type: + # Lineage's recipe pins it False too (deepseek3-671b-lineage.yml's remove_size_one_mesh_axis_from_type): MLA + # all-gathers over the attention axis it reads from the types, which this flag would strip of 'attn'. + raise ValueError( + "the A3 view's size-1 'attn' axis needs jax_remove_size_one_mesh_axis_from_type False (the " "default)" + ) + return Mesh(mesh.devices[..., None], (*FE, ATTN), axis_types=(AxisType.Explicit,) * 3) + + +def _physical(axes): + """Lineage logical axes -> the physical m3 axes AXIS_MAPPING maps them to.""" + out = set() + for a in axes: + v = AXIS_MAPPING[a] + out.update((v,) if isinstance(v, str) else v) + return frozenset(out) + + +# The leaves whose head dim Lineage shards over 'attention' (per layer: q_up / k_up / v_up [rank, heads, dim], +# out [heads, v, emb]; dsv3_sharding._MLA_8X8X8), and the routed experts' expert dim (dim 0) over 'expert'. +_HEAD_DIM = {"q_up": 1, "k_up": 1, "v_up": 1, "out": 0} + + +def lineage_types(axes_tree, shapes_tree, kind, view="m3"): + """One layer's collected Lineage weights typed `kind` ('reduced' for the weights, 'unreduced' for their + gradients) over the axes Lineage collects each along (`axes_tree`: dsv3_sparse_layer._w_ici_axes() / + dsv3_dense_layer._w_ici_axes()), head dims on 'attn' and the routed experts on 'expert' -> a tree of + PartitionSpecs on m3; `view` 'm2' is the same blocks on ds_ep's mesh (no 'attn').""" + + def one(path, axes, shape): + name = getattr(path[-1], "name", None) + dims = [None] * len(shape.shape) + if name in _HEAD_DIM: + dims[_HEAD_DIM[name]] = ATTN + if len(path) > 1 and getattr(path[-2], "name", None) == "routed": + dims[0] = "expert" + red = _physical(axes) + if view == "m2": + dims, red = [None if d == ATTN else d for d in dims], red - {ATTN} + return P(*dims, **({kind: red} if red else {})) + + return jax.tree_util.tree_map_with_path(one, axes_tree, shapes_tree, is_leaf=lambda x: isinstance(x, tuple)) + + +def layer_kwargs(cfg: DeepSeekConfig, mesh3: Mesh, capacity_factor=CAPACITY_FACTOR): + """The keyword arguments of dsv3_sparse_layer's scan-body / epilogue functions (dsv3_model.dsv3_layer_kwargs's + values from ds_ep's config). Traps: Lineage's qk_head_dim is the NOPE dim (DeepSeekConfig.qk_head_dim is nope + + rope); rope_factor an int; the router kernel stays bf16, router_dtype fp32 under float32_gate_logits; rope_fn must + be dsv3_mla.yarn itself (an identity check enables its fused tail, dsv3_mla.q_up_from_q_down). quant None: + Lineage's layers run unquantized, in bf16, where MaxText's DeepSeek-V3 Lineage recipe runs fp8 (lineage_quantization + fp8_full in deepseek3-671b-lineage.yml: the routed experts' GMMs with the token all-gather feeding them, and the MLA + projections but k up -- quantization.FP8_FULL); ds_ep's model has no fp8 path.""" + lin = import_lineage() + groups, topk_groups, in_group = routing(cfg) + return dict( + num_experts=cfg.num_experts, + num_experts_per_tok=cfg.num_experts_per_tok, + routed_scaling_factor=float(cfg.routed_scaling_factor), + n_routing_groups=groups, + topk_routing_group=topk_groups, + topk_in_group=in_group, + qk_head_dim=cfg.qk_nope_head_dim, + rope_head_dim=cfg.qk_rope_head_dim, + num_query_heads=cfg.num_query_heads, + mscale=float(cfg.mscale), + kv_lora_rank=cfg.kv_lora_rank, + max_position_embeddings=cfg.max_position_embeddings, + original_max_position_embeddings=cfg.original_max_position_embeddings, + rope_factor=int(cfg.rope_factor), + mesh=mesh3, + norm_fn=functools.partial(lin.ops.rms_norm, epsilon=cfg.normalization_layer_epsilon), + rope_fn=lin.dsv3_mla.yarn, + gmm_fn=lin.expert_mlp.make_gmm_fn(emb_dim=cfg.emb_dim), + axis_mapping=AXIS_MAPPING, + expert_axis_name="expert", + capacity_factor=float(capacity_factor), + router_dtype=jnp.float32 if cfg.float32_gate_logits else None, + quant=None, + ) + + +# The subset the prologue functions and the dense layer take. +MLA_KWARGS = ( + "qk_head_dim", + "rope_head_dim", + "num_query_heads", + "mscale", + "kv_lora_rank", + "max_position_embeddings", + "original_max_position_embeddings", + "rope_factor", + "mesh", + "norm_fn", + "rope_fn", + "axis_mapping", + "quant", +) + + +def kernels(cfg: DeepSeekConfig, mesh3: Mesh, batch, seq): + """dsv3_model.init_kernels from ds_ep's config, traced under m3's abstract mesh -> (yarn_freqs, splash_kernel): + YaRN cos / sin [batch, seq, 1, rope] for positions 0..seq-1 every row (ds_ep's segment ids are all ones, Lineage's + None, which is the same mask), and the causal splash kernel on m3 with ds_ep's blocks (`sa_blocks`) and Lineage's + defaults for the rest (dsv3_config.DSv3KernelConfig).""" + lin = import_lineage() + pos = jax.reshard(jnp.broadcast_to(jnp.arange(seq, dtype=jnp.int32), (batch, seq)), NamedSharding(mesh3, P(FE, None))) + yarn = lin.dsv3_mla.get_yarn_freqs( + pos, + rope_head_dim=cfg.qk_rope_head_dim, + rope_theta=int(cfg.rope_max_timescale), + max_position_embeddings=cfg.max_position_embeddings, + original_max_position_embeddings=cfg.original_max_position_embeddings, + beta_fast=int(cfg.beta_fast), + beta_slow=int(cfg.beta_slow), + rope_factor=int(cfg.rope_factor), + out_pspec=P("fsdp_attention", None, None), + mesh=mesh3, + axis_mapping=AXIS_MAPPING, + dtype=cfg.dtype, + ) + k = lin.dsv3_config.DSv3KernelConfig(max_target_length=seq) + splash = lin.dsv3_mla.init_splash_kernel( + *sa_blocks(cfg), + k.sa_q_layout, + k.sa_k_layout, + k.sa_v_layout, + max_target_length=seq, + num_query_heads=cfg.num_query_heads, + kernel_out_spec=P("attention", None), + mesh=mesh3, + axis_mapping=AXIS_MAPPING, + qk_diag_skip=k.qk_diag_skip, + qk_diag_grid=k.qk_diag_grid, + sv_diag_skip=k.sv_diag_skip, + diag_band_skip=k.diag_band_skip, + dq_reduction_steps=k.dq_reduction_steps, + q_prescaled_log2e=k.q_prescaled_log2e, + ) + return yarn, splash + + +# --------------------------------------------------------------- weights +# MaxText's layout (ds_ep's, with ds_ep's leaf names: ds_ep.layer_shapes) vs Lineage's collected one (dsv3_types), per +# Lineage's interop.maxtext_layout (_deinterleave_rope and the layer converters): the trailing rope channels of wq_b +# and wkv_a interleaved (2i, 2i+1) there, split-half (i, i + R/2) here; wkv_b fused there, k_up / v_up here; wi_0 / +# wi_1 separate there, one routed gate [.., E, D, 2F] here (SiLU on the first half, ops._ragged_silu_mul_kernel), +# viewed as [.., E, D/8, 8, 2F] tiles (dsv3_sparse_layer.routed_w_to_tiles; linear too); the router bias a weight leaf +# there, Lineage's moe.router.bias here. Every transform acts on a trailing axis ds_ep's compute layout leaves +# unsharded, so all run per shard, on any number of leading (layer) axes, and the gradient transforms are their exact +# inverses. No rope channels (qk_rope_head_dim 0) leave w as it is, as Lineage's converter does: w[..., -0:] would be +# all of it. +def _deinterleave_rope(w, rope): + if rope <= 0: + return w + r = w[..., -rope:] + return jnp.concatenate([w[..., :-rope], r[..., 0::2], r[..., 1::2]], axis=-1) + + +def _interleave_rope(w, rope): + if rope <= 0: + return w + r, half = w[..., -rope:], rope // 2 + # concatenate, not jnp.stack: right on unreduced values outside a shard_map too (module doc) + pairs = jnp.concatenate([r[..., :half, None], r[..., half:, None]], axis=-1) + return jnp.concatenate([w[..., :-rope], pairs.reshape(*r.shape[:-1], rope)], axis=-1) + + +def _mla_from_maxtext(att, cfg): + lin = import_lineage() + kv = att["wkv_b"]["kernel"] + R, N = cfg.qk_rope_head_dim, cfg.qk_nope_head_dim + return lin.dsv3_types.DSv3MLAWeightsPytree( + q_down=att["wq_a"]["kernel"], + q_up=_deinterleave_rope(att["wq_b"]["kernel"], R), + q_norm_scale=att["q_norm"]["scale"], + kv_down=_deinterleave_rope(att["wkv_a"]["kernel"], R), + k_up=kv[..., :N], + v_up=kv[..., N:], + kv_norm_scale=att["kv_norm"]["scale"], + out=att["out"]["kernel"], + ) + + +def _mla_to_maxtext(g, cfg): + R = cfg.qk_rope_head_dim + return { + "wq_a": {"kernel": g.q_down}, + "q_norm": {"scale": g.q_norm_scale}, + "wq_b": {"kernel": _interleave_rope(g.q_up, R)}, + "wkv_a": {"kernel": _interleave_rope(g.kv_down, R)}, + "kv_norm": {"scale": g.kv_norm_scale}, + "wkv_b": {"kernel": jnp.concatenate([g.k_up, g.v_up], axis=-1)}, + "out": {"kernel": g.out}, + } + + +def router_bias_dtype(cfg: DeepSeekConfig): + """The dtype of the router bias Lineage gets: ds_ep's compute dtype of the leaf (ds_ep.leaf_dtypes: fp32 under + float32_gate_logits, as MaxText keeps it). A model without a routed bias gets zeros of it -- in bf16 unless + float32_gate_logits, since an fp32 bias would promote the whole selection to fp32 + (dsv3_router._expert_selection_impl).""" + return jnp.dtype(jnp.float32 if cfg.float32_gate_logits else cfg.dtype) + + +def sparse_from_maxtext(lw, cfg: DeepSeekConfig, tiles=True): + """One MoE layer's (or a [n, ...] stack's) ds_ep compute weights -> Lineage's DSv3SparseLayerWeightsPytree in + its collected layout, routed experts in the tiles view unless `tiles` False. The router kernel is cast to bf16 + (Lineage computes in fp32 on a bf16 kernel under float32_gate_logits, dsv3_router.expert_selection); the router bias + is ds_ep's `moe.gate.bias` where the model has one, else zeros (`router_bias_dtype`).""" + lin = import_lineage() + T = lin.dsv3_types + moe, sh = lw["moe"], lw["moe"]["shared_experts"] + kernel = moe["gate"]["kernel"] + bias = moe["gate"].get("bias") + if bias is None: + bias = jnp.zeros(kernel.shape[:-2] + kernel.shape[-1:], router_bias_dtype(cfg)) + routed = T.DSv3MoERoutedExpertWeightsPytree(gate=jnp.concatenate([moe["wi_0"], moe["wi_1"]], axis=-1), linear=moe["wo"]) + return T.DSv3SparseLayerWeightsPytree( + pre_attn_norm_scale=lw["pre_self_attention_layer_norm"]["scale"], + mla=_mla_from_maxtext(lw["self_attention"], cfg), + post_attn_norm_scale=lw["post_self_attention_layer_norm"]["scale"], + moe=T.DSv3MoEWeightsPytree( + router=T.DSv3MoERouterWeightsPytree(kernel=kernel.astype(cfg.dtype), bias=bias), + shared=T.DSv3MoESharedExpertWeightsPytree( + gate_0=sh["wi_0"]["kernel"], gate_1=sh["wi_1"]["kernel"], linear=sh["wo"]["kernel"] + ), + routed=lin.dsv3_sparse_layer.routed_w_to_tiles(routed) if tiles else routed, + ), + ) + + +def sparse_to_maxtext(g, cfg: DeepSeekConfig, bias=False, tiles=True): + """The inverse of `sparse_from_maxtext` for gradients: a DSv3SparseLayerWeightsPytree of gradients -> ds_ep's + tree. The router kernel's gradient leaves in ds_ep's compute dtype of the kernel (fp32 under + float32_gate_logits, ds_ep.leaf_dtypes); `bias`: the tree has ds_ep's routed bias leaf, whose gradient is zero (it + only picks the experts: stop_gradient, dsv3_router._expert_selection_impl) -- the slot ds_ep fills with expert + counts when it updates the bias, not wired up here (`check`).""" + lin = import_lineage() + routed = lin.dsv3_sparse_layer.routed_w_from_tiles(g.moe.routed) if tiles else g.moe.routed + f = routed.gate.shape[-1] // 2 + kernel = g.moe.router.kernel.astype(jnp.float32 if cfg.float32_gate_logits else cfg.dtype) + gate = {"kernel": kernel} + if bias: + gate["bias"] = jnp.zeros(kernel.shape[:-2] + kernel.shape[-1:], router_bias_dtype(cfg)) + return { + "pre_self_attention_layer_norm": {"scale": g.pre_attn_norm_scale}, + "post_self_attention_layer_norm": {"scale": g.post_attn_norm_scale}, + "self_attention": _mla_to_maxtext(g.mla, cfg), + "moe": { + "gate": gate, + "wi_0": routed.gate[..., :f], + "wi_1": routed.gate[..., f:], + "wo": routed.linear, + "shared_experts": { + "wi_0": {"kernel": g.moe.shared.gate_0}, + "wi_1": {"kernel": g.moe.shared.gate_1}, + "wo": {"kernel": g.moe.shared.linear}, + }, + }, + } + + +def dense_from_maxtext(lw, cfg: DeepSeekConfig): + """One dense layer's (or a stack's) ds_ep compute weights (ds_ep.dense_layer_shapes) -> Lineage's + DSv3DenseLayerWeightsPytree: the MLA as the MoE layer's, the dense MLP's wi_0 / wi_1 / wo as gate_0 / gate_1 / + linear (not fused, unlike the routed experts).""" + lin = import_lineage() + T = lin.dsv3_types + mlp = lw["mlp"] + return T.DSv3DenseLayerWeightsPytree( + pre_attn_norm_scale=lw["pre_self_attention_layer_norm"]["scale"], + mla=_mla_from_maxtext(lw["self_attention"], cfg), + post_attn_norm_scale=lw["post_self_attention_layer_norm"]["scale"], + mlp=T.DSv3MLPWeightsPytree(gate_0=mlp["wi_0"]["kernel"], gate_1=mlp["wi_1"]["kernel"], linear=mlp["wo"]["kernel"]), + ) + + +def dense_to_maxtext(g, cfg: DeepSeekConfig): + """The inverse of `dense_from_maxtext` (for gradients).""" + return { + "pre_self_attention_layer_norm": {"scale": g.pre_attn_norm_scale}, + "post_self_attention_layer_norm": {"scale": g.post_attn_norm_scale}, + "self_attention": _mla_to_maxtext(g.mla, cfg), + "mlp": {"wi_0": {"kernel": g.mlp.gate_0}, "wi_1": {"kernel": g.mlp.gate_1}, "wo": {"kernel": g.mlp.linear}}, + } + + +# --------------------------------------------------------------- the driver +def _chain_fwd(wl, h3, yarn, splash, kw, bank_layers=None): + """Lineage's batch-split forward of len(wl) >= 1 MoE layers on `h3` (m3, ACT3) -> (y3, aux, residuals). + + The halves are each device's first and second half of its rows (ops.split_microbatches: ds_ep's h[:half] / + h[half:]). Each half's activation bank holds `BANK_FACTOR` x the balanced gating activations of `bank_layers` + layers (init_activation_bank's num_layers; None: all the call's), then one MoE chunk of scratch rows + (dsv3_sparse_layer.init_activation_bank). Each expert chunk's gate GMM writes its output at the chunk's bank row + and the SiLU reads it right back (dsv3_experts.dsv3_routed_experts_impl); the backward reads it there again, or -- a + chunk that overflowed the checkpoint rows into the scratch ones, which the next chunk overwrites -- recomputes the + gate GMM (dsv3_experts._retrieve_or_remat_gate_out, dsv3_routed_experts_bwd_impl). `bank_layers` 0 is the + forward-only bank (Region's primal): no checkpoint row, so every chunk overflows (dsv3_experts.bank_chunk_row) and + the scratch chunk is all the bank -- the same y bitwise, 0.60-0.79 GiB less temp per F program at the TPU7x bench + chunk of `Region`'s docstring; residuals from it would make the backward recompute every gate GMM. prologue(w0) + runs mb0's attention of layer 0; scan_body(w_l, w_l+1) mb0's MoE(l) + attention(l+1) and mb1's attention(l) + + MoE(l); epilogue(w_n-1) the rest of the last layer -- the calls Lineage's driver makes + (ops.w_collect_pipelined_scan_prologue_epilogue_fwd), at any n. As dsv3_sparse_layers does (its scan body, + dsv3_sparse_layers.dsv3_sparse_layers), each scan-body residual keeps mb0's MoE input as one sum (out_proj_out + + orig_x, orig_x None): the backward takes either form (dsv3_sparse_layer.dsv3_sparse_layer_scan_body_bwd), the fold + saves an activation per layer. aux[l] is layer l's routing (each scan body returns its layer's; the epilogue the + last's). Consecutive scan bodies are ordered by Lineage's step barriers (its scan unrolls steps in pairs: the + optimization barriers in the scan bodies of ops.w_collect_pipelined_scan_prologue_epilogue and of its backward -- + here the next layer's weights wait for the previous step, in the backward each step's weights for the later step's + results): the same math, bit for bit in a program that also sums its gradients in fp32 over the devices, not in + ds_ep's raw B program (dh and the summed dW differ there); on the TPU7x (D 2048, 4 layers) a B program holds 0.1 GiB + less temp with them, and the summing one 9.7 GiB instead of 14.3 (step times equal).""" + lin = import_lineage() + SL, ops, mesh = lin.dsv3_sparse_layer, lin.ops, kw["mesh"] + mla_kw = {k: kw[k] for k in MLA_KWARGS} + n = len(wl) + mb0, mb1 = ops.split_microbatches(h3, mesh=mesh) + y01 = ops.split_microbatches(yarn, mesh=mesh) + (b0, o0), (b1, o1) = SL.init_activation_bank( + mb0, + wl[0], + num_layers=n if bank_layers is None else bank_layers, + num_experts_per_tok=kw["num_experts_per_tok"], + ragged_buffer_factor=BANK_FACTOR, + capacity_factor=kw["capacity_factor"], + expert_axis_name=kw["expert_axis_name"], + axis_mapping=AXIS_MAPPING, + mesh=mesh, + ) + carry, res_pro = SL.dsv3_sparse_layer_prologue_fwd( + (mb0, mb1), wl[0], y01, splash, banks=(b0, b1), bank_offsets=(o0, o1), **mla_kw + ) + res_body, auxs, w_curr = [], [], wl[0] + for l in range(n - 1): + w_next = wl[l + 1] + if l: # Lineage's step barrier (its forward's): the next layer's weights wait for the previous step + (carry, auxs[-1]), w_next = jax.lax.optimization_barrier(((carry, auxs[-1]), w_next)) + (carry, aux), res = SL.dsv3_sparse_layer_scan_body_fwd(carry, w_curr, w_next, y01, splash, **kw) + moe0 = res.mb0.moe + res = res._replace(mb0=res.mb0._replace(moe=moe0._replace(out_proj_out=moe0.out_proj_out + moe0.orig_x, orig_x=None))) + res_body.append(res) + auxs.append(aux) + w_curr = w_next + ((y0, y1), aux), res_epi = SL.dsv3_sparse_layer_epilogue_fwd(carry, w_curr, y01, splash, **kw) + auxs.append(aux) + # The aux leaves are plain (not unreduced) values: concatenating [None] slices is jnp.stack's result anyway. + aux = jax.tree.map(lambda *a: jnp.concatenate([x[None] for x in a], axis=0), *auxs) + return ops.merge_microbatches(y0, y1, mesh=mesh), aux, (res_pro, res_body, res_epi) + + +def _chain_bwd(wl, res, dy3, yarn, splash, kw): + """The backward of `_chain_fwd` -> (per-layer weight gradients, dh3): Lineage's backward functions in reverse + with identity reductions (ops.w_collect_pipelined_scan_prologue_epilogue_bwd with every hook the identity). + Gradients come out half a layer skewed: mb0's attention gradient of layer l is computed by scan_body_bwd(l-1), which + returns layer l's full gradient (`w_next_grad_partial`, through reduce_ici_first_fn = identity); layer 0's is the + prologue's attention part plus scan_body_bwd(0)'s rest (combine_w_grads, at the end of that backward); with nothing + pending (w_pending_grad_partial None) reduce_ici_second_fn is never called (dsv3_sparse_layer_scan_body_bwd's + phases 5 and 7). No aux loss: the aux cotangent carries no logits.""" + lin = import_lineage() + SL, ops, mesh = lin.dsv3_sparse_layer, lin.ops, kw["mesh"] + no_aux = lin.dsv3_types.DSv3RouterAux(group_sizes=None, selected_experts=None, logits=None) + res_pro, res_body, res_epi = res + n = len(wl) + y01 = ops.split_microbatches(yarn, mesh=mesh) + bkw = dict(kw, yarn_freqs=y01, splash_kernel=splash) + gcarry, w_next = SL.dsv3_sparse_layer_epilogue_bwd( + res_epi, (ops.split_microbatches(dy3, mesh=mesh), no_aux), wl[-1], **bkw + ) + grads = [None] * n + for l in reversed(range(n - 1)): + w_l = wl[l] + if l < n - 2: # Lineage's step barrier (its backward's): this step's weights wait for the later step's results + (gcarry, grads[l + 2], w_next), w_l = jax.lax.optimization_barrier(((gcarry, grads[l + 2], w_next), w_l)) + gcarry, w_curr, grads[l + 1], pending = SL.dsv3_sparse_layer_scan_body_bwd( + res_body[l], (gcarry, no_aux), w_l, wl[l + 1], w_next, lambda g: g, None, None, **bkw + ) + assert pending is None + w_next = w_curr + (gx0, gx1), g0 = SL.dsv3_sparse_layer_prologue_bwd( + res_pro, gcarry, wl[0], yarn_freqs=y01, splash_kernel=splash, **{k: kw[k] for k in MLA_KWARGS} + ) + grads[0] = ops.combine_w_grads(g0, w_next) + return grads, ops.merge_microbatches(gx0, gx1, mesh=mesh) + + +# --------------------------------------------------------------- the region +def _drop_bias(w): + return dataclasses.replace(w, moe=dataclasses.replace(w.moe, router=dataclasses.replace(w.moe.router, bias=None))) + + +def _same_type(name, x, spec): + got = jax.typeof(x).sharding.spec + if got != spec: + raise ValueError(f"{name}: typed {got}, want {spec}") + + +class Region: + """A chunk's decoder layers on Lineage's code: `region(w_layers, w_dense, h) -> (y, aux)`, differentiable. + + Global view on ds_ep's stage mesh `mesh` (Explicit ('fsdp', 'expert')): `w_layers` / `w_dense` are the chunk's + 'layers' / 'dense_layers' compute copies as ds_ep's explicit programs take them (MaxText layout, typed + ds_ep.chunk_wc_specs: reduced over each leaf's partial axes; `w_dense` None without dense layers), `h` [B, S, D] + bf16 P(FE, None, None) with an even number of rows a device. The dense layers run first, on the whole + microbatch (Lineage's dsv3_dense_layer, as ds_ep's split chunk runs its dense layers unsplit), then the MoE + layers batch-split (`_chain_fwd`). `y` is P(FE, None, None); `aux` Lineage's routing per MoE layer + (DSv3RouterAux: group_sizes [n, devices, E] -- each device's tokens' expert counts -- and selected_experts + [n, B, S, k], on m2; logits None), not differentiated. Under jax.vjp the cotangents come out in ds_ep's layout + typed ds_ep.chunk_gacc_specs(explicit=True) -- unreduced over the partial axes, each device's partial sum, ready + for ds_ep's accumulators -- and dh P(FE, None, None); the router bias' cotangent is zero. + + A jax.custom_vjp: the forward rule converts the weights, reshards everything onto the A3 view and runs the chain under + m3's abstract mesh; the backward rule runs Lineage's explicit backward functions under it and returns the gradients + converted back. The dense layers' backward is a jax.vjp of each layer, recomputed from its input: the forward saves + only the dense layers' inputs, so none of their activations lives across the MoE chain's forward and backward -- one + extra dense-layer forward per backward program for that memory. (Their pullbacks could be residuals instead: + jax.vjp's VJP object crosses from one jit into another.) The primal -- what a program runs that only calls the region + (ds_ep's F programs; jax.vjp and jax.checkpoint differentiate through the forward rule) -- is the forward rule's + forward without residuals and with Lineage's activation bank sized for no layer (`_chain_fwd`): the bank holds each + half's gate-GMM outputs for the backward to read instead of recomputing them, so a forward-only program would fill it + and never read it. On the TPU7x at a bench chunk (D 2048, F 1024, 32 experts, S 4096, 2 rows a device, 2 MoE + layers) an F program's temp drops 2.434 -> 1.834 GiB on stage 1, exactly the two halves' banks, and 2.478 -> 1.691 on + stage 0 (no SparseCore), y bitwise equal and its time the same (medians of 50: 12.05 vs 12.05 ms, 14.56 vs 14.61). + The primal and both rules are nested jits held by this object, so every program that calls it traces each once per + input shape; construct one per chunk structure and stage (`region` caches them) -- and in one context (`_fwd`), so a + program with a mesh context, or a jax.checkpoint around the region, reuses them too. The SparseCore switch is part of + the identity: `sparsecore` False (default: whether libtpu offloads this mesh's collectives, + ds_ep.sparsecore_offload_available, asked once a mesh) traces under `no_sparsecore()`. Compile the programs with + `compiler_options(mesh)`. + + Numerics. Lineage's math, which is not ds_ep's (`IGNORED_STAGE_KNOBS`): against ds_ep's unsplit layers at top-k + routing on the TPU7x, with the routing pinned by a routed bias, the gradients agree to cosine >= 0.99994 and 1.6e-2 + a leaf (1-5 layers, dense ones too); routed freely they do not -- the two route a few near-tie tokens differently + (0.2-0.5% of a layer's tokens on fp32 router scores, 2.7% on bf16 ones, more in each later layer), which moves the + router kernel's gradient by 0.06-0.14 and the cosine to 0.996-0.9995 (1-5 layers): compare pinned. A MoE-only + region's forward is bitwise the same in every program; with dense layers it is not (3e-3 between a forward-only and + a backward program, about one bf16 ulp): Lineage's dense layer has no optimization barriers, so XLA rounds it by + what else the program computes, as it does Lineage's own dense layers. + """ + + def __init__( + self, + scfg: ds_ep.StageConfig, + mesh: Mesh, + n_moe: int, + n_dense: int = 0, + routed_bias: bool = False, + capacity_factor: float = CAPACITY_FACTOR, + sparsecore: bool | None = None, + ): + check(scfg.model, scfg) + if n_moe < 1: + raise ValueError( + f"a Lineage region runs at least one MoE layer (n_moe {n_moe}): Lineage's batch split is a " "MoE layer's" + ) + if not capacity_factor > 0: + raise ValueError(f"capacity_factor must be > 0, got {capacity_factor}") + if tuple(mesh.shape.values()) != (scfg.fsdp, scfg.ep): + raise ValueError(f"mesh {dict(mesh.shape)} is not fsdp {scfg.fsdp} x ep {scfg.ep}") + self.lin = lin = import_lineage() + self.scfg, self.cfg = scfg, scfg.model + self.mesh, self.mesh3 = mesh, a3_mesh(mesh) + self.n_moe, self.n_dense, self.routed_bias = n_moe, n_dense, routed_bias + self.capacity_factor = float(capacity_factor) + self.sparsecore = _sparsecore_offload(mesh) if sparsecore is None else bool(sparsecore) + ch = ds_ep.ChunkSpec( + index=0, layers=tuple(range(n_moe)), first=False, last=False, stage=0, dense=n_dense, routed_bias=routed_bias + ) + self.wc_specs = ds_ep.chunk_wc_specs(scfg, ch) + self.gacc_specs = ds_ep.chunk_gacc_specs(ch, explicit=True) + self.kw = layer_kwargs(self.cfg, self.mesh3, self.capacity_factor) + # one layer's Lineage shapes, for its types + sds = lambda shapes, dt: jax.tree.map(lambda s: jax.ShapeDtypeStruct(s, dt), shapes, is_leaf=ds_ep._is_shape) + dt = self.cfg.dtype + sparse = jax.eval_shape( + functools.partial(sparse_from_maxtext, cfg=self.cfg), sds(ds_ep.layer_shapes(self.cfg, routed_bias), dt) + ) + dense = jax.eval_shape( + functools.partial(dense_from_maxtext, cfg=self.cfg), sds(ds_ep.dense_layer_shapes(self.cfg), dt) + ) + s_axes, d_axes = lin.dsv3_sparse_layer._w_ici_axes(), lin.dsv3_dense_layer._w_ici_axes() + self.types = { + (kind, view, kd): lineage_types(axes, shapes, kind, view) + for kd, axes, shapes in (("sparse", s_axes, sparse), ("dense", d_axes, dense)) + for kind in ("reduced", "unreduced") + for view in ("m2", "m3") + } + self._prim_jit = jax.jit(self._prim_impl) + self._fwd_jit = jax.jit(self._fwd_impl) + self._bwd_jit = jax.jit(self._bwd_impl) + self._call = jax.custom_vjp(self._primal) + self._call.defvjp(self._vjp_fwd, self._vjp_bwd) + + def __call__(self, w_layers, w_dense, h): + return self._call(w_layers, w_dense, h) + + # ------------------------------------------------------------- the custom_vjp's primal and rules + # Every call of the three jits runs under the empty abstract mesh, whatever the caller's context: the mesh context is + # part of a jit's trace key -- no context and an explicitly set empty mesh are two keys -- and jax 0.11.1 calls a + # custom_vjp's primal and rules in different ones: at ds_ep's top level the primal and the forward rule with no + # context, the backward rule and jax.checkpoint's forward rule under a set empty mesh; in a program under a mesh + # (use_abstract_mesh / set_mesh) all three under that mesh. Each new context would trace Lineage again (Phase 1 + # measured a program under m2's mesh tracing both rules once more, a jax.checkpoint'ed region its forward twice). For + # Lineage's code the contexts are the same: get_abstract_mesh() reads none as the empty mesh. Which programs trace + # what: one without AD (ds_ep's F) the primal only; jax.vjp the two rules; a jax.checkpoint'ed region the primal too + # -- jax.checkpoint stages the region out, as a jit does -- though it differentiates through the forward rule alone + # (its program runs `_fwd_impl` twice, DCE'd to (y, aux) for the forward and whole for the recompute, and `_prim_impl` + # never). So a structure with an F and a B program traces its forward twice, at the two bank sizes (CPU, 2 MoE + # layers: the primal 8.5-11.5 s beside the rules' 28-32 s; the pipeline test's V=1 split precompile took 180.6 s, + # 179.8-197 s before the forward-only bank), and one under jax.checkpoint without an F program (V=1's last chunk with + # remat_fused_last) traces a primal it never lowers (that test's --remat-last split precompile: 196.6 s, 180.6 s + # before). + def _fwd(self, w_layers, w_dense, h): + with jax.sharding.use_abstract_mesh(_NO_MESH): + return self._fwd_jit(w_layers, w_dense, h) + + def _bwd(self, res, dy): + with jax.sharding.use_abstract_mesh(_NO_MESH): + return self._bwd_jit(res, dy) + + def _primal(self, w_layers, w_dense, h): + with jax.sharding.use_abstract_mesh(_NO_MESH): + return self._prim_jit(w_layers, w_dense, h) + + def _vjp_fwd(self, w_layers, w_dense, h): + return self._fwd(w_layers, w_dense, h) + + def _vjp_bwd(self, res, cts): + return self._bwd(res, cts[0]) + + # ------------------------------------------------------------- conversions on m2, reshards to / from m3 + def _to_lineage(self, w, dense): + """ds_ep's stacked compute tree (m2, typed reduced) -> one Lineage tree per layer on m3 (A3 types): converted + in a shard_map on m2 (shard-local; typed in and out like ds_ep's explicit programs), then resharded.""" + kd = "dense" if dense else "sparse" + n = self.n_dense if dense else self.n_moe + conv = dense_from_maxtext if dense else sparse_from_maxtext + t2, t3 = self.types[("reduced", "m2", kd)], self.types[("reduced", "m3", kd)] + wl = jax.shard_map( + lambda w: [conv(ds_ep._take(w, l), self.cfg) for l in range(n)], + mesh=self.mesh, + in_specs=(self.wc_specs["dense_layers" if dense else "layers"],), + out_specs=[t2] * n, + check_vma=False, + )(w) + return [jax.tree.map(lambda a, s: jax.reshard(a, NamedSharding(self.mesh3, s)), x, t3) for x in wl] + + def _from_lineage(self, grads, dense): + """Per-layer Lineage gradients on m3 (typed unreduced, checked) -> ds_ep's stacked gradient tree on m2 typed + ds_ep.chunk_gacc_specs(explicit=True): each leaf resharded to m2 (moves nothing: 'attn' has size 1), then + converted and concatenated in a shard_map, on device-local arrays (never jnp.stack an unreduced value).""" + kd = "dense" if dense else "sparse" + t2, t3 = self.types[("unreduced", "m2", kd)], self.types[("unreduced", "m3", kd)] + if not dense: + grads, t2, t3 = [_drop_bias(g) for g in grads], _drop_bias(t2), _drop_bias(t3) + for l, g in enumerate(grads): + jax.tree_util.tree_map_with_path( + lambda p, x, s, l=l: _same_type(f"Lineage gradient of layer {l}{jax.tree_util.keystr(p)}", x, s), g, t3 + ) + g2 = [jax.tree.map(lambda a, s: jax.reshard(a, NamedSharding(self.mesh, s)), g, t2) for g in grads] + + def body(gs): + trees = [dense_to_maxtext(g, self.cfg) if dense else sparse_to_maxtext(g, self.cfg, self.routed_bias) for g in gs] + return jax.tree.map(lambda *ls: jnp.concatenate([a[None] for a in ls], axis=0), *trees) + + return jax.shard_map( + body, + mesh=self.mesh, + in_specs=([t2] * len(grads),), + out_specs=self.gacc_specs["dense_layers" if dense else "layers"], + check_vma=False, + )(g2) + + def _check_inputs(self, w_layers, w_dense, h): + cfg, n_dev = self.cfg, self.scfg.fsdp * self.scfg.ep + if h.dtype != jnp.bfloat16 or h.ndim != 3 or h.shape[2] != cfg.emb_dim: + raise ValueError(f"h: want [B, S, {cfg.emb_dim}] bf16, got {h.shape} {h.dtype}") + if h.shape[0] % (2 * n_dev): + raise ValueError(f"h has {h.shape[0]} rows over {n_dev} devices: the batch split wants an even number a " "device") + _same_type("h", h, ACT2) + trees = [("w_layers", w_layers, self.wc_specs["layers"])] + if self.n_dense: + trees.append(("w_dense", w_dense, self.wc_specs["dense_layers"])) + elif w_dense is not None: + raise ValueError("w_dense given to a region without dense layers") + for name, tree, specs in trees: + if jax.tree.structure(tree) != jax.tree.structure(specs, is_leaf=ds_ep._is_spec): + raise ValueError( + f"{name}: tree {jax.tree.structure(tree)} is not ds_ep's " + f"{jax.tree.structure(specs, is_leaf=ds_ep._is_spec)}" + ) + jax.tree_util.tree_map_with_path( + lambda p, x, s, name=name: _same_type(name + jax.tree_util.keystr(p), x, s), tree, specs + ) + + # ------------------------------------------------------------- the primal's and the two rules' bodies (nested jits) + def _prim_impl(self, w_layers, w_dense, h): + """The primal: the forward alone, the activation bank sized for no layer -> (y, aux).""" + return self._forward(w_layers, w_dense, h, bank_layers=0)[0] + + def _fwd_impl(self, w_layers, w_dense, h): + """The forward rule: the forward, the bank sized for every MoE layer -> ((y, aux), the backward's residuals).""" + return self._forward(w_layers, w_dense, h, bank_layers=None) + + def _forward(self, w_layers, w_dense, h, bank_layers): + self._check_inputs(w_layers, w_dense, h) + lin, m3, kw = self.lin, self.mesh3, self.kw + with no_sparsecore(not self.sparsecore): + wl = self._to_lineage(w_layers, dense=False) + wd = self._to_lineage(w_dense, dense=True) if self.n_dense else [] + x = jax.reshard(h, NamedSharding(m3, ACT3)) + with jax.sharding.use_abstract_mesh(m3.abstract_mesh): + yarn, splash = kernels(self.cfg, m3, *h.shape[:2]) + dense_in = [] + for w in wd: + dense_in.append(x) + x = lin.dsv3_dense_layer.dsv3_dense_layer(x, w, yarn, splash, **{k: kw[k] for k in MLA_KWARGS}) + y3, aux, res = _chain_fwd(wl, x, yarn, splash, kw, bank_layers=bank_layers) + y = jax.reshard(y3, NamedSharding(self.mesh, ACT2)) + aux = lin.dsv3_types.DSv3RouterAux( + group_sizes=jax.reshard(aux.group_sizes, NamedSharding(self.mesh, P(None, FE, None))), + selected_experts=jax.reshard(aux.selected_experts, NamedSharding(self.mesh, P(None, FE, None, None))), + logits=None, + ) + return (y, aux), (wl, wd, dense_in, res, yarn) + + def _bwd_impl(self, res, dy): + lin, m3, kw = self.lin, self.mesh3, self.kw + wl, wd, dense_in, chain_res, yarn = res + with no_sparsecore(not self.sparsecore): + dx = jax.reshard(dy, NamedSharding(m3, ACT3)) + with jax.sharding.use_abstract_mesh(m3.abstract_mesh): + _, splash = kernels(self.cfg, m3, *dy.shape[:2]) + grads, dx = _chain_bwd(wl, chain_res, dx, yarn, splash, kw) + dgrads = [None] * len(wd) + mla_kw = {k: kw[k] for k in MLA_KWARGS} + for l in reversed(range(len(wd))): + _, vjp = jax.vjp( + lambda w, x: lin.dsv3_dense_layer.dsv3_dense_layer(x, w, yarn, splash, **mla_kw), wd[l], dense_in[l] + ) + dgrads[l], dx = vjp(dx) + dh = jax.reshard(dx, NamedSharding(self.mesh, ACT2)) + dw_layers = self._from_lineage(grads, dense=False) + dw_dense = self._from_lineage(dgrads, dense=True) if wd else None + return dw_layers, dw_dense, dh + + +# The Regions `region` hands out: the REGION_CACHE last asked for, the least recently used first, and any other still +# alive (`_LIVE`, weak). A Region holds its three nested jits' traces -- about 0.5 GiB of host memory once a +# 2-MoE-layer chunk's F and B programs have traced it (CPU, tracemalloc: evicting three freed 1.6 GiB) -- for as long as +# this cache or a live program holds it: an F program's trace does, and a jax.checkpoint'ed region's (the custom_vjp's +# call in their jaxprs holds its rules), a jax.vjp program's does not. So a weak cache alone would drop the Region of a +# structure whose programs are all jax.vjp's (V=1's last chunk: its fused programs) between two of them, each then +# tracing Lineage anew; nor can the stage mesh, the natural owner, hold it weakly (its traces reference the mesh: such a +# tie never breaks). A pipeline has at most one structure (a chunk structure on a stage mesh) a chunk, so 32 holds +# every structure of a pipeline of up to 32 chunks -- PP=16 x V=2 compiled in one process; at DeepSeek-V3's 58 MoE +# layers no power-of-two PP makes more than 32 structures -- each traced once. Past 32 structures (PP >= 33, or a +# deeper model at V >= 3) the least recently used is evicted, and of the evicted only a structure whose programs are all +# jax.vjp's can come back as a new Region and trace again (a program holds the others': `_LIVE` hands them out again): +# compile time, not correctness. The pipelines of a process share Regions while among the 32 last used or held by a +# program. +REGION_CACHE = 32 +_REGIONS = collections.OrderedDict() +_LIVE = weakref.WeakValueDictionary() +_REGIONS_LOCK = threading.Lock() +_OFFLOAD = {} # the SparseCore answer, a bool a stage mesh +_OFFLOAD_LOCK = threading.Lock() + + +def _sparsecore_offload(mesh: Mesh): + """ds_ep.sparsecore_offload_available(mesh), asked once a mesh (it compiles a probe program).""" + with _OFFLOAD_LOCK: + if mesh not in _OFFLOAD: + _OFFLOAD[mesh] = ds_ep.sparsecore_offload_available(mesh) + return _OFFLOAD[mesh] + + +def region( + scfg: ds_ep.StageConfig, + ch: ds_ep.ChunkSpec, + mesh: Mesh, + capacity_factor: float = CAPACITY_FACTOR, + sparsecore: bool | None = None, +): + """The `Region` of chunk `ch`'s structure (its MoE / dense layer counts, routed bias) on stage mesh `mesh`, one + per such structure: chunks alike share it, and with it its traces -- in this process, while among the REGION_CACHE + structures last asked for or otherwise alive (`_REGIONS`, `_LIVE`).""" + if sparsecore is None: + sparsecore = _sparsecore_offload(mesh) + key = (scfg, ch.n_moe, ch.dense, ch.routed_bias, mesh, float(capacity_factor), bool(sparsecore)) + with _REGIONS_LOCK: + rg = _REGIONS.pop(key, None) + if rg is None: + rg = _LIVE.get(key) + if rg is None: + rg = _LIVE[key] = Region(scfg, mesh, ch.n_moe, ch.dense, ch.routed_bias, capacity_factor, sparsecore) + _REGIONS[key] = rg # the most recently used last + while len(_REGIONS) > REGION_CACHE: + _REGIONS.popitem(last=False) + return rg diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep_multihost.sh b/src/maxtext/experimental/mpmd/jax/ds_ep_multihost.sh new file mode 100755 index 0000000000..d58914db41 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep_multihost.sh @@ -0,0 +1,278 @@ +#!/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. + +# One host of a multi-host MPMD DeepSeek run: every pod of the slice runs this +# (xpk / GKE, one process per host). The pipeline is ds_ep_pipeline +# --distributed: each process runs the stage holding its chips and takes part +# in every boundary copy. +# +# RUN_DIR=gs://bucket/run bash src/maxtext/experimental/mpmd/jax/ds_ep_multihost.sh --stages 4 --fsdp 64 --ep 1 \ +# --layout physical --transport xfer --bench --profile '$RUN_DIR/xprof' [pipeline flags...] +# +# Across v6e or v5p hosts pass --transport xfer (or ppermute; across slices, with --layout slices, relay): with the +# default, native (jax's cross-host copy), every receiving host aborts (std::bad_alloc in the receive, on a v6e-256 +# and on a v5p-128, 2026-10, jax 0.11.1, libtpu 0.0.46). +# +# It runs `$PYTHON -u -m maxtext.experimental.mpmd.jax.ds_ep_pipeline --distributed --json "$@"` from the +# directory the package imports from, under a timeout, with LIBTPU_INIT_ARGS built as ds_ep_run.sh builds it (on GPU, +# XLA_FLAGS: below) and no hash randomization (every process must build the same plan; the run checks). Then it +# copies this host's log and run records to RUN_DIR, and exits with the run's status. They live in a directory made +# for this invocation alone under $TMPDIR (default /tmp), so that no file an earlier run or another user left there is +# taken for this run's; the log's first lines name it. Once they are copied the run records go and the log stays, as +# a host's log always has: a watcher that reads these logs finds it there (a failed copy leaves the records too, and +# names the directory). Where no such directory can be made (a full, read-only or missing $TMPDIR), the host runs +# all the same, with no log file or run record: its peers would wait for it. +# +# Environment (PYTHON, MPMD_FLAG_SET, LIBTPU_INIT_ARGS_OVERRIDE and EXTRA_LIBTPU_INIT_ARGS as in ds_ep_run.sh): +# RUN_DIR where this invocation's files go (gs:// or a directory; default /tmp/mpmd_run; trailing '/'s dropped): +# each host's log to $RUN_DIR/$STEP_TAG/logs/ (mpmd__host.log, its first line the host's id +# and place, its second, under a step agent whose WID is not that id, a warning: below), the run +# records (run.json) of process 0 and the stage leaders to $RUN_DIR/$STEP_TAG/json/. '$RUN_DIR' in an +# argument is replaced by $RUN_DIR/$STEP_TAG, this invocation's directory. +# STEP_TAG a name for this invocation inside RUN_DIR (default: run). +# JAX_CACHE_DIR the persistent compile cache (default /tmp/jax_cache). Under jax.distributed +# jax writes entries from process 0 only, i.e. for its own stage's programs: every +# other host compiles its programs afresh on every run. +# MODULE another multi-host entry point to run the same way, in place of ds_ep_pipeline +# (given only "$@"; no --distributed / --json). +# TIMEOUT seconds before the run is killed (default 3600): a host that dies +# mid-step leaves its peers waiting on copies that never come. +# +# The host id ( above) is slice x hosts per slice + worker: MEGASCALE_SLICE_ID x the number of entries of +# TPU_WORKER_HOSTNAMES + TPU_WORKER_ID, so that the hosts of several slices never share one (TPU_WORKER_ID numbers the +# hosts of one slice, and repeats in every slice). +# It is the formula of jax.distributed's cluster detection, slice x len(worker list) + worker +# (jax._src.clusters.cloud_tpu_cluster), though jax may read its worker list elsewhere (TPU_PROCESS_ADDRESSES) and +# counts empty entries: on a GKE pod (one process a host) the two agree. The id names the host's log and nothing else, +# so it may differ from jax.process_index(), the TPU runtime's numbering (TPU_WORKER_ID 7 of a v5p-128 ran as process +# 8), but no two hosts may share it: in a gs:// RUN_DIR one's log would replace the other's. On one slice (no +# MEGASCALE_*) the id is TPU_WORKER_ID, else JOB_COMPLETION_INDEX. Where none of these names a worker (a GCE TPU VM, +# whose environment holds none of them) the script asks the metadata server, as jax does there: the worker is +# agent-worker-number, the slice's hosts the entries of worker-network-endpoints, and MEGASCALE_* come from tpu-env +# where unset (GCE_METADATA_IP and TPU_SKIP_MDS_QUERY as for jax); without a numeric answer within 2 s (off GCE) the +# worker is 0. MAXTEXT_MPMD_SLICE_ID, MAXTEXT_MPMD_WORKER_ID, MAXTEXT_MPMD_NUM_SLICES and +# MAXTEXT_MPMD_HOSTS_PER_SLICE, where set, take the place of MEGASCALE_SLICE_ID, TPU_WORKER_ID, MEGASCALE_NUM_SLICES +# and that number of entries, for processes that stand in for hosts without a TPU job's environment (several +# processes on one machine). A value that is not a number stops the script before anything runs (exit 2), and so do +# a slice id past the slice count and, on several slices, a worker id past the slice's hosts or no slice id at all +# (every slice would be slice 0): the ids would pass slices x hosts, or collide. +# +# Under Pathways ('proxy' JAX_PLATFORMS's first platform, as pathways.is_proxy reads it) it starts nothing (exit 2): +# one client process drives every device there, so there is no host of a multi-controller run to be -- run that one +# client through ds_ep_run.sh. +set -uo pipefail +FIRST_PLATFORM=${JAX_PLATFORMS:-} +FIRST_PLATFORM=${FIRST_PLATFORM%%,*} +FIRST_PLATFORM=${FIRST_PLATFORM//[[:space:]]/} +if [[ ${FIRST_PLATFORM,,} == proxy ]]; then + echo "ds_ep_multihost.sh: JAX_PLATFORMS=$JAX_PLATFORMS is Pathways: one client process drives every device, so" \ + "there is no host of a multi-controller run (--distributed) to start: run the one client through ds_ep_run.sh" >&2 + exit 2 +fi +# This script's directory and the directory the package imports from, every symlink resolved, without `cd` (as in +# ds_ep_run.sh). +SELF="$(readlink -f "${BASH_SOURCE[0]}")" +HERE="${SELF%/*}" +# The package, and ROOT, the directory it imports from: HERE one level up for each component of the package's name. +PKG=maxtext.experimental.mpmd.jax +ROOT=$HERE +for _ in ${PKG//./ }; do ROOT=${ROOT%/*}; done +ROOT=${ROOT:-/} +PYTHON=${PYTHON:-python3} +# GPU (PLATFORM=gpu, as a GPU job's entry script sets it, or JAX_PLATFORMS=cuda...): XLA_FLAGS from +# gpu.xla_flags (XLA_FLAGS_OVERRIDE replaces them) plus EXTRA_XLA_FLAGS, no LIBTPU_INIT_ARGS, and no libtpu flag set +# read. Said, not guessed from an nvidia-smi on the host: a TPU job's step must keep its libtpu flags wherever it runs +# (ds_ep_aot_test's Launchers.test_multihost_flag_composition). +if [[ ${PLATFORM:-} == gpu || ${JAX_PLATFORMS:-} == cuda* || ${JAX_PLATFORMS:-} == gpu* ]]; then + GPU=1 + export XLA_FLAGS="${XLA_FLAGS_OVERRIDE-$(grep -v '^#' "$HERE/gpu.xla_flags" | tr '\n' ' ')} ${EXTRA_XLA_FLAGS:-}" +else + GPU= + # LIBTPU_INIT_ARGS, as every launcher builds it (ds_ep_run.sh and ds_ep_aot.sh hold the same lines). + FLAG_SET=${MPMD_FLAG_SET:-tpu7x} + SET_FLAGS="" + if [[ $FLAG_SET != none ]]; then + SET_FILE="$HERE/libtpu_flags/$FLAG_SET.flags" + if [[ $FLAG_SET == */* || ! -f $SET_FILE ]]; then + SETS="none" + for f in "$HERE"/libtpu_flags/*.flags; do + if [[ -f $f ]]; then f=${f##*/}; SETS+=", ${f%.flags}"; fi + done + echo "ds_ep_multihost.sh: MPMD_FLAG_SET=$FLAG_SET: no such libtpu flag set ($SETS; the files of" \ + "$HERE/libtpu_flags)" >&2 + exit 1 + fi + SET_TEXT="$(sed -e 's/#.*//' "$SET_FILE")" || exit 1 # '#' starts a comment + read -r -d '' -a SET <<< "$SET_TEXT" || true # one flag a word, unglobbed + SET_FLAGS="${SET[*]-}" # joined by single spaces + fi + MPMD_LIBTPU_INIT_ARGS="--xla_max_concurrent_async_collective_permutes=64" + export LIBTPU_INIT_ARGS="${LIBTPU_INIT_ARGS_OVERRIDE-$SET_FLAGS} $MPMD_LIBTPU_INIT_ARGS ${EXTRA_LIBTPU_INIT_ARGS:-}" +fi +# Every process must build the same plan (the run checks); no hash randomization. +export PYTHONHASHSEED=0 +export JAX_CACHE_DIR=${JAX_CACHE_DIR:-/tmp/jax_cache} +export PYTHONUNBUFFERED=1 +RUN_DIR=${RUN_DIR:-/tmp/mpmd_run} +# No trailing '/': gs://bucket/runs/ would put '//' in every object name under it (the '//' of gs:// stays). +while [[ $RUN_DIR == */ && $RUN_DIR != *:// ]]; do RUN_DIR=${RUN_DIR%/}; done +TAG=${STEP_TAG:-run} + +# The metadata server's value of the instance attribute $1, where a GCE TPU VM keeps what a GKE pod has in its +# environment, and jax's cluster detection reads it; status 1 under TPU_SKIP_MDS_QUERY (as for jax), without curl, or +# without an answer: no such name (off GCE), a 404 (a VM that is no TPU VM), or no answer within 2 s three times over +# (curl retries a timeout and a 408, 429 or 5xx answer, as jax retries). +metadata() { + if [[ -n ${TPU_SKIP_MDS_QUERY+set} ]] || ! command -v curl > /dev/null; then return 1; fi + curl -sf -m 2 --retry 2 --retry-delay 1 --noproxy '*' -H 'Metadata-Flavor: Google' \ + "http://${GCE_METADATA_IP:-metadata.google.internal}/computeMetadata/v1/instance/attributes/$1" +} + +# "slice worker slices hosts_per_slice" of this host, as decimal numbers; or a message on stderr, and status 1. +host_ids() { + local given=${MAXTEXT_MPMD_SLICE_ID:-${MEGASCALE_SLICE_ID:-}} + local worker=${MAXTEXT_MPMD_WORKER_ID:-${TPU_WORKER_ID:-${JOB_COMPLETION_INDEX:-}}} + local slices=${MAXTEXT_MPMD_NUM_SLICES:-${MEGASCALE_NUM_SLICES:-}} + local hosts=${MAXTEXT_MPMD_HOSTS_PER_SLICE:-} workers=${TPU_WORKER_HOSTNAMES:-} h v + if [[ -z $worker ]]; then + worker=$(metadata agent-worker-number) || worker="" + if [[ $worker =~ ^[0-9]+$ ]]; then # a GCE TPU VM: what the environment lacks, from the metadata as well + if [[ -z $workers ]]; then workers=$(metadata worker-network-endpoints) || workers=""; fi + local key val env_slice="" env_slices="" + while IFS=: read -r key val; do # tpu-env's lines are KEY: 'value' + val=${val//[[:space:]\']/} + case ${key//[[:space:]]/} in + MEGASCALE_SLICE_ID) env_slice=$val ;; + MEGASCALE_NUM_SLICES) env_slices=$val ;; + esac + done <<< "$(metadata tpu-env || true)" + given=${given:-$env_slice} slices=${slices:-$env_slices} + else + if [[ -n $worker ]]; then + echo "ds_ep_multihost.sh: the metadata server's agent-worker-number is '$worker', not a number: worker 0" >&2 + fi + worker=0 + fi + fi + local slice=${given:-0} + slices=${slices:-1} + if [[ -z $hosts ]]; then + local -a names + IFS=, read -ra names <<< "$workers" + hosts=0 + for h in "${names[@]}"; do + if [[ -n $h ]]; then hosts=$((hosts + 1)); fi + done + if (( hosts == 0 )); then hosts=1; fi + fi + for v in "$slice" "$worker" "$slices" "$hosts"; do + if ! [[ $v =~ ^[0-9]+$ ]]; then + echo "ds_ep_multihost.sh: not a number: '$v' (slice '$slice', worker '$worker', slices '$slices'," \ + "hosts per slice '$hosts')" >&2 + return 1 + fi + done + if [[ -z $given ]] && (( 10#$slices > 1 )); then + echo "ds_ep_multihost.sh: no slice id (MEGASCALE_SLICE_ID) in a job of $slices slices: every slice would be" \ + "slice 0, and the ids of their hosts would collide" >&2 + return 1 + fi + if (( 10#$slice >= 10#$slices )); then + echo "ds_ep_multihost.sh: slice $slice of a job of $slices (MEGASCALE_NUM_SLICES; 1 when unset): its ids would" \ + "pass the job's $((10#$slices * 10#$hosts)) hosts" >&2 + return 1 + fi + if (( 10#$slices > 1 && 10#$worker >= 10#$hosts )); then + echo "ds_ep_multihost.sh: worker $worker of a slice of $hosts hosts (TPU_WORKER_HOSTNAMES, or a GCE TPU VM's" \ + "worker-network-endpoints): the ids of $slices slices would collide" >&2 + return 1 + fi + echo "$((10#$slice)) $((10#$worker)) $((10#$slices)) $((10#$hosts))" +} +IDS=$(host_ids) || exit 2 +read -r SLICE WORKER SLICES HOSTS <<< "$IDS" +ID=$((SLICE * HOSTS + WORKER)) +# A step agent (a process on each host that runs a job's steps in turn, each through this script) may export WID, +# the id it took for this host, to its steps. One that took TPU_WORKER_ID, which repeats in every slice, has the +# slices' step logs overwrite each other, and a late or restarted one skips steps the other slices' agents already +# marked done under the same id: the log's second line says so. +STALE="" +if [[ -n ${WID:-} ]] && ! { [[ $WID =~ ^[0-9]+$ ]] && (( 10#$WID == ID )); }; then + STALE="warning: the agent's WID $WID is not this host's id $ID (slice x hosts per slice + worker): an agent that" + STALE+=" numbers hosts by TPU_WORKER_ID -- the slices' step logs collide, and a late or restarted agent skips steps" +fi +WID=$ID +WHERE="" +if (( SLICES > 1 )); then WHERE="slice $SLICE of $SLICES, worker $WORKER of $HOSTS"; fi + +cd "$ROOT" +args=() +# The replacement is quoted: unquoted, bash 5.2's patsub_replacement turns an '&' in it into the match, '$RUN_DIR'. +for x in "$@"; do args+=("${x//\$RUN_DIR/"$RUN_DIR/$TAG"}"); done +# This host's log and run records (process 0 writes $JSON, a stage leader ${JSON%.json}.p.json, both at the +# end) go to a directory made for this invocation alone: a host keeps /tmp between runs (a TPU VM; an agent pod +# between steps), and a file an earlier run, or another user, left there under the same name must neither stop this +# run nor be copied as its own. So each host's --json names a file of its own (the plan check leaves --json out). +# This is best effort: no directory, no log file or record, but the run goes on. +json=() +if WORK=$(mktemp -d "${TMPDIR:-/tmp}/mpmd.XXXXXXXX"); then + LOG=$WORK/mpmd_${TAG}_host${WID}.log + JSON=$WORK/mpmd_${TAG}.json + json=(--json "$JSON") +else + echo "ds_ep_multihost.sh: no directory under ${TMPDIR:-/tmp} for this host's log and run records: running without" \ + "them" >&2 + WORK="" LOG=/dev/null JSON="" +fi +{ echo "host $WID (${WHERE:+$WHERE, }$(hostname)): ${MODULE:-$PKG.ds_ep_pipeline --distributed} ${args[*]}" + [[ -z $STALE ]] || echo "$STALE"; } | tee "$LOG" +if [[ -n $GPU ]]; then FLAGS_LINE="XLA_FLAGS=$XLA_FLAGS"; else FLAGS_LINE="LIBTPU_INIT_ARGS=$LIBTPU_INIT_ARGS"; fi +echo "$FLAGS_LINE" | tee -a "$LOG" +echo "log and run records: ${WORK:-none} (copied to $RUN_DIR/$TAG at the end)" | tee -a "$LOG" +if [[ -n "${MODULE:-}" ]]; then + cmd=("$PYTHON" -u -m "$MODULE" "${args[@]}") +else + cmd=("$PYTHON" -u -m "$PKG.ds_ep_pipeline" --distributed "${json[@]}" "${args[@]}") +fi +timeout -s KILL "${TIMEOUT:-3600}" "${cmd[@]}" 2>&1 | tee -a "$LOG" +rc=${PIPESTATUS[0]} +echo "host $WID exit $rc" | tee -a "$LOG" +# Copy this host's log and whatever run records it wrote (process 0's, a stage leader's) to RUN_DIR; then remove the +# records, unless the copy failed (no access to a gs:// RUN_DIR, say): they stay there too. The log stays either way. +if [[ -z $WORK ]]; then + echo "ds_ep_multihost.sh: nothing to copy to $RUN_DIR/$TAG (no directory for the log and records)" >&2 +elif "$PYTHON" - "$RUN_DIR/$TAG" "$LOG" "$JSON" "${JSON%.json}".p[0-9]*.json <<'EOF'; then +import os, shutil, sys +dst, files = sys.argv[1], [f for f in sys.argv[2:] if os.path.exists(f)] +if dst.startswith('gs://'): + from google.cloud import storage + bucket, _, prefix = dst[5:].partition('/') + b = storage.Client().bucket(bucket) + for f in files: + sub = 'logs' if f.endswith('.log') else 'json' + b.blob(f'{prefix}/{sub}/{os.path.basename(f)}').upload_from_filename(f) +else: + for f in files: + sub = 'logs' if f.endswith('.log') else 'json' + os.makedirs(f'{dst}/{sub}', exist_ok=True) + shutil.copy(f, f'{dst}/{sub}') +print(f'uploaded {len(files)} files to {dst}') +EOF + rm -f "$JSON" "${JSON%.json}".p[0-9]*.json +else + echo "ds_ep_multihost.sh: copying to $RUN_DIR/$TAG failed: this host's log and run records stay in $WORK" >&2 +fi +exit $rc diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep_parity.py b/src/maxtext/experimental/mpmd/jax/ds_ep_parity.py new file mode 100644 index 0000000000..8832ae04e2 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep_parity.py @@ -0,0 +1,1103 @@ +# 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. + +"""Loss and gradient parity of the MPMD PP x FSDP x EP pipeline, on TPU. + + python3 -m maxtext.experimental.mpmd.jax.ds_ep_parity --preset small [--floor] + python3 -m maxtext.experimental.mpmd.jax.ds_ep_parity --preset full-dims + python3 -m maxtext.experimental.mpmd.jax.ds_ep_parity --preset small --gbs 16 --batch-split [--batch-split-impl native] + +This runs directly, not through ds_ep_run.sh (which runs the benchmark), so +it sees whatever LIBTPU_INIT_ARGS the environment sets. The presets need 8 +devices (a TPU7x-8; `tiny` runs on 8 CPU devices, but not `--batch-split` on +Lineage's layers, whose kernels run on TPU only: refused there, and +`--batch-split-impl native` runs). On v6e, emb 1024 (`small`, `small-pp4`) +trips an assert in MaxText's SparseCore gather-reduce; use emb >= 2048 there. + +Two independent references, same weights and batch, loss and EVERY gradient: + + port `maxtext.experimental.mpmd.jax.deepseek` -- the plain-JAX DeepSeek-V3 port that + deepseek_maxtext_parity_test holds bit-exact against MaxText's + own DeepSeek-V3 on one device. The pipeline reuses the + port's layer code (`mla`, `mlp_block`, `rms_norm`, + `dense_general`, rope; at EP=1 also its argsort dispatch), which + that parity covers, but not its expert matmuls, attention kernel + or anything distributed: the port has `ragged_dot` experts + instead of ring-of-experts + ragged sort + megablox, jax splash + instead of tokamax splash, a gather embedding instead of the + iota one, no shard_map, no pipeline, no FSDP / EP collectives, + one device. + monolith `monolith_loss_and_grads`: one shard_map over one stage mesh running + every layer for every microbatch with the pipeline's own layer + math, lax collectives and AD's accumulation -- on TPU, so the + real kernels (SparseCore ragged sort, megablox, tokamax splash) + run instead of their CPU fallbacks. The benchmark's random routing. + +Routing against the port: every token takes ALL experts (top-k = num_experts). +Top-k with k < E is discontinuous, and at init the bf16 sigmoid scores sit +near 0.5 where ~3-6% of tokens have an exact tie at the top-k boundary: any +last-bit difference upstream of the router (a different attention kernel, a +differently shaped matmul) flips some of them, and causal attention spreads +each flip to every later token, so two correct implementations diverge +chaotically (measured: top-2 of 8 gives gradient cosine 0.978 against the port +while top-8 of 8 gives 0.99996; the ring-of-experts block alone matches a +custom-VJP-free dense MoE to 2e-3 even with those ties). Random routing does +not depend on the activations, so the monolith check keeps the benchmark's. + +Gradients are compared in the storage layout, reduced in fp32 +(`rs_dtype=float32`) so the check is not blurred by the bf16 reduce-scatter +the benchmark uses. The presets also keep fp32 master weights and no +`--remat-last`, not the benchmark's bf16 weights; the TPU7x presets keep +MaxText's `ep_on_chip` placement, the v6e ones (`small-v6e*`, `full-dims-v6e`, +`v6e-a`) the benchmark's `fsdp_on_chip`. Parity at every benchmark setting +is a follow-up. Megablox tiles: `--tiles clamped` (ds_ep.TILES; the tiles do +not change the outputs) unless a preset says otherwise -- the CPU presets 128 +everywhere, the full-dims v6e ones `v6e`. + +`--batch-split` checks the pipeline with each device's rows of a microbatch +run as two halves (ds_ep_pipeline --batch-split). A microbatch then needs an +even number of rows a device: `--gbs` doubles a preset's batch (`small` and +`full-dims` hold one row a device a microbatch). Its layers: + + lineage (the default `--batch-split-impl`) MaxText's Lineage layers + (ds_ep_lineage), which route top-k only, on Explicit stage + meshes. Checked: the port, at its top-k (every expert unless + `--topk`), at its tolerances (loss 2e-3, worst leaf 5e-2, cosine + 0.9999) -- loose here, as Lineage's numerics are not the port's + (its splash softmax is base-2 only, 1.0018x sharper, whatever a + preset's sa_use_base2_exp says: ignored on Lineage's layers; + bf16 rope cos / sin; a bf16 router kernel; the routing coefficient + applied before wo), and each costs the match a little. Not + checked: the monolith (its random routing has no Lineage + counterpart: skipped, and so is its phase of `--ladder`, whose + rung-to-rung phase routes top-k instead), nor anything at k < E + against the port (near-tied experts flip, as above). So only a + preset whose one-device port holds the doubled batch is checked + here: `small --gbs 16`, not `full-dims --gbs 16` (that port does + not fit on one device, and `--skip-port` leaves + nothing to check). The tight checks of + Lineage's layers are ds_ep_lineage_test's (against Lineage's own + entry points, bitwise at one layer, and ds_ep's own math with + routing pinned) and ds_ep_lineage_pipeline_test's (the pipeline + against the unsplit one at pinned top-k routing, TPU7x). + native ds_ep.split_layers over the kernels above, in Lineage's phases, + against both references: the port routes every token to all + experts, so the halves change no routing, and the monolith routes + each half with the key the pipeline gives it. Off TPU only + (`tiny`): on TPU ds_ep_pipeline refuses it for DeepSeek-V3 + (native_split_refusal). + +`--ladder` leaves out its stash rungs under either (batch split runs the +recompute programs only). + + python3 -m maxtext.experimental.mpmd.jax.ds_ep_parity --preset small-v6e-stash + python3 -m maxtext.experimental.mpmd.jax.ds_ep_parity --preset v6e-a --ladder --skip-port + +`--ladder` runs several (placement, schedule, stash[, pair stages]) rungs -- +`--rungs circular:search:none,circular:stash:lite,circular:interleaved:none:1,...`, +interleaved's pair stages 'all', 'none' or a '+' list such as 0+1 -- on the SAME +weights (made once per chunk index, `init_by_chunk`, and transplanted into +each rung's layout) and the SAME batch, and compares each rung's loss and +every gradient leaf with the rung before it: bit for bit where the two run +the same programs (same modes, same per-stage collective flavours, the same +F&B pairs), else within +loss rel 1e-5, cosine 0.999999 and max leaf rel err 1e-3 (a stash or +composed program may fuse differently on the TPU). On Lineage's layers a +rung that moves a chunk between a stage libtpu offloads collectives on and +one it does not (stage 0, which holds chip (0,0,0), on a TPU7x-8) runs that +chunk's SparseCore regions as TensorCore code on one side: such a pair is +held to loss rel 1e-5, cosine 0.9999 and max leaf rel err 2e-2 instead +(TOL_SC; the switch alone moved a leaf by 1.05e-3 in ds_ep_lineage_test, +its forward bit for bit). Pre-clip gradients are compared: the clip's +global norm sums its squares in a plan-dependent order. +Every rung is also checked against the port / the monolith as above. On CPU +(`--preset tiny`, or `tiny4` at M = 4) every rung of the default ladder is bit +for bit the one before it; F&B pair +rungs are bitwise on CPU too (ds_ep_test.test_paired_vs_unpaired_bitwise), +but count as other programs (a pair is one program: the TPU may fuse it +differently). Keep the splash kernel for stash rungs: under `--attn reference` +(which names none of its residuals) a stash backward recomputes the softmax +in other fusions than remat does, and on CPU its gradients moved by up to 9e-3 +of a leaf (cosine 0.999994) -- outside the rung tolerance. +""" + +from __future__ import annotations + +import argparse +import dataclasses +import gc +import os +import sys + +from maxtext.experimental.mpmd.jax import transfer + +if __name__ == "__main__" and os.environ.get("JAX_PLATFORMS", "") != "cpu": + transfer.set_max_inflight(1024) + +import jax # noqa: E402 +import jax.numpy as jnp # noqa: E402 +import numpy as np # noqa: E402 +from jax.sharding import NamedSharding, PartitionSpec as P # noqa: E402 + +from maxtext.experimental.mpmd.jax.deepseek import train as ds_train # noqa: E402 +from maxtext.experimental.mpmd.jax import ds_ep # noqa: E402 +from maxtext.experimental.mpmd.jax import ds_ep_pipeline as dsp # noqa: E402 + +VERBOSE = False + +PRESETS = { + # CPU sanity (interpret-mode kernels): the ds_ep_test shapes + "tiny": dict( + layers=4, + emb=256, + heads=2, + q_lora=128, + kv_lora=128, + moe_mlp=256, + experts=8, + topk=2, + vocab=512, + seq=256, + gbs=8, + mb=2, + vv=2, + wi_tiling=[128] * 9, + wo_tiling=[128] * 9, + sa_block=128, + ), + # ... at M = 4 + "tiny4": dict( + layers=4, + emb=256, + heads=2, + q_lora=128, + kv_lora=128, + moe_mlp=256, + experts=8, + topk=2, + vocab=512, + seq=256, + gbs=16, + mb=4, + vv=2, + wi_tiling=[128] * 9, + wo_tiling=[128] * 9, + sa_block=128, + ), + # layer dims shrunk so the single-device port holds the whole global batch + "small": dict( + layers=4, + emb=1024, + heads=16, + q_lora=512, + kv_lora=512, + moe_mlp=512, + experts=8, + topk=2, + vocab=4096, + seq=1024, + gbs=8, + mb=2, + vv=2, + ), + # PP=4 x FSDP=2 (over each chip's cores) x EP=1, gradients reduce-scattered every + # microbatch, argsort dispatch (what MaxText requires at EP=1) + "small-pp4": dict( + layers=4, + emb=1024, + heads=16, + q_lora=512, + kv_lora=512, + moe_mlp=512, + experts=8, + topk=2, + vocab=4096, + seq=1024, + gbs=8, + mb=2, + vv=1, + stages=4, + fsdp=2, + ep=1, + layout="snake", + grad_reduce="microbatch", + ragged_sort="off", + ), + # DeepSeek-V3's own per-layer dims (the benchmark's), 2 layers, 2 microbatches + "full-dims": dict( + layers=2, + emb=7168, + heads=128, + q_lora=1536, + kv_lora=512, + moe_mlp=2048, + experts=32, + topk=8, + vocab=32768, + seq=4096, + gbs=8, + mb=2, + vv=1, + ), + # v6e-4 (PP2 x FSDP1 x EP2, FSDP over each chip's cores): small's layer dims but emb 2048 + # (v6e's SparseCore gather-reduce asserts below 2048: its 32 subcores need >= 4 column + # partitions of >= 4 x 128 lanes to keep num_row_partitions <= its 8 SIMD lanes), 4 + # microbatches; -stash puts some (chunk, microbatch)s in 'lite' stash mode (a budget of + # three sets per stage, so the scheduler mixes the modes) + "small-v6e": dict( + layers=4, + emb=2048, + heads=16, + q_lora=512, + kv_lora=512, + moe_mlp=512, + experts=8, + topk=2, + vocab=4096, + seq=1024, + gbs=8, + mb=4, + vv=2, + fsdp=1, + ep=2, + layout="fsdp_on_chip", + ), + "small-v6e-stash": dict( + layers=4, + emb=2048, + heads=16, + q_lora=512, + kv_lora=512, + moe_mlp=512, + experts=8, + topk=2, + vocab=4096, + seq=1024, + gbs=8, + mb=4, + vv=2, + fsdp=1, + ep=2, + layout="fsdp_on_chip", + schedule="stash", + stash="lite", + stash_sets=3, + ), + # the benchmark's layer dims on v6e-4: 2 layers, 16 experts, the v6e megablox tiles + "full-dims-v6e": dict( + layers=2, + emb=7168, + heads=128, + q_lora=1536, + kv_lora=512, + moe_mlp=2048, + experts=16, + topk=8, + vocab=32768, + seq=4096, + gbs=4, + mb=2, + vv=1, + fsdp=1, + ep=2, + layout="fsdp_on_chip", + tiles="v6e", + ), + # config A itself (4 layers, gbs 16, M 8, V 2), for the full-dims ladder (--skip-port: + # the one-device port does not hold it) + "v6e-a": dict( + layers=4, + emb=7168, + heads=128, + q_lora=1536, + kv_lora=512, + moe_mlp=2048, + experts=16, + topk=8, + vocab=32768, + seq=4096, + gbs=16, + mb=8, + vv=2, + fsdp=1, + ep=2, + layout="fsdp_on_chip", + tiles="v6e", + ), + # small-pp4 at 2 chunks per stage: 8 layers and M=8, so Megatron's interleaved order (M a + # multiple of 4) and V placement run against the port and the monolith + "small-pp4-v2": dict( + layers=8, + emb=1024, + heads=16, + q_lora=512, + kv_lora=512, + moe_mlp=512, + experts=8, + topk=2, + vocab=4096, + seq=1024, + gbs=16, + mb=8, + vv=2, + stages=4, + fsdp=2, + ep=1, + layout="snake", + grad_reduce="microbatch", + ragged_sort="off", + ), + # TPU7x-8 PP=4 x FSDP=2 x EP=1 at full size, the PP=4 schedule sweep's model (8 layers, 32 + # experts, fp32 weights): rung against rung only (--skip-port --skip-monolith) + "pp4-e32": dict( + layers=8, + emb=7168, + heads=128, + q_lora=1536, + kv_lora=512, + moe_mlp=2048, + experts=32, + topk=8, + vocab=32768, + seq=4096, + gbs=32, + mb=8, + vv=2, + stages=4, + fsdp=2, + ep=1, + layout="snake", + grad_reduce="microbatch", + ragged_sort="off", + ), +} +# What a preset (or the command line) may set about the pipeline, and the defaults +# (placement None: circular; schedule None: ds_ep_pipeline.DEFAULT_SCHEDULE, +# breadth; pair_stages None: interleaved's, none). +PIPE = dict( + placement=None, + schedule=None, + stash="none", + stash_budget_gib=4.5, + stash_caps="", + init_by_chunk=False, + stash_sets=None, + pair_stages=None, + pair_gain=None, +) + + +def monolith_loss_and_grads(p, params, batch): + """(loss, grads in the storage layout) from one monolithic shard_map. + + Always uses lax collectives for EP (and the FSDP gather), so a pipeline built + with the collective-permute flavours is checked against an independent path. + Under batch split each layer runs on each device's two halves of the rows in + turn, with the halves' routing keys (ds_ep.split_layers' phases and its + whole-chunk backward are what it checks). + """ + scfg = dataclasses.replace(p.scfg, ep_collectives="xla") + mesh = p.meshes[0] + chunks = p.chunks + storage = [params[ch.stage][p.slot[ch.index]] for ch in chunks] + storage = [jax.device_put(w, jax.tree.map(lambda x: NamedSharding(mesh, x.sharding.spec), w)) for w in storage] + toks, tgts = batch + tok_sh = NamedSharding(mesh, P(ds_ep.FE, None)) + toks = [jax.device_put(t, tok_sh) for t in toks] + tgts = [jax.device_put(t, tok_sh) for t in tgts] + sspec = [ds_ep.chunk_storage_specs(c) for c in chunks] + cspec = [ds_ep.chunk_compute_specs(c) for c in chunks] + denom = float(p.gbs * p.seq) + cdt = [ds_ep.leaf_dtype_tree(scfg, c, "compute") for c in chunks] # the pipeline's compute copies' dtypes + M = p.M + + def body(storage, toks, tgts): + wc = jax.tree.map( + lambda x, s, c, d: ds_ep._gather_leaf(x, s, c, d), + storage, + sspec, + cspec, + cdt, + is_leaf=lambda x: not isinstance(x, (dict, list)), + ) + total = jnp.zeros((), jnp.float32) + for m in range(M): + h = ds_ep.embed(wc[0], toks[m], scfg) + for ch, w in zip(chunks, wc): + for l in range(ch.dense): # chunk 0's dense layers, on all of h + h = ds_ep.dense_layer_fwd(ds_ep.layer_weights(w["dense_layers"], l, ch.dense_kinds), h, scfg) + for l, lid in enumerate(ch.layers): + wl, key = ds_ep.layer_weights(w["layers"], l, ch.kinds), ds_ep._layer_key(lid, m) + if scfg.batch_split: # each device's rows as two halves, routed with keys of their own, one layer at a time + r = h.shape[0] // 2 + h = jnp.concatenate( + [ + ds_ep.layer_fwd(wl, h[:r], jax.random.fold_in(key, 0), scfg), + ds_ep.layer_fwd(wl, h[r:], jax.random.fold_in(key, 1), scfg), + ] + ) + else: + h = ds_ep.layer_fwd(wl, h, key, scfg) + total = total + ds_ep.head_loss(wc[-1], h, tgts[m], denom, scfg) + return total[None] + + f = jax.shard_map( + body, + mesh=mesh, + in_specs=(sspec, [P(ds_ep.FE, None)] * M, [P(ds_ep.FE, None)] * M), + out_specs=P(ds_ep.FE), + check_vma=False, + ) + loss, grads = jax.jit(jax.value_and_grad(lambda s, a, b: jnp.sum(f(s, a, b))))(storage, toks, tgts) + return loss, grads + + +def build( + preset, + random_routing, + attn="tokamax_splash", + topk=None, + batch_split=False, + batch_split_impl="lineage", + lineage_capacity_factor=None, + **pipe, +): + """The preset's pipeline. `pipe` overrides the preset's PIPE keys + (placement, schedule, stash, stash_budget_gib, stash_caps, init_by_chunk, + stash_sets: a stash budget of that many sets per stage, pair_stages as + `--pair-stages` has them, pair_gain) and fsdp / ep / layout / tiles / gbs. + A budget given in GiB replaces the preset's in sets. `batch_split`: the + stage programs run each device's rows as two halves + (StageConfig.batch_split), on `batch_split_impl`'s layers: Lineage's + (top-k routing only, Explicit stage meshes: ds_ep_pipeline resolves the + shard mode) or ds_ep.split_layers ('native', off TPU only).""" + k = dict(PIPE, **PRESETS[preset]) + pipe = {n: v for n, v in pipe.items() if v is not None} + if "stash_budget_gib" in pipe and "stash_sets" in pipe: + raise ValueError("give the stash budget once: stash_budget_gib or stash_sets") + if "stash_budget_gib" in pipe: + k["stash_sets"] = None + k.update(pipe) + if topk: + k["topk"] = topk + a = argparse.Namespace( + stages=k.get("stages", 2), + vv=k["vv"], + mb=k["mb"], + gbs=k["gbs"], + seq=k["seq"], + fsdp=k.get("fsdp", 2), + ep=k.get("ep", 2), + layers=k["layers"], + emb=k["emb"], + heads=k["heads"], + q_lora=k["q_lora"], + kv_lora=k["kv_lora"], + moe_mlp=k["moe_mlp"], + experts=k["experts"], + topk=k["topk"], + vocab=k["vocab"], + attn=attn, + sa_block=k.get("sa_block", 2048), + sa_block_kv_compute=min(512, k.get("sa_block", 2048)), + cost_estimate=5_000_000_000_000, + tiles=k.get("tiles", "clamped"), + wi_tiling=k.get("wi_tiling"), + wo_tiling=k.get("wo_tiling"), + rs_dtype="float32", + acc_dtype="float32", + remat_last=False, + schedule=k["schedule"], + layout=k.get("layout", "ep_on_chip"), + no_overlap=False, + fsdp_collectives="auto", + ep_collectives="auto", + pf_split=4, + rs_split=4, + costs="", + grad_reduce=k.get("grad_reduce", "step"), + routing="random" if random_routing else "topk", + shard_mode=None, + ragged_sort=k.get("ragged_sort", "auto"), + placement=k["placement"], + stash=k["stash"], + stash_budget_gib=k["stash_budget_gib"], + stash_caps=k["stash_caps"], + init_by_chunk=k["init_by_chunk"], + pair_stages=k["pair_stages"], + pair_gain=k["pair_gain"], + batch_split=batch_split, + batch_split_impl=batch_split_impl, + ) + if lineage_capacity_factor is not None: + a.lineage_capacity_factor = lineage_capacity_factor + if k["stash_sets"] is not None and k["stash"] != "none": + # a budget in whole sets: the set's size from the same pipeline without stash, under search, which runs no + # F&B pairs (build refuses the pair flags outside interleaved) + plain = {**vars(a), "schedule": "search", "stash": "none", "pair_stages": None, "pair_gain": None} + b = dsp.build(argparse.Namespace(**plain), random_routing=random_routing).progs[0].build_stash(k["stash"]).bytes + a.stash_budget_gib = k["stash_sets"] * b / 2**30 + # batch_split rides in the namespace, as --batch-split does, so resolve_tilings caps the wi dW tile (split_dw 'acc') + return dsp.build(a, random_routing=random_routing) + + +def scale_gate(p, params, factor): + """Scale every router kernel, then re-gather the pre-gathered chunks.""" + out = [] + for s_, ps in enumerate(params): + new = [] + for t in ps: + t = dict(t) + lay = dict(t["layers"]) + moe = dict(lay["moe"]) + moe["gate"] = {"kernel": moe["gate"]["kernel"] * factor} + lay["moe"] = moe + t["layers"] = lay + new.append(t) + out.append(new) + return out, [st.gather_first(q) for st, q in zip(p.stages, out)] + + +def to_host(tree): + return jax.tree.map(lambda x: np.asarray(jax.device_get(x), np.float32), tree) + + +def mpmd_loss_and_grads(p, params, wc0, batch): + grads, _, lacc = p.loss_and_grads_overlap(params, wc0, batch) + return float(jnp.sum(lacc)), [[to_host(g) for g in gs] for gs in grads] + + +def stacked(ch): + """Chunk `ch` with its layers stacked (layer_tree 'stacked'), whatever its own layer tree.""" + return dataclasses.replace(ch, kinds=(), dense_kinds=()) + + +def relayout(t, src, dst): + """A DeepSeek chunk tree `t` (weights or gradients) in chunk `src`'s layer tree -> in chunk `dst`'s: its 'layers' + and 'dense_layers' stacked ([n, ...] leaves) or one subtree a layer with a layer axis of one (layer_tree + 'per_layer': non-empty `ChunkSpec.kinds` / `dense_kinds`). Host arrays out where a stack is made; a cut is a + view.""" + t = dict(t) + for key, a, b in (("layers", src.kinds, dst.kinds), ("dense_layers", src.dense_kinds, dst.dense_kinds)): + if key not in t or bool(a) == bool(b): + continue + if a: + t[key] = jax.tree.map( + lambda *xs: np.concatenate(xs, axis=0), *(t[key][ds_ep.qwen_layer_key(l)] for l in range(len(a))) + ) + else: + t[key] = {ds_ep.qwen_layer_key(l): jax.tree.map(lambda x, l=l: x[l : l + 1], t[key]) for l in range(len(b))} + return t + + +def port_tree(p, chunk_trees): + """ds_ep chunk trees (in chunk order, in the pipeline's layer tree) -> the param tree of the DeepSeek-V3 port + (maxtext.experimental.mpmd.jax.deepseek).""" + chunk_trees = [relayout(t, ch, stacked(ch)) for ch, t in zip(p.chunks, chunk_trees, strict=True)] + + def moe_to_port(layer): + moe = layer["moe"] + return { + **{k: v for k, v in layer.items() if k != "moe"}, + "DeepSeekMoeBlock_0": { + "MoeBlock_0": {"gate": moe["gate"], "wi_0": moe["wi_0"], "wi_1": moe["wi_1"], "wo": moe["wo"]}, + "shared_experts": moe["shared_experts"], + }, + } + + cat = lambda trees: jax.tree.map(lambda *xs: np.concatenate(xs, axis=0), *trees) + decoder = { + "moe_layers": cat([moe_to_port(t["layers"]) for t in chunk_trees if "layers" in t]), + "decoder_norm": chunk_trees[-1]["decoder_norm"], + "logits_dense": chunk_trees[-1]["logits_dense"], + } + dense = [t["dense_layers"] for t in chunk_trees if "dense_layers" in t] + if dense: # the dense layers, chunk 0's (or the first chunks', in order) + decoder["dense_layers"] = cat(dense) + return {"token_embedder": chunk_trees[0]["token_embedder"], "decoder": decoder} + + +def port_to_chunks(p, g): + """Inverse of port_tree for gradients: -> list of ds_ep chunk trees, in the pipeline's layer tree.""" + out, start, dstart = [], 0, 0 + for ch in p.chunks: + n = len(ch.layers) + t = {} + if n: + lay = jax.tree.map(lambda x: x[start : start + n], g["decoder"]["moe_layers"]) + start += n + blk = lay.pop("DeepSeekMoeBlock_0") + lay["moe"] = {**blk["MoeBlock_0"], "shared_experts": blk["shared_experts"]} + t["layers"] = lay + if ch.dense: + t["dense_layers"] = jax.tree.map(lambda x: x[dstart : dstart + ch.dense], g["decoder"]["dense_layers"]) + dstart += ch.dense + if ch.first: + t["token_embedder"] = g["token_embedder"] + if ch.last: + t["decoder_norm"] = g["decoder"]["decoder_norm"] + t["logits_dense"] = g["decoder"]["logits_dense"] + out.append(relayout(t, stacked(ch), ch)) + return out + + +def port_loss_and_grads(p, params_host, tokens, targets): + cfg = dataclasses.replace( + p.scfg.model, + attention_kernel="splash" if jax.default_backend() == "tpu" else "reference", + moe_impl="ragged", + gmm_fp32_accum=True, + ) + dev = jax.devices()[0] + chunk_trees = [params_host[ch.stage][p.slot[ch.index]] for ch in p.chunks] + params = jax.device_put(port_tree(p, chunk_trees), dev) + B, L = tokens.shape + batch = jax.device_put( + { + "inputs": tokens, + "targets": targets, + "inputs_position": np.broadcast_to(np.arange(L, dtype=np.int32), (B, L)).copy(), + "inputs_segmentation": np.ones((B, L), np.int32), + "targets_segmentation": np.ones((B, L), np.int32), + }, + dev, + ) + tcfg = ds_train.TrainConfig() + f = jax.jit(jax.value_and_grad(lambda pr: ds_train.compute_loss(pr, {}, batch, cfg, tcfg)[0])) + loss, g = f(params) + return float(loss), port_to_chunks(p, to_host(g)) + + +def port_floor(p, params_host, tokens, targets): + """The reassociation floor: the port against ITSELF, whole batch vs the sum of + per-microbatch gradients -- the same numbers in a different summation order, + which is all a correct pipeline is allowed to change.""" + _, whole = port_loss_and_grads(p, params_host, tokens, targets) + parts = None + for m in range(p.M): + sl = slice(m * p.mbs, (m + 1) * p.mbs) + _, g = port_loss_and_grads(p, params_host, tokens[sl], targets[sl]) + g = jax.tree.map(lambda x: x * (p.mbs / p.gbs), g) # per-microbatch mean -> share of the batch mean + parts = g if parts is None else jax.tree.map(np.add, parts, g) + as_grads = [[None] * len(p.stage_chunks[s]) for s in range(p.S)] + for ch in p.chunks: + as_grads[ch.stage][p.slot[ch.index]] = parts[ch.index] + return errors(p, as_grads, whole) + + +def errors(p, grads, ref_chunks): + """-> (sorted [(rel_err, leaf name)], whole-model cosine, norm ratio).""" + return chunk_errors([grads[ch.stage][p.slot[ch.index]] for ch in p.chunks], ref_chunks) + + +def chunk_errors(got_chunks, ref_chunks): + """errors() of two lists of chunk trees, in chunk order.""" + rows, dot, na, nb = [], 0.0, 0.0, 0.0 + for c, (g, r) in enumerate(zip(got_chunks, ref_chunks, strict=True)): + ga = jax.tree_util.tree_flatten_with_path(g)[0] + gb = jax.tree.leaves(r) + for (path, a), b in zip(ga, gb, strict=True): + assert a.shape == b.shape, (jax.tree_util.keystr(path), a.shape, b.shape) + a64, b64 = a.astype(np.float64), b.astype(np.float64) + rows.append((float(np.linalg.norm(a64 - b64) / (np.linalg.norm(b64) + 1e-30)), f"c{c}{jax.tree_util.keystr(path)}")) + dot += float(np.vdot(a64, b64)) + na += float(np.vdot(a64, a64)) + nb += float(np.vdot(b64, b64)) + rows.sort(reverse=True) + return rows, dot / np.sqrt(na * nb), np.sqrt(na / nb) + + +def compare(label, p, loss, ref_loss, grads, ref_chunks, tol_loss, tol_leaf): + print(f"\n=== {label}") + rl = abs(loss - ref_loss) / abs(ref_loss) + print(f" loss mpmd {loss:.7f} ref {ref_loss:.7f} rel err {rl:.2e} (tol {tol_loss:.0e})") + rows, cos, gn = errors(p, grads, ref_chunks) + print(f" gradients: {len(rows)} leaves, whole-model cosine {cos:.7f}, norm ratio {gn:.6f}") + print( + f" per-leaf relative error: median {np.median([e for e, _ in rows]):.2e}, " + f"worst {rows[0][0]:.2e} (tol {tol_leaf:.0e})" + ) + for e, n in sorted(rows, key=lambda r: r[1]) if VERBOSE else rows[:5]: + print(f" {e:.2e} {n}") + ok = rl < tol_loss and rows[0][0] < tol_leaf and cos > 0.9999 + print(f' {"PASS" if ok else "FAIL"}') + return ok + + +# ------------------------------------------------------------------ ladder +# (placement, schedule, stash[, pair stages]) rungs; each is compared with the +# one before it. +RUNGS = "circular:search:none,circular:timed:none,circular:stash:lite,v:search:none,v:timed:none,v:stash:lite" +# rung to rung where the programs differ (stash, or another collective +# flavour): what a TPU fusing a program differently may move, and no more +TOL_RUNG = dict(loss=1e-5, cosine=0.999999, leaf=1e-3) +# ... where a chunk's stage's Lineage SparseCore answer differs (on Lineage's +# layers, sparsecore_moves): its Region runs those regions as TensorCore code +# on one side, an engine change, not a fusion one -- the cosine and worst leaf +# ds_ep_lineage_test holds that switch alone to (test_sparsecore_off_vs_on; +# measured: the forward bit for bit, a leaf 1.05e-3 apart), the loss as above +TOL_SC = dict(loss=1e-5, cosine=0.9999, leaf=2e-2) + + +def parse_rungs(spec, vv, mb=None, stages=2, batch_split=False): + """--rungs -> [the rung's pipeline keys], leaving out with a note the rungs the preset cannot run, a rung naming + pair stages for a schedule other than interleaved (the only one that pairs on stages), and under `batch_split` + the stash rungs (batch split runs the recompute programs only).""" + out = [] + for r in spec.split(","): + placement, schedule, stash, *pairs = r.split(":") + if placement == "v" and vv != 2: + print(f" skipping rung {r}: V placement needs vv 2 (the preset has {vv})") + continue + if batch_split and stash != "none": + print(f" skipping rung {r}: batch split runs the recompute programs only (no stash)") + continue + if pairs and schedule != "interleaved": + print(f" skipping rung {r}: only interleaved pairs F and B on stages (pair stages {pairs[0]})") + continue + if schedule == "interleaved" and (placement != "circular" or vv < 2 or (mb is not None and mb % stages)): + print( + f" skipping rung {r}: interleaved 1F1B needs circular placement, vv >= 2 and M a " + f"multiple of S = {stages} (the preset has vv {vv}, M {mb})" + ) + continue + rung = dict(placement=placement, schedule=schedule, stash=stash) + if pairs: + rung["pair_stages"] = pairs[0].replace("+", ",") + out.append(rung) + return out + + +def programs_of(p): + """What decides whether two rungs run the same arithmetic: every (chunk, + microbatch)'s mode, the collective flavours of each chunk's stage -- + under batch split on Lineage's layers also whether it runs their + SparseCore regions (ds_ep_lineage_test measured 1.05e-3 a leaf between + the two: such rungs are held to TOL_SC, sparsecore_moves) -- and which + ops run together as one F&B pair program.""" + sc = p.lineage_sparsecore() + return ( + tuple(sorted(p.modes.items())), + tuple( + (p.stage_scfg[ch.stage].ep_collectives, p.stage_scfg[ch.stage].fsdp_collectives, sc.get(ch.stage)) + for ch in p.chunks + ), + tuple(sorted((p.order[j], p.order[j + 1]) for j in p.fuse)), + ) + + +def sparsecore_moves(progs, prev): + """The chunks whose stage's Lineage SparseCore answer differs between two rungs' `programs_of` -> [chunk]; [] off + Lineage's layers, where every answer is None.""" + return [c for c, (x, y) in enumerate(zip(progs[1], prev[1], strict=True)) if x[2] != y[2]] + + +def compare_rungs(label, loss, prev_loss, grads, prev, same, strict, moved=()): + """One rung against the rung before it (chunk-order host trees). `same`: + they run the same programs, so the gradients should be bit for bit equal + (a miss within TOL_RUNG fails under `strict`, else only warns). `moved`: + the chunks whose Lineage SparseCore answer differs between the two + (sparsecore_moves), which holds them to TOL_SC instead of TOL_RUNG.""" + tol = TOL_SC if moved else TOL_RUNG + print(f"\n=== {label}") + bitwise = loss == prev_loss and all( + np.array_equal(x, y) for x, y in zip(jax.tree.leaves(grads), jax.tree.leaves(prev), strict=True) + ) + rl = abs(loss - prev_loss) / abs(prev_loss) + rows, cos, gn = chunk_errors(grads, prev) + print( + f" loss {loss:.7f} vs {prev_loss:.7f} (rel {rl:.2e}); {len(rows)} leaves, cosine {cos:.9f}, " + f"norm ratio {gn:.9f}, worst leaf rel err {rows[0][0]:.2e} ({rows[0][1]})" + ) + near = rl <= tol["loss"] and cos >= tol["cosine"] and rows[0][0] < tol["leaf"] + within = ( + f"the SparseCore switch's tolerance, TOL_SC: chunk(s) {list(moved)} run Lineage's SparseCore regions " + "on one side only" + if moved + else "tolerance" + ) + if bitwise: + verdict, ok = "PASS (bitwise)", True + elif same: + ok = near and not strict + verdict = ("WARN" if ok else "FAIL") + ": the same programs, not bitwise" + (f" (within {within})" if near else "") + else: + verdict, ok = ( + f"PASS (within {within}; the programs differ)" if near else "FAIL" + (f" (outside {within})" if moved else "") + ), near + print(f" {verdict}") + return ok + + +def ladder(a, pipe): + """Every rung on one set of weights and one batch: against the port / the + monolith (as `main` checks one pipeline), and against the rung before it.""" + pre = PRESETS[a.preset] + lineage = a.batch_split and a.batch_split_impl == "lineage" # top-k routing only: no monolith phase + rungs = parse_rungs(a.rungs, pre["vv"], pre["mb"], pre.get("stages", 2), batch_split=a.batch_split) + phases = [] + if not a.skip_port: + phases.append(("port", False, PRESETS[a.preset]["experts"] if a.topk == -1 else (a.topk or None), 0)) + if not a.skip_monolith and not lineage: + phases.append(("monolith", True, None, 1)) + if not phases: + # neither reference fits (config A: the one-device port, the one-program monolith): + # rung against rung only, with the benchmark's random routing (Lineage's layers: the preset's top-k) + phases.append(("rungs", not lineage, None, 1)) + if not rungs or (len(rungs) == 1 and phases[0][0] == "rungs"): + return [] # nothing to compare with anything: `finish` fails the run before a rung is built + results = [] + for phase, random_routing, topk, seed in phases: + prev = None + for i, r in enumerate(rungs): + name = ":".join(r.values()).replace(",", "+") + keys = {**pipe, **r, "init_by_chunk": True} + if r["schedule"] != "interleaved": # --pair-stages / --pair-gain are its pairs' (ds_ep_pipeline refuses them else) + keys = {k: v for k, v in keys.items() if k not in ("pair_stages", "pair_gain")} + p = build( + a.preset, + random_routing, + attn=a.attn if phase == "port" else "tokamax_splash", + topk=topk, + batch_split=a.batch_split, + **keys, + ) + print(f"\n##### rung {name} ({phase})\n" + p.summary(), flush=True) + if i == 0: + # the weights and the batch every rung of this phase shares + params, _, _ = p.init(jax.random.key(seed)) + trees = [to_host(t) for t in p.chunk_trees(params)] + rng = np.random.default_rng(0 if phase == "port" else 3) + tokens = rng.integers(0, p.scfg.model.vocab_size, size=(p.gbs, p.seq), dtype=np.int32) + targets = np.roll(tokens, -1, axis=1) + if phase == "port": + host = [[trees[ch.index] for ch in p.stage_chunks[s]] for s in range(p.S)] + ref_loss, ref = port_loss_and_grads(p, host, tokens, targets) + elif phase == "rungs": + ref_loss = ref = None + else: + ref_loss, ref_grads = monolith_loss_and_grads(p, params, p.put_batch(tokens, targets)) + ref_loss, ref = float(ref_loss), [to_host(g) for g in ref_grads] + del ref_grads + del params + gc.collect() + params = p.params_from_chunks(trees) + wc0 = [st.gather_first(q) for st, q in zip(p.stages, params)] + loss, grads = mpmd_loss_and_grads(p, params, wc0, p.put_batch(tokens, targets)) + if ref is not None: + results.append(compare(f"rung {name} vs {phase}", p, loss, ref_loss, grads, ref, 2e-3, 5e-2)) + else: + print(f" loss {loss:.7f}", flush=True) + chunks, progs = p.chunk_trees(grads), programs_of(p) + if prev is not None: + results.append( + compare_rungs( + f"rung {name} vs rung {prev[0]} ({phase})", + loss, + prev[1], + chunks, + prev[2], + progs == prev[3], + a.strict_bitwise, + moved=sparsecore_moves(progs, prev[3]), + ) + ) + prev = (name, loss, chunks, progs) + del p, params, wc0, grads + gc.collect() + return results + + +def finish(results): + """Exit with the verdict of the checks `results` (each True for a pass): 0 only when something was compared and + every comparison passed. Flags that leave nothing to compare -- --skip-port with the monolith phase skipped too + (--skip-monolith, or --batch-split on Lineage's layers: the monolith routes at random, which they cannot), a + --ladder whose rungs are all skipped or of one rung with no reference -- fail, rather than report ALL PASS over no + check.""" + if not results: + sys.stdout.flush() # the notes on skipped rungs before this, where a log takes stdout and stderr together + sys.exit( + "ds_ep_parity: nothing checked -- every reference phase was skipped (--skip-port; the monolith by " + "--skip-monolith, or by --batch-split on Lineage's layers), or a --ladder had no rung to run (each " + "skipped, as printed above) or one rung and no reference" + ) + print("\nALL PASS" if all(results) else "\nSOME CHECK FAILED") + sys.exit(0 if all(results) else 1) + + +def main(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("--preset", default="small", choices=list(PRESETS)) + ap.add_argument("--skip-port", action="store_true") + ap.add_argument("--verbose", action="store_true") + ap.add_argument("--floor", action="store_true", help="also measure the summation-order floor") + ap.add_argument( + "--attn", default="tokamax_splash", help="pipeline attention kernel ('reference' = the port's CPU kernel)" + ) + ap.add_argument( + "--topk", type=int, default=-1, help="experts per token for the port check (-1: all experts, see the docstring)" + ) + ap.add_argument( + "--gate-scale", type=float, default=1.0, help="multiply the router weights at init (margins between top-k choices)" + ) + ap.add_argument("--skip-monolith", action="store_true") + # the pipeline (default: the preset's) + ap.add_argument("--placement", default=None, choices=["circular", "v"]) + ap.add_argument("--schedule", default=None) + ap.add_argument("--stash", default=None) + ap.add_argument("--stash-budget-gib", type=float, default=None) + ap.add_argument("--stash-sets", type=int, default=None, help="a stash budget of this many sets per stage") + ap.add_argument("--stash-caps", default=None) + ap.add_argument("--init-by-chunk", action="store_true", default=None) + ap.add_argument("--pair-stages", default=None, help="all | none | 1 | 0,1 (see ds_ep_pipeline)") + ap.add_argument("--pair-gain", type=float, default=None) + ap.add_argument( + "--ladder", + action="store_true", + help="run --rungs on the same weights and batch, each against the one before and " "the references", + ) + ap.add_argument( + "--rungs", default=RUNGS, help="placement:schedule:stash[:pair stages],... (pair stages: all, none, 1, 0+1)" + ) + ap.add_argument( + "--strict-bitwise", + action="store_true", + help="--ladder: two rungs running the same programs must be bitwise equal (else a " + "miss within tolerance only warns)", + ) + ap.add_argument( + "--batch-split", + action="store_true", + help="each device's rows of a microbatch as two halves in Lineage's phases (ds_ep_pipeline " + "--batch-split): wants an even number of rows a device, see --gbs", + ) + ap.add_argument( + "--batch-split-impl", + default="lineage", + choices=list(ds_ep.BATCH_SPLIT_IMPLS), + help="--batch-split's layers, as ds_ep_pipeline's flag: lineage (MaxText's Lineage layers, TPU " + "only: the port check only, at top-k, so a preset whose one-device port holds the doubled " + "batch; see the docstring) or native (ds_ep.split_layers, both references; off TPU only)", + ) + ap.add_argument( + "--lineage-capacity-factor", + type=float, + default=None, + help="--batch-split on Lineage's layers: ds_ep_pipeline's flag (default its default)", + ) + ap.add_argument("--gbs", type=int, default=None, help="the preset's global batch, overridden") + a = ap.parse_args(argv) + global VERBOSE + VERBOSE = a.verbose + pipe = {k: getattr(a, k) for k in PIPE if getattr(a, k, None) is not None} + if a.gbs is not None: + pipe["gbs"] = a.gbs + lineage = a.batch_split and a.batch_split_impl == "lineage" + if lineage: + ns = argparse.Namespace(batch_split=True, batch_split_impl="lineage") + why = dsp.lineage_missing(ns) + if why is None and (a.ladder or not a.skip_port): # (else nothing runs Lineage's layers: `finish` says so) + why = dsp.lineage_off_tpu(ns) + if why is not None: + sys.exit(f"ds_ep_parity --batch-split: {why}") + pipe.update(batch_split_impl="lineage", lineage_capacity_factor=a.lineage_capacity_factor) + elif a.batch_split: + pipe["batch_split_impl"] = "native" + # the flags only Lineage's layers read, given where they do not run (ds_ep_pipeline's warning); a given + # --lineage-capacity-factor is told apart here even at ds_ep_pipeline's default (ours is None) + cf = {} if a.lineage_capacity_factor is None else {"lineage_capacity_factor": a.lineage_capacity_factor} + for line in dsp.lineage_unused( + argparse.Namespace(batch_split=a.batch_split, batch_split_impl=a.batch_split_impl, **cf), given=set(cf) + ): + print(f"warning: {line}", flush=True) + split = (", batch split on Lineage's layers" if lineage else ", batch split (native)") if a.batch_split else "" + results = [] + + if a.ladder: + finish(ladder(a, pipe)) + + if not a.skip_port: + p = build( + a.preset, + random_routing=False, + attn=a.attn, + topk=PRESETS[a.preset]["experts"] if a.topk == -1 else (a.topk or None), + batch_split=a.batch_split, + **pipe, + ) + print(p.summary(), flush=True) + params, _, wc0 = p.init(jax.random.key(0)) + if a.gate_scale != 1.0: + params, wc0 = scale_gate(p, params, a.gate_scale) + rng = np.random.default_rng(0) + tokens = rng.integers(0, p.scfg.model.vocab_size, size=(p.gbs, p.seq), dtype=np.int32) + targets = np.roll(tokens, -1, axis=1) + batch = p.put_batch(tokens, targets) + loss, grads = mpmd_loss_and_grads(p, params, wc0, batch) + params_host = [[to_host(t) for t in ps] for ps in params] + del params, wc0, batch + gc.collect() + ref_loss, ref = port_loss_and_grads(p, params_host, tokens, targets) + if a.floor: + rows, cos, _ = port_floor(p, params_host, tokens, targets) + print(f"\n=== summation-order floor (port whole batch vs port summed over {p.M} microbatches)") + print( + f" cosine {cos:.7f}; per-leaf relative error median {np.median([e for e, _ in rows]):.2e}, " + f"worst {rows[0][0]:.2e} ({rows[0][1]})" + ) + results.append( + compare( + f"MPMD pipeline vs maxtext.experimental.mpmd.jax.deepseek port (top-{p.scfg.model.num_experts_per_tok}" + f" of {p.scfg.model.num_experts} routing, {a.preset}{split})", + p, + loss, + ref_loss, + grads, + ref, + 2e-3, + 5e-2, + ) + ) + del p + gc.collect() + + if not a.skip_monolith and lineage: + print( + "\n=== monolith: skipped -- it routes at random, which Lineage's layers cannot (off TPU, --batch-split-impl " + "native checks ds_ep's own split layers against it)", + flush=True, + ) + elif not a.skip_monolith: + p = build(a.preset, random_routing=True, batch_split=a.batch_split, **pipe) + params, _, wc0 = p.init(jax.random.key(1)) + batch = p.synthetic_batch(3) + loss, grads = mpmd_loss_and_grads(p, params, wc0, batch) + ref_loss, ref_grads = monolith_loss_and_grads(p, params, batch) + results.append( + compare( + f"MPMD pipeline vs monolithic single-program reference (random routing, {a.preset}{split})", + p, + loss, + float(ref_loss), + grads, + [to_host(r) for r in ref_grads], + 2e-3, + 5e-2, + ) + ) + finish(results) + + +if __name__ == "__main__": + main() diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep_pipeline.py b/src/maxtext/experimental/mpmd/jax/ds_ep_pipeline.py new file mode 100644 index 0000000000..82934f9acd --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep_pipeline.py @@ -0,0 +1,7137 @@ +# 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 of DeepSeek-V3 sparse layers with FSDP x EP inside each stage +(or, with `--model qwen3.8-2.4t-a95b` / another QWEN_MODELS name, of a Qwen3.5-family +model's: Gated DeltaNet and gated-attention MoE layers, ds_ep.layer_fwd with +ds_ep.qwen_mixer_part in attention's place). + + S stages, each its own jitted programs on a disjoint ('fsdp','expert') + sub-mesh; the model is cut into C = S*V chunks placed circularly + (chunk c on stage c % S), which with one layer per chunk is exactly + MaxText's circular-pipeline layer map (layer = repeat * S + stage) -- + or, with `placement='v'` (V = 2), V-shaped: stage s holds chunks s and + 2S-1-s, so the embedding and the head share stage 0 and the turn at + chunk S-1 -> S stays on one stage. + +One training step, per stage: + + gather storage (fp32, FSDP-sharded) -> compute (bf16, gathered) once + F / B per microbatch, in `schedule` order, against the gathered + weights; weight gradients accumulate per device, unreduced + reduce one reduce-scatter of the accumulated gradients once + update AdamW with global-norm clipping (one scalar hop per stage) once + +Each (chunk, microbatch) runs in a mode, 'r' by default: its forward keeps +only the layer inputs and its backward recomputes the layers (MaxText's remat +'full'). `--schedule stash` gives some of them a stash mode instead +(ds_ep.STASH_POLICIES): the forward also keeps what the policy names and the +backward skips recomputing it, as many at once as a per-stage HBM budget +allows (schedule.stash_search). + +An F&B pair runs the forward of one microbatch and the backward of another, +both of one stage, as ONE program (`ds_ep.compose` of the two parts), so XLA +may overlap one's collectives and SparseCore work with the other's compute: +`--schedule interleaved` runs its steady state's F and B as pairs on the +stages `--pair-stages` names (none unless it is given: Megatron-LM's combined +1F1B, one microbatch's expert-parallel collectives beside another's compute). +It takes `--stash` too: the stash modes of its fixed order under the budget +(schedule.stash_modes). + +The driver is one Python thread that only enqueues: nothing in `step` blocks, +so every device's FIFO queue is kept full and idle time on a device can only +come from a data dependency (a pipeline bubble) -- never from the host. + + python3 -m maxtext.experimental.mpmd.jax.ds_ep_pipeline --bench --profile /tmp/xprof/mpmd +""" + +from __future__ import annotations + +import argparse +import collections +import contextlib +import dataclasses +import functools +import hashlib +import importlib.metadata +import importlib.util +import io +import itertools +import json +import numbers +import os +import queue +import re +import shutil +import socket +import stat +import statistics +import subprocess +import sys +import threading +import time +import warnings + +# The PJRT run-ahead cap must be raised before the TPU client exists. Under Pathways (JAX_PLATFORMS=proxy) there is +# no PJRT client here to cap (the IFRT proxy client takes no options; in local runs the client ran ~90 steps ahead +# without blocking), nor a jax compile cache to set up (pathways.initialize turns it off: Pathways caches compiled +# programs under its servers' --gcs_scratch_location). +from maxtext.experimental.mpmd.jax import pathways # noqa: E402 (imports neither jax nor pathwaysutils) +from maxtext.experimental.mpmd.jax import transfer # noqa: E402 (imports jax, but no backend init) + +if __name__ == "__main__" and os.environ.get("JAX_PLATFORMS", "") != "cpu" and not pathways.is_proxy(): + transfer.set_max_inflight(1024) + +import jax # noqa: E402 +import jax.numpy as jnp # noqa: E402 + +if __name__ == "__main__" and not pathways.is_proxy(): + # Programs are re-lowered every run; the persistent cache makes the second + # run of an unchanged program a disk read instead of a multi-minute compile. + # Its key strips op names (locations), so after a change that alters only + # names -- adding, removing or renaming a named scope -- point JAX_CACHE_DIR + # somewhere fresh, or every program whose IR is otherwise unchanged keeps its + # old names in the trace. + jax.config.update("jax_compilation_cache_dir", os.environ.get("JAX_CACHE_DIR", os.path.expanduser("~/jax_cache"))) + jax.config.update("jax_persistent_cache_min_compile_time_secs", 0) + jax.config.update("jax_persistent_cache_min_entry_size_bytes", -1) + + +def cache_every_process(): + """Under jax.distributed jax writes persistent-cache entries from process 0 + only (compiler._cache_write: contention on a shared filesystem such as GCS), + so every other process -- every other stage -- compiles all its programs + again on every run. Where each process's JAX_CACHE_DIR is a disk of its own + (a GPU node's local SSD: a GPU job's entry script sets + MPMD_CACHE_EVERY_PROCESS=1) every process may write its own entries: the + check reads jax's process id, so the write runs as process 0's does. Best + effort: a jax without these internals keeps its own rule. The write is + jax's own (compilation_cache.put_executable_and_time, behind the same + minimum compile time), without the process check.""" + try: + from jax._src import compilation_cache as _cc + from jax._src import compiler as _compiler + from jax._src import config as _config + except ImportError: + return False + write = getattr(_compiler, "_cache_write", None) + put = getattr(_cc, "put_executable_and_time", None) + if write is None or put is None or getattr(write, "_mpmd_every_process", False): + return False + + def every_process_write(cache_key, compile_time_secs, module_name, backend, executable): + if compile_time_secs < _config.persistent_cache_min_compile_time_secs.value: + return + try: + put(cache_key, module_name, executable, backend, int(compile_time_secs)) + except Exception as e: # jax warns and goes on likewise + warnings.warn(f"Error writing persistent compilation cache entry for '{module_name}': " f"{type(e).__name__}: {e}") + + every_process_write._mpmd_every_process = True + _compiler._cache_write = every_process_write + return True + + +if __name__ == "__main__" and os.environ.get("MPMD_CACHE_EVERY_PROCESS", "") == "1" and not pathways.is_proxy(): + cache_every_process() +import numpy as np # noqa: E402 +from jax.sharding import AxisType, Mesh, NamedSharding, PartitionSpec as P # noqa: E402 + +from maxtext.experimental.mpmd.jax.deepseek.config import DeepSeekConfig # noqa: E402 +from maxtext.experimental.mpmd.jax.qwen35.config import GDN_CONV_IMPLS, GDN_SCAN_IMPLS, Qwen35Config # noqa: E402 +from maxtext.experimental.mpmd.jax import ds_ep # noqa: E402 +from maxtext.experimental.mpmd.jax import ds_ep_lineage # noqa: E402 (Lineage itself loads when a program traces) +from maxtext.experimental.mpmd.jax import profiling # noqa: E402 +from maxtext.experimental.mpmd.jax import schedule as sched # noqa: E402 +from maxtext.experimental.mpmd.jax import xprof_align # noqa: E402 + + +# ------------------------------------------------------------------- meshes +LAYOUTS = ("fsdp_on_chip", "ep_on_chip", "snake", "physical", "physical_origin_last", "slices") + + +def libtpu_flag(flag, args=None): + """Boolean libtpu flag `flag` (its name, no dashes) as LIBTPU_INIT_ARGS (or `args`) sets it: + True, False, or None when the variable does not name the flag (libtpu's own default then + holds). The last mention wins, in any absl spelling: one dash or two, --flag, --flag=VALUE, + --noflag.""" + args = os.environ.get("LIBTPU_INIT_ARGS", "") if args is None else args + val = None + for tok in args.split(): + m = re.fullmatch(r"--?(no)?" + re.escape(flag) + r"(?:=(.*))?", tok) + if m is None: + continue + if m.group(1): + val = False + elif m.group(2) is None: + val = True + else: # anything absl would not read as true counts as off + val = m.group(2).lower() in ("true", "t", "1", "yes", "y") + return val + + +def slice_index(d): + """Device d's slice: its `slice_index` (CPU devices under jax.distributed + carry 0), None where it has none (CPU in one process, a compile-only + topology of one slice).""" + return getattr(d, "slice_index", None) + + +def slice_groups(devices=None): + """The devices (default: every device of the job) by slice -> [[device]], + in slice order, each slice's devices in (process, id) order. + + TPU devices of a multi-slice job, or of a multi-slice compile-only topology + (`ds_ep_aot --num-slices`), carry their slice's `slice_index`. Devices of + one slice -- slice 0, or none at all (CPU in one process; a one-slice + topology) -- are one group, unless MPMD_FAKE_SLICES=N stands in for N + slices: the devices in (process, id) order, cut into N equal contiguous + groups. A host belongs to one slice, so no group may split a process -- + unless one process holds them all: a one-process run, as the multi-process + tests' reference is, or a Pathways client's (pathways.multi_controller of + the devices: then no process is looked at). Devices of several slices + refuse MPMD_FAKE_SLICES (a leftover setting must not re-cut a multi-slice + job); CPU devices under jax.distributed carry slice 0, and take it. + """ + devs = list(jax.devices() if devices is None else devices) + multi = pathways.multi_controller(devs) # several processes' devices (multi-controller, a topology's hosts) + order = (lambda d: (d.process_index, d.id)) if multi else (lambda d: d.id) # (process, id); one process's: id + fake = os.environ.get("MPMD_FAKE_SLICES", "") + if fake: + n = int(fake) if fake.isdigit() else 0 + if n < 1: + raise ValueError(f"MPMD_FAKE_SLICES={fake!r}: want a positive number of slices") + if len(own := sorted({k for k in map(slice_index, devs) if k is not None})) > 1: + raise ValueError(f"MPMD_FAKE_SLICES={fake}: these devices are on slices {own} of their own; unset it") + if len(devs) % n: + raise ValueError(f"MPMD_FAKE_SLICES={n}: {len(devs)} devices do not cut into {n} equal slices") + devs, k = sorted(devs, key=order), len(devs) // n + groups = [devs[i * k : (i + 1) * k] for i in range(n)] + if multi: + procs = [{d.process_index for d in g} for g in groups] + split = sorted({q for i in range(n) for j in range(i) for q in procs[i] & procs[j]}) + if split: + raise ValueError( + f"MPMD_FAKE_SLICES={n}: slices of {k} devices would split processes {split} (a host belongs to one slice)" + ) + return groups + groups = collections.defaultdict(list) + for d in devs: + groups[slice_index(d)].append(d) + return [sorted(groups[k], key=order) for k in sorted(groups, key=lambda k: -1 if k is None else k)] + + +def slice_spanning_stages(meshes): + """The stages whose devices lie on more than one slice -> [stage]: their + FSDP and EP collectives cross DCN. --layout slices makes none; the layouts + that cut stages in device-id order make one wherever a stage's share of + the ids straddles two slices (whether a multi-slice job's runtime ids are + grouped by slice is unverified; a compile-only topology's are).""" + return [s for s, m in enumerate(meshes) if len({slice_index(d) for d in m.devices.flat} - {None}) > 1] + + +# Numbers the key-value store keys of each multi-controller pipeline's offload answers (`offload_answers`): +# every process builds its pipelines in one order, so the n-th's are under one key on every process. +_OFFLOAD_KEYS = itertools.count() + + +# The boundary transports that cross TPU slices: the host relay (every MPMD +# run of PP over DCN on 2 x v5p-128, 2026-10) and the collective-permute program. +# Between slices jax's native copy hangs and jax.experimental.transfer's +# receiver crashes within a few pulls (2026-10, jax 0.11.1, libtpu 0.0.46). +CROSS_SLICE_TRANSPORTS = ("relay", "ppermute") + + +def stage_slices(meshes): + """The slices the stages' devices are on -> sorted [slice_index] (none for devices without one).""" + return sorted({k for m in meshes for k in map(slice_index, m.devices.flat) if k is not None}) + + +def on_pathways(meshes): + """Are the meshes' devices Pathways' (the IFRT proxy's: `pathways.is_proxy_device`)?""" + return bool(meshes) and pathways.is_proxy_device(meshes[0].devices.flat[0]) + + +def cross_slice_warning(meshes, transport): + """What to warn of when the stages span TPU slices and `transport` is not + one that crosses them (CROSS_SLICE_TRANSPORTS) -> str, else None. Under + Pathways none: there the one process's native copy is an IFRT CopyArrays + that the Pathways servers carry between the slices -- not jax's cross-host + copy, which hung -- and the host transports need --distributed, which + Pathways refuses (`cross_slice_note` says how the boundaries cross).""" + across = stage_slices(meshes) + if len(across) < 2 or transport in CROSS_SLICE_TRANSPORTS or on_pathways(meshes): + return None + return ( + f"the stages span slices {across} and --transport {transport} crosses them: between TPU slices jax's " + "native copy hangs and jax.experimental.transfer's receiver crashes within a few pulls " + "(seen with jax 0.11.1, libtpu 0.0.46); --transport relay or ppermute crosses them" + ) + + +def cross_slice_note(meshes, transport, proxy=None): + """Under Pathways, when the stages span TPU slices: how the boundary copies + cross them -> str, else None. The native copy is one IFRT CopyArrays a + boundary, device to device, moved by the Pathways servers -- inside a + slice at McJAX's own rate (186 GB/s between two 2-chip halves of a + tpu7x-8, local docker Pathways); between slices unmeasured here (partir's + compiled CopyArrays crossed DCN) -- and ppermute a collective-permute + program over both stages' slices. `proxy`: whether the stages run under + Pathways (None: `on_pathways`).""" + across = stage_slices(meshes) + if len(across) < 2 or not (on_pathways(meshes) if proxy is None else proxy): + return None + how = { + "native": "one IFRT CopyArrays, which the Pathways servers carry between the slices", + "ppermute": "a collective-permute program over both stages' slices", + }.get(transport, f"--transport {transport}") + return f"the stages span slices {across}: under Pathways each boundary copy (--transport {transport}) is {how}" + + +def chip_strips(devices, k, name="the devices"): + """`devices` -- one slice's, each with its chip `coords` -- cut into k strips of whole chips -> [[device]], each in + `devices`' order: along the last chip axis (x, y, z) k divides, strip j the j-th k-th of the chips along it, every + TensorCore of each (--layout slices at k stages a slice). Along z, a 3D slice's last axis, a host (2x2x1 chips on + TPU7x and v5p) is one chip deep, so each strip there holds whole hosts. A ValueError (`name`: the devices') where + they are not every TensorCore of a solid box of chips (a fake slice cut through a chip or across a box), or where + no chip axis of the box is a multiple of k.""" + coords = [tuple(d.coords) for d in devices] + chips = collections.Counter(coords) + lo = np.min(coords, axis=0) + dims = [int(n) for n in np.max(coords, axis=0) - lo + 1] + box = "x".join(map(str, dims)) + if len(chips) != int(np.prod(dims)) or len(set(chips.values())) != 1: + raise ValueError( + f"layout 'slices': {name}'s {len(devices)} devices are not every TensorCore of a solid box of chips " + f"({len(chips)} chips in a {box} box; MPMD_FAKE_SLICES on a TPU must cut whole boxes)" + ) + axes = [a for a, n in enumerate(dims) if n % k == 0] + if not axes: + ks = sorted({j for n in dims for j in range(2, n + 1) if n % j == 0}) + raise ValueError( + f"layout 'slices' at {k} stages a slice cuts each slice's chips into {k} strips of whole chips along a chip " + f"axis {k} divides (every TensorCore of a chip in one stage: Pathways refuses a stage over part of a chip's): " + f"{name}'s chips are {box}, no axis a multiple of {k} " + + (f"(k = {' or '.join(map(str, ks))} stages a slice cut it)" if ks else "(one stage a slice)") + ) + a = axes[-1] + width = dims[a] // k + return [[d for d, c in zip(devices, coords) if (c[a] - lo[a]) // width == j] for j in range(k)] + + +def stage_meshes(n_stages=2, fsdp=2, ep=2, devices=None, layout="ep_on_chip"): + """One ('fsdp','expert') mesh per stage over disjoint devices. + + 'ep_on_chip' puts each EP pair on the two TensorCores of one chip (the + ring-of-experts all-gather / reduce-scatter runs every layer and + microbatch), and FSDP across chips (its gather / scatter runs once a step). + It is the layout MaxText's pipeline-large-moe mesh gets on this VM. + 'fsdp_on_chip' is the transpose: FSDP over a chip's two cores, EP across + chips. Which is better is a question of bytes: at 128 experts a device + receives ~13 GB of FSDP gather + reduce-scatter a step against ~5 GB of + ring-of-experts exchange, and fsdp_on_chip is 1603 vs 1699 ms/step. + Stage s takes chips [s*k, (s+1)*k) in device-id order, so stage boundaries + pair device i with device i + fsdp*ep. + + 'snake' orders the devices along a boustrophedon path over the chip grid + (both cores of a chip, then the next chip along the row, rows alternating + direction). With one or two devices per stage that keeps every stage + boundary on a direct link: on a 2x2 grid, (0,0) -> (1,0) -> (1,1) -> (0,1). + + 'physical' takes the stages from the rows of mesh_utils' topology-aware + (n_stages, fsdp*ep) device mesh over the whole slice (MaxText's mesh with + allow_split_physical_axes): on a v6e-256 at 4 stages, four 16x4 strips of + the 16x16 torus, each 16 whole hosts -- the custom 4x64 mesh. Each stage's + devices keep that mesh's order, fsdp-major. + + 'physical_origin_last' is 'physical' with the strips rotated cyclically + until the strip holding chip (0,0,0) runs the LAST stage. libtpu never + offloads a collective of a proper sub-box holding that chip to SparseCore + (`sync_collective_stages`), so under 'physical' the first stage -- which + opens and closes every step -- runs its FSDP all-gathers and reduce-scatters + synchronously on the TensorCore. Rotated, the synchronous strip runs the + last stage, which waits ~100 ms for its first input and idles ~290 ms in the + drain (v6e-256, M=16). On a slice that wraps around across the strips (the + v6e-256 torus) every stage boundary stays between neighbouring strips; on + one that does not (v6e-16 to v6e-128) the rotation puts stages S-2 and S-1 + on the slice's two far ends. A device set without chip (0,0,0) is left in + 'physical' order. Under Pathways the rotation buys nothing: its compiler + offloads the origin strip's collectives too. 'snake' and both 'physical' + layouts place by chip coordinates, which every slice repeats, so they + refuse devices of several slices. + + 'slices' runs k stages on each slice (`slice_groups`), n_stages = k x the + slices: stages k s .. k s + k - 1 are slice s, in order, and fsdp x ep is a + k-th of its devices; a boundary between slices crosses DCN. At k = 1 stage + s is all of slice s, its mesh mesh_utils' topology-aware (fsdp, ep) mesh + over its own slice alone (MaxText's ICI mesh of one slice, with + allow_split_physical_axes). At k > 1 the slice's chips are cut into k + strips of whole chips along the last chip axis k divides (`chip_strips`; + a slice with none is refused), each strip's mesh mesh_utils' topology-aware + (fsdp, ep) mesh over its own devices, as a whole slice's is at k = 1: two + stages a slice on 2 x tpu7x-4x4x4 are each a 4x4x2 half of its slice (z), + four are 4x4x1 quarters, whole hosts each. Both TensorCores of a TPU7x + chip are in one stage -- Pathways refuses a stage over part of a chip's + ("a subslice must use all logical devices of each chip"), which the rows + of mesh_utils' (k, fsdp x ep) mesh over a TPU7x slice were, its k axis on + the cores. Devices without chip coordinates (CPU, with MPMD_FAKE_SLICES) + keep (process, id) order, cut into k contiguous strips. A whole slice runs + its collectives on SparseCore, and so does a strip away from the slice's + chip (0,0,0); the strip holding it -- the first of its slice -- keeps them + synchronous under McJAX (`sync_collective_stages`; Pathways offloads + them). Of the boundary transports `--transport relay` (the host relay: + every MPMD run of PP over DCN on 2 x v5p-128) and `--transport ppermute` + cross TPU slices; jax's native copy and jax.experimental.transfer do not + (`CROSS_SLICE_TRANSPORTS`). + """ + if layout not in LAYOUTS: + raise ValueError(f"unknown layout {layout!r}: expected one of {LAYOUTS}") + devices = list(devices if devices is not None else jax.devices()) + per = fsdp * ep + if len(devices) < n_stages * per: + raise ValueError(f"need {n_stages * per} devices, have {len(devices)}") + if layout in ("snake", "physical", "physical_origin_last"): + across = sorted({k for k in map(slice_index, devices) if k is not None}) + if len(across) > 1: + raise ValueError( + f"layout {layout!r} places stages by chip coordinates, which every slice repeats: these " + f"devices span slices {across} (one stage per slice is --layout slices)" + ) + if layout == "slices": + groups = slice_groups(devices) + k = n_stages // len(groups) if n_stages % len(groups) == 0 else 0 + if not k or any(len(g) != k * per for g in groups): + raise ValueError( + f"layout 'slices' runs k stages on each slice (n_stages a multiple of the slices): {n_stages} stages " + f"of fsdp x ep = {per} devices, but the devices are {len(groups)} slice(s) of {[len(g) for g in groups]}" + ) + from jax.experimental import mesh_utils + + meshes = [] + for i, g in enumerate(groups): + if all(getattr(d, "coords", None) is not None for d in g): + strips = [(f"slice {i}'s", g)] + if k > 1: + strips = [(f"slice {i}'s strip {j}'s", s) for j, s in enumerate(chip_strips(g, k, f"slice {i}"))] + for what, devs in strips: + try: + arr = mesh_utils.create_device_mesh((fsdp, ep), devs, allow_split_physical_axes=True) + except AssertionError as e: # its message lists every device of the slice, the box's dims last + why = str(e) if len(str(e)) < 300 else f"{str(e)[:120]} ... {str(e)[-120:]}" + raise ValueError( + f"layout 'slices': mesh_utils cannot build {what} {(fsdp, ep)} mesh, its " + f"chips not a solid box (MPMD_FAKE_SLICES on a TPU must cut whole boxes): {why}" + ) from e + meshes.append(Mesh(np.asarray(arr, dtype=object).reshape(fsdp, ep), ("fsdp", "expert"))) + else: + arr = np.array(g, dtype=object).reshape(k, per) + meshes += [Mesh(arr[j].reshape(fsdp, ep), ("fsdp", "expert")) for j in range(k)] + return meshes + if layout in ("physical", "physical_origin_last"): + from jax.experimental import mesh_utils + + if len(devices) != n_stages * per: + raise ValueError(f"layout {layout!r} cuts the whole slice: {n_stages} x {per} devices, have " f"{len(devices)}") + grid = mesh_utils.create_device_mesh((n_stages, per), devices, allow_split_physical_axes=True) + rows = [list(grid[s]) for s in range(n_stages)] + if layout == "physical_origin_last": + o = next((s for s, row in enumerate(rows) if any(map(on_origin_chip, row))), None) + if o is not None: + rows = rows[o + 1 :] + rows[: o + 1] + return [Mesh(np.array(row, dtype=object).reshape(fsdp, ep), ("fsdp", "expert")) for row in rows] + devices = sorted(devices, key=lambda d: d.id) + if layout == "snake": + + def snake(d): + x, y = tuple(getattr(d, "coords", (d.id, 0)))[:2] + return (y, x if y % 2 == 0 else -x, getattr(d, "core_on_chip", 0)) + + devices = sorted(devices, key=snake) + meshes = [] + for s in range(n_stages): + blk = devices[s * per : (s + 1) * per] + arr = np.array(blk, dtype=object).reshape(fsdp, ep) + if layout == "fsdp_on_chip": + arr = np.array(blk, dtype=object).reshape(ep, fsdp).T + meshes.append(Mesh(arr, ("fsdp", "expert"))) + return meshes + + +def typed_meshes(meshes, shard_mode): + """`meshes` with the axis types `shard_mode` (ds_ep.StageConfig.shard_mode) + runs on: Explicit under 'explicit' -- the gathered weights and gradient + accumulators carry reduced / unreduced types, which only Explicit axes + take -- else Auto. A mesh that has them already is returned as it is.""" + want = AxisType.Explicit if shard_mode == "explicit" else AxisType.Auto + return [ + m if all(t == want for t in m.axis_types) else Mesh(m.devices, m.axis_names, axis_types=(want,) * len(m.axis_names)) + for m in meshes + ] + + +def on_origin_chip(d): + """Is device d on its slice's chip (0,0,0)? By the chip coordinates where + the device has them (TPU, compile-only topology devices too), else device 0.""" + coords = getattr(d, "coords", None) + return all(x == 0 for x in coords) if coords is not None else d.id == 0 + + +def _is_tpu(d): + return getattr(d, "platform", "") == "tpu" or str(getattr(d, "device_kind", "")).startswith("TPU") + + +def allocates_at_issue(d): + """Does device d's client allocate a program's outputs when the program is issued, from the issuing thread -- a TPU + VM's own (McJAX), not the IFRT proxy's (Pathways)? There `Pipeline._do_I` paces the W buffers (pace_i).""" + return _is_tpu(d) and not pathways.is_proxy_device(d) + + +def pin_model_mismatch(devices): + """The kinds of the TPU devices among `devices` that no ds_ep.PinModel, which + --prefetch-pin auto plans with, was calibrated on (ds_ep.PIN_MODELS) -> a + sorted list: none on v5p or v6e, nor off TPU.""" + return sorted({str(d.device_kind) for d in devices if _is_tpu(d)} - set(ds_ep.PIN_MODELS)) + + +def sync_collective_stages(meshes): + """The stages whose all-gathers / reduce-scatters libtpu runs synchronously + on the TensorCore -> frozenset. + + It offloads them to SparseCore, where they run async next to the program's + compute, for a box of the slice away from its origin and for the whole + slice, but never for a proper subset holding chip (0,0,0) ("Skipping + offloading collectives to SparseCore because the device assignment does not + use all devices"): AOT on the v6e:16x16 topology and on the local v6e-4 + (libtpu 0.0.46) compiled the full-row-wide origin strips of the 'physical' + layouts to synchronous all-gathers; TPU7x-8 behaves the same. (On the + v6e:16x16 topology an origin box narrower than a full 16-chip row did not + compile at all, 2026-10.) On the v6e-256 runs (PP=4 x + FSDP=64, 'physical') that cost the first stage ~70 ms of TensorCore time per + step. A stage that is a whole slice -- each stage of `--layout slices` at + one stage a slice, every one of which holds its slice's chip (0,0,0) -- is + offloaded (at k stages a slice, the strip holding it is not): on a + compile-only 2 x v5p-128 topology (libtpu 0.0.46, the v5p recipe's flags) + slice 0's all-gathers compiled to SparseCore, those of the half of it + holding (0,0,0) to synchronous ones. (There the other half compiled + synchronously too, where on one slice alone it is offloaded; never run, so + not modelled here.) A rule: Pipeline plans by libtpu's own answer where + a stage's processes probed it (`offload_answers`), by this where none did + -- ahead of time, off TPU -- or a probe failed. A slice's devices are + counted, by `slice_index`, among all the devices of the meshes' client -- + the job's (jax.devices()), or a compile-only topology's (ds_ep_aot) -- so + a stage is a whole slice only if it holds every device the slice has, + whatever the other stages hold; device objects of neither (a test's) count + among the meshes' own. A stage of one device has no FSDP collective to + offload. Decided from the devices alone (`on_origin_chip`), so every + process of a multi-controller run agrees; a single stage over part of a + slice, and other device sets libtpu does not offload (not a solid box), + are not detected. + + Under Pathways (the devices the IFRT proxy's: `pathways.is_proxy_device`) + none: the Pathways server's compiler offloads them on chip (0,0,0)'s sub- + meshes too -- and so Pipeline plans for a Pathways run ahead of time + (`proxy`: ds_ep_aot --pathways). On local docker Pathways (tpu7x-8, + images 20261117 and 20261124) the probe answered offloaded for all-gathers + over fsdp, expert and both on the 2-chip half holding chip (0,0,0) -- + which McJAX's libtpu 0.0.50.1 keeps synchronous on the same chips -- and + the trace showed them on SparseCore. The probe still decides wherever it + is asked. + """ + devs = [d for m in meshes for d in m.devices.flat] + if len(meshes) < 2 or not _is_tpu(devs[0]) or pathways.is_proxy_device(devs[0]): + return frozenset() + client = getattr(devs[0], "client", None) + every = set(client.devices() if client is not None else jax.devices()) + pool = every if set(devs) <= every else set(devs) + size = collections.Counter(map(slice_index, pool)) + + def whole_slice(m): + ks = {slice_index(d) for d in m.devices.flat} + return len(ks) == 1 and m.devices.size == size[ks.pop()] + + return frozenset( + s + for s, m in enumerate(meshes) + if m.devices.size > 1 and any(map(on_origin_chip, m.devices.flat)) and not whole_slice(m) + ) + + +def rule_offloads(meshes, s, axes, sync=None): + """The device rule's answer to `offload_answers`' question: a TPU stage + offloads an all-gather over `axes` (a mesh axis name or a tuple of them) + unless `sync_collective_stages` lists it, and if one of the axes is wider + than a device (`sync`: that set, if at hand).""" + names = (axes,) if isinstance(axes, str) else tuple(axes) + sync = sync_collective_stages(meshes) if sync is None else sync + return _is_tpu(meshes[s].devices.flat[0]) and s not in sync and any(meshes[s].shape[a] > 1 for a in names) + + +def offload_answers(meshes, asks, kv=None, key="mpmd/offload", pid=None, timeout_s=900): + """libtpu's answer to each ask (stage, axes) -- does it offload an all-gather + over `axes` on that stage's mesh to SparseCore, where it runs async + (`ds_ep.sparsecore_offload_available`: one probe compile)? -> {(stage, + axes): (answer, why)}: why None for libtpu's answer, else why it is the + device rule's (`rule_offloads`) instead. + + The processes of a stage probe its asks (every one of them, as they compile + its programs). Without `kv`, every stage's are this process's (one process, + or ahead of time). With it -- multi-controller JAX: the coordination + service's key-value store -- each stage's lowest process publishes its + answers under `key` and every process plans from those, its own stage's + too, so that all of them build one plan from libtpu's answers rather than + from the device rule, which a new topology or libtpu can break (a half of a + compile-only v5p-128 slice broke it once). A probe that fails answers by + the rule, saying so: an advisory compile must not stop one stage's + processes while the others go on and wait for them in the step.""" + sync = sync_collective_stages(meshes) + + def probe(s, axes): + try: + return bool(ds_ep.sparsecore_offload_available(meshes[s], axes)), None + except Exception as e: # what it is, in a line + why = f'its libtpu probe failed ({type(e).__name__}: {" ".join(str(e).split())[:160]})' + return rule_offloads(meshes, s, axes, sync), why + + if kv is None: # one controller (or ahead of time): every stage's asks are this process's + return {(s, axes): probe(s, axes) for s, axes in asks} + # multi-controller JAX: each stage's processes probe its asks, its lowest one publishes the answers + pid = jax.process_index() if pid is None else pid + procs = [{d.process_index for d in m.devices.flat} for m in meshes] + name = lambda s, axes: f'{key}/{s}/{axes if isinstance(axes, str) else ",".join(axes)}' + out = {} + for s, axes in asks: + if pid not in procs[s]: + continue + out[(s, axes)] = probe(s, axes) + if pid == min(procs[s]): + got, why = out[(s, axes)] + kv.key_value_set(name(s, axes), f'{int(got)} {why or ""}'.rstrip()) + for s, axes in asks: + if pid != min(procs[s]): + mine, v = out.get((s, axes)), kv.blocking_key_value_get(name(s, axes), timeout_s * 1000) + out[(s, axes)] = (v[0] == "1", v[2:] or None) + if mine is not None and mine != out[(s, axes)]: + warnings.warn( + f"stage {s}: this process answers {mine} to the libtpu probe over {axes}, its lead process " + f"{min(procs[s])} {out[(s, axes)]}: every process plans by the lead's", + RuntimeWarning, + ) + return out + + +def offload_check(meshes, s, got, why=None): + """Stage s's answer from `offload_answers` -- does libtpu offload an + all-gather over the whole stage to SparseCore (`got`), and if it is the + rule's, why -- against the device rule (`sync_collective_stages`) -> a log + line, a warning where they disagree or the probe failed. + + main logs it for each stage whose answer was asked -- its FSDP + collectives are lax ones, or, under batch split on Lineage's layers, its + Regions trace Lineage's SparseCore regions by the answer -- on every + layout: every process plans by the answer, so a rule gone wrong costs + nothing, but says the rule needs mending.""" + rule = s not in sync_collective_stages(meshes) + said = lambda x: "offloaded to SparseCore" if x else "synchronous" + if why is not None: + return ( + f"warning: stage {s}: {why}: every process plans its collectives {said(got)}, by the device rule " + "(sync_collective_stages)" + ) + if got == rule: + return f"stage {s}: libtpu probe: its collectives {said(got)}, as the device rule (sync_collective_stages) " "has it" + return ( + f"warning: stage {s}: libtpu probe: its collectives {said(got)}, where the device rule " + f"(sync_collective_stages) has them {said(rule)}: every process plans by the probe" + ) + + +def shared_stage_hosts(meshes): + """[(a, b, processes)] for every two stages whose devices share processes. + Under multi-controller JAX every stage needs hosts of its own; compiling + ahead of time for a topology checks the same on its devices.""" + owners = [frozenset(d.process_index for d in m.devices.flat) for m in meshes] + return [(b, a, sorted(owners[a] & owners[b])) for a in range(len(meshes)) for b in range(a) if owners[a] & owners[b]] + + +def split_chip_stages(meshes): + """[(stage, (slice, coords), held, of)] for each chip a stage holds part of the devices of -- `held` of its `of` + TensorCores -- stage by stage, each stage's chips in mesh order: what Pathways refuses ("Devices use 1 of the 2 + logical devices on chip 0,0,0; a subslice must use all logical devices of each chip"), as it refused --layout + slices at two stages a TPU7x slice before `chip_strips` (each stage one core of every chip). A chip's devices are + counted among all of the meshes' client's, as `sync_collective_stages` counts a slice's; devices without chip + coordinates (CPU) have none to split.""" + devs = [d for m in meshes for d in m.devices.flat] + if not devs or any(getattr(d, "coords", None) is None for d in devs): + return [] + client = getattr(devs[0], "client", None) + every = set(client.devices() if client is not None else jax.devices()) + pool = every if set(devs) <= every else set(devs) + + def chip(d): + return slice_index(d), tuple(d.coords) + + size = collections.Counter(chip(d) for d in pool if getattr(d, "coords", None) is not None) + out = [] + for s, m in enumerate(meshes): + held = collections.Counter(map(chip, m.devices.flat)) + out += [(s, c, n, size[c]) for c, n in held.items() if n < size[c]] + return out + + +def describe_mesh(mesh): + rows = [] + for d in mesh.devices.flat: + rows.append(f'{d.id}@{getattr(d, "coords", "?")}/c{getattr(d, "core_on_chip", "?")}') + return f"{dict(mesh.shape)} " + " ".join(rows) + + +# ----------------------------------------------------------------- schedule +# The named schedules (--schedule). build_schedule makes ORDER_SCHEDULES from +# the placement alone; Pipeline makes the rest itself: stash sizes its stash +# sets by building their programs, and interleaved (Megatron's per-stage +# order) hands out stash modes and pairs its steady state where asked. +ORDER_SCHEDULES = ("gpipe", "1f1b", "search", "timed", "breadth", "zbh1", "zbh2") +# The zero-bubble schedules (Qi et al., "Zero Bubble Pipeline Parallelism") on one chunk a stage, each middle chunk's +# backward split into I (the input gradient, with the recompute it needs) and W (the weight gradients, run later): +# ds_ep.ChunkPrograms.build_split. ZB-H1 holds 1F1B's residual sets and ZB-H2 about twice them, each plus up to +# zb_wbuf_cap pending W buffers a stage -- memory 1F1B does not hold: a W buffer is a microbatch's crossing set and +# the arguments its W reads, about 3.6 GiB a device per DeepSeek-V3 MoE layer at 4096 tokens a device (7.25 GiB for +# a chunk of two; the summary's 'split backward' line gives a run's). Each the fastest in simulation of its +# candidates (sched.zb_schedule) under the program costs. Chunk 0's backward stays whole (it has no input gradient +# to split off), and so does the fused last chunk, unless zb_split_last (--zb-split-last on) splits it too: its F +# runs the forward, head, loss and input gradient (AI), a W of its own its layers' weight gradients, later +# (ds_ep.ChunkPrograms.build_split_last). At 2 stages without it nothing splits, and zbh1 is 1F1B's order. +ZB_SCHEDULES = ("zbh1", "zbh2") +SCHEDULES = ORDER_SCHEDULES + ("stash", "interleaved") +# The schedule a Pipeline runs when given none (schedule None, no --schedule), +# on either placement: breadth, MaxText's order. A stage runs a chunk's M +# microbatches back to back, so a microbatch's crossings overlap the other +# microbatches' forwards, and the stages wait on the boundary only at the fill +# and the drain (2 x v5p-128, relay over DCN: 5521 ms a step, not gpipe's +# 8799). `search`, the default before, picks the same order on circular +# placement at two or more chunks a stage, or at a few small M (3 to 6) one +# with the same bubble and residual sets. At one chunk a stage it picks 1F1B, +# which keeps S residual sets rather than M but waits on the boundary: breadth +# is 8% faster at 2 stages and M=8 with 55 ms crossings. On V placement +# search's bubble is shorter (16% against breadth's 27% at 4 stages and M=8, +# F=1, B=2); --schedule search buys it back, under the step scope. +DEFAULT_SCHEDULE = "breadth" + + +def default_fsdp_scope(schedule, overlap): + """The FSDP scope a Pipeline runs when given none (fsdp_scope None, no + --fsdp-scope): 'repeat' under breadth, as MaxText's circular pipeline does + with pipeline_fsdp_ag_per_repeat (a chunk's weights gathered for each + visit, about two chunks' weights held at a time), where the fusion plan + that repeat needs is on; 'step' otherwise.""" + return "repeat" if schedule == "breadth" and overlap else "step" + + +# build_schedule's per-program costs (ms) for 'timed' when given none: the +# TPU7x-8 calibration of the pipeline's first DeepSeek-V3 benchmark configuration (2026-09), never +# re-measured (not at 128 experts, not on other hardware). Only their ratios +# matter. F0 / B0 are chunk 0's forward / backward (they carry the +# embedding), A the last chunk's fused forward + backward, xfer one +# stage-boundary copy. Pipeline passes its own table (`default_costs`: the +# v6e medians on a v6e, these elsewhere; `costs` / --costs override it). +TIMED_COSTS = sched.TPU7X_COSTS + + +def normalize_schedule(schedule): + """A custom schedule -- any sequence of (chunk, kind, microbatch) triples, + e.g. a list of lists from JSON -> a list of (int, str, int) tuples.""" + out = [] + for i, a in enumerate(schedule): + try: + c, k, m = a + except (TypeError, ValueError): + raise ValueError(f"schedule[{i}] = {a!r}: expected a (chunk, kind, microbatch) triple") from None + if not all(isinstance(v, numbers.Integral) and not isinstance(v, bool) for v in (c, m)): + raise ValueError(f"schedule[{i}] = {a!r}: chunk and microbatch must be ints") + if k not in sched.KINDS: + raise ValueError(f"schedule[{i}] = {a!r}: kind must be 'F', 'B', 'I' or 'W'") + out.append((int(c), str(k), int(m))) + return out + + +def validate_schedule(order, n_chunks, n_micro, place=None, *, fuse=frozenset()): + """Raise ValueError unless `order` runs F(c, m) and B(c, m) exactly once for + every chunk c and microbatch m, each after what it consumes: F(c, m) after + F(c-1, m); B(c, m) after F(c, m) and B(c+1, m). The last chunk's F runs its + fused forward + backward, so its B is a no-op -- but it must still appear, + after that F. + + Then `sched.validate`, the rules the step loop relies on (a + `sched.ScheduleError`, also a ValueError), so the two never disagree about + an F / B order: every chunk's forwards and gradient writes in microbatch + order, the last chunk's no-op B right after its F in its stage's sequence, + and the F&B pairs `fuse` names (which need `place`). Without `place` each + chunk counts as its own stage: the per-stage rule is then checked per chunk + only, which every order legal on the real placement also passes. + + An order with a split backward -- I(c, m) and then W(c, m) in place of a + middle chunk's B(c, m), the zero-bubble schedules' -- is `sched.validate`'s + alone, whose rules cover I and W: an I after F(c, m) and after the B or I + of (c + 1, m), its W after it, none for chunk 0 or the fused last chunk, + and every chunk's W's (its gradient writes) in microbatch order. + """ + C, M = n_chunks, n_micro + if any(k in ("I", "W") for _, k, _ in order): + if fuse and place is None: + raise ValueError("F&B pairs (fuse) run two ops of one stage: validate_schedule needs place") + sched.validate(order, list(range(C)) if place is None else place, M, fuse=fuse) + return + seen = set() + for i, (c, k, m) in enumerate(order): + at = f"schedule[{i}] = ({c}, {k!r}, {m})" + if k not in ("F", "B"): + raise ValueError(f"{at}: kind must be 'F', 'B', 'I' or 'W'") + if not (0 <= c < C and 0 <= m < M): + raise ValueError(f"{at}: out of range (chunks 0..{C - 1}, microbatches 0..{M - 1})") + if (c, k, m) in seen: + raise ValueError(f"{at}: {k}({c},{m}) appears twice") + if k == "F" and c > 0 and (c - 1, "F", m) not in seen: + raise ValueError(f"{at}: F({c},{m}) before F({c - 1},{m}), whose activation it consumes") + if k == "B" and (c, "F", m) not in seen: + raise ValueError(f"{at}: B({c},{m}) before F({c},{m})") + if k == "B" and c < C - 1 and (c + 1, "B", m) not in seen: + raise ValueError(f"{at}: B({c},{m}) before B({c + 1},{m}), whose input gradient it consumes") + seen.add((c, k, m)) + missing = [f"{k}({c},{m})" for c in range(C) for k in "FB" for m in range(M) if (c, k, m) not in seen] + if missing: + raise ValueError( + f"schedule lacks {len(missing)} of its {2 * C * M} actions: " + + ", ".join(missing[:6]) + + (" ..." if len(missing) > 6 else "") + ) + if fuse and place is None: + raise ValueError("F&B pairs (fuse) run two ops of one stage: validate_schedule needs place") + sched.validate(order, list(range(C)) if place is None else place, M, fuse=fuse) + + +def build_schedule(schedule, n_chunks, n_micro, place, costs=None, *, zb_wbuf_cap=1, zb_split_last=False): + """-> (order, name): a validated list of (chunk, kind, microbatch). + + `schedule` is one of ORDER_SCHEDULES or a custom sequence of triples (the + other SCHEDULES are Pipeline's). `costs`: the program costs of 'timed' + and of the zero-bubble schedules (any `sched.cost_table` key; TIMED_COSTS + fills in the rest, and sched.zb_costs a split chunk's I and W from its B + where the table has neither). `zb_wbuf_cap`: zbh1 / zbh2's pending W + buffers a stage (None or 0: no cap); `zb_split_last`: theirs split the + fused last chunk too (a W of its own a microbatch: sched.splits_last). + zbh1 / zbh2 run on one chunk a stage: any other placement is a ValueError. + """ + C = n_chunks + if isinstance(schedule, (list, tuple)): + order, name = normalize_schedule(schedule), "custom" + elif schedule == "gpipe": + order, name = sched.gpipe(C, n_micro, place), "gpipe" + elif schedule == "1f1b": + order, name = sched.one_f_one_b(C, n_micro, place), "1f1b" + elif schedule == "breadth": + order, name = sched.breadth_first(C, n_micro, place), "breadth" + elif schedule == "search": + res = sched.search(C, n_micro, place) + order, name = res[0], f"search {res[1]}" + elif schedule == "timed": + # Event-driven search with per-program costs. The last chunk is one + # fused program. + k = dict(TIMED_COSTS) + k.update(costs or {}) + res = sched.timed_search(C, n_micro, place, sched.cost_table(k, C), k["xfer"], fuse_last=True) + order, name = res[0], f"timed {res[1]} sim={res[2]:.1f}" + elif schedule in ZB_SCHEDULES: + if list(place) != list(range(C)): + raise ValueError( + f"schedule {schedule!r}: ZB-H1 / ZB-H2 run one chunk a stage (chunks_per_stage 1, --vv 1), not placement " + f"{list(place)}; a custom order of I and W runs on any" + ) + cap = None if zb_wbuf_cap in (None, 0) else zb_wbuf_cap + k = sched.zb_costs({**TIMED_COSTS, **(costs or {})}, C, last=zb_split_last) + order, tag, mk = sched.zb_schedule( + C, + n_micro, + sched.cost_table(k, C), + k["xfer"], + mem="h1" if schedule == "zbh1" else "h2", + wbuf_cap=cap, + split_last=zb_split_last, + ) + # the W-buffer cap where a chunk splits; at 2 stages none does (chunk 0 and the fused last chunk keep their + # backwards whole), and no W buffer is held -- but the last chunk's, split too + if all(k != "W" for _, k, _ in order): + wb = " (no split chunk)" + else: + wb = (" split-last" if zb_split_last else "") + ("" if cap is None else f" wbuf<={cap}") + name = f"{schedule} {' '.join(map(str, tag))}{wb} sim={mk:.1f}" + # Every candidate splits (sched.zb_schedule): never slower than 1F1B where a split chunk's I + W is its B (and a + # split last chunk's AI + W its A), as zb_costs prices them unless measured. Measured, they can be more (TPU7x, + # DeepSeek-V3 widths: 3.6-6.3%), an overhead each microbatch that at enough microbatches outgrows the bubble the + # W's fill -- so say so where the costs say it. + f1b = sched.timed_simulate( + sched.one_f_one_b(C, n_micro, place), place, sched.cost_table(k, C), k["xfer"], fuse_last=True + )[0] + if mk > f1b * (1 + 1e-6): + warnings.warn( + f"schedule {schedule!r} ({name}): its microbatch loop simulates slower than 1F1B's ({mk:.1f} against " + f"{f1b:.1f}) under these program costs, which price a split chunk's I + W above its B (or the split last " + f"chunk's AI + W above its A) by more than the bubble its W's fill at {n_micro} microbatches repays: " + "compare a --schedule 1f1b run", + RuntimeWarning, + ) + elif schedule in SCHEDULES: + raise ValueError( + f"schedule {schedule!r} is built by Pipeline, not build_schedule: Pipeline sizes " + "its stash sets (stash) or merges its per-stage streams (interleaved)" + ) + else: + raise ValueError( + f"unknown schedule {schedule!r}: expected one of {SCHEDULES} or a sequence of " + "(chunk, kind, microbatch) triples" + ) + order = normalize_schedule(order) + validate_schedule(order, C, n_micro, place) + return order, name + + +def zb_refusals(what, scfg, fsdp_scope, *, order=None, modes=None, fuse=()): + """Raise ValueError, naming every problem at once, where the split backward of `what` -- zbh1 / zbh2, or a custom + `order` with I and W ops (with its `modes` and `fuse`) -- cannot run: batch split on Lineage's layers, one custom + VJP of Lineage's whole region, with no input-gradient half to cut (ds_ep.ChunkPrograms.build_split); fsdp_scope + 'repeat', which gathers a chunk's weights for each visit of its stage, where a chunk's W's, which read none, would + make visits of their own; a stash mode on a split chunk, whose backward the split does not cut (the recompute one + only); and an F&B pair whose backward is an I, or whose forward is a split last chunk's AI (no program pairs + either).""" + bad = [] + if scfg.lineage_split: + bad.append( + "batch_split on Lineage's layers (batch_split_impl 'lineage'): one custom VJP of Lineage's whole region, " + "with no input-gradient half to cut" + ) + if fsdp_scope == "repeat": + bad.append( + "fsdp_scope 'repeat' (a chunk's weights gathered for each visit): a chunk's W's, which read no weights, would " + "make visits of their own, each one gathered for nothing (fsdp_scope 'step')" + ) + if order is not None: + split = {c for c, k, _ in order if k in ("I", "W")} + held = sorted(tuple(key) for key, v in (modes or {}).items() if v != "r" and tuple(key)[0] in split) + if held: + bad.append( + f"stash modes on split chunks {held[:4]}{' ...' if len(held) > 4 else ''}: the split cuts the recompute " + "backward, not a stash one" + ) + pairs = sorted(j for j in fuse if order[j + 1][1] == "I") + if pairs: + names = ", ".join("&".join(f"{c}{k}{m}" for c, k, m in order[j : j + 2]) for j in pairs[:3]) + bad.append(f"F&B pairs of a forward and an I ({names}{', ...' if len(pairs) > 3 else ''}): none is built") + C = 1 + max(c for c, _, _ in order) + if sched.splits_last(order, C) and (ai := sorted(j for j in fuse if order[j][0] == C - 1)): + names = ", ".join("&".join(f"{c}{k}{m}" for c, k, m in order[j : j + 2]) for j in ai[:3]) + bad.append( + f"F&B pairs of the split last chunk's forward (AI: its forward, head, loss and input gradient) and a " + f"backward ({names}{', ...' if len(ai) > 3 else ''}): none is built" + ) + if bad: + raise ValueError(f"{what}: the split backward (I / W) cannot run this: " + "; ".join(bad)) + + +# ----------------------------------------------------------------- pipeline +@dataclasses.dataclass(frozen=True) +class Op: + """One entry of the order as the step loop runs it: the program to call + (`desc`, a tuple of `ds_ep.pdesc` parts, built by `progs[c].program`; None + for the fused last chunk's no-op backward) and what the loop does around + it. `acc`: accumulate into the chunk's gradient buffer (every gacc writer + but the chunk's first) -- on an I, the split backward's input-gradient + half, the variant of the W it feeds (one I program feeds either, unless + in-place dW cut another: ds_ep.Split.i_acc); on a split last chunk's F + (AI) and W, into the part each writes, every one but its first; `stash`: + the (c, m) mode's policy, None for remat; `self_pf`, `pf`, `rs`, + `rs_self`: the FSDP collectives the overlap plan folds into this program + (`pf` rides in a forward; under + fsdp_scope 'repeat' also in a backward or the fused last chunk; `rs` and + `rs_self` in a gradient writer, a B or a W); `pin`, its prefetch pins + (`Pipeline._plan_pins`). `pair`, on the first op of an F&B pair (j in + `Pipeline.fuse`): the descriptor of the ONE program both run -- this op's + part, then the backward's with `peer=` its chunk's programs; the second op + keeps its own `desc`, which the loop does not call.""" + + j: int + c: int + kind: str + m: int + s: int + desc: tuple = None + acc: bool = False + stash: str = None + self_pf: bool = False + pf: tuple = None # (chunk, leaf ids) gathered here (Pipeline.pf_n[j]: in how many ops in all) + rs: tuple = None # (chunk, leaf ids) reduce-scattered here + rs_self: int = None # this chunk's own reduce-scatter, summing that many partial sumsqs + pair: tuple = None # the F&B pair's composed descriptor (on its F) + pin: tuple = None # ((point, layer, chunk, leaf id), ...): the gathers this forward pins + + +class _Box(dict): + """The act / cotangents storage of a step: what a boundary copy files (`Pipeline._file`), popped by the op that + consumes it.""" + + +class _RelayBox(_Box): + """_Box under multi-controller JAX: its `pop` resolves a relay receive (transfer.resolve), so a boundary's bytes are + waited for by the op that consumes them, not by the copy that filed them.""" + + def pop(self, k): + return transfer.resolve(super().pop(k)) + + +class _Step: + """What one step's microbatch loop carries from one program to the next.""" + + def __init__(self, p, params, wc, batch): + S, C = p.S, p.C + self.toks, self.tgts = batch[:2] + self.mtp_toks = batch[2] if p.mtp else None + self.params, self.wc = params, wc + self.res, self.stash = {}, {} + # A split backward's W buffers, from its I to its W: {(c, m): (the crossing set, the I arguments W reads)}. + self.wbuf = {} + # Under Pipeline.pace_i, each split chunk's latest W buffer this step, the crossing set its next I (AI) waits on. + self.last_i = {} + # A split last chunk's accumulator, until its last W: [its F's (AI's) part, its W's part], each a tuple of leaves. + self.gacc_parts = {} + # act / cotangents cross stages: under multi-controller JAX a relay receive filed there is resolved when it is + # popped. + box = _RelayBox if p.multi else _Box + self.act, self.cotangents = box(), box() + self.gacc = [None] * C + self.lacc = None + # A chunk's gathered leaves as its prefetch hosts deliver them, and how + # many hosts that gather still waits for (`Pipeline._install`); one + # gather of a chunk at a time, so both are keyed by chunk. + self.wparts, self.pending = {}, {} + self.gparts, self.gpending = {}, dict(p.rs_groups) # reduce-scatter groups still to come + self.gacc_leaves = {} + self.grads = [[None] * len(p.stage_chunks[s]) for s in range(S)] + self.sq = [[] for _ in range(S)] + self.stage_tot = [None] * S + + +class Pipeline: + + def __init__( + self, + scfg: ds_ep.StageConfig, + n_stages=2, + chunks_per_stage=4, + n_micro=8, + global_batch=32, + seq=4096, + schedule=None, + meshes=None, + layout="ep_on_chip", + overlap=True, + pf_split=4, + rs_split=4, + rs_self=True, + costs=None, + self_prefetch=True, + placement="circular", + stash="none", + stash_budget_gib=4.5, + stash_caps=None, + init_by_chunk=False, + modes=None, + rs_reserve=None, + pair_stages=None, + pair_gain=None, + fuse=None, + stage_ep_collectives=None, + aot=False, + transport="native", + layer_split=None, + cp=None, + fsdp_scope=None, + prefetch_pin="off", + offload_residuals=False, + norm_reduce="hops", + interleave_group=None, + stage_lineage_sparsecore=None, + direct_experts=False, + zb_wbuf_cap=1, + zb_split_last=False, + proxy=None, + ): + """`placement`: 'circular' or 'v' (chunks_per_stage 2). `schedule`: one + of SCHEDULES, a custom order, or None for DEFAULT_SCHEDULE (breadth). + `stash`: the + policy `--schedule stash` gives the (chunk, microbatch)s it stashes, as + many at once as `stash_budget_gib` of live stash sets per stage allows + (see schedule.py's memory note: the stash backwards' extra temporaries + come on top, and the 4.5 GiB default is a placeholder until a TPU + `--mem-report` sweep sets it), optionally under `stash_caps` + live sets per chunk -- or, under `interleaved`, the stash modes of its + fixed order under the same budget and caps (`sched.stash_modes`; there a + chunk left off `stash_caps` is uncapped, where `stash` never stashes it). `modes` ({(c, m): policy}) and `fuse` (the + order indices j whose op runs with order[j+1] as one F&B program) ride + along with a custom order (`schedule` as a list). `init_by_chunk`: + `init` seeds each chunk's weights from its index alone, so they do not + depend on the placement. `rs_reserve`: let the reduce-scatter plan keep + each stage's last gradient write free for rs_self (`_plan_overlap`); + None = under V and for `interleaved` (no earlier plan to keep), so circular + breadth / search / timed / stash keep the plans they have always made. + `pair_stages`: the stages `interleaved` pairs on -- 'all' every stage, () + none, else the stages listed; None, its default, none: its order stays + Megatron's own unless its pairs are asked for + (`sched.megatron_interleaved`). No other schedule takes any (a custom + order names its pairs in `fuse`); + `pair_gain`: what a pair saves over its two programs run back to back + (ms; None: the cost table's 'pair_gain', else 0), which the simulation + prices. `stage_ep_collectives`: one of + 'xla' / 'ppermute' per stage, overriding scfg.ep_collectives + (`--ep-collectives ppermute,xla`). `stage_lineage_sparsecore`: under + batch split on Lineage's layers, whether each stage runs Lineage's + SparseCore regions (a bool per stage), overriding libtpu's answer (ds_ep_aot + hands the pipeline over the real slices the answers of the one it compiles + on the first slice's devices). `rs_self`: which stages may fold a + chunk's reduce-scatter into its own last backward -- 'all' (True), 'none' + (False) or 'first': only the stage holding chunk 0, whose last backward + ends the step; elsewhere a program's outputs leave only when it ends, so + the folded reduce-scatter holds the cotangent the stage upstream waits + for, and a standalone reduce after it does not (`_plan_overlap`). Under + 'first' the other stages' last backward hosts no reduce-scatter at all, + another chunk's neither: those groups move to earlier backwards or to the + standalone reduce. + A stage whose collectives run synchronously (`sync_collective_stages`), + other than chunk 0's, reduce-scatters every chunk in one program after + its last backward, where it idles in the drain, not in its backwards. + `fsdp_scope`: how long a chunk's gathered (compute) weights live. + 'step': from their gather to the end of the microbatch loop, every chunk + of the stage at once by the backward phase. 'repeat': one visit -- a run + of the chunk's ops in its stage's sequence (`_plan_repeat`) -- at a time: + gathered inside the stage's previous visit, released after the visit's + last op, gathered again for the next one, so a stage holds about two + chunks' weights instead of all of them, for (V-1)/V more of a step's + weight all-gather under a breadth-first order (MaxText's circular + pipeline with `pipeline_fsdp_ag_per_repeat`). It needs the fusion plan + (`overlap`), no F&B pairs, and an order that visits each chunk at most + twice a step (`schedule='breadth'`). None: `default_fsdp_scope`, + 'repeat' under breadth with the fusion plan, else 'step'. + `prefetch_pin`: 'off', 'auto' or a SPEC (ds_ep.parse_prefetch_pin): which + gathers a gathering forward -- a prefetch host, the self-prefetch -- ties + to which points of its layers (`_plan_pins`). Under batch split on + Lineage's layers (scfg.lineage_split) there are no stash modes, no stash + scheduler and no pins: refused here, before anything is built. + + The split backward: the zero-bubble schedules (ZB_SCHEDULES, at + chunks_per_stage 1), or a custom order of I and W ops at any, run each + middle chunk's backward the order names so as I -- the input gradient, + which the stage upstream waits on -- and later W, the weight gradients + (ds_ep.ChunkPrograms.build_split; `split_chunks`): the W's are the + chunk's gradient writers, in microbatch order, so the gradients are the + B's bit for bit wherever XLA compiles the halves' operations as it does + the fused backward's. `zb_wbuf_cap`: zbh1 / zbh2's pending W buffers a + stage (None or 0: no cap), each one microbatch's crossing set and the + arguments its W reads (`wbuf_bytes`). `zb_split_last`: zbh1 / zbh2 split + the fused last chunk too (a custom order does where it gives the last + chunk W's): its F runs the forward, the head, the loss and the input + gradient (AI) and leaves a W buffer, its W its layers' weight gradients + (ds_ep.ChunkPrograms.build_split_last) -- its accumulator two parts, AI's + leaves and W's, merged after its last W for the stage's reduce. Not under + batch split on Lineage's layers, fsdp_scope 'repeat', a stash mode on a + split chunk or an F&B pair holding an I or a split last chunk's AI + (`zb_refusals`), nor zb_split_last on a last chunk without layers: refused + before anything is built. + + Under multi-controller JAX (`jax.distributed`, one process per host) a + process runs the stages that hold its devices (`local`): it compiles and + dispatches only their programs, and walks the whole order so that it + takes part in every cross-stage copy, in order (`_send`). `multi` says + so (pathways.multi_controller(), the one rule: jax.process_count() > 1): + every piece of that machinery runs under `multi` only. In one + controller -- a Pathways client, which drives every device, or one host's + own process -- every stage is local and none of it runs. `aot`: the + meshes are of a topology this process does not own -- every program can + be lowered and compiled (`precompile`), nothing is placed or run. + `proxy`: plan as one Pathways client driving the stages (None: whether + the meshes' devices are the IFRT proxy's, `on_pathways`) -- no stage's + collectives synchronous by the device rule (`sync_collective_stages`' + answer for Pathways' devices: its servers' compiler offloads them on chip + (0,0,0)'s sub-meshes too); ahead of time, where libtpu's probe would + answer as a TPU VM's own (a compile-only topology's), every ask answered + by that rule, unprobed (ds_ep_aot --pathways). + `transport`: how a boundary copy moves -- 'native', jax's own (a batched + device-to-device copy in one process, its cross-host copy across + processes: transfer.Channel / CrossProcessChannel); 'ppermute', a + collective-permute program over the two stages' devices + (transfer.PermuteChannel), which the two stages run together; 'xfer', + jax.experimental.transfer pulls between host pairs (transfer.XferChannel, + asynchronous, over DCN; one process per host only); or 'relay', a host + relay (transfer.RelayChannel: D2H, TCP between the hosts, H2D, in + threads of the context `relay_ctx`; asynchronous, one process per host + only), whose receive is a future the consuming op resolves (`_RelayBox`, + `step`); `relay_ctx.timing()` says where its time went and + `close()` shuts it down. + + A custom order is normalized to (int, 'F' | 'B' | 'I' | 'W', int) tuples + and checked (`validate_schedule`) before anything is built; every order, + named or custom, then passes `sched.validate` before the plan is made.""" + + def replace(c, **changes): + # dataclasses.replace re-runs StageConfig.__post_init__: do not repeat + # the padded-tiling warning `scfg` already gave. + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message=ds_ep.TILING_WARNING) + return dataclasses.replace(c, **changes) + + if cp is not None and cp != scfg.cp: # given: it overrides scfg.cp (build sets scfg.cp, not this) + scfg = replace(scfg, cp=cp) + cfg = scfg.model + self.scfg, self.S, self.V, self.M = scfg, n_stages, chunks_per_stage, n_micro + self.overlap, self.pf_split, self.rs_split = overlap, pf_split, rs_split + rs_self = {True: "all", False: "none"}.get(rs_self, rs_self) + if rs_self not in ("all", "first", "none"): + raise ValueError(f"rs_self must be 'all', 'first' or 'none' (or a bool), got {rs_self!r}") + self.rs_self_enabled, self.rs_self_policy = rs_self != "none", rs_self + if fsdp_scope not in (None, "step", "repeat"): + raise ValueError(f"fsdp_scope must be 'step' or 'repeat', got {fsdp_scope!r}") + if fsdp_scope == "repeat" and not overlap: + raise ValueError( + "fsdp_scope 'repeat' gathers and releases a chunk's weights inside the per-microbatch " + "programs: it needs the fusion plan (overlap=True; not --no-overlap)" + ) + if scfg.lineage_split: + # What a chunk on Lineage's layers has no program for (ds_ep.ChunkPrograms refuses each when it is built): + # refused here, before anything is. + bad = [] + what = ( + ([f"stash {stash!r}"] if stash != "none" else []) + + (["modes"] if modes else []) + + (["schedule 'stash'"] if isinstance(schedule, str) and schedule == "stash" else []) + ) + if what: + bad.append( + f"{' / '.join(what)}: a chunk on Lineage's layers runs them in one custom VJP whose residuals are " + "Lineage's own, which no stash policy names: no stash modes (and no stash scheduler: 'search' or " + "'timed' search the order)" + ) + if ds_ep.parse_prefetch_pin(prefetch_pin) != "off": + bad.append( + f"prefetch_pin {prefetch_pin!r}: pins tie gathers to points of ds_ep's own layers (hn / xs / y), " + "which Lineage's layers have none of: 'off'" + ) + if bad: + raise ValueError( + "batch_split on Lineage's layers (batch_split_impl 'lineage') cannot run this: " + "; ".join(bad) + ) + # The zero-bubble schedules: one chunk a stage, and what no split backward runs under, refused before anything + # is built (a custom order of I and W ops once it is normalized, below). + if isinstance(schedule, str) and schedule in ZB_SCHEDULES: + if chunks_per_stage != 1: + raise ValueError( + f"schedule {schedule!r}: ZB-H1 / ZB-H2 run one chunk a stage (chunks_per_stage 1, --vv 1), not " + f"{chunks_per_stage}; a custom order of I and W ops runs at any" + ) + zb_refusals(f"schedule {schedule!r}", scfg, fsdp_scope) + if zb_wbuf_cap is not None and (isinstance(zb_wbuf_cap, bool) or int(zb_wbuf_cap) != zb_wbuf_cap or zb_wbuf_cap < 0): + raise ValueError(f"zb_wbuf_cap must be None or an int >= 0 (0 or None: no cap), got {zb_wbuf_cap!r}") + # zbh1 / zbh2: the W buffers a stage may hold pending -- each a split chunk's crossing set and the arguments its W + # reads, for one microbatch (`wbuf_bytes`) -- None for no cap + self.zb_wbuf_cap = None if zb_wbuf_cap in (None, 0) else int(zb_wbuf_cap) + if zb_split_last not in (True, False): + raise ValueError(f"zb_split_last must be a bool, got {zb_split_last!r}") + if zb_split_last and not (isinstance(schedule, str) and schedule in ZB_SCHEDULES): + raise ValueError( + f"zb_split_last splits the fused last chunk of zbh1 / zbh2's orders, not of schedule {schedule!r} (a custom " + "order splits it by giving it W ops of its own)" + ) + self.zb_split_last = bool(zb_split_last) + C = n_stages * chunks_per_stage + # The model's first_num_dense_layers dense layers run first (ds_ep.ChunkSpec.dense). `layer_split` splits the + # MoE layers, the dense ones all in chunk 0 -- or, given as every decoder layer a chunk (its sum + # num_decoder_layers, which the MoE layers' never is while there are dense layers), all the layers in order, + # the dense ones spanning the first chunks. + self.n_dense = getattr(cfg, "first_num_dense_layers", 0) # a Qwen3.5-family config has none + L = cfg.num_decoder_layers - self.n_dense + self.every_layer = bool(self.n_dense and layer_split is not None and sum(layer_split) == cfg.num_decoder_layers) + # The first and the last chunk may hold no layer (a layer split's 0 there): the embedding's alone, the head's + # alone -- a stage of its own for a head that would make its stage the pipeline's slowest (Qwen3.8's 248320-word + # head, a third of a two-layer stage's time). + ends = ( + 0 + if layer_split is None or not len(layer_split) + else sum(1 for i in {0, len(layer_split) - 1} if tuple(layer_split)[i] == 0) + ) + if self.n_dense < 0 or L < 0 or (not self.every_layer and L < C - ends): + raise ValueError( + f"{cfg.num_decoder_layers} layers, {self.n_dense} of them dense: {C} chunks (stages x " + "chunks_per_stage) need >= 1 MoE layer each -- the first and the last may hold none under a " + "layer split with a 0 there (or one that counts every layer)" + ) + if self.n_dense and (stash != "none" or modes): + # every chunk but the last builds the policy's programs, and dense layers have none + raise ValueError( + f"{self.n_dense} dense layers: the stash programs take MoE layers only, so no stash policy " + "with dense layers (--stash none)" + ) + self.mtp = getattr(cfg, "mtp_num_layers", 0) # a Qwen3.5-family config has none + if self.mtp not in (0, 1): + raise ValueError(f"mtp_num_layers {self.mtp}: the pipeline runs 0 or 1 MTP layer") + if self.mtp and scfg.cp > 1: + raise ValueError("MTP shifts tokens along the sequence: not under context parallelism (--cp 1)") + if layer_split is None: + if L % C: + raise ValueError(f"{L} layers do not split into {C} chunks") + layer_split = (L // C,) * C + else: + layer_split = tuple(layer_split) + if ( + len(layer_split) != C + or sum(layer_split) != (cfg.num_decoder_layers if self.every_layer else L) + or not all( + isinstance(n, numbers.Integral) and not isinstance(n, bool) and n >= (0 if i in (0, C - 1) else 1) + for i, n in enumerate(layer_split) + ) + ): + raise ValueError( + f"layer_split {layer_split}: want {C} chunks (stages x chunks_per_stage) of >= 1 layer each " + "(the first and the last may hold none: the embedding's alone -- with the dense layers, " + "if any -- and the head's alone), " + f"{L} layers in all" + + ( + f" (the MoE layers, the dense ones in chunk 0; or " + f"{cfg.num_decoder_layers}, every layer, the " + f"{self.n_dense} dense ones first)" + if self.n_dense + else "" + ) + ) + # Layers per chunk, in chunk order: uneven where the head's chunk (or the + # embedding's) should hold fewer, to even out the stages. + self.layer_split = layer_split + if global_batch % n_micro: + raise ValueError("global_batch must divide into n_micro microbatches") + self.mbs, self.seq, self.gbs = global_batch // n_micro, seq, global_batch + # Context parallelism (scfg.cp): a microbatch of mbs sequences runs as + # rows = cp x mbs rows of seq / cp tokens, chunk-major per sequence (row + # cp x i + r is chunk r of sequence i), exactly one row a stage device; + # every activation and boundary copy is [rows, row_len, emb]. + self.cp = scfg.cp + if seq % self.cp: + raise ValueError(f"cp={self.cp} does not split seq={seq} into whole chunks") + self.rows, self.row_len = self.mbs * self.cp, seq // self.cp + if self.cp > 1 and self.rows != scfg.fsdp * scfg.ep: + raise ValueError( + f"cp={self.cp}: a microbatch of {self.mbs} sequences is {self.rows} rows; context " + f"parallelism wants exactly one a stage device (fsdp*ep={scfg.fsdp * scfg.ep}), so " + f"{scfg.fsdp * scfg.ep // self.cp} sequences a microbatch" + ) + if self.mbs % (scfg.fsdp * scfg.ep) and self.cp == 1: + raise ValueError(f"microbatch {self.mbs} must divide by fsdp*ep={scfg.fsdp * scfg.ep}") + self.C = C + self.placement = placement + self.place = sched.placement(n_stages, chunks_per_stage, placement) + self.init_by_chunk = init_by_chunk + if schedule is None: + schedule = DEFAULT_SCHEDULE + self.schedule = schedule if isinstance(schedule, str) else "custom" # what run records name + if fsdp_scope is None: + fsdp_scope = default_fsdp_scope(schedule, overlap) + self.fsdp_scope = fsdp_scope + # Residuals in host memory: each (chunk, microbatch)'s forward residuals + # (its input, and the first chunk's layer inputs) go to the same sharding + # in pinned host memory right after the forward and come back right + # before its backward (`_put_F` / `_take_B`), so the HBM a step holds no + # longer grows with the microbatches a schedule keeps in flight. On a + # GB200 the host is the Grace CPU behind NVLink-C2C: a 134 MB residual + # (Qwen3.8, 2 rows of 4096 x 8192 bf16) moves in ~0.3 ms each way. + self.offload_residuals = bool(offload_residuals) + # How the stages share their gradient sums of squares for the global-norm + # clip: 'hops', a scalar copy from every stage to every other one + # (S(S-1) a step, each a channel of its own -- on GPU a NCCL communicator + # of its own the first time: 2070 at 46 stages), or 'allreduce', one sum + # over every device of the job in one program (`_global_sumsq`), whose + # total each stage's update takes in place of the S partials -- under + # multi-controller JAX: in one controller every stage's sum is this + # process's, and the hops run. + if norm_reduce not in ("hops", "allreduce"): + raise ValueError(f"norm_reduce must be 'hops' or 'allreduce', got {norm_reduce!r}") + self.norm_reduce = norm_reduce + if interleave_group is not None and (not isinstance(schedule, str) or schedule != "interleaved"): + raise ValueError( + f"interleave_group {interleave_group} is the interleaved schedule's microbatch group, not " + f"schedule {schedule!r}'s" + ) + if isinstance(schedule, (list, tuple)): # fail before anything is built + # e.g. a list of lists from JSON -> (int, str, int) tuples: the plan + # looks ops up by value (`order.index((0, 'F', 0))`) + schedule = normalize_schedule(schedule) + validate_schedule(schedule, C, n_micro, self.place, fuse=frozenset(fuse or ())) + if any(k in ("I", "W") for _, k, _ in schedule): + zb_refusals( + "a custom order of I and W ops", scfg, fsdp_scope, order=schedule, modes=modes, fuse=frozenset(fuse or ()) + ) + first_layer = np.cumsum((0,) + layer_split) + if self.every_layer: # chunk c holds layers first_layer[c].. in order, the dense ones first + spans = [range(first_layer[c], first_layer[c + 1]) for c in range(C)] + dense = [sum(1 for l in r if l < self.n_dense) for r in spans] + moe = [tuple(l - self.n_dense for l in r if l >= self.n_dense) for r in spans] + else: # the MoE layers split, the dense ones in chunk 0 + dense = [self.n_dense if c == 0 else 0 for c in range(C)] + moe = [tuple(range(first_layer[c], first_layer[c + 1])) for c in range(C)] + self.chunks = [ + ds_ep.ChunkSpec( + index=c, + layers=moe[c], + first=(c == 0), + last=(c == C - 1), + stage=self.place[c], + dense=dense[c], + routed_bias=getattr(cfg, "routed_bias", False), + mtp=self.mtp if c == C - 1 else 0, + kinds=ds_ep.layer_kinds(cfg, moe[c], scfg.layer_tree == "per_layer"), + dense_kinds=ds_ep.dense_layer_kinds(dense[c], scfg.layer_tree == "per_layer"), + ) + for c in range(C) + ] + if self.zb_split_last and not (self.chunks[-1].layers or self.chunks[-1].dense): + raise ValueError( + f"zb_split_last: the last chunk holds no layer (layer_split {list(layer_split)}): its weight gradients, the " + "head's and the decoder norm's, stay in its F (AI), with nothing for a W to defer" + ) + if ds_ep.is_qwen(cfg) and (stash != "none" or modes): + # STASH_POLICIES name MLA's residuals, and the stash costs (sched.STASH_BWD_TEMP) are DeepSeek's. The stash + # schedule without a policy (--stash none) is a remat-only order search, on the costs --schedule timed uses. + raise ValueError( + "stash modes are not implemented for the Qwen3.5 family: its layers recompute in the " "backward (--stash none)" + ) + # Prefetch pins (`_plan_pins`, after the fusion plan), checked here, before anything is built: every + # name of a SPEC must select a leaf of this model, and give every leaf one point (ds_ep.pin_of), whichever + # leaves the plan's forwards gather. + self.prefetch_pin = ds_ep.parse_prefetch_pin(prefetch_pin) + if ds_ep.is_qwen(cfg) and self.prefetch_pin == "auto": + raise ValueError( + "prefetch_pin 'auto' plans from MLA's FLOPs and DeepSeek's measured window rates " + "(ds_ep.pin_windows); for the Qwen3.5 family pin by SPEC, or not at all (off)" + ) + self.leaf_names = [ds_ep.leaf_names(ch) for ch in self.chunks] + if isinstance(self.prefetch_pin, tuple): + bad = [ + n + for _, _, n in self.prefetch_pin + if not any(ds_ep.pin_selects(n, m, c) for c, names in enumerate(self.leaf_names) for m in names) + ] + if bad: + every = sorted({m for names in self.leaf_names for m in names}) + raise ValueError( + f"--prefetch-pin: {bad} select(s) no weight of this model: its leaves are {every}, each " + f"optionally prefixed with its chunk (c0. .. c{C - 1}.)" + ) + for c, names in enumerate(self.leaf_names): + for m in names: + ds_ep.pin_of(self.prefetch_pin, m, c) + self.meshes = typed_meshes(meshes or stage_meshes(n_stages, scfg.fsdp, scfg.ep, layout=layout), scfg.shard_mode) + # The stages this process compiles and dispatches (all of them in one + # process, and when compiling ahead of time for a topology), and the ones + # it places arrays on (none ahead of time). + self.aot = bool(aot) + # Multi-controller JAX (pathways.multi_controller: never under Pathways, nor in one host's own process): the one + # switch for what only several processes need -- the global-order walk, the key-value store, the barriers, the + # cross-process copies. + self.multi = pathways.multi_controller() and not self.aot + if transport not in ("native", "ppermute", "xfer", "relay"): + raise ValueError(f"transport {transport!r}: want 'native', 'ppermute', 'xfer' or 'relay'") + if transport == "xfer" and not (self.multi or self.aot): + raise ValueError( + "transport 'xfer' (jax.experimental.transfer between hosts) needs one process per " "host (--distributed)" + ) + if transport == "relay" and not (self.multi or self.aot): + raise ValueError("transport 'relay' (a host relay between processes) needs one process per host " "(--distributed)") + self.transport = transport + if self.multi: + for b, a, procs in shared_stage_hosts(self.meshes)[:1]: + raise ValueError( + f"stages {b} and {a} share processes {procs}: under multi-controller JAX every " + "stage needs hosts of its own (a boundary copy between stages of one process set " + "is a reshard jax refuses)" + ) + # The processes holding each stage's devices. A process may hold no stage (a pipeline over part of the + # slice): it still walks every copy of the order (`_do_remote`), and runs nothing. + pid = jax.process_index() + self.stage_procs = [frozenset(d.process_index for d in m.devices.flat) for m in self.meshes] + self.local = frozenset(s for s in range(n_stages) if pid in self.stage_procs[s]) + self._gsq = None # norm_reduce 'allreduce': `_global_sumsq`'s program, built at its first step + else: # one controller (or ahead of time): this process, process 0, holds every stage + self.stage_procs = [frozenset({0})] * n_stages + self.local = frozenset(range(n_stages)) + self.placed = frozenset() if self.aot else self.local + self.stage_chunks = [[ch for ch in self.chunks if ch.stage == s] for s in range(n_stages)] + self.slot = {ch.index: self.stage_chunks[ch.stage].index(ch) for ch in self.chunks} + denom = float(global_batch * seq) + # Per-stage collective flavours. libtpu offloads all-gather / reduce- + # scatter to SparseCore (async) on some sub-meshes and refuses on others + # (any part of a slice containing chip (0,0,0), but not the whole slice); + # `offload_answers` asks it, over the axes the collective in question + # spans: each stage's processes probe, and across processes its lowest + # one's answers are every process's. `stage_ep_collectives` (one of + # 'xla' / 'ppermute' per stage) overrides scfg.ep_collectives, e.g. to + # force the TPU7x benchmark runs' ['ppermute', 'xla'] whatever the probe answers. + if stage_ep_collectives is not None: + stage_ep_collectives = tuple(stage_ep_collectives) + if len(stage_ep_collectives) != n_stages or not set(stage_ep_collectives) <= {"xla", "ppermute"}: + raise ValueError( + f"stage_ep_collectives: one of 'xla' / 'ppermute' per stage ({n_stages}), got " f"{stage_ep_collectives!r}" + ) + if stage_lineage_sparsecore is not None: + stage_lineage_sparsecore = tuple(stage_lineage_sparsecore) + if len(stage_lineage_sparsecore) != n_stages or not all(isinstance(v, bool) for v in stage_lineage_sparsecore): + raise ValueError(f"stage_lineage_sparsecore: a bool per stage ({n_stages}), got {stage_lineage_sparsecore!r}") + # The asks, the same on every process (the flags decide them): EP's under + # 'auto' at EP 2 (elsewhere the permute flavour does not apply; nor on + # Lineage's layers, which run EP collectives of their own), and, but ahead + # of time, FSDP's on the TPU stages of more than one device under 'xla': + # which run them synchronously (sync_stages). + multi_device_tpu = lambda s: _is_tpu(self.meshes[s].devices.flat[0]) and self.meshes[s].devices.size > 1 + asks = [ + (s, ds_ep.EP_AXIS) + for s in range(n_stages) + if stage_ep_collectives is None and scfg.ep_collectives == "auto" and scfg.ep == 2 and not scfg.lineage_split + ] + asks += [ + (s, ds_ep.FE) for s in range(n_stages) if scfg.fsdp_collectives == "xla" and not self.aot and multi_device_tpu(s) + ] + # Batch split on Lineage's layers: does each stage run Lineage's SparseCore regions (ds_ep_lineage.Region's + # `sparsecore`)? Where libtpu offloads no collective its compiler aborts on them, so they trace as TensorCore + # code there (ds_ep_lineage.no_sparsecore). The question is the FSDP one over the whole stage, asked alike -- + # ahead of time too, as a compile-only slice answers it -- so every process of a stage traces its Regions under + # its lead's answer, and a probe that fails (a compile-only topology off its first slice: ds_ep_aot) answers by + # the device rule; `stage_lineage_sparsecore` answers instead. + if scfg.lineage_split and stage_lineage_sparsecore is None: + asks += [(s, ds_ep.FE) for s in range(n_stages) if (s, ds_ep.FE) not in asks] + self.proxy = on_pathways(self.meshes) if proxy is None else bool(proxy) + if self.aot and self.proxy: + # Ahead of time for a Pathways run (ds_ep_aot --pathways): a compile-only topology's libtpu answers as a TPU + # VM's own, where the Pathways servers' compiler offloads on chip (0,0,0)'s sub-meshes too -- the device rule's + # answers under Pathways, unprobed. + why = "planned for one Pathways client: its device rule (sync_collective_stages), unprobed" + self.offloads = {(s, axes): (rule_offloads(self.meshes, s, axes, frozenset()), why) for s, axes in asks} + elif self.multi and asks: # each stage's lead process answers for its stage, through the key-value store + from jax._src import distributed + + key = f"mpmd/offload/{next(_OFFLOAD_KEYS)}" + self.offloads = offload_answers(self.meshes, asks, kv=distributed.global_state.client, key=key) + else: + self.offloads = offload_answers(self.meshes, asks) + sc = lambda s, axes: self.offloads[(s, axes)][0] + self.stage_scfg = [] + for s in range(n_stages): + c = scfg + if stage_ep_collectives is not None: + c = replace(c, ep_collectives=stage_ep_collectives[s]) + elif scfg.ep_collectives == "auto": + # 'auto' uses the lax collectives where libtpu offloads them and async + # collective-permutes elsewhere. With EP != 2 the permute flavour does + # not apply (and at EP=1 the lax collectives are no-ops), so only probe + # when there is a choice -- and there is none on Lineage's layers, which + # run no ds_ep EP collective: 'xla', unused. + c = replace( + c, ep_collectives="xla" if (scfg.ep != 2 or scfg.lineage_split or sc(s, ds_ep.EP_AXIS)) else "ppermute" + ) + self.stage_scfg.append(c) + # Stages whose FSDP collectives are lax collectives libtpu keeps synchronous + # (collective-permutes are async DMAs on every sub-mesh): by its answer + # where it was asked over the whole stage, else by the device rule. + rule = frozenset() if self.proxy else sync_collective_stages(self.meshes) # Pathways': none (its docstring) + asked = lambda s: (s, ds_ep.FE) in self.offloads and multi_device_tpu(s) and not self.aot + self.sync_stages = frozenset( + s + for s in range(n_stages) + if self.stage_scfg[s].fsdp_collectives == "xla" and (not sc(s, ds_ep.FE) if asked(s) else s in rule) + ) + self.lineage_sc = None + if scfg.lineage_split: + self.lineage_sc = ( + stage_lineage_sparsecore + if stage_lineage_sparsecore is not None + else tuple(bool(sc(s, ds_ep.FE)) for s in range(n_stages)) + ) + self.progs = [ + ds_ep.ChunkPrograms( + self.stage_scfg[ch.stage], + ch, + self.meshes[ch.stage], + self.rows, + self.row_len, + denom, + lineage_sparsecore=None if self.lineage_sc is None else self.lineage_sc[ch.stage], + ) + for ch in self.chunks + ] + # Which chunks each stage gathers inside its optimizer program (the rest + # are prefetched inside forwards): the stage holding chunk 0 must start + # the forward right after its update, so it gathers only its first chunk + # there; every other stage waits for upstream activations anyway and + # gathers all of its chunks in that window. + first_stage = self.place[0] + self.gather_slots = [ + tuple(range(len(self.stage_chunks[s]))) if (overlap and s != first_stage) else (0,) for s in range(n_stages) + ] + # Routed experts read in place: at fsdp 1 a routed expert's compute copy + # would be its storage's bytes again -- stored over 'expert' alone, with + # no axis to gather over -- so where the two dtypes agree the stage's + # programs take the storage leaves themselves: no gather and no second + # copy for the step (12 GiB a Qwen3.8 layer at EP 4, 5.25 a DeepSeek-V3 + # one). {chunk: its leaves read so (ds_ep.routed_leaf_ids)}. The plans' + # gathers leave them out; `_whole` and `_install` take them from the + # step's params. Shard mode auto only (an explicit one types the copy). + self.direct = {} + if direct_experts and scfg.fsdp == 1 and scfg.shard_mode == "auto": + for ch in self.chunks: + sdt = ds_ep.leaf_dtypes(self.stage_scfg[ch.stage], ch, "storage") + cdt = ds_ep.leaf_dtypes(self.stage_scfg[ch.stage], ch, "compute") + ids = tuple(i for i in ds_ep.routed_leaf_ids(ch) if sdt[i] == cdt[i]) + if ids: + self.direct[ch.index] = ids + # Self-prefetch: the stage that starts the forward gathers its first + # chunk's routed experts inside that chunk's first forward (they are not + # needed until the MoE half), so the update program only gathers the rest. + self.self_prefetch = bool(overlap and self_prefetch) + self.routed_leaves = None + first_leaves = [None] * n_stages + if self.self_prefetch and (not self.chunks[0].n_moe or 0 in self.direct): + # chunk 0 is dense layers only, or its routed experts are read in place: none to gather late + self.self_prefetch = False + if self.self_prefetch: + specs = jax.tree.leaves(ds_ep.chunk_storage_specs(self.chunks[0]), is_leaf=ds_ep._is_spec) + self.routed_leaves = tuple(i for i, sp in enumerate(specs) if len(sp) > 1 and sp[1] == "expert") + first_leaves[first_stage] = tuple(i for i in range(len(specs)) if i not in self.routed_leaves) + self.first_leaves = first_leaves + + # -- schedule (after the chunk programs: the stash schedulers size a stash + # set by building its programs; the stage programs come after it, since + # the prefetch plan it decides can move a chunk's gather into them) + if stash not in ds_ep.STASH_POLICIES: + raise ValueError(f"stash {stash!r}: want one of {sorted(ds_ep.STASH_POLICIES)}") + self.stash_policy, self.stash_budget_gib = stash, stash_budget_gib + # Program costs (ms) for the timed and stash schedulers and the summary's + # simulation: `default_costs`, any key of `costs` over them (per-chunk + # keys too, see `sched.cost_table`), then each chunk's share of an + # uneven `layer_split` (`split_costs`: --costs' F / B / A scale like the + # defaults'). + table = dict(default_costs(self.meshes[0].devices.flat[0].device_kind, scfg)) + table.update(costs or {}) + # A chunk's dense layers cost about a MoE layer each (DeepSeek-V3's dense MLP has the active FLOPs of its + # experts and shared expert). + self.costs = split_costs(table, tuple(ch.dense + ch.n_moe for ch in self.chunks), remat_last=scfg.remat_fused_last) + self.modes = {} + # F&B pairs run as one program: order[j] and order[j+1] for j in fuse + self.fuse = frozenset() + self.pair_gain = float(self.costs.get("pair_gain", 0.0) if pair_gain is None else pair_gain) + # -> what megatron_interleaved takes: None every stage, () none, else the stages + if pair_stages is not None and not (isinstance(schedule, str) and schedule == "interleaved"): + raise ValueError( + f"pair_stages {pair_stages!r}: only schedule 'interleaved' pairs F and B on stages (a custom order " + "names its pairs in `fuse`)" + ) + if isinstance(pair_stages, str) and pair_stages == "all": + pair_stages = None + elif pair_stages is not None: + pair_stages = tuple(sorted(set(pair_stages))) + if any(not 0 <= s < n_stages for s in pair_stages): + raise ValueError(f"pair_stages {pair_stages}: stages are 0..{n_stages - 1}") + else: + pair_stages = () # Megatron's order as it is, unless its pairs are asked for + self.pair_stages = pair_stages + if isinstance(schedule, (list, tuple)): + self.order = list(schedule) # normalized above + self.modes = {tuple(k): v for k, v in (modes or {}).items() if v != "r"} + self.fuse = frozenset(fuse or ()) + if stash != "none" and not self.modes: + raise ValueError(f"stash {stash!r} with a custom order: say which (chunk, microbatch)s " "stash in `modes`") + self.schedule_name = ( + "custom" + + (f" ({len(self.modes)} stash)" if self.modes else "") + + (f" ({len(self.fuse)} pairs)" if self.fuse else "") + ) + elif modes or fuse: + raise ValueError("modes and fuse ride along with a custom order (schedule as a list)") + elif stash != "none" and schedule not in ("stash", "interleaved"): + raise ValueError(f"stash {stash!r} needs schedule stash or interleaved (or a custom order with modes)") + elif schedule == "interleaved": + # Megatron-LM's interleaved 1F1B, with its steady state's F&B pairs if + # asked for, as per-stage streams; `merge` lists them as one order + # (`fuse`: each pair's F), and with `stash` the order's stash modes are + # handed out under the budget. + cost, xfer, g = sched.cost_table(self.costs, C), self.costs["xfer"], self.pair_gain + if placement != "circular": + raise ValueError(f"schedule interleaved runs on placement 'circular', not {placement!r}") + # interleave_group: Megatron's microbatch_group_size_per_vp_stage (None: n_stages). At S per group a + # microbatch's forward comes round to rank 0's next chunk just in time when the boundary copies cost + # nothing; on GB200 nodes (a 470 MB DeepSeek-V3 activation a hop, ~3 ms over RDMA) every chunk switch + # stalled the 16-stage pipeline ~200 ms, twice in each 4.6 s round (megatron_interleaved). + streams = sched.megatron_interleaved( + n_stages, chunks_per_stage, n_micro, group=interleave_group, pair_stages=pair_stages + ) + head = ( + "interleaved (Megatron" + + ("" if interleave_group in (None, n_stages) else f", groups of {interleave_group}") + + ")" + ) + self.order, self.fuse, _ = sched.merge(streams, self.place, cost, xfer, g, n_micro=n_micro) + est = "" + if stash != "none": + nbytes = [self.progs[c].build_stash(stash).bytes if c != C - 1 else 0 for c in range(C)] + est = " (stash costs estimated)" if self._stash_costs(stash) else "" + self.modes = sched.stash_modes( + self.order, self.place, {stash: nbytes}, int(stash_budget_gib * 2**30), stash_caps, policy=stash + ) + mk = sched.timed_simulate( + self.order, self.place, cost, xfer, fuse_last=True, modes=self.modes, fuse=self.fuse, pair_gain=g + )[0] + on = "every stage" if pair_stages is None else f"stages {list(pair_stages)}" + # (it names its pairs only where they were asked for: an unpaired run keeps its name) + pairs = "" if pair_stages == () else f" pairs {len(self.fuse)} ({on}, gain {g:g} ms)" + self.schedule_name = ( + head + + pairs + + (f" stash {stash} budget {stash_budget_gib:g} GiB" if stash != "none" else "") + + f" sim={mk:.1f}{est}" + ) + elif schedule == "stash": + # Each forward stashes while its stage's live stash sets fit the budget + # (and its chunk is under its cap); the order is searched with the + # stash backwards' costs, measured or `sched.stash_estimates`. + pol = None if stash == "none" else stash + nbytes = [self.progs[c].build_stash(pol).bytes if pol and c != C - 1 else 0 for c in range(C)] + est = " (stash costs estimated)" if pol and self._stash_costs(pol) else "" + caps = stash_caps if pol else [0] * C + if caps is not None: + caps = list(caps) + [0] * (C - len(caps)) # the last chunk keeps nothing + res = sched.stash_search( + C, + n_micro, + self.place, + sched.cost_table(self.costs, C), + self.costs["xfer"], + nbytes, + int(stash_budget_gib * 2**30), + policy=pol or "r", + caps=caps, + ) + self.order, self.modes = res[0], res[1] + self.schedule_name = ( + f"stash {stash} budget {stash_budget_gib:g} GiB caps {res[2][0]} " f"{res[2][1]} sim={res[3]:.1f}{est}" + ) + elif schedule in ORDER_SCHEDULES: + # gpipe / 1f1b / breadth / search from the placement alone; timed, the + # event-driven search, and zbh1 / zbh2, the zero-bubble schedules, with + # this pipeline's program costs (ms, only their ratios matter; the last + # chunk is one fused program) + self.order, self.schedule_name = build_schedule( + schedule, + C, + n_micro, + self.place, + costs=self.costs, + zb_wbuf_cap=self.zb_wbuf_cap, + zb_split_last=self.zb_split_last, + ) + else: + raise ValueError( + f"unknown schedule {schedule!r}: expected one of {SCHEDULES} or a custom order " + "(a sequence of (chunk, kind, microbatch) triples)" + ) + # The fusion plan and the step loop take the order on trust; a bad one + # would fail halfway through a step, after buffers were donated. + sched.validate(self.order, self.place, n_micro, modes=self.modes, fuse=self.fuse) + if scfg.lineage_split and (ab := sorted(j for j in self.fuse if self.order[j][0] == C - 1)): + # (A custom order's: interleaved never pairs the last chunk's fused program.) + # An F&B pair whose F is the last chunk's fused forward + backward pairs two of Lineage's backwards in one + # program, which XLA compiles with an all-reduce of both chunks' layer gradients over 'fsdp' (bf16; 257 MiB a + # program at D 1024, 2 + 2 MoE layers, TPU7x, libtpu 0.0.46), each kept on one device after: the values stay + # right, the program does a synchronous collective it should not. Not in the lowered program, nor in a pair + # with one Lineage backward or of ds_ep's own layers. + raise ValueError( + f"batch_split on Lineage's layers: F&B pairs of the last chunk's fused program with another " + f"chunk's backward ({', '.join(self.op_name(j) + '&' + self.op_name(j + 1) for j in ab[:3])}" + f"{', ...' if len(ab) > 3 else ''}) run two of Lineage's backwards in one program, which XLA " + "compiles with an all-reduce of their weight gradients over 'fsdp': leave them out of `fuse`" + ) + # -- the split backward (the zero-bubble schedules): the chunks whose backwards the order runs as I and W build + # their two halves (ds_ep.ChunkPrograms.build_split: one trace of the chunk's backward, one I, and the W of its + # first gradient write, which starts its accumulator -- the others add to it; a split last chunk's AI and W, + # build_split_last), on every process -- what one microbatch holds from its I (AI) to its W (`wbuf_bytes`: the + # crossing set and the arguments W reads, per device) is in every process's summary and plan. The simulations + # price I and W from B where the table has neither, a split last chunk's W from A (sched.zb_costs). + self.split_chunks = sorted({c for c, k, _ in self.order if k in ("I", "W")}) + # `_do_I`; a plan for one Pathways client (ds_ep_aot --pathways, compile-only TPU devices) does not pace, as its run + self.pace_i = bool(self.split_chunks) and not self.proxy and allocates_at_issue(self.meshes[0].devices.flat[0]) + self.split_last = C - 1 in self.split_chunks + self.wbuf_bytes = {} + for c in self.split_chunks: + sps = [self.split_of(c, acc) for acc in ((False, True) if n_micro > 1 else (False,))] + self.wbuf_bytes[c] = max(sp.bytes + sp.kept_bytes for sp in sps) + if self.split_chunks: + self.costs = sched.zb_costs(self.costs, C, last=self.split_last) + pols = set(self.modes.values()) | ({stash} if stash != "none" else set()) + for pol in sorted(pols): + if pol not in ds_ep.STASH_POLICIES or pol == "none": + raise ValueError(f"mode {pol!r}: want a stash policy of {sorted(ds_ep.STASH_POLICIES)}") + # Bytes of one stash set per chunk and policy (per device and microbatch), + # which also builds the policy's programs. + self.stash_bytes = { + pol: [self.progs[c].build_stash(pol).bytes if c != C - 1 else 0 for c in range(C)] for pol in sorted(pols) + } + for pol in self.stash_bytes: + self._stash_costs(pol) + + # -- which ops carry which chunk's gather. fsdp_scope 'step' + # (`_prefetch_hosts`): forwards, once a step. A chunk that no earlier + # forward on its stage can carry (at n_micro=1 the first stage's only + # forward before its second chunk is 0F0, busy with self-prefetch; under + # V the head's too) is gathered by the previous step's update program + # instead, with the stage's first chunk. 'repeat' (`_plan_repeat`): once + # a visit, inside the stage's previous visit, and released after it. + # `pf_gathers`: [(chunk, [(order index, leaf ids), ...])], a gather each. + self.release_at, self.visits = {}, None + if overlap and fsdp_scope == "repeat": + if self.fuse: + raise ValueError( + "fsdp_scope 'repeat' folds its gathers into single-op programs: an order with F&B " + "pairs (interleaved with pair_stages, a custom fuse) has no place for them" + ) + self.pf_plan = {} + self.pf_gathers, self.release_at, self.visits, self.gather_slots, self.pf_fallback = self._plan_repeat() + else: + self.pf_plan, self.pf_fallback = self._prefetch_hosts() if overlap else ({}, []) + for b in self.pf_fallback: + s = self.place[b] + self.gather_slots[s] = tuple(sorted(self.gather_slots[s] + (self.slot[b],))) + self.pf_gathers = list(self.pf_plan.items()) + self.stages = [ + ds_ep.StagePrograms( + self.stage_scfg[s], + self.stage_chunks[s], + self.meshes[s], + n_stages=n_stages, + gather_slots=self.gather_slots[s], + first_leaves=first_leaves[s], + skip_leaves=[self.direct.get(ch.index, ()) for ch in self.stage_chunks[s]], + ) + for s in range(n_stages) + ] + + # -- channels: an activation channel for every two stages the placement + # links (chunk c's stage and chunk c+1's, both ways); a chunk boundary + # within one stage (the turn of a V) is no copy at all (`_send`). Across + # processes, every process holds every channel and walks every copy (the + # stages' own processes act on it), and so does the gradient norm's scalar + # hop between every two stages (`_hop`). Ahead of time only the ppermute + # channels exist: they are programs to compile; the others are runtime copies + # (and the hops' only for a multi-controller run: one Pathways client's -- + # ds_ep_aot --pathways, `proxy` -- are jax.device_puts under ppermute). + act_aval = jax.ShapeDtypeStruct((self.rows, self.row_len, cfg.emb_dim), cfg.dtype) + act = P(ds_ep.FE, None, None) + linked = {(self.place[c], self.place[c + 1]) for c in range(C - 1)} + linked |= {(b, a) for a, b in linked} + self.channels, self.sq_channels = {}, {} + # The host-side transports (multi-controller only: refused above in one controller), each with one context per + # pipeline: xfer's transfer server, or the relay's listener, streams and threads (`close`). + host = self.copy_ctx = None + if self.multi and transport in ("xfer", "relay"): + host = { + "xfer": (transfer.xfer_context, transfer.XferChannel), + "relay": (transfer.RelayContext, transfer.RelayChannel), + }[transport] + self.copy_ctx = host[0]() + for a in range(n_stages): + for b in range(n_stages): + if a == b or (self.aot and transport != "ppermute"): + continue + src, dst = NamedSharding(self.meshes[a], act), NamedSharding(self.meshes[b], act) + sq = ( + jax.ShapeDtypeStruct((), jnp.float32), + NamedSharding(self.meshes[a], P()), + NamedSharding(self.meshes[b], P()), + ) + if transport == "ppermute": + if (a, b) in linked: + self.channels[(a, b)] = transfer.PermuteChannel(act_aval, src, dst, name=f"s{a}->s{b}") + if self.multi or (self.aot and not self.proxy): # ahead of time: ds_ep_aot's multi-controller target + self.sq_channels[(a, b)] = transfer.PermuteChannel(*sq, name=f"sumsq s{a}->s{b}") + elif not self.multi: # one controller: jax's batched device-to-device copy + if (a, b) in linked: + self.channels[(a, b)] = transfer.Channel(act_aval, src, dst, name=f"s{a}->s{b}", strict=True) + if on_pathways(self.meshes): + # The gradient norm's hops too (`_hop`): through the IFRT proxy a prebuilt Channel's send costs + # ~105-155 us of host time, a jax.device_put ~150-240 us, and a step makes S(S-1) of them -- one + # batched copy either way (local docker Pathways, tpu7x-8). + self.sq_channels[(a, b)] = transfer.Channel(*sq, name=f"sumsq s{a}->s{b}", strict=True) + elif host: + # the channel's id (xfer's uuid prefix), the same on every process; its sumsq hop's is the next + k = 2 * (a * n_stages + b) + if (a, b) in linked: + self.channels[(a, b)] = host[1](act_aval, src, dst, self.copy_ctx, k, name=f"s{a}->s{b}") + self.sq_channels[(a, b)] = host[1](*sq, self.copy_ctx, k + 1, name=f"sumsq s{a}->s{b}") + else: + if (a, b) in linked: + self.channels[(a, b)] = transfer.CrossProcessChannel(act_aval, src, dst, name=f"s{a}->s{b}") + self.sq_channels[(a, b)] = transfer.CrossProcessChannel(*sq, name=f"sumsq s{a}->s{b}") + # MTP's copy of the token embedding (the last chunk's, ds_ep.mtp_shapes) + # and chunk 0's table are one parameter: each step their two gradients + # are exchanged and summed before the norm and the update (`_tie`), over + # a channel each way between the two stages -- ahead of time, as above, + # only the ppermute ones, programs to compile. + self.tie_channels = {} + a0, b0 = self.place[0], self.place[C - 1] + if self.mtp and a0 != b0 and not (self.aot and transport != "ppermute"): + emb_aval = jax.ShapeDtypeStruct((cfg.vocab_size, cfg.emb_dim), scfg.rs_dtype) + emb = P(None, ds_ep.FE) + for k, (a, b) in enumerate(((a0, b0), (b0, a0))): + src, dst = NamedSharding(self.meshes[a], emb), NamedSharding(self.meshes[b], emb) + name = f"tied embedding s{a}->s{b}" + if transport == "ppermute": + self.tie_channels[(a, b)] = transfer.PermuteChannel(emb_aval, src, dst, name=name) + elif not self.multi: + self.tie_channels[(a, b)] = transfer.Channel(emb_aval, src, dst, name=name, strict=True) + elif host: + self.tie_channels[(a, b)] = host[1](emb_aval, src, dst, self.copy_ctx, 2 * n_stages * n_stages + k, name=name) + else: + self.tie_channels[(a, b)] = transfer.CrossProcessChannel(emb_aval, src, dst, name=name) + for k, chn in self.channels.items(): + if getattr(chn, "n_slow", 0): + raise RuntimeError(f"{chn}: boundary would bounce through the host") + + # -- per-stage constants, committed once + rep = lambda s, x: jax.device_put(x, NamedSharding(self.meshes[s], P())) + self.seeds = [[rep(s, jnp.int32(m)) for m in range(n_micro)] if self._places(s) else None for s in range(n_stages)] + + # -- who writes each chunk's gradient accumulator, and when + shp = lambda c: ds_ep.chunk_shapes(scfg, self.chunks[c]) + self.treedef = {c: jax.tree.structure(shp(c), is_leaf=ds_ep._is_shape) for c in range(C)} + self.n_leaves = {c: self.treedef[c].num_leaves for c in range(C)} + self.first_writer, self.last_writer = {}, {} + for j, (c, k, m) in enumerate(self.order): + if self._writes(c, k): + self.first_writer.setdefault(c, j) + self.last_writer[c] = j + + # interleaved has no earlier plan to keep, so it reserves under circular + # placement too + self.rs_reserve = (placement == "v" or schedule == "interleaved") if rs_reserve is None else bool(rs_reserve) + # the fusion plan (empty without overlap) + self.pf, self.rs_at, self.rs_groups, self.rs_self = {}, {}, {}, {} + self.pf_n = {} # host order index -> how many hosts its gather has + self.self_pf_at, self.final_slots, self.n_partial_sq = None, [()] * n_stages, [0] * n_stages + if overlap: + self._plan_overlap() + self.pins, self.unpinned = self._plan_pins() if overlap else ({}, {}) + self._ops = {} # overlap -> [Op] + self._issue = {} # overlap -> the order's indices as the step loop issues them (issue_order) + self._exe = {} # (chunk, desc) -> compiled program (precompile) + self.step_gnorms = () # the last step's gnorm of every local stage (`step`) + self.on_grads = None # step: called with the reduced gradients before the update (--grad-digest) + + def _stash_costs(self, pol): + """Give `self.costs` a stash backward and forward cost of `pol` for every + non-last chunk: `sched.stash_estimates` wherever the table has none (the + keys `sched.cost_table` would read, d-keys included). -> the keys estimated.""" + guess, added = sched.stash_estimates(self.costs, pol, self.C), [] + for c in range(self.C - 1): + for kind in ("B", "F"): + s = f"{kind}s" + if not any( + n in self.costs for n in (f"{s}{c}:{pol}", f"d{s}{c}:{pol}", f"{s}:{pol}", f"d{s}:{pol}", f"{s}{c}", s) + ): + self.costs[f"{s}{c}:{pol}"] = guess[f"{s}{c}:{pol}"] + added.append(f"{s}{c}:{pol}") + return added + + @property + def relay_ctx(self): + """The relay's context under transport 'relay' (its settings: + `describe()`; where its time went: `timing()`), else None.""" + return self.copy_ctx if self.transport == "relay" else None + + def _runs(self, s): + """Does this process compile and run stage s's programs: in one controller -- a Pathways client, one host's own + process -- every stage, `local` not looked at; under multi-controller JAX its own stages (`local`); ahead of time + the stages ds_ep_aot compiles (`local` again: --stages-to-compile).""" + return not (self.multi or self.aot) or s in self.local + + def _places(self, s): + """Does this process put stage s's arrays (weights, batches, seeds) on its devices: in one controller every stage, + `placed` not looked at; under multi-controller JAX its own stages; ahead of time none.""" + return not (self.multi or self.aot) or s in self.placed + + def _writes(self, c, k): + """Does op (c, k, .) write chunk c's gradient accumulator? A B or a W -- a split last chunk's W its deferred + part -- and the fused last chunk's F.""" + return k == "W" or (k == "B" and c != self.C - 1) or (k == "F" and c == self.C - 1) + + def split_of(self, c, acc=False): + """Chunk c's split for the zero-bubble schedules (ds_ep.Split, of `acc`'s W): a middle chunk's backward cut into I + and W (ChunkPrograms.build_split), the fused last chunk's program into AI and W (build_split_last).""" + pr = self.progs[c] + return pr.build_split_last(acc) if c == self.C - 1 else pr.build_split(acc) + + def _send(self, a, b, x): + """Stage a's activation / cotangent x -> stage b. On the same stage (the + turn of a V placement) it is already where it is needed: no copy, and + nothing a later donation could clobber -- x has no other owner. + + Under multi-controller JAX (`multi`) every process calls this for every + boundary copy of the order, in order: x is None where stage a is not + local (its process passes no source), and the result is None where stage + b is not -- and under transport 'relay' a RelayFuture where it is, which + the consumer's pop resolves (`_RelayBox`).""" + if a == b: + return x + y = self.channels[(a, b)].send_flat([x])[0] + return y if not self.multi or b in self.local else None + + def _hop(self, t, s, x): + """Stage t's gradient sum of squares (a replicated scalar) -> stage s, for + its global-norm clip. Every process, every pair, in order, when the + stages are on different processes; None where s is not local (under + transport 'relay' a RelayFuture where it is, which `step` resolves for + the update). In one process a jax.device_put -- under Pathways with the + native transport a prebuilt Channel's send (cheaper through the proxy; + ppermute builds none, so a jax.device_put there too): one batched copy + either way.""" + if not self.multi: + if (t, s) in self.sq_channels: + return self.sq_channels[(t, s)].send_flat([x])[0] + return jax.device_put(x, NamedSharding(self.meshes[s], P())) + y = self.sq_channels[(t, s)].send_flat([x])[0] + return y if s in self.local else None + + # --------------------------------------------------------- fusion plan + def _prefetch_hosts(self): + """-> ({chunk: [(order index, leaf ids), ...]}, [chunks with no host]). + + Any forward on the stage that runs before chunk b's first forward can + carry a slice of b's gather: take the earliest free ones (1 to + `pf_split`, as many as there are), deadline-first. Chunks gathered in + the update program (gather_slots) need none; the self-prefetched 0F0 + hosts nothing else, and neither half of an F&B pair hosts anything. A + chunk left without a host is the caller's to gather in the update + program. + """ + C, order, place = self.C, self.order, self.place + paired = set(self.fuse) | {j + 1 for j in self.fuse} + used = set() + if self.self_prefetch: + j = order.index((0, "F", 0)) + if j in paired: + raise ValueError(f"0F0 (order[{j}]) gathers its own routed experts: it cannot be half of " "an F&B pair") + used.add(j) + plan, homeless = {}, [] + for s in range(self.S): + fwd_slots = [ + j for j, (c, k, m) in enumerate(order) if k == "F" and place[c] == s and c != C - 1 and j not in paired + ] + need = [ + (order.index((ch.index, "F", 0)), ch.index) + for i, ch in enumerate(self.stage_chunks[s]) + if i not in self.gather_slots[s] + ] + for deadline, b in sorted(need): + hosts = [j for j in fwd_slots if j < deadline and j not in used][: self.pf_split] + if not hosts: + homeless.append(b) + continue + groups = ds_ep.leaf_groups(ds_ep.chunk_shapes(self.scfg, self.chunks[b]), len(hosts), skip=self.direct.get(b, ())) + plan[b] = list(zip(hosts, groups)) + used.update(j for j, _ in plan[b]) + return plan, homeless + + def _visits(self): + """Each stage's visits: maximal runs of one chunk's ops in the stage's + sequence (the fused last chunk's no-op backwards left out) -> per stage + [(chunk, [order index, ...]), ...].""" + out = [] + for s in range(self.S): + vs = [] + for j, (c, k, m) in enumerate(self.order): + if self.place[c] != s or (c == self.C - 1 and k == "B"): + continue + if vs and vs[-1][0] == c: + vs[-1][1].append(j) + else: + vs.append((c, [j])) + out.append(vs) + return out + + def _plan_repeat(self): + """fsdp_scope 'repeat': gather a chunk's weights once per visit (`_visits`) + -> (pf_gathers, release_at, visits, gather_slots, fallback). + + A stage's first visit takes its chunk from the previous step's update + program (gather_slots; chunk 0's routed experts, with self-prefetch, + inside 0F0). Every later visit's gather rides in the last `pf_split` + ops (1 to `pf_split`, as many as there are) of the nearest earlier visit + that has a free one -- a forward, a backward, or the fused last chunk; + not 0F0, which gathers its own experts -- split into leaf groups of + equal bytes; never in an op of an earlier visit of the same chunk. In a + backward visit its last ops are the ones the reduce-scatter plan reaches + last (it takes the first ones after a chunk's last gradient write), so + the next chunk's weights arrive as the previous chunk's accumulator + goes. A visit with no such op keeps its chunk's weights from the + previous visit instead (or, for a chunk's first visit, has the update + program gather them: `fallback`, the summary's to explain). `release_at` + {order index: (chunks,)}: the weights + of a visit's chunk are dropped after its last op, unless the chunk's + next visit keeps them. + + Refuses an order that visits a chunk more than twice a step (a + depth-first one: `gpipe` / `1f1b` at V > 1 and M > S switch chunks + every S microbatches or so): `schedule='breadth'` visits each chunk once + forward and once backward.""" + order, C = self.order, self.C + visits = self._visits() + for s, vs in enumerate(visits): + n = collections.Counter(c for c, _ in vs) + bad = {c: k for c, k in sorted(n.items()) if k > 2} + if bad: + raise ValueError( + f"fsdp_scope 'repeat' gathers a chunk's weights once per visit (a run of its ops on its " + f"stage); this order visits stage {s}'s chunks {bad} (chunk: visits) more than twice a " + "step -- use a breadth-first order (schedule 'breadth')" + ) + self_pf = order.index((0, "F", 0)) if self.self_prefetch else None + gathers, release, slots, fallback = [], {}, [], [] + for s, vs in enumerate(visits): + slots.append((self.slot[vs[0][0]],)) + used, keep = set(), set() + for i in range(1, len(vs)): + c = vs[i][0] + prev = max((k for k in range(i) if vs[k][0] == c), default=None) + hosts, n = [], max(self.pf_split, 0) # pf_split 0: no op hosts a gather, as under 'step' + for k in range(i - 1, -1 if prev is None else prev, -1): + free = [j for j in vs[k][1] if j != self_pf and j not in used] + if free and n: + hosts = free[-n:] + break + if not hosts: + if prev is None: + slots[s] = tuple(sorted(set(slots[s]) | {self.slot[c]})) + fallback.append(c) + else: + keep.add(i) + continue + groups = ds_ep.leaf_groups(ds_ep.chunk_shapes(self.scfg, self.chunks[c]), len(hosts), skip=self.direct.get(c, ())) + gathers.append((c, list(zip(hosts, groups)))) + used.update(j for j, _ in gathers[-1][1]) + for i, (c, js) in enumerate(vs): + nxt = next((k for k in range(i + 1, len(vs)) if vs[k][0] == c), None) + if nxt not in keep: + release.setdefault(js[-1], []).append(c) + return gathers, {j: tuple(cs) for j, cs in release.items()}, visits, slots, sorted(fallback) + + def _plan_overlap(self): + """Fold the once-per-step FSDP collectives into the per-microbatch programs. + + gather: chunk k_{i+1}'s weights are all-gathered inside the first + `pf_split` forwards (1 to `pf_split`, as many as there are) of + other chunks on the same stage that run before k_{i+1}'s first + forward, split into leaf groups of equal bytes (`_prefetch_hosts`, + decided in __init__). The stage's first chunk is gathered by the + previous step's update program -- its routed experts, with + self-prefetch, inside its own first forward F(0, 0) instead -- + and so is any chunk no earlier forward can carry (`pf_fallback`). + Under fsdp_scope 'repeat', once per visit instead + (`_plan_repeat`). + reduce: chunk k's reduce-scatter rides in the next `rs_split` backward + programs on its stage after k's last gradient write, again split + by leaf groups; whatever has no later backward (the chunk that + finishes last) folds it into its own last backward (rs_self) or, + failing that, gets a small standalone program. With + `rs_reserve` (by default under V and interleaved) that last + backward is kept free for rs_self when another chunk would + take it. A split chunk's backward programs here are its W's, + its gradient writers (an I writes none, and the stage upstream + waits on its outputs): a W hosts what a backward hosts, rs_self + in a chunk's last W included -- but a split last chunk's W's, + which host nothing, as its fused program does not: its + reduce-scatter waits for its accumulator's two parts, merged + after its last W (the stage's final reduce). + + Hosts may run in stash mode (the composer builds the stash variants); + no half of an F&B pair hosts anything. The plan is keyed by order index. + """ + C, order, place = self.C, self.order, self.place + shp = lambda c: ds_ep.chunk_shapes(self.scfg, self.chunks[c]) + paired = set(self.fuse) | {j + 1 for j in self.fuse} + if self.self_prefetch: + self.self_pf_at = order.index((0, "F", 0)) + for b, hosts in self.pf_gathers: # from _prefetch_hosts / _plan_repeat + for j, g in hosts: + self.pf[j] = (b, g) + self.pf_n[j] = len(hosts) + if self.scfg.grad_reduce == "microbatch": + # Every backward already reduce-scattered its own gradient; the stage's + # final program only computes the norm the global clip needs. + self.final_slots = [tuple(range(len(self.stage_chunks[s]))) for s in range(self.S)] + for s in range(self.S): + self.stages[s].reduce_final(self.final_slots[s], 0) + return + last, first = self.last_writer, self.first_writer + + def can_rs_self(j): + c, k, _ = order[j] + return c != C - 1 and k in ("B", "W") and j != first[c] and j not in paired + + def hosts_on(s, reserve): + """Stage s's reduce-scatter hosts -> ({host: (chunk, leaf ids)}, + {chunk: groups}, leftover slots), chunks taken in the order they finish. + `reserve`: keep the stage's last gradient write out of it.""" + rs_at, n_groups, left, taken = {}, {}, [], set() + stop = max(last[c] for c in last if place[c] == s) + for c in sorted((c for c in last if place[c] == s), key=lambda c: last[c]): + hosts = [ + j + for j in range(last[c] + 1, len(order)) + if order[j][1] in ("B", "W") # a gradient writer: a B, or a split chunk's W + and order[j][0] != C - 1 + and place[order[j][0]] == s + and j not in taken + and j not in paired + and not (reserve and j == stop) + ][: self.rs_split] + if not hosts: + left.append(self.slot[c]) + continue + groups = ds_ep.leaf_groups(shp(c), len(hosts)) + n_groups[c] = len(groups) + for j, g in zip(hosts, groups): + taken.add(j) + rs_at[j] = (c, g) + return rs_at, n_groups, tuple(sorted(left)), stop + + for s in range(self.S): + if s in self.sync_stages and s != place[0]: + # Synchronous collectives (no SparseCore offload on this strip): a + # reduce-scatter folded into a backward lengthens it, and with it the + # cotangent the stage upstream waits for. This stage idles in the + # drain after its last backward: reduce every chunk there instead. + self.final_slots[s] = tuple(range(len(self.stage_chunks[s]))) + continue + rs_at, n_groups, left, stop = hosts_on(s, False) + # rs_self: a stage whose only leftover is the chunk that finishes last + # folds that reduce-scatter into the chunk's own last backward (a plain + # accumulating one) instead of a trailing standalone program; it sums the + # stage's partial sumsqs, which all come from earlier programs. With + # rs_reserve (V's default), if another chunk's groups took that backward + # (under V the head finishes on stage 0 before chunk 0 does), keep it free + # for rs_self instead -- where the other chunk still finds hosts without + # it. Off for circular: it would change the plans circular placement has + # always made (timed and search at the first TPU7x benchmark + # configurations, 1f1b / gpipe, and the greedy order since removed: one + # standalone program fewer, one host fewer for the other chunk, and the + # stage sumsq summed in another order -- the global norm moves in the last + # bit). + rs_self_here = self.rs_self_enabled and (self.rs_self_policy == "all" or s == place[0]) + if self.rs_reserve and rs_self_here and can_rs_self(stop): + alt = hosts_on(s, True) + if (len(left) != 1 or stop in rs_at) and alt[2] == (self.slot[order[stop][0]],): + rs_at, n_groups, left, stop = alt + elif self.rs_self_policy == "first" and s != place[0]: + # The point of 'first': the backward that emits this stage's last + # cotangent carries no reduce-scatter -- not another chunk's either. + rs_at, n_groups, left, stop = hosts_on(s, True) + self.rs_at.update(rs_at) + self.rs_groups.update(n_groups) + self.n_partial_sq[s] = sum(n_groups.values()) + self.final_slots[s] = left + if rs_self_here and can_rs_self(stop) and stop not in rs_at and left == (self.slot[order[stop][0]],): + self.rs_self[stop] = self.n_partial_sq[s] + self.final_slots[s] = () + for s in range(self.S): + if self.final_slots[s]: + self.stages[s].reduce_final(self.final_slots[s], self.n_partial_sq[s]) # build it now + + def gathering_forwards(self): + """{order index: [(chunk, leaf id)]}: the forwards of the fusion plan that + gather -- each prefetch host the leaves of its group, the self-prefetch + chunk 0's routed experts. Not the backwards and fused last chunk that + host a gather under fsdp_scope 'repeat': no pin reaches into those.""" + hosts = { + j: [(b, i) for i in g] + for j, (b, g) in self.pf.items() + if self.order[j][1] == "F" and self.order[j][0] != self.C - 1 + } + if self.self_pf_at is not None: + hosts.setdefault(self.self_pf_at, []).extend((0, i) for i in self.routed_leaves) + return dict(sorted(hosts.items())) + + def joint_gather_allreduce(self): + """Does libtpu compile a stage's gather over both mesh axes to an + all-reduce (`ds_ep.pin_gather_ms`)? In a program compiled for several + slices it does (its all-gather decomposer), unless LIBTPU_INIT_ARGS + prefers async all-gathers (--xla_tpu_prefer_async_allgather_to_allreduce, + the libtpu set 'prefag' of the 2 x v5p-128 runs), read as libtpu reads it: its last + mention, in any absl spelling (libtpu_flag). The slices are + counted among all the devices of the meshes' client -- the job's, or a + compile-only topology's, whose second slice's stages ds_ep_aot compiles + on the first slice's devices -- else among the meshes' own. Not on v6e + (ds_ep.NATIVE_JOINT_GATHER_KINDS), whose multi-slice programs gather such + a leaf natively.""" + devs = [d for m in self.meshes for d in m.devices.flat] + if all(str(getattr(d, "device_kind", "")) in ds_ep.NATIVE_JOINT_GATHER_KINDS for d in devs): + return False + client = getattr(devs[0], "client", None) + pool = list(client.devices()) if client is not None else devs + slices = {slice_index(d) for d in pool} - {None} + prefer = libtpu_flag("xla_tpu_prefer_async_allgather_to_allreduce") is True + return len(slices) > 1 and not prefer + + def pin_model(self, stage): + """The ds_ep.PinModel 'auto' plans `stage`'s forwards with: its devices' + kind's (ds_ep.PIN_MODELS: v5p's or v6e's), else -- off TPU, a kind none + was calibrated on, or a stage of mixed kinds -- v5p's, ds_ep.PIN_MODEL + (`_plan_pins` warns on a TPU).""" + kinds = {str(getattr(d, "device_kind", "")) for d in self.meshes[stage].devices.flat} + kind = kinds.pop() if len(kinds) == 1 else None + return ds_ep.PIN_MODELS.get(kind, ds_ep.PIN_MODEL) + + def _plan_pins(self): + """({order index: ((point, layer, chunk, leaf id), ...)}, {order index: + why none}): the prefetch pins of every forward that gathers + (`gathering_forwards`) under `prefetch_pin` -- a SPEC's points for the + leaves it names (ds_ep.pin_of), or 'auto''s plan (ds_ep.plan_pins: the + leaves' gathers and the forward's compute windows estimated with the host + stage's `pin_model`, each gather in the window it loads least) -- and why + each other gathering forward has none, for the summary. A forward in + stash mode is left unpinned: it runs its layers inside jax.vjp, whose + trace a pin would leave -- and so, under fsdp_scope 'repeat', is a + backward or the fused last chunk that hosts a gather (listed with the + unpinned forwards). 'auto' prices async SparseCore collectives + (ds_ep.PinModel): it plans only for the stages whose FSDP collectives are + lax ones ('xla') libtpu offloads -- not for collective-permutes, nor for + `sync_stages`, whose gathers block the TensorCore wherever they sit: a + pin there would hide nothing, only hold the gathered weights longer (and + compile the program with barrier removal off).""" + spec = self.prefetch_pin + if spec == "off": + return {}, {} + tokens = self.rows * self.row_len // (self.scfg.fsdp * self.scfg.ep) # a device's: whole rows of seq / cp + joint = self.joint_gather_allreduce() + out, why = {}, {} + fwd = self.gathering_forwards() + for j in self.pf.keys() - fwd.keys(): + why[j] = "the fused last chunk" if self.order[j][0] == self.C - 1 else "a backward" + for j, leaves in fwd.items(): + c, _, m = self.order[j] + host = self.chunks[c] + if self.modes.get((c, m)): + why[j] = "stash mode" + elif spec == "auto" and self.stage_scfg[host.stage].fsdp_collectives != "xla": + why[j] = "collective-permute FSDP collectives" + elif spec == "auto" and host.stage in self.sync_stages: + why[j] = "synchronous FSDP collectives" + elif spec == "auto" and not host.n_moe: + why[j] = "dense layers only: no pin points" + if j in why: + continue + if spec == "auto": + own = tuple((b, i) for b, i in leaves if b == c) + plan = ds_ep.plan_pins( + self.stage_scfg[host.stage], + host, + [(self.chunks[b], i) for b, i in leaves], + tokens, + joint_allreduce=joint, + own=own, + model=self.pin_model(host.stage), + seq=self.seq, + ) + else: + plan = [] + for b, i in leaves: + hit = ds_ep.pin_of(spec, self.leaf_names[b][i], b) + if hit is None or not ds_ep.has_gather(self.chunks[b], i): + continue + if hit[1] >= host.n_moe: # the points are in MoE layers: a dense layer has none + raise ValueError( + f"--prefetch-pin: {self.leaf_names[b][i]} (chunk {b}) is pinned in layer {hit[1]} of " + f"{self.op_name(j)}, whose chunk {c} has {host.n_moe} MoE layer(s)" + ) + plan.append((*hit, b, i)) + if plan: + out[j] = tuple(sorted(plan)) + else: + why[j] = "no window holds one of its gathers" if spec == "auto" else "none of its gathered leaves named" + if spec == "auto" and out: + odd = pin_model_mismatch(self.meshes[self.chunks[self.order[j][0]].stage].devices.flat[0] for j in out) + if odd: + warnings.warn( + f"--prefetch-pin auto: its costs (ds_ep.PIN_MODELS) are calibrated on v5p and v6e, not " + f"{', '.join(odd)}: it estimates the windows and the gathers at v5p's rates, and on a faster " + "chip may tie more to a window than its compute covers (every leaf at hn replayed 4.3 ms slower " + "on v5p); check the plan in the summary, or pin with a SPEC", + RuntimeWarning, + ) + return out, why + + def pin_summary(self): + """The prefetch pins in a line ('' under 'off', or without the fusion + plan): each pinned forward's points and the leaves pinned there, by name, + then every gathering program left unpinned and why (`_plan_pins`) -- + 'none' first where no forward took a pin, so the log of a run asked for + pins says when it ran without them.""" + if self.prefetch_pin == "off" or not self.overlap: + return "" + parts = [] + for j, plan in sorted(self.pins.items()): + by = collections.defaultdict(list) + for pt, layer, c, i in plan: + by[(ds_ep.PIN_POINTS.index(pt), layer)].append(f"c{c}.{self.leaf_names[c][i]}") + parts.append( + f"{self.op_name(j)} " + + " ".join(f'{ds_ep.PIN_POINTS[p]}{f"@{l}" if l else ""}=' + ",".join(v) for (p, l), v in sorted(by.items())) + ) + if not parts: + parts = ["none" if self.unpinned else "none (no forward gathers)"] + rest = ", ".join(f"{self.op_name(j)} ({why})" for j, why in sorted(self.unpinned.items())) + what = "auto" if self.prefetch_pin == "auto" else "spec" + return f" prefetch pins ({what}): " + "; ".join(parts) + (f"; unpinned: {rest}" if rest else "") + + # ------------------------------------------------------- op descriptors + def ops(self, overlap=None): + """The order as the step loop runs it (cached): one `Op` per entry, with + the descriptor of its program -- the part of its kind in its mode, plus + whatever the fusion plan folds into it when `overlap`.""" + overlap = self.overlap if overlap is None else bool(overlap) + if overlap and not self.overlap: + raise ValueError("this pipeline was built without overlap: it has no fusion plan") + if overlap in self._ops: + return self._ops[overlap] + pd, C, out = ds_ep.pdesc, self.C, [] + # A gather rides after the op's own part (and a backward's reduce-scatter) + # a gather of the whole chunk takes no leaf list (the program the first plans named); one host's group of fewer + # leaves -- the chunk's routed experts read in place (`direct`) -- names them + gather = lambda j, pf: ( + pd( + "G", other=self.chunks[pf[0]], leaves=pf[1] if self.pf_n[j] > 1 or len(pf[1]) < self.n_leaves[pf[0]] else None + ), + ) + w_at = {(c, m): j for j, (c, k, m) in enumerate(self.order) if k == "W"} # each split (chunk, microbatch)'s W + # a split last chunk's accumulator is two parts, its F's (AI's) and its W's, each started by its first writer + last_w0 = next((j for j, (c, k, _) in enumerate(self.order) if c == C - 1 and k == "W"), None) + for j, (c, k, m) in enumerate(self.order): + s, md = self.place[c], self.modes.get((c, m)) + acc = self._writes(c, k) and j != self.first_writer[c] + pf = self.pf.get(j) if overlap else None + if c == C - 1: + if k == "B": + out.append(Op(j, c, k, m, s)) + elif k == "F": + kind = "AI" if self.split_last else "A" + out.append(Op(j, c, k, m, s, (pd(kind, acc=acc),) + (gather(j, pf) if pf else ()), acc, pf=pf)) + else: # the split last chunk's W: its layers' weight gradients, its accumulator's deferred part + acc = j != last_w0 + out.append(Op(j, c, k, m, s, (pd("W", acc=acc),) + (gather(j, pf) if pf else ()), acc, pf=pf)) + continue + if k == "F": + self_pf = overlap and j == self.self_pf_at + pin = self.pins.get(j) if overlap else None + desc = (pd("F", stash=md, self_leaves=self.routed_leaves if self_pf else None, pin=pin),) + if pf: + desc += gather(j, pf) + out.append(Op(j, c, k, m, s, desc, stash=md, self_pf=self_pf, pf=pf, pin=pin)) + elif k == "B": + rs = self.rs_at.get(j) if overlap else None + rs_self = self.rs_self.get(j) if overlap else None + desc = (pd("B", stash=md, acc=acc, rs_self=rs_self),) + if rs: + desc += (pd("R", other=self.chunks[rs[0]], leaves=rs[1] if self.rs_groups[rs[0]] > 1 else None),) + if pf: + desc += gather(j, pf) + out.append(Op(j, c, k, m, s, desc, acc, md, rs=rs, rs_self=rs_self, pf=pf)) + elif k == "I": + # the split backward's input gradient: dx and the W buffer -- one program for either W, unless in-place dW + # cut the accumulating W its own I (ds_ep.Split.i_acc) + acc = w_at[(c, m)] != self.first_writer[c] + desc = (pd("I", acc=self.progs[c].build_split(acc).i_acc),) + (gather(j, pf) if pf else ()) + out.append(Op(j, c, k, m, s, desc, acc, pf=pf)) + else: + # W: the weight gradients, the split chunk's one gradient writer -- so, as a B is, a host of reduce-scatters + # (another chunk's, or with rs_self its own), and a better one: nothing waits on its outputs + rs = self.rs_at.get(j) if overlap else None + rs_self = self.rs_self.get(j) if overlap else None + desc = (pd("W", acc=acc, rs_self=rs_self),) + if rs: + desc += (pd("R", other=self.chunks[rs[0]], leaves=rs[1] if self.rs_groups[rs[0]] > 1 else None),) + if pf: + desc += gather(j, pf) + out.append(Op(j, c, k, m, s, desc, acc, rs=rs, rs_self=rs_self, pf=pf)) + for j in sorted(self.fuse): + # One program of both: the F's part (A for the last chunk) and then the + # backward's, taken from its own chunk (`peer`) on the same stage mesh. + # The plan folds nothing into either half. + f, b = out[j], out[j + 1] + if len(f.desc) != 1 or len(b.desc) != 1 or f.self_pf or b.rs_self is not None: + raise AssertionError(f"the fusion plan put a collective into the pair at order[{j}]") + ((kind, kw),) = b.desc + peer = self.progs[b.c] if b.c != f.c else None + out[j] = dataclasses.replace(f, pair=f.desc + (pd(kind, peer=peer, **dict(kw)),)) + self._ops[overlap] = out + return out + + def issue_order(self, overlap=None): + """The indices of `ops(overlap)` in the order the step loop issues them (cached): the order's own, but each + stage's trailing W's -- its W's after its last other op -- after every other op, in the order's order. Every + stage runs its ops in the same order either way, so the results are the same bit for bit; an order without W's is + issued as it is. + + Nothing in the loop waits on a trailing W: its outputs are its chunk's accumulator, what it reduce-scatters and + its stage's sum of squares, all read after the loop. Under McJAX the one dispatch thread allocates a program's + outputs as it issues it, and where a split stage's HBM runs out it does at its last W, which folds the + reduce-scatter (rs_self) and writes the gradients into new buffers: libtpu waits for the stage's queued programs + to finish and defragments (TpuClient::DefragmentMemory: 0.6-0.7 s of the dispatch thread at DeepSeek-V3 widths + on TPU7x without `_pace`), and every op issued after the W waits with it -- in the order's own position, the + other stages' last backwards. Issued last, it holds back only what follows the loop.""" + overlap = self.overlap if overlap is None else bool(overlap) + if overlap not in self._issue: + ops = self.ops(overlap) + last = {} # stage -> its last op but a W + for op in ops: + if op.kind != "W": + last[op.s] = op.j + tail = [op.j for op in ops if op.kind == "W" and op.j > last.get(op.s, -1)] + moved = set(tail) + self._issue[overlap] = [op.j for op in ops if op.j not in moved] + tail + return self._issue[overlap] + + def program(self, op): + """The callable `op` runs: its precompiled executable, else the jitted + composition of its parts (`ChunkPrograms.program`). For the first op of + an F&B pair that is the pair's one program (`op.pair`).""" + desc = op.pair or op.desc + exe = self._exe.get((op.c, desc)) + return exe if exe is not None else self.progs[op.c].program(desc) + + def dispatched(self, overlap=None): + """(chunk, descriptor) of every per-microbatch program one step + dispatches, in order: an F&B pair once (its first op's chunk and the + composed descriptor), the fused last chunk's no-op backward never.""" + return [(op.c, op.pair or op.desc) for op in self.ops(overlap) if op.desc is not None and op.j - 1 not in self.fuse] + + def program_at(self, j, overlap=None): + return self.program(self.ops(overlap)[j]) + + # ---------------------------------------------------------- precompile + def _avals(self, s, kind, chunk=None, slots=None): + """Abstract (sharded) arguments, for ahead-of-time lowering.""" + scfg, mesh = self.scfg, self.meshes[s] + cfg = scfg.model + sds = lambda shape, dt, spec: jax.ShapeDtypeStruct(shape, dt, sharding=NamedSharding(mesh, spec)) + + def tree(shapes, specs, dt): + if not isinstance(dt, dict): + dt = jax.tree.map(lambda _: dt, shapes, is_leaf=ds_ep._is_shape) + return jax.tree.map(lambda sh, sp, d: sds(sh, d, sp), shapes, specs, dt, is_leaf=ds_ep._is_shape) + + ch = chunk + if kind == "compute": + return tree( + ds_ep.chunk_shapes(scfg, ch), ds_ep.chunk_wc_specs(scfg, ch), ds_ep.leaf_dtype_tree(scfg, ch, "compute") + ) + if kind == "storage": + return tree(ds_ep.chunk_shapes(scfg, ch), ds_ep.chunk_storage_specs(ch), ds_ep.leaf_dtype_tree(scfg, ch, "storage")) + if kind == "grads": # the expert-count leaves stay fp32 (ds_ep.scatter_tree) + dts = jax.tree.map(lambda k: jnp.dtype(jnp.float32 if k else scfg.rs_dtype), ds_ep.count_mask(ch)) + return tree(ds_ep.chunk_shapes(scfg, ch), ds_ep.chunk_storage_specs(ch), dts) + if kind == "gacc": + return tree(ds_ep.acc_shapes(scfg, ch), ds_ep.acc_specs(scfg, ch), scfg.acc_dtype) + if kind == "act": + return sds((self.rows, self.row_len, cfg.emb_dim), cfg.dtype, P(ds_ep.FE, None, None)) + if kind == "tok": + return sds((self.rows, self.row_len), jnp.int32, P(ds_ep.FE, None)) + if kind == "scalar_i": + return sds((), jnp.int32, P()) + if kind == "scalar_f": + return sds((), jnp.float32, P()) + if kind == "loss": + return sds((scfg.fsdp * scfg.ep,), jnp.float32, P(ds_ep.FE)) + raise ValueError(kind) + + def _desc_avals(self, c, desc): + """Abstract arguments of `progs[c].program(desc)`: each part's, in turn + (the argument lists of `ChunkPrograms.part`).""" + A, out = self._avals, [] + for kind, kw in desc: + kw = dict(kw) + pr = kw.get("peer", self.progs[c]) + ch = pr.ch + s = ch.stage + w, x, i32 = A(s, "compute", ch), A(s, "tok" if ch.first else "act"), A(s, "scalar_i") + if kind == "F" and "self_leaves" in kw: + idx = kw["self_leaves"] + cl, sl = jax.tree.leaves(w), jax.tree.leaves(A(s, "storage", ch)) + out += [[cl[i] for i in range(len(cl)) if i not in idx], x, i32, [sl[i] for i in idx]] + elif kind == "F": + out += [w, x, i32] + elif kind == "B": + out += [w, x, tuple(pr.res_avals)] + out += [pr.stash_avals[kw["stash"]]] if "stash" in kw else [] + out += [A(s, "act")] + ([A(s, "gacc", ch)] if kw.get("acc") else []) + [i32] + out += [[A(s, "scalar_f")] * kw["rs_self"]] if "rs_self" in kw else [] + elif kind == "I": # the split backward's halves (ds_ep.Split): I takes a B's arguments but the accumulator + out += [w, x, tuple(pr.res_avals), A(s, "act"), i32] + elif kind == "W" and ch.last: # ... the split last chunk's W: the accumulator's deferred part, its leaves + sp = pr.build_split_last(kw.get("acc", False)) + gl = jax.tree.leaves(A(s, "gacc", ch)) + out += [sp.crossing_avals, sp.kept_avals] + ([tuple(gl[i] for i in sp.w_leaves)] if kw.get("acc") else []) + elif kind == "W": # ... W the crossing set and the arguments of I it reads, then a B's accumulator and sumsqs + sp = pr.build_split(kw.get("acc", False)) + out += [sp.crossing_avals, sp.kept_avals] + ([A(s, "gacc", ch)] if kw.get("acc") else []) + out += [[A(s, "scalar_f")] * kw["rs_self"]] if "rs_self" in kw else [] + elif kind in ("A", "AI"): # the fused last chunk, or split (AI: the accumulator's kept part, its leaves) + out += [w, x, A(s, "tok")] + [A(s, "tok")] * bool(pr.mtp) + g = A(s, "gacc", ch) + if kind == "AI": + gl = jax.tree.leaves(g) + g = tuple(gl[i] for i in pr.build_split_last(kw.get("acc", False)).i_leaves) + out += ([g, A(s, "loss")] if kw.get("acc") else []) + [i32] + elif kind in ("G", "R"): + lv = jax.tree.leaves(A(s, "storage" if kind == "G" else "gacc", kw["other"])) + out.append([lv[i] for i in kw.get("leaves", range(len(lv)))]) + else: + raise ValueError(f"no avals for part {kind!r}") + return tuple(out) + + def precompile(self, threads=64, agree=None): + """Lower every program, one at a time in job order in this thread, + compile them concurrently (XLA compiles release the GIL), and swap the compiled + executables in for the jitted functions. + + The per-microbatch programs are the distinct descriptors `dispatched` + lists -- every mode, host variant and F&B pair the order uses, each once -- + and the stage programs of the update / reduce side. Calling a + `Compiled` costs the same dispatch as a jit call, and holding it + sidesteps the jit / persistent caches re-keying a program whose lowered + HLO is identical (observed: a few programs recompiled on first use). + + Only the compiles run in the thread pool, each as soon as its program is + lowered: tracing is not thread-safe here (on 2 x TPU7x-4x4x4 one host + even raised "Store occupied" in tokamax splash attention's custom VJP, + jax 0.11.1). tokamax's splash kernel keeps + its mask tables in a functools.lru_cache, which two threads missing at + once each fill with a copy of their own -- so a program traced beside + another can hold two equal copies of a table where a program traced + alone holds one: the same values, other constants, another executable + (TPU v4: another fingerprint; on CPU most programs of a tokamax pipeline + lowered to one of several HLOs from run to run, + ds_ep_test.PrecompileIsDeterministic). Across the processes of a stage + that is another program at one launch, and the TPU runtime halts it ('an + unexpected peer shows up in the launch group with a different launch + id'). jax's splash kernel is a jit, which jax traces once per process + whatever the threads; but a trace jax caches keeps the source locations + of whichever program traced it first, and a Mosaic kernel carries them in + its body (megablox's, lowered for TPU: their text differed from run to + run too, their executables not). + + `program_prints` keeps (name, stage, lowered, executable) per program: + the sha256 of its lowered text with the text's size and constant / func + counts ({'sha', 'bytes', 'consts', 'funcs'}), and the sha256 of its + executable's fingerprint, the runtime's launch-id seed (None off TPU: + `executable_print`). `agree(prints, what)`, if given, gets this + process's [(name, stage, fingerprint, stats)] as soon as every program is + lowered (what='lowered', the compiles running on) and once they are + compiled ('executables'), before anything is installed: main passes + `check_program_agreement` across processes, so that a stage whose + processes hold different programs stops before its first launch, naming + them. + """ + import concurrent.futures as cf + + try: # private: without it every program shares this thread's context, so each compiles here + from jax._src.interpreters.mlir import _thread_local_context as mlir_ctx + except ImportError: + mlir_ctx = None + jobs = [] # (fn, args, install(compiled), stage) + A = self._avals + + def attr(obj, name): + return lambda c: setattr(obj, name, c) + + # every distinct per-microbatch program the step loop dispatches (on this + # process's stages) + for key in dict.fromkeys(self.dispatched()): + if not self._runs(self.place[key[0]]): + continue + + def put(cmp, key=key): + self._exe[key] = cmp + + jobs.append((self.progs[key[0]].program(key[1]), self._desc_avals(*key), put, self.place[key[0]])) + for s, st in enumerate(self.stages): + if not self._runs(s): + continue + chs = self.stage_chunks[s] + params = [A(s, "storage", c) for c in chs] + grads = [A(s, "grads", c) for c in chs] + opt = { + "mu": jax.tree.map(lambda a: jax.ShapeDtypeStruct(a.shape, st.adam["mu_dtype"], sharding=a.sharding), params), + "nu": params, + "count": A(s, "scalar_i"), + } + sqs = [A(s, "scalar_f") for _ in range(self.S)] + if self.overlap: + fs, npq = self.final_slots[s], self.n_partial_sq[s] + + def put_final(cmp, st=st, fs=fs, npq=npq): + st._final[(fs, npq)] = cmp + + jobs.append((st.gather_first, (params,), attr(st, "gather_first"), s)) + if fs: + jobs.append( + ( + st.reduce_final(fs, npq), + ([A(s, "gacc", chs[i]) for i in fs], [A(s, "scalar_f") for _ in range(npq)]), + put_final, + s, + ) + ) + jobs.append((st.update_gather, (params, opt, grads, sqs, A(s, "scalar_f")), attr(st, "update_gather"), s)) + else: + # every step gathers all the stage's compute weights; init_state the first ones + jobs.append((st.gather, (params,), attr(st, "gather"), s)) + jobs.append((st.gather_first, (params,), attr(st, "gather_first"), s)) + jobs.append((st.reduce, ([A(s, "gacc", c) for c in chs],), attr(st, "reduce"), s)) + jobs.append((st.update, (params, opt, grads, sqs, A(s, "scalar_f")), attr(st, "update"), s)) + # the boundary copies' collective-permute programs (transport 'ppermute') of + # this process's stages: each runs on both stages' devices + for (a, b), ch in [*self.channels.items(), *self.sq_channels.items(), *self.tie_channels.items()]: + if isinstance(ch, transfer.PermuteChannel) and (self._runs(a) or self._runs(b)): + jobs.append((ch.prog, ch.lower_args(), attr(ch, "prog"), (a, b))) + # MTP's tied embedding (`_tie`): the sum of its two gradients on chunk 0's stage and on the last chunk's + if self.mtp: + cfg = self.scfg.model + for s, keep in ((self.place[0], True), (self.place[self.C - 1], False)): + if not self._runs(s): + continue + emb = jax.ShapeDtypeStruct( + (cfg.vocab_size, cfg.emb_dim), self.scfg.rs_dtype, sharding=NamedSharding(self.meshes[s], P(None, ds_ep.FE)) + ) + + def put_tie(cmp, key=("tie", s, keep)): + self._exe[key] = cmp + + jobs.append((self._tie_sum(s, keep), (emb, emb, A(s, "scalar_f")), put_tie, s)) + t0 = time.perf_counter() + self.compiled = [] # (program name, Compiled), for mem_report + self.compiled_stage = [] # the stage of each: an int, or (a, b) for a boundary copy over both + self.compile_times = [] # (lower s, compile s) of each + self.program_prints = [] # (name, stage, lowered, executable) of each + names = [getattr(f, "__name__", "?") for f, _, _, _ in jobs] + + def compile_(lo): + t1 = time.perf_counter() + return lo.compile(), time.perf_counter() - t1 + + # The first failure ends it, naming the program, as soon as it is seen + # (a compile's before the next lowering): no waiting for the compiles + # still running or queued (no `with`, whose exit would join them). The + # rest install in job order. + ex = cf.ThreadPoolExecutor(threads) + futs, done, lowered, t_lower = {}, [None] * len(jobs), [None] * len(jobs), [None] * len(jobs) + + def stop(i, e, what="compiling"): + ex.shutdown(wait=False, cancel_futures=True) + if i is not None: + e.add_note(f"precompile: {what} {names[i]} (stage {jobs[i][3]}) failed") + + def collect(block): + """The finished compiles' results (every one's, if `block`).""" + for fu in cf.as_completed(list(futs)) if block else [fu for fu in futs if fu.done()]: + i = futs.pop(fu) + try: + done[i] = fu.result() + except BaseException as e: + stop(i, e) + raise + + if agree is not None: # multi-controller JAX (main: check_program_agreement across processes) + + def agreed(what, prints): + try: + agree(prints, what) + except BaseException as e: + stop(None, e) + raise + + for i, (f, a, _, _) in enumerate(jobs): + collect(block=False) + t1 = time.perf_counter() + try: + if mlir_ctx is not None: + mlir_ctx.set_local(None) # a context of its own: its compile thread is then its only user + lo = f.lower(*a) + lowered[i] = lowered_print(lo) # before its compile reads the module in another thread + except BaseException as e: + stop(i, e, "lowering") + raise + t_lower[i] = time.perf_counter() - t1 + if mlir_ctx is None: # the next lowering would share its context: no compile beside it + try: + done[i] = compile_(lo) + except BaseException as e: + stop(i, e) + raise + else: + futs[ex.submit(compile_, lo)] = i + del lo + if agree is not None: + agreed("lowered", [(n, s, lw["sha"], lw) for n, (_, _, _, s), lw in zip(names, jobs, lowered)]) + collect(block=True) + ex.shutdown() + execs = [executable_print(c) for c, _ in done] + if agree is not None: + agreed("executables", [(n, s, x, None) for n, (_, _, _, s), x in zip(names, jobs, execs) if x is not None]) + for n, (_, _, put, s), (c, tc), tl, lw, x in zip(names, jobs, done, t_lower, lowered, execs): + self.compiled.append((n, c)) + self.compiled_stage.append(s) + self.compile_times.append((tl, tc)) + self.program_prints.append((n, s, lw, x)) + put(c) + return len(jobs), time.perf_counter() - t0 + + def mem_report(self, state=None, top=8): + """Compile-time memory of the largest programs, and the persistent state + per device -- where HBM goes, before anything runs.""" + G = 2**30 + rows = [] + for name, c in getattr(self, "compiled", []): + m = c.memory_analysis() + if m is not None: + rows.append((m.temp_size_in_bytes, m.argument_size_in_bytes, m.output_size_in_bytes, m.alias_size_in_bytes, name)) + lines = [ + f" largest program temporaries (GiB per device): " + + ", ".join(f"{n} {t / G:.2f}" for t, _, _, _, n in sorted(rows, reverse=True)[:top]) + ] + if state: + for label, tree in state.items(): + per = collections.Counter() + for a in jax.tree.leaves(tree): + for sh in getattr(a, "addressable_shards", []): + per[sh.device.id] += sh.data.nbytes + if per: + lines.append( + f" {label:28s} per device GiB: max {max(per.values()) / G:6.2f} " + + " ".join(f"{d}:{v / G:.1f}" for d, v in sorted(per.items())) + ) + return "\n".join(lines) + + def plan_summary(self): + if not self.overlap: + return " overlap: off (stage-level gather / reduce programs)" + ( + "; --prefetch-pin: no forward gathers, nothing to pin" if self.prefetch_pin != "off" else "" + ) + name = self.op_name + pf = ", ".join(f"{name(j)}<-AG c{b}[{len(g)}]" for j, (b, g) in sorted(self.pf.items())) + rs = ", ".join(f"{name(j)}<-RS c{c}[{len(g)}]" for j, (c, g) in sorted(self.rs_at.items())) + if self.scfg.grad_reduce == "microbatch": + rs = "every backward reduce-scatters its own microbatch gradient (grad_reduce=microbatch)" + + fin = "; ".join( + f"s{s}: RS c{[self.stage_chunks[s][i].index for i in f]}" for s, f in enumerate(self.final_slots) if f + ) + fin += "".join(f"; {name(j)}<-RS self" for j in sorted(self.rs_self)) + upd = ", ".join(f"s{s}: c{[self.stage_chunks[s][i].index for i in g]}" for s, g in enumerate(self.gather_slots)) + if self.pf_fallback: + why = ( + "no earlier forward on the stage to prefetch in" + if self.fsdp_scope == "step" + else "no op of an earlier visit on the stage to gather in" + ) + upd += f" (c{self.pf_fallback}: {why})" + if self.self_prefetch: + upd += f"; routed experts of c0 gathered inside {name(self.self_pf_at)}" + if self.direct: + upd += f"; routed experts of c{sorted(self.direct)} read in place (fsdp 1: no compute copy)" + + rel = "" + if self.fsdp_scope == "repeat": + rel = "\n fsdp_scope repeat (weights per visit): released after " + ", ".join( + f"{name(j)} c{list(cs)}" for j, cs in sorted(self.release_at.items()) + ) + pins = self.pin_summary() + return f" overlap: {pf}\n {rs}\n standalone: {fin}; " f"gathered in update: {upd}{rel}" + ( + f"\n{pins}" if pins else "" + ) + + def op_name(self, j): + """order[j] as the summaries print it: '2F3', or '2F3s' in stash mode.""" + c, k, m = self.order[j] + return f"{c}{k}{m}" + ("s" if (c, m) in self.modes and k in ("F", "B") else "") + + def peak_stash_gib(self, temps=False): + """Peak live stash per stage (GiB per device), walking the order -- what + the budget holds. `temps`: plus what each stash backward holds in + temporaries over a remat one (`sched.STASH_BWD_TEMP`), while its own set + is still live: the bound on how much the step's peak grows over a remat + step (schedule.py's stash note).""" + size = lambda c, md: 0 if md == "r" else self.stash_bytes[md][c] + temp = lambda c, md: 0 if md == "r" else sched.STASH_BWD_TEMP[md] * self.stash_bytes[md][c] + return [b / 2**30 for b in sched.peak_bytes(self.order, self.place, self.modes, size, temp if temps else None)] + + def peak_wbuf_gib(self): + """Peak live W buffers per stage (GiB per device), walking the order: a split chunk's I -- a split last chunk's F + (AI) -- leaves one (`wbuf_bytes`: its crossing set and the arguments its W reads) and its W consumes it -- what + zb_wbuf_cap bounds in number (sched.peak_wbufs).""" + live, peak = [0] * self.S, [0] * self.S + for c, k, _ in self.order: + s = self.place[c] + if k == "I" or (k == "F" and c == self.C - 1 and self.split_last): + live[s] += self.wbuf_bytes[c] + peak[s] = max(peak[s], live[s]) + elif k == "W": + live[s] -= self.wbuf_bytes[c] + return [b / 2**30 for b in peak] + + def zb_sims(self): + """The microbatch loop simulated (sched.timed_simulate, this pipeline's program costs) for this order and, on + the same placement, 1F1B's and breadth's -> {name: ms}: what the zero-bubble schedules are measured against.""" + C, M, place = self.C, self.M, self.place + cost = sched.cost_table(self.costs, C) + orders = {"order": self.order, "1f1b": sched.one_f_one_b(C, M, place), "breadth": sched.breadth_first(C, M, place)} + return { + name: round(sched.timed_simulate(o, place, cost, self.costs["xfer"], fuse_last=True)[0], 3) + for name, o in orders.items() + } + + def zb_record(self): + """The run record's 'zb' block (main), under a split backward (None otherwise): the split chunks; each one's W + buffer (GiB per microbatch per device) and what it holds -- the crossing set's bytes, the arguments of I its W + reads (Split.kept) -- and the cut's size; the cap on pending W buffers; whether the step loop paces the I's (a + TPU VM's own client, McJAX: `pace_i`; Pathways' is not paced); per stage the peak pending W buffers and their + GiB, per chunk the peak residual sets; the I / W costs the schedule was priced with; and the simulated microbatch + loop of this order against 1F1B's and breadth's (`zb_sims`).""" + if not self.split_chunks: + return None + chunks = {} + cost = sched.cost_table(self.costs, self.C) + for c in self.split_chunks: + sp = self.split_of(c) + last = c == self.C - 1 # the split last chunk: AI (its F + I) and W + chunks[str(c)] = { + "wbuf_gib": self.wbuf_bytes[c] / 2**30, + "crossing_bytes": sp.bytes, + "kept_bytes": sp.kept_bytes, + "kept": [list(k) for k in sp.kept], + "crossing": len(sp.crossing_local), + "stats": dict(sp.stats), + "costs": ( + {"A": cost(c, "F"), "AI": cost(c, "F") + cost(c, "I"), "W": cost(c, "W")} + if last + else {k: self.costs.get(f"{k}{c}", self.costs.get(k)) for k in ("B", "I", "W")} + ), + } + if last: + chunks[str(c)]["deferred_leaves"] = len(sp.w_leaves) + return { + "schedule": self.schedule_name, + "split_chunks": list(self.split_chunks), + "split_last": self.split_last, + "wbuf_cap": self.zb_wbuf_cap, + "paced": self.pace_i, + "chunks": chunks, + "peak_wbufs": sched.peak_wbufs(self.order, self.place), + "peak_wbuf_gib": self.peak_wbuf_gib(), + "peak_residual_sets": sched.peak_residuals(self.order, self.C), + "sim_ms": self.zb_sims(), + } + + def dispatches(self): + """-> (programs, cross-stage copies) one step enqueues, counted off the + order and the plan: a program per op (a pair is one; the fused last + chunk's no-op backward none), the stage programs, the activation / + cotangent copies between stages and the sumsq hops before the update.""" + C, place = self.C, self.place + ops = [op for op in self.ops() if op.desc is not None] + progs = len(self.dispatched()) + if self.overlap: + progs += self.S + sum(1 for f in self.final_slots if f) # update_gather, reduce_final + else: + progs += 2 * self.S # reduce, update + copies = self.S * (self.S - 1) + for op in ops: + if op.kind == "F" and op.c != C - 1: + copies += place[op.c + 1] != op.s + if op.c != 0 and (op.kind in ("B", "I") or (op.kind == "F" and op.c == C - 1)): + copies += place[op.c - 1] != op.s + return progs, copies + + # ------------------------------------------------------------------ data + def put_batch(self, tokens, targets): + """tokens/targets: int32 [gbs, seq] host arrays -> per-microbatch device + arrays, [rows, row_len] each: under context parallelism every sequence + cut into its cp chunks, one row each (`cp_rows`). -> (tokens on chunk + 0's stage, targets on the last chunk's), and with MTP the tokens on the + last chunk's stage third (its loss embeds the next token).""" + tok = P(ds_ep.FE, None) + first, last = self.chunks[0].stage, self.chunks[-1].stage + put = lambda a, s: [ + jax.device_put(self.cp_rows(a[m * self.mbs : (m + 1) * self.mbs]), NamedSharding(self.meshes[s], tok)) + if self._places(s) + else None + for m in range(self.M) + ] + return (put(tokens, first), put(targets, last)) + ((put(tokens, last),) if self.mtp else ()) + + def cp_rows(self, a): + """[n, seq, ...] -> [n x cp, seq / cp, ...]: row cp x i + r is chunk r of + sequence i (the identity without context parallelism).""" + a = np.asarray(a) if not isinstance(a, jax.Array) else a + return a if self.cp == 1 else a.reshape(a.shape[0] * self.cp, self.row_len, *a.shape[2:]) + + def synthetic_batch(self, seed=0): + rng = np.random.default_rng(seed) + V = self.scfg.model.vocab_size + toks = rng.integers(0, V, size=(self.gbs, self.seq), dtype=np.int32) + tgts = np.roll(toks, -1, axis=1) + return self.put_batch(toks, tgts) + + def maxtext_tokens(self, impl=None): + """MaxText's synthetic batch (dataset_type=synthetic), bit for bit: [gbs, + seq + 1] tokens from randint(key 0) under the PRNG MaxText draws it with + (`impl`, default MAXTEXT_BATCH_PRNG: threefry2x32, the same bits on every + backend); inputs are tokens[:, :-1] and targets tokens[:, 1:].""" + key = jax.random.key(0, impl=impl or MAXTEXT_BATCH_PRNG) + return np.asarray(jax.random.randint(key, (self.gbs, self.seq + 1), 0, self.scfg.model.vocab_size, dtype=jnp.int32)) + + def token_batch(self, tokens): + """[gbs, seq + 1] integer tokens in [0, vocab) -> the batch: inputs + tokens[:, :-1], targets tokens[:, 1:].""" + tokens = np.asarray(tokens) + if not np.issubdtype(tokens.dtype, np.integer): + raise ValueError(f"want integer tokens, got {tokens.dtype}") + if tokens.shape != (self.gbs, self.seq + 1): + raise ValueError(f"want [gbs, seq + 1] = [{self.gbs}, {self.seq + 1}] tokens, got {list(tokens.shape)}") + vocab = self.scfg.model.vocab_size + if tokens.min() < 0 or tokens.max() >= vocab: + raise ValueError(f"tokens outside [0, {vocab}): min {tokens.min()}, max {tokens.max()}") + tokens = tokens.astype(np.int32) + return self.put_batch(tokens[:, :-1], tokens[:, 1:]) + + def chunk_trees_from(self, src): + """Chunk-order weight trees from files src/chunk.npz (src local or + gs://; `write_chunk_files`' format: keys are '.'-joined tree paths, + bfloat16 stored as uint16), for the chunks of this process's stages only + (None for the rest) -> trees for `params_from_chunks`. maxtext_parity.py + writes them from a MaxText init, next to the MaxText checkpoint of the + same weights.""" + trees = [] + for ch in self.chunks: + if not self._places(ch.stage): + trees.append(None) + continue + tree = {} + with np.load(io.BytesIO(xprof_align.read_bytes(f'{src.rstrip("/")}/chunk{ch.index}.npz'))) as z: + for k in z.files: + v = z[k] + v = v.view(jnp.bfloat16) if v.dtype == np.uint16 else v + node = tree + *path, leaf = k.split(".") + for q in path: + node = node.setdefault(q, {}) + node[leaf] = v + trees.append(tree) + return trees + + def init(self, key): + """-> (params, opts, wc0): wc0[s] lists stage s's pre-gathered chunks (gather_slots). + + Chunk c's weights come from fold_in(key, c) under `init_by_chunk` -- the + same whatever the placement, so a circular and a V pipeline start from + one model -- and otherwise from fold_in(fold_in(key, stage), c), as they + always have.""" + # MTP: chunk 0's token embedding and the last chunk's copy, one table + embed_key = jax.random.fold_in(key, 0x7AB1E) if self.mtp else None + params = [ + st.init(key if self.init_by_chunk else jax.random.fold_in(key, s), embed_key=embed_key) + if self._places(s) + else None + for s, st in enumerate(self.stages) + ] + return self.init_state(params) + + def init_state(self, params): + """Storage params per stage -> (params, fresh optimizer state, wc0); + None for a stage another process runs.""" + opts = [None if p is None else st.init_opt(p) for st, p in zip(self.stages, params)] + wc0 = [None if p is None else st.gather_first(p) for st, p in zip(self.stages, params)] + return params, opts, wc0 + + def chunk_trees(self, params): + """Per-stage params (or grads) -> one tree per chunk, in chunk order + (None for the chunks of a stage another process runs).""" + return [None if params[ch.stage] is None else params[ch.stage][self.slot[ch.index]] for ch in self.chunks] + + def params_from_chunks(self, trees): + """Chunk-order trees (host arrays, or another pipeline's `chunk_trees`, + whatever its placement) -> per-stage storage params of this pipeline: + the weight transplant between placements and schedules.""" + + def put(a, sh, dt): + if isinstance(a, jax.Array): + return jax.device_put(a if a.dtype == dt else a.astype(dt), sh) + return jax.device_put(np.asarray(a).astype(dt), sh) # no stop on a default device + + def check(ch, t): + # the model's leaves and shapes, before any copy: a file of another + # model must not load (device_put takes any divisible shape) + flat = lambda tree: { + jax.tree_util.keystr(k): tuple(np.shape(v)) for k, v in jax.tree_util.tree_flatten_with_path(tree)[0] + } + got, want = flat(t), flat(self._avals(ch.stage, "storage", ch)) + missing, extra = sorted(want.keys() - got.keys()), sorted(got.keys() - want.keys()) + if missing or extra: + raise ValueError( + f"chunk {ch.index}: the weights are not this model's: missing {missing[:4]}, " f"unexpected {extra[:4]}" + ) + bad = [(k, got[k], want[k]) for k in want if got[k] != want[k]] + if bad: + raise ValueError( + f"chunk {ch.index}: weight shapes are not this model's: " + + ", ".join(f"{k} {g} (model {w})" for k, g, w in bad[:4]) + ) + + params = [[None] * len(self.stage_chunks[s]) if self._places(s) else None for s in range(self.S)] + for ch, t in zip(self.chunks, trees, strict=True): + s, i = ch.stage, self.slot[ch.index] + if self._places(s): + check(ch, t) + params[s][i] = jax.tree.map(put, t, self.stages[s].s_sh[i], ds_ep.leaf_dtype_tree(self.scfg, ch, "storage")) + return params + + def lr_arrays(self, lr): + return [ + jax.device_put(jnp.float32(lr), NamedSharding(m, P())) if self._places(s) else None + for s, m in enumerate(self.meshes) + ] + + # ------------------------------------------------------------ one step + def loss_and_grads(self, params, batch, wc=None): + """Microbatch loop only. Returns (gaccs per stage, loss partials). + Under shard_mode 'explicit' the gaccs are typed unreduced: no host reads + or scales one (jax refuses); a stage's `reduce` sums them.""" + if wc is None: + wc = [self.stages[s].gather(params[s]) if self._runs(s) else None for s in range(self.S)] + st = self._run(params, [None if w is None else list(w) for w in wc], batch, overlap=False) + return [[st.gacc[ch.index] for ch in self.stage_chunks[s]] if self._runs(s) else None for s in range(self.S)], st.lacc + + def loss_and_grads_overlap(self, params, wc0, batch, consume=False): + """Microbatch loop with the FSDP gather / reduce-scatter folded in. + + Returns (grads per stage [storage layout, by slot], stage sumsq, loss partials). + `consume`: once the loop holds `wc0`'s weights, set its entries to None + (a list's, in place), so the caller's reference does not keep them alive + after the loop has released them (fsdp_scope 'repeat') or finished with + them -- `step` consumes its wc0. + """ + wc = [[None] * len(self.stage_chunks[s]) for s in range(self.S)] + for s in range(self.S): + for i, w in zip(self.gather_slots[s], wc0[s] or ()): + wc[s][i] = self._whole(s, i, w, params) + w = None # else the loop's variable keeps the last chunk it took past its release + if consume and isinstance(wc0, list): + wc0[:] = [None] * len(wc0) + st = self._run(params, wc, batch, overlap=True) + wc[:] = [None] * self.S # st.wc: the loop's weights, not needed by the final reduces below + stage_sq = [] + for s in range(self.S): + fs = self.final_slots[s] + if self.multi and s not in self.local: + stage_sq.append(None) + continue + if not fs: + stage_sq.append(st.stage_tot[s]) + continue + g, tot = self.stages[s].reduce_final(fs, self.n_partial_sq[s])( + [st.gacc[self.stage_chunks[s][i].index] for i in fs], st.sq[s] + ) + for i, gi in zip(fs, g): + st.grads[s][i] = gi + stage_sq.append(tot) + return st.grads, stage_sq, st.lacc + + def _run(self, params, wc, batch, overlap): + """THE step loop: every op of the order in turn (`issue_order`: each + stage's trailing W's last), through its handler. + + `wc[s][slot]` holds the compute weights gathered so far (the rest arrive + inside prefetch hosts when `overlap`). Each handler takes the op's inputs + from the step state, calls its program and files the outputs: the next + chunk's input on its stage, the residuals (and stash) for the backward, + the gradient accumulators, the gathered / reduced leaves of other chunks. + An F&B pair is one call of both ops' programs composed (`_do_pair`). + -> the step state. + """ + st = _Step(self, params, wc, batch) + handlers = {"F": self._do_F, "B": self._do_B, "I": self._do_I, "W": self._do_W} + ops, C = self.ops(overlap), self.C + + skip = False + for op in (ops[j] for j in self.issue_order(overlap)): + if skip: # the second half of a pair, run with the first + skip = False + continue + if self.multi and op.s not in self.local: # another process's stage: only its boundary copies + self._do_remote(st, op, ops) + skip = op.j in self.fuse + elif op.j in self.fuse: + self._do_pair(st, op, ops[op.j + 1]) + skip = True + elif op.c == C - 1: + if op.kind in ("F", "W"): # the fused program (split: AI), or a split last chunk's W + (self._do_A if op.kind == "F" else self._do_W)(st, op) + if overlap: # the plan's releases: only its gathers bring the weights back + self._release(st, op) + # its B is the no-op the fused program already ran + else: + handlers[op.kind](st, op) + if overlap: + self._release(st, op) + if st.wbuf or st.gacc_parts: # every I's W ran: the order is checked (sched.validate), so this is the loop's own + raise AssertionError( + f"W buffers {sorted(st.wbuf)} or accumulator parts {sorted(st.gacc_parts)} left after the loop" + ) + st.last_i.clear() # (`_pace`'s: each chunk's last crossing set, which its W has read, not held past the loop) + return st + + # Each kind's handler is its two halves: `_take_K` pops the op's arguments + # off the step state (in its part's argument order), `_put_K` files the + # outputs of its part. A pair runs one program on both argument lists. + def _do_F(self, st, op): + """A forward of a non-last chunk: -> the next chunk's input, the + residuals (and the stash, in stash mode), and whatever it gathers.""" + args = self._take_F(st, op) + self._put_F(st, op, args, list(self.program(op)(*args))) + + def _do_A(self, st, op): + """The last chunk's forward: forward, head, loss and backward in one + program -> the upstream cotangent, its gradient, the loss partials. Split + (AI): its gradient but its layers', and its W buffer for its W -- paced as + an I is (`_do_I`).""" + self._pace(st, op) + args = self._take_A(st, op) + self._put_A(st, op, args, list(self.program(op)(*args))) + + def _do_B(self, st, op): + """A backward of a non-last chunk: -> the upstream cotangent (none for + chunk 0) and its gradient; plus whatever it reduce-scatters (another + chunk's groups, or with rs_self its own finished gradient).""" + args = self._take_B(st, op) + self._put_B(st, op, args, list(self.program(op)(*args))) + + def _do_pair(self, st, op_f, op_b): + """An F&B pair: order[j] (an F, or the fused last chunk's A) and + order[j+1] (a B of another microbatch on the same stage) as ONE program, + `compose` of both parts (`op_f.pair`) on the two argument lists one after + the other; its outputs are the B's, then the F's (ds_ep.composed_order; + an A&B pair's, the A's, then the B's), filed as `_do_F` / `_do_A` and + `_do_B` file theirs, the F's first: in the order `_do_remote` issues + their boundary copies. The plan folds no collective into a pair, so the + B's are its dx (but chunk 0's) and its gacc.""" + last = op_f.c == self.C - 1 + fa = self._take_A(st, op_f) if last else self._take_F(st, op_f) + ba = self._take_B(st, op_b) + out = list(self.program(op_f)(*fa, *ba)) + nb = 1 + (op_b.c != 0) + fwd_out, bwd_out = (out[:-nb], out[-nb:]) if last else (out[nb:], out[:nb]) + (self._put_A if last else self._put_F)(st, op_f, fa, fwd_out) + self._put_B(st, op_b, ba, bwd_out) + + def _file(self, box, key, a, b, x): + """File stage a's output x as box[key], the input of an op on stage b + (`_send`) -- under multi-controller JAX where stage b is local.""" + y = self._send(a, b, x) + if not self.multi or y is not None: + box[key] = y + + def _do_remote(self, st, op, ops): + """An op of a stage another process runs (multi-controller): no program, + only the boundary copies its handler would issue, in the same order + (`_put_F` / `_put_A` / `_put_B` / `_put_I`; an F&B pair's F, then its B), + without a source -- filing whatever arrives for a local stage. A W + copies nothing.""" + C, place = self.C, self.place + for o in (op, ops[op.j + 1]) if op.j in self.fuse else (op,): + c, m, s = o.c, o.m, o.s + if o.kind == "F" and c != C - 1: + self._file(st.act, (c + 1, m), s, place[c + 1], None) + elif c != 0 and ((o.kind in ("B", "I") and c != C - 1) or (o.kind == "F" and c == C - 1)): + self._file(st.cotangents, (c - 1, m), s, place[c - 1], None) + + def _take_F(self, st, op): + c, m, s = op.c, op.m, op.s + x = st.toks[m] if c == 0 else st.act.pop((c, m)) + args = [st.wc[s][self.slot[c]], x, self.seeds[s][m]] + if op.self_pf: # w is the chunk's other leaves; gather its routed experts here + sl = jax.tree.leaves(st.params[s][self.slot[c]]) + args.append([sl[i] for i in self.routed_leaves]) + return args + self._pf_args(st, op) + + def _pf_args(self, st, op): + """The storage leaves of the gather `op` carries (its 'G' part's one + argument), else nothing.""" + if not op.pf: + return [] + b, g = op.pf + sl = jax.tree.leaves(st.params[op.s][self.slot[b]]) + return [[sl[i] for i in g]] + + def _whole(self, s, i, w, params): + """Stage s's slot-i entry of the gathered weights (`gather_first`'s or + `update_gather`'s) as the programs take it: as given, but a chunk with + leaves read in place (`direct`), whose gather delivered its other leaves + as a flat list (StagePrograms.keep): those, with the direct ones from + `params`, the storage leaves themselves -- no copy.""" + c = self.stage_chunks[s][i].index + if c not in self.direct or w is None: + return w + full = list(jax.tree.leaves(params[s][i])) + for j, v in zip(self.stages[s].keep[i], w, strict=True): + full[j] = v + return jax.tree.unflatten(self.treedef[c], full) + + def _install(self, st, op, leaves): + """File the leaves `op`'s gather delivered; once the last of its hosts + has, the chunk's weights are whole: install them in st.wc. A chunk's + leaves read in place (`direct`) are its storage's, there from the start.""" + b, g = op.pf + parts = st.wparts.get(b) + if parts is None: + parts = st.wparts[b] = [None] * self.n_leaves[b] + if b in self.direct: + sl = jax.tree.leaves(st.params[op.s][self.slot[b]]) + for i in self.direct[b]: + parts[i] = sl[i] + for i, v in zip(g, leaves): + parts[i] = v + left = st.pending.get(b, self.pf_n[op.j]) - 1 + if left: + st.pending[b] = left + else: + st.pending.pop(b, None) + st.wc[op.s][self.slot[b]] = jax.tree.unflatten(self.treedef[b], st.wparts.pop(b)) + + def _release(self, st, op): + """fsdp_scope 'repeat': drop the weights of the chunks whose visit `op` + ends (`release_at`). The programs already issued keep what they use + until they have run; nothing else holds them (`step` consumes wc0).""" + for b in self.release_at.get(op.j, ()): + st.wc[op.s][self.slot[b]] = None + + def _put_F(self, st, op, args, out): + c, m, s = op.c, op.m, op.s + slot = self.slot + w, x = args[0], args[1] + y, r = out.pop(0), out.pop(0) + if op.stash: + st.stash[(c, m)] = out.pop(0) + if op.self_pf: + full = [None] * self.n_leaves[c] + for i, v in zip(self.first_leaves[s], w): + full[i] = v + for i, v in zip(self.routed_leaves, out.pop(0)): + full[i] = v + st.wc[s][slot[c]] = jax.tree.unflatten(self.treedef[c], full) + if op.pf: + self._install(st, op, out.pop(0)) + st.res[(c, m)] = self._offload((x, r)) if self.offload_residuals else (x, r) + self._file(st.act, (c + 1, m), s, self.place[c + 1], y) + + @staticmethod + def _offload(tree): + """`tree`'s arrays copied to their shardings in pinned host memory + (asynchronously, behind the program that wrote them) -> (the host copies, + the device shardings to bring them back to).""" + leaves, tdef = jax.tree.flatten(tree) + shardings = [a.sharding for a in leaves] + host = [jax.device_put(a, sh.with_memory_kind("pinned_host")) for a, sh in zip(leaves, shardings)] + return ("offloaded", tdef, host, shardings) + + @staticmethod + def _restore(held): + """`_offload`'s copies back on their devices (asynchronously; the + backward that takes them waits for the copy); anything else as it is.""" + if not (isinstance(held, tuple) and len(held) == 4 and held[0] == "offloaded"): + return held + _, tdef, host, shardings = held + return jax.tree.unflatten(tdef, [jax.device_put(a, sh) for a, sh in zip(host, shardings)]) + + def _take_A(self, st, op): + c, m, s = op.c, op.m, op.s + x = st.toks[m] if c == 0 else st.act.pop((c, m)) + args = [st.wc[s][self.slot[c]], x, st.tgts[m]] + ([st.mtp_toks[m]] if self.mtp else []) + if op.acc: # the accumulator -- split (AI), its kept part -- and the loss partials + args += [st.gacc_parts[c][0] if self.split_last else st.gacc[c], st.lacc] + return args + [self.seeds[s][m]] + self._pf_args(st, op) + + def _put_A(self, st, op, args, out): + """File the fused last chunk's outputs: its accumulator (split: AI's part) and the loss partials, the upstream + cotangent (but a first chunk's) -- and, split, its W buffer: the crossing set and the arguments its W reads.""" + c, m, s = op.c, op.m, op.s + if op.pf: # the gather's leaves come last + self._install(st, op, out.pop()) + if self.split_last: # AI: the accumulator's kept part and a W buffer, the crossing set after the loss + cross = out.pop() + nt = 1 + bool(self.mtp) # the targets [, the tokens] + i_args = args[: 2 + nt] + [args[2 + nt + 2 * op.acc]] # (w, x, tgt[, tok], seed) + st.wbuf[(c, m)] = (cross, self.split_of(c, op.acc).kept_of(i_args)) + if self.pace_i: + st.last_i[c] = cross + parts = st.gacc_parts.setdefault(c, [None, None]) + out, (parts[0], st.lacc) = out[:-2], out[-2:] + elif c == 0: + st.gacc[c], st.lacc = out + out = [] + else: + out, (st.gacc[c], st.lacc) = out[:-2], out[-2:] + if c != 0: + (dx,) = out + self._file(st.cotangents, (c - 1, m), s, self.place[c - 1], dx) + + def _take_B(self, st, op): + c, m, s = op.c, op.m, op.s + x, r = self._restore(st.res.pop((c, m))) + args = [st.wc[s][self.slot[c]], x, r] + args += [st.stash.pop((c, m))] if op.stash else [] + args.append(st.cotangents.pop((c, m))) + args += [st.gacc[c]] if op.acc else [] + args.append(self.seeds[s][m]) + return args + self._acc_tail_args(st, op) + self._pf_args(st, op) + + def _acc_tail_args(self, st, op): + """A gradient writer's (a B's or a W's) arguments after its own part's leading ones: with rs_self the stage's + partial sums of squares, and the leaves of another chunk's accumulator it reduce-scatters (op.rs, which it takes + off the step state).""" + args = [] + if op.rs_self is not None: + args.append(st.sq[op.s]) + if op.rs: + o, g = op.rs + if o not in st.gacc_leaves: + st.gacc_leaves[o] = jax.tree.leaves(st.gacc[o]) + st.gacc[o] = None + gl = st.gacc_leaves[o] + args.append([gl[i] for i in g]) + for i in g: + gl[i] = None + return args + + def _put_acc(self, st, op, out): + """File a gradient writer's (a B's or a W's) outputs off the end of `out`: its gather's leaves, its + reduce-scatter's gradients and partial sumsq, and its accumulator -- or with rs_self the chunk's reduced + gradients and the stage's sumsq. What is left in `out` is a B's dx (none for chunk 0, nor for a W).""" + c, s = op.c, op.s + if op.pf: # the gather's leaves come last (after a reduce-scatter's) + self._install(st, op, out.pop()) + if op.rs: + o, g = op.rs + got, part_sq = out[-2:] + del out[-2:] + st.sq[s].append(part_sq) + parts = st.gparts.setdefault(o, [None] * self.n_leaves[o]) + for i, v in zip(g, got): + parts[i] = v + st.gpending[o] -= 1 + if not st.gpending[o]: + st.grads[s][self.slot[o]] = jax.tree.unflatten(self.treedef[o], st.gparts.pop(o)) + del st.gacc_leaves[o] + if op.rs_self is not None: + st.grads[s][self.slot[c]], st.stage_tot[s] = out[-2:] + del out[-2:] + st.gacc[c] = None + else: + st.gacc[c] = out.pop() + + def _put_B(self, st, op, args, out): + c, m, s = op.c, op.m, op.s + self._put_acc(st, op, out) + if c != 0: + self._file(st.cotangents, (c - 1, m), s, self.place[c - 1], out[0]) + + # The split backward (the zero-bubble schedules; ds_ep.ChunkPrograms.build_split): an I takes what its B would + # but the accumulator, files the upstream cotangent and leaves its W buffer on the stage -- the crossing set it + # returns and the references of the arguments W reads (Split.kept, which I does not donate: no copy) -- and its W + # takes the buffer and is the chunk's gradient writer: the first W starts the accumulator, the others add to it in + # microbatch order (sched.validate), as the B's they replace would, and a W hosts what a B hosts (a split last + # chunk's W nothing: `_plan_overlap`). + def _do_I(self, st, op): + """The input-gradient half of a split backward: -> the upstream cotangent and the chunk's W buffer. Issued once + the chunk's previous I has finished, where the client allocates outputs at issue (`_pace`).""" + self._pace(st, op) + args = self._take_I(st, op) + self._put_I(st, op, args, list(self.program(op)(*args))) + + def _pace(self, st, op): + """Under McJAX (`pace_i`), wait for the chunk's previous W buffer this step to be written before issuing the + next one's program: an I, or a split last chunk's AI. + + A TPU VM's client allocates a program's outputs when the one dispatch thread issues it, and the loop runs ahead + of the chips, so the W buffers of I's issued ahead would be held from then on: the split stages' HBM fills + whatever --zb-wbuf-cap says (87.5 GiB of 94.7 a device at DeepSeek-V3 widths on TPU7x, where the HBM walk says + 56), each I waits in Execute for a W to free some, and the stage's last W, which writes the reduce-scattered + gradients into new buffers, finds none: libtpu waits for the stage to drain and defragments, and the copies out + of the stage wait for that too. Paced, an I is issued with the buffers its order holds pending and its own; the + stage still has the ops between the two (a W, an F) to run meanwhile. Pathways' client issues asynchronously + and is not paced.""" + if self.pace_i: + prev = st.last_i.pop(op.c, None) + if prev is not None: + jax.block_until_ready(prev) + + def _do_W(self, st, op): + """The weight-gradient half of a split backward: its W buffer (and the accumulator) -> the accumulator, and + whatever it reduce-scatters (another chunk's groups, or with rs_self its own finished gradient).""" + args = self._take_W(st, op) + self._put_W(st, op, args, list(self.program(op)(*args))) + + def _take_I(self, st, op): + c, m, s = op.c, op.m, op.s + x, r = self._restore(st.res.pop((c, m))) + args = [st.wc[s][self.slot[c]], x, r, st.cotangents.pop((c, m)), self.seeds[s][m]] + return args + self._pf_args(st, op) + + def _put_I(self, st, op, args, out): + c, m, s = op.c, op.m, op.s + if op.pf: # the gather's leaves come last + self._install(st, op, out.pop()) + dx, cross = out + st.wbuf[(c, m)] = (cross, self.progs[c].build_split(op.acc).kept_of(args[:5])) + if self.pace_i: + st.last_i[c] = cross + self._file(st.cotangents, (c - 1, m), s, self.place[c - 1], dx) + + def _take_W(self, st, op): + c, m = op.c, op.m + cross, kept = st.wbuf.pop((c, m)) + if op.acc: # the accumulator -- a split last chunk's W, its deferred part + args = [cross, kept, st.gacc_parts[c][1] if c == self.C - 1 else st.gacc[c]] + else: + args = [cross, kept] + return args + self._acc_tail_args(st, op) + self._pf_args(st, op) + + def _put_W(self, st, op, args, out): + """File a W's outputs: a middle chunk's as a B's (`_put_acc`); a split last chunk's deferred part, and after its + last W the chunk's whole accumulator (`_merge_parts`).""" + del args # (the _put_K signature: a W files nothing of its arguments) + c = op.c + if c == self.C - 1: # the split last chunk's deferred part; after its last W, its whole accumulator + if op.pf: # the gather's leaves come last + self._install(st, op, out.pop()) + parts = st.gacc_parts.setdefault(c, [None, None]) + parts[1] = out.pop() + if op.j == self.last_writer[c]: + st.gacc[c] = self._merge_parts(c, *st.gacc_parts.pop(c)) + else: + self._put_acc(st, op, out) + if out: + raise AssertionError(f"{self.op_name(op.j)}: {len(out)} outputs left after its accumulator") + + def _merge_parts(self, c, kept, deferred): + """A split last chunk's accumulator from its two parts (ds_ep.Split.i_leaves / w_leaves): a regroup of the + leaves, no device work.""" + sp = self.split_of(c) + leaves = [None] * self.n_leaves[c] + for idx, part in ((sp.i_leaves, kept), (sp.w_leaves, deferred)): + for i, v in zip(idx, part, strict=True): + leaves[i] = v + return jax.tree.unflatten(self.treedef[c], leaves) + + def step(self, params, opts, wc0, batch, lrs): + """One full training step -> (params, opts, wc0, loss_partials, gnorm). + + With the fusion plan, like params and opts (which the update programs + donate), a list wc0 is used up: its entries are set to None as the + microbatch loop takes them (`loss_and_grads_overlap(consume=True)`), so + a chunk's gathered weights are freed when the loop is done with them -- + not held by the caller through the update, which gathers the next + step's. Without it (overlap=False) wc0 is not used: the loop gathers + every chunk itself. + + Under multi-controller JAX the per-stage lists hold None for the stages + another process runs, the loss partials are None unless the last chunk's + stage is local, and gnorm comes from a local stage (None on a process + that holds no stage). `self.step_gnorms` keeps every local stage's + gnorm, an output of its update program and never donated: blocking on + them (and on the loss partials) waits for this process's whole step.""" + S = self.S + if self.overlap: + grads, sq, lacc = self.loss_and_grads_overlap(params, wc0, batch, consume=True) + else: + gaccs, lacc = self.loss_and_grads(params, batch) + red = [self.stages[s].reduce(gaccs[s]) if self._runs(s) else (None, None) for s in range(S)] + grads = [r[0] for r in red] + sq = [r[1] for r in red] + if self.mtp: + grads, sq = self._tie(grads, sq) + if self.on_grads is not None: + self.on_grads(grads) + new_p, new_o, new_w, gns, gn = [], [], [], [], None + # Every hop goes out before any update, in the same order on every + # process, so no update waits on another stage's: under 'ppermute' a hop + # is a program of both its stages, which an update queued ahead of it on + # one would hold back from the other, and under 'relay' a hop's receive + # is a future its update resolves (`transfer.resolve` passes the other + # transports' arrays through). + if self.multi and self.norm_reduce == "allreduce": + total = self._global_sumsq(sq) + zeros = self._gsq["zeros"] + hops = {(t, s): zeros.get(s) for s in range(S) for t in range(S) if t != s} + sq = [total.get(s) for s in range(S)] + else: + hops = {(t, s): self._hop(t, s, sq[t]) for s in range(S) for t in range(S) if t != s} + for s in range(S): + mine = [hops[(t, s)] if t != s else sq[t] for t in range(S)] + if self.multi: + if s not in self.local: + new_p.append(None) + new_o.append(None) + new_w.append(None) + continue + mine = [transfer.resolve(x) for x in mine] + if self.overlap: + p, o, g, w0 = self.stages[s].update_gather(params[s], opts[s], grads[s], mine, lrs[s]) + else: + p, o, g = self.stages[s].update(params[s], opts[s], grads[s], mine, lrs[s]) + w0 = None + new_p.append(p) + new_o.append(o) + new_w.append(w0) + gns.append(g) + gn = g if gn is None else gn + self.step_gnorms = tuple(gns) + return new_p, new_o, new_w, lacc, gn + + def _global_sumsq(self, sq): + """norm_reduce 'allreduce': the stages' sums of squares (replicated + scalars on their meshes, None for other processes' stages) -> {local stage: + their total, replicated on its mesh}, by one program over every device of + the job that every process runs at the same point of its step: each + stage's first device contributes its stage's value, every other device 0. + The update then takes [total, 0, ..., 0] for the S partials (`step`).""" + if self._gsq is None: + devs = jax.devices() + gmesh = Mesh(np.array(devs), ("d",)) + first = {self.meshes[s].devices.flat[0].id: s for s in range(self.S)} + # On GPU the sum stays a NCCL all-reduce: XLA's default for a clique + # inside one NVLink domain is its Triton one-shot kernel, whose + # compile fails at 64 ranks over the 16 hosts of a GB200 NVL72 rack + # ("size mismatch when packing elements for LLVM struct", jax 0.12.0.1) + # -- and a scalar once a step has nothing to gain from it. + opts = {"xla_gpu_experimental_use_collective_kernels": ""} if devs[0].platform == "gpu" else None + prog = jax.jit(lambda v: jnp.sum(v), out_shardings=NamedSharding(gmesh, P()), compiler_options=opts) + zero = {d.id: jax.device_put(np.zeros((1,), np.float32), d) for d in jax.local_devices()} + zeros = {s: jax.device_put(np.float32(0), NamedSharding(self.meshes[s], P())) for s in self.local} + self._gsq = dict(mesh=gmesh, first=first, prog=prog, zero=zero, zeros=zeros) + g = self._gsq + parts = [] + for d in g["mesh"].local_devices: + s = g["first"].get(d.id) + if s is None: + parts.append(g["zero"][d.id]) + else: + (shard,) = [x.data for x in sq[s].addressable_shards if x.device == d] + parts.append(shard.reshape(1)) + v = jax.make_array_from_single_device_arrays((len(g["mesh"].devices.flat),), NamedSharding(g["mesh"], P("d")), parts) + tot = g["prog"](v) + by_dev = {x.device.id: x.data for x in tot.addressable_shards} + # this process's shards only: a stage may span processes (a one-stage, data-parallel layout over every node) + return { + s: jax.make_array_from_single_device_arrays( + (), NamedSharding(self.meshes[s], P()), [by_dev[d.id] for d in self.meshes[s].devices.flat if d.id in by_dev] + ) + for s in self.local + } + + def _tie(self, grads, sq): + """MTP's tied token embedding: chunk 0's table and the last chunk's copy + (ds_ep.mtp_shapes) are one parameter, so each takes the sum of their two + reduced gradients, and the global norm counts that sum once -- chunk 0's + stage adds |sum|^2 - |own|^2 to its sum of squares, the last chunk's + takes |own|^2 off. Both then run the same update from the same state: + the copies stay equal. Every process walks both copies in order (the + channels' contract); -> (grads, sq) with the local stages' replaced.""" + a, b, C = self.place[0], self.place[self.C - 1], self.C + ia, ib = self.slot[0], self.slot[C - 1] + get = lambda s, i, path: functools.reduce(lambda t, k: t[k], path, grads[s][i]) if self._runs(s) else None + pa, pb = ("token_embedder", "embedding"), ("mtp", "token_embedder", "embedding") + ga, gb = get(a, ia, pa), get(b, ib, pb) + if a == b: + other_a, other_b = gb, ga + else: + other_a = self.tie_channels[(b, a)].send_flat([gb])[0] + other_b = self.tie_channels[(a, b)].send_flat([ga])[0] + grads, sq = list(grads), list(sq) + + def put(s, i, path, g): + tree = node = dict(grads[s][i]) + for k in path[:-1]: + node[k] = dict(node[k]) + node = node[k] + node[path[-1]] = g + grads[s] = list(grads[s]) + grads[s][i] = tree + + for s, i, path, own, other, keep in ((a, ia, pa, ga, other_a, True), (b, ib, pb, gb, other_b, False)): + if self._runs(s): + g, sq[s] = self._tie_sum(s, keep)(own, transfer.resolve(other) if self.multi else other, sq[s]) + put(s, i, path, g) + return grads, sq + + def _tie_sum(self, s, keep): + """Stage s's program of `_tie`: (own, other, sumsq) -> (own + other, the + corrected sumsq); `keep`: this stage's norm counts the sum (chunk 0's).""" + key = ("tie", s, keep) + if key not in self._exe: + mesh, dt = self.meshes[s], self.scfg.rs_dtype + emb = P(None, ds_ep.FE) + + def body(own, other, sq): + g = (own.astype(jnp.float32) + other.astype(jnp.float32)).astype(dt) + norm = lambda x: jax.lax.psum(jnp.sum(jnp.square(x.astype(jnp.float32))), ds_ep.FE) + return g, sq - norm(own) + (norm(g) if keep else 0.0) + + ns = lambda spec: NamedSharding(mesh, spec) + self._exe[key] = jax.jit( + ds_ep._named( + jax.shard_map(body, mesh=mesh, in_specs=(emb, emb, P()), out_specs=(emb, P()), check_vma=False), + f"tie_s{s}" if keep else f"tie_mtp_s{s}", + ), + in_shardings=(ns(emb), ns(emb), ns(P())), + out_shardings=(ns(emb), ns(P())), + ) + return self._exe[key] + + def close(self): + """Shut down what runs besides the programs: under transport 'relay' + the relay's sockets and threads (`relay_ctx.close`, which flushes + first). Every receive must have been consumed -- after the last step, + on every process. Idempotent; nothing to do in one controller (no + relay there).""" + if self.multi and self.relay_ctx is not None: + self.relay_ctx.close() + + # --------------------------------------------------------------- report + def lineage_sparsecore(self): + """{stage: does it run Lineage's SparseCore regions} under batch_split on Lineage's layers ({} otherwise): the + answers its chunks' Regions trace under, every stage's (`__init__`: libtpu's, agreed across processes, the + device rule's where a probe failed, or `stage_lineage_sparsecore`) -- read, never probed here. A stage holding + chip (0,0,0) of a slice it is part of says no: its Regions trace Lineage's SparseCore regions as TensorCore + code.""" + return {} if self.lineage_sc is None else dict(enumerate(self.lineage_sc)) + + def summary(self): + cfg = self.scfg.model + sync = ( + f"; synchronous on stage {sorted(self.sync_stages)} (its strip holds chip (0,0,0): no " f"SparseCore offload)" + if self.sync_stages + else "" + ) + marks, remote = [""] * self.S, "" + if self.multi or self.aot: + # Another process's stage (multi-controller JAX; or a stage ds_ep_aot's --stages-to-compile leaves out) is + # never probed here: its flavours are libtpu's rule from the devices (`sc`), marked '*'; its leader logs what + # it resolved. + other = frozenset(range(self.S)) - self.local + if other: + marks, remote = ["*" if s in other else "" for s in range(self.S)], " (* another process's stage: inferred)" + flav = lambda kind: [getattr(c, kind) + marks[s] for s, c in enumerate(self.stage_scfg)] + dense_at = " 0" if not self.every_layer else f"s {[c.index for c in self.chunks if c.dense]}" + ep = f'EP collectives per stage: {flav("ep_collectives")}' + if self.scfg.lineage_split: + # every chunk's layers are Lineage's, which run EP collectives of their own: ds_ep's flavours go unused + sc = self.lineage_sparsecore() + on, off = sorted(s for s, v in sc.items() if v), sorted(s for s, v in sc.items() if not v) + ep = ( + "EP collectives: Lineage's own (" + + "; ".join( + ([f"on SparseCore on stage {on}"] if on else []) + + ([f"as TensorCore code on stage {off}, where libtpu offloads no collective"] if off else []) + ) + + ")" + ) + rows = self.rows // (self.scfg.fsdp * self.scfg.ep) + if ds_ep.is_qwen(cfg): + n_attn = sum(map(cfg.is_attention_layer, range(cfg.num_decoder_layers))) + model = ( + f"MPMD Qwen3.5 family: {cfg.num_decoder_layers} MoE layers ({cfg.num_decoder_layers - n_attn} " + f"Gated DeltaNet, {n_attn} gated attention)" + ) + else: + model = f"MPMD DeepSeek sparse: {cfg.num_decoder_layers - self.n_dense} MoE layers" + lines = [ + f'{ep}; FSDP collectives per stage: {flav("fsdp_collectives")}{sync}{remote}', + f"{model}" + f'{f" after {self.n_dense} dense (mlp {cfg.mlp_dim}, in chunk{dense_at})" if self.n_dense else ""}' + f'{f" + {self.mtp} MTP" if self.mtp else ""}, ' + f"{self.C} chunks " + f'(V={self.V}{"" if len(set(self.layer_split)) == 1 else f", layers {list(self.layer_split)}"}), ' + f"{self.S} stages x (fsdp={self.scfg.fsdp}, ep={self.scfg.ep}), " + f"M={self.M} x mbs={self.mbs} x seq={self.seq}" + f'{f" (cp={self.cp}: {self.rows} rows of {self.row_len})" if self.cp > 1 else ""}, ' + f"schedule={self.schedule_name}" + + ( + ", fsdp_scope=repeat (a chunk's weights gathered per visit, released after it)" + if self.fsdp_scope == "repeat" + else "" + ) + + ( + ", shard_mode=explicit (Explicit mesh axes; weight copies reduced, gradient accumulators unreduced)" + if self.scfg.shard_mode == "explicit" + else "" + ) + + ( + ", expert_weights=sliced (megablox reads per-layer slices, which XLA copies first)" + if self.scfg.expert_weights == "sliced" and not self.scfg.lineage_split + else "" + ) + + ( + ", rs_axes=each (a leaf stored over both mesh axes reduce-scattered one axis at a time, but the " + "vocab leaves)" + if self.scfg.rs_axes == "each" + else "" + ) + + ( + ", gather_axes=each (a leaf stored over both mesh axes gathered one axis at a time)" + if self.scfg.gather_axes == "each" + else "" + ) + + ( + f", batch_split=lineage (each device's {rows} rows of a microbatch as two halves through MaxText's " + "Lineage layers, ds_ep_lineage: one half's EP collectives beside the other half's compute; the " + f"chunks' programs global-view jits; capacity factor {self.scfg.lineage_capacity_factor:g})" + if self.scfg.lineage_split + else "" + ) + + ( + f", batch_split=native (ds_ep.split_layers; each " + f"device's {rows} rows of a microbatch as two halves, EP collectives beside the other half's " + "compute; the halves' expert weight " + + ( + "gradients accumulated in the dW kernel)" + if self.scfg.split_dw == "acc" + else "gradients summed after their kernels)" + ) + if self.scfg.batch_split and not self.scfg.lineage_split + else "" + ), + ] + for s, m in enumerate(self.meshes): + lines.append(f" stage {s}: {describe_mesh(m)} chunks {[c.index for c in self.stage_chunks[s]]}") + nparam = ds_ep.num_params(self.scfg, self.chunks) + progs, copies = self.dispatches() + mk, busy = sched.timed_simulate( + self.order, + self.place, + self.costs, + self.costs["xfer"], + fuse_last=True, + modes=self.modes, + fuse=self.fuse, + pair_gain=self.pair_gain, + ) + bub = sched.bubble(self.order, self.place, self.costs, modes=self.modes, fuse=self.fuse, pair_gain=self.pair_gain) + lines.append( + f" params {nparam / 1e9:.2f}B; placement {self.placement}; bubble(sim F=1,B=2) " + f"{100 * sched.bubble(self.order, self.place):.1f}%, with the program costs and " + f"modes {100 * bub:.1f}%; microbatch loop {mk:.1f} (sim, stage busy " + f"{[round(b, 1) for b in busy]}); dispatches/step {progs} programs + {copies} copies" + ) + if self.split_chunks: + sims = self.zb_sims() + cap = "no cap" if self.zb_wbuf_cap is None else f"cap {self.zb_wbuf_cap}" + lines.append( + f" split backward (I / W) on chunks {self.split_chunks}: W buffer " + f"{[round(self.wbuf_bytes[c] / 2**30, 3) for c in self.split_chunks]} GiB per microbatch per device; peak " + f"live W buffers per stage {sched.peak_wbufs(self.order, self.place)} ({cap}) = " + f"{[round(g, 3) for g in self.peak_wbuf_gib()]} GiB per device; peak residual sets per chunk " + f"{sched.peak_residuals(self.order, self.C)}; microbatch loop (sim) {sims['order']:.1f} against 1f1b " + f"{sims['1f1b']:.1f} and breadth {sims['breadth']:.1f}" + ) + if self.modes: + nset = self.C - 1 if self.C > 1 else 0 + per = ", ".join(f"{pol} {max(b) / 2**30:.3f}" for pol, b in self.stash_bytes.items()) + lines.append( + f" stash: {len(self.modes)} of {nset * self.M} (chunk, microbatch)s " + f"({per} GiB per set per device); peak live stash per stage (GiB per device) " + f"{[round(g, 2) for g in self.peak_stash_gib()]}, budget {self.stash_budget_gib:g}; " + f"with the stash backwards' extra temporaries the step peak grows by up to " + f"{[round(g, 2) for g in self.peak_stash_gib(temps=True)]}" + ) + if self.fuse: + per = collections.Counter(self.place[self.order[j][0]] for j in self.fuse) + lines.append( + f" F&B pairs: {len(self.fuse)} programs (" + + ", ".join(f"s{s} {per[s]}" for s in range(self.S)) + + f"), each simulated {self.pair_gain:g} ms under its two halves back to back; " + + ( + "no pair hosts an FSDP gather, and every backward, a pair's too, " + "reduce-scatters its own microbatch gradient (grad_reduce=microbatch)" + if self.scfg.grad_reduce == "microbatch" + else "no pair hosts an FSDP collective" + ) + ) + for s in range(self.S): + names = [ + self.op_name(j) + ("&" if j in self.fuse else " ") + for j, (c, _, _) in enumerate(self.order) + if self.place[c] == s + ] + lines.append(f" s{s}: " + "".join(names).rstrip()) + lines.append(self.plan_summary()) + return "\n".join(lines) + + +# ---------------------------------------------------------------------- CLI +# `--model`: deepseek3 is the shape flags' own defaults (DeepSeek-V3 MoE layers); a +# Qwen3.5-family model, by MaxText's model_name, sets those defaults to its +# config (`ModelParser`), so `--model qwen3.8-2.4t-a95b` alone is the whole model +# and any shape flag given still wins (`--layers 8 --experts 64`: fewer layers +# and experts at its per-layer dims). The DeepSeek-only flags (--q-lora, +# --kv-lora) default to None there and are refused if given. +QWEN_MODELS = { + # MaxText's configs/models/qwen3.8-2.4t-a95b.yml: 2.42T parameters, 95.3B active. It sets no use_mrope, so + # base.yml's false: the partial RoPE (PartialRotaryEmbedding), not the Qwen3.5 ymls' text mRoPE. + "qwen3.8-2.4t-a95b": dict( + layers=92, + emb=8192, + heads=64, + kv_heads=4, + head_dim=256, + moe_mlp=2048, + experts=512, + topk=10, + vocab=248320, + gdn_key_heads=16, + gdn_value_heads=128, + gdn_key_head_dim=128, + gdn_value_head_dim=128, + qwen_rope="partial", + ), + "qwen3.5-397b-a17b": dict( + layers=60, + emb=4096, + heads=32, + kv_heads=2, + head_dim=256, + moe_mlp=1024, + experts=512, + topk=10, + vocab=248320, + gdn_key_heads=16, + gdn_value_heads=64, + gdn_key_head_dim=128, + gdn_value_head_dim=128, + qwen_rope="mrope", + ), + "qwen3.5-35b-a3b": dict( + layers=40, + emb=2048, + heads=16, + kv_heads=2, + head_dim=256, + moe_mlp=512, + experts=256, + topk=8, + vocab=248320, + gdn_key_heads=16, + gdn_value_heads=32, + gdn_key_head_dim=128, + gdn_value_head_dim=128, + qwen_rope="mrope", + ), +} +MODELS = ("deepseek3",) + tuple(QWEN_MODELS) +QWEN_ONLY_FLAGS = ( + "kv_heads", + "head_dim", + "gdn_key_heads", + "gdn_value_heads", + "gdn_key_head_dim", + "gdn_value_head_dim", + "qwen_rope", +) +DEEPSEEK_ONLY_FLAGS = ("q_lora", "kv_lora", "qk_nope_head_dim", "qk_rope_head_dim", "v_head_dim") + + +PLATFORMS = ("auto", "tpu", "gpu", "cpu") +# The flags whose parser defaults are TPU's kernels and collectives, and what a +# GPU run takes instead when it leaves them out (ModelParser): cuDNN's flash +# attention, tokamax's grouped matmuls on a compact local buffer (no MaxText +# SparseCore sort, no megablox), a gathered embedding, NCCL collectives. CPU +# keeps TPU's defaults (the tests pin them). +GPU_DEFAULTS = { + "attn": "cudnn", + "gmm_impl": "tokamax", + "ragged_sort": "off", + "embed": "gather", + "fsdp_collectives": "xla", + "ep_collectives": "xla", + "layer_tree": "per_layer", + "norm_reduce": "allreduce", + "gdn_conv": "shift", + "gdn_scan": "triton", + "direct_experts": "on", + "combine_impl": "triton", + "route_weights": "experts", +} + + +def resolve_platform(name="auto"): + """--platform: 'tpu', 'gpu' or 'cpu' as given, else, without starting a jax + backend (jax.distributed comes first): the first platform the process is + pinned to (jax.config's jax_platforms, else JAX_PLATFORMS; cuda / rocm / gpu + -> 'gpu'), else 'tpu' where libtpu is installed, 'gpu' where a jax CUDA / + ROCm plugin is, 'cpu' otherwise.""" + if name != "auto": + return name + pinned = _config_platforms() or os.environ.get("JAX_PLATFORMS", "") + first = str(pinned).split(",")[0].strip().lower() + if first: + return "gpu" if first in ("cuda", "rocm", "gpu") else first + + def has(mod): + try: + return importlib.util.find_spec(mod) is not None + except (ImportError, ValueError): + return False + + if has("libtpu"): + return "tpu" + if any(has(m) for m in ("jax_cuda13_plugin", "jax_cuda12_plugin", "jax_rocm7_plugin", "jax_rocm60_plugin")): + return "gpu" + return "cpu" + + +def _config_platforms(): + """jax.config's jax_platforms: what jax.config.update pinned, or JAX_PLATFORMS when jax was imported.""" + return getattr(jax.config, "jax_platforms", None) + + +class ModelParser(argparse.ArgumentParser): + """The base of `make_parser`'s parser (`_Parser`): for each parse, `--model` + picks the shape flags' defaults -- the flags' own for deepseek3, its + QWEN_MODELS entry for a Qwen3.5-family model (with the DeepSeek-only flags at + None) -- so every caller of `parse_args` gets the model's dims for the flags + it does not give. The model is the one the parse ends with, by argparse's + own precedence: the arguments' --model, else a given `namespace`'s, else the + default. The defaults are the parser's own again once the parse returns.""" + + def parse_known_args(self, args=None, namespace=None): + args = sys.argv[1:] if args is None else list(args) # read twice: a one-shot iterable once + # Peek into a namespace holding only the given one's model and platform (no other attribute of the caller's to + # touch): argparse's precedence -- the arguments', else the namespace's, else the default -- for both. + given = {k: getattr(namespace, k) for k in ("model", "platform") if hasattr(namespace, k)} + first = super().parse_known_args(args, argparse.Namespace(**given) if given else None)[0] + model = first.model + over = dict(QWEN_MODELS[model], **{k: None for k in DEEPSEEK_ONLY_FLAGS}) if model in QWEN_MODELS else {} + # --platform: a GPU run's kernel and collective defaults (GPU_DEFAULTS) + platform = resolve_platform(getattr(first, "platform", "auto")) + if platform == "gpu": + over.update(GPU_DEFAULTS) + saved = {act: act.default for act in self._actions if act.dest in over} + try: + for act in saved: + act.default = over[act.dest] + return super().parse_known_args(args, namespace) + finally: + for act, default in saved.items(): + act.default = default + + +def resolve_inplace_dw(v, tokamax_gmm="mosaic"): + """--inplace-dw auto -> 'all' where gpu_kernels.ragged_dw's tcgen05 kernel takes an fp32 accumulator (an sm_100 + device, MOSAIC_F32_ACC: 1.78 ms against 2.67 for tokamax's dW plus the add at DeepSeek-V3's EP 8 shapes) and + runs it (--tokamax-gmm mosaic: ds_ep._ragged_dw gives the others ragged_dw's Triton kernel, 2.69 ms, or lax's + form), else 'on'. Every process of a run sees the same GPUs, so they all resolve it alike.""" + if v != "auto": + return v + if tokamax_gmm != "mosaic": + return "on" + try: + from maxtext.experimental.mpmd.jax import gpu_kernels + + fast = jax.default_backend() == "gpu" and gpu_kernels.mosaic_supported() and gpu_kernels.MOSAIC_F32_ACC + except Exception: # pylint: disable=broad-except + fast = False + return "all" if fast else "on" + + +def _or_default(v, default): + """A flag's value, or `default` where it was not given (None) -- an explicit 0 stays 0 instead of becoming the + default (--qk-rope-head-dim 0 is MLA without RoPE; model_config refuses the head dims that leave no attention).""" + return default if v is None else v + + +def model_config(a): + """The model config the flags describe: a DeepSeekConfig, or a Qwen35Config under a Qwen3.5-family --model.""" + name = getattr(a, "model", "deepseek3") + if name in QWEN_MODELS: + return qwen_model_config(a) + if name != "deepseek3": + raise ValueError(f"--model {name!r}: want one of {MODELS}") + given = [f'--{k.replace("_", "-")}' for k in QWEN_ONLY_FLAGS if getattr(a, k, None) is not None] + if given: + raise ValueError(f"{given}: Qwen3.5-family flags, but --model is deepseek3") + dense, groups, topk_groups = ( + getattr(a, "dense_layers", 0), + getattr(a, "routing_groups", -1), + getattr(a, "topk_groups", -1), + ) + bias, rate = getattr(a, "routed_bias", "off") == "on", getattr(a, "bias_update_rate", 0.0) + if (groups > 0) != (topk_groups > 0): + raise ValueError("--routing-groups and --topk-groups come together (MaxText n_routing_groups / topk_routing_group)") + if groups > 0 and (a.experts % groups or topk_groups > groups or a.topk > topk_groups * (a.experts // groups)): + raise ValueError( + f"--routing-groups {groups} --topk-groups {topk_groups}: want groups dividing --experts " + f"{a.experts}, at most {groups} groups kept, holding --topk {a.topk} experts" + ) + if rate and not bias: + raise ValueError("--bias-update-rate updates the routed bias: needs --routed-bias on") + if getattr(a, "routing", "random") == "random" and (bias or groups > 0): + raise ValueError( + "--routed-bias / --routing-groups shape top-k routing: they need --routing topk (random routing " + "ignores them, as MaxText use_random_routing does)" + ) + base2 = getattr(a, "sa_base2_exp", None) # None: tokamax's base-2, MaxText's default + if base2 == "on" and a.attn != "tokamax_splash": + raise ValueError(f"--sa-base2-exp on is tokamax_splash's base-2 softmax; --attn {a.attn} computes the exact one") + base2 = base2 != "off" + nope, rope, v = ( + _or_default(getattr(a, k, None), d) + for k, d in (("qk_nope_head_dim", 128), ("qk_rope_head_dim", 64), ("v_head_dim", 128)) + ) + if min(nope, rope) < 0 or nope + rope < 1 or v < 1: + # v 0: an empty attention output, every layer's attention adds zeros; nope + rope 0: no query / key channels + raise ValueError( + f"--qk-nope-head-dim {nope} --qk-rope-head-dim {rope} --v-head-dim {v}: want a value head dim " + "of at least 1 and non-negative query / key head dims summing to at least 1 " + "(--qk-rope-head-dim 0 is MLA without RoPE)" + ) + dkv = getattr(a, "sa_block_dkv", None) or a.sa_block + return DeepSeekConfig( + vocab_size=a.vocab, + emb_dim=a.emb, + num_decoder_layers=a.layers, + first_num_dense_layers=dense, + num_query_heads=a.heads, + num_kv_heads=a.heads, + q_lora_rank=a.q_lora, + kv_lora_rank=a.kv_lora, + qk_nope_head_dim=nope, + qk_rope_head_dim=rope, + v_head_dim=v, + mlp_dim=getattr(a, "mlp", None) or a.moe_mlp, + moe_mlp_dim=a.moe_mlp, + num_experts=a.experts, + num_experts_per_tok=a.topk, + shared_experts=1, + routed_bias=bias, + routed_bias_update_rate=rate, + n_routing_groups=groups, + topk_routing_group=topk_groups, + mtp_num_layers=getattr(a, "mtp", 0), + mtp_loss_scaling_factor=getattr(a, "mtp_loss_scale", 0.1), + float32_gate_logits=getattr(a, "float32_gate_logits", "off") == "on", + load_balance_loss_weight=getattr(a, "lb_loss_weight", 0.0), + moe_use_megatron_seq_aux_loss=getattr(a, "lb_loss_weight", 0.0) > 0, + attention_kernel=a.attn, + sa_block_q=a.sa_block, + sa_block_kv=a.sa_block, + sa_block_kv_compute=a.sa_block_kv_compute, + sa_block_q_dkv=dkv, + sa_block_kv_dkv=dkv, + sa_block_kv_dkv_compute=getattr(a, "sa_block_kv_dkv_compute", None) or dkv, + sa_cost_estimate_flops_fwd=a.cost_estimate, + sa_cost_estimate_flops_bwd=a.cost_estimate, + sa_use_base2_exp=base2, + max_target_length=a.seq, + remat_policy="full", + dtype=jnp.dtype(getattr(a, "dtype", "bfloat16")), + weight_dtype=jnp.dtype(getattr(a, "weight_dtype", "float32")), + ) + + +def qwen_model_config(a) -> Qwen35Config: + """A Qwen3.5-family `--model` as the maxtext.experimental.mpmd.jax.qwen35 config ds_ep's Qwen layers read: + MaxText's qwen3_5 decoder (3 Gated DeltaNet layers, then one gated full-attention layer; every layer MoE with one + gated shared expert), the dims from the flags (`ModelParser` defaults them to the model's). --float32-gate-logits + is MaxText's for qwen3_5 too: GateLogit's logits in fp32, from an fp32 compute copy of the router's kernel. The + model flags only the DeepSeek-V3 layers implement are refused: MLA's ranks, dense layers and routing groups, which + MaxText's qwen3_5 does not have either (get_topk routes by groups only for the model names of + common_types.DEEPSEEK_V3_ROUTING_MODEL_PREFIXES and GLM5's decoder block -- never a qwen3_5 one); the routed bias's + update rate (MaxText balances loss-free in its DeepSeek decoder blocks only); and the routed bias, the aux loss and + MTP, which this pipeline's Qwen layers do not implement (MaxText's qwen3_5 takes a routed bias and a load-balance + loss, but --routed-bias is DeepSeek-V3's, which picks the experts without weighing them, and --lb-loss-weight its + sequence-wise aux loss).""" + given = [f'--{k.replace("_", "-")}' for k in DEEPSEEK_ONLY_FLAGS if getattr(a, k, None) is not None] + given += [ + flag + for flag, on in ( + ("--dense-layers", getattr(a, "dense_layers", 0)), + ("--mlp", getattr(a, "mlp", None) is not None), + ("--routed-bias", getattr(a, "routed_bias", "off") == "on"), + ("--bias-update-rate", getattr(a, "bias_update_rate", 0.0)), + ("--routing-groups", getattr(a, "routing_groups", -1) > 0), + ("--topk-groups", getattr(a, "topk_groups", -1) > 0), + ("--lb-loss-weight", getattr(a, "lb_loss_weight", 0.0)), + ("--mtp", getattr(a, "mtp", 0)), + ) + if on + ] + if given: + raise ValueError(f"{given}: only the DeepSeek-V3 layers implement these, but --model is {a.model}") + missing = [f'--{k.replace("_", "-")}' for k in QWEN_ONLY_FLAGS if getattr(a, k, None) is None] + if missing: + raise ValueError(f"--model {a.model}: {missing} unset (make_parser().parse_args defaults them to the model)") + base2 = getattr(a, "sa_base2_exp", None) # None: tokamax's base-2, MaxText's default + if base2 == "on" and a.attn != "tokamax_splash": + raise ValueError(f"--sa-base2-exp on is tokamax_splash's base-2 softmax; --attn {a.attn} computes the exact one") + dkv = getattr(a, "sa_block_dkv", None) or a.sa_block + rd = int(a.head_dim * Qwen35Config.partial_rotary_factor) + # Text positions make every mRoPE section the same rotation; any split of rotary_dim // 2 into three + # non-negative parts is valid: the most even one (qwen3.5's (11, 11, 10) at head_dim 256). + q, r = divmod(rd // 2, 3) + sections = tuple(q + (i < r) for i in range(3)) + return Qwen35Config( + vocab_size=a.vocab, + emb_dim=a.emb, + num_decoder_layers=a.layers, + num_query_heads=a.heads, + num_kv_heads=a.kv_heads, + head_dim=a.head_dim, + mrope_section=sections, + gdn_num_key_heads=a.gdn_key_heads, + gdn_num_value_heads=a.gdn_value_heads, + gdn_key_head_dim=a.gdn_key_head_dim, + gdn_value_head_dim=a.gdn_value_head_dim, + moe_mlp_dim=a.moe_mlp, + num_experts=a.experts, + num_experts_per_tok=a.topk, + shared_experts=1, + attention_kernel=a.attn, + use_mrope=a.qwen_rope == "mrope", + float32_gate_logits=getattr(a, "float32_gate_logits", "off") == "on", + sa_block_q=a.sa_block, + sa_block_kv=a.sa_block, + sa_block_kv_compute=a.sa_block_kv_compute, + sa_block_q_dkv=dkv, + sa_block_kv_dkv=dkv, + sa_block_kv_dkv_compute=getattr(a, "sa_block_kv_dkv_compute", None) or dkv, + sa_cost_estimate_flops_fwd=a.cost_estimate, + sa_cost_estimate_flops_bwd=a.cost_estimate, + sa_use_base2_exp=base2 != "off", + gdn_conv_impl=getattr(a, "gdn_conv", "conv"), + gdn_scan_impl=getattr(a, "gdn_scan", "scan"), + max_target_length=a.seq, + dtype=jnp.dtype(getattr(a, "dtype", "bfloat16")), + weight_dtype=jnp.dtype(getattr(a, "weight_dtype", "float32")), + ) + + +# Measured cost tables `--costs` can name (see schedule.py's measured costs): +# 'v6e' was measured with padded tiles (tk = D in every kernel), 'v6e_tiles' with `--tiles v6e`. +COST_TABLES = {"tpu7x": sched.TPU7X_COSTS, "v6e": sched.V6E_COSTS, "v6e_tiles": sched.V6E_TILES_COSTS} + + +def load_costs(spec): + """`--costs`: a JSON object of program costs, `@path` to a file holding + one (what `python3 -m maxtext.experimental.mpmd.jax.xprof costs DIR` prints), or the name + of a table in COST_TABLES (to price a CPU dry run as the TPU would). + Anything else -- a table name COST_TABLES does not have, say -- is a + ValueError naming the flag and the tables.""" + if not spec: + return None + if spec in COST_TABLES: + return dict(COST_TABLES[spec]) + if spec.startswith("@"): + with open(spec[1:]) as f: + spec = f.read() + elif not spec.lstrip().startswith("{"): # a JSON object is the one form left + raise ValueError(f"--costs {spec!r}: not a JSON object, @file or one of the tables {', '.join(COST_TABLES)}") + return {k: v for k, v in json.loads(spec).items() if not k.startswith("_")} # '_source' etc.: notes + + +def split_costs(table, layer_split, remat_last=False): + """A cost table of even chunks -> the same for chunks of `layer_split` layers. Every key describes an even + split's chunk, and each chunk but the last costs in proportion to its layers: its F / B -- the table's F{c} / + B{c} where it has them (a per-chunk key is that chunk's own cost and wins over F / B), else chunk 0's F0 / B0, + else F / B -- its split backward's I / W where measured (I{c} / W{c}, else I / W; sched.zb_costs fills in the + others from the scaled B{c}), and its stash keys, the ones `sched.cost_table` reads for it, scaled as chunk c's + own (a d-key stays one, added to the scaled F{c} / B{c}). The last chunk's fused A keeps its head and norm and + moves its layers' share: B a chunk's worth, as its backward recomputes nothing (StageConfig.remat_fused_last + False), or F + B under `remat_last`; the head's share (A less an even chunk's layers) is held at 0 or more, so a + table whose A undercuts its layers never prices the last chunk below its layers. Split (--zb-split-last), its W + -- its layers' weight gradients, W{C-1} or WA where measured, else A - AI from a measured AI -- scales with its + layers, and a measured AI moves as A does less what W takes of the move.""" + if len(set(layer_split)) == 1: + return table + n = sum(layer_split) / len(layer_split) + out = dict(table) + pols = sorted( + { + k.split(":", 1)[1] + for k in table + if ":" in k and k.split(":", 1)[0].lstrip("d").rstrip("0123456789") in ("Fs", "Bs") + } + ) + for c, k in enumerate(layer_split[:-1]): + for kind in ("F", "B"): + base = table.get(f"{kind}{c}", table.get(f"{kind}0" if c == 0 else kind, table[kind])) + out[f"{kind}{c}"] = base * k / n + s = f"{kind}s" + for names in [[f"{s}{c}:{p}", f"d{s}{c}:{p}", f"{s}:{p}", f"d{s}:{p}"] for p in pols] + [[f"{s}{c}", s]]: + have = next((x for x in names if x in table), None) # the key cost_table would read for chunk c + if have is not None: + out[names[1] if have.startswith("d") else names[0]] = table[have] * k / n + for kind in ("I", "W") if c else (): # a middle chunk's measured split (chunk 0's backward never splits) + base = table.get(f"{kind}{c}", table.get(kind)) + if base is not None: + out[f"{kind}{c}"] = base * k / n + L, r = len(layer_split) - 1, layer_split[-1] / n + layers = table["B"] + (table["F"] if remat_last else 0.0) # an even fused chunk's layers + out["A"] = max(table["A"] - layers, 0.0) + layers * r + w_key = next((x for x in (f"W{L}", "WA") if x in table), None) # the split last chunk's W, where measured + w = table[w_key] if w_key else table["A"] - table["AI"] if "AI" in table else None + if w_key: + out[w_key] = w * r + if "AI" in table: + out["AI"] = table["AI"] + (out["A"] - table["A"]) - (w * r - w) + return out + + +def default_costs(device_kind, scfg): + """The program costs `--schedule timed / stash / interleaved` start from + (any `--costs` key overrides them): TPU7x ones (TPU7X_COSTS) anywhere but + a v6e, and on a v6e the medians measured with the megablox tiles `scfg` + runs (ds_ep.TILES): + + v6e V6E_TILES_COSTS, measured with them. + clamped V6E_TILES_COSTS, though never measured: the schedulers read + only the costs' ratios, and what skews V6E_COSTS' ratios is the + padding -- the padded kernels are one of a forward's three + grouped matmuls but three of a backward's six, so its B/F is + 2.67 against the unpadded 2.37. clamped pads nothing, like the + v6e tiles; it differs from them in tm / tn, which every kernel + shares (config A: 1447 ms/step clamped, 1328 v6e, 1607 padded). + Its stash deltas were measured unpadded too. + other V6E_COSTS, measured with padded tiles (any other tiling). + + Under batch split's split_dw 'acc' the presets count with their wi dW tm + capped at 256, as `build` and StageConfig cap them (split_acc_wi_tiling). + """ + if "v6" not in device_kind.lower(): + return sched.TPU7X_COSTS + tiling = (tuple(scfg.wi_tiling), tuple(scfg.wo_tiling)) + presets = [ds_ep.TILES[k](scfg.model) for k in ("v6e", "clamped")] + if scfg.batch_split and scfg.batch_split_impl == "native" and scfg.split_dw == "acc": # (split_acc_wi_tiling) + presets = [(ds_ep.split_acc_wi_tiling(wi), tuple(wo)) for wi, wo in presets] + if tiling in [(tuple(wi), tuple(wo)) for wi, wo in presets]: + return sched.V6E_TILES_COSTS + return sched.V6E_COSTS + + +def resolve_tilings(a, cfg: DeepSeekConfig | Qwen35Config): + """(wi_tiling, wo_tiling): the --tiles preset (ds_ep.TILES; wi's dW tm + capped at 256 under --batch-split on ds_ep.split_layers -- --batch-split-impl + native, a Qwen3.5-family model's default -- with --split-dw acc, + ds_ep.split_acc_wi_tiling), then --wi-tiling / --wo-tiling. + + Attributes a hand-built namespace lacks fall back to the defaults. + """ + wi, wo = ds_ep.TILES[getattr(a, "tiles", None) or "clamped"](cfg) + if getattr(a, "batch_split", False) and batch_split_impl(a) == "native" and getattr(a, "split_dw", "acc") == "acc": + wi = ds_ep.split_acc_wi_tiling(wi) + if getattr(a, "wi_tiling", None): + wi = tuple(a.wi_tiling) + if getattr(a, "wo_tiling", None): + wo = tuple(a.wo_tiling) + return tuple(wi), tuple(wo) + + +def native_transport_aborts(device_kind): + """Does jax's cross-host copy (--transport native under --distributed) + abort every receiver on this device kind? On TPU v6e and v5p with jax + 0.11.1 / libtpu 0.0.46 it does (a v6e-256 and a v5p-128, 2026-10: + std::bad_alloc in the receive); libtpu reports v5p as 'TPU v5' (Pathways: + 'TPU v5p'), v5e as 'TPU v5 lite'.""" + kind = str(device_kind).lower() + return "v6" in kind or kind in ("tpu v5", "tpu v5p") + + +def float32_ragged_sort_problem(a, scfg): + """The message to stop with if the stage config `scfg` (from the parsed + flags `a`) computes in float32 with the ragged sort where MaxText's + ragged_gather_reduce (maxtext/kernels/ragged/ragged_gather_reduce_v2.py) + runs its JAX fallback -- off TPU (GPU, CPU), or on a TPU without + SparseCores, as that function chooses -- else None. The fallback returns + bfloat16 whatever it is given, so the sort's backward hands a bfloat16 + gradient to a float32 activation, and the first backward program fails to + lower on a bare AssertionError from jax's autodiff. DeepSeek-V3's layers + and a Qwen3.5-family model's run the same dispatch; Lineage's (--batch-split + on them) run their own, never the ragged sort.""" + if not scfg.use_ragged_sort or scfg.lineage_split or jnp.dtype(scfg.model.dtype) == jnp.bfloat16: + return None + from jax.experimental.pallas import tpu as pltpu + + if pltpu.is_tpu_device() and pltpu.get_tpu_info().sparse_core is not None: + return None + return ( + f"--dtype {a.dtype} with the ragged sort (--ragged-sort {a.ragged_sort} at --ep {a.ep}) needs a TPU with " + f"SparseCores, not {jax.devices()[0].device_kind}: elsewhere MaxText's ragged_gather_reduce returns " + "bfloat16 and the backward fails; add --ragged-sort off (the argsort dispatch, float32 anywhere)" + ) + + +def qwen_model(a): + """Do the flags `a` name a Qwen3.5-family --model (QWEN_MODELS), whose layers Lineage does not build?""" + return getattr(a, "model", "deepseek3") in QWEN_MODELS + + +def on_gpu(a): + """Do the flags `a` run on GPU (--platform gpu, or auto resolving to it: `resolve_platform`)?""" + return resolve_platform(getattr(a, "platform", "auto")) == "gpu" + + +def model_batch_split_impl(a): + """The --batch-split-impl the flags' --model makes the default: lineage for deepseek3, native (ds_ep.split_layers) + for a Qwen3.5-family model, whose layers Lineage does not build -- as ds_ep.StageConfig resolves batch_split_impl + None by its model -- and for any model on GPU (`on_gpu`), where Lineage's kernels (Pallas TPU splash and gmmv2, + SparseCore dispatch and combine) do not run and split_layers runs the GPU kernels.""" + return "native" if qwen_model(a) or on_gpu(a) else "lineage" + + +def batch_split_impl(a): + """--batch-split-impl of the flags `a`, else (None: left out, or not in a namespace made by hand) the model's + (`model_batch_split_impl`).""" + impl = getattr(a, "batch_split_impl", None) + return model_batch_split_impl(a) if impl is None else impl + + +def uses_lineage(a): + """Do the flags `a` batch-split on Lineage's layers (--batch-split, --batch-split-impl lineage: DeepSeek-V3's + default)?""" + return bool(getattr(a, "batch_split", False)) and batch_split_impl(a) == "lineage" + + +# The flags that pick among ds_ep's own layer kernels, which --batch-split on Lineage's layers does not run +# (ds_ep_lineage.IGNORED_STAGE_KNOBS / IGNORED_MODEL_FIELDS): the routed experts' grouped matmuls and their tilings, +# the dispatch, the EP collectives, the halves' dW combine, the experts' weight reads, where the routing weights +# apply, the attention kernel, its softmax (Lineage's splash is base-2 always: --sa-base2-exp on is what it computes +# anyway) and its cost estimate. +LINEAGE_IGNORED_FLAGS = ( + "gmm_impl", + "tiles", + "wi_tiling", + "wo_tiling", + "strict_tiling", + "ragged_sort", + "ep_collectives", + "split_dw", + "expert_weights", + "route_weights", + "attn", + "sa_base2_exp", + "cost_estimate", +) + + +def lineage_ignored(a): + """The LINEAGE_IGNORED_FLAGS `a` sets away from their defaults (--sa-base2-exp: off) where --batch-split runs + Lineage's layers -> ['--flag value', ...]; [] under any other flags, and for a Qwen3.5-family model (which `build` + refuses there). Accepted, as they still mean what they say to an unsplit run of the same flags; main warns of + each.""" + if not uses_lineage(a) or qwen_model(a): + return [] + ap, out = make_parser(), [] + for k in LINEAGE_IGNORED_FLAGS: + d = ap.get_default(k) + v = getattr(a, k, d) + if v == d or (k == "sa_base2_exp" and v != "off"): + continue + flag = "--" + k.replace("_", "-") + out.append(flag if v is True else f"{flag} {' '.join(map(str, v)) if isinstance(v, (list, tuple)) else v}") + return out + + +def lineage_unused(a, given=()): + """The other direction: the flags only --batch-split on Lineage's layers reads, given where it does not run (not + `uses_lineage`) -> ['--flag value: why', ...]; [] under any other flags. Accepted; main warns of each. Given: + set away from its default, or named in `given`, the flags (dests) a caller knows were given -- ds_ep_parity's + --lineage-capacity-factor, whose default None tells it apart; main's flags cannot be told apart at their defaults + (--lineage-capacity-factor 2, --batch-split-impl the model's: lineage, or native for a Qwen3.5-family model).""" + if uses_lineage(a): + return [] + split, impl, model_impl = bool(getattr(a, "batch_split", False)), batch_split_impl(a), model_batch_split_impl(a) + out, d = [], make_parser().get_default("lineage_capacity_factor") + if "lineage_capacity_factor" in given or getattr(a, "lineage_capacity_factor", d) != d: + # split, not on Lineage's layers: on split_layers, given (DeepSeek-V3) or the model's default (the Qwen3.5 family) + why = ( + "without --batch-split" + if not split + else f"by --batch-split-impl {impl}" + if impl != model_impl + else f"by --model {a.model}'s batch split, ds_ep.split_layers" + ) + out.append( + f"--lineage-capacity-factor {a.lineage_capacity_factor:g}: not used {why} (Lineage's MoE chunk size: " + "only --batch-split on Lineage's layers reads it)" + ) + if not split and ("batch_split_impl" in given or impl != model_impl): + out.append(f"--batch-split-impl {impl}: not used without --batch-split (it picks the batch " "split's layers)") + return out + + +def lineage_partial(a): + """The flags `a` gives that --batch-split on Lineage's layers applies in part only -> ['--flag value: how', ...]; + [] under any other flags, and for a Qwen3.5-family model (which `build` refuses there). Not + LINEAGE_IGNORED_FLAGS (they still change what runs); main warns of each.""" + if not uses_lineage(a) or qwen_model(a) or getattr(a, "float32_gate_logits", "off") != "on": + return [] + return [ + "--float32-gate-logits on: on Lineage's layers only the expert selection runs in fp32 (Lineage's " + "router_dtype): the router kernel's fp32 compute copy is rounded to bf16 first, and its gradient comes back " + "in bf16 (bf16 operands, fp32 accumulation)" + ] + + +def split_defaults(a): + """The flags whose default --batch-split decides, filled in where left out (None) -> `a`, in place. First + --batch-split-impl, by the model (`batch_split_impl`): lineage for DeepSeek-V3, native for a Qwen3.5-family + model, whose layers Lineage does not build. On Lineage's layers (`uses_lineage`) --routing is topk -- they route + top-k only, there is no RNG in them -- and --shard-mode explicit: their code reads its layouts from sharding + types, so the chunks' programs run at global view on Explicit stage meshes (typed_meshes; + ds_ep.StageConfig.batch_split_impl). Else random and auto, as ever (so under a Qwen3.5-family model's batch + split too). A flag given stands: one Lineage cannot run is refused by `build` (`lineage_problems`). + make_parser's parser fills them in as it parses; `build` again for a namespace made by hand.""" + a.batch_split_impl = batch_split_impl(a) + lineage = uses_lineage(a) + if getattr(a, "routing", None) is None: + a.routing = "topk" if lineage else "random" + if getattr(a, "shard_mode", None) is None: + a.shard_mode = "explicit" if lineage else "auto" + return a + + +def lineage_problems(a, cfg: DeepSeekConfig | Qwen35Config): + """What the flags `a` ask of --batch-split on Lineage's layers that they cannot run, named by flag, every one at + once, the model's too (ds_ep_lineage.check of `cfg`, which `a` made) -> [str]; [] when they run. StageConfig + refuses the stage's settings itself (ds_ep.StageConfig._check_lineage; a one-device stage, which shard_mode + explicit cannot run, apart), Pipeline the stash and pins, ChunkPrograms an odd number of rows a device and a chunk + without a MoE layer: these say so before anything is built, in the flags' terms. A Qwen3.5-family model is + refused alone: Lineage builds none of its layers, so no other flag matters.""" + if ds_ep.is_qwen(cfg): + return [ + f"--model {a.model}: Lineage builds DeepSeek-V3's layers only, none of a Qwen3.5-family model's (Gated " + "DeltaNet, gated attention, the sigmoid-gated shared expert)" + ] + bad = [] + if a.routing == "random": + bad.append( + "--routing random: Lineage routes top-k only, there is no RNG in it (leave --routing out: topk under " + "--batch-split)" + ) + if a.shard_mode == "auto": + bad.append( + "--shard-mode auto: Lineage's code reads its layouts from sharding types, so the chunks' programs run " + "at global view on Explicit stage meshes (leave --shard-mode out: explicit under --batch-split)" + ) + if a.fsdp * a.ep == 1: # (whatever --shard-mode says: Lineage's layers need explicit) + bad.append( + f"--fsdp {a.fsdp} --ep {a.ep}: a one-device stage, which the Explicit stage meshes Lineage's layers " + "run on cannot be (fsdp x ep > 1: jax lowers a one-device stage's shard_maps inline, which refuses " + "their unreduced outputs)" + ) + if getattr(a, "grad_reduce", "step") == "microbatch": + bad.append( + "--grad-reduce microbatch: the programs add Lineage's per-device partial weight gradients into " + "unreduced accumulators, reduce-scattered once a step (step)" + ) + if getattr(a, "ragged_buffer_factor", -1.0) > 0: + bad.append( + f"--ragged-buffer-factor {a.ragged_buffer_factor:g}: Lineage is dropless, > 0 drops the tokens past " + "the ring's capped dispatch buffer (<= 0)" + ) + if getattr(a, "cp", 1) > 1: + bad.append( + f"--cp {a.cp}: the batch split halves the rows a device holds, context parallelism holds one (and " + "Lineage's splash attention shards heads, never the sequence)" + ) + stash = [f"--stash {a.stash}"] if getattr(a, "stash", "none") != "none" else [] + if a.schedule == "stash": + stash.append("--schedule stash") + if stash: + bad.append( + f"{' / '.join(stash)}: a chunk runs Lineage's layers in one custom VJP whose residuals are Lineage's " + "own, which no stash policy names (--schedule search or timed search the order without stash)" + ) + if ds_ep.parse_prefetch_pin(getattr(a, "prefetch_pin", "off")) != "off": # as Pipeline reads it (None: off) + bad.append( + f"--prefetch-pin {a.prefetch_pin}: pins tie gathers to points of ds_ep's own layers (hn / xs / y), " + "which Lineage's layers have none of" + ) + if cfg.num_experts % a.ep: + bad.append( + f"--experts {cfg.num_experts} is not a multiple of --ep {a.ep}: Lineage splits the experts evenly " "over EP" + ) + n_dev, rows = a.fsdp * a.ep, a.gbs // a.mb + if getattr(a, "cp", 1) == 1 and a.gbs % a.mb == 0 and rows % n_dev == 0 and (rows // n_dev) % 2: # (else Pipeline's) + bad.append( + f"--gbs {a.gbs} / --mb {a.mb}: {rows // n_dev} row(s) a device a microbatch (fsdp x ep " + f"{n_dev}): the batch split runs each device's rows as two halves, so it wants an even number" + ) + split, n_dense = parse_layer_split(getattr(a, "layer_split", "")), cfg.first_num_dense_layers + if split is not None and n_dense and sum(split) == cfg.num_decoder_layers: # every layer counted + if dense_only := [c for c, end in enumerate(np.cumsum(split)) if end <= n_dense]: + bad.append( + f"--layer-split {a.layer_split}: chunk(s) {dense_only} hold dense layers only (it counts every " + f"layer, the {n_dense} dense ones first): Lineage batch-splits MoE layers, so every chunk needs one" + ) + try: + ds_ep_lineage.check(cfg) + except ValueError as e: + bad.append(str(e)) + return bad + + +def lineage_missing(a): + """Why --batch-split on Lineage's layers cannot run here -- Lineage is not importable: the ImportError's message + (ds_ep_lineage.import_lineage) -- else None (also + under any other flags, and for a Qwen3.5-family model, which `build` refuses on Lineage's layers whatever is + installed). The pipeline builds without it, its programs import it when they trace: main asks first.""" + if not uses_lineage(a) or qwen_model(a): + return None + try: + ds_ep_lineage.import_lineage() + except ImportError as e: + return f"{e} (off TPU, --batch-split-impl native runs without it)" + return None + + +def native_split_refusal(a, devices=None): + """Why the flags `a` cannot batch-split DeepSeek-V3 on ds_ep.split_layers (--batch-split --batch-split-impl + native) on `devices`, the devices the pipeline runs on (default jax.devices(), which starts the backend: build + asks after main's init_distributed): on TPU devices -- a TPU VM's own, or Pathways' through the IFRT proxy, which + report the platform tpu -- Lineage's layers run DeepSeek-V3's batch split. Else None (also under any other + flags; for a Qwen3.5-family model, whose only batch split split_layers is; and on other devices, where Lineage's + TPU kernels do not run: split_layers is DeepSeek-V3's batch split on GPU, its default there, and on CPU). The + devices decide, not --platform, which picks the flags' defaults before any backend starts and resolves auto to + tpu wherever libtpu is installed: a CPU process with libtpu installed (MaxText's CPU CI) runs on CPU devices. + `build` refuses it.""" + if not getattr(a, "batch_split", False) or batch_split_impl(a) != "native" or qwen_model(a): + return None + if not any(_is_tpu(d) for d in (jax.devices() if devices is None else devices)): + return None + return ( + "--batch-split-impl native: on TPU DeepSeek-V3's batch split runs Lineage's layers (--batch-split-impl " + "lineage, its default); ds_ep.split_layers batch-splits DeepSeek-V3 off TPU only (on GPU, its default " + "there, and on CPU), and the Qwen3.5 family anywhere" + ) + + +def lineage_off_tpu(a, devices=None): + """Why --batch-split on Lineage's layers cannot run on `devices` (default jax.devices(), which initializes the + backend: main asks after init_distributed) -- they are not all TPU devices, and Lineage's kernels (Pallas TPU + splash and gmmv2, SparseCore dispatch and combine) have no other path: the first program's trace would fail -- + else None (also under any other flags, and for a Qwen3.5-family model, which `build` refuses on Lineage's layers + on any backend). ds_ep_aot refuses a non-TPU backend itself.""" + if not uses_lineage(a) or qwen_model(a): + return None + devs = jax.devices() if devices is None else devices + if not (off := sorted({str(getattr(d, "platform", "?")) for d in devs if not _is_tpu(d)})): + return None + return ( + f"Lineage's layers run TPU kernels only (Pallas splash and gmmv2, SparseCore dispatch and combine), and " + f"this process's devices are {' / '.join(off)} ones (--batch-split-impl native runs here)" + ) + + +def ep_collectives_arg(s): + """--ep-collectives: auto, xla or ppermute for every stage, or one of xla / + ppermute per stage, comma-separated (e.g. ppermute,xla).""" + if s in ds_ep.EP_COLLECTIVES or ("," in s and set(s.split(",")) <= {"xla", "ppermute"}): + return s + raise argparse.ArgumentTypeError( + f"{s!r}: expected auto, xla, ppermute, or one of xla / ppermute per " "stage, comma-separated (e.g. ppermute,xla)" + ) + + +def prefetch_pin_arg(s): + """--prefetch-pin: off, auto or a SPEC, checked for its form here + (ds_ep.parse_prefetch_pin) and for its leaf names when the pipeline is + built.""" + try: + ds_ep.parse_prefetch_pin(s) + except ValueError as e: + raise argparse.ArgumentTypeError(str(e)) from None + return s.strip() + + +def float_dtype_arg(s): + """--rs-dtype, --acc-dtype, --weight-dtype: any name jnp.dtype reads (bfloat16, float32, f4, ...) of a floating + dtype, kept as given. An integer one would truncate every reduced gradient, accumulator or master weight to 0: + a gradient norm of 0 and a loss that never moves, with no error.""" + try: + dt = jnp.dtype(s) + except TypeError: + raise argparse.ArgumentTypeError(f"{s!r} is not a dtype: want a floating one, e.g. bfloat16 or float32") from None + if not jnp.issubdtype(dt, jnp.floating): + raise argparse.ArgumentTypeError(f"want a floating dtype, e.g. bfloat16 or float32, not {s!r}") + return s + + +def resolved_config(a, p): + """Write what pipeline `p` resolved back into its arguments `a`, so a + run's recorded config (run.json, ds_ep_aot's --json) names what ran: the + placement --placement defaulted to, the schedule --schedule did, the + scope --fsdp-scope did.""" + a.placement, a.schedule, a.fsdp_scope = p.placement, p.schedule, p.fsdp_scope + + +def build(a, meshes=None, aot=False, stage_lineage_sparsecore=None, proxy=None, **scfg_overrides): + """The Pipeline the flags `a` (make_parser's, or a namespace made by hand: missing flags take their defaults) + describe, on `meshes` (default: stage_meshes of --layout; `aot`: a topology this process does not own; `proxy`: + planned for one Pathways client, Pipeline's), with `scfg_overrides` replacing StageConfig fields and + `stage_lineage_sparsecore` libtpu's per-stage answers for Lineage's SparseCore regions (Pipeline; ds_ep_aot's). + It refuses --pair-stages / --pair-gain outside --schedule interleaved and --batch-split-impl native for DeepSeek-V3 + on TPU (`native_split_refusal`), and under --batch-split on Lineage's layers every flag they cannot run that the + flags alone decide, at once (`lineage_problems`), before building anything.""" + a = split_defaults(argparse.Namespace(**vars(a))) # a copy: the caller's flags stay as given + cfg = model_config(a) + if a.schedule != "interleaved" and (getattr(a, "pair_stages", None), getattr(a, "pair_gain", None)) != (None, None): + raise ValueError( + "--pair-stages / --pair-gain: the F&B pairs of --schedule interleaved's steady state, which no other " + f"schedule runs (--schedule {a.schedule or DEFAULT_SCHEDULE})" + ) + if (why := native_split_refusal(a, None if meshes is None else [m.devices.flat[0] for m in meshes])) is not None: + raise ValueError(why) + if uses_lineage(a) and (bad := lineage_problems(a, cfg)): + raise ValueError( + "--batch-split runs Lineage's layers (--batch-split-impl lineage), which cannot run this: " + + "; ".join(bad) + + ( + " (leave --batch-split-impl out: a Qwen3.5-family model's default, " "native, runs ds_ep.split_layers)" + if ds_ep.is_qwen(cfg) + else " (off TPU, --batch-split-impl native runs ds_ep.split_layers)" + ) + ) + wi_tiling, wo_tiling = resolve_tilings(a, cfg) + ep_coll = getattr(a, "ep_collectives", "auto").split(",") + inplace_dw = resolve_inplace_dw(getattr(a, "inplace_dw", "on"), getattr(a, "tokamax_gmm", "mosaic")) + scfg = ds_ep.StageConfig( + model=cfg, + fsdp=a.fsdp, + ep=a.ep, + wi_tiling=wi_tiling, + wo_tiling=wo_tiling, + strict_tiling=getattr(a, "strict_tiling", False), + gmm_impl=getattr(a, "gmm_impl", "megablox"), + tokamax_gmm=getattr(a, "tokamax_gmm", "mosaic"), + inplace_dw=inplace_dw in ("on", "all"), + inplace_dw_any_dtype=inplace_dw == "all", + buffer_masks=getattr(a, "buffer_masks", "on") == "on", + combine_impl=getattr(a, "combine_impl", "xla"), + route_weights=getattr(a, "route_weights", "combine"), + lean_experts=getattr(a, "lean_experts", "on") == "on", + layer_tree=getattr(a, "layer_tree", "stacked"), + rs_dtype=jnp.dtype(a.rs_dtype), + acc_dtype=jnp.dtype(a.acc_dtype), + grad_dtype=(None if getattr(a, "grad_dtype", "auto") == "auto" else jnp.dtype(a.grad_dtype)), + fsdp_collectives=( + a.fsdp_collectives + if a.fsdp_collectives != "auto" + else "ppermute" + if (a.fsdp in (1, 2) and a.ep in (1, 2) and (a.fsdp, a.ep) != (1, 1)) + else "xla" + ), + remat_fused_last=a.remat_last, + save_residuals=getattr(a, "save_residuals", "off") == "on", + ep_collectives=ep_coll[0] if len(ep_coll) == 1 else "auto", + grad_reduce=a.grad_reduce, + random_routing=(a.routing == "random"), + use_ragged_sort=( + (a.ep > 1 and getattr(a, "gmm_impl", "megablox") != "tokamax") + if a.ragged_sort == "auto" + else a.ragged_sort == "on" + ), + iota_embed=(getattr(a, "embed", "iota") == "iota"), + adam_math=getattr(a, "adam_math", "fp32"), + grad_clip=getattr(a, "grad_clip", 1.0), + ragged_buffer_factor=getattr(a, "ragged_buffer_factor", -1.0), + cp=getattr(a, "cp", 1), + shard_mode=getattr(a, "shard_mode", "auto"), + rs_axes=getattr(a, "rs_axes", "joint"), + gather_axes=getattr(a, "gather_axes", "joint"), + batch_split=getattr(a, "batch_split", False), + batch_split_impl=a.batch_split_impl, + lineage_capacity_factor=getattr(a, "lineage_capacity_factor", ds_ep_lineage.CAPACITY_FACTOR), + split_dw=getattr(a, "split_dw", "acc"), + expert_weights=getattr(a, "expert_weights", "stacked"), + ) + if scfg_overrides: + scfg = dataclasses.replace(scfg, **scfg_overrides) + caps = getattr(a, "stash_caps", "") + placement = getattr(a, "placement", None) or "circular" + return Pipeline( + scfg, + n_stages=a.stages, + chunks_per_stage=a.vv, + n_micro=a.mb, + global_batch=a.gbs, + seq=a.seq, + schedule=a.schedule, + layout=a.layout, + overlap=not a.no_overlap, + pf_split=a.pf_split, + rs_split=a.rs_split, + rs_self=getattr(a, "rs_self", "all"), + rs_reserve={"auto": None, "on": True, "off": False}[getattr(a, "rs_reserve", "auto")], + costs=load_costs(a.costs), + placement=placement, + stash=getattr(a, "stash", "none"), + stash_budget_gib=getattr(a, "stash_budget_gib", 4.5), + stash_caps=[int(x) for x in caps.split(",")] if caps else None, + init_by_chunk=getattr(a, "init_by_chunk", False), + offload_residuals=getattr(a, "offload_residuals", "off") == "on", + norm_reduce=getattr(a, "norm_reduce", "hops"), + interleave_group=getattr(a, "interleave_group", None) or None, + direct_experts=getattr(a, "direct_experts", "off") == "on", + zb_wbuf_cap=getattr(a, "zb_wbuf_cap", 1), + zb_split_last=getattr(a, "zb_split_last", "off") == "on", + proxy=proxy, + pair_stages=parse_pair_stages(getattr(a, "pair_stages", None)), + pair_gain=getattr(a, "pair_gain", None), + stage_ep_collectives=ep_coll if len(ep_coll) > 1 else None, + meshes=meshes, + aot=aot, + transport=getattr(a, "transport", "native"), + layer_split=parse_layer_split(getattr(a, "layer_split", "")), + fsdp_scope=getattr(a, "fsdp_scope", None), + prefetch_pin=getattr(a, "prefetch_pin", "off"), + stage_lineage_sparsecore=stage_lineage_sparsecore, + ) + + +def parse_layer_split(spec): + """--layer-split '3,1' -> (3, 1); '' -> None (an even split).""" + if not spec: + return None + try: + return tuple(int(x) for x in spec.split(",")) + except ValueError: + raise ValueError(f"--layer-split {spec!r}: want comma-separated layer counts, one a chunk (e.g. 3,1)") from None + + +def parse_pair_stages(spec): + """`--pair-stages` -> Pipeline's pair_stages: 'all' (every stage), 'none' + (no pairs) or a comma list of stages, e.g. '1' or '0,1'; None, the flag + left out, is interleaved's default (none).""" + if spec is None or spec == "all": + return spec + if spec in ("none", ""): + return () + return tuple(int(x) for x in str(spec).split(",")) + + +# The PRNG MaxText's synthetic batch is drawn with: SyntheticDataIterator's jax.random.key(0, impl="threefry2x32"). +MAXTEXT_BATCH_PRNG = "threefry2x32" + + +def _git(path): + """{'sha', 'branch', 'dirty'} of the git checkout holding `path`; {} if none.""" + + def git(*args): + return subprocess.run( + ["git", "-C", path, *args], capture_output=True, text=True, timeout=10, check=True + ).stdout.strip() + + try: + return { + "sha": git("rev-parse", "HEAD"), + "branch": git("rev-parse", "--abbrev-ref", "HEAD"), + "dirty": bool(git("status", "--porcelain", "--untracked-files=no")), + } + except (OSError, subprocess.SubprocessError): + return {} + + +def _dist_version(*names): + for n in names: + try: + return importlib.metadata.version(n) + except importlib.metadata.PackageNotFoundError: + pass + return None + + +def _import_root(): + """The directory the package imports from: ds_ep's directory, one level up for each component of its package's + dotted name -- a MaxText checkout's src/ (git finds the checkout from it). By ds_ep's name, not this module's, + which is __main__ in a `python3 -m` run.""" + root = os.path.dirname(os.path.abspath(ds_ep.__file__)) + for _ in ds_ep.__name__.split(".")[:-1]: + root = os.path.dirname(root) + return root + + +def provenance(scfg: ds_ep.StageConfig | None = None, tiles: str | None = None): + """What produced a run's numbers (best effort): the maxtext package the + kernels come from -- located with find_spec, not imported, so this is the + checkout PYTHONPATH / the editable install actually resolve -- and its git + state; 'mpmd', the directory this package imports from (`_import_root`) and + its git state, the revision of the pipeline's own code; the jax / jaxlib / + libtpu / tokamax versions, LIBTPU_INIT_ARGS, the devices, and the resolved + grouped-matmul tilings; under batch split on Lineage's layers the Lineage + package's path and git state too (ds_ep_lineage.provenance, which imports + it: None, with the error, where it does not import) and its capacity factor. + Under Pathways the mode too (`pathways.describe`: the proxy client, the + server's build and the image, MPMD_PATHWAYS_IMAGE): the libtpu version and + LIBTPU_INIT_ARGS are then the client's, which compiles nothing -- the server + image's compiler and the servers' flags did.""" + try: + spec = importlib.util.find_spec("maxtext") + except (ImportError, ValueError): + spec = None + mt = None + if spec is not None: + path = os.path.dirname(spec.origin) if spec.origin else next(iter(spec.submodule_search_locations or ()), None) + mt = {"path": path, **(_git(path) if path else {})} + here = _import_root() + devs = jax.devices() + out = { + "maxtext": mt, + "mpmd": {"path": here, **_git(here)}, + "versions": { + "jax": jax.__version__, + "jaxlib": _dist_version("jaxlib"), + "libtpu": _dist_version("libtpu", "libtpu-nightly"), + "tokamax": _dist_version("tokamax"), + }, + "LIBTPU_INIT_ARGS": os.environ.get("LIBTPU_INIT_ARGS"), + "devices": f"{len(devs)} x {devs[0].device_kind}" if devs else None, + } + if devs and pathways.is_proxy_device(devs[0]): + out["pathways"] = pathways.describe(devs[0].client) + if devs and devs[0].platform == "gpu": + out["versions"].update( + { + k: _dist_version(*d) + for k, d in ( + ("cuda_plugin", ("jax-cuda13-plugin", "jax-cuda12-plugin")), + ("cudnn", ("nvidia-cudnn-cu13", "nvidia-cudnn-cu12")), + ("nccl", ("nvidia-nccl-cu13", "nvidia-nccl-cu12")), + ("cublas", ("nvidia-cublas", "nvidia-cublas-cu12")), + ("triton", ("triton",)), + ("jax_triton", ("jax-triton",)), + ) + } + ) + out["XLA_FLAGS"] = os.environ.get("XLA_FLAGS") + if scfg is not None: + out.update(gmm_impl=scfg.gmm_impl, tiles=tiles, wi_tiling=scfg.wi_tiling, wo_tiling=scfg.wo_tiling) + if scfg.batch_split: + out["batch_split_impl"] = scfg.batch_split_impl + if scfg.lineage_split: + out.update(ds_ep_lineage.provenance(), lineage_capacity_factor=scfg.lineage_capacity_factor) + return out + + +def provenance_line(pv): + """`provenance` as one line.""" + + def repo(r): + if not r: + return "not found" + sha = (r.get("sha") or "?")[:12] + return f"{r['path']} @ {sha} ({r.get('branch', '?')}{', dirty' if r.get('dirty') else ''})" + + v = pv["versions"] + line = ( + f"provenance: maxtext {repo(pv['maxtext'])} | mpmd {repo(pv['mpmd'])} | " + + " ".join(f"{k} {v[k]}" for k in v) + + f" | {pv['devices']}" + ) + if "lineage" in pv: # batch split on Lineage's layers: no grouped-matmul tiling of ds_ep's runs + line += ( + f" | batch split on Lineage {repo(pv['lineage'])}" + + (f" ({pv['error']})" if pv.get("error") else "") + + f", capacity factor {pv['lineage_capacity_factor']:g}" + ) + elif "gmm_impl" in pv: + line += ( + f" | gmm {pv['gmm_impl']} tiles {pv['tiles']} wi={','.join(map(str, pv['wi_tiling']))} " + f"wo={','.join(map(str, pv['wo_tiling']))}" + + (f" | batch split {pv['batch_split_impl']}" if "batch_split_impl" in pv else "") + ) + if "XLA_FLAGS" in pv: + return line + f" | XLA_FLAGS={pv['XLA_FLAGS']!r}" + if "pathways" in pv: # the client's libtpu and flags compile nothing here: the server image's compiler does + pw = pv["pathways"] + return ( + line + + f" | Pathways: {pw['backend']}, server {pw['server']!r}, image {pw['image'] or 'unknown (MPMD_PATHWAYS_IMAGE)'}" + + f" | client LIBTPU_INIT_ARGS={pv['LIBTPU_INIT_ARGS']!r} (planning only)" + ) + return line + f" | LIBTPU_INIT_ARGS={pv['LIBTPU_INIT_ARGS']!r}" + + +def maxtext_training_flops(cfg: DeepSeekConfig, tokens: int, seq: int): + """`(learnable-weight FLOPs, causal-attention FLOPs)` of one training step + over `tokens` tokens of `seq`-long sequences, by MaxText's own accounting. + + Ported from maxtext/utils/maxtext_utils.py (calculate_tflops_training_per_device, + DeepSeek branch: calculate_mla_tflops_per_device + + calculate_routed_and_shared_ffn_tflops_per_device, dense layers included), so + a TFLOP/s printed here and MaxText's `TFLOP/s/device` log line divide the + SAME numerator. fwd + 2 x bwd (the `* 3`); remat recompute is not counted + (by either side), and neither is the embedding lookup (a gather) -- only the + unembedding. A Qwen3.5-family config: `qwen_training_flops`. + """ + if ds_ep.is_qwen(cfg): + return qwen_training_flops(cfg, tokens, seq) + b, D, H, V = tokens, cfg.emb_dim, cfg.num_query_heads, cfg.vocab_size + qk = cfg.qk_nope_head_dim + cfg.qk_rope_head_dim + ffn = lambda f: 2 * b * f * D * len(cfg.mlp_activations) + 2 * b * f * D + moe = ( + 2 * b * D * cfg.num_experts + + ffn(cfg.shared_expert_mlp_dim) * cfg.shared_experts + + ffn(cfg.moe_mlp_dim) * cfg.num_experts_per_tok + ) + L, n_dense, mtp = cfg.num_decoder_layers, cfg.first_num_dense_layers, cfg.mtp_num_layers + if cfg.q_lora_rank == 0: + q = 2 * b * D * H * qk + else: + q = 2 * b * (D * cfg.q_lora_rank + cfg.q_lora_rank * H * qk) + kv = ( + 2 + * b + * (D * (cfg.kv_lora_rank + cfg.qk_rope_head_dim) + cfg.kv_lora_rank * H * (cfg.qk_nope_head_dim + cfg.v_head_dim)) + ) + attn = 2 * b * seq * H * (qk + cfg.v_head_dim) / 2 + proj = 2 * b * D * H * cfg.v_head_dim + emb = 2 * b * D * V + # an MTP layer as MaxText counts it: one more MoE layer's FFN, attention projections and attention, not its + # [2 x emb -> emb] projection or its pass through the shared head (maxtext_utils.calculate_tflops_training_per_device) + weights = ( + ffn(cfg.mlp_dim) * n_dense + moe * (L - n_dense) + (q + kv + proj) * L + emb + (moe + q + kv + proj) * mtp + ) * 3 + return float(weights), float(attn * (L + mtp) * 3) + + +def qwen_training_flops(cfg: Qwen35Config, tokens: int, seq: int): + """`maxtext_training_flops` of a Qwen3.5-family model: MaxText's own + accounting for decoder_block qwen3_5 (maxtext/utils/maxtext_utils.py, + calculate_tflops_training_per_device's QWEN3_5 branch with + calculate_routed_and_shared_ffn_tflops_per_device and + calculate_gated_delta_net_flops_per_device). Per layer the MoE (router, + shared expert, top-k routed experts); per full-attention layer q / k / v + (not the query's gate half) and the output projection, and causal attention; + per Gated DeltaNet layer its projections and conv, and 8 Hv Dk Dv a token + for the delta rule (counted with attention); the unembedding. x 3 for fwd + + bwd; remat recompute not counted.""" + b, D, V = tokens, cfg.emb_dim, cfg.vocab_size + H, kv, hd = cfg.num_query_heads, cfg.num_kv_heads, cfg.head_dim + ffn = lambda f: 2 * b * f * D * len(cfg.mlp_activations) + 2 * b * f * D + moe = ( + 2 * b * D * cfg.num_experts + + ffn(cfg.shared_expert_mlp_dim) * cfg.shared_experts + + ffn(cfg.moe_mlp_dim) * cfg.num_experts_per_tok + ) + qkv = 2 * b * D * (H + 2 * kv) * hd + attn = 4 * b * seq * H * hd / 2 # causal + proj = 2 * b * D * H * hd + emb = 2 * b * D * V + K, Vd, hv = cfg.gdn_key_dim, cfg.gdn_value_dim, cfg.gdn_num_value_heads + gdn_w = 2 * b * D * (2 * K + 2 * Vd + 2 * hv) + 2 * b * D * Vd + 2 * b * cfg.gdn_conv_kernel_dim * (2 * K + Vd) + gdn_core = b * hv * cfg.gdn_key_head_dim * cfg.gdn_value_head_dim * 8 + L = cfg.num_decoder_layers + n_full = L // cfg.inhomogeneous_layer_cycle_interval + n_lin = L - n_full + weights = (moe * L + emb + (qkv + proj) * n_full + gdn_w * n_lin) * 3 + return float(weights), float((attn * n_full + gdn_core * n_lin) * 3) + + +def maxtext_tflops_per_device(p: Pipeline): + """Per-device training TFLOP per step, by MaxText's own accounting + (`maxtext_training_flops`: dense layers and MTP as MaxText counts them).""" + w, a = maxtext_training_flops(p.scfg.model, p.gbs * p.seq, p.seq) + return (w + a) / (p.S * p.scfg.fsdp * p.scfg.ep) / 1e12 + + +def peak_hbm(): + """{device id: peak HBM in use so far, GiB} -- every (local) device, not + just the worst: the stages hold different chunks (and stash), so they differ. + A device whose backend keeps no statistics it can report is left out: the + IFRT proxy's (Pathways) raise ("MemoryStats is only supported for + addressable PjRt devices"), so there it is {}.""" + out = {} + for d in jax.local_devices(): + stats, why = pathways.memory_stats(d) + if why is None: + out[d.id] = round(stats.get("peak_bytes_in_use", 0) / 2**30, 2) + return out + + +def peak_hbm_line(per): + """main's line for `peak_hbm`'s answer `per` (after "peak HBM"): the GiB per device, or why there are none.""" + if per: + return f"(GiB per device) {per}" + return "not reported: the devices keep no memory statistics this client can read (through the IFRT proxy, Pathways)" + + +class _Parser(ModelParser): + """make_parser's parser: `--model` picks the shape flags' defaults (ModelParser), and what it parses comes back + with the defaults --batch-split decides filled in (`split_defaults`: the impl by the model, then --routing and + --shard-mode by the impl), so every parse of these flags -- main's, ds_ep_aot's, a test's -- names what runs.""" + + def parse_known_args(self, args=None, namespace=None): + a, rest = super().parse_known_args(args, namespace) + return split_defaults(a), rest + + +def make_parser(): + ap = _Parser() + ap.add_argument( + "--model", + default="deepseek3", + choices=list(MODELS), + help="the layer family and its dims: deepseek3 (DeepSeek-V3 MoE layers, the shape flags as given) " + "or a Qwen3.5-family model by its MaxText name (qwen3.8-2.4t-a95b: 92 layers, 3 Gated " + "DeltaNet then 1 gated attention, every layer MoE), whose dims become the shape flags' " + "defaults (QWEN_MODELS); any shape flag given still wins", + ) + ap.add_argument( + "--platform", + default="auto", + choices=list(PLATFORMS), + help="the platform whose defaults the kernel and collective flags take (auto: JAX_PLATFORMS, else " + "libtpu -> tpu, a jax CUDA plugin -> gpu). On gpu " + + ", ".join(f'--{k.replace("_", "-")} {v}' for k, v in GPU_DEFAULTS.items()) + + "; tpu and cpu keep the TPU defaults", + ) + ap.add_argument("--stages", type=int, default=2) + ap.add_argument("--vv", type=int, default=2, help="chunks per stage") + ap.add_argument("--mb", type=int, default=8) + ap.add_argument("--gbs", type=int, default=32) + ap.add_argument("--seq", type=int, default=4096) + ap.add_argument("--fsdp", type=int, default=2) + ap.add_argument("--ep", type=int, default=2) + ap.add_argument("--layers", type=int, default=4) + ap.add_argument("--emb", type=int, default=7168) + ap.add_argument("--heads", type=int, default=128) + ap.add_argument("--q-lora", type=int, default=1536) + ap.add_argument("--kv-lora", type=int, default=512) + ap.add_argument( + "--qk-nope-head-dim", + type=int, + default=128, + help="MLA's query / key head dims without and with RoPE and its value head dim (DeepSeek-V3's " + "128 / 64 / 128). On sm80 cuDNN's flash attention takes equal query / key and value head " + "dims of at most 128 (e.g. 64 + 64 / 128); sm90 and later take DeepSeek-V3's 192 / 128. " + "--qk-rope-head-dim 0 is MLA without RoPE; a value head dim below 1, or query / key head dims " + "negative or summing to 0, are refused", + ) + ap.add_argument("--qk-rope-head-dim", type=int, default=64) + ap.add_argument("--v-head-dim", type=int, default=128) + ap.add_argument("--moe-mlp", type=int, default=2048) + ap.add_argument( + "--dense-layers", + type=int, + default=0, + help="DeepSeek-V3's first_num_dense_layers: dense decoder layers (MLP width --mlp) before the MoE " + "layers, all in chunk 0 (or spanning the first chunks under a --layer-split that counts every " + "layer); --layers counts them (real DeepSeek-V3: --layers 61 --dense-layers 3 --mlp 18432)", + ) + ap.add_argument( + "--mlp", + type=int, + default=None, + help="the dense layers' MLP width (MaxText base_mlp_dim; DeepSeek-V3 18432; default --moe-mlp)", + ) + ap.add_argument("--experts", type=int, default=128) + ap.add_argument("--topk", type=int, default=8) + ap.add_argument("--vocab", type=int, default=32768) + # DeepSeek-V3 as MaxText's deepseek3-671b with the MLPerf recipe's routing, aux loss and MTP: --layers 61 + # --dense-layers 3 --mlp 18432 --routed-bias on --bias-update-rate 0.001 --routing-groups 8 --topk-groups 4 + # --float32-gate-logits on --lb-loss-weight 0.01 --mtp 1 --routing topk + ap.add_argument( + "--routed-bias", + default="off", + choices=["off", "on"], + help="MaxText routed_bias: a bias on every router's scores picks the experts (not their weights)", + ) + ap.add_argument( + "--bias-update-rate", + type=float, + default=0.0, + help="MaxText routed_bias_update_rate: after each step every routed bias moves by rate x sign(mean " + "load - load), the loads counted over the step's tokens (DeepSeek-V3: 0.001)", + ) + ap.add_argument( + "--routing-groups", + type=int, + default=-1, + help="MaxText n_routing_groups: top-k picks among each token's --topk-groups best groups of " + "experts (a group scored by its two best scores; DeepSeek-V3: 8)", + ) + ap.add_argument("--topk-groups", type=int, default=-1, help="MaxText topk_routing_group (DeepSeek-V3: 4)") + ap.add_argument( + "--float32-gate-logits", + default="off", + choices=["off", "on"], + help="MaxText float32_gate_logits: the routers in fp32, from an fp32 compute copy of their kernels " + "(GateLogit casts the stored kernel), their routed biases fp32 in storage too. Under " + "--batch-split on Lineage's layers only the expert selection runs in fp32 (Lineage's " + "router_dtype): the kernel copy is rounded to bf16 first, and its gradient comes back in bf16 " + "(bf16 operands, fp32 accumulation; warned of)", + ) + ap.add_argument( + "--lb-loss-weight", + type=float, + default=0.0, + help="MaxText load_balance_loss_weight with moe_use_megatron_seq_aux_loss: every MoE layer's " + "sequence-wise aux loss (Megatron-LM seq_aux_loss), summed into the objective (DeepSeek-V3 " + "recipe: 0.01)", + ) + ap.add_argument( + "--mtp", + type=int, + default=0, + choices=[0, 1], + help="MaxText mtp_num_layers: a multi-token-prediction MoE layer after the head, on the last chunk; " + "its embedding is the input's (mtp_reuse_input_embedding)", + ) + ap.add_argument("--mtp-loss-scale", type=float, default=0.1, help="MaxText mtp_loss_scaling_factor") + ap.add_argument("--kv-heads", type=int, default=None, help="Qwen3.5 family: gated attention's kv heads (GQA)") + ap.add_argument("--head-dim", type=int, default=None, help="Qwen3.5 family: gated attention's head dim") + ap.add_argument("--gdn-key-heads", type=int, default=None, help="Qwen3.5 family: Gated DeltaNet key heads") + ap.add_argument("--gdn-value-heads", type=int, default=None, help="Qwen3.5 family: Gated DeltaNet value heads") + ap.add_argument("--gdn-key-head-dim", type=int, default=None, help="Qwen3.5 family: Gated DeltaNet key head dim") + ap.add_argument("--gdn-value-head-dim", type=int, default=None, help="Qwen3.5 family: Gated DeltaNet value head dim") + ap.add_argument( + "--qwen-rope", + default=None, + choices=["partial", "mrope"], + help="Qwen3.5 family: gated attention's rotary embedding, MaxText's use_mrope -- partial, " + "PartialRotaryEmbedding (bf16 sin/cos and rotation: qwen3.8-2.4t-a95b's yml, which leaves " + "use_mrope false), or mrope, the text mRoPE (fp32 sin/cos and rotation: the qwen3.5 ymls); " + "default the --model's (maxtext.experimental.mpmd.jax.qwen35.attention)", + ) + ap.add_argument( + "--attn", + default="tokamax_splash", + help="the attention kernel (DeepSeekConfig.attention_kernel; a Qwen3.5-family model's gated " + "attention's too): tokamax_splash (tokamax's splash, the benchmark's), splash (MaxText's), " + "dot_product or reference (the port's CPU kernel). Not under --batch-split on Lineage's " + "layers, which run Lineage's own splash (base-2 softmax)", + ) + ap.add_argument( + "--sa-block", + type=int, + default=2048, + help="tokamax_splash's and splash's forward q and kv blocks (MaxText sa_block_q, sa_block_kv); " + "under --batch-split on Lineage's layers Lineage's splash's too, whatever --attn says (it " + "clamps each of the six blocks to --seq)", + ) + ap.add_argument( + "--sa-block-kv-compute", + type=int, + default=512, + help="tokamax_splash's and splash's forward kv compute block (MaxText sa_block_kv_compute; 512 " + "tuned for tokamax_splash); under --batch-split on Lineage's layers Lineage's splash's too, " + "which keeps its SV diagonal skip only where this equals --sa-block (both clamped to --seq): " + "the default 512 below --sa-block 2048 turns it off (Lineage's own blocks: 2048, all six)", + ) + ap.add_argument( + "--sa-block-dkv", + type=int, + default=None, + help="tokamax_splash, and Lineage's splash under --batch-split on its layers: the fused backward's " + "q and kv blocks (MaxText sa_block_q_dkv, sa_block_kv_dkv); default --sa-block", + ) + ap.add_argument( + "--sa-block-kv-dkv-compute", + type=int, + default=None, + help="tokamax_splash, and Lineage's splash under --batch-split on its layers (whose QK diagonal " + "skip needs it equal to --sa-block-dkv): the fused backward's kv compute block (MaxText " + "sa_block_kv_dkv_compute); default --sa-block-dkv", + ) + ap.add_argument( + "--sa-base2-exp", + default=None, + choices=["on", "off"], + help="tokamax_splash: its base-2 softmax (MaxText sa_use_base2_exp, on in MaxText's base.yml), on " + "by default as tokamax always ran: MaxText's numerics -- the kernels scale the bf16 query by " + "log2(e) rounded to bf16 (1.4453125), a 1.0018x sharper softmax with ~0.3%% larger attention " + "gradients. off: the exact softmax, as --attn splash computes (for parity against MaxText " + "with sa_use_base2_exp=false), ~1.2%% slower in the kernel (fwd + bwd at 4096 x 128 heads on " + "TPU7x, 11.49 vs 11.34 ms). on with another --attn is refused. Not under --batch-split on " + "Lineage's layers, whose splash is base-2 always (off is ignored there, with a warning)", + ) + ap.add_argument("--cost-estimate", type=int, default=5_000_000_000_000) + ap.add_argument( + "--tiles", + default="clamped", + choices=sorted(ds_ep.TILES), + help="megablox tilings (ds_ep.TILES): clamped (every tk <= the k it tiles), " + "v6e (swept on TPU v6e at emb 7168, moe_mlp 2048). Not under --batch-split on Lineage's " + "layers (--batch-split-impl lineage), which run no megablox kernel", + ) + ap.add_argument( + "--wi-tiling", + type=int, + nargs=9, + default=None, + metavar="T", + help="wi_0 / wi_1 megablox tiling (fwd tm tk tn, dlhs tm tk tn, drhs tm tk tn); " + "overrides --tiles (not under --batch-split on Lineage's layers)", + ) + ap.add_argument( + "--wo-tiling", + type=int, + nargs=9, + default=None, + metavar="T", + help="wo megablox tiling, as --wi-tiling; overrides --tiles (not under --batch-split on Lineage's " "layers)", + ) + ap.add_argument( + "--strict-tiling", action="store_true", help="refuse (instead of warning about) a tile larger than the k it tiles" + ) + ap.add_argument( + "--gmm-impl", + default="megablox", + choices=list(ds_ep.GMM_IMPLS), + help="routed-expert grouped matmuls: megablox (MaxText's kernels, the tilings " + "above), ragged_dot (pure JAX: XLA's ragged dot) or tokamax (GPU: " + "tokamax's / gpu_kernels' grouped matmuls on a compact local buffer, --tokamax-gmm; the GPU " + "default). Not under --batch-split on Lineage's layers, whose experts run Lineage's own gmmv2 " + "kernels", + ) + ap.add_argument( + "--tokamax-gmm", + default="mosaic", + choices=list(ds_ep.TOKAMAX_GMM), + help="--gmm-impl tokamax: the backend of the forward and dlhs grouped matmuls (mosaic: Mosaic GPU, " + "on sm100 gpu_kernels.grouped_matmul -- the weight read as stored, tuned tiles -- else " + "tokamax's, with dW on Triton but an in-place one (--inplace-dw, or mb0's under --split-dw acc) " + "on gpu_kernels' tcgen05 kernel on sm100, where --inplace-dw auto puts an fp32 accumulator's " + "in place too; tokamax_mosaic: tokamax's Mosaic kernels everywhere, dW on Triton; triton: all " + "three on Triton; xla: lax throughout, for CPU)", + ) + ap.add_argument( + "--gdn-conv", + default="conv", + choices=list(GDN_CONV_IMPLS), + help="Qwen: the Gated DeltaNet's causal depthwise conv as lax.conv_general_dilated (conv: MaxText's op, " + "bitwise) or as its 4 shifted multiply-adds in fp32 (shift: the GPU default -- XLA:GPU fuses " + "them, where cuDNN's grouped conv runs ~10x slower than its bytes); DeepSeek ignores it", + ) + ap.add_argument( + "--gdn-scan", + default="scan", + choices=list(GDN_SCAN_IMPLS), + help="Qwen: the Gated DeltaNet's chunked delta rule with its inter-chunk recurrence as a lax.scan " + "(scan: MaxText's) or on Triton kernels (triton: the GPU default -- at the model's chunks of " + "64 the whole rule, gdn_triton.FUSED: the WY factors, the triangular solve, the intra-chunk " + "output and their backward as per-chunk kernels around the recurrence's, a GB200 layer's " + "forward + backward 27.4 -> 10.7 ms; at a chunk FUSED does not take, the recurrence alone, " + "the chunk outputs batched in XLA; runs per device, as the stage programs do); DeepSeek " + "ignores it", + ) + ap.add_argument( + "--layer-tree", + default="stacked", + choices=list(ds_ep.LAYER_TREES), + help="a DeepSeek chunk's layer weights, MoE and dense: stacked ([n, ...] leaves; TPU's, megablox " + "reads a layer's experts in place) or per_layer (one subtree a layer, as a Qwen chunk's: no " + "gradient stacking in every backward, in-place dW on every chunk; the GPU default)", + ) + ap.add_argument( + "--inplace-dw", + default="auto", + choices=["auto", "on", "off", "all"], + help="--gmm-impl tokamax: add the routed experts' weight gradients into the step accumulator inside " + "the dW kernel (on; where the accumulator dtype is the compute dtype), also into an accumulator " + "of its own dtype (an fp32 one) on every chunk but the last (all: on sm_100 under --tokamax-gmm " + "mosaic the tcgen05 kernel, elsewhere gpu_kernels.ragged_dw's Triton one (slower than " + "tokamax's dW plus an add on an A100), and under --tokamax-gmm xla lax's form), or write each " + "to a buffer and add it after (off). auto: all where the tcgen05 kernel takes an fp32 " + "accumulator (sm_100 under --tokamax-gmm mosaic), else on", + ) + ap.add_argument( + "--buffer-masks", + default="on", + choices=["on", "off"], + help="--gmm-impl tokamax: zero the compact expert buffer's rows past its groups after the dispatch, " + "every grouped matmul and on each gradient (on), or skip those buffer-wide passes (off): every " + "reader of the rows is bounded by the group sizes or gathers valid rows only " + "(StageConfig.buffer_masks)", + ) + ap.add_argument( + "--combine-impl", + default="xla", + choices=["xla", "triton"], + help="gmm_impl 'tokamax': the per-token sums over a token's routed choices (the combine, the " + "dispatch's gradient): 'xla' walks all T x K choices, 'triton' (GPU; the GPU default) loads only " + "the rows this shard has (StageConfig.combine_impl; 64 B200, DeepSeek-V3 dims: 15.33 -> " + "14.86 s a step)", + ) + ap.add_argument( + "--route-weights", + default="combine", + choices=list(ds_ep.ROUTE_WEIGHTS), + help="where the routing weights multiply the routed experts' output: in the combine's weighted sum " + "(combine: MaxText's), or on the rows of the gated activation before the wo product, the " + "combine then an unweighted sum (experts: Megatron-LM's; the GPU default) -- whose backward " + "needs no expert output row, so --save-residuals keeps none (896 MiB a DeepSeek-V3 layer at one " + "sequence a GPU, EP 8, --ragged-buffer-factor 2). Rounds the weighted activation to the " + "compute dtype before wo. experts needs --gmm-impl tokamax or --ragged-sort off " + "(StageConfig.route_weights)", + ) + ap.add_argument( + "--lean-experts", + default="on", + choices=["on", "off"], + help="with --save-residuals on: the routed experts' grouped matmuls keep what their lhs is recomputed " + "from (on: the gathered tokens and the gated product's inputs, the fewest bytes) or the lhs " + "itself (off: the buffer rows and the product; no row gather, and one evaluation of the gated " + "product fewer, in the backward, for ~0.7 GiB more a DeepSeek-V3 layer-microbatch at one " + "sequence a GPU, EP 8, --ragged-buffer-factor 2)", + ) + ap.add_argument("--rs-dtype", default="bfloat16", type=float_dtype_arg) + ap.add_argument( + "--grad-dtype", + default="auto", + choices=["auto", "float32", "bfloat16"], + help="the dtype the reduced gradient enters AdamW (and the clip) in, cast from --rs-dtype: " + "MaxText grad_dtype, which its trainer applies after the reduction (auto: under --adam-math " + "optax each weight's dtype, as MaxText's gradients take their parameter's; else --rs-dtype, " + "no cast). --rs-dtype bfloat16 --grad-dtype float32 --adam-math optax is MaxText's " + "weight_dtype=float32 grad_dtype=float32, which reduce-scatters in bf16 and casts after (but " + "for an fp32 router's kernel, which MaxText reduces in fp32). --adam-math fp32 computes in " + "fp32 whatever this is. MaxText casts fp32 gradients only: with bf16 weights keep auto", + ) + ap.add_argument("--acc-dtype", default="float32", type=float_dtype_arg) + ap.add_argument( + "--weight-dtype", + default="bfloat16", + type=float_dtype_arg, + help="master weights and AdamW nu (MaxText weight_dtype); mu is always bf16", + ) + ap.add_argument( + "--dtype", + default="bfloat16", + choices=["bfloat16", "float32"], + help="activations and compute copies (MaxText dtype): float32 for parity checks with the " + "pure-JAX kernels (--gmm-impl ragged_dot --ragged-sort off, --attn dot_product)", + ) + ap.add_argument( + "--remat-last", action="store_true", help="also recompute the fused last chunk (MaxText-identical FLOPs)" + ) + ap.add_argument( + "--save-residuals", + default="off", + choices=["on", "off"], + help="every chunk's forward keeps its backward's residuals (its layers under jax.vjp; Megatron-LM's " + "default) instead of recomputing the chunk's forward inside its backward: no forward computed " + "twice, for the residuals' memory until the backward (StageConfig.save_residuals)", + ) + ap.add_argument( + "--direct-experts", + default="off", + choices=["on", "off"], + help="at --fsdp 1 the stages read their routed experts in place (on; the GPU default): stored over " + "'expert' alone, a compute copy would be their storage's bytes again (12 GiB a Qwen3.8 " + "layer at EP 4), so no gather makes one; off gathers that copy as at --fsdp > 1 (TPU's plans)", + ) + ap.add_argument( + "--interleave-group", + type=int, + default=0, + help="--schedule interleaved: microbatches a chunk runs before the next chunk (Megatron-LM's " + "microbatch_group_size_per_vp_stage; 0: --stages). Above --stages each chunk switch has " + "slack against the boundary copies' latency, for (V-1) x the excess more warmup forwards " + "held, and about the excess more boundary inputs waiting at the first and last stage (which " + "--offload-residuals does not move); --mb must be a multiple of it", + ) + ap.add_argument( + "--schedule", + default=None, + choices=list(SCHEDULES), + help="microbatch order (see Pipeline); default breadth (DEFAULT_SCHEDULE), on either " + "placement. timed is the event-driven search over " + "per-program costs (--costs); zbh1 / zbh2 the zero-bubble schedules at --vv 1, each middle chunk's backward " + "split into its input and weight gradients (I and W, the W's run later; the fused last chunk's too with " + "--zb-split-last on), priced by --costs too: ZB-H1 holds 1F1B's residual sets and ZB-H2 about twice them, each " + "plus up to --zb-wbuf-cap pending W buffers a stage (a W buffer: about 3.6 GiB a device per DeepSeek-V3 MoE " + "layer at 4096 tokens a device); stash the HBM-budgeted " + "stash scheduler (--stash, " + "--stash-budget-gib); interleaved Megatron-LM's " + "interleaved 1F1B (circular placement, --vv >= 2, --mb a multiple of --stages; F&B pairs " + "in its steady state on --pair-stages); breadth " + "MaxText's circular-pipeline order: each stage runs a chunk's forward for every " + "microbatch before its next chunk, the backwards the same in reverse (what search picks at " + "--stages 4, --vv 2 and 4, --mb 8; --fsdp-scope repeat needs an order like it, each chunk " + "visited at most twice a step). gpipe at --vv > 1 is depth-first, not interleaved", + ) + ap.add_argument( + "--zb-wbuf-cap", + type=int, + default=1, + help="--schedule zbh1 / zbh2: the W buffers a stage may hold pending (0: no cap), on top of the residual sets " + "(1F1B's under zbh1). Each is one microbatch's split chunk's crossing set and the arguments its W reads -- " + "the summary's 'split backward' line gives their GiB, about 3.6 GiB a device a DeepSeek-V3 MoE layer at 4096 " + "tokens a device -- so 1 by default, which keeps most of the schedules' gain in simulation", + ) + ap.add_argument( + "--zb-split-last", + default="off", + choices=["off", "on"], + help="--schedule zbh1 / zbh2: split the fused last chunk too -- its F runs the forward, the head, the loss and " + "the input gradient (AI), a W of its own each microbatch its layers' weight gradients, later -- so the last " + "stage holds W buffers too, under --zb-wbuf-cap (7.2 GiB a device for two DeepSeek-V3 MoE layers at 4096 " + "tokens a device). Off by default; turn it on at --stages 2, where no middle chunk splits and it is the only " + "split (without it zbh1 is 1F1B's order). Measured (README, 'Zero-bubble schedules'): faster in every pair " + "on one TPU7x-8, slower under zbh2 at four stages on 2 x TPU7x-4x4x4", + ) + ap.add_argument( + "--placement", + default=None, + choices=["circular", "v"], + help="chunk -> stage map: circular (chunk c on c %% S, MaxText's; the default) or v (--vv 2: " + "stage s holds chunks s and 2S-1-s)", + ) + ap.add_argument( + "--pair-stages", + default=None, + help="--schedule interleaved: the stages that run its steady state's F(k+W) and B(k) as one " + "program, one microbatch's EP collectives beside another's compute (Megatron-LM's combined " + "1F1B): all, none, or a list such as 1 or 0,1 (default none, Megatron's order as it is)", + ) + ap.add_argument( + "--pair-gain", + type=float, + default=None, + help="--schedule interleaved: ms an F&B pair program saves over its two halves back to back, for " + "the simulation (default: the cost table's pair_gain, else 0)", + ) + ap.add_argument( + "--stash", + default="none", + choices=[k for k in ds_ep.STASH_POLICIES if k != "all"], + help="--schedule stash / interleaved: the policy of the " + "stash-mode (chunk, microbatch)s (ds_ep.STASH_POLICIES; none under --batch-split)", + ) + ap.add_argument( + "--stash-budget-gib", + type=float, + default=4.5, + help="--stash: live stash sets allowed per stage, GiB per device, on top of " + "a remat step (a placeholder until a --mem-report sweep on the TPU sets it); " + "the stash backwards' extra temporaries come on top (the summary prints both)", + ) + ap.add_argument( + "--stash-caps", + default="", + help="--stash: live stash sets per chunk, e.g. 1,3,2 (default: searched under " + "--schedule stash, none on a fixed order). A chunk left off the list never " + "stashes under --schedule stash and is uncapped on a fixed order (interleaved)", + ) + ap.add_argument( + "--norm-reduce", + default="hops", + choices=["hops", "allreduce"], + help="how stages share their gradient sums of squares for the global-norm clip under --distributed: " + "hops (a scalar copy between every two stages, S(S-1) a step) or allreduce (one sum over every " + "device of the job; the GPU default; in one process the hops run; refused under Pathways)", + ) + ap.add_argument( + "--offload-residuals", + default="off", + choices=["off", "on"], + help="keep each microbatch's forward residuals in pinned host memory until its backward (on: the " + "HBM a step holds stops growing with the microbatches in flight; a GB200's Grace host sits " + "behind NVLink-C2C)", + ) + ap.add_argument( + "--init-by-chunk", + action="store_true", + help="seed each chunk from its index alone: the same weights under any placement", + ) + ap.add_argument( + "--dry-run", + action="store_true", + help="build the pipeline and print the schedule, the plan and the peak stash; " "compile and run nothing", + ) + ap.add_argument( + "--layout", + default="fsdp_on_chip", + choices=list(LAYOUTS), + help="fsdp_on_chip | ep_on_chip (MaxText's placement) | snake (PP=4/8) | physical " + "(MaxText's mesh over a whole slice: stage s = row s) | physical_origin_last " + "(physical, rotated so the strip holding device 0 -- the one libtpu keeps " + "synchronous -- runs the last stage) | slices (k stages per TPU slice: --stages = k x " + "the number of slices, fsdp x ep = a k-th of the devices of one; each stage's mesh topology-aware " + "over its own slice, or at k > 1 over a strip of its whole chips along the last chip axis k divides (both " + "TensorCores of a chip in one stage, as Pathways requires); its collectives on SparseCore, but in the strip " + "holding chip (0,0,0) under McJAX; boundaries between slices cross DCN, which " + "--transport relay (run on 2 and 4 slices) and ppermute (2) cross and native and xfer " + "do not; on CPU MPMD_FAKE_SLICES=N cuts the devices into N slices)", + ) + ap.add_argument("--no-precompile", action="store_true") + ap.add_argument( + "--embed", + default="iota", + choices=["iota", "gather"], + help="token embedding: 'iota' = one_hot @ table (MaxText use_iota_embed=true, the " + "baseline's), 'gather' = table[tokens] (the port's)", + ) + ap.add_argument( + "--ragged-sort", + default="auto", + choices=["auto", "on", "off"], + help="auto: on iff EP > 1 (MaxText rejects use_ragged_sort at EP=1). Not under --batch-split " + "on Lineage's layers, which dispatch their own way", + ) + ap.add_argument( + "--cp", + type=int, + default=1, + choices=[1, 2, 4], + help="context parallelism: each microbatch sequence cut into this many chunks, one row of seq / cp " + "tokens a stage device (cp x mbs = fsdp x ep); attention gathers the other chunks' kv " + "latents over the expert axis", + ) + ap.add_argument( + "--layer-split", + default="", + help="layers per chunk in chunk order, comma-separated (e.g. 3,1: the head's chunk holds fewer); " + "default an even split. With --dense-layers it counts the MoE layers, the dense ones all in " + "chunk 0 -- or, summing to --layers, every layer, in order, so the dense ones may span the " + "first chunks (e.g. --layers 5 --dense-layers 2 --layer-split 1,2,1,1). The schedulers' " + "program costs (--costs) scale with each chunk's layers, a dense one as a MoE one", + ) + ap.add_argument( + "--ragged-buffer-factor", + type=float, + default=-1.0, + help="MaxText ragged_buffer_factor: the ring of experts' dispatch buffer, <= 0 the worst case " + "(dropless), > 0 that many times the balanced load (drops tokens past it; needs the " + "ragged sort). > 0 is refused under --batch-split on Lineage's layers, which are dropless " + "(--lineage-capacity-factor sizes their expert loop)", + ) + ap.add_argument( + "--routing", + default=None, + choices=["random", "topk"], + help="MaxText use_random_routing=true / false (MaxText requires topk at EP=1). Default random, " + "but topk under --batch-split on Lineage's layers, which route top-k only (random is " + "refused there)", + ) + ap.add_argument( + "--batch-split", + action="store_true", + help="Lineage's batch split: each device's rows of a microbatch run as two halves through a " + "chunk's MoE layers in phases, one half's EP all-gather / reduce-scatter beside the other " + "half's attention (a Qwen3.5-family layer's Gated DeltaNet or gated attention) or experts -- " + "by default on MaxText's Lineage layers for DeepSeek-V3 (TPU only), on ds_ep.split_layers for " + "a Qwen3.5-family --model, whose layers Lineage does not build, and on GPU " + "(--batch-split-impl). A microbatch is two of the unsplit pipeline's, so it wants an even " + "number of rows a device (gbs / mb / (fsdp x ep)), and --cp 1 and no --stash; and, as neither " + "implementation keeps expert counts or an aux loss, no --bias-update-rate, --lb-loss-weight or " + "--mtp. A chunk without a MoE layer (the embedding's or the head's alone, or dense layers " + "only) has nothing to split: split_layers runs it unsplit, Lineage's layers refuse it. On " + "Lineage's layers --routing defaults to topk and --shard-mode to explicit", + ) + ap.add_argument( + "--batch-split-impl", + default=None, + choices=list(ds_ep.BATCH_SPLIT_IMPLS), + help="--batch-split: whose code runs the chunks' decoder layers; default the --model's: lineage " + "for deepseek3, native for a Qwen3.5-family model (split_defaults). lineage: MaxText's " + "Lineage layers (ds_ep_lineage; its modules import typeguard and jaxtyping): its MLA and splash " + "attention, router, SparseCore dispatch " + "and combine and gmmv2 experts, chained as its driver chains them, the chunks' programs " + "global-view jits on Explicit stage meshes. TPU only: its kernels have no CPU or GPU path " + "(refused there, but for a --dry-run). It takes --shard-mode explicit and --routing topk " + "(their defaults there), so a stage of more than one device (fsdp x ep > 1), --grad-reduce " + "step, a dropless --ragged-buffer-factor, --cp 1, no --stash or --schedule stash, no " + "--prefetch-pin, an even number of rows " + "a device, a MoE layer in every chunk, and a model Lineage builds (ds_ep_lineage.check: " + "DeepSeek-V3's layers only, bf16, sigmoid scores, ...); --gmm-impl, the tilings, --ragged-sort, " + "--ep-collectives, --split-dw, --expert-weights, --attn, --sa-base2-exp off and " + "--cost-estimate do not apply to its layers, --float32-gate-logits on only in part (each " + "warned of when given). native: ds_ep.split_layers, ds_ep's own layers over MaxText's " + "ring-of-experts and megablox kernels -- DeepSeek-V3's off TPU only (on GPU its default; refused on " + "TPU, where lineage runs its batch split: native_split_refusal), the Qwen3.5 family's only batch " + "split, its mixer in attention's place (ds_ep.StageConfig.batch_split_impl)", + ) + ap.add_argument( + "--lineage-capacity-factor", + type=float, + default=ds_ep_lineage.CAPACITY_FACTOR, + help="--batch-split on Lineage's layers: Lineage's MoE chunk size, in units of a device's balanced " + "load of routed slots. Dropless at any value: it sets how many trips its expert loop takes " + "(MaxText's DeepSeek-V3 Lineage recipe: 3.0; ds_ep.StageConfig.lineage_capacity_factor)", + ) + ap.add_argument( + "--split-dw", + default="acc", + choices=list(ds_ep.SPLIT_DW), + help="--batch-split on ds_ep.split_layers (--batch-split-impl native, a Qwen3.5-family model's " + "default): acc adds mb0's routed-expert weight gradients into mb1's inside megablox's dW " + "kernel (tgmm existing_out; the --tiles preset's wi dW tm capped at 256 for the VMEM it takes, " + "ds_ep.split_acc_wi_tiling); sum gives each half its own copy and adds the two after " + "(ds_ep.StageConfig.split_dw). Lineage's layers accumulate the halves' expert gradients in " + "their own kernels", + ) + ap.add_argument( + "--expert-weights", + default="stacked", + choices=list(ds_ep.EXPERT_WEIGHTS), + help="how the routed experts' megablox kernels read a layer's weights: stacked, in place in the " + "chunk's stacked leaves; sliced, from a per-layer slice XLA copies into a buffer first " + "(ds_ep.StageConfig.expert_weights). Not under --batch-split on Lineage's layers", + ) + ap.add_argument( + "--grad-reduce", + default="step", + choices=["step", "microbatch"], + help="'microbatch': reduce-scatter every microbatch's gradient (MaxText's " + "pipeline_fsdp_ag_per_repeat cadence); 'step': once per step (the only one under --shard-mode " + "explicit, so under --batch-split on Lineage's layers)", + ) + ap.add_argument( + "--shard-mode", + default=None, + choices=list(ds_ep.SHARD_MODES), + help="auto: Auto stage-mesh axes, nothing typed (a gradient accumulator carries a leading axis over " + "the mesh axes its per-device partial sums are still to be reduced over); explicit: Explicit " + "axes, the gathered weights typed reduced and the accumulators unreduced over those axes -- " + "same programs, collectives and folding (ds_ep.StageConfig.shard_mode; needs --grad-reduce " + "step). Default auto, but explicit under --batch-split on Lineage's layers, whose code reads " + "its layouts from sharding types (auto is refused there)", + ) + ap.add_argument( + "--rs-axes", + default="joint", + choices=list(ds_ep.RS_AXES), + help="--fsdp-collectives xla: a gradient leaf stored over both mesh axes reduce-scatters in one " + "psum_scatter over both (joint) or one axis at a time, fsdp first, but for the embedding and " + "the head (each: on a v5p-128 stage of fsdp 4 x ep 16 the joint one compiles to a full-size " + "all-reduce; on v6e and TPU7x to a reduce-scatter: ds_ep.StageConfig.rs_axes)", + ) + ap.add_argument( + "--gather-axes", + default="joint", + choices=list(ds_ep.GATHER_AXES), + help="--fsdp-collectives xla: a weight stored over both mesh axes all-gathers in one all_gather over " + "both (joint) or one axis at a time, the minor first (each: on a stage of a multi-slice v5p " + "program the joint one compiles to a zero buffer + a full-size all-reduce, each to native " + "SparseCore all-gathers; the same values bit for bit: ds_ep.StageConfig.gather_axes)", + ) + ap.add_argument( + "--prefetch-pin", + default="off", + type=prefetch_pin_arg, + metavar="off|auto|SPEC", + help="tie the gathers folded into a forward (a prefetch host's, the self-prefetch's) to points of " + "its layers with optimization barriers, so they run inside its compute windows: hn (the MoE " + "input, after attention), xs (the sorted tokens, before the expert gmms), y (gmm_wo's output, " + "before the unsort). auto: planned per program from estimated SparseCore gather and compute " + "times, on the stages whose FSDP collectives are lax ones (xla) libtpu offloads to SparseCore " + "(not a stage it runs them on synchronously); " + "SPEC: point[@layer]=leaf,...;... by leaf name (ds_ep.leaf_names: moe.wi_0, moe.gate, " + "self_attention.out, logits_dense, ...; a name selects the leaves under it too, of every " + "chunk, or of one with a chunk prefix: c3.moe.wi_0; a Qwen3.5-family leaf is one layer's, " + "named with its key in the chunk: 01.mlp.routed_experts.wi_0), e.g. " + "'hn=moe.wi_0;y=moe.wo,logits_dense'; 'auto' is DeepSeek's only. A pinned program compiles " + "with xla_tpu_aggressive_opt_barrier_removal DISABLED (ds_ep.PIN_COMPILER_OPTIONS); off: no " + "pins (the only one under --batch-split on Lineage's layers, which have no points to tie)", + ) + ap.add_argument( + "--ep-collectives", + default="auto", + type=ep_collectives_arg, + metavar="auto|xla|ppermute|C0,C1,...", + help="ring-of-experts gather / reduce-scatter. auto: per stage, the lax " + "collectives where libtpu offloads them to SparseCore, collective-permutes " + "elsewhere; xla / ppermute: every stage; or one per stage, comma-separated " + "(ppermute,xla is what auto picked in the TPU7x benchmark runs). Not under --batch-split " + "on Lineage's layers, which run their own: on SparseCore where libtpu offloads the stage's " + "collectives, as TensorCore code elsewhere", + ) + ap.add_argument( + "--fsdp-scope", + default=None, + choices=["step", "repeat"], + help="how long a chunk's gathered weights live. step: gathered once a step, every chunk of " + "the stage held by the backward phase. repeat: per visit (a run of the chunk's ops on " + "its stage) -- gathered inside the stage's previous visit, released after it, gathered " + "again for the backward: about two chunks' weights at a time, for (V-1)/V more weight " + "all-gather a step (MaxText's circular pipeline with pipeline_fsdp_ag_per_repeat). " + "Needs --schedule breadth, the default (or another order that " + "visits each chunk at most twice a step), the fusion plan (no --no-overlap) and no F&B " + "pairs. Default (default_fsdp_scope): repeat under breadth with the fusion plan, else " + "step", + ) + ap.add_argument( + "--costs", + default="", + help="program costs (ms) for --schedule timed / stash / interleaved: JSON " + '(e.g. \'{"F0": 18.5, "F": 16.5, "B0": 51.3, "B": 48.6, "A": 58.3, "xfer": 1.0}\': ' + "F0/B0 chunk 0, A the fused last chunk, xfer a stage-boundary copy; per-chunk and " + "stash keys as schedule.cost_table reads them), @file.json as written by `xprof " + "costs`, or a table name: tpu7x, v6e (measured with padded tiles), v6e_tiles " + "(with --tiles v6e). Default: on a v6e the table of --tiles (v6e_tiles for v6e and " + "clamped, v6e for custom tilings: default_costs), TPU7x ones elsewhere; " + "its keys are overridden by these. Under an uneven --layer-split every key is an even " + "split's chunk, each chunk's scaled to its layers (split_costs)", + ) + ap.add_argument( + "--rs-self", + default="all", + choices=["all", "first", "none"], + help="which stages fold their last chunk's reduce-scatter into its own last backward: " + "all, or first -- only the stage holding chunk 0, whose last backward ends the " + "step (elsewhere the folded reduce-scatter holds back the cotangent the stage " + "upstream waits for; a standalone reduce right after it does not). Under first " + "the other stages' last backward hosts no reduce-scatter at all: other chunks' " + "groups move to earlier backwards or to the standalone reduce after it", + ) + ap.add_argument( + "--rs-reserve", + default="auto", + choices=["auto", "on", "off"], + help="keep each stage's last backward free for its own reduce-scatter (rs_self) " + "when another chunk's would take it; auto: under --placement v and for " + "--schedule interleaved (circular breadth / search / timed / stash " + "keep the plans they have always made, which can end a stage with a standalone reduce-scatter: on " + "folds it). " + "It frees one backward, so it folds a single leftover reduce-scatter: at 3+ " + "chunks per stage a stage can still end with a standalone one", + ) + ap.add_argument( + "--pf-split", + type=int, + default=4, + help="ops each chunk gather is spread over: forwards before the chunk's first one; under " + "--fsdp-scope repeat the last ops of the stage's previous visit (0: none -- the update " + "gathers the chunk, or under repeat a visit keeps its chunk's weights from the last)", + ) + ap.add_argument("--rs-split", type=int, default=4, help="backwards each chunk reduce-scatter is spread over") + ap.add_argument( + "--fsdp-collectives", + default="auto", + choices=["auto", "ppermute", "xla"], + help="auto: collective-permutes (async TensorCore DMA) where fsdp, ep <= 2 (at fsdp = ep " + "= 1 there is nothing to gather: xla), lax collectives (xla) otherwise", + ) + ap.add_argument("--no-overlap", action="store_true", help="stage-level gather / reduce programs instead of fused ones") + ap.add_argument("--steps", type=int, default=10) + ap.add_argument("--warmup", type=int, default=3) + ap.add_argument("--bench", action="store_true") + ap.add_argument( + "--profile", + default="", + help="trace the --profile-steps steps after the warm-up (and --bench) into this XProf logdir; under " + "Pathways (JAX_PLATFORMS=proxy) a gs:// one, where the Pathways workers write their device planes", + ) + ap.add_argument("--profile-steps", type=int, default=2) + ap.add_argument("--lr", type=float, default=1e-5) + ap.add_argument( + "--adam-math", + default="fp32", + choices=["fp32", "optax"], + help="the AdamW update's arithmetic: fp32 (whatever the storage dtype), or optax's chain " + "as MaxText runs it, every op in its leaf's dtype (bf16 moments and learning rate " + "with bf16 weights): for parity runs against MaxText. The clip compares this " + "pipeline's fp32 global norm (MaxText's optax reduces it in bf16), so the update " + "matches MaxText's bit for bit while the norm stays below the clip, or both round " + "to the same bf16 value", + ) + ap.add_argument( + "--grad-clip", + type=float, + default=1.0, + help="the global-norm clip's threshold (MaxText's gradient_clipping_threshold); 0: no clip", + ) + ap.add_argument( + "--data", + default="synthetic", + help="synthetic (numpy random tokens, targets the tokens rolled by one) | maxtext " + "(MaxText's dataset_type=synthetic batch, bit for bit, drawn as MaxText draws it, under " + "threefry2x32) | " + "npy:PATH ([gbs, seq + 1] integer tokens in [0, vocab), local or gs://; inputs " + "[:, :-1], targets [:, 1:])", + ) + ap.add_argument( + "--init-from", + default="", + help="load the weights from DIR/chunk.npz (local or gs://; maxtext_parity.py writes " + "them from a MaxText init) instead of initializing them", + ) + ap.add_argument( + "--max-ahead", + type=int, + default=None, + help="in the --bench and --profile loops, dispatch at most this many steps beyond the " + "last one finished (0: block after every step; default: no bound, but under Pathways " + f"(JAX_PLATFORMS=proxy) {PATHWAYS_MAX_AHEAD}, PATHWAYS_MAX_AHEAD -- a large number for practically none)", + ) + ap.add_argument( + "--json", + default="", + help="write the run record here (process 0), a local path or gs:// (a Pathways head pod's disk goes " + "with its pod); under --distributed the processes of " + "--json-procs write theirs next to it, .p before the extension (run.json -> " + "run.p3.json). With --profile it is written before the profiled steps as well, so that a run cut short " + "while profiling keeps it; a local file is replaced whole (written beside it, then renamed, its mode kept; " + "a symlinked record replaces the file the link names), while this process's stdout or stderr by any name " + "(/dev/stdout, a link to it, the log's own path) or another of its descriptors (/dev/fd/N) takes each record " + "after what was printed there before, and a named pipe or another target that is not a regular file is written " + "in place, and only after the profiled steps (a pipe keeps nothing across a crash, and its reader may stop at the " + "first record's end)", + ) + ap.add_argument( + "--json-procs", + default="leaders", + help="--distributed: which processes write a run record besides process 0: leaders " + "(each stage's first), all, or a comma list. A value other than leaders is refused under Pathways (one " + "client: --json)", + ) + ap.add_argument( + "--mem-report", + action="store_true", + help="print per-program compile-time memory and the persistent state per device", + ) + ap.add_argument( + "--grad-digest", + type=int, + default=0, + metavar="N", + help="diagnostics: every process logs a digest of each gradient leaf of its local chunks (its " + "shards, reduced, before the update) in the first N warmup steps -- to find, between two runs " + "of one setup, the first gradients that differ. Blocks each of those steps once", + ) + ap.add_argument( + "--distributed", + action="store_true", + help="multi-controller JAX: jax.distributed.initialize() (one process per host; a " + "process runs the stages on its devices and takes part in every boundary copy)", + ) + ap.add_argument( + "--transport", + default="native", + choices=["native", "ppermute", "xfer", "relay"], + help="boundary copies: native (jax's copy: batched D2D in one process, its cross-host copy across " + "processes -- on TPU v6e and v5p with jax 0.11.1 / libtpu 0.0.46 every receiving host aborts " + "in it), ppermute (a collective-permute program over " + "the two stages' devices, which both run: ICI inside a slice), xfer " + "(jax.experimental.transfer between host pairs, async, over DCN) or relay (a host relay: D2H, " + "TCP between the hosts, H2D, async, no libtpu cross-host path -- for across slices; " + "MPMD_RELAY_STREAMS / _CHUNK_MB / _TIMEOUT / _SOCKBUF_MB / _IP / _PORT tune it, " + "transfer.RelayContext; each process logs where its time went, transfer.RELAY_MEASURES, after " + "the warm-up and after --bench / --profile)", + ) + ap.add_argument( + "--profile-procs", + default="leaders", + help="--profile on which processes: leaders (each stage's first), all, or a comma list; across processes " + "they write one XProf session, on one clock (xprof_align). A value other than leaders is refused under " + "Pathways (--profile-hosts picks its traced worker hosts)", + ) + ap.add_argument( + "--profile-hlo-proto", + choices=("auto", "on", "off"), + default="auto", + help="--profile: whether the trace carries the compiled programs' HLO protos (its " + "/host:metadata plane; the XProf UI's op and graph views read them, xprof.py does not). " + "auto, the default on every platform, TPU too: off when this process's lowered programs " + "pass HLO_PROTO_AUTO_BYTES (1 GiB) of text -- a trace past protobuf's 2 GB is not written at " + "all, and a one-stage layout's 383 DeepSeek-V3 programs' protos alone were 2.6 GB; on: " + "always, as every trace did before this flag", + ) + ap.add_argument( + "--profile-chips", + type=profiling.chip_count, + default=None, + help="--profile: how many chips each traced process profiles, its first ones (libtpu " + "tpu_num_chips_to_profile_per_task), or 'all'. Default profiling.CHIPS, 1: one TPU a traced process, " + "one a slice under --layout slices; a process holding several stages (the one process of a " + "run, say) shows its first chip's stage only, unless this covers the others' chips. Under " + "Pathways (JAX_PLATFORMS=proxy) the default is all: every chip of each traced worker host", + ) + ap.add_argument( + "--profile-hosts", + type=profiling.positive_int, + default=None, + help="--profile under Pathways (JAX_PLATFORMS=proxy): how many Pathways worker hosts trace " + "(pathwaysutils' max_num_hosts; a multi-controller run picks its traced processes with " + "--profile-procs). Default $MPMD_PROFILE_HOSTS, else 1", + ) + return ap + + +def load_tokens(path): + """[gbs, seq + 1] int tokens from a .npy file (local or gs://).""" + return np.load(io.BytesIO(xprof_align.read_bytes(path))) + + +def missing_input(a, p): + """The message to stop with if a file the parsed flags `a` name for this + process of pipeline `p` to read does not exist, else None: --init-from's + chunk.npz for this process's stages (the files + `Pipeline.chunk_trees_from` reads), --data npy:'s file; local or gs://. + main asks before anything compiles, so a mistyped path fails in seconds, + not after the precompile.""" + exists = lambda path: xprof_align._blob(path).exists() if path.startswith("gs://") else os.path.exists(path) + if a.init_from: + for ch in p.chunks: + path = f'{a.init_from.rstrip("/")}/chunk{ch.index}.npz' + if (not p.multi or ch.stage in p.placed) and not exists(path): # in one controller every chunk's + return f"--init-from {a.init_from}: no such file {path}" + if a.data.startswith("npy:") and not exists(a.data[len("npy:") :]): + return f"--data {a.data}: no such file" + return None + + +def missing_input_anywhere(msg, timeout_s=900): + """Multi-controller: this process's `missing_input` answer `msg` -> the + message every process stops with if any process lacks a file, else None. + + Each process checks only the files it reads (its stages' chunks, maybe in a + directory local to its host), so a file some hosts lack would stop only + those: the others would wait for them at the next barrier until the + coordination service aborted every process, minutes later, without saying + why. So each process lacking a file publishes its message through the + key-value store (no TPU program); after a barrier every process reads them + all, so all of them stop together, each naming the processes lacking a file + and the file.""" + from jax._src import distributed + + client = distributed.global_state.client + if msg: + client.key_value_set(f"mpmd/inputs/{jax.process_index()}", msg) + client.wait_at_barrier("mpmd_inputs", timeout_s * 1000) + groups = collections.defaultdict(list) # message -> the processes giving it + for key, val in client.key_value_dir_get("mpmd/inputs/"): + groups[val].append(int(key.rsplit("/", 1)[1])) + if not groups: + return None + return ( + f"input files missing on {sum(map(len, groups.values()))} of {jax.process_count()} processes, so every " + "process stops: " + + "; ".join( + f'{m} (process{"es" if len(q) > 1 else ""} {_ranges(q)})' + for m, q in sorted(groups.items(), key=lambda kv: min(kv[1])) + ) + ) + + +def write_chunk_files(out, trees): + """Chunk-order weight trees (nested dicts of arrays, as `chunk_trees` + gives) -> out/chunk.npz (out local or gs://), the files + `Pipeline.chunk_trees_from` reads (--init-from): keys are the '.'-joined + tree paths, bfloat16 travels as its uint16 bits.""" + + def flat(node, prefix=()): + for k, v in node.items(): + if not isinstance(k, str) or "." in k: + raise ValueError(f'chunk tree key {k!r} at {".".join(prefix) or "the root"}: want a str without "."') + if isinstance(v, dict): + yield from flat(v, prefix + (k,)) + else: + yield ".".join(prefix + (k,)), v + + for c, tree in enumerate(trees): + arrays = {} + for k, v in flat(tree): + v = np.asarray(v) + arrays[k] = v.view(np.uint16) if v.dtype == jnp.bfloat16 else v + buf = io.BytesIO() + np.savez(buf, **arrays) + xprof_align.write_bytes(f'{out.rstrip("/")}/chunk{c}.npz', buf.getvalue()) + + +def init_distributed(): + """jax.distributed.initialize(), before the backend exists. + + The cross-host copy flags are plain flags jax does not read from the + environment: take them from it here (CPU needs the socket address; on TPU + they select the DCN path instead of the plugin's own). Cloud TPU / GKE + detect the rest; elsewhere (a CPU test on one machine) + JAX_COORDINATOR_ADDRESS, JAX_NUM_PROCESSES and JAX_PROCESS_ID say who is who. + Under Pathways (JAX_PLATFORMS=proxy) a SystemExit: one client drives every + device there, and jax.distributed would look for a cluster in its pod.""" + if pathways.is_proxy(): + raise SystemExit( + "--distributed: JAX_PLATFORMS=proxy is Pathways, where ONE client process drives every device of the job " + "(jax.process_count() is 1) and the pipeline runs its one-process path: run without --distributed" + ) + + def flag(v, name): + # jax's own spellings of a boolean environment variable (config.bool_env) + v = v.strip().lower() + if v in ("y", "yes", "t", "true", "on", "1"): + return True + if v in ("n", "no", "f", "false", "off", "0"): + return False + raise ValueError(f"{name.upper()}={v!r}: want 1/0, true/false, yes/no or on/off") + + for name, cast in ( + ("jax_cross_host_transfer_socket_address", str), + ("jax_cross_host_transport_addresses", str), + ("jax_force_dcn_cross_host_transfers", flag), + ("jax_cross_host_transfer_transfer_size", int), + ("jax_cross_host_transfer_timeout_seconds", int), + ): + if os.environ.get(name.upper()): + v = os.environ[name.upper()] + jax.config.update(name, cast(v, name) if cast is flag else cast(v)) + kw = { + k: int(os.environ[e]) + for k, e in (("num_processes", "JAX_NUM_PROCESSES"), ("process_id", "JAX_PROCESS_ID")) + if e in os.environ + } + # MPMD_COORD_PORT: a coordinator port of this run's own (TPU pods), so that + # a host late from an earlier run cannot join this one. jax's cluster + # detection puts it on worker 0 (after waiting for that name to resolve). + # On several slices that is MEGASCALE_COORDINATOR_ADDRESS's host (slice 0's + # worker 0; jax drops that address's port) at this same port, and jax + # numbers the processes slice x len(worker list) + worker of slices x + # len(worker list) (jax 0.11.1's clusters/cloud_tpu_cluster.py; jax's main + # of 2026-10-11 differs only in reading the worker list from + # TPU_PROCESS_ADDRESSES_PATH's file first; ds_ep_test's + # MultiController.test_multislice_coordinator). A JAX_COORDINATOR_PORT + # already set wins (a step running two programs can give each its own), + # with a warning: in the pod's environment it would give every step one port. + if os.environ.get("MPMD_COORD_PORT"): + port = os.environ.setdefault("JAX_COORDINATOR_PORT", os.environ["MPMD_COORD_PORT"]) + if port != os.environ["MPMD_COORD_PORT"]: + print( + f"init_distributed: warning: JAX_COORDINATOR_PORT={port} takes the place of this step's " + f'MPMD_COORD_PORT={os.environ["MPMD_COORD_PORT"]}: runs on one port can join each other\'s ' + "coordinator", + flush=True, + ) + # GPU pods (a GKE GPU JobSet): nothing autodetects the coordinator + # there, so the JobSet names its pod 0 (MAXTEXT_MPMD_COORD_HOST) and each step + # its port (MPMD_COORD_PORT, 8500 + step), as jax would put it on TPU. + if not os.environ.get("JAX_COORDINATOR_ADDRESS") and os.environ.get("MAXTEXT_MPMD_COORD_HOST"): + port = os.environ.get("JAX_COORDINATOR_PORT") or os.environ.get("MPMD_COORD_PORT") or "8482" + os.environ["JAX_COORDINATOR_ADDRESS"] = f"{os.environ['MAXTEXT_MPMD_COORD_HOST']}:{port}" + # Pods of a fresh slice start minutes apart (each pulls the image): wait + # for all of them, not jax's default 300 s. + kw["initialization_timeout"] = int(os.environ.get("MPMD_INIT_TIMEOUT", "1800")) + jax.distributed.initialize(**kw) + + +def multi_controller_only(a): + """What of `a` (make_parser's flags) asks for multi-controller JAX alone -> [message], in this order: --transport + relay or xfer (pathways.check_transport's message, its one copy), --distributed, --json-procs and --profile-procs + at a value other than their default (leaders), --norm-reduce allreduce -- each saying what to use instead. main + and mem_probe refuse them under Pathways (JAX_PLATFORMS=proxy) before the backend starts, in the same words: one + client process drives every device there (pathways.multi_controller() is False), so none of them could act, and + taking one silently would hide that. Elsewhere they stay as they are: a one-host run takes them (--norm-reduce + allreduce, the GPU default, runs the hops in one process; --distributed initializes a one-host slice's one process). + The multi-controller environment is not refused, since it may be set cluster-wide: MPMD_COORD_PORT, + JAX_COORDINATOR_*, MPMD_INIT_TIMEOUT, JAX_CROSS_HOST_*, MPMD_RELAY_* and MPMD_XFER_* are read only under + --distributed or the relay / xfer, refused here, and the import of this module skips MPMD_CACHE_EVERY_PROCESS under + the proxy.""" + out = [] + try: + pathways.check_transport(getattr(a, "transport", "native")) + except ValueError as e: + out.append(str(e)) + if getattr(a, "distributed", False): + out.append( + "--distributed: under Pathways (JAX_PLATFORMS=proxy) one client process drives every device, so there is no " + "jax.distributed to initialize: run without it" + ) + for flag, dest, instead in ( + ("--json-procs", "json_procs", "leave it out: the client writes the one run record, --json"), + ("--profile-procs", "profile_procs", "--profile-hosts N (or MPMD_PROFILE_HOSTS) traces N Pathways worker hosts"), + ): + if (procs := getattr(a, dest, "leaders")) != "leaders": + out.append( + f"{flag} {procs}: picks processes of a multi-controller run (--distributed); under Pathways one client " + f"process drives every device: {instead}" + ) + if getattr(a, "norm_reduce", "hops") == "allreduce": + out.append( + "--norm-reduce allreduce: one sum over every device of a multi-controller run (--distributed); under " + "Pathways one client holds every stage's sum of squares and hops it to the others, a scalar copy each: " + "--norm-reduce hops (the default)" + ) + return out + + +def plan_fingerprint(p, extra=()): + """Everything that decides which boundary copies and gradient-norm hops a + process issues, and how they move: the order and its fusion plan, the + placement, the transport, the stage meshes (which device of which process + holds each shard, and their axis types), the shard mode, the activation's + shape and dtype; what else of the plan decides a stage's programs, which + its processes must compile alike: the prefetch pins (an 'auto' plan also + reads LIBTPU_INIT_ARGS and the client's slices) and how the gathers and + reduce-scatters split their collectives; plus `extra` (main adds every + flag but --json, the run loop's step counts among them) -> a tuple with a + deterministic repr.""" + cfg = p.scfg.model + return ( + p.order, + tuple(p.place), + p.placement, + p.transport, + p.overlap, + sorted(p.modes.items()), + sorted(p.fuse), + sorted(p.pf.items()), + sorted(p.pf_n.items()), + p.fsdp_scope, + sorted(p.release_at.items()), + sorted(p.rs_at.items()), + sorted(p.rs_self.items()), + p.final_slots, + p.gather_slots, + p.mbs, + p.seq, + p.cp, + p.S, + p.C, + cfg.emb_dim, + str(jnp.dtype(cfg.dtype)), + p.scfg.shard_mode, + [m.device_ids.tolist() for m in p.meshes], + [tuple(m.axis_names) for m in p.meshes], + [tuple(str(t) for t in m.axis_types) for m in p.meshes], + sorted(p.pins.items()), + p.scfg.gather_axes, + p.scfg.rs_axes, + tuple(extra), + ) + + +def host_barrier(name, timeout_s=1800): + """Multi-controller: wait until every process gets here, through the + coordination service (a host barrier: no TPU program). main holds every + process at one after the compiles and one after init, so no stage starts + programs that its peers' devices (or, under --transport ppermute, the next + stage's) must join while another process is still compiling: on 2 x + TPU7x-4x4x4 a stage's first programs, launched while the other stage still + compiled, failed the slices (SLICE_FAILURE_SW_INJECT_ERROR), and a fused + last chunk halted its stage's cores on a launch-id mismatch.""" + from jax._src import distributed + + distributed.global_state.client.wait_at_barrier(name, timeout_s * 1000) + + +def check_plan_agreement(p, timeout_s=900, extra=()): + """Multi-controller: stop every process unless all of them built the same + plan (`plan_fingerprint`). + + Each process walks the order and issues every boundary copy in it; two + processes with different plans (a schedule search that is not + deterministic, different flags) would pair copies wrongly -- silently -- + or wait on copies that never come, and two of one stage that compiled its + programs differently (other prefetch pins) would hang in their + collectives. Each process publishes its hash through the coordination + service's key-value store (no TPU program); after a barrier every process + compares all of them, so all of them stop together, each naming the + processes that differ.""" + from jax._src import distributed + + h = hashlib.sha256(repr(plan_fingerprint(p, extra)).encode()).hexdigest() + client = distributed.global_state.client + client.key_value_set(f"mpmd/plan/{jax.process_index()}", h) + client.wait_at_barrier("mpmd_plan_agreement", timeout_s * 1000) + groups = collections.defaultdict(list) + for key, val in client.key_value_dir_get("mpmd/plan/"): + groups[val].append(int(key.rsplit("/", 1)[1])) + if len(groups) > 1: + raise RuntimeError( + f"the processes built {len(groups)} different plans (" + + "; ".join(f"{v[:12]}: processes {sorted(q)}" for v, q in groups.items()) + + "): they would issue different boundary copies" + ) + return h + + +def lowered_print(lowered): + """A lowered program's print, cheap to compare across processes and runs: + {'sha': the sha256 of its text (16 hex digits), 'bytes', 'consts', + 'funcs': the text's size and its constant / function counts} -- the counts + say at a glance how two prints of one program differ (one constant more: + a table copied where the other shares it).""" + txt = lowered.as_text() + return { + "sha": hashlib.sha256(txt.encode()).hexdigest()[:16], + "bytes": len(txt), + "consts": txt.count("stablehlo.constant"), + "funcs": txt.count("func.func"), + } + + +def executable_print(compiled): + """The sha256 (16 hex digits) of a compiled TPU program's executable + fingerprint, from which jaxlib derives the id of each of its launches (with + the count of launches before) -- or None off TPU, where nothing launches by + id and the fingerprint is not even stable (CPU: a program compiled twice in + one process can print two ways; on TPU a fresh compile, a second one and + one read back from the persistent cache print alike), and where the + backend gives none (an executable for a compile-only topology may refuse + to).""" + try: + exe = compiled.runtime_executable() + if {d.platform for d in exe.local_devices()} != {"tpu"}: + return None + fp = getattr(exe, "fingerprint", None) + except Exception: # an UNIMPLEMENTED from the backend: no print, nothing to compare + return None + if fp is None: + return None + return hashlib.sha256(fp if isinstance(fp, bytes) else str(fp).encode()).hexdigest()[:16] + + +def _stage_key(stage): + """A program's stage as the key-value store keys it: '1', or '0-1' for a + boundary copy over stages 0 and 1.""" + return "-".join(map(str, stage)) if isinstance(stage, tuple) else str(stage) + + +def _ranges(ids): + """[0, 1, 2, 5, 7, 8] -> '0-2,5,7-8'.""" + ids, out = sorted(ids), [] + for i in ids: + if out and i == out[-1][1] + 1: + out[-1][1] = i + else: + out.append([i, i]) + return ",".join(str(a) if a == b else f"{a}-{b}" for a, b in out) + + +# Numbers the key-value store keys of each `check_program_agreement`: every process makes its checks in one order. +_PROGRAM_KEYS = itertools.count() + + +def check_program_agreement(p, prints, what, timeout_s=3600, show=6): + """Multi-controller: stop every process, before any program launches, + unless each program is the same on all the processes that run it. + + `prints` are this process's [(name, stage, fingerprint, stats)] + (`Pipeline.precompile`'s `agree`): what='lowered', the sha256 of each + lowered text with its `lowered_print` stats, or 'executables', of each + executable's fingerprint. A stage's programs run on all its processes (a + boundary copy's, stage (a, b), on both stages'), and processes that launch + different programs at one launch -- a precompile racing in a kernel's + cache, a compiler that is not deterministic -- halt the TPU runtime long + after the cause ('an unexpected peer shows up in the launch group with a + different launch id than the current group leader'). So each process + publishes a digest of its programs per stage, and its prints, in the + coordination service's key-value store (no TPU program); after a barrier + every process compares every stage's digests and, where they differ, + fetches the prints of one process per digest: all of them stop together, + each naming the programs that differ, their prints and the processes + holding each. -> {stage key: digest}.""" + from jax._src import distributed + + client = distributed.global_state.client + pid, n = jax.process_index(), next(_PROGRAM_KEYS) + key = f"mpmd/programs/{what}/{n}" + seen, named, mine = collections.Counter(), [], collections.defaultdict(list) + for name, stage, fp, st in prints: # a name twice on a stage: name, name#1, ... + sk = _stage_key(stage) + k = seen[(name, sk)] + seen[(name, sk)] += 1 + named.append((f"{name}#{k}" if k else name, sk, fp, st)) + mine[sk].append((named[-1][0], fp)) + for sk, progs in mine.items(): + client.key_value_set(f"{key}/digest/{sk}/{pid}", hashlib.sha256(json.dumps(sorted(progs)).encode()).hexdigest()[:16]) + client.key_value_set(f"{key}/prints/{pid}", json.dumps(named)) + client.wait_at_barrier(f"mpmd_programs_{what}_{n}", timeout_s * 1000) + digests = collections.defaultdict(lambda: collections.defaultdict(set)) # stage key -> digest -> processes + for k, v in client.key_value_dir_get(f"{key}/digest/"): + sk, q = k.rsplit("/", 2)[1:] + digests[sk][v].add(int(q)) + + def procs(sk): + return frozenset().union(*(p.stage_procs[int(s)] for s in sk.split("-"))) + + bad = sorted( + (sk for sk in digests if len(digests[sk]) > 1 or set().union(*digests[sk].values()) != procs(sk)), + key=lambda sk: [int(s) for s in sk.split("-")], + ) + if not bad: + return {sk: next(iter(d)) for sk, d in digests.items()} + cache = {} + + def prints_of(q): + if q not in cache: + cache[q] = { + (nm, sk): (fp, st) + for nm, sk, fp, st in json.loads(client.blocking_key_value_get(f"{key}/prints/{q}", timeout_s * 1000)) + } + return cache[q] + + def said(fp, st): + return fp if not st else f'{fp} ({st["bytes"]} bytes, {st["consts"]} constants, {st["funcs"]} funcs)' + + lines = [] + for sk in bad: + groups = sorted(digests[sk].items(), key=lambda kv: min(kv[1])) + missing = procs(sk) - set().union(*digests[sk].values()) + lines.append( + f'stage {sk}: {len(groups)} program set{"s" if len(groups) > 1 else ""} (' + + "; ".join(f"{d}: processes {_ranges(q)}" for d, q in groups) + + (f"; none from processes {_ranges(missing)}" if missing else "") + + ")" + ) + reps = [min(q) for _, q in groups] + names = sorted({nm for r in reps for nm, s in prints_of(r) if s == sk}) + differ = [nm for nm in names if len({prints_of(r).get((nm, sk), (None,))[0] for r in reps}) > 1] + for nm in differ[:show]: + lines.append( + f" {nm}: " + + "; ".join( + f'{said(*prints_of(r)[(nm, sk)]) if (nm, sk) in prints_of(r) else "not lowered"} on processes ' + f"{_ranges(q)}" + for r, (_, q) in zip(reps, groups) + ) + ) + if len(differ) > show: + lines.append(f" ... and {len(differ) - show} more: {differ[show:]}") + raise RuntimeError( + f"the processes hold different {what} programs, which would halt the TPU runtime at their first " + 'launch ("a different launch id than the current group leader"):\n' + "\n".join(lines) + ) + + +def grad_digest_lines(p, grads, step): + """This process's reduced gradients (`Pipeline.step`'s, before the update) + -> a line per local chunk: each leaf's sha256 (8 hex digits) over its local + shards' bytes, in device order -- equal between two runs of one setup only + where each shard is bit for bit.""" + out = [] + for s in sorted(p.local) if p.multi else range(p.S): + for ch, tree in zip(p.stage_chunks[s], grads[s]): + leaves = [] + for path, x in jax.tree_util.tree_flatten_with_path(tree)[0]: + h = hashlib.sha256() + for sh in sorted(x.addressable_shards, key=lambda sh: sh.device.id): + h.update(np.ascontiguousarray(np.asarray(sh.data)).reshape(-1).view(np.uint8)) + leaves.append(f'{jax.tree_util.keystr(path, simple=True, separator=".")}={h.hexdigest()[:8]}') + out.append(f"grad digest step {step} c{ch.index}: " + " ".join(leaves)) + return out + + +def program_prints_lines(p, stage): + """Stage `stage`'s programs as precompile printed them (`program_prints`): + one line per program -- the lowered text's sha256, size and constant + count, and the executable's sha256.""" + rows = [(n, lw, x) for n, s, lw, x in getattr(p, "program_prints", []) if s == stage] + digest = hashlib.sha256(json.dumps(sorted((n, lw["sha"], x) for n, lw, x in rows)).encode()).hexdigest()[:16] + out = [ + f"stage {_stage_key(stage)}: {len(rows)} programs, digest {digest} (each: sha256 of the lowered text, its " + "bytes and constants; of the executable fingerprint)" + ] + out += [f' {n} {lw["sha"]} {lw["bytes"]}B {lw["consts"]}c {x or "-"}' for n, lw, x in rows] + return out + + +def shared_profile_session(timeout_s=900): + """Multi-controller --profile: (session name, origin ns since the epoch) + every process agrees on. After a barrier -- the profiled steps start from + a drained pipeline on every stage -- process 0 takes its clock less 10 ms + (host clocks agree to far less: NTP) as the origin every traced host + rebases onto, and names the session after it in local time, as jax names + a one-process session (pathways.session_id): a logdir's sessions go by + their names (XProf, xprof.find_xplane).""" + from jax._src import distributed + + client = distributed.global_state.client + client.wait_at_barrier("mpmd_profile_start", timeout_s * 1000) + if jax.process_index() == 0: + origin = time.time_ns() - 10_000_000 + session = pathways.session_id(origin / 1e9) + client.key_value_set("mpmd/profile_session", f"{session} {origin}") + else: + session, origin = client.blocking_key_value_get("mpmd/profile_session", timeout_s * 1000).split() + return session, int(origin) + + +# --profile-hlo-proto auto's bound on this process's lowered program text: their HLO protos in a trace run ~1.2x it +# (one-stage layouts on GB200: the Qwen3.8 16-layer one's 174 programs, 0.53 GB of text, 0.63 GB of protos; +# DeepSeek-V3's 383, 2.14 GB and 2.63 GB, whose trace was then not written), and protobuf writes no message past 2 GB. +HLO_PROTO_AUTO_BYTES = 1 << 30 + + +def profile_hlo_proto(mode, p): + """--profile-hlo-proto -> does this process's trace keep its programs' HLO protos. 'auto': yes unless the + lowered text of the programs it compiled (`program_prints`: none without a precompile) passes + HLO_PROTO_AUTO_BYTES.""" + if mode != "auto": + return mode == "on" + return sum(lw.get("bytes", 0) for _, _, lw, _ in getattr(p, "program_prints", ())) <= HLO_PROTO_AUTO_BYTES + + +def proc_set(spec, p, flag="--profile-procs"): + """--profile-procs / --json-procs -> a set of processes: leaders (each + stage's first process), all, or a comma list of process ids (SystemExit on + anything else; every process parses the same flags, so all stop together).""" + if spec == "all": + return set(range(jax.process_count())) + if spec == "leaders": + return {min(p.stage_procs[s]) for s in range(p.S)} + try: + got = {int(x) for x in spec.split(",")} + except ValueError: + raise SystemExit(f"{flag}: leaders, all or a comma list of process ids, not {spec!r}") from None + if bad := sorted(got - set(range(jax.process_count()))): + raise SystemExit(f"{flag}: no process {bad} (there are {jax.process_count()})") + return got + + +# --max-ahead's default under Pathways: the steps the client may dispatch beyond the last one finished. Nothing else +# bounds it there -- the IFRT proxy client takes no PJRT options (transfer.set_max_inflight is a local client's) -- +# and a local Pathways run queued ~90 steps, so that a worker running out of memory surfaced only as a dropped proxy +# connection, steps after the step that caused it. run_steps waits for the steps to finish beside the dispatch +# (`_Finished`), so bounded or not a short step takes the same time there. +PATHWAYS_MAX_AHEAD = 2 + + +class _Finished: + """run_steps' bound on running ahead: a thread of its own waits, in order, for each step's outputs it is handed + (`watch`) to be ready, and `wait` returns once the oldest step not yet waited for has finished -- or raises what + waiting for it raised. Through the IFRT proxy even a wait for a step long finished is a round trip: made in the + dispatch loop, as a jax.block_until_ready a step, it slowed short steps by a quarter (local Pathways, tpu7x-8, M=1 + S=2: 2.0 ms a step unbounded, 2.6 so bounded); made here, beside the dispatch, by nothing measurable (2.0).""" + + def __init__(self): + self._todo = queue.SimpleQueue() + self._done = threading.Semaphore(0) + self._errors = [] + threading.Thread(target=self._run, name="mpmd-run-ahead", daemon=True).start() + + def _run(self): + while (outs := self._todo.get()) is not None: + try: + jax.block_until_ready(outs) + # the step's own error, whatever it is: `wait` raises it in the dispatch loop + except BaseException as e: # pylint: disable=broad-exception-caught + self._errors.append(e) + del outs + self._done.release() + + def watch(self, outs): + self._todo.put(outs) + + def wait(self): + self._done.acquire() # pylint: disable=consider-using-with # one finished step, counted off: no release + if self._errors: + raise self._errors[0] + + def close(self): + self._todo.put(None) + + +def run_steps(p, state, n, batch, lrs, max_ahead=None): + """n steps of `p` back to back (`Pipeline.step`), with at most `max_ahead` + of them dispatched beyond the last one this process has seen finish -- + every local stage's update and the loss partials, waited for beside the + dispatch (`_Finished`); no bound for None -> (params, opts, wc0, lacc, + gnorms) after the last. + + `state` is [params, opts, wc0], emptied first, so that the caller holds no + reference to what the first step consumes. The gathered weights wc0 are not + donated: a caller that kept them for the whole loop held a second copy (2.3 + GB a stage-0 device on 2 x v6e-128 at E384), and on 31 GiB chips that + fragmented HBM so that stage 0's first chunk-0 backward, which allocates + the chunk's gradient accumulators, stopped to defragment it in nearly every + run-ahead step (85-104 ms, 2026-10). The loop that blocks every step + rebinds them each step, so it never had the copy.""" + params, opts, wc0 = state + state.clear() + lacc = gn = None + finished = None if max_ahead is None else _Finished() + try: + for k in range(n): + if finished is not None and k > max_ahead: + finished.wait() # step k - max_ahead - 1 + params, opts, wc0, lacc, gn = p.step(params, opts, wc0, batch, lrs) + if finished is not None: + finished.watch((p.step_gnorms, lacc)) # never donated + finally: + if finished is not None: + finished.close() + return params, opts, wc0, lacc, gn + + +def json_target(path): + """What the local --json path `path` is -> (descriptor, stat): one of this process's file descriptors to write the + record through, or None; and os.stat(path), through every link, or None where nothing is there (or it was not + asked, the path naming a descriptor). Raises the OSError of a stat that fails otherwise (write_json returns it).""" + if m := re.fullmatch( + rf"/dev/std(in|out|err)|/(?:dev|proc/(?:self|thread-self|{os.getpid()}))/fd/(\d+)", os.path.abspath(path) + ): + # By its name, never resolved: with stdout `> run.log`, /dev/stdout -> /proc/self/fd/1 -> run.log, a regular file, + # and a temp file renamed onto it replaced the log (the descriptor writing on into the unlinked file, and the next + # record going to a new file named what /proc/self/fd/1 then gives, 'run.log (deleted)'). + return int(m[2]) if m[2] else {"in": 0, "out": 1, "err": 2}[m[1]], None + try: + st = os.stat(path) # through every link: a symlinked record, say + except FileNotFoundError: + return None, None + # Stdout or stderr by a name the pattern misses -- a link to /dev/stdout, a directory link to /dev, the log's own + # path -- names the log its descriptor is open on: replaced, the log was lost as with /dev/stdout resolved. + for k in 1, 2: + try: + if os.path.samestat(os.fstat(k), st): + return k, st + except OSError: # k closed + pass + return None, st + + +def write_json(path, record, provisional=False): + """`record` as JSON at `path`, local or gs:// (--json's run record) -> None, or the error that kept it from being + written. A local file is written whole or not at all: under a temporary name beside it, then renamed over it + (os.replace, atomic within a filesystem), so a run cut short while writing it, or a write that fails (a full disk), + leaves the record written before -- main's of the steps before a profile, say -- as it was. Where `path` is a + symlink the file it names is the one replaced (the link stays), and an existing record keeps its permission bits. + + Two kinds of local target are not replaced. One of this process's descriptors -- by the name /dev/stdout, + /dev/stderr, /dev/fd/N, /proc/self/fd/N, /proc/thread-self/fd/N or /proc//fd/N, and stdout and stderr by any + other name os.stat finds to be the file descriptor 1 or 2 is open on (a link to /dev/stdout, the log's own path) -- + is written through the descriptor, whatever it is open on, after what the process wrote there before, with a + newline after the record: with stdout `> run.log` or `>> run.log`, --json /dev/stdout (a link to it, run.log) + leaves the log every line and each record in its place. (A descriptor other than 1 and 2 by another name, a link + to /dev/fd/3 say, is taken for the file it is open on: a regular file there is replaced.) A target that is no + regular file (a named pipe, a device) is written in place, and gets no `provisional` record (main's before the + profile, which the one after it replaces): it keeps nothing across a crash, and each write opens it anew, so a pipe + whose reader read the first record to its end and went left the second write's open waiting for another reader + without end.""" + data = json.dumps(record, indent=1, default=str) + if path.startswith("gs://"): # a Pathways head pod's disk goes with its pod; a GCS object is replaced whole + try: + xprof_align.write_bytes(path, data.encode()) + # google.api_core's errors are no OSError + except Exception as e: # pylint: disable=broad-exception-caught + return e + return None + try: + fd, st = json_target(path) + if fd is not None: + for s in sys.stdout, sys.stderr: # what the process printed so far comes before the record + if s is not None: # None: the process started with that descriptor closed (`>&-`), nothing printed to flush + s.flush() + with os.fdopen(os.dup(fd), "w", encoding="utf-8") as f: + f.write(data + "\n") + return None + if st is not None and not stat.S_ISREG(st.st_mode): # a named pipe, a device: nothing to replace + if provisional: + return None + with open(path, "w", encoding="utf-8") as f: + f.write(data) + return None + path = os.path.realpath(path) # a symlink's file is replaced beside itself, the link kept + tmp = os.path.join(os.path.dirname(path), f".{os.path.basename(path)}.{os.getpid()}.tmp") + try: + with open(tmp, "w", encoding="utf-8") as f: + f.write(data) + if st is not None: # an existing record keeps its permission bits (the temp file has the umask's) + os.chmod(tmp, stat.S_IMODE(st.st_mode)) + os.replace(tmp, path) + finally: + try: + os.remove(tmp) # still there only if the write or the rename failed + except OSError: + pass + except OSError as e: + return e + return None + + +def main(argv=None): + # Under Pathways (JAX_PLATFORMS=proxy): pathwaysutils, before anything starts a backend (else nothing). + proxy = pathways.initialize() + warnings.filterwarnings("ignore", message="Some donated buffers were not usable") + a = make_parser().parse_args(argv) + if a.data not in ("synthetic", "maxtext") and not a.data.startswith("npy:"): + raise SystemExit(f"--data must be synthetic, maxtext or npy:PATH, not {a.data!r}") + if a.max_ahead is not None and a.max_ahead < 0: + raise SystemExit(f"--max-ahead must be >= 0 (leave it out for no bound), not {a.max_ahead}") + # Checked now, not where they are used, after the compile and warm-up (--bench divides by --steps there). + if a.bench and a.steps < 1: + raise SystemExit(f"--steps must be >= 1 with --bench (the steps it times), not {a.steps}") + if a.profile and a.profile_steps < 1: + raise SystemExit(f"--profile-steps must be >= 1 with --profile (the steps it traces), not {a.profile_steps}") + if a.profile_hosts is not None and not proxy: + raise SystemExit( + "--profile-hosts is Pathways' (JAX_PLATFORMS=proxy) count of traced worker hosts; a multi-controller run " + "picks its traced processes with --profile-procs" + ) + # Under Pathways what only multi-controller JAX takes: refused before the backend starts (and before the write + # probe and the Lineage checks below), not by Pipeline or init_distributed after them. + if proxy and (bad := multi_controller_only(a)): + raise SystemExit("\n".join(bad)) + if proxy and a.max_ahead is None: # the client's run-ahead bounded there (PATHWAYS_MAX_AHEAD); the record says so + a.max_ahead = PATHWAYS_MAX_AHEAD + # A gs:// path that names no bucket stops the run now, in every mode (a dry run too), before + # jax.distributed.initialize: every process parses the same flags, so all stop together (across processes the + # probe's answer is only a warning, and their traces would go into a local directory 'gs:'). + for flag, path in (("--profile", a.profile), ("--json", a.json)): + try: + pathways.check_bucket(path, flag) + except ValueError as e: + raise SystemExit(str(e)) from None + profile_hosts = None + if a.profile and proxy: # a trace only goes to gs:// there: said now, not after the compile and the steps + try: + pathways.check_trace_dir(a.profile) + except ValueError as e: + raise SystemExit(str(e)) from None + env_hosts = os.environ.get("MPMD_PROFILE_HOSTS", "1") + try: + profile_hosts = a.profile_hosts or profiling.positive_int(env_hosts) + except (ValueError, argparse.ArgumentTypeError) as e: + raise SystemExit(f"MPMD_PROFILE_HOSTS={env_hosts!r}: a number of hosts, at least 1 ({e})") from None + unwritable = None # under --distributed, why this client cannot write a gs:// --profile: acted on once initialized + if a.profile and str(a.profile).startswith("gs://") and not a.dry_run: + # Tried now, in any mode: a bucket nobody can write would hang a trace written straight into it when it stops + # (one process, Pathways or not; under Pathways the proxy with it). Under --distributed the answer waits for + # jax.distributed.initialize, since a process stopping before it would keep the others waiting: then one process + # (a one-host slice) stops as well, while across processes each traced one writes a local directory first and an + # export error only costs the profile (a warning). Not on a dry run, which traces nothing. + try: + pathways.probe_trace_dir(a.profile) + except ValueError as e: + if not a.distributed: + raise SystemExit(str(e)) from None + unwritable = str(e) + if (why := lineage_missing(a)) is not None: + # the pipeline would build and only its first program's trace fail: say so before anything starts (a dry run + # traces nothing, so it only warns) + if not a.dry_run: + raise SystemExit(f"--batch-split: {why}") + print(f"warning: --batch-split: {why}", flush=True) + if a.distributed: # multi-controller JAX: jax.distributed first (a one-host slice runs one process) + init_distributed() + if unwritable is not None: + if not pathways.multi_controller(): # one process: its trace goes straight into gs://, as without --distributed + raise SystemExit(unwritable) + print( + f"warning: {unwritable} -- not across {jax.process_count()} processes: a traced one writes its trace into " + "a local directory first, and keeps it there when the export fails", + flush=True, + ) + # this process's id: jax's under multi-controller JAX (whoever started jax.distributed), 0 in one controller + pid = jax.process_index() if pathways.multi_controller() else 0 + if (why := lineage_off_tpu(a)) is not None: + # the same: Lineage's kernels have no CPU / GPU path (asked only now: asking initializes the backend, which + # jax.distributed.initialize refuses to follow) + if not a.dry_run: + raise SystemExit(f"--batch-split: {why}") + if pid == 0: + print(f"warning: --batch-split: {why}", flush=True) + + p = build(a) + # Pathways or not, from here on the Pipeline's answer (its devices' client: on_pathways), which JAX_PLATFORMS's + # first platform (pathways.is_proxy) only predicted before the backend started. + if on_pathways(p.meshes) != proxy: + p.close() + raise SystemExit( + f"JAX_PLATFORMS={os.environ.get('JAX_PLATFORMS')!r} said {'' if proxy else 'not '}Pathways, but the " + f"pipeline's devices are {'not ' if proxy else ''}the IFRT proxy's " + f"({getattr(p.meshes[0].devices.flat[0].client, 'runtime_type', '?')}): give JAX_PLATFORMS=proxy for " + "Pathways, a platform of this host's own otherwise" + ) + resolved_config(a, p) + popts = None + if a.profile: + # Under Pathways no process is a stage's, so each traced worker host traces every chip unless told otherwise, + # under a session name known here (the line naming where the profile went gives it). + chips = profiling.EVERY_CHIP if proxy and a.profile_chips is None else a.profile_chips + popts = profiling.profile_options(chips, platform=jax.devices()[0].platform) + if proxy: + popts.session_id = pathways.session_id() + last = p.chunks[-1].stage + # In one controller everything prints as it always has: this process runs every stage (and the last), writes the + # record and traces. Across processes (multi-controller JAX) process 0 prints the run's header, each stage's first + # process its stage's numbers, tagged with the stage, and the last chunk's stage the loss; the processes of + # --json-procs write records, those of --profile-procs trace (flags every process parses alike, checked before any + # compile or step). + if p.multi: + traced_procs = proc_set(a.profile_procs, p, "--profile-procs") if a.profile else None + json_procs = proc_set(a.json_procs, p, "--json-procs") | {0} + lead = {s: min(p.stage_procs[s]) for s in range(p.S)} + mine = sorted(p.local) + is_lead = any(lead[s] == pid for s in mine) + runs_last = last in p.local + tag = f'[s{",".join(map(str, mine))} p{pid}] ' if mine else f"[idle p{pid}] " + else: + traced_procs = json_procs = None + lead, mine, is_lead, runs_last, tag = dict.fromkeys(range(p.S), pid), list(range(p.S)), True, True, "" + + def log(msg, when=True): + if when: + print(tag + msg, flush=True) + + for flag in lineage_ignored(a): + log( + f"warning: {flag}: not used by --batch-split on Lineage's layers, which run their own expert kernels, " + "dispatch, EP collectives and splash attention (ds_ep_lineage.IGNORED_STAGE_KNOBS / IGNORED_MODEL_FIELDS)", + pid == 0, + ) + for line in lineage_unused(a) + lineage_partial(a): + log(f"warning: {line}", pid == 0) + pv = provenance(p.scfg, tiles=("custom" if (a.wi_tiling or a.wo_tiling) else a.tiles)) + log(provenance_line(pv), pid == 0) + log(p.summary(), pid == 0) + if p.multi: + # every flag goes into the check: the step counts decide how many copies + # each process walks, and every stage's processes must train the same data. + # But --json, the file a process writes its record to, decides nothing of + # the plan, and a launcher may name one in each host's own directory. + h = check_plan_agreement(p, extra=sorted((k, v) for k, v in vars(a).items() if k != "json")) + idle = sorted(set(range(jax.process_count())) - set().union(*p.stage_procs)) + log( + f"multi-controller: {jax.process_count()} processes; this one runs stage {mine} with " + f"{len(jax.local_devices())} local devices; stage leaders {lead}; plan {h[:12]} agreed", + is_lead, + ) + log( + f'{len(idle)} process{"es hold" if len(idle) > 1 else " holds"} no stage ({p.S} stages x ' + f"{a.fsdp * a.ep} devices of {jax.device_count()}): only taking part in the boundary copies", + pid == 0 and bool(idle), + ) + log("this process holds no stage: it only takes part in the boundary copies", not mine) + if p.relay_ctx is not None: # its settings, and the host's that its throughput depends on + log(p.relay_ctx.describe(), is_lead) + if p.transport == "native" and native_transport_aborts(jax.devices()[0].device_kind): + log( + "warning: --transport native across v6e / v5p hosts: jax's cross-host receive aborts there (jax 0.11.1, " + "libtpu 0.0.46): --transport xfer, ppermute or, across slices, relay", + pid == 0, + ) + # Stages over several slices: across processes (jax's own copies between them: one host never spans slices), or in + # the one process of a Pathways run, which holds them all (each copy one IFRT CopyArrays: the note). + if p.multi and (msg := cross_slice_warning(p.meshes, p.transport)): + log(f"warning: {msg}", pid == 0) + if msg := cross_slice_note(p.meshes, p.transport): + log(msg, pid == 0) + if span := slice_spanning_stages(p.meshes): + log( + f"warning: stages {span} span TPU slices, so their FSDP and EP collectives cross DCN: --layout " + f"{a.layout} does not place by slice (one stage per slice is --layout slices)", + pid == 0, + ) + if proxy and (msg := pathways.client_flags_note()): + log(msg) + # Each stage's collectives, and libtpu's SparseCore answer against the device rule where it was asked: across + # processes, and in the one process of a Pathways run, whose server compiles otherwise than McJAX's libtpu (it + # offloads where McJAX keeps a stage synchronous, so its plan can differ). + if p.multi or proxy: + for s in mine: + c = p.stage_scfg[s] + ep = ( + f"Lineage's own ({'on SparseCore' if p.lineage_sc[s] else 'as TensorCore code'})" + if p.scfg.lineage_split + else c.ep_collectives + ) # (on Lineage's layers ds_ep's flavour runs nowhere: the summary's line) + log(f"stage {s}: EP collectives {ep}, FSDP collectives {c.fsdp_collectives}", lead[s] == pid) + if (s, ds_ep.FE) in p.offloads and _is_tpu(p.meshes[s].devices.flat[0]) and p.meshes[s].devices.size > 1: + log(offload_check(p.meshes, s, *p.offloads[(s, ds_ep.FE)]), lead[s] == pid) # the plan's answer + if a.dry_run: + p.close() + rec = {"config": vars(a), "summary": p.summary(), "provenance": pv} + if p.split_chunks: + rec["zb"] = p.zb_record() + return rec + # Before the precompile, which would stop lowering the first backward; the processes share flags and device + # kind, so all of them stop here together. + if msg := float32_ragged_sort_problem(a, p.scfg): + p.close() + raise SystemExit(msg) + msg = missing_input(a, p) # before the precompile: a mistyped path fails in seconds + if p.multi and (a.init_from or a.data.startswith("npy:")): # flags alike on all processes: all reach its barrier + msg = missing_input_anywhere(msg) + if msg: + p.close() + raise SystemExit(msg) + if not a.no_precompile: + # across processes every stage's programs must be the same on all its processes: checked before any launches + n, dt = p.precompile(agree=functools.partial(check_program_agreement, p) if p.multi else None) + log(f"precompiled {n} programs in {dt:.1f}s" + (", each the same on all its processes" if p.multi else ""), is_lead) + for s in dict.fromkeys(s for _, s, _, _ in p.program_prints): # a boundary copy's: under its first local stage + log( + "\n".join(program_prints_lines(p, s)), + not p.multi or lead[s if isinstance(s, int) else next(x for x in s if x in p.local)] == pid, + ) + if p.multi: + t0 = time.perf_counter() + host_barrier("mpmd_precompiled") + log(f"every process compiled: waited {time.perf_counter() - t0:.1f}s at the barrier", is_lead) + t0 = time.perf_counter() + if a.init_from: + if p.scfg.layer_tree == "per_layer" and not ds_ep.is_qwen(p.scfg.model): + raise SystemExit( + f"--init-from {a.init_from}: chunk files hold a DeepSeek chunk's layers stacked; run with " + "--layer-tree stacked" + ) + try: + params, opts, wc0 = p.init_state(p.params_from_chunks(p.chunk_trees_from(a.init_from))) + except ValueError as e: + raise SystemExit(f"--init-from {a.init_from}: {e}") from None + else: + params, opts, wc0 = p.init(jax.random.key(0)) + if a.data == "synthetic": + batch = p.synthetic_batch() + else: + impl = MAXTEXT_BATCH_PRNG if a.data == "maxtext" else None + toks = p.maxtext_tokens(impl) if impl else load_tokens(a.data[len("npy:") :]) + try: + batch = p.token_batch(toks) + except ValueError as e: + raise SystemExit(f"--data {a.data}: {e}") from None + digest = hashlib.sha256(np.ascontiguousarray(np.asarray(toks, np.int32)[:, :-1]).tobytes()).hexdigest()[:16] + log(f"data: {a.data}{f' (under {impl})' if impl else ''}, inputs sha256 {digest}", is_lead) + lrs = p.lr_arrays(a.lr) + jax.block_until_ready((params, opts, batch)) + log(f"init {time.perf_counter() - t0:.1f}s" + (f" (weights from {a.init_from})" if a.init_from else ""), is_lead) + if p.multi: + host_barrier("mpmd_initialized") + if a.mem_report: + log( + p.mem_report( + {"params (storage)": params, "optimizer (mu, nu)": opts, "pre-gathered weights (wc0)": wc0, "batch": batch} + ), + is_lead, + ) + + losses, gnorms = [], [] + if a.grad_digest: + seen = itertools.count() + + def on_grads(grads): + k = next(seen) + if k < a.grad_digest: + log("\n".join(grad_digest_lines(p, grads, k)), bool(mine)) + + p.on_grads = on_grads + t0 = time.perf_counter() + for i in range(a.warmup): + params, opts, wc0, lacc, gn = p.step(params, opts, wc0, batch, lrs) + read = None + if proxy: # one client runs every stage (gn and lacc are its own) + # one round trip for both (each costs a few ms through the IFRT proxy): the same values as the reads below + read = [float(x) for x in jax.device_get((gn, jnp.sum(lacc)))] + gnorms.append(None if gn is None else read[0] if read else float(gn)) # the global norm: every stage has it + # With bf16 weights MaxText reports its norms as bf16 scalars: compare those with this one rounded. + gnorm = "" if gn is None else f"gnorm {gnorms[-1]:.6f} (bf16 {float(jnp.bfloat16(gnorms[-1])):.6g})" + if runs_last: # the sum is a program on the last stage: all its processes run it + l = read[1] if read else float(jnp.sum(lacc)) + losses.append(l) + log(f"warmup step {i}: loss {l:.7f} {gnorm} ({time.perf_counter() - t0:.1f}s)", lead[last] == pid) + else: + log(f"warmup step {i}: {gnorm} ({time.perf_counter() - t0:.1f}s)", is_lead) + p.on_grads = None # --grad-digest digests warmup steps only: none of the timed or profiled ones + if a.mem_report: + log(f"peak HBM after warmup {peak_hbm_line(peak_hbm())}", is_lead) + out = { + "config": vars(a), + "summary": p.summary(), + "provenance": pv, + "warmup_losses": losses, + "warmup_gnorms": gnorms, + "warmup_gnorms_bf16": [None if g is None else float(jnp.bfloat16(g)) for g in gnorms], + } + if p.split_chunks: # the split backward: its chunks, W buffers and simulated gain (Pipeline.zb_record) + out["zb"] = p.zb_record() + if getattr(p, "program_prints", None): # this process's programs, to compare across runs + out["programs"] = [(n, _stage_key(s), lw["sha"], x) for n, s, lw, x in p.program_prints] + if p.multi: + out.update(process=pid, stages=mine, processes=jax.process_count()) + + def relay_window(key, what): + """Where this process's relay time went (transfer.RELAY_MEASURES) since the last window -> out[key], then + forgotten: one window per kind of step -- warm-up, run-ahead (--bench's steady state), blocked, profiled. + Taken once every process is past the window's steps: each process's receives of them are in when its steps + return (a consumer resolves its receive before it is dispatched), so then so is every send of them, but for + its last write's bookkeeping, and none of the next window's has started. Multi-controller only (the relay + needs --distributed): the callers ask `p.multi`.""" + if p.relay_ctx is None: + return + from jax._src import distributed + + distributed.global_state.client.wait_at_barrier(f"mpmd_relay_{key}", 30 * 60 * 1000) + out[key] = p.relay_ctx.timing(reset=True) + log(f"relay timing, {what}: {transfer.relay_timing_line(out[key])}", bool(mine)) + + def write_record(provisional=False): + """--json: this process's record, `out` as it stands -> None, or the error that kept it from being written (main + raises it after its last barrier: the other processes need not wait it out). Under multi-controller JAX the + processes of --json-procs write theirs, each but process 0's beside --json (run.json -> run.p3.json). + `provisional`: the record before the profile, which a local target written in place (a named pipe, a device: + write_json) does not get.""" + if not a.json: + return None + if not p.multi: + return write_json(a.json, out, provisional) + if pid not in json_procs: + return None + root, ext = os.path.splitext(a.json) + return write_json(a.json if pid == 0 else f'{root}.p{pid}{ext or ".json"}', out, provisional) + + if p.multi: + relay_window("relay_warmup", "warmup steps") + ahead = "run-ahead" if a.max_ahead is None else f"at most {a.max_ahead} step(s) ahead" + if a.bench: + # steady state: keep the queues full, block once at the end + jax.block_until_ready(params) + t0 = time.perf_counter() + state = [params, opts, wc0] + del params, opts, wc0 # run_steps holds the only references + params, opts, wc0, lacc, gn = run_steps(p, state, a.steps, batch, lrs, a.max_ahead) + jax.block_until_ready((params, opts, lacc)) + dt = (time.perf_counter() - t0) / a.steps + tf = maxtext_tflops_per_device(p) + loss = f" loss {float(jnp.sum(lacc)):.5f}" if runs_last else "" + log( + f"step {dt * 1e3:.2f} ms (mean of {a.steps}, {ahead}){loss} " + f"TFLOP/s/device {tf / dt:.1f} (MaxText accounting, {tf:.2f} TFLOP/step/device) " + f"tokens/s/device {p.gbs * p.seq / dt / (p.S * a.fsdp * a.ep):.0f}", + is_lead, + ) + out.update(step_ms=dt * 1e3, tflops_per_device=tf / dt, tflop_per_step_per_device=tf) + if p.multi: + relay_window("relay", "the run-ahead steps") + # per-step latency with a block after each + lat = [] + for _ in range(max(3, a.steps)): + t1 = time.perf_counter() + params, opts, wc0, lacc, gn = p.step(params, opts, wc0, batch, lrs) + jax.block_until_ready((params, opts, lacc)) + lat.append(time.perf_counter() - t1) + # Blocking after every step is also a way to RUN: with stash sets holding + # HBM, run-ahead lets the next step's first programs contend for memory + # with this step's tail, and a blocked loop can be the faster one. + med = statistics.median(lat) + log( + f"blocked step latency {min(lat) * 1e3:.2f} ms (min of {len(lat)}); " + f"mean {sum(lat) / len(lat) * 1e3:.2f} ms, median {med * 1e3:.2f}, max {max(lat) * 1e3:.2f} " + f"(a loop that blocks every step)", + is_lead, + ) + out["blocked_step_mean_ms"] = sum(lat) / len(lat) * 1e3 + out["blocked_step_ms"] = min(lat) * 1e3 + out["blocked_step_median_ms"] = med * 1e3 + out["blocked_steps_ms"] = [x * 1e3 for x in lat] + if p.multi: + relay_window("relay_blocked", "the blocked steps") + per = peak_hbm() + log(f"peak HBM {peak_hbm_line(per)}", is_lead) + out["peak_hbm_gib"] = max(per.values()) if per else (None if proxy else 0.0) # None: not reported (Pathways) + out["peak_hbm_gib_per_device"] = per + if a.profile: + # The record so far (warm-up, --bench) goes out before the profile as well: a run cut short while profiling keeps + # it (a GKE job preempted during its profiled steps lost its numbers so). The write after the profile adds what + # the profile reports. + if (failed := write_record(provisional=True)) is not None: + why = pathways.storage_error(failed) + log(f"warning: --json {a.json}: not written before the profile ({why}); it is tried again after the profile") + jax.block_until_ready(params) + # Every process runs the profiled steps (they share every boundary copy); + # only --profile-procs trace them, --profile-chips chips each (popts: + # one TPU, one a slice under --layout slices), named in stage order + # (profiling.trace_label). Across processes the traced hosts + # write ONE XProf session, each rebased to an origin process 0 picks + # (xprof_align): every stage's TPUs on one timeline in the trace viewer. + traced = not p.multi or pid in traced_procs + if traced and not profile_hlo_proto(a.profile_hlo_proto, p): + popts.enable_hlo_proto = False + log(f"--profile-hlo-proto {a.profile_hlo_proto}: the trace leaves out the programs' HLO protos", True) + if p.multi: + session, origin = shared_profile_session() + local = xprof_align.local_trace_dir() if traced else None + target = local if p.multi else a.profile + if traced and proxy: + # Pathways: the client's trace and `profile_hosts` worker hosts' (their device planes), one session in gs://, + # with a settle after the start (pathways.trace) + tracer = pathways.trace(target, popts, max_num_hosts=profile_hosts) + else: + tracer = jax.profiler.trace(target, profiler_options=popts) if traced else contextlib.nullcontext() + trace_error = None + try: + with tracer: + state = [params, opts, wc0] + del params, opts, wc0 + params, opts, wc0, lacc, gn = run_steps(p, state, a.profile_steps, batch, lrs, a.max_ahead) + jax.block_until_ready((params, opts, lacc)) + # A Pathways trace that did not start (its steps then did not run) or did not stop: the profile is a by-product, + # its loss must not lose the run record (the steps' own errors are no TraceError, and go on up). + except pathways.TraceError as e: + trace_error = str(e) + if p.multi: + relay_window("relay_profile", "the profiled steps") + where = a.profile + if proxy and trace_error is None: + where = f'{a.profile.rstrip("/")}/plugins/profile/{popts.session_id}' + out["profile_session"] = where + chips = popts.advanced_configuration.get("tpu_num_chips_to_profile_per_task", "all") + where += f" ({profile_hosts} Pathways worker host(s), {chips} chip(s) each)" + elif proxy: + out["profile_error"] = trace_error + where = f"no profile: --profile {a.profile}: {trace_error}" + if p.multi and traced: + # The profile is a by-product: an export error (say, a bucket this host + # cannot write) must not lose the run record or keep the others waiting. + try: + where = xprof_align.export_into_session( + local, + a.profile, + session, + origin, + host=profiling.trace_label(mine[0] if mine else None, pid, p.S, jax.process_count(), socket.gethostname()), + ) + shutil.rmtree(local, ignore_errors=True) + except Exception as e: + where = f"{local} only: exporting into {a.profile} failed ({pathways.storage_error(e)})" + log(f"warning: {where}" if trace_error else f"profile written under {where}", traced) + err = write_record() + if p.multi: + # Nobody leaves (and takes the coordination service with it, process 0) + # before everyone is done. + from jax._src import distributed + + distributed.global_state.client.wait_at_barrier("mpmd_main_done", 30 * 60 * 1000) + # every process is past its last step, every relay receive consumed: its streams can end + p.close() + if err is not None: + raise err + return out + + +if __name__ == "__main__": + main() diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep_progbench.py b/src/maxtext/experimental/mpmd/jax/ds_ep_progbench.py new file mode 100644 index 0000000000..4cd2e4d923 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep_progbench.py @@ -0,0 +1,404 @@ +# 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. + +"""Time ONE pipeline program in isolation under different compiler options. + + python3 -m maxtext.experimental.mpmd.jax.ds_ep_progbench --prog fwd_pf --chunk 0 --group 1 \ + --opts '{}' --opts '{"xla_tpu_enable_latency_hiding_layer_scheduler": false}' + + # v6e-4 (PP2 x FSDP1 x EP2, 16 experts): a stash backward + python3 -m maxtext.experimental.mpmd.jax.ds_ep_progbench --preset v6e --prog bwda_s --stash-policy lite + +Builds the full-size Pipeline (no step compile) -- by default the 128-expert +TPU7x benchmark with the `clamped` megablox tiles (`--tiles`, ds_ep.TILES), +`--preset v6e` the v6e-4 one with the `v6e` tiles -- +materializes random inputs with the exact shardings the step uses, compiles +the program once per --opts, and prints the median and min of --reps runs +for each, and the program's compile-time temporaries. At the default config +chunk 0's forwards carry chunk 2's gather in 4 leaf groups (--group 0..3); a +chunk that carries none exits with the list of chunks that do. Unlike +ds_ep_pipeline's default the default preset uses MaxText's placement +(`ep_on_chip`). FSDP_COLL / EP_COLL (environment) pick the FSDP and EP +collectives (default ppermute / auto). Used to tune the scheduling of the +programs that fold FSDP collectives in, and to measure what the schedules +assume: the stash backward's cost (`Bs`), and a split backward's I and W +(`--prog bwdi` / `bwdwa`: the zero-bubble schedules' I / W costs). + +Stash programs (`--stash-policy`, ds_ep.STASH_POLICIES) take the stash their +own forward produces from the random inputs, so the backward sees real +routing (group sizes), not zeros. The inputs are random activations, and for +chunk 0 random token ids: under top-k routing identical tokens would make +every token's hidden state the same after the first layer and send them all +to the same experts. +""" + +import argparse +import json +import os +import time +import warnings + +from maxtext.experimental.mpmd.jax import transfer + +transfer.set_max_inflight(1024) +import jax # noqa: E402 +import jax.numpy as jnp # noqa: E402 + +from maxtext.experimental.mpmd.jax import ds_ep # noqa: E402 +from maxtext.experimental.mpmd.jax import ds_ep_pipeline as dsp # noqa: E402 + +# The full-size config, a TPU7x benchmark shape, and what each preset changes. +BASE = dict( + stages=2, + vv=2, + mb=8, + gbs=32, + seq=4096, + fsdp=2, + ep=2, + layers=4, + emb=7168, + heads=128, + q_lora=1536, + kv_lora=512, + moe_mlp=2048, + experts=128, + topk=8, + weight_dtype="bfloat16", + vocab=32768, + attn="tokamax_splash", + sa_block=2048, + sa_block_kv_compute=512, + cost_estimate=5_000_000_000_000, + tiles="clamped", + wi_tiling=None, + wo_tiling=None, + rs_dtype="bfloat16", + acc_dtype="float32", + remat_last=False, + schedule=None, + layout="ep_on_chip", + no_overlap=False, + fsdp_collectives=os.environ.get("FSDP_COLL", "ppermute"), + ep_collectives=os.environ.get("EP_COLL", "auto"), + pf_split=4, + rs_split=4, + costs="", + grad_reduce="step", + routing="random", + ragged_sort="auto", +) +PRESETS = { + "default": {}, + # v6e-4: 2 stages x (fsdp 1 x ep 2), 16 experts, gbs 16 in 8 microbatches, and the + # megablox tiles swept on v6e (ds_ep.TILES['v6e']), as the v6e baseline runs + "v6e": dict(stages=2, fsdp=1, ep=2, experts=16, gbs=16, mb=8, layout="fsdp_on_chip", tiles="v6e"), + # TPU7x-8: PP=4 x FSDP=2 x EP=1 over each chip's cores, the shape of a PP=4 comparison with MaxText + # (32 experts, 8 layers, fp32 weights, top-k routing, per-microbatch reduce-scatter) + "pp4": dict( + stages=4, + fsdp=2, + ep=1, + layers=8, + experts=32, + weight_dtype="float32", + layout="snake", + routing="topk", + ragged_sort="off", + grad_reduce="microbatch", + ), +} +# (flag, type): each overrides the preset +OVERRIDES = [ + ("stages", int), + ("vv", int), + ("mb", int), + ("gbs", int), + ("seq", int), + ("fsdp", int), + ("ep", int), + ("layers", int), + ("emb", int), + ("heads", int), + ("q_lora", int), + ("kv_lora", int), + ("moe_mlp", int), + ("experts", int), + ("topk", int), + ("vocab", int), + ("sa_block", int), + ("sa_block_kv_compute", int), + ("layout", str), + ("schedule", str), + ("tiles", str), +] + + +def materialize(avals, key, vocab=None): + """Random arrays with `avals`' shapes, dtypes and shardings: floats + ~N(0, 0.02^2); integer arrays (token ids) uniform over [0, vocab), and zero + without a `vocab`; integer scalars (seeds, counters) zero.""" + leaves, tdef = jax.tree.flatten(avals) + out = [] + for i, a in enumerate(leaves): + k = jax.random.fold_in(key, i) + if jnp.issubdtype(a.dtype, jnp.integer) and vocab and a.ndim: + f = lambda k, a=a: jax.random.randint(k, a.shape, 0, vocab, a.dtype) + elif jnp.issubdtype(a.dtype, jnp.integer): + f = lambda k, a=a: jnp.zeros(a.shape, a.dtype) + else: + f = lambda k, a=a: (0.02 * jax.random.normal(k, a.shape, jnp.float32)).astype(a.dtype) + out.append(jax.jit(f, out_shardings=a.sharding)(k)) + return jax.tree.unflatten(tdef, out) + + +def bench(label, fn, args_, donated, opts, reps): + """Compile `fn` for `args_` under compiler options `opts` (a JSON string), + run it `reps` times and print one line; returns the median in ms.""" + o = json.loads(opts) + t0 = time.perf_counter() + comp = fn.lower(*args_).compile(compiler_options=o or None) + tc = time.perf_counter() - t0 + mem = comp.memory_analysis() + tmp = f"temp {mem.temp_size_in_bytes / 2**30:6.2f} GiB" if mem is not None else "" + ts = [] + for _ in range(reps): + x = [jax.tree.map(lambda v: v.copy(), args_)] if donated else [args_] + jax.block_until_ready(x) + t1 = time.perf_counter() + out = comp(*x[0]) + jax.block_until_ready(out) + ts.append(time.perf_counter() - t1) + del out + ts.sort() + med = ts[len(ts) // 2] * 1e3 + print(f"{label} {opts:80s} median {med:7.2f} ms min {ts[0] * 1e3:7.2f} {tmp} (compile {tc:.0f}s)", flush=True) + return med + + +def forward_host(p, j): + """Is order[j] a forward that can host a prefetch group -- not the fused + last chunk's (A), which under --fsdp-scope repeat hosts re-gathers too?""" + c, k, _ = p.order[j] + return k == "F" and c != p.C - 1 + + +def host_op(p, c, group, prog): + """Chunk c's `group`-th host op for --prog fwd_pf (a forward's prefetch + group) or bwd_rs (a backward's reduce-scatter group, with whatever else + it carries: under --fsdp-scope repeat a gather, B + R + G) -> (op, its + program, the program's abstract arguments); SystemExit naming the chunks + that host one.""" + if prog == "fwd_pf": + js = sorted(j for j in p.pf if forward_host(p, j) and p.order[j][0] == c) + what, hosts = "prefetch groups in its forwards", sorted({p.order[j][0] for j in p.pf if forward_host(p, j)}) + else: + js = sorted(j for j in p.rs_at if p.order[j][0] == c) + what, hosts = "reduce-scatter groups", sorted({p.order[j][0] for j in p.rs_at}) + if group >= len(js): + raise SystemExit(f"chunk {c} hosts {len(js)} {what}; hosts are {hosts}") + op = p.ops()[js[group]] + return op, p.program(op), p._desc_avals(op.c, op.desc) + + +def main(): + warnings.filterwarnings("ignore") + ap = argparse.ArgumentParser() + ap.add_argument( + "--prog", + default="fwd_pf", + choices=[ + "fwd", + "fwd_pf", + "bwda", + "bwd_rs", + "update_ag", + "fwd_s", + "bwd_s", + "bwda_s", + "fwd_pf_s", + "bwd_rs_s", + "bwdi", + "bwdwa", + ], + help="the program to time; bwdi / bwdwa are a middle chunk's split backward (the zero-bubble schedules' I and " + "accumulating W: ds_ep.ChunkPrograms.build_split), W on the crossing set I makes of the random inputs", + ) + ap.add_argument("--chunk", type=int, default=None, help="default: the first chunk hosting --prog") + ap.add_argument("--group", type=int, default=0, help="which prefetch/reduce leaf group") + ap.add_argument("--opts", action="append", default=[], help="JSON compiler options; repeatable") + ap.add_argument("--reps", type=int, default=10) + ap.add_argument("--preset", default="default", choices=sorted(PRESETS)) + ap.add_argument( + "--stash-policy", + default="lite", + choices=[k for k in ds_ep.STASH_POLICIES if k != "none"], + help="for the *_s programs", + ) + ap.add_argument("--wi-tiling", type=int, nargs=9, default=None, help="wi_0 / wi_1 tiling (overrides --tiles)") + ap.add_argument("--wo-tiling", type=int, nargs=9, default=None, help="wo tiling (overrides --tiles)") + for name, typ in OVERRIDES: + ap.add_argument("--" + name.replace("_", "-"), type=typ, default=None, help="overrides --preset") + a = ap.parse_args() + cfg = dict(BASE, **PRESETS[a.preset]) + cfg.update({k: getattr(a, k) for k, _ in OVERRIDES if getattr(a, k) is not None}) + if cfg["tiles"] not in ds_ep.TILES: + raise SystemExit(f"--tiles {cfg['tiles']!r}: want one of {sorted(ds_ep.TILES)}") + for k in ("wi_tiling", "wo_tiling"): + if getattr(a, k): + cfg[k] = getattr(a, k) + args = argparse.Namespace(**cfg) + p = dsp.build(args) + sc = p.progs[0].scfg + print( + f"preset {a.preset}: " + + " ".join(f"{k}={cfg[k]}" for k, _ in OVERRIDES) + + f" wi_tiling={sc.wi_tiling} wo_tiling={sc.wo_tiling}", + flush=True, + ) + A = p._avals + + def mat(avals, key_): + """`materialize` with this model's vocabulary for the token ids.""" + return materialize(avals, key_, vocab=p.scfg.model.vocab_size) + + pd = ds_ep.pdesc + hosts = { + "fwd_pf": sorted({p.order[j][0] for j in p.pf if forward_host(p, j)}), + "bwd_rs": sorted({p.order[j][0] for j in p.rs_at}), + } + hosts["fwd_pf_s"], hosts["bwd_rs_s"] = hosts["fwd_pf"], hosts["bwd_rs"] + if a.prog in hosts and not hosts[a.prog]: + what = "forward carries a gather" if a.prog.startswith("fwd") else "backward carries another chunk's reduce-scatter" + why = "" + if a.prog.startswith("bwd") and p.scfg.grad_reduce == "microbatch": + why = ": this preset reduce-scatters every microbatch's gradient in its own backward " "(time --prog bwda)" + raise SystemExit(f"--prog {a.prog}: no {what} in this configuration{why}") + c = a.chunk + if c is None: + c = hosts[a.prog][0] if a.prog in hosts else 2 + ch = p.chunks[c] + s = ch.stage + pr = p.progs[c] + key = jax.random.key(0) + pol = a.stash_policy + stash_progs = ("fwd_s", "bwd_s", "bwda_s", "fwd_pf_s", "bwd_rs_s") + opts = a.opts or ["{}"] + + def x_of(ch_): + return A(ch_.stage, "tok" if ch_.first else "act") + + def stash_of(pr_): + st = pr_.build_stash(pol) + print( + f"stash {pol} c{pr_.ch.index}: {len(st.avals)} arrays, {st.bytes / 2**30:.3f} GiB/device/microbatch " + f'({", ".join(f"{b / 2**30:.3f}" for b in st.layer_bytes)} per layer)', + flush=True, + ) + return st + + def forward(pr_, stash): + """(w, x, seed) of chunk pr_, random, and what its forward makes of them: + res (the layer inputs), and the stash in stash mode.""" + ch_ = pr_.ch + w, x, seed = mat((A(ch_.stage, "compute", ch_), x_of(ch_), A(ch_.stage, "scalar_i")), key) + if stash: + _, res, stash_ = stash_of(pr_).fwd(w, x, seed) + return w, x, seed, res, stash_ + _, res = pr_.fwd(w, x, seed) + return w, x, seed, res, None + + if a.prog in stash_progs and ch.last: + raise SystemExit(f"chunk {c} is the last: its forward and backward are one fused program (A)") + if a.prog in ("bwdi", "bwdwa"): + if ch.first or ch.last: + raise SystemExit(f"--prog {a.prog}: chunk {c} has no split backward (a middle chunk's: 1 to {p.C - 2})") + w, x, seed, res, _ = forward(pr, False) + dy, gacc = mat((A(s, "act"), A(s, "gacc", ch)), key) + i_args = [w, x, res, dy, seed] + i_prog = pr.program((pd("I", acc=pr.build_split(True).i_acc),)) # the I the accumulating W reads + if a.prog == "bwdi": + fn, args_ = i_prog, i_args + else: # W's inputs: the crossing set the I makes of these, and the arguments of I it reads (no copy) + _, cross = i_prog(*jax.tree.map(lambda v: v.copy(), i_args)) # (I donates dy where W does not read it) + fn, args_ = pr.program((pd("W", acc=True),)), [cross, pr.build_split(True).kept_of(i_args), gacc] + for o in opts: + bench(f"{a.prog} c{c}", fn, args_, True, o, a.reps) + return + if a.prog == "fwd": + fn, av = pr.fwd, (A(s, "compute", ch), A(s, "tok" if ch.first else "act"), A(s, "scalar_i")) + elif a.prog in ("fwd_pf", "bwd_rs"): + op, fn, av = host_op(p, c, a.group, a.prog) + elif a.prog == "bwda": + fn = pr.bwda + av = ( + A(s, "compute", ch), + A(s, "tok" if ch.first else "act"), + tuple(A(s, "act") for _ in range(pr.n_res)), + A(s, "act"), + A(s, "gacc", ch), + A(s, "scalar_i"), + ) + elif a.prog == "update_ag": + st = p.stages[s] + chs = p.stage_chunks[s] + params = [A(s, "storage", cc) for cc in chs] + opt = { + "mu": jax.tree.map(lambda x: jax.ShapeDtypeStruct(x.shape, jnp.bfloat16, sharding=x.sharding), params), + "nu": params, + "count": A(s, "scalar_i"), + } + fn = st.update_gather + av = (params, opt, [A(s, "grads", cc) for cc in chs], [A(s, "scalar_f")] * p.S, A(s, "scalar_f")) + if a.prog in ("fwd", "fwd_pf", "bwda", "bwd_rs", "update_ag"): + args_ = mat(av, key) + donated = a.prog in ("bwda", "bwd_rs", "update_ag") + label = f"{a.prog} c{c} g{a.group}" + if a.prog in ("fwd_pf", "bwd_rs"): + label += f' ({p.op_name(op.j)}: {"+".join(k for k, _ in op.desc)})' + for o in opts: + bench(label, fn, args_, donated, o, a.reps) + return + # stash programs: inputs from the chunk's own stash forward + w, x, seed, res, stash = forward(pr, True) + dy, gacc = mat((A(s, "act"), A(s, "gacc", ch)), key) + if a.prog == "fwd_s": + fn, args_ = pr.build_stash(pol).fwd, [w, x, seed] + elif a.prog in ("bwd_s", "bwda_s"): + fn = pr.program((pd("B", stash=pol, acc=a.prog == "bwda_s"),)) + args_ = [w, x, res, stash, dy] + ([gacc] if a.prog == "bwda_s" else []) + [seed] + elif a.prog == "fwd_pf_s": + hop, _, _ = host_op(p, c, a.group, "fwd_pf") + b, g = hop.pf + fn = pr.program((pd("F", stash=pol), pd("G", other=p.chunks[b], leaves=g if p.pf_n[hop.j] > 1 else None))) + st = jax.tree.leaves(mat(A(s, "storage", p.chunks[b]), key)) + args_ = [w, x, seed, [st[i] for i in g]] + else: # bwd_rs_s + js = sorted(j for j in p.rs_at if p.order[j][0] == c) + if a.group >= len(js): + raise SystemExit( + f"chunk {c} hosts {len(js)} reduce-scatter groups; hosts are " f"{sorted({p.order[j][0] for j in p.rs_at})}" + ) + j = js[a.group] + o_, g = p.rs_at[j] + acc = j != min(jj for jj, (cc, k, m) in enumerate(p.order) if cc == c and k == "B") + fn = pr.program((pd("B", stash=pol, acc=acc), pd("R", other=p.chunks[o_], leaves=g if p.rs_groups[o_] > 1 else None))) + gl = jax.tree.leaves(mat(A(s, "gacc", p.chunks[o_]), key)) + args_ = [w, x, res, stash, dy] + ([gacc] if acc else []) + [seed, [gl[i] for i in g]] + for o in opts: + bench(f"{a.prog} {pol} c{c} g{a.group}", fn, args_, a.prog not in ("fwd_s", "fwd_pf_s"), o, a.reps) + + +if __name__ == "__main__": + main() diff --git a/src/maxtext/experimental/mpmd/jax/ds_ep_run.sh b/src/maxtext/experimental/mpmd/jax/ds_ep_run.sh new file mode 100755 index 0000000000..3fba4c4b9c --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/ds_ep_run.sh @@ -0,0 +1,91 @@ +#!/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. + +# MPMD DeepSeek sparse-layer pipeline (PP x FSDP x EP) under a libtpu flag set (libtpu_flags/: by default tpu7x, +# the flags both sides of the TPU7x measurements ran), plus the one flag below. +# +# bash src/maxtext/experimental/mpmd/jax/ds_ep_run.sh --bench --profile /tmp/xprof/mpmd [pipeline flags...] +# MPMD_FLAG_SET=v5p bash src/maxtext/experimental/mpmd/jax/ds_ep_run.sh --bench # MaxText's v5p DeepSeek-V3 recipe flags +# +# Environment (PYTHON, MPMD_FLAG_SET, LIBTPU_INIT_ARGS_OVERRIDE and EXTRA_LIBTPU_INIT_ARGS alike in ds_ep_aot.sh and +# ds_ep_multihost.sh; MAXTEXT_DIR in ds_ep_aot.sh too): +# PYTHON the interpreter (default python3). +# MAXTEXT_DIR if set, that checkout's src/ goes first on PYTHONPATH, so the MPMD programs call that checkout's +# MaxText kernels (ragged sort, megablox), and the run stops if `maxtext` resolves anywhere else. +# MPMD_FLAG_SET the libtpu flag set: the name of a file in libtpu_flags/ without .flags -- tpu7x (the default), +# v5p (MaxText's v5p DeepSeek-V3 recipe set), v5p_fsdp_extra (additions to v5p, given through +# EXTRA_LIBTPU_INIT_ARGS: see its header) -- or none. A name without a file is an error, and +# nothing runs. +# LIBTPU_INIT_ARGS_OVERRIDE replaces the set's flags, even when set to "". +# EXTRA_LIBTPU_INIT_ARGS appended after every other flag (the last mention of a flag wins). +# JAX_CACHE_DIR the persistent compile cache (default ~/jax_cache). +# LIBTPU_INIT_ARGS becomes the set's flags (or LIBTPU_INIT_ARGS_OVERRIDE's), then the MPMD flag below, then +# EXTRA_LIBTPU_INIT_ARGS; a value LIBTPU_INIT_ARGS had before is not used. +set -euo pipefail +# This script's directory and the directory the package imports from, with every symlink resolved (a link to the +# script or to its directory still finds this checkout), and without `cd`, which an exported CDPATH makes print. +SELF="$(readlink -f "${BASH_SOURCE[0]}")" +HERE="${SELF%/*}" +# The package, and ROOT, the directory it imports from: HERE one level up for each component of the package's name. +PKG=maxtext.experimental.mpmd.jax +ROOT=$HERE +for _ in ${PKG//./ }; do ROOT=${ROOT%/*}; done +ROOT=${ROOT:-/} +PYTHON=${PYTHON:-python3} +if [[ -n "${MAXTEXT_DIR:-}" ]]; then + MAXTEXT_DIR="$(CDPATH='' cd "$MAXTEXT_DIR" && pwd)" + export PYTHONPATH="$MAXTEXT_DIR/src${PYTHONPATH:+:$PYTHONPATH}" +fi +# LIBTPU_INIT_ARGS, as every launcher builds it (ds_ep_aot.sh and ds_ep_multihost.sh hold the same lines). +FLAG_SET=${MPMD_FLAG_SET:-tpu7x} +SET_FLAGS="" +if [[ $FLAG_SET != none ]]; then + SET_FILE="$HERE/libtpu_flags/$FLAG_SET.flags" + if [[ $FLAG_SET == */* || ! -f $SET_FILE ]]; then + SETS="none" + for f in "$HERE"/libtpu_flags/*.flags; do + if [[ -f $f ]]; then f=${f##*/}; SETS+=", ${f%.flags}"; fi + done + echo "ds_ep_run.sh: MPMD_FLAG_SET=$FLAG_SET: no such libtpu flag set ($SETS; the files of $HERE/libtpu_flags)" >&2 + exit 1 + fi + SET_TEXT="$(sed -e 's/#.*//' "$SET_FILE")" || exit 1 # '#' starts a comment + read -r -d '' -a SET <<< "$SET_TEXT" || true # one flag a word, unglobbed + SET_FLAGS="${SET[*]-}" # joined by single spaces +fi +# Plus one flag the MPMD programs need: the FSDP gather / reduce-scatter are +# collective-permutes folded into forward / backward programs, and libtpu's +# default cap on concurrent async permutes serializes them (measured: 19.4 ms +# of 22.4 ms exposed -> 8.0 ms with the cap raised). MaxText's step time was +# unchanged by it (2.986 s/step with, 2.987 without), measured in the first +# configuration (32 experts, 8 layers) only, not re-measured at 128 experts. +MPMD_LIBTPU_INIT_ARGS="--xla_max_concurrent_async_collective_permutes=64" +export LIBTPU_INIT_ARGS="${LIBTPU_INIT_ARGS_OVERRIDE-$SET_FLAGS} $MPMD_LIBTPU_INIT_ARGS ${EXTRA_LIBTPU_INIT_ARGS:-}" +cd "$ROOT" +if [[ -n "${MAXTEXT_DIR:-}" ]]; then + # Found, not imported (cheap), from the directory the pipeline runs in. + "$PYTHON" - "$MAXTEXT_DIR/src" <<'EOF' +import importlib.util +import os +import sys + +spec = importlib.util.find_spec('maxtext') +path = spec and (spec.origin or next(iter(spec.submodule_search_locations or ()), None)) +if not path or not os.path.realpath(path).startswith(os.path.realpath(sys.argv[1]) + os.sep): + sys.exit(f'ds_ep_run.sh: `maxtext` resolves to {path}, not under {sys.argv[1]}') +EOF +fi +exec "$PYTHON" -m "$PKG.ds_ep_pipeline" "$@" diff --git a/src/maxtext/experimental/mpmd/jax/gpu.xla_flags b/src/maxtext/experimental/mpmd/jax/gpu.xla_flags new file mode 100644 index 0000000000..a1e4bf1c3f --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/gpu.xla_flags @@ -0,0 +1,23 @@ +# XLA_FLAGS of ds_ep_multihost.sh on GPU (PLATFORM=gpu; one flag a line; '#' lines are comments). +# The latency-hiding scheduler overlaps the async NCCL collectives (EP all-gathers / reduce-scatters, the folded +# FSDP collectives) with compute; collectives combine up to these sizes; GEMMs stay on cuBLAS (Triton GEMM +# fusions off). Command buffers (CUDA graphs) for fusions, cuBLAS, custom calls (tokamax's, cuDNN's) and control +# flow, not collectives: the Qwen3.5-family Gated DeltaNet's chunk scan launches ~10^6 small kernels a step +# (8.3% shorter steps on a GB200 at Qwen3.8's per-layer dims), and they stay on under the profiler, so a profiled +# step runs as an unprofiled one does. No custom (Triton one-shot) collective kernels: XLA picks them for a small +# all-reduce whose devices share an NVLink domain, and their compile fails at 64 ranks over the 16 hosts of a GB200 +# NVL72 rack ("size mismatch when packing elements for LLVM struct", jax 0.12.0.1) -- a one-stage (data-parallel) +# layout's loss psum, the global norm's sum -- so every collective stays NCCL's. +--xla_gpu_experimental_use_collective_kernels= +--xla_gpu_enable_latency_hiding_scheduler=true +--xla_gpu_enable_triton_gemm=false +--xla_gpu_enable_command_buffer=FUSION,CUBLAS,CUBLASLT,CUSTOM_CALL,WHILE,CONDITIONAL +--xla_enable_command_buffers_during_profiling=true +--xla_gpu_all_reduce_combine_threshold_bytes=134217728 +--xla_gpu_all_gather_combine_threshold_bytes=134217728 +--xla_gpu_reduce_scatter_combine_threshold_bytes=67108864 +--xla_gpu_enable_pipelined_all_gather=true +--xla_gpu_enable_pipelined_reduce_scatter=true +--xla_gpu_enable_pipelined_all_reduce=true +--xla_gpu_enable_while_loop_double_buffering=true +--xla_disable_hlo_passes=rematerialization diff --git a/src/maxtext/experimental/mpmd/jax/gpu_kernels.py b/src/maxtext/experimental/mpmd/jax/gpu_kernels.py new file mode 100644 index 0000000000..17ab1c7dd5 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/gpu_kernels.py @@ -0,0 +1,785 @@ +# 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. + +"""GPU kernels the MPMD pipeline's tokamax path needs beyond tokamax (gmm_impl 'tokamax': tokamax_gmm 'mosaic' runs +grouped_matmul and ragged_dw's kernels, 'tokamax_mosaic' and 'triton' ragged_dw's Triton one only; combine_impl +'triton' runs gather_sum). + +`grouped_matmul(lhs, rhs, group_sizes)` -- the routed experts' forward and dlhs grouped matmuls on Blackwell +(sm_100), reading the weight as it lies. tokamax's Mosaic GPU kernel takes its weight N-major and transposes the whole +`[E / EP, D, F]` weight into a copy on every forward call (half of a 1.59 ms DeepSeek-V3 forward product at EP 4 on a +GB200); this is that kernel with the weight's tiles loaded as stored and handed to the tensor core as an MN-major +operand, and tiles tuned at the pipeline's shapes (0.82 ms; dlhs, whose transposes cancel, 1.0 -> 0.85 ms). + +`ragged_dw(lhs, g, group_sizes, acc)` is, per group e of the rows (sorted by group, `group_sizes` the groups' sizes, +rows past them ignored), `acc[e] + lhs[rows of e]^T @ g[rows of e]` -- megablox tgmm's existing_out, which TPU's +pipeline uses to accumulate a weight gradient inside its dW kernel (ds_ep named_gmm's acc). tokamax's grouped matmuls +take no starting value, so without it a chunk's backward writes each layer's routed-expert dW into a buffer of its own +(3 x [E / EP, D, F]: 12 GiB a Qwen3.8 layer at EP 4) and adds it to the step's accumulator in a pass of its own (a +read of both and a write). Here the kernel loads the accumulator's tile, adds its fp32 partial sum and stores the tile +back into the same buffer (a jax.Ref: jax_triton aliases it to the call's output, so a donated accumulator is updated +where it lies), one rounding to its dtype. On sm_100 it is a tcgen05 (Mosaic GPU) kernel (`_dw_mosaic`, into an +fp32 accumulator too, DW_MOSAIC_F32; ds_ep runs it under tokamax_gmm 'mosaic' only): 0.94 ms at DeepSeek-V3's shapes, +against 2.0 for tokamax's dW and a bf16 add (2.7 with the add in fp32); elsewhere, and for shapes the tcgen05 kernel +does not take, tokamax's Triton ragged-contracting kernel (tokamax/_src/ops/ragged_dot/triton.py, +`_ragged_contracting_dim_dot_kernel`) with the accumulator's tile loaded first (1.74 ms). Off GPU (CPU tests), and +under tokamax_gmm 'xla', it is lax.ragged_dot_general plus the add, in fp32. + +`gather_sum(y, pos, w)` -- the EP combine's weighted sum over a token's K choices, and the dispatch's gradient +(ds_ep combine_impl 'triton'): a Triton kernel that loads only the rows that exist, where XLA's fill-gather walks +all T x K of them (its section below). +""" + +from __future__ import annotations + +import functools +import os + +import jax +import jax.numpy as jnp +from jax import lax + +_CONTRACTING = lax.RaggedDotDimensionNumbers( + dot_dimension_numbers=(((0,), (0,)), ((), ())), lhs_ragged_dimensions=[0], rhs_group_dimensions=[] +) +# Tuned on a GB200 at DeepSeek-V3's and Qwen3.8's EP 4 shapes (tokamax's heuristic tiles, 128 / 128 / 32, 4 warps, +# 4 stages, ran 6-12% slower here; 64-wide k at 4 stages 40% slower) +TILES = dict(block_m=128, block_n=128, block_k=64, num_warps=4, num_stages=3) + + +@functools.cache +def _kernel(): + import triton + import triton.language as tl + + @triton.jit + def dw_acc_kernel( + a_ptr, + b_ptr, + cum_ptr, + acc_ptr, + m: tl.constexpr, + n: tl.constexpr, + stride_ak: tl.constexpr, + stride_am: tl.constexpr, + stride_bk: tl.constexpr, + stride_bn: tl.constexpr, + stride_oe: tl.constexpr, + stride_om: tl.constexpr, + stride_on: tl.constexpr, + block_m: tl.constexpr, + block_n: tl.constexpr, + block_k: tl.constexpr, + ): + pid_m = tl.program_id(0) + pid_n = tl.program_id(1) + pid_e = tl.program_id(2).to(tl.int64) + lo = tl.load(cum_ptr + pid_e) + hi = tl.load(cum_ptr + pid_e + 1) + offs_m = (pid_m * block_m).to(tl.int64) + tl.arange(0, block_m) + offs_n = (pid_n * block_n).to(tl.int64) + tl.arange(0, block_n) + offs_k = lo.to(tl.int64) + tl.arange(0, block_k) + # no m / n masks where the tiles divide the weight (tokamax's: a masked load vectorizes worse) + m_mask = True if m % block_m == 0 else (offs_m[None, :] < m) + n_mask = True if n % block_n == 0 else (offs_n[None, :] < n) + o_ptrs = acc_ptr + pid_e * stride_oe + offs_m[:, None] * stride_om + offs_n[None, :] * stride_on + o_mask = (True if m % block_m == 0 else (offs_m[:, None] < m)) & n_mask + # the accumulator's tile is loaded before the contraction, not after it: its latency then hides behind the + # loop instead of stalling the store (1.74 against 1.98 ms at DeepSeek-V3's shapes on a GB200) + prev = tl.load(o_ptrs, mask=o_mask, other=0.0) + a_ptrs = a_ptr + offs_k[:, None] * stride_ak + offs_m[None, :] * stride_am + b_ptrs = b_ptr + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn + acc = tl.zeros((block_m, block_n), dtype=tl.float32) + for start_k in range(lo, hi, block_k): + k_mask = (start_k + tl.arange(0, block_k))[:, None] < hi + a = tl.load(a_ptrs, mask=k_mask & m_mask, other=0.0) + b = tl.load(b_ptrs, mask=k_mask & n_mask, other=0.0) + acc = tl.dot(tl.trans(a), b, acc=acc) + a_ptrs += block_k * stride_ak + b_ptrs += block_k * stride_bk + tl.store(o_ptrs, (acc + prev.to(tl.float32)).to(acc_ptr.dtype.element_ty), mask=o_mask) + + return dw_acc_kernel + + +def _strides(shape): + out, s = [], 1 + for d in reversed(shape): + out.append(s) + s *= d + return tuple(reversed(out)) + + +# ------------------------------------------------- gather_sum: the EP combine's and the dispatch backward's reduction +# +# out[t] = sum_k w[t, k] y[pos[t, k]] over a token's K choices, pos[t, k] = len(y) for a choice whose row is not in +# y (another EP shard's expert, or one past the buffer). XLA emits it as a gather of T x K rows (zeros for the +# missing ones) reduced over K: it walks all T x K x D elements, though at EP 8 seven choices in eight have no row. +# This kernel loads only the rows that exist and accumulates in fp32 in registers. B200, DeepSeek-V3's EP 8 shapes +# (a batch-split half: 32768 tokens x 8 choices x 7168): the combine 0.34 against XLA's 0.51 ms, the dispatch's +# gradient 0.25 against 0.41; A100, dsv3-mini's (65536 x 6 x 4096): 0.68 against 0.97, 0.64 against 0.84. +GATHER_SUM_TILES = dict(block_t=8, block_d=512, num_warps=8) + + +@functools.cache +def _gather_sum_kernel(): + import triton + import triton.language as tl + + @triton.jit + def gather_sum_kernel( + y_ptr, + pos_ptr, + w_ptr, + out_ptr, + t: tl.constexpr, + r: tl.constexpr, + k: tl.constexpr, + d: tl.constexpr, + block_t: tl.constexpr, + block_d: tl.constexpr, + weighted: tl.constexpr, + ): + offs_t = (tl.program_id(0) * block_t + tl.arange(0, block_t)).to(tl.int64) + offs_d = (tl.program_id(1) * block_d + tl.arange(0, block_d)).to(tl.int64) + t_mask = offs_t < t + d_mask = True if d % block_d == 0 else (offs_d[None, :] < d) + acc = tl.zeros((block_t, block_d), dtype=tl.float32) + for j in tl.static_range(k): + p = tl.load(pos_ptr + offs_t * k + j, mask=t_mask, other=r) + has = p < r + rows = tl.where(has, p, 0).to(tl.int64) + v = tl.load(y_ptr + rows[:, None] * d + offs_d[None, :], mask=has[:, None] & d_mask, other=0.0) + v = v.to(tl.float32) + if weighted: + v = v * tl.load(w_ptr + offs_t * k + j, mask=t_mask, other=0.0).to(tl.float32)[:, None] + acc += v + tl.store( + out_ptr + offs_t[:, None] * d + offs_d[None, :], acc.to(out_ptr.dtype.element_ty), mask=t_mask[:, None] & d_mask + ) + + return gather_sum_kernel + + +def gather_sum(y, pos, w=None, *, out_dtype=None, tiles=None): + """sum_k w[t, k] y[pos[t, k]] for every t -> [T, D] in `out_dtype` (y's by default), accumulated in fp32. + + y [R, D]; pos [T, K] int32, R for a missing row (it adds nothing); w [T, K] (None: every weight 1). On GPU a + Triton kernel that reads only the rows that exist (see above; `tiles` overrides GATHER_SUM_TILES); elsewhere the + same sum in XLA (a fill-gather of T x K rows).""" + T, K = pos.shape + R, D = y.shape + out_dtype = jnp.dtype(out_dtype or y.dtype) + if jax.default_backend() != "gpu": + yk = jnp.take(y, pos.reshape(-1), axis=0, mode="fill", fill_value=0).reshape(T, K, D).astype(jnp.float32) + if w is None: + return yk.sum(axis=1).astype(out_dtype) + return jnp.einsum("tkd,tk->td", yk, w.astype(jnp.float32)).astype(out_dtype) + import jax_triton as jt + + t = dict(GATHER_SUM_TILES, **(tiles or {})) + bd = min(t["block_d"], 1 << (D - 1).bit_length()) + w_arg = pos if w is None else w # an unread placeholder when unweighted + return jt.triton_call( + y, + pos.astype(jnp.int32), + w_arg, + kernel=_gather_sum_kernel(), + out_type=jax.ShapeDtypeStruct((T, D), out_dtype), + name="gather_sum", + grid=((T + t["block_t"] - 1) // t["block_t"], (D + bd - 1) // bd), + num_warps=t["num_warps"], + num_stages=1, + t=T, + r=R, + k=K, + d=D, + block_t=t["block_t"], + block_d=bd, + weighted=w is not None, + ) + + +# ------------------------------------------------- the forward on the weight as stored ([G, K, N]) +# +# tokamax's Blackwell grouped matmul (tokamax/_src/ops/ragged_dot/pallas_mosaic_gpu_kernel_sm100.py, +# `ragged_dot_gpu_non_quant_blackwell_kernel`, Apache 2.0) takes its weight N-major ([G, N, K]) and makes it so with +# `rhs.mT` -- a transposed copy of the whole weight on every call: on a GB200 1.3 ms of a Qwen3.8 layer's 2.7 ms +# forward product at EP 4 (128 x 8192 x 2048 bf16), 0.66 of DeepSeek-V3's 1.59. The dlhs product's weight is the +# transposed view already (the two transposes cancel). This is that kernel with the weight's tiles loaded as they +# lie ([block_k, block_n] of the stored [G, K, N]) and handed to the tensor core transposed (an MN-major SMEM +# operand), which tcgen05 reads as fast; in the collective (two-CTA) form each CTA loads its half of the tile's +# columns. Everything else -- the group schedule, the TMEM double buffer, the ragged store -- is tokamax's. +_COMPUTE_WG, _MMA_WARP, _TMA_WARP, _EPILOGUE_WG = 0, 1, 0, 1 + + +def mosaic_config(**kw): + """A tokamax Mosaic GPU ragged-dot Config from plain values (grid_minor_dim 'M' / 'N').""" + from tokamax._src.ops.ragged_dot import pallas_mosaic_gpu_common as common + + kw = dict(kw) + kw["grid_minor_dim"] = getattr(common.MatmulDimension, kw.get("grid_minor_dim", "M")) + return common.Config(split_k=1, persistent=False, **kw) + + +def _mosaic_kernel(lhs, rhs, group_sizes, out_dtype, config, rhs_kn): + from jax.experimental import pallas as pl + from jax.experimental.pallas import mosaic_gpu as plgpu + from tokamax._src import mosaic_gpu as mgpu_lib + from tokamax._src.ops.ragged_dot import pallas_mosaic_gpu_common as common + + tcgen05, tcgen05_t = plgpu.Layout.TCGEN05, plgpu.Layout.TCGEN05_TRANSPOSED + + block_m, block_n, block_k = config.block_m, config.block_n, config.block_k + collective = config.collective + cluster_block_m = block_m * 2 if collective else block_m + cluster_block_n = block_n * 2 if collective else block_n + m, k = lhs.shape + g, n = rhs.shape[0], rhs.shape[2] if rhs_kn else rhs.shape[1] + m_iters = pl.cdiv(m, cluster_block_m) + g - 1 + n_iters = pl.cdiv(n, cluster_block_n) + k_iters = pl.cdiv(k, block_k) + num_stages = min(config.num_stages, k_iters) + align_tile = 8 + + def kernel( + x_gmem, + w_gmem, + group_id_gmem, + start_within_block_gmem, + actual_size_gmem, + block_start_gmem, + out_gmem, + x_smem, + w_smem, + acc_smem, + acc_tmem, + xw_barrier, + xw_consumed_barrier, + acc_barrier, + acc_consumed_barrier, + ): + cluster_idx = lax.axis_index("cluster") + + @plgpu.dynamic_scheduling_loop( + ("mn",), thread_axis="wg", cluster_axes=("cluster",) if collective else (), init_carry=0 + ) + def mn_loop(loop_info, carry): + (idx,) = loop_info.index + tid_m, ni = plgpu.planar_snake(idx, (m_iters, n_iters), config.grid_minor_dim, config.grid_tile_width) + wg = lax.axis_index("wg") + group_id = group_id_gmem[tid_m] + start_within_block = start_within_block_gmem[tid_m] + actual_size = actual_size_gmem[tid_m] + block_start = pl.multiple_of(block_start_gmem[tid_m], align_tile) + ms = pl.ds(block_start, cluster_block_m) + ns = pl.ds(ni * cluster_block_n, cluster_block_n) + + @pl.when(actual_size > 0) + def compute(): + @mgpu_lib.warp_map_when(wg == _COMPUTE_WG) + def compute_wg_warp(warp_id): + cluster_axis = "cluster" if collective else None + + @pl.when(warp_id == _TMA_WARP) + def tma_warp(): + @pl.loop(0, k_iters) + def tma_loop(ki): + ks = pl.ds(ki * block_k, block_k) + step = carry * k_iters + ki + si = lax.rem(step, num_stages) + + @pl.when(step >= num_stages) + def _(): + plgpu.barrier_wait(xw_consumed_barrier.at[si]) + + plgpu.copy_gmem_to_smem( + x_gmem.at[ms, ks], + x_smem.at[si], + xw_barrier.at[si], + leader_tracked=plgpu.CopyPartition.PARTITIONED(0) if collective else None, + collective_axes=cluster_axis, + ) + # [block_k, cluster_block_n] of a [G, K, N] weight (a CTA takes its columns), or tokamax's + # [cluster_block_n, block_k] of a [G, N, K] one (its rows) + plgpu.copy_gmem_to_smem( + w_gmem.at[group_id, ks, ns] if rhs_kn else w_gmem.at[group_id, ns, ks], + w_smem.at[si], + xw_barrier.at[si], + leader_tracked=plgpu.CopyPartition.PARTITIONED(int(rhs_kn)) if collective else None, + collective_axes=cluster_axis, + ) + + @pl.when((warp_id == _MMA_WARP) & (cluster_idx == 0)) + def mma_warp(): + si_acc = lax.rem(carry, jnp.int32(2)) + ms_acc = pl.ds(si_acc * cluster_block_m, cluster_block_m) + + @pl.when(carry > 1) + def _(): + plgpu.barrier_wait(acc_consumed_barrier.at[si_acc]) + + @pl.loop(0, k_iters) + def mma_loop_body(ki): + si_tma = lax.rem(carry * k_iters + ki, num_stages) + plgpu.barrier_wait(xw_barrier.at[si_tma]) + w_tile = w_smem.at[si_tma].T if rhs_kn else w_smem.at[si_tma] # [block_n, block_k] either way + plgpu.tcgen05_mma( + acc_tmem.at[:, ms_acc], + w_tile, + x_smem.at[si_tma].T, + xw_consumed_barrier.at[si_tma], + accumulate=(ki > 0), + collective_axis=cluster_axis, + ) + + plgpu.tcgen05_commit_arrive(acc_barrier.at[si_acc], collective_axis=cluster_axis) + + @pl.when(wg == _EPILOGUE_WG) + def epilogue_wg(): + si = lax.rem(carry, jnp.int32(2)) + plgpu.barrier_wait(acc_barrier.at[si]) + ms_acc = pl.ds(si * cluster_block_m, cluster_block_m) + acc = plgpu.async_load_tmem(acc_tmem.at[:, ms_acc], layout=tcgen05) + acc = acc.astype(acc_smem.dtype) + acc_smem.T[...] = plgpu.layout_cast(acc, tcgen05_t) + plgpu.wait_load_tmem() + plgpu.barrier_arrive(acc_consumed_barrier.at[si]) + plgpu.commit_smem() + common.copy_ragged_smem_to_gmem( + acc_smem, + out_gmem, + block_start=block_start, + start_within_block=start_within_block, + actual_size=actual_size, + ns=pl.ds(ni * cluster_block_n + cluster_idx * block_n, block_n), + max_rows=min(cluster_block_m, m), + ) + + return carry + (actual_size > 0) + + if collective: + acc_consumed_barrier = plgpu.ClusterBarrier(collective_axes=("cluster",), num_barriers=2, orders_tensor_core=True) + else: + acc_consumed_barrier = plgpu.Barrier(num_barriers=2, orders_tensor_core=True) + scratch_shapes = dict( + x_smem=common.tiled_swizzled_smem((num_stages, block_m, block_k), lhs.dtype, "x"), + w_smem=common.tiled_swizzled_smem( + (num_stages, block_k, block_n) if rhs_kn else (num_stages, block_n, block_k), rhs.dtype, "w" + ), + acc_tmem=plgpu.TMEM((block_n, cluster_block_m * 2), jnp.float32, collective=collective), + acc_smem=common.tiled_swizzled_smem((cluster_block_m, block_n), out_dtype, "acc", tiling_prefix=(1,)), + xw_barrier=plgpu.Barrier(num_arrivals=2, num_barriers=num_stages), + xw_consumed_barrier=plgpu.Barrier(num_barriers=num_stages, orders_tensor_core=True), + acc_barrier=plgpu.Barrier(num_barriers=2, orders_tensor_core=True), + acc_consumed_barrier=acc_consumed_barrier, + ) + f = plgpu.kernel( + kernel, + out_type=jax.ShapeDtypeStruct((m, n), out_dtype), + scratch_types=scratch_shapes, + num_threads=2, + thread_name="wg", + grid=(m_iters * n_iters,), + grid_names=("mn",), + cluster=(1 + collective,), + cluster_names=("cluster",), + kernel_name="grouped_matmul_kn_sm100" if rhs_kn else "grouped_matmul_nk_sm100", + compiler_params=plgpu.CompilerParams( + approx_math=True, unsafe_no_auto_barriers=True, lowering_semantics=plgpu.LoweringSemantics.Warpgroup + ), + ) + info = common.GroupInfo.create_aligned(group_sizes, cluster_block_m, m_iters, align_tile) + return f(lhs, rhs, info.group_id, info.start_within_block, info.actual_size, info.block_start) + + +def mosaic_tiles(rows, groups): + """The tuned tiles for a buffer of `rows` rows over `groups` groups: 128-row tiles, 4 stages where the groups + average 768 rows or more of the buffer (DeepSeek-V3's 65536 over 64), else 64-row tiles, 6 stages (Qwen3.8's + 61440 over 128) -- on a GB200 each is the other's shape's runner-up within 2-7%.""" + big = rows >= 768 * groups + return dict( + block_m=128 if big else 64, + block_n=128, + block_k=64, + num_stages=4 if big else 6, + collective=True, + grid_minor_dim="M", + grid_tile_width=1, + ) + + +def mosaic_supported(device=None): + """Blackwell datacenter GPUs (sm_100 / sm_103: tcgen05), where `grouped_matmul` runs.""" + device = device or jax.devices()[0] + try: + return device.platform == "gpu" and int(float(getattr(device, "compute_capability", 0))) == 10 + except (TypeError, ValueError): + return False + + +def grouped_matmul_supported(lhs, rhs, device=None): + """Can `grouped_matmul` take this product: an sm_100 device, bf16 (or f16) both sides, and the weight's two + dims multiples of 64 (its SMEM tiling). Any row count and group sizes go: rows are padded to the tiling's 8 + where they are not a multiple of it (a copy of lhs, which the pipeline's buffers -- dropless, or a factor of 1.5 + or 2 -- never need).""" + return ( + lhs.dtype == rhs.dtype + and lhs.dtype in (jnp.bfloat16, jnp.float16) + and rhs.ndim == 3 + and rhs.shape[1] % 64 == 0 + and rhs.shape[2] % 64 == 0 + and mosaic_supported(device) + ) + + +def grouped_matmul(lhs, rhs, group_sizes, *, transpose_rhs=False, out_dtype=None, config=None): + """lhs[rows of group e] @ rhs[e] for every group e -> [M, N], reading rhs as it lies: [G, K, N], or with + transpose_rhs a [G, N, K] weight contracted on its last dim (lhs @ rhs[e]^T: the dlhs product). + + lhs [M, K] holds the rows sorted by group, `group_sizes` [G] int32 (sum <= M); the rows past the groups are not + written (tokamax's kernel's contract: callers mask them). bf16 x bf16 (or f16) -> out_dtype (lhs's) from an fp32 + accumulator, on sm_100 only (mosaic_supported); `config` a tokamax Mosaic Config (default: mosaic_tiles).""" + M, K = lhs.shape + G = rhs.shape[0] + K2, N = (rhs.shape[2], rhs.shape[1]) if transpose_rhs else rhs.shape[1:] + if rhs.ndim != 3 or K2 != K or group_sizes.shape != (G,): + raise ValueError( + f"grouped_matmul: lhs {lhs.shape}, rhs {rhs.shape} (transpose_rhs={transpose_rhs}), " + f"group_sizes {group_sizes.shape}" + ) + if lhs.dtype != rhs.dtype or lhs.dtype not in (jnp.bfloat16, jnp.float16): + raise ValueError(f"grouped_matmul takes bf16 x bf16 (or f16), got {lhs.dtype} x {rhs.dtype}") + config = config if config is not None else mosaic_config(**mosaic_tiles(M, G)) + # The kernel's [block_m, block_k] SMEM tiling (8, 64) applies to the whole [M, K] operand, which Mosaic GPU then + # wants a multiple of 8 rows long (or at most 8): pad, and drop the rows again (they lie past the groups, so the + # kernel neither reads them into a group nor writes them). + pad = -M % 8 if M > 8 else 0 + x = jnp.pad(lhs, ((0, pad), (0, 0))) if pad else lhs + out = _mosaic_kernel( + x, rhs, group_sizes.astype(jnp.int32), jnp.dtype(out_dtype or lhs.dtype), config, rhs_kn=not transpose_rhs + ) + return out[:M] if pad else out + + +# ------------------------------------------------- the in-place dW on Blackwell's tensor cores (tcgen05) +# +# The ragged contraction -- acc[e] += lhs[rows of e]^T g[rows of e] -- as a warp-specialized Mosaic GPU kernel in +# the forward kernel's mould: a dynamic scheduling loop over (group, cluster tile of acc[e]) work items, group-major +# (a group's rows stay in L2 while its tiles run), a TMA warp streaming [block_k rows, block_m] tiles of lhs and +# [block_k, block_n] of g through num_stages SMEM slots, an MMA warp accumulating lhs^T g in TMEM (lhs's tile as an +# MN-major A operand, g's as an MN-major B; two-CTA collective MMA: a cluster tile is 256 x 256), double-buffered so +# that the epilogue warpgroup -- the accumulator's tile TMA-loaded beside the MMAs, + the fp32 sum, one rounding, +# a TMA store back into the same buffer -- overlaps the next tile's MMAs. The contraction is ragged and Mosaic's +# 8-row SMEM tiling wants every TMA to start on a row 8 divides, so each group runs as full block_k-row steps from +# its first 8-aligned row (its body) and its other rows -- < 8 before the body, < block_k after it -- are gathered, +# zero-padded, into a side buffer of 2 x block_k rows a group (_dw_sides) whose one or two steps run like any other: +# no step ever reads another group's row. On a GB200, side buffers included: 0.92 ms at DeepSeek-V3's EP 4 shapes +# (the Triton kernel below: 1.74; tokamax's Triton dW writing a fresh buffer: 1.22), 1.91 ms at Qwen3.8's (3.29; +# 2.09). +DW_MOSAIC = dict( + block_m=128, + block_n=128, + block_k=64, + num_stages=5, + collective=True, + grid_minor_dim="M", + grid_tile_width=1, + epi_chunk=128, +) +# An fp32 accumulator (Megatron's main_grad): its epilogue tile is 128 KB of SMEM, which leaves room for 3 stages of +# A / B tiles (32 KB each) within sm_100's 227 KB. B200, DeepSeek-V3's wi at EP 8 ([32, 7168, 2048] from 65536 rows): +# 1.77 ms and exact against an fp32 product, against 2.69 for the Triton kernel and 1.34 with a bf16 accumulator. +# MAXTEXT_MPMD_DW_MOSAIC_F32=0 puts fp32 accumulators back on the Triton kernel. +DW_MOSAIC_F32 = dict(DW_MOSAIC, num_stages=3) +MOSAIC_F32_ACC = os.environ.get("MAXTEXT_MPMD_DW_MOSAIC_F32", "1") != "0" + + +def _dw_sides(lhs, g, group_sizes, bk): + """Per group: the first row of its body (8-aligned: the full bk-row steps), the body's step count and the step + count in all; and the group's other rows (< 8 before the body, < bk after it) zero-padded into side buffers of + 2 x bk rows a group, [E * 2 * bk, m] / [E * 2 * bk, n].""" + R = lhs.shape[0] + cum = jnp.cumulative_sum(group_sizes.astype(jnp.int32), include_initial=True) + lo, hi = cum[:-1], cum[1:] + body = (lo + 7) // 8 * 8 # 8-aligned always (the kernel's TMA rows), past a group shorter than that + nbody = jnp.maximum(hi - body, 0) // bk + body_end = body + nbody * bk + head, tail = jnp.minimum(body, hi) - lo, jnp.maximum(hi - body_end, 0) + nsteps = nbody + (head + tail + bk - 1) // bk + j = jnp.arange(2 * bk, dtype=jnp.int32)[None, :] + idx = jnp.where(j < head[:, None], lo[:, None] + j, body_end[:, None] + j - head[:, None]) + ok = (j < (head + tail)[:, None]).reshape(-1)[:, None] + idx = jnp.clip(idx, 0, R - 1).reshape(-1) + side_l = jnp.where(ok, jnp.take(lhs, idx, axis=0), jnp.zeros((), lhs.dtype)) + side_g = jnp.where(ok, jnp.take(g, idx, axis=0), jnp.zeros((), g.dtype)) + return body, nbody, nsteps, side_l, side_g + + +def _dw_mosaic(lhs, g, group_sizes, acc_ref, cfg): + from jax.experimental import pallas as pl + from jax.experimental.pallas import mosaic_gpu as plgpu + from tokamax._src import mosaic_gpu as mgpu_lib + from tokamax._src.ops.ragged_dot import pallas_mosaic_gpu_common as common + + bm, bn, bk, stages = cfg["block_m"], cfg["block_n"], cfg["block_k"], cfg["num_stages"] + collective = cfg["collective"] + cbm, cbn = (2 * bm, 2 * bn) if collective else (bm, bn) # the cluster's tile: A split by rows, B by columns + E, m, n = acc_ref.shape + m_iters, n_iters = m // cbm, n // cbn + tiles_per_group = m_iters * n_iters + minor = getattr(common.MatmulDimension, cfg["grid_minor_dim"]) + ec = cfg["epi_chunk"] + if cbn % ec: # the epilogue adds cbn // ec whole chunks: the columns past them would be stored back without dW + raise ValueError(f"ragged_dw: epi_chunk {ec} does not divide the cluster tile's {cbn} columns") + tcgen05 = plgpu.Layout.TCGEN05 + body, nbody, nsteps, side_l, side_g = _dw_sides(lhs, g, group_sizes, bk) + + def kernel( + x_gmem, + y_gmem, + xs_gmem, + ys_gmem, + body_gmem, + nbody_gmem, + nsteps_gmem, + acc_gmem, + x_smem, + y_smem, + e_smem, + acc_tmem, + xw_barrier, + xw_consumed, + acc_barrier, + acc_consumed, + prev_barrier, + ): + cluster_idx = lax.axis_index("cluster") + + @plgpu.dynamic_scheduling_loop( + ("w",), thread_axis="wg", cluster_axes=("cluster",) if collective else (), init_carry=(jnp.int32(0), jnp.int32(0)) + ) + def loop(info, carry): + steps, tiles = carry # k-steps and (non-empty) tiles this CTA ran: SMEM / TMEM slots + (idx,) = info.index + e = lax.div(idx, jnp.int32(tiles_per_group)) + mi, ni = plgpu.planar_snake( + lax.rem(idx, jnp.int32(tiles_per_group)), (m_iters, n_iters), minor, cfg["grid_tile_width"] + ) + start = pl.multiple_of(body_gmem[e], 8) + side0 = pl.multiple_of(e * (2 * bk), 8) + nb, nst = nbody_gmem[e], nsteps_gmem[e] + wg = lax.axis_index("wg") + ms, ns = pl.ds(mi * cbm, cbm), pl.ds(ni * cbn, cbn) + + @pl.when(nst > 0) # an empty group's tiles keep their accumulator: nothing to do + def work(): + @mgpu_lib.warp_map_when(wg == _COMPUTE_WG) + def compute_wg_warp(warp_id): + cluster_axis = "cluster" if collective else None + part = plgpu.CopyPartition.PARTITIONED(1) if collective else None + + @pl.when(warp_id == _TMA_WARP) + def tma_warp(): + @pl.loop(0, nst) + def tma_loop(ki): + step = steps + ki + si = lax.rem(step, stages) + + @pl.when(step >= stages) + def _(): + plgpu.barrier_wait(xw_consumed.at[si]) + + def load(xsrc, ysrc, row): + rows = pl.ds(row, bk) + plgpu.copy_gmem_to_smem( + xsrc.at[rows, ms], x_smem.at[si], xw_barrier.at[si], leader_tracked=part, collective_axes=cluster_axis + ) + plgpu.copy_gmem_to_smem( + ysrc.at[rows, ns], y_smem.at[si], xw_barrier.at[si], leader_tracked=part, collective_axes=cluster_axis + ) + + pl.when(ki < nb)(lambda: load(x_gmem, y_gmem, start + ki * bk)) + pl.when(ki >= nb)(lambda: load(xs_gmem, ys_gmem, side0 + (ki - nb) * bk)) + + @pl.when((warp_id == _MMA_WARP) & (cluster_idx == 0)) + def mma_warp(): + slot = lax.rem(tiles, 2) + + @pl.when(tiles > 1) + def _(): + plgpu.barrier_wait(acc_consumed.at[slot]) + + @pl.loop(0, nst) + def mma_loop(ki): + si = lax.rem(steps + ki, stages) + plgpu.barrier_wait(xw_barrier.at[si]) + plgpu.tcgen05_mma( + acc_tmem.at[:, pl.ds(slot * cbn, cbn)], + x_smem.at[si].T, + y_smem.at[si], + xw_consumed.at[si], + accumulate=(ki > 0), + collective_axis=cluster_axis, + ) + + plgpu.tcgen05_commit_arrive(acc_barrier.at[slot], collective_axis=cluster_axis) + + @pl.when(wg == _EPILOGUE_WG) + def epilogue_wg(): + slot = lax.rem(tiles, 2) + rows = pl.ds(mi * cbm + cluster_idx * bm, bm) # this CTA's rows of the cluster tile + plgpu.wait_smem_to_gmem(0, wait_read_only=True) # the last tile's store has read e_smem + plgpu.copy_gmem_to_smem(acc_gmem.at[e, rows, ns], e_smem, prev_barrier.at[0]) + plgpu.barrier_wait(acc_barrier.at[slot]) + plgpu.barrier_wait(prev_barrier.at[0]) + for c in range(cbn // ec): + cols = pl.ds(c * ec, ec) + part_sum = plgpu.async_load_tmem(acc_tmem.at[:, pl.ds(slot * cbn + c * ec, ec)], layout=tcgen05) + prev = plgpu.load(e_smem.at[:, cols], layout=tcgen05, optimized=False) + plgpu.wait_load_tmem() + e_smem.at[:, cols][...] = (part_sum + prev.astype(jnp.float32)).astype(e_smem.dtype) + plgpu.barrier_arrive(acc_consumed.at[slot]) + plgpu.commit_smem() + plgpu.copy_smem_to_gmem(e_smem, acc_gmem.at[e, rows, ns]) + + return steps + nst, tiles + (nst > 0).astype(jnp.int32) + + plgpu.wait_smem_to_gmem(0) + + if collective: + acc_consumed = plgpu.ClusterBarrier(collective_axes=("cluster",), num_barriers=2, orders_tensor_core=True) + else: + acc_consumed = plgpu.Barrier(num_barriers=2, orders_tensor_core=True) + scratch = dict( + x_smem=common.tiled_swizzled_smem((stages, bk, bm), lhs.dtype, "x"), + y_smem=common.tiled_swizzled_smem((stages, bk, bn), g.dtype, "y"), + e_smem=common.tiled_swizzled_smem((bm, cbn), acc_ref.dtype, "e"), + acc_tmem=plgpu.TMEM((bm, 2 * cbn), jnp.float32, collective=collective), + xw_barrier=plgpu.Barrier(num_arrivals=2, num_barriers=stages), + xw_consumed=plgpu.Barrier(num_barriers=stages, orders_tensor_core=True), + acc_barrier=plgpu.Barrier(num_barriers=2, orders_tensor_core=True), + acc_consumed=acc_consumed, + prev_barrier=plgpu.Barrier(num_arrivals=1, num_barriers=1), + ) + f = plgpu.kernel( + kernel, + out_type=(), + scratch_types=scratch, + num_threads=2, + thread_name="wg", + grid=(E * tiles_per_group,), + grid_names=("w",), + cluster=(1 + collective,), + cluster_names=("cluster",), + kernel_name="ragged_dw_sm100", + compiler_params=plgpu.CompilerParams( + approx_math=True, unsafe_no_auto_barriers=True, lowering_semantics=plgpu.LoweringSemantics.Warpgroup + ), + ) + f(lhs, g, side_l, side_g, body, nbody, nsteps, acc_ref) + + +def _dw_mosaic_cfg(acc_dtype, mosaic=None): + return dict(DW_MOSAIC_F32 if jnp.dtype(acc_dtype) == jnp.float32 else DW_MOSAIC, **(mosaic or {})) + + +def ragged_dw_mosaic_supported(lhs, g, acc, device=None, cfg=None): + """Does ragged_dw run the tcgen05 kernel here: an sm_100 device, bf16 (or f16) lhs and g, an accumulator of + their dtype or fp32 (DW_MOSAIC_F32's tiles; MOSAIC_F32_ACC), acc's two dims multiples of the cluster tile + (256 x 256 by default; rows of any count, padded to the tiling's 8), and the tile's columns a multiple of the + epilogue's epi_chunk (it adds whole chunks).""" + cfg = cfg or _dw_mosaic_cfg(acc.dtype) + k = 2 if cfg["collective"] else 1 + acc_ok = acc.dtype == lhs.dtype or (acc.dtype == jnp.float32 and MOSAIC_F32_ACC) + return ( + lhs.dtype == g.dtype + and lhs.dtype in (jnp.bfloat16, jnp.float16) + and acc_ok + and acc.ndim == 3 + and acc.shape[1] % (k * cfg["block_m"]) == 0 + and acc.shape[2] % (k * cfg["block_n"]) == 0 + and (k * cfg["block_n"]) % cfg["epi_chunk"] == 0 + and mosaic_supported(device) + ) + + +def _sm80_dw_tiles(acc_dtype): + """The Triton kernel's tiles for an fp32 accumulator on an sm80 GPU (A100): 64-row tiles -- the 128 x 128 default + holds a 128 x 128 fp32 accumulator tile in registers beside the contraction's, and spills (A100, dsv3-mini expert + shapes [64, 4096, 1536] from 49152 rows: 5.66 ms against 6.70 at the default tiles, 6.06-10.4 at the others tried). + {} elsewhere (TILES: tuned on GB200, where the bf16 kernel runs on tcgen05 anyway).""" + try: + cc = float(getattr(jax.devices()[0], "compute_capability", 0) or 0) + except Exception: # no GPU backend + return {} + return dict(block_m=64, block_n=128) if 8 <= cc < 9 and jnp.dtype(acc_dtype).itemsize == 4 else {} + + +def ragged_dw(lhs, g, group_sizes, acc, *, tiles=None, mosaic=None, xla=False): + """acc[e] + lhs[rows of group e]^T @ g[rows of group e] for every group e -> acc's shape and dtype. + + lhs [R, m] and g [R, n] hold the rows sorted by group, `group_sizes` [E] int32 (sum <= R; rows past them ignored), + acc [E, m, n]. On GPU acc's buffer is updated in place (jax.Ref; donated, no copy) with one rounding: on sm_100 + by the tcgen05 kernel where it takes the shapes (ragged_dw_mosaic_supported; `mosaic` a dict of tiles over + DW_MOSAIC's -- DW_MOSAIC_F32's for an fp32 acc -- or False for the Triton kernel), else by the Triton one (`tiles`: + its TILES); elsewhere, or with `xla` (tokamax_gmm 'xla'), the product is lax's, added in fp32. ds_ep tells it + which per tokamax_gmm (ds_ep._ragged_dw).""" + E, m, n = acc.shape + if lhs.shape[1] != m or g.shape[1] != n or lhs.shape[0] != g.shape[0] or group_sizes.shape != (E,): + raise ValueError(f"ragged_dw: lhs {lhs.shape}, g {g.shape}, group_sizes {group_sizes.shape} against acc {acc.shape}") + if xla or jax.default_backend() != "gpu": + dw = lax.ragged_dot_general(lhs, g, group_sizes, _CONTRACTING, preferred_element_type=jnp.float32) + return (acc.astype(jnp.float32) + dw).astype(acc.dtype) + cfg = None if mosaic is False or tiles is not None else _dw_mosaic_cfg(acc.dtype, mosaic) + if cfg is not None and ragged_dw_mosaic_supported(lhs, g, acc, cfg=cfg): + R = lhs.shape[0] + pad = -R % 8 if R > 8 else 0 # the 8-row SMEM tiling applies to the whole [R, .] operands + if pad: + lhs, g = jnp.pad(lhs, ((0, pad), (0, 0))), jnp.pad(g, ((0, pad), (0, 0))) + ref = jax.new_ref(acc) + _dw_mosaic(lhs, g, group_sizes.astype(jnp.int32), ref, cfg) + return ref[...] + import jax_triton as jt + + t = dict(TILES, **(_sm80_dw_tiles(acc.dtype) if tiles is None else {}), **(tiles or {})) + cum = jnp.cumulative_sum(group_sizes.astype(jnp.int32), include_initial=True) + ref = jax.new_ref(acc) + sa, sb, so = _strides(lhs.shape), _strides(g.shape), _strides(acc.shape) + cdiv = lambda a, b: (a + b - 1) // b + jt.triton_call( + lhs, + g, + cum, + ref, + kernel=_kernel(), + out_type=(), + grid=(cdiv(m, t["block_m"]), cdiv(n, t["block_n"]), E), + name="ragged_dw_acc", + num_warps=t["num_warps"], + num_stages=t["num_stages"], + m=m, + n=n, + stride_ak=sa[0], + stride_am=sa[1], + stride_bk=sb[0], + stride_bn=sb[1], + stride_oe=so[0], + stride_om=so[1], + stride_on=so[2], + block_m=t["block_m"], + block_n=t["block_n"], + block_k=t["block_k"], + ) + return ref[...] diff --git a/src/maxtext/experimental/mpmd/jax/libtpu_flags/tpu7x.flags b/src/maxtext/experimental/mpmd/jax/libtpu_flags/tpu7x.flags new file mode 100644 index 0000000000..29a7987ca6 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/libtpu_flags/tpu7x.flags @@ -0,0 +1,48 @@ +# The TPU7x flag set: the 30 libtpu flags both sides of the TPU7x measurements ran, MaxText's SPMD pipeline and the +# MPMD pipeline. The launchers (ds_ep_run.sh, ds_ep_aot.sh, +# ds_ep_multihost.sh) run it by default (MPMD_FLAG_SET=tpu7x) and add +# --xla_max_concurrent_async_collective_permutes=64 to any set. MaxText's public DeepSeek3-671B tpu7x-512 example +# (docs/guides/optimization/benchmark_and_performance.md) differs from it by two flags each way: it sets +# --xla_tpu_aggressive_opt_barrier_removal=true and --xla_tpu_enable_all_gather_offload_tracing=true, this set +# --xla_tpu_enable_ici_rs_pipelining=true and --xla_tpu_num_sparse_cores_for_gather_offloading=1. +# +# --xla_tpu_enable_ici_ag_pipelining=true is not in it. With that flag, libtpu 0.0.46.1 fails to compile MaxText's +# DeepSeek-V3 train step: "INVALID_ARGUMENT: layout minor_to_major field contains 2 elements, but shape has 0 +# dimensions: {1, 0}; shape: s32[]" (bisected: that flag alone with the scoped VMEM limit reproduces it). +# +# The set names the scoped VMEM limit the megablox tiles need (65536 KiB). LIBTPU_INIT_ARGS_OVERRIDE (even "") +# replaces the set's flags; EXTRA_LIBTPU_INIT_ARGS is appended. HLO dumps go through XLA_FLAGS (libtpu rejects +# --xla_dump_* in LIBTPU_INIT_ARGS), e.g. +# XLA_FLAGS="--xla_dump_to=/tmp/hlo --xla_dump_hlo_as_text --xla_dump_hlo_module_re=jit_train_step" +# One flag per line; '#' lines are comments. +# Read with: grep -v '^#' src/maxtext/experimental/mpmd/jax/libtpu_flags/tpu7x.flags | tr '\n' ' ' +--xla_tpu_dvfs_p_state=7 +--xla_tpu_scoped_vmem_limit_kib=65536 +--xla_tpu_num_sparse_cores_for_gather_offloading=1 +--xla_tpu_bf16_emission_mode=NATIVE_EMISSION +--xla_tpu_enable_sparse_core_reduce_scatter_v2=true +--xla_tpu_enable_sparse_core_collective_offload_all_gather=true +--xla_tpu_enable_sparse_core_collective_offload_2d_all_gather=true +--xla_tpu_use_tc_device_shape_on_sc=True +--xla_sc_disable_megacore_partitioning=True +--xla_tpu_enable_async_collective_fusion_fuse_all_gather=false +--xla_enable_async_all_gather=true +--xla_tpu_prefer_async_allgather_to_allreduce=true +--xla_tpu_enable_sparse_core_collective_offload_all_reduce=true +--xla_tpu_enable_sparse_core_collective_offload_reduce_scatter=true +--xla_tpu_enable_sparse_core_collective_offload_3d_all_gather=true +--xla_tpu_use_single_sparse_core_for_all_gather_offload=true +--xla_tpu_enable_concurrent_sparse_core_offloading=true +--xla_tpu_enable_offloading_gather_to_sparsecore=true +--xla_tpu_sparse_core_all_gather_latency_multiplier=1 +--xla_tpu_sparse_core_reduce_scatter_latency_multiplier=3 +--xla_tpu_enable_sparse_core_collective_aggregator=true +--xla_tpu_enable_latency_hiding_layer_scheduler=true +--xla_tpu_scheduler_percent_shared_memory_limit=150 +--xla_tpu_enable_layer_scheduler_for_dependent_collectives=true +--xla_tpu_enable_sparse_core_collective_offload_nd_reduce_scatter=true +--xla_tpu_pcie_bandwidth_multiplier=0.03 +--xla_tpu_enable_sparse_core_offload_queuing_in_lhs=true +--xla_tpu_enable_multi_compute_overlap_in_layer_scheduler=false +--xla_tpu_enable_3d_reduce_scatter_decomposer=false +--xla_tpu_enable_ici_rs_pipelining=true diff --git a/src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p.flags b/src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p.flags new file mode 100644 index 0000000000..340003ad37 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p.flags @@ -0,0 +1,47 @@ +# libtpu flags of MaxText's tuned v5p DeepSeek-V3 recipe, for both sides of a v5p comparison: the XLA_FLAGS of +# tpu-recipes training/v5p/DeepSeek3-671B-MaxText/cluster_toolkit/run_recipe.sh (tpu-recipes 2a2f894c95, +# 2026-10-02), which takes them from MaxText's benchmarks/maxtext_v5p_model_configs.py `deepseek3_671b_v5p_1024`: +# ENABLE_SPARSECORE_OFFLOADING_FOR_RS_AG_AR + HOST_OFFLOAD_FLAGS + LAYOUT_FOR_ALL_REDUCE_SCATTER + +# DATA_PARALLEL_OVERLAP + MOE_VMEM_LIMIT_FLAG + DISABLE_MEGACORE_FUSION_ALLOW_AGS + ENABLE_ASYNC_COLLECTIVE_PERMUTE. +# The recipe image runs libtpu 0.0.46, as the MPMD image does. One flag per line; '#' lines are comments. +# One recipe flag is left out: --2a886c8_chip_config_name=megachip_tccontrol. libtpu 0.0.46 rejects it ("Unknown +# command line flag"), and MaxText dropped it from ENABLE_SPARSECORE_OFFLOADING_BASE_FLAGS on 2026-01-26 (commit +# "remove --2a886c8_chip_config_name flag in sparsecore offloading"); the recipe's flags predate that. +# libtpu 0.0.46 accepts the chip config megachip_tccontrol under another flag name; set that way, it made no +# difference to MaxText on a v5p-128 (10673 vs 10676 ms a step, one slice, 2026-10). +# The set names its own scoped VMEM limit (81920 KiB, MOE_VMEM_LIMIT_FLAG). The launchers (ds_ep_run.sh, +# ds_ep_aot.sh, ds_ep_multihost.sh) run it with MPMD_FLAG_SET=v5p, adding +# --xla_max_concurrent_async_collective_permutes=64. v5p_fsdp_extra.flags adds to it, through EXTRA_LIBTPU_INIT_ARGS. +# Read with: grep -v '^#' src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p.flags | tr '\n' ' ' +--xla_tpu_enable_async_collective_fusion_fuse_all_gather=false +--xla_tpu_enable_async_collective_fusion_fuse_all_reduce=false +--xla_tpu_enable_async_collective_fusion_fuse_reduce_scatter=false +--xla_tpu_enable_sparse_core_collective_offload_all_gather=true +--xla_tpu_enable_sparse_core_collective_offload_reduce_scatter=true +--xla_tpu_enable_sparse_core_collective_offload_all_reduce=true +--xla_tpu_enable_all_gather_offload_tracing=true +--xla_tpu_enable_reduce_scatter_offload_tracing=true +--xla_tpu_enable_all_reduce_offload_tracing=true +--xla_tpu_use_tc_device_shape_on_sc=true +--xla_sc_enable_instruction_fusion=false +--xla_sc_disjoint_spmem=false +--xla_sc_disable_megacore_partitioning=true +--xla_tpu_enable_all_experimental_scheduler_features=true +--xla_tpu_enable_scheduler_memory_pressure_tracking=true +--xla_tpu_host_transfer_overlap_limit=24 +--xla_tpu_aggressive_opt_barrier_removal=ENABLED +--xla_lhs_prioritize_async_depth_over_stall=ENABLED +--xla_tpu_enable_ag_backward_pipelining=true +--xla_should_allow_loop_variant_parameter_in_chain=ENABLED +--xla_should_add_loop_invariant_op_in_chain=ENABLED +--xla_max_concurrent_host_send_recv=100 +--xla_tpu_scheduler_percent_shared_memory_limit=100 +--xla_latency_hiding_scheduler_rerun=2 +--xla_tpu_use_minor_sharding_for_major_trivial_input=true +--xla_tpu_relayout_group_size_threshold_for_reduce_scatter=1 +--xla_tpu_assign_all_reduce_scatter_layout=true +--xla_tpu_enable_data_parallel_all_reduce_opt=true +--xla_tpu_data_parallel_opt_different_sized_ops=true +--xla_tpu_scoped_vmem_limit_kib=81920 +--xla_tpu_megacore_fusion_allow_ags=false +--xla_enable_async_collective_permute=true diff --git a/src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p_fsdp_extra.flags b/src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p_fsdp_extra.flags new file mode 100644 index 0000000000..76971e8e7c --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p_fsdp_extra.flags @@ -0,0 +1,14 @@ +# libtpu flags added to v5p.flags for MaxText's pure-FSDP baseline on a v5p-128, and given to MPMD too. +# The recipe offloads 1D all-gathers to SparseCore and turns off TensorCore async collective fusion for all-gathers. An +# FSDP=64 gather over a v5p-128's 4x4x4 torus spans all three dimensions, so neither path applies, and MaxText's 52 +# FSDP weight all-gathers ran synchronously on the TensorCore: 165 ms a step. With these two flags they become async +# SparseCore computations (in the AOT compile's HLO), and MaxText's step went from 10640 to 10514 ms +# (2026-10). libtpu 0.0.46 has both; MaxText's benchmarks/xla_flags_library.py uses neither, but its +# DeepSeek3-671B tpu7x-512 example (docs/guides/optimization/benchmark_and_performance.md) sets both. +# One flag per line; '#' lines are comments. It adds to v5p: give it through EXTRA_LIBTPU_INIT_ARGS +# (MPMD_FLAG_SET=v5p_fsdp_extra alone would run these two flags without the recipe's), e.g. +# F=src/maxtext/experimental/mpmd/jax/libtpu_flags/v5p_fsdp_extra.flags +# MPMD_FLAG_SET=v5p EXTRA_LIBTPU_INIT_ARGS="$(grep -v '^#' $F | tr '\n' ' ')" \ +# bash src/maxtext/experimental/mpmd/jax/ds_ep_multihost.sh [pipeline flags...] +--xla_tpu_enable_sparse_core_collective_offload_3d_all_gather=true +--xla_tpu_enable_sparse_core_collective_offload_2d_all_gather=true diff --git a/src/maxtext/experimental/mpmd/jax/maxtext_parity.py b/src/maxtext/experimental/mpmd/jax/maxtext_parity.py new file mode 100644 index 0000000000..1628fd7198 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/maxtext_parity.py @@ -0,0 +1,779 @@ +# 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. + +"""Numerical parity of the MPMD pipeline against MaxText: one set of weights, one batch, both trainers. + + # 1. one MaxText init -> a MaxText params checkpoint, and the same weights as ds_ep chunk files + JAX_PLATFORMS=cpu XLA_FLAGS=--xla_force_host_platform_device_count=4 \\ + python3 -m maxtext.experimental.mpmd.jax.maxtext_parity init OUT [MaxText key=value ...] + # against MaxText without PP (DP over DCN): one device, the ds_ep run's --layer-split, and copies in other + # dtypes; --exact for DeepSeek-V3 itself (dense layers, routed biases, MTP), a split summing to every layer + # for dense layers spanning the first chunks + JAX_PLATFORMS=cpu python3 -m maxtext.experimental.mpmd.jax.maxtext_parity init OUT --layer-split 1,1,... \\ + [--cast bfloat16] [--exact] ici_pipeline_parallelism=1 [MaxText key=value ...] + # 2. MaxText's trainer (maxtext.trainers.pre_train.train): load_parameters_path=OUT/maxtext_params + # enable_checkpointing=true save_checkpoint_on_start=false save_checkpoint_on_completion=false + # (an older MaxText refuses to load parameters with checkpointing off; these flags work on any. The + # two save_* flags keep it from saving -- by default it saves at step 0, and on several hosts a save into + # a host-local base_output_directory times out waiting for directories only process 0 creates; a gs:// + # one fails MaxText's mkdir check, which finds no directory object there) + # metrics_file=M.txt log_period=1 steps=N num_experts_per_tok=K use_random_routing=false + # learning_rate=LR warmup_steps_fraction=0 learning_rate_final_fraction=1.0 + # gradient_clipping_threshold=0, with its own synthetic data; + # ds_ep_pipeline: --init-from OUT/ds_chunks --data maxtext --routing topk --topk K --lr LR + # --adam-math optax --grad-clip 0 --warmup N --json D.json (the same N), and the same MoE path on both: + # use_ring_of_experts / use_ragged_sort / ragged_buffer_factor there, --ragged-sort / + # --ragged-buffer-factor here. With fp32 weights --rs-dtype bfloat16 follows MaxText's gradients, which + # its bf16 reduce-scatters sum before the cast to fp32 (--adam-math optax takes each gradient in its + # weight's dtype). And one softmax on both: tokamax's base-2 on both (MaxText's default and ds_ep's: see + # softmax below), or --attn splash (or --sa-base2-exp off) here with sa_use_base2_exp=false there + # DeepSeek-V3 itself: MaxText with weight_dtype=float32 grad_dtype=float32 sa_use_base2_exp=false (and its + # batch saved for ds_ep --data npy:), ds_ep --attn splash --weight-dtype float32 --rs-dtype bfloat16 + # --adam-math optax (MaxText's casts: see precision) + # A Qwen3.5-family model (init --model): MaxText with model_name= override_model_config=true, + # init's key=value overrides and packing=false, ds_ep --model with the same dims. ds_ep's Gated + # DeltaNet takes no segment ids (ds_ep.qwen_mixer_part), MaxText's GDN under packing=false; under its default + # packing MaxText's trainer runs the packed GDN on the synthetic batch's all-one segment ids, the same math + # in other roundings: fp32's in fp32 (its step-0 norm came 1e-4 from the pipeline's, 8x MaxText's own + # 1-vs-2-device spread: maxtext_parity_test.test_qwen_trains_as_maxtext_fp32), bf16's in a bf16 compute + # dtype (with fp32 weights its conv keeps the fp32 kernel ds_ep's rounds to bf16) + # 3. per step: loss and the pre-clip gradient norm. With bf16 MaxText gradients the norm is a bf16 value, + # blind to a 5e-4 difference: prefer an fp32 MaxText norm (held to --gnorm32-rtol at step 0), and add + # --control M2.txt, MaxText on another mesh, whose spread bounds every step's loss difference + python3 -m maxtext.experimental.mpmd.jax.maxtext_parity compare M.txt D.json [--control M2.txt] + +What makes the two runs comparable: + weights MaxText initializes; `init` writes its params with MaxText's save_params_to_path (what + load_parameters_path restores; the optimizer starts fresh, as in ds_ep's init_state) and the same + arrays as ds_ep chunk files. MaxText stacks a pipelined leaf [repeat, stage, ...]; ds_ep's chunk c + is MaxText's [c // S, c % S] (circular placement: chunk c runs on stage c % S, repeat c // S), with + DeepSeekMoeBlock_0/MoeBlock_0 renamed to moe. Without PP (ici_pipeline_parallelism=1, DP over DCN) + MaxText scans its layers, a leaf's layer axis at param_scan_axis: DeepSeek's first layers in + decoder/dense_layers and the MoE layers in decoder/moe_layers, cut into chunks by --layer-split as + ds_ep_pipeline cuts them (the MoE layers a chunk, the dense ones in chunk 0; or every layer a chunk). + Its routed biases are MoEBiasVars, not parameters (zero at init; `init` writes them into the params + checkpoint, where MaxText's loader looks them up), and its MTP layer shares the token embedding, + which ds_ep's last chunk keeps a copy of. bfloat16 goes over as raw bits; --cast writes the same + weights in another dtype too (OUT/maxtext_params_, OUT/ds_chunks_). + data MaxText's dataset_type=synthetic is one batch, the same every step: randint(key 0) under + threefry2x32, the same bits on every backend. ds_ep_pipeline --data maxtext regenerates it bit for + bit (ds_ep_pipeline.MAXTEXT_BATCH_PRNG), and logs its sha256. + routing MaxText draws its random routing from NNX rng streams split per (repeat, stage) and advanced + every pipeline iteration, under unsafe_rbg: not reproducible from outside. Compare at top-k + routing (num_experts_per_tok=K use_random_routing=false there, --routing topk --topk K here). + Top-k of all experts has no selection boundary; below it a last-bit difference upstream can flip + a token's expert where two router scores tie (bf16 scores near 0.5 at init). Measured: top-8 of + 16 moved step 0's loss by 4e-6 (top-16 of 16: 2e-7) and then tracked as closely as top-16 + (8 x TPU7x 2x2x2, 2026-10-25). DeepSeek-V3's own routing (top-8 of 256 in 4 of 8 groups) under + float32_gate_logits compares as it is: its fp32 scores leave the step-0 losses a few fp32 ulps apart + (measured 6e-9 to 1.2e-7 relative, by jax and MaxText revision: + maxtext_parity_test.test_exact_trains_as_maxtext_fp32). + schedule A constant learning rate on both sides: learning_rate=LR warmup_steps_fraction=0 + learning_rate_final_fraction=1.0 here, --lr LR there. + optimizer --adam-math optax: ds_ep's AdamW runs optax's chain in the leaf dtypes (bf16 with bf16 weights), + op for op as maxtext.experimental.mpmd.jax.deepseek.train, which matches MaxText's optax.adamw bit + for bit; ds_ep's default fp32 arithmetic differs in the last bits, and with bf16 moments that grows + over the steps. + norms MaxText reduces its gradient norm in its gradients' dtype (max_utils.l2norm_pytree): bf16 with bf16 + weights or grad_dtype=bfloat16. A run whose MaxText norms are all bf16 values is compared with + ds_ep's fp32 norm rounded to bf16 (warmup_gnorms_bf16), any other with ds_ep's fp32 norm. + loss ds_ep's loss is the cross entropy plus MTP's (scaled); a load-balance loss rides its layers' backward + only, so `compare` takes MaxText's learning/moe_lb_loss off its learning/loss. + softmax The attention kernels must compute one softmax. MaxText's tokamax splash with sa_use_base2_exp=true + (its base.yml default, and the MLPerf recipe's) scales the bf16 query by log2(e) rounded to bf16 + (1.4453125), a softmax 1.0018x sharper than its logits, as ds_ep's tokamax does by default; ds_ep's + --attn splash, and tokamax with --sa-base2-exp off, compute the exact one. Pair --attn splash with + MaxText sa_use_base2_exp=False, or --attn tokamax_splash with MaxText's default. + Mismatched, at DeepSeek-V3 dims (4 layers, lr 1e-5): the step-0 loss still agrees (the sharpening + moves layer 0's attention output by ~0.3%, below the loss's fp32 resolution), MaxText's fp32 gradient + norm is 0.049% above ds_ep --rs-dtype float32's (0.053% above its bf16 reduce-scatter's) at every + step, and the loss parts from the second update (+5e-5..+1.3e-4 by step 4: under 1e-5 relative, so + --loss-rtol cannot see it; an fp32 MaxText norm or --control does). + precision MaxText weight_dtype=float32 grad_dtype=float32 reduce-scatters its bf16 compute copies' gradients + (the fp32 routers' kernels' in fp32) and casts the result to fp32: pair it with ds_ep --rs-dtype + bfloat16 --grad-dtype float32, the same casts but for the routers' kernels (ds_ep reduce-scatters them in + --rs-dtype). At DeepSeek-V3 dims and lr 1e-5 the loss then agrees within 1e-5 over 20 steps but at steps + 14 (2.3e-5) and 17 (4.5e-5), two of the steps MaxText's own grad_dtype switch moves most; on the steps + that switch leaves alone it drifts by +4.3e-7 +- 2.2e-7 a step (steps 10-19: +1.05e-5 on average, 9 of + 10 positive), and the fp32 norm stays 0.5-1.2e-5 below MaxText's. ds_ep --rs-dtype float32 (an fp32 + reduction) stays within ds_ep's own run-to-run spread (~1e-5) through step 9, then drifts one way by + ~2e-6 a step (-1.4e-4 at step 17), its norm 3.1-3.8e-5 above MaxText's: the reduction's precision, which + alone moves ds_ep's loss by ~2.6e-6 a step (bfloat16 against float32, the same run otherwise). + --rs-dtype bfloat16 with grad_dtype=bfloat16 does not drift but parts at isolated steps of this batch + (5, 10, 13, 14, 17, 19: 7.7e-5 at step 5, up to 7.9e-4 by step 17), the steps whose loss also moves + 2e-4..1.3e-3 when MaxText alone switches its grad_dtype. Why (confirmed: at lr 1.1e-5 both moved + where predicted): the init is all bf16, so every fp32 master starts on the bf16 grid, and AdamW's + near-sign steps move most weights 0.992-0.996 lr an update; the bf16 copies the forward reads change + a binade at a time, at the update counts (2m+1) 2^(b-8) / lr (at lr 1e-5 the loss falls ~0.09 at steps + 4, 7, 10, ~0.04 at 2, 5, 8, 11; at 1.1e-5 ~0.09 at 3, 6, 9), and a step n whose fence + (2m+1) 2^(b-8) / (n lr) falls in 0.97-0.997, inside the per-weight steps, has a 0.01-0.1% difference + in AdamW's step decide which copies have moved -- one step's gap, the larger the coarser the binade + (1e-3 at lr 1.1e-5 step 7). Compare away from those steps, or from an init off the bf16 grid (not + tried). bf16 gradients shorten optax's steps by 0.03-0.1% (it divides by 1 - b1^t rounded to + bf16). So loss parity cannot check the routed-bias update here (it moves the loss at most 1e-5 in 12 + steps): compare the bias vectors (MaxText's checkpoints). `compare` notes a pairing that mismatches + precision or optimizer arithmetic. (optax multiplies the bf16 mu by bf16 b1, 0.8984375, whatever the + gradient's dtype; bf16 gradients also round 1-b1 and 1-b2 to bf16 and compute the new mu in bf16.) + +What still differs, by design (in the pipelined protocol: bf16 weights and gradients, --rs-dtype bfloat16, +tokamax on both sides): MaxText accumulates pipeline weight gradients in bf16 and all-reduces the routed +experts' over fsdp, ds_ep accumulates in fp32 and reduce-scatters in bf16; the kernels' fusion and summation +order differ; and the global-norm clip compares ds_ep's fp32 norm where MaxText's optax reduces it in bf16, so +the updates agree bit for bit only while the norm stays below the clip (gradient_clipping_threshold, 1.0) or +both norms round to the same bf16 value -- or with the clip off on both sides (gradient_clipping_threshold=0, +--grad-clip 0). ds_ep's SparseCore ragged sort (--ragged-sort on) is not bit-reproducible from run to run +(identical executables, two runs with identical flags part by up to 1.1e-5 by step 5, nine by up to 1.5e-5; +step 0 agrees); with --ragged-sort off --ragged-buffer-factor 0 (the TensorCore sort, +24% step time at +DeepSeek-V3 dims) three runs, on different slices, agree bit for bit, as MaxText's do. Measured at small scale +(v6e-4, PP2 x FSDP2, 4 layers, full DeepSeek-V3 per-layer dims, top-16 of 16, bf16; tokamax with base-2 exp +on both sides): loss 5.3e-7 relative at step 0, within 8.7e-6 over 4 steps, the bf16 gradient norm equal at +every step; MaxText against itself with pinned vs default XLA numerics moves the loss by 1e-5. Against +MaxText DP over DCN (8 x TPU7x 2x2x2, 8 stages, 19 layers, 100 steps, 2026-10-25): 2e-7 to 4e-6 +at step 0, within 1e-3 through step 40. DeepSeek-V3 itself (2 x tpu7x-4x4x4 a side, 3 dense + 1 MoE layer + +MTP, top-8 of 256 in 4 of 8 groups, 6 steps at lr 1e-5; ds_ep --attn splash, MaxText +sa_use_base2_exp=False): with fp32 gradients on both sides the loss agrees within 6.8e-6 at every step and the +fp32 norm within 3.3-3.7e-5 (MaxText's bf16 reduce-scatters), against a MaxText-vs-MaxText spread (EP 4 x FSDP +32 vs EP 8 x FSDP 16) of 6.7e-6; at lr 1e-4 within 3.6e-5 through step 5, where MaxText's base-2 softmax parts +by 3e-4 at step 1 and 4.8e-3 by step 11. These DeepSeek-V3 runs, and those under precision above, predate +ds_ep's fp32 router kernel (ds_ep.leaf_dtypes): their routers read the bf16 compute copy of the fp32 master, +where MaxText's GateLogit reads the master's values. +""" + +from __future__ import annotations + +import argparse +import ast +import json +import math +import os +import sys +import time + +# The model the MPMD runs train, as the MaxText SPMD pipeline baseline of the TPU7x comparison set it, minus +# everything that does not shape a parameter; `init` takes MaxText key=value overrides on top (a run's other +# settings). +MODEL = dict( + model_name="deepseek3-671b", + override_model_config=True, + vocab_size=32768, + first_num_dense_layers=0, + base_mlp_dim=2048, + num_experts_per_tok=8, + shared_experts=1, + routed_bias=False, + dtype="bfloat16", + weight_dtype="bfloat16", + custom_mesh_and_rule="pipeline-large-moe", + allow_split_physical_axes=True, + max_target_length=4096, + megablox=True, + sparse_matmul=True, + attention="flash", + use_tokamax_splash=True, +) +RUN = dict( + run_name="maxtext_parity_init", + base_output_directory="/tmp/maxtext_parity", + dataset_type="synthetic", + enable_checkpointing=False, + skip_jax_distributed_system=True, + enable_goodput_recording=False, +) +# `init --exact`: DeepSeek-V3 itself, the model of the exact-DSv3 runs -- deepseek3-671b's own vocabulary, dense +# layers, dense MLP and routed bias (MODEL has the sparse prototype's) and the MLPerf recipe's MTP layer. +EXACT = dict(vocab_size=129280, first_num_dense_layers=3, base_mlp_dim=18432, routed_bias=True, mtp_num_layers=1) +# `init --model qwen3.8-2.4t-a95b` (or a Qwen3.5 model): MaxText's yml of that name -- decoder_block qwen3_5, its +# own vocabulary, rotary embedding (Qwen3.8: base.yml's use_mrope false) and every dim -- with the benchmark's +# numerics; the key=value overrides cut it down (base_num_decoder_layers, num_experts, ...). Cut to another +# head_dim, a Qwen3.5 model's text mRoPE needs sections summing to rotary_dim // 2 = int(head_dim * 0.25) // 2 +# (MaxText checks it; text positions never read the split): mrope_section=[3,3,2] at head_dim 64. `init` refuses +# a leaf with no place in a chunk (qwen_to_chunks: use_multimodal=true's vision encoder, say) before it writes +# anything. +QWEN_MODEL = dict( + override_model_config=True, + dtype="bfloat16", + weight_dtype="bfloat16", + max_target_length=4096, + megablox=True, + sparse_matmul=True, + attention="flash", + use_tokamax_splash=True, +) +QWEN_MODELS = ("qwen3.8-2.4t-a95b", "qwen3.5-397b-a17b", "qwen3.5-35b-a3b") + + +def _value(v): + """A key=value override's value: an int, a float, a list, tuple or dict literal (mrope_section=[3,3,2]: pyconfig + takes a keyword's value as it is, and the string would fail its validation), true / false, else the string.""" + for cast in (int, float): + try: + return cast(v) + except ValueError: + pass + if v.strip()[:1] in ("[", "(", "{"): + try: + return ast.literal_eval(v) + except (ValueError, SyntaxError): + pass + return {"true": True, "false": False}.get(v.lower(), v) + + +def maxtext_models_dir(): + """MaxText's configs/models/, its model ymls: maxtext.utils.globals.MAXTEXT_CONFIGS_DIR's models/.""" + from maxtext.utils.globals import MAXTEXT_CONFIGS_DIR # pylint: disable=import-outside-toplevel + + return os.path.join(MAXTEXT_CONFIGS_DIR, "models") + + +def _moe_names(rest): + """MaxText's names inside a DeepSeek layer -> ds_ep's: the MoE block is moe, the routed experts not nested + (DeepSeekMoeBlock_0/MoeBlock_0 is moe, DeepSeekMoeBlock_0/shared_experts moe/shared_experts).""" + rest = list(rest) + if rest and rest[0] == "DeepSeekMoeBlock_0": + rest = ["moe"] + (rest[2:] if rest[1] == "MoeBlock_0" else rest[1:]) + return rest + + +def maxtext_to_chunks(flat, n_stages, n_chunks, layer_split=None, scan_axis=1): + """MaxText's params {path tuple: array} -> ds_ep chunk trees {'/'-joined path: array}, chunk order. + + The pipeline's layout (decoder/pipeline_module/layers, a leaf [repeat, stage, ...]: one layer a chunk), or + the scanned one of a run without PP (decoder/dense_layers and decoder/moe_layers, a leaf's layer axis at + `scan_axis`, a routed bias's -- an MoEBiasVar, not a parameter -- at 0), cut by `layer_split` as + ds_ep_pipeline cuts --layer-split: the MoE layers a chunk, the dense layers all in chunk 0, or -- its sum + every layer -- all of them in order, the dense ones first. The MTP layer (mtp_block/mtp_layer_1/mtp_1_*) goes + to the last chunk's 'mtp', with a copy of the token embedding that MaxText shares with the decoder's input + (ds_ep's last chunk keeps one: ds_ep.mtp_shapes).""" + import numpy as np + + chunks = [{} for _ in range(n_chunks)] + axis = lambda rest: 0 if list(rest[-2:]) == ["gate", "bias"] else scan_axis + scanned = { + p: ("dense_layers" if p[1] == "dense_layers" else "layers", _moe_names(p[2:])) + for p in flat + if p[:2] in (("decoder", "dense_layers"), ("decoder", "moe_layers")) + } + owner = {} # 'dense_layers' / 'layers' -> the chunk of each of those layers, in order + if scanned: + if layer_split is None: + raise ValueError( + f'MaxText parameter {"/".join(next(iter(scanned)))} is a scanned layer leaf: give the layer ' "split" + ) + if len(layer_split) != n_chunks: + raise ValueError(f"layer split {list(layer_split)}: {len(layer_split)} chunks, not {n_chunks}") + depth = {} + for p, (kind, rest) in scanned.items(): + n = flat[p].shape[axis(rest)] + if depth.setdefault(kind, n) != n: + raise ValueError( + f'MaxText {kind} leaf {"/".join(rest)} stacks {n} layers on axis {axis(rest)}, its others ' f"{depth[kind]}" + ) + n_dense, n_moe = depth.get("dense_layers", 0), depth.get("layers", 0) + chunk_of = [c for c, n in enumerate(layer_split) for _ in range(n)] + if len(chunk_of) == n_moe: # the MoE layers a chunk, the dense ones in chunk 0 + owner = {"dense_layers": [0] * n_dense, "layers": chunk_of} + elif len(chunk_of) == n_dense + n_moe: # every layer a chunk, in order + owner = {"dense_layers": chunk_of[:n_dense], "layers": chunk_of[n_dense:]} + else: + raise ValueError( + f"MaxText scans {n_moe} MoE layers, the layer split {list(layer_split)} holds " + f"{len(chunk_of)}" + (f" (nor every layer, {n_dense + n_moe} with the {n_dense} dense ones)" if n_dense else "") + ) + for path, v in flat.items(): + if path in scanned: + kind, rest = scanned[path] + layers = np.moveaxis(v, axis(rest), 0) # the layer axis first, the rest in order: a view + for c in range(n_chunks): + mine = [i for i, o in enumerate(owner[kind]) if o == c] + if mine: # a chunk's layers of a kind are consecutive: a slice, a view, no copy + chunks[c]["/".join([kind] + rest)] = layers[mine[0] : mine[-1] + 1] + elif path[:3] == ("decoder", "pipeline_module", "layers"): + rest = _moe_names(path[3:]) + stacked = v if n_chunks > n_stages else v[None] # [repeat, stage, ...]; no repeat axis at V=1 + for c in range(n_chunks): + chunks[c]["/".join(["layers"] + rest)] = stacked[c // n_stages, c % n_stages][None] + elif path[:2] == ("mtp_block", "mtp_layer_1") and path[2].startswith("mtp_1_"): + name = path[2][len("mtp_1_") :] + rest = (["layer"] + _moe_names(path[3:])) if name == "transformer_layer" else [name, *path[3:]] + chunks[-1]["/".join(["mtp"] + rest)] = v + elif path == ("token_embedder", "embedding"): + chunks[0]["token_embedder/embedding"] = v + elif path == ("decoder", "decoder_norm", "scale"): + chunks[-1]["decoder_norm/scale"] = v + elif path == ("decoder", "logits_dense", "kernel"): + chunks[-1]["logits_dense/kernel"] = v + else: + raise ValueError(f'MaxText parameter {"/".join(path)} has no place in a ds_ep chunk') + if any(k.startswith("mtp/") for k in chunks[-1]): + chunks[-1]["mtp/token_embedder/embedding"] = chunks[0]["token_embedder/embedding"] + return chunks + + +def qwen_to_chunks(flat, layer_split, cycle, scan_axis=1): + """A MaxText qwen3_5's params {path tuple: array} (no PP: its scanned blocks, a block's layers as its nested scan + holds them, local_layers + global_layer: maxtext.experimental.mpmd.jax.qwen35.convert) -> ds_ep chunk trees + {'/'-joined path: array}, chunk order, cut by `layer_split` (every layer a chunk; ds_ep_pipeline --layer-split). + Layer l is position l % cycle of block l // cycle; in its chunk it is one subtree (ds_ep.qwen_layer_key) whose + leaves keep a layer axis of one: the common leaves under their names, its mixer -- MaxText's 'attention' -- as + 'gdn', or as 'attn' for a full-attention layer (whose leaves sit under 'attention'/'attention'). Views of + MaxText's arrays wherever a slice is one. A MaxText parameter with no place in a chunk (a vision encoder's, a + decoder-level leaf of a later MaxText, one beside a full-attention layer's inner 'attention', which 'attn' leaves + out) is an error, as in maxtext_to_chunks; a layer's other extra leaf goes to its chunk, where params_from_chunks + reports it.""" + import jax + import numpy as np + from maxtext.experimental.mpmd.jax import ds_ep + from maxtext.experimental.mpmd.jax.qwen35 import convert + + places = {("token_embedder", "embedding"), ("decoder", "decoder_norm", "scale"), ("decoder", "logits_dense", "kernel")} + layer_keys = {"local_layers", "global_layer"} # MaxText's nested scan of a block + for path in flat: + if tuple(path) not in places and not ( + tuple(path[:2]) == ("decoder", "layers") and len(path) > 3 and path[2] in layer_keys + ): + raise ValueError(f'MaxText parameter {"/".join(path)} has no place in a ds_ep chunk') + port = convert.from_flat([(list(p), v) for p, v in flat.items()], scan_axis, asarray=np.asarray) + blocks = port["decoder"]["layers"] + if sorted(blocks) != sorted(f"layer_{i}" for i in range(cycle)): # a nested scan of another length + raise ValueError(f"MaxText's blocks hold {sorted(blocks)}, not a block of {cycle} layers") + n_layers = cycle * jax.tree.leaves(blocks)[0].shape[0] + if sum(layer_split) != n_layers: + raise ValueError(f"layer split {list(layer_split)} holds {sum(layer_split)} layers, MaxText has {n_layers}") + chunks, first = [{} for _ in layer_split], 0 + for c, n in enumerate(layer_split): + for j, l in enumerate(range(first, first + n)): + lw = jax.tree.map(lambda a, b=l // cycle: a[b : b + 1], blocks[f"layer_{l % cycle}"]) # [1, ...]: a view + mixer = lw.pop("attention") + if "attention" in mixer and len(mixer) > 1: # 'attn' is the inner attention alone + raise ValueError( + f"MaxText parameters {sorted('attention/' + k for k in mixer if k != 'attention')} beside " + f"layer {l}'s inner attention have no place in a ds_ep chunk" + ) + lw["attn" if "attention" in mixer else "gdn"] = mixer["attention"] if "attention" in mixer else mixer + for path, v in jax.tree_util.tree_flatten_with_path(lw)[0]: + chunks[c]["/".join(["layers", ds_ep.qwen_layer_key(j)] + [k.key for k in path])] = v + first += n + chunks[0]["token_embedder/embedding"] = port["token_embedder"]["embedding"] + chunks[-1]["decoder_norm/scale"] = port["decoder"]["decoder_norm"]["scale"] + chunks[-1]["logits_dense/kernel"] = port["decoder"]["logits_dense"]["kernel"] + return chunks + + +def nest(flat): + """{'/'-joined path: array} -> nested dicts, the chunk trees ds_ep_pipeline.write_chunk_files takes.""" + tree = {} + for k, v in flat.items(): + *path, leaf = k.split("/") + node = tree + for q in path: + node = node.setdefault(q, {}) + node[leaf] = v + return tree + + +def cmd_init(a): + """MaxText init (CPU is fine: PP=S x FSDP=1 has the PP=S x FSDP=64 shapes; FSDP only shards). Without PP + (ici_pipeline_parallelism=1, the layout of a DP-over-DCN run) on one device, its shapes at any sharding, cut + by --layer-split.""" + import jax + import numpy as np + from flax import nnx + from flax.linen import partitioning as nn_partitioning + from maxtext.common import checkpointing + from maxtext.common.common_types import MODEL_MODE_TRAIN + from maxtext.configs import pyconfig + from maxtext.utils import model_creation_utils + import maxtext + from maxtext.experimental.mpmd.jax import ds_ep_pipeline as dsp + + t0 = time.perf_counter() + log = lambda *x: print(f"[{time.perf_counter() - t0:7.1f}s]", *x, flush=True) + split = tuple(int(n) for n in a.layer_split.split(",")) if a.layer_split else None + qwen = a.model in QWEN_MODELS + if qwen and (a.exact or not split): + sys.exit(f"init --model {a.model}: MaxText without PP, cut by --layer-split (every layer a chunk); not --exact") + kw = dict(QWEN_MODEL, model_name=a.model, **RUN) if qwen else dict(MODEL, **RUN, **(EXACT if a.exact else {})) + kw.update((k, _value(v)) for k, v in (x.split("=", 1) for x in a.overrides)) + S = int(kw.get("ici_pipeline_parallelism", 1)) + if (S == 1) != (split is not None): + sys.exit( + "init: --layer-split goes with ici_pipeline_parallelism=1 (MaxText scans its layers; the split cuts " + "them into ds_ep chunks), and only there (a pipeline is one layer a chunk)" + ) + # Init on whatever devices there are: one per stage, no data / fsdp / expert sharding. + kw.update( + ici_pipeline_parallelism=S, + ici_fsdp_parallelism=1, + ici_expert_parallelism=1, + ici_data_parallelism=1, + dcn_data_parallelism=1, + per_device_batch_size=1, + compile_topology="", + compile_topology_num_slices=-1, + ) + if S > 1: + kw.update(num_pipeline_microbatches=S, pipeline_fsdp_ag_per_repeat=False, pipeline_fsdp_ag_once=False) + else: + kw.pop("custom_mesh_and_rule", None) # the pipeline's mesh rules + if jax.device_count() != S: + sys.exit( + f"init: run with exactly ici_pipeline_parallelism = {S} devices " + f"(XLA_FLAGS=--xla_force_host_platform_device_count={S}), have {jax.device_count()}" + ) + base_yml = os.path.join(os.path.dirname(maxtext.__file__), "configs", "base.yml") + cfg = pyconfig.initialize([sys.argv[0], base_yml], **kw) + if S > 1: + n_chunks = cfg.num_decoder_layers // cfg.num_layers_per_pipeline_stage + log( + f"MaxText {os.path.dirname(maxtext.__file__)}: {cfg.num_decoder_layers} layers, {cfg.num_experts} " + f"experts, {S} stages x {cfg.num_pipeline_repeats} repeats -> {n_chunks} ds_ep chunks; weight_dtype " + f"{cfg.weight_dtype}" + ) + if cfg.num_layers_per_pipeline_stage != 1: + sys.exit("init: ds_ep chunks of one layer need num_layers_per_pipeline_stage=1") + elif qwen: + n_chunks = len(split) + if sum(split) != cfg.num_decoder_layers or not cfg.scan_layers: + sys.exit( + f"init: the layer split holds {sum(split)} layers: MaxText has {cfg.num_decoder_layers}, scanned " + f"(scan_layers {cfg.scan_layers})" + ) + log( + f"MaxText {os.path.dirname(maxtext.__file__)}: {cfg.model_name}, {cfg.num_decoder_layers} layers in blocks " + f"of {cfg.inhomogeneous_layer_cycle_interval}, {cfg.num_experts} experts, use_mrope {cfg.use_mrope}, no PP " + f"(blocks scanned at axis {cfg.param_scan_axis}) -> {n_chunks} ds_ep chunks {list(split)}; weight_dtype " + f"{cfg.weight_dtype}" + ) + else: + n_chunks = len(split) + dense = cfg.first_num_dense_layers + if sum(split) not in (cfg.num_decoder_layers - dense, cfg.num_decoder_layers) or not cfg.scan_layers: + sys.exit( + f"init: the layer split holds {sum(split)} layers: MaxText has {cfg.num_decoder_layers - dense} MoE " + f"layers after {dense} dense, scanned (scan_layers {cfg.scan_layers}): give the MoE layers a chunk or " + "every layer a chunk, as ds_ep_pipeline --layer-split" + ) + log( + f"MaxText {os.path.dirname(maxtext.__file__)}: {cfg.num_decoder_layers} layers ({dense} dense), " + f"{cfg.mtp_num_layers} MTP, {cfg.num_experts} experts, no PP (layers scanned at axis {cfg.param_scan_axis}) " + f"-> {n_chunks} ds_ep chunks {list(split)}; weight_dtype {cfg.weight_dtype}" + ) + create, abstract = model_creation_utils.create_nnx_abstract_model( + cfg, + mesh=None, + devices=jax.devices(), + model_mode=MODEL_MODE_TRAIN, + rng_key=jax.random.PRNGKey(cfg.init_weights_seed), + ) + graphdef, abs_state = nnx.split(abstract) + shardings = jax.tree.map(lambda x: x.sharding, abs_state) + with nn_partitioning.axis_rules(cfg.logical_axis_rules), jax.set_mesh(abstract.mesh): + state = jax.jit(lambda: nnx.state(create()), out_shardings=shardings)() + model = nnx.merge(graphdef, state) + from maxtext.layers.moe import MoEBiasVar + + # What load_parameters_path restores: the parameters and the routed biases, MoEBiasVars (zero at init), + # which its loader looks up in the params collection when the checkpoint has no collection of theirs. + weights = nnx.state(model, nnx.Any(nnx.Param, MoEBiasVar)) + jax.block_until_ready(weights) + log("initialized") + n_params = sum(v.size for _, v in nnx.state(model, nnx.Param).flat_state()) + pure = weights.to_pure_dict() + flat = { + tuple(str(p) for p in k): np.asarray(v.get_value() if hasattr(v, "get_value") else v) + for k, v in weights.flat_state() + } + del weights, state, model + if qwen: # before anything is written + # The cut (views, no copy): a leaf with no place in a chunk (use_multimodal=true's vision encoder, say). + try: + qwen_to_chunks(flat, split, cfg.inhomogeneous_layer_cycle_interval, cfg.param_scan_axis) + except ValueError as e: + sys.exit(f"init --model {a.model}: {e}") + out = a.out.rstrip("/") + for dtype in [None] + list(a.cast): + sfx = f"_{dtype}" if dtype else "" + tree = pure if dtype is None else jax.tree.map(lambda x: x.astype(dtype), pure) + checkpointing.save_params_to_path(f"{out}/maxtext_params{sfx}", {"params": tree}) + log(f"MaxText params checkpoint -> {out}/maxtext_params{sfx}") + del tree + leaves = flat if dtype is None else {k: v.astype(dtype) for k, v in flat.items()} + # Local or gs://, like the checkpoint; the files ds_ep_pipeline --init-from reads. + trees = ( + qwen_to_chunks(leaves, split, cfg.inhomogeneous_layer_cycle_interval, cfg.param_scan_axis) + if qwen + else maxtext_to_chunks(leaves, S, n_chunks, split, cfg.param_scan_axis) + ) + dsp.write_chunk_files(f"{out}/ds_chunks{sfx}", [nest(t) for t in trees]) + log( + f"ds_ep chunk files -> {out}/ds_chunks{sfx}/chunk0..{n_chunks - 1}.npz " + f"({n_params / 1e9:.3f}B parameters, {next(iter(leaves.values())).dtype})" + ) + del leaves + + +# ------------------------------------------------------------------ compare +def read_maxtext_metrics(path): + """MaxText's metrics_file (JSON lines, one per logged step) -> {step: record}.""" + from maxtext.experimental.mpmd.jax import xprof_align + + rows = [json.loads(line) for line in xprof_align.read_bytes(path).decode().splitlines() if line.strip()] + return {int(r["step"]): r for r in rows} + + +def read_ds_ep(path): + from maxtext.experimental.mpmd.jax import xprof_align + + d = json.loads(xprof_align.read_bytes(path)) + if d.get("warmup_gnorms") is None: + sys.exit(f"{path} has no warmup_gnorms (the JSON of an older ds_ep_pipeline): rerun it with this one") + # A load-balance loss rides ds_ep's layer outputs' backward, out of its loss. + aux = (d.get("config") or {}).get("lb_loss_weight", 0) > 0 + return d.get("warmup_losses"), d["warmup_gnorms"], d.get("warmup_gnorms_bf16"), aux + + +def _loss(record, minus_aux): + return float(record["learning/loss"]) - (float(record["learning/moe_lb_loss"]) if minus_aux else 0.0) + + +def compare( + mt, + losses, + gnorms, + gnorms_bf16, + loss_rtol, + loss0_rtol, + gnorm_rtol, + minus_aux=False, + gnorm32_rtol=1e-4, + control=None, + control_factor=3.0, + gnorm32_later_rtol=None, + rs_dtype=None, + grad_dtype=None, + adam_math=None, + weight_dtype=None, +): + """-> (table lines, failures). `minus_aux`: the ds_ep run has a load-balance loss, which is in MaxText's + learning/loss (learning/moe_lb_loss) and not in ds_ep's: compare MaxText's loss without it. A run whose MaxText + norms are all bf16 values (bf16 gradients: MaxText reduces the norm in bf16) is held against ds_ep's norms + rounded to bf16 at `gnorm_rtol` (bf16 ulps), any other against its fp32 norms at `gnorm32_rtol` at step 0 (one + set of weights: the gradient itself) and after at `gnorm32_later_rtol`, by default `gnorm_rtol` (the + trajectories may part): one run, one precision, so an fp32 norm that happens to fall on the bf16 grid is not + taken for a bf16 one. `control`: the + metrics of a MaxText run that computes the same thing another way (another mesh): every step's loss must also + be within `control_factor` x the largest MaxText-vs-control difference of any step. `rs_dtype`, `grad_dtype`, + `weight_dtype`: ds_ep's gradient reduce-scatter dtype, its --grad-dtype (the dtype the reduced gradient enters + AdamW in; None or 'auto': under --adam-math optax the weight's, else rs_dtype) and its weight dtype, to note a + pairing whose precision does not match MaxText's gradients; `adam_math` (--adam-math), to note a ds_ep AdamW + that is not optax's arithmetic, MaxText's.""" + import ml_dtypes + import numpy as np + + noise = None + if control is not None: + keys = ("learning/loss",) + (("learning/moe_lb_loss",) if minus_aux else ()) + usable = lambda r: all(k in r for k in keys) + common = [t for t in control if t in mt and usable(control[t]) and usable(mt[t])] + if not common: + return [], [f'the control run shares no step with the MaxText run (with {" and ".join(keys)})'] + diffs = [abs(_loss(control[t], minus_aux) - _loss(mt[t], minus_aux)) for t in common] + noise = max(diffs) + if not all(math.isfinite(x) for x in diffs) or noise == 0: + return [], [ + f"the control's spread is {noise:.3g}: a control must be finite and differ from MaxText (MaxText " + "is bit-reproducible on one mesh: run the control on another)" + ] + lines = [ + f'step MaxText loss{"-lb" if minus_aux else " "} ds_ep loss rel diff MaxText raw gnorm ' + "ds_ep gnorm (as compared) rel diff" + (" |ds-MT| / control spread" if control else "") + ] + fails, noted, worst = [], False, (0.0, None) + if grad_dtype not in (None, "auto"): + adam_dtype = grad_dtype + elif adam_math == "optax" and weight_dtype: + adam_dtype = weight_dtype # optax takes each gradient in its weight's dtype + else: + adam_dtype = rs_dtype + norms = [ + float(mt[t]["learning/raw_grad_norm"]) for t in range(len(losses)) if t in mt and "learning/raw_grad_norm" in mt[t] + ] + bf16 = all(float(ml_dtypes.bfloat16(x)) == x for x in norms if math.isfinite(x)) + if adam_math not in (None, "optax"): + lines.append( + f" note: ds_ep ran --adam-math {adam_math}, AdamW in fp32 with fp32 constants, where MaxText's " + "optax multiplies its bf16 mu by bf16 b1 (0.8984375): pair --adam-math optax" + ) + for t, (l, g) in enumerate(zip(losses, gnorms)): + if t not in mt: + fails.append(f"step {t}: not in the MaxText metrics") + continue + # MaxText logs no raw_grad_norm under optimizer_memory_host_offload. + want = ("learning/loss", "learning/raw_grad_norm") + (("learning/moe_lb_loss",) if minus_aux else ()) + missing = [k for k in want if k not in mt[t]] + if missing: + fails.append(f'step {t}: MaxText logged no {" or ".join(missing)}') + continue + ml, mg = _loss(mt[t], minus_aux), float(mt[t]["learning/raw_grad_norm"]) + gb = gnorms_bf16[t] if gnorms_bf16 and bf16 else float(np.float32(g)) + if not all(math.isfinite(x) for x in (l, ml, gb, mg)): + fails.append(f"step {t}: not finite (MaxText loss {ml}, gnorm {mg}; ds_ep loss {l}, gnorm {gb})") + continue + dl, dg = abs(l - ml) / max(abs(ml), 1e-30), abs(gb - mg) / max(abs(mg), 1e-30) + ctl = f" {abs(l - ml) / noise:9.1f}" if noise else (" {:>9}".format("-") if control else "") + as_compared = f"bf16 {gb:.6g}" if bf16 and gnorms_bf16 else "fp32" + lines.append(f"{t:4d} {ml:13.7f} {l:13.7f} {dl:9.2e} {mg:17.6g} {g:11.6f} ({as_compared:>11}) {dg:9.2e}{ctl}") + if worst[1] is None or dl > worst[0]: + worst = (dl, t) + if adam_dtype and not noted and (adam_dtype == "bfloat16") != bf16: + noted = True + how = ( + f"reduce-scattered in {rs_dtype}" + if adam_dtype == rs_dtype + else f"took AdamW in {adam_dtype}" + (f" (reduce-scattered in {rs_dtype})" if rs_dtype else "") + ) + lines.append( + f' note: MaxText\'s gradients are {"bf16" if bf16 else "fp32"} (its norm is) and ds_ep ' + f"{how}: such a pairing parts from about the fifth update (see precision)" + ) + if dl > (loss0_rtol if t == 0 else loss_rtol): + fails.append(f"step {t}: loss rel diff {dl:.2e}") + if bf16: + tol = gnorm_rtol + elif t == 0: + tol = gnorm32_rtol + else: + tol = gnorm_rtol if gnorm32_later_rtol is None else gnorm32_later_rtol + if dg > tol: + fails.append(f'step {t}: {"bf16" if bf16 else "fp32"} gnorm rel diff {dg:.2e}') + if control is not None and t not in common: + fails.append(f"step {t}: not in the control run") + elif control is not None and abs(l - ml) > max(control_factor * noise, 1e-7 * abs(ml)): + fails.append( + f"step {t}: loss diff {abs(l - ml):.2e} > {max(control_factor * noise, 1e-7 * abs(ml)):.2e} " + f"({control_factor:g} x the control's spread {noise:.2e}, at least 1e-7 x the loss)" + ) + if worst[1] is not None: + lines.append(f"largest loss rel diff {worst[0]:.2e} (step {worst[1]})") + extra = sorted(t for t in mt if t >= len(losses)) + if extra: + fails.append(f"MaxText steps {extra[0]}..{extra[-1]} are not in the ds_ep run ({len(losses)} warmup steps)") + return lines, fails + + +def ds_ep_config(path): + """The run JSON's config (the ds_ep_pipeline flags) -> dict.""" + from maxtext.experimental.mpmd.jax import xprof_align + + return json.loads(xprof_align.read_bytes(path)).get("config") or {} + + +def cmd_compare(a): + mt = read_maxtext_metrics(a.maxtext_metrics) + losses, gnorms, gnorms_bf16, aux = read_ds_ep(a.ds_ep_json) + if not losses: + sys.exit(f"{a.ds_ep_json} has no warmup losses: take the JSON of the process running the last stage") + control = read_maxtext_metrics(a.control) if a.control else None + cfg = ds_ep_config(a.ds_ep_json) + lines, fails = compare( + mt, + losses, + gnorms, + gnorms_bf16, + a.loss_rtol, + a.loss0_rtol, + a.gnorm_rtol, + minus_aux=aux, + gnorm32_rtol=a.gnorm32_rtol, + control=control, + control_factor=a.control_factor, + gnorm32_later_rtol=a.gnorm32_later_rtol, + rs_dtype=cfg.get("rs_dtype"), + grad_dtype=cfg.get("grad_dtype"), + adam_math=cfg.get("adam_math"), + weight_dtype=cfg.get("weight_dtype"), + ) + print("\n".join(lines)) + print("PASS" if not fails else "FAIL: " + "; ".join(fails)) + return 0 if not fails else 1 + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("init", help="MaxText init -> OUT/maxtext_params and OUT/ds_chunks") + p.add_argument("out") + p.add_argument("overrides", nargs="*", help="MaxText key=value overrides (model shape, stages, repeats)") + p.add_argument("--exact", action="store_true", help="DeepSeek-V3 itself (EXACT), not the sparse prototype") + p.add_argument( + "--model", + default="deepseek3-671b", + choices=("deepseek3-671b",) + QWEN_MODELS, + help="MaxText's model: DeepSeek-V3's sparse prototype (MODEL), or a Qwen3.5-family yml as it is " + "(QWEN_MODEL: ds_ep_pipeline --model of the same name; no PP, --layer-split every layer a " + "chunk), its trainer run with packing=false (ds_ep's Gated DeltaNet takes no segment ids: the module " + "docstring, step 2)", + ) + p.add_argument( + "--layer-split", + default="", + help="without PP (ici_pipeline_parallelism=1): the ds_ep run's --layer-split, its MoE layers a chunk " + "(the dense ones in chunk 0, e.g. 1,1,1,1) or every layer a chunk (e.g. 2,2,1,1)", + ) + p.add_argument( + "--cast", + action="append", + default=[], + metavar="DTYPE", + help="also write the same weights in DTYPE (OUT/maxtext_params_DTYPE, OUT/ds_chunks_DTYPE)", + ) + p = sub.add_parser("compare", help="MaxText's metrics_file vs a ds_ep_pipeline run JSON, per step") + p.add_argument("maxtext_metrics") + p.add_argument("ds_ep_json") + # Defaults from the small-scale measurement above, with headroom for depth 8 and 16 microbatches. + p.add_argument("--loss0-rtol", type=float, default=1e-5) + p.add_argument("--loss-rtol", type=float, default=1e-4) + p.add_argument( + "--gnorm-rtol", + type=float, + default=8e-3, + help="a bf16 MaxText norm: one bf16 ulp is 3.9e-3 to 7.8e-3 " "relative (2^-8 to 2^-7)", + ) + p.add_argument( + "--gnorm32-rtol", + type=float, + default=1e-4, + help="an fp32 MaxText norm (weight_dtype and grad_dtype float32) at step 0: MaxText's bf16 " + "reduce-scatters alone leave 3.3-3.7e-5 against ds_ep --rs-dtype float32, the softmax bias of " + "sa_use_base2_exp 4.9e-4 (5.3e-4 against --rs-dtype bfloat16)", + ) + p.add_argument( + "--gnorm32-later-rtol", + type=float, + default=None, + help="an fp32 MaxText norm after step 0 (default --gnorm-rtol): 3-4e-5 over 20 steps at lr 1e-5; at " + "lr 1e-4 the matched trajectories part, 2e-3 by step 11", + ) + p.add_argument( + "--control", + help="the metrics_file of a MaxText run computing the same thing another way (another " + "mesh): fail a step whose loss is further from MaxText's than --control-factor x the control's spread", + ) + p.add_argument("--control-factor", type=float, default=3.0) + a = ap.parse_args(argv) + return cmd_init(a) if a.cmd == "init" else cmd_compare(a) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/maxtext/experimental/mpmd/jax/mem_probe.py b/src/maxtext/experimental/mpmd/jax/mem_probe.py new file mode 100644 index 0000000000..a03be78944 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/mem_probe.py @@ -0,0 +1,138 @@ +# 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. + +"""Compile a ds_ep_pipeline run's programs on the devices it will run on and price its HBM, without allocating any +state: each program's memory (temporaries, arguments, outputs, aliased; largest temporaries first), then each local +stage's estimated peak -- ds_ep_aot's hbm_walk, what is live when the stage's heaviest program runs, the boundary +inputs waiting on the stage included, plus the programs' code -- against the device's memory (bytes_limit: what the +allocator was given), and what it leaves free. ds_ep_aot does the same for a TPU slice this host does not have, +against a compile-only topology; on GPU a run's own devices compile it. Takes ds_ep_pipeline's flags (with +--distributed, one process a host: each prices its own stages) and --headroom. Under Pathways (JAX_PLATFORMS=proxy) +the Pathways server compiles every stage's programs and the devices report no bytes_limit (memory_stats raises +through the proxy), so the HBM is the device kind's (pathways.HBM_BYTES), or --hbm-gib's; there one client prices +every stage, and the flags only multi-controller JAX takes are refused (ds_ep_pipeline.multi_controller_only). + + python3 -m maxtext.experimental.mpmd.jax.mem_probe --model qwen3.8-2.4t-a95b --stages 2 --ep 4 ... [--distributed] +""" + +import sys + +from maxtext.experimental.mpmd.jax import ds_ep_pipeline as pipe +from maxtext.experimental.mpmd.jax import pathways + + +def stage_line(r): + """A stage's row of ds_ep_aot.report as mem_probe prints it: the estimated peak against the device's memory (less + the headroom asked for), whether it fits and by how much -- what it leaves free, or how far over it is -- and at + which program it peaks, of what.""" + parts = ", ".join( + f'{k[5:-4] if k.startswith("live_") else k[:-4]} {r[k]:.1f}' + for k in ( + "persistent_gib", + "live_weights_gib", + "live_gacc_gib", + "live_grads_gib", + "live_residuals_gib", + "live_inputs_gib", + "live_temp_gib", + "code_gib", + ) + ) + free = r["hbm_gib"] - r["est_peak_gib"] + room = f' less {r["headroom_gib"]:.1f} headroom' if r["headroom_gib"] else "" + margin = f"{free:.1f} GiB free" if free >= 0 else f"{-free:.1f} GiB over" + return ( + f'stage {r["stage"]}: est. peak {r["est_peak_gib"]:.1f} of {r["hbm_gib"]:.1f} GiB{room} ' + f'({"fits" if r["fits"] else "DOES NOT FIT"}, {margin}) at {r["peak_at"]}: {parts}' + ) + + +def device_hbm(devices, given_gib=None): + """The HBM to price against, bytes: `given_gib` (--hbm-gib) if given, else the least bytes_limit of `devices` (0 + where a device keeps no statistics: CPU), or where their backend cannot report any (through the IFRT proxy + memory_stats raises) their kind's (pathways.hbm_bytes) -> (bytes, where it came from).""" + if given_gib is not None: + return int(given_gib * 2**30), "--hbm-gib" + stats = [pathways.memory_stats(d) for d in devices] + if not any(why for _, why in stats): + return min(st.get("bytes_limit", 0) for st, _ in stats), "bytes_limit" + kinds = {d.device_kind for d in devices} + table = [pathways.hbm_bytes(k) for k in kinds] + if table and all(table): + return min(table), f"the device kind's ({', '.join(sorted(map(str, kinds)))}: pathways.HBM_BYTES)" + raise SystemExit( + f"mem_probe: the devices ({', '.join(sorted(map(str, kinds)))}) report no bytes_limit and pathways.HBM_BYTES " + "has no entry for their kind: give --hbm-gib" + ) + + +def main(argv=None): + proxy = pathways.initialize() # under JAX_PLATFORMS=proxy, before any backend starts + ap = pipe.make_parser() + ap.add_argument( + "--headroom", + type=float, + default=0.0, + help="share of the device's memory the estimated peak must leave free to fit (default %(default)s: " + "it fits under the whole bytes_limit). ds_ep_aot keeps 10%% free on TPU for what its walk " + "leaves out there: run-ahead (the next step's first programs), which this estimate leaves out " + "too, and the boundary inputs, which it prices", + ) + ap.add_argument( + "--hbm-gib", + type=float, + default=None, + help="price against this much HBM per device (GiB) instead of the devices' bytes_limit (or, where they report " + "none -- through the IFRT proxy, Pathways -- their kind's, pathways.HBM_BYTES)", + ) + a = ap.parse_args(argv) + if not 0 <= a.headroom < 1: + sys.exit(f"--headroom is a share of the device memory in [0, 1), not {a.headroom}") + if proxy and (bad := pipe.multi_controller_only(a)): + # one client under Pathways: said before the backend starts (and before --distributed's init), in main's words -- + # relay / xfer first, pathways.check_transport's message + raise SystemExit("\n".join(bad)) + if a.distributed: + pipe.init_distributed() + import jax + + p = pipe.build(a) + # each line tagged with its process under multi-controller JAX (each prices its own stages); one controller's not + tag = f"[p{jax.process_index()}] " if p.multi else "" + n, dt = p.precompile() + G = 2**30 + rows = [] + for name, c in p.compiled: + m = c.memory_analysis() + if m is not None: + rows.append((m.temp_size_in_bytes, m.argument_size_in_bytes, m.output_size_in_bytes, m.alias_size_in_bytes, name)) + print(f"{tag}{n} programs compiled in {dt:.1f}s; GiB per device:", flush=True) + for t, ar, o, al, name in sorted(rows, reverse=True): + print( + f"{tag} {name:30s} temp {t / G:7.2f} args {ar / G:7.2f} out {o / G:7.2f} alias {al / G:7.2f}", + flush=True, + ) + from maxtext.experimental.mpmd.jax import ds_ep_aot + + hbm, src = device_hbm(jax.local_devices(), a.hbm_gib) + if src != "bytes_limit": + print(f"{tag}HBM per device {hbm / G:.2f} GiB, {src}", flush=True) + out = ds_ep_aot.report(p, hbm, a.headroom, inputs=True) + for r in out: + print(f"{tag}{stage_line(r)}", flush=True) + return out + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/src/maxtext/experimental/mpmd/jax/pathways.py b/src/maxtext/experimental/mpmd/jax/pathways.py new file mode 100644 index 0000000000..ffee122eb6 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/pathways.py @@ -0,0 +1,450 @@ +# 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 -- single-controller JAX, JAX_PLATFORMS=proxy -- for the MPMD pipeline. + +Under Pathways one Python process, the client (on a GKE Pathways job's head pod, or any VM that reaches the proxy), +drives every device of the job through the IFRT proxy: jax.process_count() is 1 and every device is the client's. +ds_ep_pipeline then takes its one-process path as it is -- every stage local, each stage boundary one IFRT CopyArrays +(transfer.Channel), nothing of the multi-controller machinery -- and this module holds what differs from a TPU VM's +own PJRT client (McJAX), and the checks main makes in every mode, McJAX too (check_bucket, probe_trace_dir): + + is_proxy() the mode, from JAX_PLATFORMS ('proxy' its first platform: jax's default backend), asked before + any backend starts; is_proxy_device(d) asks a device (its client's runtime_type, + 'proxy/pathways') -- the same answer for the devices jax.devices() gives, which + ds_ep_pipeline's Pipeline asks. + check_transport() a --transport the mode cannot take: the relay and xfer move arrays between processes (and + jax.experimental.transfer, xfer's, kills the client) -- ds_ep_pipeline and mem_probe refuse + them through it (ds_ep_pipeline.multi_controller_only) before the backend starts, and + ds_ep_aot --pathways as well (pathways_problems). + initialize() pathwaysutils.initialize(), once, before the first backend use: its profiler patch (Pathways + traces go to gs:// only) and jax's persistent compile cache off (Pathways keeps its own under + the servers' --gcs_scratch_location; jax's is silently inert through the proxy). + server_flags() ... the libtpu / XLA flags: the proxy server compiles, so flags in the client's LIBTPU_INIT_ARGS + reach no compiler. They go to the proxy server, the resource manager and the workers -- + xpk's --custom-pathways-{proxy-server,server,worker}-args (server_args), or the local docker + containers' arguments -- and the same set stays in the client's LIBTPU_INIT_ARGS, which the + pipeline's planning reads (ds_ep_pipeline.libtpu_flag). + hbm_bytes() a device's HBM by its kind: memory_stats() raises through the proxy ("MemoryStats is only + supported for addressable PjRt devices"). + check_bucket() in every mode: a gs:// --profile or --json that names no bucket (gs://, gs:///traces/run: a + `gs://$BUCKET/...` with BUCKET unset), refused before anything starts. + check_trace_dir() a Pathways profile's directory: gs:// only (pathwaysutils refuses others), with a bucket. + probe_trace_dir() in every mode: can this client write into a gs:// --profile (an object written there and + deleted)? main asks before anything starts in a run that traces into one, since a trace + written straight into a bucket that does not exist hangs when it stops, in one McJAX process + too (under Pathways in stop_trace, leaving the proxy refusing the next clients). + trace() a profile: max_num_hosts worker hosts, an explicit session id, and a settle after the start (the + workers' TPU tracer starts late: without it a trace has no device plane); a failure to start or + stop it is a TraceError, which the caller can record and go on. + describe() what provenance records of the mode: the backend, the server build, the image (MPMD_PATHWAYS_IMAGE, + set by the launcher: the client cannot see it). + multi_controller() THE rule for the pipeline's multi-controller logic: several JAX processes, one per host + (jax.distributed), each driving only its own devices? Never under Pathways (one client drives + every device), nor in one host's own process: what exists only for several processes -- every + boundary copy walked in one global order, the key-value store's agreements and barriers, the + relay, xfer and cross-process copies, per-process records and traces -- runs only where it says + yes (ds_ep_pipeline's Pipeline keeps it as `multi`), and its flags are refused under Pathways + before the backend starts (ds_ep_pipeline.multi_controller_only). + +Also different under the proxy, with nothing to do here: host callbacks are UNIMPLEMENTED (the pipeline has none), +device ids change with every client session (the pipeline only orders by them), each new client waits ~10 s for the +worker, and only one client may hold the proxy at a time. + + python3 -m maxtext.experimental.mpmd.jax.pathways flags tpu7x # one line: client LIBTPU_INIT_ARGS, docker args + python3 -m maxtext.experimental.mpmd.jax.pathways flags tpu7x --xpk # xpk's three --custom-pathways-*-args + +Jax-light: imports neither jax nor pathwaysutils at import. +""" + +from __future__ import annotations + +import argparse +import contextlib +import os +import shlex +import sys +import time +import warnings + +# The flag ds_ep_run.sh, ds_ep_aot.sh and ds_ep_multihost.sh add to any libtpu flag set: the FSDP gathers and +# reduce-scatters are collective-permutes folded into the stage programs, and libtpu's default cap on concurrent +# async permutes serializes them. +MPMD_FLAGS = ("--xla_max_concurrent_async_collective_permutes=64",) +# xpk's options that carry flags to each Pathways container (xpk splits each value on single spaces). +SERVER_OPTIONS = ("--custom-pathways-proxy-server-args", "--custom-pathways-server-args", "--custom-pathways-worker-args") +# The platform that selects Pathways (JAX_PLATFORMS=proxy), and the client's runtime_type through the IFRT proxy, +# 'proxy/pathways' ('pjrt_ifrt' on a TPU VM's own client). +PROXY = "proxy" +PROXY_RUNTIME = "proxy/" +# The settle after a trace starts: the Pathways workers' TPU tracer starts late, and a trace stopped within ~1 s of +# its start has no device plane at all (local docker Pathways on tpu7x, images 20261117 and 20261124). +TRACE_SETTLE_S = 1.0 +# A device's HBM, bytes, by its device_kind: what memory_stats()'s bytes_limit reports where it can (the TPU7x one on a +# tpu7x-8, libtpu 0.0.50.1), else what ds_ep_aot.TOPOLOGIES holds (v6e: a v6e-4's bytes_limit; v5p: what XLA compiles +# a v5p-8 program against). Through the proxy memory_stats() raises: mem_probe prices against this. +HBM_BYTES = { + "TPU7x": 101_724_450_816, + "TPU v6 lite": 33_546_041_344, + "TPU v5": 102_786_660_352, # v5p, as libtpu names it + "TPU v5p": 102_786_660_352, # v5p, as Pathways names it +} + +_initialized = False + + +def is_proxy(platforms=None): + """Does this process run on Pathways: is 'proxy' JAX_PLATFORMS's first platform (or `platforms`')? jax makes the + first platform listed its default backend (and fails where a listed one does not start), so this is what + `is_proxy_device` says of the devices jax.devices() gives -- ds_ep_pipeline's Pipeline asks its meshes' devices, + main this, and the two agree. Asked from the environment, so it is known before any backend starts. ('proxy' + further down the list starts the proxy backend beside another default one: pathwaysutils, which asks whether + 'proxy' is anywhere in the list, then patches the profiler of a run whose devices are not the proxy's.)""" + platforms = os.environ.get("JAX_PLATFORMS", "") if platforms is None else platforms + return platforms.split(",")[0].strip().lower() == PROXY + + +def is_proxy_device(d): + """Is device `d` a Pathways device: its client's runtime_type 'proxy/...' (a TPU VM's own client says 'pjrt_ifrt'; + a test's fake device may carry a client that says either).""" + return str(getattr(getattr(d, "client", None), "runtime_type", "")).startswith(PROXY_RUNTIME) + + +def multi_controller(devices=None): + """Is this run multi-controller JAX -- several processes, one per host (jax.distributed), each driving only its own + devices: jax.process_count() > 1? Given `devices`: are they several processes' (a multi-controller run's, or a + compile-only topology's hosts: ds_ep_aot), not one client's? + + The one predicate for the pipeline's multi-controller logic: walking every boundary copy in one global order (an + op of another process's stage copies, its own runs), the key-value store's agreements and barriers, the relay, + xfer and cross-process copies, per-process records and traces. It runs where this says yes and nowhere else. + Under Pathways the answer is no: one client process drives every device (jax.process_count() is 1), so none of + that runs there, not even as a walk that finds nothing to do -- and a proxy reporting several processes would + break that premise: refused (RuntimeError). A one-host run on its own PJRT client is single-controller too. Ask + it once jax.distributed is up: before jax.distributed.initialize every process counts one. Devices: the IFRT + proxy's are one client's (unwalked); others, by their process_index.""" + if devices is not None: + devs = list(devices) + return bool(devs) and not is_proxy_device(devs[0]) and len({d.process_index for d in devs}) > 1 + import jax # pylint: disable=import-outside-toplevel + + n = jax.process_count() + if n > 1 and is_proxy(): + raise RuntimeError( + f"JAX_PLATFORMS=proxy (Pathways) reports {n} processes: a Pathways run is one client process driving every " + "device, which the pipeline's single-controller path assumes (its multi-controller paths -- key-value " + "agreements, barriers, cross-process copies -- are not for a proxy)" + ) + return n > 1 + + +def check_transport(transport): + """Raise ValueError for a --transport a Pathways run cannot take: the relay and xfer move arrays between processes + (--distributed), and under Pathways one client process drives every device. ds_ep_pipeline.main and mem_probe ask + it before the backend starts (through ds_ep_pipeline.multi_controller_only), and ds_ep_aot --pathways + (pathways_problems): the Pipeline would say only after the start that they need --distributed, which Pathways + refuses too. The message's one copy.""" + if transport in ("relay", "xfer"): + raise ValueError( + f"--transport {transport}: under Pathways (JAX_PLATFORMS=proxy) one client process drives every device, " + "and the relay and xfer move arrays between processes (--distributed): use --transport native (each " + "boundary one IFRT CopyArrays, device to device) or ppermute (collective-permute programs)" + ) + + +def initialize(): + """Under JAX_PLATFORMS=proxy: pathwaysutils.initialize(), once -> True; else nothing -> False. + + Call it before the first backend use. It patches jax's profiler (start_trace, stop_trace and trace also start the + Pathways workers' trace; they then take only gs:// directories) and turns jax's persistent compile cache off, which + through the proxy writes nothing anyway: Pathways caches compiled programs under the servers' + --gcs_scratch_location. jax >= 0.12 registers the proxy backend itself, so where the backends are up already (a + test session that touched jax first) only the patch and the cache switch apply. Without pathwaysutils the run goes + on, with a warning: only a --profile then fails (trace says why).""" + global _initialized + if not is_proxy(): + return False + if _initialized: + return True + try: + import pathwaysutils # pylint: disable=import-outside-toplevel + except ImportError: + warnings.warn( + "JAX_PLATFORMS=proxy without pathwaysutils (pip install 'pathwaysutils>=0.1.14'): jax's own proxy backend " + "runs, but a profile records no Pathways worker", + RuntimeWarning, + ) + _initialized = True + return True + import jax # pylint: disable=import-outside-toplevel + from jax._src import xla_bridge # pylint: disable=import-outside-toplevel + + if xla_bridge.backends_are_initialized(): + from pathwaysutils import profiling as pw_profiling # pylint: disable=import-outside-toplevel + + pw_profiling.monkey_patch_jax() + jax.config.update("jax_enable_compilation_cache", False) + else: + pathwaysutils.initialize() + _initialized = True + return True + + +# ------------------------------------------------------------------------------------------------- flags +def flags_dir(): + """The package's libtpu flag sets: libtpu_flags/.flags, one flag a line, '#' starting a comment.""" + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "libtpu_flags") + + +def flag_sets(): + """The names of the flag sets there, sorted.""" + return sorted(f[: -len(".flags")] for f in os.listdir(flags_dir()) if f.endswith(".flags")) + + +def read_flag_set(name): + """The flags of set `name` (libtpu_flags/.flags) -> [flag], in file order: what the launchers read + (ds_ep_run.sh: '#' starts a comment, a flag a word).""" + path = os.path.join(flags_dir(), f"{name}.flags") + if "/" in name or not os.path.isfile(path): + raise ValueError(f"no libtpu flag set {name!r}: the sets are {flag_sets()} ({flags_dir()})") + with open(path, encoding="utf-8") as f: + return [tok for line in f for tok in line.split("#", 1)[0].split()] + + +def server_flags(flag_set="tpu7x", extra=()): + """The flags a Pathways run gives its servers -> [flag]: set `flag_set`'s (None: none), the launchers' MPMD_FLAGS, + then `extra` (flags, or strings of them), each flag once -- a later mention of a flag (the text before its '=') + replaces an earlier one's value in its place, as libtpu's last mention wins.""" + out = {} + for tok in [*(read_flag_set(flag_set) if flag_set else ()), *MPMD_FLAGS, *(t for e in extra for t in str(e).split())]: + if not tok.startswith("-"): + raise ValueError(f"{tok!r} is not a flag (--name or --name=value)") + out[tok.split("=", 1)[0]] = tok + return list(out.values()) + + +def joined(flags): + """`flags` as one argument value: single spaces, no empty token, nothing a split on ' ' would cut wrongly -- xpk + splits each --custom-pathways-*-args value on ' ', so a doubled or trailing space would make an empty argument.""" + for f in flags: + if not f or f != "".join(f.split()): + raise ValueError(f"flag {f!r}: empty or holding whitespace, which a split on ' ' would cut") + return " ".join(flags) + + +def server_args(flags): + """xpk's options for `flags` -> {option: value}: the same flags to the proxy server (it compiles every program), + the resource manager and the workers (SERVER_OPTIONS).""" + value = joined(flags) + return {opt: value for opt in SERVER_OPTIONS} + + +def client_flags_note(flags=None): + """A line for a Pathways run whose client sets libtpu flags (LIBTPU_INIT_ARGS, or `flags`) beyond jax's own launch + barrier one, else None: they configure no compiler here, only the pipeline's planning reads them.""" + flags = os.environ.get("LIBTPU_INIT_ARGS", "") if flags is None else flags + own = {"--xla_tpu_use_enhanced_launch_barrier=true"} # jax's cloud TPU init adds it wherever libtpu is installed + mine = [f for f in flags.split() if f not in own] + if not mine: + return None + return ( + f"note: LIBTPU_INIT_ARGS sets {len(mine)} flag(s) in this client: under Pathways the proxy server compiles, so " + "they reach no compiler; the plan reads them (ds_ep_pipeline.libtpu_flag) -- give the servers the same set " + "(python3 -m maxtext.experimental.mpmd.jax.pathways flags SET --xpk; README.md, Pathways)" + ) + + +# ------------------------------------------------------------------------------------------------- devices +def hbm_bytes(device_kind): + """HBM per device of `device_kind`, bytes (HBM_BYTES), or None for a kind not in the table.""" + return HBM_BYTES.get(str(device_kind)) + + +def memory_stats(d): + """d.memory_stats() -> (stats or {}, None), or ({}, why) where the backend keeps none: the IFRT proxy raises.""" + try: + return d.memory_stats() or {}, None + # through the IFRT proxy a JaxRuntimeError, INVALID_ARGUMENT + except Exception as e: # pylint: disable=broad-exception-caught + return {}, f"{type(e).__name__}: {' '.join(str(e).split())[:160]}" + + +# ------------------------------------------------------------------------------------------------- profiling +class TraceError(RuntimeError): + """A Pathways trace that did not start or did not stop (`trace`): the profile is lost, the steps it timed are not.""" + + +def check_bucket(path, flag="--profile"): + """Raise ValueError, naming `flag`, where `path` is a gs:// URL that names no bucket: gs://, or gs:///traces/run (a + `gs://$BUCKET/traces/run` with BUCKET unset). Nothing can be written there, and nothing else says so in time: jax + exports a trace into gs:// to the bucket 'plugins' (/plugins/profile/), the write probe joined onto + gs:// wrote a local directory 'gs:' and passed, and a record fails only when it is written (google-cloud-storage's + IndexError on an empty bucket name).""" + if str(path).startswith("gs://") and not str(path)[5:].split("/", 1)[0]: + raise ValueError(f"{flag} {path}: no bucket name (gs://BUCKET/...)") + + +def check_trace_dir(path): + """Raise ValueError unless `path` is a gs:// directory with a bucket (check_bucket), the only kind a Pathways trace + writes to (the workers write their device planes there, the client its own).""" + if not str(path).startswith("gs://"): + raise ValueError( + f"--profile {path}: under Pathways a trace goes to a gs:// directory (the Pathways workers write their device " + "planes there; pathwaysutils refuses any other)" + ) + check_bucket(path) + + +def storage_error(e): + """A storage error in one line: ' : ' for a google.api_core error, whose + str() carries the response's whole JSON body (the message is its error.message), else ': '.""" + msg = None + try: + msg = e.response.json()["error"]["message"] + except Exception: # pylint: disable=broad-exception-caught (no response, not JSON, or another shape) + pass + code = getattr(e, "code", None) + head = f"{type(e).__name__} {code}" if isinstance(code, int) else type(e).__name__ + return f"{head}: {' '.join(str(msg or e).split())[:400]}" + + +def probe_trace_dir(path): + """Write a small object into gs:// directory `path` and delete it -> None where the write works (a failed delete + only warns: a bucket that takes writes but not deletes still takes a trace); else raise ValueError with the storage + error (storage_error). A trace written straight into a directory nobody can write -- a bucket that does not exist + -- hangs when it stops: under Pathways the client waits on stop_trace's future without end and the proxy refuses + the next clients until it restarts (pathwaysutils 0.1.14, images 20261117 and 20261124); in one McJAX process + jax's profiler waits in export_profile_data. Call it before anything starts, as check_trace_dir. It checks the + client's access only: the Pathways servers write the device planes with credentials of their own. Without + google-cloud-storage it cannot check: a warning, and no error. A gs:// URL that names no bucket is a ValueError + before any write (check_bucket).""" + # jax-light, as this module + from maxtext.experimental.mpmd.jax import xprof_align # pylint: disable=import-outside-toplevel + + check_bucket(path) + obj = f'{str(path).rstrip("/")}/.mpmd_write_probe.{os.getpid()}.{time.time_ns()}' + try: + xprof_align.write_bytes(obj, b"mpmd: can this client write here?\n") + except ImportError as e: # google-cloud-storage missing: --json gs:// would fail too, a trace may not + warnings.warn(f"--profile {path}: not checked that this client can write there ({e})", RuntimeWarning) + return + # google.api_core / google.auth errors are no OSError, and the bucket's absence is one of them + except Exception as e: # pylint: disable=broad-exception-caught + raise ValueError( + f"--profile {path}: this client cannot write there ({storage_error(e)}); a trace into it would hang when it " + "stops (under Pathways leaving the proxy refusing the next clients)" + ) from None + try: + xprof_align.delete(obj) + except Exception as e: # pylint: disable=broad-exception-caught + warnings.warn(f"--profile {path}: could not delete the write probe {obj} ({storage_error(e)})", RuntimeWarning) + + +def session_id(when=None): + """A trace session's name as jax and pathwaysutils make one: `when` (seconds since the epoch; None: now) to the + second, in this host's local time. XProf sorts a logdir's sessions by it, and so does xprof.find_xplane: every + session this code names (a Pathways one; the multi-controller one, ds_ep_pipeline.shared_profile_session) is named + here, in the time zone jax names its own in -- the zone TZ or /etc/localtime names (a TZ that is a POSIX rule, not + a zone's name -- PST8, say -- jax takes for UTC).""" + return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(when)) + + +@contextlib.contextmanager +def trace(log_dir, profiler_options=None, max_num_hosts=1, settle_s=TRACE_SETTLE_S): + """A Pathways trace of the body into gs:// `log_dir`: the client's own and up to `max_num_hosts` worker hosts' -- + pathwaysutils' start_trace (whose request carries `profiler_options`' advanced configuration, the chip and + SparseCore trims, and its session_id) -- then `settle_s` of sleep before the body, so the workers' TPU tracers are + recording when the first program runs; stop_trace when the body ends, whatever way. The session's files land in + `log_dir`/plugins/profile//. + + A trace that does not start (the body then does not run) or does not stop is a TraceError, and the body's own + error stays its own: where the body raised, a stop_trace failure is only a note on that error. pathwaysutils is + needed (a TraceError without it).""" + check_trace_dir(log_dir) + try: + from pathwaysutils import profiling as pw_profiling # pylint: disable=import-outside-toplevel + except ImportError as e: + raise TraceError( + "--profile under Pathways needs pathwaysutils >= 0.1.14 (it asks the workers for their trace)" + ) from e + try: + pw_profiling.start_trace(str(log_dir), profiler_options=profiler_options, max_num_hosts=max_num_hosts) + except Exception as e: # pylint: disable=broad-exception-caught (a RuntimeError, or the backend's own) + raise TraceError(f"the trace did not start ({type(e).__name__}: {e})") from e + try: + time.sleep(settle_s) + yield + except BaseException as body: + try: + pw_profiling.stop_trace() + except Exception as e: # pylint: disable=broad-exception-caught + body.add_note(f"and stopping the Pathways trace failed: {type(e).__name__}: {e}") + raise + try: + pw_profiling.stop_trace() + except Exception as e: # pylint: disable=broad-exception-caught + raise TraceError(f"the trace did not stop ({type(e).__name__}: {e})") from e + + +# ------------------------------------------------------------------------------------------------- provenance +def describe(backend=None): + """The mode as provenance records it -> {'backend', 'server', 'image'}: the client's runtime type and the server's + platform version (`backend`: the jax client, default jax's), and the image, MPMD_PATHWAYS_IMAGE (the launcher's: + the client has no way to see it), None where unset.""" + if backend is None: + import jax # pylint: disable=import-outside-toplevel + + backend = jax.devices()[0].client + return { + "backend": str(getattr(backend, "runtime_type", "?")), + "server": " ".join(str(getattr(backend, "platform_version", "?")).split()), + "image": os.environ.get("MPMD_PATHWAYS_IMAGE") or None, + } + + +# ------------------------------------------------------------------------------------------------- command line +def main(argv=None): + ap = argparse.ArgumentParser( + prog="python3 -m maxtext.experimental.mpmd.jax.pathways", + description="The libtpu / XLA flags of a Pathways run, for its servers (and the client's LIBTPU_INIT_ARGS).", + ) + sub = ap.add_subparsers(dest="cmd", required=True) + f = sub.add_parser("flags", help="a flag set (libtpu_flags/.flags) plus the launchers' MPMD flags") + f.add_argument("set", help=f"the flag set: one of {flag_sets()}, or none") + f.add_argument( + "--extra", + action="append", + default=[], + help="more flags after the set's, a string of them: --extra='--xla_a=1 --xla_b=2' (with '=': a value that " + "starts with '--')", + ) + f.add_argument( + "--xpk", + action="store_true", + help="print xpk's three --custom-pathways-*-args options, shell-quoted, instead of one line of flags", + ) + a = ap.parse_args(argv) + try: + flags = server_flags(None if a.set == "none" else a.set, a.extra) + except ValueError as e: + raise SystemExit(f"pathways flags: {e}") from None + if a.xpk: + print(" ".join(f"{opt}={shlex.quote(v)}" for opt, v in server_args(flags).items())) + else: + print(joined(flags)) + return flags + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/src/maxtext/experimental/mpmd/jax/profiling.py b/src/maxtext/experimental/mpmd/jax/profiling.py new file mode 100644 index 0000000000..fa1e448a3d --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/profiling.py @@ -0,0 +1,98 @@ +# 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 MPMD pipeline's profiling defaults: one TPU, one SparseCore and one SparseCore tile a traced host, and the +hosts named in pipeline-stage order. + +Every profile the pipeline takes for XProf traces the first CHIPS chips of each traced process (one TPU a slice where +one host a slice traces), with SPARSECORE_TRIM; a MaxText run gets the same trace from the config overrides +MAXTEXT_ARGS. --profile-chips N traces more: a process holding several pipeline stages shows only its first chip's +otherwise (under Pathways, where a traced worker host holds several stages, every chip is the default: EVERY_CHIP). +XProf lays a session's hosts out sorted by name, so trace_label zero-pads the stage and process numbers. The module +imports no other module of the package, and jax only inside profile_options. +""" + +from __future__ import annotations + +import argparse + +# one TPU a traced process: a host's four tpu7x chips made a 1.5-1.7 GB xplane of two DeepSeek-V3 steps +CHIPS = 1 +# every chip of a traced process (no tpu_num_chips_to_profile_per_task): the default under Pathways, where no process +# is a stage's own and a traced worker host holds several stages' chips +EVERY_CHIP = "all" +# one SparseCore and one tile a chip: their traces fill the device trace buffer in ~0.6 s otherwise +SPARSECORE_TRIM = {"tpu_num_sparse_cores_to_trace": 1, "tpu_num_sparse_core_tiles_to_trace": 1} +# the same trace from MaxText's profiler (they act only with profiler=xplane) +MAXTEXT_ARGS = ( + "enable_tpu_profiling_options=true", + f"tpu_num_chips_to_profile_per_task={CHIPS}", + *(f"{k}={v}" for k, v in SPARSECORE_TRIM.items()), +) + + +def padded(i, n): + """i zero-padded to the width of n - 1 (no padding below ten).""" + return f"{i:0{len(str(max(n - 1, 0)))}d}" + + +def trace_label(stage, process, n_stages, n_processes, host): + """s-p-, padded; sidle for stage None (a process holding none).""" + s = "idle" if stage is None else padded(stage, n_stages) + return f"s{s}-p{padded(process, n_processes)}-{host}" + + +def positive_int(s): + n = int(s) + if n < 1: + raise argparse.ArgumentTypeError(f"at least 1, not {n}") + return n + + +def chip_count(s): + """--profile-chips's type: a count of one or more, or 'all' (EVERY_CHIP).""" + return EVERY_CHIP if s == EVERY_CHIP else positive_int(s) + + +# A GPU trace's CUPTI caps: jax's defaults drop the kernels of a long pipeline step (a DeepSeek-V3 stage launches +# ~10^5 a step), and an event dropped is a gap in the timeline xprof.py reads. +GPU_EVENT_CAPS = {"gpu_max_activity_api_events": 1 << 24, "gpu_max_callback_api_events": 1 << 24} +GPU_PLATFORMS = ("gpu", "cuda", "rocm") + + +def profile_options(chips=None, platform=None, **attrs): + """jax.profiler.ProfileOptions for the first `chips` chips (None: CHIPS; EVERY_CHIP: all of them) of the traced + process; `attrs` set other fields (host_tracer_level=2, session_id=...). + + TPU (platform None or 'tpu'): libtpu's tpu_num_chips_to_profile_per_task, trimmed by SPARSECORE_TRIM. GPU + (`platform` 'gpu' / 'cuda' / 'rocm', a device's .platform): CUPTI's own keys -- gpu_num_chips_to_profile_per_task + and GPU_EVENT_CAPS -- and no Python tracer (it times every Python call of the host-bound MPMD driver). The GPU + tracer refuses any key it does not know, the TPU ones among them, and then records no device at all (jax's + raise_error_on_start_failure is off by default), so the platform must be right.""" + chips = CHIPS if chips is None else chips + if chips != EVERY_CHIP and chips < 1: + raise ValueError(f"at least one chip, not {chips}") + import jax + + o = jax.profiler.ProfileOptions() + if platform in GPU_PLATFORMS: + n = {} if chips == EVERY_CHIP else {"gpu_num_chips_to_profile_per_task": chips} + o.advanced_configuration = {**n, **GPU_EVENT_CAPS} + o.python_tracer_level = 0 + else: + n = {} if chips == EVERY_CHIP else {"tpu_num_chips_to_profile_per_task": chips} + o.advanced_configuration = {**n, **SPARSECORE_TRIM} + for k, v in attrs.items(): + setattr(o, k, v) + return o diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/__init__.py b/src/maxtext/experimental/mpmd/jax/qwen35/__init__.py new file mode 100644 index 0000000000..f820e495d8 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/__init__.py @@ -0,0 +1,61 @@ +# 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. + +"""Pure-JAX Qwen3.5 text decoder (MaxText `decoder_block: qwen3_5`). + + config.py Qwen35Config (with `shard`, a ShardPolicy, and `gdn_core`), + tiny / qwen35_397b / qwen35_35b, from_maxtext; DeepSeek's + shared-config Protocol + _ops.py every sharding-sensitive call site (one small function each), + through src/maxtext/experimental/mpmd/jax/sharding_mode.py + layers.py zero-centred / plain RMSNorm (both `norm_numerics`) + gdn.py Gated DeltaNet: causal conv, chunked gated delta rule with a + custom-VJP unit-lower-triangular inverse, the layer + attention.py gated full attention + MaxText's two rotary embeddings, by + use_mrope: the text mRoPE (Qwen3.5's ymls) and the partial + RoPE (PartialRotaryEmbedding: Qwen3.8-2.4T's) + moe.py softmax-top-k router, routed experts, sigmoid-gated shared expert + model.py decoder layer, 4-layer block scan with block/layer remat, + forward, parameter avals + init.py parameter init by MaxText's rules where they shape the math + train.py loss and train step (the DeepSeek port's trainer pieces) + convert.py MaxText NNX state -> parameter tree (either MaxText layout) + +Same style as `src/maxtext/experimental/mpmd/jax/deepseek/`: plain functions over parameter pytrees and a +frozen config. The MPMD pipeline that runs these layers is +`src/maxtext/experimental/mpmd/jax/ds_ep_pipeline.py` (`--model qwen3.8-2.4t-a95b`; its +`ds_ep.qwen_mixer_part` calls this package's mixers and norms). The model +traces with no mesh, under an Auto stage mesh and under an Explicit one +(`qwen35_explicit_test`). The tests are +`tests/unit/mpmd_test/qwen35_*_test.py`; +`qwen35_maxtext_parity_test` (scheduled_only: MaxText's scheduled CI runs it) holds +the port to MaxText's own `qwen3_5` model: bf16 forward logits bit-exact +(`megablox=false`), fp32 forward logits to 1e-6 and fp32 gradients to +max(1e-5, 4 x a measured floor), and the GDN's pieces bit for bit against +MaxText's own functions. + +Semantics follow MaxText where it differs from HF: the mRoPE keeps fp32 +cos/sin (the partial RoPE rounds them to the activation dtype, as HF does), +the GDN rounds as MaxText does (`gdn.py`), and padding (segment 0) is zeroed +after the GDN's input projections (HF zeroes padded hidden states first). +Packed documents: attention masks across segments, and so does the GDN -- +its conv window and recurrent state restart at every document -- under +`Qwen35Config.gdn_packing`, MaxText's `packing` (its default); without it +they run on across documents. `config.from_maxtext` reads the GDN's two +MaxText options (`gdn_packing`, `gdn_chunk_inverse`) off the MaxText config, +and takes how the two RMSNorm kinds round as a parameter (`norm_numerics`: +'fp32', the default, is MaxText's since 2026-09-10; 'bf16' is MaxText's before +then, which the port was first written against -- neither is HF's: HF's +zero-centred norm rounds as 'fp32' does, its GDN gated norm as 'bf16' does). +""" diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/_ops.py b/src/maxtext/experimental/mpmd/jax/qwen35/_ops.py new file mode 100644 index 0000000000..cf0e6b8913 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/_ops.py @@ -0,0 +1,285 @@ +# 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. + +"""Every sharding-sensitive call site of the Qwen3.5 port, one small function each. + +The model modules (`layers`, `gdn`, `attention`, `moe`, `model`) never touch a +weight, gather an embedding, start a scan carry, regroup heads, run the conv, +dispatch the MoE, place the GDN core or call an attention kernel except +through this module, and make no sharding call (`reshard`, +`with_sharding_constraint`, `out_sharding=`, `shard_map`, `auto_axes`) of +their own; `qwen35_model_test.CallSiteTest` enforces both, and +`qwen35_explicit_test.OpsCallSiteTest` that this module's own sharding calls +are `mode`'s. The bodies here go through +`src/maxtext/experimental/mpmd/jax/sharding_mode.py` (whose docstring has the modes and the +three helper groups), as the DeepSeek port's do, so that + + * under auto -- and with no mesh at all -- every body is the plain + expression the port traced before these bodies existed: the same auto + program, byte for byte (a canonical-HLO A/B showed it when they came in); + * under explicit every value the model makes has a type, which is what + lets the same code trace there; + * `config.gdn_core='manual'` forces the SAME per-device GDN core in both + modes, so an auto-vs-explicit comparison compares typing. + +What explicit needs here, found by probing an Explicit mesh with batch- +sharded activations (jax 0.10.2 / 0.11 / 0.12): an FSDP weight sharded on an +output dim needs a gather or an `out_sharding` (DeepSeek's +`dense_general`); the GDN head regroup reshape (E3) and the scan carry (E2) +need a type; a weight used elementwise (A_log, dt_bias, the conv kernel) must +be replicated; the embedding gather needs `out_sharding`; the MoE global +argsort cannot run on a batch-sharded axis (DeepSeek's dispatch); and +`solve_triangular`'s VJP is not explicit-clean, hence the custom-VJP inverse +in `gdn.py` (E1, used in EVERY mode), whose two typing points are below. + +The wrappers around `maxtext.experimental.mpmd.jax.deepseek` functions (`dense`, `mlp`, `norm`, +`embed`, `routed_experts`, `attention`) are converted on the DeepSeek side; +here they only mark where Qwen depends on them. +""" + +from __future__ import annotations + +import jax +import jax.numpy as jnp +from jax.sharding import PartitionSpec as P + +from maxtext.experimental.mpmd.jax.deepseek import attention as ds_attention +from maxtext.experimental.mpmd.jax.deepseek import layers as ds_layers +from maxtext.experimental.mpmd.jax.deepseek import moe as ds_moe +from maxtext.experimental.mpmd.jax import sharding_mode as mode + + +# ------------------------------------------------------------------ weights +def use_weight(w, dtype, config): + """A weight used by a matmul-like op (norm scales, the router kernel): cast + to `dtype`, its storage sharding left to the consuming op's `out_spec`. + """ + del config + return jnp.asarray(w, dtype) + + +def small_weight(w, dtype, config): + """A weight used ELEMENTWISE against activations: GDN `A_log`, `dt_bias`, + and the depthwise conv kernel. + + `use_weight`, then replicated under explicit: a broadcasting multiply has + no `out_sharding`, an FSDP-sharded `[Hv]` against a batch-sharded + `[B, S, Hv]` would put one mesh axis on two dims, and a channel-sharded + conv kernel is rejected outright. A few KB per layer. A type obligation + (`mode.retype`): auto and none emit nothing beyond the cast. + """ + return mode.retype(use_weight(w, dtype, config), P()) + + +def dense(params, x, config, axis=(-1,)): + """Every projection (`in_proj_*`, `out_proj`, q/k/v/out, shared-expert gate, + head): `maxtext.experimental.mpmd.jax.deepseek.layers.dense_general` (weights cast to `dtype` right + before the dot, MaxText's rule; then `dot_general(out_spec=act)`).""" + return ds_layers.dense_general(params, x, config, axis) + + +def mlp(params, x, config): + """The shared expert: `maxtext.experimental.mpmd.jax.deepseek.layers.mlp_block` (SwiGLU).""" + return ds_layers.mlp_block(params, x, config) + + +def norm(params, x, config): + """Plain RMSNorm, `maxtext.experimental.mpmd.jax.deepseek.layers.rms_norm` -- the normalised value + rounded to `dtype`, then a `dtype` scale multiply: both norm kinds under + `norm_numerics='bf16'` (the zero-centred ones once `layers.rms_norm` has + folded the `+ 1` into the scale). The scale realignment against a + batch-sharded activation is DeepSeek's (the cast + `einsum(out_spec=act)`).""" + return ds_layers.rms_norm(params, x, config) + + +def norm_fp32(params, x, config): + """RMSNorm with the scale multiply in fp32, NOT rounded: `fp32(x) * rsqrt( + mean(fp32(x)^2) + eps) * fp32(scale)`, as MaxText's RMSNorm computes it with a + `scale_offset` (zero-centred) or with `dtype=float32` (the GDN gated norm's + inner norm) since 2026-09-10 -- both norm kinds under `norm_numerics='fp32'`. + The caller rounds (after the `silu(z)` gate, for the gated norm). + + DeepSeek's `rms_norm` conversion, in fp32: the scale through `use_weight`, + the multiply an einsum typed like the activation (the FSDP-sharded scale + would otherwise put the stage's mesh axis on the batch AND the features), + at `matmul_precision` (`precision_or_none`: None, as before, at 'default'). + """ + x = jnp.asarray(x, jnp.float32) + mean2 = jnp.mean(jax.lax.square(x), axis=-1, keepdims=True) + y = x * jax.lax.rsqrt(mean2 + config.normalization_layer_epsilon) + scale = use_weight(params["scale"], jnp.float32, config) + return mode.einsum( + "...k,k->...k", y, scale, out_spec=mode.act_spec(y.ndim), precision=ds_layers.precision_or_none(config) + ) + + +def dot_general(lhs, rhs, dimension_numbers, *, precision, preferred_element_type=None): + """The router logits `x @ gate.kernel` (batch on lhs axis 0), typed like the + activation: the kernel can be FSDP-sharded on its expert (output) axis.""" + (lc, _), (lb, _) = dimension_numbers + out_ndim = lhs.ndim + rhs.ndim - 2 * len(lc) - len(lb) + return mode.dot_general( + lhs, + rhs, + dimension_numbers, + out_spec=mode.act_spec(out_ndim), + precision=precision, + preferred_element_type=preferred_element_type, + ) + + +# --------------------------------------------------------------- activations +def embed(params, tokens, config): + """The token embedding gather: `maxtext.experimental.mpmd.jax.deepseek.layers.embed_lookup` + (`mode.take(table, ids, out_spec=act)`).""" + return ds_layers.embed_lookup(params, tokens, config) + + +def zeros(shape, dtype, *, batch_dim=0): + """A fresh `lax.scan` carry (the GDN state `[B, Hv, Dk, Dv]`), E2. + + `mode.zeros`, typed like the activation under explicit: a scan's carry must + have one type on the way in and out, and a replicated init against a + batch-sharded update would make them differ. + """ + return mode.zeros(shape, dtype, mode.act_spec(len(shape), batch_dim)) + + +def regroup(x, shape, *, batch_dim=0): + """The GDN per-key-head -> per-value-head regroup `[B,S,Hk,Vpk*D] -> [B,S,Hv,D]` + (and `[B,S,Hk,Vpk] -> [B,S,Hv]`), which splits one axis and merges it with + another, E3: explicit rejects that reshape without an `out_sharding`, so it + gets the activation's (`mode.out_sharding`; under auto/none the plain + reshape).""" + sh = mode.out_sharding(mode.act_spec(len(shape), batch_dim)) + if sh is None: + return x.reshape(shape) + return jnp.reshape(x, shape, out_sharding=sh) + + +def broadcast_like(x, like): + """`jnp.broadcast_to(x, like.shape)`, typed like `like`: the identity of the + GDN inverse's forward in the custom VJP (E1) -- the triangular solve's RHS, + the block doubling's starting inverse. + + The type comes from `like`'s own aval (`mode.sharding_of`: typed exactly + like `like`, which `mode.bwd_out_sharding`, a cotangent's type, is not for + a reduced or unreduced value), the rule for custom-VJP code: a replicated + RHS against a batch-sharded matrix breaks the batched solve's vmap under + explicit. + """ + sh = mode.sharding_of(like) + if sh is None: + return jnp.broadcast_to(x, like.shape) + return jnp.broadcast_to(x, like.shape, out_sharding=sh) + + +def retype_like(x, like): + """A custom-VJP cotangent, typed as its primal's cotangent (the GDN + inverse's backward, E1): `mode.retype_like`, which emits nothing when the + types agree and nothing at all under auto.""" + return mode.retype_like(x, like) + + +def conv_general_dilated(lhs, rhs, *, window_strides, padding, dimension_numbers, feature_group_count, precision): + """The GDN depthwise causal conv (batch on axis 0 of `lhs` and the output). + + The kernel comes in through `small_weight`, i.e. replicated under explicit, + which is all the conv's sharding rule needs; the result is batch-sharded + like `lhs`. No `out_sharding` is passed in any mode. + """ + return jax.lax.conv_general_dilated( + lhs, + rhs, + window_strides=window_strides, + padding=padding, + dimension_numbers=dimension_numbers, + feature_group_count=feature_group_count, + precision=precision, + ) + + +def segment_cumsum(mask, g): + """The packed GDN's per-document cumulative decay, `einsum('bnhij,bnhj->bnhi', mask, g)` at HIGHEST: `mask + [B, N, 1, C, C]` the fp32 lower-triangular same-document mask of each chunk, `g [B, N, H, C]` fp32 (MaxText's + gdn_packing.prepare_jax_gdn_segment_masks, the same contraction). Batch-major, typed like the activation under + explicit.""" + return mode.einsum("bnhij,bnhj->bnhi", mask, g, out_spec=mode.act_spec(g.ndim), precision=jax.lax.Precision.HIGHEST) + + +def conv_taps(taps, w): + """The packed causal conv's rows at a document edge, `einsum('bskc,kc->bsc', taps, w)` at HIGHEST with fp32 + accumulation: `taps [B, S, K, C]` the window of each such row with the other documents' tokens zeroed, `w [K, C]` + the fp32 kernel (through `small_weight`: replicated under explicit), as MaxText's + gdn_packing._compute_segmented_conv1d_core computes them. Typed like the activation under explicit.""" + return mode.einsum( + "bskc,kc->bsc", + taps, + w, + out_spec=mode.act_spec(3), + precision=jax.lax.Precision.HIGHEST, + preferred_element_type=jnp.float32, + ) + + +# ---------------------------------------------------------------- dispatch +def routed_experts(params, x, weights, indices, config): + """MoE dispatch: `maxtext.experimental.mpmd.jax.deepseek.moe.routed_experts`, the DeepSeek + dispatcher, which picks the kernel by `config.moe_impl` (sort + grouped + matmuls, or dense); under explicit its global argsort runs on replicated + tokens, a correctness path.""" + return ds_moe.routed_experts(params, x, weights, indices, config) + + +def attention(query, key, value, segment_ids, config): + """The attention kernel call: `maxtext.experimental.mpmd.jax.deepseek.attention.attention_op`. + + GQA: the dot-product and splash kernels map query head h to kv head + h // (num_query_heads / num_kv_heads) themselves; the fp32 'reference' + stand-in is MHA-only, so it gets the kv heads repeated in exactly that + order (`jnp.repeat`), which is the definition of GQA. + """ + if config.attention_kernel == "reference" and key.shape[2] != query.shape[2]: + rep = query.shape[2] // key.shape[2] + key = jnp.repeat(key, rep, axis=2) + value = jnp.repeat(value, rep, axis=2) + return ds_attention.attention_op(query, key, value, segment_ids, config) + + +def gdn_core(core, query, key, value, g, beta, config, segment_ids=None): + """Where the chunked gated delta rule `core(query, key, value, g, beta)` runs + (`core(query, key, value, g, beta, segment_ids=segment_ids)` with packed + documents' segment ids `[B, S]`), per `config.gdn_core`: + + 'inline' in the surrounding program: today's program under auto, typed + op by op under explicit (E1 + E2 + the regroups above). + 'manual' per device, in a `shard_map` over the stage's batch axes + (`mode.manual`, scope 'gdn_core'), in BOTH modes: MaxText's + layout (its GDN kernel runs in a shard_map), and the same + per-device program under auto and explicit, so the core's time + is mode-invariant. The cumsum, the solve and the state scan + are batch-local by construction, where auto on its own may + pick a head- or feature-sharded layout and move between them + with all-to-alls. + + Every operand is batch-major `[B, S, ...]`, the result too. + """ + args = (query, key, value, g, beta) + if segment_ids is not None: + args, plain = args + (segment_ids,), core + core = lambda q, k, v, g, beta, seg: plain(q, k, v, g, beta, segment_ids=seg) # noqa: E731 + if config.gdn_core == "inline": + return core(*args) + b = mode.act_spec(1) # the batch dim of every operand + return mode.manual(core, in_specs=(b,) * len(args), out_specs=b, name="gdn_core")(*args) diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/attention.py b/src/maxtext/experimental/mpmd/jax/qwen35/attention.py new file mode 100644 index 0000000000..a13c8f065c --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/attention.py @@ -0,0 +1,153 @@ +# 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. + +"""Qwen3.5's gated full attention (every 4th layer) and its rotary embeddings. + +Mirrors `Attention.__call__` with `is_qwen3_hybrid` (MaxText's layers/attentions.py, +wrapped by `Qwen3NextFullAttention` in models/qwen3.py): + + q2 = x @ query [B,S,H,2D] -> per head: first D = query, second D = gate + k, v = x @ key, x @ value [B,S,Hkv,D] (GQA) + q, k = zero-centred RMSNorm over D, BEFORE the rotary embedding + q, k = rotary embedding on the first rotary_dim features (text mRoPE or + partial RoPE, by use_mrope) + q = q * D^-1/2 (query_pre_attn_scalar; the kernel scale is 1) + o = attention(q, k, v) causal + segment mask + o = o.reshape(B,S,H*D) * sigmoid(gate) + out = o @ out kernel [H*D, E] + +The rotary embedding is one of MaxText's two for the qwen3_5 decoder, by its +`use_mrope` (`Qwen35Config.use_mrope`): + + * use_mrope=true (Qwen3.5's ymls; Qwen3OmniMoe text mRoPE, embeddings.py's + Qwen3OmniMoeThinkerTextRotaryEmbedding): text positions are broadcast to + the three (t, h, w) sections, so the section interleave is the identity and + what remains is rotate-half RoPE on the first `rotary_dim` features with + fp32 cos/sin of `position * (1 / timescale)`, an fp32 rotation and one + final rounding to `dtype` (`mrope_text`). + * use_mrope=false (Qwen3.8-2.4T's yml, which leaves it at base.yml's false; + PartialRotaryEmbedding, Qwen3-Next's): sin/cos of `position / timescale`, + each rounded to the activation dtype, and the rotation in that dtype + (`partial_rope`). +The same rotation; in fp32 they part in the last bits (a division against a +multiply by the reciprocal), in bf16 by the roundings. +""" + +from __future__ import annotations + +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.qwen35 import _ops +from maxtext.experimental.mpmd.jax.qwen35 import layers + + +def rope_timescale(config): + """`[rotary_dim // 2]` fp32 timescales, as MaxText's RotaryEmbedding.timescale + computes them (`rope_inv_freq` is their reciprocal).""" + rd = config.rotary_dim + fraction = 2 * jnp.arange(0, rd // 2) / rd + return config.rope_min_timescale * (config.rope_max_timescale / config.rope_min_timescale) ** fraction + + +def rope_inv_freq(config): + """`[rotary_dim // 2]` fp32 inverse frequencies, computed as MaxText does. + + Traced (not numpy), so inside a jit XLA constant-folds it exactly as it folds + MaxText's in-graph copy; called eagerly it is the same folded constant (a + test pins the two bitwise). A caller that computes it once + (`rope_inv_freq_jit`) passes it as `model.forward`'s `inv_freq`. + """ + return 1.0 / rope_timescale(config) + + +rope_inv_freq_jit = jax.jit(rope_inv_freq, static_argnums=0) + + +def mrope_text(inputs, positions, inv_freq, config): + """Rotate-half RoPE on `inputs[..., :rotary_dim]`, fp32 cos/sin, rounded once. + + inputs `[B, S, N, D]` (`dtype`), positions `[B, S]` int, inv_freq + `[rotary_dim // 2]` fp32. + + The cos/sin tables are written per call -- for q and for k, in every + attention layer -- as MaxText writes them, and XLA folds that: in the + optimized program of a scanned 4-block forward (CPU, jax 0.10.2) there is + one cosine and one sine, shared by q and k and hoisted out of the block + scan, plus one more of each in a remat backward's replay. Building the + tables once per forward by hand would buy nothing and change the program + (a checkpointed scan would then keep them as residuals), so it is not done + (review finding 10). + """ + rd = config.rotary_dim + freqs = positions[..., jnp.newaxis] * inv_freq[jnp.newaxis, jnp.newaxis, :] # [B, S, rd/2] fp32 + emb = jnp.concatenate([freqs, freqs], axis=-1) + cos = jnp.cos(emb)[:, :, jnp.newaxis, :] + sin = jnp.sin(emb)[:, :, jnp.newaxis, :] + x_rot, x_pass = jnp.split(inputs, [rd], axis=-1) + x1, x2 = jnp.split(x_rot, 2, axis=-1) + rotated = x_rot * cos + jnp.concatenate((-x2, x1), axis=-1) * sin + return jnp.concatenate([rotated, x_pass], axis=-1).astype(config.dtype) + + +def partial_rope(inputs, positions, config): + """MaxText's PartialRotaryEmbedding (use_mrope=false: Qwen3.8-2.4T, Qwen3-Next) + on `inputs[..., :rotary_dim]`, op for op: sin / cos of `position / timescale` + in fp32, each rounded to the inputs' dtype, the rotate-half rotation in that + dtype, the pass-through features appended, the result in `dtype`. + + inputs `[B, S, N, D]`, positions `[B, S]` int.""" + rd = config.rotary_dim + x_rot, x_pass = jnp.split(inputs, [rd], axis=-1) + sinusoid = positions[:, :, jnp.newaxis, jnp.newaxis] / rope_timescale(config) + sin_half = jnp.sin(sinusoid).astype(x_rot.dtype) + cos_half = jnp.cos(sinusoid).astype(x_rot.dtype) + sin = jnp.concatenate([sin_half, sin_half], axis=-1) + cos = jnp.concatenate([cos_half, cos_half], axis=-1) + x1, x2 = jnp.split(x_rot, 2, axis=-1) + rotated = (x_rot * cos) + (jnp.concatenate((-x2, x1), axis=-1) * sin) + return jnp.concatenate([rotated, x_pass], axis=-1).astype(config.dtype) + + +def rope(inputs, positions, inv_freq, config): + """The rotary embedding `config.use_mrope` names (the module docstring): + `mrope_text` on `inv_freq` (None: computed in-graph), or `partial_rope`.""" + if not config.use_mrope: + return partial_rope(inputs, positions, config) + return mrope_text(inputs, positions, rope_inv_freq(config) if inv_freq is None else inv_freq, config) + + +def gated_attention(params, x, positions, segment_ids, config, inv_freq=None): + """`[B, S, E]` -> `[B, S, E]`. `inv_freq=None` computes it in-graph (the + mRoPE path's; the partial RoPE computes its timescales in-graph always).""" + b, s, _ = x.shape + h, d = config.num_query_heads, config.head_dim + q = _ops.dense(params["query"], x, config) # [B, S, H, 2D] + k = _ops.dense(params["key"], x, config) # [B, S, Hkv, D] + v = _ops.dense(params["value"], x, config) + q, gate = jnp.split(q, 2, axis=-1) + gate = gate.reshape(b, s, h * d) + q = layers.rms_norm(params["query_norm"], q, config) + k = layers.rms_norm(params["key_norm"], k, config) + q = rope(q, positions, inv_freq, config) + k = rope(k, positions, inv_freq, config) + q = q * (config.head_dim**-0.5) + q = jax.ad_checkpoint.checkpoint_name(q, "query_proj") + k = jax.ad_checkpoint.checkpoint_name(k, "key_proj") + v = jax.ad_checkpoint.checkpoint_name(v, "value_proj") + out = _ops.attention(q, k, v, segment_ids, config) # [B, S, H, D] + out = jax.ad_checkpoint.checkpoint_name(out, "attention_out") + out = out.reshape(b, s, h * d) * jax.nn.sigmoid(gate) + out = _ops.dense(params["out"], out, config) + return jax.ad_checkpoint.checkpoint_name(out, "out_proj") diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/config.py b/src/maxtext/experimental/mpmd/jax/qwen35/config.py new file mode 100644 index 0000000000..c9c6804eed --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/config.py @@ -0,0 +1,610 @@ +# 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. + +"""Config for the pure-JAX Qwen3.5 text decoder (MaxText `decoder_block: qwen3_5`). + +Field names and defaults mirror MaxText's resolved config for +`model_name=qwen3.5-397b-a17b`, so that a MaxText `pyconfig` translates 1:1 +(`from_maxtext`). As in `src/maxtext/experimental/mpmd/jax/deepseek/config.py`, only the knobs the +training forward pass reads are kept, and what this port does not implement is +refused rather than silently ignored. + +The port calls a handful of `maxtext.experimental.mpmd.jax.deepseek` functions whose arithmetic is +identical for both models (dense projections, the gated MLP, the plain RMSNorm, +the embedding gather, the routed experts and their dispatch, the attention +kernels, the remat policy table). +`maxtext.experimental.mpmd.jax.deepseek.config.SharedLayerConfig` lists exactly the config fields +those functions read; `Qwen35Config` satisfies it (`qwen35_model_test` +checks both directions), which is why it carries DeepSeek's names for them. + +How the model shards is `shard`, a `maxtext.experimental.mpmd.jax.sharding_mode.ShardPolicy` +(the default policy, as DeepSeek's), plus one Qwen knob, `gdn_core`, for where +the Gated DeltaNet's chunked delta rule runs; its default is the program the +port has always traced. +""" + +from __future__ import annotations + +import dataclasses +from typing import Any + +import jax +import jax.numpy as jnp + +# The config surface of the shared DeepSeek functions, which Qwen35Config +# satisfies (re-exported: it is the one Protocol both models are held to). +from maxtext.experimental.mpmd.jax.deepseek.config import SHARED_LAYER_FIELDS, SharedLayerConfig # noqa: F401 +from maxtext.experimental.mpmd.jax.deepseek.model import REMAT_POLICIES +from maxtext.experimental.mpmd.jax.sharding_mode import ShardPolicy + + +ATTENTION_KERNELS = ("splash", "tokamax_splash", "dot_product", "reference", "cudnn") +REMAT_GRANULARITIES = ("block", "layer", "block+layer") +NORM_NUMERICS = ("fp32", "bf16") +GDN_CORES = ("inline", "manual") +# How the GDN's causal depthwise conv runs (`gdn.causal_depthwise_conv`): 'conv', lax.conv_general_dilated as +# MaxText's nnx.Conv (TPU's, bitwise MaxText's), or 'shift', its K shifted multiply-adds in fp32 (XLA:GPU fuses +# them; cuDNN's grouped conv is ~10x slower than the bytes it moves there). +GDN_CONV_IMPLS = ("conv", "shift") +# How the chunked delta rule runs (`gdn.chunk_gated_delta_rule`): 'scan', its inter-chunk recurrence a lax.scan +# (MaxText's), or 'triton', on Triton kernels (`gdn_triton`): at a chunk of 16, 32 or 64 (64 by default) the whole +# rule (gdn_triton.FUSED: the WY factors, the triangular solve, the intra-chunk output and their backward as per-chunk +# kernels around the recurrence's), at another chunk the recurrence alone, one kernel each way, the chunk outputs +# batched over the chunks in XLA. GPU only, per device -- inside the MPMD pipeline's shard_maps or under +# gdn_core='manual' -- and without packed documents: the kernels restart no state at a document, so the rule refuses +# segment ids, and a caller that passes them (qwen35.train does, all one for unpacked rows) needs gdn_packing=False, +# which keeps them out of the rule. The MPMD pipeline's GDN takes none. +GDN_SCAN_IMPLS = ("scan", "triton") +# How the chunked delta rule inverts its unit-lower-triangular WY matrix (`gdn.unit_lower_inv`), MaxText's +# `gdn_chunk_inverse`: 'block_doubling', exact sub-block inverses merged by matmuls (MaxText's default), or 'solve', +# `solve_triangular` (MaxText's reference path). +GDN_CHUNK_INVERSES = ("block_doubling", "solve") + + +@dataclasses.dataclass(frozen=True) +class Qwen35Config: + """Resolved Qwen3.5 hyperparameters (defaults: qwen3.5-397b-a17b).""" + + # --- vocabulary / shape --------------------------------------------------- + vocab_size: int = 248320 + emb_dim: int = 4096 + num_decoder_layers: int = 60 + # A block is `cycle` layers: cycle - 1 Gated DeltaNet layers, then one gated + # full-attention layer (layer i is attention iff (i + 1) % cycle == 0). + inhomogeneous_layer_cycle_interval: int = 4 + + # --- gated full attention ------------------------------------------------- + num_query_heads: int = 32 + num_kv_heads: int = 2 + head_dim: int = 256 + # Which of MaxText's two rotary embeddings the gated attention applies + # (attention.py): True, the text-only mRoPE of the Qwen3.5 ymls -- + # rotate-half RoPE on the first `rotary_dim` features with fp32 cos/sin; False, + # PartialRotaryEmbedding, base.yml's default and so Qwen3.8-2.4T's (its yml + # sets no use_mrope): sin/cos rounded to the activation dtype, the rotation in + # it. The same rotation, other roundings. + use_mrope: bool = True + # The mRoPE's (t, h, w) sections must sum to rotary_dim // 2 (MaxText checks + # it); for text positions they do not change the math. Unread without mRoPE. + partial_rotary_factor: float = 0.25 + rope_min_timescale: float = 1.0 + rope_max_timescale: float = 10_000_000.0 + mrope_section: tuple[int, ...] = (11, 11, 10) + + # --- Gated DeltaNet (linear attention) ------------------------------------- + gdn_num_key_heads: int = 16 + gdn_num_value_heads: int = 64 + gdn_key_head_dim: int = 128 + gdn_value_head_dim: int = 128 + gdn_conv_kernel_dim: int = 4 + gdn_chunk_size: int = 64 + use_qk_norm_in_gdn: bool = True + # Where the chunked delta rule runs (`_ops.gdn_core`): 'inline' in the + # surrounding program (the port's program; typed op by op under explicit), + # 'manual' per device in a shard_map over the stage's batch axes, in BOTH + # shard modes -- MaxText's layout, and the same per-device program under + # auto and explicit. A strategy pinned in both modes, so it changes the + # auto program only when set. + gdn_core: str = "inline" + # GDN_CONV_IMPLS: 'conv' (MaxText's op) or 'shift' (the GPU default of ds_ep_pipeline). + gdn_conv_impl: str = "conv" + # GDN_SCAN_IMPLS: 'scan' (MaxText's) or 'triton'. Orthogonal to gdn_core, which says where the rule runs + # ('triton' needs it per device: gdn_core='manual' under auto / explicit, or a caller's shard_map). 'triton' takes + # no packed documents: with segment ids (the single-controller model always passes them) set gdn_packing=False. + gdn_scan_impl: str = "scan" + # How the GDN reads segment ids and inverts its WY matrix: MaxText's options (`from_maxtext` reads them off its + # config). The rest is MaxText's GDN as it is (`gdn.gated_delta_net`): the padding's q/k/v projections zeroed + # before the causal conv as well as after it, g = -exp(A_log) * softplus(a + dt_bias) in fp32, and the WY matrix + # fp32(k k^T) * (fp32(beta) * exp(dg)), k k^T at the key heads (rounded to `dtype` as it comes out of the matmul), + # then repeated to the value heads, the query and key heads repeated inside the delta rule. + # gdn_packing -- MaxText's `packing` as its GDN reads it (true by default there): every segment id is a + # document, and the conv taps and the recurrent state stop at its edges (canonical + # documents: a segment id that comes back after another is a new one). False (MaxText's + # packing=false): segment ids only zero padding (segment 0); the state and the conv window + # run on from one document into the next, as attention does not. Without segment ids + # (the MPMD pipeline's GDN) neither applies. gdn_scan_impl 'triton' has no packed path: + # with segment ids it needs False. + # gdn_chunk_inverse -- GDN_CHUNK_INVERSES. + # HF / FLA reset the state per document (cu_seqlens) as gdn_packing does, but zero padded hidden states before the + # input projections. + gdn_packing: bool = True + gdn_chunk_inverse: str = "block_doubling" + + # --- MoE ------------------------------------------------------------------ + moe_mlp_dim: int = 1024 + num_experts: int = 512 + num_experts_per_tok: int = 10 + # 0 or 1: MaxText builds ONE shared expert of width `moe_mlp_dim` whenever + # this is positive, with a sigmoid gate in front of it. + shared_experts: int = 1 + norm_topk_prob: bool = True + mlp_activations: tuple[str, ...] = ("silu", "linear") + # `ragged` = MaxText sparse_matmul (sort + grouped matmul), `dense` = + # dense_matmul (einsum over every expert). See `src/maxtext/experimental/mpmd/jax/deepseek/moe.py`. + moe_impl: str = "ragged" + gmm_fp32_accum: bool = True + gmm_exact_drhs: bool = False + moe_use_direct_token_gather: bool = False + float32_weight_sum: bool = True + float32_gate_logits: bool = False + # Not plumbed to the loss (as in the DeepSeek port): > 0 is refused here, at + # construction, rather than on the first trace. + load_balance_loss_weight: float = 0.0 + + # --- numerics ------------------------------------------------------------- + normalization_layer_epsilon: float = 1.0e-6 + dtype: Any = jnp.bfloat16 + # MaxText's revisions disagree on one leaf: before 2026-09-10 it built + # `shared_expert_gate` without a weight_dtype, so that kernel stayed fp32 + # whatever this says (`from_maxtext` refuses anything but fp32 for that + # reason); later revisions type it like every other leaf. + weight_dtype: Any = jnp.float32 + matmul_precision: str = "default" + cast_logits_to_fp32: bool = True + # How the two RMSNorm kinds round, which differs between MaxText revisions + # (both compute their statistics and the normalised value in fp32): + # 'fp32' -- MaxText since 2026-09-10: the zero-centred norms multiply the + # fp32 normalised value by `fp32(scale) + 1` and round once; the + # GDN gated norm multiplies it by `fp32(scale)` and by + # `silu(fp32(z))`, then rounds once. + # 'bf16' -- MaxText before then (which the port was first written + # against): the normalised value is rounded to `dtype` first, + # and the scale multiply (`bf16(scale) + 1`, the add itself in + # bf16, for the zero-centred norms) runs in `dtype`. + # HF (transformers 5.13.0, bf16 weights) matches neither: its zero-centred + # norm rounds as 'fp32' does, its gated norm as 'bf16' does. With + # `dtype=float32` the two settings are the same computation. + norm_numerics: str = "fp32" + + # --- attention kernel (see src/maxtext/experimental/mpmd/jax/deepseek/config.py) -------------------- + attention_kernel: str = "splash" + sa_block_q: int = 512 + sa_block_kv: int = 512 + sa_block_kv_compute: int = 512 + sa_block_q_dkv: int = 0 + sa_block_kv_dkv: int = 0 + sa_block_kv_dkv_compute: int = 0 + sa_cost_estimate_flops_fwd: int = -1 + sa_cost_estimate_flops_bwd: int = -1 + # tokamax's base-2 softmax, MaxText's: see src/maxtext/experimental/mpmd/jax/deepseek/config.py + sa_use_base2_exp: bool = True + + # --- training ------------------------------------------------------------- + max_target_length: int = 4096 + scan_layers: bool = True + # MaxText's policy name for the block's checkpoint, and the layers' unless + # `layer_remat_policy` names one ('none' and 'full' both mean "save nothing, + # recompute everything", as in MaxText). + remat_policy: str = "full" + # Where the `jax.checkpoint`s go on the scanned path: + # 'block' -- one around each 4-layer block body (MaxText before its + # nested Qwen3 scan of 2026-10-21), policy + # `remat_policy`. Stores one [B, L, E] per block; the + # block's backward holds all four layers' recomputed + # intermediates at once. + # 'layer' -- one around each layer, policy `layer_remat_policy`; the + # scan body itself is not checkpointed (MaxText since + # that nested scan: a checkpoint per sub-layer inside + # it, none around the block). Stores the four layer + # inputs per block, holds one layer's working set. + # 'block+layer' -- both, nested: the block's checkpoint (`remat_policy`) + # around the layers' (`layer_remat_policy`). Block remat's + # stored residuals with one layer's working set, for one + # more forward pass of the GDN layers. + # Measured on v5p (jax 0.12, libtpu 0.0.49), the backward program of a + # one-block chunk at 397B dims, 32 experts, 4096 tokens: 29.3 / 12.0 / 12.0 GB + # of temporaries for block / layer / block+layer, storing 34 / 134 / 34 MB of + # residuals per microbatch (two-block chunk: 37.9 / 21.0 / 21.6 GB); with + # norm_numerics='bf16', 29.0 / 14.2 / 13.7 GB (38.1 / 21.0 / 21.6 GB). + # `from_maxtext` does not map it: 'block', whatever the MaxText revision. + remat_granularity: str = "block" + # The per-layer checkpoints' policy; '' means `remat_policy`. + layer_remat_policy: str = "" + + # --- sharding ------------------------------------------------------------- + # How the model shards (`src/maxtext/experimental/mpmd/jax/sharding_mode.py`): the default + # policy, the program this port has always traced, the only one there is. + # Frozen, like this class, which stays hashable. + shard: ShardPolicy = ShardPolicy() + + def __post_init__(self): + # Hashable: the config is a static argument of jitted helpers + # (`attention.rope_inv_freq_jit`). + object.__setattr__(self, "mrope_section", tuple(self.mrope_section)) + object.__setattr__(self, "mlp_activations", tuple(self.mlp_activations)) + cyc = self.inhomogeneous_layer_cycle_interval + if cyc < 1 or self.num_decoder_layers % cyc: + raise ValueError(f"num_decoder_layers={self.num_decoder_layers} is not a multiple of " f"the {cyc}-layer block") + if self.gdn_num_value_heads % self.gdn_num_key_heads: + raise ValueError( + f"gdn_num_value_heads={self.gdn_num_value_heads} is not a multiple of " + f"gdn_num_key_heads={self.gdn_num_key_heads}" + ) + if self.num_query_heads % self.num_kv_heads: + raise ValueError( + f"num_query_heads={self.num_query_heads} is not a multiple of " f"num_kv_heads={self.num_kv_heads}" + ) + rd = self.rotary_dim + if rd <= 0 or rd % 2 or rd > self.head_dim: + raise ValueError( + f"rotary_dim={rd} (head_dim {self.head_dim} x partial_rotary_factor " + f"{self.partial_rotary_factor}) must be even and in (0, head_dim]" + ) + if self.use_mrope and sum(self.mrope_section) != rd // 2: + raise ValueError(f"mrope_section {tuple(self.mrope_section)} must sum to rotary_dim // 2 " f"= {rd // 2}") + if not 1 <= self.num_experts_per_tok <= self.num_experts: + raise ValueError(f"num_experts_per_tok={self.num_experts_per_tok} not in " f"[1, num_experts={self.num_experts}]") + if self.moe_mlp_dim < 1: + raise ValueError(f"moe_mlp_dim={self.moe_mlp_dim} must be positive") + if self.shared_experts not in (0, 1): + raise ValueError( + f"shared_experts={self.shared_experts}: Qwen3.5 has at most one shared " + "expert (MaxText builds one of width moe_mlp_dim for any positive value)" + ) + if self.moe_impl not in ("ragged", "dense"): + raise ValueError(f"unknown moe_impl {self.moe_impl!r}") + if self.attention_kernel not in ATTENTION_KERNELS: + raise ValueError(f"unknown attention_kernel {self.attention_kernel!r}") + if self.remat_granularity not in REMAT_GRANULARITIES: + raise ValueError(f"remat_granularity must be one of {REMAT_GRANULARITIES}, got " f"{self.remat_granularity!r}") + if self.norm_numerics not in NORM_NUMERICS: + raise ValueError(f"norm_numerics must be one of {NORM_NUMERICS}, got {self.norm_numerics!r}") + if self.gdn_chunk_size < 1 or self.gdn_conv_kernel_dim < 1: + raise ValueError("gdn_chunk_size and gdn_conv_kernel_dim must be positive") + if self.load_balance_loss_weight > 0.0: + # The aux loss would be computed per layer and never reach the loss -- a + # different model from MaxText's, silently (the DeepSeek port refuses it too). + raise NotImplementedError( + "load_balance_loss_weight > 0 is not supported: the aux loss " "is not plumbed out of the layer stack" + ) + # MaxText has more policies than the port runs; an unknown name would only + # fail on the first trace, deep inside the scanned block. + for field in ("remat_policy", "layer_remat_policy"): + name = getattr(self, field) + if name and name not in REMAT_POLICIES: + raise ValueError(f"{field}={name!r} is not supported; the policies are " f"{sorted(REMAT_POLICIES)}") + if not isinstance(self.shard, ShardPolicy): + raise TypeError(f"shard must be a maxtext.experimental.mpmd.jax.sharding_mode.ShardPolicy, got {self.shard!r}") + if self.gdn_core not in GDN_CORES: + raise ValueError(f"gdn_core must be one of {GDN_CORES}, got {self.gdn_core!r}") + if self.gdn_conv_impl not in GDN_CONV_IMPLS: + raise ValueError(f"gdn_conv_impl must be one of {GDN_CONV_IMPLS}, got {self.gdn_conv_impl!r}") + if self.gdn_scan_impl not in GDN_SCAN_IMPLS: + raise ValueError(f"gdn_scan_impl must be one of {GDN_SCAN_IMPLS}, got {self.gdn_scan_impl!r}") + if self.gdn_chunk_inverse not in GDN_CHUNK_INVERSES: + raise ValueError(f"gdn_chunk_inverse must be one of {GDN_CHUNK_INVERSES}, got {self.gdn_chunk_inverse!r}") + + # --- derived -------------------------------------------------------------- + @property + def num_blocks(self) -> int: + return self.num_decoder_layers // self.inhomogeneous_layer_cycle_interval + + @property + def rotary_dim(self) -> int: + return int(self.head_dim * self.partial_rotary_factor) + + @property + def gdn_key_dim(self) -> int: + return self.gdn_num_key_heads * self.gdn_key_head_dim + + @property + def gdn_value_dim(self) -> int: + return self.gdn_num_value_heads * self.gdn_value_head_dim + + @property + def gdn_v_per_k(self) -> int: + """Value heads per key head (value head j reads key head j // v_per_k).""" + return self.gdn_num_value_heads // self.gdn_num_key_heads + + @property + def gdn_conv_dim(self) -> int: + """Channels of the depthwise conv: [q_all | k_all | v_all].""" + return 2 * self.gdn_key_dim + self.gdn_value_dim + + @property + def gdn_qkvz_dim(self) -> int: + return 2 * self.gdn_key_dim + 2 * self.gdn_value_dim + + @property + def shared_expert_mlp_dim(self) -> int: + return self.moe_mlp_dim + + @property + def block_remat(self) -> bool: + """Is each scanned block body inside a `jax.checkpoint`?""" + return bool(self.scan_layers) and self.remat_granularity in ("block", "block+layer") + + @property + def layer_remat(self) -> bool: + """Is each layer inside its own `jax.checkpoint`?""" + return bool(self.scan_layers) and self.remat_granularity in ("layer", "block+layer") + + @property + def layer_remat_policy_name(self) -> str: + return self.layer_remat_policy or self.remat_policy + + def is_attention_layer(self, i: int) -> bool: + """Layer i (global or within a block) is gated full attention.""" + return (i + 1) % self.inhomogeneous_layer_cycle_interval == 0 + + def replace(self, **kwargs) -> "Qwen35Config": + return dataclasses.replace(self, **kwargs) + + +# --------------------------------------------------------------------- presets +# The tiny shape at which the port is bit-exact against MaxText on CPU: every +# structural feature of 397B-A17B (3:1 GDN:attention, GQA 2:1, 4 value heads per +# GDN key head, partial RoPE 0.25, top-k MoE + sigmoid-gated shared expert, +# untied head) at toy widths. +TINY = dict( + vocab_size=256, + emb_dim=64, + num_decoder_layers=8, + num_query_heads=4, + num_kv_heads=2, + head_dim=64, + mrope_section=(3, 3, 2), + gdn_num_key_heads=2, + gdn_num_value_heads=8, + gdn_key_head_dim=16, + gdn_value_head_dim=16, + gdn_chunk_size=16, + moe_mlp_dim=32, + num_experts=8, + num_experts_per_tok=2, + max_target_length=64, + attention_kernel="dot_product", +) + +# Per-layer dims of qwen3.5-35b-a3b (the class defaults are 397B-A17B's). +_Q35B = dict( + emb_dim=2048, + num_query_heads=16, + num_kv_heads=2, + head_dim=256, + gdn_num_key_heads=16, + gdn_num_value_heads=32, + gdn_key_head_dim=128, + gdn_value_head_dim=128, + moe_mlp_dim=512, + num_experts_per_tok=8, +) + + +def tiny(**overrides) -> Qwen35Config: + """The tiny CPU config (bf16, dot-product attention), bit-exact vs MaxText.""" + return Qwen35Config(**{**TINY, **overrides}) + + +def qwen35_397b( + num_decoder_layers: int = 60, num_experts: int = 512, vocab_size: int = 248320, **overrides +) -> Qwen35Config: + """qwen3.5-397b-a17b per-layer dims; depth, expert count and vocab are knobs. + + Shrinking `num_experts` keeps the active FLOPs per token (top-k is fixed). + `num_decoder_layers` must be a multiple of the 4-layer block (checked). + Vocab 32768 keeps the head off the critical stage. + """ + return Qwen35Config(num_decoder_layers=num_decoder_layers, num_experts=num_experts, vocab_size=vocab_size, **overrides) + + +def qwen35_35b( + num_decoder_layers: int = 40, num_experts: int = 256, vocab_size: int = 248320, **overrides +) -> Qwen35Config: + """qwen3.5-35b-a3b per-layer dims; depth, expert count and vocab are knobs.""" + return Qwen35Config( + **{ + **_Q35B, + "num_decoder_layers": num_decoder_layers, + "num_experts": num_experts, + "vocab_size": vocab_size, + **overrides, + } + ) + + +# ------------------------------------------------------------------ MaxText +def resolve_attention_kernel(cfg, platform: str | None = None) -> str: + """`attention_op.AttentionOp.apply_attention`'s train-mode dispatch. + + `autoselected` runs the bf16 dot-product path below 128 tokens AND on CPU; + otherwise (and for `flash`) the TPU splash kernel, or tokamax's with + `use_tokamax_splash`. `src/maxtext/experimental/mpmd/jax/deepseek/config.py` omits the CPU clause. + """ + kernel = cfg.attention + platform = platform or jax.default_backend() + if kernel == "dot_product": + return "dot_product" + if kernel in ("autoselected", "flash"): + if kernel == "autoselected" and (int(cfg.max_target_length) < 128 or platform == "cpu"): + return "dot_product" + return "tokamax_splash" if getattr(cfg, "use_tokamax_splash", False) else "splash" + raise ValueError(f"unsupported attention kernel for this port: {kernel}") + + +def _refuse(cond, what): + if cond: + raise NotImplementedError(f"Qwen3.5 port: {what}") + + +def maxtext_gdn_fields(cfg) -> dict: + """The GDN settings MaxText's options `packing` and `gdn_chunk_inverse` of the pyconfig `cfg` give + (`Qwen35Config.gdn_packing`, `gdn_chunk_inverse`).""" + return dict(gdn_packing=bool(cfg.packing), gdn_chunk_inverse=str(cfg.gdn_chunk_inverse)) + + +def from_maxtext(cfg, platform: str | None = None, *, norm_numerics: str = Qwen35Config.norm_numerics) -> Qwen35Config: + """Builds a Qwen35Config from an initialized MaxText pyconfig. + + Raises on the MaxText features that would change the math and that this port + does not implement, instead of training a different model without a word. + + `norm_numerics` is a property of the MaxText REVISION, not of its pyconfig, + so it cannot be read off `cfg`: the default is MaxText's since 2026-09-10, + this MaxText's; pass 'bf16' for an earlier one (`Qwen35Config.norm_numerics`). + `qwen35_maxtext_parity_test` reads it off the MaxText it imports. The GDN's + settings MaxText's options give it reads off `cfg` (`maxtext_gdn_fields`). + """ + block = getattr(cfg.decoder_block, "value", cfg.decoder_block) + _refuse(str(block) != "qwen3_5", f"decoder_block={block!r}, expected qwen3_5") + # The dense Qwen3.5 variants (num_experts=1, e.g. qwen3.5-9b): MaxText builds + # an MlpBlock of width mlp_dim there, and the port has only the sparse MoE. + _refuse( + int(getattr(cfg, "num_experts", 1)) <= 1, + f'num_experts={getattr(cfg, "num_experts", 1)} (the dense Qwen3.5 MLP, e.g. qwen3.5-9b: ' + "MaxText builds an MlpBlock of width mlp_dim)", + ) + _refuse( + getattr(cfg, "routed_score_func", "") not in ("", None), + f"routed_score_func={cfg.routed_score_func!r} (Qwen routes on raw logits)", + ) + _refuse(getattr(cfg, "routed_bias", False), "routed_bias=true") + _refuse(float(getattr(cfg, "routed_scaling_factor", 1.0)) != 1.0, "routed_scaling_factor != 1") + _refuse(getattr(cfg, "logits_via_embedding", False), "logits_via_embedding=true (tied head)") + _refuse(getattr(cfg, "logits_dot_in_fp32", False), "logits_dot_in_fp32=true") + # use_qk_norm=true makes MaxText's qwen3-hybrid attention build PLAIN RMSNorms + # (ones init, no +1) for its q/k norms (attentions.py); the port applies the + # zero-centred (1 + scale) norm the Qwen3.5 checkpoints are trained with. + _refuse(getattr(cfg, "use_qk_norm", False), "use_qk_norm=true (plain q/k RMSNorms instead of the zero-centred ones)") + # The dense MoE (sparse_matmul=false) drops tokens over expert capacity when + # capacity_factor > 0; the port never drops. MaxText's sparse_matmul path + # ignores capacity_factor (layers/moe.py reads it only in dense_matmul and its + # masks), so ragged + capacity_factor is MaxText's own no-drop math. + _refuse( + float(getattr(cfg, "capacity_factor", -1.0)) > 0 and not cfg.sparse_matmul, + "capacity_factor > 0 with sparse_matmul=false (token dropping)", + ) + # mlp_bias adds wi_0/wi_1/wo biases to the routed experts, leaves the port has + # no use for: the converted tree would carry them and the forward ignore them. + _refuse(getattr(cfg, "mlp_bias", False), "mlp_bias=true (expert biases)") + # MaxText's trainer applies dropout only with enable_dropout (the Qwen3.5 ymls + # set it false); the port has none. + _refuse( + float(getattr(cfg, "dropout_rate", 0.0)) > 0 and getattr(cfg, "enable_dropout", True), + "dropout_rate > 0 with enable_dropout=true (the port has no dropout)", + ) + _refuse(getattr(cfg, "quantization", "") not in ("", None), f'quantization={getattr(cfg, "quantization", "")!r}') + # Neither adds a parameter, so `convert.check_params` cannot catch them: + # activations_in_float32 runs the shared expert's (MlpBlock) and the dense + # MoE's activations in fp32; use_untrainable_positional_embedding adds + # sinusoidal position embeddings to the embedded tokens. + _refuse(getattr(cfg, "activations_in_float32", False), "activations_in_float32=true (fp32 MLP / expert activations)") + _refuse( + getattr(cfg, "use_untrainable_positional_embedding", False), + "use_untrainable_positional_embedding=true (sinusoidal position embeddings)", + ) + # These add no parameter either: the rotary embeddings MaxText's gated attention picks ahead of + # PartialRotaryEmbedding under use_mrope=false (attentions.Attention.init_rotary_embedding), LLaMA-3.1's (rope_type + # llama3.1, or a llama3.1 model_name) and YaRN (rope_type yarn), both over all of head_dim, where the port has + # only the partial RoPE. Under use_mrope=true the mRoPE comes first and rope_type is unread. + rope_type = getattr(cfg, "rope_type", None) or "default" + rope_type = str(getattr(rope_type, "value", rope_type)).lower() # str() of a (str, Enum) RopeType: 'RopeType.X' + model_name = str(getattr(cfg, "model_name", "") or "") + _refuse( + not cfg.use_mrope and (rope_type != "default" or model_name.startswith("llama3.1")), + f"use_mrope=false with rope_type={rope_type!r}, model_name={model_name!r} (MaxText rotates with its " + "LLaMA-3.1 or YaRN RoPE there, not PartialRotaryEmbedding)", + ) + # Before 2026-09-10 MaxText built shared_expert_gate without a weight_dtype, + # so that kernel stayed fp32 while every other leaf followed weight_dtype; the + # port types every leaf alike (`model.param_avals`), as later revisions do. + # fp32 (base.yml and the Qwen3.5 configs) is the one setting both agree on. + _refuse( + jnp.dtype(getattr(cfg, "weight_dtype", jnp.float32)) != jnp.float32, + f"weight_dtype={jnp.dtype(cfg.weight_dtype).name} (MaxText revisions disagree on " + "the shared_expert_gate kernel dtype; only float32 is the same in all)", + ) + # MaxText options that compute the GDN in other numerics than the port's JAX GDN: the Tokamax GDN kernel, its two-pass + # bf16 refinement, and FP8 in_proj_qkvz / out_proj matmuls. None adds a parameter, so the tree check cannot catch them. + _refuse(getattr(cfg, "use_tokamax_gdn", False), "use_tokamax_gdn=true (the Tokamax GDN kernel's own rounding)") + _refuse(getattr(cfg, "gdn_two_pass_bf16", False), "gdn_two_pass_bf16=true (the Tokamax GDN kernel's refinement)") + _refuse(getattr(cfg, "gdn_fp8_projections", False), "gdn_fp8_projections=true (FP8 GDN projections)") + gdn = maxtext_gdn_fields(cfg) + sa = { + k: getattr(cfg, k) + for k in ("sa_block_q_dkv", "sa_block_kv_dkv", "sa_block_kv_dkv_compute") + if getattr(cfg, k, None) is not None + } + return Qwen35Config( + vocab_size=cfg.vocab_size, + emb_dim=cfg.emb_dim, + num_decoder_layers=cfg.num_decoder_layers, + inhomogeneous_layer_cycle_interval=cfg.inhomogeneous_layer_cycle_interval, + num_query_heads=cfg.num_query_heads, + num_kv_heads=cfg.num_kv_heads, + head_dim=cfg.head_dim, + partial_rotary_factor=cfg.partial_rotary_factor, + rope_min_timescale=cfg.rope_min_timescale, + rope_max_timescale=cfg.rope_max_timescale, + # use_mrope=false (Qwen3.8-2.4T's yml) with the default rope_type (anything else is refused above): + # PartialRotaryEmbedding (attention.partial_rope); the sections are then unread (and checked by neither + # MaxText nor Qwen35Config) + use_mrope=bool(cfg.use_mrope), + mrope_section=tuple(cfg.mrope_section), + gdn_num_key_heads=cfg.gdn_num_key_heads, + gdn_num_value_heads=cfg.gdn_num_value_heads, + gdn_key_head_dim=cfg.gdn_key_head_dim, + gdn_value_head_dim=cfg.gdn_value_head_dim, + gdn_conv_kernel_dim=cfg.gdn_conv_kernel_dim, + gdn_chunk_size=cfg.gdn_chunk_size, + use_qk_norm_in_gdn=bool(cfg.use_qk_norm_in_gdn), + **gdn, + moe_mlp_dim=cfg.moe_mlp_dim, + num_experts=cfg.num_experts, + num_experts_per_tok=cfg.num_experts_per_tok, + shared_experts=1 if cfg.shared_experts else 0, + norm_topk_prob=bool(cfg.norm_topk_prob), + mlp_activations=tuple(cfg.mlp_activations), + moe_impl="ragged" if cfg.sparse_matmul else "dense", + gmm_fp32_accum=bool(cfg.megablox or cfg.use_tokamax_gmm), + moe_use_direct_token_gather=bool(cfg.moe_use_direct_token_gather), + float32_weight_sum=bool(cfg.float32_weight_sum), + float32_gate_logits=bool(cfg.float32_gate_logits), + load_balance_loss_weight=float(cfg.load_balance_loss_weight), + normalization_layer_epsilon=cfg.normalization_layer_epsilon, + dtype=cfg.dtype, + weight_dtype=cfg.weight_dtype, + matmul_precision=cfg.matmul_precision, + cast_logits_to_fp32=bool(cfg.cast_logits_to_fp32), + norm_numerics=norm_numerics, + attention_kernel=resolve_attention_kernel(cfg, platform), + sa_block_q=cfg.sa_block_q, + sa_block_kv=cfg.sa_block_kv, + sa_block_kv_compute=cfg.sa_block_kv_compute, + sa_use_base2_exp=bool(cfg.sa_use_base2_exp), + max_target_length=cfg.max_target_length, + scan_layers=bool(cfg.scan_layers), + remat_policy=cfg.remat_policy, + **sa, + ) diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/convert.py b/src/maxtext/experimental/mpmd/jax/qwen35/convert.py new file mode 100644 index 0000000000..eba679ab18 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/convert.py @@ -0,0 +1,138 @@ +# 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. + +"""MaxText NNX state -> this port's parameter tree. + +The main layout difference is the scanned block axis: MaxText stores every leaf +under `decoder/layers` with the block axis at `param_scan_axis` (1 by default, +e.g. `in_proj_qkvz [E, NB, 2Kd+2Vd]`, `wi_0 [X, NB, E, F]`); this port keeps it +at 0, natural for `jax.lax.scan`. Names are MaxText's NNX path names +verbatim, so nothing else is renamed (cf. `src/maxtext/experimental/mpmd/jax/deepseek/convert.py`). + +MaxText holds a block's layers as its nested scan: `local_layers`, the +block's cycle - 1 Gated DeltaNet layers scanned inside the block, each leaf +with their axis right after the block axis (`in_proj_qkvz [E, NB, cycle - 1, +...]`), and `global_layer`, its full-attention layer (`[E, NB, ...]`). This +port keeps one subtree a layer, `layer_0 .. layer_{cycle-1}`, the +full-attention layer last: the layer order unchanged. Leaves already in the +port's layout pass through as they are. +Imports no MaxText or Flax: it only walks `state.flat_state()`. +""" + +from __future__ import annotations + +import jax +import jax.numpy as jnp +import numpy as np + +from maxtext.experimental.mpmd.jax.qwen35 import model as q_model + + +def _value(var): + if hasattr(var, "get_value"): + return var.get_value() + return getattr(var, "value", var) + + +def _leaves(tree): + return { + jax.tree_util.keystr(p): (tuple(int(d) for d in a.shape), jnp.dtype(a.dtype)) + for p, a in jax.tree_util.tree_flatten_with_path(tree)[0] + } + + +def check_params(params, config) -> None: + """Raises ValueError unless `params` has exactly `model.param_avals(config)`'s + leaves, shapes and dtypes. + + A MaxText setting that adds parameters (`mlp_bias`'s expert biases, say) + would otherwise convert into leaves the forward never reads -- a different + model, silently. + """ + got, want = _leaves(params), _leaves(q_model.param_avals(config)) + extra = sorted(set(got) - set(want)) + missing = sorted(set(want) - set(got)) + wrong = sorted(f"{k}: {got[k]} != {want[k]}" for k in set(got) & set(want) if got[k] != want[k]) + if extra or missing or wrong: + + def head(items): + return items[:6] + ([f"... {len(items) - 6} more"] if len(items) > 6 else []) + + raise ValueError( + f"parameter tree is not param_avals(config): {len(extra)} extra leaves " + f"{head(extra)}, {len(missing)} missing {head(missing)}, {len(wrong)} with " + f"another shape/dtype {head(wrong)}" + ) + + +def from_nnx_state(state, param_scan_axis: int = 1, params_only: bool = True, config=None): + """`nnx.split(model)[1]` of MaxText's `Qwen3_5` model -> nested dict of arrays. + + Keeps `nnx.Param` leaves only (no RNG state, no intermediates) and moves the + block axis of every `decoder/layers` leaf from `param_scan_axis` to 0. + `params_only=False` keeps every array leaf, for a state that is already + parameters only, e.g. the gradient of a loss w.r.t. `nnx.split(model, + nnx.Param, ...)[1]`. With `config` (the `from_maxtext` of the same + pyconfig) the result must be exactly `model.param_avals(config)`'s tree + (`check_params`). + """ + items = [] + for path, var in state.flat_state(): + parts = [str(getattr(p, "key", p)) for p in path] + if "rngs" in parts or (params_only and type(var).__name__ != "Param"): + continue + if not hasattr(_value(var), "shape"): + continue + items.append((parts, _value(var))) + return from_flat(items, param_scan_axis, config=config) + + +def from_flat(items, param_scan_axis: int = 1, config=None, asarray=jnp.asarray): + """MaxText's parameters as (path parts, array) pairs -- `from_nnx_state`'s, or + a params checkpoint's flattened -- -> this port's tree (the module docstring: + the block axis to 0, the nested scan's layers to layer_0..). `asarray`: what each + array becomes (np.asarray keeps host arrays on the host, views where it can). + With `config`, `check_params`.""" + params, global_layer = {}, {} + moveaxis = jnp.moveaxis if asarray is jnp.asarray else np.moveaxis + + def put(tree, parts, val): + node = tree + for key in parts[:-1]: + node = node.setdefault(key, {}) + node[parts[-1]] = val + + for parts, val in items: + parts = [str(p) for p in parts] + val = asarray(val) + if "layers" in parts and param_scan_axis != 0: + val = moveaxis(val, param_scan_axis, 0) + nested = parts[:2] == ["decoder", "layers"] and len(parts) > 2 and parts[2] in ("local_layers", "global_layer") + if nested and parts[2] == "local_layers": + # [NB, ..., cycle - 1, ...] (the block axis now at 0, the local layers' axis still right after + # param_scan_axis) -> layer_0 .. layer_{cycle-2}, by basic indexing: a view of a host array + axis = param_scan_axis + 1 + for i in range(val.shape[axis]): + put(params, ["decoder", "layers", f"layer_{i}"] + parts[3:], val[(slice(None),) * axis + (i,)]) + elif nested: + put(global_layer, parts[3:], val) + else: + put(params, parts, val) + if global_layer: + # the block's full-attention layer comes last: layer_{cycle-1}, cycle - 1 being local_layers' length + layers = params.setdefault("decoder", {}).setdefault("layers", {}) + layers[f'layer_{sum(k.startswith("layer_") for k in layers)}'] = global_layer + if config is not None: + check_params(params, config) + return params diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/gdn.py b/src/maxtext/experimental/mpmd/jax/qwen35/gdn.py new file mode 100644 index 0000000000..37631b46ef --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/gdn.py @@ -0,0 +1,563 @@ +# 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 Gated DeltaNet (linear-attention) layer of Qwen3.5. + +Mirrors `Qwen3NextGatedDeltaNet.__call__` (MaxText's models/qwen3.py, +training path), its chunked gated delta rule (`jax_chunk_gated_delta_rule`) and +its packed-document helpers (kernels/attention/gdn_packing.py), op for op and +dtype for dtype; the config's `gdn_packing` and `gdn_chunk_inverse` follow +MaxText's options `packing` and `gdn_chunk_inverse`. The details that are +easy to get wrong: the qkvz / ba +projections are interleaved per KEY head; the conv runs over the flat +[q | k | v] channel order, causal, no bias, silu in fp32; key heads are +`jnp.repeat`ed (not tiled) to the value heads, inside the delta rule, after +the l2 norm, the q scale and the q k^T / k k^T products; the l2 norm adds its +eps inside the sqrt, in the input dtype; the gates `g` in fp32 (`beta` in +`dtype`); masks are applied with -1e30 BEFORE `exp`; q, k, v, beta enter in +bf16, so the k k^T and q k^T products come out of bf16 matmuls (rounded, then +cast to fp32), beta and the decay multiply k k^T in fp32, and the WY factors +u, w are rounded back to bf16; the decay, the masks, the inverse and the state +recurrence are fp32 at HIGHEST. + +Segment ids (`gated_delta_net`): padding (segment 0) is zeroed before the +causal conv and its k, v and g after it, so a padded token neither decays nor +updates the state. Under `gdn_packing` (MaxText's `packing`, its default) +every segment id is a document (canonical: an id that comes back after another +starts a new one): the conv sums only its own document's taps +(`segmented_causal_conv`, in fp32 with the fp32 kernel, one rounding) and +writes zeros on padding, and the delta rule restarts the state at each +document (`_segment_masks`: a per-document cumulative decay as a masked +matmul, and masks on the state's entry, exit and carry). Without it the state +and the conv window run on across documents. + +The one deliberate difference from MaxText is the backward of the WY inverse +`A = (I + S)^-1`: `unit_lower_inv` computes the same forward (block doubling, +or `solve_triangular`, by `gdn_chunk_inverse`), but carries a custom VJP (two +matmuls and a mask) instead of differentiating the forward. JAX's own +transpose rule for the batched triangular solve is not explicit-sharding clean +(jax 0.10.2, 0.11 and 0.12), the block doubling's autodiff costs four matmuls +a doubling level, and the custom rule costs the same as the solve's on TPU +(v5p, the 397B-shape core: 8.5 / 16.8 ms fwd / fwd+bwd either way), so it is +used in EVERY mode: an auto-vs-explicit comparison then differs in the +sharding mode only. Its gradient matches the solve's to ~4e-7 in fp32. + +Under explicit sharding the layer traces as written once four sites are +typed, all in `_ops`: the inverse's identity (E1), the state scan's carry +(E2), the per-key-head -> per-value-head regroups (E3), and the elementwise +weights (A_log, dt_bias, the conv kernel: replicated); the packed path adds +two contractions (`_ops.segment_cumsum`, `_ops.conv_taps`). +`config.gdn_core='manual'` runs the chunked rule per device instead, in a +`shard_map` over the batch, in both modes (`_ops.gdn_core`). +""" + +from __future__ import annotations + +import functools + +import jax +import jax.numpy as jnp +import numpy as np + +from maxtext.experimental.mpmd.jax.qwen35 import _ops +from maxtext.experimental.mpmd.jax.qwen35 import layers + +_HI = jax.lax.Precision.HIGHEST +_NEG = -1e30 # mask value applied BEFORE exp, so masked entries are exp(-inf) = 0 + + +# ------------------------------------------------------------- primitives +def l2norm(x, eps=1e-6): + """`normalizations.l2norm`: `x * rsqrt(sum(x^2) + eps)`, in `x.dtype`.""" + return x * jax.lax.rsqrt((x * x).sum(axis=-1, keepdims=True) + jnp.array(eps, dtype=x.dtype)) + + +def causal_depthwise_conv(x, kernel, config): + """`nnx.Conv(feature_group_count=C, padding='CAUSAL', use_bias=False)` as MaxText + calls it (`qwen3.Qwen3NextGatedDeltaNet`'s `conv1d`), in `config.dtype`; kernel `[K, 1, C]`. + + Output t is `sum_{i int32 documents 1, 2, ... a row, 0 on padding + (ids <= 0). A document starts wherever a valid token's id differs from the last valid token's before it, so an id + that comes back after another ([1, 2, 1]) is a new document ([1, 2, 3]), and padding inside one ([1, 0, 1]) does not + split it.""" + seg = jnp.maximum(segment_ids.astype(jnp.int32), 0) + active = jax.lax.associative_scan(lambda a, b: jnp.where(b > 0, b, a), seg, axis=-1) + prev_active = jnp.concatenate([active[..., :1] * 0, active[..., :-1]], axis=-1) + valid = seg > 0 + doc = jnp.cumsum((valid & (seg != prev_active)).astype(jnp.int32), axis=-1) + return jnp.where(valid, doc, 0).astype(jnp.int32) + + +def segmented_causal_conv(x, kernel, segment_ids, config): + """`causal_depthwise_conv` within documents (MaxText's gdn_packing.segmented_causal_depthwise_conv1d, its + single-device path): output t is `sum_{i 0)[..., None], xp, 0) + tap_seg = [segp[:, i : i + s] for i in range(k)] # the segment of each row's tap i + if config.gdn_conv_impl == "shift": + out = jnp.where((tap_seg[0] == seg)[..., None], xm[:, :s], 0).astype(jnp.float32) * w[0, 0] + for i in range(1, k): + out = out + jnp.where((tap_seg[i] == seg)[..., None], xm[:, i : i + s], 0).astype(jnp.float32) * w[i, 0] + else: + out = _ops.conv_general_dilated( + xm.astype(jnp.float32), + w, + window_strides=(1,), + padding="VALID", + dimension_numbers=("NHC", "HIO", "NHC"), + feature_group_count=c, + precision=_HI, + ) + if halo > 0: + cross = None # rows with a tap in another (valid) document + for i in range(halo): + hit = (seg > 0) & (tap_seg[i] > 0) & (tap_seg[i] != seg) + cross = hit if cross is None else cross | hit + taps = jnp.stack( + [jnp.where((cross & (tap_seg[i] == seg))[..., None], xm[:, i : i + s], 0) for i in range(k)], axis=2 + ) + out = jnp.where(cross[..., None], _ops.conv_taps(taps, w[:, 0, :]), out) + return jnp.where((seg > 0)[..., None], out, 0.0).astype(config.dtype) + + +def _segment_masks(segment_ids, n, c): + """MaxText's gdn_packing.prepare_jax_gdn_segment_masks, its single-device path with no initial state, on raw + segment ids `[B, S]` and the delta rule's N chunks of C: the per-chunk masks `[B, N, 1, ...]` of the packed rule. + + -> (valid [B,N,1,C] bool: a document's token, not padding (the S..N*C tail is padding of the row's last document); + cum [B,N,1,C,C] fp32: lower triangle within one document, the per-document cumulative decay's matmul; + strict, causal [B,N,1,C,C] bool: the strictly lower / lower triangle between valid tokens of one document; + m_in [B,N,1,C] fp32: 1 where a token continues the document the chunk's incoming state belongs to; + m_out [B,N,1,C] fp32: 1 where a token belongs to the document at the chunk's end, the one its state carries on; + m_keep [B,N,1,1] fp32: 1 where that document is the incoming state's, so the state is kept, decayed).""" + b, s = segment_ids.shape + seg = jnp.maximum(canonical_segment_ids(segment_ids), 0) + # signed: +d on document d's tokens, -d on padding after document d (0 before the first) + active = jax.lax.associative_scan(lambda x, y: jnp.where(y > 0, y, x), seg, axis=-1) + enc = jnp.where(seg > 0, seg, -active).astype(jnp.float32) + if n * c > s: + enc = jnp.concatenate([enc, jnp.repeat(-jnp.abs(enc[:, -1:]), n * c - s, axis=1)], axis=1) + seg_c = enc.reshape(b, n, 1, c) + valid = seg_c > 0.5 + act = jnp.abs(seg_c) + act_end = act[..., -1] # [B, N, 1] + seg_prev = jnp.concatenate([act_end[:, :1] * 0.0, act_end[:, :-1, :]], axis=1)[..., None] # [B, N, 1, 1] + # The triangles traced, as MaxText writes them: numpy constants change how XLA fuses what they mask, and the fp32 + # results by a rounding (the delta rule's, from the strict triangle on). + same_act = (jnp.abs(act[..., :, None] - act[..., None, :]) < 0.5) & (act[..., :, None] > 0.5) + cum = jnp.tril(jnp.ones((c, c), dtype=jnp.float32)) * same_act.astype(jnp.float32) + same_valid = (jnp.abs(seg_c[..., :, None] - seg_c[..., None, :]) < 0.5) & valid[..., :, None] + strict = jnp.tril(jnp.ones((c, c), dtype=bool), k=-1) & same_valid + causal = jnp.tril(jnp.ones((c, c), dtype=bool), k=0) & same_valid + act_last = act[..., -1:] + m_in = ((jnp.abs(seg_c - seg_prev) < 0.5) & (seg_prev > 0.5)).astype(jnp.float32) + m_out = ((jnp.abs(seg_c - act_last) < 0.5) & (act_last > 0.5)).astype(jnp.float32) + m_keep = ((jnp.abs(act_last - seg_prev) < 0.5) & (seg_prev > 0.5)).astype(jnp.float32) + return valid, cum, strict, causal, m_in, m_out, m_keep + + +# ------------------------------------------------------------ the inverse +def _block_doubling(s): + """MaxText's gdn_packing.block_doubling_unit_lower_inverse: `(I + s)^-1` for strictly-lower-triangular `s + [..., C, C]` (fp32), bottom up -- from 1 x 1 diagonal blocks (inverse 1), each level merges two neighbouring b x b + blocks with [[A11, 0], [A21, A22]]^-1 = [[A11^-1, 0], [-A22^-1 A21 A11^-1, A22^-1]], two matmuls at HIGHEST + (ceil(log2 C) levels, any C).""" + c = s.shape[-1] + ar = jnp.arange(c) + inv = _ops.broadcast_like(jnp.eye(c, dtype=jnp.float32), s) + blk = 1 + while blk < c: + # the lower-left blk x blk block of each 2 blk x 2 blk diagonal block: what inv has not folded in yet + cross = ((ar[:, None] // (2 * blk)) == (ar[None, :] // (2 * blk))) & ( + (ar[:, None] // blk) == (ar[None, :] // blk) + 1 + ) + off = jnp.matmul(jnp.matmul(inv, jnp.where(cross, s, 0.0), precision=_HI), inv, precision=_HI) + inv = inv - jnp.where(cross, off, 0.0) + blk *= 2 + return inv + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(1,)) +def unit_lower_inv(s, method="block_doubling"): + """`(I + s)^-1` for strictly-lower-triangular `s [..., C, C]`, as MaxText computes it under `gdn_chunk_inverse` + `method`: 'block_doubling' (`_block_doubling`; the default, as gdn_chunk_inverse's and MaxText's), or 'solve' + (MaxText's reference path, and what the Triton kernels' triangular solve stands for in their tests), + `solve_triangular(I + S, I, lower=True, unit_diagonal=True)` -- with the backward written out either way: + `dS = -tril(A^T dA A^T, -1)`.""" + if method == "block_doubling": + return _block_doubling(s) + if method != "solve": + raise ValueError(f"unit_lower_inv: method must be 'block_doubling' or 'solve', got {method!r}") + eye = jnp.eye(s.shape[-1], dtype=s.dtype) + return jax.scipy.linalg.solve_triangular(eye + s, _ops.broadcast_like(eye, s), lower=True, unit_diagonal=True) + + +def _unit_lower_inv_fwd(s, method): + a = unit_lower_inv(s, method) + return a, a + + +def _unit_lower_inv_bwd(method, a, g): + del method + at = a.swapaxes(-1, -2) + ds = -jnp.matmul(jnp.matmul(at, g, precision=_HI), at, precision=_HI) + c = a.shape[-1] + ds = jnp.where(jnp.tril(jnp.ones((c, c), dtype=bool), k=-1), ds, 0.0) + return (_ops.retype_like(ds, a),) + + +unit_lower_inv.defvjp(_unit_lower_inv_fwd, _unit_lower_inv_bwd) + + +# ------------------------------------------------------- the delta rule +def chunk_gated_delta_rule( + query, + key, + value, + g, + beta, + chunk_size, + use_qk_norm, + compute_dtype, + scan_impl="scan", + *, + segment_ids=None, + chunk_inverse="block_doubling", +): + """`jax_chunk_gated_delta_rule` (models/qwen3.py), same op order and dtypes. + + query/key `[B, S, Hk, Dk]`, value `[B, S, H, Dv]`, g / beta `[B, S, H]`, value + head j reading key head j // (H / Hk). Returns `o [B, S, H, Dv]` in query's + dtype. The cumulative decay, the masks, the inverse and the state + recurrence are fp32 at HIGHEST; q/k/v/beta are rounded to `compute_dtype` + first and the WY factors u, w are rounded back to it. S is padded up to a + multiple of `chunk_size` with zeros (g = 0 there: no decay, no update). + The initial state is zero, as in training. + + `segment_ids` `[B, S]` (packed documents, `Qwen35Config.gdn_packing`): the + state restarts at every document (`_segment_masks`), padding neither reads + nor writes it, and its output is zero. None: one sequence a row. + + `chunk_inverse` (`gdn_chunk_inverse`): how `unit_lower_inv` inverts the WY + matrix, which is built from k k^T at the key heads times fp32 beta and decay, + the key heads repeated in here, as MaxText's GDN builds it. + + `scan_impl` (config.gdn_scan_impl): 'scan', the inter-chunk recurrence as a + `lax.scan` (MaxText's); 'triton', Triton kernels (`gdn_triton`): with a + chunk of 16 / 32 / 64 the whole rule (`gdn_triton.chunk`, FUSED), else the + recurrence as one kernel each way and the chunk outputs batched over all + chunks in XLA: GPU only, per device (the MPMD pipeline's stage programs, + gdn_core='manual', or no mesh at all), the same math to fp32 rounding, and + with no packed documents. + """ + if scan_impl == "triton" and segment_ids is not None: + raise ValueError( + "gdn_scan_impl 'triton' has no packed documents: call the GDN without segment ids (as the MPMD pipeline " + "does) or set gdn_packing=False" + ) + initial_dtype = query.dtype + if use_qk_norm: + query = l2norm(query) + key = l2norm(key) + g = g.astype(jnp.float32) + query = query.astype(compute_dtype) + key = key.astype(compute_dtype) + value = value.astype(compute_dtype) + beta = beta.astype(compute_dtype) + scale = jax.lax.rsqrt(jnp.array(query.shape[-1], dtype=jnp.float32)).astype(compute_dtype) + query = query * scale + + b, s, hk, dk = key.shape + h, dv = value.shape[2], value.shape[-1] + if h % hk: + raise ValueError(f"value heads {h} vs key heads {hk}: the key heads, repeated here, must divide the value heads") + rep = h // hk + c = chunk_size + pad = (c - s % c) % c + if pad: + + def pad_fn(x): + return jnp.pad(x, ((0, 0), (0, pad)) + ((0, 0),) * (x.ndim - 2)) + + query, key, value, g, beta = map(pad_fn, (query, key, value, g, beta)) + n = query.shape[1] // c + + def to_chunk(x): # [B, S, Hx, D] -> [B, N, Hx, C, D] + return x.reshape(b, n, c, x.shape[2], -1).transpose(0, 1, 3, 2, 4) + + def to_chunk_s(x): # [B, S, H] -> [B, N, H, C] + return x.reshape(b, n, c, h).transpose(0, 1, 3, 2) + + def heads(x, axis): # key heads -> value heads (value head j <- key head j // rep) + return jnp.repeat(x, rep, axis=axis) if rep > 1 else x + + q_c, k_c, v_c = to_chunk(query), to_chunk(key), to_chunk(value) + g_c, beta_c = to_chunk_s(g), to_chunk_s(beta) + # The op order is MaxText's: any order gives the same values, but an fp32 program's last bits can depend on how XLA + # fuses it. + if segment_ids is None: + g_cum = jnp.cumsum(g_c, axis=-1) # fp32 + strict = jnp.tril(jnp.ones((c, c), dtype=bool), k=-1) + else: + valid, cum, strict, causal, m_in, m_out, m_keep = _segment_masks(segment_ids, n, c) + q_c = jnp.where(valid[..., None], q_c, 0.0) + k_c = jnp.where(valid[..., None], k_c, 0.0) + v_c = jnp.where(valid[..., None], v_c, 0.0) + g_c = jnp.where(valid, g_c, 0.0) + beta_c = jnp.where(valid, beta_c, 0.0) + g_cum = _ops.segment_cumsum(cum, g_c) # fp32, restarting at each document + if scan_impl == "triton": + _triton_context() + from maxtext.experimental.mpmd.jax.qwen35 import gdn_triton + + if gdn_triton.FUSED and gdn_triton.fused_supported(c, dk, dv): # the whole rule on kernels + o = gdn_triton.chunk(heads(q_c, 2), heads(k_c, 2), v_c, beta_c, g_cum, out_dtype=initial_dtype) + return o.transpose(0, 1, 3, 2, 4).reshape(b, -1, h, dv)[:, :s] + + # Intra-chunk WY factors (all chunks in parallel): the WY matrix from k k^T at the key heads (rounded to + # `compute_dtype` as it comes out of the matmul), repeated to the value heads, times fp32 beta and decay. + kk = heads(jnp.matmul(k_c, k_c.swapaxes(-1, -2), precision=_HI).astype(jnp.float32), 2) + g_diff = jnp.where(strict, g_cum[..., :, None] - g_cum[..., None, :], _NEG) + smat = jnp.where(strict, kk * (beta_c.astype(jnp.float32)[..., :, None] * jnp.exp(g_diff)), 0.0) + a = unit_lower_inv(smat, chunk_inverse) + v_beta = v_c * beta_c[..., None] + u = jnp.matmul(a, v_beta.astype(jnp.float32), precision=_HI).astype(compute_dtype) + k_beta = heads(k_c, 2) * beta_c[..., None] + decay_in = jnp.exp(g_cum) if segment_ids is None else jnp.exp(g_cum) * m_in + k_beta_g = k_beta.astype(jnp.float32) * decay_in[..., None] + w = jnp.matmul(a, k_beta_g, precision=_HI).astype(compute_dtype) + + if scan_impl == "triton": # the recurrence on kernels + from maxtext.experimental.mpmd.jax.qwen35 import gdn_triton + + o = gdn_triton.inter_chunk(heads(q_c, 2), heads(k_c, 2), u, w, g_cum) # [B, N, H, C, Dv] fp32 + return o.transpose(0, 1, 3, 2, 4).reshape(b, -1, h, dv)[:, :s].astype(initial_dtype) + if scan_impl != "scan": + raise ValueError(f"scan_impl must be 'scan' or 'triton', got {scan_impl!r}") + + # Inter-chunk recurrence over the state H [B, H, Dk, Dv]. + perm_v, perm_s = (1, 0, 2, 3, 4), (1, 0, 2, 3) + xs = (w.transpose(perm_v), u.transpose(perm_v), q_c.transpose(perm_v), k_c.transpose(perm_v), g_cum.transpose(perm_s)) + if segment_ids is not None: # each chunk's masks + xs += tuple(x.transpose(perm_v if x.ndim == 5 else perm_s) for x in (m_in, m_out, m_keep, causal, valid)) + + def step(state, xs_i): + w_i, u_i, q_i, k_i, g_i = xs_i[:5] + if segment_ids is None: + causal_i = jnp.tril(jnp.ones((c, c), dtype=bool)) + else: + m_in_i, m_out_i, m_keep_i, causal_i, valid_i = xs_i[5:] + # q k^T at the key heads, then the value heads + attn = heads(jnp.matmul(q_i, k_i.swapaxes(-1, -2), precision=_HI).astype(jnp.float32), 1) + q_i, k_i = heads(q_i, 1), heads(k_i, 1) + decay_q = jnp.exp(g_i) if segment_ids is None else jnp.exp(g_i) * m_in_i + q_g = q_i.astype(jnp.float32) * decay_q[..., None] + attn_inter = jnp.matmul(q_g, state, precision=_HI) + v_new = u_i.astype(jnp.float32) - jnp.matmul(w_i.astype(jnp.float32), state, precision=_HI) + gd = jnp.where(causal_i, g_i[..., :, None] - g_i[..., None, :], _NEG) + attn = jnp.where(causal_i, attn * jnp.exp(gd), 0.0) + o = attn_inter + jnp.matmul(attn, v_new, precision=_HI) + decay_state = jnp.exp(g_i[..., -1, None, None]) + if segment_ids is None: + decay_k = jnp.exp(g_i[..., -1, None] - g_i) + else: + o = jnp.where(valid_i[..., None], o, 0.0) + decay_state = decay_state * m_keep_i[..., None] + decay_k = jnp.exp(jnp.where(m_out_i > 0.5, g_i[..., -1, None] - g_i, _NEG)) * m_out_i + new_state = state * decay_state + k_dec = k_i.astype(jnp.float32) * decay_k[..., None] + new_state = new_state + jnp.matmul(k_dec.swapaxes(-1, -2), v_new, precision=_HI) + return new_state, o + + state0 = _ops.zeros((b, h, dk, dv), jnp.float32, batch_dim=0) + _, o = jax.lax.scan(step, state0, xs) + o = o.transpose(1, 0, 3, 2, 4).reshape(b, -1, h, dv)[:, :s] + return o.astype(initial_dtype) + + +def _triton_context(): + """gdn_scan_impl 'triton' runs its kernels per device on a GPU: refuse anywhere else, before a custom call + reaches a partitioner that would gather its operands (auto) or a backend without Triton.""" + from maxtext.experimental.mpmd.jax import sharding_mode as mode + + if jax.default_backend() != "gpu": + raise ValueError( + f"gdn_scan_impl 'triton' runs Triton kernels: it needs a GPU backend, not " + f"{jax.default_backend()!r} (gdn_scan_impl 'scan' runs anywhere)" + ) + if mode.context_mode() not in ("none", "manual"): + raise ValueError( + f"gdn_scan_impl 'triton' runs per device: under the {mode.context_mode()!r} sharding mode set " + "gdn_core='manual' (the rule mapped over the batch's devices), as the MPMD pipeline's stage " + "programs run it" + ) + + +def recurrent_gated_delta_rule(query, key, value, g, beta, use_qk_norm=True): + """The definitional per-token recurrence, in numpy float64 (a test oracle). + + HF's `torch_recurrent_gated_delta_rule`: with q, k l2-normalised and q scaled + by `Dk^-1/2`, `S <- S exp(g_t); d = beta_t (v_t - S^T k_t); S <- S + k_t d^T; + o_t = S^T q_t`. The decay applies before the delta update. + """ + q, k, v, g, beta = (np.asarray(t, np.float64) for t in (query, key, value, g, beta)) + if use_qk_norm: + q = q / np.sqrt((q * q).sum(-1, keepdims=True) + 1e-6) + k = k / np.sqrt((k * k).sum(-1, keepdims=True) + 1e-6) + q = q / np.sqrt(q.shape[-1]) + b, s, h, dk = k.shape + state = np.zeros((b, h, dk, v.shape[-1])) + out = np.zeros(v.shape) + for t in range(s): + state = state * np.exp(g[:, t])[:, :, None, None] + delta = (v[:, t] - np.einsum("bhkv,bhk->bhv", state, k[:, t])) * beta[:, t][..., None] + state = state + np.einsum("bhk,bhv->bhkv", k[:, t], delta) + out[:, t] = np.einsum("bhkv,bhk->bhv", state, q[:, t]) + return out + + +# ------------------------------------------------------------------ layer +def gated_rms_norm(params, x, gate, config): + """`Qwen3NextRMSNormGated`: plain RMSNorm over the last axis (ones init, no + offset), then `* silu(fp32(gate))`, rounded to `dtype`. + + `norm_numerics='fp32'`: the scaled value stays fp32 until that one rounding + (MaxText since 2026-09-10, whose inner RMSNorm has `dtype=float32`); 'bf16': + the normalised value is rounded to `dtype` and scaled there first (MaxText + before then; HF with bf16 weights). + """ + if config.norm_numerics == "fp32": + y = _ops.norm_fp32(params["rms_norm"], x, config) + else: + y = layers.rms_norm(params["rms_norm"], x, config, zero_centered=False) + return (y * jax.nn.silu(gate.astype(jnp.float32))).astype(config.dtype) + + +def gated_delta_net(params, x, segment_ids, config): + """`Qwen3NextGatedDeltaNet.__call__`, training path. `x [B, S, E]` -> `[B, S, E]`. + + `segment_ids` `[B, S]` (None: one sequence a row, nothing masked). Padding + (segment 0) is zeroed before the causal conv and its k, v and g after it, so + a padded token neither decays nor updates the state. Under `gdn_packing` + (MaxText's `packing`) every segment id is a document: the conv sums only the + document's own taps (`segmented_causal_conv`) and the delta rule restarts + the state at each one (`chunk_gated_delta_rule`'s `segment_ids`). Without it + the state and the conv window run on across documents (MaxText's + packing=false), while attention masks across them. + """ + b, s, _ = x.shape + hk, hv = config.gdn_num_key_heads, config.gdn_num_value_heads + dk, dv = config.gdn_key_head_dim, config.gdn_value_head_dim + vpk = config.gdn_v_per_k + qkvz = _ops.dense(params["in_proj_qkvz"], x, config) # [B, S, 2Hk*Dk + 2Hv*Dv] + ba = _ops.dense(params["in_proj_ba"], x, config) # [B, S, 2Hv] + # Per-KEY-HEAD interleaved columns: [q_h | k_h | v_{h,0..vpk-1} | z_{h,0..vpk-1}], + # and [b_{h,.} | a_{h,.}] -- value head j belongs to key head j // vpk. + mixed = qkvz.reshape(b, s, hk, 2 * dk + 2 * vpk * dv) + q, k, v_raw, z_raw = jnp.split(mixed, [dk, 2 * dk, 2 * dk + vpk * dv], axis=3) + v = _ops.regroup(v_raw, (b, s, hv, dv)) + z = _ops.regroup(z_raw, (b, s, hv, dv)) + b_raw, a_raw = jnp.split(ba.reshape(b, s, hk, 2 * vpk), [vpk], axis=3) + b_in = _ops.regroup(b_raw, (b, s, hv)) + a_in = _ops.regroup(a_raw, (b, s, hv)) + + # The conv runs over the flat channel order [q_all | k_all | v_all]. + qkv = jnp.concatenate([q.reshape(b, s, -1), k.reshape(b, s, -1), v.reshape(b, s, -1)], axis=-1) + packed = segment_ids is not None and config.gdn_packing + if segment_ids is not None: + qkv = jnp.where((segment_ids != 0)[..., None], qkv, 0.0) + if packed: + conv = segmented_causal_conv(qkv, params["conv1d"]["kernel"], segment_ids, config) + else: + conv = causal_depthwise_conv(qkv, params["conv1d"]["kernel"], config) + qkv = jax.nn.silu(conv.astype(jnp.float32)).astype(config.dtype) + qc, kc, vc = jnp.split(qkv, [config.gdn_key_dim, 2 * config.gdn_key_dim], axis=-1) + query = qc.reshape(b, s, hk, dk) + key = kc.reshape(b, s, hk, dk) + value = vc.reshape(b, s, hv, dv) + + # Gates: g in fp32 (HF's bf16 checkpoints: in `dtype`), beta in `dtype`. + gate_dtype = jnp.float32 + a_log = _ops.small_weight(params["A_log"], gate_dtype, config) + dt_bias = _ops.small_weight(params["dt_bias"], gate_dtype, config) + beta = jax.nn.sigmoid(b_in) + g = -jnp.exp(a_log) * jax.nn.softplus(a_in.astype(gate_dtype) + dt_bias) + if segment_ids is not None: + keep = segment_ids != 0 + key = jnp.where(keep[..., None, None], key, 0.0) + value = jnp.where(keep[..., None, None], value, 0.0) + g = jnp.where(keep[..., None], g, 0.0) + rule = functools.partial( + chunk_gated_delta_rule, + chunk_size=config.gdn_chunk_size, + use_qk_norm=config.use_qk_norm_in_gdn, + compute_dtype=config.dtype, + scan_impl=config.gdn_scan_impl, + chunk_inverse=config.gdn_chunk_inverse, + ) + core = _ops.gdn_core(rule, query, key, value, g, beta, config, segment_ids=segment_ids if packed else None) + y = gated_rms_norm(params["norm"], core, z, config).reshape(b, s, -1) + return _ops.dense(params["out_proj"], y, config) diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/gdn_triton.py b/src/maxtext/experimental/mpmd/jax/qwen35/gdn_triton.py new file mode 100644 index 0000000000..2f0d76bdab --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/gdn_triton.py @@ -0,0 +1,978 @@ +# 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 Gated DeltaNet's chunked delta rule as Triton kernels (`Qwen35Config.gdn_scan_impl='triton'`, GPU). + +`gdn.chunk_gated_delta_rule` runs the recurrence over the state `S [Dk, Dv]` as a 64-step `lax.scan` (4096 tokens, +chunks of 64) whose every step is a handful of small fp32 matmuls, elementwise ops and slice updates: on a GB200 at a +Qwen3.8 device's shapes (B=2, 128 value heads, Dk = Dv = 128) 10.0 ms forward and 27.4 ms forward + backward a layer +a microbatch. Here the part that is sequential -- per (batch, head) and chunk n, + + o_n = (q_n e^{g_n}) S; vn_n = u_n - w_n S; S <- a_n S + Kd_n^T vn_n, Kd_n = k_n * e_n[:, None] + +(u_n, w_n the chunk's WY factors, a_n = exp(g_n[-1]), e_n = exp(g_n[-1] - g_n), the state entering the chunk on +the right-hand sides) -- runs as ONE kernel that keeps S on chip and loops over the chunks (a program per +(batch * head, Dv tile): every op is linear in Dv, so Dv tiles are independent). The rest -- the WY factors +before it, the intra-chunk term `A_n vn_n` of the output after it -- runs on per-chunk kernels too (FUSED, below), +or, unfused, stays in XLA, batched over all chunks, at HIGHEST as before. The exps (e, a, e^g) are XLA's, computed +as the reference computes them; the kernels only multiply. + +The backward is the reverse recurrence, also one kernel: with lam = 0 after the last chunk and, for n = N-1 .. 0, + + dvt_n = dvn_n + Kd_n lam; lam <- (q_n e^{g_n})^T do_n + a_n lam - w_n^T dvt_n + +(do_n, dvn_n the cotangents of o_n and vn_n), it writes dvt_n and the lam after chunk n; then, batched over the +chunks (in XLA; FUSED: its `prod` kernel), du_n = dvt_n, dw_n = -dvt_n h_n^T, d(q e^g)_n = do_n h_n^T, +dKd_n = vn_n lam_n^T (-> dk_n, de_n) and da_n = , h_n the state entering chunk n -- which the +differentiated forward stores (the undifferentiated one never writes it). XLA's autodiff (FUSED: `chunk_rule`'s +VJP) carries de, da and d(e^g) on to g through the exps. + +Every kernel matmul pairs an operand whose values are exact in the compute dtype (q, k, w: bf16) with an fp32 one +(the state, its cotangent, vn scaled by a decay); the expressions are arranged so (`(q e^g) S = e^g (q S)`, +`(k e)^T vn = k^T (e vn)`), and the fp32 side is split into three bf16 parts -- three bf16 tensor-core products, +fp32's 24 bits ('bf16x3e', DEFAULT_PRECISION); fp32 compute uses Triton's 'tf32x3'. Triton's 'ieee' fp32 dot runs +on the FMA units, several times slower than the scan it replaces. Summed in another order than cuBLAS's, the +result matches the scan to fp32 rounding, not bitwise; in bf16 compute it is as far from an fp32-compute run as the +scan is (gdn_kernels_test). + +FUSED (`chunk` / `chunk_rule`: the default under 'triton' where it applies, chunks of 16, 32 or 64 -- the model's +64): the rest of the rule on kernels as well, a program per (batch, chunk, head), so that XLA keeps only the layout +changes, the exps and the decays' shares of dg -- + + wy_fwd smat = (k beta) k^T decay-masked, A = (I + smat)^-1 (its 16-row diagonal blocks by forward + substitution, then the block rows X_i = X_ii (E_i - sum_{k dq, dk, and the decay's share of dg + -- the recurrence's backward kernel -- + prod the per-chunk products: dw = -dvt h^T, d(q e^g) = do h^T, dKd = vn lam^T, da = (dq whole) + wy_bwd the WY factors' backward: dA = du (v beta)^T + (dw (k beta)^T) e^{g_j}, dS = -A^T dA A^T -> dk, dv, + dbeta, dg (dk, dv whole) + +Operands pair as in the recurrence: one exact in bf16 (q, k, v, beta; the output's cotangent when the output is in +the compute dtype) against an fp32 one split three ways. The products of two fp32 operands (A against the +cotangents, P against vn, the states against theirs) split both into two bf16 parts and take three products +('bf16x3': the dropped terms are 2^-16 of the operands' scale, under the bf16 rounding of what bf16 compute +returns; TWO_SIDED); in fp32 compute those are 'tf32x3' too. The 16 x 16 solves and the block rows run at 'ieee'. + +On a GB200 at a Qwen3.8 device's shapes (bf16 compute), forward and forward + backward a layer a microbatch, and +XLA's temporaries for each: + the scan 9.9 ms 27.4 ms 2.0 GiB 8.3 GiB + the recurrence's kernels 5.5 14.5 2.5 6.5 + FUSED 3.7 10.7 1.8 5.8 +(the kernels of FUSED's forward + backward, ms: wy_fwd 1.55, recurrence 1.46, out 0.36 | out_bwd 1.04, recurrence +1.70, prod 1.90, wy_bwd 2.08; the rest, ~0.6 ms, XLA's layout changes, l2norm and casts). Against the scan in fp32 +compute on the same bf16 inputs, FUSED's output and five gradients are as close as the bf16 scan's or closer (rms +4.3e-3 .. 5.9e-3 of each tensor's, the scan's 4.9e-3 .. 7.2e-3). + +Memory: h [B, N, H, Dk, Dv] fp32 (1.07 GB at the shapes above) and vn (0.54 GB) are the backward's residuals (FUSED +adds A, 0.27 GB), lam (1.07 GB) and dvt (0.54 GB) its temporaries -- the scan's own VJP keeps its per-step carries +(the same 1.07 GB) and more. +""" + +from __future__ import annotations + +import functools + +import jax +import jax.numpy as jnp + +_HI = jax.lax.Precision.HIGHEST +PRECISIONS = ("ieee", "tf32x3", "tf32", "tf32x2e", "bf16x3e") +EXACT_PRECISIONS = ("tf32x2e", "bf16x3e") # these need q, k, w exact in the split's head: bf16 or f16 for +# 'tf32x2e' (10 mantissa bits), bf16 alone for 'bf16x3e' (7) +# The kernels' dots in bf16 / f16 compute: 'bf16x3e' -- the fp32 operand split into three bf16 parts against the +# exact-in-bf16 one (q, k or w), three bf16 tensor-core products: fp32's 24 bits. In fp32 compute 'tf32x3' (three +# tf32 products, Triton's split of both operands: 9e-7 of HIGHEST's result at these shapes). Triton's 'ieee' fp32 +# dot runs on the FMA units, 4x slower than the scan it replaces on a GB200. On a GB200 at a Qwen3.8 device's +# shapes, the rule's forward + backward unfused: bf16x3e 14.5 ms, tf32x2e 14.4, tf32x3 16.1, ieee 120; the scan 27.4. +DEFAULT_PRECISION = "bf16x3e" + + +def supported(chunk, dk, dv): + """The kernels' shape limits: the chunk and both head dims powers of two, at least 16 (tl.arange and tl.dot).""" + return all(x >= 16 and x & (x - 1) == 0 for x in (chunk, dk, dv)) + + +def default_block_v(dv): + """The Dv tile a program carries (64 on a GB200: 128 with 8 warps ties it, 32 is 3% slower).""" + return min(dv, 64) + + +@functools.cache +def _kernels(): + import triton + import triton.language as tl + + @triton.jit + def mm(a, b, PREC: tl.constexpr): + # a @ b with fp32 accumulation. 'tf32x2e' takes an `a` whose values are exact in tf32 (bf16 or f16 q, k, w), + # 'bf16x3e' one exact in bf16: b is split into a tf32 head and tail (two tf32 products) or into three bf16 parts + # (three bf16 products, b to fp32's 24 bits); the others are Triton's own precisions on fp32 operands. + if PREC == "tf32x2e": + af = a.to(tl.float32) + hi = (b.to(tl.uint32, bitcast=True) & 0xFFFFE000).to(tl.float32, bitcast=True) + return tl.dot(af, b - hi, acc=tl.dot(af, hi, input_precision="tf32"), input_precision="tf32") + elif PREC == "bf16x3e": + ab = a.to(tl.bfloat16) + b1 = b.to(tl.bfloat16) + r = b - b1.to(tl.float32) + b2 = r.to(tl.bfloat16) + b3 = (r - b2.to(tl.float32)).to(tl.bfloat16) + return tl.dot(ab, b3, acc=tl.dot(ab, b2, acc=tl.dot(ab, b1))) + else: + return tl.dot(a.to(tl.float32), b, input_precision=PREC) + + @triton.jit + def fwd_kernel( + u_ptr, + w_ptr, + k_ptr, + e_ptr, + a_ptr, + q_ptr, + eg_ptr, + o_ptr, + vn_ptr, + h_ptr, + N: tl.constexpr, + H: tl.constexpr, + C: tl.constexpr, + DK: tl.constexpr, + DV: tl.constexpr, + BV: tl.constexpr, + PREC: tl.constexpr, + STORE_H: tl.constexpr, + ): + pid_bh = tl.program_id(0) + pid_v = tl.program_id(1) + b = (pid_bh // H).to(tl.int64) + hh = (pid_bh % H).to(tl.int64) + offs_c = tl.arange(0, C) + offs_k = tl.arange(0, DK) + offs_v = pid_v * BV + tl.arange(0, BV) + s = tl.zeros((DK, BV), dtype=tl.float32) + for n in range(N): + bnh = (b * N + n) * H + hh # [B, N, H, ...] layouts throughout + rows = bnh * C + offs_c + ck = rows[:, None] * DK + offs_k[None, :] + cv = rows[:, None] * DV + offs_v[None, :] + w = tl.load(w_ptr + ck) # [C, DK], the compute dtype + k = tl.load(k_ptr + ck) + q = tl.load(q_ptr + ck) + u = tl.load(u_ptr + cv).to(tl.float32) # [C, BV] + e = tl.load(e_ptr + rows) # [C] + eg = tl.load(eg_ptr + rows) + a = tl.load(a_ptr + bnh) + if STORE_H: # h_n = S, for the backward + tl.store(h_ptr + (bnh * DK + offs_k)[:, None] * DV + offs_v[None, :], s) + tl.store(o_ptr + cv, eg[:, None] * mm(q, s, PREC)) # (q e^g) h_n + vn = u - mm(w, s, PREC) + tl.store(vn_ptr + cv, vn) + s = s * a + mm(tl.trans(k), vn * e[:, None], PREC) # (k e)^T vn + + @triton.jit + def bwd_kernel( + w_ptr, + k_ptr, + e_ptr, + a_ptr, + q_ptr, + eg_ptr, + do_ptr, + dvn_ptr, + dvt_ptr, + lam_ptr, + N: tl.constexpr, + H: tl.constexpr, + C: tl.constexpr, + DK: tl.constexpr, + DV: tl.constexpr, + BV: tl.constexpr, + PREC: tl.constexpr, + ): + pid_bh = tl.program_id(0) + pid_v = tl.program_id(1) + b = (pid_bh // H).to(tl.int64) + hh = (pid_bh % H).to(tl.int64) + offs_c = tl.arange(0, C) + offs_k = tl.arange(0, DK) + offs_v = pid_v * BV + tl.arange(0, BV) + lam = tl.zeros((DK, BV), dtype=tl.float32) # lam_{n+1}: the cotangent of the state after chunk n + for i in range(N): + n = N - 1 - i + bnh = (b * N + n) * H + hh + rows = bnh * C + offs_c + ck = rows[:, None] * DK + offs_k[None, :] + cv = rows[:, None] * DV + offs_v[None, :] + tl.store(lam_ptr + (bnh * DK + offs_k)[:, None] * DV + offs_v[None, :], lam) + w = tl.load(w_ptr + ck) + k = tl.load(k_ptr + ck) + q = tl.load(q_ptr + ck) + e = tl.load(e_ptr + rows) + eg = tl.load(eg_ptr + rows) + a = tl.load(a_ptr + bnh) + do = tl.load(do_ptr + cv) + dvn = tl.load(dvn_ptr + cv) + dvt = dvn + e[:, None] * mm(k, lam, PREC) # + (k e) lam + tl.store(dvt_ptr + cv, dvt) + dh = mm(tl.trans(q), do * eg[:, None], PREC) # the cotangent of h_n + lam = dh + lam * a - mm(tl.trans(w), dvt, PREC) + + return fwd_kernel, bwd_kernel + + +# The launch: warps a program and the software-pipelining depth of the chunk loop (a GB200 at a Qwen3.8 device's +# shapes: 4 warps, no pipelining, at Dv tiles of 64; deeper pipelines ran slower). +LAUNCH = dict(num_warps=4, num_stages=1) + + +def _launch(kernel, args, out_type, b, h, n, c, dk, dv, block_v, precision, name, **meta): + import jax_triton as jt + + if dv % block_v: + raise ValueError(f"gdn_triton: Dv {dv} is not a multiple of the block {block_v}") + return jt.triton_call( + *args, + kernel=kernel, + out_type=out_type, + grid=(b * h, dv // block_v), + name=name, + N=n, + H=h, + C=c, + DK=dk, + DV=dv, + BV=block_v, + PREC=precision, + **meta, + **LAUNCH, + ) + + +def _fwd_call(u, w, k, e, a, q, eg, block_v, precision, store_h): + """The forward kernel -> (o_inter, vn, h): o_inter [B, N, H, C, Dv] = (q e^g) h_n, vn [B, N, H, C, Dv], h + [B, N, H, Dk, Dv] the state entering each chunk (store_h; else a placeholder never written). All fp32.""" + b, n, h, c, dk = w.shape + dv = u.shape[-1] + f32 = jnp.float32 + out = ( + jax.ShapeDtypeStruct((b, n, h, c, dv), f32), + jax.ShapeDtypeStruct((b, n, h, c, dv), f32), + jax.ShapeDtypeStruct((b, n, h, dk, dv) if store_h else (1,), f32), + ) + fwd, _ = _kernels() + return _launch( + fwd, + (u, w, k, e.astype(f32), a.astype(f32), q, eg.astype(f32)), + out, + b, + h, + n, + c, + dk, + dv, + block_v, + precision, + "gdn_scan_fwd", + STORE_H=bool(store_h), + ) + + +def _bwd_call(w, k, e, a, q, eg, do, dvn, block_v, precision): + """The reverse recurrence -> (dvt, lam): dvt_i the total cotangent of vn_i, lam_i that of the state after + chunk i (lam_{N-1} = 0); the cotangent of h_i, (q_i e^{g_i})^T do_i, is formed inside.""" + b, n, h, c, dk = w.shape + dv = do.shape[-1] + f32 = jnp.float32 + out = (jax.ShapeDtypeStruct((b, n, h, c, dv), f32), jax.ShapeDtypeStruct((b, n, h, dk, dv), f32)) + _, bwd = _kernels() + return _launch( + bwd, + (w, k, e.astype(f32), a.astype(f32), q, eg.astype(f32), do.astype(f32), dvn.astype(f32)), + out, + b, + h, + n, + c, + dk, + dv, + block_v, + precision, + "gdn_scan_bwd", + ) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(7, 8)) +def scan(u, w, k, e, a, q, eg, block_v, precision): + """The inter-chunk recurrence (module docstring) -> (o_inter, vn), both fp32. + + u [B, N, H, C, Dv], w, k, q [B, N, H, C, Dk] (any float dtype: read as fp32), e, eg [B, N, H, C] and + a [B, N, H] fp32; o_inter = (q e^g) h_n with h_n the state entering chunk n (zero for the first), vn = u - w h_n. + Undifferentiated, h is never written; differentiated, it is the backward's residual.""" + o, vn, _ = _fwd_call(u, w, k, e, a, q, eg, block_v, precision, store_h=False) + return o, vn + + +def _scan_fwd(u, w, k, e, a, q, eg, block_v, precision): + o, vn, h = _fwd_call(u, w, k, e, a, q, eg, block_v, precision, store_h=True) + return (o, vn), (jnp.zeros((0,), u.dtype), w, k, e, a, q, eg, h, vn) + + +def _scan_bwd(block_v, precision, res, cts): + u0, w, k, e, a, q, eg, h, vn = res + do, dvn = cts + f32 = jnp.float32 + dvt, lam = _bwd_call(w, k, e, a, q, eg, do, dvn, block_v, precision) + ht = h.swapaxes(-1, -2) + dw = -jnp.matmul(dvt, ht, precision=_HI) + dqg = jnp.matmul(do.astype(f32), ht, precision=_HI) + dkd = jnp.matmul(vn, lam.swapaxes(-1, -2), precision=_HI) + da = jnp.sum(h * lam, axis=(-2, -1)) + ef, egf = e.astype(f32), eg.astype(f32) + dk = dkd * ef[..., None] + de = jnp.sum(dkd * k.astype(f32), axis=-1) + dq = dqg * egf[..., None] + deg = jnp.sum(dqg * q.astype(f32), axis=-1) + return ( + dvt.astype(u0.dtype), + dw.astype(w.dtype), + dk.astype(k.dtype), + de.astype(e.dtype), + da.astype(a.dtype), + dq.astype(q.dtype), + deg.astype(eg.dtype), + ) + + +scan.defvjp(_scan_fwd, _scan_bwd) + + +# ------------------------------------------------------------------ the whole rule on kernels (FUSED) +# +# The kernels above take the recurrence; the rest of the rule -- the WY factors (the intra-chunk triangular solve +# among them), the output's intra-chunk term and every backward product -- ran in XLA, fp32 at HIGHEST, which on a +# GPU is CUDA-core SGEMMs and a batched trsm (on a GB200 ~5 + 1.7 s of a 65 s Qwen3.8 step on a stage with two GDN +# layers). With FUSED, `chunk_rule` runs them as per-chunk kernels too (the module docstring: wy_fwd, out, out_bwd, +# prod, wy_bwd), one program a (batch, chunk, head), every product on the tensor cores. False: the unfused path. +FUSED = True +FUSED_CHUNKS = (16, 32, 64) # wy_fwd's 16-row blocks, at most 4 of them + + +def fused_supported(chunk, dk, dv): + """Shapes `chunk_rule` takes: `supported`'s and a chunk of 16, 32 or 64 rows.""" + return supported(chunk, dk, dv) and chunk in FUSED_CHUNKS + + +@functools.cache +def _chunk_kernels(): + import triton + import triton.language as tl + + @triton.jit + def mm(a, b, acc, PREC: tl.constexpr): + # acc + a @ b, `a` exact in the compute dtype against `b` fp32 split three ways (bf16x3e) or two (tf32x2e). + # Every helper accumulates into the `acc` it is handed (a loop's carried sum stays the MMAs' accumulator) + if PREC == "tf32x2e": + af = a.to(tl.float32) + hi = (b.to(tl.uint32, bitcast=True) & 0xFFFFE000).to(tl.float32, bitcast=True) + return tl.dot(af, b - hi, acc=tl.dot(af, hi, acc=acc, input_precision="tf32"), input_precision="tf32") + elif PREC == "bf16x3e": + ab = a.to(tl.bfloat16) + b1 = b.to(tl.bfloat16) + r = b - b1.to(tl.float32) + b2 = r.to(tl.bfloat16) + b3 = (r - b2.to(tl.float32)).to(tl.bfloat16) + return tl.dot(ab, b3, acc=tl.dot(ab, b2, acc=tl.dot(ab, b1, acc=acc))) + else: + return tl.dot(a.to(tl.float32), b, acc=acc, input_precision=PREC) + + @triton.jit + def mme(a, b, acc, PREC: tl.constexpr): + # acc + a @ b, both exact in the compute dtype (bf16 / f16: their products are exact in fp32): one native product + if PREC == "bf16x3e" or PREC == "tf32x2e": + return tl.dot(a, b, acc=acc) + else: + return tl.dot(a.to(tl.float32), b.to(tl.float32), acc=acc, input_precision=PREC) + + @triton.jit + def mml(a, b, acc, PREC: tl.constexpr): + # acc + a @ b, `a` fp32 split three ways (bf16x3e) or two (tf32x2e) against a `b` exact in the compute dtype + if PREC == "bf16x3e": + a1 = a.to(tl.bfloat16) + r = a - a1.to(tl.float32) + a2 = r.to(tl.bfloat16) + a3 = (r - a2.to(tl.float32)).to(tl.bfloat16) + bb = b.to(tl.bfloat16) + return tl.dot(a3, bb, acc=tl.dot(a2, bb, acc=tl.dot(a1, bb, acc=acc))) + elif PREC == "tf32x2e": + bf = b.to(tl.float32) + hi = (a.to(tl.uint32, bitcast=True) & 0xFFFFE000).to(tl.float32, bitcast=True) + return tl.dot(a - hi, bf, acc=tl.dot(hi, bf, acc=acc, input_precision="tf32"), input_precision="tf32") + else: + return tl.dot(a, b.to(tl.float32), acc=acc, input_precision=PREC) + + @triton.jit + def mmf(a, b, acc, PREC: tl.constexpr): + # acc + a @ b, both fp32 and neither exact. 'bf16x3': each split in two bf16 parts, three bf16 products (the + # dropped terms 2^-16 of |a||b|: below the bf16 rounding of what bf16 compute returns); else Triton's own + # ('tf32x3': three tf32 products, ~fp32's precision) + if PREC == "bf16x3": + a1 = a.to(tl.bfloat16) + a2 = (a - a1.to(tl.float32)).to(tl.bfloat16) + b1 = b.to(tl.bfloat16) + b2 = (b - b1.to(tl.float32)).to(tl.bfloat16) + return tl.dot(a2, b1, acc=tl.dot(a1, b2, acc=tl.dot(a1, b1, acc=acc))) + else: + return tl.dot(a, b, acc=acc, input_precision=PREC) + + @triton.jit + def wy_fwd_kernel( + k_ptr, + v_ptr, + beta_ptr, + g_ptr, + a_ptr, + u_ptr, + w_ptr, + C: tl.constexpr, + DK: tl.constexpr, + DV: tl.constexpr, + NB: tl.constexpr, + BD: tl.constexpr, + PREC: tl.constexpr, + FPREC: tl.constexpr, + ): + pid = tl.program_id(0).to(tl.int64) + base = pid * C + o16 = tl.arange(0, 16) + oc = tl.arange(0, C) + ok = tl.arange(0, DK) + od = tl.arange(0, BD) + eye = (o16[:, None] == o16[None, :]).to(tl.float32) + for i in tl.static_range(NB): + ri = base + i * 16 + o16 + k_i = tl.load(k_ptr + ri[:, None] * DK + ok[None, :]) + g_i = tl.load(g_ptr + ri) + kb_i = (k_i.to(tl.float32) * tl.load(beta_ptr + ri).to(tl.float32)[:, None]).to(k_i.dtype) + strict = o16[:, None] > o16[None, :] + s_ii = mme(kb_i, tl.trans(k_i), tl.zeros((16, 16), dtype=tl.float32), PREC) + s_ii = tl.where(strict, s_ii * tl.exp(tl.where(strict, g_i[:, None] - g_i[None, :], 0.0)), 0.0) + x_ii = eye # (I + S_ii)^-1, row by row: x_r = e_r - sum_{j= oc[None, :] + p = qk_tiles(q_ptr, k_ptr, rows, DK, BD, C, PREC) + p = tl.where(causal, p * tl.exp(tl.where(causal, g[:, None] - g[None, :], 0.0)), 0.0) + for t in tl.range(0, DV // BD): + cv = rows[:, None] * DV + (t * BD + od)[None, :] + o = tl.load(oi_ptr + cv) + mmf(p, tl.load(vn_ptr + cv), tl.zeros((C, BD), dtype=tl.float32), FPREC) + tl.store(o_ptr + cv, o.to(o_ptr.dtype.element_ty)) + + @triton.jit + def out_bwd_kernel( + q_ptr, + k_ptr, + g_ptr, + do_ptr, + vn_ptr, + dvn_ptr, + dq_ptr, + dk_ptr, + dg_ptr, + C: tl.constexpr, + DK: tl.constexpr, + DV: tl.constexpr, + BD: tl.constexpr, + PREC: tl.constexpr, + FPREC: tl.constexpr, + DO_EXACT: tl.constexpr, + ): + pid = tl.program_id(0).to(tl.int64) + oc = tl.arange(0, C) + od = tl.arange(0, BD) + rows = pid * C + oc + g = tl.load(g_ptr + rows) + causal = oc[:, None] >= oc[None, :] + dm = tl.where(causal, tl.exp(tl.where(causal, g[:, None] - g[None, :], 0.0)), 0.0) + qk = qk_tiles(q_ptr, k_ptr, rows, DK, BD, C, PREC) + pt = tl.trans(qk * dm) + dp = tl.zeros((C, C), dtype=tl.float32) + for t in tl.range(0, DV // BD): + cv = rows[:, None] * DV + (t * BD + od)[None, :] + do = tl.load(do_ptr + cv) + if DO_EXACT: # the cotangent of an output in the compute dtype: exact there + tl.store(dvn_ptr + cv, mml(pt, do, tl.zeros((C, BD), dtype=tl.float32), PREC)) # P^T do + dp = mm(do, tl.trans(tl.load(vn_ptr + cv)), dp, PREC) # do vn^T + else: + tl.store(dvn_ptr + cv, mmf(pt, do.to(tl.float32), tl.zeros((C, BD), dtype=tl.float32), FPREC)) + dp = mmf(do.to(tl.float32), tl.trans(tl.load(vn_ptr + cv)), dp, FPREC) + dqk = dp * dm + dqkt = tl.trans(dqk) + for t in tl.range(0, DK // BD): + ck = rows[:, None] * DK + (t * BD + od)[None, :] + tl.store(dq_ptr + ck, mml(dqk, tl.load(k_ptr + ck), tl.zeros((C, BD), dtype=tl.float32), PREC)) + tl.store(dk_ptr + ck, mml(dqkt, tl.load(q_ptr + ck), tl.zeros((C, BD), dtype=tl.float32), PREC)) + dl = dqk * qk # d log D: + row i, - column j + tl.store(dg_ptr + rows, tl.sum(dl, axis=1) - tl.sum(dl, axis=0)) + + @triton.jit + def prod_kernel( + dvt_ptr, + h_ptr, + do_ptr, + vn_ptr, + lam_ptr, + k_ptr, + q_ptr, + e_ptr, + eg_ptr, + dqo_ptr, + dko_ptr, + dw_ptr, + dq_ptr, + dk_ptr, + deg_ptr, + de_ptr, + da_ptr, + C: tl.constexpr, + DK: tl.constexpr, + DV: tl.constexpr, + BK: tl.constexpr, + BD: tl.constexpr, + PREC: tl.constexpr, + FPREC: tl.constexpr, + DO_EXACT: tl.constexpr, + ): + pid = tl.program_id(0).to(tl.int64) + pk = tl.program_id(1) + nk = DK // BK + oc = tl.arange(0, C) + obk = pk * BK + tl.arange(0, BK) + od = tl.arange(0, BD) + rows = pid * C + oc + hrow = (pid * DK + obk)[:, None] * DV # this K tile's rows of h / lam + ndw = tl.zeros((C, BK), dtype=tl.float32) + dqg = tl.zeros((C, BK), dtype=tl.float32) + dkd = tl.zeros((C, BK), dtype=tl.float32) + da = tl.zeros((BK, BD), dtype=tl.float32) + for t in tl.range(0, DV // BD): + ov = t * BD + od + cv = rows[:, None] * DV + ov[None, :] + ht = tl.trans(tl.load(h_ptr + hrow + ov[None, :])) + lam = tl.load(lam_ptr + hrow + ov[None, :]) + ndw = mmf(tl.load(dvt_ptr + cv), ht, ndw, FPREC) # -dw + if DO_EXACT: + dqg = mm(tl.load(do_ptr + cv), ht, dqg, PREC) + else: + dqg = mmf(tl.load(do_ptr + cv).to(tl.float32), ht, dqg, FPREC) + dkd = mmf(tl.load(vn_ptr + cv), tl.trans(lam), dkd, FPREC) + da += tl.trans(ht) * lam + ckb = rows[:, None] * DK + obk[None, :] + tl.store(dw_ptr + ckb, -ndw) + dq = dqg * tl.load(eg_ptr + rows)[:, None] + tl.load(dqo_ptr + ckb) # + the intra-chunk term's + tl.store(dq_ptr + ckb, dq.to(dq_ptr.dtype.element_ty)) + tl.store(deg_ptr + (pid * nk + pk) * C + oc, tl.sum(dqg * tl.load(q_ptr + ckb).to(tl.float32), axis=1)) + tl.store(dk_ptr + ckb, dkd * tl.load(e_ptr + rows)[:, None] + tl.load(dko_ptr + ckb)) + tl.store(de_ptr + (pid * nk + pk) * C + oc, tl.sum(dkd * tl.load(k_ptr + ckb).to(tl.float32), axis=1)) + tl.store(da_ptr + pid * nk + pk, tl.sum(tl.sum(da, axis=1), axis=0)) + + @triton.jit + def wy_bwd_kernel( + k_ptr, + v_ptr, + beta_ptr, + g_ptr, + a_ptr, + du_ptr, + dw_ptr, + dkin_ptr, + dk_ptr, + dv_ptr, + dbeta_ptr, + dg_ptr, + C: tl.constexpr, + DK: tl.constexpr, + DV: tl.constexpr, + BD: tl.constexpr, + PREC: tl.constexpr, + FPREC: tl.constexpr, + ): + pid = tl.program_id(0).to(tl.int64) + oc = tl.arange(0, C) + od = tl.arange(0, BD) + rows = pid * C + oc + beta = tl.load(beta_ptr + rows).to(tl.float32) + g = tl.load(g_ptr + rows) + eg = tl.exp(g) + a = tl.load(a_ptr + rows[:, None] * C + oc[None, :]) + at = tl.trans(a) + # dA = du vb^T + (dw kb^T) e^{g_j} (u = A vb, w = (A e^g) kb), and kb k^T for S's decay gradient + da_u = tl.zeros((C, C), dtype=tl.float32) + for t in tl.range(0, DV // BD): + cv = rows[:, None] * DV + (t * BD + od)[None, :] + v = tl.load(v_ptr + cv) + da_u = mml(tl.load(du_ptr + cv), tl.trans((v.to(tl.float32) * beta[:, None]).to(v.dtype)), da_u, PREC) + da_w = tl.zeros((C, C), dtype=tl.float32) + kk = tl.zeros((C, C), dtype=tl.float32) + for t in tl.range(0, DK // BD): + ck = rows[:, None] * DK + (t * BD + od)[None, :] + k = tl.load(k_ptr + ck) + kb = (k.to(tl.float32) * beta[:, None]).to(k.dtype) + da_w = mml(tl.load(dw_ptr + ck), tl.trans(kb), da_w, PREC) + kk = mme(kb, tl.trans(k), kk, PREC) + zc = tl.zeros((C, C), dtype=tl.float32) + ds = -mmf(mmf(at, da_u + da_w * eg[None, :], zc, FPREC), at, zc, FPREC) # A = (I + S)^-1 + strict = oc[:, None] > oc[None, :] + dkk = tl.where(strict, ds * tl.exp(tl.where(strict, g[:, None] - g[None, :], 0.0)), 0.0) + dl = dkk * kk + dkkt = tl.trans(dkk) + dbeta = tl.zeros((C,), dtype=tl.float32) + dgw = tl.zeros((C,), dtype=tl.float32) + for t in tl.range(0, DK // BD): + ck = rows[:, None] * DK + (t * BD + od)[None, :] + k = tl.load(k_ptr + ck) + kf = k.to(tl.float32) + kb = (kf * beta[:, None]).to(k.dtype) + dkbe = mmf(at, tl.load(dw_ptr + ck), tl.zeros((C, BD), dtype=tl.float32), FPREC) # w = A (kb e^g) + dkb = mml(dkk, k, dkbe * eg[:, None], PREC) + dk = mml(dkkt, kb, dkb * beta[:, None], PREC) + tl.load(dkin_ptr + ck) + tl.store(dk_ptr + ck, dk.to(dk_ptr.dtype.element_ty)) + dbeta += tl.sum(dkb * kf, axis=1) + dgw += tl.sum(dkbe * kb.to(tl.float32), axis=1) + for t in tl.range(0, DV // BD): + cv = rows[:, None] * DV + (t * BD + od)[None, :] + dvb = mmf(at, tl.load(du_ptr + cv), tl.zeros((C, BD), dtype=tl.float32), FPREC) + tl.store(dv_ptr + cv, (dvb * beta[:, None]).to(dv_ptr.dtype.element_ty)) + dbeta += tl.sum(dvb * tl.load(v_ptr + cv).to(tl.float32), axis=1) + tl.store(dbeta_ptr + rows, dbeta) + tl.store(dg_ptr + rows, tl.sum(dl, axis=1) - tl.sum(dl, axis=0) + eg * dgw) + + return dict(wy_fwd=wy_fwd_kernel, out=out_kernel, out_bwd=out_bwd_kernel, prod=prod_kernel, wy_bwd=wy_bwd_kernel) + + +# Each per-chunk kernel's launch: warps a program, the width of the D tiles its loops take, the software-pipelining +# depth of those loops -- the best of BD 16 / 32 / 64 / 128 x 4 / 8 warps x 1 / 2 / 3 stages on a GB200 at a +# Qwen3.8 device's shapes (ms: wy_fwd 1.54, out 0.36, out_bwd 1.05, prod 1.91, wy_bwd 2.08; the worst of the +# 4-warp configurations 10-60% slower, 2 warps several times so) +CHUNK_LAUNCH = dict( + wy_fwd=dict(num_warps=4, BD=128, num_stages=1), + out=dict(num_warps=4, BD=32, num_stages=2), + out_bwd=dict(num_warps=4, BD=128, num_stages=1), + prod=dict(num_warps=8, BD=64, num_stages=1), + wy_bwd=dict(num_warps=4, BD=64, num_stages=1), +) + + +# The precision of the products whose operands are both fp32 (neither exact in the compute dtype), by the compute +# precision: in bf16 / f16 compute (whose results are rounded to it) 'bf16x3', two bf16 parts a side, three bf16 +# products; in fp32 compute its own precision ('tf32x3', or the tests' 'ieee'). +TWO_SIDED = {"bf16x3e": "bf16x3", "tf32x2e": "bf16x3"} + + +def _call(name, args, out_type, grid, **meta): + import jax_triton as jt + + launch = CHUNK_LAUNCH[name] + bd = min(launch["BD"], meta.get("DK", 1 << 30), meta.get("DV", 1 << 30)) + fprec = TWO_SIDED.get(meta["PREC"], meta["PREC"]) + return jt.triton_call( + *args, + kernel=_chunk_kernels()[name], + out_type=out_type, + grid=grid, + name=f"gdn_{name}", + num_warps=launch["num_warps"], + num_stages=launch["num_stages"], + BD=bd, + FPREC=fprec, + **meta, + ) + + +def _wy_fwd_call(k, v, beta, g, precision): + """-> (A [B, N, H, C, C] fp32, u [.., C, Dv], w [.., C, Dk] in k's dtype): the WY factors of every chunk.""" + b, n, h, c, dk = k.shape + dv = v.shape[-1] + f32 = jnp.float32 + out = ( + jax.ShapeDtypeStruct((b, n, h, c, c), f32), + jax.ShapeDtypeStruct((b, n, h, c, dv), k.dtype), + jax.ShapeDtypeStruct((b, n, h, c, dk), k.dtype), + ) + return _call("wy_fwd", (k, v, beta, g.astype(f32)), out, (b * n * h,), C=c, DK=dk, DV=dv, NB=c // 16, PREC=precision) + + +def _out_call(oi, q, k, g, vn, precision, out_dtype=jnp.float32): + """-> o = oi + causal(q k^T e^{g_i - g_j}) vn [B, N, H, C, Dv] in out_dtype.""" + b, n, h, c, dk = q.shape + dv = vn.shape[-1] + return _call( + "out", + (oi, q, k, g.astype(jnp.float32), vn), + jax.ShapeDtypeStruct(oi.shape, out_dtype), + (b * n * h,), + C=c, + DK=dk, + DV=dv, + PREC=precision, + ) + + +def _do_exact(do, q, precision): + # the output's cotangent, when the output is in the compute dtype, is exact in it: one-sided splits apply + return bool(precision in EXACT_PRECISIONS and do.dtype == q.dtype) + + +def _out_bwd_call(q, k, g, do, vn, precision): + """The intra-chunk term's backward -> (dvn, dq, dk, dg), fp32.""" + b, n, h, c, dk = q.shape + dv = vn.shape[-1] + f32 = jnp.float32 + out = ( + jax.ShapeDtypeStruct(vn.shape, f32), + jax.ShapeDtypeStruct(q.shape, f32), + jax.ShapeDtypeStruct(q.shape, f32), + jax.ShapeDtypeStruct(g.shape, f32), + ) + return _call( + "out_bwd", + (q, k, g.astype(f32), do, vn), + out, + (b * n * h,), + C=c, + DK=dk, + DV=dv, + PREC=precision, + DO_EXACT=_do_exact(do, q, precision), + ) + + +def _prod_call(dvt, h, do, vn, lam, k, q, e, eg, dq_o, dk_o, precision, block_k=64, dq_dtype=jnp.float32): + """The recurrence's per-chunk products -> (dw, dq, dk, deg, de, da), fp32 but dq (dq_dtype): dq, dk with their + decays applied and the intra-chunk term's dq_o, dk_o added -- dq whole, dk without the WY factors' share.""" + b, n, hh, c, dk = k.shape + dv = vn.shape[-1] + bk = min(block_k, dk) + nk = dk // bk + f32 = jnp.float32 + out = ( + jax.ShapeDtypeStruct(k.shape, f32), + jax.ShapeDtypeStruct(k.shape, dq_dtype), + jax.ShapeDtypeStruct(k.shape, f32), + jax.ShapeDtypeStruct((b, n, hh, nk, c), f32), + jax.ShapeDtypeStruct((b, n, hh, nk, c), f32), + jax.ShapeDtypeStruct((b, n, hh, nk), f32), + ) + dw, dq, dkk, deg, de, da = _call( + "prod", + (dvt, h, do, vn, lam, k, q, e.astype(f32), eg.astype(f32), dq_o.astype(f32), dk_o.astype(f32)), + out, + (b * n * hh, nk), + C=c, + DK=dk, + DV=dv, + BK=bk, + PREC=precision, + DO_EXACT=_do_exact(do, q, precision), + ) + return dw, dq, dkk, deg.sum(-2), de.sum(-2), da.sum(-1) + + +def _wy_bwd_call(k, v, beta, g, a, du, dw, dk_in, precision, dk_dtype=jnp.float32, dv_dtype=jnp.float32): + """The WY factors' backward -> (dk + dk_in in dk_dtype, dv in dv_dtype, dbeta, dg fp32).""" + b, n, h, c, dk = k.shape + dv = v.shape[-1] + f32 = jnp.float32 + out = ( + jax.ShapeDtypeStruct(k.shape, dk_dtype), + jax.ShapeDtypeStruct(v.shape, dv_dtype), + jax.ShapeDtypeStruct(g.shape, f32), + jax.ShapeDtypeStruct(g.shape, f32), + ) + return _call( + "wy_bwd", + (k, v, beta, g.astype(f32), a, du.astype(f32), dw.astype(f32), dk_in.astype(f32)), + out, + (b * n * h,), + C=c, + DK=dk, + DV=dv, + PREC=precision, + ) + + +def _decays(g): + return jnp.exp(g[..., -1:] - g), jnp.exp(g[..., -1]), jnp.exp(g) + + +def _rule_fwd_impl(q, k, v, beta, g, block_v, precision, out_dtype, store): + a_inv, u, w = _wy_fwd_call(k, v, beta, g, precision) + e, a, eg = _decays(g) + oi, vn, h = _fwd_call(u, w, k, e, a, q, eg, block_v, precision, store_h=store) + return _out_call(oi, q, k, g, vn, precision, out_dtype), (a_inv, w, h, vn) + + +@functools.partial(jax.custom_vjp, nondiff_argnums=(5, 6, 7)) +def chunk_rule(q, k, v, beta, g, block_v, precision, out_dtype): + """The chunked rule on kernels -> o [B, N, H, C, Dv] in out_dtype. q, k [B, N, H, C, Dk], v [.., C, Dv], beta + [.., C] in the compute dtype, g [B, N, H, C] fp32 the decays' cumulative sum within each chunk (the reference's + g_cum). Its cotangent arrives in out_dtype: exact in the compute dtype when the two agree, which the backward's + products of it then take one-sided.""" + return _rule_fwd_impl(q, k, v, beta, g, block_v, precision, out_dtype, store=False)[0] + + +def _chunk_rule_fwd(q, k, v, beta, g, block_v, precision, out_dtype): + o, (a_inv, w, h, vn) = _rule_fwd_impl(q, k, v, beta, g, block_v, precision, out_dtype, store=True) + return o, (q, k, v, beta, g, a_inv, w, h, vn) + + +def _chunk_rule_bwd(block_v, precision, out_dtype, res, do): + q, k, v, beta, g, a_inv, w, h, vn = res + e, a, eg = _decays(g) + dvn, dq_o, dk_o, dg_o = _out_bwd_call(q, k, g, do, vn, precision) + dvt, lam = _bwd_call(w, k, e, a, q, eg, do, dvn, block_v, precision) + dw, dq, dk_os, deg, de, da = _prod_call(dvt, h, do, vn, lam, k, q, e, eg, dq_o, dk_o, precision, dq_dtype=q.dtype) + dk, dv, dbeta, dg_w = _wy_bwd_call(k, v, beta, g, a_inv, dvt, dw, dk_os, precision, dk_dtype=k.dtype, dv_dtype=v.dtype) + dg = dg_o + dg_w + deg * eg - de * e # e^g, and e = e^{g_last - g} (its -g side) + dg = dg.at[..., -1].add(jnp.sum(de * e, axis=-1) + da * a) # e's g_last side and a = e^{g_last} + return dq, dk, dv, dbeta.astype(beta.dtype), dg.astype(g.dtype) + + +chunk_rule.defvjp(_chunk_rule_fwd, _chunk_rule_bwd) + + +def _precision_for(dtype, precision, operands): + # bf16 compute: 'bf16x3e' (q, k, w exact in bf16); f16: 'tf32x2e' (f16's 11 bits fit tf32's head, not bf16's 8); + # fp32: 'tf32x3' + precision = precision or {jnp.dtype(jnp.bfloat16): DEFAULT_PRECISION, jnp.dtype(jnp.float16): "tf32x2e"}.get( + jnp.dtype(dtype), "tf32x3" + ) + if precision not in PRECISIONS: + raise ValueError(f"gdn_triton precision must be one of {PRECISIONS}, got {precision!r}") + exact = (jnp.bfloat16,) if precision == "bf16x3e" else (jnp.bfloat16, jnp.float16) + if precision in EXACT_PRECISIONS and not all(x.dtype in exact for x in operands): + raise ValueError( + f"gdn_triton precision {precision!r} needs q, k, w in " + f'{" / ".join(jnp.dtype(t).name for t in exact)}, got ' + f'{" / ".join(str(x.dtype) for x in operands)}' + ) + return precision + + +def chunk(q_c, k_c, v_c, beta_c, g_cum, *, block_v=None, precision=None, out_dtype=jnp.float32): + """`chunk_gated_delta_rule` from its chunked operands on the kernels alone (`chunk_rule`) -> o [B, N, H, C, Dv] + in out_dtype. q_c, k_c [B, N, H, C, Dk], v_c [.., C, Dv], beta_c [.., C] (compute dtype), g_cum [.., C] fp32.""" + precision = _precision_for(q_c.dtype, precision, (q_c, k_c, v_c)) + c, dk, dv = q_c.shape[-2], q_c.shape[-1], v_c.shape[-1] + if not fused_supported(c, dk, dv): + raise ValueError( + f"gdn_triton.chunk needs the head dims powers of two >= 16 and a chunk of {FUSED_CHUNKS}, got " + f"chunk {c}, Dk {dk}, Dv {dv}" + ) + return chunk_rule( + q_c, k_c, v_c, beta_c, g_cum.astype(jnp.float32), block_v or default_block_v(dv), precision, jnp.dtype(out_dtype) + ) + + +def inter_chunk(q_c, k_c, u, w, g_cum, *, block_v=None, precision=None): + """`chunk_gated_delta_rule`'s inter-chunk part on the kernels -> o [B, N, H, C, Dv] fp32, the scan's outputs. + + q_c, k_c [B, N, H, C, Dk] (compute dtype), u [B, N, H, C, Dv], w [B, N, H, C, Dk] (the WY factors, compute + dtype), g_cum [B, N, H, C] fp32 -- the reference's operands before it transposes them for its scan.""" + # bf16 compute: 'bf16x3e' (q, k, w exact in bf16); f16: 'tf32x2e' (f16's 11 bits fit tf32's head, not bf16's 8); + # fp32: 'tf32x3' + precision = precision or {jnp.dtype(jnp.bfloat16): DEFAULT_PRECISION, jnp.dtype(jnp.float16): "tf32x2e"}.get( + jnp.dtype(q_c.dtype), "tf32x3" + ) + if precision not in PRECISIONS: + raise ValueError(f"gdn_triton precision must be one of {PRECISIONS}, got {precision!r}") + exact = (jnp.bfloat16,) if precision == "bf16x3e" else (jnp.bfloat16, jnp.float16) + if precision in EXACT_PRECISIONS and not all(x.dtype in exact for x in (q_c, k_c, w)): + raise ValueError( + f"gdn_triton precision {precision!r} needs q, k, w in " + f'{" / ".join(jnp.dtype(t).name for t in exact)}, got {q_c.dtype} / {k_c.dtype} / {w.dtype}' + ) + c, dk, dv = q_c.shape[-2], q_c.shape[-1], u.shape[-1] + if not supported(c, dk, dv): + raise ValueError( + f"gdn_scan_impl 'triton' needs the chunk and head dims powers of two >= 16, got chunk {c}, " f"Dk {dk}, Dv {dv}" + ) + f32 = jnp.float32 + e = jnp.exp(g_cum[..., -1, None] - g_cum) # the reference's k_dec factor + a = jnp.exp(g_cum[..., -1]) # its state decay + eg = jnp.exp(g_cum) # and its q_g factor + attn_inter, vn = scan(u, w, k_c, e, a, q_c, eg, block_v or default_block_v(dv), precision) + causal = jnp.tril(jnp.ones((c, c), dtype=bool)) + attn = jnp.matmul(q_c, k_c.swapaxes(-1, -2), precision=_HI).astype(f32) + gd = jnp.where(causal, g_cum[..., :, None] - g_cum[..., None, :], -1e30) + attn = jnp.where(causal, attn * jnp.exp(gd), 0.0) + return attn_inter + jnp.matmul(attn, vn, precision=_HI) diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/init.py b/src/maxtext/experimental/mpmd/jax/qwen35/init.py new file mode 100644 index 0000000000..c7e40d7001 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/init.py @@ -0,0 +1,177 @@ +# 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. + +"""Parameter init for the Qwen3.5 port, by MaxText's rules where they shape the math. + +`init_params` materialises a parameter tree (`model.param_avals(config)`, or a +subtree of it) straight onto its devices; `leaf_rule` says how each leaf is +drawn. `ds_ep.qwen_init_rule` (the MPMD pipeline's `StagePrograms.init`) +holds a second copy of the zeros / ones / a_log choice and of `A_LOG_RANGE` +(`ds_ep_qwen_test.QwenInit` holds the two to each other). + +Not in `model.py`: `qwen35_model_test.CallSiteTest` holds the model modules to +making no fresh array (`jnp.zeros` / `jnp.ones`) of their own. +""" + +from __future__ import annotations + +import math +import zlib + +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.qwen35.model import LAYERS + + +def _dict_path(path): + """A tuple of dict keys, or a jax key path -> its dict keys.""" + if path and not isinstance(path[0], str): + return tuple(k.key for k in path if isinstance(k, jax.tree_util.DictKey)) + return tuple(path) + + +def is_stacked(path) -> bool: + """True for a leaf under `decoder/layers`, whose axis 0 is the block axis. + + `path` is a tuple of dict keys (or a jax key path). DeepSeek's stacks are + `dense_layers` / `moe_layers`; a rule that looks for those would treat every + Qwen leaf as unstacked. + """ + keys = _dict_path(path) + return len(keys) >= 2 and keys[0] == "decoder" and keys[1] == LAYERS + + +def fan_in(path, shape) -> int: + """Elements the kernel at `path` contracts. Stacked leaves carry the block + axis first, so everything is read from the right. + + [.., in, out] 2-D kernels (projections, gates, experts, head): shape[-2] + [.., E, heads, D] query / key / value: shape[-3] + [.., K, 1, C] the depthwise conv: K taps x 1 input channel = shape[-3] + embedding 1 (unit-scale rows, MaxText's normal(1.0)) + """ + keys = _dict_path(path) + shape = tuple(int(d) for d in shape) + if "token_embedder" in keys: + return 1 + if len(shape) < 2: + return max(1, shape[-1]) if shape else 1 + parent = keys[-2] if len(keys) >= 2 else "" + if parent in ("query", "key", "value", "conv1d"): + return shape[-3] + return shape[-2] + + +def _leaf_key(key, keys): + """`key` folded with a stable hash of the leaf's path (not its tree position).""" + return jax.random.fold_in(key, zlib.crc32("/".join(keys).encode()) & 0x7FFFFFFF) + + +# `A_log = log A` with A ~ U(A_LOG_RANGE): qwen3.py's A ~ U(0, 16], kept off 0. +A_LOG_RANGE = (1e-9, 16.0) +LEAF_KINDS = ("zeros", "ones", "a_log", "normal") + + +def leaf_rule(path, shape) -> tuple[str, int]: + """`(kind, fan_in)`: how the init draws the leaf at `path`, of (per-block) `shape`. + + 'zeros' the zero-centred norm scales (input / post-attention / final, + q / k norms) and any empty leaf + 'ones' the GDN output (gated) norm scale, `dt_bias` + 'a_log' `A_log` = log U(A_LOG_RANGE) + 'normal' normal / sqrt(fan_in): every kernel and the embedding + + `fan_in` is 0 unless the kind is 'normal'. `init_leaf` draws by it and + refuses a kind it does not know, so a leaf given a rule of its own here + needs a draw there too. `ds_ep.qwen_init_rule` holds a second copy of the + zeros / ones / a_log choice, and of A_LOG_RANGE, but draws 'normal' as + N(0, 0.02^2) rather than by fan_in. + """ + keys = _dict_path(path) + shape = tuple(int(d) for d in shape) + name = keys[-1] if keys else "" + if math.prod(shape) == 0: + return "zeros", 0 + if name == "scale": + gated = len(keys) >= 3 and keys[-3:-1] == ("norm", "rms_norm") + return ("ones" if gated else "zeros"), 0 + if name == "A_log": + return "a_log", 0 + if name == "dt_bias": + return "ones", 0 + return "normal", fan_in(keys, shape) + + +def _init_one(keys, shape, dtype, key): + kind, fan = leaf_rule(keys, shape) + if kind == "zeros": + return jnp.zeros(shape, dtype) + if kind == "ones": + return jnp.ones(shape, dtype) + if kind == "a_log": + lo, hi = A_LOG_RANGE + return jnp.log(jax.random.uniform(key, shape, jnp.float32, minval=lo, maxval=hi)).astype(dtype) + if kind == "normal": + return (jax.random.normal(key, shape, jnp.float32) * (fan**-0.5)).astype(dtype) + raise ValueError(f'no init for leaf kind {kind!r} at {"/".join(keys)}') + + +def init_leaf(path, shape, dtype, key): + """One parameter, by MaxText's Qwen3.5 rules where they matter for the math + (`leaf_rule`): + + zero-centred norm scales (input / post-attention / final, q / k norms) 0 + the GDN output (gated) norm scale 1 + A_log log U(1e-9, 16) (qwen3.py, = log A, A ~ U(0, 16]) + dt_bias 1 + every kernel and the embedding normal / sqrt(fan_in) (MaxText: truncated normal) + + The norm rules are not cosmetic: a zero-centred norm initialised at 1 + doubles its gain. `key` is the leaf's own key (`init_params` folds the + leaf's path into the model key). A stacked (`decoder/layers`) leaf draws + block b's slice from `fold_in(key, b)`. + """ + keys = _dict_path(path) + shape, dtype = tuple(int(d) for d in shape), jnp.dtype(dtype) + if not is_stacked(keys) or not shape: + return _init_one(keys, shape, dtype, key) + if not shape[0]: + return jnp.zeros(shape, dtype) + # A loop (lax.map), not a vmap: each block's draw is then exactly its + # unbatched draw for ANY key implementation -- the RngBitGenerator ones + # ('rbg') give batch-size-dependent bits under vmap, threefry does not. + return jax.lax.map( + lambda b: _init_one(keys, shape[1:], dtype, jax.random.fold_in(key, b)), jnp.arange(shape[0], dtype=jnp.uint32) + ) + + +def init_params(avals, key, shardings=None): + """Materialise a parameter tree (`model.param_avals(config)`, or a subtree + of it) straight onto `shardings` (None: jit's default placement). + + Driven by the aval tree, so the full model never exists anywhere. Every + leaf draws from `key` folded with its path, so a leaf's values do not + depend on what else is in the tree. + """ + leaves, treedef = jax.tree_util.tree_flatten_with_path(avals) + + def build(): + out = [] + for path, a in leaves: + keys = _dict_path(path) + out.append(init_leaf(keys, a.shape, a.dtype, _leaf_key(key, keys))) + return jax.tree.unflatten(treedef, out) + + return jax.jit(build, out_shardings=shardings)() diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/layers.py b/src/maxtext/experimental/mpmd/jax/qwen35/layers.py new file mode 100644 index 0000000000..5fb00dfe77 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/layers.py @@ -0,0 +1,59 @@ +# 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. + +"""Qwen3.5's RMSNorms, as plain functions over parameter pytrees. + +Both kinds compute their statistics and the normalised value in fp32; how they +round after that is `config.norm_numerics` (MaxText changed it on 2026-09-10; +see `Qwen35Config.norm_numerics`): + + * zero-centred (`Qwen3NextRMSNorm`, normalizations.py) -- the input / + post-attention / final norms and the attention q/k norms. The stored + scale starts at 0 and the applied one is `scale + 1`. + 'fp32': `fp32(normed) * (fp32(scale) + 1)`, rounded once to `dtype` + (`_ops.norm_fp32`; MaxText since 2026-09-10, and HF). + 'bf16': `bf16(normed) * (bf16(scale) + 1)`, the add and the multiply in + `dtype` (`_ops.norm`, the DeepSeek port's RMSNorm; MaxText before + 2026-09-10). + * plain (`Qwen3NextRMSNormGated`'s inner norm) -- the GDN output norm over + the value head dim, ones-initialised, no offset. `gdn.gated_rms_norm` adds + the `silu(z)` gate and does the rounding: 'fp32' keeps the scaled value in + fp32 until after the gate (MaxText since 2026-09-10); 'bf16' rounds the + normalised value to `dtype` and scales it there (MaxText before it, and + HF with its bf16 weights). + +The GDN's q / k l2 norm is `gdn.l2norm`. +""" + +from __future__ import annotations + +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.deepseek.layers import precision_of # noqa: F401 re-exported for the model modules +from maxtext.experimental.mpmd.jax.qwen35 import _ops + + +def rms_norm(params, x, config, zero_centered: bool = True): + """`x / rms(x) * scale` (plain) or `* (scale + 1)` (zero-centred), in `dtype`. + + `zero_centered=False` is the plain norm under 'bf16' numerics only: the gated + norm under 'fp32' scales in fp32 and rounds after its gate + (`gdn.gated_rms_norm`). + """ + if config.norm_numerics == "fp32" and zero_centered: + scale = _ops.use_weight(params["scale"], jnp.float32, config) + 1.0 + return _ops.norm_fp32({"scale": scale}, x, config).astype(config.dtype) + if zero_centered: + params = {"scale": _ops.use_weight(params["scale"], config.dtype, config) + 1.0} + return _ops.norm(params, x, config) diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/model.py b/src/maxtext/experimental/mpmd/jax/qwen35/model.py new file mode 100644 index 0000000000..7879500bd3 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/model.py @@ -0,0 +1,251 @@ +# 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 Qwen3.5 text decoder, as plain functions over parameter pytrees. + +Mirrors MaxText's `decoder_block: qwen3_5` training forward pass +(models/qwen3_5.py: `Qwen3_5ScannableBlock` + `Qwen3_5DecoderLayer`, scanned by +layers/nnx_decoders.py): + + y = embedding.astype(bf16)[tokens] + scan over NB = L/4 blocks, each = 4 decoder layers [GDN, GDN, GDN, gated attn]: + h = zc_rms_norm(x); x = x + mixer(h) (pre-norm) + h = zc_rms_norm(x); x = x + sparse_moe(h) (both residuals bf16) + logits = zc_rms_norm(y) @ logits_dense (untied), cast to fp32 + +Parameter layout = MaxText's NNX tree before its nested Qwen3 scan (2026-10-21), +with the scanned block axis moved from `param_scan_axis = 1` to axis 0, as the +DeepSeek port does. `convert.from_nnx_state` maps that tree, and the +nested-scan tree of later MaxText (this one: `local_layers` +[.., NB, cycle - 1, ..] + `global_layer`), onto it: + + token_embedder/embedding [V, E] + decoder/decoder_norm/scale [E] zero-centred, init 0 + decoder/logits_dense/kernel [E, V] + decoder/layers/layer_{0,1,2}/... [NB, ...] Gated DeltaNet layers + decoder/layers/layer_3/... [NB, ...] gated full attention + +Remat: on the scanned path one `jax.checkpoint` per BLOCK +(`remat_granularity='block'`, MaxText's placement before its nested scan, policy +`remat_policy`), one per LAYER with an un-checkpointed scan body (`'layer'`, +policy `layer_remat_policy`: MaxText's placement since the nested scan, a +checkpoint per sub-layer inside its nested scan and none around the block), or +both, nested (`'block+layer'`); MaxText's policy names, though 'minimal' and +'save_dot_except_mlp' save other sets than MaxText's +(`maxtext.experimental.mpmd.jax.deepseek.model.REMAT_POLICIES`). As in the DeepSeek port, +`scan_layers=False` unrolls with no checkpoint at all. + +This package imports jax/numpy (and `maxtext.experimental.mpmd.jax.deepseek`'s shared kernels) only, +never MaxText. +""" + +from __future__ import annotations + +import functools + +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.deepseek import model as ds_model +from maxtext.experimental.mpmd.jax.qwen35 import _ops +from maxtext.experimental.mpmd.jax.qwen35 import attention +from maxtext.experimental.mpmd.jax.qwen35 import gdn +from maxtext.experimental.mpmd.jax.qwen35 import layers +from maxtext.experimental.mpmd.jax.qwen35 import moe + +LAYERS = "layers" + + +def remat_policy_for(config): + """MaxText's `get_remat_policy` (nnx_decoders.py), shared with the DeepSeek port. + + `full` and `none` both mean "save nothing inside the checkpoint". The names + the policies save that this model emits are the gated attention's + `query_proj` / `key_proj` / `value_proj` / `out_proj` (and `context` from the + splash kernels); the GDN emits none, as in MaxText, and so does the MoE, + unlike MaxText's: its routed experts tag `mlpwi_0` / `mlpwo` (the dense MoE + also `mlpwi_1`) and its shared expert `mlpwi_0` / `mlpwi_1` / `mlpwo`, which + MaxText's 'minimal' saves and this table's does not. + """ + return ds_model.remat_policy_for(config) + + +def layer_remat_policy_for(config): + """The per-layer checkpoints' policy (`layer_remat_policy`, default `remat_policy`).""" + return ds_model.remat_policy_for(config.replace(remat_policy=config.layer_remat_policy_name)) + + +def decoder_layer(params, x, positions, segment_ids, inv_freq, config, is_attention): + """`Qwen3_5DecoderLayer.__call__`: pre-norm mixer + pre-norm MoE, two residuals.""" + h = layers.rms_norm(params["input_layernorm"], x, config) + if is_attention: + a = attention.gated_attention(params["attention"]["attention"], h, positions, segment_ids, config, inv_freq) + else: + a = gdn.gated_delta_net(params["attention"], h, segment_ids, config) + x = x + a + h = layers.rms_norm(params["post_attention_layernorm"], x, config) + return x + moe.sparse_moe_block(params["mlp"], h, config) + + +def _layer_fns(config): + """One callable per position in the block, checkpointed under layer remat.""" + fns = [] + for i in range(config.inhomogeneous_layer_cycle_interval): + f = functools.partial(decoder_layer, config=config, is_attention=config.is_attention_layer(i)) + if config.layer_remat: + # With the CSE barrier. The layers' recomputes are independent of one + # another (each starts from its own stored input), and without it XLA + # hoists them together and the per-layer checkpoint no longer bounds the + # working set: one 397B-dims block's backward program on v5p (4096 + # tokens, jax 0.12) holds 22.6 GB of temporaries without the barrier, + # 12.0 GB with it, 29.3 GB under block remat (norm_numerics='bf16': + # 20.8 / 14.2 / 29.0 GB). (The block checkpoint keeps + # prevent_cse=False, as MaxText: the scan already separates it.) + f = jax.checkpoint(f, policy=layer_remat_policy_for(config), prevent_cse=True) + fns.append(f) + return fns + + +def apply_blocks(stack, x, positions, segment_ids, config, inv_freq=None): + """Run the `[nb, ...]` stacked blocks of `stack` (`decoder/layers`) over `x`.""" + if inv_freq is None: + inv_freq = attention.rope_inv_freq(config) + fns = _layer_fns(config) + + def body(carry, blk): + for i, f in enumerate(fns): + carry = f(blk[f"layer_{i}"], carry, positions, segment_ids, inv_freq) + return carry, None + + if config.scan_layers: + if config.block_remat: + body = jax.checkpoint(body, policy=remat_policy_for(config), prevent_cse=False) + out, _ = jax.lax.scan(body, x, stack) + return out + nb = int(jax.tree.leaves(stack)[0].shape[0]) + for i in range(nb): + x, _ = body(x, jax.tree.map(lambda leaf, i=i: leaf[i], stack)) + return x + + +def embed(params, tokens, config): + """`[B, L]` int tokens -> `[B, L, E]` residual stream in `dtype`.""" + return _ops.embed(params["token_embedder"], tokens, config).astype(config.dtype) + + +def head(params, y, config): + """Final zero-centred norm + untied unembedding (bf16 dot), logits cast to fp32.""" + dec = params["decoder"] + y = layers.rms_norm(dec["decoder_norm"], y, config) + logits = _ops.dense(dec["logits_dense"], y, config) + return logits.astype(jnp.float32) if config.cast_logits_to_fp32 else logits + + +def forward(params, tokens, positions, segment_ids, config, inv_freq=None): + """`Transformer.__call__` for training. Returns `[B, L, vocab]` logits. + + `inv_freq` is the rotary table (`attention.rope_inv_freq`); None computes it + in-graph, as MaxText does. + """ + y = embed(params, tokens, config) + y = apply_blocks(params["decoder"][LAYERS], y, positions, segment_ids, config, inv_freq) + return head(params, y, config) + + +# ------------------------------------------------------------- param avals +def _sds(shape, dtype): + return jax.ShapeDtypeStruct(tuple(int(d) for d in shape), dtype) + + +def _moe_avals(config, n): + wd, e, x, f = config.weight_dtype, config.emb_dim, config.num_experts, config.moe_mlp_dim + tree = { + "routed_experts": { + "gate": {"kernel": _sds((n, e, x), wd)}, + "wi_0": _sds((n, x, e, f), wd), + "wi_1": _sds((n, x, e, f), wd), + "wo": _sds((n, x, f, e), wd), + } + } + if config.shared_experts: + fs = config.shared_expert_mlp_dim + tree["shared_expert"] = { + "wi_0": {"kernel": _sds((n, e, fs), wd)}, + "wi_1": {"kernel": _sds((n, e, fs), wd)}, + "wo": {"kernel": _sds((n, fs, e), wd)}, + } + tree["shared_expert_gate"] = {"kernel": _sds((n, e, 1), wd)} + return tree + + +def gdn_layer_avals(config, n): + """One stacked GDN layer position, `[n, ...]`.""" + wd, e = config.weight_dtype, config.emb_dim + hv, k = config.gdn_num_value_heads, config.gdn_conv_kernel_dim + return { + "input_layernorm": {"scale": _sds((n, e), wd)}, + "post_attention_layernorm": {"scale": _sds((n, e), wd)}, + "attention": { + "in_proj_qkvz": {"kernel": _sds((n, e, config.gdn_qkvz_dim), wd)}, + "in_proj_ba": {"kernel": _sds((n, e, 2 * hv), wd)}, + "conv1d": {"kernel": _sds((n, k, 1, config.gdn_conv_dim), wd)}, + "A_log": _sds((n, hv), wd), + "dt_bias": _sds((n, hv), wd), + "norm": {"rms_norm": {"scale": _sds((n, config.gdn_value_head_dim), wd)}}, + "out_proj": {"kernel": _sds((n, config.gdn_value_dim, e), wd)}, + }, + "mlp": _moe_avals(config, n), + } + + +def attention_layer_avals(config, n): + """One stacked gated-attention layer position, `[n, ...]`.""" + wd, e = config.weight_dtype, config.emb_dim + h, kv, d = config.num_query_heads, config.num_kv_heads, config.head_dim + return { + "input_layernorm": {"scale": _sds((n, e), wd)}, + "post_attention_layernorm": {"scale": _sds((n, e), wd)}, + "attention": { + "attention": { + "query": {"kernel": _sds((n, e, h, 2 * d), wd)}, + "key": {"kernel": _sds((n, e, kv, d), wd)}, + "value": {"kernel": _sds((n, e, kv, d), wd)}, + "query_norm": {"scale": _sds((n, d), wd)}, + "key_norm": {"scale": _sds((n, d), wd)}, + "out": {"kernel": _sds((n, h * d, e), wd)}, + } + }, + "mlp": _moe_avals(config, n), + } + + +def block_avals(config, n): + """`decoder/layers` for `n` stacked blocks.""" + return { + f"layer_{i}": (attention_layer_avals(config, n) if config.is_attention_layer(i) else gdn_layer_avals(config, n)) + for i in range(config.inhomogeneous_layer_cycle_interval) + } + + +def param_avals(config): + """`jax.ShapeDtypeStruct` tree of the FULL model; never materialised.""" + wd = config.weight_dtype + return { + "token_embedder": {"embedding": _sds((config.vocab_size, config.emb_dim), wd)}, + "decoder": { + LAYERS: block_avals(config, config.num_blocks), + "decoder_norm": {"scale": _sds((config.emb_dim,), wd)}, + "logits_dense": {"kernel": _sds((config.emb_dim, config.vocab_size), wd)}, + }, + } diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/moe.py b/src/maxtext/experimental/mpmd/jax/qwen35/moe.py new file mode 100644 index 0000000000..8f53ebb65d --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/moe.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. + +"""Qwen3.5's sparse MoE block: softmax-over-top-k router, routed experts, and one +sigmoid-gated shared expert. + +Mirrors `Qwen3NextSparseMoeBlock.__call__` (models/qwen3.py) and the routing +path `GateLogit` + `RoutedMoE.get_topk` takes for it (layers/moe.py): + + logits = x @ gate.kernel [B,S,X], `dtype` (fp32 with float32_gate_logits), + no bias, no score function + w, idx = top_k(logits, k) top-k on the RAW logits + w = bf16(softmax(fp32(w))) softmax over the k selected only + w = w / sum(w) norm_topk_prob, in bf16 (not an identity) + out = experts(x, w, idx) + sigmoid(x @ shared_expert_gate) * shared_mlp(x) + +That is HF's "softmax over all experts, top-k, renormalise", up to rounding. +The routed experts and the shared expert are the DeepSeek port's +(`moe.routed_experts` and `layers.mlp_block`). +""" + +from __future__ import annotations + +import jax +import jax.numpy as jnp + +from maxtext.experimental.mpmd.jax.qwen35 import _ops +from maxtext.experimental.mpmd.jax.qwen35 import layers + + +def route(params, x, config): + """Returns `(weights [B,S,k] dtype, indices [B,S,k] int32)`.""" + gate_dtype = jnp.float32 if config.float32_gate_logits else config.dtype + kernel = _ops.use_weight(params["kernel"], gate_dtype, config) + logits = _ops.dot_general( + jnp.asarray(x, gate_dtype), kernel, (((x.ndim - 1,), (0,)), ((), ())), precision=layers.precision_of(config) + ) + weights, indices = jax.lax.top_k(logits, config.num_experts_per_tok) + weights = jax.nn.softmax(weights.astype(jnp.float32), axis=-1).astype(config.dtype) + if config.norm_topk_prob: + weights = weights / weights.sum(axis=-1, keepdims=True) + return weights, indices + + +def sparse_moe_block(params, x, config): + """`[B, S, E]` -> `[B, S, E]`. (No load-balance loss: the config refuses it.)""" + x = x.astype(config.dtype) + routed = params["routed_experts"] + weights, indices = route(routed["gate"], x, config) + out = _ops.routed_experts(routed, x, weights, indices, config) + if config.shared_experts: + shared = _ops.mlp(params["shared_expert"], x, config) + gate = _ops.dense(params["shared_expert_gate"], x, config) # [B, S, 1] + out = out + jax.nn.sigmoid(gate) * shared + return out diff --git a/src/maxtext/experimental/mpmd/jax/qwen35/train.py b/src/maxtext/experimental/mpmd/jax/qwen35/train.py new file mode 100644 index 0000000000..21ddab8da0 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/qwen35/train.py @@ -0,0 +1,91 @@ +# 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. + +"""Loss and the single-controller train step for Qwen3.5. + +Everything model-agnostic is the DeepSeek port's (`src/maxtext/experimental/mpmd/jax/deepseek/train.py`, +MaxText's trainer reproduced in raw JAX): the T5X custom-VJP cross entropy, +AdamW, global-norm clipping, the LR schedule and the synthetic batch. They are +re-exported here so a Qwen caller never has to reach into the DeepSeek package. +Only the model call differs: Qwen3.5 has no router bias, hence no `aux` tree. +""" + +from __future__ import annotations + +import jax + +from maxtext.experimental.mpmd.jax.deepseek.train import ( # noqa: F401 re-exported + EPS, + TrainConfig, + adamw_init, + adamw_update, + apply_updates, + clip_by_global_norm, + cross_entropy_with_logits, + global_norm, + learning_rate_schedule, + loss_from_logits, + packed_segment_ids, + synthetic_batch, +) +from maxtext.experimental.mpmd.jax.qwen35 import model as q_model + + +def compute_loss(params, batch, config, train_cfg=None, inv_freq=None): + """`train.py:loss_fn` -- MaxText's masked-mean token cross entropy. + + `batch` is a `synthetic_batch`-shaped dict (targets already next-token + shifted). Returns `(loss, metrics)`. + """ + z_loss = 0.0 if train_cfg is None else train_cfg.z_loss_multiplier + logits = q_model.forward( + params, batch["inputs"], batch["inputs_position"], batch["inputs_segmentation"], config, inv_freq=inv_freq + ) + return loss_from_logits(logits, batch["targets"], batch["targets_segmentation"], config.vocab_size, z_loss) + + +def train_step(params, opt_state, batch, config, train_cfg, schedule, inv_freq=None): + """One MaxText training step: loss -> grads -> clip -> AdamW -> apply. + + The update half is `maxtext.experimental.mpmd.jax.deepseek.train.train_step`'s, verbatim. + """ + grad_fn = jax.value_and_grad(compute_loss, has_aux=True) + (loss, metrics), raw_grads = grad_fn(params, batch, config, train_cfg, inv_freq) + grads = clip_by_global_norm(raw_grads, train_cfg.gradient_clipping_threshold) + updates, opt_state = adamw_update(grads, opt_state, params, train_cfg, schedule) + params = apply_updates(params, updates) + metrics = dict(metrics) + metrics["loss"] = loss + metrics["raw_grad_norm"] = global_norm(raw_grads) + metrics["grad_norm"] = global_norm(grads) + metrics["param_norm"] = global_norm(params) + return params, opt_state, metrics + + +__all__ = [ + "EPS", + "TrainConfig", + "adamw_init", + "adamw_update", + "apply_updates", + "clip_by_global_norm", + "compute_loss", + "cross_entropy_with_logits", + "global_norm", + "learning_rate_schedule", + "loss_from_logits", + "packed_segment_ids", + "synthetic_batch", + "train_step", +] diff --git a/src/maxtext/experimental/mpmd/jax/schedule.py b/src/maxtext/experimental/mpmd/jax/schedule.py new file mode 100644 index 0000000000..d80e945459 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/schedule.py @@ -0,0 +1,1962 @@ +# 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. + +"""Pipeline schedules as data: a flat, static list of (chunk, kind, microbatch). + +The driver (`ds_ep_pipeline`) never asks "which schedule am I running?". It just +replays an `order` list. Every published schedule is therefore just a different +(n_chunks, placement, order) triple: + + GPipe / 1F1B C = S, place[c] = c + interleaved 1F1B C = S * V, place[c] = c % S + V-shape (ZBV/DualPipe) C = 2 * S, place[c] = c if c < S else 2*S-1-c + +`greedy` is one list scheduler covering all of them. Two knobs decide which +textbook schedule falls out: + + * `cap[c]` -- how many microbatches chunk c may hold in flight. `cap = M` + everywhere gives GPipe (fill the pipe, then drain); `cap[c] = C - c` gives + 1F1B (the cap alone forces the F/B alternation -- you do NOT also need to + prefer backward, and doing so actually *hurts*, see `eager_bwd`). + * `f_key` / `b_key` -- which of a device's own chunks to advance when several + are ready. Only matters when a device owns >1 chunk, i.e. V > 1. + +For interleaved and V-shaped placement there is no single rule that is optimal +at every (S, V, M), so `search` enumerates the small heuristic space and scores +it with `simulate`. Empirically that reaches the analytic optimum +`(M + (S-1)/V) * (t_F + t_B)` at every configuration tested. The snapshot +rounds do not reproduce Megatron-LM's own interleaved 1F1B (63 against 57 at +S=4, V=2, M=8 in unit costs); `megatron_interleaved` writes it per stage, for +`merge`. + +Costs are in units of "one chunk forward"; a backward is 2. To compare across +different V, divide the makespan by V (each chunk is 1/V of the model). + +Kinds and side-cars. A backward may also be split into 'I' (the input +gradient, including the recompute under remat) and 'W' (the weight gradient), +together one 'B'. Two optional side-cars ride along with an order without +changing its shape: + + * `modes`: {(chunk, microbatch): mode} -- 'r' (remat, the default: the + forward keeps only its inputs and the backward recomputes) or a stash + policy name (the forward keeps a residual set and the backward replays it). + * `fuse`: {j} -- order[j] (an F) and order[j+1] (a B or I of another + microbatch on the same stage) run as ONE program. + +`validate` is the contract between a generator and the driver; `merge` turns +per-stage action lists (how most published schedules are written down) into +one global order. Measured per-program costs go through `cost_table`. + +Zero bubble. `zb_schedule` builds ZB-H1 / ZB-H2 (Qi et al.) on one chunk a +stage, with the middle chunks' backwards split into I and W: the fastest of +the handcrafted streams (`zb_h1`, `zb_h2`), the list scheduler (`zb_search` +over `zb_greedy`) and 1F1B with each B as I then W, under a cap on pending W +buffers. `zb_costs` prices I and W where a cost table has none. With +`split_last` the fused last chunk splits too (`splits_last`): its F runs the +forward, the head, the loss and the input gradient (`cost_table`'s AI), and a +W of its own per microbatch its layers' weight gradients, later. +""" + +from __future__ import annotations + +import functools +import inspect + +# Backward passes cost ~2x a forward for a typical transformer stage; split, +# that is ~1 for the input gradient and ~1 for the weight gradient. +COST = {"F": 1.0, "B": 2.0, "I": 1.0, "W": 1.0} +KINDS = ("F", "B", "I", "W") + + +# ---------------------------------------------------------------------- legality +class ScheduleError(ValueError): + """An order the driver must not run. Raised before anything is dispatched: + once a step starts, a bad order fails halfway through, after donated + buffers are already gone.""" + + +def _fmt(a): + c, k, m = a + return f"{c}{k}{m}" + + +def deps(c, k, m, C): + """What action (c, k, m) of a C-chunk model waits for. + + `(c', 'BI', m)` stands for whichever of B or I ran for that chunk and + microbatch -- the op that produces its input gradient. The last chunk's + backward is fused into its forward, so the chunk before it waits on a no-op + B that is done when the last chunk's F is -- and so does a split last + chunk's W (`splits_last`), whose F ran the input gradient. + """ + if k == "F": + return [(c - 1, "F", m)] if c else [] + if k in ("B", "I"): + return [(c, "F", m)] + ([(c + 1, "BI", m)] if c < C - 1 else []) + if k == "W": + return [(c, "BI", m)] + raise ScheduleError(f"unknown kind {k!r} in {(c, k, m)}") + + +def validate(order, place, n_micro, *, modes=None, fuse=frozenset(), fuse_last=True, fifo=True): + """Raise `ScheduleError` unless the driver can replay `order` as is. + + Every rule here is one the driver relies on without checking: + + * every (c, m) has exactly one F; every non-last chunk one B, or one I + and then one W -- and chunk 0 only B, since it has no input gradient; + * F(c, m) after F(c-1, m); B or I(c, m) after F(c, m) and after B or + I(c+1, m); W after its I; + * `fuse_last`: the last chunk is one fused forward+backward program, so it + has no I, and its B is a no-op that sits right after its F (after the + pair, if that F heads one) in its stage's own sequence. Ops of other + stages may come between: a timed order lists everything that starts at + the same instant together. It has a W for every microbatch or for + none: split (`splits_last`), its F runs the forward, the head, the loss + and the input gradient, and its W, after its F (and the no-op B), the + weight gradients it defers; + * `fifo`: per chunk, the forwards and every op that writes the gradient + accumulator (B, W, or the fused last chunk's F -- and a split last + chunk's W's, which write the leaves its F does not) run in microbatch + order. That is what makes two schedules bitwise-interchangeable: the + fp32 accumulation happens in the same order whatever else moves; + * each j in `fuse` pairs an F with the next op, a B or I on the same stage + and of a different microbatch (the same microbatch would depend on + itself); + * `modes` name only non-last chunks: the fused last chunk keeps nothing. + """ + C, M = len(place), n_micro + pos, spos, n_on = {}, [], [0] * (max(place) + 1) # spos[j]: index in its stage's sequence + for j, a in enumerate(order): + a = tuple(a) if isinstance(a, (tuple, list)) else (a,) + if len(a) != 3 or a[1] not in KINDS: + raise ScheduleError(f"order[{j}] = {a!r} is not (chunk, kind in {KINDS}, microbatch)") + c, k, m = a + if not (0 <= c < C and 0 <= m < M): + raise ScheduleError(f"order[{j}] = {_fmt(a)} is outside {C} chunks x {M} microbatches") + if a in pos: + raise ScheduleError(f"{_fmt(a)} appears twice (order[{pos[a]}] and order[{j}])") + pos[a] = j + spos.append(n_on[place[c]]) + n_on[place[c]] += 1 + fuse = frozenset(fuse) + for j in sorted(fuse): + if not 0 <= j < len(order) - 1: + raise ScheduleError(f"fused pair at {j} is outside the order") + (cf, kf, mf), (cb, kb, mb) = order[j], order[j + 1] + if kf != "F" or kb not in ("B", "I"): + raise ScheduleError( + f"fused pair at {j} is {_fmt(order[j])}&{_fmt(order[j + 1])}: " "it must be an F and then a B or I" + ) + if cb == C - 1 and fuse_last: + raise ScheduleError(f"fused pair at {j}: {_fmt(order[j + 1])} is the fused last chunk's " "no-op backward") + if place[cf] != place[cb]: + raise ScheduleError( + f"fused pair at {j}: {_fmt(order[j])} is on stage {place[cf]} and " f"{_fmt(order[j + 1])} on stage {place[cb]}" + ) + if mf == mb: + raise ScheduleError( + f"fused pair at {j}: {_fmt(order[j])}&{_fmt(order[j + 1])} share " f"microbatch {mf}, so one waits on the other" + ) + # the fused last chunk split: a W of its own (for every microbatch, checked below) + last_w = fuse_last and any((C - 1, "W", m) in pos for m in range(M)) + for c in range(C): + for m in range(M): + has = {k: (c, k, m) in pos for k in KINDS} + if not has["F"]: + raise ScheduleError(f"{c}F{m} is missing") + if c == C - 1 and fuse_last: + if has["I"]: + raise ScheduleError(f"chunk {c} is the fused last chunk: it has no I (its F runs the input gradient)") + if last_w and not has["W"]: + raise ScheduleError(f"{c}W{m} is missing: a split last chunk has a W for every microbatch") + if not has["B"]: + raise ScheduleError(f"{c}B{m} (the fused last chunk's no-op backward) is missing") + jf, jb = pos[(c, "F", m)], pos[(c, "B", m)] + if spos[jb] != spos[jf] + (2 if jf in fuse else 1): + raise ScheduleError( + f"{c}B{m} (order[{jb}]) is not right after its fused forward " f"(order[{jf}]) on stage {place[c]}" + ) + continue + if c == 0 and (has["I"] or has["W"]): + raise ScheduleError(f"chunk 0 has no input gradient to split off: 0B{m} only, no I/W") + if has["B"] and (has["I"] or has["W"]): + raise ScheduleError(f"({c}, {m}) has both a B and an I/W") + if not has["B"] and not (has["I"] and has["W"]): + what = { + (False, False): f"{c}B{m}", + (True, False): f"{c}W{m} (after {c}I{m})", + (False, True): f"{c}I{m} (before {c}W{m})", + }[(has["I"], has["W"])] + raise ScheduleError(f"{what} is missing") + for a, j in pos.items(): + for dc, dk, dm in deps(*a, C): + if dk == "BI": + jd = pos.get((dc, "B", dm), pos.get((dc, "I", dm))) + name = f"{dc}B{dm}/{dc}I{dm}" + else: + jd = pos.get((dc, dk, dm)) + name = _fmt((dc, dk, dm)) + if jd is None or jd >= j: + raise ScheduleError(f"{_fmt(a)} at order[{j}] runs before {name}, which it needs") + if fifo: + for c in range(C): + fs = sorted(range(M), key=lambda m: pos[(c, "F", m)]) + if fs != list(range(M)): + raise ScheduleError(f"chunk {c} runs its forwards in microbatch order {fs}, not FIFO") + if c == C - 1 and fuse_last: + # its gradient writer is the forward, just checked -- and, split, its W's + ws = sorted(range(M), key=lambda m, c=c: pos[(c, "W", m)]) if last_w else list(range(M)) + if ws != list(range(M)): + raise ScheduleError( + f"chunk {c} accumulates its deferred weight gradients in microbatch order {ws}, not FIFO: the fp32 " + "sum would not be bitwise-reproducible" + ) + continue + wr = sorted(range(M), key=lambda m: pos.get((c, "W", m), pos.get((c, "B", m)))) + if wr != list(range(M)): + raise ScheduleError( + f"chunk {c} accumulates its weight gradients in microbatch order " + f"{wr}, not FIFO: the fp32 sum would not be bitwise-reproducible" + ) + for key, md in (modes or {}).items(): + c, m = key + if not (0 <= c < C and 0 <= m < M): + raise ScheduleError(f"mode for {key} is outside {C} chunks x {M} microbatches") + if c == C - 1: + raise ScheduleError(f"mode {md!r} on ({c}, {m}): the last chunk keeps no residuals") + if not isinstance(md, str) or not md: + raise ScheduleError(f"mode for ({c}, {m}) must be 'r' or a stash policy name, got {md!r}") + + +# --------------------------------------------------------------------- placement +def placement(n_stages, chunks_per_stage=1, shape="circular"): + """Which device owns each chunk. Chunks are always in model order.""" + C = n_stages * chunks_per_stage + if shape == "circular": + return [c % n_stages for c in range(C)] + if shape == "v": + if chunks_per_stage != 2: + raise ValueError("v-shape needs chunks_per_stage=2") + return [c if c < n_stages else 2 * n_stages - 1 - c for c in range(C)] + raise ValueError(f"unknown shape {shape!r}") + + +# ---------------------------------------------------------------- list scheduler +def greedy(n_chunks, n_micro, place, cap=None, eager_bwd=False, f_key=None, b_key=None): + """Emit a legal, deadlock-free (chunk, kind, microbatch) order. + + Devices advance in *snapshot rounds*: every device picks against frozen state, + then all picks commit together. Without the snapshot an action issued by + device d becomes visible to device d+1 in the same round, which walks one + microbatch through the whole pipe at once and serializes the streams. + + `eager_bwd` prefers B over F when both are ready. Leave it False: with a 1F1B + cap it over-fires backward on the early devices and starves everything + downstream (measured 45% worse makespan at S=4, M=8). + """ + C, M = n_chunks, n_micro + cap = [C - c for c in range(C)] if cap is None else list(cap) + if len(cap) != C: + raise ValueError(f"cap must have {C} entries, got {len(cap)}") + ndev = max(place) + 1 + own = [[c for c in range(C) if place[c] == d] for d in range(ndev)] + fdone, bdone = set(), set() + nf, nb, inflight = [0] * C, [0] * C, [0] * C + f_key = f_key or (lambda c, m: (m, c)) + b_key = b_key or (lambda c, m: (m, -c)) + order, total, rounds = [], 2 * C * M, 0 + + while len(order) < total: + picks = [] + for d in range(ndev): + + def ready_b(d=d): + cs = [c for c in own[d] if nb[c] < M and (c, nb[c]) in fdone and (c == C - 1 or (c + 1, nb[c]) in bdone)] + if not cs: + return None + c = min(cs, key=lambda c: b_key(c, nb[c])) + return ("B", c, nb[c]) + + def ready_f(d=d): + cs = [c for c in own[d] if nf[c] < M and inflight[c] < cap[c] and (c == 0 or (c - 1, nf[c]) in fdone)] + if not cs: + return None + c = min(cs, key=lambda c: f_key(c, nf[c])) + return ("F", c, nf[c]) + + first, second = (ready_b, ready_f) if eager_bwd else (ready_f, ready_b) + p = first() or second() + if p: + picks.append(p) + if not picks: + raise RuntimeError(f"deadlock after {rounds} rounds: nf={nf} nb={nb} " f"inflight={inflight} cap={cap}") + for k, c, m in picks: + order.append((c, k, m)) + if k == "F": + fdone.add((c, m)) + nf[c] += 1 + inflight[c] += 1 + if c == C - 1: # last chunk fuses F+B, so its F implies its B + bdone.add((c, m)) + nb[c] += 1 + inflight[c] -= 1 + order.append((c, "B", m)) + else: + bdone.add((c, m)) + nb[c] += 1 + inflight[c] -= 1 + rounds += 1 + return order + + +def gpipe(n_chunks, n_micro, place): + """All forwards, then all backwards. Holds M residual sets per chunk.""" + return greedy(n_chunks, n_micro, place, cap=[n_micro] * n_chunks) + + +def one_f_one_b(n_chunks, n_micro, place): + """PipeDream-Flush. Same makespan as GPipe, C-c residual sets on chunk c.""" + return greedy(n_chunks, n_micro, place) + + +def breadth_first(n_chunks, n_micro, place): + """MaxText's circular-pipeline order: every device runs one of its chunks' + forwards for all microbatches before it starts its next chunk's, then the + backwards chunk by chunk in reverse (all forwards, then all backwards). + Under the circular placement at M >= S it reaches the interleaved optimum, + a bubble of (S-1)/(V M + S-1) at unit costs, and it visits each chunk at + most twice a step -- once forward, once backward -- which is what a + pipeline holding only the chunk it runs (`ds_ep_pipeline --fsdp-scope + repeat`) needs. `search` finds the same order at S=4, V=2 and 4, M=8; this + pins it. It is ds_ep_pipeline's default: a microbatch's stage crossings + overlap the other microbatches' forwards (on 2 x v5p-128 with the relay + boundary over DCN, M=8, a step took 5521 ms in this order and 8799 ms in + gpipe's). On V placement its bubble is longer than `search`'s. Within a chunk the backwards run microbatch 0 first; + MaxText's transposed scan runs them M-1 first.""" + return greedy(n_chunks, n_micro, place, cap=[n_micro] * n_chunks, f_key=lambda c, m: (c, m), b_key=lambda c, m: (-c, m)) + + +# ------------------------------------------------------------- heuristic search +def _keys(blk): + """Priority over a device's ready chunks, keyed on (chunk, next microbatch). + + `blk` groups microbatches into runs of `blk` on one chunk before rotating to + the next -- Megatron's interleaved warmup rule, which wants blk = n_stages. + """ + b = max(1, blk) + return { + "mb_lo_chunk": lambda c, m: (m // b, c, m), + "mb_hi_chunk": lambda c, m: (m // b, -c, m), + "chunk_lo_mb": lambda c, m: (c, m), + "chunk_hi_mb": lambda c, m: (-c, m), + } + + +def _caps(n_chunks, n_micro, place): + """Candidate in-flight limits, cheapest memory first.""" + C, M = n_chunks, n_micro + S = max(place) + 1 + V = C // S + # Megatron-interleaved: device d warms up on (S-d-1)*2 + (V-1)*S microbatches, + # spread over the V chunks it owns (the deeper chunk needs fewer). + meg = [max(1, min(M, (S - place[c] - 1) * 2 + (V - 1 - c // S) * S + 1)) for c in range(C)] + return {"1f1b": [C - c for c in range(C)], "megatron": meg, "none": [M] * C} + + +def _enumerate(n_chunks, n_micro, place, caps=None): + """Yield (makespan, peak_residual_sets, order, tag) for the heuristic space.""" + C, M = n_chunks, n_micro + S = max(place) + 1 + cands = _caps(C, M, place) if caps is None else caps + for cap_name, cap in cands.items(): + for blk in sorted({1, S}): + for eager in (False, True): + keys = _keys(blk) + for fn, fk in keys.items(): + for bn, bk in keys.items(): + try: + o = greedy(C, M, place, cap=cap, eager_bwd=eager, f_key=fk, b_key=bk) + except RuntimeError: + continue # this combination deadlocks; skip it + yield (simulate(o, place)[0], max(peak_residuals(o, C)), o, (cap_name, blk, eager, fn, bn)) + + +def search(n_chunks, n_micro, place, max_residual_sets=None, caps=None): + """Fastest schedule in the heuristic space, subject to a memory budget. + + Returns (order, tag, makespan). `max_residual_sets` caps how many in-flight + microbatches any single chunk may hold; leave None for pure speed. Ties break + toward less memory. + + There is no single textbook rule that is optimal for every (S, V, M) once a + device owns more than one chunk, so we score candidates with `simulate` rather + than hard-coding one. + """ + if max_residual_sets is not None: + if max_residual_sets < 1: + raise ValueError("max_residual_sets must be >= 1 to make progress") + caps = _caps(n_chunks, n_micro, place) if caps is None else caps + caps = {k: [min(c, max_residual_sets) for c in v] for k, v in caps.items()} + best = None + for mk, peak, o, tag in _enumerate(n_chunks, n_micro, place, caps): + if max_residual_sets is not None and peak > max_residual_sets: + continue + if best is None or (mk, peak) < (best[0], best[1]): + best = (mk, peak, o, tag) + if best is None: + raise RuntimeError("no schedule fits the residual budget " f"{max_residual_sets}; try raising it") + return best[2], best[3], best[0] + + +def pareto(n_chunks, n_micro, place, caps=None): + """The (makespan, peak_residual_sets) frontier, fastest first. + + Interleaving buys speed with memory, and how much of each you want depends on + the model -- so hand back the whole tradeoff instead of picking for the user. + """ + pts = {} + for mk, peak, o, tag in _enumerate(n_chunks, n_micro, place, caps): + if (mk, peak) not in pts: + pts[(mk, peak)] = (o, tag) + keys = sorted(pts) + front = [k for k in keys if not any(q[0] <= k[0] and q[1] <= k[1] and q != k for q in keys)] + return [(mk, peak) + pts[(mk, peak)] for mk, peak in front] + + +# ------------------------------------------------------------------- cost model +def _by_kind(cost): + """A dict that prices by kind alone, like `COST` (not a `cost_table`).""" + return isinstance(cost, dict) and set(cost) <= set(KINDS) + + +def _cost_fn(cost, C): + """Any cost spec -> cost(c, kind, mode), for C chunks. + + None means `COST`. A dict of kinds prices by kind alone; any other dict is + a program-cost table such as `V6E_COSTS` and goes through `cost_table`. A + callable gets the mode if it has a `mode` parameter, takes *args, or + requires three arguments; anything else is the older `cost(c, kind)` (maybe + with defaulted extras, as closures over a table often have) and is wrapped + so it never sees the mode. + """ + cost = cost or COST + if _by_kind(cost): + return lambda c, k, mode="r", table=cost: table[k] + if isinstance(cost, dict): + return cost_table(cost, C) + try: + ps = inspect.signature(cost).parameters + except (TypeError, ValueError): # no introspectable signature: trust it + return cost + if "mode" in ps: + return lambda c, k, mode="r": cost(c, k, mode=mode) + pos = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) + if ( + any(p.kind == p.VAR_POSITIONAL for p in ps.values()) + or sum(p.kind in pos and p.default is p.empty for p in ps.values()) >= 3 + ): + return cost + return lambda c, k, mode="r": cost(c, k) + + +def _programs(order, fuse): + """The ops of each program in turn: one op, or the two of a fused pair.""" + j = 0 + while j < len(order): + n = 2 if j in fuse else 1 + yield order[j : j + n] + j += n + + +def simulate(order, place, cost=None, *, modes=None, fuse=frozenset(), pair_gain=0.0): + """Replay `order` against a per-device timeline. -> (makespan, busy, util). + + Assumes transfers are free, which on a v6e sub-mesh boundary they nearly are + (D2D at 64-184 GB/s depending on payload size, and overlapped with compute by + JAX's async dispatch). + + `cost` is a {kind: cost} dict (default `COST`), a program-cost table (see + `cost_table`) or `cost(c, kind, mode)`, and `modes` gives each (c, m) its + mode. A fused pair (j in `fuse`) is one busy interval of both costs minus + `pair_gain`: it starts once both halves are ready, and both results land at + its end. A split last chunk (`splits_last`) has its no-op B priced as the + input gradient its F runs, its I: F + I + W, not F + B + W. + """ + # `search` scores ~200 orders with this, so the common case -- one op + # priced by kind -- stays a straight-line loop. + table = (cost or COST) if _by_kind(cost or COST) else None + cost, modes = _cost_fn(cost, len(place)), modes or {} + ndev = max(place) + 1 + free, busy, done = [0.0] * ndev, [0.0] * ndev, {} + last = len(place) - 1 if splits_last(order, len(place)) else None + + def dep(c, k, m): + if k == "F": + return done.get((c - 1, "F", m), 0.0) if c else 0.0 + if k == "W": # after its I -- a split last chunk's after its (no-op) B + return done.get((c, "I", m), done.get((c, "B", m), 0.0)) + return max(done.get((c, "F", m), 0.0), done.get((c + 1, "B", m), done.get((c + 1, "I", m), 0.0))) + + j, n = 0, len(order) + while j < n: + if j in fuse: + ops = order[j : j + 2] + d = place[ops[0][0]] + dur = sum(cost(c, "I" if c == last and k == "B" else k, modes.get((c, m), "r")) for c, k, m in ops) - pair_gain + t = max(free[d], *(dep(*a) for a in ops)) + dur + for a in ops: + done[tuple(a)] = t + j += 2 + else: + c, k, m = order[j] + d = place[c] + p = "I" if c == last and k == "B" else k + dur = table[p] if table is not None else cost(c, p, modes.get((c, m), "r")) + t = max(free[d], dep(c, k, m)) + dur + done[(c, k, m)] = t + j += 1 + free[d] = t + busy[d] += dur + mk = max(free) + return mk, busy, [b / mk for b in busy] + + +def peak_residuals(order, n_chunks): + """Max simultaneously-live residual sets per chunk. Multiply by the stage's + per-microbatch residual bytes to get HBM. The last chunk stores nothing -- + the driver fuses its forward and backward. A set lives from its F to its + B or I (the I consumes the residuals; W keeps a buffer, see `peak_wbufs`).""" + live, peak = [0] * n_chunks, [0] * n_chunks + for c, k, _ in order: + if c == n_chunks - 1: + continue + if k == "F": + live[c] += 1 + peak[c] = max(peak[c], live[c]) + elif k in ("B", "I"): + live[c] -= 1 + return peak + + +def _set_size(set_bytes): + """`set_bytes` -> size(c, mode). A callable is used as is; a mapping gives + bytes per mode, each a number or a per-chunk sequence / dict. Left out, + 'r' costs 0 (so {'lite': ...} measures stash alone); any other mode it does + not name raises KeyError, as `cost_table` does, rather than count a live + stash set as free.""" + if callable(set_bytes): + return set_bytes + + def size(c, mode): + if mode not in set_bytes: + if mode == "r": + return 0 + raise KeyError(f"no residual-set bytes for mode {mode!r} (have {sorted(set_bytes)})") + b = set_bytes[mode] + return b[c] if isinstance(b, (list, tuple, dict)) else b + + return size + + +def peak_bytes(order, place, modes, set_bytes, temp_bytes=None): + """Peak bytes of live residual sets per stage. -> [bytes per stage]. + + Like `peak_residuals`, walked in order (a set lives from its F to its B or + I), but summed over the chunks each stage owns and priced by mode: + `set_bytes(c, mode)`, or a {mode: bytes or per-chunk bytes} mapping (which + must name every stash mode used; 'r' defaults to 0). With modes None every + set is 'r'. A fused pair counts its F's new set and its B's old one + together, as the program holds both. `temp_bytes`, in the same forms: + what a B / I of that mode holds in temporaries over a remat backward's, + added while it runs, its own set still live -- the stash note's bound on + how much the step's peak grows, instead of the live sets alone. + """ + C, size, modes = len(place), _set_size(set_bytes), modes or {} + temp = (lambda c, mode: 0) if temp_bytes is None else _set_size(temp_bytes) + live, peak = [0] * (max(place) + 1), [0] * (max(place) + 1) + for c, k, m in order: + if c == C - 1: + continue + s, mode = place[c], modes.get((c, m), "r") + if k == "F": + live[s] += size(c, mode) + peak[s] = max(peak[s], live[s]) + elif k in ("B", "I"): + peak[s] = max(peak[s], live[s] + temp(c, mode)) + live[s] -= size(c, mode) + return peak + + +def splits_last(order, n_chunks): + """Does `order` split the fused last chunk, chunk n_chunks - 1 -- has it W's of its own (and no I: its F runs + the input gradient)? Its F then runs the forward, the head, the loss and the input gradient, priced + cost(C-1, 'F') + cost(C-1, 'I') (`cost_table`'s AI), and leaves a W buffer for its W, which runs the weight + gradients it defers.""" + ks = {k for c, k, _ in order if c == n_chunks - 1} + return "W" in ks and "I" not in ks + + +def peak_wbufs(order, place): + """Max pending weight-gradient buffers per stage: an I leaves one (what W + needs: layer inputs and output cotangents) and its W consumes it -- as does + a split last chunk's F (`splits_last`).""" + live, peak = [0] * (max(place) + 1), [0] * (max(place) + 1) + C = len(place) + last = splits_last(order, C) + for c, k, _ in order: + s = place[c] + if k == "I" or (last and c == C - 1 and k == "F"): + live[s] += 1 + peak[s] = max(peak[s], live[s]) + elif k == "W": + live[s] -= 1 + return peak + + +def peak_inflight(order, place): + """Max microbatches in flight per stage: each from its F to the op that ends its backward, its W (or its B where the + backward is whole) -- a residual set until its I, then a pending W buffer. The paper's memory count, which + `zb_greedy`'s `inflight_cap` bounds. The fused last chunk holds no residual set: nothing here (a split one's W + buffers, from its F to its W, are `peak_wbufs`', which `wbuf_cap` bounds).""" + C = len(place) + live, peak = [0] * (max(place) + 1), [0] * (max(place) + 1) + for c, k, _ in order: + if c == C - 1: + continue + s = place[c] + if k == "F": + live[s] += 1 + peak[s] = max(peak[s], live[s]) + elif k in ("B", "W"): + live[s] -= 1 + return peak + + +def bubble(order, place, cost=None, *, modes=None, fuse=frozenset(), pair_gain=0.0): + """Fraction of the makespan the busiest device spends idle.""" + mk, busy, _ = simulate(order, place, cost, modes=modes, fuse=fuse, pair_gain=pair_gain) + return (mk - max(busy)) / mk + + +def describe(order, place, n_chunks=None): + """Per-device action streams, for eyeballing that a schedule is what you think.""" + C = n_chunks or max(c for c, _, _ in order) + 1 + lines = [] + for d in range(max(place) + 1): + acts = [f"{k}{m}" if C == max(place) + 1 else f"c{c}{k}{m}" for c, k, m in order if place[c] == d] + lines.append(f" dev{d}: " + " ".join(acts)) + mk, busy, util = simulate(order, place) + lines.append( + f" makespan={mk:.1f} bubble={bubble(order, place) * 100:.1f}% " f"peak_residual_sets={peak_residuals(order, C)}" + ) + return "\n".join(lines) + + +# ------------------------------------------------ timed list scheduling +def timed_greedy(n_chunks, n_micro, place, cost, xfer=0.0, prefer="F", f_key=None, b_key=None, cap=None, fuse_last=False): + """Event-driven list scheduler with per-(chunk, kind) costs. + + `greedy` advances in unit-time snapshot rounds, which is exact only when + every action costs the same. Here each device, whenever it goes idle, + starts the best action that is READY at that instant (dependencies done + plus `xfer` for a cross-device hop); if none is ready it waits for the + earliest one. `cost(c, kind)`, or a cost dict as for `timed_simulate`, + gives action durations; `prefer` picks F or B when both are ready; + `fuse_last` makes the last chunk's F imply its B (the driver then runs one + fused program). + + Returns (order, makespan). The order is sorted by start time, which is a + valid topological order for the single-threaded driver. + """ + C, M = n_chunks, n_micro + ndev = max(place) + 1 + if isinstance(cost, dict): + cost = _cost_fn(cost, C) + cap = [M] * C if cap is None else list(cap) + f_key = f_key or (lambda c, m: (c, m)) + b_key = b_key or (lambda c, m: (-c, m)) + done = {} + nf, nb, inflight = [0] * C, [0] * C, [0] * C + free = [0.0] * ndev + started = [] + + def ready_time(c, k, m): + if k == "F": + if c == 0: + return 0.0 + t = done.get((c - 1, "F", m)) + return None if t is None else t + (xfer if place[c - 1] != place[c] else 0.0) + tf = done.get((c, "F", m)) + if tf is None: + return None + if c == C - 1: + return tf + tb = done.get((c + 1, "B", m)) + if tb is None: + return None + return max(tf, tb + (xfer if place[c + 1] != place[c] else 0.0)) + + total = 2 * C * M + while len(started) < total: + # the device that frees up first picks next + best = None + for d in range(ndev): + cands = [] + for c in range(C): + if place[c] != d: + continue + if nf[c] < M and inflight[c] < cap[c]: + r = ready_time(c, "F", nf[c]) + if r is not None: + cands.append((max(r, free[d]), "F", c, nf[c])) + if nb[c] < M and not (fuse_last and c == C - 1): + r = ready_time(c, "B", nb[c]) + if r is not None: + cands.append((max(r, free[d]), "B", c, nb[c])) + if not cands: + continue + t0 = min(x[0] for x in cands) + now = [x for x in cands if x[0] <= t0 + 1e-9] + + def rank(x): + _, k, c, m = x + pk = 0 if k == prefer else 1 + return (pk, f_key(c, m) if k == "F" else b_key(c, m)) + + pick = min(now, key=rank) + if best is None or pick[0] < best[0] - 1e-9 or (abs(pick[0] - best[0]) <= 1e-9 and d < best[4]): + best = (*pick, d) + if best is None: + raise RuntimeError(f"timed_greedy deadlock: nf={nf} nb={nb} inflight={inflight}") + t, k, c, m, d = best + dur = cost(c, k) + (cost(c, "B") if (fuse_last and c == C - 1 and k == "F") else 0.0) + free[d] = t + dur + done[(c, k, m)] = t + dur + started.append((t, c, k, m)) + if k == "F": + nf[c] += 1 + inflight[c] += 1 + if fuse_last and c == C - 1: + done[(c, "B", m)] = t + dur + nb[c] += 1 + inflight[c] -= 1 + started.append((t + 1e-9, c, "B", m)) + else: + nb[c] += 1 + inflight[c] -= 1 + started.sort(key=lambda x: x[0]) + return [(c, k, m) for _, c, k, m in started], max(free) + + +def timed_search(n_chunks, n_micro, place, cost, xfer=0.0, fuse_last=False, caps=None): + """Best `timed_greedy` order over a small policy space. -> (order, tag, makespan).""" + C = n_chunks + if isinstance(cost, dict): + cost = _cost_fn(cost, C) + S = max(place) + 1 + keys = {**_keys(1), **{f"{k}/blk{S}": v for k, v in _keys(S).items()}} + cands = caps or {"none": None, "1f1b": [C - c for c in range(C)], **{f"cap{v}": [v] * C for v in (2, 3, 4)}} + best = None + for cn, cap in cands.items(): + for prefer in ("F", "B"): + for fn, fk in keys.items(): + for bn, bk in keys.items(): + try: + o, mk = timed_greedy(C, n_micro, place, cost, xfer, prefer, fk, bk, cap, fuse_last) + except RuntimeError: + continue + if best is None or mk < best[2] - 1e-9: + best = (o, (cn, prefer, fn, bn), mk) + return best + + +# ------------------------------------------------- stash list scheduling +# How the stash scheduler sees memory. A stash-mode forward leaves a +# residual set (`ds_ep.ChunkPrograms.build_stash`: `bytes` per device and +# microbatch) that stays live on its stage until its backward consumes it +# (donated; it is live while that backward runs, as an argument). The budget +# is the bytes of simultaneously-live stash sets per stage -- `peak_bytes` +# with {policy: bytes}, which leaves out the layer inputs every mode keeps -- +# on top of what a remat step holds. That is not all the step's peak grows +# by: the stash programs' temporaries are LARGER than the remat ones', not +# smaller (G1, `memory_analysis` at --preset v6e). A stash backward holds +# +0.38 GiB (attn, attn_min), +0.42 / +0.67 (lite, chunks 2 / 0) and +# -0.08 / +0.17 (lite_y) over the remat backward's 6.34 GiB -- STASH_BWD_TEMP, +# as shares of the set -- so the peak can grow by the live sets plus that: +# 4.06 + 0.67 GiB for three lite sets at config A, over a 4.5 GiB budget +# (`peak_bytes(..., temp_bytes=)`, `Pipeline.peak_stash_gib(temps=True)`, +# which the summary prints next to the budget). The stash forwards' extra +# temporaries (+0.8 to 1.7 GiB over 1.75) stay below a backward's. +# How much headroom a chip really has (31.25 GiB on a v6e, less params, +# optimizer state, gathered weights, gradient accumulators, the largest +# program's temporaries and fragmentation) is a measurement, not this model: +# the default budget must be set from a `--mem-report` sweep on the TPU (G2), +# reading each run's peak against that bound, not against the budget alone. + + +def _per(x, n, what): + """A number (every index), a sequence of n, or {index: value} (0 elsewhere) -> list of n.""" + if isinstance(x, dict): + return [x.get(i, 0) for i in range(n)] + if isinstance(x, (list, tuple)): + if len(x) != n: + raise ValueError(f"{what} has {len(x)} entries, want {n}") + return list(x) + return [x] * n + + +def stash_greedy( + n_chunks, + n_micro, + place, + cost, + xfer=0.0, + stash_bytes=0, + budget_bytes=0, + *, + policy="s", + caps=None, + prefer="F", + f_key=None, + b_key=None, + prio=None, +): + """`timed_greedy`'s event engine, choosing each forward's mode as it goes. + + -> (order, modes, makespan, peak): `modes` is {(c, m): policy} for the + stash-mode forwards (every other (c, m) is remat, 'r'), `peak` the peak + live stash bytes per stage. + + Whenever a device goes idle it starts the best action READY at that + instant, as `timed_greedy` does, ranked by `prefer` and `f_key` / `b_key` + -- or by a priority vector `prio[(chunk, kind)]`, lower first, ties to the + lower microbatch. Picking a forward of a non-last chunk c sets its mode: + stash (`policy`) if c holds fewer than `caps[c]` live stash sets (None: no + cap) and its stage's live stash bytes plus `stash_bytes[c]` stay within + `budget_bytes` (per stage; see the memory note above), else remat. Its + backward then costs `cost(c, 'B', policy)` and frees the set. `cost` is + as for `timed_simulate`; `stash_bytes` a number or one per chunk. + + The last chunk is one fused program (the driver's only mode), its no-op B + right after its F. Every chunk runs its forwards and backwards in + microbatch order (FIFO), so the fp32 gradient accumulation happens in the + same order as under any other schedule: order and modes change no + gradient bit. Deterministic. + """ + C, M = n_chunks, n_micro + S = max(place) + 1 + cost = _cost_fn(cost, C) + sb = _per(stash_bytes, C, "stash_bytes") + bud = _per(budget_bytes, S, "budget_bytes") + cap = [M] * C if caps is None else [M if x is None else x for x in _per(caps, C, "caps")] + f_key = f_key or (lambda c, m: (c, m)) + b_key = b_key or (lambda c, m: (-c, m)) + if prio is not None: + rank = lambda k, c, m: (prio[(c, k)], m) + else: + rank = lambda k, c, m: (k != prefer, f_key(c, m) if k == "F" else b_key(c, m)) + own = [[c for c in range(C) if place[c] == d] for d in range(S)] + hop_f = [0.0] + [xfer if place[c - 1] != place[c] else 0.0 for c in range(1, C)] # into F(c) + hop_b = [xfer if place[c + 1] != place[c] else 0.0 for c in range(C - 1)] + [0.0] # into B(c) + done_f = [[None] * M for _ in range(C)] + done_b = [[None] * M for _ in range(C)] + nf, nb, slive = [0] * C, [0] * C, [0] * C + free, live, peak = [0.0] * S, [0] * S, [0] * S + modes, picks = {}, [] + for _ in range(2 * C * M - M): # every op but the last chunk's no-op backwards + best = None + for d in range(S): + cands = [] + for c in own[d]: + if nf[c] < M: + m = nf[c] + r = 0.0 if c == 0 else done_f[c - 1][m] + if r is not None: + cands.append((max(r + hop_f[c], free[d]), "F", c, m)) + if c != C - 1 and nb[c] < M: + m = nb[c] + tf, tb = done_f[c][m], done_b[c + 1][m] + if tf is not None and tb is not None: + cands.append((max(tf, tb + hop_b[c], free[d]), "B", c, m)) + if not cands: + continue + t0 = min(x[0] for x in cands) + pick = min((x for x in cands if x[0] <= t0 + 1e-9), key=lambda x: rank(*x[1:])) + if best is None or pick[0] < best[0] - 1e-9: + best = pick + (d,) + if best is None: + raise RuntimeError(f"stash_greedy deadlock: nf={nf} nb={nb}") + t, k, c, m, d = best + s = place[c] + if k == "F": + mode = "r" + if c != C - 1 and slive[c] < cap[c] and live[s] + sb[c] <= bud[s]: + mode = policy + modes[(c, m)] = mode + slive[c] += 1 + live[s] += sb[c] + peak[s] = max(peak[s], live[s]) + dur = cost(c, "F", mode) + (cost(c, "B") if c == C - 1 else 0.0) + done_f[c][m] = t + dur + if c == C - 1: + done_b[c][m] = t + dur + nf[c] += 1 + else: + mode = modes.get((c, m), "r") + if mode != "r": + slive[c] -= 1 + live[s] -= sb[c] + dur = cost(c, "B", mode) + done_b[c][m] = t + dur + nb[c] += 1 + free[d] = t + dur + picks.append((t, c, k, m)) + # Picks are made in start order (a device only ever starts at or after the + # instant of the previous pick), so the list is already a topological order; + # the stable sort only settles ties the 1e-9 slack let through. + order = [] + for _, c, k, m in sorted(picks, key=lambda p: p[0]): + order.append((c, k, m)) + if c == C - 1: + order.append((c, "B", m)) + return order, modes, max(free), peak + + +def _stash_caps(C, M, place, sb, bud, limit=32): + """Per-chunk live stash caps that fill each stage's budget: every maximal + allocation (one more set of any chunk would not fit), as the product over + stages; the most even `limit` of them if there are more.""" + S = max(place) + 1 + per_stage = [] + for s in range(S): + chs = [c for c in range(C - 1) if place[c] == s and sb[c] > 0] + allocs = [] + + def rec(i, left, cur, chs=chs, allocs=allocs): + if i == len(chs): + if all(sb[c] > left or n == M for c, n in zip(chs, cur)): + allocs.append(tuple(cur)) + return + for n in range(min(M, int(left // sb[chs[i]])) + 1): + rec(i + 1, left - n * sb[chs[i]], cur + [n]) + + rec(0, bud[s], []) + per_stage.append((chs, allocs)) + out = [[M if sb[c] <= 0 and c != C - 1 else 0 for c in range(C)]] + for chs, allocs in per_stage: + nxt = [] + for cap in out: + for a in allocs: + cap = list(cap) + for c, n in zip(chs, a): + cap[c] = n + nxt.append(cap) + out = nxt + if len(out) > limit: + spread = lambda cap: max(cap[: C - 1]) - min(cap[: C - 1]) + out = sorted(out, key=spread)[:limit] + return out + + +def stash_search( + n_chunks, n_micro, place, cost, xfer=0.0, stash_bytes=0, budget_bytes=0, *, policy="s", caps=None, trials=128, seed=0 +): + """Best `stash_greedy` order and modes under a stash budget. + -> (order, modes, tag, makespan) + + Tries per-chunk caps -- `caps` if given, else every allocation that fills + each stage's `budget_bytes` with whole sets (one more set of any chunk + would not fit) plus none at all (the budget alone, first come first + served) -- against `timed_search`'s rank families and `trials` random + priority vectors over (chunk, kind) drawn from `seed`. The fastest wins; + ties go to the least peak stash, then the first found. Deterministic. + + Which forwards to stash is not only a matter of memory: a set lives from + its forward to its backward, so stashing chunk 0 -- whose backward comes + last -- holds budget for a whole round trip that later chunks could reuse + several times over. The caps are how the search tries that trade. + """ + import random + + C, M = n_chunks, n_micro + S = max(place) + 1 + cost = _cost_fn(cost, C) + sb = _per(stash_bytes, C, "stash_bytes") + bud = _per(budget_bytes, S, "budget_bytes") + cands = [list(caps)] if caps is not None else _stash_caps(C, M, place, sb, bud) + [None] + keys = {**_keys(1), **{f"{k}/blk{S}": v for k, v in _keys(S).items()}} + ranks = [ + ((prefer, fn, bn), dict(prefer=prefer, f_key=fk, b_key=bk)) + for prefer in ("F", "B") + for fn, fk in keys.items() + for bn, bk in keys.items() + ] + rng = random.Random(seed) + for t in range(trials): + ranks.append((("prio", t), dict(prio={(c, k): rng.random() for c in range(C) for k in "FB"}))) + best = None + for cap in cands: + for rtag, kw in ranks: + o, md, mk, pk = stash_greedy(C, M, place, cost, xfer, sb, bud, policy=policy, caps=cap, **kw) + if best is None or mk < best[3] - 1e-9 or (mk <= best[3] + 1e-9 and sum(pk) < best[4]): + best = (o, md, ("budget" if cap is None else tuple(cap), rtag), mk, sum(pk)) + return best[:4] + + +# The stash programs' costs as shares of a non-first chunk's remat forward F, +# for a cost table that has none of its own: what G1 measured on v6e (chunk +# 2, `--tiles v6e`, progbench deltas against the remat programs; F = 22.77 +# ms), carried to other shapes and chips in proportion -- an estimate there. +# STASH_SAVES what the stash backward no longer recomputes: Bs = B - +# share x F. (attn skips the attention projections and +# the splash forward, lite also the gathered tokens and the +# experts' up-projections, lite_y gmm_wo too; 'all' keeps +# the vjp's own intermediates and loses some of that to +# the extra memory traffic.) +# STASH_FWD_EXTRA what the stash forward costs over the remat one: Fs = F +# + share x F (writing the stash out, and the fusions it +# breaks). +STASH_SAVES = dict(attn=0.272, attn_min=0.244, lite=0.421, lite_y=0.534, all=0.440) +STASH_FWD_EXTRA = dict(attn=0.082, attn_min=0.087, lite=0.120, lite_y=0.215, all=0.200) +# What a stash backward holds in temporaries over the remat backward it +# replaces, as a share of its stash set's bytes (G1, `memory_analysis` temps +# of bwda_s less bwda's 6.34 GiB, the worse of chunks 0 and 2 -- attn was +# measured on chunk 2 only): attn +0.38 GiB on a 0.713 set, attn_min +0.38 on +# 0.659, lite +0.42 / +0.67 on 1.354, lite_y -0.08 / +0.17 on 2.229, all +# -0.83 / -0.86 (0: never counted below the remat backward). See the stash +# note above; the scheduler's budget does not include it. +STASH_BWD_TEMP = dict(attn=0.533, attn_min=0.577, lite=0.495, lite_y=0.076, all=0.0) + + +def stash_estimates(k, policy, n_chunks): + """{'Bs{c}:{policy}': ms, 'Fs{c}:{policy}': ms} for every non-last chunk c: + ESTIMATES of the stash backward and forward from the remat costs of the + table `k` (as `cost_table` reads it) and the shares above of the forward + F of a non-first chunk (chunk 0's embedding is not recomputed in either + mode, nor stashed). For a table without stash costs of its own (the + driver fills them in: TPU7x, the padded tiles' v6e table (V6E_COSTS), an + `xprof costs` table).""" + cost = cost_table(k, n_chunks) + f = float(k["F"]) if "F" in k else cost(min(1, n_chunks - 2), "F") + out = {} + for c in range(n_chunks - 1): + out[f"Bs{c}:{policy}"] = round(cost(c, "B") - STASH_SAVES[policy] * f, 2) + out[f"Fs{c}:{policy}"] = round(cost(c, "F") + STASH_FWD_EXTRA[policy] * f, 2) + return out + + +def timed_simulate(order, place, cost, xfer=0.0, fuse_last=False, *, modes=None, fuse=frozenset(), pair_gain=0.0): + """Replay a fixed order with real costs. -> (makespan, per-device busy). + + `cost(c, kind, mode)`, the older `cost(c, kind)`, or a program-cost table + such as `V6E_COSTS`; `modes` gives each (c, m) its mode; a fused pair (j in + `fuse`) is one program costing both halves minus `pair_gain`, whose results + both land at its end. `fuse_last`: the last chunk's F costs its F + B, or, + split (`splits_last`: W's of its own), its F + I. + """ + ndev = max(place) + 1 + C = max(c for c, _, _ in order) + 1 + cost, modes = _cost_fn(cost, C), modes or {} + free, busy, done = [0.0] * ndev, [0.0] * ndev, {} + rest = "I" if splits_last(order, C) else "B" # what the fused last chunk's F runs besides its forward + + def dep_dur(c, k, m, d): + mode = modes.get((c, m), "r") + if k == "F": + dep = 0.0 if c == 0 else done[(c - 1, "F", m)] + (xfer if place[c - 1] != d else 0.0) + return dep, cost(c, "F", mode) + (cost(c, rest, mode) if fuse_last and c == C - 1 else 0.0) + if k == "W": + return done[(c, "BI", m)], cost(c, "W", mode) + dep = done[(c, "F", m)] + if c < C - 1: + dep = max(dep, done[(c + 1, "BI", m)] + (xfer if place[c + 1] != d else 0.0)) + return dep, cost(c, k, mode) + + for ops in _programs(order, fuse): + c, k, m = ops[0] + d = place[c] + if len(ops) == 1 and fuse_last and c == C - 1 and k == "B": + done[(c, k, m)] = done[(c, "BI", m)] = done[(c, "F", m)] + continue + if len(ops) == 1: + dep, dur = dep_dur(c, k, m, d) + else: + dd = [dep_dur(*a, d) for a in ops] + dep, dur = max(x for x, _ in dd), sum(y for _, y in dd) - pair_gain + t = max(free[d], dep) + dur + for c, k, m in ops: + done[(c, k, m)] = t + if k in ("B", "I"): + done[(c, "BI", m)] = t + free[d] = t + busy[d] += dur + return max(free), busy + + +# ------------------------------------------------------ per-stage streams +def merge(streams, place, cost, xfer=0.0, pair_gain=0.0, *, modes=None, n_micro=None): + """Per-stage action lists -> one global order. -> (order, fuse, makespan) + + Most published schedules (1F1B, ZB-V, DualPipeV) are written down as what + each stage runs, in its own order; the driver replays one global list. + `streams[s]` is stage s's list of items, each an op `(c, kind, m)` or a + fused pair `((cF, 'F', i), (cB, 'B' or 'I', j))` run as one program. + + Event-driven, like `timed_greedy` with every choice already made: start + whichever stage's next item is ready earliest (its dependencies done, plus + `xfer` for a cross-stage hop; ties to the lower stage). `cost` is as for + `timed_simulate`. A pair lasts both costs minus `pair_gain`, and both + results land at its end. The last chunk is fused -- its F runs + `cost(C-1, 'F') + cost(C-1, 'B')`, or split (W's of its own in the streams, + `splits_last`) `cost(C-1, 'F') + cost(C-1, 'I')`, as + `timed_simulate(fuse_last=True)` has it -- and its no-op B may be left out of + the streams: it is re-inserted right after the item holding its F. + + The order is sorted by start time (ties to the lower stage), a valid + topological order, and `fuse` holds the index of each pair's F. A stage + whose next item can never become ready raises `ScheduleError` -- which is + how an illegal per-stage order is caught -- and so does a merged order + that `validate` rejects (FIFO is not required here). Pass `n_micro`, as + every generator should: without it the count is read off the streams + themselves, so a microbatch missing from every stage goes unnoticed. + """ + C, S = len(place), max(place) + 1 + if len(streams) != S: + raise ScheduleError(f"{len(streams)} streams for {S} stages") + cost, modes = _cost_fn(cost, C), modes or {} + items = [] + for s, st in enumerate(streams): + row = [] + for it in st: + ops = (tuple(it),) if isinstance(it[0], int) else tuple(tuple(a) for a in it) + if len(ops) == 1 and ops[0][0] == C - 1 and ops[0][1] == "B": + continue # the fused last chunk's no-op backward; re-inserted below + if len(ops) == 2: + ops = tuple(sorted(ops, key=lambda a: a[1] != "F")) + if len(ops) > 2 or (len(ops) == 2 and (ops[0][1] != "F" or ops[1][1] not in ("B", "I"))): + raise ScheduleError(f'stage {s}: {"&".join(map(_fmt, ops))} is not an op or an F&B pair') + for a in ops: + if place[a[0]] != s: + raise ScheduleError(f"{_fmt(a)} is in stage {s}'s stream but chunk {a[0]} is on " f"stage {place[a[0]]}") + row.append(ops) + items.append(row) + + done = {} + + def ready(c, k, m): + hop = lambda c2: xfer if place[c2] != place[c] else 0.0 + if k == "F": + if c == 0: + return 0.0 + t = done.get((c - 1, "F", m)) + return None if t is None else t + hop(c - 1) + if k == "W": + return done.get((c, "BI", m)) + if k not in ("B", "I"): + raise ScheduleError(f"unknown kind {k!r} in {(c, k, m)}") + tf = done.get((c, "F", m)) + if tf is None or c == C - 1: + return tf + tb = done.get((c + 1, "BI", m)) + return None if tb is None else max(tf, tb + hop(c + 1)) + + rest = "I" if splits_last([a for row in items for ops in row for a in ops], C) else "B" + + def dur(c, k, m): + mode = modes.get((c, m), "r") + if c == C - 1 and k == "F": + return cost(c, "F", mode) + cost(c, rest, mode) + return cost(c, k, mode) + + ptr, free = [0] * S, [0.0] * S + started = [] # (start, stage, ops), in the order they start + n_items = sum(len(r) for r in items) + while len(started) < n_items: + best = None + for s in range(S): + if ptr[s] == len(items[s]): + continue + ops = items[s][ptr[s]] + ts = [ready(*a) for a in ops] + if any(t is None for t in ts): + continue + t0 = max([free[s]] + ts) + if best is None or t0 < best[0] - 1e-12: + best = (t0, s, ops) + if best is None: + raise ScheduleError( + "deadlock: no stage's next item can ever run -- " + + ", ".join( + f"s{s}: " + ("&".join(map(_fmt, items[s][ptr[s]])) if ptr[s] < len(items[s]) else "done") for s in range(S) + ) + ) + t0, s, ops = best + t1 = t0 + (dur(*ops[0]) if len(ops) == 1 else sum(dur(*a) for a in ops) - pair_gain) + for c, k, m in ops: + done[(c, k, m)] = t1 + if k in ("B", "I") or (k == "F" and c == C - 1): + done[(c, "BI", m)] = t1 + started.append((t0, s, ops)) + free[s] = t1 + ptr[s] += 1 + order, fuse = [], set() + for _, _, ops in started: + if len(ops) == 2: + fuse.add(len(order)) + order.extend(ops) + order.extend((C - 1, "B", m) for c, k, m in ops if c == C - 1 and k == "F") + if n_micro is None and order: + n_micro = 1 + max(m for _, _, m in order) + if n_micro is not None: + validate(order, place, n_micro, modes=modes, fuse=fuse, fifo=False) + return order, frozenset(fuse), max(free) + + +# ---------------------------------------------------------- measured costs +# Per-program medians in ms (`xprof costs` reads them off a capture): F0 / B0 +# chunk 0 (which also embeds), F / B every other chunk, A the fused last chunk +# (forward, head and backward in one program, no recompute), xfer one stage +# boundary hop. Only the ratios matter to the schedulers. +# TPU7x: the reference shape `--schedule timed` was first tuned on. +# v6e: PP2 x FSDP1 x EP2, 16 experts, gbs 16, M 8, V 2 -- one v6e-4 capture +# (1613 ms/step) with the padded megablox tiles of MaxText's +# production flags (one (512, D, 512) x3 for both weights: see +# ds_ep.TILES). Its update programs take another 15.9 / 19.2 ms +# per stage. +# v6e tiles: the same run with `--tiles v6e` (1319 ms/step), which unpads the +# three gmm kernels with a 7168 contraction tile: ~3.2 ms off every +# forward, ~15.6 off every backward and A; the updates are as above. +# The driver also prices the default `--tiles clamped` with it +# (unmeasured, but unpadded too: ds_ep_pipeline.default_costs). +# Its stash programs (`--schedule stash`) are d-keys, G1's +# progbench deltas against the remat programs: see +# V6E_TILES_STASH_DELTAS at the end of the file. +# pair_gain: what an F&B pair program saves over its two halves run back to +# back (`merge` / `timed_simulate(pair_gain=)`; the driver's default for +# `--pair-gain`). An F2&B0 pair under the padded tiles: 98.3 ms back to back, +# 96.4 as one program. Not re-measured with the v6e tiles, nor for the other +# pair types (F1&B2, F2&B1, A3&B0 under V): the v6e-tiles table carries the +# same 1.9. +TPU7X_COSTS = dict(F0=18.5, F=16.5, B0=51.3, B=48.6, A=58.3, xfer=1.0) +V6E_COSTS = dict(F0=27.98, F=25.70, B0=71.65, B=68.70, A=86.98, xfer=1.0, pair_gain=1.9) +V6E_TILES_COSTS = dict(F0=24.75, F=22.44, B0=55.84, B=53.10, A=71.46, xfer=1.0, pair_gain=1.9) # + stash d-keys, below + + +def cost_table(k, C, policy=None): + """A cost table (ms per program) -> `cost(c, kind, mode='r')` for C chunks. + + Each cost is looked up most specific key first: + + forward F{c}, F (F0 is chunk 0's own key, so the + remat backward B{c}, B old F0/F/B0/B tables mean what + input gradient I{c}, I they always did) + weight gradient W{c}, W + stash backward Bs{c}:{p}, dBs{c}:{p}, Bs:{p}, dBs:{p}, Bs{c}, Bs (policy p) + stash forward Fs{c}:{p}, dFs{c}:{p}, Fs:{p}, dFs:{p}, Fs{c}, Fs, + then the remat forward + fused last chunk A for its F; its B is then 0. Split (W's of its own, + `splits_last`): its W is W{c}, else WA, and its F runs + AI (default A - W) -- F + I, so its I is AI - A + + A d-key is what the stash program costs over the remat one, so it follows + the table's own F{c} / B{c}: a table that overrides those (`--costs`) + reprices the stash programs with them, where an absolute stash key would go + stale. A mode is 'r' (remat), a stash policy name, or 's' for `policy`. A + missing key raises KeyError rather than guess; F and B of every chunk are + looked up here, so a table short of one fails now, not inside a search. + Keys it does not read (xfer, pair_gain, the `xprof costs` extras) are ignored. + """ + + def get(names, base=()): + for n in names: + if n in k: # a d-key adds to the first of `base` the table has + return float(k[n]) + (get(base) if n.startswith("d") else 0.0) + raise KeyError(f"cost table has none of {names}") + + def cost(c, kind, mode="r"): + if c == C - 1: + if kind == "F": + return get(["A"]) + if kind == "W": # a split last chunk's deferred weight gradients + return get([f"W{c}", "WA"]) + if kind == "I": # ... and what its F, AI, takes off A + return (get(["AI"]) if "AI" in k else get(["A"]) - get([f"W{c}", "WA"])) - get(["A"]) + return 0.0 + p = policy if mode == "s" else mode + remat = [f"{kind}{c}", kind] + if kind in ("F", "B") and mode != "r": + s = f"{kind}s" + names = [f"{s}{c}:{p}", f"d{s}{c}:{p}", f"{s}:{p}", f"d{s}:{p}"] if p else [] + names += [f"{s}{c}", s] + if kind == "B": + return get(names, remat) + try: + return get(names, remat) + except KeyError: + pass # a stash forward costs what the remat one does unless measured + if kind not in KINDS: + raise ScheduleError(f"unknown kind {kind!r}") + return get(remat) + + for c in range(C): + cost(c, "F") + cost(c, "B") + return cost + + +# ------------------------------------------ interleaved 1F1B, F&B pairs, stash modes +def megatron_interleaved(n_stages, chunks_per_stage, n_micro, group=None, pair_stages=()): + """Megatron-LM's interleaved 1F1B as per-stage streams, for `merge`. + + Circular placement, `placement(S, V)`: rank r owns model chunks j = 0..V-1, + which are global chunks j*S + r. Rank r runs the virtual microbatches + k = 0..M*V-1 (`forward_backward_pipelining_with_interleaving`), in groups of + G microbatches a chunk (`group`, Megatron's microbatch_group_size_per_vp_stage, + default S): + + warmup F(k) k < W = min((S-r-1)*2 + (V-1)*G, M*V) + steady F(k+W), B(k) for the remaining M*V - W + cooldown B(k) for the last W + + where virtual microbatch k is model chunk (k % (G*V)) // G going forward + (V-1 minus that going backward) and microbatch (k // (G*V)) * G + k % G. + A group of S is just enough for a microbatch's forward to come round the S + stages to rank 0's next chunk when nothing costs time between the stages: with + G > S each chunk switch has G - S programs of slack against the boundary + copies' latency, at the price of (V-1)(G-S) more warmup forwards held (their + residuals), and of about G - S more boundary inputs waiting on the end ranks + while they finish a group -- on rank 0 the activations for its next chunk, on + rank S-1 the cotangents for its next chunk going backward -- which + --offload-residuals, moving only the residuals to the host, leaves in HBM. + The fused last chunk's B is left out; `merge` puts the no-op back. Needs + V >= 2 and G >= S, as Megatron does, and M a multiple of G: at G > S that is + stricter than Megatron, which also runs a last group of S..G-1 microbatches. + + `pair_stages` (None: every rank; by default none) are the ranks whose + steady state runs each F(k+W), B(k) as ONE program, an F&B pair: the + forward of one microbatch beside the backward of another, so that XLA may + overlap one's expert-parallel all-gather / reduce-scatter with the other's + compute, as Megatron's combined 1F1B (overlap_moe_expert_parallel_comm) + overlaps its all-to-alls. Where B(k) is the fused last chunk's no-op its F + runs alone, and the warmup and cooldown stay single ops, so every rank's + sequence is the unpaired one: the merged order is as FIFO. On rank S-1 + F(k+W) is the fused last chunk's exactly where B(k) is its no-op, so that + program never pairs. (Megatron warms up one forward more there so that + F(k+W) and B(k) are never one microbatch's; they are only where B(k) is + the last chunk's, which the fused program holds.) A pair's F output + leaves only when its B is done too, while the backward chain keeps each + rank a step behind the next: a boundary copy's latency is no longer + hidden, and in unit costs each steady-state step grows by about the + copy's (S=8, V=2, M=128, G=8 at xfer 0.16: 833 against 794 unpaired), + which the pair's overlap has to win back (`pair_gain`). + """ + S, V, M = n_stages, chunks_per_stage, n_micro + G = S if group is None else int(group) + if V < 2: + raise ValueError("interleaved 1F1B needs chunks_per_stage >= 2 (V=1 is plain 1F1B)") + if G < S: + raise ValueError(f"interleaved 1F1B needs a microbatch group of at least n_stages, got {G} and {S}") + if M % G: + what = "n_stages" if G == S else "its microbatch group" + raise ValueError(f"interleaved 1F1B needs n_micro a multiple of {what}, got {M} and {G}") + C, total = S * V, M * V + + def op(r, k, kind): + j = (k % (G * V)) // G + if kind == "B": + j = V - 1 - j + return (j * S + r, kind, (k // (G * V)) * G + k % G) + + paired = set(range(S)) if pair_stages is None else set(pair_stages) + noop = lambda a: a[0] == C - 1 and a[1] == "B" + streams = [] + for r in range(S): + w = min((S - r - 1) * 2 + (V - 1) * G, total) + st = [op(r, k, "F") for k in range(w)] + for k in range(total - w): + f, b = op(r, k + w, "F"), op(r, k, "B") + st += [f] if noop(b) else [(f, b)] if r in paired else [f, b] + st += [b for b in (op(r, k, "B") for k in range(total - w, total)) if not noop(b)] + streams.append(st) + return streams + + +def stash_modes(order, place, stash_bytes, budget_bytes, caps=None, *, policy=None): + """Stash modes for a FIXED order under a per-stage byte budget. -> {(c, m): policy} + + The post-pass for schedules that do not pick modes as they go (Megatron's + interleaved 1F1B, its pairs): a (c, m) of a non-last chunk may stash -- keep its residual set + from its F to its B or I and skip the recompute -- where it fits: + + * the live sets of every stage, priced as `peak_bytes` prices them with + `stash_bytes`, stay within `budget_bytes` (a number, or one per stage), + so `peak_bytes(order, place, modes, stash_bytes) <= budget`; + * chunk c holds at most `caps[c]` stash sets at a time (`caps` a + per-chunk sequence or {chunk: n}; None or a chunk left out: no cap). + + Every stashed set saves one recompute, so the aim is as many as fit. The + sets go in the order their stage frees them -- by the position of their B + or I among the stage's ops, earliest first -- and each is taken if it fits + over its whole life (else it stays remat). This is the interval-scheduling + greedy: of the sets still to place, the one freed first leaves the most + room for the rest, so where every set of a stage adds the same bytes and + no cap applies it stashes as many sets as any assignment can. With + per-chunk sizes or caps it is a heuristic. On a FIFO order a chunk's B's + run in microbatch order, so its sets are handed out in that order too. + Deterministic. + + `stash_bytes` is as for `peak_bytes`: a {mode: bytes or per-chunk bytes} + mapping (leave 'r' out to budget the stash sets alone, or name it to budget + every live set) or `size(c, mode)`. `policy` is the stash policy handed + out; by default the one mode besides 'r' that the mapping names. Raises + ValueError if the remat sets alone exceed the budget. + """ + C, S = len(place), max(place) + 1 + size = _set_size(stash_bytes) + if policy is None: + names = [p for p in stash_bytes if p != "r"] if isinstance(stash_bytes, dict) else [] + if len(names) != 1: + raise ValueError(f"pass policy=: cannot tell the stash policy from {stash_bytes!r}") + policy = names[0] + if policy == "r": + raise ValueError("'r' is remat, not a stash policy") + budget = list(budget_bytes) if isinstance(budget_bytes, (list, tuple)) else [budget_bytes] * S + if len(budget) != S: + raise ValueError(f"budget_bytes must have {S} entries, got {len(budget)}") + cap = dict(enumerate(caps)) if isinstance(caps, (list, tuple)) else dict(caps or {}) + cap = {c: n for c, n in cap.items() if n is not None} + seq = [[] for _ in range(S)] # each stage's own sequence: (order index, op) + for j, a in enumerate(order): + seq[place[a[0]]].append((j, tuple(a))) + live = [[0] * len(q) for q in seq] # bytes live at each position of a stage + held = [[0] * len(seq[place[c]]) for c in range(C)] # chunk c's stash sets there + sets, at = [], {} + for s, q in enumerate(seq): + for i, (j, (c, k, m)) in enumerate(q): + if c == C - 1: + continue # the fused last chunk keeps nothing + if k == "F": + at[(c, m)] = i + elif k in ("B", "I"): + if (c, m) not in at: + raise ScheduleError(f"{_fmt((c, k, m))} at order[{j}] runs before {c}F{m}") + f = at.pop((c, m)) + sets.append((s, i, c, m, f)) # it lives over positions [f, i) + for t in range(f, i): + live[s][t] += size(c, "r") + if at: + c, m = min(at) + raise ScheduleError(f"{c}F{m} has no B or I") + for s in range(S): + if live[s] and max(live[s]) > budget[s]: + raise ValueError(f"stage {s}: the remat sets alone need {max(live[s])}, over the budget " f"{budget[s]}") + modes = {} + for _, i, c, m, f in sorted(sets): # stage by stage, the earliest freed first + s, extra = place[c], size(c, policy) - size(c, "r") + if max(live[s][f:i]) + extra > budget[s] or max(held[c][f:i]) >= cap.get(c, float("inf")): + continue + for t in range(f, i): + live[s][t] += extra + held[c][t] += 1 + modes[(c, m)] = policy + return modes + + +# Stash programs with `--tiles v6e`, as `cost_table` d-keys: what the stash +# variant of a chunk's program costs over its remat one, so they follow any +# `--costs` that overrides F / B. G1's progbench medians, `fwd_s` / `bwda_s` +# against `fwd` / `bwda` of the same chunk in the same session: chunk 2 as +# dFs:{p} / dBs:{p}, which every chunk but 0 takes, and chunk 0 as dFs0:{p} / +# dBs0:{p} (it also embeds). attn was timed on chunk 2 alone (22.76 -> 24.62 +# ms forward, 53.47 -> 47.27 backward), so chunk 0's is an ESTIMATE: chunk +# 2's deltas scaled as attn_min's are between the two chunks (x 1.75 / 1.97 +# forward, x 4.14 / 5.56 backward). `all` saves less than `lite_y`: +# measured, not a typo. Absolute Fs / Bs keys a table names win. +# {policy: ((forward ms, backward ms) chunk 2, ... chunk 0)}: +V6E_TILES_STASH_DELTAS = { + "attn": ((1.86, -6.20), (1.65, -4.62)), + "attn_min": ((1.97, -5.56), (1.75, -4.14)), + "lite": ((2.73, -9.58), (2.18, -9.16)), + "lite_y": ((4.90, -12.15), (4.05, -11.00)), + "all": ((4.56, -10.01), (4.20, -4.74)), +} +V6E_TILES_COSTS.update( + { + f"d{kind}s{c}:{p}": d + for p, per in V6E_TILES_STASH_DELTAS.items() + for c, deltas in zip(("", "0"), per) + if deltas + for kind, d in zip("FB", deltas) + } +) + + +# ------------------------------------------------------- zero-bubble schedules +# Zero Bubble Pipeline Parallelism (Qi et al., ICLR 2024) splits a chunk's backward into I, the input gradient (with +# the recompute under remat), and W, the weight gradient, and moves the W's into the bubbles: nothing waits on a W +# but its own chunk's next gradient write. ZB-H1 keeps 1F1B's residual sets (stage s holds at most S - s), ZB-H2 +# about twice them (2 (S - s) - 1), whose deeper warm-up fills the start of the pipe. The generators below are +# V = 1 schedules (one chunk a stage, place[c] = c) under the driver's rules: chunk 0 has no input gradient to send, +# so it runs a whole B (all W to the schedule, which may move it like one), and the last chunk is one fused forward +# + backward program, its F carrying its B. The middle chunks split -- and with `split_last` the last one too, its F +# the forward, head, loss and input gradient (AI), a W of its own its layers' weight gradients -- so at S = 2 without +# it there is nothing to split and ZB-H1 is 1F1B. On top of the residual sets a stage holds its pending W buffers +# (I done, W not), each what W reads from I -- at DeepSeek-V3 sizes GiBs a layer, tens of residual sets -- so that, +# more than the residual sets, is the memory that binds: `zb_schedule`'s `wbuf_cap`. Every chunk's I's and W's run +# in microbatch order (FIFO), so its gradient sum is any other schedule's, bit for bit. + +# W's share of a split chunk's backward, for a cost table without I / W keys (`zb_costs`): the weight-gradient +# matmuls are 0.29-0.33 of a remat backward's XLA flops on DeepSeek-V3 chunks (I re-runs the forward and computes +# dx). Measured times differ -- I's attention core and collectives have no W counterpart -- so give I / W keys where +# they were measured. +ZB_W_SHARE = 0.3 +# A split last chunk's W share of its fused program A (`zb_costs` with `last`): its layers' weight-gradient matmuls, +# about what a middle chunk's W is -- 0.3 of its B, on TPU7X_COSTS 14.6 of B's 48.6 ms, a quarter of A's 58.3 -- as the +# head, the decoder norm and the loss stay in its F (AI). 0.19-0.32 of A's XLA flops at TINY widths on CPU (bf16 with +# and without remat_fused_last, fp32 on XLA's ops). +ZB_W_SHARE_LAST = 0.25 + + +def zb_costs(table, n_chunks, w_share=None, *, last=False, w_share_last=None): + """`table` (`cost_table` keys) with an I and a W cost for every chunk that can split -- the middle ones, 1 .. C-2 + -- where it has none, so that I + W = B: W = w_share x B (default ZB_W_SHARE) and I = B - W, from B{c}, else B; a + measured I alone gives W = B - I, a measured W alone I = B - W. `last`: the fused last chunk split too + (`splits_last`): its W, WA = w_share_last x A (default ZB_W_SHARE_LAST), where the table has neither W{C-1} nor WA + -- or A - AI, a measured AI (its F, `cost_table`) alone. The F, B and A costs, and so every order priced without I + / W, stay as they are. Refuses (ValueError) a negative I, W or AI, and a measured I or W alone above its chunk's B + -- or the last chunk's W or AI alone above A: the other would come out negative (give both, as measured).""" + share = ZB_W_SHARE if w_share is None else float(w_share) + share_last = ZB_W_SHARE_LAST if w_share_last is None else float(w_share_last) + for name, x in (("w_share", share), ("w_share_last", share_last)): + if not 0.0 <= x <= 1.0: + raise ValueError(f"{name} must be within [0, 1], got {x}") + out = dict(table) + remat = cost_table(table, n_chunks) # also checks that the table prices every chunk's F and B + + def get(kind, c): + return float(out[f"{kind}{c}"] if f"{kind}{c}" in out else out[kind]) + + def has(kind, c): + return f"{kind}{c}" in out or kind in out + + bad = [] + for c in range(1, n_chunks - 1): + b = remat(c, "B") + bad += [f"{kind}{c} = {get(kind, c)} < 0" for kind in "IW" if has(kind, c) and get(kind, c) < 0] + bad += [ + f"{kind}{c} = {get(kind, c)} > B{c} = {b}, which leaves {other}{c} = B - {kind} negative" + for kind, other in (("I", "W"), ("W", "I")) + if has(kind, c) and not has(other, c) and get(kind, c) > b + ] + L = n_chunks - 1 + w_key = next((k for k in (f"W{L}", "WA") if k in out), None) # the split last chunk's W, if measured + if last: + a = remat(L, "F") + given = {name: float(out[key]) for name, key in (("W", w_key), ("AI", "AI")) if key in out} + bad += [f"the last chunk's {name} = {x} < 0" for name, x in given.items() if x < 0] + if len(given) == 1 and max(given.values()) > a: + ((name, x),) = given.items() + other = "AI" if name == "W" else "W" + bad.append(f"the last chunk's {name} = {x} > A = {a}, which leaves its {other} = A - {name} negative") + if bad: + raise ValueError(f"zb_costs: {'; '.join(bad)} (give a chunk's I and W both, as measured, or neither)") + for c in range(1, n_chunks - 1): + b = remat(c, "B") + has_c = {kind: has(kind, c) for kind in "IW"} + if not has_c["W"]: + out[f"W{c}"] = round(b - get("I", c) if has_c["I"] else share * b, 4) + if not has_c["I"]: + out[f"I{c}"] = round(b - get("W", c), 4) + if last and w_key is None: + a = remat(L, "F") + out["WA"] = round(a - float(out["AI"]) if "AI" in out else share_last * a, 4) + return out + + +def _zb_check(n_stages, n_micro): + if n_stages < 2 or n_micro < 1: + raise ValueError(f"a zero-bubble schedule needs >= 2 stages and >= 1 microbatch, got {n_stages} and {n_micro}") + + +def _zb_op(c, k, m, C, split_last=False): + """One action of a zero-bubble stream, mapped onto the chunks that do not split: chunk 0's I is its whole B (and + its W none), the fused last chunk's I and W are part of its F (none) -- its I only, where it splits too + (`split_last`: a W of its own).""" + if c == C - 1: + return [(c, k, m)] if k == "F" or (k == "W" and split_last) else [] + if c == 0: + return [] if k == "W" else [(c, "B" if k == "I" else k, m)] + return [(c, k, m)] + + +def zb_h1(n_stages, n_micro, w_lag=None, *, split_last=False): + """ZB-H1 as per-stage streams (place[c] = c), for `merge`: 1F1B's warm-up of S - 1 - r forwards on stage r and its + steady state, each backward an I, and stage r's W's `w_lag[r]` microbatches behind its I's (default r) -- the + stages near the front run each W soon after its I, those further down keep their I's back to back to feed the + stages upstream and run the W's they owe in the drain, while the stages upstream are still busy. Stage r holds at + most S - r residual sets (F to I), as 1F1B does, and min(w_lag[r] + 1, M) pending W buffers (`peak_wbufs`) -- + `split_last`: the last stage too, its F's running the input gradient (`splits_last`) and its W's lagging them. + Cost-agnostic; in the paper's setting (T_F = T_I = T_W, every chunk split) its bubble is a third of 1F1B's.""" + _zb_check(n_stages, n_micro) + S, M = n_stages, n_micro + lag = list(range(S)) if w_lag is None else _per(w_lag, S, "w_lag") + op = functools.partial(_zb_op, C=S, split_last=split_last) + streams = [] + for r in range(S): + warm = min(S - 1 - r, M) + st, w_next = [], 0 + for m in range(warm): + st += op(r, "F", m) + for k in range(M): + if warm + k < M: + st += op(r, "F", warm + k) + st += op(r, "I", k) + if k >= lag[r]: + st += op(r, "W", w_next) + w_next += 1 + while w_next < M: + st += op(r, "W", w_next) + w_next += 1 + streams.append(st) + return streams + + +def zb_h2(n_stages, n_micro, w_lag=None, *, split_last=False): + """ZB-H2 as per-stage streams (place[c] = c), for `merge`: stage r warms up with 2 (S - r) - 1 forwards -- enough to + fill the bubble before its first I arrives at unit costs -- then runs I, F, W, its W's `w_lag[r]` microbatches + behind its I's (default 2 r), and the deferred W's at the tail, where they fill the drain: 1F1B's trapezoid + becomes a parallelogram. Stage r holds at most 2 (S - r) - 1 residual sets and min(w_lag[r] + 1, M) pending W + buffers -- `split_last`: the last stage min(w_lag + 2, M), its warm-up forward's W buffer besides (each F runs its + I). Cost-agnostic; in the paper's setting (T_F = T_I = T_W, every chunk split) its bubble is the warm-up ramp + alone, (S - 1) T_F.""" + _zb_check(n_stages, n_micro) + S, M = n_stages, n_micro + lag = [2 * r for r in range(S)] if w_lag is None else _per(w_lag, S, "w_lag") + op = functools.partial(_zb_op, C=S, split_last=split_last) + streams = [] + for r in range(S): + warm = min(2 * (S - r) - 1, M) + st, f_next, w_next = [], 0, 0 + for _ in range(warm): + st += op(r, "F", f_next) + f_next += 1 + for k in range(M): + st += op(r, "I", k) + if f_next < M: + st += op(r, "F", f_next) + f_next += 1 + if k >= lag[r]: + st += op(r, "W", w_next) + w_next += 1 + while w_next < M: + st += op(r, "W", w_next) + w_next += 1 + streams.append(st) + return streams + + +def zb_caps(n_stages, mem): + """Per-stage memory limits in microbatches of ZB-H1 (mem 'h1': 1F1B's, S - s) and ZB-H2 ('h2': 2 (S - s) - 1). + `zb_search` caps by them either the residual sets (F to I or B) or the microbatches in flight (F to W or B, + `peak_inflight`), which bounds the residual sets too.""" + S = n_stages + if mem == "h1": + return [S - s for s in range(S)] + if mem == "h2": + return [2 * (S - s) - 1 for s in range(S)] + raise ValueError(f"mem must be 'h1' or 'h2', got {mem!r}") + + +def zb_greedy( + n_chunks, + n_micro, + place, + cost, + xfer=0.0, + *, + split=None, + inflight_cap=None, + res_cap=None, + wbuf_cap=None, + prio=("BI", "F", "W"), + f_key=None, + b_key=None, + w_slack=0.0, + slack_kinds=("I", "B"), + w_first=False, + fuse_last=True, + split_last=False, +): + """Event-driven list scheduler with a split backward -> (per-stage streams for `merge`, makespan). + + `timed_greedy`'s engine: whenever a stage goes idle it starts the best op READY at that instant (its dependencies + done, plus `xfer` for a cross-stage hop), else waits for the earliest. `split`: the chunks whose backward runs as + I then W (default the middle ones; a fused last chunk never splits). Per-stage caps, each a number or one per + stage (None: no cap): `inflight_cap`, microbatches between their F and their W or B (`peak_inflight` -- a residual + set, then a pending W buffer: the paper's memory count); `res_cap`, residual sets (F to I or B); `wbuf_cap`, + pending W buffers (an I waits for a W). `prio` ranks the kinds ready at the same instant ('BI': an I or an unsplit + B, which unblocks the stage upstream); `f_key` / `b_key` rank a stage's chunks within a kind. `w_first`: when no + forward is ready but the stage has forwards left (its caps or its inputs hold them back), a ready W goes first -- + it frees the in-flight slot a forward may wait on. `w_slack`: rather than start a W, the stage takes an op of + `slack_kinds` that becomes ready within w_slack x cost(W) -- it would wait behind the W. + + Each chunk's F's, I's (or B's) and W's run in microbatch order, a W after its I; the fused last chunk's F costs its + F + B (its no-op B is `merge`'s to re-insert) -- `split_last`, the fused last chunk split too: its F costs its F + + I, leaves a W buffer (under `wbuf_cap`, not the in-flight or residual caps: it holds no residual set) and its W's + run later, each after its F. `cost` is as for `timed_simulate`. Deterministic. Raises RuntimeError if the caps + deadlock (a split chunk needs `wbuf_cap` >= 1).""" + C, M = n_chunks, n_micro + S = max(place) + 1 + cost = _cost_fn(cost, C) + L = C - 1 if fuse_last else -1 # the fused last chunk, if any + split = set(range(1, C - 1)) if split is None else set(split) - {L} + last_w = split_last and L >= 0 # the fused last chunk's W's + inf_cap, r_cap, w_cap = ( + None if x is None else _per(x, S, what) + for x, what in ((inflight_cap, "inflight_cap"), (res_cap, "res_cap"), (wbuf_cap, "wbuf_cap")) + ) + own = [[c for c in range(C) if place[c] == d] for d in range(S)] + f_key = f_key or (lambda c, m: (m, c)) + b_key = b_key or (lambda c, m: (m, -c)) + rank_of = {k: i for i, k in enumerate(prio)} + done = {} + nf, nb, nw = [0] * C, [0] * C, [0] * C + free = [0.0] * S + inflight, wbuf, res = [0] * S, [0] * S, [0] * S + streams = [[] for _ in range(S)] + + def hop(a, b): + return xfer if place[a] != place[b] else 0.0 + + def ready_f(c, m): + if c == 0: + return 0.0 + t = done.get((c - 1, "F", m)) + return None if t is None else t + hop(c - 1, c) + + def ready_b(c, m): + tf = done.get((c, "F", m)) + if tf is None or c == C - 1: + return tf + tb = done.get((c + 1, "BI", m)) + return None if tb is None else max(tf, tb + hop(c + 1, c)) + + def rank(x): + _, k, c, m = x + return (rank_of["BI" if k in ("B", "I") else k], f_key(c, m) if k == "F" else b_key(c, m)) + + def candidates(d): + """(start, kind, chunk, microbatch) of every op stage d may start next, under its caps.""" + cands = [] + cap_ok = (inf_cap is None or inflight[d] < inf_cap[d]) and (r_cap is None or res[d] < r_cap[d]) + w_ok = w_cap is None or wbuf[d] < w_cap[d] + for c in own[d]: + ok = (w_ok or not last_w) if c == L else cap_ok + r = ready_f(c, nf[c]) if nf[c] < M and ok else None + if r is not None: + cands.append((max(r, free[d]), "F", c, nf[c])) + k = "I" if c in split else "B" + if c != L and nb[c] < M and (k == "B" or w_ok): + r = ready_b(c, nb[c]) + if r is not None: + cands.append((max(r, free[d]), k, c, nb[c])) + if c in split and nw[c] < nb[c]: + cands.append((max(done[(c, "I", nw[c])], free[d]), "W", c, nw[c])) + if c == L and last_w and nw[c] < nf[c]: + cands.append((max(done[(c, "F", nw[c])], free[d]), "W", c, nw[c])) + return cands + + total = sum((2 * M if last_w else M) if c == L else (3 * M if c in split else 2 * M) for c in range(C)) + for _ in range(total): + best, best_t = None, float("inf") + for d in range(S): + cands = candidates(d) + if not cands: + continue + t0 = min(x[0] for x in cands) + now = [x for x in cands if x[0] <= t0 + 1e-9] + pick = min(now, key=rank) + if w_first and pick[1] != "W" and all(x[1] != "F" for x in now) and any(nf[c] < M for c in own[d]): + pick = min([x for x in now if x[1] == "W"] or [pick], key=rank) + if pick[1] == "W" and w_slack > 0: + soon = [x for x in cands if x[1] in slack_kinds and x[0] < t0 + w_slack * cost(pick[2], "W") - 1e-9] + if soon: + pick = min(soon, key=lambda x: x[0]) + if pick[0] < best_t - 1e-9: + best, best_t = (*pick, d), pick[0] + if best is None: + raise RuntimeError(f"zb_greedy deadlock: nf={nf} nb={nb} nw={nw} inflight={inflight} wbuf={wbuf}") + t, k, c, m, d = best + t1 = t + (cost(c, "F") + cost(c, "I" if last_w else "B") if (c == L and k == "F") else cost(c, k)) + free[d] = t1 + done[(c, k, m)] = t1 + streams[d].append((c, k, m)) + if k == "F": + nf[c] += 1 + if c == L: # its backward ran too (split: its input gradient, its W buffer left for its W) + done[(c, "B", m)] = done[(c, "BI", m)] = t1 + wbuf[d] += last_w + else: + inflight[d] += 1 + res[d] += 1 + elif k == "W": + nw[c] += 1 + wbuf[d] -= 1 + inflight[d] -= c != L + else: + nb[c] += 1 + res[d] -= 1 + done[(c, "BI", m)] = t1 + if k == "I": + wbuf[d] += 1 + else: + inflight[d] -= 1 + return streams, max(free) + + +# `zb_search`'s rules: which op a stage takes when several are ready (the kinds' rank, `w_first`) and when a W may +# start (`w_slack`). The first is the plain greedy. +ZB_POLICIES = ( + ("greedy", {}), + ("w_slack 0.5", {"w_slack": 0.5}), + ("w_slack 1", {"w_slack": 1.0}), + ("w_slack 1 +F", {"w_slack": 1.0, "slack_kinds": ("I", "B", "F")}), + ("w_slack 0.5 +F", {"w_slack": 0.5, "slack_kinds": ("I", "B", "F")}), + ("W before F", {"prio": ("BI", "W", "F")}), + ("F first", {"prio": ("F", "BI", "W")}), + ("w_first", {"w_first": True}), + ("F first, w_first", {"prio": ("F", "BI", "W"), "w_first": True}), + ("W before F, w_first", {"prio": ("BI", "W", "F"), "w_first": True}), +) +# ... each run under both memory forms: 'inflight' caps the microbatches in flight a stage (F to W or B: a pending W +# buffer counts, the paper's notion) by `zb_caps`; 'res' caps the residual sets by `zb_caps` and the microbatches in +# flight by S (ZB-H1) or 2 S - 1 (ZB-H2) on every stage. +ZB_MEMORY_FORMS = ("inflight", "res") + + +def _zb_mem_caps(n_stages, mem, form): + S = n_stages + if form == "inflight": + return {"inflight_cap": zb_caps(S, mem)} + if form == "res": + return {"res_cap": zb_caps(S, mem), "inflight_cap": S if mem == "h1" else 2 * S - 1} + raise ValueError(f"memory form must be one of {ZB_MEMORY_FORMS}, got {form!r}") + + +def _zb_fastest(cands): + """(makespan, W buffers, item) in tie order -> (item, makespan) of the fastest; makespans within a relative 1e-9 + tie, and a tie goes to fewer W buffers, then to the earlier. (None, inf) if there are none.""" + best, best_mk, best_wb = None, float("inf"), float("inf") + for mk, wb, item in cands: + tol = 1e-9 * max(1.0, abs(mk)) + if mk < best_mk - tol or (abs(mk - best_mk) <= tol and wb < best_wb): + best, best_mk, best_wb = item, mk, wb + return best, best_mk + + +def zb_search( + n_stages, + n_micro, + cost, + xfer=0.0, + *, + mem="h1", + wbuf_cap=None, + policies=ZB_POLICIES, + forms=ZB_MEMORY_FORMS, + split_last=False, +): + """The fastest `zb_greedy` on S stages of one chunk each (place[c] = c), the middle chunks split (`split_last`: the + fused last chunk too), over `policies` each under every memory form of `forms` at ZB-H1's (mem 'h1') or ZB-H2's + ('h2') `zb_caps`, with at most `wbuf_cap` pending W buffers a stage (None: no cap) -> (streams, (mem, form, + policy), makespan). Ties go to fewer W buffers, then to the earlier form and policy.""" + _zb_check(n_stages, n_micro) + S, place = n_stages, list(range(n_stages)) + + def runs(): + for form in forms: + caps = _zb_mem_caps(S, mem, form) + for name, pol in policies: + try: + streams, mk = zb_greedy(S, n_micro, place, cost, xfer, wbuf_cap=wbuf_cap, split_last=split_last, **caps, **pol) + except RuntimeError: + continue # these caps deadlock under this policy + yield mk, max(peak_wbufs([a for st in streams for a in st], place)), (streams, (mem, form, name)) + + best, mk = _zb_fastest(runs()) + if best is None: + raise RuntimeError(f"zb_search: every policy deadlocks under mem={mem!r}, wbuf_cap={wbuf_cap!r}") + return best[0], best[1], mk + + +def zb_schedule(n_stages, n_micro, cost, xfer=0.0, *, mem="h1", wbuf_cap=1, split_last=False): + """ZB-H1 (mem 'h1') or ZB-H2 ('h2') on S stages of one chunk each (place[c] = c) for the driver -> (order, tag, + makespan). The fastest per `merge`, with `cost` (as for `timed_simulate`, I and W priced: `zb_costs`), of + + * 1F1B with each split B run as I and then W at once: 1F1B's order, timeline and memory, so the result is never + slower than 1F1B where I + W <= B -- and at S = 2, where no chunk splits, it is 1F1B's order itself; + * the handcrafted streams `zb_h1` (for ZB-H2 also `zb_h2`), their W lag cut to `wbuf_cap` - 1; + * `zb_search` under ZB-H1's memory (for ZB-H2 also under its own): every rule of ZB_POLICIES under each of the + ZB_MEMORY_FORMS. + + `split_last`: the fused last chunk splits too, in every candidate (`splits_last`: its F runs the forward, the head, + the loss and the input gradient, AI, and its W's its layers' weight gradients) -- in 1F1B's, each W right after its + F (and the no-op B): 1F1B's timeline with the input gradient upstream sooner, so never slower than 1F1B where AI + + W <= A (and, at three stages or more, each middle chunk's I + W <= B), and at S = 2 faster, the last chunk the one + that splits. + + Ties go to fewer pending W buffers, then to the earlier candidate above. ZB-H2 tries every ZB-H1 candidate, so it + is never the slower. Memory: stage s holds at most S - s residual sets (ZB-H1, 1F1B's) or 2 (S - s) - 1 (ZB-H2), + and at most `wbuf_cap` pending W buffers (None: no cap -- the streams then hold up to min(r + 1, M) (ZB-H1) or + min(2 r + 1, M) (ZB-H2) on stage r, the searches up to S or 2 S - 1; a candidate over the cap is dropped). A + looser cap is not always faster: list scheduling under different caps can land either side (by 0.15% in 2 of 216 + simulated cases). The order passes `validate`, FIFO included: every chunk's forwards and gradient writes run in + microbatch order, so its fp32 accumulation is any other schedule's. Deterministic.""" + _zb_check(n_stages, n_micro) + if mem not in ("h1", "h2"): + raise ValueError(f"mem must be 'h1' or 'h2', got {mem!r}") + if wbuf_cap is not None and (isinstance(wbuf_cap, bool) or int(wbuf_cap) != wbuf_cap or wbuf_cap < 1): + raise ValueError(f"wbuf_cap must be None (no cap) or an int >= 1 -- an I leaves a W buffer -- got {wbuf_cap!r}") + S, M = n_stages, n_micro + place = list(range(S)) + cost = _cost_fn(cost, S) + mems = ("h1", "h2") if mem == "h2" else ("h1",) + cands = [] # (order, tag), in the order ties go to + base = [] + for c, k, m in one_f_one_b(S, M, place): + if k == "B" and 0 < c < S - 1: + base += [(c, "I", m), (c, "W", m)] + else: + base += [(c, k, m)] + ([(c, "W", m)] if split_last and k == "B" and c == S - 1 else []) + cands.append((base, ("1f1b", "I+W"))) + for mm in mems: + lag = None + if wbuf_cap is not None: + # a lag of d holds min(d + 1, M) W buffers -- ZB-H2's split last stage min(d + 2, M), its warm-up forward's too + extra = [int(mm == "h2" and split_last and r == S - 1) for r in range(S)] + lag = [max(0, min(r if mm == "h1" else 2 * r, int(wbuf_cap) - 1 - extra[r])) for r in range(S)] + streams = (zb_h1 if mm == "h1" else zb_h2)(S, M, w_lag=lag, split_last=split_last) + cands.append((merge(streams, place, cost, xfer, n_micro=M)[0], (f"zb_{mm}", "streams"))) + for mm in mems: + streams, tag, _ = zb_search(S, M, cost, xfer, mem=mm, wbuf_cap=wbuf_cap, split_last=split_last) + cands.append((merge(streams, place, cost, xfer, n_micro=M)[0], ("search",) + tag)) + (order, tag), mk = _zb_fastest( + (timed_simulate(o, place, cost, xfer, fuse_last=True)[0], wb, (o, tag)) + for o, tag in cands + for wb in (max(peak_wbufs(o, place)),) + if wbuf_cap is None or wb <= wbuf_cap + ) + validate(order, place, M) + return order, tag, mk diff --git a/src/maxtext/experimental/mpmd/jax/sharding_mode.py b/src/maxtext/experimental/mpmd/jax/sharding_mode.py new file mode 100644 index 0000000000..278adf806b --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/sharding_mode.py @@ -0,0 +1,436 @@ +# 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 sharding mode the code being traced runs in, and the helpers that +model code shards through. + +One stage function is traced in four situations, and this module is how it +tells them apart: + + none No mesh in context: a single-device reference (`ds_ep_parity`'s + run of the DeepSeek port in `deepseek/`), or `eval_shape` over + plain avals. Every helper is the identity, because there is + nothing to shard. + manual Inside a `shard_map` over every axis (`ds_ep`'s per-stage + programs, or `manual()` below), where values are per-device + blocks. Every helper is the identity again: a second `shard_map` + over the same axes fails in every jax version we run. + auto A sub-mesh whose axes are `AxisType.Auto`, in which XLA + propagates the shardings. A helper emits exactly the expression + the model wrote before this module existed: today's program. + explicit A sub-mesh whose axes are `AxisType.Explicit`. Every value + carries its sharding in its type, and an op whose result type + would be ambiguous will not trace without an `out_sharding=` or a + `reshard`. + +The mode is read off the abstract mesh in context. No production path +enters auto or explicit: `ds_ep` runs the models per device, inside its own +shard_maps (manual), and `ds_ep_parity`'s port reference runs them with no +mesh (none). The auto and explicit branches of the helpers below, +`trace_context` (which sets the context), `manual()`'s shard_map and +`replicate()` are exercised only by the model tests (`sharding_mode_test`, +`deepseek_model_test`, `qwen35_explicit_test`), which trace the ports at +global view in both modes, so that the ports keep tracing there. Such a +caller enters `trace_context` inside every program it traces under explicit; +under auto every helper is the model's own expression with or without a +mesh, and the context is not free there (see `trace_context`), so it is +entered only for `manual`'s per-device regions. Reading the context rather +than an argument is what lets one stage function serve every case: under an +`eval_shape` of plain avals there is no context, so the helpers step aside. +The mode is never passed around as a Python flag, so there is no flag that +can disagree with the types. + +The helpers come in three groups, and the grouping is the point: + + (1) Type obligations, explicit only: `out_sharding`, `retype`, `zeros`, + and the forms a `custom_vjp` rule uses, `bwd_out_sharding`, + `sharding_of` and `retype_like` (types read off an aval). + They are what explicit needs in order to trace at all, and they emit + NOTHING under auto, so that auto stays the same program, byte for + byte. + (2) Strategy forcing, both modes: `replicate`, the ONLY place auto gets a + `with_sharding_constraint`; it forces the same layout in both modes, + so that a comparison of the two is one of typing. The models call it + nowhere (`ShardPolicy` holds the default policy alone). + (3) Ops that need an `out_sharding=` under explicit: `dot_general`, + `einsum`, `take`, `set_at`, `bincount`, plus the `manual` region. The + auto/none branch of each but `manual` (a shard_map under auto, on + purpose) is the literal expression the model used before, and + `sharding_mode_test.py` asserts that its jaxpr is the same. + +Two rules for the code that uses them. First, model code never calls +`reshard`, `with_sharding_constraint` or `out_sharding=` itself, so that every +departure from today's program is in this file. Second, a `custom_vjp` rule +types what it returns only from the primals' own avals: an op inside it gets +`out_sharding=bwd_out_sharding(primal)` (or `sharding_of(x)` for a result +typed exactly like `x`), and a value that comes out typed otherwise goes +through `retype_like(value, primal)`. A cotangent must be +typed exactly as its primal's cotangent type (jax refuses a bwd rule that +returns anything else), and a bwd rule is traced lazily, during +transposition. The abstract mesh is still captured there, but a Python +context variable set in the forward is not, so the primal's own type is the +one reliable witness. + +Version notes, for jax 0.10.2 / 0.11.x / 0.12: this file never constructs an +`AbstractMesh(...)`, never calls `make_mesh` with keywords and never uses +`are_all_axes_*`; all three changed in 0.12. Shardings are always +`NamedSharding(get_abstract_mesh(), spec)`, never a bare `PartitionSpec`: +a bare spec needs a concrete mesh set with `jax.set_mesh`, which is illegal +inside `jit` and would anyway be one mesh for a pipeline that has one per +stage. +""" + +from __future__ import annotations + +import contextlib +import dataclasses +from typing import Literal + +import jax +import jax.numpy as jnp +from jax.sharding import AxisType, NamedSharding, PartitionSpec as P + +Mode = Literal["none", "manual", "auto", "explicit"] + + +# --------------------------------------------------------------------- policy +@dataclasses.dataclass(frozen=True) +class ShardPolicy: + """How a model shards: the default policy, today's program, and no other. + + A config carries one (`config.shard`) and the helpers below never read it: + what a helper emits is the mode's (see the module docstring). The + strategies a policy once forced in both modes -- gathered or + tensor-parallel weights, other MoE dispatches, attention per device, a + recomputed embedding lookup, fixed routing -- served whole-model pipelines + that traced at global view, and went with them; ds_ep runs the models per + device, inside its own shard_maps, where a policy has no say. Frozen, so a + config that holds one stays hashable. + """ + + +# ------------------------------------------------------------------- the mode +def _mode_of(mesh, what) -> Mode: + """Classify an abstract mesh: empty, all Manual, all Explicit or all Auto.""" + if mesh.empty: + return "none" + types = set(mesh.axis_types) + if types == {AxisType.Manual}: + return "manual" + if types == {AxisType.Explicit}: + return "explicit" + if types == {AxisType.Auto}: + return "auto" + # A mesh that mixes Explicit and Auto axes, or one only partly inside a + # shard_map. No sub-mesh in this repo is either, and guessing which axes + # the batch rides on would be a silent remap, so it is an error instead. + axes = ", ".join(f"{n}: {t}" for n, t in zip(mesh.axis_names, mesh.axis_types)) + raise ValueError( + f"{what} mixes axis types ({axes}). The sharding helpers " + "need every axis Auto, every axis Explicit or every axis " + "Manual." + ) + + +def context_mode() -> Mode: + """The mode of the abstract mesh in context (see the module docstring).""" + return _mode_of(jax.sharding.get_abstract_mesh(), "the context mesh") + + +def aval_mode(x) -> Mode: + """The same classification, read off the mesh in `x`'s type. + + A committed array, a tracer, a `ShapeDtypeStruct` or an aval (a jaxpr + variable's) all work. For a value with no mesh in its type (a numpy array, + a Python scalar, an untyped `ShapeDtypeStruct`) the answer is 'none'. + """ + try: + t = jax.typeof(x) + except TypeError: # already an aval, e.g. `ShapedArray` + t = x + mesh = getattr(getattr(t, "sharding", None), "mesh", None) + if mesh is None: + return "none" + return _mode_of(mesh, f"the type of {t}") + + +def trace_context(abstract_mesh): + """Trace with `abstract_mesh` in context. `None` means no context. + + The models' one way to `jax.sharding.use_abstract_mesh` (their call-site + tests refuse one of their own; `ds_ep_lineage`, which runs MaxText's + Lineage code, enters it itself), and only the model tests enter it (see the + module docstring). Enter it INSIDE the function being traced, never around + the call. `jax.set_mesh` is illegal inside `jit`, and a context around the + call becomes part of the jit cache key, which costs one extra trace per + executable. A concrete `Mesh` is accepted too and stands for its + `abstract_mesh`. + + Under an Auto mesh it is not free, which is why a caller should enter it + under auto only for `manual`'s per-device regions (Qwen's + `gdn_core='manual'`). Every aval traced under it carries the mesh, and + Pallas's TPU lowering compares a kernel's avals with mesh-less ones it + builds itself (`load_aval != aval_out` in its load rule), so a kernel + traced under it gets an identity `vector.shape_cast` per load: jax's splash + kernel lowers to a different Mosaic body, with bitwise the same results, in + every program that calls it. + """ + if abstract_mesh is None: + return contextlib.nullcontext() + return jax.sharding.use_abstract_mesh(getattr(abstract_mesh, "abstract_mesh", abstract_mesh)) + + +def batch_axes() -> tuple[str, ...]: + """The context mesh's non-Manual axes, i.e. the axes the batch rides on. + + Every axis of an MPMD sub-mesh shards the batch (`ds_ep` splits a stage's + microbatch over all of them), so these are simply the axes `manual()` would + map over. + """ + m = jax.sharding.get_abstract_mesh() + return tuple(n for n, t in zip(m.axis_names, m.axis_types) if t != AxisType.Manual) + + +def act_spec(ndim: int, batch_dim: int = 0) -> P: + """The PartitionSpec of a batch-major activation of rank `ndim`. + + The batch dim is sharded over `batch_axes()` and nothing else is. With no + batch axes (no mesh, or inside `manual`) the spec is all None. + """ + axes = batch_axes() + spec = [None] * ndim + if axes and ndim: + spec[batch_dim] = axes[0] if len(axes) == 1 else axes + return P(*spec) + + +def named(spec) -> NamedSharding: + """`NamedSharding(get_abstract_mesh(), spec)`, the only sharding the helpers + ever build. + + It needs no concrete mesh in context, only the abstract one that + `trace_context` sets. With no mesh at all it raises: the helpers only call + it under auto or explicit, where there always is one, so a call without a + mesh is a mistake to surface, not to paper over. + """ + m = jax.sharding.get_abstract_mesh() + if m.empty: + raise ValueError(f"named({spec}) needs a mesh in context: call it while " "tracing under mode.trace_context(...).") + return NamedSharding(m, spec) + + +def _type(x): + try: + return jax.typeof(x) + except TypeError: # already an aval, e.g. `ShapedArray` + return x + + +def _partitions(spec): + """A spec's partitions. `tuple(spec)` raises once it has a reduced or + unreduced set, so never iterate a spec that may carry one.""" + return tuple(spec.partitions) + + +# ---------------------------------------------------- (1) type obligations +def out_sharding(spec) -> NamedSharding | None: + """The value for an op's `out_sharding=`: `named(spec)` under explicit, else + None, which is the op's default.""" + return named(spec) if context_mode() == "explicit" else None + + +def retype(x, spec): + """`reshard` `x` to `spec` under explicit, the identity in any other mode.""" + if context_mode() == "explicit": + return jax.sharding.reshard(x, named(spec)) + return x + + +def zeros(shape, dtype, spec): + """`jnp.zeros`, typed `spec` under explicit, e.g. for a scan carry. + + A scan's carry must have the same type on the way in as on the way out, and + a `zeros` without an `out_sharding` is typed replicated. + """ + if context_mode() == "explicit": + return jnp.zeros(shape, dtype, out_sharding=named(spec)) + return jnp.zeros(shape, dtype) + + +def retype_like(x, like): + """`x` typed as the cotangent of `like` when `like`'s type is Explicit, + else `x`. For every value but a reduced or unreduced one that is `like`'s + own type (`bwd_out_sharding`). + + The form of `retype` a `custom_vjp` rule uses: the type comes from an aval + (`bwd_out_sharding`), never from the context, which a lazily traced bwd + rule does not reliably see. A cotangent can come out of perfectly typed + arithmetic typed otherwise than its primal -- the cross entropy's follows + the targets when only they are batch-sharded -- and jax refuses a bwd rule + that returns it. `x` and `like` have the same shape. Nothing is emitted + when the two types already agree, so the common case costs no op at all. + """ + sh = bwd_out_sharding(like) + if sh is None or jax.typeof(x).sharding == sh: + return x + return jax.sharding.reshard(x, sh) + + +# --------------------------------------------------- (2) strategy forcing +def replicate(x): + """Make `x` replicated over the stage, in both modes. + + A `reshard` under explicit and a `with_sharding_constraint` under auto. A + `reshard` on Auto axes would lower to nothing, so the dispatch matters: the + wrong one is a silent no-op. The identity under none and manual. + """ + mode = context_mode() + if mode == "explicit": + return jax.sharding.reshard(x, named(P())) + if mode == "auto": + return jax.lax.with_sharding_constraint(x, named(P())) + return x + + +# ------------------------------------------- (3) ops that need out_sharding +def dot_general(lhs, rhs, dims, *, out_spec, precision, preferred_element_type=None): + """`jax.lax.dot_general`, with `out_sharding=named(out_spec)` under explicit. + + `out_spec=None` leaves the result type to the op's sharding rule in every + mode. + """ + if out_spec is not None and context_mode() == "explicit": + return jax.lax.dot_general( + lhs, rhs, dims, precision=precision, preferred_element_type=preferred_element_type, out_sharding=named(out_spec) + ) + return jax.lax.dot_general(lhs, rhs, dims, precision=precision, preferred_element_type=preferred_element_type) + + +def einsum(eq, *operands, out_spec, precision=None, preferred_element_type=None): + """`jnp.einsum`, with `out_sharding=named(out_spec)` under explicit.""" + if out_spec is not None and context_mode() == "explicit": + return jnp.einsum( + eq, *operands, precision=precision, preferred_element_type=preferred_element_type, out_sharding=named(out_spec) + ) + return jnp.einsum(eq, *operands, precision=precision, preferred_element_type=preferred_element_type) + + +def take(table, ids, *, out_spec): + """`table[ids]`: rows of `table` at integer `ids`, e.g. an embedding lookup. + + Under explicit, a gather with batch-sharded indices has no unambiguous + result type, so it becomes `.at[ids].get(out_sharding=)`, which jax + implements as an auto_axes island. Anywhere else it is `table[ids]`, + whose jaxpr is that of `.at[ids].get()`. It is never `jnp.take`, which + fills out-of-range rows with NaN rather than promising they are in bounds. + """ + if context_mode() == "explicit": + return table.at[ids].get(out_sharding=named(out_spec)) + return table[ids] + + +def set_at(x, ids, values, *, out_spec): + """`x.at[ids].set(values)`, typed `out_spec` under explicit. + + The scatter twin of `take`: writing `values` at batch-sharded `ids` into a + buffer has no unambiguous result type under explicit (the dense MoE's + routing-weight scatter), so it needs one. Anywhere else it is the plain + expression. + """ + if context_mode() == "explicit": + return x.at[ids].set(values, out_sharding=named(out_spec)) + return x.at[ids].set(values) + + +def bincount(x, *, length): + """`jnp.bincount`. Under explicit the counts are typed replicated: a + scatter-add of sharded indices into a replicated buffer needs one.""" + if context_mode() == "explicit": + return jnp.bincount(x, length=length, out_sharding=named(P())) + return jnp.bincount(x, length=length) + + +def manual(f, *, in_specs, out_specs, name): + """`f` in a `shard_map` over `batch_axes()`, under auto and explicit. + + Under none and manual this returns `f` unchanged: there is nothing to map, + or the axes are already Manual. Call it while tracing, since that is when + the mode is read. Under explicit the arguments are first `retype`d to + `in_specs`, because a `shard_map` refuses inputs typed otherwise. The + `shard_map` runs in `jax.named_scope(name)` and the retype does not, so a + profile can measure the time in the scope -- the same per-device program + in both modes -- apart from the retype, which is where the modes differ. + + Every operand needs a PartitionSpec; `P()` is a replicated one. A `None` + is refused in every mode: `shard_map` reads it as "close over the whole + array", which under auto hands the body the full array and under explicit + fails for any sharded operand, so the two modes would part ways. + """ + if any(s is None for s in jax.tree.leaves(in_specs, is_leaf=lambda s: s is None or isinstance(s, P))): + raise ValueError( + f"manual({name!r}): in_specs {in_specs} has a None. Give every " + "operand a PartitionSpec; P() is replicated (shard_map reads None as " + '"close over the whole array", which explicit refuses for a sharded ' + "operand and auto does not)." + ) + mode = context_mode() + if mode in ("none", "manual"): + return f + axes = frozenset(batch_axes()) + is_spec = lambda s: isinstance(s, P) + + def run(*args): + if mode == "explicit": + args = jax.tree.map(lambda spec, sub: jax.tree.map(lambda a: retype(a, spec), sub), in_specs, args, is_leaf=is_spec) + with jax.named_scope(name): + return jax.shard_map(f, mesh=None, in_specs=in_specs, out_specs=out_specs, axis_names=axes, check_vma=False)(*args) + + return run + + +def sharding_of(x): + """The sharding of `x`'s type when it is Explicit, else None: the + `out_sharding=` of an op whose result is typed exactly like `x`. + + For a `custom_vjp` forward whose output is typed like an input, and for a + bwd rule that types a cotangent like another cotangent. Both are the + value's own type, which for a reduced or unreduced value is not its + cotangent's (`bwd_out_sharding`). + """ + if aval_mode(x) == "explicit": + return _type(x).sharding + return None + + +def bwd_out_sharding(primal): + """The `out_sharding=` a `custom_vjp` bwd rule gives the cotangent of + `primal`: the cotangent type of `primal`'s type when it is Explicit, and + None otherwise. + + That is the primal's own type for every value but a reduced or unreduced + one, whose cotangent has the two swapped: a value typed reduced (one copy + promised equal on every device) gets an unreduced cotangent (each device's + partial sum), and jax refuses a bwd rule that returns one typed like the + primal. See the module docstring for why the type, and not the context, + decides. A value typed exactly like another one is `sharding_of`. + """ + if aval_mode(primal) != "explicit": + return None + sharding = _type(primal).sharding + spec = sharding.spec + reduced = frozenset(getattr(spec, "reduced", ()) or ()) + unreduced = frozenset(getattr(spec, "unreduced", ()) or ()) + if not (reduced or unreduced): + return sharding + return NamedSharding(sharding.mesh, P(*_partitions(spec), reduced=unreduced, unreduced=reduced)) diff --git a/src/maxtext/experimental/mpmd/jax/stage_ad.py b/src/maxtext/experimental/mpmd/jax/stage_ad.py new file mode 100644 index 0000000000..c5b533a763 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/stage_ad.py @@ -0,0 +1,422 @@ +# 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. + +"""Autodiff of a stage's programs: `closure_convert_all`, and the split of a backward into I and W. + +`closure_convert_all` is `jax.closure_convert` that hoists EVERY closed-over +tracer. `ds_ep.ChunkPrograms.build_stash` closure-converts each layer's vjp +with it, so that everything a stash backward reads is an explicit constant -- +int and bool ones too, which `jax.closure_convert` would bake into the callable +as escaped tracers -- and the forward can hand the backward its residuals as +arrays. + +The split engine cuts a chunk's backward for the zero-bubble schedules (Qi et +al., "Zero Bubble Pipeline Parallelism", ICLR 2024) into I, what the input +gradient needs -- the recompute of the forward included -- and W, what the +weight gradients need beyond that, which the schedule runs later. It cuts the +program the pipeline already runs, not the model: the chunk's fused backward +body is traced to one flat per-device jaxpr, and its equations are partitioned +by data dependence, each one whole. The halves compute the same operations on +the same operands as the fused body, so they reproduce its outputs bit for bit +wherever XLA computes each operation the same way in either program. + + inline_eval evaluates a jaxpr with the body of every nested jit and + closed_call -- and of every remat (jax.checkpoint) -- evaluated + in place, so that a trace of it holds none of those calls and + the cut sees inside them. An inlined remat's operands pass the + optimization barrier its lowering puts on them, so its + recompute still cannot merge with the forward's values. Every + other equation -- custom_vjp / custom_jvp calls, Pallas kernels, + scan / cond / while, collectives -- is bound again as it is, + atomic. + trace_body the flat per-device `Body` of jax.shard_map(fn) at abstract + arguments: its jaxpr, the spec of each input and output, and + where each input comes from -- a flat argument, or a constant of + the trace that shard_map hoisted into an input (`Const`). + split_jaxpr the cut of a body's jaxpr (`JaxprSplit`): I computes the + outputs it keeps, W every other output; the values W reads from + I cross between them, in the order W first reads them. + same_jaxpr whether two traces made one program (`same_values` for + constants). + +No jax._src: jax.extend's jaxprs, equations, primitives and source info, and +each equation's bind parameters and context, which jax.core.eval_jaxpr re-binds +an equation with too. +""" + +from __future__ import annotations + +import dataclasses +import math + +import jax +from jax import lax +from jax.extend import core as jcore +from jax.extend import source_info_util +from jax.sharding import PartitionSpec as P +import numpy as np + +eval_jaxpr = jax.core.eval_jaxpr + + +def closure_convert_all(fun, *example_args): + """Like `jax.closure_convert`, but hoists EVERY closed-over tracer. + + `jax.closure_convert` only hoists consts whose tangent space is nontrivial + (`_maybe_perturbed`). Any bool/int/PRNG-key residual -- i.e. every relu mask, + every argmax/top-k routing index, every dropout key -- is instead *baked into* + the returned callable as an escaped tracer, and blows up with + `UnexpectedTracerError` the moment you call it outside the originating trace. + """ + flat_args, in_tree = jax.tree.flatten(example_args) + store = {} + + def flat_fun(*flat): + out = fun(*jax.tree.unflatten(in_tree, list(flat))) + out_flat, out_tree = jax.tree.flatten(out) + store["out_tree"] = out_tree + return out_flat + + closed = jax.make_jaxpr(flat_fun)(*flat_args) + jaxpr, consts, out_tree = closed.jaxpr, list(closed.consts), store["out_tree"] + n_top = len(example_args) + + def converted(*args_and_consts): + args, cs = args_and_consts[:n_top], list(args_and_consts[n_top:]) + flat, tree = jax.tree.flatten(args) + if tree != in_tree: + raise TypeError(f"closure_convert_all: expected {in_tree}, got {tree}") + return jax.tree.unflatten(out_tree, eval_jaxpr(jaxpr, cs, *flat)) + + return converted, consts + + +# ------------------------------------------------------------ inline_eval +# The calls inline_eval evaluates in place: XLA inlines a jit's and a closed_call's computation anyway. A remat's +# lowering emits its body in place too, behind an optimization barrier on the operands it flags (prevent_cse) once +# differentiated -- jax's ad_checkpoint._remat_lowering -- and inline_eval puts the same barrier there (_barrier). +_CALLS = frozenset({jcore.primitives.jit_p, jcore.primitives.closed_call_p, jcore.primitives.call_p}) +_REMAT = jcore.primitives.remat_p + + +def _call_body(eqn): + """The jaxpr an inlined call equation evaluates, and its constants' values.""" + j = eqn.params["jaxpr"] if "jaxpr" in eqn.params else eqn.params["call_jaxpr"] + return getattr(j, "jaxpr", j), list(getattr(j, "consts", ())) + + +def _barrier(args, prevent_cse): + """`args`, those `prevent_cse` flags (one bool for all, or one per argument) passed through ONE optimization + barrier: what a differentiated remat's lowering does to its operands, so that XLA cannot merge the recompute + behind it with the forward's values (common-subexpression elimination) and keep those alive instead.""" + flags = [prevent_cse] * len(args) if isinstance(prevent_cse, bool) else list(prevent_cse) + idx = [k for k, f in enumerate(flags) if f] + out = list(args) + if idx: + for k, v in zip(idx, lax.optimization_barrier(tuple(args[k] for k in idx))): + out[k] = v + return out + + +def inline_eval(jaxpr, consts, *args, inline_remat=True): + """Evaluate `jaxpr` at `args` (`consts`: its constvars' values) under the current trace, as jax.core.eval_jaxpr + does, but with the body of every jit and closed_call -- and with `inline_remat`, of every remat -- evaluated in + place: a trace of it holds none of those calls. A differentiated remat's operands with prevent_cse pass one + optimization barrier first, as in its lowering. Every other equation is bound again with its own parameters + (`get_bind_params`), source info and context.""" + if len(consts) != len(jaxpr.constvars) or len(args) != len(jaxpr.invars): + raise TypeError( + f"inline_eval: {len(consts)} consts and {len(args)} args for a jaxpr of {len(jaxpr.constvars)} constvars " + f"and {len(jaxpr.invars)} invars" + ) + env = {} + + def read(v): + return v.val if isinstance(v, jcore.Literal) else env[v] + + for v, x in zip(jaxpr.constvars, consts): + env[v] = x + for v, x in zip(jaxpr.invars, args): + env[v] = x + for eqn in jaxpr.eqns: + ins = [read(v) for v in eqn.invars] + name_stack = source_info_util.current_name_stack() + eqn.source_info.name_stack + with source_info_util.user_context(eqn.source_info.traceback, name_stack=name_stack): + if eqn.primitive in _CALLS: + outs = inline_eval(*_call_body(eqn), *ins, inline_remat=inline_remat) + elif eqn.primitive is _REMAT and inline_remat: + if eqn.params["differentiated"]: + with eqn.ctx.manager: + ins = _barrier(ins, eqn.params["prevent_cse"]) + with source_info_util.extend_name_stack("checkpoint"): + outs = inline_eval(*_call_body(eqn), *ins, inline_remat=True) + else: + with eqn.ctx.manager: + outs = eqn.primitive.bind(*ins, **eqn.primitive.get_bind_params(eqn.params)) + if not eqn.primitive.multiple_results: + outs = [outs] + for v, x in zip(eqn.outvars, outs): + if not isinstance(v, jcore.DropVar): + env[v] = x + return [read(v) for v in jaxpr.outvars] + + +# ------------------------------------------------------------- trace_body +@dataclasses.dataclass(frozen=True, eq=False) +class Const: + """An input of a traced body that is a constant of the trace -- a splash attention mask table, rope frequencies, an + array a jitted helper closes over -- which shard_map hoisted into an input of its own (replicated).""" + + value: object + + +@dataclasses.dataclass(frozen=True, eq=False) +class Body: + """A flat per-device body (trace_body): `jaxpr`, the spec of each of its invars (`in_specs`) and outvars + (`out_specs`), and per invar where its value comes from (`src`): an int, the position among the traced function's + flat arguments, or a Const. Its outvars are the function's flat outputs, in order.""" + + jaxpr: object + in_specs: tuple + out_specs: tuple + src: tuple + + def operands(self, flat_args): + """The values of `jaxpr`'s invars, from the traced function's flat arguments (a Const: its value).""" + return [flat_args[s] if isinstance(s, int) else s.value for s in self.src] + + +def _spec_leaves(specs): + return jax.tree.leaves(specs, is_leaf=lambda x: x is None or isinstance(x, P)) + + +def _shard_map_body(fn, avals, mesh, in_specs, out_specs): + """The Body of jax.shard_map(fn) traced at `avals` (src: positions in `avals`, or Consts).""" + closed = jax.make_jaxpr( + jax.shard_map(fn, mesh=mesh, in_specs=tuple(in_specs), out_specs=tuple(out_specs), check_vma=False) + )(*avals) + outer = closed.jaxpr + if len(outer.eqns) != 1 or outer.eqns[0].primitive.name != "shard_map": + raise ValueError(f"trace_body: expected one shard_map, got {[e.primitive.name for e in outer.eqns]}") + (sm,) = outer.eqns + if list(sm.outvars) != list(outer.outvars): + raise ValueError("trace_body: the shard_map's outputs are not the trace's") + pos = {v: i for i, v in enumerate(outer.invars)} + const = dict(zip(outer.constvars, closed.consts)) + src = [] + for v in sm.invars: + if v in pos: + src.append(pos[v]) + elif v in const: + src.append(Const(const[v])) + else: + raise ValueError(f"trace_body: shard_map input {v} is neither an argument nor a constant of the trace") + return Body(sm.params["jaxpr"], tuple(sm.params["in_specs"]), tuple(sm.params["out_specs"]), tuple(src)) + + +def trace_body(fn, avals, mesh, in_specs, out_specs, *, inline_remat=True): + """The flat per-device Body of jax.shard_map(fn, mesh=mesh, in_specs=in_specs, out_specs=out_specs, + check_vma=False) at `avals`, a tuple of fn's arguments as pytrees of ShapeDtypeStructs (in_specs / out_specs: + pytrees of PartitionSpecs over its arguments and outputs, as for shard_map). Its src positions are those of + jax.tree.leaves(avals), and its outvars are jax.tree.leaves of fn's outputs. + + Two traces: shard_map(fn) itself, then its per-device jaxpr again through inline_eval (`inline_remat`: the remats + too) inside a shard_map of the same specs, every input of the first an argument of the second -- the constants + shard_map hoisted too. Constants of the second trace (arrays an inlined jit closed over) become Consts.""" + flat, in_tree = jax.tree.flatten(avals) + fin, fout = _spec_leaves(in_specs), _spec_leaves(out_specs) + if len(fin) != len(flat): + raise ValueError(f"trace_body: {len(fin)} in_specs for {len(flat)} arguments") + + def flat_fn(*xs): + outs = jax.tree.leaves(fn(*jax.tree.unflatten(in_tree, list(xs)))) + if len(outs) != len(fout): + raise ValueError(f"trace_body: {len(fout)} out_specs for {len(outs)} outputs") + return tuple(outs) + + first = _shard_map_body(flat_fn, flat, mesh, fin, fout) + j1, c1 = getattr(first.jaxpr, "jaxpr", first.jaxpr), list(getattr(first.jaxpr, "consts", ())) + avals2 = [flat[s] if isinstance(s, int) else jax.ShapeDtypeStruct(s.value.shape, s.value.dtype) for s in first.src] + + def inlined(*xs): + return tuple(inline_eval(j1, c1, *xs, inline_remat=inline_remat)) + + second = _shard_map_body(inlined, avals2, mesh, first.in_specs, first.out_specs) + src = tuple(first.src[s] if isinstance(s, int) else s for s in second.src) + return Body(second.jaxpr, second.in_specs, second.out_specs, src) + + +# ------------------------------------------------------------ split_jaxpr +# Effects an equation may carry and still move to W, or out of a program that does not need it: a collective's named +# mesh axis, which types the equation rather than doing anything. Any other -- a callback, an ordered or a state +# effect -- would run at another time in the schedule, or not at all, and split_jaxpr refuses the body. +MOVABLE_EFFECTS = ("NamedAxisEffect",) +# Equations that only move or retype a value. A W of these alone computes nothing of its own -- I computed every +# deferred output, W would reshape or convert it (a backward whose remat stays one equation: inline_remat=False) -- +# and split_jaxpr refuses it. +MOVES = frozenset( + {"broadcast_in_dim", "reshape", "squeeze", "expand_dims", "transpose", "convert_element_type", "copy", "copy_p"} +) + + +@dataclasses.dataclass(frozen=True, eq=False) +class JaxprSplit: + """The two halves of a body's jaxpr (split_jaxpr): + + i_jaxpr(*jaxpr's invars) -> (*outvars[i_out], *crossing) + w_jaxpr(*crossing, *jaxpr's invars[w_inputs]) -> (*outvars[w_out]) + + `crossing`: the values I computes that W reads -- W's equations in order, each one's operands in order, then the + outputs W returns as they are -- the same layout in every trace of the same program, as every McJAX process + traces its own. An operand of an inlined remat that W reads crosses as its barrier's output. `i_inputs` / + `w_inputs`: the positions of the invars each half reads, ascending. `stats`: the body's equations (`eqns`), I's + and W's (`i_eqns`, `w_eqns`; any other is dead code, in neither), those I computes that W's outputs need too + (`shared`), and the crossing set's size (`crossing`) and bytes (`crossing_bytes`, per device: a body's avals are + per-device).""" + + i_jaxpr: object + w_jaxpr: object + i_out: tuple + w_out: tuple + crossing: tuple + i_inputs: tuple + w_inputs: tuple + stats: dict + + @property + def crossing_avals(self): + return tuple(v.aval for v in self.crossing) + + +def _nbytes(aval): + return math.prod(aval.shape) * aval.dtype.itemsize + + +def _closure(eqns, producer, roots): + """The positions of the equations `roots` depend on, each equation whole: all of its operands' producers too.""" + need, stack, seen = set(), [v for v in roots if isinstance(v, jcore.Var)], set() + while stack: + v = stack.pop() + if v in seen: + continue + seen.add(v) + k = producer.get(v) + if k is None or k in need: + continue + need.add(k) + stack.extend(u for u in eqns[k].invars if isinstance(u, jcore.Var)) + return need + + +def _effects(eqns): + return frozenset().union(*(e.effects for e in eqns)) + + +def split_jaxpr(jaxpr, i_out): + """Cut `jaxpr` (a Body's: per-device and flat) by data dependence -> JaxprSplit. + + `i_out`: the outvars I computes (their positions, or an int n: the first n) -- the input gradient, any + accumulator leaf not deferred; W computes the others. I is every equation its outputs need; W every equation the + others need that I does not compute (each equation whole, in the body's order); the crossing set the values I + computes that W reads. No equation runs twice, and none is changed: a custom_vjp call, a kernel or a loop that + both halves' outputs need is computed in I, its outputs crossing to W as needed. + + Refuses (ValueError) a body with an effect outside MOVABLE_EFFECTS, an I or a W that computes nothing -- no output + kept or none deferred, no equation in I, or in W none but MOVES (every deferred output an input or one of I's + values, reshaped or converted at most) -- and positions out of range.""" + outvars = list(jaxpr.outvars) + i_out = tuple(sorted(set(range(i_out) if isinstance(i_out, int) else i_out))) + if any(not 0 <= k < len(outvars) for k in i_out): + raise ValueError(f"split_jaxpr: i_out {i_out} out of range for {len(outvars)} outputs") + w_out = tuple(k for k in range(len(outvars)) if k not in i_out) + if not i_out or not w_out: + raise ValueError( + f"split_jaxpr: I keeps {len(i_out)} of the {len(outvars)} outputs and W {len(w_out)}: nothing to split" + ) + eqns = list(jaxpr.eqns) + for k, e in enumerate(eqns): + bad = sorted(str(x) for x in e.effects if type(x).__name__ not in MOVABLE_EFFECTS) + if bad: + raise ValueError( + f"split_jaxpr: equation {k} ({e.primitive.name}) has effects {bad}: split, it would run at another " + "time, or not at all" + ) + producer = {v: k for k, e in enumerate(eqns) for v in e.outvars if not isinstance(v, jcore.DropVar)} + need_i = _closure(eqns, producer, [outvars[k] for k in i_out]) + need_w = _closure(eqns, producer, [outvars[k] for k in w_out]) + i_eqns, w_eqns = sorted(need_i), sorted(need_w - need_i) + if not i_eqns: + raise ValueError(f"split_jaxpr: I would compute nothing: no equation of the {len(eqns)} computes the outputs kept") + if all(eqns[k].primitive.name in MOVES for k in w_eqns): + raise ValueError( + f"split_jaxpr: W would compute nothing: the deferred outputs are inputs or I's values, which its " + f"{len(w_eqns)} equation(s) {sorted({eqns[k].primitive.name for k in w_eqns})} only move" + ) + w_defined = {v for k in w_eqns for v in eqns[k].outvars} + invar_pos = {v: i for i, v in enumerate(jaxpr.invars)} + constvars = set(jaxpr.constvars) + crossing, crossed, w_reads = [], set(), set() + + def w_read(v): + if not isinstance(v, jcore.Var) or v in w_defined or v in constvars: + return + if v in invar_pos: + w_reads.add(invar_pos[v]) + elif v not in crossed: + crossed.add(v) + crossing.append(v) + + for k in w_eqns: + for v in eqns[k].invars: + w_read(v) + for k in w_out: + w_read(outvars[k]) + i_vars = [v for k in i_eqns for v in eqns[k].invars] + [outvars[k] for k in i_out] + i_inputs = tuple(sorted({invar_pos[v] for v in i_vars if isinstance(v, jcore.Var) and v in invar_pos})) + w_inputs = tuple(sorted(w_reads)) + i_jaxpr = jaxpr.replace( + eqns=[eqns[k] for k in i_eqns], + outvars=[outvars[k] for k in i_out] + crossing, + effects=_effects(eqns[k] for k in i_eqns), + ) + w_jaxpr = jaxpr.replace( + invars=crossing + [jaxpr.invars[i] for i in w_inputs], + eqns=[eqns[k] for k in w_eqns], + outvars=[outvars[k] for k in w_out], + effects=_effects(eqns[k] for k in w_eqns), + ) + stats = { + "eqns": len(eqns), + "i_eqns": len(i_eqns), + "w_eqns": len(w_eqns), + "shared": len(need_i & need_w), + "crossing": len(crossing), + "crossing_bytes": sum(_nbytes(v.aval) for v in crossing), + } + return JaxprSplit(i_jaxpr, w_jaxpr, i_out, w_out, tuple(crossing), i_inputs, w_inputs, stats) + + +def same_values(a, b): + """Whether `a` and `b` (arrays or scalars) are one value: the same shape, dtype and bits.""" + a, b = np.asarray(a), np.asarray(b) + return a.shape == b.shape and a.dtype == b.dtype and a.tobytes() == b.tobytes() + + +def same_jaxpr(a, b): + """Whether jaxprs `a` and `b` (open or closed) are one program: printed alike -- every equation's primitive, + parameters (nested jaxprs too) and variables, which the printer names in order of appearance, so that two traces + of one function compare alike -- and their constants alike (`same_values`). A parameter printed with an object's + address (a function) makes two traces of one function differ: no false match.""" + ca, cb = list(getattr(a, "consts", ())), list(getattr(b, "consts", ())) + return len(ca) == len(cb) and str(a) == str(b) and all(same_values(x, y) for x, y in zip(ca, cb)) diff --git a/src/maxtext/experimental/mpmd/jax/testing.py b/src/maxtext/experimental/mpmd/jax/testing.py new file mode 100644 index 0000000000..d4fdc39f7f --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/testing.py @@ -0,0 +1,522 @@ +# 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. + +"""Shared test gates for the mpmd/jax tests: Lineage, device counts, the hardware; and where things are. + +Each gate decorates a unittest.TestCase class or a test method. It skips (or, where a run asks for it, fails) and +applies the pytest marker, if any, that MaxText's CI selects on (its pytest.ini's: scheduled_only, tpu_only, +gpu_only, cpu_only). The tests apply the markers themselves as @pytest.mark. decorators, which +tests/utils/newly_added_detection.py reads statically (it sees no marker a gate applies: requires_gpu's gpu_only). + + slow skip unless MAXTEXT_MPMD_SLOW_TESTS=1, which no CI job sets: a check of several minutes of CPU + compiles each, more than MaxText's scheduled CPU CI should carry, run by hand. Marker + scheduled_only. (A check of up to two minutes or so is a plain @pytest.mark.scheduled_only, which + MaxText's scheduled CI runs.) + requires_lineage skip unless Lineage (MaxText's experimental/lineage) imports; under MAXTEXT_MPMD_REQUIRE_LINEAGE=1 + fail instead. No marker. + needs_devices(n) skip unless jax has n devices. No marker. MaxText's CPU CI runs with 4; a class whose + pipeline stages fit either asks for 4 and takes stage_axes()'s stages. + needs_ynn_off skip where XLA:CPU's YNNPACK fusions are on: jaxlib >= 0.11.2 on CPU, XLA_FLAGS without + --xla_cpu_experimental_ynn_fusion_type= (and with jaxlib_before=, a jaxlib older than that). No + marker. + trips_cpu_heap_bug skip on CPU under the jaxlibs whose XLA:CPU corrupts its heap on the class's programs + (CPU_HEAP_BUG_JAXLIBS: 0.12.0.x, 0.12.1), unless MAXTEXT_MPMD_RUN_JAXLIB_CPU_CRASH=1. No marker. + requires_gpu skip unless jax runs on a GPU (of a compute capability, sm=), with the Python packages a kernel + needs installed (a Triton kernel's triton and jax_triton, which no requirements file brings). + Marker gpu_only. + +Two compile-option sets, per program, for checks that hold two programs to the same bits: NO_EXCESS_PRECISION (XLA's +excess precision off) and ynn_off() (XLA:CPU's YNNPACK fusions off). + +A module of CPU checks calls require_cpu() from its setUpModule. A tpu_only class calls require_tpu(here) where it +sets up -- `here` whether jax runs on the TPUs it needs (tpu_devices(): a TPU VM's own, or Pathways' through +JAX_PLATFORMS=proxy) -- which skips, saying what jax runs on and how to put it on TPUs, or under +MAXTEXT_MPMD_REQUIRE_TPU=1 fails instead: a run meant for the TPU cannot pass as skips. A TPU check of a TPU VM's +own libtpu (McJAX), such as which stages it offloads collectives to SparseCore on, calls skip_on_pathways(why). A +class whose meshes take several devices asks for them with needs_devices: on CPU that is +XLA_FLAGS=--xla_force_host_platform_device_count=N (4 in MaxText's CPU CI; 8 for the classes that need them). No +test module sets JAX_PLATFORMS or XLA_FLAGS itself: collected with other modules, a default set at import would apply +to every test of the session. + +This module imports neither jax nor MaxText at import: a gate asks for devices or imports Lineage when its class sets +up or its test runs, never at collection. assert_warns_regex stands in for unittest's assertWarnsRegex, which breaks +once transformers is imported (see its docstring). + +Where things are, the same wherever the package lives (PACKAGE, its dotted name; in MaxText the tests are +tests.unit.mpmd_test, apart from the package): + package_dir() the package's directory, with its data files (the launchers, libtpu_flags/, gpu.xla_flags). + import_root([module]) the directory the package (or a test module) imports from, by its dotted name's depth: a + child process's working directory. + child_pythonpath(test) PYTHONPATH for a child process that imports the package and the tests. + is_maxtext(name) is a module MaxText's own, not the package (nor a package above it)? +""" + +import contextlib +import functools +import importlib +import importlib.util +import os +import re +import sys +import unittest +import warnings + +try: + import pytest +except ImportError: # plain unittest without pytest installed: the gates still skip, with no markers + pytest = None + + +def cpu_hint(devices=4): + """How to run a CPU test: on `devices` fake CPU devices (MaxText's CPU CI runs with 4).""" + return f"run with JAX_PLATFORMS=cpu XLA_FLAGS=--xla_force_host_platform_device_count={devices}" + + +def env_on(name): + """Is the switch `name` (MAXTEXT_MPMD_SLOW_TESTS, MAXTEXT_MPMD_REQUIRE_LINEAGE, ...) set to 1?""" + return os.environ.get(name) == "1" + + +# The package's dotted name: this module's, less its own last component. +PACKAGE = __name__.rpartition(".")[0] + + +def package_dir(): + """The package's directory, where its modules and data files are (the launchers, libtpu_flags/, gpu.xla_flags). A + test finds them here, never through its own directory: in MaxText the tests live apart from the package.""" + return os.path.dirname(os.path.abspath(__file__)) + + +def import_root(module=None): + """The directory a module imports from: its file's directory, one level up for each component of its package's + dotted name. `module` is the name of an imported module (a test's __name__; one run with `python3 -m` is __main__, + whose spec keeps the name), by default this one: the package's root, a child process's working directory -- the + repository root here, src/ in MaxText, whose tests import from the repository root (tests.unit.experimental...). + None for a module run by its file's path, whose package Python does not know.""" + mod = sys.modules[module or __name__] + spec = getattr(mod, "__spec__", None) + if spec is None: + return None + root = os.path.dirname(os.path.abspath(mod.__file__)) + for _ in spec.parent.split(".") if spec.parent else (): + root = os.path.dirname(root) + return root + + +def child_pythonpath(test=None): + """PYTHONPATH for a child process that imports the package and, `test` given (a test module's __name__), the + tests: import_root(), the test's root where that is another one (MaxText's tests), then the PYTHONPATH inherited.""" + roots = [import_root(), import_root(test) if test else None, os.environ.get("PYTHONPATH")] + return os.pathsep.join(filter(None, dict.fromkeys(roots))) + + +def mark(name): + """The pytest marker `name` as a decorator (a no-op where pytest is not installed).""" + if pytest is None: + return lambda obj: obj + return getattr(pytest.mark, name) + + +def _before(check): + """A decorator that runs `check()` (which raises unittest.SkipTest, or an error) before a test method, or once + before a TestCase class's setUpClass.""" + + def decorate(obj): + if isinstance(obj, type): + own = obj.__dict__.get("setUpClass") + + def setUpClass(cls): + check() + if own is not None: + own.__func__(cls) + else: + super(obj, cls).setUpClass() + + obj.setUpClass = classmethod(setUpClass) + return obj + + @functools.wraps(obj) + def run(*args, **kwargs): + check() + return obj(*args, **kwargs) + + return run + + return decorate + + +SLOW_TESTS = "MAXTEXT_MPMD_SLOW_TESTS" +MULTIHOST_TESTS = "MAXTEXT_MPMD_MULTIHOST_TESTS" + + +def require_multihost(): + """Raise unittest.SkipTest unless MAXTEXT_MPMD_MULTIHOST_TESTS=1, which no CI job sets: for a test that starts + several JAX processes (multi-controller JAX over local CPU processes). MaxText's CPU CI runs many test modules in + each pytest worker, and there the out-of-memory killer took such children (exit -9). Run them by hand -- + MAXTEXT_MPMD_MULTIHOST_TESTS=1 python3 -m pytest .""" + if not env_on(MULTIHOST_TESTS): + raise unittest.SkipTest( + f"{MULTIHOST_TESTS}=1 runs it, by hand (no CI job sets it): it starts several JAX processes, more memory than " + "a CI worker running other test modules has" + ) + + +def slow(obj): + """Skip the test unless MAXTEXT_MPMD_SLOW_TESTS=1, which no CI job sets, and mark it scheduled_only: a check of + several minutes of CPU compiles (over two on a 4-device CPU replica of MaxText's CI, under load), run by hand -- + MAXTEXT_MPMD_SLOW_TESTS=1 python3 -m pytest .""" + why = f"{SLOW_TESTS}=1 runs it, by hand (no CI job sets it): several minutes of CPU compiles" + return mark("scheduled_only")(unittest.skipUnless(env_on(SLOW_TESTS), why)(obj)) + + +def needs_devices(n, why=""): + """Skip the test, or the class (in its setUpClass), unless jax has `n` devices: what its meshes take, or more + (`why` says so). Asked when it runs: the question starts jax's backend.""" + + def check(): + import jax # pylint: disable=import-outside-toplevel + + have = jax.device_count() + if have < n: + note = f" ({why})" if why else "" + raise unittest.SkipTest(f"needs {n} devices{note}, jax has {have}: on CPU, {cpu_hint(n)}") + + return _before(check) + + +def stage_axes(stages=2): + """{'fsdp': ..., 'ep': ...} of each of `stages` pipeline stages on the devices jax has: FSDP 2 x EP 2 where there + are 4 devices a stage (8 for two stages), else FSDP 1 x EP 2 (two stages on MaxText's CPU CI's 4 devices). Both + keep the expert axis -- its ring of experts, and the storage sharded over fsdp and expert together (ds_ep.FE), so + the gathers and reduce-scatters move data either way; FSDP 1 has no fsdp-only collective. A class whose stages + take these asks for 2 * stages devices (needs_devices). Asked when a class sets up or a test runs: the question + starts jax's backend.""" + import jax # pylint: disable=import-outside-toplevel + + return {"fsdp": 2, "ep": 2} if jax.device_count() >= 4 * stages else {"fsdp": 1, "ep": 2} + + +# XLA's excess precision (on by default) lets it drop an intermediate bf16 rounding where it fuses the producer into +# its consumer, so which roundings survive depends on the fusion: two programs doing the same bf16 arithmetic but +# fused differently part in the last bits (jax 0.12.0.1's XLA:CPU, the bf16 moments' b1 * mu in AdamW). A test that +# holds one to the other bit for bit compiles both without it (jax.jit's or Lowered.compile's compiler_options). +NO_EXCESS_PRECISION = {"xla_allow_excess_precision": False} + + +def ynn_off(backend=None): + """{'xla_cpu_experimental_ynn_fusion_type': ''} on CPU (`backend`, default jax's), else {}: per-program compile + options without XLA:CPU's YNNPACK fusions, which are on by default. A YNNPACK dot's summation order follows its + operands' shapes, so a sharded program (per-device shapes) and its unsharded reference part in the last bits; and on + jax >= 0.11.2 a bf16 dot no longer accumulates in fp32 there. Without them a dot is XLA's own, fp32-accumulated, + the same at any shape and thread count. For test-only computations held to each other bit for bit; per program, so the + process keeps its flags (no test module sets XLA_FLAGS).""" + import jax # pylint: disable=import-outside-toplevel + + return {"xla_cpu_experimental_ynn_fusion_type": ""} if (backend or jax.default_backend()) == "cpu" else {} + + +def version_tuple(version): + """The version string `version`'s leading numeric components as a tuple of ints, () where it starts with none: + '0.12.0.1' gives (0, 12, 0, 1). A pre-release, post-release, nightly or local build reads as its release: + '0.12.1rc1', '0.12.1.post1' and '0.12.1+cuda12' give (0, 12, 1), '0.12.2.dev20261201' gives (0, 12, 2) -- the dotted + prefix that jax's own check of jaxlib's version reads (jax._src.lib.check_jaxlib_version).""" + m = re.match(r"[0-9]+(?:\.[0-9]+)*", version) + return tuple(int(x) for x in m.group(0).split(".")) if m else () + + +def jaxlib_version(): + """jaxlib's version as a tuple of ints, e.g. (0, 12, 0, 1): its version module's __version__ by version_tuple, which + starts no backend. Not the module's __version_info__, which drops every component with a suffix: 0.12.1rc1's is + (0, 12), which the gates below would take for no 0.12.1 build.""" + from jaxlib import version # pylint: disable=import-outside-toplevel + + return version_tuple(getattr(version, "__version__", "")) + + +# XLA:CPU's YNNPACK fusions, which `YNN_FLAG=` (no fusion type) in XLA_FLAGS turns off for the process. jaxlib runs +# them by default, and from 0.11.2 on a bf16 dot inside one no longer accumulates in fp32 as on 0.11.1. +YNN_FLAG = "--xla_cpu_experimental_ynn_fusion_type" + + +def ynn_on(): + """Why XLA:CPU's YNNPACK fusions are on in this process the way jaxlib 0.11.2 brought them, else None: jax on CPU, + jaxlib >= 0.11.2, and XLA_FLAGS without `YNN_FLAG=` (the last of its YNN_FLAG settings counts, a quoted value + without its quotes as XLA reads it: `YNN_FLAG=""` turns them off too; the backend read it when it started). This + starts jax's backend: ask where a class sets up or a test runs.""" + import jax # pylint: disable=import-outside-toplevel + + if jax.default_backend() != "cpu" or jaxlib_version() < (0, 11, 2): + return None + setting = None + for flag in os.environ.get("XLA_FLAGS", "").split(): + if flag.startswith(YNN_FLAG + "="): + setting = flag[len(YNN_FLAG) + 1 :] + # xla/parse_flags_from_env.cc takes a value in single or double quotes without them + if setting is not None and len(setting) >= 2 and setting[0] == setting[-1] and setting[0] in "'\"": + setting = setting[1:-1] + if setting == "": + return None + return f"XLA:CPU's YNNPACK fusions are on (jaxlib {'.'.join(map(str, jaxlib_version()))}'s default)" + + +# Some checks fail with XLA:CPU's YNNPACK fusions on through bugs of particular jaxlibs, not by design -- gradients NaN +# or wrong, XLA:CPU crashing: seen on jaxlib 0.12.0.1 and 0.12.1 (2026-11-26), not on 0.11.1. Their gates skip only +# before this jaxlib (needs_ynn_off's jaxlib_before), so that a later one runs them with the fusions on again: they +# pass once the bugs are fixed, or fail, and the bound moves up. A nightly or rc of this jaxlib (0.12.2.dev20261201, +# 0.12.2rc1) is this jaxlib to jaxlib_version, not one before it. +YNN_BUG_JAXLIBS_BEFORE = (0, 12, 2) + + +def needs_ynn_off(why, jaxlib_before=None): + """Skip the test, or the class (in its setUpClass), where XLA:CPU's YNNPACK fusions are on (ynn_on: jaxlib >= 0.11.2 + on CPU without `YNN_FLAG=` in XLA_FLAGS), saying `why` they break it and how to run it: with the flag in + XLA_FLAGS. For a check of the pipeline's own programs, which a test cannot compile with ynn_off()'s per-program + options (several of them run inside others, where jax refuses compiler_options). `jaxlib_before`, a version tuple + (YNN_BUG_JAXLIBS_BEFORE), bounds the gate of a check the fusions break through a jaxlib bug: from that jaxlib on the + check runs with them on.""" + + def check(): + on = ynn_on() + if on is not None and (jaxlib_before is None or jaxlib_version() < tuple(jaxlib_before)): + raise unittest.SkipTest(f"{on}: {why} -- run it with XLA_FLAGS='... {YNN_FLAG}='") + + return _before(check) + + +# jaxlib 0.12.0.x's XLA:CPU corrupts its own heap compiling or running some programs -- the Qwen3.5-family MoE block's +# backward most of all (a top-k dispatch by sort / argsort, gathers, a masked grouped matmul, a scatter-add) -- and the +# process then dies somewhere later (SIGSEGV; SIGABRT from tcmalloc's "Attempt to free invalid pointer" or an absl +# CHECK in HloCostAnalysis or YnnFusionThunk) or, once seen, computes a NaN. Not the YNNPACK fusions (it happens with +# them off), not a race in jax (one Python thread is enough), and no XLA:CPU flag tried avoids it. `pytest +# ds_ep_qwen_test.py -k "QwenInit or QwenMoeVsPort"` on 8 CPU devices, 12 processes one at a time, crashed in 4 of 12 +# on jaxlib 0.12.0.1 (6 of 12 with the YNNPACK fusions off), 10 of 12 on 0.12.1 and 0 of 12 on 0.11.1. Under +# pytest-xdist the crash takes a worker and the tests it had left: about one worker a round of the tests, all in +# ds_ep_qwen_test, and none once its QwenMoeVsPort skips (2026-11-25). A crash at the memory-map limit +# (vm.max_map_count, 65530 by default) is not this bug, and can come on any jaxlib. Compiled programs' code takes the +# maps -- 27k to 44k for one case of ds_ep_test's RepeatScope.test_bitwise_vs_step_more (two tiny pipelines) on jaxlib +# 0.12.0.1 with the YNNPACK fusions off, under 10k for the processes above -- and the cure is freeing dead pipelines +# sooner (gc.collect(), as RepeatScope and BatchSplitLineage do), not a skip (2026-11-27). In a test run's log the two +# look alike: pytest's default capture drops XLA's stderr when the process dies (the heap bug's messages above as well), +# leaving "Fatal Python error: Aborted" or "Segmentation fault" over a Python stack (at the map limit, in jax's +# backend_compile_and_load). Rerun the test alone with -s or --capture=sys: at the limit XLA:CPU logs +# "LLVM compilation error: Cannot allocate memory" just before a SIGSEGV, or before "allocateMappedMemory failed", +# "LLVM ERROR: Unable to allocate section memory!" and a SIGABRT. Or watch the process's map count +# (wc -l < /proc/PID/maps): it reaches vm.max_map_count just before the crash (the last sample, up to 2 s before it, +# read 64.4k to 65.5k), and a run that passes shows how near it came. The jaxlib versions the heap corruption was seen +# on, as prefixes of jaxlib_version (a nightly or rc of one matches too): +CPU_HEAP_BUG_JAXLIBS = ((0, 12, 0), (0, 12, 1)) + + +def cpu_heap_bug(): + """Why a test whose programs trip jaxlib's XLA:CPU heap corruption (CPU_HEAP_BUG_JAXLIBS) is not run here, else + None: jax on CPU under one of those jaxlibs, and MAXTEXT_MPMD_RUN_JAXLIB_CPU_CRASH=1 (run it anyway) not set. This + starts jax's backend: ask where a class sets up or a test runs.""" + import jax # pylint: disable=import-outside-toplevel + + if env_on("MAXTEXT_MPMD_RUN_JAXLIB_CPU_CRASH") or jax.default_backend() != "cpu": + return None + v = jaxlib_version() + if not any(v[: len(p)] == p for p in CPU_HEAP_BUG_JAXLIBS): + return None + return ( + f"jaxlib {'.'.join(map(str, v))}'s XLA:CPU corrupts its heap compiling and running these programs (the Qwen MoE " + "backward), and the process dies later, anywhere (testing.CPU_HEAP_BUG_JAXLIBS): " + "MAXTEXT_MPMD_RUN_JAXLIB_CPU_CRASH=1 runs them anyway" + ) + + +def trips_cpu_heap_bug(obj): + """Skip the test, or the class (in its setUpClass), where jaxlib's XLA:CPU heap corruption would take the process + (cpu_heap_bug): a class whose programs crashed pytest-xdist workers on jaxlib 0.12.0.1 (ds_ep_qwen_test's + QwenMoeVsPort).""" + + def check(): + why = cpu_heap_bug() + if why is not None: + raise unittest.SkipTest(why) + + return _before(check)(obj) + + +def gpu_missing(*modules, sm=None): + """Why a GPU test cannot run here, else None: jax runs on no GPU, or on one whose compute capability's major version + is not `sm` (10: Blackwell's sm_100 / sm_103), or a Python package it needs (`modules`) is not installed -- found + with importlib.util.find_spec, not imported. This starts jax's backend: ask where a class sets up or a test runs.""" + import jax # pylint: disable=import-outside-toplevel + + d = jax.devices()[0] + if d.platform != "gpu": + return f"needs a GPU, jax runs on {d.platform}: run with JAX_PLATFORMS=cuda XLA_FLAGS=" + if sm is not None: + cc = getattr(d, "compute_capability", None) + try: + major = int(float(cc)) + except (TypeError, ValueError): + major = None + if major != sm: + return f"needs an sm_{sm}0 GPU, this one's compute capability is {cc}" + missing = [m for m in modules if importlib.util.find_spec(m) is None] + if missing: + return f"needs {' and '.join(missing)} installed (pip install {' '.join(m.replace('_', '-') for m in missing)})" + return None + + +def requires_gpu(*modules, sm=None, why=""): + """Skip unless jax runs on a GPU -- of compute capability major `sm` where given -- with the Python packages + `modules` installed (gpu_missing), checked when the class sets up or the test runs: the backend question starts + jax's backend, never at collection. Marks gpu_only. @requires_gpu(), @requires_gpu(sm=10), or + @requires_gpu('triton', 'jax_triton', why='the Triton kernel').""" + + def check(): + err = gpu_missing(*modules, sm=sm) + if err is not None: + raise unittest.SkipTest(f"{why}: {err}" if why else err) + + def decorate(obj): + return mark("gpu_only")(_before(check)(obj)) + + return decorate + + +def require_cpu(what="CPU tests"): + """For setUpModule: skip the module unless jax runs on CPU (its bounds are CPU measurements, or it stands in for + hardware it does not have).""" + import jax # pylint: disable=import-outside-toplevel + + if jax.default_backend() != "cpu": + raise unittest.SkipTest(f"{what}: {cpu_hint()}") + + +# The JAX_PLATFORMS entries that put jax on TPUs: a TPU VM's own client (McJAX), and Pathways' IFRT proxy, whose +# devices report the platform 'tpu' too -- MaxText's CI runs its tpu_only tests both ways. +TPU_PLATFORMS = ("tpu", "proxy") + + +def tpu_devices(): + """jax's devices where they are TPUs -- a TPU VM's own, or Pathways' through the IFRT proxy, which report the + platform 'tpu' as MaxText's tests/conftest.py reads it -- else []. This starts jax's backend (under + JAX_PLATFORMS=proxy after pathways.initialize()): ask where a class sets up or a test runs.""" + from maxtext.experimental.mpmd.jax import pathways # pylint: disable=import-outside-toplevel + + pathways.initialize() + import jax # pylint: disable=import-outside-toplevel + + try: + devs = jax.devices() + except RuntimeError: # a JAX_PLATFORMS naming a platform that does not start (a proxy that does not answer) + return [] + return devs if devs and devs[0].platform == "tpu" else [] + + +def tpu_hint(): + """What jax runs on (its devices: how many, of what kind) and, where JAX_PLATFORMS keeps it off TPUs, how to put + it on them: JAX_PLATFORMS=tpu, or proxy on Pathways (TPU_PLATFORMS). This starts jax's backend: ask where a class + sets up or a test runs.""" + import jax # pylint: disable=import-outside-toplevel + + try: + devs = jax.devices() + on = f"{jax.default_backend()} ({len(devs)} x {devs[0].device_kind})" + except RuntimeError as e: # a JAX_PLATFORMS naming a platform that does not start + on = f"no backend ({e})" + platforms = os.environ.get("JAX_PLATFORMS") + if platforms is None or set(TPU_PLATFORMS) & {p.strip().lower() for p in platforms.split(",")}: + return f"jax runs on {on}" + return f"jax runs on {on}: JAX_PLATFORMS={platforms!r} -- run with JAX_PLATFORMS=tpu (proxy on Pathways)" + + +def require_tpu(here, what="a TPU"): + """For a tpu_only class where it sets up (or a test): nothing if `here`, jax running on the TPU it needs (`what`); + else unittest.SkipTest saying what jax runs on and how to put it on a TPU (tpu_hint) -- or, under + MAXTEXT_MPMD_REQUIRE_TPU=1, set by a run meant for that TPU, an error, so that such a run cannot pass as skips (a + JAX_PLATFORMS=cpu left over from the CPU tests, say).""" + if here: + return + why = f"needs {what}; {tpu_hint()}" + if env_on("MAXTEXT_MPMD_REQUIRE_TPU"): + raise RuntimeError(f"MAXTEXT_MPMD_REQUIRE_TPU=1, but this {why}") + raise unittest.SkipTest(why) + + +def on_pathways(): + """Are jax's devices Pathways' (the IFRT proxy's: pathways.is_proxy_device) rather than a TPU VM's own client's + (McJAX)? This starts jax's backend (under JAX_PLATFORMS=proxy after pathways.initialize()): ask where a class sets + up or a test runs.""" + from maxtext.experimental.mpmd.jax import pathways # pylint: disable=import-outside-toplevel + + pathways.initialize() + import jax # pylint: disable=import-outside-toplevel + + try: + devs = jax.devices() + except RuntimeError: # a JAX_PLATFORMS naming a platform that does not start + return False + return bool(devs) and pathways.is_proxy_device(devs[0]) + + +def skip_on_pathways(why): + """For a TPU class where it sets up (or a test) that holds behaviour of a TPU VM's own libtpu which Pathways' + servers do not share (`why`): unittest.SkipTest on Pathways' devices (on_pathways), MAXTEXT_MPMD_REQUIRE_TPU=1 or + not -- such a check does not apply there; it is not missing a TPU.""" + if on_pathways(): + raise unittest.SkipTest(f"McJAX only, jax runs on Pathways' devices: {why}") + + +def is_maxtext(name): + """Is the module `name` one of MaxText's own: maxtext or a module under it, but not the package or anything in it, + nor a package above it (in MaxText the package is maxtext.experimental.mpmd.jax).""" + return (name == "maxtext" or name.startswith("maxtext.")) and not ( + name == PACKAGE or name.startswith(PACKAGE + ".") or PACKAGE.startswith(name + ".") + ) + + +@functools.lru_cache(maxsize=None) +def lineage_missing(): + """Why Lineage does not import here (ds_ep_lineage.import_lineage's ImportError: the maxtext in use and what it + lacks), else None.""" + from maxtext.experimental.mpmd.jax import ds_ep_lineage # pylint: disable=import-outside-toplevel + + try: + ds_ep_lineage.import_lineage() + except ImportError as e: + return str(e) + return None + + +def requires_lineage(obj): + """Skip unless Lineage imports, checked when the class sets up or the test runs; under MAXTEXT_MPMD_REQUIRE_LINEAGE=1 + a Lineage that does not import is an error, not a skip.""" + + def check(): + err = lineage_missing() + if err is None: + return + if env_on("MAXTEXT_MPMD_REQUIRE_LINEAGE"): + raise ImportError(f"MAXTEXT_MPMD_REQUIRE_LINEAGE=1, but Lineage does not import: {err}") + raise unittest.SkipTest(f"needs Lineage: {err}") + + return _before(check)(obj) + + +@contextlib.contextmanager +def assert_warns_regex(test, category, regex): + """test.assertWarnsRegex(category, regex) without its reset of every loaded module's warning registry. That + reset reads an attribute of each module in sys.modules, and transformers' lazy alias modules (loaded with + MaxText's model and trainer code) then import what they stand for, which imports torch: where torch is not + installed, every later assertWarnsRegex in the process failed.""" + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") # a warning given before shows again + yield seen + got = [str(w.message) for w in seen if issubclass(w.category, category)] + test.assertTrue(any(re.search(regex, m) for m in got), f"no {category.__name__} matching {regex!r} in {got}") diff --git a/src/maxtext/experimental/mpmd/jax/transfer.py b/src/maxtext/experimental/mpmd/jax/transfer.py new file mode 100644 index 0000000000..149c05750f --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/transfer.py @@ -0,0 +1,2653 @@ +# 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. + +"""Cross-mesh device-to-device transfer layer for the pure-JAX MPMD pipeline. + +The driver moves one activation (or cotangent) pytree per stage boundary per +microbatch. `jax.device_put` works, but costs 58-72 us of host Python per +call on a v5p host (against Channel's 13; v5p-8, jax 0.11.1, 2026-10-07), and +host dispatch is the binding cost of the whole design. A `Channel` +resolves one boundary ONCE at setup (device lists, shardings, copy semantics) +and then issues the entire boundary as a single +`xc.batched_copy_array_to_devices_with_sharding` call. + +Rules baked in here, all of them learned the hard way: + * `ArrayCopySemantics.DONATE_INPUT` on a cross-mesh copy SEGFAULTS. Only + REUSE_INPUT is ever used; free the source by dropping the Python reference + AFTER the copy is issued (PJRT keeps it alive until the copy completes). + * A put whose per-device index map differs between src and dst silently + round-trips through the host (`x._value`) and caches a numpy copy forever. + It is still numerically correct, so no value check catches it -- hence + `same_index_map` / `assert_d2d` at SETUP and `no_host_bounce()` in CI. + * Index maps must be compared as ORDERED VALUES; the maps are keyed by Device + and stage sub-meshes are disjoint, so dict equality is always False. + * The batched copy does NOT check that the arrays it is handed carry the + sharding they were resolved for. Hand it shards laid out differently and it + reinterprets them under the destination layout and returns a structurally + inconsistent Array: no exception, no host bounce, WRONG NUMBERS downstream. + That is why `send` validates every fast-path leaf: ~0.16 us/leaf measured, + ~1% of the ~12 us/leaf send. Slow-but-correct has three guards, so + fast-and-wrong gets one too. + +Across processes (one per host) a boundary is a CrossProcessChannel (jax's +cross-host copy), a PermuteChannel (a collective-permute program both stages +run), an XferChannel (jax.experimental.transfer pulls) or a RelayChannel: the +one deliberate host round trip, D2H -> TCP between the hosts -> H2D, for +where libtpu's own cross-host paths fail (across MegaScale slices). +""" + +from __future__ import annotations +import bisect +import collections +import contextlib +import functools +import hmac +import math +import os +import queue +import secrets +import socket +import struct +import sys +import threading +import time +import warnings +import zlib + +import numpy as np +import jax +from jax.sharding import Sharding +from jaxlib import xla_client as xc + +from maxtext.experimental.mpmd.jax import pathways + +try: # private, version-guarded + from jax._src import array as _jax_array +except Exception: # pragma: no cover - jax internals + _jax_array = None + +# ------------------------------------------------------------ version guards +_BATCHED_COPY = getattr(xc, "batched_copy_array_to_devices_with_sharding", None) +BATCHED_COPY_AVAILABLE = _BATCHED_COPY is not None +REUSE_INPUT = xc.ArrayCopySemantics.REUSE_INPUT # never DONATE_INPUT: segfaults + + +class ShardingMismatchError(ValueError): + """A cross-mesh put would silently take the host-round-trip reshard path.""" + + +class HostBounceError(RuntimeError): + """A device->host transfer happened inside a `no_host_bounce()` region.""" + + +# ------------------------------------------------------------- the predicate +def _index_values(sharding, shape): + return tuple(sharding.addressable_devices_indices_map(tuple(shape)).values()) + + +def _private_fastpath_verdict(src_sharding, dst_sharding, ndim): + """jax's own fastpath predicate, or None if this build does not have it. + + jax 0.11.1's `_sharding_indices_and_eq(src, dst, ndim)` returns a plain bool + (HLO shardings equal AND addressable device counts equal) despite the name. + """ + fn = getattr(_jax_array, "_sharding_indices_and_eq", None) + if fn is None: + return None + try: + res = fn(src_sharding, dst_sharding, ndim) + except Exception: # NotImplementedError, signature drift + return None + return res if isinstance(res, bool) else None + + +@functools.lru_cache(maxsize=4096) +def _same_index_map_cached(src_sharding, dst_sharding, shape): + src, dst = _index_values(src_sharding, shape), _index_values(dst_sharding, shape) + mine = len(src) == len(dst) and src == dst + theirs = _private_fastpath_verdict(src_sharding, dst_sharding, len(shape)) + if theirs is not None and theirs != mine: + warnings.warn( + f"same_index_map disagrees with jax._src.array._sharding_indices_and_eq " + f"for {src_sharding} -> {dst_sharding} shape={shape}: ours={mine} " + f"jax={theirs}; taking the conservative AND.", + RuntimeWarning, + ) + return mine and theirs + return mine + + +def same_index_map(src_sharding, dst_sharding, shape) -> bool: + """True iff a put src->dst is a pure device-to-device copy (no reshard). + + Compares the ORDERED VALUES of `addressable_devices_indices_map(shape)` -- + never the dicts, which are keyed by Device and therefore never equal across + two disjoint stage sub-meshes -- plus equal addressable device counts. + """ + return _same_index_map_cached(src_sharding, dst_sharding, tuple(shape)) + + +def _try_same_index_map(src_sharding, dst_sharding, shape) -> bool: + """`same_index_map`, but a sharding that cannot produce an index map is False. + + Used where an exception must not escape (classification, hot-path + validation): if D2D cannot be PROVEN, it must be assumed not to hold. + """ + if src_sharding is None or dst_sharding is None: + return False + try: + return same_index_map(src_sharding, dst_sharding, shape) + except Exception: # unusual sharding, no index map + return False + + +def _fmt_index(idx): + def one(s): + if isinstance(s, slice): + a = "" if s.start is None else s.start + b = "" if s.stop is None else s.stop + return f"{a}:{b}" + return str(s) + + if not isinstance(idx, tuple): + idx = (idx,) + return "(" + ", ".join(one(s) for s in idx) + ")" + + +def assert_d2d(src, dst_sharding, name: str = "transfer", max_report: int = 4): + """Raise unless `jax.device_put(src, dst_sharding)` is a true D2D copy. + + `src` is a jax.Array (or anything with `.sharding` and `.shape`, e.g. a + ShapeDtypeStruct with a sharding). Call this at SETUP for every boundary, + never in the hot loop. + """ + src_sharding = getattr(src, "sharding", None) + if src_sharding is None: + raise ShardingMismatchError( + f"{name}: source has no .sharding ({type(src).__name__}); a host array " "cannot be device-to-device copied." + ) + shape = tuple(src.shape) + if same_index_map(src_sharding, dst_sharding, shape): + return True + sv, dv = _index_values(src_sharding, shape), _index_values(dst_sharding, shape) + if len(sv) != len(dv): + detail = f"addressable device counts differ: src={len(sv)} dst={len(dv)}" + else: + bad = [(i, a, b) for i, (a, b) in enumerate(zip(sv, dv)) if a != b] + detail = "mismatching per-device shard indices [i: src -> dst]: " + ", ".join( + f"{i}: {_fmt_index(a)} -> {_fmt_index(b)}" for i, a, b in bad[:max_report] + ) + if len(bad) > max_report: + detail += f", ... ({len(bad)} of {len(sv)} devices differ)" + raise ShardingMismatchError( + f"{name}: cross-mesh put for shape={shape} would RESHARD, not copy, and " + f"silently round-trip through the host (x._value, ~21 ms for 16 MB, and " + f"the numpy copy is cached in x._npy_value forever).\n" + f' src spec: {getattr(src_sharding, "spec", src_sharding)} ' + f"({src_sharding})\n" + f' dst spec: {getattr(dst_sharding, "spec", dst_sharding)} ' + f"({dst_sharding})\n" + f" {detail}\n" + f" Fix: give both sub-meshes the same axis names/sizes and use the same " + f"PartitionSpec on both sides of the boundary." + ) + + +# ------------------------------------------------------------------- Channel +def _is_extended(dtype) -> bool: + try: + return jax.dtypes.issubdtype(dtype, jax.dtypes.extended) + except Exception: + return False + + +def _axis_type_class(mesh): + """What a mesh's axis types mean for the arrays on it, for comparing two. + + A mesh whose axes all have one type -- all Auto, all Explicit -- types an + array that way whatever its rank or shape, so that one type is the class. + A mixed mesh is compared axis by axis, by name. + """ + types = set(mesh.axis_types) + if len(types) == 1: + return types.pop() + return frozenset(zip(mesh.axis_names, mesh.axis_types)) + + +def _device_list(sharding): + dl = getattr(sharding, "_internal_device_list", None) + return None if dl is None else dl.addressable_device_list + + +class Channel: + """A pre-resolved, reusable transfer channel for ONE stage boundary. + + Built once at setup from `(avals, src_shardings, dst_shardings)` -- pytrees of + the same structure, or a single Sharding to broadcast over all leaves. All + per-leaf work (fast/slow classification, device lists, copy semantics) is done + in `__init__`; `send` is a flat list build plus one batched copy call. + + ch = Channel(y_avals, src_shardings, dst_shardings, name='s0->s1') + assert ch.n_slow == 0 + y_next = ch.send(y) # one host call for the whole boundary + + `strict=True` rejects a resharding boundary at BUILD time, whatever else is + also wrong with the leaf. `validate=True` (the default) rejects, at SEND + time, an array that does not carry the sharding the channel was resolved for. + + `check_axis_types=True` (the default) rejects, at BUILD time, a leaf whose + src and dst meshes type it differently. The copy itself does not care + (index maps and HLO shardings ignore axis types), but its output carries + the DST sharding, and so the dst's types. An Explicit activation would + arrive Auto-typed and trace its consumer untyped, and nothing would say so. + Meshes of different rank are compared by mode, not axis by axis: two + all-Auto meshes type nothing whatever their shapes (`_axis_type_class`). + Pass False only if re-typing is the intent. + """ + + __slots__ = ( + "name", + "treedef", + "avals", + "src", + "dst", + "n_fast", + "n_slow", + "n_leaves", + "degraded", + "reasons", + "reshards", + "validate", + "_fast_pos", + "_slow_pos", + "_dev_lists", + "_shardings", + "_copy_semantics", + "_checks", + "_fallbacks", + "last_fallback_error", + ) + + def __init__( + self, avals, src_shardings, dst_shardings, name="channel", strict=False, validate=True, check_axis_types=True + ): + flat_avals, treedef = jax.tree.flatten(avals) + self.name, self.treedef, self.avals = name, treedef, tuple(flat_avals) + self.n_leaves = len(flat_avals) + self.validate = bool(validate) + self.src = self._broadcast(src_shardings, "src_shardings") + self.dst = self._broadcast(dst_shardings, "dst_shardings") + if check_axis_types: + self._check_axis_types() + + self._fast_pos, self._slow_pos, self.reasons, self.reshards = [], [], [], [] + self._dev_lists, self._shardings = [], [] + for i, aval in enumerate(flat_avals): + why, reshards = self._classify(aval, self.src[i], self.dst[i]) + self.reasons.append(why) + self.reshards.append(reshards) + # Independent of `why`: a resharding boundary is rejected under strict= + # even when the leaf is ALSO slow for an earlier reason (extended dtype, + # missing batched symbol), which used to mask it. + if strict and reshards: + assert_d2d(_ShapedSrc(aval, self.src[i]), self.dst[i], name=f"{name}[leaf {i}]") + if why is None: + self._fast_pos.append(i) + self._dev_lists.append(_device_list(self.dst[i])) + self._shardings.append(self.dst[i]) + else: + self._slow_pos.append(i) + self._copy_semantics = [REUSE_INPUT] * len(self._fast_pos) + # Pre-bound (position, declared sharding, declared shape) for the hot-path + # validation, so it is three compares and no attribute walks per leaf. + self._checks = [] if not self.validate else [(i, self.src[i], tuple(flat_avals[i].shape)) for i in self._fast_pos] + self.n_fast, self.n_slow = len(self._fast_pos), len(self._slow_pos) + self.degraded = self.n_fast == 0 and self.n_leaves > 0 + self._fallbacks, self.last_fallback_error = 0, None + + def _check_axis_types(self): + """Raise if any leaf's src and dst meshes would type it differently.""" + for i, (src, dst) in enumerate(zip(self.src, self.dst)): + sm, dm = getattr(src, "mesh", None), getattr(dst, "mesh", None) + if getattr(sm, "axis_types", None) is None or getattr(dm, "axis_types", None) is None: + continue + if _axis_type_class(sm) != _axis_type_class(dm): + raise ShardingMismatchError( + f"{self.name}[leaf {i}]: src mesh axis types " + f"{dict(zip(sm.axis_names, sm.axis_types))} != dst " + f"{dict(zip(dm.axis_names, dm.axis_types))}. The copy " + "would silently re-type the array to the dst's types (an Explicit " + "array arriving Auto-typed traces its consumer untyped). Build " + "both sub-meshes with the same shard_mode, or pass " + "check_axis_types=False if re-typing is the intent." + ) + + def _broadcast(self, shardings, what): + if isinstance(shardings, Sharding): + return [shardings] * self.n_leaves + flat = self.treedef.flatten_up_to(shardings) + if len(flat) != self.n_leaves: + raise ValueError(f"{self.name}: {what} has {len(flat)} leaves, avals have " f"{self.n_leaves}") + return list(flat) + + def _classify(self, aval, src_sharding, dst_sharding): + """`(reason, reshards)`; reason is None iff the leaf rides the batched path. + + EVERY condition is evaluated and all of them are reported, joined by '; '. + In particular the index-map check runs even when an earlier condition has + already forced the slow path: `strict=` must reject a resharding boundary + whether or not the leaf is also an extended dtype or the jaxlib is missing + the batched symbol. Returning only the first reason silently accepted + those boundaries, and they really do round-trip through the host. + """ + reasons = [] + if not BATCHED_COPY_AVAILABLE: + reasons.append("no batched_copy_array_to_devices_with_sharding in this " "jaxlib") + if _is_extended(aval.dtype): + reasons.append(f"extended dtype {aval.dtype} rejected by the batched call") + if _device_list(dst_sharding) is None: + reasons.append(f"dst sharding {dst_sharding} has no addressable device " "list") + reshards = not _try_same_index_map(src_sharding, dst_sharding, aval.shape) + if reshards: + reasons.append("reshard: src and dst index maps differ (host round trip)") + return ("; ".join(reasons) if reasons else None), reshards + + def check(self, tree=None): + """Setup-time assertion that every leaf is a real D2D copy. + + With no argument, checks the declared src shardings; with a pytree, checks + the shardings the arrays actually carry. `send` validates the fast-path + leaves on every call anyway (see `_reject_leaf`); this stays as the + setup-time, whole-boundary form and is the only check the SLOW leaves get. + """ + leaves = self.avals if tree is None else self.treedef.flatten_up_to(tree) + srcs = self.src if tree is None else [getattr(a, "sharding", None) for a in leaves] + for i, (s, leaf) in enumerate(zip(srcs, leaves)): + if s is None: + raise ShardingMismatchError( + f"{self.name}[leaf {i}]: {type(leaf).__name__} has no .sharding; a " + "host array cannot be device-to-device copied." + ) + assert_d2d(_ShapedSrc(_Aval(leaf.shape, self.avals[i].dtype), s), self.dst[i], name=f"{self.name}[leaf {i}]") + return True + + def _reject_leaf(self, i, x): + """Raise: leaf `i` does not carry the sharding this channel was resolved for. + + Called only off the hot path, after the cheap identity/equality compare in + `send_flat` has already failed. Re-checks the real predicate first, at the + array's OWN shape: a different sharding object with the same per-device + index map, or a differently shaped array that still shards identically on + both sides (a short last microbatch), is a perfectly good source for the + batched copy and is accepted rather than rejected. + """ + s = getattr(x, "sharding", None) + shape = tuple(getattr(x, "shape", ())) + if _try_same_index_map(s, self.dst[i], shape): + return # equivalent layout, still D2D + aval = self.avals[i] + if s is None: + detail = f"leaf is a {type(x).__name__} with no .sharding -- a host " "array cannot be device-to-device copied" + else: + sv, dv = None, None + try: + sv, dv = _index_values(s, shape), _index_values(self.dst[i], shape) + except Exception: # pragma: no cover - exotic sharding + pass + if sv is None or dv is None: + detail = "the actual sharding cannot produce an index map" + elif len(sv) != len(dv): + detail = f"addressable device counts differ: actual={len(sv)} " f"dst={len(dv)}" + else: + bad = [(j, a, b) for j, (a, b) in enumerate(zip(sv, dv)) if a != b] + detail = "per-device shard indices [i: actual -> dst]: " + ", ".join( + f"{j}: {_fmt_index(a)} -> {_fmt_index(b)}" for j, a, b in bad[:4] + ) + if len(bad) > 4: + detail += f", ... ({len(bad)} of {len(sv)} devices differ)" + raise ShardingMismatchError( + f"{self.name}[leaf {i}]: send() was handed an array that does NOT carry " + f"the sharding this channel was built for, and the batched copy does " + f"not check. It would reinterpret the source shards under the " + f"destination layout and return a structurally inconsistent Array that " + f"produces WRONG NUMBERS downstream -- no exception, no warning, no " + f"host bounce.\n" + f' declared src: {getattr(self.src[i], "spec", self.src[i])} ' + f"({self.src[i]})\n" + f' actual src: {getattr(s, "spec", s)} ({s})\n' + f' dst : {getattr(self.dst[i], "spec", self.dst[i])} ' + f"({self.dst[i]})\n" + f" declared shape {tuple(aval.shape)}, actual shape {shape}\n" + f" {detail}\n" + f" Fix: produce the array with the declared sharding (jit " + f"out_shardings=...), or rebuild the Channel from the shardings you " + f"actually have. Channel(..., validate=False) skips this check " + f"(~0.16 us/leaf, ~1% of a send) and restores the silent corruption." + ) + + def send_flat(self, leaves): + """Hot path: list of arrays in tree order -> list of arrays on the dst mesh.""" + out = list(leaves) + if self._fast_pos: + for i, want_sharding, want_shape in self._checks: + # ~0.16 us/leaf: a tuple compare plus an identity (then equality) + # compare. Anything that fails it goes to the slow diagnostic, which + # re-checks the real predicate before deciding to raise. + x = out[i] + try: + if x.shape != want_shape or ((s := x.sharding) is not want_sharding and s != want_sharding): + self._reject_leaf(i, x) + except AttributeError: # not a jax.Array at all + self._reject_leaf(i, x) + srcs = [out[i] for i in self._fast_pos] + try: + copies = _BATCHED_COPY(srcs, self._dev_lists, self._shardings, self._copy_semantics) + # strict=: a short return would silently leave trailing leaves holding + # their SOURCE array, and feeding a mesh-A array into a mesh-B jit works + # exactly once before raising INVALID_ARGUMENT forever after. + for i, c in zip(self._fast_pos, copies, strict=True): + out[i] = c + except Exception as e: # never lose a step to an API drift + self._fallbacks += 1 + self.last_fallback_error = e + if self._fallbacks == 1: + warnings.warn( + f"{self.name}: batched copy failed ({type(e).__name__}: " f"{e}); falling back to jax.device_put per leaf.", + RuntimeWarning, + ) + for i in self._fast_pos: + out[i] = jax.device_put(leaves[i], self.dst[i]) + for i in self._slow_pos: + out[i] = jax.device_put(leaves[i], self.dst[i]) + return out + + def send(self, tree): + """Move one pytree across this boundary. Returns the same tree structure.""" + return jax.tree.unflatten(self.treedef, self.send_flat(self.treedef.flatten_up_to(tree))) + + def __repr__(self): + return ( + f"' + ) + + +# ------------------------------------------- multi-controller (one process per host) +def process_indices(sharding) -> frozenset: + """The processes that own `sharding`'s devices.""" + return frozenset(d.process_index for d in sharding.device_set) + + +def is_cross_process(src_sharding, dst_sharding) -> bool: + """Under multi-controller JAX: do the two shardings live on different + processes? (Always False in one process.)""" + return jax.process_count() > 1 and process_indices(src_sharding) != process_indices(dst_sharding) + + +def _global_index_values(sharding, shape): + """Per-device shard indices over ALL devices, in device-assignment order -- + `addressable_devices_indices_map` sees only this process's devices, which + for a cross-process boundary is one side or neither.""" + return tuple(sharding.devices_indices_map(tuple(shape)).values()) + + +class CrossProcessChannel: + """One stage boundary between stages that live on different processes. + + jax's cross-host copy (`batched_copy_array_to_devices_with_sharding` with + the shardings on different processes, jax/_src/dispatch.py) takes its + transfer keys from a counter that EVERY process advances on EVERY such call, + whether or not it sends or receives (pjrt_client.cc `CreateNewTransferKey`). + So every process issues every cross-process send, in the same order: one + that skips a send pairs every later transfer with the wrong one, silently + (verified on CPU, jax 0.11.1: a bystander that skips one copy makes its next + copy deliver the previous copy's array). `send_flat` takes the source + arrays where this process owns them and None elsewhere (a placeholder with + no local shards stands in); the destination stage's processes get its + array back, a process owning neither side an array with no local shards. + + Checked at build time, as jax does before taking that path + (`_is_supported_cross_host_transfer`): the same device kind and HLO sharding + on both sides, and -- the copy pairs shard k of the source with shard k of + the destination -- the same global per-device index map, with every pair on + two different processes (jax copies across processes only when every shard + crosses; a pair within one process would fail on that process alone, at + send time). A boundary that would reshard is rejected: jax refuses + cross-process reshards. + """ + + __slots__ = ( + "name", + "treedef", + "avals", + "src", + "dst", + "n_leaves", + "validate", + "owns_src", + "owns_dst", + "_dev_lists", + "_copy_semantics", + "_placeholders", + ) + + def __init__(self, avals, src_shardings, dst_shardings, name="xchannel", validate=True): + if not BATCHED_COPY_AVAILABLE: + raise RuntimeError(f"{name}: no batched_copy_array_to_devices_with_sharding in this jaxlib") + flat_avals, treedef = jax.tree.flatten(avals) + self.name, self.treedef, self.avals = name, treedef, tuple(flat_avals) + self.n_leaves = len(flat_avals) + self.validate = bool(validate) + bc = lambda s: [s] * self.n_leaves if isinstance(s, Sharding) else list(treedef.flatten_up_to(s)) + self.src, self.dst = bc(src_shardings), bc(dst_shardings) + pid = jax.process_index() + for i, (aval, s, d) in enumerate(zip(flat_avals, self.src, self.dst)): + where = f"{name}[leaf {i}]" + if not is_cross_process(s, d): + raise ValueError(f"{where}: source and destination are on the same processes; use Channel") + if _is_extended(aval.dtype): + raise ShardingMismatchError(f"{where}: extended dtype {aval.dtype} cannot be copied across processes") + kinds = {x.device_kind for x in s.device_set} | {x.device_kind for x in d.device_set} + if len(kinds) != 1: + raise ShardingMismatchError(f"{where}: device kinds differ across the boundary: {kinds}") + nd = len(aval.shape) + if s._to_xla_hlo_sharding(nd) != d._to_xla_hlo_sharding(nd): + raise ShardingMismatchError(f"{where}: HLO shardings differ ({s} vs {d}): the copy would reshard") + sv, dv = _global_index_values(s, aval.shape), _global_index_values(d, aval.shape) + if len(sv) != len(dv): + raise ShardingMismatchError( + f"{where}: device counts differ: {len(sv)} source devices, " f"{len(dv)} destination devices" + ) + if sv != dv: + bad = [(j, a, b) for j, (a, b) in enumerate(zip(sv, dv)) if a != b] + raise ShardingMismatchError( + f"{where}: per-device shard indices differ [i: src -> dst]: " + + ", ".join(f"{j}: {_fmt_index(a)} -> {_fmt_index(b)}" for j, a, b in bad[:4]) + ) + same = [ + j + for j, (x, y) in enumerate(zip(s._device_assignment, d._device_assignment)) + if x.process_index == y.process_index + ] + if same: + raise ShardingMismatchError( + f"{where}: shards {same[:4]} would stay on one process (process " + f"{s._device_assignment[same[0]].process_index}); jax copies across processes only when " + "every shard crosses" + ) + self.owns_src = [any(x.process_index == pid for x in s.device_set) for s in self.src] + self.owns_dst = [any(x.process_index == pid for x in d.device_set) for d in self.dst] + self._dev_lists = [d._internal_device_list for d in self.dst] + self._copy_semantics = [REUSE_INPUT] * self.n_leaves + self._placeholders = [None] * self.n_leaves + + def placeholder(self, i): + """The source of leaf i as a process that owns none of it passes it: the + global shape and sharding, no local shards.""" + if self._placeholders[i] is None: + a = self.avals[i] + self._placeholders[i] = jax.make_array_from_single_device_arrays(tuple(a.shape), self.src[i], [], dtype=a.dtype) + return self._placeholders[i] + + def send_flat(self, leaves): + """Every process, every call: leaves (arrays, or None where this process + owns no shard of the source) -> arrays on the destination stage.""" + srcs = [] + for i, x in enumerate(leaves): + if x is None: + if self.owns_src[i]: + raise ValueError( + f"{self.name}[leaf {i}]: this process owns shards of the source, so it must " "pass the array, not None" + ) + x = self.placeholder(i) + elif self.validate and ( + tuple(x.shape) != tuple(self.avals[i].shape) or x.dtype != self.avals[i].dtype or x.sharding != self.src[i] + ): + # the receiver allocates the declared aval: a mismatch would fail there, not here + raise ShardingMismatchError( + f"{self.name}[leaf {i}]: send() was handed a {x.dtype}{list(x.shape)} array sharded " + f"{x.sharding}, not the declared {self.avals[i].dtype}{list(self.avals[i].shape)} on " + f"{self.src[i]}" + ) + srcs.append(x) + out = _BATCHED_COPY(srcs, self._dev_lists, self.dst, self._copy_semantics) + return list(out) + + def send(self, tree): + return jax.tree.unflatten(self.treedef, self.send_flat(self.treedef.flatten_up_to(tree))) + + def __repr__(self): + return ( + f"" + ) + + +# (device, shard shape, dtype) -> the zero buffer PermuteChannel's destination +# side passes as its half of the program's input (`PermuteChannel._dummy`) +_PERMUTE_DUMMIES = {} + + +class PermuteChannel: + """One stage boundary as a collective-permute program over the union of + the two stages' devices: shard i of the source stage goes to device i of + the destination, over ICI inside one slice; between two slices (one stage + per slice: ds_ep_pipeline --layout slices) XLA makes it a send / recv over + DCN, the one cross-slice device copy known to work on TPU (at every size + tried, 2026-10; RelayChannel crosses slices through the hosts instead). + + The alternative to jax's cross-host copy where that does not work: on TPU + v6e and v5p (jax 0.11.1, libtpu 0.0.46) its native receive aborts the process + (std::bad_alloc; in EnqueueCrossHostReceive on v6e), and on v6e the DCN + socket path hangs. + The program runs on both stages' devices, so the two meet at it: the + source stage cannot run ahead of a destination still busy with earlier + work (an async copy could). + + The program's input is ONE array over the union mesh, replicated along its + leading axis: the source stage's devices hold the real shards (zero-copy + views of the source array), the destination's a dummy buffer each; the + body permutes along that axis, and the destination's output shards ARE its + stage array (again zero-copy). Under multi-controller JAX + (pathways.multi_controller) only the processes of the two stages call + `send_flat`, in the order every process walks, each with the shards it + holds; anyone else gets None back at once. In one controller -- a Pathways + client, one host's run -- both sides are this process's, and no process is + looked at. Same-shape meshes and identical specs on both sides (checked). + """ + + AXIS = "_xfer" + __slots__ = ( + "name", + "treedef", + "avals", + "src", + "dst", + "n_leaves", + "union", + "u_sh", + "prog", + "multi", + "owns_src", + "owns_dst", + "_dummies", + "_dst_devices", + ) + + def __init__(self, avals, src_shardings, dst_shardings, name="pchannel"): + import numpy as np + from jax import lax + from jax.sharding import Mesh, NamedSharding + + flat_avals, treedef = jax.tree.flatten(avals) + self.name, self.treedef, self.avals = name, treedef, tuple(flat_avals) + self.n_leaves = len(flat_avals) + bc = lambda s: [s] * self.n_leaves if isinstance(s, Sharding) else list(treedef.flatten_up_to(s)) + self.src, self.dst = bc(src_shardings), bc(dst_shardings) + ma, mb = self.src[0].mesh, self.dst[0].mesh + if ma.axis_names != mb.axis_names or ma.devices.shape != mb.devices.shape: + raise ShardingMismatchError(f"{name}: the stage meshes differ ({dict(ma.shape)} vs {dict(mb.shape)})") + if set(ma.device_ids.flat) & set(mb.device_ids.flat): + raise ValueError(f"{name}: the two stages share devices") + for i, (s, d) in enumerate(zip(self.src, self.dst)): + if s.mesh != ma or d.mesh != mb or s.spec != d.spec: + raise ShardingMismatchError( + f"{name}[leaf {i}]: want one mesh per side and the same spec on both " f"({s} vs {d})" + ) + self.union = Mesh(np.stack([ma.devices, mb.devices]), (self.AXIS,) + tuple(ma.axis_names)) + self.u_sh = [NamedSharding(self.union, s.spec) for s in self.src] + specs = tuple(s.spec for s in self.src) + ax = self.AXIS + + def body(*xs): + return tuple(lax.ppermute(x, ax, [(0, 1)]) for x in xs) + + sm = jax.shard_map(body, mesh=self.union, in_specs=specs, out_specs=specs, check_vma=False) + + def xfer(*xs): + return sm(*xs) + + xfer.__name__ = xfer.__qualname__ = "xfer_" + name.replace("->", "_to_").replace(" ", "_") + self.prog = jax.jit(xfer, in_shardings=tuple(self.u_sh), out_shardings=tuple(self.u_sh)) + self.multi = pathways.multi_controller() + if self.multi: # which sides' devices this process holds + pid = jax.process_index() + self.owns_src = any(x.process_index == pid for x in ma.devices.flat) + self.owns_dst = any(x.process_index == pid for x in mb.devices.flat) + else: # one controller: both + self.owns_src = self.owns_dst = True + self._dst_devices = frozenset(mb.devices.flat) + self._dummies = None + + def lower_args(self): + """Abstract arguments of `prog`, for ahead-of-time compiles.""" + return tuple(jax.ShapeDtypeStruct(a.shape, a.dtype, sharding=u) for a, u in zip(self.avals, self.u_sh)) + + def _dummy(self): + # The program never writes or donates its input, so one zero buffer per + # (device, shard shape, dtype) serves every channel into a stage. + import numpy as np + + if self._dummies is None: + devs = list(self.union.devices[1].flat) + if self.multi: # the destination's devices this process holds + pid = jax.process_index() + devs = [d for d in devs if d.process_index == pid] + + def zeros(shape, dtype, d): + key = (d, shape, np.dtype(dtype)) + if key not in _PERMUTE_DUMMIES: + _PERMUTE_DUMMIES[key] = jax.device_put(np.zeros(shape, dtype), d) + return _PERMUTE_DUMMIES[key] + + self._dummies = [ + [zeros(tuple(s.shard_shape(tuple(a.shape))), a.dtype, d) for d in devs] for a, s in zip(self.avals, self.dst) + ] + return self._dummies + + def send_flat(self, leaves): + """The two stages' processes, every boundary copy in order: leaves on the + source side (None on the destination's) -> the destination stage's arrays + there, None elsewhere (multi-controller JAX). In one controller: the + leaves -> the destination stage's arrays.""" + if self.multi and not (self.owns_src or self.owns_dst): + return [None] * self.n_leaves + ins = [] + for i, a in enumerate(self.avals): + shards = [] + if not self.multi or self.owns_src: + x = leaves[i] + if x is None or tuple(x.shape) != tuple(a.shape) or x.dtype != a.dtype or x.sharding != self.src[i]: + raise ShardingMismatchError( + f"{self.name}[leaf {i}]: the source side must pass the declared " + f"{a.dtype}{list(a.shape)} array on {self.src[i]}, got {x!r}"[:400] + ) + shards += [s.data for s in x.addressable_shards] + if not self.multi or self.owns_dst: + shards += self._dummy()[i] + ins.append(jax.make_array_from_single_device_arrays(tuple(a.shape), self.u_sh[i], shards)) + outs = self.prog(*ins) + if self.multi and not self.owns_dst: + return [None] * self.n_leaves + return [ + jax.make_array_from_single_device_arrays( + tuple(a.shape), d, [s.data for s in o.addressable_shards if s.device in self._dst_devices] + ) + for a, d, o in zip(self.avals, self.dst, outs) + ] + + def send(self, tree): + return jax.tree.unflatten(self.treedef, self.send_flat(self.treedef.flatten_up_to(tree))) + + def __repr__(self): + return f"" + + +def _host_ip(): + """This host's address peers can reach (the pod IP on GKE hostNetwork).""" + import socket + + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("10.255.255.255", 1)) # no packet is sent; picks the outgoing interface + return s.getsockname()[0] + except OSError: + return socket.gethostbyname(socket.gethostname()) + finally: + s.close() + + +class XferContext: + """This process's `jax.experimental.transfer` server, its peers' addresses + (published once through the coordination service's key-value store) and + its connections to them, shared by every XferChannel of the process. + + One per process: its address is published under a key of the process, so + get it with `xfer_context()` rather than constructing another.""" + + def __init__(self, n_transport=None, parallel_copies=None, transfer_size=None, timeout_s=1800): + if _XFER_CONTEXT is not None: + raise RuntimeError( + "this process already has an XferContext (its address is published once): " "use transfer.xfer_context()" + ) + # MPMD_XFER_TRANSPORTS / _COPIES / _CHUNK_MB tune the sockets (defaults measured on v6e-256: + # 8.95 GB/s per host for a 1 GiB boundary) + n_transport = n_transport or int(os.environ.get("MPMD_XFER_TRANSPORTS", "16")) + parallel_copies = parallel_copies or int(os.environ.get("MPMD_XFER_COPIES", "32")) + transfer_size = transfer_size or int(float(os.environ.get("MPMD_XFER_CHUNK_MB", "16")) * 2**20) + from jax.experimental import transfer as jxt + from jax._src import distributed + + self.jxt, self.timeout_ms = jxt, timeout_s * 1000 + self.client = distributed.global_state.client + ip = os.environ.get("MPMD_XFER_IP") or _host_ip() + backend = jax.local_devices()[0].client + # never an empty transport_addresses list: the sender CHECK-fails on one (jax 0.11.1) + self.srv = jxt.start_transfer_server( + backend, + f"{ip}:0", + [f"{ip}:0"] * n_transport, + max_num_parallel_copies=parallel_copies, + transfer_size=transfer_size, + ) + self.pid = jax.process_index() + self.client.key_value_set(f"mpmd/xfer_addr/{self.pid}", self.srv.address()) + self._conns = {} + + def conn(self, peer): + if peer not in self._conns: + addr = self.client.blocking_key_value_get(f"mpmd/xfer_addr/{peer}", self.timeout_ms) + self._conns[peer] = self.srv.connect(addr) + return self._conns[peer] + + +_XFER_CONTEXT = None + + +def xfer_context(**kw): + """This process's XferContext, started on first use (`kw` go to that first + construction; later calls return the same context).""" + global _XFER_CONTEXT + if _XFER_CONTEXT is None: + ctx = XferContext(**kw) + _XFER_CONTEXT = ctx + return _XFER_CONTEXT + + +# --------------------------- boundaries between hosts, shard k to device k (Xfer, Relay) +def _same_mesh_boundary(name, avals, src, dst, as_bytes=False): + """XferChannel's and RelayChannel's checks at build time: shard k of the + source stage goes to device k of the destination, so identical stage + meshes (axis names and shape), one mesh a side, the same spec on both + sides, and the same per-device index map -> the two meshes. `as_bytes` + (the relay, which sends a shard's bytes) also refuses extended dtypes.""" + ma, mb = src[0].mesh, dst[0].mesh + if ma.axis_names != mb.axis_names or ma.devices.shape != mb.devices.shape: + raise ShardingMismatchError(f"{name}: the stage meshes differ ({dict(ma.shape)} vs {dict(mb.shape)})") + for i, (aval, s, d) in enumerate(zip(avals, src, dst)): + if s.mesh != ma or d.mesh != mb or s.spec != d.spec: + raise ShardingMismatchError(f"{name}[leaf {i}]: want one mesh per side and the same spec on both") + if as_bytes and _is_extended(aval.dtype): + raise ShardingMismatchError(f"{name}[leaf {i}]: extended dtype {aval.dtype} cannot travel as bytes") + if _global_index_values(s, aval.shape) != _global_index_values(d, aval.shape): + raise ShardingMismatchError(f"{name}[leaf {i}]: per-device shard indices differ between the stages") + return ma, mb + + +def _check_sources(name, leaves, avals, src): + """XferChannel's and RelayChannel's source side, at each send: every leaf + the declared array -- its shape, its dtype, and its declared sharding or + one equivalent to it (the same devices holding the same slices, as + P('d') is to P('d', None)), since its shards are taken by device.""" + for i, (x, a, s) in enumerate(zip(leaves, avals, src)): + if ( + x is None + or tuple(x.shape) != tuple(a.shape) + or x.dtype != a.dtype + or (x.sharding != s and not _equivalent(x.sharding, s, len(a.shape))) + ): + raise ShardingMismatchError( + f"{name}[leaf {i}]: the source side must pass the declared " f"{a.dtype}{list(a.shape)} array on {s}" + ) + + +def _equivalent(a, b, ndim): + try: + return a.is_equivalent_to(b, ndim) + except Exception: # a sharding without the comparison: not proven equivalent + return False + + +def _host_routes(src_mesh, dst_mesh, pid, what): + """Shard k of the source stage goes from the process holding it to the + process holding device k of the destination -> for process `pid`, (the + destination's devices in mesh order, {destination process: the positions + `pid` sends there}, {source process: the positions `pid` fills from + there}). Raises ValueError for stages sharing devices, or a process + holding devices of both (`what` moves data between hosts only).""" + fa, fb = list(src_mesh.devices.flat), list(dst_mesh.devices.flat) + if set(fa) & set(fb): + raise ValueError("the two stages share devices") + sends, recvs = {}, {} + for k, (x, y) in enumerate(zip(fa, fb)): + if x.process_index == pid: + sends.setdefault(y.process_index, []).append(k) + if y.process_index == pid: + recvs.setdefault(x.process_index, []).append(k) + if sends and recvs: + raise ValueError( + f"process {pid} holds devices of both stages; {what} moves data between hosts " + "only (use Channel within a process)" + ) + return fb, sends, recvs + + +def xfer_peers(src_mesh, dst_mesh, pid): + """XferChannel's host pairing for process `pid` -> (source mesh positions + it offers, destination devices it receives on, the one process it pulls + from or None, the one process it gives to or None). Raises ValueError + where the boundary cannot be one host pair per host: a process holding + both sides, one taking its shards from several source hosts, or one + giving its shards to several destination hosts. A function of the meshes + and `pid` alone, so a check ahead of time can run it for every process.""" + fb, sends, recvs = _host_routes(src_mesh, dst_mesh, pid, "XferChannel") + if len(recvs) > 1: + raise ValueError( + f"process {pid} would receive from processes {sorted(recvs)}; each host must take all " + "its shards from one source host" + ) + if len(sends) > 1: + raise ValueError( + f"process {pid} would send to processes {sorted(sends)}; each host must give all its " + "shards to one destination host" + ) + src_pos = sorted(k for ks in sends.values() for k in ks) + dst_pos = sorted(k for ks in recvs.values() for k in ks) + return src_pos, [fb[k] for k in dst_pos], next(iter(recvs), None), next(iter(sends), None) + + +class XferChannel: + """One stage boundary over `jax.experimental.transfer` (DCN sockets): + each source host offers its local shards under a uuid (`await_pull`), and + the destination host holding the same mesh positions pulls them -- matched + by the uuid, not by call order, so only the two hosts of each pair take + part, and the copy is asynchronous on both sides (neither stage waits for + the other at the boundary, unlike PermuteChannel). + + The uuid is the channel's index and a per-channel sequence number both + sides advance on every send, in the order every process walks. Shards + travel as single-device arrays sorted by mesh position; the receiver + reassembles its stage array zero-copy. Requires identical stage meshes + (axis names, shape, specs, so shard k is the same slice on both sides) and + every destination host's devices taking their shards from ONE source host + (`xfer_peers`), checked at build time. + + The source returns as soon as its offer is queued and the peer pulls it + later, from the same buffers: never donate or delete a sent array (drop the + reference instead; the transfer server keeps the buffers until pulled). + """ + + __slots__ = ( + "name", + "idx", + "treedef", + "avals", + "src", + "dst", + "n_leaves", + "ctx", + "seq", + "owns_src", + "owns_dst", + "peer", + "_src_pos", + "_dst_devs", + "_pull_avals", + ) + + def __init__(self, avals, src_shardings, dst_shardings, ctx, idx, name="xchannel"): + flat_avals, treedef = jax.tree.flatten(avals) + self.name, self.idx, self.ctx, self.seq = name, idx, ctx, 0 + self.treedef, self.avals, self.n_leaves = treedef, tuple(flat_avals), len(flat_avals) + bc = lambda s: [s] * self.n_leaves if isinstance(s, Sharding) else list(treedef.flatten_up_to(s)) + self.src, self.dst = bc(src_shardings), bc(dst_shardings) + ma, mb = _same_mesh_boundary(name, flat_avals, self.src, self.dst) + pid = jax.process_index() + try: + self._src_pos, self._dst_devs, self.peer, _ = xfer_peers(ma, mb, pid) + except ValueError as e: + raise ValueError(f"{name}: {e}") from None + self.owns_src, self.owns_dst = bool(self._src_pos), bool(self._dst_devs) + from jax.sharding import SingleDeviceSharding + + self._pull_avals = [ + jax.ShapeDtypeStruct(d.shard_shape(tuple(a.shape)), a.dtype, sharding=SingleDeviceSharding(dev)) + for a, d in zip(self.avals, self.dst) + for dev in self._dst_devs + ] + + def send_flat(self, leaves): + """Every process, every boundary copy in order (the two stages' hosts + act; the rest only return None): source arrays where owned -> the + destination stage's arrays there, None elsewhere.""" + if not (self.owns_src or self.owns_dst): + return [None] * self.n_leaves + uuid = (self.idx << 40) | self.seq + if self.owns_src: + _check_sources(self.name, leaves, self.avals, self.src) + flat = [] + for i, x in enumerate(leaves): + by_dev = {s.device: s.data for s in x.addressable_shards} + flat += [by_dev[dev] for dev in (list(self.src[i].mesh.devices.flat)[k] for k in self._src_pos)] + self.seq += 1 # only a send that goes out advances the sequence both sides keep + self.ctx.srv.await_pull(uuid, flat) + return [None] * self.n_leaves + self.seq += 1 + got = self.ctx.conn(self.peer).pull(uuid, self._pull_avals) + nd, out = len(self._dst_devs), [] + for i, (a, d) in enumerate(zip(self.avals, self.dst)): + out.append(jax.make_array_from_single_device_arrays(tuple(a.shape), d, list(got[i * nd : (i + 1) * nd]))) + return out + + def send(self, tree): + return jax.tree.unflatten(self.treedef, self.send_flat(self.treedef.flatten_up_to(tree))) + + def __repr__(self): + return f"" + + +# ---------------------------------------------------------------- host relay +# Across MegaScale slices libtpu's cross-host paths fail: jax's copy hangs, +# jax.experimental.transfer's receiver aborts on about the 8th pull, and the +# collective-permute that works is a rendezvous coupling the two stages' +# queues. The relay leaves the bytes to the hosts: device-to-host copy, +# TCP between the two hosts, host-to-device copy, each end in threads of its +# own. Every message is a fixed header, then `length` bytes: +# DATA bytes [offset, offset + length) of shard (leaf, mesh position) of +# receive (channel id, sequence number); `total` is the shard's size +# and `sig` a CRC of its dtype and shape; +# HELLO opens a stream: channel id = the sender's process, seq = the +# stream's index, total = its number of streams, sig = a CRC of the +# context's key; the receiving context's token follows (random per +# context, published with its address). A connection that does not +# open with these within _RELAY_HELLO_S is refused; +# ERROR the sender could not make the send (channel id, seq); the reason +# follows as text; +# ABORT the sender gives up on this process before all its streams are +# open, so the rest never come: every receive still missing its +# shards fails. The reason follows as text. +_RELAY_MAGIC = b"MRL1" +_RELAY_HDR = struct.Struct("<4sB3xIQIIQQQI") # magic kind | cid seq leaf pos offset length total sig +_DATA, _HELLO, _ERROR, _ABORT = 0, 1, 2, 3 +_RELAY_TEXT_MAX = 1 << 16 # an ERROR's or ABORT's reason, at most +_RELAY_HELLO_S = 60.0 # a new connection's HELLO must come within (at most the timeout) +# This process's RelayContexts without a key of their own, in creation order: the n-th publishes +# under mpmd/relay/. A context takes its number under the lock, once its address is published. +_relay_lock = threading.Lock() +_relay_contexts = 0 +# RelayContext.timing's measures, in seconds: a sample per shard sent +# (send_*), per receive completed (recv_wire, recv_dispatch), and per +# receive its consumer resolved (recv_wait). None of them holds a receive's +# host-to-device copies: each is issued (jax.device_put returns before the +# copy is done, on TPU) and runs on asynchronously, and the consumer's +# program waits for it on the device. A context counts, sums and takes the +# largest of every sample since its last reset, and keeps the newest +# _RELAY_SAMPLES of each per channel for the percentiles: at 64 +# microbatches of 4 shards, the last 64 steps. +RELAY_MEASURES = { + "send_host": "a shard queued -> on the host: the wait for its producing program (and for the shards " + "queued to that peer before it), then its device-to-host copy", + "send_wire": "on the host -> its last chunk written to a socket", + "recv_wire": "a receive's first chunk in -> its last byte in", + "recv_dispatch": "its last byte in -> its arrays assembled: its last host-to-device copy issued (each " + "shard's is at its own last byte), not waited for", + "recv_wait": "how long its consumer blocked in RelayFuture.result(): 0 when its arrays were assembled, " + "their host-to-device copies perhaps still running", +} +_RELAY_SAMPLES = 1 << 14 +_RELAY_POOL = 4 # receive buffers a context keeps per (channel, leaf, mesh position) +# The relay's three data-moving steps as profiler events, so a trace shows them by name (a trace's +# boundary time can be measured off them): a chunk written to its socket, a chunk's payload read off its +# socket, a completed shard's host-to-device copy issued (the copy itself runs on after the event). +# A TraceAnnotation costs 0.3-0.5 us when no profile is being taken, against about a millisecond a +# 4 MiB chunk spends on the wire. +RELAY_TRACE = {"send": "relay_send", "recv": "relay_recv", "place": "relay_place"} + + +class RelayError(RuntimeError): + """A relay transfer failed: a stream broke or carried a malformed message, + the sending process could not make the send, or a peer closed its streams + (or gave up opening them) with shards of a receive still unsent.""" + + +class RelayTimeoutError(RelayError, TimeoutError): + """A relay receive was not complete after MPMD_RELAY_TIMEOUT seconds.""" + + +def relay_routes(src_mesh, dst_mesh, pid): + """RelayChannel's routes for process `pid` -> ({destination process: the + mesh positions whose source shards `pid` sends there}, {source process: the + mesh positions whose destination devices `pid` fills from there}). Shard k + of the source stage goes to device k of the destination, from the process + holding the one to the process holding the other: any number of peers each + way (unlike `xfer_peers`). Raises ValueError for stages sharing devices, + or a process holding devices of both (a copy within one process is a + Channel's). A function of the meshes and `pid` alone.""" + _, sends, recvs = _host_routes(src_mesh, dst_mesh, pid, "RelayChannel") + return sends, recvs + + +def _relay_sig(dtype, shape): + return zlib.crc32(f"{np.dtype(dtype).name}{list(shape)}".encode()) + + +def _relay_setting(arg, name, default): + """A RelayContext setting: `arg` unless None, else environment variable + `name` unless unset or blank, else `default` -- so that 0 means the same + given either way (RelayContext refuses what it cannot run with).""" + if arg is not None: + return arg + v = os.environ.get(name, "").strip() + return v if v else default + + +def _host_view(x): + """Whether np.asarray(x), x a jax array, views its device buffer (CPU) + rather than copying it to host memory (TPU, GPU).""" + try: + return all(d.platform == "cpu" for d in x.devices()) + except AttributeError: + return True + + +def host_net_settings(): + """This host's settings the relay's throughput depends on, as the kernel + prints them (None where unreadable): transparent huge pages (a receive + buffer not taken from the pool is fresh memory) and the TCP buffer limits + (autotuning grows a socket's buffers up to tcp_[rw]mem's last field; an + explicit MPMD_RELAY_SOCKBUF_MB is capped at [rw]mem_max).""" + + def read(path): + try: + with open(path) as f: + return " ".join(f.read().split()) + except OSError: + return None + + return { + "thp": read("/sys/kernel/mm/transparent_hugepage/enabled"), + "tcp_rmem": read("/proc/sys/net/ipv4/tcp_rmem"), + "tcp_wmem": read("/proc/sys/net/ipv4/tcp_wmem"), + "rmem_max": read("/proc/sys/net/core/rmem_max"), + "wmem_max": read("/proc/sys/net/core/wmem_max"), + } + + +def _relay_socket(sockbuf): + """A TCP socket with Nagle off, and SO_SNDBUF / SO_RCVBUF of `sockbuf` bytes + if asked (0: left to the kernel). An explicit size switches the kernel's + autotuning off and is capped at net.core.[rw]mem_max unless the process may + force it: on the TPU VM this was written on that cap is 212992 bytes while + autotuning grows a receive buffer to tcp_rmem's 300 MB, so the default + leaves it alone.""" + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + if sockbuf: + force = (32, 33) if sys.platform.startswith("linux") else (None, None) # SO_{SND,RCV}BUFFORCE + for opt, f in zip((socket.SO_SNDBUF, socket.SO_RCVBUF), force): + try: + if f is None: + raise OSError + s.setsockopt(socket.SOL_SOCKET, f, sockbuf) + except OSError: # not privileged: the capped request + s.setsockopt(socket.SOL_SOCKET, opt, sockbuf) + return s + + +def _relay_connect(addr, sockbuf, timeout_s): + """A stream to a peer's listener (retrying a refusal for up to a minute), + left BLOCKING -- one sendmsg per chunk, the GIL released for all of it -- + with the kernel's SO_SNDTIMEO bounding a peer that stops reading.""" + deadline = time.monotonic() + min(timeout_s, 60.0) + while True: + s = _relay_socket(sockbuf) + s.settimeout(10.0) + try: + s.connect(addr) + break + except OSError: + s.close() + if time.monotonic() > deadline: + raise + time.sleep(0.1) + s.settimeout(None) + s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("ll", int(timeout_s), int(timeout_s % 1 * 1e6))) + return s + + +def _send_all(sock, *bufs): + """Write every byte of `bufs`, in order (a blocking socket takes a whole + sendmsg at once unless interrupted).""" + views = [v for v in (memoryview(b).cast("B") for b in bufs) if v.nbytes] + while views: + n = sock.sendmsg(views) + while n: + if n >= views[0].nbytes: + n -= views.pop(0).nbytes + else: + views[0], n = views[0][n:], 0 + + +def _recv_exact(sock, buf, eof_ok=False): + """Fill `buf` from `sock` (MSG_WAITALL: one syscall, and one GIL release, + per chunk). -> False if the stream ended before its first byte and + `eof_ok`; an end anywhere else is a RelayError.""" + view = memoryview(buf).cast("B") + n, got = view.nbytes, 0 + while got < n: + k = sock.recv_into(view[got:], n - got, socket.MSG_WAITALL) + if not k: + if got == 0 and eof_ok: + return False + raise RelayError(f"the stream ended {got} bytes into a {n}-byte read") + got += k + return True + + +def _relay_text(kind, cid, seq, leaf, pos, text): + """An ERROR or ABORT message: its header and its reason (cut short).""" + msg = text.encode(errors="replace")[:_RELAY_TEXT_MAX] + return _RELAY_HDR.pack(_RELAY_MAGIC, kind, cid, seq, leaf, pos, 0, len(msg), 0, 0), memoryview(msg) + + +def _take_span(spans, lo, hi): + """Add bytes [lo, hi), lo < hi, to `spans` -- a sorted list of disjoint + (start, end) runs, merged where they meet -> False, leaving it as it was, + if they overlap a run already there.""" + i = bisect.bisect_left(spans, (lo, lo)) # the first run starting at lo or later + if (i and spans[i - 1][1] > lo) or (i < len(spans) and spans[i][0] < hi): + return False + if i < len(spans) and spans[i][0] == hi: + hi = spans.pop(i)[1] + if i and spans[i - 1][1] == lo: + i -= 1 + lo = spans.pop(i)[0] + spans.insert(i, (lo, hi)) + return True + + +def _refs(lst, i): + return sys.getrefcount(lst[i]) + + +_ONLY_LISTED = _refs([object()], 0) # `_refs` of an object nothing but its list holds + + +class _RelayRecv: + """One receive of a RelayChannel on this process (its index and sequence + number): the shards arrived so far, each straight into its buffer and, at + its last byte, onto its destination device (`placed`); then the + destination arrays, or the error its RelayFutures raise. `spans`: per + shard, the byte ranges taken by chunks in or coming in, as disjoint runs + (`_take_span`); `got`, how many of those bytes are in. `claimed`: the + channel's send_flat has handed out its futures (data may come first). + t_first / t_last: when its first chunk and its last byte came in; + `waited`: its consumer's wait is counted (RelayContext.timing).""" + + __slots__ = ( + "ch", + "seq", + "bufs", + "spans", + "got", + "done", + "placed", + "claimed", + "event", + "out", + "err", + "t_first", + "t_last", + "waited", + ) + + def __init__(self, ch, seq): + self.ch, self.seq = ch, seq + self.bufs, self.spans, self.got, self.done, self.placed = {}, {}, {}, set(), {} + self.claimed = self.waited = False + self.event, self.out, self.err = threading.Event(), None, None + self.t_first = self.t_last = None + + def what(self): + return f"{self.ch.name} (relay channel #{self.ch.idx}) seq {self.seq}" + + def missing(self): + """{source process: how many of its shards of this receive are not in}.""" + out = {} + for key, (_, _, q) in self.ch._recv_spec.items(): + if key not in self.done: + out[q] = out.get(q, 0) + 1 + return out + + +class RelayFuture: + """Leaf `i` of a relay receive, which reader threads complete. + `result()` waits for it -- MPMD_RELAY_TIMEOUT seconds unless told + otherwise, then RelayTimeoutError naming the channel, the sequence number + and the processes whose shards are missing -- and returns the destination + array, or raises what failed the receive. `resolve` is what a consumer + calls on whatever a boundary handed it; how long the first leaf resolved + kept it waiting goes into the context's timing (recv_wait).""" + + __slots__ = ("_r", "_i") + + def __init__(self, r, i): + self._r, self._i = r, i + + def done(self): + return self._r.event.is_set() + + def result(self, timeout=None): + r = self._r + ctx = r.ch.ctx + timeout = ctx.timeout_s if timeout is None else timeout + t0 = time.monotonic() + if not r.event.wait(timeout): + with ctx._lock: + miss, need = r.missing(), len(r.ch._recv_spec) + if not miss: + raise RelayTimeoutError(f"{r.what()}: all {need} shards in after {timeout:g} s, not yet all on their " "devices") + raise RelayTimeoutError( + f"{r.what()}: {need - sum(miss.values())} of {need} shards in after {timeout:g} s, waiting on " + + ", ".join(f'process {q} ({n} shard{"s" if n > 1 else ""})' for q, n in sorted(miss.items())) + ) + if r.err is not None: + raise r.err.with_traceback(None) # one error object, raised by every future of it + if not r.waited: + r.waited = True + ctx._note("recv_wait", r.ch.name, time.monotonic() - t0) + return r.out[self._i] + + def __repr__(self): + return f'' + + +def resolve(x): + """`x` itself, or -- a RelayFuture -- the array it stands for, blocking + until it has arrived.""" + return x.result() if type(x) is RelayFuture else x + + +class _RelayUnsent: + """A send this process does not make (`RelayContext._send`: an earlier + one failed), queued for a peer in place of its shards: the peer gets an + ERROR for it, in order behind what was queued there before.""" + + __slots__ = ("cid", "seq", "why") + + def __init__(self, cid, seq, why): + self.cid, self.seq, self.why = cid, seq, why + + +class _RelayPeer: + """A RelayContext's streams to one destination process and the threads + feeding them: a stager that takes the queued shards in order, waits for + each one's device-to-host copy and cuts it into chunks (zero-copy views), + and one writer per stream sending whichever chunk is next, so one shard + spreads over every stream. `pending` counts the shards and chunks not yet + written, for `flush`. A failed stream fails them all: the stager and the + writers then only drain, every stream is shut (the peer sees them end and + fails whatever it still expects from here), and this process's next send + raises, once it has told its destinations it is not coming + (`RelayContext._send`). If the streams do not all open, the ones that did + carry an ABORT before they end: the peer counts a sender gone only once + every stream its HELLO announced has ended.""" + + def __init__(self, ctx, pid): + self.ctx, self.pid = ctx, pid + self.items = queue.SimpleQueue() + self.chunks = queue.Queue(maxsize=4 * ctx.streams) # bounds the host memory staged ahead + self.cv = threading.Condition() + self.pending, self.sent, self.failed = 0, 0, None + self.socks, self.writers = [], [] + self.stager = threading.Thread(target=self._stage, name=f"relay-stage-p{pid}", daemon=True) + self.stager.start() + + def put(self, item): + with self.cv: + self.pending += 1 + self.items.put(item) + + def _done(self, n=1, nbytes=0, rec=None): + """`n` shards or chunks are off the queue, `nbytes` of them written; a + written chunk's `rec` is its shard's [chunks unwritten, when it reached + the host, channel name]: the last one notes send_wire, before a flush + can see the shard written.""" + with self.cv: + self.pending -= n + self.sent += nbytes + if rec is not None: + rec[0] -= 1 + if not rec[0]: + self.ctx._note("send_wire", rec[2], time.monotonic() - rec[1]) + if not self.pending: + self.cv.notify_all() + + def _fail(self, e): + err = e if isinstance(e, RelayError) else RelayError(f"relay to process {self.pid}: {type(e).__name__}: {e}") + with self.cv: + first = self.failed is None + if first: + self.failed = err + self.cv.notify_all() + if first: + self.ctx._sender_failed(err) + self._shut() + + def abort(self, err): + """close() at its deadline with this peer's threads still at work (a + peer that stopped reading, say): shut the streams, so that the writers + stop at once, the stager only drains, and the peer sees the streams + end -- unlike `_fail`, without failing this process's sends.""" + with self.cv: + if self.failed is None: + self.failed = err + self.cv.notify_all() + self._shut() + + def _shut(self): + for s in list(self.socks): + try: + s.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + def _connect(self): + ctx = self.ctx + addr, token = ctx.kv.blocking_key_value_get(f"{ctx.key}/addr/{self.pid}", int(ctx.timeout_s * 1000)).split() + host, port = addr.rsplit(":", 1) + token = bytes.fromhex(token) # the peer's: each HELLO carries it + for i in range(ctx.streams): + s = _relay_connect((host, int(port)), ctx.sockbuf, ctx.timeout_s) + self.socks.append(s) + _send_all( + s, _RELAY_HDR.pack(_RELAY_MAGIC, _HELLO, ctx.pid, i, 0, 0, 0, len(token), ctx.streams, ctx._key_sig), token + ) + for i, s in enumerate(self.socks): + t = threading.Thread(target=self._write, args=(s,), name=f"relay-write-p{self.pid}-{i}", daemon=True) + t.start() + # listed once started, as _accept does its readers: close() may `join` meanwhile, and a thread not + # yet started cannot be joined + with self.cv: + self.writers.append(t) + + def _stage(self): + try: + self._connect() + except BaseException as e: # the peer never published, or never accepted + err = RelayError(f"relay to process {self.pid}: connecting failed: {type(e).__name__}: {e}") + self.ctx._sender_failed(err) # this process's next send raises, before the peer hears + # With fewer streams than its HELLO announced ever ending, the peer would never count this + # process gone, and would wait out its timeout: an ABORT on each stream that did open. + for s in self.socks: + try: + _send_all(s, *_relay_text(_ABORT, self.ctx.pid, 0, 0, 0, str(err))) + except OSError: + pass + self._fail(err) + for s in self.socks: # no writer was started + s.close() + while self._cut_next(): + pass + for _ in self.writers: + self.chunks.put(None) + + def _cut_next(self): + """The stager, the next queued shard (-> False at the end): wait for its + copy to host, then queue its chunks for the writers -- or tell the peer + it cannot come. Its own frame holds the shard, so that it can let go.""" + item = self.items.get() + if item is None: + return False + if self.failed is not None: + self._done() + return True + if type(item) is _RelayUnsent: # a send not made: the peer's receive of it fails at once + self.chunks.put((*_relay_text(_ERROR, item.cid, item.seq, 0, 0, item.why), None, None)) + return True + cid, seq, leaf, pos, data, nbytes, sig, name, t_queued = item + del item + try: + host = np.asarray(data) # waits for the producing program and the copy to host + flat = memoryview(host.reshape(-1).view(np.uint8)) + if flat.nbytes != nbytes: + raise RelayError(f"the shard has {flat.nbytes} bytes, the channel declared {nbytes}") + except BaseException as e: + # The program that produced it failed, most likely: tell the peer, whose receive fails at + # once instead of timing out, and fail this process's next send. + why = f"{type(e).__name__}: {e}" + self.ctx._sender_failed(RelayError(f"{name} seq {seq}: could not send to process {self.pid}: {why}")) + self.chunks.put((*_relay_text(_ERROR, cid, seq, leaf, pos, why), None, None)) + return True + t_host = time.monotonic() + self.ctx._note("send_host", name, t_host - t_queued) + # On CPU `host` views the device buffer, so `data` rides along with the chunks; anywhere + # else `host` is a copy, and letting go of `data` now frees the device buffer as soon as + # the pipeline drops the array too, not once the last chunk is written. + keep = data if _host_view(data) else None + del data + n = max(1, -(-nbytes // self.ctx.chunk)) + rec = [n, t_host, name] + with self.cv: + self.pending += n - 1 + for j in range(n): + off = j * self.ctx.chunk + ln = min(self.ctx.chunk, nbytes - off) + self.chunks.put( + ( + _RELAY_HDR.pack(_RELAY_MAGIC, _DATA, cid, seq, leaf, pos, off, ln, nbytes, sig), + flat[off : off + ln], + keep, + rec, + ) + ) + return True + + def _write(self, s): + while True: + c = self.chunks.get() + if c is None: + break + hdr, payload, keep, rec = c + del c + ok = self.failed is None + if ok: + try: + with jax.profiler.TraceAnnotation(RELAY_TRACE["send"], bytes=payload.nbytes): + _send_all(s, hdr, payload) + except BlockingIOError: # SO_SNDTIMEO: the peer's reader no longer drains + ok = False + self._fail( + RelayError( + f"relay to process {self.pid}: no progress in {self.ctx.timeout_s:g} s " + "(MPMD_RELAY_TIMEOUT): the peer stopped reading" + ) + ) + except BaseException as e: + ok = False + self._fail(e) + self._done(1, payload.nbytes if ok else 0, rec if ok else None) + del payload, keep, rec # a written chunk holds nothing until the next one + try: + s.shutdown(socket.SHUT_WR) # the peer's reader sees the stream end between messages + except OSError: + pass + s.close() + + def flush(self, timeout): + """Wait until everything queued is written -> True, or False (timeout, failure).""" + with self.cv: + return self.cv.wait_for(lambda: not self.pending or self.failed is not None, timeout) and self.failed is None + + def stop(self): + self.items.put(None) + + def join(self, deadline): + """Wait until `deadline` for the stager, then for the writers it started + (every one of them, once the stager has ended).""" + self.stager.join(max(0.0, deadline - time.monotonic())) + with self.cv: + writers = list(self.writers) + for t in writers: + t.join(max(0.0, deadline - time.monotonic())) + + def running(self): + """The names of this peer's threads still running.""" + with self.cv: + return [t.name for t in (self.stager, *self.writers) if t.is_alive()] + + +class RelayContext: + """This process's end of the host relay its RelayChannels move boundaries + over. A TCP listener on the address (MPMD_RELAY_IP, which must be one of + this host's, or the host's primary IPv4, and MPMD_RELAY_PORT or a free + port) that the process publishes once through the coordination service's + key-value store, as XferContext does -- with a random token, which every + stream's HELLO must carry. Per peer it sends to, MPMD_RELAY_STREAMS + connections (default 8), opened at the first send and fed by threads of + their own (`_RelayPeer`, chunks of MPMD_RELAY_CHUNK_MB, default 4); per + accepted connection, a reader thread that receives each chunk straight + into its shard's buffer, puts a shard on its local destination device at + its last byte, and completes a receive's futures once all its shards are + there. Sequence numbers, sizes and dtype/shape CRCs are checked on + arrival; a malformed or broken stream fails every receive outstanding, a + peer whose streams all end (or that gave up opening them) fails those + still missing its shards. On the sending side a send that fails (a + broken stream, a shard that never reached the host) makes every later one + raise, each after an ERROR to its destinations, whose receives then fail + at once. MPMD_RELAY_SOCKBUF_MB (default 0, the kernel's autotuning) sizes + the socket buffers; MPMD_RELAY_TIMEOUT (default 1800 s) bounds a wait for + a receive, an address, a stuck peer. `timing()` says where the time went + (RELAY_MEASURES), `describe()` what the settings are. + + One per Pipeline. Every process creates its contexts in the same order, + so the n-th of each publishes and looks up under one key (mpmd/relay/, + or `key`; one that fails to start takes no number, and shuts its + listener). `kv` (default jax.distributed's client) and `pid` (default + jax.process_index()) are there for tests in one process. `close()` + flushes and shuts the sockets and threads down.""" + + def __init__( + self, kv=None, pid=None, key=None, ip=None, port=None, streams=None, chunk_mb=None, timeout_s=None, sockbuf_mb=None + ): + env = os.environ.get + if kv is None: + from jax._src import distributed + + kv = distributed.global_state.client + if kv is None: + raise RuntimeError( + "RelayContext: jax.distributed is not initialized (peers find this process " "through its key-value store)" + ) + self.kv = kv + self.pid = jax.process_index() if pid is None else int(pid) + streams = int(_relay_setting(streams, "MPMD_RELAY_STREAMS", 8)) + chunk_mb = float(_relay_setting(chunk_mb, "MPMD_RELAY_CHUNK_MB", 4)) + timeout_s = float(_relay_setting(timeout_s, "MPMD_RELAY_TIMEOUT", 1800)) + sockbuf_mb = float(_relay_setting(sockbuf_mb, "MPMD_RELAY_SOCKBUF_MB", 0)) + for bad, what in ( + (streams < 1, f"{streams} streams per peer (MPMD_RELAY_STREAMS): want at least 1"), + (int(chunk_mb * 2**20) < 1, f"{chunk_mb:g} MiB chunks (MPMD_RELAY_CHUNK_MB): want at least a byte"), + (not timeout_s > 0, f"a {timeout_s:g} s timeout (MPMD_RELAY_TIMEOUT): want more than 0"), + ( + not sockbuf_mb >= 0, + f"{sockbuf_mb:g} MiB socket buffers (MPMD_RELAY_SOCKBUF_MB): want 0 (the " "kernel's autotuning) or more", + ), + ): + if bad: # before anything is bound or started + raise ValueError(f"RelayContext: {what}") + self.streams, self.chunk, self.timeout_s = streams, int(chunk_mb * 2**20), timeout_s + self.sockbuf = int(sockbuf_mb * 2**20) + self._lock = threading.Lock() + self._cv = threading.Condition(self._lock) + self._channels, self._recvs, self._floor, self._retired = {}, {}, {}, {} + self._dead = set() # (channel, seq) failed: whatever of it still comes is drained + self._pool = {} # (channel, leaf, mesh position) -> its receive buffers (`_buffer`) + self._peers, self._streams_from, self._gone, self._gone_why, self._readers = {}, {}, set(), {}, [] + self._fatal = self._send_err = None + self._closing = self._closed = False + self.received = 0 + self._tlock = threading.Lock() # the timing samples' own: never held while taking another + self._times = {} # (measure, channel name) -> [samples, their sum, their largest, + # the newest _RELAY_SAMPLES of them], in seconds + self._listener = None + # A stream's HELLO must carry it: the peers read it with the address, from the key-value store, + # so a connection from anywhere else -- another job, a port scan -- is refused. + self._token = secrets.token_bytes(16) + global _relay_contexts + with _relay_lock: # a number is used up only once this context has published under it + self.key = key or f"mpmd/relay/{_relay_contexts}" + self._key_sig = zlib.crc32(self.key.encode()) + self._lsock = _relay_socket(self.sockbuf) # accepted streams inherit its buffer sizes + try: + self._lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + host = ip or env("MPMD_RELAY_IP") or _host_ip() + self._lsock.bind((host, int(port if port is not None else env("MPMD_RELAY_PORT") or 0))) + self._lsock.listen(256) + self.address = f"{host}:{self._lsock.getsockname()[1]}" + self._listener = threading.Thread(target=self._accept, name="relay-listen", daemon=True) + self._listener.start() + kv.key_value_set(f"{self.key}/addr/{self.pid}", f"{self.address} {self._token.hex()}") + except BaseException: # nobody could close this context: shut its listener here + self._closing = self._closed = True + try: + self._lsock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + self._lsock.close() + if self._listener is not None: + self._listener.join(1.0) + raise + if key is None: + _relay_contexts += 1 + + # ------------------------------------------------ the channels' side + def register(self, ch): + """RelayChannel's constructor: the receives of channel `ch.idx` are its.""" + with self._cv: + if not 0 <= ch.idx < 2**32: + raise ValueError(f"{ch.name}: relay channel id {ch.idx} is not a uint32") + if ch.idx in self._channels: + raise ValueError(f"{ch.name}: relay channel id {ch.idx} is taken by {self._channels[ch.idx].name}") + self._channels[ch.idx] = ch + self._cv.notify_all() + + def check(self): + """Raise if this context is closed: it sends nothing more (its peers see + its streams end). A send that failed fails the next one in `_send`.""" + if self._closing or self._closed: + raise RelayError(f"relay context {self.key} (process {self.pid}) is closed") + + def _send(self, ch, seq, leaves): + """The source side of send `seq` of `ch`: each shard's copy to host + starts now, and it is queued for the peer holding its destination. Once + a send of this context has failed, none is made: each destination of + this one gets an ERROR for it instead, in order behind what was queued + for it -- so that its receive fails at once rather than wait out + MPMD_RELAY_TIMEOUT, and the numbers both sides keep stay in step -- and + it raises what failed.""" + err = self._send_err + if err is not None: + for q, _ in ch._send_items: + self._peer(q).put(_RelayUnsent(ch.idx, seq, f"an earlier send failed ({err})")) + raise err.with_traceback(None) + t = time.monotonic() + by_dev = [{s.device: s.data for s in x.addressable_shards} for x in leaves] + for q, items in ch._send_items: + p = self._peer(q) + for i, k, dev in items: + d = by_dev[i][dev] + d.copy_to_host_async() + p.put((ch.idx, seq, i, k, d, ch._nbytes[i], ch._sigs[i], ch.name, t)) + + def _peer(self, q): + with self._lock: + if q not in self._peers: + self._peers[q] = _RelayPeer(self, q) + return self._peers[q] + + def _sender_failed(self, err): + with self._lock: + if self._send_err is None: + self._send_err = err + + def _claim(self, ch, seq): + """The destination side of send `seq` of `ch` -> its _RelayRecv (made + here, or by its first chunk), failed at once if it cannot complete.""" + with self._lock: + r = self._recvs.get((ch.idx, seq)) + if r is None: + r = self._recvs[(ch.idx, seq)] = _RelayRecv(ch, seq) + r.claimed = True + if not r.event.is_set(): + if self._fatal is not None: + self._fail_recv(r, self._fatal) + elif self._closing: + self._fail_recv(r, RelayError(f"{r.what()}: relay context {self.key} (process {self.pid}) is " "closed")) + else: + gone = sorted(q for q in r.missing() if q in self._gone) + if gone: + why = "".join(f"; process {q}: {self._gone_why[q]}" for q in gone if q in self._gone_why) + self._fail_recv( + r, + RelayError( + f"{r.what()}: process(es) {gone} closed their relay streams " f"with shards of it unsent{why}" + ), + ) + if r.event.is_set(): + self._retire(r) + return r + + # ---------------------------------------------------- the reader side + def _accept(self): + while True: + try: + conn, _ = self._lsock.accept() + except OSError as e: + if self._closing: + return # close() shut the listener down + # EMFILE, ENOBUFS, ECONNABORTED...: a listener that stopped here would leave every stream + # still to come unread, its writers and this process's receives waiting out their timeout + warnings.warn(f"relay listener {self.address}: accept failed ({type(e).__name__}: {e}); retrying", RuntimeWarning) + time.sleep(0.1) + continue + conn.settimeout(min(self.timeout_s, _RELAY_HELLO_S)) # until its HELLO is in (`_hello`) + conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + t = threading.Thread(target=self._read, args=(conn,), name="relay-read", daemon=True) + with self._lock: + if self._closing: + conn.close() + continue + # started under the lock, since close() joins what it finds in _readers and a thread + # not yet started cannot be joined (start() waits for the thread to run, not for the lock) + self._readers.append((conn, t)) + t.start() + + def _hello(self, conn): + """A new connection's first message -> (the process it is a stream of, + that process's number of streams), or None: anything but a HELLO with + this context's key CRC and its token, within _RELAY_HELLO_S, is refused + with a warning (a stray connection is no reason to stop the relay); one + that ends before its first byte, quietly.""" + hdr = bytearray(_RELAY_HDR.size) + try: + if not _recv_exact(conn, hdr, eof_ok=True): + return None + magic, kind, q, _, _, _, _, ln, n, sig = _RELAY_HDR.unpack(hdr) + why = f"magic {bytes(magic)!r}, kind {kind}, key CRC {sig:#x}" + if magic == _RELAY_MAGIC and kind == _HELLO and sig == self._key_sig: + token = bytearray(len(self._token)) + if ln == len(token): + _recv_exact(conn, token) + if hmac.compare_digest(bytes(token), self._token): + conn.settimeout(None) + return q, n + why = f"a HELLO as process {q} without this context's token" + except (OSError, RelayError) as e: + why = f"no HELLO: {type(e).__name__}: {e}" + if not self._closing: + warnings.warn( + f"relay listener {self.address}: refused a connection that is not a stream of this " f"context ({why})", + RuntimeWarning, + ) + return None + + def _read(self, conn): + hdr = bytearray(_RELAY_HDR.size) + try: + hello = self._hello(conn) + if hello is None: + return + peer, n = hello + with self._lock: + self._streams_from.setdefault(peer, [n, 0]) + try: + while _recv_exact(conn, hdr, eof_ok=True): + magic, kind, cid, seq, leaf, pos, off, ln, total, sig = _RELAY_HDR.unpack(hdr) + if magic != _RELAY_MAGIC: + raise RelayError(f"relay stream from process {peer}: bad magic {bytes(magic)!r} (the framing " "is lost)") + if kind == _DATA: + view = self._into(peer, cid, seq, leaf, pos, off, ln, total, sig) + with jax.profiler.TraceAnnotation(RELAY_TRACE["recv"], bytes=ln): + _recv_exact(conn, view) + del view + self._got(cid, seq, leaf, pos, ln) + elif kind in (_ERROR, _ABORT): + if ln > _RELAY_TEXT_MAX: + raise RelayError(f"relay stream from process {peer}: a {ln}-byte reason (the framing is lost)") + msg = bytearray(ln) + _recv_exact(conn, msg) + if kind == _ERROR: + self._remote_error(peer, cid, seq, msg.decode(errors="replace")) + else: + self._peer_aborted(peer, msg.decode(errors="replace")) + else: + raise RelayError(f"relay stream from process {peer}: unknown message kind {kind}") + except BaseException as e: + if not self._closing: + self._fail_all( + e if isinstance(e, RelayError) else RelayError(f"relay stream from process {peer}: {type(e).__name__}: {e}") + ) + finally: + self._stream_ended(peer) + finally: + conn.close() + + def _channel(self, cid, peer): + with self._cv: + self._cv.wait_for(lambda: cid in self._channels or self._closing or self._fatal is not None, self.timeout_s) + if self._fatal is not None: + raise self._fatal + if cid not in self._channels: + raise RelayError(f"process {peer} sent data of relay channel #{cid}, which process {self.pid} has " "not built") + return self._channels[cid] + + def _into(self, peer, cid, seq, leaf, pos, off, ln, total, sig): + """Where DATA chunk (cid, seq, leaf, pos, off, ln) from `peer` goes, once + checked against what the channel expects from it -> a writable view. Its + bytes are taken for it here (`spans`), before they are read: no byte of + a shard comes twice, whichever streams its chunks take.""" + ch = self._channel(cid, peer) + with self._lock: + if self._fatal is not None: + raise self._fatal + r = self._recvs.get((cid, seq)) + if r is None: + if (cid, seq) in self._dead: # failed (and retired) already: drain + return memoryview(np.empty(ln, np.uint8)) + if seq < self._floor.get(cid, 0) or seq in self._retired.get(cid, ()): + raise RelayError( + f"{ch.name} (relay channel #{cid}): process {peer} sent seq {seq} again, after " + "this process completed that receive" + ) + r = self._recvs[(cid, seq)] = _RelayRecv(ch, seq) + where = f"{r.what()} leaf {leaf} position {pos} from process {peer}" + spec = ch._recv_spec.get((leaf, pos)) + if spec is None or spec[2] != peer: + raise RelayError(f"{where}: not a shard this process takes from that process") + if (total, sig) != spec[:2]: + raise RelayError( + f"{where}: {total} bytes, dtype/shape CRC {sig:#010x}; this process expects " + f"{spec[0]} bytes, CRC {spec[1]:#010x}: the two processes built the channel " + "with different avals" + ) + key = (leaf, pos) + spans = r.spans.setdefault(key, []) + if key in r.done or off + ln > total or (ln and not _take_span(spans, off, off + ln)): + raise RelayError( + f"{where}: bytes [{off}, {off + ln}) of a {total}-byte shard " + + ("run past its end" if off + ln > total else "overlap bytes already in") + + ": duplicate or overlong data" + ) + if r.event.is_set(): # failed already, not yet retired: drain + return memoryview(np.empty(ln, np.uint8)) + if r.t_first is None: + r.t_first = time.monotonic() + buf = r.bufs.get(key) + if buf is None: + buf = r.bufs[key] = self._buffer(cid, key, total) + r.got[key] = 0 + return memoryview(buf)[off : off + ln] + + def _buffer(self, cid, key, total): # under the lock + """A host buffer for shard `key` of a receive of channel `cid`: a pooled + one nothing else holds any more, else a new one, pooled while there is + room (_RELAY_POOL). Memory the allocator cannot recycle is faulted in + and zeroed page by page: copying 58.7 MB into it took 9-13 ms against + 3.3 ms into a buffer in use before, on the THP=always VM this was + written on (31-33 ms with THP off). "Nothing else" counts jax: + jax.device_put keeps what it reads, on TPU until its host-to-device copy + is done, and on CPU, where the placed array is a view of the buffer, as + long as that array lives; and every view of it, a reader's included. + Nothing can take a reference to a buffer nothing holds but through the + pool, under the lock: a free one stays free.""" + pool = self._pool.setdefault((cid, *key), []) + for i in range(len(pool)): + if _refs(pool, i) <= _ONLY_LISTED: + return pool[i] + buf = np.empty(total, np.uint8) + if len(pool) < _RELAY_POOL: + pool.append(buf) + return buf + + def _got(self, cid, seq, leaf, pos, ln): + """DATA chunk (cid, seq, leaf, pos) of `ln` bytes is in. The chunk that + completes a shard puts it on its device -- on this reader thread, out of + the lock, while the other streams keep coming in -- and the one whose + shard is a receive's last there assembles its arrays (`_finish`).""" + with self._lock: + self.received += ln + r = self._recvs.get((cid, seq)) + key = (leaf, pos) + if r is None or r.event.is_set() or key in r.done: # done: a zero-byte shard's chunk again + return + size = len(r.bufs[key]) + r.got[key] += ln + if r.got[key] < size: # no byte twice (`_into`): its bytes add up to its size once all are in + return + r.done.add(key) + buf = r.bufs.pop(key) + if len(r.done) == len(r.ch._recv_spec): + r.t_last = time.monotonic() + try: + x = r.ch._place(key, buf) + except BaseException as e: + with self._lock: + if not r.event.is_set(): + self._fail_recv( + r, + RelayError( + f"{r.what()}: placing leaf {leaf} position {pos} on its device " f"failed: {type(e).__name__}: {e}" + ), + ) + if r.claimed: + self._retire(r) + return + del buf + with self._lock: + if r.event.is_set(): # failed meanwhile + return + r.placed[key] = x + if len(r.placed) < len(r.ch._recv_spec): + return + placed = r.placed + self._finish(r, placed) + + def _finish(self, r, placed): + """Every shard of receive r is on its device: its arrays (no copy).""" + try: + out, err = r.ch._assemble(placed), None + except BaseException as e: + out, err = None, RelayError(f"{r.what()}: assembling the received shards failed: {type(e).__name__}: " f"{e}") + t = time.monotonic() + with self._lock: + if r.event.is_set(): # failed meanwhile (`_fail_all`): that stands + return + if err is not None: + self._fail_recv(r, err) + else: # noted before a consumer can see it complete + self._note("recv_wire", r.ch.name, r.t_last - r.t_first) + self._note("recv_dispatch", r.ch.name, t - r.t_last) + r.out, r.placed = out, None + r.event.set() + if r.claimed: + self._retire(r) + + def _remote_error(self, peer, cid, seq, msg): + ch = self._channel(cid, peer) + with self._lock: + r = self._recvs.get((cid, seq)) + if r is None: + if seq < self._floor.get(cid, 0) or seq in self._retired.get(cid, ()): + return + r = self._recvs[(cid, seq)] = _RelayRecv(ch, seq) + if not r.event.is_set(): + self._fail_recv(r, RelayError(f"{r.what()}: process {peer} could not send it: {msg}")) + if r.claimed: + self._retire(r) + + def _stream_ended(self, peer): + """One of `peer`'s streams ended. Once every stream its HELLO announced + has (each after all that was sent on it is read), what is still missing + its shards never comes. One stream's end alone says nothing: another may + still carry the rest of a receive.""" + with self._lock: + st = self._streams_from[peer] + st[1] += 1 + if st[1] < st[0] or self._closing: + return + self._gone.add(peer) + self._fail_missing( + peer, lambda r, n: f"{r.what()}: process {peer} closed its relay streams with {n} " "shard(s) of it unsent" + ) + + def _peer_aborted(self, peer, msg): + """An ABORT from `peer`: some of its streams never opened, so the rest of + what it sends here never comes (`_RelayPeer._stage`).""" + with self._lock: + self._gone.add(peer) + self._gone_why[peer] = msg + self._fail_missing( + peer, + lambda r, n: f"{r.what()}: process {peer} gave up on its relay streams to " + f"this process with {n} shard(s) of it unsent: {msg}", + ) + + def _fail_missing(self, peer, why): # under the lock + for r in list(self._recvs.values()): + n = r.missing().get(peer) if not r.event.is_set() else None + if n: + self._fail_recv(r, RelayError(why(r, n))) + if r.claimed: + self._retire(r) + + def _fail_all(self, err): + with self._cv: + if self._fatal is None: + self._fatal = err + for r in list(self._recvs.values()): + if not r.event.is_set(): + self._fail_recv(r, err) + if r.claimed: + self._retire(r) + self._cv.notify_all() + + def _fail_recv(self, r, err): # under the lock + """Fail receive r: its futures raise `err`, and whatever of it still + comes is drained (`_into`), not taken for a new receive or a repeat.""" + r.err, r.bufs, r.placed = err, None, None + r.event.set() + self._dead.add((r.ch.idx, r.seq)) + + def _retire(self, r): + """Forget a receive both claimed and finished (under the lock); its + number is remembered, so a later chunk of it is an error, not a new + receive.""" + cid = r.ch.idx + if self._recvs.get((cid, r.seq)) is r: + del self._recvs[(cid, r.seq)] + done = self._retired.setdefault(cid, set()) + done.add(r.seq) + f = self._floor.get(cid, 0) + while f in done: + done.discard(f) + f += 1 + self._floor[cid] = f + + # ------------------------------------------------------------- the rest + def _note(self, measure, channel, secs): + with self._tlock: + t = self._times.get((measure, channel)) + if t is None: + t = self._times[(measure, channel)] = [0, 0.0, 0.0, collections.deque(maxlen=_RELAY_SAMPLES)] + t[0] += 1 + t[1] += secs + t[2] = max(t[2], secs) + t[3].append(secs) + + def timing(self, reset=False): + """Where the relay's time went on this process (RELAY_MEASURES) -> + {'all': {measure: summary}, 'channels': {channel name: {measure: + summary}}}, a summary {'n': the samples since the last reset, 'total_s': + their sum, 'max_ms': their largest, 'p50_ms' / 'p99_ms': percentiles of + the newest _RELAY_SAMPLES of them per channel, 'kept': how many those + are}. `reset`: forget the samples (say, after warm-up).""" + with self._tlock: + snap = {k: (n, total, top, list(q)) for k, (n, total, top, q) in self._times.items()} + if reset: + self._times.clear() + + def summary(n, total, top, xs): + p50, p99 = np.percentile(np.asarray(xs, np.float64), [50, 99]) + return dict(n=n, p50_ms=float(p50) * 1e3, p99_ms=float(p99) * 1e3, max_ms=top * 1e3, total_s=total, kept=len(xs)) + + every, by_ch = {}, {} + for (m, ch), (n, total, top, xs) in sorted(snap.items()): + e = every.setdefault(m, [0, 0.0, 0.0, []]) + e[0], e[1], e[2] = e[0] + n, e[1] + total, max(e[2], top) + e[3].extend(xs) + by_ch.setdefault(ch, {})[m] = summary(n, total, top, xs) + return {"all": {m: summary(*e) for m, e in every.items()}, "channels": by_ch} + + def describe(self): + """The relay's settings and this host's (`host_net_settings`), one line.""" + buf = ( + f"{self.sockbuf / 2**20:g} MiB socket buffers" + if self.sockbuf + else "socket buffers left to the kernel's autotuning" + ) + return ( + f"relay {self.key} p{self.pid} at {self.address}: {self.streams} streams per peer, " + f"{self.chunk / 2**20:g} MiB chunks, {buf}, timeout {self.timeout_s:g} s; this host: " + + ", ".join(f"{k}: {v}" for k, v in host_net_settings().items()) + ) + + def stats(self): + """{'sent': bytes written to peers, 'received': bytes read from them, + 'unclaimed': receives that arrived (in part) with no send_flat for them + yet, 'waiting': claimed receives not complete}.""" + with self._lock: + return dict( + sent=sum(p.sent for p in self._peers.values()), + received=self.received, + unclaimed=sorted(r.what() for r in self._recvs.values() if not r.claimed), + waiting=sorted(r.what() for r in self._recvs.values() if r.claimed), + ) + + def close(self, timeout_s=10.0): + """Flush every queued send, half-close the streams (the peers' readers see + them end between messages), give the peers' streams into this process + the same time to end, then stop the listener and every thread -- all + within `timeout_s`. A peer whose threads are still at work then (one + that stopped reading, say) has its streams shut: its threads end within + a second more, and it sees the streams end. A receive claimed but not + complete fails at once: nothing completes it once the streams are gone. + Idempotent. Warns, never raises (it runs on the way out, where it must + not hide what failed), about sends left unwritten, receives claimed but + not complete, receives that arrived with nobody to claim them, and + threads that did not end.""" + if self._closed: + return + self._closed = True + deadline = time.monotonic() + timeout_s + peers = list(self._peers.values()) + unflushed = [p.pid for p in peers if not p.flush(max(0.0, deadline - time.monotonic()))] + with self._cv: + self._closing = True + waiting = sorted( + (r for r in self._recvs.values() if r.claimed and not r.event.is_set()), key=lambda r: (r.ch.idx, r.seq) + ) + for r in waiting: + self._fail_recv( + r, + RelayError( + f"{r.what()}: relay context {self.key} (process {self.pid}) is closed " "and the receive was not complete" + ), + ) + self._retire(r) + self._cv.notify_all() + peers, readers = list(self._peers.values()), list(self._readers) + for p in peers: + p.stop() + for p in peers: + p.join(deadline) + stuck = [p for p in peers if p.running()] + for p in stuck: # else, until SO_SNDTIMEO, its writers would hold their buffers and shards + p.abort( + RelayError(f"relay context {self.key} (process {self.pid}) closed with sends to process {p.pid} " "unwritten") + ) + for p in stuck: + p.join(time.monotonic() + 1.0) + for _, t in readers: + t.join(max(0.0, deadline - time.monotonic())) + for s in (self._lsock, *(c for c, _ in readers)): + try: + s.shutdown(socket.SHUT_RDWR) + except OSError: + pass + self._lsock.close() + for c, t in readers: + t.join(1.0) + c.close() + self._listener.join(1.0) + with self._lock: + self._pool.clear() # what a live array or a reader still holds goes with it + st = self.stats() + running = [n for p in peers for n in p.running()] + running += [t.name for t in (self._listener, *(t for _, t in readers)) if t.is_alive()] + bad = [] + if unflushed: + bad.append(f"sends to process(es) {unflushed} not all written") + if waiting: + bad.append(f"{len(waiting)} claimed receive(s) not complete (failed now), e.g. {waiting[0].what()}") + if st["unclaimed"]: + bad.append( + f'{len(st["unclaimed"])} receive(s) arrived that no send_flat claimed, e.g. ' + f'{st["unclaimed"][0]} (the processes walked different orders?)' + ) + if self._send_err is not None: + bad.append(f"a send failed: {self._send_err}") + if running: # say, a stager still waiting for its shard's program, or for an address + bad.append(f'threads still running: {", ".join(running)}') + if bad: + warnings.warn(f"RelayContext {self.key} (process {self.pid}) closed with " + "; ".join(bad), RuntimeWarning) + + def __repr__(self): + return ( + f"> 10}K peers={sorted(self._peers)}>" + ) + + +def relay_timing_line(t): + """RelayContext.timing()'s summary in one line: each measure's p50 / p99, + and the channels whose consumers waited longest in all.""" + a = t["all"] + if not a: + return "no transfers" + pp = lambda m: f'p50 {a[m]["p50_ms"]:.2f} / p99 {a[m]["p99_ms"]:.2f} ms' if m in a else "none" + parts = [] + if "send_host" in a: + parts.append(f'sent {a["send_host"]["n"]} shards (on the host {pp("send_host")}, written {pp("send_wire")})') + if "recv_wire" in a: + parts.append( + f'received {a["recv_wire"]["n"]} (wire {pp("recv_wire")}, dispatched to the devices ' f'{pp("recv_dispatch")})' + ) + if "recv_wait" in a: + w = sorted(((c["recv_wait"]["total_s"], ch) for ch, c in t["channels"].items() if "recv_wait" in c), reverse=True) + parts.append( + f'consumers waited {pp("recv_wait")}, {a["recv_wait"]["total_s"]:.3f} s in all (' + + ", ".join(f"{ch} {s:.3f} s" for s, ch in w[:4]) + + (", ..." if len(w) > 4 else "") + + ")" + ) + return "; ".join(parts) + + +class RelayChannel: + """One stage boundary over the host relay (RelayContext). Each source + host starts its shards' copies to host memory and queues them for the host + holding the same mesh positions of the destination stage, which receives + them in threads of its own and places each on its device as it completes. + Nothing goes through libtpu's cross-host machinery or a collective, and + neither stage waits for the other at the boundary: the source's send_flat + returns once its shards are queued; the destination's returns a + RelayFuture per leaf at once, and only `resolve` -- its consumer -- waits + for the bytes. + + The calling contract is XferChannel's and PermuteChannel's: every process + calls send_flat for every copy, in the one global order (the two stages' + processes act, everyone else gets None back). Messages carry the + channel's index and a sequence number both sides advance on every send, + so a receive takes its own data whatever arrives first. Shard k of the + source mesh goes to device k of the destination: identical meshes, specs + and per-device index maps, checked at build time; any host pairing + (`relay_routes`). A sent array is held, not copied, until its shards + are on the host (on CPU, until they are on the wire): never donate or + delete one (drop the reference).""" + + __slots__ = ( + "name", + "idx", + "treedef", + "avals", + "src", + "dst", + "n_leaves", + "ctx", + "seq", + "owns_src", + "owns_dst", + "sends", + "recvs", + "_send_items", + "_recv_pos", + "_recv_devs", + "_recv_spec", + "_dev_at", + "_shapes", + "_dtypes", + "_nbytes", + "_sigs", + ) + + def __init__(self, avals, src_shardings, dst_shardings, ctx, idx, name="rchannel"): + flat_avals, treedef = jax.tree.flatten(avals) + self.name, self.idx, self.ctx, self.seq = name, idx, ctx, 0 + self.treedef, self.avals, self.n_leaves = treedef, tuple(flat_avals), len(flat_avals) + bc = lambda s: [s] * self.n_leaves if isinstance(s, Sharding) else list(treedef.flatten_up_to(s)) + self.src, self.dst = bc(src_shardings), bc(dst_shardings) + ma, mb = _same_mesh_boundary(name, flat_avals, self.src, self.dst, as_bytes=True) + try: + self.sends, self.recvs = relay_routes(ma, mb, ctx.pid) + except ValueError as e: + raise ValueError(f"{name}: {e}") from None + self.owns_src, self.owns_dst = bool(self.sends), bool(self.recvs) + fa, fb = list(ma.devices.flat), list(mb.devices.flat) + self._shapes = [tuple(d.shard_shape(tuple(a.shape))) for a, d in zip(self.avals, self.dst)] + self._dtypes = [np.dtype(a.dtype) for a in self.avals] + self._nbytes = [math.prod(s) * t.itemsize for s, t in zip(self._shapes, self._dtypes)] + self._sigs = [_relay_sig(t, s) for t, s in zip(self._dtypes, self._shapes)] + self._send_items = [ + (q, [(i, k, fa[k]) for i in range(self.n_leaves) for k in ks]) for q, ks in sorted(self.sends.items()) + ] + src_of = {k: q for q, ks in self.recvs.items() for k in ks} + # mesh-position order: the destination sharding's addressable order + self._recv_pos = sorted(src_of) + self._recv_devs = [fb[k] for k in self._recv_pos] + self._dev_at = dict(zip(self._recv_pos, self._recv_devs)) + self._recv_spec = { + (i, k): (self._nbytes[i], self._sigs[i], src_of[k]) for i in range(self.n_leaves) for k in self._recv_pos + } + ctx.register(self) + + def _place(self, key, buf): + """A reader thread, at the last byte of shard `key` = (leaf, mesh + position): its bytes as numpy -> its destination device.""" + i, k = key + with jax.profiler.TraceAnnotation(RELAY_TRACE["place"], bytes=buf.nbytes): + return jax.device_put(buf.view(self._dtypes[i]).reshape(self._shapes[i]), self._dev_at[k]) + + def _assemble(self, placed): + """Once every shard of a receive is on its device ({(leaf, mesh + position): single-device array}): the destination arrays.""" + return [ + jax.make_array_from_single_device_arrays(tuple(a.shape), d, [placed[(i, k)] for k in self._recv_pos]) + for i, (a, d) in enumerate(zip(self.avals, self.dst)) + ] + + def send_flat(self, leaves): + """Every process, every boundary copy in order: source arrays where owned + -> a RelayFuture per leaf on the destination stage's processes, None + elsewhere (and on the source side, which returns once its shards are + queued). After a send of the context failed, the source side raises, + once it has told the destinations this one is not coming.""" + if not (self.owns_src or self.owns_dst): + return [None] * self.n_leaves + if self.owns_src: + _check_sources(self.name, leaves, self.avals, self.src) + self.ctx.check() # closed: no number, no message (the peers see the streams end) + seq, self.seq = self.seq, self.seq + 1 + self.ctx._send(self, seq, leaves) + return [None] * self.n_leaves + seq, self.seq = self.seq, self.seq + 1 + r = self.ctx._claim(self, seq) + return [RelayFuture(r, i) for i in range(self.n_leaves)] + + def send(self, tree): + return jax.tree.unflatten(self.treedef, self.send_flat(self.treedef.flatten_up_to(tree))) + + def __repr__(self): + return f"" + + +class _Aval: + """Minimal shape/dtype carrier (avoids importing jax.core here).""" + + __slots__ = ("shape", "dtype") + + def __init__(self, shape, dtype): + self.shape, self.dtype = tuple(shape), dtype + + +class _ShapedSrc: + """Adapter so `assert_d2d` can be used on an (aval, sharding) pair.""" + + __slots__ = ("shape", "dtype", "sharding") + + def __init__(self, aval, sharding): + self.shape, self.dtype, self.sharding = tuple(aval.shape), aval.dtype, sharding + + +# ------------------------------------------------------------ CI: no D2H at all +@contextlib.contextmanager +def no_host_bounce(): + """Make every device->host fetch raise `HostBounceError` inside the block. + + Patches `jax._src.array.ArrayImpl._value`, which is the single funnel for + `np.asarray`, `float()`, `print`, and the silent reshard round trip. Note on + the CPU backend a SINGLE-shard array also satisfies the Python buffer + protocol, so `np.asarray` on it bypasses `_value` entirely; multi-device + sharded arrays (the pipeline case) always go through `_value`. + """ + if _jax_array is None: # pragma: no cover + raise RuntimeError("jax._src.array unavailable; cannot install the guard") + cls = _jax_array.ArrayImpl + original = cls.__dict__.get("_value") + if original is None: # pragma: no cover + raise RuntimeError("ArrayImpl._value not found; jax internals changed") + + def _raise(self): + raise HostBounceError( + f"device->host transfer of a {self.shape} {self.dtype} array inside " + "no_host_bounce(): something called np.asarray/float/print on a device " + "array, or a device_put resharded instead of copying." + ) + + setattr(cls, "_value", property(_raise)) + try: + yield + finally: + setattr(cls, "_value", original) + + +# --------------------------------------------------------------- run-ahead cap +# The PJRT client-creation option that caps enqueued-but-incomplete executions +# per device. It is NOT a jax-side name: it appears nowhere in jax/jaxlib +# python (`grep -rn max_inflight` over both packages returns nothing) and is +# read by the plugin. `libtpu.so` contains the literal string, which is the +# only evidence available in a CPU-only process; `option_name_evidence()` +# re-checks that at runtime instead of taking it on faith. +MAX_INFLIGHT_OPTION = "max_inflight_computations" + +# Platforms whose PJRT client is created through a factory that actually reads +# `jax_pjrt_client_create_options`. In jax 0.11.1 the config is funnelled +# through `xla_bridge._options_from_jax_configs`, which has exactly two callers: +# `xla_bridge.make_tpu_client` and `xla_bridge.make_pjrt_c_api_client`. +# The built-in CPU client comes from +# `xla_client.make_cpu_client()`, whose signature has no options argument at +# all, so on CPU this whole knob is inert -- and a healthy `jax.devices()` after +# setting a garbage option proves exactly nothing. The CUDA / ROCm plugins are +# C-API clients (make_pjrt_c_api_client), whose PJRT_Client_Create takes the +# option too: the GPU client caps a device's enqueued executions at 32 as well. +OPTION_AWARE_PLATFORMS = ("tpu", "cuda", "gpu", "rocm") + + +def pjrt_client_options(plugin: str = "tpu"): + """The exact options dict jax would hand to `plugin`'s PJRT client right now. + + Thin wrapper over `jax._src.xla_bridge._options_from_jax_configs(plugin)` -- + the single place `jax_pjrt_client_create_options` is turned into client + options. Returns None if that private helper is gone (jax internals drift). + """ + try: + from jax._src import xla_bridge as xb + + fn = getattr(xb, "_options_from_jax_configs", None) + return None if fn is None else dict(fn(plugin)) + except Exception: # pragma: no cover - jax internals + return None + + +def pinned_platforms() -> tuple[str, ...]: + """Platforms this process is pinned to, without initializing any backend.""" + val = getattr(jax.config, "jax_platforms", None) or os.environ.get("JAX_PLATFORMS", "") + return tuple(p.strip().lower() for p in str(val).split(",") if p.strip()) + + +def option_name_evidence(): + """`(found, where)` for the literal option name in an installed PJRT plugin. + + Scans `libtpu.so` for `MAX_INFLIGHT_OPTION`. `found is None` means no plugin + binary was found to scan (nothing proven either way), False means the name is + absent from the plugin that would consume it -- i.e. a typo. + """ + import mmap + # Fixed locations only. This used to add a recursive `/usr/lib/**` glob -- + # evaluated whether or not the pip wheel had already been found -- and it + # runs in every `TransferTest.test_transfer_layer` (transfer_test.py, through + # `check_transfer_layer`): a walk over every file under /usr/lib, following + # directory symlinks, on every run of that test. + pats = [ + os.path.join(os.path.dirname(os.path.dirname(jax.__file__)), "libtpu", "libtpu.so"), + "/usr/lib/libtpu.so", + "/usr/local/lib/libtpu.so", + ] + for path in pats: + if not os.path.exists(path): + continue + try: + with open(path, "rb") as f: + with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: + return m.find(MAX_INFLIGHT_OPTION.encode()) >= 0, path + except Exception: # pragma: no cover - unreadable + continue + return None, None + + +def set_max_inflight(n: int = 128, plugin: str = "tpu") -> bool: + """Raise the PJRT per-device run-ahead queue above its default of 32. + + The 33rd enqueued-but-incomplete execution BLOCKS the single driver thread, + and a 4-stage x 16-microbatch fwd+bwd schedule sits exactly on that cliff. + + MUST be called before the first backend initialization (i.e. before any + `jax.devices()` / first jit). + + Returns True ONLY when the value was (a) accepted by the config system, (b) + observed, as an int, in the very options dict `plugin`'s client factory reads + (`pjrt_client_options`), and (c) this process is actually going to build that + kind of client. Otherwise it warns and returns False -- never an exception, + except for a nonsense `n`, which is a caller bug. In particular it returns + False on a CPU-pinned process: `make_cpu_client` takes no options, so the cap + is not applied and reporting success there would be a lie. + """ + if isinstance(n, bool) or not isinstance(n, int): + raise TypeError( + f"set_max_inflight(n): n must be an int, got {n!r} " + f"({type(n).__name__}); PJRT silently ignores an option it " + "cannot parse." + ) + if n <= 0: + raise ValueError(f"set_max_inflight(n): n must be positive, got {n}") + try: + from jax._src import xla_bridge as xb + + if xb.backends_are_initialized(): + warnings.warn( + "set_max_inflight() called after backend initialization; " + "PJRT client options are read only at client creation, so " + "this is a no-op. Call it before the first jax.devices().", + RuntimeWarning, + ) + return False + except Exception: # pragma: no cover + pass + cur = getattr(jax.config, "jax_pjrt_client_create_options", None) + opts = {} + if isinstance(cur, dict): + opts.update(cur) + elif isinstance(cur, str) and cur: + # jax ships a default "k1:v1;k2:v2" string (ml_framework_name/version); + # keep those entries instead of clobbering them with a bare dict. + for kv in cur.split(";"): + if kv.count(":") == 1: + k, v = kv.split(":") + opts[k] = v + keep = dict(opts) + opts[MAX_INFLIGHT_OPTION] = n + try: + jax.config.update("jax_pjrt_client_create_options", opts) + except Exception as e: + warnings.warn(f"set_max_inflight({n}) rejected by this jax build: " f"{type(e).__name__}: {e}", RuntimeWarning) + return False + + seen = pjrt_client_options(plugin) + if seen is None: + warnings.warn( + "set_max_inflight(): jax._src.xla_bridge." + "_options_from_jax_configs is gone, so there is no way to " + "verify the option reaches the PJRT client; treating as not " + "applied.", + RuntimeWarning, + ) + return False + if seen.get(MAX_INFLIGHT_OPTION) != n or not isinstance(seen.get(MAX_INFLIGHT_OPTION), int): + warnings.warn( + f"set_max_inflight({n}): the option did not survive into the " + f"{plugin} client options ({seen!r}); not applied.", + RuntimeWarning, + ) + return False + dropped = [k for k, v in keep.items() if seen.get(k) != v] + if dropped: # pragma: no cover - defensive + warnings.warn( + f"set_max_inflight({n}) clobbered pre-existing PJRT client " f"options {dropped}; not applied.", RuntimeWarning + ) + return False + plats = pinned_platforms() + if "proxy" in plats and not any(p in OPTION_AWARE_PLATFORMS for p in plats): + warnings.warn( + f"set_max_inflight({n}) stored the option, but JAX_PLATFORMS={','.join(plats)} is Pathways: the IFRT proxy " + "client takes no PJRT client options, so the run-ahead cap is NOT applied here -- how far the client runs " + "ahead is the Pathways workers' (ds_ep_pipeline does not call this under the proxy; a local Pathways run " + "queued ~90 steps without blocking).", + RuntimeWarning, + ) + return False + if plats and not any(p in OPTION_AWARE_PLATFORMS for p in plats): + warnings.warn( + f"set_max_inflight({n}) stored the option and it does reach " + f"_options_from_jax_configs({plugin!r}), but JAX_PLATFORMS=" + f'{",".join(plats)} pins this process to a backend whose client is ' + f"built by xla_client.make_cpu_client(), which takes no options: the " + f"run-ahead cap is NOT applied here. Only {OPTION_AWARE_PLATFORMS} " + "read jax_pjrt_client_create_options.", + RuntimeWarning, + ) + return False + return True + + +def block_all(pytree): + """The single end-of-step barrier. One call, not a loop of per-array waits.""" + return jax.block_until_ready(pytree) + + +# -------------------------------------------------------------------- smoke +def smoke_test(): + """Fail loudly if the batched-copy fast path is gone after a jaxlib bump.""" + if not BATCHED_COPY_AVAILABLE: + raise RuntimeError( + "xla_client.batched_copy_array_to_devices_with_sharding is MISSING in " + f"this jaxlib; Channel would silently degrade to jax.device_put for " + "every leaf, costing ~3x the host dispatch. Pin jaxlib or update " + "transfer.py." + ) + import numpy as np + from jax.sharding import Mesh, NamedSharding, PartitionSpec as P + + devs = jax.devices() + half = max(1, len(devs) // 2) + src_mesh = Mesh(np.array(devs[:half]), ("fsdp",)) + dst_mesh = Mesh(np.array(devs[half:] or devs[:half]), ("fsdp",)) + spec = P("fsdp", None) + x_np = np.arange(8 * half * 4, dtype=np.float32).reshape(8 * half, 4) + x = jax.device_put(x_np, NamedSharding(src_mesh, spec)) + dst = NamedSharding(dst_mesh, spec) + if not same_index_map(x.sharding, dst, x.shape): + raise RuntimeError("smoke_test: identical specs on equal-sized meshes no " "longer produce identical index maps") + ch = Channel(jax.ShapeDtypeStruct(x.shape, x.dtype), x.sharding, dst, name="smoke") + if ch.n_fast != 1: + raise RuntimeError(f"smoke_test: fast path not taken ({ch.reasons})") + y = block_all(ch.send(x)) + if not np.array_equal(np.asarray(y), x_np): + raise RuntimeError("smoke_test: batched copy returned wrong values") + if y.sharding != dst: + raise RuntimeError(f"smoke_test: wrong output sharding {y.sharding}") + return True diff --git a/src/maxtext/experimental/mpmd/jax/xprof.py b/src/maxtext/experimental/mpmd/jax/xprof.py new file mode 100644 index 0000000000..376b0df3e3 --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/xprof.py @@ -0,0 +1,2162 @@ +# 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. + +"""Read an MPMD xplane trace from the command line, because the UI cannot. + + python3 -m maxtext.experimental.mpmd.jax.xprof summary DIR_OR_XPLANE + python3 -m maxtext.experimental.mpmd.jax.xprof timeline DIR_OR_XPLANE + python3 -m maxtext.experimental.mpmd.jax.xprof modules DIR_OR_XPLANE [-d 0] + python3 -m maxtext.experimental.mpmd.jax.xprof gaps DIR_OR_XPLANE [-d 0] + python3 -m maxtext.experimental.mpmd.jax.xprof idle DIR_OR_XPLANE [--min-us 20] + python3 -m maxtext.experimental.mpmd.jax.xprof ops DIR_OR_XPLANE -m jit_bwda_c0 [-d 0] + python3 -m maxtext.experimental.mpmd.jax.xprof roofline DIR_OR_XPLANE -m jit_bwda_c0 + [--flops N --bytes N] + python3 -m maxtext.experimental.mpmd.jax.xprof scopes DIR_OR_XPLANE [-d 0] [--step -1] + python3 -m maxtext.experimental.mpmd.jax.xprof costs DIR_OR_XPLANE [-d 0] > costs.json + +`DIR_OR_XPLANE` is a `.xplane.pb` or any directory above one, so a profile +directory straight out of `ds_ep_pipeline --profile` works; a TPU or a GPU +capture (GPU CAPTURES below says what differs). `-d` restricts to one +device; without it `ops` and `roofline` pool every device's instances of the +module. + +`-m` takes a program's name as `modules` lists it, without the id in +parentheses: `jit__c` and what else the program carries, e.g. +`jit_fwd_c0_agself`, `jit_bwda_c0_rs2p0` (the scheme is +`ds_ep.ChunkPrograms.program`'s). A name no program has is taken as a +substring, which must then be in one program's name only: in several, the +command exits and lists them with their instance counts rather than pool +programs that differ (see `_select`). The default, `jit_bwda_c0`, is chunk +0's plain accumulating backward: a backward past the first microbatch's that +carries no FSDP gather or reduce-scatter and recomputes its forward (not a +stash backward, `_st`). Not every plan has one -- at S=2, V=2, M=4 under the +default flags each of chunk 0's backwards carries part of chunk 2's +reduce-scatter -- and then the default lists chunk 0's accumulating +backwards, or reads the one there is. It runs on stage 0, which holds the +first chip (in every layout but physical_origin_last), the one a +single-process capture traces by default; and under its own name: the trace +keys a program by its HLO fingerprint, so identical programs of different +chunks show under whichever name loaded first, but chunk 0's hold the +embedding and match no other. + +WHY THIS FILE EXISTS +-------------------- +A TensorBoard profile of an SPMD program is one program on N devices, so every +aggregate the UI computes ("step time", "FLOP utilization", the roofline, the +Overview page) is an average over N copies of the same thing, which is the +thing you wanted. MPMD breaks that assumption in four specific ways, and the +UI does not warn you about any of them: + + 1. THERE ARE NO STEPS. The `Steps` line on an MPMD device has one event per + *module execution* -- 64 of them for a 2-step capture, 48 on the last + stage, whose second chunk is one fused forward+backward -- not one per + training step. Anything the UI derives from step boundaries (Step Time + graph, Input Pipeline Analyzer, "steps/sec") is therefore reporting on a + unit that does not exist. `summary` recovers the real boundaries from + the module-name sequence, which repeats once per step on every device. + Do not try to recover them from the widest gaps instead: on these + captures the widest all-device-idle gap is sometimes a turnaround inside + a step and sometimes a hole in the drain. See `Trace.n_steps`. + + 2. EVERY DEVICE RUNS A DIFFERENT PROGRAM. A device-level aggregate is an + average over four unrelated executables, which is why `summary` and `gaps` + always break out per device -- the *shape* across devices is the finding, + not the mean. `ops` and `roofline` pool the instances of one program + over the devices that run it: a stage's devices, and other stages' where + the trace lists their identical programs under the same name (see 3). + They never pool programs whose names differ (`_select`). Pass `-d` when + you want one stage. + + 3. THE TRACE VIEWER SHOWS A WALL OF LOOK-ALIKE BOXES. One step is dozens + of module executions per device. A program's name carries its chunk, + `_c`, but nothing in it carries the microbatch: that is the box's + place in the step. Nor is the name always the chunk's own -- the trace + keys a program by its HLO fingerprint, which leaves names out, so + identical programs of different chunks all show under whichever name + loaded first (on a TPU7x-8 capture at PP=4, V=2, stages 1-3 ran every + chunk but the fused last one under stage 1's names). The device row + gives the stage, the order within the step the chunk and the microbatch. + `timeline` prints the whole step as one line of text per device instead. + + 4. OP-LEVEL GAPS SHATTER THE IDLE INTO CONFETTI. Measured on `XLA Ops`, + TPU:0 of a v6e-4 capture at mbs 256 has 1,207 gaps; 1,144 of them sit *inside* a + module, are every one sub-microsecond, and sum to 0.006 ms. The other 63 + are the module-level gaps and carry the whole 30.9 ms. The total idle is + the same either way -- what op granularity destroys is the *distribution*, + and "idle spread over ~1,200 small gaps" is exactly the fingerprint of + host dispatch, so reading the trace at op level invents a dispatch problem + that is not there. `gaps` therefore works on `XLA Modules` and classifies + each gap by the pair of modules it separates. A bubble puts each stage's + idle in a DIFFERENT place -- stage 0 waits mid-step for the gradient, + stage 3 waits at the step edges -- while a dispatch stall has no reason to + land differently per device, and tracks the driver thread. + +Peaks are read from the trace's own plane stats, never from a spec sheet. +Note that these captures carry no per-op cost model -- no `flops` or +`bytes_accessed` stat is emitted on any line -- so arithmetic intensity cannot +be read off the trace and `roofline` takes it as an argument. + +GPU CAPTURES +------------ +A capture with `/device:GPU:N` planes and no TPU one reads the same way, and +the reports call its devices `GPU:N`. A GPU plane has none of the TPU's +lines: its lines are CUDA streams -- `Stream #50(Memset,Compute,MemcpyD2D)`, +the NCCL kernels on a stream of their own, PJRT's copies on others -- and each +event is one kernel, memcpy or memset, named after itself, with the program it +ran in among its stats. `Trace._read_gpu` builds the TPU's lines out of them: + + XLA Modules one event per execution of a program, named `hlo_module(program_id)` + as a TPU module is, from its first event to its last over every + stream. Which execution an event belongs to comes off the + `/host:__ScopeRangeCallStack__` plane (`gpu_executions`): XLA opens + one annotation scope per executable run and nests each thunk's + inside it, so the root of an event's `scope_range_id` chain is its + execution. Exact, where cutting at gaps is not: the four forwards + of a chunk run back to back with sub-microsecond gaps between them, + as small as the gaps inside one. + XLA Ops one event per kernel, memcpy and memset inside a program, named by + its `hlo_op` (the kernel name where it has none), its `name` stat -- + the JAX name stack, `jit(fwd_c0)/shard_map/ep_all_gather/mb0/ + all_gather` -- kept as `tf_op`, where a TPU op carries it (a GPU + kernel's own `tf_op` is `XlaModule:`). Nothing nests -- a `while` is + its body's kernels again -- but the NCCL stream runs BESIDE the + compute stream, so op time is a union (`merged`), never a sum, and + `ops` and `scopes` take every kernel of the execution, not `children`. + Transfers whatever runs outside every program: PJRT's copies -- `device_put` + between local GPUs is MemcpyP2P, to and from pinned host memory + (--offload-residuals) MemcpyD2H / H2D -- and its cross-process + NCCL send/recv. The P2P copies and the send/recv are the stage + boundary; `summary` prints the rest apart. + +There is no `Steps` line, no SparseCore, and no peak FLOP/s stat (the plane +gives `memory_bandwidth`, so `roofline` scores the bandwidth side alone). And +a GPU module spans the gaps between its kernels, where a host launching kernels +slower than they run shows up, so `summary` and `idle` put the kernels' own +union beside the module figures. +""" + +from __future__ import annotations + +import argparse +import bisect +import collections +import functools +import glob +import json +import math +import os +import re +import statistics +import sys + +PS = 1e6 # picoseconds per microsecond +PS_MS = 1e9 # picoseconds per millisecond + + +@functools.cache +def _xplane_pb2(): + """The xplane protobuf messages (XSpace and the rest), built once a process + from tsl/profiler/protobuf/xplane.proto's field numbers -- on first use: + parsing needs them, running the pipeline does not. + + Never tensorflow's `xplane_pb2`, even where tensorflow is installed. The two + agree on every field, so a capture parses and serializes to the same bytes + through either (xprof_pb_test.MessagesTest), and importing tensorflow costs + a process some 10 s and 0.7 GB: this module's, every worker xprof_align + spawns and a pipeline host exporting its trace. + """ + import types + from google.protobuf import descriptor_pb2 as D, descriptor_pool, message_factory + + F = D.FieldDescriptorProto + O, R = F.LABEL_OPTIONAL, F.LABEL_REPEATED + I, S, B, M, DB, U = (F.TYPE_INT64, F.TYPE_STRING, F.TYPE_BYTES, F.TYPE_MESSAGE, F.TYPE_DOUBLE, F.TYPE_UINT64) + pk = ".tensorflow.profiler." + fd = D.FileDescriptorProto(name="xplane_mpmd.proto", package="tensorflow.profiler", syntax="proto3") + + def msg(name, fields, oneof=None, parent=None): + m = (parent.nested_type if parent else fd.message_type).add(name=name) + if oneof: + m.oneof_decl.add(name=oneof) + for n, num, t, lab, *r in fields: + f = m.field.add(name=n, number=num, type=t, label=lab) + if r and r[0]: + f.type_name = r[0] + if len(r) > 1: + f.oneof_index = 0 + return m + + msg("XSpace", [("planes", 1, M, R, pk + "XPlane"), ("errors", 2, S, R), ("warnings", 3, S, R), ("hostnames", 4, S, R)]) + pl = msg( + "XPlane", + [ + ("id", 1, I, O), + ("name", 2, S, O), + ("lines", 3, M, R, pk + "XLine"), + ("event_metadata", 4, M, R, pk + "XPlane.EventMetadataEntry"), + ("stat_metadata", 5, M, R, pk + "XPlane.StatMetadataEntry"), + ("stats", 6, M, R, pk + "XStat"), + ], + ) + for nm, v in (("EventMetadataEntry", "XEventMetadata"), ("StatMetadataEntry", "XStatMetadata")): + msg(nm, [("key", 1, I, O), ("value", 2, M, O, pk + v)], parent=pl).options.map_entry = True + msg( + "XLine", + [ + ("id", 1, I, O), + ("display_id", 10, I, O), + ("name", 2, S, O), + ("display_name", 11, S, O), + ("timestamp_ns", 3, I, O), + ("duration_ps", 9, I, O), + ("events", 4, M, R, pk + "XEvent"), + ], + ) + msg( + "XEvent", + [ + ("metadata_id", 1, I, O), + ("offset_ps", 2, I, O, None, 0), + ("num_occurrences", 5, I, O, None, 0), + ("duration_ps", 3, I, O), + ("stats", 4, M, R, pk + "XStat"), + ], + oneof="data", + ) + msg( + "XStat", + [ + ("metadata_id", 1, I, O), + ("double_value", 2, DB, O, None, 0), + ("uint64_value", 3, U, O, None, 0), + ("int64_value", 4, I, O, None, 0), + ("str_value", 5, S, O, None, 0), + ("bytes_value", 6, B, O, None, 0), + ("ref_value", 7, U, O, None, 0), + ], + oneof="value", + ) + msg( + "XEventMetadata", + [ + ("id", 1, I, O), + ("name", 2, S, O), + ("display_name", 4, S, O), + ("metadata", 3, B, O), + ("stats", 5, M, R, pk + "XStat"), + ("child_id", 6, I, R), + ], + ) + msg("XStatMetadata", [("id", 1, I, O), ("name", 2, S, O), ("description", 3, S, O)]) + pool = descriptor_pool.DescriptorPool() + pool.Add(fd) + return types.SimpleNamespace( + **{ + n: message_factory.GetMessageClass(pool.FindMessageTypeByName("tensorflow.profiler." + n)) + for n in ("XSpace", "XPlane", "XLine", "XEvent", "XStat", "XEventMetadata", "XStatMetadata") + } + ) + + +def has_device_planes(path): + """Does the xplane file at `path` hold a device plane (/device:TPU:n or /device:GPU:n)? Found in its bytes, where a + plane's name is written as it is, without parsing a capture of up to a few GB.""" + import mmap + + with open(path, "rb") as f: + if os.fstat(f.fileno()).st_size == 0: + return False + with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: + return m.find(b"/device:TPU:") >= 0 or m.find(b"/device:GPU:") >= 0 + + +# A capture directory's name as jax, pathwaysutils and ds_ep_pipeline name a trace session: a time to the second, +# YYYY_MM_DD_HH_MM_SS, zero-padded, in the naming host's local time (jax takes it when its trace stops, ds_ep_pipeline +# before the profiled steps: pathways.session_id), so that the names of the sessions named in one time zone sort in +# time order (XProf lists sessions by them). +SESSION_NAME = re.compile(r"\d{4}(_\d\d){5}") + + +def find_xplane(path): + """Accept a .xplane.pb, or any directory above one, and find it. + + `jax.profiler.trace` writes a fresh `plugins/profile//` sibling on + every run, so re-profiling into the same directory leaves several captures + behind. Take the newest, and say which -- picking the oldest silently, as + this used to, means a second run appears to have changed nothing. Where + every capture directory is named as a session (SESSION_NAME) the newest is + the session named last: a copy from gs:// (gcloud storage cp, as a Pathways + profile needs) gives each file the time it was downloaded, not the time it + was captured. (Names given in different time zones -- a cluster's session + copied beside a workstation's -- do not sort so.) Otherwise the newest is + the file written last (its mtime). + + One capture can be several files: a Pathways session (ds_ep_pipeline + --profile gs://... under JAX_PLATFORMS=proxy, copied here) holds the + client's own trace (.xplane.pb, client.*.xplane.pb: no device plane) + beside each traced worker host's (server-.0.0.xplane.pb: the device + planes) and a small one of the resource manager's. So within the newest + capture's directory a file with device planes wins (`has_device_planes`), + the newest of them. + """ + if os.path.isfile(path): + return path + # escaped: a capture directory may be named after a label with glob characters in it, `hybrid[rand]`, + # and an unescaped `[...]` is a glob character class that matches nothing here + hits = glob.glob(os.path.join(glob.escape(path), "**", "*.xplane.pb"), recursive=True) + if not hits: + raise SystemExit(f"no *.xplane.pb under {path}") + capture = {h: os.path.basename(os.path.dirname(h)) for h in hits} # its directory's name + by_name = all(SESSION_NAME.fullmatch(name) for name in capture.values()) + hits.sort(key=lambda h: (capture[h] if by_name else "", os.path.getmtime(h), h)) + pick = hits[-1] + same = [h for h in hits if os.path.dirname(h) == os.path.dirname(pick)] + if len(same) > 1: + pick = next((h for h in reversed(same) if has_device_planes(h)), pick) + if len(hits) > 1: + if by_name: + what = "file with device planes" if len(same) > 1 else "file" + what = f"the newest session's {what} (sessions by name: when each was named)" + else: + what = "the newest" if len(same) == 1 else "the newest capture's file with device planes" + print(f"# {len(hits)} traces under {path}, using {what}:", file=sys.stderr) + for h in hits: + print(f'# {"->" if h == pick else " "} {h}', file=sys.stderr) + return pick + + +# ------------------------------------------------------------------- GPU planes +# A GPU capture's executions are read off this plane (`gpu_executions`): its stats are the scope-range tree, one a +# scope, metadata id the scope's id and value its parent's. Its only named stat metadata is `process_id`. +SCOPE_TREE = "/host:__ScopeRangeCallStack__" +# The stats of a GPU event anything here reads. A kernel carries about ten more (correlation_id, occupancy, +# kernel_details, ...), and at ~10^5 kernels a pipeline step, decoding them would be most of the parse. +GPU_STATS = ("hlo_op", "hlo_module", "program_id", "name", "tf_op", "scope_range_id", "memcpy_details", "Memset_details") +# What a collective kernel's `hlo_op` can read, as `hlo_opcode` leaves it: XLA's opcodes, and the JAX primitive +# names its MLIR-spelled instructions keep (`psum.7.1` is an all-reduce, `psum.7.0-fusion.1` XLA's own one-warp +# all-reduce kernel). send / recv are a collective-permute's halves: `collective-permute` holds send/recv. +_GPU_OPCODES = { + "all-gather": "all-gather", + "reduce-scatter": "reduce-scatter", + "all-reduce": "all-reduce", + "all-to-all": "all-to-all", + "ragged-all-to-all": "all-to-all", + "collective-permute": "collective-permute", + "send": "collective-permute", + "recv": "collective-permute", + "collective-broadcast": "collective-broadcast", + "psum": "all-reduce", + "psum-scatter": "reduce-scatter", + "ppermute": "collective-permute", +} +# NCCL names its device kernels after the collective -- ncclDevKernel_AllGather_RING, +# ncclDevKernel_ReduceScatter_bf16_RING, ncclKernel_AllReduce_RING_LL_Sum_float -- matched with the underscores out, +# longest first (allreduce before reduce). send/recv (None) is a collective-permute, or an all-to-all, which NCCL +# runs as grouped send/recv: `hlo_op` decides. +_NCCL = ( + ("allgather", "all-gather"), + ("reducescatter", "reduce-scatter"), + ("allreduce", "all-reduce"), + ("alltoall", "all-to-all"), + ("sendrecv", None), + ("send", None), + ("recv", None), + ("broadcast", "collective-broadcast"), + ("reduce", "reduce"), +) + + +def gpu_kernels(pl, lines=None): + """Every event on a `/device:GPU:N` plane's streams, as (start ps, end ps, stream id, name, {stat: value}). + + Sorted by (start, -duration), as `Trace._events` sorts. `lines` defaults to + the plane's own; a caller that parses the lines out of the file's bytes itself + passes those, with `pl` the plane's metadata. Only `Stream #` lines are streams (a plane + that went through xprof's converter also has derived lines, its own `XLA + Modules` among them), only `GPU_STATS` are read, and a `ref_value` -- how a + GPU plane stores every string stat -- is decoded to the stat-metadata name it + points at. + """ + smd = {k: m.name for k, m in pl.stat_metadata.items()} + want = {k: n for k, n in smd.items() if n in GPU_STATS} + emd = pl.event_metadata + out = [] + for ln in pl.lines if lines is None else lines: + if not ln.name.startswith("Stream #"): + continue + base = ln.timestamp_ns * 1000 + for e in ln.events: + st = {} + for s in e.stats: + n = want.get(s.metadata_id) + if n is not None: + w = s.WhichOneof("value") + v = getattr(s, w) if w else None + st[n] = smd.get(v, "") if w == "ref_value" else v + s0 = base + e.offset_ps + out.append((s0, s0 + e.duration_ps, ln.id, emd[e.metadata_id].name if e.metadata_id in emd else "", st)) + out.sort(key=lambda k: (k[0], -k[1])) + return out + + +def scope_tree(pl): + """The `SCOPE_TREE` plane -> {scope range id: its parent's}.""" + named = {k for k, m in pl.stat_metadata.items() if m.name} + return {s.metadata_id: s.int64_value for s in pl.stats if s.metadata_id not in named} + + +def gpu_executions(kernels, tree): + """`gpu_kernels`' events grouped one index list per program execution, in order of first event; and how many + events were grouped without the tree. + + An event's execution is the root of its `scope_range_id` chain in `tree`: + XLA's GPU executable opens one annotation scope per run and every thunk's + nests inside it -- a kernel's scope is its thunk's, an NCCL kernel's one + level deeper, under its async wrapper's. Measured on a 2-step A100 capture + (5,074 kernels) and a GB200 one (11,912): every event had a root, each root + one (hlo_module, program_id), and the roots split the back-to-back + executions of one program (`jit_fwd_c2` x4 a step) that nothing on the + device timeline does. The key keeps (hlo_module, program_id) anyway, so a + root shared by two programs could not merge them. + + Without the tree (older jaxlibs), or for an event whose scope it lacks, a + run of consecutive events of one (hlo_module, program_id) is one execution + -- how xprof's own derived `XLA Modules` line read GPU traces before the + tree: back-to-back executions of one program merge, and two programs on two + streams at once cut each other into pieces. Events with no `hlo_module` + (PJRT's copies, its cross-process NCCL send/recv) are in no execution. + """ + roots, groups, order, run, approx = {}, {}, [], None, 0 + for i, (_, _, _, _, st) in enumerate(kernels): + mod = st.get("hlo_module") + if not mod: + continue + prog, sid = st.get("program_id"), st.get("scope_range_id") + if sid is not None and sid in tree: + r = roots.get(sid) + if r is None: + r, n = sid, 0 + while r in tree and n < 64: # a cycle cannot hang the walk + r, n = tree[r], n + 1 + roots[sid] = r + key, run = ("scope", r, mod, prog), None + else: + approx += 1 + if run is None or run[2:] != (mod, prog): + run = ("run", len(order), mod, prog) + key = run + g = groups.get(key) + if g is None: + g = groups[key] = [] + order.append(key) + g.append(i) + return [groups[k] for k in order], approx + + +def hlo_opcode(hlo_op): + """`all_gather.26.1` -> `all-gather`, `all-reduce-start.3` -> `all-reduce`: a GPU event's `hlo_op` with its + ordinals, async suffix and MLIR underscores off -- the nearest thing to an opcode a GPU trace carries.""" + op = (hlo_op or "").split(".")[0].replace("_", "-") + for suf in ("-start", "-done", "-update"): + if op.endswith(suf): + return op[: -len(suf)] + return op + + +def gpu_collective(kernel, hlo_op): + """The collective a GPU kernel runs (`_GPU_OPCODES`' values, 'reduce', or 'other'), None for any other kernel. + + NCCL's kernels (and NVSHMEM's) are collectives whatever their `hlo_op`, their + name saying which (`_NCCL`); a kernel of no library is one if its `hlo_op` + is (XLA's own collective kernels). Memcpys and memsets are `gpu_op_kind`'s. + """ + k = kernel.lower() + op = _GPU_OPCODES.get(hlo_opcode(hlo_op)) + if "nccl" not in k and "nvshmem" not in k: + return op + body = k.split("(")[0].replace("_", "") + for pat, kind in _NCCL: + if pat in body: + return kind or (op if op == "all-to-all" else "collective-permute") + return op or "other" # ncclDevKernel_Generic: hlo_op or nothing + + +def gpu_op_kind(kernel, stats): + """('memcpy', 'P2P' / 'D2D' / 'H2D' / 'D2H'), ('memset', None), ('collective', `gpu_collective`) or + ('compute', None) of one GPU event.""" + if "memcpy_details" in stats or kernel.startswith("Memcpy"): + k = kernel[6:].split()[0].upper().replace("TO", "2") if kernel.startswith("Memcpy") and kernel[6:].split() else "" + if k not in ("P2P", "D2D", "H2D", "D2H", "H2H"): + m = re.search(r"kind_src:(\w+) kind_dst:(\w+)", stats.get("memcpy_details") or "") + k = "2".join("D" if x == "device" else "H" for x in m.groups()) if m else "D2D" + return "memcpy", k + if "Memset_details" in stats or kernel.startswith("Memset"): + return "memset", None + c = gpu_collective(kernel, stats.get("hlo_op")) + return ("collective", c) if c else ("compute", None) + + +def gpu_bytes(stats): + """A memcpy's `size:` (a memset's `num_bytes:`), or None.""" + m = re.search(r"\b(?:size|num_bytes):(\d+)", stats.get("memcpy_details") or stats.get("Memset_details") or "") + return int(m.group(1)) if m else None + + +def gpu_path(stats): + """A GPU event's JAX name stack: its `name` stat, else its `tf_op` unless that is the `XlaModule:` every kernel + carries; None for neither.""" + t = stats.get("tf_op") + return stats.get("name") or (t if t and not str(t).startswith("XlaModule") else None) + + +def gpu_module_name(stats): + """`jit_fwd_c0(3)`: a GPU execution named as a TPU module is, its program id in parentheses.""" + p = stats.get("program_id") + return f'{stats.get("hlo_module")}({p})' if p is not None else str(stats.get("hlo_module")) + + +class Event: + """One module or op execution, with its XLA cost-model stats attached.""" + + __slots__ = ("start", "dur", "name", "stats") + + def __init__(self, start, dur, name, stats): + self.start, self.dur, self.name, self.stats = start, dur, name, stats + + @property + def end(self): + return self.start + self.dur + + @property + def base(self): + """`jit_bwda_c0(1731438548)` -> `jit_bwda_c0`; `%fusion.3 = f32[..]` -> `fusion`.""" + n = self.name.split(" = ")[0].lstrip("%") + return n.split("(")[0].split(".")[0] + + @property + def program_id(self): + """The `(12345)` in a module name: the program's id. + + Not what tells chunks apart: a pipeline program's name carries its chunk + (`_c`), and for programs with identical HLO, which show under one + name, the device and the order within the step do. Two programs under + one base name differ here; `is_mpmd` reads it, SPMD running one + executable everywhere. + """ + if "(" in self.name and self.name.endswith(")"): + return self.name[self.name.rindex("(") + 1 : -1] + return "" + + +class Trace: + """One xplane file, flattened to what an MPMD question actually needs.""" + + # The only lines anything here reads. Materialising the rest is not free: + # `counters_0` is 43,641 zero-duration events per device, 95% of the events + # in the file, and about a second of parse time that is thrown away. + DEVICE_LINES = ("XLA Modules", "XLA Ops", "Steps") + # 'GPU' on a capture read by `_read_gpu`. A class attribute, so a Trace built + # without a file (`Trace.__new__`, as xprof_test's are) is a TPU one. + platform = "TPU" + notes = () + + def __init__(self, path): + self.path = path + xplane_pb2 = _xplane_pb2() + from google.protobuf.message import DecodeError + + space = xplane_pb2.XSpace() + with open(path, "rb") as f: + try: + space.ParseFromString(f.read()) + except DecodeError as e: + # Easy to hit: the `RUN.txt` and the `*.trace.json.gz` that sit beside + # every capture are both plausible things to name on the command line. + raise SystemExit(f"{path} is not a serialized XSpace: {e}") from e + self.devices = {} # dev -> {line name -> [Event]} + self.peaks = {} # dev -> (peak_flops, peak_hbm_bw) + self.plane_stats = {} # dev -> {plane stat name -> value} + self.n_steps_line = {} # dev -> len(Steps), to show how wrong it is + self.host = {} # line name -> [Event], the driver thread + self.sparsecore = [] # plane names set aside, see below + self.notes = [] # what a reading had to approximate; `main` prints them + gpu, tree = [], {} # GPU planes, read only where there is no TPU one + for pl in space.planes: + if pl.name.startswith("/device:TPU"): + # `/device:TPU:0 SparseCore 0` is a plane too, on chips that have + # SparseCores (v6e has two per chip). It has its own line types -- + # `Sparse Core Steps`, `TEC 0..15` -- and none of the `DEVICE_LINES`, + # so everything below is about the TensorCore planes, keyed by the + # bare device number. MoE gathers and scatters are what land there. + tail = pl.name.rsplit(":", 1)[1] + if not tail.isdigit(): + self.sparsecore.append(pl.name) + continue + d = int(tail) + meta = self._op_metadata(pl) + self.devices[d] = {ln.name: self._events(pl, ln, meta) for ln in pl.lines if ln.name in self.DEVICE_LINES} + self.n_steps_line[d] = len(self.devices[d].get("Steps", [])) + st = {pl.stat_metadata[s.metadata_id].name: s for s in pl.stats} + # e.g. `has_megacore`: on v5p two TensorCore planes are ONE chip + self.plane_stats[d] = { + k: getattr(v, v.WhichOneof("value")) if v.WhichOneof("value") else None for k, v in st.items() + } + self.peaks[d] = ( + st["peak_teraflops_per_second"].double_value * 1e12 if "peak_teraflops_per_second" in st else None, + st["peak_hbm_bw_gigabytes_per_second"].double_value * 1e9 + if "peak_hbm_bw_gigabytes_per_second" in st + else None, + ) + elif pl.name == "/host:CPU": + self.host = {ln.name: self._events(pl, ln) for ln in pl.lines if ln.name.startswith(("python", "train.py"))} + elif pl.name.startswith("/device:GPU:"): + gpu.append(pl) + elif pl.name == SCOPE_TREE: + tree = scope_tree(pl) + if not self.devices and gpu: + self._read_gpu(gpu, tree) + if not self.devices: + raise SystemExit(f"no /device:TPU:* planes in {path}, nor /device:GPU:*") + + def _read_gpu(self, planes, tree): + """The GPU planes -> the per-device lines the TPU planes carry natively (GPU CAPTURES, in the module docstring). + + `XLA Ops` holds every event inside a program and `Transfers` the ones + outside every program, each an Event named by its `hlo_op` (else its own + name) with stats `kernel` (that name), `stream` (the line id), `kind` + (`gpu_op_kind`'s, its detail under the same key: `collective` + 'all-gather', `memcpy` 'P2P'), `hlo_module` / `program_id`, `tf_op` (the + JAX name stack, `gpu_path`) and `bytes` (a copy's). An `XLA Modules` event + keeps its execution's events, in start order, as `kernels`. Peaks: + (None, `memory_bandwidth`) -- a GPU plane carries no FLOP/s peak. + """ + self.platform = "GPU" + approx = 0 + for pl in planes: + tail = pl.name.rsplit(":", 1)[1] + if not tail.isdigit(): + continue + d = int(tail) + ks = gpu_kernels(pl) + evs = [] + for s, e, stream, name, st in ks: + kind, what = gpu_op_kind(name, st) + stats = {"kernel": name, "stream": stream, "kind": kind} + if what: + stats[kind] = what + if st.get("hlo_module"): # in a program, as `gpu_executions` reads it + stats["hlo_module"] = st["hlo_module"] + if st.get("program_id") is not None: + stats["program_id"] = st["program_id"] + path, nb = gpu_path(st), gpu_bytes(st) + if path: + stats["tf_op"] = path + if nb is not None: + stats["bytes"] = nb + evs.append(Event(s, e - s, st.get("hlo_op") or name, stats)) + groups, n = gpu_executions(ks, tree) + approx += n + mods = [] + for idx in groups: + mine = [evs[i] for i in idx] + lo, hi = min(m.start for m in mine), max(m.end for m in mine) + mods.append( + Event( + lo, hi - lo, gpu_module_name(ks[idx[0]][4]), {"hlo_module": ks[idx[0]][4]["hlo_module"], "kernels": mine} + ) + ) + mods.sort(key=lambda ev: (ev.start, -ev.dur)) + self.devices[d] = { + "XLA Modules": mods, + "XLA Ops": [ev for ev in evs if "hlo_module" in ev.stats], + "Transfers": [ev for ev in evs if "hlo_module" not in ev.stats], + } + self.n_steps_line[d] = None + smd, ps = {k: m.name for k, m in pl.stat_metadata.items()}, {} + for s in pl.stats: # gpu_device_name, clock_rate, core_count, memory_bandwidth, ... + w = s.WhichOneof("value") + v = getattr(s, w) if w else None + ps[smd.get(s.metadata_id, "?")] = smd.get(v) if w == "ref_value" else v + self.plane_stats[d] = ps + bw = ps.get("memory_bandwidth") + self.peaks[d] = (None, float(bw) if bw else None) + if approx: + self.notes.append( + f"{approx} GPU events have no scope in the {SCOPE_TREE} tree: each run of consecutive " + "events of one program counts as one execution there, so back-to-back executions of a " + "program read as one (`gpu_executions`)" + ) + + def label(self, d): + """`TPU:0` or `GPU:0`: the device as every report names it.""" + return f"{self.platform}:{d}" + + # Stats of an op's METADATA (not of each event) worth attaching to its + # events. `tf_op` is the HLO op_name, i.e. the JAX name stack: where + # `jax.named_scope` lands -- `fsdp_all_gather` and the rest (see + # `cmd_scopes`) -- and what the trace viewer's "Framework Name Scope" row is + # built from. `hlo_category` is XLA's own class of the op ("convolution + # fusion", "all-reduce-scatter fusion", ...): the only marker that a TPU + # collective fused into `fusion.N` is a collective at all. + OP_METADATA = ("tf_op", "hlo_category") + + @classmethod + def _op_metadata(cls, pl): + """Op metadata id -> {stat: value} for the `OP_METADATA` stats it carries. + + They are stats of the op's *metadata*, not of each event, so `_events` + would never see them. + """ + ids = {m.name: k for k, m in pl.stat_metadata.items()} + want = {ids[n]: n for n in cls.OP_METADATA if n in ids} + out = {} + if not want: + return out + for mid, em in pl.event_metadata.items(): + for s in em.stats: + name = want.get(s.metadata_id) + if name is not None: + out.setdefault(mid, {})[name] = s.str_value or ( + pl.stat_metadata[s.ref_value].name if s.ref_value in pl.stat_metadata else "" + ) + return out + + @staticmethod + def _events(pl, ln, meta=None): + out = [] + for e in ln.events: + stats = {} + for s in e.stats: + nm = pl.stat_metadata[s.metadata_id].name + stats[nm] = getattr(s, s.WhichOneof("value")) if s.WhichOneof("value") else None + if meta and e.metadata_id in meta: + stats.update(meta[e.metadata_id]) + out.append(Event(ln.timestamp_ns * 1000 + e.offset_ps, e.duration_ps, pl.event_metadata[e.metadata_id].name, stats)) + out.sort(key=lambda ev: (ev.start, -ev.dur)) + return out + + def modules(self, d): + return self.devices[d].get("XLA Modules", []) + + def ops(self, d): + return self.devices[d].get("XLA Ops", []) + + def device_list(self, d): + """`-d` resolved to a list of devices, with a diagnostic on a bad index.""" + if d is None: + return sorted(self.devices) + if d not in self.devices: + have = ", ".join(self.label(x) for x in sorted(self.devices)) + raise SystemExit(f"no {self.label(d)} in {self.path} -- it has {have}") + return [d] + + def n_steps(self): + """How many training steps the capture holds, from module-name periodicity. + + A step runs the same modules in the same order every time, so each device's + module-name sequence is k identical blocks and k is the step count. That + is exact and needs no timing threshold, which matters because the obvious + alternative -- cut at the widest gaps in the union of the device timelines, + where the end-of-step `block_until_ready` shows up -- is wrong: + + * On the mbs-256 gpipe capture the forward->backward turnaround leaves + all four devices idle for 108 and 130 us, and a threshold under those + reports 4 steps for a 2-step run. + * On the mbs-4096 1f1b capture the widest union gap (646 us) is inside + the drain, not at the edge -- the real edge is the *narrowest* of the + five gaps over 100 us (646, 640, 638, 637, 582) -- so cutting at the + widest reports walls of 476 and 14 ms for a run whose steps are both + 245 ms. + + There is no threshold between those two, which is why this does not use + one. Returns 1 if nothing repeats -- a single-step capture, or one the + profiler truncated; `summary` prints the union gaps next to the boundaries + it chose so a truncated capture is visible rather than silent. + """ + if getattr(self, "_n_steps", None) is not None: + return self._n_steps + seqs = [[m.name for m in self.modules(d)] for d in sorted(self.devices)] + seqs = [s for s in seqs if s] + if not seqs: + self._n_steps = 0 + return 0 + g = 0 + for s in seqs: # k must divide every device's count + g = math.gcd(g, len(s)) + best = 1 + for k in range(2, g + 1): + if g % k == 0 and all(all(nm == s[i % (len(s) // k)] for i, nm in enumerate(s)) for s in seqs): + best = k + self._n_steps = best + return best + + def is_mpmd(self): + """Do the devices run different programs, or one program replicated? + + Worth asking before printing any of the pipeline readings, because this + tool gets pointed at the SPMD baseline too: on a MaxText capture "step + lead-in (waiting for the fill)" and "that spread IS the bubble" are not so + much wrong as meaningless, and a reader has no way to tell. + + The test is whether any program id runs on more than one device. Names + will not do it: MaxText's TPU:0 additionally runs the `jit__multi_slice` + staging programs, so a name-multiset comparison calls it MPMD. Program + ids are exact -- SPMD replicates one executable, so all four devices share + its id, while every MPMD chunk lives on exactly one device. + """ + ids = [{m.program_id for m in self.modules(d)} for d in self.devices] + ids = [s for s in ids if s] + return len(ids) > 1 and not set.intersection(*ids) + + def steps(self): + """Each step as a (start, end) window in picoseconds. + + The window runs from the first module to start on ANY device to the last to + finish, so it contains the pipeline fill and drain. That is the + denominator a pipeline should be judged on: a stage that goes quiet early + is idle, not finished. + """ + k = self.n_steps() + if not k: + return [] + out = [] + for i in range(k): + lo, hi = None, None + for d in self.devices: + mods = self.modules(d) + if not mods: + continue + blk = len(mods) // k + a, b = mods[i * blk].start, mods[(i + 1) * blk - 1].end + lo = a if lo is None else min(lo, a) + hi = b if hi is None else max(hi, b) + out.append((lo, hi)) + return out + + def union_gaps(self): + """Every gap in the union of the device timelines, longest first. + + `steps` does not use these -- but a threshold-based reading would, and + `summary` prints them beside the boundaries it chose so you can see for + yourself that the widest gap is not always the step edge. + """ + spans = sorted((m.start, m.end) for d in self.devices for m in self.modules(d)) + if not spans: + return [] + gaps, cur = [], spans[0][1] + for s, e in spans[1:]: + if s > cur: + gaps.append(s - cur) + cur = max(cur, e) + return sorted(gaps, reverse=True) + + def all_idle(self, lo, hi): + """Intervals within [lo, hi) when NO device is running any module. + + Deliberately not what `gaps` measures, and the difference is the whole + point. A pipeline bubble is one stage waiting while another works: it is + the price of the schedule, it is bounded by `(S-1)/(M*V + S-1)`, and you + buy throughput with it. An interval where *every* chip is idle buys + nothing. Reading one for the other is easy -- the trace viewer draws them + identically -- and it is why a 30.9 ms per-device idle figure and a 0.16 ms + nobody-is-working figure can both be true of the same step. + + Returns `(start, end, before, after)` per interval, where `before` is the + `(device, event)` whose end opened it and `after` the `(device, event)` + pairs that close it, so the caller can name the handoff it sits in. + """ + # The clip is redundant given the overlap filter -- checked against all 38 + # step windows of 19 v6e-4 captures, it changes nothing -- and it is + # here anyway so that every span is visibly inside the window at the point + # you read it, rather than only if you also reason about the filter. + spans = sorted( + (max(m.start, lo), min(m.end, hi), d, m) + for d in self.devices + for m in self.modules(d) + if m.end > lo and m.start < hi + ) + out, cur, prev = [], lo, None + for s, e, d, m in spans: + if s > cur: + out.append((cur, s, prev, [(dd, mm) for ss, _, dd, mm in spans if ss == s])) + if e > cur: + cur, prev = e, (d, m) + if hi > cur: + out.append((cur, hi, prev, [])) + return out + + def framing(self): + """The capture's outermost host frames: what is program, what is profiler. + + A trace file is not a recording of your program, it is a recording of the + process that hosted it, and on these captures the program is the minority + of it -- 102 ms of device work inside a 627 ms file, the other 525 ms being + `jax.profiler.trace`'s own `__enter__` and `__exit__`. Measured over the + 19 v6e-4 captures the profiler's share of the file runs 40% to 84%, + mean 59%; quote the range, not the 84%, which is the worst single file. + Opened in a viewer, that is most of the width, every pixel of it with four + idle chips, and it looks exactly like a catastrophic pipeline stall. It is + not; it is the profiler starting up and then serializing what it captured. + + Teardown dominates and does not scale with the step: 397-499 ms across a + 2.3x step-size and 4x model sweep, because what it serializes is ~52 MB of + which 83-86% is the fixed `counters_0` sampling. Do not go looking for the + cause of it in your own code. + + Returns `(start_up, work_lo, work_hi, tear_down, frames)` in picoseconds, + with `frames` the outermost host frames in order for the caller to print. + """ + if not self.host: + return 0, None, None, 0, [] + line = max(self.host.values(), key=lambda v: sum(o.name.startswith("PjitFunction") for o in v)) + frames = children(line, min(o.start for o in line), max(o.end for o in line) + 1) if line else [] + lo = min((m.start for d in self.devices for m in self.modules(d)), default=None) + hi = max((m.end for d in self.devices for m in self.modules(d)), default=None) + up = sum(f.dur for f in frames if "__enter__" in f.name) + down = sum(f.dur for f in frames if "__exit__" in f.name) + return up, lo, hi, down, frames + + def driver_busy(self, lo, hi): + """Wall the Python driver thread spends issuing work, within [lo, hi]. + + One thread issues every module execution and every transfer in the whole + pipeline, so its duty cycle is the ceiling MPMD dispatch can support: at + 100% the next step cannot be enqueued until the current one is done. + + The thread's whole life is six outermost frames: `jax.profiler.trace`'s + `__enter__`, then per step a frame of the driving script that issues (a + `` on these captures) and an `$api.py block_until_ready` that + waits, then `__exit__`. Count the issuing frames -- the ones holding a + `PjitFunction` -- clipped to the window. + + Do not measure this as the sum of `PjRtCApiLoadedExecutable::Execute` + instead: that is the innermost leaf of a dispatch and misses the tracing, + the argument handling and all 112 transfer sends per step, which on the + mbs-256 capture is half of the real figure. Nor as the residual + `window - block_until_ready`, which is the same number on fifteen of the + nineteen captures and wrong on the other four: the window comes from the + device planes and this line from the host plane, and where the two clocks + are far apart -- 4.2 ms on mbs-256 gpipe, the first capture its process + took, whose `start_trace` ran 47 ms instead of 26 -- the window opens + before the first dispatch and the residual charges the profiler's own + start-up as work, reporting 14.9 ms against 10.7 for the step after it. + """ + # `self.host` is keyed by whatever the plane calls the interpreter line -- + # `python3` on these captures, but that is the binary's name, and a host + # plane can carry one line per thread. Take the line doing the dispatching. + line = max(self.host.values(), default=[], key=lambda v: sum(o.name.startswith("PjitFunction") for o in v)) + if not line: + return 0 + busy = 0 + for e in children(line, min(x.start for x in line), max(x.end for x in line) + 1): + if not any(o.name.startswith("PjitFunction") and e.start <= o.start and o.end <= e.end for o in line): + continue + s, t = max(e.start, lo), min(e.end, hi) + if t > s: + busy += t - s + return busy + + +# ------------------------------------------------------------------ containment +def children(events, start, end): + """Direct children of [start, end): outermost non-overlapping contained ops. + + The `XLA Ops` line is flat but the events nest by time, so a plain sum + double-counts a `while` against its own body. One greedy left-to-right pass + over events sorted by (start, -duration) keeps only the outermost ones. + + `events` must already be sorted that way -- `Trace._events` does it. Passing + an unsorted list silently returns the wrong answer, because the pass relies on + a container arriving before anything it contains. + """ + out, cur = [], -1 + for e in events: + if e.start >= start and e.end <= end and e.dur > 0 and e.start >= cur: + out.append(e) + cur = e.end + return out + + +def merged(events): + """Wall covered by `events`, overlaps counted once. + + Module busy does not compare across MPMD and SPMD: MaxText runs the whole + training step as one program, so the sum of its `XLA Modules` durations is + 99.6% of the capture by construction, whatever the chip is doing. The union + of the `XLA Ops` intervals is the same measurement on both. + + `events` must be sorted by start -- `Trace._events` does it. + """ + tot, cur = 0, None + for e in events: + if cur is None or e.start > cur[1]: + tot += cur[1] - cur[0] if cur else 0 + cur = [e.start, e.end] + else: + cur[1] = max(cur[1], e.end) + return tot + (cur[1] - cur[0] if cur else 0) + + +def _merge_spans(spans, lo=-math.inf, hi=math.inf): + """(start, end) `spans`, in any order, clipped to [lo, hi) and merged: sorted disjoint [start, end] pairs.""" + out = [] + for s, e in sorted((max(s, lo), min(e, hi)) for s, e in spans if e > lo and s < hi): + if out and s <= out[-1][1]: + out[-1][1] = max(out[-1][1], e) + else: + out.append([s, e]) + return out + + +def _span_union(spans, lo, hi): + """Wall covered by (start, end) `spans` inside [lo, hi), overlaps counted once.""" + return sum(e - s for s, e in _merge_spans(spans, lo, hi)) + + +def _overlap(union, s, e): + """How much of [s, e) the `_merge_spans` pairs `union` cover.""" + return sum(min(b, e) - max(a, s) for a, b in union if a < e and b > s) + + +def _select(tr, devs, want): + """Instances of module `want` on `devs`, as (device, event) pairs. + + An exact base-name match wins if there is one; failing that, `want` is + taken as a substring, but only where it picks out one program. A substring + pools the program you asked for with every one whose name extends it, and + reports a blend that is none of them: on one v6e-4 capture `-m + jit__bwd` caught the 14 first-microbatch backwards (1151.8 us each) *and* + the 98 accumulating `jit__bwda` (2015.5 us), and reported 1907.6 us. The + pipeline's names extend each other the same way -- `jit_fwd_c0` and + `jit_fwd_c0_agself`, `jit_bwda_c0` and `jit_bwda_c0_rs2p0` -- and a capture + need not hold the plain program at all: at S=2, V=2, M=4 under the default + flags every backward of chunk 0 carries part of chunk 2's reduce-scatter, so + `-m jit_bwda_c0` would pool `jit_bwda_c0_rs2p0`, `_rs2p5` and `_rs2p6`. A + substring in several programs' names therefore exits, listing them with + their instance counts for you to pick one. One in a single program's name + -- a bare program id, or `jit_bwda_c0` where chunk 0's only accumulating + backward is `jit_bwda_c0_rsself` -- reads that program, and stderr names it. + Exact-wins means the name you read off `modules` selects exactly that row. + """ + pairs = [(d, m) for d in devs for m in tr.modules(d)] + exact = [(d, m) for d, m in pairs if m.base == want] + if exact: + return exact + sub = [(d, m) for d, m in pairs if want in m.name] + bases = collections.Counter(m.base for _, m in sub) + if len(bases) > 1: + rows = "\n".join(f" {n:6d}x {b}" for b, n in sorted(bases.items())) + raise SystemExit( + f"no program on device(s) {devs} is named {want!r}, and {len(bases)} have it in their names -- " + f"pooled, they would report a blend that is none of them; pick one with -m:\n{rows}" + ) + if sub: + print( + f"# no program on device(s) {devs} is named {want!r}: reading {sub[0][1].base}, whose name has it", + file=sys.stderr, + ) + return sub + + +def uncontended(durs): + """A stall inside a module inflates the mean; the median survives it. + + Returns (n, mean, median, p10) in the same unit as the input. `p10` is the + nearest-rank 10th percentile, `ceil(0.10 n)`th smallest -- for the n=14 and + n=28 samples these captures give, that is the 2nd and 3rd, not the 1st and + 2nd that truncation would pick. + """ + if not durs: + return (0, 0.0, 0.0, 0.0) + s = sorted(durs) + return (len(s), sum(s) / len(s), statistics.median(s), s[-(-len(s) // 10) - 1]) + + +# ------------------------------------------------------------------- subcommands +def cmd_summary(tr, args): + steps = tr.steps() + gaps = tr.union_gaps() + print(f"{tr.path}\n") + counts = ", ".join(f"{len(tr.modules(d))}" for d in sorted(tr.devices)) + print( + f"{len(tr.devices)} device planes; {len(steps)} step(s), because the " + f"module-name sequence\n ({counts} modules per device) is that many " + "identical repeats. No timing threshold." + ) + for d in sorted(tr.devices): + if tr.n_steps_line[d] is None: # a GPU plane: no such line + print( + f" {tr.label(d)} has no `Steps` line; its modules are its program executions, read off its " + f"kernels\n (GPU CAPTURES in this file's docstring)" + ) + break + print( + f" the `Steps` line on TPU:{d} claims " f'{tr.n_steps_line[d]} "steps" -- that is module executions, ignore it' + ) + break + between = [b[0] - a[1] for a, b in zip(steps, steps[1:])] + if between: + rest = list(gaps) + for g in between: # a boundary IS a union gap; drop it + if g in rest: + rest.remove(g) + print(" all devices go quiet for " + ", ".join(f"{g / PS_MS:.2f}ms" for g in between) + " between steps") + decoys = [g for g in rest if g >= min(between)] + if decoys: + print( + f" {len(decoys)} gap(s) INSIDE a step are just as wide (up to " + f"{max(decoys) / PS:.0f}us) -- a threshold would\n have split " + "there and been wrong; see `Trace.n_steps`" + ) + elif rest: + print( + f" the other {len(rest)} union gaps are all narrower, " + f"largest {rest[0] / PS:.1f}us -- transfer latency, not step edges" + ) + elif gaps: + # One step means nothing repeated, which is either the truth or a capture + # the profiler cut short. Say so, and show the widest hole: if that is a + # step edge, every per-step number below is really several steps merged. + print( + f" only 1 step, so no boundary to show. The widest all-device gap is " + f"{gaps[0] / PS:.1f}us -- if that\n is a step edge the capture is " + 'truncated and this "1 step" is really several; see `Trace.n_steps`' + ) + print() + hdr = ( + f'{"":>6s} {"modules":>8s} {"programs":>9s} {"busy":>10s} ' + f'{"own span":>10s} {"occ/own":>8s} {"occ/step":>9s} {"idle":>10s}' + ) + print(hdr) + print("-" * len(hdr)) + for si, (lo, hi) in enumerate(steps): + if len(steps) > 1: + print(f"step {si} [{(hi - lo) / PS_MS:.2f} ms wall]") + for d in sorted(tr.devices): + mods = [m for m in tr.modules(d) if m.start >= lo and m.end <= hi] + if not mods: + continue + busy = sum(m.dur for m in mods) + span = max(m.end for m in mods) - min(m.start for m in mods) + prog = len({m.program_id for m in mods}) + print( + f"{tr.label(d)} {len(mods):8d} {prog:9d} {busy / PS_MS:9.2f}ms " + f"{span / PS_MS:9.2f}ms {100 * busy / span:7.1f}% " + f"{100 * busy / (hi - lo):8.1f}% {(hi - lo - busy) / PS_MS:9.2f}ms" + ) + drv = tr.driver_busy(lo, hi) + if drv: + print( + f" driver thread issuing work: {drv / PS_MS:.2f} ms " + f"= {100 * drv / (hi - lo):.1f}% of the step; the rest it is " + "waiting, mostly in\n `block_until_ready` -- only mostly, because " + "this line comes off the host plane\n and the step window off the " + "device planes, and the two clocks can sit several\n ms apart (see " + "`driver_busy`). One Python thread issues every execution and\n " + "every transfer, so dispatch binds as this approaches 100%." + ) + print() + print( + "occ/own divides by the device's own first-to-last module and so hides" + "\nthe drain -- the last stage finishes early and simply stops being " + "measured.\nocc/step divides by the whole step and is the number a " + "pipeline is judged on." + ) + if tr.is_mpmd(): + print("The two agree on stage 0 and diverge on the last stage; that spread " "IS the bubble.") + print() + if steps: + lo = min(m.start for d in tr.devices for m in tr.modules(d)) + hi = max(m.end for d in tr.devices for m in tr.modules(d)) + com, own = [], [] + for d in sorted(tr.devices): + mods = tr.modules(d) + if not mods: # a plane the capture caught idle + continue + busy = sum(m.dur for m in mods) + com.append(busy / (hi - lo)) + own.append(busy / (max(m.end for m in mods) - min(m.start for m in mods))) + n = len(com) + print( + f"whole capture ({(hi - lo) / PS_MS:.2f} ms, {len(steps)} steps), " + "mean over devices -- the busy share on the common clock and on each device's own window:" + ) + print(f" common clock {100 * sum(com) / n:5.1f}% busy, " f"{100 - 100 * sum(com) / n:4.1f}% idle") + print(f" per-device window {100 * sum(own) / n:5.1f}% busy, " f"{100 - 100 * sum(own) / n:4.1f}% idle\n") + ops = {d: tr.ops(d) for d in sorted(tr.devices) if tr.ops(d)} + if ops: + olo = min(e.start for v in ops.values() for e in v) + ohi = max(e.end for v in ops.values() for e in v) + print( + f"per device, from the union of the `XLA Ops` intervals over a " + f"{(ohi - olo) / PS_MS:.2f} ms clock.\nThat is the measure to " + "compare against an SPMD capture -- see `merged`." + + ("\nNote again how much occ/own flatters the stage with the " "longest drain:" if tr.is_mpmd() else "") + ) + for d, v in ops.items(): + busy = merged(v) + span = max(e.end for e in v) - min(e.start for e in v) + print( + f" {tr.label(d)} {busy / PS_MS:8.2f}ms busy " + f"{100 * busy / (ohi - olo):6.1f}% " + f"(occ/own {100 * busy / span:.1f}% of its own {span / PS_MS:.2f} ms)" + ) + print() + if tr.platform == "GPU": + _gpu_summary(tr) + print( + "programs per device, by name and (program id). A pipeline program's name carries its chunk, _c,\n" + "but programs with identical HLO all show under one name, whichever loaded first: for those the device\n" + "and the order within the step tell the chunks apart." + ) + for d in sorted(tr.devices): + c = collections.Counter(m.name for m in tr.modules(d)) + print(f" {tr.label(d)}") + for nm, n in sorted(c.items(), key=lambda kv: -kv[1]): + print(f" {n:4d}x {nm}") + + +def _gpu_summary(tr): + """`summary`'s GPU lines: each device's kernel time against its programs' spans, and what ran outside them -- + the stage boundary apart from the rest.""" + print( + "inside the programs, per device: their kernels' union against the programs' own spans. A GPU\n" + "module spans the gaps between its kernels: a host launching kernels slower than they run, or a\n" + "stream waiting on another, is the difference" + ) + for d in sorted(tr.devices): + mods = tr.modules(d) + if mods: + span = sum(m.dur for m in mods) + kern = sum(merged(m.stats["kernels"]) for m in mods) + coll = sum(merged([k for k in m.stats["kernels"] if k.stats.get("kind") == "collective"]) for m in mods) + print( + f" {tr.label(d)} {kern / PS_MS:8.2f}ms of kernels in {span / PS_MS:.2f}ms of programs " + f"({100 * kern / span:.1f}%); collective kernels {coll / PS_MS:.2f}ms of it" + ) + # The stage boundary is the copies between GPUs and the send/recv: the copies to and from host memory + # (--offload-residuals') run outside every program too. + parts = ([], []) + for x in tr.devices[d].get("Transfers", []): + parts[x.stats.get("memcpy") != "P2P" and x.stats["kind"] != "collective"].append(x) + for xs, what in zip( + parts, + ( + "PJRT's copies between GPUs and cross-process send/recv: the stage boundary", + "the rest, not the boundary: PJRT's copies to and from host memory, " "--offload-residuals' among them", + ), + ): + if not xs: + continue + kinds = collections.Counter( + f'Memcpy{x.stats["memcpy"]}' if x.stats.get("memcpy") else x.stats["kernel"].split("(")[0] for x in xs + ) + nb = sum(x.stats.get("bytes") or 0 for x in xs) + print( + f' outside any program: {", ".join(f"{n} {k}" for k, n in kinds.most_common())}' + f" -- {merged(xs) / PS_MS:.2f}ms" + (f", {nb / 1e6:.1f} MB copied" if nb else "") + f"\n ({what})" + ) + print() + + +CHARS = [ + ("fwd", "F"), + ("_fba", "A"), # (and a split last chunk's AI, fbai / fbi: the same program less its layers' dW) + ("_fb", "A"), + ("_bwdi", "I"), # the split backward's halves, before '_bwd', a prefix of both + ("_bwdw", "W"), + ("_bwda", "B"), + ("_bwd", "b"), + ("loss", "L"), + ("multi_slice", "s"), + ("gather", "G"), + ("reduce", "R"), + ("update", "U"), + ("train_step", "T"), +] + + +def _char(name): + for pat, ch in CHARS: + if pat in name: + return ch + return "o" + + +def cmd_timeline(tr, args): + steps = tr.steps() + if not steps: + raise SystemExit(f"no XLA Modules events in {tr.path}") + if args.width < 1: + raise SystemExit(f"--width must be at least 1, got {args.width}") + i = args.step if args.step >= 0 else args.step + len(steps) + if not 0 <= i < len(steps): + raise SystemExit( + f"--step {args.step} out of range: this capture has " + f"{len(steps)} step(s), so 0..{len(steps) - 1} " + "(or -1 for the last)" + ) + lo, hi = steps[i] + width = args.width + scale = (hi - lo) / width + print(f"{tr.path}") + print( + f"step {i} of {len(steps)}: {(hi - lo) / PS_MS:.2f} ms over {width} " f"columns, {scale / PS:.1f} us per column\n" + ) + for d in sorted(tr.devices): + row = [" "] * width + for m in tr.modules(d): + if m.end <= lo or m.start >= hi: + continue + a = max(0, int((m.start - lo) / scale)) + b = min(width - 1, int((m.end - lo) / scale)) + for i in range(a, b + 1): + row[i] = _char(m.name) + busy = sum(m.dur for m in tr.modules(d) if m.start >= lo and m.end <= hi) + print(f'{tr.label(d)} |{"".join(row)}| {100 * busy / (hi - lo):5.1f}% busy') + print("\n F = forward b = backward (first microbatch, no accumulate)") + print(" B = backward + accumulate A = fused fwd+bwd (last chunk)") + print(" I / W = a split backward's input / weight gradients (zbh1, zbh2)") + print(" L = MaxText's single fused step s = multi_slice space = IDLE") + print( + "\n A blank run on an early device while a later device is busy is the" + "\n pipeline bubble. A blank column across ALL devices is a step edge" + "\n or a host stall -- check the driver line in `summary`." + ) + + +def cmd_modules(tr, args): + devs = tr.device_list(args.device) + print(tr.path) + for d in devs: + by = collections.defaultdict(list) + for m in tr.modules(d): + by[m.name].append(m.dur / PS) + print(f"\n{tr.label(d)}") + print(f' {"module":52s} {"n":>4s} {"total":>9s} {"mean":>9s} ' f'{"median":>9s} {"p10":>9s}') + for nm, durs in sorted(by.items(), key=lambda kv: -sum(kv[1])): + n, mean, med, p10 = uncontended(durs) + print(f" {nm[:52]:52s} {n:4d} {sum(durs) / 1e3:8.2f}ms " f"{mean:8.1f}us {med:8.1f}us {p10:8.1f}us") + print( + " mean > median means some instances absorbed a stall (a receive " + "wait\n lands INSIDE the module, not in the gap before it). Compare " + "medians." + ) + + +def cmd_gaps(tr, args): + """Where each device's idle goes, measured against the whole step. + + Gaps *between* a device's modules are only part of its idle: the last stage + also sits out the fill at the head of the step and the drain at the tail, + and that is most of what it does. Counting only the in-between gaps -- the + bug this used to have -- divides by the device's own first-to-last module + and so reports the stage with the worst bubble as the one with the least + idle. Lead-in and drain are therefore buckets like any other, and the total + reconciles exactly with `summary`'s occ/step idle column. + """ + steps = tr.steps() + devs = tr.device_list(args.device) + print(f"{tr.path}\n") + print( + f"{len(steps)} step(s), {sum(hi - lo for lo, hi in steps) / PS_MS:.2f} " + "ms of wall between the first and last module of each." + ) + print(f'{"":>6s} {"total idle":>11s} classified by the module pair it ' "separates") + fill, drain = ( + ("step lead-in (waiting for the fill)", "step drain (waiting for stage 0)") + if tr.is_mpmd() + else ("step lead-in (before its first module)", "step drain (after its last module)") + ) + for d in devs: + buckets = collections.Counter() + tot = 0 + for lo, hi in steps: + mods = [m for m in tr.modules(d) if m.start >= lo and m.end <= hi] + if not mods: + continue + for key, g in ( + [(fill, mods[0].start - lo)] + + [(f"{_kind(a.name)} -> {_kind(b.name)}", b.start - a.end) for a, b in zip(mods, mods[1:])] + + [(drain, hi - mods[-1].end)] + ): + if g > 0: + buckets[key] += g + tot += g + print(f"\n{tr.label(d)} {tot / PS_MS:10.2f}ms") + for k, v in buckets.most_common(): + print(f" {v / PS_MS:10.2f}ms {100 * v / tot:5.1f}% {k}") + if len(steps) > 1: + off = sum(b[0] - a[1] for a, b in zip(steps, steps[1:])) + print( + f"\n Excluded: {off / PS_MS:.2f} ms between steps, when every device " + "is idle at once.\n That is the driver's end-of-step " + "`block_until_ready`, not pipeline idle." + ) + if tr.is_mpmd(): + print( + "\n A stage that waits mid-step (bwd -> bwda) is waiting on the " + "gradient coming\n back down the pipe; a stage that waits in lead-in " + "and drain is waiting for\n stage 0 at the step edges. The bubble " + "rotates around the pipeline, so the\n SHAPE of this table is the " + "finding -- the totals are nearly flat.\n Idle that is flat across " + "devices AND tracks the driver line is host dispatch." + ) + else: + print( + "\n Every device here runs the same program, so there is no bubble " + "to read a\n shape out of: the stages are replicas and their idle is " + "collective wait.\n Compare the totals with an MPMD capture's, not " + "the rows with each other." + ) + + +def _kind(name): + """A module name's program kind for the summary's transitions: the first of these it holds (each before the ones + it extends: '_bwdwa' before '_bwdw' before '_bwd', '_fbai' and '_fbi' before '_fba' and '_fb'), else its name.""" + for pat in ( + "fwd", + "_fbai", + "_fbi", + "_fba", + "_fb", + "_bwdi", + "_bwdwa", + "_bwdw", + "_bwda", + "_bwd", + "loss", + "multi_slice", + "gather", + "reduce", + "update", + ): + if pat in name: + return pat.lstrip("_") + return name.split("(")[0] + + +def cmd_idle(tr, args): + """Time when NO device is working: the idle a bubble does not explain. + + `gaps` answers "when is this stage idle", and the answer is dominated by the + bubble, which is the schedule working as designed. This answers "when is + the machine idle", which is a different and much smaller number, and every + millisecond of it is recoverable in principle. Three things produce it and + they want opposite responses, so they are reported apart: + + profiler start-up and teardown -- not your program at all, and 40-84% of + the file (mean 59% over 19 v6e-4 captures); + the gap between steps -- one host round trip, and flat in absolute terms + across a 16x microbatch sweep, which is how you know it is host and not + data. Issuing both steps before waiting on either took this from 406 + us per boundary to 7.5 us; a capture that still shows hundreds of + microseconds here was taken by a loop that blocked; + holes inside a step -- a handoff nothing else overlaps, in the drain, + where the last microbatch's gradient walks back one stage at a time with + nothing left to hide behind. One such hop per step is the floor. + + What that leaves, at S=4 V=2 M=8 E4096 mbs256: `search`, the schedule the + code actually picks, idles every chip for 0.05% of the step. MaxText SPMD + on the same shape is 0.01%. `1f1b` is 1.90% and `gpipe` 0.09%, but both are + 9-11 ms/step slower overall, so the idle is not what is wrong with them. + """ + up, wlo, whi, down, frames = tr.framing() + steps = tr.steps() + print(f"{tr.path}\n") + if frames and wlo is not None: + flo = min(min(f.start for f in frames), wlo) + fhi = max(max(f.end for f in frames), whi) + print( + f"capture framing -- {(fhi - flo) / PS_MS:.2f} ms of file, of which " + f"{(whi - wlo) / PS_MS:.2f} ms " + f"({100 * (whi - wlo) / (fhi - flo):.1f}%) has any device running:" + ) + if tr.platform == "GPU" and not up + down: + print( + f" ({len(frames)} outermost frames on the driver thread, none of them the profiler's: a GPU " + "capture runs\n without the Python tracer (profiling.profile_options), so there is no start-up " + "or teardown\n to split out, and no frame to list)" + ) + else: + for f in frames: + tag = ( + "profiler start-up" + if "__enter__" in f.name + else "profiler teardown, serializing the capture" + if "__exit__" in f.name + else "issuing a step" + if "lambda" in f.name + else "waiting" + ) + print(f" {(f.start - wlo) / PS_MS:+9.2f} ms for " f"{f.dur / PS_MS:8.2f} ms {tag}") + if up + down: + print( + f" {(up + down) / PS_MS:.2f} ms of that is profiler overhead with " + "the chips idle. It is not\n pipeline idle and it is not in any " + "timed region -- but it is most of what a\n trace viewer draws, " + "so do not read the file's own occupancy as the program's." + ) + print() + + in_step, n_holes = 0, 0 + for si, (lo, hi) in enumerate(steps): + holes = [h for h in tr.all_idle(lo, hi)] + tot = sum(b - a for a, b, _, _ in holes) + in_step += tot + n_holes += len(holes) + print( + f"step {si} [{(hi - lo) / PS_MS:.2f} ms] nobody working for " + f"{tot / PS_MS:.3f} ms ({100 * tot / (hi - lo):.2f}%) " + f"in {len(holes)} hole(s)" + ) + for a, b, before, after in sorted(holes, key=lambda h: h[0] - h[1]): + if b - a < args.min_us * PS: + continue + drv = tr.driver_busy(a, b) + src = f"{tr.label(before[0])} {_kind(before[1].name)}" if before else "lead-in" + dst = ", ".join(sorted({f"{tr.label(d)} {_kind(m.name)}" for d, m in after})) or "end of step" + print( + f" {(b - a) / PS:8.1f} us at {100 * (a - lo) / (hi - lo):5.1f}%" + f" of the step {src:18s} -> {dst:18s}" + f" driver issuing {100 * drv / (b - a):4.1f}%" + ) + if tr.platform == "GPU": + # Measured on modules, a hole misses the gaps INSIDE a GPU module (GPU CAPTURES): the kernel-level figure + # adds them, and every op lies inside its module's span, so the difference is exactly those gaps. + kern = _span_union([(o.start, o.end) for d in tr.devices for o in tr.ops(d)], lo, hi) + mods = _span_union([(m.start, m.end) for d in tr.devices for m in tr.modules(d)], lo, hi) + print( + f" kernel level: no kernel on any GPU for {(hi - lo - kern) / PS_MS:.3f} ms " + f"({100 * (hi - lo - kern) / (hi - lo):.2f}%), {(mods - kern) / PS_MS:.3f} ms of it inside a " + "program --\n the gaps between its kernels, where the host launching them slowly shows" + ) + if steps: + print( + f" (holes under {args.min_us:g} us are counted above but not " + "listed; they are the\n 1.1 us between two back-to-back modules on " + "one device, not a stall.)\n" + ) + + between = sum(b[0] - a[1] for a, b in zip(steps, steps[1:])) + if len(steps) > 1: + print( + f"between steps: {between / PS_MS:.3f} ms over " + f"{len(steps) - 1} boundary(ies), " + f"{between / (len(steps) - 1) / PS:.1f} us each." + ) + for a, b in zip(steps, steps[1:]): + drv = tr.driver_busy(a[1], b[0]) + print( + f" driver issuing {100 * drv / (b[0] - a[1]):.1f}% of it; the " + "rest is the round trip from\n the last module completing to " + "the next step being enqueued." + ) + span = sum(hi - lo for lo, hi in steps) + between + if span: + print( + f"\nall-chip idle over the {span / PS_MS:.2f} ms the steps occupy: " + f"{(in_step + between) / PS_MS:.3f} ms = " + f"{100 * (in_step + between) / span:.2f}%" + f"\n {in_step / PS_MS:.3f} ms inside steps, " + f"{between / PS_MS:.3f} ms between them." + ) + print( + "\n Compare with `gaps`, which will report far more idle per device. " + "Both are\n right: that is the bubble, one stage waiting while " + "another works, and it is\n what the schedule buys throughput with. " + "This number is the part nobody is\n using, and it is the only idle " + "worth calling waste." + ) + + +def cmd_ops(tr, args): + """Decompose a module into its top-level ops, pooled over devices. + + With no `-d`, every device's instances of the program go into one pool: a + stage's devices run the same program, and stages the trace lists under one + name run identical ones. Pooling is what makes the mean stable enough to + compare across shapes; programs whose names differ stay apart (`_select`). + Pass `-d` to isolate one stage. + """ + devs = tr.device_list(args.device) + sel = _select(tr, devs, args.module) + if not sel: + raise SystemExit(f"no module matching {args.module!r} on device(s) {devs}") + print(tr.path) + n = len(sel) + tot = sum(m.dur for _, m in sel) + agg, cnt = collections.Counter(), collections.Counter() + inner, icnt = collections.Counter(), collections.Counter() + covered = 0 + gpu = tr.platform == "GPU" + for d, m in sel: + if gpu: + # Nothing nests on a GPU, and which kernels are this execution's is known (`Trace._read_gpu`); the NCCL + # stream overlaps the compute stream, so coverage is their union. + kids = [k for k in m.stats["kernels"] if k.dur > 0] + covered += merged(kids) + for k in kids: + key = _gpu_gmm(k) or k.base + agg[key] += k.dur + cnt[key] += 1 + continue + ops = tr.ops(d) + kids = children(ops, m.start, m.end) + covered += sum(k.dur for k in kids) + for k in kids: + agg[k.base] += k.dur + cnt[k.base] += 1 + if k.base == "while": + # The body, not the `while` over again. `children` keeps anything the + # window contains and the window *is* `k`, so `k` matches itself first + # and shadows everything inside it. Drop whatever exactly spans the + # window -- by span rather than by identity, so that a duplicate event + # at the same bounds cannot shadow the body either. + body = [o for o in ops if o.start != k.start or o.end != k.end] + for c in children(body, k.start, k.end): + inner[c.base] += c.dur + icnt[c.base] += 1 + who = tr.label(devs[0]) if len(devs) == 1 else f"{len(devs)} devices pooled" + print(f"\n{who} {args.module} n={n} mean module {tot / n / PS:.1f} us") + if gpu: + print( + f" kernels cover {100 * covered / tot:.2f}% of the module (their union: nothing nests on a GPU, but " + "the\n NCCL stream runs beside the compute stream, so the shares below can sum past it)" + ) + else: + print( + f" top-level ops cover {100 * covered / tot:.2f}% of the module " + "(a containment stack, so a `while` is charged once)" + ) + print(f' {"op":40s} {"n/mod":>7s} {"us/mod":>9s} {"share":>7s}') + for k, v in agg.most_common(): + if v / n / PS < 0.05: + continue + print(f" {k[:40]:40s} {cnt[k] / n:7.1f} {v / n / PS:9.1f} " f"{100 * v / tot:6.1f}%") + if inner: + print(" -- inside the `while`:") + for k, v in inner.most_common(): + if v / n / PS < 0.05: + continue + print(f" {k[:37]:37s} {icnt[k] / n:7.1f} {v / n / PS:9.1f} " f"{100 * v / tot:6.1f}%") + if gpu: + print( + " An op is its hlo_op, ordinal off: custom-call a cuBLAS or cuDNN call, gmm_* a grouped-matmul\n" + " kernel (named off its scope, `_gpu_gmm`), the collectives NCCL kernels on their own stream.\n" + " The module time the kernels leave uncovered is the gaps between them (`summary`)." + ) + return + print( + " Rows are the top-level ops by XLA name: the pipeline's grouped-matmul kernels by their own (gmm_wi_0," + "\n gmm_wo_dx, gmm_wo_dw, ...), its FSDP and EP collectives anonymous (collective-permute-*, all-gather-*," + "\n reduce-scatter-*, fusion) -- `scopes` finds those by their named scope. A `while` is charged once," + "\n its body listed under it." + ) + + +def cmd_roofline(tr, args): + """Score a module against the chip peaks the trace itself reports. + + These captures carry no per-op cost model: no `flops` or `bytes_accessed` + stat is emitted on any line, so there is nothing to read an arithmetic + intensity off. The counts have to come from a byte model instead -- pass + `--flops` and `--bytes` for ONE module instance and this + divides them by the measured time. Given neither, it prints the peaks and + stops rather than inventing an intensity. + + A GPU plane's one peak is its `memory_bandwidth`: there the bandwidth side is + scored and the compute side only measured -- no ridge, no verdict. + """ + devs = tr.device_list(args.device) + print(tr.path) + pk_f, pk_b = tr.peaks[devs[0]] + bw_only = tr.platform == "GPU" and pk_f is None and pk_b is not None + if (pk_f is None or pk_b is None) and not bw_only: + raise SystemExit("this plane carries no peak_teraflops_per_second / " "peak_hbm_bw_gigabytes_per_second stat") + sel = [m for _, m in _select(tr, devs, args.module)] + if not sel: + raise SystemExit(f"no module matching {args.module!r} on device(s) {devs}") + n = len(sel) + mean = sum(m.dur for m in sel) / n / 1e12 # picoseconds -> seconds + who = tr.label(devs[0]) if len(devs) == 1 else f"{len(devs)} devices pooled" + print(f"\n{who} {args.module} n={n}") + if bw_only: + print( + f" peak from the trace: {pk_b / 1e9:.2f} GB/s (memory_bandwidth); a GPU plane carries no FLOP/s " + "peak,\n so there is no ridge and no compute-bound verdict: the bandwidth side alone" + ) + print(f" measured: {mean * 1e6:.1f} us per instance (first kernel to last, gaps included)") + if args.flops: + print(f" compute: {args.flops / mean / 1e12:8.1f} TF/s (no peak in the trace to score it against)") + if args.bytes: + print(f" memory: {args.bytes / mean / 1e9:8.1f} GB/s = {100 * args.bytes / mean / pk_b:.1f}% of peak") + print(f" bandwidth floor {args.bytes / pk_b * 1e6:.1f} us; measured is {mean * pk_b / args.bytes:.2f}x that") + if not args.flops and not args.bytes: + print("\n No --flops/--bytes given; supply the analytic counts for one module instance.") + return + print(f" peaks from the trace: {pk_f / 1e12:.1f} TF/s, " f"{pk_b / 1e9:.2f} GB/s, ridge {pk_f / pk_b:.0f} FLOP/byte") + print(f" measured: {mean * 1e6:.1f} us per instance") + if not args.flops and not args.bytes: + print( + "\n No --flops/--bytes given, and this trace carries no per-op cost" + "\n model, so there is no intensity to report. Supply the analytic" + "\n counts for one module instance: the FLOPs of the layers it runs" + "\n at this microbatch (a remat backward recomputes their forward" + "\n too) and the HBM bytes it moves -- weights, gradient accumulator," + "\n activations." + ) + return + f, b = float(args.flops or 0), float(args.bytes or 0) + if f: + print(f" compute: {f / mean / 1e12:8.1f} TF/s " f"= {100 * f / mean / pk_f:.1f}% of peak") + if b: + print(f" memory: {b / mean / 1e9:8.1f} GB/s " f"= {100 * b / mean / pk_b:.1f}% of peak") + if f and b: + ai = f / b + floor = max(f / pk_f, b / pk_b) + side = "compute" if ai > pk_f / pk_b else "BANDWIDTH" + print(f" intensity: {ai:.1f} FLOP/byte against a {pk_f / pk_b:.0f} ridge " f"-> {side}-bound") + print( + f" roofline floor {floor * 1e6:.1f} us; measured is " + f"{mean / floor:.2f}x that ({100 * floor / mean:.1f}% of attainable)" + ) + if ai <= pk_f / pk_b: + print( + "\n AI below the ridge => bandwidth-bound. Weight and accumulator" + "\n bytes do not grow with the microbatch while FLOPs do, so more" + "\n tokens per microbatch raise AI and wider layers do not." + ) + + +# `ds_ep.py` runs its FSDP, EP and grad-norm collectives under these +# `jax.named_scope`s, and names each grouped-matmul kernel. +SCOPES = ("fsdp_all_gather", "fsdp_reduce_scatter", "ep_all_gather", "ep_reduce_scatter", "grad_norm_all_reduce") +CONTAINERS = ("while", "conditional", "call") + + +def leaves(ops, start, end, starts=None): + """Top-level ops of [start, end), looking through `while`/`call` bodies. + + `ops` sorted as `Trace._events` leaves them; pass `starts`, the list of + their start times, when calling once per module over one device's ops. + """ + if starts is None: + starts = [o.start for o in ops] + window = ops[bisect.bisect_left(starts, start) : bisect.bisect_left(starts, end)] + out = [] + for k in children(window, start, end): + if k.base in CONTAINERS: + # the body, not the container again (see `cmd_ops`) + body = [o for o in window if k.start <= o.start < k.end and (o.start != k.start or o.end != k.end)] + out.extend(leaves(body, k.start, k.end)) + else: + out.append(k) + return out + + +def _gpu_gmm(o): + """A GPU kernel's grouped-matmul name -- `gmm_wi_0`, `gmm_wo_dx` -- off its name stack, or None. + + ds_ep scopes each grouped matmul `/` (`ds_ep._kernel_scope`). On + a TPU the kernel then takes the name; on a GPU it is `triton_kernel_call` + (tokamax's Triton kernels), at `.../tokamax/gmm_wi_0/triton_kernel_call`, so + the name is the scope right above a kernel call's primitive (`*_call`: + triton_kernel_call, pallas_call, mosaic_gpu_call). An XLA fusion inside the + scope -- a cast, a pad -- is not the kernel. + """ + parts = (o.stats.get("tf_op") or "").split("/") + if len(parts) >= 2 and parts[-1].endswith("_call") and parts[-2].startswith(("gmm_", "tgmm_")): + return parts[-2] + # tokamax's Mosaic GPU kernels (gmm_impl 'tokamax', the forward and dlhs products by default) sit deeper: + # `.../tokamax/gmm_wi_1_dx/eval_jaxpr/ragged_dot_sm100/mpmd_map` -- the nearest enclosing gmm_ scope names them. + if parts and (parts[-1] in _GPU_KERNEL_PRIMS or parts[-1].endswith("_call")): + for q in reversed(parts[:-1]): + if q.startswith(("gmm_", "tgmm_")): + return q + return None + + +# The primitive names a GPU kernel's name stack ends in when it is a hand-written kernel, not an XLA fusion: +# Mosaic GPU's (tokamax's sm90 / sm100 grouped matmuls) next to the `*_call` ones. +_GPU_KERNEL_PRIMS = ("mpmd_map",) + + +def gpu_scope(ev): + """`scope_of` for a GPU kernel, whose name stack lists every op XLA combined into it -- `prefix/(a:b:c)` -- + where a combiner merged collectives: the parts' scopes, in `SCOPES` order, joined with `+` where they differ. + + `ep_all_gather+fsdp_all_gather` is a microbatch's EP gather riding one NCCL + call with the FSDP gathers; `scope_of` alone would hand the whole kernel to + whichever of `SCOPES` comes first. + """ + t = ev.stats.get("tf_op") or "" + i = t.find("/(") + if i < 0 or not t.endswith(")"): + return scope_of(ev) + got = [] + for part in t[i + 2 : -1].split(":"): + sc = scope_of(Event(0, 0, "", {"tf_op": t[: i + 1] + part})) + if sc and sc not in got: + got.append(sc) + order = SCOPES + tuple(f"transpose({sc})" for sc in SCOPES) + return "+".join(sorted(got, key=lambda sc: order.index(sc) if sc in order else len(order))) or None + + +def scope_of(ev): + """Which of `SCOPES` an op ran under, or None. + + In a backward the scope reads `transpose(jvp(ep_all_gather))`, and the + transpose of a collective is its dual -- that one is a reduce-scatter -- so + it comes back as `transpose(ep_all_gather)`, its own row. + """ + t = ev.stats.get("tf_op") or "" + for sc in SCOPES: + i = t.find(sc) + if i >= 0: + wrap = t[t.rfind("/", 0, i) + 1 : i] # the transforms around this scope + return f"transpose({sc})" if "transpose(" in wrap else sc + return None + + +def _async_part(ev): + """An async collective's start / update / done (incl. XLA's async-call + wrappers, `all-gather.2.cloned.1.call-done`), or None.""" + raw = ev.name.split(" = ")[0].lstrip("%") + for part in raw.split("."): + if part.endswith(("-start", "-update", "-done")): + return raw.split(".call-")[0] if ".call-" in raw else raw + return None + + +def cmd_scopes(tr, args): + """Per program: the named-scope collectives it carries, and its gmm kernels. + + The FSDP gather and reduce-scatter have no program of their own -- they are + folded into forwards, backwards and the optimizer program -- and on the + `XLA Ops` row they are anonymous `collective-permute-*` / `all-gather-*` / + fusions. Their `tf_op` carries the scope, so this finds them the way the + trace viewer's "Framework Name Scope" row draws them. + + `ops` is the number of top-level TensorCore ops under the scope, `TC ms` the + TensorCore time they take, and `wait ms` the part of it in an async + collective's start / update / done: what the TensorCore spends issuing and + blocked on the collective (a permute's peer rendezvous is paid in its + start). The rest of `TC ms` is the assembly or the add. Collectives + offloaded to SparseCore move their bytes on the SparseCore planes; only + their start / done are here. + + On a GPU `ops` counts every kernel under the scope and `GPU ms` is their + time; `exposed ms` is the part of its collective (NCCL) kernels' time with + no compute kernel of the program running beside them -- what the TPU's + `wait` is, the collective the device does not hide. A collective XLA + combined from several scopes reads `a+b` (`gpu_scope`); one whose name stack + XLA dropped -- the pipelined reduce-scatters, the DP reduce -- gets a row of + its collective's own, `reduce-scatter (no scope)`. + """ + steps = tr.steps() + if not steps: + raise SystemExit(f"no XLA Modules events in {tr.path}") + k = len(steps) + i = args.step if args.step >= 0 else args.step + k + if not 0 <= i < k: + raise SystemExit(f"--step {args.step} out of range: 0..{k - 1}") + lo, hi = steps[i] + print(tr.path) + print(f"step {i} of {k}, {(hi - lo) / PS_MS:.2f} ms\n") + rows = SCOPES + tuple(f"transpose({sc})" for sc in SCOPES) + unit, wait = ("GPU", "exposed") if tr.platform == "GPU" else ("TC", "wait") + for d in tr.device_list(args.device): + ops = tr.ops(d) + starts = [o.start for o in ops] + mods = tr.modules(d) + blk = len(mods) // k + progs = collections.OrderedDict() + # Step i is the i-th block of the device's module sequence, as in + # `Trace.steps` -- not whatever overlaps the union window, which would + # also pick up a neighbouring step's first or last program. + if tr.platform == "GPU": + _gpu_scopes(mods[i * blk : (i + 1) * blk], progs) + else: + for m in mods[i * blk : (i + 1) * blk]: + p = progs.setdefault( + m.base, + { + "n": 0, + "sc": collections.Counter(), + "tc": collections.Counter(), + "wait": collections.Counter(), + "gmm": collections.Counter(), + }, + ) + p["n"] += 1 + pending = {} # async-call prefix -> scope of its start + for o in leaves(ops, m.start, m.end, starts): + if o.base.startswith(("gmm_", "tgmm_")): + p["gmm"][o.base] += 1 + part = _async_part(o) + sc = scope_of(o) + if part is not None: + # an async `.call-update` carries no tf_op: it is its start's + if sc is None: + sc = pending.get(part) + else: + pending[part] = sc + if sc: + p["sc"][sc] += 1 + p["tc"][sc] += o.dur + if part is not None: + p["wait"][sc] += o.dur + tot = collections.Counter() + # a TPU's scopes are all `rows`; a GPU's add combined ones and collectives of no scope + shown = rows + tuple(sorted({sc for p in progs.values() for sc in p["sc"]} - set(rows))) + w = 30 if tr.platform != "GPU" else max([30] + [len(sc) for p in progs.values() for sc in p["sc"]]) + print(tr.label(d)) + for name, p in progs.items(): + n = p["n"] + print(f" {name} x{n}") + for sc in shown: + if p["sc"][sc]: + tot[sc] += p["tc"][sc] + print( + f' {sc:{w}s} {p["sc"][sc] / n:6.1f} ops ' + f'{p["tc"][sc] / n / PS_MS:7.2f} {unit} ms ' + f'{p["wait"][sc] / n / PS_MS:6.2f} {wait} ms per instance' + ) + if p["gmm"]: + g = " ".join(f"{kn} {v / n:g}" for kn, v in sorted(p["gmm"].items())) + print(f" kernels per instance: {g}") + print( + f" step total {unit} ms: " + + (", ".join(f"{sc} {tot[sc] / PS_MS:.2f}" for sc in shown if tot[sc]) or "none") + + "\n" + ) + + +def _gpu_scopes(mods, progs): + """`cmd_scopes`' per-program counters off GPU executions `mods`, into `progs`: every kernel of each (nothing + nests), its scope `gpu_scope`'s or, for a collective with none, ` (no scope)`; `wait` the collective + kernels' time with no compute kernel of the execution beside it; grouped matmuls named by `_gpu_gmm`.""" + for m in mods: + p = progs.setdefault( + m.base, + { + "n": 0, + "sc": collections.Counter(), + "tc": collections.Counter(), + "wait": collections.Counter(), + "gmm": collections.Counter(), + }, + ) + p["n"] += 1 + ks = m.stats.get("kernels", []) + comp = _merge_spans((o.start, o.end) for o in ks if o.stats.get("kind") == "compute") + for o in ks: + g = _gpu_gmm(o) + if g: + p["gmm"][g] += 1 + coll = o.stats.get("collective") + sc = gpu_scope(o) or (f"{coll} (no scope)" if coll else None) + if sc: + p["sc"][sc] += 1 + p["tc"][sc] += o.dur + if coll: + p["wait"][sc] += o.dur - _overlap(comp, o.start, o.end) + + +# `ds_ep` program names: jit_{fwd,bwd,bwda,fb,fba}_c, the split +# backward's halves under the zero-bubble schedules (jit_bwdi_c, the +# input gradient I; jit_bwdw_c / jit_bwdwa_c, the weight +# gradients W, the chunk's first and accumulating -- the last chunk's too where +# it splits, its fused program then jit_fbi_c / jit_fbai_c, AI), +# and the host variants that also carry FSDP gathers (_ag..., _agself) +# and / or reduce-scatters (_rs..., _rsself) -- under --fsdp-scope +# repeat in a backward or the fused last chunk too (bwd_c3_rs5p5_ag1p4, +# fba_c3_ag1p5). Stash variants (_st) and F&B pairs (__) are left out. +_PROG = re.compile(r"^jit_(fwd|bwdwa|bwdw|bwdi|bwda|bwd|fbai|fbi|fba|fb)_c(\d+)((?:_(?:ag|rs)(?:self|\d+(?:p\d+)?))*)$") +_KIND = { + "fwd": "F", + "bwd": "B", + "bwda": "B", + "bwdi": "I", + "bwdw": "W", + "bwdwa": "W", + "fb": "A", + "fba": "A", + "fbi": "AI", + "fbai": "AI", +} + + +def program_costs(tr, devs): + """Per-chunk program medians (ms) as a `--costs` table, pooled over `devs` + (every device of a stage runs the same programs). + + F median plain `fwd_c` + B median plain `bwda_c` -- the accumulating backward, which is + every microbatch's but the first + I under a split backward (zbh1 / zbh2), median `bwdi_c`, its + input gradient + W ... median plain `bwdwa_c`, its accumulating weight gradients; + and B, which such a chunk never runs, their sum + A median `fba_c`, the fused last chunk + AI where the last chunk splits too (--zb-split-last), median + `fbai_c`, its forward, head, loss and input gradient + W, WA ... median `bwdwa_c`, its layers' weight gradients; + and A, which it never runs, AI + WA + F, B the median over chunks >= 1: what a chunk without its own key gets + I, W the median over the split middle chunks + dF_ag median extra ms of a forward that also carries a gather + dB_rs median extra ms of a backward that also carries a reduce-scatter + dB_ag, dB_ag+rs, dA_ag the same for what a backward or the fused last + chunk carries under --fsdp-scope repeat, where measured + update the slowest stage's median optimizer program + + A host variant is its plain program plus a delta, so it is folded in as + one: its delta against the same chunk's plain median goes into the + d_ key, and a chunk that ran only host variants + gets their median minus that delta -- or, where its kind has none (the + fused last chunk when every one of its programs carries a gather), minus + the median delta of the same collectives in the other kinds. The + schedulers read F/B/A (`schedule.cost_table`); the rest is for the + reader, and is ignored there. + """ + durs = collections.defaultdict(list) # (prog, chunk, host) -> [ms]; host 'ag', 'rs', 'ag+rs' or None + upd = collections.defaultdict(list) + for d in devs: + for m in tr.modules(d): + mt = _PROG.match(m.base) + if mt: + host = "+".join(sorted(set(re.findall(r"_(ag|rs)", mt.group(3))))) or None + durs[(mt.group(1), int(mt.group(2)), host)].append(m.dur / PS_MS) + elif m.base.startswith("jit_update"): + upd[m.base].append(m.dur / PS_MS) + med = {k: statistics.median(v) for k, v in durs.items()} + delta = collections.defaultdict(list) # (kind, host) -> [ms over the same chunk's plain program] + for (prog, c, host), v in durs.items(): + if host and (prog, c, None) in med: + delta[(_KIND[prog], host)] += [x - med[(prog, c, None)] for x in v] + dm = {k: statistics.median(v) for k, v in delta.items()} + + def host_delta(kind, host): + if (kind, host) in dm: + return dm[(kind, host)] + pooled = [x for (_, h), v in delta.items() if h == host for x in v] + return statistics.median(pooled) if pooled else 0.0 + + def chunk_cost(c, progs): + for prog in progs: + if (prog, c, None) in med: + return med[(prog, c, None)] + v = [x - host_delta(_KIND[prog], h) for (p, c2, h), xs in durs.items() if p == prog and c2 == c and h for x in xs] + if v: + return statistics.median(v) + return None + + chunks = sorted({c for _, c, _ in durs}) + last = max((c for p, c, _ in durs if _KIND[p] in ("A", "AI")), default=None) + out = {} + for key, progs in (("F", ("fwd",)), ("B", ("bwda", "bwd")), ("I", ("bwdi",)), ("W", ("bwdwa", "bwdw"))): + for c in chunks: + x = None if c == last else chunk_cost(c, progs) + if x is not None: + out[f"{key}{c}"] = x + for c in chunks: # a split chunk's backward, which it ran as I and W only: what sched.cost_table reads for its B + if f"B{c}" not in out and f"I{c}" in out and f"W{c}" in out: + out[f"B{c}"] = out[f"I{c}"] + out[f"W{c}"] + if last is not None: + out["A"] = chunk_cost(last, ("fba", "fb")) + ai, wa = chunk_cost(last, ("fbai", "fbi")), chunk_cost(last, ("bwdwa", "bwdw")) + if ai is not None: # the split last chunk: AI and its W, which together run what A does + out["AI"] = ai + if wa is not None: + out[f"W{last}"] = out["WA"] = wa + if out["A"] is None and ai is not None and wa is not None: + out["A"] = ai + wa + if out["A"] is None: + del out["A"] + for key in ("F", "B", "I", "W"): + rest = [v for k, v in out.items() if k[0] == key and k[1:].isdigit() and k != f"{key}0" and k != f"{key}{last}"] + if rest: + out[key] = statistics.median(rest) + for (kind, host), v in sorted(dm.items()): + out[f"d{kind}_{host}"] = v + if upd: + out["update"] = max(statistics.median(v) for v in upd.values()) + return {k: round(v, 2) for k, v in out.items()} + + +def cmd_costs(tr, args): + """Per-chunk program medians as JSON on stdout, for `--costs @file.json`. + + A capture of some stages only -- one chip, profiling.CHIPS, is the default + where one process holds them all -- has no fused last chunk (A), and maybe + no chunk past the first (F, B): the table still prints, and stderr names + what is missing, which --costs would take from default_costs.""" + table = program_costs(tr, tr.device_list(args.device)) + if not any(k[0] in "FBA" for k in table): + raise SystemExit(f"no ds_ep programs (jit_fwd_c*, jit_bwda_c*, jit_fba_c*) in {tr.path}") + missing = [k for k in ("A", "F", "B") if k not in table] + if missing: + print( + f'# no {", ".join(missing)} cost in {tr.path}: its devices hold only some stages (A is the fused ' + "last chunk, F and B the chunks past the first); --costs would price them from default_costs. " + "Capture with --profile-chips covering every stage's chips (the default traces one).", + file=sys.stderr, + ) + print(json.dumps(table, indent=1)) + + +def main(argv=None): + p = argparse.ArgumentParser( + prog="python3 -m maxtext.experimental.mpmd.jax.xprof", + description=__doc__.split("WHY THIS FILE EXISTS")[0], + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + p.add_argument("cmd", choices=["summary", "timeline", "modules", "gaps", "idle", "ops", "roofline", "scopes", "costs"]) + p.add_argument("path", help="a .xplane.pb, or any directory above one") + p.add_argument("-d", "--device", type=int, default=None) + p.add_argument( + "-m", + "--module", + default="jit_bwda_c0", + help="program name as `modules` lists it, without the (id): exact if a program has it, else a " + "substring of one program's name -- of several, the command exits listing them (default " + "jit_bwda_c0, chunk 0's plain accumulating backward, one past the first microbatch's that " + "carries no FSDP collective: not every plan has one)", + ) + p.add_argument("--step", type=int, default=-1, help="which step, negative counts from the end (default -1)") + p.add_argument("--width", type=int, default=110, help="timeline columns") + p.add_argument("--min-us", type=float, default=20.0, help="idle: list holes at least this wide (default 20)") + p.add_argument("--flops", type=float, default=0, help="roofline: analytic FLOPs in ONE module instance") + p.add_argument("--bytes", type=float, default=0, help="roofline: analytic bytes moved by ONE module instance") + a = p.parse_args(argv) + tr = Trace(find_xplane(a.path)) + for note in tr.notes: + print(f"# {note}", file=sys.stderr) + { + "summary": cmd_summary, + "timeline": cmd_timeline, + "modules": cmd_modules, + "gaps": cmd_gaps, + "idle": cmd_idle, + "ops": cmd_ops, + "roofline": cmd_roofline, + "scopes": cmd_scopes, + "costs": cmd_costs, + }[a.cmd](tr, a) + + +if __name__ == "__main__": + main() diff --git a/src/maxtext/experimental/mpmd/jax/xprof_align.py b/src/maxtext/experimental/mpmd/jax/xprof_align.py new file mode 100644 index 0000000000..9fc1761d5b --- /dev/null +++ b/src/maxtext/experimental/mpmd/jax/xprof_align.py @@ -0,0 +1,337 @@ +# 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. + +"""Every host of a multi-host profile in ONE XProf session, on one clock. + +Each host's `jax.profiler.trace` writes `/plugins/profile//.xplane.pb`, and every timeline in it -- TPU devices, +SparseCores, host threads -- counts from that host's own +`profile_start_time` (a stat of the 'Task Environment' plane; the device +lines carry timestamp_ns = 0). XProf's trace viewer merges the hosts of one +session (`hosts=a,b,...`) but takes each file's times as they are, so hosts +that started tracing at different moments land shifted against each other. +On the v6e-256 runs the four stage leaders started one stage drain apart -- ++26.7, +53.4, +83.1 ms -- which in an MPMD timeline puts a stage's forward +before the copy that feeds it. + +This rebases every host onto one origin -- each line's timestamp_ns moves by +(that host's profile_start_time - origin), and profile_start_time becomes the +origin -- and writes the hosts side by side in one session: + + python3 -m maxtext.experimental.mpmd.jax.xprof_align SRC [SRC ...] --out LOGDIR --session NAME + +SRC: xplane files, or directories (local or gs://) holding `*.xplane.pb` at +any depth; LOGDIR/plugins/profile/NAME/ gets one `.xplane.pb` each. +`xprof --logdir LOGDIR` then lists session NAME, and its trace viewer takes +every host at once. Checked on the v6e-256 ppermute run: the boundary +collective-permutes, which end at the same instant on both stages, line up +across hosts to within 50 us after the shift (26.7 ms apart before it). + +`ds_ep_pipeline --distributed --profile` does this as it writes +(`export_into_session`): every traced host joins one session, rebased to an +origin process 0 picks. + +XProf caches what it converts from each host's xplane beside it (.SSTABLE, +...) and serves that while the session's cache_version.txt is current. Both +writers therefore remove the caches of every host they write, and +cache_version.txt, so re-aligning into a session XProf has shown takes effect. + +What a traced host captures, and the name it is listed under (in stage order), +are profiling.py's. +""" + +from __future__ import annotations + +import argparse +import collections +import concurrent.futures as cf +import contextlib +import glob +import multiprocessing +import os +import sys +import tempfile +import warnings + +START_STAT = "profile_start_time" + + +def _xplane_pb2(): + """`xprof`'s xplane messages, built from their descriptor: never tensorflow's, whose import would cost each process + that parses a capture -- every worker `align` spawns, a pipeline host exporting its trace -- some 10 s and 0.7 GB.""" + from maxtext.experimental.mpmd.jax import xprof + + return xprof._xplane_pb2() + + +# ------------------------------------------------------------------- I/O +def _blob(url): + from google.cloud import storage + + bucket, _, name = url[5:].partition("/") + return storage.Client().bucket(bucket).blob(name) + + +def read_bytes(path): + if path.startswith("gs://"): + return _blob(path).download_as_bytes() + with open(path, "rb") as f: + return f.read() + + +def write_bytes(path, data): + if path.startswith("gs://"): + _blob(path).upload_from_string(data) + return + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as f: + f.write(data) + + +def delete(path): + """Remove the file `path` (local or gs://).""" + if path.startswith("gs://"): + _blob(path).delete() + return + os.remove(path) + + +def find_xplanes(src): + """Every `*.xplane.pb` at or below `src` (a file or a directory, local or gs://).""" + if src.endswith(".xplane.pb"): + return [src] + if src.startswith("gs://"): + from google.cloud import storage + + bucket, _, prefix = src[5:].partition("/") + prefix = prefix.rstrip("/") + "/" if prefix else "" + return sorted( + f"gs://{bucket}/{b.name}" + for b in storage.Client().list_blobs(bucket, prefix=prefix) + if b.name.endswith(".xplane.pb") + ) + return sorted(glob.glob(os.path.join(src, "**", "*.xplane.pb"), recursive=True)) + + +# ---------------------------------------------------------------- the shift +def _start_stat(space): + """(plane, stat) holding the host's profile_start_time, or (None, None).""" + for pl in space.planes: + names = {k: v.name for k, v in pl.stat_metadata.items()} + for s in pl.stats: + if names.get(s.metadata_id) == START_STAT: + return pl, s + return None, None + + +def start_time_ns(space): + """The host's absolute profile start (ns since the epoch).""" + _, s = _start_stat(space) + if s is None: + raise ValueError(f"no {START_STAT} stat in this xplane: cannot place it on a common clock") + return int(s.int64_value or s.uint64_value) + + +def rebase(space, origin_ns): + """Move every timeline of `space` from its own profile start onto + `origin_ns` (ns since the epoch, at or before the start) -> the shift (ns).""" + start = start_time_ns(space) + shift = start - origin_ns + if shift < 0: + raise ValueError(f"origin {origin_ns} is after this host's profile start {start}") + for pl in space.planes: + for ln in pl.lines: + ln.timestamp_ns += shift + _, s = _start_stat(space) + if s.HasField("uint64_value"): + s.uint64_value = origin_ns + else: + s.int64_value = origin_ns + return shift + + +def _load(path): + space = _xplane_pb2().XSpace() + space.ParseFromString(read_bytes(path)) + return space + + +def _start_of(path): + return start_time_ns(_load(path)) + + +def _size(path): + if path.startswith("gs://"): + b = _blob(path) + b.reload() + return b.size or 0 + return os.path.getsize(path) + + +def _pool_size(paths, workers): + """`workers`, fewer for big xplanes: each worker holds one parsed XSpace, some + 8x its file (a 1.93 GB TPU capture: 11.5 GB parsed, 15.7 GB while rebased).""" + try: + with open("/proc/meminfo") as f: + avail = next(int(ln.split()[1]) * 1024 for ln in f if ln.startswith("MemAvailable:")) + except (OSError, StopIteration, ValueError): + return min(workers, len(paths)) + return max(1, min(workers, len(paths), avail // (8 * max(map(_size, paths)) + 1))) + + +def _rebase_into(path, origin_ns, dst): + space = _load(path) + shift = rebase(space, origin_ns) + write_bytes(dst, space.SerializeToString()) + return shift + + +def _labels(paths, names): + """The host XProf lists each xplane under (its file's name before + `.xplane.pb`): names[its path, or the nearest directory above it in names], + else names[the host jax wrote], else that host. Captures that would share + one get their directory's name appended (jax's capture timestamp), then a + count: a session holds one file per host.""" + norm = lambda p: p.rstrip("/") if p.startswith("gs://") else os.path.abspath(p) + host = lambda p: os.path.basename(p)[: -len(".xplane.pb")] + + def label(p): + under = [(len(norm(k)), v) for k, v in names.items() if (norm(p) + "/").startswith(norm(k) + "/")] + return max(under)[1] if under else names.get(host(p), host(p)) + + labels = [label(p) for p in paths] + shared = collections.Counter(labels) + labels = [f"{l}-{os.path.basename(os.path.dirname(p))}" if shared[l] > 1 else l for p, l in zip(paths, labels)] + seen = set() + for i, l in enumerate(labels): + k = 1 + while labels[i] in seen: + labels[i] = f"{l}-{k}" + k += 1 + seen.add(labels[i]) + return labels + + +def _drop_xprof_caches(session_dir, labels): + """Remove XProf's caches of the hosts `labels` in session_dir (every + `