Repository navigation
FastSentenceTransformer: background collation, lean LoRA, decoder packing, ModernBERT FA2 - #17859
Conversation
…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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if prefetch_enabled(self) and not isinstance(loader, PrefetchedDataLoader): | ||
| loader = PrefetchedDataLoader(loader) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
|
@codex review |
There was a problem hiding this comment.
💡 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".
| iterator = source() | ||
| for batch in iterator: |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…ives stay on the training thread [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
…_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.
…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.
Faster
FastSentenceTransformertraining. Each lever has its own off switch.Changes
UNSLOTH_ST_PREFETCH=0UNSLOTH_ST_LEAN_LORA=0token_embeddingsUNSLOTH_ST_PACKING=0Packing 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.
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.