Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Block compile: drop a caller's strict mark_dynamic so Qwen3.8-Flash-Next layers stay compiled (#17609)

Daniel Hanf1c5502baa9b
diff --git a/tests/test_block_compile.py b/tests/test_block_compile.py
index 49983713506..572fa8a7115 100644
--- a/tests/test_block_compile.py
+++ b/tests/test_block_compile.py
@@ -1950,3 +1950,59 @@ def test_parametrized_class_is_reused_per_module(monkeypatch):
assert type(b) is not seen[0] and torch.equal(
b.weight, 2 * b.parametrizations["weight"].original
)
+
+
+def test_relax_strict_dynamic_aliases_only_marked_tensors():
+ M = _load()
+ ids = torch.zeros(2, 16, dtype = torch.long)
+ torch._dynamo.mark_dynamic(ids, 1)
+ other = torch.zeros(2, 16)
+ pos = (torch.zeros(1, 16), torch.zeros(1, 16))
+ out = M._relax_strict_dynamic((other, pos, {"ple_input_ids": ids, "x": None}))
+ assert out[0] is other and out[1] is pos
+ alias = out[2]["ple_input_ids"]
+ assert alias is not ids and alias.data_ptr() == ids.data_ptr() and alias.shape == ids.shape
+ assert not getattr(alias, "_dynamo_dynamic_indices", None)
+ assert ids._dynamo_dynamic_indices == {1} # the caller's tensor keeps its own mark
+ unmarked = (other, {"a": other})
+ assert M._relax_strict_dynamic(unmarked) is unmarked
+
+
+def test_strict_marked_kwarg_does_not_demote_the_block(monkeypatch, capsys):
+ """Qwen4Exp passes input_ids (strictly marked by unsloth_zoo's loss bookkeeping) into every block as
+ ple_input_ids; a length the block specialized raised ConstraintViolationError and the layer kind fell
+ back to the stock forward."""
+ M = _load()
+ real_compile = torch.compile
+ monkeypatch.setattr(
+ torch,
+ "compile",
+ lambda fn, **kwargs: real_compile(fn, backend = "eager", fullgraph = False, dynamic = None),
+ )
+ torch._dynamo.reset()
+
+ class PleDecoderLayer(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj = torch.nn.Linear(8, 8)
+
+ def forward(
+ self,
+ hidden_states,
+ ple_input_ids = None,
+ **kwargs,
+ ):
+ out = self.proj(hidden_states)
+ if ple_input_ids.shape[1] == 16: # a block that specializes the length
+ out = out + 1
+ return out
+
+ M._wrap(PleDecoderLayer, {})
+ layer = PleDecoderLayer().train()
+ x = torch.randn(2, 16, 8, requires_grad = True)
+ ids = torch.zeros(2, 16, dtype = torch.long)
+ torch._dynamo.mark_dynamic(ids, 1)
+ layer(x, ple_input_ids = ids).sum().backward()
+ torch._dynamo.reset()
+ assert "block compile failed" not in capsys.readouterr().out
+ assert layer._unsloth_block_mode != M._OFF
diff --git a/unsloth/models/_block_compile.py b/unsloth/models/_block_compile.py
index 6f12fa59ddb..278867a88cf 100644
--- a/unsloth/models/_block_compile.py
+++ b/unsloth/models/_block_compile.py
@@ -816,6 +816,24 @@ def _rebind_class(cls):
setattr(cls, key, new)
+def _relax_strict_dynamic(obj):
+ """Alias tensors that carry a caller's strict mark_dynamic so the block only sees its own maybe marks.
+
+ unsloth_zoo marks input_ids dim 1 for its loss bookkeeping, and Qwen4Exp passes input_ids into every
+ block as ple_input_ids. A length the block specializes then raised ConstraintViolationError and demoted
+ the layer kind to the stock forward. A view drops the mark (it lives on the tensor object), not the data.
+ """
+ if isinstance(obj, torch.Tensor):
+ return obj.view(obj.shape) if getattr(obj, "_dynamo_dynamic_indices", None) else obj
+ if type(obj) in (tuple, list):
+ new = [_relax_strict_dynamic(o) for o in obj]
+ return obj if all(a is b for a, b in zip(new, obj)) else type(obj)(new)
+ if type(obj) is dict:
+ new = {k: _relax_strict_dynamic(v) for k, v in obj.items()}
+ return obj if all(new[k] is obj[k] for k in obj) else new
+ return obj
+
+
def _mark_seq_dynamic(seq_len, obj):
if isinstance(obj, torch.Tensor):
# A float tensor's last dim is a width even when it equals seq_len (mrope ids are int).
@@ -1659,6 +1677,7 @@ def _wrap(
if _GDN_OP[0] is None and hasattr(self, "linear_attn"):
_prepare_gdn(self, hidden_states)
if hidden_states.dim() == 3 and hidden_states.shape[1] > 1:
+ hidden_states, args, kwargs = _relax_strict_dynamic((hidden_states, args, kwargs))
_mark_seq_dynamic(hidden_states.shape[1], (hidden_states, args, kwargs))
if _DYNAMIC_BATCH and hidden_states.shape[0] > 1:
_mark_batch_dynamic(hidden_states.shape[0], (hidden_states, args, kwargs))