Repository navigation
[config] Migrate ModelConfigConverter to ModelConfigTransform - #6164
Conversation
Every model config converter is now a ModelConfigTransform: BatchInvariantFlexTransform, LMHeadFP32OutputTransform, and the MXFP8/NVFP4 linear and grouped-linear transforms (base QuantizationTransform). ModelConfigConverter, validate_converter_compatibility and the `converters` argument of every build_model_config are deleted; recipes apply the transforms with apply_transforms. TransformRelations now carries what the "converters run first" rule and validate_converter_compatibility enforced: quantization and the fp32 lm_head run before LoRA, and quantization conflicts with the fp32 lm_head and with async TP. Fixes #6087.
|
@claude Review this PR |
There was a problem hiding this comment.
Verdict: Request changes -- the migration is right and the parity evidence is thorough, but it drops the structural guarantee that quantization runs before LoRA and puts nothing in its place. In-repo configs are unaffected; a later apply_transforms call can still silently unfreeze LoRA base weights. The fix is a few lines.
What this PR does. It finishes the ModelConfigConverter -> ModelConfigTransform migration. Batch-invariant flex, the fp32 lm_head and the four quantization converters become transforms. The converters argument is removed from all 13 build_model_configs. Recipes now call apply_transforms. The old rule that converters always run first becomes explicit TransformRelations: quantization and the fp32 lm_head run before LoRA, and quantization conflicts with the fp32 lm_head and with async TP.
Example.
# before
config.model = build_model_config("8B", seq_len=seq_len, parallelism=config.parallelism,
converters=[NVFP4LinearConverter.Config(fqns=fqns)])
# after
config = apply_transforms(config, [NVFP4LinearTransform(fqns=fqns)])
# newly possible, and silent: quantizing in a call after LoRA
config = apply_transforms(llama3_debugmodel_lora(),
[MXFP8LinearTransform(fqns=["feed_forward"])])
# FrozenLinear.Config w13/w2 -> plain MXFP8Linear.Config, so the base FFN weights trainMust fix
- PR description -- the template's "Summary (human-written)" section is missing. The TLDR may be meant as the summary; put it under that heading (written by the author).
torchtitan/config/transform/relations.py:35-38-- the before-LoRA order is checked only within one call, and "convert only stock projection configs" isn't enforced. LoRA's frozen configs pass_validate_quantizable_linearand lose their freezing. Fix: add atype(config) is not owner.Configcheck in the quantization transforms (details inline).
Should consider
torchtitan/config/transform/relations.py:47-49-- the async TP conflict also bans grouped-only quantization, which async TP never touches and which main allowed. The comment also says async TP rejects quantized projections; in fact it silently skips them (details inline).
Details
- Gate: this finishes the migration listed in
direction.md(#6087), removes themodels -> config.transformdependency that went against the package's direction, and has net -363 LoC. Nothing else in flight overlaps. - Cross-call composition:
_orderedand_reject_conflicts(apply.py) only see one call's list. For the fp32 lm_head this is already covered:LMHeadFP32OutputTransformraises on a non-plainLinear.Config, so applying it after LoRA fails loudly. Quantization has no such check. That is the must-fix above. QuantizationTransform<->LMHeadFP32OutputTransformis also per call.rl_grpo_qwen3_0_6b_varlen_mxfp8relies on that by calling.transform()directly afterbuild_rl_model_configsapplied the fp32 head. Main had the same behavior, and the TODO there covers it.- Grouped quantization vs
TokenDispatcherTransform: the result now depends on list order. The recipes list quantization first and passpad_multiplein the dispatcher kwargs, so main's behavior is reproduced. The PR's "You may ask" answers this. - Mechanical parts checked: the 13 builders, renames in tests and docs, and recipe rewrites (
_enable_mxfp8droppingflavor, graph_trainer and muse_spark rebuilding from the base config). The 225-config identity check covers these.
Not verified: the silent-unfreeze path was traced by reading lora.py:137-160 and quantization.py, not by running it (no Python in this environment).
| # LoRA replaces each target projection config with an adapter and every | ||
| # other config with a frozen dynamic subclass. Quantization and the fp32 | ||
| # lm_head convert only stock projection configs, so they run first. | ||
| (QuantizationTransform, LoRATransform), |
There was a problem hiding this comment.
This ordering only applies inside a single apply_transforms / transform_model_config_ call. The claim that quantization "converts only stock projection configs" (here and in README.md:66-70) isn't enforced. On main the order was guaranteed by structure: converters always ran inside build_model_config, before any transform. With this PR, a later call can quantize a tree that LoRA already rewrote:
config = llama3_debugmodel_lora() # LoRA on wqkv/wo; w13/w2 become FrozenLinear.Config
config = apply_transforms(config, [MXFP8LinearTransform(fqns=["feed_forward"])])FrozenConfig subclasses Linear.Config and inherits _owner = Linear (lora.py:144). So _validate_quantizable_linear accepts it, and the new MXFP8Linear.Config loses the build() override that freezes the weights. The FFN base weights then train, and nothing raises. The grouped transforms behave the same way: frozen GroupedLinear.Config experts are rebuilt as trainable quantized configs (quantization.py:250, :366). LMHeadFP32OutputTransform already guards against this with type(linear_config) is not Linear.Config.
Smallest fix: reject non-stock config types in the quantization transforms. In _validate_quantizable_linear:
if type(config) is not owner.Config:
raise ValueError(
f"Cannot quantize {fqn!r}: {type(config).__qualname__} is not a stock "
"config (e.g. frozen by LoRATransform). Apply quantization before or "
"together with LoRATransform."
)Add the same check on config in both grouped loops. Only dynamic config subclasses fail it, so the in-repo recipe configs stay the same.
| # Async TP does not support quantized projections, and quantization does | ||
| # not support the async projection classes. | ||
| (AsyncTensorParallelTransform, QuantizationTransform), |
There was a problem hiding this comment.
Should consider: this conflict names the QuantizationTransform base, so it also bans AsyncTensorParallelTransform + MXFP8GroupedLinearTransform / NVFP4GroupedLinearTransform on their own. Async TP never touches those: it converts only projections whose owner is exactly ColumnParallelLinear or RowParallelLinear (async_tensor_parallel.py). Main allowed that combination. Either name the two dense transforms (MXFP8LinearTransform, NVFP4LinearTransform), or say in the PR that the wider ban is intended.
Also, the comment overstates the current behavior. Async TP doesn't reject quantized projections; it skips them, because their owner is a get_quantized_linear subclass. So with quantization in an earlier apply_transforms call and async TP in a later one, those projections still stay synchronous and nothing raises, as on main. If you want this covered, raising in AsyncTensorParallelTransform.transform on a quantized Column/Row owner handles both orders and both call patterns.
…only with dense quantization Relations order transforms only within one apply_transforms call. On main, converters always ran inside build_model_config, so quantization could never follow LoRA; now a later call could, and it rebuilt LoRA's frozen projections as trainable quantized configs. The quantization transforms now reject a config subclass (e.g. one LoRATransform froze), as LMHeadFP32OutputTransform does. Async TP converts only stock ColumnParallelLinear/RowParallelLinear owners, so the conflict names MXFP8LinearTransform and NVFP4LinearTransform; grouped quantization changes only routed experts and stays allowed, as on main.
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. 6995e45 fixes both code findings from the last review. Only the PR description item is left. This changes core config code, so a maintainer still needs to review it.
What changed since the last review. Quantization transforms now refuse to convert a projection whose config type is not its owner's stock Config. The async TP conflict now names only the two dense quantization transforms.
Example.
config = llama3_debugmodel_lora() # w13/w2 -> FrozenLinear.Config
apply_transforms(config, [MXFP8LinearTransform(fqns=["feed_forward"])])
# before 6995e45: w2 silently rebuilt as a trainable MXFP8Linear.Config
# now: ValueError "Cannot quantize ...: ... is not the stock Linear.Config
# (e.g. LoRATransform froze it)"Earlier findings
- Resolved: a later quantization call silently unfroze LoRA base weights.
_require_stock_config(quantization.py:43-57) now runs in_validate_quantizable_linearand in both grouped loops (:265,:367).ColumnParallelLinearandRowParallelLineareach define their ownConfig, so stock configs still pass.FrozenConfiginherits_owner = Linearbut is a different type, so it is rejected.test_quantization_rejects_a_projection_lora_frozecovers all 4 transforms. - Resolved: the async TP conflict was too broad.
relations.py:55-56now pairs it only withMXFP8LinearTransformandNVFP4LinearTransform. The comment now says async TP would silently leave quantized projections synchronous, which is accurate.
Must fix
- PR description: the template's "Summary (human-written)" section is still missing. Put the summary under that heading, written by you.
No new problems in 6995e45.
Not verified: unit tests were not run in this environment. The PR reports they pass.
| # TODO: Allow this pair once linear quantization and HiMidLoLinear can | ||
| # preserve each other's config and compute semantics. | ||
| (QuantizationTransform, LMHeadFP32OutputTransform), |
There was a problem hiding this comment.
I don't know if this breaks existing recipes or not, but we need to support it for RL with quantization. The two transforms should target different modules -- quantization shouldn't be applied on the lm_head.
The guard doesn't need to be in this relations.py file. It could be that
- we have to apply one of them first -- maybe quantization first, because in build_rl_model_configs you apply lm_head transform after base transforms.
- then in lm_head transform, raise error if the module is already quantized
There was a problem hiding this comment.
I see, we should ban the quantization + lm_head relation. let me change it
RL with quantization needs both transforms: they target different Linears (e.g. MXFP8LinearTransform(fqns=["layers."]) leaves lm_head to the fp32 transform). Replace their conflict relation with a precedence: quantization runs first in the same call, and LMHeadFP32OutputTransform raises on a quantized lm_head (its error now names quantization and points to the quantization transform's fqns). Quantization already rejects a HiMidLoLinear. rl_grpo_qwen3_0_6b_varlen_mxfp8 drops its TODO and applies MXFP8 through apply_transforms; its config is unchanged.
…_config #6164 deleted ModelConfigConverter, validate_converter_compatibility and the converters argument of every build_model_config. The Flash-Next stack (#6046-#6054) landed after it with CI from the older base, so qwen3_8_flash_next/flavors.py still imports them and fails at import time. Remove the import, the argument and its loop, as #6164 did for the other models; no Flash-Next caller passes converters.
…_config pytorch#6164 deleted ModelConfigConverter, validate_converter_compatibility and the converters argument of every build_model_config. The Flash-Next stack (pytorch#6046-pytorch#6054) landed after it with CI from the older base, so qwen3_8_flash_next/flavors.py still imports them and fails at import time. Remove the import, the argument and its loop, as pytorch#6164 did for the other models; no Flash-Next caller passes converters.
…onfig (#6316) Stacked PRs: * #6305 * #6308 * #6203 * #6202 * #6201 * __->__#6316 --- --- --- ### [qwen3_8_fn] Drop the removed ModelConfigConverter from build_model_config ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> #6164 deleted `ModelConfigConverter`, `validate_converter_compatibility` and the `converters` argument of every `build_model_config`, while the Flash-Next model (#6046-#6054) landed still using them. On main, importing `torchtitan.models.qwen3_8_flash_next` fails with `ImportError: cannot import name 'ModelConfigConverter'`, so every Flash-Next test errors at collection. This applies #6164's change to Flash-Next: remove the import, the `converters` argument and its conversion block from `build_model_config`, as #6164 did for the other models. Recipes apply converters as transforms with `apply_transforms`. No in-repo caller passes `converters` to Flash-Next. ```bash pytest -q tests/unit_tests/cpu/models/qwen3_8_flash_next ```
…_config (#6314) ## Summary (human-written) as titled. ## Why `main` fails to import Flash-Next. #6164 deleted `ModelConfigConverter`, `validate_converter_compatibility` and the `converters` argument of every `build_model_config`. The Flash-Next stack (#6046-#6054) merged about 2.5 hours later, but its CI had run against the older base, so `torchtitan/models/qwen3_8_flash_next/flavors.py` still imports the deleted names. **Example.** ``` $ python -c "import torchtitan.models.qwen3_8_flash_next" ImportError: cannot import name 'ModelConfigConverter' from 'torchtitan.config.transform' ``` On `main` (65e88e9) this breaks: - CPU Unit Test: the 4 Flash-Next CPU test modules fail to collect; - 1 GPU and Multi-GPU Unit Tests: the Flash-Next GPU test modules fail to collect; - lint: pyrefly `missing-module-attribute` at `qwen3_8_flash_next/flavors.py:19-21`. ## What changed - `qwen3_8_flash_next/flavors.py`: remove the import, the `converters` argument of `build_model_config` and its loop, as #6164 did for the other 13 models. No Flash-Next caller passes `converters`; recipes apply transforms with `apply_transforms`. ## Numerics None: the removed branch ran only when `converters` was passed, and no caller passed it. ## Testing - `pytest tests/unit_tests/cpu` (with `main`'s attn-gym pin): all Flash-Next tests pass. The 12 failures are in `test_loss`, `test_dist_moe`, `test_lora` and `qwen3_5`; the same 12 fail in this environment on `main` before the Flash-Next stack (31d93fe), so they come from the local environment, not this change. - Pyrefly reports no errors in `qwen3_8_flash_next/flavors.py`. ## Known issues / follow-ups - #6055 (6/n, pipeline parallelism) needs a rebase onto `main` with this change.
Conflicts, per-commit effect on ezpz, the three replays (pytorch#6164, pytorch#6325, pytorch#5881), the attn_gym venv upgrade for pytorch#6172, and the 21-arm smoke matrix on 15efc8b across Sunspot, Aurora and Sirius. Aurora 2B losses differ from earlier syncs; an attn_gym-hidden control on the same nodes reproduces the old values exactly.
TLDR
ModelConfigTransform:BatchInvariantFlexTransform,LMHeadFP32OutputTransform, andMXFP8LinearTransform,MXFP8GroupedLinearTransform,NVFP4LinearTransform,NVFP4GroupedLinearTransform(baseQuantizationTransform).ModelConfigConverter,validate_converter_compatibilityand theconvertersargument of all 13build_model_configs are deleted.apply_transforms, like the other transforms. All 225 recipe configs that build on CPU are identical to main, and 21 debug recipes covering every changed model family plus an RL run train with bitwise-identical loss and grad_norm (numbers below).Fixes #6087.
Why
build_model_config, so model builders importedtorchtitan.config.transform, against that package's dependency direction (its README: "Those packages must not import this package").validate_converter_compatibility; transforms are ordered and checked byTransformRelations. The implicit "converters first" rule is what made quantization and the fp32 lm_head safe with LoRA.What
config/transform/): eachX.Config's fields become fields of the transform dataclass, and its__post_init__checks stay in__post_init__. The torchao and SM100 checks move from__init__to the start oftransform(); before,build()ran them right beforeconvert(). The bodies are otherwise unchanged.relations.py), replacing the implicit order andvalidate_converter_compatibility:QuantizationTransformandLMHeadFP32OutputTransformrun beforeLoRATransform. LoRA turns every non-target config into a frozen subclass, which neither of them converts.QuantizationTransformruns beforeLMHeadFP32OutputTransform. On mainvalidate_converter_compatibilityrejected the pair, but RL with quantization needs both, and they target different Linears (e.g.MXFP8LinearTransform(fqns=["layers."])leaveslm_headto the fp32 transform).LMHeadFP32OutputTransformraises on a quantizedlm_head, and quantization raises on aHiMidLoLinear.rl_grpo_qwen3_0_6b_varlen_mxfp8drops its TODO about this pair and applies MXFP8 throughapply_transforms.MXFP8LinearTransformandNVFP4LinearTransformconflict withAsyncTensorParallelTransform(the TODO inrelations.py): async TP converts only stockColumnParallelLinear/RowParallelLinearowners and would silently leave quantized projections synchronous. Grouped quantization changes only routed experts, which async TP never converts, so it stays allowed, as on main.build_model_config, so quantization could never follow LoRA; now a laterapply_transformscall could. The quantization transforms therefore reject a config subclass (e.g. one LoRA froze) instead of rebuilding it as a trainable quantized config, asLMHeadFP32OutputTransformalready does.convertersis removed from everybuild_model_config;config/transform/README.mddrops the note about builders importing the package.converters=[...]becomes anapply_transformscall, merged into the recipe's existing call where there is one, with quantization listed first as before. A recipe that rebuilt the model only to pass converters now transforms its base config (configs verified identical).build_rl_model_configs(transforms=...)replaces theconverterskwarg it forwarded tobuild_model_config; itsfp32_lm_headdefault appendsLMHeadFP32OutputTransform.rl_dapo_qwen3_30b_a3b_math_8kpassedLMHeadFP32OutputConverteron top of that default, a no-op, so it is dropped.OVERRIDE.md, MXFP8, NVFP4 and Flux READMEs,BITWISE_PARITY.md,.claude/rules/direction.md(the migration is finished).Breaking changes
XConverter.Config(...)->XTransform(...), andbuild_model_config(..., converters=[...])->apply_transforms(config, [...])(ortransform_model_config_(model_config, [...])without a trainer config).validate_converter_compatibilityis gone;apply_transformsandtransform_model_config_check the relations.Verification
All comparisons are against main 49dbf7a.
torchtitan_recipesfunction with no required arguments, built on main and on this branch;reprof the whole config compared (worktree paths normalized). Quantization ran for real (torchao nightly on CPU, SM100 check patched);DistMoeTransformwas stubbed to record its input model.test_transforms.py::TestQuantizationAndLMHeadRelations: quantization and fp32 lm_head ordered before LoRA; quantization composes with the fp32 lm_head when they target different Linears, and a quantized lm_head is rejected; the async TP conflict.test_quantization.py::test_quantization_rejects_a_projection_lora_froze: LoRA in one call, then each of the 4 quantization transforms in a later callpytest tests/unit_tests/cpu;test_quantization.py(torchao nightly); RL CPU tests that load recipes (test_alphabet_sort.py,test_dapo_math.py,test_model_defaults.pyand 7 more)undefined symbol: c10::ParallelGuardin this env); 62 passed, as on main; 263 passed, 5 skippedLoss parity:
scripts/loss_compare.py --assert-equal --metrics loss,grad_norm, 20 steps, seed 42, deterministic. Loss and grad_norm are bitwise identical to main at every step for every recipe below.llama3_debugmodel,qwen3_debugmodel,qwen35_debugmodel_varlen_attn,qwen36_debugmodel_varlen_attn,qwen38_debugmodel_varlen_attn,kimi_k2_5_debugmodel,muse_glimmer_debugmodel,muse_spark_debugmodel(4 GPUs).llama3_debugmodel_mxfp8,llama3_debugmodel_nvfp4,llama3_debugmodel_first_85_pct_layers_nvfp4,qwen3_debugmodel_nvfp4,qwen3_debugmodel_first_85_pct_layers_nvfp4,deepseek_v3_debugmodel,deepseek_v3_debugmodel_mxfp8,deepseek_v3_debugmodel_dist_moe_mxfp8,deepseek_v4_debugmodel,gpt_oss_debugmodel,kimi_k3_debugmodel,graph_trainer_llama3_debugmodel_mxfp8,graph_trainer_deepseek_v3_debugmodel_mxfp8.rl_grpo_qwen3_0_6b_varlen_batch_invariant(seed 42, deterministic, trainer TP=4 + 1 generator TP=4, on-policy, 10 steps, TorchStore weight sync on both sides):loss/meanandtrainer/grad_norm/meanbitwise identical.kimi_k2_5_debugmodel,deepseek_v4_debugmodel,kimi_k3_debugmodeland both graph_trainer recipes.kimi_k3_debugmodeldiffered once from step 2 on GB300; main vs main and main vs this PR were then both identical.qwen35_debugmodel_varlen_attn: main's first (cold Triton cache) run gave a different step-2 loss than main's later runs; with a warm cache, main and this PR are identical.nvfp4_ffn_mxfp8_attn, muse_sparkdist_moe_mxfp8, and flux (no autoencoder asset here). Their configs are identical to main.llama3_8b_mxfp8,llama3_8b_first_85_pct_layers_nvfp4,qwen3_8b_first_85_pct_layers_nvfp4,deepseek_v3_16b_dist_moe_mxfp8,deepseek_v3_16b_nvfp4_ffn_mxfp8_attn,deepseek_v3_671b_dist_moe_mxfp8,deepseek_v3_671b_nvfp4_ffn_mxfp8_attn,flux_schnell_mxfp8,flux_dev_mxfp8.rl_grpo_qwen3_0_6b_varlen_mxfp8,rl_grpo_qwen3_0_6b_flex_batch_invariant(BatchInvariantFlexTransform) andrl_dapo_qwen3_30b_a3b_math_8k.Rechecked at 6995e45 (the review fix): all 237 recipe functions give the same config or the same error as main, so the stock-config check fires for no in-repo recipe; the loss parity runs above were at 150c127. Config identity details: 12 functions fail identically on both sides (missing
verifiers/sglang, unset env vars, the Hopper-only flex flash backend, and'TrainingConfig' object has no attribute 'max_norm'in 4 graph_trainer numerics recipes, also on main).rl_dapo_qwen3_30b_a3b_math_8k_mxfp8failed only on thedist_moestub; compared on its own, it is identical. The 2 remaining functions are the renamed helpers (*_mxfp8_linear_converter_config->*_mxfp8_linear_transform).You may ask
transformmethods unannotated, unlikeBatchInvariantFlexTransform.transform? Theirconvertmethods were unannotated. Annotatingmodel: Module.Configmakes pyrefly flag thetraverseresults (parent/attrunions,_owner | None,local_compileonModule.Config), and narrowing them would change the bodies. This PR keeps the bodies as they were.DistMoeTransformorTokenDispatcherTransform? Every recipe lists quantization first, the order converters ran in, so nothing changes; Dist-MoE already rejects non-stock grouped projections when it runs.