Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(embedding): floor contrastive batch size at 2 and refuse batch 1 (#1234) (#1296)

Nurkhan Esenbekf76c8afd0c1c
diff --git a/changelog.d/0.75.1/1296.fixed.md b/changelog.d/0.75.1/1296.fixed.md
new file mode 100644
index 00000000..98cea989
--- /dev/null
+++ b/changelog.d/0.75.1/1296.fixed.md
@@ -0,0 +1 @@
+- `task: embedding` with `embedding_loss: contrastive` (the default) no longer trains on one-row batches, where the loss and gradient are exactly 0 and the adapter never moves: `batch_size: 1` is refused at config load, `batch_size: auto` resolves to at least 2 (also when `triplet` falls back to contrastive for rows without `negative`), the last partial batch of an epoch is dropped, and a batch larger than the training set is lowered to its size. Auto batch sizing and the hardware-fit estimate also stop guessing 7B for BGE / E5 / GTE / BERT / RoBERTa / MiniLM checkpoints named `-small` / `-base` / `-large` (#1234 by @kok-o in #1296).
diff --git a/docs/data.md b/docs/data.md
index ec4d2651..bae61c68 100644
--- a/docs/data.md
+++ b/docs/data.md
@@ -601,6 +601,8 @@ Or use `.txt` files directly (one document per line).
{"anchor": "What is Python?", "positive": "A programming language.", "negative": "A type of snake."}
```
+With `embedding_loss: contrastive` (the default), each row's negatives are the other rows' positives in the same batch, so a batch needs at least two rows: `batch_size: 1` is refused at config load, `batch_size: auto` resolves to at least 2, and the last partial batch of each epoch is dropped. This also applies when `triplet` falls back to contrastive because the rows have no `negative`. Use `triplet` with a `negative` on every row, or `cosine`, to train at batch size 1.
+
**Audio (speech + conversation):**
```json
{"audio": "recording.wav", "messages": [{"role": "user", "content": "Transcribe."}, {"role": "assistant", "content": "Hello world."}]}
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 39eed82f..27b5a34c 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -5909,6 +5909,20 @@ class SoupConfig(BaseModel):
)
return self
+ @model_validator(mode="after")
+ def _validate_embedding_contrastive_batch_size(self) -> "SoupConfig":
+ """#1234 - contrastive in-batch negatives need batch_size >= 2."""
+ if self.task == "embedding" and not self.training.stream_layers:
+ tcfg = self.training
+ loss = getattr(tcfg, "embedding_loss", "contrastive")
+ bs = getattr(tcfg, "batch_size", "auto")
+ if loss == "contrastive" and bs == 1:
+ raise ValueError(
+ "contrastive in-batch negatives need batch_size >= 2; "
+ "use triplet (with negatives) or cosine for batch 1"
+ )
+ return self
+
@model_validator(mode="after")
def _validate_lora_target_parameters_scope(self) -> "SoupConfig":
"""#573 — raw-parameter LoRA is live in resident SFT/pretrain only."""
diff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.py
index e2ba08d8..ebae4a44 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -100,24 +100,6 @@ class EmbeddingTrainerWrapper:
f" / {total:,} total ({pct:.2f}%)"
)
- # --- Batch size ---
- batch_size = tcfg.batch_size
- if batch_size == "auto":
- from soup_cli.utils.gpu import get_gpu_info
-
- gpu_info = get_gpu_info()
- model_size = model_size_from_name(cfg.base)
- batch_size = estimate_batch_size(
- model_params_b=model_size,
- seq_length=cfg.data.max_length,
- gpu_memory_bytes=gpu_info["memory_total_bytes"],
- quantization=tcfg.quantization,
- lora_r=tcfg.lora.r,
- )
- # Embedding processes pairs/triplets → roughly 2-3x memory per sample
- batch_size = max(1, batch_size // 3)
- console.print(f"[green]Auto batch size (embedding):[/] {batch_size}")
-
# --- Dataset ---
train_ds = Dataset.from_list(dataset["train"])
eval_ds = None
@@ -130,13 +112,6 @@ class EmbeddingTrainerWrapper:
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
-
# --- Determine loss function ---
loss_type = tcfg.embedding_loss
margin = tcfg.embedding_margin
@@ -149,11 +124,56 @@ class EmbeddingTrainerWrapper:
)
loss_type = "contrastive"
+ # --- Batch size ---
+ batch_size = tcfg.batch_size
+ if batch_size == "auto":
+ from soup_cli.utils.gpu import get_gpu_info
+
+ gpu_info = get_gpu_info()
+ model_size = model_size_from_name(cfg.base)
+ batch_size = estimate_batch_size(
+ model_params_b=model_size,
+ seq_length=cfg.data.max_length,
+ gpu_memory_bytes=gpu_info["memory_total_bytes"],
+ quantization=tcfg.quantization,
+ lora_r=tcfg.lora.r,
+ )
+ # Embedding processes pairs/triplets → roughly 2-3x memory per sample.
+ # Contrastive in-batch negatives need batch_size >= 2 (#1234).
+ min_batch = 2 if loss_type == "contrastive" else 1
+ batch_size = max(min_batch, batch_size // 3)
+ console.print(f"[green]Auto batch size (embedding):[/] {batch_size}")
+ elif batch_size == 1 and loss_type == "contrastive":
+ raise ValueError(
+ "contrastive in-batch negatives need batch_size >= 2; "
+ "use triplet (with negatives) or cosine for batch 1"
+ )
+
+ if loss_type == "contrastive":
+ if len(train_ds) < 2:
+ raise ValueError(
+ "contrastive in-batch negatives need at least 2 training samples; "
+ f"got {len(train_ds)}"
+ )
+ if batch_size > len(train_ds):
+ batch_size = len(train_ds)
+ console.print(
+ f"[yellow]Batch size capped at training set size ({batch_size}) "
+ "so dataloader_drop_last does not drop all samples.[/]"
+ )
+
console.print(
f"[green]Embedding config:[/] loss={loss_type}, margin={margin}, "
f"pooling={tcfg.embedding_pooling}"
)
+ # --- Calculate warmup steps from ratio ---
+ total_steps = (
+ math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
+ * tcfg.epochs
+ )
+ warmup_steps = int(total_steps * tcfg.warmup_ratio)
+
# --- Training args ---
_bf16, _fp16 = bf16_fp16_flags(self.device)
training_kwargs = {
@@ -174,6 +194,7 @@ class EmbeddingTrainerWrapper:
"fp16": _fp16,
"report_to": self.report_to,
"remove_unused_columns": False,
+ "dataloader_drop_last": (loss_type == "contrastive"),
"deepspeed": self.deepspeed_config,
**training_seed_kwargs(tcfg),
}
@@ -420,6 +441,10 @@ class EmbeddingTrainerWrapper:
"total_steps": self.trainer.state.global_step,
}
+ @property
+ def args(self):
+ return self.trainer.args if self.trainer is not None else None
+
def _pool_embeddings(last_hidden_state, attention_mask, pooling: str):
"""Apply pooling strategy to hidden states."""
@@ -524,6 +549,17 @@ class _EmbeddingTrainer:
import torch
from torch.nn import functional as nn_func
+ # Fail fast if contrastive batch is degenerate (< 2) before running model forwards (#1234)
+ if (
+ self._loss_type == "contrastive"
+ or (self._loss_type == "triplet" and "negative_input_ids" not in inputs)
+ ):
+ batch_sz = inputs["anchor_input_ids"].size(0)
+ if batch_sz < 2:
+ raise ValueError(
+ f"contrastive in-batch negatives need batch_size >= 2; got {batch_sz}"
+ )
+
# Encode anchor
anchor_out = model(
input_ids=inputs["anchor_input_ids"],
@@ -603,3 +639,6 @@ class _EmbeddingTrainer:
@property
def args(self):
return self._trainer.args
+
+ def compute_loss(self, model, inputs, return_outputs=False):
+ return self._compute_embedding_loss(model, inputs, return_outputs)
diff --git a/src/soup_cli/utils/gpu.py b/src/soup_cli/utils/gpu.py
index a91e67e5..5f210757 100644
--- a/src/soup_cli/utils/gpu.py
+++ b/src/soup_cli/utils/gpu.py
@@ -370,6 +370,20 @@ def model_size_from_name(model_name: str) -> float:
if million:
return float(million.group(1)) / 1000.0
+ # Common encoder / embedding checkpoints (BGE, E5, GTE, BERT, RoBERTa, MiniLM)
+ # carry -small / -base / -large suffixes rather than "Nb" or "Nm" (#1234).
+ encoder_prefixes = ("bge-", "e5-", "gte-", "bert-", "roberta-", "minilm")
+ if any(p in name_lower for p in encoder_prefixes):
+ if "large" in name_lower:
+ return 0.335
+ if "base" in name_lower:
+ return 0.11
+ if "small" in name_lower:
+ return 0.033
+ if "mini" in name_lower or "tiny" in name_lower:
+ return 0.022
+ return 0.335
+
return 7.0 # default guess
diff --git a/tests/test_issue1234_embedding_contrastive_batch_size.py b/tests/test_issue1234_embedding_contrastive_batch_size.py
new file mode 100644
index 00000000..69af1f17
--- /dev/null
+++ b/tests/test_issue1234_embedding_contrastive_batch_size.py
@@ -0,0 +1,453 @@
+"""Tests for #1234: embedding contrastive in-batch negatives require batch_size >= 2."""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pytest
+import yaml
+
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.utils.gpu import model_size_from_name
+
+
+def _tiny_bert_dir(tmp_path):
+ """Build a tiny offline BERT model and tokenizer on CPU without downloading."""
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import BertConfig, BertModel, PreTrainedTokenizerFast
+
+ model_dir = tmp_path / "tiny_bert"
+ model_dir.mkdir(parents=True, exist_ok=True)
+
+ config = BertConfig(
+ vocab_size=64,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ intermediate_size=64,
+ max_position_embeddings=128,
+ )
+ model = BertModel(config).eval()
+ model.save_pretrained(str(model_dir))
+
+ vocab = {"[PAD]": 0, "[UNK]": 1, "[CLS]": 2, "[SEP]": 3, "hello": 4, "world": 5, "python": 6}
+ tok = Tokenizer(models.WordLevel(vocab=vocab, unk_token="[UNK]"))
+ tok.pre_tokenizer = pre_tokenizers.Whitespace()
+ fast = PreTrainedTokenizerFast(
+ tokenizer_object=tok,
+ unk_token="[UNK]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ sep_token="[SEP]",
+ )
+ fast.save_pretrained(str(model_dir))
+ return str(model_dir)
+
+
+class TestParseTimeRefusal:
+ """Explicit batch_size: 1 with embedding_loss: contrastive must be refused at parse time."""
+
+ def test_refuse_explicit_batch_size_1_contrastive(self):
+ cfg_str = """
+base: test-model
+task: embedding
+data:
+ train: dummy.jsonl
+ max_length: 64
+training:
+ batch_size: 1
+ embedding_loss: contrastive
+"""
+ with pytest.raises(ValueError) as excinfo:
+ load_config_from_string(cfg_str)
+ err = str(excinfo.value)
+ assert "contrastive" in err
+ assert "batch_size" in err
+ assert "batch_size >= 2" in err
+
+ def test_refuse_explicit_batch_size_1_with_gradient_accumulation(self):
+ cfg_str = """
+base: test-model
+task: embedding
+data:
+ train: dummy.jsonl
+ max_length: 64
+training:
+ batch_size: 1
+ gradient_accumulation_steps: 4
+ embedding_loss: contrastive
+"""
+ with pytest.raises(ValueError) as excinfo:
+ load_config_from_string(cfg_str)
+ err = str(excinfo.value)
+ assert "contrastive" in err
+ assert "batch_size" in err
+
+ def test_allow_batch_size_1_cosine(self):
+ cfg_str = """
+base: test-model
+task: embedding
+data:
+ train: dummy.jsonl
+ max_length: 64
+training:
+ batch_size: 1
+ embedding_loss: cosine
+"""
+ cfg = load_config_from_string(cfg_str)
+ assert cfg.training.batch_size == 1
+ assert cfg.training.embedding_loss == "cosine"
+
+ def test_allow_batch_size_1_triplet(self):
+ cfg_str = """
+base: test-model
+task: embedding
+data:
+ train: dummy.jsonl
+ max_length: 64
+training:
+ batch_size: 1
+ embedding_loss: triplet
+"""
+ cfg = load_config_from_string(cfg_str)
+ assert cfg.training.batch_size == 1
+ assert cfg.training.embedding_loss == "triplet"
+
+ def test_allow_batch_size_2_contrastive(self):
+ cfg_str = """
+base: test-model
+task: embedding
+data:
+ train: dummy.jsonl
+ max_length: 64
+training:
+ batch_size: 2
+ embedding_loss: contrastive
+"""
+ cfg = load_config_from_string(cfg_str)
+ assert cfg.training.batch_size == 2
+ assert cfg.training.embedding_loss == "contrastive"
+
+
+class TestAutoBatchSizeFlooring:
+ """batch_size: auto resolves to at least 2 when effective loss is contrastive."""
+
+ @pytest.mark.parametrize("gib", [0, 16, 24, 40])
+ def test_auto_batch_size_floored_at_2_contrastive(self, tmp_path, monkeypatch, gib):
+ from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
+
+ model_path = _tiny_bert_dir(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ cfg_dict = {
+ "base": model_path,
+ "task": "embedding",
+ "data": {"train": "train.jsonl", "max_length": 64},
+ "training": {
+ "batch_size": "auto",
+ "embedding_loss": "contrastive",
+ "quantization": "none",
+ "lora": {"r": 8, "alpha": 16, "target_modules": ["query", "value"]},
+ },
+ "output": str(tmp_path / "out"),
+ }
+ cfg = load_config_from_string(yaml.safe_dump(cfg_dict))
+
+ mock_gpu = {"memory_total_bytes": int(gib * 1024**3)}
+ with patch("soup_cli.utils.gpu.get_gpu_info", return_value=mock_gpu):
+ wrapper = EmbeddingTrainerWrapper(cfg, device="cpu")
+ dataset = {
+ "train": [
+ {"anchor": "hello", "positive": "world"},
+ {"anchor": "hi", "positive": "there"},
+ {"anchor": "good", "positive": "day"},
+ {"anchor": "great", "positive": "job"},
+ ]
+ }
+ wrapper.setup(dataset)
+ assert wrapper.args.per_device_train_batch_size >= 2
+ assert wrapper.args.dataloader_drop_last is True
+
+ def test_triplet_fallback_to_contrastive_with_batch_size_1_rejected_at_setup(
+ self, tmp_path, monkeypatch
+ ):
+ from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
+
+ model_path = _tiny_bert_dir(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ cfg_dict = {
+ "base": model_path,
+ "task": "embedding",
+ "data": {"train": "train.jsonl", "max_length": 64},
+ "training": {
+ "batch_size": 1,
+ "embedding_loss": "triplet",
+ "quantization": "none",
+ "lora": {"r": 8, "alpha": 16, "target_modules": ["query", "value"]},
+ },
+ "output": str(tmp_path / "out"),
+ }
+ cfg = load_config_from_string(yaml.safe_dump(cfg_dict))
+ wrapper = EmbeddingTrainerWrapper(cfg, device="cpu")
+ # Dataset without 'negative' column triggers fallback to contrastive
+ dataset = {
+ "train": [
+ {"anchor": "hello", "positive": "world"},
+ {"anchor": "hi", "positive": "there"},
+ ]
+ }
+ with pytest.raises(ValueError) as excinfo:
+ wrapper.setup(dataset)
+ err = str(excinfo.value)
+ assert "contrastive in-batch negatives need batch_size >= 2" in err
+
+ def test_triplet_with_negatives_at_batch_size_1_allowed(self, tmp_path, monkeypatch):
+ from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
+
+ model_path = _tiny_bert_dir(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ cfg_dict = {
+ "base": model_path,
+ "task": "embedding",
+ "data": {"train": "train.jsonl", "max_length": 64},
+ "training": {
+ "batch_size": 1,
+ "embedding_loss": "triplet",
+ "quantization": "none",
+ "lora": {"r": 8, "alpha": 16, "target_modules": ["query", "value"]},
+ },
+ "output": str(tmp_path / "out"),
+ }
+ cfg = load_config_from_string(yaml.safe_dump(cfg_dict))
+ wrapper = EmbeddingTrainerWrapper(cfg, device="cpu")
+ dataset = {
+ "train": [
+ {"anchor": "hello", "positive": "world", "negative": "bad"},
+ {"anchor": "hi", "positive": "there", "negative": "wrong"},
+ ]
+ }
+ wrapper.setup(dataset)
+ assert wrapper.args.per_device_train_batch_size == 1
+ assert wrapper.args.dataloader_drop_last is False
+
+ def test_contrastive_batch_size_capped_at_dataset_size_with_drop_last(
+ self, tmp_path, monkeypatch
+ ):
+ from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
+
+ model_path = _tiny_bert_dir(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ cfg_dict = {
+ "base": model_path,
+ "task": "embedding",
+ "data": {"train": "train.jsonl", "max_length": 64},
+ "training": {
+ "batch_size": 4,
+ "embedding_loss": "contrastive",
+ "quantization": "none",
+ "lora": {"r": 8, "alpha": 16, "target_modules": ["query", "value"]},
+ },
+ "output": str(tmp_path / "out"),
+ }
+ cfg = load_config_from_string(yaml.safe_dump(cfg_dict))
+ wrapper = EmbeddingTrainerWrapper(cfg, device="cpu")
+ dataset = {
+ "train": [
+ {"anchor": "hello", "positive": "world"},
+ {"anchor": "hi", "positive": "there"},
+ {"anchor": "good", "positive": "day"},
+ ]
+ }
+ wrapper.setup(dataset)
+ assert wrapper.args.per_device_train_batch_size == 3
+ assert wrapper.args.dataloader_drop_last is True
+
+
+class TestRealCpuEmbeddingTraining:
+ """Verify that template training block on CPU updates weights and has non-zero loss."""
+
+ def test_cpu_template_training_trains_and_updates_lora(self, tmp_path, monkeypatch):
+ from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
+
+ model_path = _tiny_bert_dir(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ # Match the shipped template configuration
+ cfg_dict = {
+ "base": model_path,
+ "task": "embedding",
+ "data": {"train": "train.jsonl", "max_length": 64},
+ "training": {
+ "epochs": 1,
+ "lr": 1e-4,
+ "batch_size": "auto",
+ "gradient_accumulation_steps": 1,
+ "lora": {"r": 8, "alpha": 16, "target_modules": ["query", "value"]},
+ "quantization": "none",
+ "embedding_loss": "contrastive",
+ "embedding_margin": 0.5,
+ "embedding_pooling": "mean",
+ },
+ "output": str(tmp_path / "out"),
+ }
+ cfg = load_config_from_string(yaml.safe_dump(cfg_dict))
+ wrapper = EmbeddingTrainerWrapper(cfg, device="cpu")
+
+ dataset = {
+ "train": [
+ {"anchor": "hello world", "positive": "hello world"},
+ {"anchor": "python programming", "positive": "python language"},
+ {"anchor": "data science", "positive": "machine learning"},
+ {"anchor": "good morning", "positive": "good day"},
+ {"anchor": "computer vision", "positive": "image processing"},
+ ]
+ }
+ wrapper.setup(dataset)
+ assert wrapper.args.per_device_train_batch_size >= 2
+ assert wrapper.args.dataloader_drop_last is True
+
+ res = wrapper.train()
+ assert res["total_steps"] > 0
+ assert res["final_loss"] > 0.0
+
+ # Verify LoRA B weights moved (not all zeros)
+ moved = 0
+ for name, param in wrapper.model.named_parameters():
+ if "lora_B" in name:
+ if (param != 0).any():
+ moved += 1
+ assert moved > 0, "LoRA B weights should have been updated by training"
+
+
+class TestRuntimeGuard:
+ """Runtime guard in _compute_loss raises if similarity.size(0) < 2."""
+
+ def test_compute_loss_raises_on_single_sample_batch(self, tmp_path, monkeypatch):
+ import torch
+
+ from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
+
+ model_path = _tiny_bert_dir(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ cfg_dict = {
+ "base": model_path,
+ "task": "embedding",
+ "data": {"train": "train.jsonl", "max_length": 64},
+ "training": {
+ "batch_size": 2,
+ "embedding_loss": "contrastive",
+ "quantization": "none",
+ "lora": {"r": 8, "alpha": 16, "target_modules": ["query", "value"]},
+ },
+ "output": str(tmp_path / "out"),
+ }
+ cfg = load_config_from_string(yaml.safe_dump(cfg_dict))
+ wrapper = EmbeddingTrainerWrapper(cfg, device="cpu")
+ dataset = {
+ "train": [
+ {"anchor": "hello", "positive": "world"},
+ {"anchor": "hi", "positive": "there"},
+ ]
+ }
+ wrapper.setup(dataset)
+
+ # Force a single-item input batch to compute_loss
+ device = next(wrapper.model.parameters()).device
+ single_inputs = {
+ "anchor_input_ids": torch.ones((1, 4), dtype=torch.long, device=device),
+ "anchor_attention_mask": torch.ones((1, 4), dtype=torch.long, device=device),
+ "positive_input_ids": torch.ones((1, 4), dtype=torch.long, device=device),
+ "positive_attention_mask": torch.ones((1, 4), dtype=torch.long, device=device),
+ }
+ with pytest.raises(ValueError) as excinfo:
+ wrapper.trainer.compute_loss(wrapper.model, single_inputs)
+ assert "contrastive in-batch negatives need batch_size >= 2" in str(excinfo.value)
+
+
+class TestModelSizeFromNameEncoder:
+ """Encoder models (BGE, E5, GTE, etc.) resolve to accurate parameter sizes."""
+
+ def test_bge_base_size(self):
+ assert model_size_from_name("BAAI/bge-base-en-v1.5") == 0.11
+
+ def test_bge_large_size(self):
+ assert model_size_from_name("BAAI/bge-large-en-v1.5") == 0.335
+
+ def test_bge_small_size(self):
+ assert model_size_from_name("BAAI/bge-small-en-v1.5") == 0.033
+
+ def test_encoder_without_size_defaults_to_large(self):
+ assert model_size_from_name("BAAI/bge-m3") == 0.335
+
+
+ROWS = [
+ {"anchor": "hello", "positive": "world"},
+ {"anchor": "hi", "positive": "there"},
+ {"anchor": "good", "positive": "day"},
+ {"anchor": "great", "positive": "job"},
+]
+
+
+def _wrapper(tmp_path, monkeypatch, **training):
+ from soup_cli.trainer.embedding import EmbeddingTrainerWrapper
+
+ model_path = _tiny_bert_dir(tmp_path)
+ monkeypatch.chdir(tmp_path)
+ body = {
+ "quantization": "none",
+ "lora": {"r": 8, "alpha": 16, "target_modules": ["query", "value"]},
+ **training,
+ }
+ cfg = load_config_from_string(
+ yaml.safe_dump({
+ "base": model_path,
+ "task": "embedding",
+ # the shipped template's max_length: the estimator sizes for it
+ "data": {"train": "train.jsonl", "max_length": 512},
+ "training": body,
+ "output": str(tmp_path / "out"),
+ })
+ )
+ return EmbeddingTrainerWrapper(cfg, device="cpu")
+
+
+class TestTheIssueEstimatesHitTheFloor:
+ """The issue's table: bge-base guessed as 7B at max_length 512 estimates 1/1/2/4
+ on CPU/16/24/40 GiB, i.e. 0/0/0/1 after the embedding // 3. The tiny local BERT
+ is sized from its own weights (24k params), so without pinning the size the
+ 16/24/40 GiB cases resolve to 5-10 and never reach the floor."""
+
+ @pytest.mark.parametrize("gib", [0, 16, 24, 40])
+ def test_auto_resolves_to_exactly_two(self, tmp_path, monkeypatch, gib):
+ wrapper = _wrapper(
+ tmp_path, monkeypatch, batch_size="auto", embedding_loss="contrastive"
+ )
+ with patch("soup_cli.trainer.embedding.model_size_from_name", return_value=7.0), patch(
+ "soup_cli.utils.gpu.get_gpu_info",
+ return_value={"memory_total_bytes": int(gib * 1024**3)},
+ ):
+ wrapper.setup({"train": list(ROWS)})
+ assert wrapper.args.per_device_train_batch_size == 2
+ assert wrapper.args.dataloader_drop_last is True
+
+ def test_triplet_without_negatives_is_floored_too(self, tmp_path, monkeypatch):
+ """The triplet -> contrastive fallback is contrastive for the floor as well."""
+ wrapper = _wrapper(
+ tmp_path, monkeypatch, batch_size="auto", embedding_loss="triplet"
+ )
+ with patch("soup_cli.trainer.embedding.model_size_from_name", return_value=7.0), patch(
+ "soup_cli.utils.gpu.get_gpu_info", return_value={"memory_total_bytes": 0}
+ ):
+ wrapper.setup({"train": list(ROWS)})
+ assert wrapper.args.per_device_train_batch_size == 2
+ assert wrapper.args.dataloader_drop_last is True
+
+
+def test_contrastive_refuses_a_one_row_dataset(tmp_path, monkeypatch):
+ wrapper = _wrapper(tmp_path, monkeypatch, batch_size=2, embedding_loss="contrastive")
+ with pytest.raises(ValueError, match="at least 2 training samples; got 1"):
+ wrapper.setup({"train": ROWS[:1]})
diff --git a/tests/test_issue353_seed_every_task.py b/tests/test_issue353_seed_every_task.py
index 6a43b2e4..98d17124 100644
--- a/tests/test_issue353_seed_every_task.py
+++ b/tests/test_issue353_seed_every_task.py
@@ -121,7 +121,7 @@ def _prompt_rows(n=8):
#: KTO refuses `per_device_train_batch_size == 1` (its KL term is degenerate
#: there), so the floor is per task rather than global. GRPO needs the batch to
#: be divisible by `num_generations`.
-_MIN_BATCH = {"kto": 2, "grpo": 2}
+_MIN_BATCH = {"kto": 2, "grpo": 2, "embedding": 2}
#: task -> (module, wrapper class, rows, extra `training:` keys)
#: Every entry here is driven through a real `setup()`.
diff --git a/tests/test_issue690_embedding_trainer_attrs.py b/tests/test_issue690_embedding_trainer_attrs.py
index 17d1078b..6b3d75cc 100644
--- a/tests/test_issue690_embedding_trainer_attrs.py
+++ b/tests/test_issue690_embedding_trainer_attrs.py
@@ -95,7 +95,7 @@ def _embedding_wrapper(tmp_path, monkeypatch, *, precision=None):
"max_length": 64,
},
"training": {
- "batch_size": 1,
+ "batch_size": 2,
"quantization": "none",
"epochs": 1,
"logging_steps": 1,
diff --git a/tests/test_trainer_coverage_v035.py b/tests/test_trainer_coverage_v035.py
index 9622fb8b..465002bb 100644
--- a/tests/test_trainer_coverage_v035.py
+++ b/tests/test_trainer_coverage_v035.py
@@ -225,10 +225,11 @@ def test_activation_offloading_context_missing_attr_safe(tmp_path) -> None:
def _build_yaml_config(task: str, **training_extra) -> dict:
"""Helper: build a minimal config dict accepted by load_config_from_string."""
+ default_bs = 2 if task == "embedding" else 1
body = {
"base": "meta-llama/Llama-3.2-1B",
"task": task,
- "training": {"epochs": 1, "lr": 1e-4, "batch_size": 1, **training_extra},
+ "training": {"epochs": 1, "lr": 1e-4, "batch_size": default_bs, **training_extra},
}
if task == "pretrain":
body["data"] = {"train": "data.jsonl", "format": "plaintext"}