Skip to content

FastSentenceTransformer: background collation, lean LoRA, decoder packing, ModernBERT FA2 - #17859

Merged
danielhanchen merged 11 commits into
mainfrom
w13-st-decision-eff
Nov 15, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
w13-st-decision-eff

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Faster FastSentenceTransformer training. Each lever has its own off switch.

Changes

Change Off switch
The next batches are tokenized on a background thread, pinned to the training device UNSLOTH_ST_PREFETCH=0
A lean LoRA forward on the encoder path (shared with the decision models) UNSLOTH_ST_LEAN_LORA=0
Qwen3-style decoder embedders on FlashAttention 2 pack the real tokens into one row, then re-pad before pooling. This also covers chat-templated text, and only applies where the transformer writes token_embeddings UNSLOTH_ST_PACKING=0
ModernBERT on transformers 4 picks FlashAttention 2 itself, instead of being forced to SDPA (which turned off its unpadded path) none

Packing stays off where FlashAttention 2 is not available (T4), and on sentence-transformers 6, which already packs itself.

Results

Colab L4, transformers 4.57.6, the sentence-transformers notebooks. Two runs per arm unless noted.

Notebook main ms/step This PR ms/step Change Peak memory, GB
All-MiniLM-L6 186.9 / 182.8 134.8 / 134.6 -27% 2.65 to 2.50
ModernBERT 394.5 / 388.6 334.8 / 337.9 -14% 1.31 to 0.90
BGE-M3 (one run each) 711 633 -11% 11.99 to 11.43
Qwen3-Embedding-0.6B 789.6 / 785.2 595.5 / 594.3 -24.5% 11.79 to 6.15
Qwen3-Embedding-4B (one run each) 4261 2503 -41% 10.65 to 9.69
EmbeddingGemma 6605 / 6607 6191 / 6188 -6.3% unchanged
  • T4 fp16 (Kaggle): MiniLM -26%, BGE-M3 -7%, ModernBERT -3%.
  • transformers 5.17: MiniLM -24%, ModernBERT -7%.
  • Repeat runs on main are bit-identical. This PR vs main drifts by at most 0.1-0.55% relative over 36 steps.
  • tests/test_st_decoder_packing_gpu.py (L4): main fails 3, this PR passes 3. Left- and right-padded batches match the padded run on embeddings and gradients.
  • tests/test_st_training_fast_paths.py: 5 pass.

…coder packing

* Encoder LoRA uses the lean forward decision encoders already had (no PEFT
  per-call checks or fp32 round trip of x); UNSLOTH_ST_LEAN_LORA=0 turns it off.
* SentenceTransformerTrainer tokenizes each batch in its collator on the
  training thread; a background thread now fetches the next batches while the
  current one trains (same batches, same order; UNSLOTH_ST_PREFETCH=0).
* Causal decoder embedders on FlashAttention 2 (Qwen3-Embedding) train on one
  packed row of real tokens with per-row positions, re-padded before pooling;
  sentence-transformers' own flattening needs transformers 5, this covers 4.x
  (UNSLOTH_ST_PACKING=0).
…ntion 2

Forcing SDPA on the fast encoder path turned off ModernBERT's own unpadded
FlashAttention 2 route, so LoRA training ran slower than plain
sentence-transformers (L4: 0.400 s vs 0.369 s per step).
sentence-transformers turns plain text into the message format when the
tokenizer has a chat template, so such embedders never packed.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T20:08:12.226218Z c93230e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9d8b3649b7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +110 to +111
if prefetch_enabled(self) and not isinstance(loader, PrefetchedDataLoader):
loader = PrefetchedDataLoader(loader)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve Accelerate loader handling when resuming checkpoints

When distributed training on an iterable dataset resumes partway through an epoch, Transformers calls accelerate.skip_first_batches() on this wrapper. That function uses isinstance checks for DataLoaderDispatcher and DataLoaderShard, which __getattr__ cannot preserve, so it reconstructs an ordinary SkipDataLoader instead. For the dispatcher used by default with iterable datasets, this drops the dispatch-time sharding and makes every rank consume the underlying unsharded dataset, silently changing the training samples. Preserve Accelerate's loader identity or explicitly handle checkpoint skipping before wrapping it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: the prefetching loader is now an instance of a subclass of the loader's own class (PrefetchedDataShard -> DataLoaderShard, etc.) sharing its state, so accelerate's isinstance dispatch in skip_first_batches rebuilds a real DataLoaderShard / DataLoaderDispatcher on resume. New test test_prefetched_loader_keeps_accelerate_identity_for_resume checks isinstance, the prefetched order, and that skip_first_batches returns a DataLoaderShard yielding the remaining batches.

Comment on lines 3236 to +3239
peft_model = peft_get_peft_model(inner_model, lora_config)
if os.environ.get("UNSLOTH_ST_LEAN_LORA", "1") != "0":
from ._lean_lora import apply_lean_lora
apply_lean_lora(peft_model)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recheck the active adapter before using the lean forward

For a fast encoder that subsequently loads or adds another adapter and selects it with set_adapter(), the newly installed forward continues applying the adapter cached in _unsloth_adapter, regardless of active_adapters. The single-adapter check only runs during installation, so ordinary PEFT adapter switching now silently produces embeddings from the original adapter and can train the wrong parameters. Fall back to PEFT whenever the active adapter set or the single-adapter eligibility conditions change.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: the lean forward now hands off to PEFT whenever the layer holds more than one adapter or the active adapters are not the one cached at install. test_fast_encoder_lora_runs_lean_forward now adds a second adapter, selects it, and checks the output matches PEFT's (it returned the old adapter's output before this commit).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 70495f1f94

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +42 to +43
iterator = source()
for batch in iterator:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep distributed dispatch collectives off the prefetch thread

When distributed training uses an iterable dataset, Accelerate normally returns a DataLoaderDispatcher, whose iteration broadcasts batches across ranks. Running that iterator on this background thread allows its broadcasts to overlap training-thread collectives, such as DDP gradient reductions or MultipleNegativesRankingLoss(gather_across_devices=True). Because queue consumption and thread scheduling differ between ranks, those collectives can be issued in different orders on the same process group, causing collective mismatches or hangs. Preserving the dispatcher's class identity fixes checkpoint skipping but does not serialize these communications; exclude distributed dispatchers from prefetching or prefetch only their underlying CPU collation while keeping dispatch on the training thread.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in the latest commit: prefetch_enabled now returns False whenever a process group with world size > 1 is initialized, so accelerate's dispatcher broadcasts and the shard's RNG sync stay on the training thread. Single-process training keeps the background collation. New test test_prefetch_is_off_under_a_distributed_process_group covers it.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: c93230ea55

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

[skip ci]
@danielhanchen
danielhanchen merged commit 8a1f9b3 into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the w13-st-decision-eff branch November 15, 2026 20:44
danielhanchen added a commit that referenced this pull request Nov 16, 2026
…_dataloader (#17893)

## Summary

`Repo tests (CPU, rest-2)` has failed on `main` since #17859
(FastSentenceTransformer background collation):

```
tests/test_mixed_nvidia_capabilities.py::test_sentence_transformer_trainer_checks_the_placement_before_the_deferred_compile[trainer_init]
tests/test_mixed_nvidia_capabilities.py::test_sentence_transformer_trainer_checks_the_placement_before_the_deferred_compile[before_train]
unsloth/models/sentence_transformer.py:3448: in _patch_sentence_transformer_trainer
unsloth/models/_sentence_transformer_prefetch.py:116:
E   AttributeError: type object 'SentenceTransformerTrainer' has no attribute 'get_train_dataloader'
```

`_patch_sentence_transformer_trainer` now ends with
`patch_train_dataloader(SentenceTransformerTrainer)`, which reads
`trainer_class.get_train_dataloader` unconditionally. The placement
tests patch a minimal stand-in trainer (just `__init__` and `train`), so
the call raises after `__init__` and `train` were already patched.

The real `SentenceTransformerTrainer` always has the method (it is a
transformers `Trainer`), so #17859 is correct for the shipped classes.
Still, the prefetch wrapper is an add-on: a trainer class with no train
loader has nothing to prefetch and should not abort the rest of the
patching.

## Change

- `patch_train_dataloader` returns early when the class has no
`get_train_dataloader`. Classes that do have it are wrapped exactly as
before.
- New
`tests/test_st_training_fast_paths.py::test_prefetch_patch_skips_a_trainer_without_a_train_dataloader`
pins that. It fails without the change.

## Verification

`tests/test_st_training_fast_paths.py
tests/test_mixed_nvidia_capabilities.py`: 91 passed. On `main`, the two
placement cases fail as above.
Penguinjanator pushed a commit to Penguinjanator/unsloth that referenced this pull request Nov 16, 2026
…on without Triton, kernel and test gates (unslothai#17882)

Backend CI on main has been red since today's merges. Every failure
traces to one commit; this fixes the unsloth side (the gloo-cp shard
also needs unslothai/unsloth-zoo#2542, since CI installs zoo from main).

| CI shard / test | Cause | Fix |
|---|---|---|
| gloo: `test_qwen4exp_parallel_matches_one_process[pp*]`,
`test_pp_splits_streams_and_runs_the_mixer_last`, all of
`test_frozen_table_pp_gloo.py` | unslothai#17785: transformers 5.17 (the CI pin)
names the Qwen4Exp layer type `qwen_sparse_attention`, 5.22 renamed it
`indexed_attention`; pipeline parallel only accepted the new name, so
every rank raised "hybrid layer stacks" | accept both names in
`_PP_HYBRID_FAMILIES` |
| diffusion (Python 3.13): 13 tests in
`test_diffusion_int8_attention_triton_device.py` | unslothai#17855: `_launch`
read `triton.runtime` while `triton` is `None` on that shard | check
`triton is not None` first |
| rest: `test_every_constexpr_line_has_a_comment` | unslothai#17860: 23
uncommented `tl.constexpr` parameters in `large_head_attention.py` |
comments added; `_tma_tile`'s signature split one parameter per line |
| rest: `test_every_launch_requests_fp_fusion` | unslothai#17860: the `_launch`
helper forwards `enable_fp_fusion` from every caller, but the gate did
not know it is a helper | registered like `layernorm.py`'s |
| rest: `test_no_file_is_dropped_or_run_twice` | unslothai#17868:
`tests/test_ddp_push_rank0_gloo.py` matched both the gloo shard and
rest-2's `test_[dimsu]*.py` | renamed
`tests/test_hub_push_rank0_ddp_gloo.py` |
| rest-2: `test_checked_in_file_reads_name_an_encoding` | unslothai#17867:
`read_text()` without an encoding in
`tests/test_bind_local_cuda_device.py` | `encoding = "utf-8"` |
| rest-2:
`test_sentence_transformer_trainer_checks_the_placement_before_the_deferred_compile[*]`
| unslothai#17859: `patch_train_dataloader` assumed every trainer class has
`get_train_dataloader` | skip the patch when the method is missing |
| rest-2:
`test_router_aux_loss_gradient_survives_unsloth_checkpointing[*]` |
unslothai#17873: the gpu-marked test still runs under CI's `-m 'not server and
not e2e'` | `has_real_accelerator()` skip next to the gpu mark |
| studio: `test_no_skip_guard_reads_a_spoofable_accelerator_probe` |
unslothai#17850: `test_block_cudagraphs_side_grad.py` skipped on
`torch.cuda.is_available()`, which the CUDA spoof fakes | skip on
`has_real_cuda()` |

## Tests

In a venv matching CI (Python 3.12, torch 2.10.0+cpu, transformers
5.17.0, TRL 1.15, PEFT 0.21.3, `UNSLOTH_COMPILE_DISABLE=1`, `-m 'not
server and not e2e'`):

- gloo: `test_qwen4exp_parallel_gloo.py` failed on main, 9 / 9 pass
here; `test_frozen_table_pp_gloo.py` 13 / 13.
- rest / rest-2 / studio: the nine affected files had exactly CI's 9
failures on main; 153 passed / 6 skipped here.
- diffusion: with Triton blocked (as on the Python 3.13 shard), the 13
failures pass here; with Triton present everything passes.

The only non-test code changes are the PP layer-type name, the Triton
`None` check and the Sentence Transformers method check;
`large_head_attention.py` changes are comments only.
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.

1 participant