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.

Keep torch's bundled flash on Blackwell for short documents under UNSLOTH_FLASH_ATTENTION_IMPL=auto (#13631)

Daniel Han95526e49aea7
diff --git a/tests/utils/test_flash_impl.py b/tests/utils/test_flash_impl.py
index ec148884c29..47e50a9050c 100644
--- a/tests/utils/test_flash_impl.py
+++ b/tests/utils/test_flash_impl.py
@@ -406,6 +406,135 @@ def test_flash_impl_allows_reads_torch_active_impl(monkeypatch):
assert fi.flash_impl_allows(256, None, torch.device("cuda", 0))
[email protected]("mean_len", [150.0, 700, 1023])
+def test_blackwell_auto_keeps_bundled_flash_for_short_documents(fake, monkeypatch, mean_len):
+ assert fi.maybe_activate_flash_attention_impl(_model(), mean_document_length = mean_len) is None
+ assert fake.probes == [] and fake.current_impl is None
+ assert f"{mean_len:.0f}" in fi.FLASH_IMPL_STATE["reason"]
+ for long_or_unknown in (fi._BLACKWELL_AUTO_MIN_MEAN_DOC_LEN, 8192, None):
+ assert (
+ fi.maybe_activate_flash_attention_impl(_model(), mean_document_length = long_or_unknown)
+ == "FA4"
+ )
+ assert fi.maybe_activate_flash_attention_impl(_model(), mean_document_length = mean_len) is None
+ assert fake.current_impl is None and fi.FLASH_IMPL_STATE["active"] is None
+ monkeypatch.setenv(fi._ENV, "fa4")
+ assert fi.maybe_activate_flash_attention_impl(_model(), mean_document_length = mean_len) == "FA4"
+ fi.deactivate_flash_attention_impl()
+ monkeypatch.setenv(fi._ENV, "auto")
+ monkeypatch.setattr(fi, "_device_majors", lambda: {9})
+ assert fi.maybe_activate_flash_attention_impl(_model(), mean_document_length = mean_len) == "FA3"
+ fi.deactivate_flash_attention_impl()
+
+
+def test_mean_document_length_reads_packed_and_padding_free_rows():
+ datasets = pytest.importorskip("datasets")
+ packed = datasets.Dataset.from_dict(
+ {"input_ids": [[1] * 8, [1] * 6], "seq_lengths": [[3, 5], [6]]}
+ )
+ assert fi._mean_document_length(packed) == pytest.approx(14 / 3)
+ packed.set_format("torch")
+ assert fi._mean_document_length(packed) == pytest.approx(14 / 3)
+ rows = datasets.Dataset.from_dict({"input_ids": [[1] * 100, [1] * 300], "labels": [[1], [1]]})
+ assert fi._mean_document_length(rows) == 200
+ assert fi._mean_document_length(rows, rows = 1) == 100
+ longest_first = datasets.Dataset.from_dict(
+ {"input_ids": [[1] * n for n in (400, 300, 200, 100)]}
+ )
+ assert fi._mean_document_length(longest_first, rows = 2) == 250
+ # The sample reaches the tail when the size is not a multiple of rows: 128 x 1200 then 72 x 100.
+ tail = datasets.Dataset.from_dict({"input_ids": [[1] * 1200] * 128 + [[1] * 100] * 72})
+ assert fi._mean_document_length(tail) < 1024
+ mixed = datasets.Dataset.from_dict(
+ {"input_ids": [[1] * 8, [1] * 6], "seq_lengths": [[3, 5], None]}
+ )
+ assert fi._mean_document_length(mixed) == pytest.approx(14 / 3)
+ # The last row is always sampled: 128 one-document rows, then one row of many short documents.
+ last = datasets.Dataset.from_dict(
+ {
+ "input_ids": [[1] * 1024] * 128 + [[1] * 1024],
+ "seq_lengths": [[1024]] * 128 + [[8] * 128],
+ }
+ )
+ assert fi._mean_document_length(last) < 1024
+ # Columns hidden by the format are not read: the collator sees one document per row.
+ hidden = datasets.Dataset.from_dict({"input_ids": [[1] * 8192], "seq_lengths": [[64] * 128]})
+ hidden.set_format("torch", columns = ["input_ids"])
+ assert fi._mean_document_length(hidden) == 8192
+ empty = datasets.Dataset.from_dict(
+ {"input_ids": [[1] * 100, [1] * 300], "seq_lengths": [[], []]}
+ )
+ assert fi._mean_document_length(empty) == 200
+ custom = datasets.Dataset.from_dict({"input_ids": [[1] * 2000], "doc_lens": [[100] * 20]})
+ assert fi._mean_document_length(custom, key = "doc_lens") == 100
+ assert fi._mean_document_length(custom) == 2000
+ assert fi._mean_document_length(None) is None
+ assert fi._mean_document_length(datasets.Dataset.from_dict({"text": ["a"]})) is None
+ assert fi._mean_document_length(rows.select([])) is None
+ streamed = rows.to_iterable_dataset()
+ assert fi._mean_document_length(streamed) is None
+
+
+def test_mean_document_length_with_dataset_transforms_is_unknown():
+ datasets = pytest.importorskip("datasets")
+ calls = [0]
+
+ def truncate(batch):
+ calls[0] += 1
+ return {"input_ids": [ids[:10] for ids in batch["input_ids"]]}
+
+ stored = datasets.Dataset.from_dict({"input_ids": [[1] * 4096, [1] * 4096]}).with_transform(
+ truncate
+ )
+ assert fi._mean_document_length(stored) is None
+
+ def tokenize(batch):
+ calls[0] += 1
+ return {"input_ids": [[1] * len(text) for text in batch["text"]]}
+
+ raw = datasets.Dataset.from_dict({"text": ["a" * 100]}).with_transform(tokenize)
+ assert fi._mean_document_length(raw) is None
+ assert calls[0] == 0
+
+
+def test_document_length_only_read_under_auto_on_sm100(fake, monkeypatch):
+ calls = []
+
+ def length():
+ calls.append(1)
+ return 100
+
+ for requested, majors in (("fa4", {10}), ("auto", {9}), ("off", {10})):
+ monkeypatch.setenv("UNSLOTH_FLASH_ATTENTION_IMPL", requested)
+ monkeypatch.setattr(fi, "_device_majors", lambda majors = majors: majors)
+ fi.maybe_activate_flash_attention_impl(_model(), mean_document_length = length)
+ fi.deactivate_flash_attention_impl()
+ assert calls == []
+ monkeypatch.setenv("UNSLOTH_FLASH_ATTENTION_IMPL", "auto")
+ monkeypatch.setattr(fi, "_device_majors", lambda: {10})
+ assert fi.maybe_activate_flash_attention_impl(_model(), mean_document_length = length) is None
+ assert calls == [1]
+
+
+def test_scope_to_train_reads_the_train_dataset_document_length(fake):
+ datasets = pytest.importorskip("datasets")
+ seen = []
+
+ class Trainer:
+ def train(self):
+ seen.append(fake.current_impl)
+
+ short = datasets.Dataset.from_dict({"input_ids": [[1] * 8], "seq_lengths": [[200] * 40]})
+ long = datasets.Dataset.from_dict({"input_ids": [[1] * 8], "seq_lengths": [[4096, 4096]]})
+ for dataset in (short, long, None):
+ trainer = Trainer()
+ trainer.model, trainer.train_dataset = _model(), dataset
+ fi.scope_flash_attention_impl_to_train(trainer, trainer.model)
+ trainer.train()
+ assert seen == [None, "FA4", "FA4"] and fake.current_impl is None
+ assert len(fake.probes) == 1
+
+
def _fa4_ready():
if not has_real_cuda() or torch.version.hip is not None:
return False
diff --git a/unsloth/utils/flash_impl.py b/unsloth/utils/flash_impl.py
index 26f9d2bba60..7755473ab83 100644
--- a/unsloth/utils/flash_impl.py
+++ b/unsloth/utils/flash_impl.py
@@ -50,6 +50,10 @@ FLASH_IMPL_STATE = {"active": None, "reason": None, "verdicts": {}, "logged": se
_HOPPER_AUTO_MIN_HIDDEN = 2048
_logger = logging.getLogger(__name__)
+# B200/FA4: ~0.1 ms extra host time per call makes short-document packed SFT 8-11% slower than bundled flash.
+# 1024 matches attention_dispatch._VARLEN_CUDNN_MAX_MEAN_LEN.
+_BLACKWELL_AUTO_MIN_MEAN_DOC_LEN = 1024
+
def _requested():
value = os.environ.get(_ENV, "auto").strip().lower()
@@ -396,8 +400,9 @@ def _probe_error(impl, cases, activate, restore):
return None
-def maybe_activate_flash_attention_impl(model = None):
- """Returns the active impl or None. Never call while a backward is pending."""
+def maybe_activate_flash_attention_impl(model = None, mean_document_length = None):
+ """Returns the active impl or None. Never call while a backward is pending.
+ mean_document_length: float, lazy callable (sm100 auto only) or None if unknown."""
requested = _requested()
registry = _registry()
if requested is None or registry is None:
@@ -428,6 +433,20 @@ def maybe_activate_flash_attention_impl(model = None):
)
deactivate_flash_attention_impl()
return None
+ if requested == "auto" and major == 10 and callable(mean_document_length):
+ mean_document_length = mean_document_length()
+ if (
+ requested == "auto"
+ and major == 10
+ and mean_document_length is not None
+ and mean_document_length < _BLACKWELL_AUTO_MIN_MEAN_DOC_LEN
+ ):
+ FLASH_IMPL_STATE["reason"] = (
+ f"auto keeps torch's bundled flash on sm100 for documents averaging under "
+ f"{_BLACKWELL_AUTO_MIN_MEAN_DOC_LEN} tokens ({mean_document_length:.0f}); {_ENV}=fa4 opts in"
+ )
+ deactivate_flash_attention_impl()
+ return None
facts = model_facts(model) if model is not None else (False, [], None, None, None, None)
cases = _probe_cases(facts)
# auto falls through to the next impl when one is missing, refuses this model or fails its probe.
@@ -477,7 +496,57 @@ def deactivate_flash_attention_impl():
pass
-def scope_flash_attention_impl_to_train(trainer, model) -> None:
+def _sampled_rows(dataset, indices, key):
+ # Custom transform = unknown: rows may differ from storage and running it early advances its RNG.
+ format = getattr(dataset, "format", None) or {}
+ if format.get("type") == "custom":
+ return None
+ columns = set(dataset.column_names)
+ if format.get("columns") is not None and not format.get("output_all_columns", False):
+ columns &= set(format["columns"])
+ wanted = [c for c in dict.fromkeys((key, "input_ids")) if c in columns]
+ if not wanted:
+ return None
+ return list(dataset.with_format(None).select_columns(wanted).select(indices))
+
+
+def _mean_document_length(
+ dataset,
+ rows = 128,
+ key = "seq_lengths",
+):
+ # Rows spread across the dataset: TRL BFD puts the longest documents first.
+ try:
+ total = len(dataset)
+ if total <= 0:
+ return None
+ n = min(rows, total)
+ indices = sorted({i * (total - 1) // (n - 1) for i in range(n)}) if n > 1 else [0]
+ sample = _sampled_rows(dataset, indices, key)
+ if sample is None:
+ return None
+ lengths = []
+ for row in sample:
+ per_document = row.get(key)
+ if per_document is None:
+ ids = row.get("input_ids")
+ if ids is None:
+ continue
+ per_document = [len(ids)]
+ lengths.extend(int(x) for x in per_document)
+ if not lengths:
+ lengths = [len(row["input_ids"]) for row in sample if row.get("input_ids") is not None]
+ except Exception:
+ return None
+ lengths = [x for x in lengths if x > 0]
+ return sum(lengths) / len(lengths) if lengths else None
+
+
+def scope_flash_attention_impl_to_train(
+ trainer,
+ model,
+ sequence_lengths_key = "seq_lengths",
+) -> None:
"""Active only during trainer.train: FA4's launch cost makes decode attention ~6x slower."""
if trainer is None or getattr(trainer, "_unsloth_flash_impl_wrapped", False):
return
@@ -492,7 +561,10 @@ def scope_flash_attention_impl_to_train(trainer, model) -> None:
activated = None
try:
activated = maybe_activate_flash_attention_impl(
- getattr(trainer, "model", None) or model
+ getattr(trainer, "model", None) or model,
+ mean_document_length = lambda: _mean_document_length(
+ getattr(trainer, "train_dataset", None), key = sequence_lengths_key
+ ),
)
except Exception as exc:
FLASH_IMPL_STATE["reason"] = f"activation error ({type(exc).__name__}: {exc})"
diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.py
index b91ae1bfbe4..bf4011e3e8b 100644
--- a/unsloth/utils/packing.py
+++ b/unsloth/utils/packing.py
@@ -203,10 +203,14 @@ def _enable_hf_packed_attention() -> None:
logging.getLogger(__name__).info(f"Unsloth: packed varlen attention not enabled ({exc})")
-def _scope_flash_attention_impl(model, trainer) -> None:
+def _scope_flash_attention_impl(
+ model,
+ trainer,
+ sequence_lengths_key = "seq_lengths",
+) -> None:
try:
from .flash_impl import scope_flash_attention_impl_to_train
- scope_flash_attention_impl_to_train(trainer, model)
+ scope_flash_attention_impl_to_train(trainer, model, sequence_lengths_key)
except Exception as exc:
logging.getLogger(__name__).info(f"Unsloth: flash attention impl not scoped ({exc})")
@@ -237,7 +241,7 @@ def enable_sample_packing(
if collator is None or not hasattr(collator, "torch_call"):
return
_enable_hf_packed_attention()
- _scope_flash_attention_impl(model, trainer)
+ _scope_flash_attention_impl(model, trainer, sequence_lengths_key)
if getattr(collator, "_unsloth_packing_wrapped", False):
return