Skip to content

[qwen3-8-flash] Superseded by the Qwen3.8 Flash-Next PR stack - #5655

Closed
shuhuayu wants to merge 2 commits into
pytorch:mainfrom
shuhuayu:qwen3-8-flash-next
Closed

shuhuayu wants to merge 2 commits into
pytorch:mainfrom
shuhuayu:qwen3-8-flash-next

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Status

Superseded by the following Qwen3.8 Flash-Next draft stack:

The original branch and local worktree are retained for reference.
The description below records the earlier implementation and its validation.

Summary

Add the released Qwen3.8-Flash-Next text and vision backbone, following the add_model workflow proposed in #5636.

  • Add qwen3_8_flash_next with the released 125B-A6B configuration and an eight-layer debug configuration.
  • Implement four gated residual streams (GR), per-layer lexical embeddings (PLE), and Qwen Sparse Attention (QSA), including the sparse-stage indexer KL objective.
  • Add HF checkpoint conversion, reference parity checks, CPU feature tests, combined distributed training fixtures, and a committed deterministic numerical golden with an independent remote replay.

Architectural choices

Flash-Next uses 48 decoder layers, dimension 2560, and a 3:1 Gated DeltaNet/QSA layout. It adds four residual streams, a learned block indexer, and a large n-gram lexical lookup table to the existing Qwen architecture. These components need model-specific equations and checkpoint mappings.

The port reuses Qwen3.5's Gated DeltaNet, expert computation and dispatch, vision encoder, multimodal preprocessing, MRoPE, and training lifecycle. The model-specific MoE adapters preserve HF's BF16 router rounding. Shared embedding, normalization, and RoPE options preserve existing defaults and checkpoint layouts.

PLE resets at EOS and packed document boundaries. Original token IDs and document positions survive pipeline boundaries independently of multimodal rotary coordinates. The lexical table uses TP across features, preserving HF row-chunk export without gathering the full table on each rank.

QSA selects complete four-token blocks causally and includes the current partial block. The training target sums detached main-attention probabilities across heads, max-pools complete blocks, and normalizes over selected blocks. TP heads are summed before pooling. The report does not give a loss coefficient; this configuration uses 1.0, independently of the MoE load-balancing coefficient 0.001.

Strict deterministic training exposed GDN L2-normalization backward autotuning choosing different FP32 reduction orders across fresh processes. The shared chunk, CP, and recomputed backward paths now disable this autotuning when strict determinism is enabled, matching KDA's existing policy. Normal-mode autotuning is preserved. The reference parity report and nine shared GDN GPU forward/backward tests pass with this change.

Sources and checkpoint compatibility

The adapter covers all 1,627 backbone/vision checkpoint entries and warns about the 31 unused mtp.* entries. Reduced checkpoint round trips load strictly; the complete released checkpoint schema is checked using meta tensors. Native parameter accounting is 177,392,830,576, including the 51,200,245,760-parameter lexical table and 448,931,056-parameter vision encoder. The flavor name follows the release's 125B-A6B label.

Validation

The recorded runtime evidence uses source base 72a3a126fe732317d1ebaecab566933dca769758, PyTorch 2.16.0.dev20261006+cu132, seed 42, and strict deterministic execution. The reports record software, input, tokenizer, initialization, and source provenance.

  • pre-commit run --all-files: all hooks passed, including a fresh run before opening this draft.
  • 146 targeted CPU tests passed: independent functional oracles, gradients, packed boundaries, model/config contracts, checkpoint conversion, shared components, auxiliary-loss resets, and integration-recipe registration.
  • Nine shared GDN GPU forward/backward tests passed in strict deterministic mode.
  • Ten-step plain/remat runs matched every full-precision TensorBoard loss and grad_norm exactly.
  • A real eight-GPU GB200 TorchX/MAST run completed ten steps with FSDP2 + TP2 + EP4 + PP2, sequence parallelism, 1F1B, two microbatches, and PLE on the second pipeline stage.
  • Separate PP2 and multimodal runs completed ten steps. The image fixture uses sequence length 1024 and exercises the vision encoder.
  • A 100-step reduced-model run on C4 English with the pinned official tokenizer reduced mean loss from 12.507574 (steps 1-10) to 7.963772 (steps 91-100). These convergence values use stdout rounded to five decimal places.

Same-weight reference parity

Comparison Maximum absolute error
GR forward, input and parameter gradients, FP32 0
PLE forward, FP32 7.45e-9
PLE input and parameter gradients, FP32 3.19e-12
QSA forward, FP32 4.10e-8
Vision including merger, FP32 3.28e-7
Full eight-layer logits, BF16 0.001953125

The BF16 fixture selects identical experts at every layer. Logit cosine similarity is 0.9999963898; mean per-token KL(reference || native) is 8.10e-8; top-1 and top-5 sets agree for every fixture token. The reproducible harness and checked-in report are:

  • scripts/checkpoint_conversion/numerical_tests_qwen3_8_flash_next.py
  • tests/assets/numerics/qwen3_8_flash_next_reference.json

Packed BF16 routing has two near-tied tokens whose expert sets differ from separate document invocations, with maximum logit error 0.02587890625. Replaying isolated expert IDs while recomputing packed mixing weights reduces the maximum error to 0.00390625. Independent CPU boundary tests verify the underlying math; unconstrained packed BF16 routing is not bitwise equivalent in this fixture.

Deterministic remote golden

Two independent fresh GB200 launches completed ten TP2/EP2/SP steps with identical full-precision loss and grad_norm before golden export. The registered integration runner then exported the golden. A subsequent independent launch imported the committed golden without export and passed exact loss and grad_norm assertions at every step.

  • Golden: tests/assets/losses/real_pg/qwen3_8_flash_next_gb200.txt
  • Registered B200 test: qwen3_8_flash_next_tp_ep_numerics
  • H100 suite fixtures: combined parallelism, PP2, activation remat, and multimodal training.
python -m tests.integration_tests.run_tests outputs/flash-next-replay \
  --test_suite b200 --test_name qwen3_8_flash_next_tp_ep_numerics \
  --execution_mode real_pg --gpu_arch_type cuda --gpu_arch b200 \
  --ngpu 2 --no-parallel

The model README and golden header contain the remote job IDs, persistent output paths, and complete replay provenance.

Execution limits

  • QSA uses bounded gather/indexer chunks and native SDPA MATH. Dynamic selection shapes currently require disabling CUDA graphs; context parallelism is explicitly rejected.
  • MTP training and speculative decoding are outside the port's current scope.
  • Full 177B parameter materialization, production-scale convergence, and production throughput have not been validated.
  • The pinned nightly has a preexisting CosSinRoPE eager/compile discrepancy on unchanged upstream/main: one BF16 gradient value differs by 9.54e-7. The pinned CUTLASS DSL 4.6.2 supports the validated fused GDN backend; the optional cuDNN backend requires DSL 4.7.0.

Draft follow-ups for current upstream/main

The two implementation commits were validated against the source base above. Latest upstream/main (3f990a8e9 when this draft was prepared) merges without textual conflicts, but has since changed the compile configuration and loss contracts.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 28, 2026
@shuhuayu

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 3m 12s —— View job


Request changes -- see the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Request changes -- The model port is the right thing to add, but it changes shared code (three single-consumer flags, plus a GDN determinism fix for every GDN model), lets the indexer KL train the backbone with a coefficient that isn't sourced, and commits internal-infra provenance to OSS files.

What this PR does. Adds qwen3_8_flash_next, a subclass of Qwen3.5. It adds three things:

  • four gated residual streams, carried as one [T, 4*D] tensor;
  • a hashed n-gram lexical table (PLE) on layer 1, TP-sharded by feature;
  • QSA, where each query attends to the top-k 4-token blocks plus its own partial block, and an indexer is distilled from detached main-attention probabilities via AuxLoss.inject.

It also changes common/embedding.py, common/norm.py, common/rope.py and common/attention/{gdn,cp_gdn}.py, and adds five integration entries with a B200 golden.

Example. For a packed document at token 9 with compress_ratio=4 and token_budget=4 (one block):

complete blocks: [0..3] ends at 3, [4..7] ends at 7 -> visible (end <= 9, same doc)
indexer scores both, picks top-1, e.g. [4..7]
tail: token 8 and 9 (local_count % 4 = 2 -> current partial block)
SDPA over J = [4,5,6,7,8,9]; KL target = max-pool over heads-summed probs of [4..7]

Today, gradients of that KL reach x_TD and every layer below it. In DeepSeek V4's equivalent, they stop at the indexer.

Must fix

  1. tests/assets/losses/real_pg/qwen3_8_flash_next_gb200.txt:1-43 and torchtitan/models/qwen3_8_flash_next/README.md:125-185 -- These files contain MAST job IDs, metaconda/torchx images and Manifold paths under a username. The README also narrates validation history ("previously chose", "the original MAST image predates..."). Move both to the PR description. The README should describe the architecture, the supported and verified parallelisms, and the HF numerics check.
  2. torchtitan/models/common/embedding.py:31, common/norm.py:30, common/rope.py:390 -- Three boolean flags in shared modules, each set only by Flash-Next. Move them into model-folder subclasses, or make the HF rounding the single behavior if it matches the reference for Qwen3.5 too (see inline comments).
  3. torchtitan/models/common/attention/gdn.py:125-126 -- The GDN l2norm autotune change is a separate concern that touches every GDN model. The recurrent path is changed unconditionally, which contradicts the description and may break trainer/generator parity. Split it into its own PR.
  4. torchtitan/models/qwen3_8_flash_next/attention.py:325-331 -- The indexer input isn't detached, so indexer-KL gradients train the backbone, and coeff=1.0 (flavors.py:236) has no source. Detach the input as DSV4 does, or cite the report.
  5. torchtitan/models/qwen3_8_flash_next/model.py:120 -- The production flavor compiles nothing by default, including loss and the norm regions, and nothing explains why. Inherit Qwen3.5's default when migrating to LocalCompileConfig (#5463), which the description already lists as a follow-up.
  6. tests/integration_tests/h100.py:188-219 -- Four new H100 entries. pp2 is a subset of all_parallelism, and ac and mm can be merged. Prefer an interleaved schedule with spmd typechecking in the combined entry.
  7. tests/unit_tests/cpu/models/test_qwen3_8_flash_next.py:499-590 -- These tests only re-read recipe and golden config. Delete them.
  8. tests/assets/numerics/qwen3_8_flash_next_reference.json -- A 374-line report that no test reads. The script writes to outputs/ by default. Keep the summary in the PR description and drop the file from tests/assets/.

Should consider

  • torchtitan/models/qwen3_8_flash_next/attention.py:241-285, 111-148 -- Each QSA layer runs a per-chunk TP all-reduce (about 16k at the flavor's 262k context) and recomputes the block metadata with .nonzero() syncs. Do one all-reduce per forward and add a TODO for a sparse kernel. Enabling CUDA graphs should fail clearly instead of at capture.
  • torchtitan/models/qwen3_8_flash_next/attention.py:209-212,322 -- build_attention_metadata builds varlen metadata every step, and forward then discards it.
  • torchtitan/models/qwen3_8_flash_next/moe.py:31 -- .to(input.dtype).float() is the round trip that Inductor drops (hi_mid_lo_linear.py:413). Under compile, the HF-matching router rounding may silently disappear.
  • torchtitan/models/qwen3_8_flash_next/flavors.py:369-373 -- attn_backend accepts only its own default and raises otherwise. Drop the parameter.
  • torchtitan/models/qwen3_8_flash_next/model.py:213-222 -- document_positions and ple_input_ids fall back silently, but preprocess_inputs always supplies both. Remove the fallbacks.
  • torchtitan/models/qwen3_8_flash_next/state_dict_adapter.py:89,119 -- chunk/cat along dim 0 of the 51B-row table, which FSDP shards on dim 0, may redistribute across DP. The same applies to FSDP unsharding the table on every forward at full scale (unverified). This bears on the README's "without gathering" claim.

Questions

  • Was the GB200-recorded golden checked on the B200 CI runner the suite actually uses?
  • Does the report specify whether the indexer KL should back-propagate into the backbone?

Not verified: GPU numerics, l2norm forward rounding under autotune, DTensor redistribution in the adapter. A maintainer still needs to review, since this touches models/common/.

Comment on lines +1 to +43
# config: qwen38_flash_next_debugmodel_tp2
# ngpu: 2
# parallelism: FSDP=1, TP=2, EP=2
# hardware: NVIDIA GB200, SM100, two GPUs on one MAST host
# execution_mode: real_pg; sequence_parallel=True; spmd_typechecking=True
# date: 2026-10-27
# source_base: upstream/main 72a3a126fe732317d1ebaecab566933dca769758
# export_workspace: metaconda_demo:5c740da5bd5b4ac0b9848110bf5f7904
# source_ast_sha256: 199ae9c1ed85c0e29675554a40260d371915e82327dc8ade0214f466901be486
# source_ast_scope: torchtitan/, torchtitan_recipes/, scripts/_checkpoint_test_config.py, scripts/loss_compare.py
# source_ast_algorithm: sorted Python filename, NUL, ast.dump(include_attributes=False), NUL
# conda_image: torchx_base_conda_env:9195bda55b1445a2a161b34121d13687
# python: 3.12.13
# torch: 2.16.0.dev20261006+cu132, 1a66f68165eb1685c14874588d9a2e0cd475e116
# cuda: 13.2; driver: 580.126.20
# dependencies: spmd_types=0.3.1, attn-gym=0.0.17, torch_remat=0.2.2, torch_checkpointing=0.1.1
# dependencies: nvidia-cutlass-dsl=4.6.2, triton=3.9.0+gitaad2a60d, torchao=0.19.0.dev20261007+cu132
# precision: FP32 parameters/optimizer, BF16 mixed-precision compute, FP32 reduction
# attention: QSA SDPA MATH, fused GDN, L2-norm backward autotune=False
# initialization: independently recreated CPU FP32 DCP seed checkpoint; seed=42
# seed_config: torchtitan_recipes.tests.models.qwen3_8_flash_next.qwen38_flash_next_debugmodel
# state: fresh optimizer, scheduler and dataloader; strict deterministic=True
# features: four residual streams, PLE, GDN, QSA top-4 blocks, MoE 8 experts/top-2
# auxiliary_loss_coefficients: qsa_indexer=1.0, moe_load_balance=0.001
# optimizer: fused AdamW, lr=0.0008, betas=(0.9,0.95), eps=1e-8, weight_decay=0.1, max_norm=1.0
# scheduler: warmup_steps=2, linear decay_ratio=0.8, min_lr_factor=0.0
# compile: off; activation_remat: off; cuda_graphs: off
# input: context_length=64, tokens_per_train_step=128, shuffle=False, ConcatThenSplitPacking
# dataset: tests/assets/c4_test/data.json
# dataset_sha256: 07a274d2f6c903fd1c491260be302f99383930d31656f50de33ef467af6643b1
# tokenizer: tests/assets/tokenizer/tokenizer.json
# tokenizer_sha256: a9eb477ec2c2520fa45c2e73078e930ca57d316fe8cce2f45842ac3cc48f5271
# tokenizer_config_sha256: acf745f72b6b8f4dd11ee38fa1931022978d408c0a3477495c8ab27086082697
# repeatability: qwen38-flash-next-numerics-k-tv4bvsmb, qwen38-flash-next-numerics-l-mcss09v9
# repeatability: all 10 full-precision loss and grad_norm values matched before export
# export_job: qwen38-flash-next-numerics-export-m-xlhlt75f, registered b200 integration runner
# outputs: torchtrain_datasets/tree/shuhuay/qwen38-flash-next/{numerics-k,numerics-l,numerics-export-m}
# replay_job: qwen38-flash-next-numerics-replay-n-s2744wlm
# replay_source_commit: 43aaf58ec68902d6fa79dd5d0bf9b787fec548a1
# replay_workspace: metaconda_demo:ed3fe5acc5b44b32ae58a3cd313eb5d9
# replay: committed golden imported without export; all 10 loss and grad_norm assertions passed
# replay_outputs: torchtrain_datasets/tree/shuhuay/qwen38-flash-next/numerics-replay-n
# step loss grad_norm

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This header names internal infrastructure in an OSS file:

  • MAST hosts (line 4)
  • metaconda_demo: workspaces (lines 8, 41)
  • torchx_base_conda_env (line 12)
  • MAST job IDs (lines 36, 38, 40)
  • Manifold paths under a personal username (lines 39, 43)

External contributors can't use any of it, and none of it is needed to replay the golden. Sibling goldens such as kimi_k3_b200.txt keep a header of about 4 lines: config, ngpu, parallelism, hardware. Trim the header to that and put the provenance in the PR description.

Related question: the golden was recorded on GB200 hosts, but the registered suite runs on B200 CI runners. Has a B200 run been checked to reproduce these values bit for bit?

num_embeddings: int
embedding_dim: int
padding_idx: int | None = None
vocab_parallel: bool = True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This adds a boolean mode switch to the shared Embedding, and its only consumer is the Flash-Next n-gram table (flavors.py:139). It also forces the edit in transformers_modeling_backend/module_conversion.py.

.claude/rules/config.md says implementations are selected by config type, not by a boolean. Core principle 4 says shared modules shouldn't be bent for one model.

NGramEmbedding already owns the table's sharding (ngram_table_sharding, TP S(1)). It can hold a plain nn.Embedding (or call F.embedding on its own parameter) inside qwen3_8_flash_next/embedding.py. That would leave common/embedding.py and module_conversion.py unchanged.

dim: int
eps: float
activation_fn: UnaryActivationFn.Config
cast_before_gate: bool = False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rounding flag has a single consumer. So does CosSinRoPE.compute_in_float32 (rope.py:390). Each adds a per-model knob to a shared component.

Question: as far as I know, HF's Qwen3.5/Qwen3-Next RMSNormGated also casts to the input dtype before applying the weight and gate. Is that right? HF's apply_rotary_pos_emb also rotates in the input dtype.

  • If yes: this rounding is the reference behavior for every Qwen GDN model, not something specific to Flash-Next. Pick one behavior for all consumers, explain the numerics change and regenerate the affected goldens. No flag.
  • If no: keep the variant in the model folder as a subclass, as moe.py already does for RouterLinear and FlashNextRouter.

Either way, common/norm.py and common/rope.py shouldn't gain flags that only one model sets.

Comment on lines +125 to +126
normalized_q_BTHK = l2norm(q_BTHK, cu_seqlens=cu_seqlens, autotune=False)
normalized_k_BTHK = l2norm(k_BTHK, cu_seqlens=cu_seqlens, autotune=False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the recurrent path, autotuning is disabled unconditionally, not only in deterministic mode. That contradicts the description's "normal-mode autotuning is preserved".

This path exists so the trainer's forward is bitwise identical to the vLLM generator. The generator still calls l2norm(query, cu_seqlens=cu_seqlens) with default autotuning (rl/generator/vllm/gdn.py:323-324). If l2norm's forward tile choice affects rounding, trainer/generator parity breaks (unverified).

More broadly, this GDN determinism change affects every GDN model (qwen3_5/6/8, RL) and fixes a pre-existing issue that isn't specific to Flash-Next. It also carries renames (normalized_q -> normalized_q_BTHK, the B = batch legend).

Please split it into its own PR, with:

  • the problem shown on main (a fresh-process mismatch for qwen3_5);
  • a check that the deterministic goldens of existing GDN models are unchanged, or regenerated with an explanation;
  • the recurrent call sites either left alone or matched on both the trainer and generator sides.

Comment on lines +325 to +331
x_TD = maybe_gather_tp_input(self, x_TD)
selected_indices_TJ, scores_TB = self.indexer(
x_TD,
positions=positions,
document_positions_T=document_positions_T,
padding_mask_T=padding_mask_T,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The indexer receives a non-detached x_TD, so the indexer-KL gradient flows into the residual streams, the hyper-connections and every earlier layer. The KL target is detached (attention.py:259); the student input is not.

DeepSeek V4, the existing sparse-indexer distillation in this repo, detaches the indexer inputs (deepseek_v4/attention.py:392: self.indexer(x.detach(), qr.detach(), ...)). With coeff=1.0 (flavors.py:236, 100x DSV4's 0.01) and no coefficient in the report, the KL can noticeably reshape backbone training.

Unless the Flash-Next report says the indexer loss should train the backbone, pass x_TD.detach() to the indexer here. Either way, state the choice and where coeff=1.0 comes from in the flavor.

Comment on lines +271 to +275
tp_group = spmd_mesh_group("tp")
if tp_group is not None:
teacher_QJ = wait_tensor(
all_reduce(teacher_QJ, "sum", tp_group)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This issues one TP all_reduce for every 16-query chunk. With the flavor's 262144 context, that is about 16k collectives plus 16k SDPA-MATH calls per QSA layer per microbatch. The surrounding loop does the same work in Python.

The block metadata at lines 111-148 (document_starts, .nonzero() x2, num_selected from .numel()) is recomputed in all 12 QSA layers. It depends only on document_positions/padding_mask, and each call adds device-to-host syncs.

Smallest improvements:

  • Collect teacher_QJ across chunks and all-reduce once per forward, as SparseIndexerLoss does in deepseek_v4/compressor.py.
  • Add a TODO that the gather+MATH path is a placeholder for a sparse kernel.

Also, this code can't be CUDA-graph captured, but only the recipes set disable_cuda_graphs. A user who enables CUDA graphs gets a capture failure instead of a ValueError.

class Config(Qwen35Model.Config):
num_streams: int
hyper_connection_mixer: GatedResidual.Config
local_compile_regions: list[str] = field(default_factory=list)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This re-declares the base field with an empty default, so the 125B-A6B flavor runs every local-compile region eagerly, including loss, gated_rmsnorm, offset_rmsnorm and partial_rope. Its parent Qwen35Model.Config compiles all of those by default (qwen3_5/model.py:337).

There's no comment explaining the change. The production flavor would silently get slower than its Qwen3.5 sibling.

The field is also the stale API that #5463 replaced with LocalCompileConfig, as the description notes. When migrating, inherit Qwen3.5's default. If a region genuinely can't compile for this model, drop only that region and add a comment explaining why.

Comment on lines +188 to +219
IntegrationTestDefinition(
configs=[qwen38_flash_next_debugmodel_all_parallelism],
test_descr="Qwen3.8-Flash-Next FSDP2+TP2+EP4+PP2 with PLE on stage two",
test_name="qwen3_8_flash_next_all_parallelism",
ngpu=8,
use_real_pg=True,
skip_rocm_test=True,
),
IntegrationTestDefinition(
configs=[qwen38_flash_next_debugmodel_mm],
test_descr="Qwen3.8-Flash-Next images, multimodal rotary positions and PLE",
test_name="qwen3_8_flash_next_mm",
ngpu=1,
use_real_pg=True,
skip_rocm_test=True,
),
IntegrationTestDefinition(
configs=[qwen38_flash_next_debugmodel_ac],
test_descr="Qwen3.8-Flash-Next full activation rematerialization",
test_name="qwen3_8_flash_next_ac",
ngpu=1,
use_real_pg=True,
skip_rocm_test=True,
),
IntegrationTestDefinition(
configs=[qwen38_flash_next_debugmodel_pp2],
test_descr="Qwen3.8-Flash-Next original token metadata for PLE on stage two",
test_name="qwen3_8_flash_next_pp2",
ngpu=2,
use_real_pg=True,
skip_rocm_test=True,
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Four new H100 entries for one model is more CI than the coverage needs (.claude/rules/tests.md):

  • qwen3_8_flash_next_pp2 (PP2, PLE on stage 2) is a strict subset of qwen3_8_flash_next_all_parallelism. Drop it.
  • _ac and _mm are both 1-GPU runs. Fold them into one entry (remat plus images), or enable remat in all_parallelism.
  • all_parallelism uses 1F1B with no SPMD type checking. Switching to an interleaved schedule with spmd_typechecking=True covers the harder configuration at no extra cost.

That gives one 8-GPU entry and at most one 1-GPU entry.

Comment on lines +499 to +590
def test_integration_recipe_and_pipeline_placement():
from torchtitan.distributed.pipeline_parallel import (
_generate_llm_fqn_per_model_part,
)
from torchtitan.models.common.decoder import TransformerBlock
from torchtitan.models.qwen3_8_flash_next.model import Qwen38FlashNextModel

from tests.integration_tests.h100 import build_h100_tests_list

test = next(
test
for test in build_h100_tests_list()
if test.test_name == "qwen3_8_flash_next_all_parallelism"
)
cfg = test.configs[0]()
assert test.ngpu == 8 and test.use_real_pg
assert isinstance(cfg.model, Qwen38FlashNextModel.Config)
assert all(isinstance(layer, TransformerBlock.Config) for layer in cfg.model.layers)
parallelism = cfg.parallelism
assert (
parallelism.data_parallel_shard_degree,
parallelism.tensor_parallel_degree,
parallelism.expert_parallel_degree,
parallelism.pipeline_parallel_degree,
) == (2, 2, 4, 2)
assert parallelism.num_pp_microbatches == 2 and cfg.training.steps >= 10
assert (
cfg.debug.seed == 42
and cfg.debug.deterministic
and not cfg.debug.deterministic_warn_only
)
stages = _generate_llm_fqn_per_model_part(
2,
8,
parallelism.pipeline_parallel_first_stage_less_layers,
parallelism.pipeline_parallel_last_stage_less_layers,
)
assert "layers.1" not in stages[0] and "layers.1" in stages[1]


def test_numerical_recipe_and_golden_retain_model_features():
from torchtitan_recipes.tests.models.qwen3_8_flash_next import (
qwen38_flash_next_debugmodel,
qwen38_flash_next_debugmodel_tp2,
)

from tests.integration_tests.b200 import build_b200_tests_list

test = next(
test
for test in build_b200_tests_list()
if test.test_name == "qwen3_8_flash_next_tp_ep_numerics"
)
assert list(test.configs) == [qwen38_flash_next_debugmodel_tp2]
assert test.loss_compare_seed_config is qwen38_flash_next_debugmodel
assert test.ngpu == 2 and test.use_real_pg and not test.disabled
cfg = test.configs[0]()
assert (
cfg.parallelism.tensor_parallel_degree,
cfg.parallelism.expert_parallel_degree,
cfg.parallelism.pipeline_parallel_degree,
cfg.parallelism.context_parallel_degree,
) == (2, 2, 1, 1)
assert cfg.parallelism.enable_sequence_parallel and cfg.debug.spmd_typechecking
assert cfg.debug.seed == 42 and cfg.debug.deterministic
assert not cfg.debug.deterministic_warn_only
assert cfg.training.steps >= 10 and cfg.training.disable_cuda_graphs
assert cfg.activation_remat is None and not cfg.model.local_compile_regions
assert cfg.model.num_streams == 4 and cfg.model.layers[1].ple is not None
assert any(isinstance(layer.attention, GDN.Config) for layer in cfg.model.layers)
sparse_layers = [
layer
for layer in cfg.model.layers
if isinstance(layer.attention, QSAAttention.Config)
]
assert sparse_layers and all(
isinstance(layer.feed_forward, MoE.Config) for layer in cfg.model.layers
)
assert all(
layer.attention.indexer.token_budget < cfg.training.max_context_length
for layer in sparse_layers
)
assert test.golden_numerics_path is not None
golden = Path(__file__).resolve().parents[4] / test.golden_numerics_path
lines = golden.read_text().splitlines()
assert "# step loss grad_norm" in lines
rows = [line.split() for line in lines if line.strip() and not line.startswith("#")]
assert [int(row[0]) for row in rows] == list(range(1, 11))
assert all(
len(row) == 3 and all(math.isfinite(float(value)) for value in row[1:])
for row in rows
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two tests only re-read what the recipes and integration entries just set: parallelism degrees, seed, deterministic, steps >= 10, local_compile_regions. They also parse the golden file's format and import a private _generate_llm_fqn_per_model_part.

The integration runner already checks the golden and catches a broken recipe. .claude/rules/tests.md says not to add tests that re-read config. Delete both.

The flavor-constant asserts near the top of the file (:36-60, :341-345) fall in the same category.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant