Skip to content

Fix hybrid packing gate for qwen3_5 + LoRA: probe the trainer's model, not get_base_model() - #18526

Open
BlagonravovSL wants to merge 1 commit into
unslothai:mainfrom
BlagonravovSL:fix/hybrid-packing-gate-lora
Open

BlagonravovSL wants to merge 1 commit into
unslothai:mainfrom
BlagonravovSL:fix/hybrid-packing-gate-lora

Conversation

@BlagonravovSL

Copy link
Copy Markdown
Contributor

Hybrid packing is never enabled for qwen3_5 + LoRA: the gate probes get_base_model()

Summary. With packing=True and UNSLOTH_EXPERIMENTAL_HYBRID_PACKING=1 the trainer always reports
Unsloth: packing=True ignored (qwen3_5 (packed rows) mixes tokens across packed documents).
The varlen shim is installed successfully right before the gate, but the gate probes
model.get_base_model(), where the shim is not visible, so it answers mixes for a model that
does keep packed documents apart.

Environment.

  • unsloth 2026.11.7, Studio 0.1.920-beta
  • torch 2.11.0+rocm7.14.0, HIP 7.14.60850, gfx1151 (Radeon 8060S, 64 GB for GPU)
  • transformers 5.5.4, Windows 11
  • model empero-ai/Qwen3.8-4B-Distill (qwen3_5 hybrid: GDeltanet + full attention), LoRA r=16

Where it happens (unsloth/trainer.py, sha 022b2e0 = current main):

hybrid_varlen_active = patch_hybrid_linear_attention_varlen(model)   # 2116, shim installed here
...
packed_rows = _packed_rows_verdict(model, model_config)              # 2224, gate

and inside _packed_rows_verdict:

target = model.get_base_model() if callable(getattr(model, "get_base_model", None)) else model
probe = target if unknown else getattr(target, "model", None)
if _packing_honored(probe, None, packed_lengths = True):
    return "as_is"
return "mixes"

With LoRA the trainer is handed a PeftModelForCausalLM; get_base_model() unwraps it to
Qwen3_5ForConditionalGeneration (unsloth_compiled_module_qwen3_5). The shim lives on the wrapper.

Measurements - same weights, same probe code, only the probed object differs:

probed object control leak leak/control
PeftModel (what the trainer trains) 0.881 0.0090 0.010
get_base_model() (what the gate probes) 0.881 0.8518 0.967

Second run: 0.017 and 0.968. Library threshold is 0.2.
The shim's own probe passes: probe_runs=1, probe_passed=1, last_probe_rel_err=1.38e-4.

Minimal reproduction (script below):

gate_before_shim   : mixes
patch              : True, probe_passed = 1, last_probe_rel_err = 1.38e-4
boundary PeftModel : ratio 0.0102  passes
boundary base      : ratio 0.9668  fails
gate_after_shim    : mixes        <- bug

Proposed fix. Branch fix/hybrid-packing-gate-lora on BlagonravovSL/unsloth,
commit 2e73839: probe the object the trainer was handed first and fall back to the previous
target. The verdict still requires a passing numeric probe, so nothing is loosened:

probes = []
if isinstance(model, torch.nn.Module):
    probes.append(model)
if not any(probe is candidate for candidate in probes):
    probes.append(probe)
verdict = "mixes"
if any(_honored(candidate) for candidate in probes):
    verdict = "as_is"
elif mrope and any(_honored(candidate, _text_prepended_position_ids) for candidate in probes):
    verdict = "text_prepended"

Verified with the patched file temporarily installed: gate returns mixes before the shim and
as_is after it, on the same model object. Negative control kept - without the shim it still refuses.

Throughput note, in case it matters for the release note: with packing actually enabled on
gfx1151, step time went 85 s -> 119 s (+40 %) while tokens per step rose only ~14 %, so tok/s fell
from ~555 to ~461. Correctness is fine (loss trains normally); the varlen path is just slower than
padding on this device.

Hybrid models pack only when patch_hybrid_linear_attention_varlen reports success,
and the trainer installs that shim before the packed-row gate runs. The shim lives
on the object the trainer was handed, which for LoRA is the Peft wrapper.
_packed_rows_verdict resolves target = model.get_base_model() and probed only that
object, where the shim is not visible, so the gate always answered "mixes" for
qwen3_5 + LoRA and packing was refused:

  Unsloth: packing=True ignored (qwen3_5 (packed rows) mixes tokens across packed documents).

Measured on empero-ai/Qwen3.8-4B-Distill (unsloth 2026.11.7, ROCm 7.14, gfx1151),
same weights, same probe, only the probed object differs:

  PeftModel (what the trainer trains)  leak/control = 0.017   boundaries kept
  get_base_model()                     leak/control = 0.968   documents mixed

Probe the handed-in model first and fall back to the previous backbone target, so
known-model behaviour is unchanged and the verdict still requires a passing numeric
probe. Gate values before/after the shim, on the same model object:

  before: "mixes"   after: "as_is"
@danielhanchen

Copy link
Copy Markdown
Member

Repo tests (CPU, rest-2) fails on this PR only; main passes the same test:

tests/test_mrope_packing_boundary.py::test_probe_runs_once_and_not_when_packing_is_off
E   assert 3 == 2
E    +  where 3 = len([1, 1, 1])

The test counts calls to unsloth.models.rl._packing_honored across one trainer with packing on and one with it off, and expects exactly one probe per packing-capable trainer (2 total). With this change the probe runs a third time, so one of the two trainers now probes twice, most likely once on the trainer's model and once more on the path that previously used get_base_model(). Probing the trainer's model is the right idea here; it just needs to replace the old probe rather than add to it.

danielhanchen added a commit that referenced this pull request Nov 19, 2026
…treaming without diffusers (#18535)

## Summary

`(Python 3.13, diffusion)` fails on `main` for every PR (seen on #18526
and #18348, neither of which touches diffusion). Four tests, from two
recent merges:

```
FAILED tests/test_diffusion_backend.py::test_apply_loras_quant_unbaked_requires_reload
FAILED tests/test_diffusion_backend.py::test_apply_loras_quant_baked_matrix
    Expected regex: 'Reload the model with the adapter selection'
    Actual message: 'This INT8 build was loaded without LoRA adapters, ... Reload the model with the LoRA selection: on the Images page click Reapply ...'
FAILED tests/test_diffusion_te_residency.py::test_release_streams_and_restore_unhooks_with_identical_outputs
    assert 0 == 4   (release('test') == r.mib)
FAILED tests/test_diffusion_te_residency.py::test_a_restore_that_runs_out_of_memory_keeps_streaming
    assert True is False
```

## Root causes

**LoRA reload refusal (#18420).** #18420 turned this refusal into
`LoraReloadRequiredError` and rewrote its message to name the remedy
(Reapply on the Images page, or `loras` in `/images/load`). The routes
key on the type (`X-Unsloth-Refusal: lora-reload`, `error.code =
"lora_reload_required"`). The two tests still matched the old wording.
The behaviour is intended; the tests pinned prose.

**Encoder residency streaming (#18424).** `EncoderResidency.release()`
streams the text encoders through diffusers' group offloading. The
`(Python 3.13, diffusion)` lane does not install diffusers (the same log
shows `No module named 'diffusers'` skips), so the stream fails,
`release()` correctly keeps the encoders resident and returns 0, and the
two tests that need a real stream fail. The module is right to refuse;
the tests needed diffusers and did not say so.

## Changes

- `test_diffusion_backend.py`: both tests assert
`pytest.raises(LoraReloadRequiredError, match = "Reload the model with
the LoRA selection")`, the typed refusal plus the remedy phrase both
messages share.
- `test_diffusion_te_residency.py`: the two streaming tests are marked
to skip when `importlib.util.find_spec("diffusers") is None`. Only the
absence of diffusers skips: with diffusers installed, a regression in
Unsloth's streaming still fails them. The tests that do not stream (host
RAM refusal, a failed stream putting the encoders back) keep running
everywhere.

Test-only change.

## Testing

- With diffusers 0.43.0 (current release) on a CPU host: `pytest
tests/test_diffusion_te_residency.py tests/test_diffusion_backend.py`:
733 passed, the two streaming tests included.
- Sabotage: raising a plain `LoraSelectionError` instead of
`LoraReloadRequiredError` fails both LoRA tests.
- The no-diffusers lane is the `(Python 3.13, diffusion)` job on this
PR.
Comment thread unsloth/trainer.py

verdict = "mixes"
if _packing_honored(probe, None, packed_lengths = True):
if any(_honored(candidate) for candidate in probes):

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.

Keep a failed wrapper isolation check authoritative

With Qwen3-VL and a PEFT prompt-tuning adapter, the wrapper drops position_ids and fails _packing_honored. The backbone passes, so this any(...) enables packing. On an RTX 3090 with a two-layer model and a real SFTTrainer batch, replacing only document A changed document B’s logits by up to 0.316. The prompt gradient from B differed from running B alone by 80.2% (relative L2). The merge base already accepts this batch. The new wrapper check detects the problem, but its fallback overrides the result.

I tested selecting just the wrapper when PEFT or the hybrid shim wraps the forward, keeping the existing probe for unwrapped models, and caching the verdict on the trainer’s model. Changing A then had zero effect on B’s gradient. The compiled Qwen3.5 LoRA model still passed with the varlen shim, and the existing Qwen2-VL probe-count test passed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants