Skip to content

Commit d6d45b7

Browse files
titaiwangmsCopilot
andauthored
Add experimental opset 29 function fallbacks for the MoE family (#814)
## Summary Add **experimental, default-off opset-29 function fallbacks** for native `com.microsoft::MoE` and raw INT4 `com.microsoft::QMoE`. Use the existing **function factory → registry → EP-controlled public `InlinePass`** mechanism. `moe(config)` and `qmoe(config)` return real, configuration-specialized `ir.Function` bodies. No separate lowering pass, replacement emitter, `_opset29.py` auditor, or additional framework remains. ```python from mobius import build_from_module from mobius._flags import override_flags with override_flags(experimental_opset29=True): package = build_from_module(module, config, execution_provider="onnx-standard") ``` `MOBIUS_EXPERIMENTAL_OPSET29=1` also enables the flag before import. | Build path | Behavior | |---|---| | Flag off | Existing opset-24/default behavior, except the QNN capability correction below | | Flag on, native-capable EP | Existing opset-24 native calls; no fallback ABI restrictions | | Flag on, fallback EP | New graph/functions constructed at 29; supported native calls registered and inlined | | Existing opset-24 graph requesting the new fallback | Explicit rebuild error, not import relabeling/version conversion | The global `OPSET_VERSION` remains 24. Generic dense `MoELayer` implementations, arbitrary routing gates, and Qwen4 routing algebra are unchanged. **Gemma4's model source is restored, not extended:** `gemma4.py` is byte-identical to PR base `858ead` and the reviewed main snapshot `e475e4871b0430f58654bc25b13fd17806b2f9c5`. Non-native EPs retain its dense Einsum path at both opset 24 and 29. Existing native/quantized branch implementations are unchanged. This PR does not add direct GroupedMatMul Gemma dispatch. **QNN is an intentional flag-off exception:** correcting its profile to `supports_fused_moe=False` changes capability-based model dispatch even when `experimental_opset29=False`. Qwen4 selects its existing `_standard_dispatch`; eligible unquantized Gemma4 configurations that previously selected native MoE select the existing dense path instead. QNN still builds at opset 24 with the flag off, without registering these MoE/QMoE fallback bodies. This fixes an incorrect kernel capability, not a new model dispatch implementation, and does not qualify QNN device execution of opset 29 or quantized Gemma4. ## Supported semantics - **MoE:** row-major expert weights, FLOAT/FLOAT16, optional biases, ReLU/tanh-GELU/SiLU/identity/interleaved SwiGLU, full-expert FLOAT softmax before TopK, higher-expert-ID probability ties, selected normalization, positive-route masking, CPU-reference HALF rounding, FLOAT weighted reduction. - **Raw INT4 QMoE:** low-nibble-first UINT8 weights, blocked scales, optional packed asymmetric zero points (**omission means 8**), `weights_prepacked=0`, interleaved SwiGLU, logit-first CPU routing, input-14 router weights, `<=1e-8` route suppression, and FLOAT dequantization/GEMMs before any final HALF cast. - Rank-2/rank-3 hidden inputs, dynamic/empty tokens, original packed initializer names, optional input positions, and compatible output annotations/docs/metadata are preserved. CPU source supplies the **semantic reference**, not a CPU-only execution restriction or an all-provider equivalence claim. Unsupported ABIs fail explicitly. BFLOAT16, FP4/MXFP4, prepacked weights, arbitrary gates, CUDA-specific routing, and fused-kernel performance are not qualified. Registration validates every target, containing-root imports, ownership, and collisions before body construction/mutation. Binary32-canonical specialization identities survive save/load/re-registration. Caller-owned functions remain unmodified. Public inliner preconditions remain authoritative; distinct alias-return boundaries prevent clobbering input/upstream metadata. ## Copilot review 5880527221: four confirmed issues repaired | Issue | Repair and regression evidence | |---|---| | QNN incorrectly inherits fused MoE capability | Set `supports_fused_moe=False`. Test flag-off 24 / flag-on 29 construction and actual optimizer registration/public inlining of raw INT4 QMoE. **No QNN runtime qualification is implied.** | | Empty-key-only core-opset lookups reject valid aliases | Use one read-only resolver for model roots, containing functions, source/destination specializations, and ordinary factories. Accept sole `ai.onnx` and matching dual aliases; reject conflicts atomically without normalizing imports. Preserve flag-first validation and public inliner mismatch checks. | | Added Gemma branch changes tied TopK selection | Remove the added integration instead of reversing model tensors. Original lower-ID dense TopK remains; add flag-off/on, preinitialized/scale-only top-1 numerical cases. | | Folding live expert scale into W2 overflows early | Restore original contribution-side scaling and dense dispatch. Add the same matrix with W2=`2e38`, live scale=`2`, and intermediate approximately `0.1`; require finite output approximately `4e37`. | Lead independently executed the **old e217b50 graphs**, not merely structural assertions: tied inputs changed `0.43863517` to `-3.72839904` with the flag; the overflow example changed finite `3.99999972e37` to infinity. Both were reproduced for preinitialized weights and scale-only updates. The repaired graph's numerical regressions pass against independent references. No tolerance weakening, weight reversal, or compensating routing transform. The original proposed Gemma FLOAT scale-folding repair is superseded by this restoration; it is not retained or claimed as a fix. ## Copilot review 5900254968: documentation and coverage follow-up | Issue | Repair | |---|---| | QNN flag-off dispatch exception was undocumented | Both lowering guides and this description now explicitly distinguish the QNN profile correction from the default-off opset-29 feature. Existing Qwen4/Gemma branches are selected differently on QNN even with the flag off; no new model implementation is added. | | Multi-layer post-build quantized-weight binding was untested | Add two consecutive shared raw-INT4 `MoELayer`s through `build_from_module(..., task="feature-extraction", execution_provider="onnx-standard")`, with every parameter initially unbound. Apply original packed checkpoint names only to the returned package, assert every binding is consumed, and compare a test-only expanded copy against independent NumPy dequantization/routing over two batches and three tokens. Production imports remain 29. | | Flag-off test used a native-capable profile | Use QNN, assert its capability is false, and check unchanged native inputs/attributes plus absence of fallback functions. A gate-only in-memory mutation produces two expected failures, demonstrating that the corrected regression detects removal of the flag guard. | This follow-up changes only two existing test files and the two lowering guides; no production dispatch, optimizer, or lowering implementation changes. The released-schema environment skips the new standard-pipeline case because its final public validator needs the official GroupedMatMul-29 schema. A QNN-only diagnostic is not treated as acceptance for the requested `onnx-standard` path; that path is validated with the exact schema pin. ### November 14 focused validation Command: `python -m pytest src/mobius/functions/moe_registration_test.py src/mobius/functions/qmoe_test.py -m opset29 -q -rs`. | Check | Result | |---|---| | Released ONNX 1.19, current IR/ONNXScript | **394 passed, 7 skipped**; includes the schema-gated new export case | | Exact pinned ONNX source, current IR/ONNXScript, integrated root checkout | **397 passed, 4 skipped**; the real standard-export multi-layer case executes and passes | | Flag-guard-only mutation | **2 expected failures** with the corrected fallback-profile test; mutation restored | | Ruff lint/format and complete four-file diff check | Passed | The four pinned skips are existing direct opset-29 runtime probes, unsupported by ORT 1.31.1. The multi-layer fixture found no production metadata or binding bug: it verifies existing behavior that previously lacked end-to-end coverage. Lead reviewed the complete four-file follow-up; this is not a new unified review of the cumulative 46-file PR. ## Justin's eleven review comments Implementation: `d9c4acc4848e4dfbeb66d5071dd0fa9e9f1b1062`. Comment-only readability follow-up: `982a05412c3361ed58aa8426827bf28e2a1fd511`. Cold-collection dependency fix: `e217b5093b4dbd9584cc0c25f89f16cadc544c11`. | Request | Change | |---|---| | Select CI tests by marker | Register `opset29`; both phases use `pytest src/mobius tests/ep_optimization_test.py -m opset29`. At that revision, all 832 previous cases retained and 40 added. Collection dependencies `httpx`/`gguf`/`jsonschema` are explicit. | | Remove redundant docs section | Remove QMoE's Runtime/validation section and repair the inbound MoE link. | | Bound inlining | At most initial function count + 1 rounds, with leaf-retirement progress checks and explicit failure. Preserve public validation and the existing unused-leaf clean exit. | | Avoid installed-schema dependence | Remove the redundant GroupedMatMul availability gate. Public construction, registration, and inlining work on actual ONNX 1.19; checking/export auditing remains schema-dependent. | | Use SwiGLU | Standard SwiGLU-28 in both bodies, retaining clipping, alpha/beta, and HALF boundaries. | | Use Swish | Standard Swish-24 for MoE SiLU. | | Expand variable names | Spell out QMoE internals without changing the native 15-input positional ABI. | | TODO for unpack | Add TODO; no current standard raw nibble-unpack op. BitCast requires equal widths; DequantizePacked's GGUF formats do not match raw QMoE. | | Is zero-point construction redundant? | Retain explicit default 8: omitted ONNX DQ zeros instead mean 0. Numerical tests compare omission with explicit 8 and distinguish explicit 3. | | Simplify routing/pattern matching | Remove the redundant routing Where. Retain safe zero-total normalization and the final contribution Where, which suppresses inactive expert NaNs. No fusion/performance promise. | | Use Slice | Negative-step expert reversal and stride-2 gate/up slicing replace index lists in both bodies. Comments explain endpoints and interleaving. | Operator versions were compared with the official ONNX catalog at `94d0e6056931a8c1dad84104c2e567e0011d04f2` and the pinned schema revision below; the relevant versions agree. ### Earlier review and public IR repairs Retain binary32 identity roundtrips, alias-output metadata isolation, direct MoE activation validation, direct QMoE configuration/block validation, and snapshotted-opset dispatch. Gemma HALF rounding and remaining live scales are protected by retaining its original dense implementation, not by adding new native-call integration. Earlier code-quality suggestions remain addressed. Use public `Function.clone`, `Graph.append`, `Function.outputs`, `Shape.copy`, graph traversal, `InlinePass.requires`/execution, `ir.convenience.extract`, `ir.convenience.replace_nodes_and_values`, and `ir.save`/`ir.load`. No new private graph-state mutation, explicit protobuf operation, production activation expansion, or production opset relabeling was added. ## Dependencies and runtime limits **Construction/registration does not require the installed opset-29 schemas.** Normal export validation, ONNX checking, and schema inference still audit real schemas; removing the registration gate does not bypass them. The experimental schema environment builds official ONNX revision `82721c0908fa965dd84e674c006147791313f3e1` (reporting 1.24), with IR 1.1.0 / onnxscript 0.7.2. ONNX 1.19 is the released-schema compatibility environment. Default dependency minimums remain unchanged. IR 1.0.0 cannot parse the pinned source build's newer `FLOAT6E2M3` enum, also reproduced on the unchanged earlier parent with ordinary opset-29 MatMulNBits construction. Minimum API availability does not imply the minimum packages can parse every experimental schema. The actual ONNX 1.19 + minimum IR 1.0.0 / onnxscript 0.7.1 combination is tested below. ORT 1.31.1 does **not** execute these opset-29 graphs directly. Generic MoE/QMoE numerical tests expand GroupedMatMul and SwiGLU on a **test-only copy** for older kernels, using Swish-24 plus Mul for SwiGLU. Production retains standard operators and original imports. Restored dense Gemma regressions use ReferenceEvaluator at their original 24/29 imports. Native HALF MoE tests have explicit capability skips on the FLOAT-only CPU registration; independent rounded-HALF coverage stays active. ## Prior full-cohort validation at 1a45c28 Broad command: `python -m pytest src/mobius tests/ep_optimization_test.py -m opset29 -q -rs`. | Check | Result | |---|---| | Final repair, actual ONNX 1.19 + IR 1.1.0 / onnxscript 0.7.2 | **893 passed, 23 skipped, 9995 deselected** | | Same repair, actual ONNX 1.19 + minimum IR 1.0.0 / onnxscript 0.7.1 | **893 passed, 23 skipped, 9995 deselected** | | Same repair, exact pinned ONNX schema source + IR 1.1.0 / onnxscript 0.7.2 | **905 passed, 11 skipped, 9995 deselected** | | Marker coverage | **916 selected:** 865 unchanged IDs, 7 explicitly renamed Gemma cases for restored dispatch, 44 new cases; no prior parameter case missing | | Existing targeted Gemma MoE/expert/preprocessing/precision suite | **68 passed** | | Fail-before regressions, developer | Gemma **5 failed / 9 passed**; QNN/aliases **21 failed / 14 passed** | | Independent old-head numerical reproduction, lead | Both actual wrong-expert and finite-to-infinity failures reproduced | | Ruff lint/format on all five changed Python files; diff check | Passed | | Mypy on the three changed production sources versus exact e217b50 baseline | **65 pre-existing Gemma errors, zero added/removed diagnostics**, exact message/column/unchanged-line comparison; resolver and provider clean | The 11 pinned skips are five unavailable native MoE HALF kernels, four unsupported direct opset-29 runtime cases, and two optional OpenVINO cases. Released-schema runs additionally skip schema-dependent checks, not the new dense Gemma export test. Local results are not overall hosted-CI success. ## Hosted CI diagnosis At e217b50, the dedicated experimental job **passed both stages**: released ONNX **848 passed / 24 skipped**, pinned schemas **861 passed / 11 skipped**. The previously pending pinned stage completed. The three failures in run `43282577546` (Integration fast, L4, L5) occurred **before tests**, while installing ORT GPU from external Azure feed/blob endpoints: read timeouts/connection resets, not model assertions. Those installation commands are unchanged versus exact PR base `858ead`. On that exact base, Integration fast **passed** and L4/L5 were **cancelled**; these are **not claimed to be matching base failures**. No unrelated workflow retry/tolerance/skip change is included. The completed run `43300507986` at `1a45c280` passed the experimental stages (**893 passed / 23 skipped** released; **905 passed / 11 skipped** pinned), the Linux/Windows test matrix, Lint, L1, L3, and fast CPU OGA. L4/L5 were **cancelled**, not passed. The next repair push starts fresh CI; its status must be checked separately. ## Review, dissent, and exclusions Historical static review of d9c4acc: Code and Critical used actual `gpt-6.1-sol`; Deep and Readability used actual `claude-sonnet-5.5`, verified from runtime events. This bounded follow-up received direct lead review and developer/lead execution evidence; **no fresh full-team approval is claimed**. | ID | Severity | Raised by | Finding | Disposition | |---|---|---|---|---| | C1 | Major | Copilot | QNN native capability | **Confirmed; fixed** | | C2 | Major | Copilot | Core import aliases | **Confirmed; fixed** | | C3 | Major | Copilot | Gemma tie ordering | **Confirmed; fixed by removing added integration** | | C4 | Major | Copilot | Gemma remaining-scale overflow | **Confirmed; fixed by removing added integration** | | F1, historical | Major | Deep | Uncalled selected functions allegedly reach the no-progress error | **Rejected; reviewer withdrew.** Existing no-annotation early return handles them; reproduced on IR 1.0.0 and 1.1.0. | **Minority/correction record:** F1 was disproved by its concrete trace and existing branch, then withdrawn. Deep also corrected reversed-diff claims about the unpack TODO and explicit-zero comment. No disagreement remains on F1. C3/C4's bugs were accepted; the minimal restoration replaces the suggested tensor-reversal workaround. **Attributed questions:** Readability's active-mask placement question remains non-blocking; its placement keeps routing-threshold semantics together. Deep withdrew the raw-unpack question after confirming the TODO and absence of a standard raw-unpack operator. **Coverage gap:** Historical Integration review remains blocked by the authored/runtime mismatch (`mai-code-2.x1` versus `mai-code-2`); its coverage is not credited or replaced. Historical Deep/Readability excluded numeric test bodies; runtime evidence comes from lead/developer. Critical's threat model was N/A; this follow-up adds no privileged execution boundary. Earlier non-blocking limits remain: bypassing Gemma weight preprocessing is not newly qualified; QMoE accepts a bounded power-of-two block subset; direct configs require Python integers; uninlined optional arguments in other consumers are not qualified. **Residual risk:** no direct opset-29 kernels, QNN device execution, CUDA/other-provider parity, performance/load measurements, GPU/L5 full-model generation, arbitrary gates, BFLOAT16/FP4/prepacked qualification, exhaustive HALF proof, or whole-repository integration clearance. Whole-repository Mypy is not clean. Task-created caches/intermediate models are removed after validation; small evidence reports are retained. The full cumulative 46-file diff has not received a unified latest-head internal review; previous snapshot and bounded follow-up reviews are not claimed as equivalent coverage. ## Scope and history This consolidates the earlier MoE/QMoE work into #814; #815 remains closed unmerged. Earlier thread resolutions remain scoped to their cited evidence, including containing-root import authority and public IR alias handling. No private-domain workaround was added. See [float MoE](docs/moe-lowering.md) and [INT4 QMoE](docs/qmoe-lowering.md) for qualified ABIs and runtime exclusions. --------- Signed-off-by: titaiwangms <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent fe7043a commit d6d45b7

46 files changed

Lines changed: 5175 additions & 61 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/main.yml‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,42 @@ jobs:
2727
- name: Lint with lintrunner
2828
uses: justinchuby/lintrunner-action@main
2929

30+
opset29-lowering:
31+
name: Experimental opset 29 function fallbacks
32+
runs-on: ubuntu-latest
33+
timeout-minutes: 30
34+
env:
35+
CMAKE_BUILD_PARALLEL_LEVEL: "2"
36+
MAX_JOBS: "2"
37+
CUDA_VISIBLE_DEVICES: ""
38+
HF_HUB_OFFLINE: "1"
39+
PYTHONDONTWRITEBYTECODE: "1"
40+
steps:
41+
- uses: actions/checkout@v7
42+
- uses: actions/setup-python@v7
43+
with:
44+
python-version: "3.12"
45+
- name: Install PyTorch CPU
46+
run: pip install torch --index-url https://download.pytorch.org/whl/cpu
47+
- name: Install released dependencies
48+
run: |
49+
# Test-only dependencies allow source collection before marker selection.
50+
pip install -e . pytest httpx "gguf>=0.10.0" "jsonschema>=4.0" \
51+
onnx==1.19.0 onnxruntime==1.31.1 onnxruntime-easy==0.1.2 \
52+
onnxscript==0.7.2 onnx_ir==1.1.0
53+
- name: Test with released ONNX 1.19 schemas
54+
run: |
55+
python -c "import onnx; assert not onnx.defs.has('GroupedMatMul', 29)"
56+
python -m pytest src/mobius tests/ep_optimization_test.py -m opset29 -q -rs
57+
- name: Install pinned opset-29 schemas
58+
run: |
59+
pip install --no-cache-dir --no-deps --force-reinstall \
60+
https://github.com/onnx/onnx/archive/82721c0908fa965dd84e674c006147791313f3e1.tar.gz
61+
python -c "import onnx; assert onnx.defs.has('GroupedMatMul', 29)"
62+
- name: Test with pinned opset-29 schemas
63+
run: |
64+
python -m pytest src/mobius tests/ep_optimization_test.py -m opset29 -q -rs
65+
3066
detect-affected:
3167
name: Detect affected models
3268
runs-on: ubuntu-latest

‎docs/index.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ execution_providers
3232
api/index
3333
gguf-capability-catalog
3434
feature-flags
35+
qmoe-lowering
36+
moe-lowering
3537
```
3638

3739
```{toctree}

‎docs/moe-lowering.md‎

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
# Native float MoE function fallback (experimental opset 29)
2+
3+
```python
4+
from mobius import build_from_module
5+
from mobius._flags import override_flags
6+
7+
# module/config use the normal mobius model and configuration APIs.
8+
with override_flags(experimental_opset29=True):
9+
package = build_from_module(module, config, execution_provider="onnx-standard")
10+
model = package["model"]
11+
```
12+
13+
**Experimental, default off.** Set `experimental_opset29` (or
14+
`MOBIUS_EXPERIMENTAL_OPSET29=1` before import) around the normal build API.
15+
On EPs without fused MoE support, graphs and ordinary function bodies are
16+
created at opset 29 from the outset. Native `com.microsoft::MoE`/`QMoE` calls
17+
receive call-specialized standard functions through `register_function_bodies`;
18+
the normal EP-controlled `InlinePass` expands them. There is no separate
19+
`lower_moe`/`lower_qmoe` API or model-wide compatibility converter.
20+
21+
Except for the QNN profile correction below, flag-off behavior is unchanged.
22+
Native-capable EPs keep opset 24 and native calls without fallback ABI restrictions,
23+
even with the flag enabled. The global `OPSET_VERSION` remains 24. The lowering
24+
does not modify generic `MoELayer` dense implementations or arbitrary gates/experts.
25+
Gemma4 uses its existing model-specific dense dispatch
26+
on non-native EPs at both opset 24 and 29, preserving lower-ID TopK ties and
27+
applying any remaining per-expert scale to normalized routing weights, not W2.
28+
This includes live scales supplied by partial weight updates. Generic function
29+
lowering only touches pre-existing supported native calls; it does not add a
30+
Gemma4 dispatch path. GEGLU, BFLOAT16, and sigmoid/SparseMixer routing remain
31+
outside the qualified fallback ABI. Qwen4's probability-based routing is not
32+
converted to raw-logit routing; probabilities must not be softmaxed twice.
33+
34+
**QNN exception, with the flag off or on:** this PR corrects QNN's profile to
35+
`supports_fused_moe=False`, because QNN has no ORT contrib MoE/QMoE kernels.
36+
That changes existing capability-based model dispatch even with the flag off:
37+
Qwen4 selects `_standard_dispatch`, and eligible unquantized Gemma4 configurations
38+
that previously selected native MoE use the existing dense path instead.
39+
Flag-off QNN still builds at opset 24 without registering these MoE/QMoE
40+
fallback bodies. This capability correction does not qualify QNN device
41+
execution of opset 29 or quantized Gemma4.
42+
43+
This replaces `com.microsoft::MoE` with two standard `GroupedMatMul-29` calls,
44+
targeting the pinned **CPU reference**, not all execution providers.
45+
Construction and registration do not require installed opset-29 schemas;
46+
checking and execution require schemas and a runtime implementing these operators.
47+
ORT 1.31.1 cannot execute these graphs directly. There is no production
48+
opset-24 expansion or performance/memory-use promise. Default dependency
49+
minimums are unchanged.
50+
51+
## Supported ABI
52+
53+
* Input 0: FLOAT or FLOAT16 hidden states `[T,H]` or `[B,S,H]`, positive static
54+
H. Dynamic token axes and empty token dimensions are supported; `T=B*S`.
55+
* Input 1: matching-dtype router **logits**, named `router_probs`, `[T,E]`.
56+
* Input 2: matching-dtype modern row-major W1 `[E,N,H]`.
57+
* Input 3: optional matching-dtype bias1 `[E,N]`.
58+
* Input 4: matching-dtype modern row-major W2 `[E,H,I]`.
59+
* Input 5: optional matching-dtype bias2 `[E,H]`.
60+
* Positive static E, I, H; `N=2I` for SwiGLU, otherwise `N=I`; `1<=k<=E`.
61+
Square non-SwiGLU projections are qualified as modern row-major, consistent
62+
with the pinned helper's legacy-layout predicate.
63+
* Explicit `activation_type`: `relu`, `gelu` (TANH approximation, **not erf**),
64+
`silu`, `identity`, or `swiglu`. SwiGLU requires `swiglu_fusion=1` and
65+
alternating gate/up W1 rows. Other activations require fusion absent or 0.
66+
* SwiGLU is
67+
`min(gate,L)*sigmoid(alpha*min(gate,L))*(clip(up,-L,L)+beta)`.
68+
Defaults: alpha=1, beta=0, L=infinity. Alpha/beta must be finite; L must be
69+
nonnegative and not NaN (infinity allowed). As in CPU, these attributes have
70+
no effect on non-SwiGLU activations.
71+
Config validation also applies to direct `moe(MoEFunctionConfig(...))` calls.
72+
Alpha, beta, and limit use ONNX FLOAT (binary32) precision in both body
73+
constants and specialization identities, so saved registered calls can be
74+
loaded and registered again without changing their overloads.
75+
* `normalize_routing_weights` defaults to **0** and must be 0 or 1.
76+
`use_sparse_mixer` and `swiglu_limit_after_activation` must be absent or 0.
77+
78+
FC3 inputs 6/7, extended slots, unknown attributes, GEGLU,
79+
fusion=2, sparse mixer, post-activation clipping, legacy-transposed layouts,
80+
mixed dtypes, BFLOAT16, malformed tensor metadata, and missing input shape/type
81+
metadata are rejected before mutation. Output metadata is optional (native
82+
custom-op intermediates may be untyped/unshaped); missing metadata is inferred
83+
from X. Existing output metadata must agree with hidden input rank, known
84+
dimensions, and dtype, and is preserved.
85+
86+
## Routing and arithmetic
87+
88+
Unlike QMoE, native CPU MoE converts half router inputs to FLOAT, softmaxes
89+
**all E logits before TopK**, and selects k probabilities. Ties in those FLOAT
90+
probabilities (including probability-rounding ties) prefer the **higher expert
91+
ID**. The lowering reverses the expert axis before ONNX TopK and maps back.
92+
With normalization enabled, selected full-softmax values are renormalized;
93+
otherwise their sum may be less than one.
94+
95+
CPU enqueues routes with weight **>0**, not QMoE's `>1e-8`. The lowering retains
96+
tiny positive weights and uses `Where` to mask inactive contributions, rather
97+
than allowing `0*NaN` to contaminate the output. Router feeds must be finite or
98+
masked `-inf` with at least one finite logit per row. All-infinite/NaN logits
99+
and other out-of-contract feeds need not be runtime-validated. Hidden states,
100+
weights, and biases must contain finite values.
101+
102+
FLOAT16 CPU arithmetic rounds GEMM1 output to half, then bias1 addition to
103+
half, evaluates activation in FLOAT and rounds it to half, rounds GEMM2 output
104+
to half, and then bias2 addition to half. The lowering computes in FLOAT with
105+
explicit half round-trips at each of these boundaries. Route weighting and
106+
accumulation remain FLOAT; only the final output is cast to half. This differs
107+
from QMoE's FLOAT-through-both-GEMMs behavior. CPU thread/expert accumulation
108+
order and math-library implementations may differ; bitwise equality is not
109+
claimed.
110+
111+
This defines a FLOAT-accumulation reference, not parity with every
112+
platform-specific MLAS half-GEMM kernel. Near a top-k boundary, different Softmax
113+
implementations may round probabilities differently and select different experts.
114+
The higher-ID tie rule applies to equal probabilities produced by the graph.
115+
116+
The first GMM maps `[T,H]` to `[T,k,N]`; activation produces `[T,k,I]`.
117+
The second GMM consumes `[T*k,I]` and expert indices `[T*k,1]`, then reshapes
118+
to `[T,k,H]`. After optional bias2, route weighting, and reduction, the result
119+
is restored using `Shape(X)` with `allowzero=1`, including empty rank-3 axes.
120+
Original initializer names and input/output names, shape/type, documentation,
121+
and output metadata are preserved.
122+
123+
## Native runtime qualification
124+
125+
The tested ORT **1.31.1** wheel reports build commit
126+
`6af1a932e2286d5c58166085d24c68783033edee`. Its CPU MoE kernel registration
127+
accepts **FLOAT only**, not FLOAT16. ORT automatically inserts FLOAT casts for
128+
half X, router, and weights, executes FLOAT MoE, then casts the output to half.
129+
Even successful normalized-half execution therefore does **not** validate the
130+
native half-stage rounding described above.
131+
132+
That wheel also has an older FLOAT kernel aliasing bug: it copies hidden input
133+
only when `normalize_routing_weights` is enabled, then clears the output.
134+
Because its kernel permits `MayInplace(0,0)`, clearing an output aliased to an
135+
internally inserted FLOAT input buffer destroys the hidden states when
136+
normalization is disabled. External feed arrays can remain unchanged while
137+
that internal buffer is corrupted. A bias-free identity/k=1 example with
138+
X=`[1,2,3,4]`, tied logits, and expert output `[1,2,3,6]` incorrectly returns
139+
zeros instead of `[1/3,2/3,1,2]` through the half-to-FLOAT fallback.
140+
The [exact wheel source](https://github.com/microsoft/onnxruntime/blob/6af1a932e2286d5c58166085d24c68783033edee/onnxruntime/contrib_ops/cpu/moe/moe_cpu.cc)
141+
contains the normalization-dependent copy. The
142+
[pinned reference source](https://github.com/microsoft/onnxruntime/blob/bbedf7b115be0077a2f4b76fd927fa94a82d0d1a/onnxruntime/contrib_ops/cpu/moe/moe_cpu.cc)
143+
instead correctly copies whenever input and output buffers alias.
144+
145+
Native parity tests inspect the CPU kernel's **actual T dtype constraint**
146+
and explicitly skip unsupported dtypes, rather than accepting automatic
147+
FLOAT fallback or marking discrepancies as expected failures. FLOAT native
148+
comparisons remain active. FLOAT16 verification here is reference-based, using
149+
the pinned CPU source and independent rounded-stage NumPy reference, with
150+
test-copy GroupedMatMul expansion; every independent FLOAT16 test remains
151+
active, including the proof that intermediate half rounding is observable.
152+
This is not a claim of native-half parity against the 1.31.1 wheel.
153+
154+
## Registration, ownership, and imports
155+
156+
Advanced graph builders may use
157+
`register_function_bodies(model, moe_fallback=True)` on an already-built
158+
opset-29 model under the flag. Existing opset-24 models requesting this fallback
159+
raise **“rebuild under experimental opset29”** before specialization. Nothing
160+
converts or relabels imported graphs or caller functions. All containing
161+
function roots must also import 29: lexical child graph hints cannot override
162+
their serialized root scope. IR's standard inliner rejects both 29-function /
163+
24-model and 24-function / 29-model mismatches.
164+
Standard-domain imports may use `""`, `"ai.onnx"`, or both at the same version.
165+
Conflicting simultaneous aliases are rejected before registration changes;
166+
imports are not normalized or relabeled.
167+
168+
All target ABIs, output annotations, specializations, and ownership collisions
169+
are checked before changing target overloads or adding functions. Bodies have
170+
eight positional formals; absent optional slots remain `None`, never compacted
171+
or replaced with dummy tensors. Frozen `MoEFunctionConfig` describes dimensions,
172+
activation/routing attributes, dtype, and optional-bias masks, not token counts,
173+
names, or tensor contents. `moe(config)` returns a fresh `ir.Function`.
174+
175+
Deterministic full-config hashes (including stable infinity encoding) identify
176+
overloads. Existing function-body ownership metadata and config identity make
177+
registration idempotent and prevent mutable sharing between models. Caller-owned
178+
source/destination functions are never replaced; unrelated user overloads are
179+
preserved. No-target registration still attaches the ordinary known bodies; it
180+
is not a byte-preserving no-op. The existing inline boundary preserves output
181+
names, compatible annotations/refinements, documentation, and metadata.
182+
183+
## Pinned authorities
184+
185+
ORT revision `bbedf7b115be0077a2f4b76fd927fa94a82d0d1a`:
186+
187+
* [Native CPU execution and routing](https://github.com/microsoft/onnxruntime/blob/bbedf7b115be0077a2f4b76fd927fa94a82d0d1a/onnxruntime/contrib_ops/cpu/moe/moe_cpu.cc)
188+
* [Shape/layout checks](https://github.com/microsoft/onnxruntime/blob/bbedf7b115be0077a2f4b76fd927fa94a82d0d1a/onnxruntime/contrib_ops/cpu/moe/moe_helper.h)
189+
* [Activation formula](https://github.com/microsoft/onnxruntime/blob/bbedf7b115be0077a2f4b76fd927fa94a82d0d1a/onnxruntime/contrib_ops/cpu/moe/moe_utils.cc)
190+
* [Attribute defaults](https://github.com/microsoft/onnxruntime/blob/bbedf7b115be0077a2f4b76fd927fa94a82d0d1a/onnxruntime/contrib_ops/cpu/moe/moe_base_cpu.h)
191+
192+
ONNX revision `82721c0908fa965dd84e674c006147791313f3e1`:
193+
[GroupedMatMul schema/function](https://github.com/onnx/onnx/blob/82721c0908fa965dd84e674c006147791313f3e1/onnx/defs/math/defs.cc).

0 commit comments

Comments
 (0)