Skip to content

Gemma-4 vision: pass the clip flag in the E2E script, keep packing on for text-only runs - #3

Open
nuinashco-ks wants to merge 1144 commits into
lokic233:gemma4-e2b-e4b-vision-clipped-linearsfrom
KyivstarDMP:pr/4790-fixes
Open

nuinashco-ks wants to merge 1144 commits into
lokic233:gemma4-e2b-e4b-vision-clipped-linearsfrom
KyivstarDMP:pr/4790-fixes

Conversation

@nuinashco-ks

@nuinashco-ks nuinashco-ks commented Nov 10, 2026 •

Copy link
Copy Markdown

Description

Two small fixes on top of AI-Hypercomputer#4790, each answering an open review comment. We ported that PR into our fork and validated it on TPU v6e.

Stacked on #2 (merge of main). Until that lands, this diff includes the merge; the two commits on their own: compare.

Changes

1. fix(testing): convert with clip bounds in the E2B multimodal E2E script (review comment)

should you also pass? use_clipped_linears_for_vit=true. as Clipping defaults to false.

Yes. Step 1 of test_gemma4_multimodal.sh converts the checkpoint without use_clipped_linears_for_vit=true. The config gate of AI-Hypercomputer#4790 rejects that, so the script stops at its first step:

Multimodal for gemma4-e2b requires use_clipped_linears_for_vit=True ...

2. fix(config): keep packing on for text-only Gemma-4 E2B/E4B runs (review comment)

will this change default packing behavior for text as well?

Yes, packing: false in the E2B/E4B model ymls also changes text-only runs. Model-config keys apply to every run of the model and cannot be overridden from the CLI, so text-only runs lost packing and packing=true raised.

Images only enter the data pipeline for multimodal SFT (use_sft and use_multimodal in hf_data_processing.py and grain_data_processing.py). There, the existing check For multimodal SFT, packing is not yet supported already rejects packing for every multimodal model. So this removes the yml lines and gate (e), the config check that rejected packing for E2B/E4B multimodal in any training mode; E2B/E4B now follow the same rule as Gemma-3 and the 26B/31B models.

Config Before After
E2B/E4B text-only packing=False packing=True
E2B/E4B text-only, packing=true raises (model-config override) packing=True
E2B multimodal SFT, packing=true raises (gate e) raises (For multimodal SFT, packing is not yet supported.)
E2B multimodal SFT, no packing arg packing=False (from yml) raises, same as Gemma-3; the sft-vision-*.yml configs set packing: false
E2B multimodal, not SFT (decode, logit checker) packing=False packing=True; these paths load no images

test_packing_hard_fails now checks the multimodal-SFT case; new test_text_only_keeps_packing covers E2B and E4B.

Tests

On this branch:

  • JAX_PLATFORMS=cpu python3 -m pytest tests/unit/gemma4_small_layers_test.py: 31 passed.
  • With the merge's source and this PR's tests, test_text_only_keeps_packing fails, so the new test covers the change.

Checklist

Before submitting this PR, please make sure (put X in square brackets):

  • I have performed a self-review of my code. For an optional AI review, add the gemini-review label.
  • I have necessary comments in my code, particularly in hard-to-understand areas.
  • I have run end-to-end tests tests and provided workload links above if applicable.
  • I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in our documentation.

darisoy and others added 30 commits October 22, 2026 16:44
Allows moe_flat_fsdp_weights=True without the explicit fp8 weight all-gather (bf16 and prefetch_fsdp_weights=True), so routed-expert weights are stored as 2D [E * rows, cols] and FSDP-gathered on their major-most dim. The gathered weight is then a free bitcast of the [E_local, rows, cols] gmm operand instead of a 3.5 GiB transpose per layer.

fsdp_prefetch: pin the gathered-weight layout only for 3D+ weights gathered on their minor-most dim, and drop the per-layer sub-stack slicing / concatenation and the up-front moveaxis that added full-stack copies.

Tests: unit test for _needs_minor_dim_layout_pin (now module level), and an abstract-model/sharding test for unquantized moe_flat_fsdp_weights with prefetch_fsdp_weights.

fsdp_prefetch_inhomogeneous: its stage params are already layer-major, so the shared setup no longer moves the scan axis for them (scan_axis=0); flat routed-expert weights are covered by new Qwen3.5 parity tests.
Qwen3.5 tests check that flat routed-expert weights are gathered per sub-layer over fsdp only (tagged, on dim 0, no layout pin) under expert parallelism.
…hen/ds4-sft

PiperOrigin-RevId: 1004927472
…/fix/gmm-v2-k-tail-rhs-scale

PiperOrigin-RevId: 1004993131
…y-fix-decoupled-explicit-sharding-tests

PiperOrigin-RevId: 1004996501
…hen/ds4-e2e-sft

PiperOrigin-RevId: 1005008960
… attached its Goodput `CloudLogger` via private Orbax internals (`_manager._logger`) and wrapped `load_checkpointables()` in a helper to manually time and emit `RestoreStepStatistics` (cl/995181750). Now that `orbax.checkpoint.v1.training.Checkpointer` natively accepts a `logger` argument and emits `RestoreStepStatistics` from `load_checkpointables()` (cl/998371284), those private workarounds are no longer needed.

Pass `logger=orbax_logger` directly to `ocp.training.Checkpointer` in `create_orbax_checkpoint_manager()`, call `checkpoint_manager.load_checkpointables()` directly in `load_state_if_possible()`, and remove the temporary `_attach_checkpoint_logger` and `_load_checkpointables_with_logging` helpers.

TESTED: https://github.com/AI-Hypercomputer/maxtext/actions/runs/39555767369/job/119075066871

# Checklist

- [X] I have performed a self-review of my code. For an optional AI review, add the `gemini-review` label.
- [X] I have necessary comments in my code, particularly in hard-to-understand areas.
- [X] I have run end-to-end tests tests and provided workload links above if applicable.
- [X] I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in our documentation.

PiperOrigin-RevId: 1005014349
- Run the mdformat hook directly via pre-commit in update_changelog.yml
  instead of duplicating the mdformat pin and plugins.
- Move the gather_changes unit test to
  .gemini/skills/update-changelog/scripts/gather_changes_test.py and run
  it in update_changelog.yml.
…treaming DiLoCo.

# Description

Adds `trainers/diloco/utils/fragment_transfer.py`: the jitted pieces a threaded
DiLoCo learner uses to extract one parameter fragment per sync step, move it to
another set of devices for the outer step, and apply the synced result a few steps
later. Nothing uses it yet. The trainer comes in a follow-up CL.

-   A *transfer fragment* is a dict `key -> 1-D jax.Array`, keyed like
    `FragmentedTreeManipulator.get_flat_fragment`. Each leaf is flattened
    shard-locally with `jax.shard_map`, so extract/apply never move data between
    chips and host transfers only see 1-D arrays. The 1-D element order is
    mesh-block-major, i.e. a permutation of the reshaped `get_flat_fragment`
    output. Leaves whose fragment shape isn't divisible by their sharding fall back
    to a global reshape.
-   `FragmentTransfer(manipulator, params, alpha)`: one jitted extract and one
    jitted apply for all layer fragments (the fragment index is a traced argument,
    passed as a host `np.int32` so no device-to-device copy precedes each call),
    plus a pair for fragment 0. Extract pins its output shardings; `apply` pins its
    output shardings to the live parameters and donates them, so the train step sees
    unchanged shardings and the scanned layer stacks are updated in place. With
    strided layer assignment, the scan axis is viewed as (layers, stride) and
    sliced, so neither path uses gather/scatter. `alpha` implements
    `communication_overlapping_alpha`. Construction checks that layer fragments form
    an arithmetic progression and that every parameter has a NamedSharding on a
    single mesh; out-of-range fragment indices raise. The layout is pinned to the
    shardings of `params`, so any resharding must happen before construction.
-   `move_fragment(fragment, mesh)`: one batched `device_put` that keeps each
    array's PartitionSpec.
-   `nesterov_outer_step`: Nesterov outer step on the pseudo-gradient
    `mean(outer - learner fragment)`, equivalent to
    `optax.sgd(lr, momentum, nesterov=True)` and to the SPMD sync's form, so elements
    no learner changed get exactly zero update. Arithmetic is done in float32; the
    new outer value and the momentum trace keep the dtypes of `outer` and `trace`.
    The trace is donated; the outer value is not (callers may share it). Outputs keep
    the shardings of `outer` and `trace`.

Testing: new `tests/unit/diloco_fragment_transfer_test.py` on 4 CPU devices:
extract->apply moves exactly one fragment (sequential/strided, bucketized or not,
single-axis and 2x2x2 meshes with tuple specs, f32 and bf16), transfer arrays are
1-D and shard-local, a round trip between two `split_mesh_along_axis` submeshes,
apply keeps shardings, donates and writes the right values, layer fragments share
one executable, interleaved layers lower without gather/scatter, alpha
interpolation, invalid layouts/shardings/indices are rejected, the index needs no
device-to-device transfer (`transfer_guard`), and the outer step matches optax,
leaves unchanged elements at zero, computes bf16 inputs in f32, donates only the
trace, and matches `spmd_diloco_sync.synchronize_fragment_state` over 2 and 3
replicas for two rounds.

# PR Series for threaded Streaming DiLoCo

AI-Hypercomputer#5392
AI-Hypercomputer#5393
AI-Hypercomputer#5394
AI-Hypercomputer#5503
AI-Hypercomputer#5504
AI-Hypercomputer#5505
AI-Hypercomputer#5506

# Checklist

Before submitting this PR, please make sure (put X in square brackets):
- [x] I have performed a self-review of my code. For an optional AI review, add the `gemini-review` label.
- [x] I have necessary comments in my code, particularly in hard-to-understand areas.
- [x] I have run end-to-end tests tests and provided workload links above if applicable.
- [x] I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in [our documentation](https://maxtext.readthedocs.io/en/latest/development.html#adding-new-documentation-files).

PiperOrigin-RevId: 1005023017
…post-training-unit`, and `cpu-post-training-integration`) in `.github/workflows/run_tests_coordinator.yml` from `linux-x86-n2-32` to `linux-x86-n4-32`.

PiperOrigin-RevId: 1005027382
…angelog-generator-formatting

PiperOrigin-RevId: 1005061537
…sue-5814-tpu-docker-ci

PiperOrigin-RevId: 1005064486
DeepSeek-V4 ships no Jinja chat_template, so apply_chat_template fails during SFT preprocessing. The official encoder was only vendored under benchmarks/api_server, which src/maxtext cannot import, and that copy had lost the blank lines in TOOLS_TEMPLATE and several docstrings, so its tool-calling prompts no longer matched the official encoder goldens.

- Move benchmarks/api_server/encoding/encoding_dsv4.py to src/maxtext/input_pipeline/encoding_dsv4.py, restore the stripped blank lines, and import it from benchmarks/api_server/{maxtext_server,server_utils}.py.
- input_pipeline_utils.apply_chat_template: when chat_template is None and the model or tokenizer name is DeepSeek-V4, encode with encode_messages and split it into prompt and completion chunks. In thinking mode, turns whose reasoning the encoder dropped stay in the prompt. Encoded text left after the final assistant turn raises ValueError.
- grain_data_processing: build the SFT tokenizer with add_bos=False and add_eos=False, as the HF and vision SFT paths do; with transformers 5.x, add_bos_token=True prepended BOS to every chunk.
- grain_data_processing and hf_data_processing: forward model_name to apply_chat_template.
- tests: golden parity with the 4 official encoder fixtures, Grain and HF SFT loss masks, name-only DeepSeek-V4 detection, thinking-mode history turns, Grain tokenizer flags, and model_name forwarding.
The same-group sub-layer scans of fsdp_prefetch_inhomogeneous carried one gathered-weight buffer, so each step's all-gather of the next sub-layer landed in a fresh buffer that XLA copied into the loop carry (a full-size TensorCore copy of every gathered weight, e.g. three 512 MiB routed-expert weights per Qwen3.5-35B-A3B GDN sub-layer step, in both passes).

Same-group scans with >= 2 steps now run two sub-layers per loop trip and alternate between two gathered-weight buffers, with the optimization-barrier ordering of fsdp_prefetch, so the all-gather reuses the loop-carry buffer. _sublayer_scan unrolls by hand: jax.lax.scan(unroll=2) drops the while-loop entirely for a single 2-step trip, which moves the copy to the block loop carry instead.

Tests: Qwen3.5 parity with 4 local layers per block (2-step trip plus a 1-step remainder), and a check that same-group scans unroll by 2.
…e BSW.

With a cp-as-ep rule (e.g. `exp -> ['context', 'expert']`), 'context' is part of
expert parallelism for the routed-MoE weights. `remove_gathered_mesh_axes`
stripped it like an FSDP axis, so the BSW (buffer sliding window):
  * all-gathered expert weights over 'context' (2x BSW bytes/memory), and
  * had to collective-permute them back to the ('context', 'expert') layout the
    MoE shard_map expects (a 4x2 device transpose; 896 MiB x 24 per step on a
    small DSv3 PP4xFSDP4xEP4xCP2 run).

Also, `get_current_weights_from_bsw` built its select shard_map specs with
`_remove_fsdp_from_physical_partition_spec`, which differs from the BSW layout
(keeps 'expert' on non-MoE weights and 'context' on MoE weights), causing a
reshard on every pipeline iteration. It now uses the same
`remove_gathered_mesh_axes` specs as `from_repeat_weights_to_bsw`.

Results (small DeepSeek-V3, 11 layers, bf16, seq 4096, pdb 0.5, tpu7x 4x4x4):
  PP4xFSDP4xEP4xCP2 M=4:  1.656 -> 1.001 s/step (-40%), collective-permute
                          47.3 -> 1.2 GiB/step, all-gather 93 -> 54 GiB/step.
  PP4xFSDP2xEP4xCP4 M=8:  0.834 s/step (non-PP FSDP16xEP4xCP2: 0.776).
Loss curves unchanged.
…hen/ds4-chat-encoder

PiperOrigin-RevId: 1005250313
Copies the CI Pulse dashboard files from Google Cloud Storage to gh-pages
every 4 hours, where https://ai-hypercomputer.github.io/maxtext/dev/bench/#ci
reads them. The data is collected outside this repository (a Cloud Run job
writes the dashboard files to GCS), so no collector code runs in maxtext.

- Two jobs, so Google Cloud access and the repository write token are never
  on the same machine:
  - download: runs on a MaxText self-hosted runner (linux-x86-n4-16-buildkit,
    in the cloud-sdk:528.0.0 image, like build_and_push_docker_image.yml),
    which is already signed in to Google Cloud as its own service account.
    No key, no secret, no Workload Identity Federation, and no GitHub token
    permissions. It prints only the account's name (the logs are public) and
    hands the files over as an artifact kept for 1 day.
  - publish: runs on ubuntu-latest with contents: write only, and never
    talks to Google Cloud.
- Runs every 4 hours at :40, twenty minutes after the collector, and by hand
  (dry_run and allow_shrink inputs). A dry run reports that it would
  publish, and pushes nothing.
- Checks the files before publishing: only the dashboard's JSON files, all
  valid JSON (no NaN), every month file that meta.json lists, never older
  than the live data, no tab emptied, never less than half of its rows.
- Publishes with the built-in GITHUB_TOKEN, starting each attempt from the
  newest gh-pages so that a concurrent push (the Benchmarks robot) is kept.
- Does nothing until the CI_PULSE_BUCKET repository variable is set.
  CI_PULSE_PUBLISH=off pauses the schedule while manual runs (for example a
  dry run) still work.
- Excludes this workflow in .github/scripts/analyze_code_changes.sh, like
  update_changelog.yml, so PRs that only edit it run no hardware test suites.
…ybrid blocks

Since Qwen3.5 reuses Qwen3NextScannableBlock, a scanned Qwen3-Next/Qwen3.5
decoder raises NotImplementedError when vLLM hands it per-layer attention
metadata (a dict keyed by `layer.{i}`, one entry per KV-cache group), because
the sub-layers of a scanned block do not know their global layer index.
vllm_decode forwards `scan_layers` to the adapter, so
`vllm_decode ... scan_layers=True` -- used by the Qwen3.5 RL E2E test on its
scanned checkpoints -- fails on the first forward pass.

With external (vLLM) KV caches the decoder already unrolls the blocks
statically, so it now resolves the dict per block instead:
- NNXDecoder._apply_qwen3_hybrid_scanned_blocks looks each layer up by its
  global index (the same lookup as the unscanned path) and hands every block,
  and the remainder block, a tuple with its sub-layers' entries, ordered like
  the block's KV caches.
- _apply_layers_sequentially takes `per_iteration_kwargs` (static-unroll path
  only), passed as call arguments so they survive jax.checkpoint.
- Qwen3NextScannableBlock accepts that per-sub-layer tuple together with
  external KV caches, and still rejects an unresolved dict.
# Description

Regenerating the post-training requirements in 161ad61 bumped triton from
3.6.0 to 3.7.0. triton 3.7.0 segfaults when libtriton.so is loaded after
TensorFlow (LLVM symbol clash in its static initializers). The multimodal SFT
E2E tests install TensorFlow at runtime and `train.py` imports it before
`torch._dynamo` imports triton, so `train_sft_native` crashes at import time
(exit code 139) for qwen3-vl-2b and gemma3-4b.

torch's PyPI (CUDA) wheel pins triton==3.7.0, but TPU images install the CPU
torch wheel, so pin triton through tpu_post_train_overrides.txt and regenerate
the post-training requirements with generate_requirements.sh.

# Tests

- Reproduced the segfault with the 10/23 post-training image
  (`import tensorflow; import triton`); pinning triton to 3.6.0 fixes it.
- Built the post-training image from this branch (all regenerated versions,
  triton 3.6.0) and ran the post-training E2E scripts on a v5p Pathways
  cluster the same way as the maxtext_e2e_tpu_post_training DAG (gcluster):
  - gemma3-4b sft, lora, multimodal_sft (v5p-8) and rl (v5p-32): passed
  - qwen3-vl-2b multimodal_sft (v5p-8): passed

# Checklist

Before submitting this PR, please make sure (put X in square brackets):
- [X] I have performed a self-review of my code. For an optional AI review, add the `gemini-review` label.
- [X] I have necessary comments in my code, particularly in hard-to-understand areas.
- [X] I have run end-to-end tests and provided workload links above if applicable.
- [X] I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in [our documentation](https://maxtext.readthedocs.io/en/latest/development.html#adding-new-documentation-files).

Signed-off-by: EmmaLien <emmalien@google.com>
Add the DeepSeek V4 Pro (1600B) support announcement bullet under Latest news in README.md, linking to tests/end_to_end/tpu/deepseek/Run_DeepSeek.md.
…ix-qwen35-scanned-vllm-metadata

PiperOrigin-RevId: 1005708219
… leak across BSW leaves.

`derive_stage_weight_partition_specs` passes one `axes_to_remove` list to every leaf, and `remove_gathered_mesh_axes`
appended "expert" to it in place for each non-MoE leaf. Routed-MoE leaves visited after a non-MoE leaf (e.g. `layers_1`
of a sequential multi-layer stage, after `layers_0`'s shared experts and attention) then lost 'expert' too, so
`from_repeat_weights_to_bsw` all-gathered them over 'expert' and laid them out differently from
`get_current_weights_from_bsw` (which builds a fresh list per leaf), resharding every iteration. The fix was in the
phase-split change; it belongs here.

Add tests/unit/pipeline_utils_test.py for `remove_gathered_mesh_axes` (cp-as-ep 'context' kept only next to 'expert'
on MoE weights, 'expert' and 'context' stripped from non-MoE weights, the caller's list left unchanged) and for
`derive_stage_weight_partition_specs` over a two-layer stage.
…s and sown-metrics reduction.

- Add `pipeline_bsw_phase_split`, `pipeline_bsw_no_carry`, and `pipeline_bsw_in_compute_dtype` options for `NNXCircularPipeline` (`pipeline_fsdp_ag_per_repeat=True`).
- Fix `weight_prefetching` to gather `loop_iteration + iterations_to_complete_first_microbatch_one_repeat()` so all stages receive the same repeat's weights in the prefetched BSW slot.
- Record and reduce sown `nnx.Intermediate` metrics (`moe_lb_loss`, `moe_bias_updates`, `moe_has_overflow`, etc.) per layer across valid microbatch iterations via `reduce_sown_metrics_per_layer`, dropping bubble compute.
…rmoon-patch-2

PiperOrigin-RevId: 1005719401
Re-gather the previous repeat's weights in every repeat by default instead of carrying the gathered slot across the
repeat scan, which stacks num_pipeline_repeats copies of one repeat's gathered stage weights in HBM for the backward
pass (~19 GiB/device for DeepSeek-V3 PP=8 EP=8 FSDP=128). The flag is a no-op without pipeline_fsdp_ag_per_repeat, so
it leaves the check that the BSW options are only set with weight prefetching. Add
test_circular_pipeline_ag_per_repeat_carry so the carried slot keeps a test now that the others run without it.
Dr-Left and others added 24 commits November 6, 2026 22:41
…ica on a submesh.

# Description

Threaded DiLoCo runs several independent learners, one per slice, in one process.
Each learner needs to build its train state on its own submesh and read a disjoint
share of the data. With the defaults, every change here is a no-op.

-   `train_utils.setup_train_loop(..., mesh=None)`: optionally train on a prebuilt
    mesh instead of the one derived from the config (also used as the fallback mesh
    when restoring LoRA weights).
-   `input_pipeline_utils.get_dataloading_shard(config, process_indices,
    shard_offset=0, shards_per_host=1)`: one place that computes
    `(shard_index, shard_count)` for this process. Grain (train, the
    `expansion_factor_real_data` restore list, eval), HF (train/eval) and TFDS
    (train/eval) now call it instead of computing the index inline. It further
    splits each host's shard among `num_data_replicas_per_process` replicas.
    Contract: a replica's `global_batch_size_to_load` is its own batch, while the
    shard set covers all replicas. Everything sized for the shard set uses
    `get_all_replicas_batch_size` (batch times replicas):
    -   the grain ElasticIterator's global batch, so each replica gets its own batch;
    -   the mmap_npy train and eval sample budgets, so no replica runs out early;
    -   mmap_npy blends: a shuffle window of one all-replica step runs before the
        host/replica stride, so every replica reads a mix of all components and the
        union of the replicas' batches is the single-replica step batch.
-   Synthetic data: `SyntheticDataIterator` builds the batch of all replicas and
    keeps rows `[data_replica_index * B, (data_replica_index + 1) * B)`, so replica
    i gets the same rows as replica i of SPMD DiLoCo (which splits one global batch
    along its first axis). Before, every replica generated the same batch.
-   New `DatasetGeneral` fields `num_data_replicas_per_process` (default 1) and
    `data_replica_index` (default 0), validated so the index is below the count.
    Replicas above 1 are rejected with `colocated_python_data_input`, `c4_mlperf`
    and `olmo_grain`. Configs without these fields (duck-typed test configs) read
    the defaults.
-   `HyperParameters.replace(**updates)`: returns a copy with fields overridden
    verbatim (pydantic `model_copy`), for deriving per-learner configs. Unknown keys
    raise and the data-replica fields are re-validated; other validation and
    derived fields (including output paths derived from `run_name`) are not
    recomputed, and the docstring lists them.

Testing:

-   `tests/unit/input_pipeline_utils_test.py`: `GetDataloadingShardTest` (one
    replica matches the old host position, replicas split a host shard, several
    shards per host, configs without the replica fields, index range checks).
-   `tests/unit/pyconfig_test.py`: `replace` returns an updated copy, rejects
    unknown fields and re-checks the replica fields; field boundaries and
    incompatible pipelines are rejected.
-   `tests/unit/grain_data_processing_test.py`: two replicas through a real grain
    ElasticIterator get disjoint batches of the per-replica size whose union per
    step is the single-replica batch.
-   `tests/unit/mmap_data_processing_test.py`: every replica gets data for every
    step through a real 2-component blend (train), the eval budget covers all
    replicas, and each replica's batch is a mix whose per-step union equals the
    single-replica batch. The existing `GrainMmapNpyEvalConfigTest` passes.

# PR Series for threaded Streaming DiLoCo

AI-Hypercomputer#5392
AI-Hypercomputer#5393
AI-Hypercomputer#5394
AI-Hypercomputer#5503
AI-Hypercomputer#5504
AI-Hypercomputer#5505
AI-Hypercomputer#5506

# Checklist

Before submitting this PR, please make sure (put X in square brackets):
- [x] I have performed a self-review of my code. For an optional AI review, add the `gemini-review` label.
- [x] I have necessary comments in my code, particularly in hard-to-understand areas.
- [x] I have run end-to-end tests tests and provided workload links above if applicable.
- [x] I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in [our documentation](https://maxtext.readthedocs.io/en/latest/development.html#adding-new-documentation-files).

PiperOrigin-RevId: 1016130539
…yers=True).

# Description

When `shard_optimizer_over_data=True` (ZeRO-1) and `scan_layers=True` run on multi-host (`jax.process_count() > 1`), `reshard_train_state` previously called `jax.device_put(state, state_mesh_shardings)` directly on a `TrainState` PyTree containing scanned typed PRNG keys (`rngs.{params,dropout,aqt}.key` of shape `(num_layers,)`).

In JAX (`jax._src.sharding_impls.logical_sharding`), a 1D replicated `PRNGKeyArray` reports `NamedSharding(mesh, P(None,))` as its `.sharding` because `logical_sharding` pads `phys_sharding.spec` to `len(phys_shape)` with `None` before slicing off the inner key shape's dimensions. Meanwhile, `get_nnx_var_named_sharding_with_scan_axis` assigns `NamedSharding(mesh, P())` to unannotated NNX variables. Because `jax.device_put` checks `src_sharding == dst_sharding` (rather than `is_equivalent_to`) for its fast-path short-circuit and `PRNGKeyArray` does not take `ArrayImpl`'s multi-host resharding path, `jax.device_put` falls through to the `is_fully_addressable` check and raises `ValueError` on multi-host runs before step 0.

On multi-controller runs (`not enable_single_controller`), `_device_put_with_raw_keys` unwraps typed PRNG keys via `jax.random.key_data`, appends `None` dimensions for the inner key shape via `_raw_key_sharding`, executes a single `jax.device_put` call across all leaves (preserving zero-copy HBM reuse for unchanged model parameters and already-equivalent scanned RNG keys on both single-process and multi-process runs), and re-wraps the keys via `jax.random.wrap_key_data`.

# Tests

* `pytest tests/unit/sharding_reshard_train_state_test.py`: unit and two-process distributed regression tests verifying `reshard_train_state` across `nnx.RngKey`-wrapped and bare typed keys and across two JAX CPU processes (`gloo`), including zero-copy buffer reuse (`unsafe_buffer_pointer()`) for `P(None,)` -> `P()` and multi-host resharding for `P(None,)` -> `P("data")`.

# Checklist

Before submitting this PR, please make sure (put X in square brackets):
- [X] I have performed a self-review of my code. For an optional AI review, add the `gemini-review` label.
- [X] I have necessary comments in my code, particularly in hard-to-understand areas.
- [X] I have run end-to-end tests and provided workload links above if applicable.
- [X] I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in [our documentation](https://maxtext.readthedocs.io/en/latest/development.html#adding-new-documentation-files).

PiperOrigin-RevId: 1016160810
…specific backend name.

PiperOrigin-RevId: 1016288694
… rules

# Description

Step guards, spike protection and model construction rules:
- skip_step_on_nan (default false) skips a step whose gradient norm is non-finite,
  leaving the state unchanged and recording step_skipped.
- skip_step_on_spikes (shared with pre_train runs) previously applied a NaN
  step during warmup and let NaN into its rolling buffers during warmup and
  post-warmup; it now skips non-finite steps during warmup too and keeps NaN
  out of the rolling buffers.
- The model is built under the logical axis rules with any caller mesh cleared,
  and eval_step traces under the engine's logical axis rules.
- parameter_memory_host_offload and a logical_axis_rules_for_eval that differs
  from the training rules raise NotImplementedError instead of being silently
  ignored.
- Add test guidance to training_engine/AGENTS.md.

Differences from atwigg/mlperf:
- MLPerf defaults skip_step_on_nan to True and included max_grad_norm_spike.
  Here skip_step_on_nan defaults to False, and max_grad_norm_spike was omitted
  because MLPerf training reproduces without it. The MLPerf recipes aren't
  affected, because Tunix's mlperf launcher passes skip_step_on_nan explicitly.
- skip_step_on_nan is declared in types.py (relying on its default there
  rather than duplicating it in base.yml) and read as a typed config field,
  without MLPerf's getattr(config, ...) fallbacks; no os.environ switches are added.

# Tests

```bash
python -m pytest tests/unit/optimizers_test.py tests/post_training/unit/maxtext_engine_test.py tests/post_training/unit/maxtext_engine_constructor_test.py -q
```
Result: All tests passed:
- `//third_party/py/maxtext/tests/unit:optimizers_test`: passed
- `//third_party/py/maxtext/tests/post_training/unit:maxtext_engine_test`: passed (291.8s)
- `//third_party/py/maxtext/tests/post_training/unit:maxtext_engine_constructor_test`: passed (71.7s)

# Checklist

Before submitting this PR, please make sure (put X in square brackets):
- [x] I have performed a self-review of my code. For an optional AI review, add the `gemini-review` label.
- [x] I have necessary comments in my code, particularly in hard-to-understand areas.
- [x] I have run end-to-end tests and provided workload links above if applicable.
- [x] I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in [our documentation](https://maxtext.readthedocs.io/en/latest/development.html#adding-new-documentation-files).

Co-authored-by: Andy Twigg <andy.twigg@gmail.com>
Co-authored-by: Mohit Khatwani <mohitkhatwani@google.com>
PiperOrigin-RevId: 1016451169
…and_backward_grad_parity` is flaking in CI `cpu-unit` runs (for example, https://github.com/AI-Hypercomputer/maxtext/actions/runs/42409117174/job/128514209470 and https://github.com/AI-Hypercomputer/maxtext/actions/runs/42304894767/job/128192485759?pr=6093).

Skip `test_e2e_logits_loss_aux_loss_and_backward_grad_parity` in `granitemoe_test.py` while the underlying flakiness is investigated.

PiperOrigin-RevId: 1016495168
With `colocated_python_data_input=True`, every colocated host listed the data files and opened every ArrayRecord shard to count its records whenever it built its iterator: at startup, on every elastic attempt, and on every eval. Doing this simultaneously across all hosts causes hosts × shards GCS reads before training can start.

Shard ArrayRecord record counting across the colocated hosts on the iterator's CPU mesh and cache both pattern listings (`functools.cache`) and shard record counts in each colocated sidecar process. Each host lists patterns locally using `config.grain_data_source_max_workers` threads, counts only its assigned `1 / num_hosts` slice of unique shards, and exchanges integer counts through `RemoteIteratorWrapper` before building `FileInstruction` descriptors locally. The controller never reads dataset files or mixture JSONs, each shard is opened once cluster-wide on cold start, and surviving colocated processes open zero shards on subsequent elastic resizes, pause/resumes, or evals. Only colocated input with `grain_file_type=arrayrecord` changes; single patterns, weighted mixtures (`a,w;b,w` and `grain_train_mixture_config_path`), and eval files are covered.

Reimplements, using only Grain's public API, the FileInstruction pre-resolution from AI-Hypercomputer#4870 (commit AI-Hypercomputer@296fec0), later re-proposed in AI-Hypercomputer#5019.

PiperOrigin-RevId: 1017016224
…I-Hypercomputer#6052)

CPU flavors run the whole suite under pytest-xdist inside one container
whose cgroup memory limit (~125.8 GiB on linux-x86-n4-32) is shared by
every worker. A single TrainCompile AOT compile peaks at 10-16 GB and the
worker keeps 6-8 GB afterwards, so `-n auto` (32 workers) overcommits the
pod: scheduled cpu-unit shards die at 94-99 % progress with no traceback.

Workflow (.github/workflows/run_tests_against_package.yml, CPU flavors):
- Pin CPU_XDIST_WORKERS=8 (~16 GB per worker) and use it for both the
  split and non-split pytest invocations.
- Set MALLOC_ARENA_MAX=2 so glibc does not create 8*ncores arenas per
  worker process.
- Log the budget (nproc, worker count, cgroup memory.max, free -g,
  df -h /tmp, findmnt -T /tmp, available cgroup files) and sample the
  cgroup's memory.current / peak / RSS sum every 30 s while pytest runs
  ([memwatch]), so a killed shard can be diagnosed from the run log.
  The log showed /tmp is a 9p mount on the ~98 GB runner work disk, not
  tmpfs.
- Keep tools/dev/calculate_workers.py CPU_XDIST_PARALLELISM (used to
  size the shard count from baseline durations) in sync at 8, and update
  its test and comments accordingly.

tests/unit/train_compile_test.py:
- Every TrainCompile test writes a serialized executable to /tmp/test_*
  or gettempdir()/test_* and never deletes it. Snapshot `test_*` files in
  the temp dirs in setUp and remove, via addCleanup, whatever appeared
  during the test; pre-existing files are left alone.

tests/conftest.py:
- clear_jax_compilation_cache only ran on tpu/gpu/proxy backends. CPU
  flavors run under long-lived xdist workers that execute many modules
  back to back, so clearing when a worker leaves a module bounds how much
  JAX/XLA cache it carries forward. Intra-module cache reuse is unchanged.

Validated with the `scheduled-only` label (full scheduled universe):
24/24 cpu-unit shards survived across 6 runs, peak cgroup memory
29-41 GiB of 125.8 GiB, Run Tests 18-33 min (90-min timeout).
…r/moe-late-tp-combine

PiperOrigin-RevId: 1017441812
…o cpu-integration

Move the tests/unit/m3/glm5_3_flash_* files that hold slow (median CI
time >= 30s) tests to tests/integration/m3/ with a module-level
integration_test mark, and mark
train_compile_test::test_moe_deepseek_unscanned_bf16 as integration_test.
This removes ~23% of cpu-unit test time, which is hitting OOM kills and
pod scheduling timeouts on the linux-x86-n4-32 pool during scheduled runs.

The two tests that need 4 JAX devices stay in cpu-unit (the only CPU
flavor that sets 4 host devices) in
tests/unit/m3/glm5_3_flash_multi_device_test.py.

Also install CPU torch for cpu-integration in scheduled runs, so the moved
HF-parity tests run there instead of being skipped for missing torch.

BUGS: b/581488296
…era/bound-cpu-unit-heavy-tail

PiperOrigin-RevId: 1017491718
…i-pulse-setup

PiperOrigin-RevId: 1017498530
…7x-ci-test

PiperOrigin-RevId: 1017502145
…gression-alert-followups

PiperOrigin-RevId: 1017514161
load_sharded_hf_state sharded every HF tensor with Orbax's maximal
sharding, which often splits an inner axis (e.g. (1536, 4096) is split
along 4096). A safetensors tensor is stored row-major, so each process
then needs thousands of small strided byte ranges per file, and Orbax
reads whole file spans instead: every host reads almost the whole
checkpoint. On 64 v5e hosts, mixtral-8x22b read 246.6 GiB per host to
use 4.1 GiB (60x), and qwen3-235b-a22b was still reading after 43 min
when Orbax's 30 min load barrier timed out.

On several processes, shard each tensor along its leading axis only:
across all devices if it divides evenly, else across processes, else
not at all (small tensors). Each process then reads one contiguous range
per tensor. Set max_over_read_ratio=1.0, since files with more than 1024
tensors (fine-grained MoE) would otherwise still be read as whole spans.
A single process keeps the maximal sharding.

Each of these reads also downloaded gcsfs's 5 MiB read-ahead block: a
host of DeepSeek-V3 on 128 hosts needs about 230 KB per tensor but got
5.3 MB. Turn the read-ahead off while the safetensors are read.

Reads along the leading axis leave MoE wi_0 and wi_1 split on the axis
their hook transposes, so each tensor needed an all-to-all to reach its
stack's sharding: about 0.1 s per tensor on two v5e-256 slices, 25 min
for each of these weights of DeepSeek-V3. A tensor split over all
devices is now stacked as read, and each stack is resharded once. The
read layout orders devices by process and the model's mesh by topology;
between two device orders XLA can reshard by gathering the whole array
on every device (the 37.6 GB llama3.1-70b wi_0 stack needed 70 GB per
device with data parallelism across two v5e-256 slices), so arrays over
1 GiB are resharded in slices along an axis the target does not split.

The inner stacks of a multi-axis stack (one per expert) of such tensors
also stay as read until the final reshard. Placing each inner stack with
the target's sharding of its own axes left out the axes not stacked yet
and copied it across the expert mesh axis: with ici_expert_parallelism=16,
DeepSeek-V3 and qwen3-480b-a35b on two v5e-256 slices ran out of HBM
during the load, while pure FSDP loaded.

Only host 0 lists the files of a Hugging Face repo; the other hosts read
the GCS cache that host 0 fills. Listing from every host was
rate-limited (HTTP 429) on 128 hosts.
…moe E2E parity test

# Description

Re-enable `GraniteMoePyTorchParityAndPerturbTest.test_e2e_logits_loss_aux_loss_and_backward_grad_parity` and eliminate global PyTorch autograd state pollution across `tests/unit/`.

**Root cause:**
Seven unit test modules in `tests/unit/` (`gemma4_layers_test.py`, `gemma4_small_layers_test.py`, `qwen3_5_layers_test.py`, `qwen3_omni_layers_test.py`, `qwen3_vl_layers_test.py`, `hy4_vs_reference_test.py`, and `ming_layers_test.py`) called `torch.set_grad_enabled(False)` globally at module-import or `setUpClass` time without restoring it. Whenever `pytest-split` / `pytest-xdist` scheduled any of those modules on the same worker ahead of `granitemoe_test.py`, global autograd remained disabled when `test_e2e_logits_loss_aux_loss_and_backward_grad_parity` ran `hf_total_loss.backward()`, failing intermittently with:
```text
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
```

**Changes:**
- Replace un-restored module/class-level `torch.set_grad_enabled(False)` calls across all 7 offending `tests/unit/` modules with test-scoped `setUp` + `self.addCleanup(torch.set_grad_enabled, torch.is_grad_enabled())` teardowns so autograd is disabled during each test without polluting shared `pytest-xdist` workers.
- Re-enable `test_e2e_logits_loss_aux_loss_and_backward_grad_parity` in `tests/unit/m3/granitemoe_test.py` with `with torch.enable_grad():` around the two PyTorch backward passes, and add regression test `test_e2e_backward_parity_when_global_torch_grad_disabled` (`with torch.no_grad():`).
- Update the router forward hook in `tests/unit/m3/granitemoe_tpu_parity_test.py` to extract the floating-point router logits tensor across both `transformers <= 5.12.1` and `transformers >= 5.22.1`.

Part of AI-Hypercomputer#6052

# Tests

- `pyink --pyink --pyink-indentation=2 --line-length=122 --check` (unchanged) and `pylint` (`10.00/10`) across all 9 modified test files.
- Verified full 16-shard `granitemoe_test` suite (including `test_e2e_logits_loss_aux_loss_and_backward_grad_parity` and `test_e2e_backward_parity_when_global_torch_grad_disabled`) passes deterministically.

# Checklist

Before submitting this PR, please make sure (put X in square brackets):
- [X] I have performed a self-review of my code. For an optional AI review, add the `gemini-review` label.
- [X] I have necessary comments in my code, particularly in hard-to-understand areas.
- [X] I have run end-to-end tests and provided workload links above if applicable.
- [X] I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in [our documentation](https://maxtext.readthedocs.io/en/latest/development.html#adding-new-documentation-files).
…edo/fix-granitemoe-grad-mode

PiperOrigin-RevId: 1017670860
…v-cpu-unit-to-integration

PiperOrigin-RevId: 1017675290
…fetensors-dynamic-contiguous-read

PiperOrigin-RevId: 1017682327
…fetensors-dynamic-entry-points

PiperOrigin-RevId: 1017717306
…astic-default-device-all-threads

PiperOrigin-RevId: 1017719361
@nuinashco-ks nuinashco-ks changed the title Gemma-4 vision: clip flag in the E2E script, keep packing for text-only runs Gemma-4 vision: pass the clip flag in the E2E script, keep packing on for text-only runs Nov 11, 2026
@nuinashco-ks
nuinashco-ks marked this pull request as ready for review November 12, 2026 22:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.