Repository navigation
[PyTorch] Fix strict load_state_dict for te.ops.Linear without bias - #3915
bhargavchintam wants to merge 2 commits into
Conversation
Linear._load_from_state_dict added state_dict["bias"] = None when the op had no bias. torch leaves None parameters out of the keys it expects, so a strict load reported the added key as unexpected, and a bias-free te.ops.Linear could not load the state dict it had just saved. Add the bias key only when the op has a bias. Run TestCheckpointing.test_linear with bias=False as well as bias=True. Signed-off-by: Bindu Bhargava R Chintam <bindubhargavareddy@gmail.com>
[Low impact] The PR appears safe to merge; no actionable issues were found. SummaryFixes strict checkpoint loading for bias-free
Reviews (2) · Last reviewed commit: "[PyTorch] Test strict load of a bias che..." · Reviewed by Greptile |
lxcxjxhx
left a comment
There was a problem hiding this comment.
Looks right, and I checked the two things that usually make a fix of this shape incomplete.
Is the pattern repeated in the sibling ops? No. state_dict[...] = None inside _load_from_state_dict exists only in ops/linear.py:214 across transformer_engine/pytorch/ops/*.py, so fixing Linear alone is the whole fix rather than the first of several.
if self._bias_idx is not None and f"{prefix}bias" not in state_dict:
state_dict[f"{prefix}bias"] = state_dict[f"{prefix}basic_ops.{self._bias_idx}.bias"]Is dropping the None insertion safe for the reverse direction? A model with bias=False now leaves a checkpoint's bias key alone, so a bias-carrying checkpoint loaded into a bias-free op fails strict load as an unexpected key — which is the correct strict-load answer, and it is the same failure class the old code produced (the inserted None never matched either). Worth one sentence in the description so the next reader does not read it as a regression.
The parametrisation covers what the issue reports: bias × quantization × quantized_weight turns the single passing case into six, and the bias-free six are exactly the ones that failed on main before this change.
One thing I could not check here: the test needs a GPU and the compiled extension, so I did not run it — the reasoning above is from the diff plus a grep for the pattern.
|
Thanks for checking the sibling ops. I added the reverse case to the description. A |
|
@timmoon10, this is a two-line fix in |
lxcxjxhx
left a comment
There was a problem hiding this comment.
The fix matches the reported failure, and the new bias parametrisation is the right shape for a round-trip test. Two things I would add before this goes in.
1. The mismatch direction is described in the description but not asserted. The body says:
Loading a
bias=Truecheckpoint into a bias-free op still fails a strict load, as it should. With this change the unexpected keys are0.basic_ops.1.biasand0.basic_ops.1._extra_state.
That behaviour is exactly what the change trades against: the fix works by not putting a key into state_dict, so the property worth pinning is that a bias which really exists in the checkpoint is still reported. Nothing in the test does that — model_load.load_state_dict(state_dict["model"]) at line 4655 is the same-bias round trip only. A three-line addition next to the parametrisation covers it:
if bias:
with pytest.raises(RuntimeError, match="Unexpected key"):
te_ops.Linear(in_features, out_features, bias=False, ...).load_state_dict(...)Without it, a later "silence the remaining unexpected keys" change would drop a trained bias and every test would still pass.
2. The weight branch directly above still indexes unconditionally. After this PR the two branches read:
if f"{prefix}weight" not in state_dict:
state_dict[f"{prefix}weight"] = state_dict[f"{prefix}basic_ops.{self._linear_idx}.weight"] # KeyError if absent
if self._bias_idx is not None and f"{prefix}bias" not in state_dict:
state_dict[f"{prefix}bias"] = state_dict[f"{prefix}basic_ops.{self._bias_idx}.bias"]So a partial state_dict (one that has neither prefix + "weight" nor the corresponding basic-op weight — e.g. someone loading a checkpoint that legitimately lacks that layer) now raises KeyError: '…basic_ops.N.weight' from inside the hook. torch normally answers that case with Missing key(s) in state_dict, which names the layer and the missing key; a bare KeyError from a _load_from_state_dict hook is much harder to read. Guarding the source key the same way the bias branch guards its target would keep the two branches symmetric:
if f"{prefix}weight" not in state_dict and f"{prefix}basic_ops.{self._linear_idx}.weight" in state_dict:I am not asking for it in this PR if it is out of scope — it is the same class of defect, one line away, and worth deciding either way.
For completeness: _extra_state does not appear anywhere in linear.py (grep: 0 hits), so the 0.basic_ops.1._extra_state in your unexpected-keys list comes from the basic ops, not from this hook — I checked before raising (2), in case the same "insert a key the loader does not expect" pattern existed there too.
…thout bias The load hook no longer adds a bias key for an op without bias. Check that a strict load of a bias=True checkpoint into such an op still fails on the checkpoint's bias keys, so a trained bias is not dropped silently. Signed-off-by: Bindu Bhargava R Chintam <bindubhargavareddy@gmail.com>
|
Added in 6430df8. For The weight lookup also breaks |
Description
A bias-free
te.ops.Linearcan't load the state dict it just saved with a strictload_state_dict. It fails withUnexpected key(s) in state_dict: "0.bias".Linear._load_from_state_dictaddedstate_dict["bias"] = Nonewhen the op has no bias. torch leavesNoneparameters out of the keys it expects, so the added key was reported as unexpected. This PR adds the bias key only when the op has a bias.Loading a
bias=Truecheckpoint into a bias-free op still fails a strict load, as it should. With this change the unexpected keys are0.basic_ops.1.biasand0.basic_ops.1._extra_state; main also listed the inserted0.bias. The test now checks this case too, and fails if the load hook drops those keys.Fixes #3914
Type of change
Changes
transformer_engine/pytorch/ops/linear.py:Linear._load_from_state_dictadds{prefix}biasonly when the op has a bias. Two lines replace five.tests/pytorch/test_fusible_ops.py:TestCheckpointing.test_linearis parametrized overbiasin(False, True)and passes it to bothte_ops.Linearconstructions. Forbias=Trueit also loads the checkpoint into a bias-free op and expectsUnexpected key. That check sits inside the existingtry, so the delayed-scaling cases get the pickle setting they need.Testing
On an NVIDIA RTX PRO 6000 Blackwell (compute capability 12.0) in the NGC PyTorch 26.10 container (torch 2.15.0a0, CUDA 13.4, driver 580.196.07), I built TE from main e6f9e86 with
NVTE_FRAMEWORK=pytorch NVTE_CUDA_ARCHS=120 MAX_JOBS=24 python -m pip install -e . -v --no-build-isolation. This PR changes only Python files, so every run below uses that one build with the files swapped in.python -m pytest -v tests/pytorch/test_fusible_ops.py -k "TestCheckpointing and test_linear"with main'sops/linear.pyand this branch's test:The first case again with
--tb=short:The same command on this branch (source tree
41c825fc, the tree of commit 6430df8):The 12 skipped cases are the
nvfp4,nvfp4_4over6andfp8_block_scalingrecipes, which skip on this GPU.To check that the new assertion catches what it is for, I changed
Linear._load_from_state_dictto delete checkpoint keys for basic ops the op doesn't have, the kind of change that would hide a checkpoint's bias. With that change this branch's test fails everybias=Truecase:The first of them with
--tb=short:The test from before the assertion (commit 71968de) passes with the same change:
The whole file on this branch, as
qa/L0_pytorch_unittest/test.shruns it (python -m pytest tests/pytorch/test_fusible_ops.py):The same 84 tests fail with main's
ops/linear.py(84 failed, 13 warnings in 5.99s), and they are the same 84 as in the first run of this PR, so none of them comes from this change. They arefp8_delayed_scalingcases oftest_activation(36),test_layernorm_mlp(24),test_clamped_swiglu(16) andtest_swiglu(8). All of them stop incast_gated_tmawith "Only rowwise cast supported in this function" on this GPU.TE_PATH=$PWD PYTHON_ONLY=1 bash qa/L0_pytorch_lint/test.shon this branch:pre-commit run --from-ref origin/main --to-ref HEADon this branch:TE_PATH="$PWD" bash qa/L0_license/test.shexits 0 on a clean checkout of this branch. The MXFP8 recipe did not run: the test file adds it only whenmxfp8_availableis true, and it is false on this GPU.Checklist: