Skip to content

fix: repair the BaseQModel attr recursion and the transformers-5.22 cache shim, and realign the stale tests from #4358 - #4397

Merged
Qubitium merged 2 commits into
mainfrom
fix/4358-test-triage-regressions
Nov 16, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/4358-test-triage-regressions

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

TL;DR

Issue #4358 lists a batch of test-suite failures. I reproduced every item at def6e61e3 (current main) and classified each one. Two are real library defects, not stale tests; the rest are stale expectations or missing availability gates. Net diff: 16 files, +~300/-45.

Fixes #4358.

1. The problem

Two items were reported as test-side issues but are reachable from production code.

a. BaseQModel.__getattr__ infinite recursion. The hook forwards unknown attributes to the inner model and looks that up through self._modules. Reading self._modules before nn.Module.__init__ has populated it (during __init__, or on a fixture built with object.__new__) went through hasattr(self, "_modules"), which re-enters __getattr__. Result: RecursionError on the first unrelated attribute probe, and a pytest teardown that spent minutes formatting the traceback.

flowchart TD
    A["obj.some_attribute"] --> B["BaseQModel.__getattr__"]
    B --> C["super().__getattr__ raises AttributeError"]
    C --> D{"__dict__ contains 'model'?"}
    D -- no --> E["hasattr(self, '_modules')"]
    E --> F["__getattr__('_modules')"]
    F --> C
    C -.- G["RecursionError<br/>never returns False"]
Loading

b. Legacy cache-length shim never installed on transformers 5.22. _patch_transformers_remote_code_compat reinstalls Cache.get_max_length / get_usable_length for older remote decoders, but gated the reinstall on hasattr(Cache, "get_max_cache_shape"). In 5.22 that cache-level name is gone too — the query lives on CacheLayerMixin.get_max_length() — so the shim was skipped and remote decode still raised AttributeError.

Area Before After
BaseQModel.__getattr__ container probe hasattr(self, "_modules") (gptqmodel/models/base.py:6247) self.__dict__.get("_modules") (gptqmodel/models/base.py:6247)
Cache shim install gate required Cache.get_max_cache_shape (gptqmodel/utils/hf.py:1208) only requires Cache.get_max_length to be missing (gptqmodel/utils/hf.py:1208)
Cache length value source unconditional self.get_max_cache_shape(layer_idx) (gptqmodel/utils/hf.py:1231) layer API first; cache-level shape only when callable; otherwise None (gptqmodel/utils/hf.py:1233)

2. The new flow

flowchart TD
    A["_patch_transformers_remote_code_compat"] --> B{"Cache.get_max_length exists?"}
    B -- yes --> Z["leave the installed API alone"]
    B -- no --> C["install get_max_length(self, layer_idx=0)"]
    C --> D{"layer defines get_max_length?"}
    D -- yes --> E["layer.get_max_length()"]
    D -- no --> F{"layer defines get_max_cache_shape?"}
    F -- yes --> G["layer.get_max_cache_shape()"]
    F -- no --> H["cache-level get_max_cache_shape,<br/>only when callable"]
    H -- absent --> I["return None (unbounded)"]
    E --> J["None if value is None or negative"]
    G --> J
    I --> J
    J --> K["get_usable_length(new_seq_length, layer_idx)"]
Loading

3. Failure and ambiguity contract

Situation Before After
Attribute lookup before _modules exists RecursionError AttributeError from the original exception
Inner model present, attribute missing on wrapper forwarded to model forwarded to model (unchanged)
Cache has no layer and no shape query AttributeError (shim absent) None = unbounded
Dynamic layer reports -1 n/a (shim absent) None, matching transformers 4 semantics
Cache-level get_max_cache_shape present (older 5.x) used still used

4. Test-side items

Each was reproduced first; none changes library behaviour.

Test Cause Change
kernels/test_awq_machete_group_size.py mocked (True, None) stayed in the class-level cached_validate_once lru-cache after monkeypatch.undo(), breaking two test_selection.py nodes fixture clears both caches on teardown
test_machete_jit.py layout tests (5) MacheteLinear.__init__ validates the kernel, so a host without the compiled extension cannot allocate the checkpoint buffers fixture marks the extension as built (classmethod replaced, real lru-cache untouched)
test_machete_jit.py::...build_only... fails with Ninja is required when ninja is absent skip when ninja is missing
module_tree/test_moe_expert_coverage.py[bailing_hybrid] BailingMoeQModel now declares the alternate remote attention.* branch for native bailing_hybrid (self_attn.*) accept the alternate root only while the primary root resolves on some layer
test_torch_cpu_avx512{,_awq}.py oracle tests (4) #4178 keeps the checkpoint scales dtype; FP32 affine metadata is scales_and_zeros assert scales.dtype == checkpoint_scale_dtype and scales_and_zeros.dtype == float32
test_torch_cpu_avx512_awq.py::...train_mode... (1) reference rounded the weight/accumulation in BF16, adding a second rounding compare against x.float() @ w.float() + bias rounded once, bounded by one output ulp
kernels/test_ret_idx_cache_invalidation.py load_assign (4) state_dict() emits the #4091 checkpoint snapshot layout, not the live runtime layout drive the wider-dtype load from the live packed buffers
kernels/test_w4afp8_gb10.py qzeros_format is the in-process marker every GPTQ kernel emits add it to the expected key set (checkpoint writes strip it)
test_exllamav3_torch_padding.py (2) BF16 routes to _torch_inner by design assert the refreshed handle of the path the dtype uses
test_gguf_all_formats.py (i) formats with no quantizer on the host failed instead of skipping; (ii) C++ kernel construct failed when the llama.cpp shared library cannot load; (iii) the dense expectation pre-rounded the weight, double-rounding skip on missing quantizer/C++ runtime with a precise reason; compare BF16/FP16 against a one-ulp bound of the exact product (FP32 keeps the strict tolerance)
test_split_by_layer_save.py _DummyQuantizeConfig lacked has_dynamic_exclusions add it, mirroring QuantizeConfig
test_subset_plan.py the looper mock returned a truthy layer_modules_for_prefix, replacing the caller's blocks stub it to None (flat declaration)
test_hf_config_compat.py warning goes through logbar, not stdout/stderr observe it with caplog
test_nf12_kernel_manifest.py (5) mlx_nf12 imports MLX at module scope skip the resolution when MLX is absent; the claim table is still asserted unconditionally

5. Tests / guarantees

Test Invariant
tests/test_base_qmodel_getattr_recursion.py (new, 4) bare/partially constructed instances raise AttributeError; forwarding to the inner model still works; an early hasattr probe in __init__ does not recurse
tests/test_hf_config_compat.py::test_normalize_hf_config_compat_restores_legacy_cache_length_helpers shim installs on 5.22, reads the layer API, reports None for dynamic layers
tests/module_tree/test_moe_expert_coverage.py every quantizable spec resolves, or is a declared alternate branch whose primary branch resolves
tests/test_gguf_all_formats.py::test_gguf_kernel_independent_packed_oracle BF16/FP16 stay within one visible rounding step of the exact FP32 product

6. Validation

Exact commands, run on def6e61e3 plus this branch:

pytest tests/test_hf_config_compat.py tests/test_nf12_kernel_manifest.py \
  tests/test_machete_jit.py tests/kernels/test_awq_machete_group_size.py \
  tests/kernels/test_selection.py tests/kernels/test_ret_idx_cache_invalidation.py \
  tests/kernels/test_w4afp8_gb10.py tests/module_tree/test_moe_expert_coverage.py \
  tests/test_exllamav3_torch_padding.py tests/test_gguf_all_formats.py \
  tests/test_split_by_layer_save.py tests/test_subset_plan.py \
  tests/test_torch_cpu_avx512.py tests/test_torch_cpu_avx512_awq.py \
  tests/test_locateanything_support.py tests/test_base_qmodel_getattr_recursion.py \
  tests/test_legacy_generation_compat.py tests/test_bailing_hybrid_support.py \
  -q -p no:randomly
-> 768 passed, 752 skipped

ruff check on every touched file: clean.

Before/after on the affected nodes (same host, same interpreter):

Node group Failures at def6e61e3 This branch
test_awq_machete_group_size.py + test_selection.py -k "Machete or group_size" 2 failed 16 passed, 3 skipped
test_moe_expert_coverage.py[bailing_hybrid] 1 failed 27 passed
test_torch_cpu_avx512.py / _awq.py 5 failed 68 passed
test_nf12_kernel_manifest.py 5 failed 22 passed, 5 skipped
test_machete_jit.py 6 failed 33 passed, 3 skipped
test_hf_config_compat.py 2 failed 49 passed
test_split_by_layer_save.py, test_subset_plan.py 2 failed 14 passed
test_ret_idx_cache_invalidation.py 4 failed 76 passed
test_exllamav3_torch_padding.py 2 failed 129 passed
test_gguf_all_formats.py 118 failed 136 passed, 564 skipped
test_base_qmodel_getattr_recursion.py RecursionError (new test) 4 passed

An additional sweep of tests/module_tree reports 17 failures, which reproduce unchanged at def6e61e3: 9 native-fusion kernel cases, 4 llama-fusion storage cases, glm4v leaf coverage, nemotronh_nano_omni MoE tags, jamba shared-input planning, and one falcon-Mamba AWQ fold. They are out of scope for this issue.

7. Reviewer notes

  • Skips are narrow and name the missing dependency/provider in the reason; nothing is blanket-skipped, and each skipped case keeps its availability contract asserted elsewhere (for example the MLX claim table).
  • The _missing_specs alternate-branch rule is explicit per model type, not a generic "ignore anything that misses" escape: it still fails when neither branch resolves.
  • docs/transformers-5-compat.md § J.7 carries the same flow diagram and the before/after table for the cache shim.

Validation was run on the affected node groups only; a full-suite sweep was not attempted.

Each item in #4358 was reproduced at def6e61 and classified before editing.
Two are library defects rather than stale tests:

- `BaseQModel.__getattr__` probed `hasattr(self, "_modules")`. During
  `__init__` and on fixtures built with `object.__new__`, that probe re-enters
  the hook forever, so any unrelated attribute lookup raised `RecursionError`
  and a test teardown spent minutes formatting the traceback. Read the
  container from `__dict__` instead.
- `_patch_transformers_remote_code_compat` gated the legacy cache-length shim
  on `Cache.get_max_cache_shape`, which transformers 5.22 also removed (the
  query moved to `CacheLayerMixin.get_max_length`). Every remote decode that
  asks the cache for its limit still raised `AttributeError`. Install from the
  layer API, and fall back to `None` when no shape query exists.

The remaining items are test-side:

- Machete group-size test: mock `cached_validate_once` in a fixture that
  clears both caches on teardown, so the mocked Hopper answer no longer leaks
  into `test_selection.py`.
- Machete JIT layout tests: treat the extension as built, and skip the build
  smoke test when `ninja` is missing.
- MoE expert coverage: `bailing_hybrid` legitimately declares the alternate
  remote `attention.*` branch next to native `self_attn.*`; accept it only
  while the primary branch resolves on some layer.
- `scales` keeps the loaded checkpoint dtype since #4178; the FP32 affine
  metadata lives in `scales_and_zeros`. Assert the packed tensor, not the
  checkpoint buffer, and compare the BF16 training fallback against a single
  FP32-rounded reference.
- `state_dict()` emits the checkpoint snapshot layout (#4091), so the
  runtime-layout `load_assign` case is driven from the live packed buffers.
- Add `qzeros_format` to the W4A-FP8 `state_dict()` expectation; checkpoint
  writes strip it.
- EXL3 bias-refresh test: BF16 goes through `_torch_inner` by design, so
  assert against the handle the chosen path owns.
- GGUF: skip formats this host cannot quantize (no `gguf`, no working ggml
  runtime) instead of failing, skip the C++ kernel when its shared library
  does not load, and compare the BF16/FP16 single-rounding paths against a
  one-ulp bound of the exact product.
- `_DummyQuantizeConfig` gains `has_dynamic_exclusions`, and the subset-plan
  test stubs `layer_modules_for_prefix`.
- `test_hf_config_compat` observes the warning through `caplog`: the library
  logger writes to a logbar sink, not to the captured stdout/stderr.
- NF12 MLX manifest test: skip a claimed variant when MLX is not installed;
  the claim table itself is still asserted unconditionally.

docs/transformers-5-compat.md records the cache-shim flow change.
@Qubitium

Copy link
Copy Markdown
Collaborator

@ZX-ModelCloud conflict

…regressions

# Conflicts:
#	tests/test_gguf_all_formats.py
@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

CI note: AWQ CPU (unit) fails tests/test_awq_weight_mean.py (9 nodes). All 9 reproduce identically at 0600c0a8e without this branch — the mocks in that file are stale against the current quantize() keyword signature (sym/syms). This branch does not touch that file or the AWQ search path, so it is pre-existing and tracked separately.

Everything else is green: ruff-check, Analyze, CodeQL, AWQ CPU (dense), AWQ CPU (moe).

@Qubitium
Qubitium merged commit ae89c3d into main Nov 16, 2026
8 of 9 checks passed
@Qubitium
Qubitium deleted the fix/4358-test-triage-regressions branch November 16, 2026 11:52
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.

[TEST] CUDA test-suite triage at 842d666 (RTX 5090): test regressions from this round's fix commits, plus stale tests not in #4241/#4351

2 participants