Repository navigation
fix(ernie4_5_vl_moe): expand routed text/vision expert indices - #3754
Conversation
`Ernie4_5_VLMoeQModel` declared no `dynamic_expert_index`, so
`simple_layer_modules()` returned the literal `{expert_index}` placeholder for
both expert families. Quantization matches concrete module names, so
`create_named_modules` could never hit those entries; with
`layer_modules_strict = False` each one was only recorded as a miss and both
the text and vision routed experts stayed in the source dtype.
Set `dynamic_expert_index = "moe_num_experts"` on the definition. The field is
owned by the nested `text_config`, not the multimodal wrapper, so resolve it
through `BaseQModel._expert_count_config()`, which follows `text_config`, then
`thinker_config.text_config`, then `ffn_config`, then the top-level config.
`ffn_config` covers DBRX, which had the same class of defect: no
`dynamic_expert_index`, and undeclared `norm_1`, `norm_2` and router weights.
Both ERNIE families are also fully declared now: the routers and their
`moe_statics` score-correction bias carry `:!`, and the DBRX norms and router
layer do too, so every checkpoint-owned weight has a declared owner with the
right tag.
Measured on the default ERNIE config (64 experts): before, 16 specs with 6
placeholders; after, 394 specs with 0 placeholders, 192 per expert family.
Tests:
- registry-wide placeholder-expansion guard over every `MODEL_MAP` definition
- real-model Defuser layout, layer-spec expansion, weight-ownership and plan
contract for ERNIE text/vision experts
- tiny end-to-end load/quantize asserting each expert projection becomes a
quantized linear
- DBRX nested `ffn_config` cardinality and explicit non-quantized tags
Docs: `docs/module-plan-guide.md` records the nested-config resolution rule and
the silent-miss consequence.
The new `_expert_count_config()` returned `ffn_config` whenever the attribute existed, before falling back to the top-level config. For a config that carries an unrelated `ffn_config` sub-config but keeps its routed-expert cardinality at the top level, that branch selected an object without the field and `get_num_experts()` raised `AttributeError` instead of reading the top-level value. Existing definitions were unaffected only because no HF-resolvable model type in `MODEL_MAP` currently exposes `ffn_config` other than DBRX; a remote-code config would hit it. Resolve `ffn_config` only when it actually declares the requested field, so the added branch cannot shadow a resolvable top-level cardinality. Document the narrowed condition and add a regression test covering the top-level-only, `ffn_config`-owned, and both-declared cases. Tests: 1023 passed, 136 skipped across the module-plan suites; ruff check clean.
ZX-ModelCloud
left a comment
There was a problem hiding this comment.
Review: verified, plus one resolution bug fixed on the branch
I reproduced the defect on c9704b72c and validated the fix on a2076de3c, then
pushed one follow-up commit (cf4da26fd) for a resolution regression the change
introduced. Details below.
Claims I reproduced independently
| Claim | Result |
|---|---|
| ERNIE default config: 16 specs / 6 placeholders → 394 specs / 0 placeholders, 192 per family | confirmed exactly |
moe_num_experts absent on the multimodal wrapper, present on text_config |
confirmed |
DBRX: 3 placeholder leaks and undeclared norm_1 / norm_2 / router.layer on main |
confirmed exactly |
End-to-end ERNIE expert coverage fails on main |
confirmed: mlp.text_moe.experts.0.gate_proj stays HookedLinear; passes on the branch |
A surviving placeholder is a silent miss under layer_modules_strict = False |
confirmed at module_looper.py:2066 |
"0 regressions" walking every dynamic_expert_index definition |
confirmed. I compared old vs. new resolution for all 70 such definitions against real HF configs; only dbrx_converted gains a resolvable field |
The new tests are real guards, not snapshots. Deleting dynamic_expert_index from
the definition fails 7 tests, including the registry-wide one. The suite the PR
lists reports 1020 passed, 136 skipped here (the PR says 1022; the two extra are
test_ernie_expert_projections.py, which I ran separately and also passes). The
test_fusable_models.py cohere_compass/flint failures are identical on main
(22/22 same node IDs), so they are pre-existing.
I also audited the real converted DBRX checkpoint (dbrx_converted,
ffn_config.moe_num_experts = 16): 52 concrete specs, 0 placeholders, 0 missing
specs, and 0 undeclared state_dict() owners. The experts.mlp.#.{w1,v1,w2} and
separate q/k/v layout matches the definition. The PR only tests DBRX at config
level, so this closes that gap; it would be worth committing as a test if a
checkpoint is available in CI.
Bug introduced by this change (fixed in cf4da26fd)
_expert_count_config() returned ffn_config whenever the attribute existed,
before falling back to the top-level config. For any config that carries an
unrelated ffn_config sub-config but keeps its expert count at the top level, the
new branch selected an object without the field and get_num_experts() raised
AttributeError instead of reading the top-level value:
qwen3_moe with SimpleNamespace(ffn_config=..., num_experts=8)
before this PR: 8
as submitted: AttributeError: no attribute 'num_experts'
It is latent today only because dbrx is the sole HF-resolvable MODEL_MAP type
exposing ffn_config; any remote-code config would hit it. The fix selects
ffn_config only when it actually declares the requested field, and adds a
regression test for the top-level-only, ffn_config-owned, and both-declared
cases. The PR note that "the text_config / thinker_config / top-level
precedence is byte-for-byte preserved" was therefore not accurate as written; the
doc and test now state the narrowed condition.
Remaining review points (not blocking)
- Flow documentation. The PR argues no diagram is needed because this only
sets an attribute and adds a fallback. The second half is a change to a
resolution order inside a new function (_expert_count_config) and it converts
a silent no-op into quantization work, which the repository guidance lists as
diagram-qualifying. A compact before/after table plus oneflowchartin the
existingdocs/module-plan-guide.mdsection would satisfy it without a new
page. Your call, but I would not waive it on the current justification. layer_modules_strictstaysFalse. With the experts now expanded, the
remaining per-layer misses are only the dense/sparse branch difference
(mlp.gate_projetc. on sparse layers, the 384 expert specs on dense layers),
which is expected. Flipping to strict still fails the end-to-end test, so
leaving it is correct — worth one sentence in the PR so a future reader does
not assume it was overlooked.moe_staticsscope. The PR description frames the ERNIE change as
dynamic_expert_indexplus router tags; themoe_statics:!addition is a
third, independently necessary fix (verified:mlp.vision_moe.gate.moe_statics
is an undeclared checkpoint owner onmain). Worth listing explicitly.
No GPU/accelerator-specific results are included here by request; device coverage
was checked separately.
…s rationale Add an expert-cardinality resolution reference page under docs/ (Mermaid flow plus before/after evidence table) and link it from README. Annotate the ERNIE declaration in place: why layer_modules_strict stays False for a tree that serves both dense and sparse layers, and why moe_statics needs its own :! entry instead of riding on gate:!.
|
All three non-blocking points are addressed in
Re-validated after the edits: |
`Ernie4_5_VLMoeQModel` now declares `dynamic_expert_index =
"moe_num_experts"`, but the *published* ERNIE 4.5 VL repositories
(`baidu/ERNIE-4.5-VL-28B-A3B`, `...-28B-A3B-PT`, `...-424B-A47B-PT`) do not
use the converted `text_config` layout this branch measured. They ship a flat
remote-code config with `model_type = "ernie4_5_moe_vl"` (mapped to the same
definition) and a per-modality `moe_num_experts = [64, 64]`.
`build_moe_modules_if_need()` fed that list straight to `range()`:
TypeError: 'list' object cannot be interpreted as an integer
gptqmodel/models/base.py:1228 for index in range(expert_count(n))
On `main` the same config returned 16 specs with 6 placeholders and only
recorded a miss. The branch therefore turned a silent, non-fatal defect into a
hard quantization failure for the checkpoint users actually download.
`_coerce_expert_count()` accepts a non-negative scalar and returns None for
list/tuple/dict/set/bool, and both expansion paths now keep the literal
placeholder, warn once per definition, and let `create_named_modules()` record
the miss. A *missing* field still raises `AttributeError`, so a real
definition/config mismatch stays loud.
`ModuleLooper` skips a routing override when the count is unresolved instead
of calling `routing_override(None)`.
Do not sum the list: the remote-code model fuses both families under
`mlp.experts` and `mlp.mlp_text` splits them by modality, so a single summed
cardinality would expand the wrong number of names for either family. The
converted layout that Defuser produces (`text_moe`/`vision_moe`, 64 each) is
unaffected because its `text_config.moe_num_experts` is the scalar 64.
Tests: new registry cases for both aliases (non-scalar → placeholder kept, no
exception; scalar → expands) and for a missing field still raising.
1026 passed, 136 skipped across the module-plan suites; ruff clean.
|
Review notes: I checked cardinality lookup and concrete expert expansion against the real Transformers + Defuser ERNIE layout, DBRX's Scope note: the published flat remote-code ERNIE configs with |
Qubitium
left a comment
There was a problem hiding this comment.
Reviewed the converted ERNIE text/vision expert expansion and DBRX cardinality/owner fixes. The integrated module-tree suites pass (435 passed, 137 skipped), including an end-to-end tiny ERNIE quantization, and Ruff/diff checks pass. The PR discussion records the distinct published flat remote-code config limitation.
TL;DR
Ernie4_5_VLMoeQModeldeclared nodynamic_expert_index, sosimple_layer_modules()returned the literal{expert_index}placeholder for both routed-expert families. Quantization matches concrete module names, socreate_named_modules()could never hit those six entries; withlayer_modules_strict = Falseeach one was only recorded as a miss and both the text and the vision experts stayed in the source dtype.The fix declares the expert cardinality, resolves it from the config object that actually owns it, and adds registry-wide plus real-model regression coverage. Declaring the field also exposes an independent defect on the published checkpoints — a per-modality
moe_num_experts = [64, 64]list that previously fed a barerange()— so the same change makes a non-scalar count resolve to "unresolved" instead of raising.Measured on the converted ERNIE 4.5 VL MoE config (64 experts): before 16 specs with 6 placeholders, after 394 specs with 0 placeholders (192 per expert family).
dbrx_convertedhad the same class of defect and is fixed in the same change.1. The problem
1a. Placeholder never expanded
#in a module tree is a placeholder, not a path.build_moe_modules_if_need()only expands it when the definition declaresdynamic_expert_index(gptqmodel/models/base.py:1146). Onmain(c9704b72c)gptqmodel/models/definitions/ernie4_5_vl_moe.py:24-65setslayer_modules_strict = Falsebut never declares that attribute, so the placeholder survives intocreate_named_modules()(gptqmodel/looper/module_looper.py:2056-2067):Because the definition is non-strict, the miss is recorded rather than raised: quantization "succeeds" while every text and vision routed expert remains unquantized.
1b. The field is not on the top-level config
For the converted snapshots this work was measured on,
moe_num_expertslives on the nestedtext_config; the multimodal wrapper does not expose it. The legacy resolver only followedtext_config/thinker_config.text_config, so DBRX — which keepsmoe_num_expertsunderffn_config— could not declare the field at all:moe_num_expertsernie4_5_vl_moe,text_configpresent)text_configdbrxffn_configernie4_5_moe_vl, flat)[64, 64]1c. The published checkpoints carry a per-modality list
baidu/ERNIE-4.5-VL-28B-A3B,...-28B-A3B-PTand...-424B-A47B-PTship a flat remote-code config:model_type = "ernie4_5_moe_vl"(the backward-compatibility alias mapped to this same definition),auto_mappresent, notext_config, andmoe_num_experts = [64, 64].has_native_transformers_causallm_support()is false for those repos, so the remote-code load path is reachable.Declaring
dynamic_expert_indexon its own turns that into a hard failure:On
mainthe same config produced 16 specs with 6 placeholders and only recorded a miss. An attribute-only fix therefore converts a silent, non-fatal defect into a crash for the checkpoints users actually download.Summing the list is not a valid fix: the remote-code model fuses both families under
mlp.expertsand splits them by modality throughmlp_text, while the converted layout exposestext_moe/vision_moewith 64 each. One summed cardinality expands the wrong number of names for either family.1d. Undeclared checkpoint-owned weights
dbrx_convertedalso leftnorm_attn_norm.norm_1,norm_attn_norm.norm_2andffn.router.layerundeclared, so a real checkpoint audit reported checkpoint weights with no owning plan spec.2. The new flow
flowchart TD T["definition.module_tree contains #"] --> G{"dynamic_expert_index declared?"} G -->|"no"| RAW["simple_layer_modules returns the literal<br/>EXPERT_INDEX_PLACEHOLDER path"] G -->|"yes"| R["get_num_experts(config)"] R --> C["_expert_count_config(config, field)"] C --> T1{"config.text_config?"} T1 -->|"yes"| USE1["text_config"] T1 -->|"no"| T2{"config.thinker_config?"} T2 -->|"yes"| USE2["thinker_config.text_config"] T2 -->|"no"| T3{"ffn_config declares field?"} T3 -->|"yes"| USE3["ffn_config"] T3 -->|"no"| USE4["top-level config"] USE1 --> N["expert count"] USE2 --> N USE3 --> N USE4 --> N N --> S{"_coerce_expert_count:<br/>scalar value?"} S -->|"yes"| EXP["expand # to 0..N-1"] S -->|"no, e.g. [64, 64]"| NONSCALAR["returns None"] NONSCALAR --> KEEP["build_moe_modules_if_need keeps<br/>literal placeholder, warns once"] KEEP --> MISS RAW --> MISS["create_named_modules: record_miss<br/>no exception when strict is False"] EXP --> HIT["concrete names resolve"] style RAW fill:#ffa39e,stroke:#a8071a style MISS fill:#ffa39e,stroke:#a8071a style NONSCALAR fill:#ffe7ba,stroke:#ad6800 style KEEP fill:#ffe7ba,stroke:#ad6800 style HIT fill:#d9f7be,stroke:#237804A missing field is not on this diagram on purpose:
getattr(config, field)keeps raisingAttributeError, because that means the definition and the config disagree rather than that the value is unexpandable.2a. Nested-config resolution
gptqmodel/models/base.py:Both
get_num_experts()andget_num_experts_for_module()use it, so the precedence stays identical for the existing definitions and only the previously-unresolvableffn_configcase changes.The
ffn_configbranch is guarded by the field lookup: an unrelated architecture that happens to carry anffn_configobject without the expert-count field would otherwise select it and newly raiseAttributeError, shadowing a cardinality kept on the top-level config.test_ffn_config_does_not_shadow_a_top_level_expert_countpins that behaviour.I walked every
MODEL_MAPdefinition that declaresdynamic_expert_indexand compared old against new resolution: 0 regressions (onlydbrx_convertedgains a resolvable field).2b. Non-scalar cardinality is unresolved, not a crash
_coerce_expert_count()returns a non-negative int for a scalar value andNonefor a list/tuple/dict/set/bool.build_moe_modules_if_need()keeps the literal placeholder for an unresolved count, warns once per definition, and letscreate_named_modules()record the miss.ModuleLooperskips the routing override when the count is unresolved instead of callingrouting_override(None).2c. Definitions
ernie4_5_vl_moe.pydynamic_expert_index = "moe_num_experts";moe_statics:!on both routers (independent fix, see below)dbrx_converted.pydynamic_expert_index = "moe_num_experts"; explicitnorm_1:!,norm_2:!,router.layer:!The routers and their score-correction bias are checkpoint-owned but never quantized, so they carry an explicit
:!tag rather than relying on a default.moe_statics:!is an independent fix, not a consequence of the placeholder bug.gate.moe_statics.e_score_correction_biasis a separate checkpoint-owned tensor under the router path; declaring onlygate:!leaves that bias with no owning spec, so it would surface as an undeclared owner in a checkpoint audit even after the expert indices expand correctly. It is included here because it is the same declaration site and the same "checkpoint weight, no plan owner" defect class.3. Before / after and the failure contract
main)get_num_expertsandget_num_experts_for_module;text_config,thinker_config, else top level_expert_count_config(); adds a guardedffn_configstepbase.py:1236-1244,:1273-1277→base.py:_expert_count_configdynamic_expert_index"moe_num_experts"ernie4_5_vl_moe.pydeclarationbase.py:build_moe_modules_if_need64)[64, 64])TypeErrorinrange()base.py:1228→_coerce_expert_countAttributeErrorAttributeErrordynamic_expert_index"moe_num_experts"dbrx_converted.pynorm_1,norm_2,router.layer:!eachdbrx_converted.pycreate_named_modulesand is only recordedmodule_looper.py:2063-2066Situation → outcome for the cardinality value:
64)[64, 64])TypeError, quantization abortsNone→ placeholder kept, warned once, recorded as missAttributeErrorAttributeError4. Validation
The real Transformers config and the real Defuser conversion are used throughout; no mocked dispatch.
New tests:
test_definition_declares_the_text_config_expert_counttext_config, not the wrappertest_defuser_layout_splits_the_fused_checkpoint_expertstext_moe/vision_moeexpert liststest_layer_modules_expand_every_experttest_every_quantizable_spec_resolves_on_the_real_layerstest_every_checkpoint_weight_owner_is_declared_with_the_right_tagstate_dict()owners resolve throughModulePlan.find(); non-quantized owners are explicitly taggedtest_routers_and_score_correction_bias_are_not_quantizedgate/moe_staticsexcluded, every expert projection quantizedtest_module_plan_exposes_both_expert_containerstest_looper_records_no_miss_for_expanded_expert_specstest_ffn_config_does_not_shadow_a_top_level_expert_countffn_configwithout the field does not shadow a top-level counttest_quantized_model_covers_both_expert_familiesload→quantize; every text/vision expert projection is aTorchLineartest_non_scalar_expert_count_fails_closed_instead_of_raising(both aliases)None, keeps every placeholder, does not raise; scalar count still expandstest_missing_expert_field_still_raisesAttributeErrorRegistry-wide guards added to
test_registered_module_plans.py:test_every_expert_placeholder_expands_to_concrete_names— every definition whose tree declares the placeholder must also declaredynamic_expert_index, and expansion must leave no placeholder (covers all nesting precedences generically).test_dbrx_converted_nested_ffn_config_expert_count— DBRX cardinality plus explicit non-quantized tags.test_moe_expert_coverage.py: thePLACEHOLDER_EXPERT_MODELSxfail forernie4_5_vl_moeis removed; the model moves intoFIXED_MODELSso a regression fails loudly instead of being tolerated.ruff checkis clean on all changed files.Pre-existing, unrelated
test_flash_model_tree_consumption.py::...[glm5_next]fails identically on cleanmain(owner count 41 ≠ 37).test_fusable_models.pycohere_compass / flint fail on cleanmain(missingtransformers.models.flint).test_subset.py::test_stage_subset_early_stop_and_callbacksandtest_qwen3_5_moe_subset_early_stop_follows_module_tree_execution_orderfail identically on cleanmain(_DummyQwen3_5Modelhas noprepare_layer_replay_keep_mask).Scope limit
A full 28B checkpoint quantization was not run. The evidence here is the real meta model through the real Defuser conversion, a real-checkpoint key audit (all 28 layers,
text_config.moe_num_experts=64, keysmodel.layers.N.mlp.experts.{0..127}split 0–63 text / 64–127 vision by the HF conversion mapping), and a tiny local end-to-end quantization. This local reproduction is not a substitute for a full-model quantization result. The published flat-config layout is covered at the resolution/expansion level (the non-scalar tests), not by instantiating its remote code.5. Flow documentation
Expert cardinality is a resolution decision, so it is documented as one:
docs/model-tree-resolution.mdgains an Expert cardinality resolution page(
### Expert cardinality resolution) containing the same Mermaid flow drawn fromthe shipped code, the before/after evidence table with
file:linereferences,and the explicitly marked failure path.
README.mdlinks that page directly.The page also records the non-scalar contract:
_coerce_expert_count()returnsNone,build_moe_modules_if_need()keeps the placeholder and warns once, andthe miss is recorded downstream. Follow-up changes to the same flow update the
same page.
6. Reviewer notes
ffn_configbranch is the only behavioural addition to the resolution chain; thetext_config/thinker_config/ top-level precedence is byte-for-byte preserved. The branch is field-guarded (see 2a), so it cannot shadow a top-level count.layer_modules_strictstaysFalseonErnie4_5_VLMoeQModel, now with an in-code rationale: one tree serves both dense and sparse layers, so every decoder layer legitimately misses the other branch's specs (a dense layer hasmlp.gate_proj/up_proj/down_projbut no experts; a sparse layer has both MoE families and no dense MLP). Strictness would fail on every layer for reasons unrelated to expert coverage; the expanded-expert invariants are asserted bytest_layer_modules_expand_every_expertandtest_looper_records_no_miss_for_expanded_expert_specsinstead.dbrx_converted) layout that this definition loads via remote code:ffn.experts.mlp.{i}.w1/v1/w2,norm_attn_norm.norm_1/norm_2,ffn.router.layer. Defuser'sdbrxentry does not rewrite that layout, so no second mapping is needed here.deepseek_vl_v2overridesget_num_experts()forlanguage_configand is unaffected.MODEL_MAP.