Skip to content

fix: L2 test failures - memory budget, XLM/XLNet activation - #224

Merged
justinchuby merged 14 commits into
mainfrom
justinchu/fix-l2-tests
May 1, 2026
Merged

justinchuby merged 14 commits into
mainfrom
justinchu/fix-l2-tests

Conversation

@justinchuby

@justinchuby justinchuby commented Apr 28, 2026 •

Copy link
Copy Markdown
Member

This pull request introduces several improvements and fixes for model configuration extraction, focusing on more robust handling of activation functions, RoPE (Rotary Position Embedding) detection, and Mixture-of-Experts (MoE) parameters. It also improves support for models with non-standard or missing config fields and adds targeted tests for new fallback logic.

Configuration Extraction Improvements:

  • Added a comprehensive _resolve_hidden_act function to robustly extract the activation function from HuggingFace configs, supporting a wide range of field names and fallback patterns (e.g., ff_activation, gelu_activation, Qwen/CTRL defaults) (src/mobius/_configs.py, [1] [2].
  • Improved RoPE detection logic to recognize implicit RoPE usage in models that don't expose rope_scaling or rope_parameters, using model-type-specific defaults and non-default rope_theta as signals (src/mobius/_configs.py, [1] [2] [3].
  • Enhanced MoE parameter extraction with additional field fallbacks and logic for shared expert size calculation, supporting more model variants (ERNIE, GLM, Hunyuan) (src/mobius/_configs.py, [1] [2].

Vision and Numeric Field Handling:

  • Improved handling of vision model configs where hidden sizes or image sizes may be lists or dicts, ensuring correct scalar extraction for multi-stage models (e.g., Florence2, PVT-v2) (src/mobius/_configs.py, [1] [2].

Testing and Validation:

  • Added targeted tests for activation function extraction fallbacks to ensure correct behavior for various config patterns (e.g., XLNet, XLM) (src/mobius/_configs_test.py, src/mobius/_configs_test.pyR977-R1036).
  • Updated the architecture validation test suite with more explicit skip reasons for models with missing or non-standard vision configs, and improved config resolution for Qwen3-Omni (tests/arch_validation_test.py, [1] [2].

Other Fixes:

These changes collectively improve the robustness and coverage of model config parsing, especially for edge cases and recent model architectures.

- Use psutil for current RSS instead of ru_maxrss peak RSS in memory
  budget tests (fixes all 313 false-positive memory failures)
- Add ff_activation to hidden_act extraction chain (fixes XLNet)
- Handle gelu_activation=True boolean (fixes XLM)

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@github-actions

github-actions Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 93f0f55 → bb9be82

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 60 60 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 107 107 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 53 53 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 61 61 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 58 58 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 98 98 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 59 59 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 61 61 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 58 58 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 275 275 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 129 129 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 408 408 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 166 166 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

Copilot AI 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.

Pull request overview

Fixes L2 arch_validation test failures by making the RSS memory budget check measure current memory (instead of cumulative peak) and by improving activation extraction for HF configs that don’t use hidden_act.

Changes:

  • Update tests/arch_validation_test.py::_get_rss_bytes() to prefer psutil current RSS, with ru_maxrss fallback.
  • Extend ArchitectureConfig.from_transformers() activation-field extraction to handle XLNet (ff_activation) and XLM (gelu_activation=True).

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
tests/arch_validation_test.py Switch memory measurement to current RSS via psutil to avoid cumulative peak-RSS false positives in long sequential runs.
src/mobius/_configs.py Expand activation attribute fallback chain to correctly infer hidden_act for XLNet/XLM configs.

Comment thread tests/arch_validation_test.py Resolved
Comment thread tests/arch_validation_test.py Resolved
Comment thread src/mobius/_configs.py Resolved
@github-actions

github-actions Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 93f0f55 → bb9be82

Model Sub-model Changes Status
bert (feature-extraction) model 0 ⚪
falcon model 0 ⚪
gemma2 model 0 ⚪
gemma4 (gemma4) decoder 0 ⚪
gemma4 (gemma4) embedding 0 ⚪
gemma4 (gemma4) vision_encoder 0 ⚪
gemma4_text model 0 ⚪
gpt2 model 0 ⚪
llama model 0 ⚪
llama (static-cache) model 0 ⚪
mamba (ssm-text-generation) model 0 ⚪
phi3 model 0 ⚪
phi3 (static-cache) model 0 ⚪
qwen model 0 ⚪
qwen (static-cache) model 0 ⚪
qwen2 model 0 ⚪
qwen2 (static-cache) model 0 ⚪
qwen2_moe model 0 ⚪
qwen2_moe (static-cache) model 0 ⚪
qwen3 model 0 ⚪
qwen3 (static-cache) model 0 ⚪
qwen3_5_moe (hybrid-text-generation) model 0 ⚪
qwen3_5_text (hybrid-text-generation) model 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) decoder 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) embedding 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) vision_encoder 0 ⚪
qwen3_moe model 0 ⚪
qwen3_moe (static-cache) model 0 ⚪
qwen3_next (hybrid-text-generation) model 0 ⚪
t5 (seq2seq) decoder 0 ⚪
t5 (seq2seq) encoder 0 ⚪
whisper (speech-to-text) decoder 0 ⚪
whisper (speech-to-text) encoder 0 ⚪

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

@codecov

codecov Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.13253% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/mobius/_configs.py 54.16% 9 Missing and 2 partials ⚠️
src/mobius/_config_resolver.py 40.00% 2 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

justinchuby and others added 4 commits April 29, 2026 00:54
Root-cause fixes across 12 failure categories:

Config extraction (_configs.py):
- Default hidden_act for CTRL (relu) and SAM2 (gelu)
- Handle vision_config as list (pick first element)
- Support image_size dict in _as_int()
- Compute shared_expert_intermediate_size from moe_num_shared_experts,
  n_shared_experts, and num_shared_expert (Hunyuan)
- Extract num_experts_per_tok from moe_topk (per-layer list)
- Add _IMPLICIT_ROPE_DEFAULTS for models that use RoPE but don't
  expose it in config JSON (jamba, chatglm, deepseek_vl_v2, qwen3_omni_moe)
- Add rope_theta fallback in _extract_rope_config

Activation mapping (_activations.py):
- Map xielu → silu in ACT2FN for Apertus

RoPE (_rotary_embedding.py):
- Use qk_rope_head_dim for inv_freq in MLA models (MiniCPM3)

Model fixes:
- longcat_flash: Set config_class = LongcatFlashConfig (was inheriting
  CausalLMConfig, skipping field mappings)

Config resolver (_config_resolver.py):
- Wrap PretrainedConfig construction in try/except for phi4_multimodal

Test (arch_validation_test.py):
- Resolve text_config within talker_config (Qwen3-Omni)
- xfail 8 models requiring trust_remote_code for VisionConfig
- Remove unused os import

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
rope_theta=10000.0 is the common default that NoPE models inherit
as dead config data. Only treat it as a RoPE signal when it differs
from the default, avoiding false positives for NemotronH, GraniteMoeHybrid, etc.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@justinchuby
justinchuby force-pushed the justinchu/fix-l2-tests branch from e3f5085 to 1f3a961 Compare April 29, 2026 02:36
justinchuby and others added 5 commits April 29, 2026 04:58
- Add psutil to testing optional-dependencies in pyproject.toml
- Fix macOS ru_maxrss units (bytes on macOS, KB on Linux)
- Add TestActivationFallbacks tests for ff_activation and gelu_activation

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
xielu is parametric (learnable alpha_p/alpha_n). The silu mapping
is a placeholder so CausalLMModel base __init__ doesn't crash.
ApertusCausalLMModel replaces the MLP with real XIELUActivation.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
No longer needed — was producing false positives and adds no value.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
- Remove leftover gc.collect() calls after gc import was removed
- Use hybrid-text-generation task for qwen3_next (registers
  CausalConvWithState and LinearAttention function ops)
- Default symbolic conv/recurrent state dims to 1 instead of 0

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@titaiwangms

Copy link
Copy Markdown
Contributor

Exploration Summary (Architect Review)

Quick orientation for reviewers — full analysis in the crew artifact store.

What this PR does

Drives the L2 arch_validation test suite from 76 failures → 0 by fixing root causes across 6 categories:

Category Files touched
Config extraction (activation, RoPE, MoE, vision) _configs.py
HF config dict robustness _config_resolver.py
Activation registry _activations.py
MLA RoPE dimension _rotary_embedding.py
Config class registration bug longcat_flash.py
Test cleanup + xfails arch_validation_test.py, integration_test.py

Key design decisions worth noting

  1. Memory budget test removed — ru_maxrss peak RSS is cumulative and non-decreasing within a process; it can never correctly measure per-test memory in a sequential run. Removal is the right call. If memory regression detection is needed later, it requires per-test subprocess isolation.

  2. RoPE theta signal — rope_theta=10000.0 (the HF default) is now excluded as a RoPE trigger via math.isclose(). Correct fix for NoPE models (NemotronH, GraniteMoeHybrid) that inherit this as dead config data.

  3. _IMPLICIT_ROPE_DEFAULTS allowlist — A pragmatic fix for models that hardcode RoPE internally without exposing rope_scaling in their config JSON. Creates ongoing maintenance debt as new model types are added.

  4. xielu → silu placeholder — Well-commented; ApertusCausalLMModel overrides the MLP with real XIELUActivation. The comment is essential and correctly explains the pattern.

  5. LongcatFlashCausalLMModel.config_class — Silent correctness bug: model loaded without error but with wrong config, producing incorrect ONNX graphs. The fix is minimal and correct.

One concern to discuss

The try/except (AttributeError, KeyError, TypeError) in _config_resolver.py that strips rope_scaling/rope_parameters on failure is pragmatic but broad. If a future transformers release changes the exception type or the bug disappears, this silently becomes a no-op that could mask a real issue. Worth adding a log warning on the except branch so failures are visible in CI logs.

@titaiwangms titaiwangms 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.

Architect Review — PR #224: L2 arch-validation test fixes

Verdict: Approve with minor suggestions — the changes are well-motivated, correctness-focused, and appropriately scoped. No blocking issues.


Summary

This PR eliminates 76 L2 arch-validation failures across ~25 model types. The root causes are real bugs and HuggingFace config heterogeneity rather than test fragility. Changes are predominantly additive fallbacks with solid unit test coverage.


Strengths

  • Root-cause fixes, not suppression. Each failure category has a genuine fix — activation fallbacks, MLA rope dim, config class registration. The xfails are reserved only for cases that genuinely cannot work without trust_remote_code.
  • Memory budget test removal is correct. ru_maxrss is a cumulative peak metric at the process level — it structurally cannot measure per-test memory in a sequential run. This test was a false-positive generator, not a safety net.
  • xielu → silu placeholder is clearly documented. The comment explains the three-part picture: base class init, why silu is safe, and that ApertusCausalLMModel overrides it. Future maintainers will not be confused.
  • New unit tests (TestActivationFallbacks) cover the key new paths with lightweight fake configs — no model downloads required. The gelu_activation=False negative case is especially good.

Suggestions

1. Add a log warning in the _config_resolver.py except branch (non-blocking)

# Current (silent):
except (AttributeError, KeyError, TypeError):
    d = {k: v for k, v in d.items() if k not in ("rope_scaling", "rope_parameters")}
    config = transformers.PretrainedConfig(**d)

Suggested addition:

except (AttributeError, KeyError, TypeError):
    import logging
    logging.getLogger(__name__).warning(
        "_dict_to_pretrained_config: stripped rope fields due to PretrainedConfig error; "
        "if this is unexpected, check transformers version compatibility"
    )
    d = {k: v for k, v in d.items() if k not in ("rope_scaling", "rope_parameters")}
    config = transformers.PretrainedConfig(**d)

This ensures the fallback is visible in CI logs rather than silently eating exceptions.

2. _IMPLICIT_ROPE_DEFAULTS maintenance burden (informational)

The hardcoded model-type → rope_theta dict is a pragmatic solution for models that hardcode RoPE internally without exposing rope_scaling. As the model registry grows, this list will need manual updates. Consider adding a comment near the dict pointing maintainers to where they should check when adding a new model that uses RoPE without config exposure.

3. _shared_expert_size() attribute name proliferation (informational)

The function now has 4 different attribute names for "number of shared experts" (moe_num_shared_experts, n_shared_experts, num_shared_expert, num_shared_experts via the top-level field). This reflects real HF config heterogeneity, not a code quality issue. Leaving a comment linking each name to the model family that uses it would help future contributors.


Correctness Highlights (confirmed correct)

  • rope_theta non-default signal: math.isclose(raw_rope_theta, 10_000.0) correctly excludes the HF default. The default is universally 10000.0 across transformers, so this is a safe threshold.
  • qk_rope_head_dim for MLA models: Using config.qk_rope_head_dim or config.head_dim is correct — MLA splits Q/K into a compressed latent part and a RoPE part; applying inv_freq over the full head_dim would produce wrong frequencies.
  • LongcatFlashCausalLMModel.config_class: This was a silent correctness bug. Without it, _config_from_hf() resolved to ArchitectureConfig base class, bypassing LongcatFlashConfig-specific fields. Fix is minimal and correct.
  • qwen3_next state shape 0 → 1: np.zeros((B, D, 0)) is a valid but empty array — numerical comparison would trivially pass or fail depending on implementation. Using 1 as the concrete symbolic dim is correct for a meaningful integration test.

Architecture Note

The pattern of config extraction fallback chains in from_transformers() is growing in complexity (activation lookup now has 8+ fallbacks; MoE fields have 4+ aliases each). This is unavoidable given HF config heterogeneity across 100+ model types. However, as the registry expands, consider extracting the fallback chains into per-field helper functions (like _shared_expert_size()) for readability and testability. The existing _extract_rope_config() and _extract_vision_config() are good models of this pattern.


Overall: well-executed, clearly motivated, correctly fixes real bugs. The minor suggestions above are improvements rather than requirements. Ready to merge once CI passes.

@titaiwangms titaiwangms 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.

Consolidated Review — PR #224 (Code + Critical + Readability + Architect)

Verdict: ✅ Approve with required changes — 2 pre-merge blockers, 2 should-fix items, then this is ready to merge.

The fixes are correct and well-targeted. Clearing 76 L2 failures by addressing real root causes (not masking them) is the right approach. The concerns below are actionable and none require architectural redesign.


🔴 Pre-Merge Blocker 1 — Replace try/except in _config_resolver.py with conditional logic

File: src/mobius/_config_resolver.py (flagged by both code and critical reviewers)

The current approach catches (AttributeError, KeyError, TypeError) and strips rope fields on failure. This has three compounding problems:

  1. Transformers version fragility — if a future release changes the rope-standardization crash to ValueError, the catch silently stops working and all Phi4-MM loads fail
  2. Silent correctness failure — nothing is logged when the except fires; an unrelated KeyError strips rope fields and produces a wrong config without any signal
  3. Exception chain loss — if stripping rope fields doesn't fix the problem, the retry obscures the original traceback

The triggering condition is known and inspectable before the call. Replace with:

# PretrainedConfig.__post_init__ attempts rope standardization when
# rope_scaling is present, which requires max_position_embeddings.
# Composite configs (e.g. Phi4-MM) may have rope_scaling at the top
# level without max_position_embeddings — strip rope fields proactively.
# The nested text_config carries its own rope_scaling intact.
d_to_use = dict(d)
if "rope_scaling" in d_to_use and "max_position_embeddings" not in d_to_use:
    logger.debug(
        "Stripping top-level rope fields from %s config: "
        "rope_scaling present without max_position_embeddings",
        d_to_use.get("model_type", "unknown"),
    )
    d_to_use.pop("rope_scaling", None)
    d_to_use.pop("rope_parameters", None)

config = transformers.PretrainedConfig(**d_to_use)

This is condition-driven, version-stable, always logged, and narrowly scoped.


🔴 Pre-Merge Blocker 2 — PR description is stale and misleading

File: PR body (flagged by both readability and critical reviewers)

The PR description says the memory budget change was "replaced with an info-level log", added psutil, and fixed a macOS ru_maxrss units issue. None of this exists in the diff. The actual change is a complete removal of the memory test and all related infrastructure. This describes an earlier draft approach that was abandoned.

Reviewers approving based on the description may believe memory protection still exists when it doesn't.

Please update the memory budget section to accurately state: the test was entirely removed because ru_maxrss is a cumulative peak metric (monotonically non-decreasing in a process lifetime) that is structurally unsuitable for per-test assertions in a sequential run. If memory regression detection is still a goal, it would require per-test subprocess isolation or a dedicated benchmark tracked as a CI metric.


🟡 Should Fix 3 — _extract_rope_config() docstring contradicts new behavior

File: src/mobius/_configs.py

The existing docstring says rope_theta alone is NOT a sufficient RoPE signal. The PR adds has_nondefault_rope_theta, which explicitly treats non-default rope_theta as a RoPE indicator. A reader who trusts the docstring will form the wrong mental model.

Fix: Update to reflect the nuance: rope_theta=10000.0 (the HF default) is not a signal, but a non-default value (e.g., 50,000 for Arctic) is now treated as one.


🟡 Should Fix 4 — Missing test for has_nondefault_rope_theta (new behavior change)

File: src/mobius/_configs_test.py

has_nondefault_rope_theta is a behavior change: previously rope_theta=50_000.0 without rope_scaling returned None; now it returns a RoPEConfig. The existing test_rope_theta_alone_is_not_a_rope_signal uses rope_theta=10_000.0 (the default) and does not exercise the new path.

Add:

def test_nondefault_rope_theta_without_rope_scaling_activates_rope(self):
    """Non-default rope_theta alone (e.g. 50000) is treated as RoPE signal."""
    class Cfg:
        rope_theta = 50_000.0  # no rope_scaling/rope_parameters

    result = _extract_rope_config(Cfg())
    assert result is not None
    assert result.rope_type == "default"
    assert result.rope_theta == pytest.approx(50_000.0)

🔵 Structural Concern 5 — _IMPLICIT_ROPE_DEFAULTS needs maintenance docs + registry TODO

File: src/mobius/_configs.py

This dict is correct and necessary. The concern is the discovery protocol: new models that belong here are only detected reactively (wrong ONNX outputs). With 50+ models today, silent failures will recur without documentation.

Before merge, add this comment:

# Models that use RoPE but hardcode rope_theta entirely in model __init__,
# not in config JSON.  NOT detectable via config introspection without
# trust_remote_code.  When a new model fails L2 with missing RoPE:
# 1. Confirm the model HF source uses rotary embeddings
# 2. Find the hardcoded rope_theta in the transformers source
# 3. Add an entry here: model_type → rope_theta
# TODO: migrate to a registry annotation (uses_rope: bool, rope_theta: float)

Post-merge: Add arch-validation assertion for known-RoPE model types, and migrate to registry entries for single source of truth.


🟢 Minor Items (follow-up OK)

  • _as_int() empty dict raises StopIteration; use next(iter(value.values()), None) with fallback
  • _shared_expert_size() or chain skips falsy-zero moe_num_shared_experts; use _first_not_none() for inner chain
  • Activation fallback comments: move each comment immediately before its specific or line
  • Rename _shared_expert_size() → _shared_expert_intermediate_size() to match the field name
  • _IMPLICIT_ROPE_DEFAULTS → _IMPLICIT_ROPE_THETA reads more naturally at call site
  • _rotary_embedding.py: add comment that MLA models are assumed to have partial_rotary_factor=1.0
  • Arch test module docstring "Must stay under 2 GB RAM" is stale — remove it
  • xfail messages: standardize template (some say VisionConfig.hidden_size missing, others say VisionConfig missing)
  • _shared_expert_size() defined ~500 lines after its call site — move above from_transformers()
  • Post-merge: consider __init_subclass__ check in CausalLMModel to catch missing config_class at definition time

✅ Confirmed Correct — No Action Needed

  • Memory budget test removal ✓ (all reviewers agree — ru_maxrss is structurally broken for this use)
  • LongcatFlashCausalLMModel.config_class ✓ (silent correctness bug; minimal correct fix)
  • MLA RoPE qk_rope_head_dim ✓ (full head_dim produced wrong inv_freq shape for DeepSeek-V2/MiniCPM3)
  • xielu → silu placeholder ✓ (subclass overrides immediately; the "why" comment is exemplary)
  • Activation fallback chain additions ✓ (additive-only, correct short-circuit semantics)
  • Sam2Config gelu default ✓ (guarded by if base.hidden_act is None)
  • Qwen3-Omni talker_config.text_config unwrapping ✓
  • qwen3_next hybrid-text-generation + 0 → 1 for symbolic dims ✓
  • TestActivationFallbacks tests ✓ (well-scoped; negative case is especially valuable)

Reviewed by: Code Reviewer · Critical Reviewer · Readability Reviewer · Architect

@titaiwangms

Copy link
Copy Markdown
Contributor

Review Addendum — Two Additional Findings

This supplements the consolidated review above with two items identified during cross-team synthesis.


Addendum A — _IMPLICIT_ROPE_DEFAULTS: potential dead-code entries for jamba and qwen3_omni_moe

The jamba entry uses rope_theta=8_000.0 and qwen3_omni_moe uses rope_theta=1_000_000.0 — both non-default values. The PR also adds has_nondefault_rope_theta, which fires first in _extract_rope_config() when rope_theta differs from 10,000.0.

The interaction: if jamba/qwen3_omni_moe config JSON does serialize rope_theta, then has_nondefault_rope_theta returns a RoPEConfig, so rope_config is None is False, and the _IMPLICIT_ROPE_DEFAULTS fallback for those entries is never reached. The entries would be dead code.

The dict is only necessary for entries whose config JSON does not serialize rope_theta at all (e.g., chatglm and deepseek_vl_v2, both at 10,000.0 — they would get no RoPE from either path without this dict).

Action requested: Please add a per-entry comment clarifying whether each model's config JSON serializes rope_theta. For jamba/qwen3_omni_moe, if rope_theta is always present in the JSON, those entries can be removed. If it's absent (pure implicit), the entry is correct but should say so explicitly. This directly affects correctness reasoning for future maintainers updating these entries.


Addendum B — Activation fallback chain: extract into _resolve_hidden_act() helper

The fallback chain is now 10 levels deep. Both readability and critical reviewers separately identified that it has outgrown inline placement. The fix they converge on: extract it into a named helper, following the pattern already established by _extract_rope_config() and _extract_vision_config().

Suggested helper:

def _resolve_hidden_act(config, model_type: str) -> str | None:
    """Resolve the hidden activation function from heterogeneous HF config patterns.

    Fallback order (first truthy value wins):
      hidden_act            — standard field (most models)
      hidden_activation     — some encoder models
      activation_function   — GPT-2 family
      ff_activation         — XLNet
      dense_act_fn          — some BERT variants
      activation            — generic fallback
      afn                   — older BERT configs
      "silu"  (qwen)        — Qwen v1 hardcodes silu; no activation attr in config
      "relu"  (ctrl)        — CTRL hardcodes relu; no hidden_act attr in config
      gelu_activation=True  — XLM uses a boolean flag, not a string field;
                              placed last so it cannot override an explicit
                              hidden_act in any other model
    """
    return (
        getattr(config, "hidden_act", None)
        or getattr(config, "hidden_activation", None)
        or getattr(config, "activation_function", None)
        or getattr(config, "ff_activation", None)
        or getattr(config, "dense_act_fn", None)
        or getattr(config, "activation", None)
        or getattr(config, "afn", None)
        or ("silu" if model_type in ("qwen",) else None)
        or ("relu" if model_type in ("ctrl",) else None)
        or ("gelu" if getattr(config, "gelu_activation", False) else None)
    )

Benefits:

  • Independently unit-testable (the existing TestActivationFallbacks tests can call this directly)
  • The docstring makes the fallback order and each entry's rationale authoritative and searchable
  • The gelu_activation placement constraint ("must be last") is documented where it matters — in the function, not buried in inline comments
  • from_transformers() reduces to a single hidden_act=_resolve_hidden_act(config, model_type) call

This doesn't need to block the current PR — it can ship in an immediate follow-up — but the helper signature and docstring above are ready to use as-is.


All other items remain as stated in the consolidated review above.

@titaiwangms titaiwangms 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.

Final Consolidated Review — PR #224 (All Reviewers)

Verdict: ✅ Approve with required changes — 5 pre-merge blockers, 2 medium items, 3 follow-ups.

The fixes in this PR are correct and well-targeted. Clearing 76 L2 failures by addressing real root causes is the right approach. All items below are actionable and none require architectural redesign.


🔴 Pre-Merge Blockers

1. Replace try/except in _config_resolver.py with condition-based stripping

The current approach catches (AttributeError, KeyError, TypeError) and strips rope fields on failure. This has two compounding problems:

Version fragility: These are three of Python's most generic exception types. If a future transformers release changes the rope-standardization crash to ValueError, the catch silently stops working and all Phi4-MM loads fail without any clear signal. If transformers later fixes the crash, the except branch becomes invisible dead code.

Lost debuggability: Nothing is logged when the except fires. If stripping rope fields doesn't fix the problem (i.e., the exception had a different root cause), the retry raises from the second call site and the original traceback is gone.

The triggering condition is deterministic and inspectable before the call. Replace with:

def _dict_to_pretrained_config(d: dict):
    import transformers

    # PretrainedConfig.__post_init__ attempts rope standardization when
    # rope_scaling is present, which requires max_position_embeddings.
    # Composite configs (e.g. Phi4-MM) may have rope_scaling at the top
    # level without max_position_embeddings — strip rope fields proactively
    # so PretrainedConfig doesn't crash.  The nested text_config carries
    # its own rope_scaling with max_position_embeddings intact.
    d_to_use = dict(d)
    if "rope_scaling" in d_to_use and "max_position_embeddings" not in d_to_use:
        logger.debug(
            "Stripping top-level rope fields from %s config: "
            "rope_scaling present without max_position_embeddings",
            d_to_use.get("model_type", "unknown"),
        )
        d_to_use.pop("rope_scaling", None)
        d_to_use.pop("rope_parameters", None)

    config = transformers.PretrainedConfig(**d_to_use)
    ...

This is condition-driven, version-stable, always logged at debug level, and narrowly scoped to the known failure condition.


2. Add comment + TODO to _IMPLICIT_ROPE_DEFAULTS

This dict handles a genuinely distinct failure class: models that hardcode rope_theta entirely inside their Python model class, not in the config JSON — so getattr(config, "rope_theta", None) returns None even though the model uses RoPE. The has_nondefault_rope_theta signal (new in this PR) cannot help these models.

The problem is the discovery protocol: the only way to know a model belongs here is to observe wrong ONNX output, trace the failure back to from_transformers(), and manually add it. This is silent and reactive. With 50+ models today, it will recur.

Add this comment above the dict:

# Models that use RoPE but hardcode rope_theta entirely in model __init__,
# not in config JSON.  These are NOT detectable via config introspection
# without trust_remote_code.  When a new model fails L2 with missing RoPE:
# 1. Confirm the model's HF source uses rotary embeddings
# 2. Find the hardcoded rope_theta in the transformers source
# 3. Add an entry here: model_type → rope_theta
# TODO: migrate to a registry annotation (uses_rope: bool, rope_theta: float)
# once the registry schema supports per-model capability flags.

Also see item M2 below regarding jamba/qwen3_omni_moe entries that may be redundant with has_nondefault_rope_theta.


3. Fix the PR description — memory budget section is factually wrong

The PR description says:

"Removed hard assertion on memory budget — replaced with an info-level log so CI never fails on transient memory spikes. Added psutil as a testing dependency for accurate current RSS measurement. macOS ru_maxrss fix…"

None of this exists in the diff. The actual change is a complete removal of the memory test and all related infrastructure (resource, gc, _get_rss_bytes, _MAX_RSS_BYTES). This appears to describe an earlier draft approach that was abandoned.

This is harmful in two ways: reviewers may approve believing memory protection still exists (it doesn't), and future git blame readers will be misled.

Please update the memory budget section to accurately state: the test was entirely removed because ru_maxrss is a cumulative peak RSS metric — monotonically non-decreasing in a process lifetime — making it structurally unsuitable for per-test assertions in a sequential run. No replacement currently exists; if memory regression detection is needed, it would require per-test subprocess isolation or a dedicated benchmark.


4. Update _extract_rope_config() docstring — it contradicts the new code

The existing docstring includes:

"Note: rope_theta alone is NOT a sufficient RoPE signal because models like NemotronH carry rope_theta in their config as dead data…"

The PR adds has_nondefault_rope_theta, which explicitly makes non-default rope_theta a RoPE signal. The docstring now directly contradicts the implementation. A reader who trusts the docstring will form the wrong mental model and may inadvertently revert this behavior in a future change.

Update the docstring to reflect the nuance: rope_theta=10000.0 (the HF default) is excluded as a signal via math.isclose(), but a non-default rope_theta (e.g., 50,000 for Arctic, 500,000 for others) is now treated as a RoPE indicator to avoid false negatives on models that don't expose rope_scaling.


5. Add test for has_nondefault_rope_theta — silent behavior change with no coverage

has_nondefault_rope_theta is a behavior change: previously, rope_theta=50_000.0 without rope_scaling/rope_parameters would cause _extract_rope_config() to return None. Now it returns a RoPEConfig. This is the most impactful new logic in the PR and has no direct unit test.

The existing test_rope_theta_alone_is_not_a_rope_signal uses rope_theta=10_000.0 (the default) — it tests that the default is excluded, but not that a non-default value is included. Its description ("rope_theta alone is NOT a RoPE signal") is now misleading.

Add this test:

def test_nondefault_rope_theta_without_rope_scaling_activates_rope(self):
    """Non-default rope_theta alone (e.g. 50000) is treated as a RoPE signal."""
    class Cfg:
        rope_theta = 50_000.0  # no rope_scaling, no rope_parameters

    result = _extract_rope_config(Cfg())
    assert result is not None
    assert result.rope_type == "default"
    assert result.rope_theta == pytest.approx(50_000.0)

🟡 Medium Items (same PR or immediate follow-up)

M1. Extract activation fallback chain into _resolve_hidden_act() helper

The fallback chain is now 10 levels deep with implicit precedence. All three reviewers converge on this: extract it into a named helper following the pattern of _extract_rope_config() and _extract_vision_config().

def _resolve_hidden_act(config, model_type: str) -> str | None:
    """Resolve the hidden activation function from heterogeneous HF config patterns.

    Fallback order (first truthy value wins):
      hidden_act            — standard field (most models)
      hidden_activation     — some encoder models
      activation_function   — GPT-2 family
      ff_activation         — XLNet
      dense_act_fn          — some BERT variants
      activation            — generic fallback
      afn                   — older BERT configs
      "silu"  (qwen)        — Qwen v1 hardcodes silu; no activation attr in config
      "relu"  (ctrl)        — CTRL hardcodes relu; no hidden_act attr in config
      gelu_activation=True  — XLM uses a boolean flag, not a string field;
                              placed last so it cannot override an explicit
                              hidden_act in any other model
    """
    return (
        getattr(config, "hidden_act", None)
        or getattr(config, "hidden_activation", None)
        or getattr(config, "activation_function", None)
        or getattr(config, "ff_activation", None)
        or getattr(config, "dense_act_fn", None)
        or getattr(config, "activation", None)
        or getattr(config, "afn", None)
        or ("silu" if model_type in ("qwen",) else None)
        or ("relu" if model_type in ("ctrl",) else None)
        or ("gelu" if getattr(config, "gelu_activation", False) else None)
    )

Benefits: independently unit-testable; the docstring makes fallback order and per-entry rationale authoritative; the gelu_activation placement constraint ("must be last — why") is explicit where it matters; from_transformers() becomes one line: hidden_act=_resolve_hidden_act(config, model_type).

M2. Clarify jamba/qwen3_omni_moe entries — may be dead code

jamba uses rope_theta=8_000.0 and qwen3_omni_moe uses rope_theta=1_000_000.0 — both non-default. If their HF config JSON does serialize rope_theta, then has_nondefault_rope_theta fires first → _extract_rope_config() returns a RoPEConfig → rope_config is None is False → the _IMPLICIT_ROPE_DEFAULTS fallback for those entries is never reached.

The dict is only necessary when rope_theta is entirely absent from the config JSON. chatglm and deepseek_vl_v2 (both at 10,000.0) are clearly in this category — they'd get nothing from has_nondefault_rope_theta. But jamba/qwen3_omni_moe need clarification.

Action: Add a per-entry comment stating whether each model serializes rope_theta to config.json or not. Remove the entries if they're redundant with has_nondefault_rope_theta.


🔵 Follow-Up (post-merge)

  1. Registry annotation: Add uses_rope: bool / rope_theta: float to model registry entries so _IMPLICIT_ROPE_DEFAULTS can be derived from a single source of truth and gaps are caught at registry definition time
  2. Arch-validation assertion: For known-RoPE model types, assert arch_config.rope_config is not None to surface gaps at test time rather than at inference time
  3. CausalLMModel.__init_subclass__ enforcement: Warn (or error) when a CausalLMModel subclass doesn't declare config_class — would have caught the LongcatFlash silent bug at class definition time, not at test time

✅ Confirmed Correct — No Action Needed

  • Memory budget test removal — ru_maxrss is structurally broken for this use case; all reviewers agree
  • LongcatFlashCausalLMModel.config_class — silent correctness bug; minimal and correct fix
  • MLA RoPE qk_rope_head_dim — correct; full head_dim produced wrong inv_freq shape for DeepSeek-V2/MiniCPM3
  • xielu → silu placeholder — well-commented; the "why" comment is exemplary and prevents future misdiagnosis
  • Activation fallback chain additions — ff_activation, gelu_activation, relu are additive-only with correct short-circuit semantics
  • Sam2Config gelu default — guarded by if base.hidden_act is None; cannot override an explicitly set value
  • Qwen3-Omni talker_config.text_config unwrapping — minimal and correct
  • qwen3_next integration test — hybrid-text-generation task type correct; 0 → 1 for symbolic dims correct
  • TestActivationFallbacks tests — well-scoped; negative case for gelu_activation=False is especially valuable

Reviewed by: Code Reviewer · Critical Reviewer · Readability Reviewer · Architect

@gramalingam gramalingam left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM ... I see copilots have substantial reviews already, I assume that they will be addressed.

@justinchuby
justinchuby marked this pull request as draft April 30, 2026 17:06
justinchuby and others added 3 commits April 30, 2026 17:45
… rope defaults

- Extract 10-level activation fallback chain into _resolve_hidden_act()
  helper with docstring documenting fallback order and rationale
- Replace try/except in _dict_to_pretrained_config with proactive
  rope field stripping when max_position_embeddings is absent
- Remove dead qwen3_omni_moe entry from _IMPLICIT_ROPE_DEFAULTS
  (its config JSON has rope_scaling, so _extract_rope_config handles it)
- Add per-entry comments to remaining _IMPLICIT_ROPE_DEFAULTS entries

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
…havior

The docstring stated rope_theta alone is NOT a RoPE signal, but the
code now treats non-default rope_theta (!=10000.0) as a signal via
math.isclose(). Update the docstring to document all three signal
categories and explain the 10000.0 exclusion rationale.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
- Add logger.debug when stripping top-level rope fields in
  _dict_to_pretrained_config (visibility for debugging)
- Add discovery protocol comment + TODO above _IMPLICIT_ROPE_DEFAULTS
- Add test_nondefault_rope_theta_without_rope_scaling_activates_rope
  to cover the has_nondefault_rope_theta behavior change

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@justinchuby
justinchuby marked this pull request as ready for review May 1, 2026 04:56
Catches silent bugs where a registry entry specifies a specialized
config_class but the model class has a different one (e.g. the
LongcatFlash bug where missing config_class caused wrong ONNX graphs).

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@justinchuby
justinchuby force-pushed the justinchu/fix-l2-tests branch from f9ef9a9 to bb9be82 Compare May 1, 2026 05:00
@justinchuby

Copy link
Copy Markdown
Member Author

Thanks for the reivew. All comments addressed

@justinchuby
justinchuby enabled auto-merge (squash) May 1, 2026 05:01
@justinchuby
justinchuby merged commit e73e0a5 into main May 1, 2026
17 of 21 checks passed
@justinchuby
justinchuby deleted the justinchu/fix-l2-tests branch May 1, 2026 05:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants