Skip to content

Gemma-4: make the fixed HF buffers UntrainableParam - #4

Open
nuinashco-ks wants to merge 1148 commits into
lokic233:gemma4-e2b-e4b-vision-clipped-linearsfrom
KyivstarDMP:pr/4790-untrainable-clip-bounds
Open

nuinashco-ks wants to merge 1148 commits into
lokic233:gemma4-e2b-e4b-vision-clipped-linearsfrom
KyivstarDMP:pr/4790-untrainable-clip-bounds

Conversation

@nuinashco-ks

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

Copy link
Copy Markdown

Description

Makes the weights that the Hugging Face Gemma-4 checkpoints store as fixed buffers UntrainableParam: the 448 vision clip bounds, the vision tower's std_bias/std_scale and the decoder's layer_scalar. The optimizer then freezes them by type; the clip bounds were frozen by name before.

Stacked on #2 and #3. Until they land, this diff includes them; the four commits on their own: compare.

Why

Today the bounds are plain nnx.Param, kept out of training by name patterns inside apply_trainable_parameters_mask when use_clipped_linears_for_vit is on. That stops working silently if a bound is renamed, and it does not reach the RL trainer, which builds its own optimizer.

UntrainableParam is an nnx.Param subclass, so the bounds are still stored in params and existing checkpoints load unchanged. They get no gradient, no update, no weight decay and no optimizer state.

std_bias/std_scale are fixed buffers in HF for the models with standardize=True (26B/31B), and E2B/E4B have none (standardize=False), so the converter fills them with 0 and 1 there. As plain params they were trained, and an HF export of E2B/E4B drops them, so the exported model differed from the trained one. As UntrainableParam they keep their converted values; for E2B/E4B that is a permanent no-op.

layer_scalar is the same case in the text decoder: a fixed buffer in HF that MaxText trained. AI-Hypercomputer#6224 has the details.

AI-Hypercomputer#4807 fixes std_bias/std_scale in a different way: a standardize_for_vit key that every Gemma-4 model yml must set, a new VisionStdVar variable class for 26B/31B, and no std_bias/std_scale at all for E2B/E4B. This PR does not use it, for two reasons:

What this PR does not do is remove the two unused weights from E2B/E4B.

Commits

  1. feat(nnx): add UntrainableParam for weights that are never trained: the first commit of Add UntrainableParam for weights that are never trained AI-Hypercomputer/maxtext#6224 (draft PR to main), cherry-picked so this branch works before it lands. It matches Add UntrainableParam for weights that are never trained AI-Hypercomputer/maxtext#6224 at 2b5f19858; if that PR changes in review, this copy has to follow before main is merged here again.
  2. refactor(gemma4): make the vision clip bounds UntrainableParam: _mk_clip_bound returns UntrainableParam. Removed: _CLIP_LEAF_TOKENS, _CLIP_BOUND_NAMES, _is_clip_bound_path, clip_optimizer_freeze_mask, _clip_bound_value, the clip branch in optimizers.py and its tests. After this, the branch does not change optimizers.py beyond Add UntrainableParam for weights that are never trained AI-Hypercomputer/maxtext#6224.
  3. fix(gemma4): make std_bias and std_scale UntrainableParam: two constructors in Gemma4VisionEncoderLayer, plus a test that the optimizer treats both as untrainable.
  4. fix(gemma4): make layer_scalar UntrainableParam: the second commit of Add UntrainableParam for weights that are never trained AI-Hypercomputer/maxtext#6224, cherry-picked for the same reason.

Tests

On this branch, with main's dependency versions:

  • JAX_PLATFORMS=cpu python3 -m pytest tests/unit/gemma4_small_layers_test.py tests/unit/optimizers_test.py tests/unit/gemma4_layers_test.py tests/unit/model_creation_utils_test.py tests/unit/untrainable_param_test.py: 148 passed, 46 skipped. The new VisionStdTest fails without the third commit.
  • Golden logits on TPU, same check as on the merge: all 448 clip bounds validated, max KL 4.2959e-4, unchanged, with and without the third and fourth commits.
  • Real E2B training on TPU through train.py's train step: 3 AdamW steps with weight decay 2.0, trainable_parameters_mask=['vision_encoder'] (which also matches the bounds by name) and the tower's gradient stopped, so weight decay was the only force on it. Clip bounds changed: 0 of 448. Regular tower weights changed: 212 of 213. No optimizer state was allocated for the bounds. This run predates the third commit.
  • Real E2B training on TPU, 50 AdamW steps with lr 2e-5, weight decay 0.1 and the vision tower trained: before the third commit std_bias moved by up to 3.4e-4 and the held-out loss of the trained model and of its HF export differed by 0.0015 (0.57124 vs 0.56973); with it, std_bias and std_scale moved 0 and both losses are 0.56136.

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.

bvandermoon and others added 30 commits October 22, 2026 19:13
…/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.
…uojin-pp-bsw-cp-as-ep-context

PiperOrigin-RevId: 1005770385
…v-tests-in-ci

PiperOrigin-RevId: 1005776137
abhinavclemson and others added 21 commits November 8, 2026 20:47
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: make the clip bounds UntrainableParam Gemma-4 vision: make the clip bounds and std_bias/std_scale UntrainableParam Nov 10, 2026
@nuinashco-ks nuinashco-ks changed the title Gemma-4 vision: make the clip bounds and std_bias/std_scale UntrainableParam Gemma-4: make the fixed HF buffers UntrainableParam Nov 10, 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.