Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(sft): preserve assistant loss mask during sample packing (#1236) (#1304)
Nurkhan Esenbek5628a3772f6c
diff --git a/changelog.d/0.75.1/1304.fixed.md b/changelog.d/0.75.1/1304.fixed.mdnew file mode 100644index 00000000..b7254655--- /dev/null+++ b/changelog.d/0.75.1/1304.fixed.md@@ -0,0 +1 @@+- **`training.packing: true` preserves assistant-only loss mask during SFT instead of training prompt/system tokens (#1236).** In TRL 0.29.1, dataset packing drops the unpreserved `labels` column and falls back to training all input tokens except the first. SFT datasets now ensure an `assistant_masks` column alongside `labels`, which TRL packs alongside `input_ids` and uses to mask prompt/system tokens with `-100` during collation (and prevents label dropping under `use_liger: true`). Pre-tokenized caches carrying `labels` are also augmented with `assistant_masks` automatically (#1236 by @kok-o in #1304).diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex 29bbbaab..01c0c7dd 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -469,7 +469,7 @@ training:packing: true # Pack short samples together (faster training)```-Works with SFT and Pretrain tasks. Warning emitted if `max_length < 256`.+Works with SFT and Pretrain tasks. Packed SFT keeps the assistant-only loss mask (`train_on_responses_only`, `train_on_messages_with_train_field`, `mask_history`, or a pre-tokenised `labels` column). Warning emitted if `max_length < 256`.## Curriculum Learningdiff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.pyindex a6ae2dce..54eb7e38 100644--- a/src/soup_cli/trainer/sft.py+++ b/src/soup_cli/trainer/sft.py@@ -166,6 +166,20 @@ def _map_text_sft_rows()+def _ensure_assistant_masks(dataset: Any) -> Any:+ """Ensure `assistant_masks` column exists alongside `labels` for TRL packing (#1236)."""+ if dataset is None:+ return None+ cols = getattr(dataset, "column_names", ())+ if "labels" in cols and "assistant_masks" not in cols:+ return dataset.map(+ lambda row: {+ "assistant_masks": [1 if int(x) != -100 else 0 for x in row["labels"]]+ }+ )+ return dataset++def _validate_pretokenized_targets(dataset: Any, *, split: str, max_length: int) -> None:"""Apply the same target invariant to trusted pre-tokenized datasets."""from soup_cli.data.loss_mask import (@@ -898,6 +912,11 @@ class SFTTrainerWrapper(StreamingSetupMixin):max_length=cfg.data.max_length,)+ # #1236 - Ensure assistant_masks exists alongside labels for TRL packing+ train_ds = _ensure_assistant_masks(train_ds)+ if eval_ds is not None:+ eval_ds = _ensure_assistant_masks(eval_ds)+# --- Output dir ---output_dir = Path(cfg.output)if cfg.experiment_name:diff --git a/tests/test_issue1236_packing_loss_mask.py b/tests/test_issue1236_packing_loss_mask.pynew file mode 100644index 00000000..d17a8d16--- /dev/null+++ b/tests/test_issue1236_packing_loss_mask.py@@ -0,0 +1,234 @@+"""Tests for issue #1236: `packing: true` preserves SFT assistant-only loss mask.++Asserts that supervised token positions (labels != -100) match between+`packing: false` and `packing: true` across:+- default responses_only+- train_on_messages_with_train_field+- train_on_eot+- pre-tokenized cache+- pretrain with packing is unaffected+"""++from __future__ import annotations++import pytest++pytest.importorskip("torch")+pytest.importorskip("trl")+pytest.importorskip("transformers")+pytest.importorskip("peft")++import yaml+from datasets import Dataset++from soup_cli.config.loader import load_config_from_string+from soup_cli.trainer.pretrain import PretrainTrainerWrapper+from soup_cli.trainer.sft import SFTTrainerWrapper+from tests.test_issue691_sft_packing import _tiny_causal_model_dir+++def _count_supervised_and_real_tokens(dataloader):+ """Count supervised positions (labels != -100) and real tokens in a dataloader."""+ real = 0+ supervised = 0+ for batch in dataloader:+ lab = batch["labels"]+ supervised += int((lab != -100).sum())+ if "attention_mask" in batch:+ real += int(batch["attention_mask"].sum())+ else:+ real += int(batch["input_ids"].numel())+ return supervised, real+++def _build_sft_wrapper(tmp_path, monkeypatch, data_extra=None, **training_extra):+ weights = _tiny_causal_model_dir(tmp_path)+ monkeypatch.chdir(tmp_path)+ tcfg = {+ "batch_size": 2,+ "quantization": "none",+ "epochs": 1,+ "logging_steps": 1,+ "save_steps": 1000,+ "lora": {"r": 4, "alpha": 8, "target_modules": ["q_proj", "v_proj"]},+ }+ tcfg.update(training_extra)+ dcfg = {+ "train": "train.jsonl",+ "max_length": 128,+ "chat_template": "chatml",+ }+ if data_extra:+ dcfg.update(data_extra)++ cfg = load_config_from_string(+ yaml.safe_dump(+ {+ "base": weights,+ "task": "sft",+ "backend": "transformers",+ "modality": "text",+ "data": dcfg,+ "training": tcfg,+ "output": str(tmp_path / "out"),+ }+ )+ )+ return SFTTrainerWrapper(cfg, device="cpu")+++class TestSFTPackingLossMask:+ def test_default_responses_only_packing_preserves_mask(self, tmp_path, monkeypatch):+ row = {+ "messages": [+ {"role": "system", "content": "sys prompt"},+ {"role": "user", "content": "hello there"},+ {"role": "assistant", "content": "world reply"},+ ]+ }+ rows = [row] * 8++ # Packing false+ w_false = _build_sft_wrapper(tmp_path / "f", monkeypatch, packing=False)+ w_false.setup({"train": rows})+ sup_false, _ = _count_supervised_and_real_tokens(w_false.trainer.get_train_dataloader())++ # Packing true+ w_true = _build_sft_wrapper(tmp_path / "t", monkeypatch, packing=True)+ w_true.setup({"train": rows})+ sup_true, _ = _count_supervised_and_real_tokens(w_true.trainer.get_train_dataloader())++ assert sup_true == sup_false, (+ f"Supervised tokens mismatch: packed={sup_true} vs unpacked={sup_false}"+ )+ assert sup_true < 100, f"Expected assistant-only tokens, but got {sup_true}"++ def test_train_field_packing_preserves_mask(self, tmp_path, monkeypatch):+ row = {+ "messages": [+ {"role": "system", "content": "sys prompt", "train": False},+ {"role": "user", "content": "hello there", "train": False},+ {"role": "assistant", "content": "world reply", "train": True},+ ]+ }+ rows = [row] * 8+ d_extra = {+ "train_on_responses_only": False,+ "train_on_messages_with_train_field": True,+ }++ w_false = _build_sft_wrapper(tmp_path / "f", monkeypatch, data_extra=d_extra, packing=False)+ w_false.setup({"train": rows})+ sup_false, _ = _count_supervised_and_real_tokens(w_false.trainer.get_train_dataloader())++ w_true = _build_sft_wrapper(tmp_path / "t", monkeypatch, data_extra=d_extra, packing=True)+ w_true.setup({"train": rows})+ sup_true, _ = _count_supervised_and_real_tokens(w_true.trainer.get_train_dataloader())++ assert sup_true == sup_false++ def test_train_on_eot_packing(self, tmp_path, monkeypatch):+ row = {+ "messages": [+ {"role": "user", "content": "hello"},+ {"role": "assistant", "content": "world"},+ ]+ }+ rows = [row] * 8++ w_false = _build_sft_wrapper(tmp_path / "f", monkeypatch, train_on_eot=True, packing=False)+ w_false.setup({"train": rows})+ sup_false, _ = _count_supervised_and_real_tokens(w_false.trainer.get_train_dataloader())++ w_true = _build_sft_wrapper(tmp_path / "t", monkeypatch, train_on_eot=True, packing=True)+ w_true.setup({"train": rows})+ sup_true, _ = _count_supervised_and_real_tokens(w_true.trainer.get_train_dataloader())++ assert sup_true == sup_false++ def test_pretokenized_dataset_with_labels_packing(self, tmp_path, monkeypatch):+ # Create dummy pretokenized dataset with input_ids and labels+ input_ids = [1, 5, 6, 7, 2]+ labels = [-100, -100, -100, 7, 2]+ ds = Dataset.from_dict({+ "input_ids": [input_ids] * 8,+ "labels": [labels] * 8,+ "attention_mask": [[1] * 5] * 8,+ })+ cache_f = tmp_path / "f" / "pretok_cache"+ cache_f.parent.mkdir(parents=True, exist_ok=True)+ ds.save_to_disk(str(cache_f))++ d_extra_f = {"format": "pre_tokenized", "tokenized_path": "./pretok_cache"}+ w_false = _build_sft_wrapper(+ tmp_path / "f", monkeypatch, data_extra=d_extra_f, packing=False+ )+ w_false.setup({})+ sup_false, _ = _count_supervised_and_real_tokens(+ w_false.trainer.get_train_dataloader()+ )++ cache_t = tmp_path / "t" / "pretok_cache"+ cache_t.parent.mkdir(parents=True, exist_ok=True)+ ds.save_to_disk(str(cache_t))+ d_extra_t = {"format": "pre_tokenized", "tokenized_path": "./pretok_cache"}+ w_true = _build_sft_wrapper(+ tmp_path / "t", monkeypatch, data_extra=d_extra_t, packing=True+ )+ w_true.setup({})+ sup_true, _ = _count_supervised_and_real_tokens(+ w_true.trainer.get_train_dataloader()+ )++ assert sup_true == sup_false++ def test_eval_split_packing_preserves_mask(self, tmp_path, monkeypatch):+ row = {+ "messages": [+ {"role": "system", "content": "sys prompt"},+ {"role": "user", "content": "hello there"},+ {"role": "assistant", "content": "world reply"},+ ]+ }+ counts = {}+ for packing in (False, True):+ wrapper = _build_sft_wrapper(tmp_path / str(packing), monkeypatch, packing=packing)+ wrapper.setup({"train": [row] * 8, "val": [row] * 4})+ assert wrapper.trainer.eval_dataset is not None+ counts[packing], _ = _count_supervised_and_real_tokens(+ wrapper.trainer.get_eval_dataloader()+ )+ assert counts[True] == counts[False], counts+++class TestPretrainPackingUnaffected:+ def test_pretrain_with_packing(self, tmp_path, monkeypatch):+ weights = _tiny_causal_model_dir(tmp_path)+ monkeypatch.chdir(tmp_path)+ cfg = load_config_from_string(+ yaml.safe_dump(+ {+ "base": weights,+ "task": "pretrain",+ "backend": "transformers",+ "modality": "text",+ "data": {+ "train": "train.jsonl",+ "max_length": 64,+ },+ "training": {+ "batch_size": 2,+ "quantization": "none",+ "epochs": 1,+ "packing": True,+ },+ "output": str(tmp_path / "out_pretrain"),+ }+ )+ )+ wrapper = PretrainTrainerWrapper(cfg, device="cpu")+ wrapper.setup({"train": [{"text": "hello world the cat sat on the mat"}] * 8})+ # Pretrain packing works as expected+ dataloader = wrapper.trainer.get_train_dataloader()+ assert dataloader is not None+ assert "assistant_masks" not in wrapper.trainer.train_dataset.column_names