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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Use the requested max_seq_length for encoder embedding models (#12915)
Nilay65095e0a6494
diff --git a/tests/python/test_sentence_transformer_max_seq_length.py b/tests/python/test_sentence_transformer_max_seq_length.pynew file mode 100644index 00000000000..8c6261c362d--- /dev/null+++ b/tests/python/test_sentence_transformer_max_seq_length.py@@ -0,0 +1,116 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.++import pytest+import torch++from real_accelerator import has_real_accelerator++LONG_TEXT = " ".join(f"word{i % 60 + 3}" for i in range(200))+++def _save_encoder_sentence_model(+ tmp_path,+ family,+ position_limit = 32,+):+ if not has_real_accelerator() or not torch.cuda.is_available():+ pytest.skip("FastSentenceTransformer needs CUDA")+ pytest.importorskip("sentence_transformers")+ import unsloth # noqa: F401+ from sentence_transformers import SentenceTransformer+ from sentence_transformers.models import Pooling, Transformer+ from tokenizers import Tokenizer+ from tokenizers.models import WordLevel+ from tokenizers.pre_tokenizers import Whitespace+ from transformers import BertConfig, BertModel, PreTrainedTokenizerFast+ from transformers import RobertaConfig, RobertaModel++ pad = 0 if family == "bert" else 1+ config_class, model_class = {+ "bert": (BertConfig, BertModel),+ "roberta": (RobertaConfig, RobertaModel),+ }[family]+ config = config_class(+ vocab_size = 64,+ hidden_size = 16,+ num_hidden_layers = 2,+ num_attention_heads = 2,+ intermediate_size = 24,+ max_position_embeddings = position_limit + (0 if family == "bert" else pad + 1),+ pad_token_id = pad,+ )+ checkpoint = tmp_path / "base"+ model_class(config).save_pretrained(checkpoint)+ vocab = {f"word{i}": i for i in range(64) if i not in (pad, 2)}+ vocab.update({"[PAD]": pad, "[UNK]": 2})+ tokenizer = Tokenizer(WordLevel(vocab, unk_token = "[UNK]"))+ tokenizer.pre_tokenizer = Whitespace()+ PreTrainedTokenizerFast(+ tokenizer_object = tokenizer, pad_token = "[PAD]", unk_token = "[UNK]"+ ).save_pretrained(checkpoint)+ SentenceTransformer(+ modules = [Transformer(str(checkpoint), max_seq_length = 8), Pooling(16)],+ device = "cpu",+ ).save_pretrained(str(tmp_path / "sentence"))+ return str(tmp_path / "sentence")+++def _load(path, **kwargs):+ from unsloth import FastSentenceTransformer+ return FastSentenceTransformer.from_pretrained(path, full_finetuning = True, **kwargs)++[email protected]("for_inference", [False, True])[email protected]("family", ["bert", "roberta"])+def test_requested_max_seq_length_replaces_the_saved_one(tmp_path, family, for_inference):+ path = _save_encoder_sentence_model(tmp_path, family)+ model = _load(path, max_seq_length = 20, for_inference = for_inference)+ assert model.max_seq_length == 20+ assert model.tokenize([LONG_TEXT])["input_ids"].shape[1] == 20++ from sentence_transformers import SentenceTransformer++ model.save_pretrained(str(tmp_path / "saved"))+ assert SentenceTransformer(str(tmp_path / "saved"), device = "cpu").max_seq_length == 20++[email protected]("for_inference", [False, True])[email protected]("family", ["bert", "roberta"])+def test_max_seq_length_is_capped_at_the_model_positions(tmp_path, family, for_inference):+ path = _save_encoder_sentence_model(tmp_path, family)+ model = _load(path, max_seq_length = 4096, for_inference = for_inference)+ assert model.max_seq_length == 32+ assert model.encode([LONG_TEXT]).shape == (1, 16)+++def test_saved_max_seq_length_stays_when_none_is_requested(tmp_path):+ path = _save_encoder_sentence_model(tmp_path, "bert")+ assert _load(path).max_seq_length == 8+++def test_router_uses_the_smallest_encoder_position_limit(tmp_path):+ if not has_real_accelerator() or not torch.cuda.is_available():+ pytest.skip("FastSentenceTransformer needs CUDA")+ pytest.importorskip("sentence_transformers")+ from sentence_transformers import SentenceTransformer+ from sentence_transformers.models import Router++ query_model = SentenceTransformer(+ _save_encoder_sentence_model(tmp_path / "query", "bert", position_limit = 24),+ device = "cpu",+ )+ document_model = SentenceTransformer(+ _save_encoder_sentence_model(tmp_path / "document", "roberta"),+ device = "cpu",+ )+ router = Router.for_query_document(+ query_modules = list(query_model.children()),+ document_modules = list(document_model.children()),+ )+ path = tmp_path / "router"+ SentenceTransformer(modules = [router], device = "cpu").save_pretrained(str(path))++ model = _load(str(path), max_seq_length = 4096, for_inference = True)+ assert model.max_seq_length == 24+ assert {route[0].max_seq_length for route in model[0].sub_modules.values()} == {24}diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex 6d37cc32b17..a33cd505986 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -153,11 +153,32 @@ def _maybe_upcast_force_float32_inference(st_model):return True+def _apply_max_seq_length(st_model, max_seq_length):+ if max_seq_length is None:+ return+ limits = []+ for module in st_model[0].modules():+ embeddings = getattr(getattr(module, "auto_model", None), "embeddings", None)+ position_embeddings = getattr(embeddings, "position_embeddings", None)+ if isinstance(position_embeddings, torch.nn.Embedding):+ # RoBERTa-style positions start after padding_idx, so 514 rows hold 512 tokens.+ padding_idx = position_embeddings.padding_idx+ limits.append(+ position_embeddings.num_embeddings - (0 if padding_idx is None else padding_idx + 1)+ )+ if limits and max_seq_length > (limit := min(limits)):+ print(+ f"Unsloth: max_seq_length = {max_seq_length} is longer than this model supports. "+ f"Using {limit}."+ )+ max_seq_length = limit+ st_model.max_seq_length = max_seq_length++def _normalize_save_method(save_method):- """Fold "MERGED_16BIT" and "merged 16bit" onto "merged_16bit". unsloth_save_model (save.py) normalizes case and spaces before validating, so the same spelling has to mean the same thing here, else a keyword call that worked before starts raising."""+ """match unsloth_save_model case and spacing normalization before routing save requests."""if isinstance(save_method, str):- # Stripped BEFORE the spaces are folded, or " lora " becomes "_lora_" and the- # adapter guard below sends the request to the merge path instead.+ # strip before replacing spaces so " lora " does not become "_lora_" and bypass the adapter guard.return save_method.strip().lower().replace(" ", "_")return save_method@@ -2392,26 +2413,19 @@ class FastSentenceTransformer(FastModel):cache_dir = st_kwargs.get("cache_folder"),revision = revision,)- # Load the snapshot that was checked. Without this the gate reads one commit of- # a branch and the load resolves the branch again, so a repository that advances- # in between is validated on the old files and loaded from the new ones.- #- # Whenever the gate resolved a commit, including when the caller named a- # revision. Restricting it to a falsey revision left `revision = "main"` racing- # exactly as before, and it does not override anyone's choice: _validated IS- # what the caller's own revision resolved to, so pinning only removes the second- # resolution. An explicit commit resolves to itself and the pin is a no-op.+ # pin the validated commit so a moving branch cannot change between checking and loading.if _validated:st_kwargs["revision"] = _validatedst_model = SentenceTransformer(model_name, **st_kwargs)- # "auto" keeps a bfloat16 checkpoint in bfloat16 on GPUs without it (T4, V100): emulated and slow. An explicit float16 request is what these families cannot run at all (non-finite activations). Either way move to bfloat16 where supported, else float32 when the copy fits.+ # unsupported GPUs emulate bfloat16 slowly; float16 can yield non-finite activations.if (dtype is None and not SUPPORTS_BFLOAT16) or dtype == torch.float16:_maybe_upcast_force_float32_inference(st_model)if _ensure_sentence_attention_masks(getattr(st_model[0], "auto_model", None)) and hasattr(st_model[0], "unpad_inputs"):- # Refresh ST's cached capability decision after changing the backend.+ # refresh ST cached backend capability after attention-mask patching.st_model[0].unpad_inputs = st_model[0].unpad_inputs+ _apply_max_seq_length(st_model, max_seq_length)st_model._unsloth_trust_remote_code = trust_remote_codereturn st_model@@ -2419,14 +2433,14 @@ class FastSentenceTransformer(FastModel):kwargs["auto_model"] = AutoModeltransformers4 = Version(transformers.__version__).major < 5- # SentenceTransformer's config_kwargs (e.g. {"vision_config": None} to skip a multimodal model's vision tower) must reach the config, not the model constructor.+ # config_kwargs must reach the config, not the model constructor.config_kwargs = kwargs.pop("config_kwargs", None) or {}model_type = ""config = kwargs.get("config", None)if config is not None:model_type = getattr(config, "model_type", "")else:- # One dict, caller's config_kwargs last, so {"trust_remote_code": True} overrides instead of duplicating a keyword (as SentenceTransformer merges them). Same revision and cache as the weight load, since this config builds the model when config_kwargs is set.+ # merge caller config last to avoid duplicates and reuse the weight revision and cache._config_load_kwargs = {"token": token,"trust_remote_code": trust_remote_code,@@ -2526,7 +2540,7 @@ class FastSentenceTransformer(FastModel):cache_dir = kwargs.get("cache_dir") or kwargs.get("cache_folder"),revision = revision,)- # Same race as the delegated route above, same pin.+ # the delegated route has the same race and revision pin.st_model = SentenceTransformer(model_name,device = st_device,@@ -2539,6 +2553,7 @@ class FastSentenceTransformer(FastModel):)st_model._unsloth_fast_encoder = True+ _apply_max_seq_length(st_model, max_seq_length)_mark_full_finetuning(st_model[0].auto_model, full_finetuning)st_model._compile_mode = compile_modest_model._dtype = dtype