Skip to content

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.

Studio: batch packed fine-tuning jobs, each job packing only its own documents (#15733)

Daniel Han75555ccb544a
diff --git a/studio/backend/core/training/multi_lora_trainer.py b/studio/backend/core/training/multi_lora_trainer.py
index 979932fdcaa..6ebd6a63d30 100644
--- a/studio/backend/core/training/multi_lora_trainer.py
+++ b/studio/backend/core/training/multi_lora_trainer.py
@@ -35,6 +35,8 @@ class _Member:
config: dict
tokenizer: Any = None
rows: list = field(default_factory = list)
+ # Per packed row, its documents' lengths; empty when unpacked.
+ seq_lengths: list = field(default_factory = list)
output_dir: str = ""
total_steps: int = 0
steps_per_epoch: int = 1
@@ -284,6 +286,15 @@ def _check_routed(model, device) -> None:
)
+def _text_tokenizer(tokenizer):
+ """A vision model's processor reads a text-only call's first argument as images; the single job unwraps it."""
+ from transformers import ProcessorMixin
+
+ if isinstance(tokenizer, ProcessorMixin) and hasattr(tokenizer, "tokenizer"):
+ return tokenizer.tokenizer
+ return tokenizer
+
+
def _member_tokenizer(tokenizer, model_name: str, final_format: str):
from utils.datasets.chat_templates import get_training_chat_template
if getattr(tokenizer, "chat_template", None) or final_format not in (
@@ -457,6 +468,142 @@ class _PerMemberLR:
pass
+def _packs(model) -> bool:
+ """Whether the single job packs here (unsloth.trainer blocklist, packed-kwargs and hybrid varlen gates)."""
+ try:
+ from unsloth import trainer as unsloth_trainer
+ from unsloth.utils.packing import _enable_hf_packed_attention, mark_allow_overlength
+
+ if getattr(model.config, "is_encoder_decoder", False) or any(
+ t in unsloth_trainer.PADDING_FREE_BLOCKLIST
+ for t in unsloth_trainer.get_transformers_model_type(model.config)
+ ):
+ return False
+ if not unsloth_trainer._forward_accepts_packing_kwargs(model):
+ return False
+ # Gated DeltaNet / conv state would carry from one document into the next without the varlen kernels.
+ if unsloth_trainer._is_hybrid_linear_attention_model(
+ model
+ ) and not unsloth_trainer.patch_hybrid_linear_attention_varlen(model):
+ return False
+ mark_allow_overlength(model)
+ _enable_hf_packed_attention()
+ if not _packed_forward_isolated(model):
+ # Members share a row, so a leak here would mix jobs, not just one job's documents.
+ logger.warning(
+ "Batched training: packed documents are not isolated on this model; not packing"
+ )
+ return False
+ except Exception as exc:
+ logger.info("Batched training: packing unavailable (%s)", exc)
+ return False
+ return True
+
+
+def _packed_forward_isolated(model) -> bool:
+ """Measured: Qwen3.5 on transformers 5.3 passes every static check yet its full attention crossed documents."""
+ import torch
+
+ embeddings = model.get_input_embeddings()
+ device, vocab = embeddings.weight.device, embeddings.num_embeddings
+ generator = torch.Generator().manual_seed(0)
+ first = torch.randint(0, vocab, (48,), generator = generator).to(device)
+ second = torch.randint(0, vocab, (32,), generator = generator).to(device)
+
+ def logits(ids, lengths):
+ positions = torch.cat([torch.arange(n) for n in lengths]).to(device)
+ out = model(
+ input_ids = ids[None],
+ position_ids = positions[None],
+ packed_seq_lengths = torch.tensor(lengths, dtype = torch.int32, device = device),
+ use_cache = False,
+ ).logits
+ return out[0, -len(second) :].float()
+
+ training = model.training
+ model.eval()
+ try:
+ with torch.no_grad():
+ alone = logits(second, [len(second)])
+ packed = logits(torch.cat([first, second]), [len(first), len(second)])
+ finally:
+ model.train(training)
+ return bool((packed - alone).abs().mean() <= 0.05 * alone.abs().mean())
+
+
+def _pack_num_proc(tokenizer) -> Optional[int]:
+ """The single job's packing workers: TRL packs each worker's shard on its own, so the count moves the rows."""
+ from core.training.trainer import _tokenizer_blocks_map_workers
+ from utils.hardware import dataset_map_num_proc
+
+ try:
+ from unsloth_zoo.dataset_num_proc import get_dataset_num_proc
+ except ImportError:
+ from unsloth.dataset_num_proc import get_dataset_num_proc
+ return get_dataset_num_proc(
+ dataset_map_num_proc(
+ 1 if _tokenizer_blocks_map_workers(tokenizer) else None, serial_as_none = False
+ )
+ )
+
+
+def _pack_rows(
+ rows: list,
+ max_length: int,
+ num_proc: Optional[int] = None,
+) -> tuple[list, list]:
+ """The single job's packing (TRL's default strategy) of one member's documents into rows of max_length."""
+ import dataclasses
+ import inspect
+
+ from datasets import Dataset
+ from trl import SFTConfig
+ from trl.data_utils import pack_dataset
+
+ dataset = Dataset.from_dict({"input_ids": [r[0] for r in rows], "labels": [r[1] for r in rows]})
+ if "strategy" in inspect.signature(pack_dataset).parameters:
+ strategy = next(
+ (f.default for f in dataclasses.fields(SFTConfig) if f.name == "packing_strategy"),
+ "bfd",
+ )
+ packed = pack_dataset(
+ dataset, max_length, strategy = strategy, map_kwargs = {"num_proc": num_proc}
+ )
+ else:
+ packed = pack_dataset(dataset, max_length, map_kwargs = {"num_proc": num_proc})
+ ids = [list(x) for x in packed["input_ids"]]
+ # Wrapped packing (TRL < 0.20) keeps no boundaries: one sequence per row, as the single job trains it.
+ lengths = (
+ [list(n) for n in packed["seq_lengths"]]
+ if "seq_lengths" in packed.column_names
+ else [[len(x)] for x in ids]
+ )
+ return [(x, list(lab)) for x, lab in zip(ids, packed["labels"])], lengths
+
+
+def _collate_packed(rows: list, slots: list, lengths: list) -> dict:
+ """One padding-free row as the single job packs it, each token routed to its member, no label across documents."""
+ import torch
+
+ seq = [n for row in lengths for n in row]
+ input_ids = torch.tensor([t for ids, _ in rows for t in ids], dtype = torch.long)
+ labels = torch.tensor([t for _, lab in rows for t in lab], dtype = torch.long)
+ sizes = torch.tensor(seq, dtype = torch.long)
+ starts = torch.cumsum(sizes, 0) - sizes
+ labels[starts[1:]] = -100
+ position_ids = torch.arange(len(input_ids)) - torch.repeat_interleave(starts, sizes)
+ adapter_ids = torch.repeat_interleave(
+ torch.tensor(slots, dtype = torch.long), torch.tensor([len(ids) for ids, _ in rows])
+ )
+ return {
+ "input_ids": input_ids[None],
+ "labels": labels[None],
+ "position_ids": position_ids[None],
+ "packed_seq_lengths": sizes.to(torch.int32),
+ "adapter_ids": adapter_ids[None],
+ }
+
+
def _collate(rows: list, slots: list, pad_id: int) -> dict:
import torch
@@ -689,25 +836,51 @@ def _run(event_queue, stop_queue, config: dict, members: list) -> None:
)
trainer.load_in_4bit = load_in_4bit
trainer.is_cpt = False
- model, tokenizer = trainer.model, trainer.tokenizer
+ model, processor = trainer.model, trainer.tokenizer
+ tokenizer = _text_tokenizer(processor)
max_length = int(config.get("max_seq_length") or 2048)
model_cap = getattr(model, "max_seq_length", None)
if isinstance(model_cap, int) and 0 < model_cap < max_length:
max_length = model_cap
_send_status(event_queue, "Tokenizing datasets...")
+ from utils.datasets.pretokenized import PRETOKENIZED_FORMAT
+
+ packs = pack_workers = None
for member in members:
if member.done:
continue
try:
- member.tokenizer, member.rows = _tokenize_member(
- datasets.pop(member.run_id),
+ info = datasets.pop(member.run_id)
+ final_format = (
+ str(info.get("final_format", "")).lower() if isinstance(info, dict) else ""
+ )
+ member_tok, member.rows = _tokenize_member(
+ info,
tokenizer,
member.config,
model_name,
max_length,
vocab_size = int(model.get_input_embeddings().num_embeddings),
)
+ # Saved as the single job saves it: the full processor (preprocessor_config.json for export).
+ member.tokenizer = processor if member_tok is tokenizer else member_tok
+ # The single job turns packing off for pre-tokenized rows, whose labels packing would drop.
+ if member.config.get("packing") and final_format != PRETOKENIZED_FORMAT:
+ if packs is None:
+ packs = _packs(model)
+ pack_workers = _pack_num_proc(processor) if packs else None
+ if packs:
+ documents = len(member.rows)
+ member.rows, member.seq_lengths = _pack_rows(
+ member.rows, max_length, pack_workers
+ )
+ logger.info(
+ "Batched training: %s packs %d documents into %d rows",
+ member.run_id,
+ documents,
+ len(member.rows),
+ )
except Exception as exc:
member.done = True
_send(
@@ -858,6 +1031,7 @@ def _build_sft_trainer(
tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
)
pad_id = 0 if pad_id is None else int(pad_id)
+ packed = any(m.seq_lengths for m in live)
bf16 = fp16 = False
if device.type == "cuda":
from unsloth import is_bfloat16_supported
@@ -961,7 +1135,7 @@ def _build_sft_trainer(
samples = []
counts = None
for k in range(num_batches):
- rows, slots = [], []
+ rows, slots, lengths = [], [], []
for member in self.round:
window = windows[member.slot]
if k < len(window):
@@ -969,11 +1143,21 @@ def _build_sft_trainer(
member.num_tokens += sum(len(ids) for ids, _ in picked)
rows.extend(picked)
slots.extend([member.slot] * len(picked))
+ lengths.extend(
+ member.seq_lengths[r]
+ if member.seq_lengths
+ else [len(member.rows[r][0])]
+ for r in window[k]
+ )
if not rows:
# Every member's window is shorter here (an epoch end); the step keeps its size.
samples.append({"multi_lora_empty": torch.zeros(1)})
continue
- batch = _collate(rows, slots, pad_id)
+ batch = (
+ _collate_packed(rows, slots, lengths)
+ if packed
+ else _collate(rows, slots, pad_id)
+ )
found = adapter_token_counts(batch["labels"], batch["adapter_ids"], U).cpu()
counts = found if counts is None else counts + found
samples.append(batch)
@@ -990,12 +1174,21 @@ def _build_sft_trainer(
if "multi_lora_empty" in inputs:
return torch.zeros((), device = self.args.device, requires_grad = True)
ids = inputs["adapter_ids"]
- set_multi_lora_batch(self.model, ids, seq_len = inputs["input_ids"].shape[1])
- logits = model(
- input_ids = inputs["input_ids"],
- attention_mask = inputs["attention_mask"],
- use_cache = False,
- ).logits
+ if "position_ids" in inputs:
+ set_multi_lora_batch(self.model, ids)
+ logits = model(
+ input_ids = inputs["input_ids"],
+ position_ids = inputs["position_ids"],
+ packed_seq_lengths = inputs["packed_seq_lengths"],
+ use_cache = False,
+ ).logits
+ else:
+ set_multi_lora_batch(self.model, ids, seq_len = inputs["input_ids"].shape[1])
+ logits = model(
+ input_ids = inputs["input_ids"],
+ attention_mask = inputs["attention_mask"],
+ use_cache = False,
+ ).logits
loss, per = per_adapter_loss(
logits,
inputs["labels"],
diff --git a/studio/backend/routes/openai_fine_tuning.py b/studio/backend/routes/openai_fine_tuning.py
index b8df3a862ba..98618bd8fdd 100644
--- a/studio/backend/routes/openai_fine_tuning.py
+++ b/studio/backend/routes/openai_fine_tuning.py
@@ -458,6 +458,7 @@ _BATCH_MEMBER_FIELDS = frozenset(
"weight_decay",
"warmup_steps",
"warmup_ratio",
+ "packing",
}
)
_BATCH_OPTIMIZERS = ("adamw_8bit", "adamw_torch")
@@ -621,7 +622,6 @@ def _batchable(request: TrainingStartRequest) -> bool:
and not (request.hf_dataset or request.dataset_streaming or request.s3_config is not None)
and not (request.resume_from_checkpoint or request.start_request_id)
and not (request.local_eval_datasets or evaluation_enabled(request.eval_steps))
- and not request.packing
and request.lora_dropout == 0
and not (request.use_dora or request.use_loftq)
and not (
diff --git a/studio/backend/tests/test_multi_lora_trainer.py b/studio/backend/tests/test_multi_lora_trainer.py
index 91880562e0c..5775b5267cb 100644
--- a/studio/backend/tests/test_multi_lora_trainer.py
+++ b/studio/backend/tests/test_multi_lora_trainer.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import copy
import json
+import math
import os
import queue
import types
@@ -31,7 +32,7 @@ except Exception as exc: # noqa: BLE001 - no multi-LoRA kernels or no importabl
from datasets import Dataset
from safetensors.torch import load_file
from tokenizers import Tokenizer, models, pre_tokenizers
-from transformers import PreTrainedTokenizerFast, Qwen3Config, Qwen3ForCausalLM
+from transformers import PreTrainedTokenizerFast, ProcessorMixin, Qwen3Config, Qwen3ForCausalLM
from core.training import multi_lora_trainer as mlt
@@ -108,6 +109,7 @@ def _member_config(m):
"warmup_steps": m.get("warmup_steps", 0),
"weight_decay": m.get("weight_decay", 0.0),
"gradient_accumulation_steps": 2,
+ "packing": m.get("packing", False),
}
@@ -129,6 +131,7 @@ def _run(
trainer_attrs = None,
datasets = None,
model_attrs = None,
+ wrap_tokenizer = None,
**extra,
):
base = _base()
@@ -156,7 +159,8 @@ def _run(
inboxes = []
def load_base(trainer, config, hf_token, event_queue):
- trainer.model, trainer.tokenizer = base, tokenizer
+ trainer.model = base
+ trainer.tokenizer = tokenizer if wrap_tokenizer is None else wrap_tokenizer(tokenizer)
return False
def stop_reader(stop_queue, inbox, trainer):
@@ -528,3 +532,242 @@ def test_batched_member_trains_as_it_would_alone(batched_run, monkeypatch):
assert batched_loss[1:] == pytest.approx(alone_loss[1:], rel = 1e-4)
for key in alone:
torch.testing.assert_close(batched[key], alone[key], atol = 1e-5, rtol = 1e-4)
+
+
+PACKED = [
+ dict(
+ run_id = "job_a",
+ rows = 12,
+ batch_size = 2,
+ num_epochs = 2,
+ lr = 1e-2,
+ r = 4,
+ alpha = 8,
+ seed = 11,
+ packing = True,
+ ),
+ dict(
+ run_id = "job_b",
+ rows = 16,
+ batch_size = 1,
+ num_epochs = 1,
+ lr = 5e-3,
+ r = 8,
+ alpha = 16,
+ seed = 22,
+ packing = True,
+ ),
+ dict(run_id = "job_c", rows = 7, batch_size = 2, num_epochs = 1, lr = 2e-2, r = 2, alpha = 4, seed = 33),
+]
+
+
+def _final(events, run_id):
+ mine = _member_events(events, run_id)
+ losses = [e["loss"] for e in mine if e["type"] == "progress" and e["step"] > 0]
+ state = load_file(os.path.join(mine[0]["output_dir"], "adapter_model.safetensors"))
+ return losses, state
+
+
+def _spy_packed(monkeypatch):
+ seen = []
+ real = mlt._collate_packed
+
+ def spy(rows, slots, lengths):
+ batch = real(rows, slots, lengths)
+ seen.append(batch)
+ return batch
+
+ monkeypatch.setattr(mlt, "_collate_packed", spy)
+ return seen
+
+
+def test_packing_members_never_share_a_document_or_see_a_neighbour(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ seen = _spy_packed(monkeypatch)
+ events, _, _ = _run(monkeypatch, PACKED, max_seq_length = 24)
+ assert seen
+ for batch in seen:
+ ids, pos, lengths = (
+ batch["adapter_ids"][0],
+ batch["position_ids"][0],
+ batch["packed_seq_lengths"],
+ )
+ starts = (pos == 0).nonzero().flatten()
+ assert starts.tolist() == (torch.cumsum(lengths, 0) - lengths).tolist()
+ # One adapter per document, and the label opening each document is never trained.
+ for start, n in zip(starts.tolist(), lengths.tolist()):
+ assert ids[start : start + n].unique().numel() == 1
+ assert (batch["labels"][0, starts[1:]] == -100).all()
+ rows_a = math.ceil(12 / 2) # unpacked micro-batches per epoch
+ steps_a = max(e["step"] for e in _member_events(events, "job_a") if e["type"] == "progress")
+ assert steps_a < 2 * math.ceil(rows_a / 2)
+ neighbour = [
+ dict(PACKED[0]),
+ dict(PACKED[1], rows = 9, seed = 99, lr = 3e-2),
+ dict(PACKED[2], packing = True),
+ ]
+ other, _, _ = _run(monkeypatch, neighbour, max_seq_length = 24)
+ alone, _, _ = _run(monkeypatch, [PACKED[0]], max_seq_length = 24)
+ losses, state = _final(events, "job_a")
+ for run in (other, alone):
+ run_losses, run_state = _final(run, "job_a")
+ assert run_losses == pytest.approx(losses, rel = 1e-4)
+ # Float noise from the shared row's size only; a leaked neighbour moves the losses ~1e-3.
+ for key in state:
+ torch.testing.assert_close(run_state[key], state[key], atol = 1e-4, rtol = 1e-3)
+
+
+def test_an_unpacked_member_beside_packed_ones_trains_as_it_would_alone(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ mixed, _, _ = _run(monkeypatch, PACKED, max_seq_length = 24)
+ alone, _, _ = _run(monkeypatch, [PACKED[2]], max_seq_length = 24)
+ losses, state = _final(mixed, "job_c")
+ alone_losses, alone_state = _final(alone, "job_c")
+ assert losses == pytest.approx(alone_losses, rel = 1e-4)
+ for key in state:
+ torch.testing.assert_close(state[key], alone_state[key], atol = 1e-5, rtol = 1e-4)
+
+
+def test_packing_is_ignored_where_the_single_job_ignores_it(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setattr(mlt, "_packs", lambda model: False)
+ seen = _spy_packed(monkeypatch)
+ events, _, _ = _run(monkeypatch, PACKED[:1], max_seq_length = 24)
+ assert seen == []
+ steps = max(e["step"] for e in _member_events(events, "job_a") if e["type"] == "progress")
+ assert steps == 2 * math.ceil(math.ceil(12 / 2) / 2)
+
+
[email protected]("varlen", [True, False])
+def test_a_hybrid_packs_only_with_the_varlen_kernels(monkeypatch, varlen):
+ transformers = pytest.importorskip("transformers", minversion = "5.2")
+ from unsloth import trainer as unsloth_trainer
+
+ config = transformers.Qwen3_5TextConfig(
+ vocab_size = 64,
+ hidden_size = 32,
+ intermediate_size = 64,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ head_dim = 8,
+ layer_types = ["linear_attention", "full_attention"],
+ linear_num_key_heads = 2,
+ linear_num_value_heads = 4,
+ linear_key_head_dim = 8,
+ linear_value_head_dim = 8,
+ )
+ model = transformers.Qwen3_5ForCausalLM(config)
+ calls = []
+
+ def patch(m):
+ calls.append(m)
+ return varlen
+
+ monkeypatch.setattr(unsloth_trainer, "patch_hybrid_linear_attention_varlen", patch)
+ assert mlt._packs(model) is varlen and calls == [model]
+ assert mlt._packs(_base()) is True
+
+
+def test_pack_rows_keeps_each_documents_labels_with_its_tokens():
+ rows = [([i] * n, [-100] + [i] * (n - 1)) for i, n in enumerate([5, 9, 3, 7, 4], start = 1)]
+ packed, lengths = mlt._pack_rows(rows, 12)
+ assert all(len(ids) <= 12 and sum(n) == len(ids) for (ids, _), n in zip(packed, lengths))
+ docs = sorted(
+ (ids[s : s + n], lab[s : s + n])
+ for (ids, lab), ns in zip(packed, lengths)
+ for s, n in zip([sum(ns[:k]) for k in range(len(ns))], ns)
+ )
+ assert docs == sorted(rows)
+
+
+def test_pack_rows_on_trl_without_packing_strategies(monkeypatch):
+ import trl.data_utils
+
+ real = trl.data_utils.pack_dataset
+
+ def legacy(
+ dataset,
+ seq_length,
+ map_kwargs = None,
+ ):
+ return real(dataset, seq_length, strategy = "wrapped")
+
+ monkeypatch.setattr(trl.data_utils, "pack_dataset", legacy)
+ rows = [([i] * n, [-100] + [i] * (n - 1)) for i, n in enumerate([5, 9, 3, 7, 4], start = 1)]
+ packed, lengths = mlt._pack_rows(rows, 12)
+ # Documents wrap across rows; each row is one sequence, as TRL's wrapped packing trains it.
+ assert [ids for ids, _ in packed] == [
+ [t for ids, _ in rows for t in ids][i : i + 12] for i in range(0, 28, 12)
+ ]
+ assert [labels for _, labels in packed] == [
+ [t for _, lab in rows for t in lab][i : i + 12] for i in range(0, 28, 12)
+ ]
+ assert lengths == [[12], [12], [4]]
+
+
+class _Processor(ProcessorMixin):
+ """A vision model's processor: called with text, it reads it as images."""
+
+ def __init__(self, tokenizer):
+ self.tokenizer = tokenizer
+
+ def __call__(
+ self,
+ images = None,
+ text = None,
+ **kwargs,
+ ):
+ raise ValueError("Incorrect image source.")
+
+ def save_pretrained(self, path, **kwargs):
+ self.tokenizer.save_pretrained(path)
+ open(os.path.join(path, "preprocessor_config.json"), "w").write("{}")
+
+
+def test_a_vision_models_processor_tokenizes_text_as_the_single_job_does(
+ batched_run, monkeypatch, tmp_path
+):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ events, _, _ = _run(monkeypatch, MEMBERS, wrap_tokenizer = _Processor)
+ plain, _, _ = batched_run
+ for m in MEMBERS:
+ mine = _member_events(events, m["run_id"])
+ assert mine[-1]["type"] == "complete", mine[-1]
+ assert os.path.exists(os.path.join(mine[-1]["output_dir"], "preprocessor_config.json"))
+ losses = [e["loss"] for e in mine if e["type"] == "progress"]
+ assert losses == pytest.approx(
+ [e["loss"] for e in _member_events(plain, m["run_id"]) if e["type"] == "progress"],
+ rel = 1e-5,
+ )
+
+
+def test_pack_rows_packs_each_worker_shard_as_the_single_job_does():
+ from datasets import Dataset
+ from trl.data_utils import pack_dataset
+
+ rows = [([i % 50 + 4] * 8, [i % 50 + 4] * 8) for i in range(16)]
+ single = pack_dataset(
+ Dataset.from_dict({"input_ids": [r[0] for r in rows], "labels": [r[1] for r in rows]}),
+ 2048,
+ strategy = "bfd",
+ map_kwargs = {"num_proc": 4},
+ )
+ packed, lengths = mlt._pack_rows(rows, 2048, num_proc = 4)
+ assert len(packed) == len(single) == 4
+ assert [ids for ids, _ in packed] == [list(x) for x in single["input_ids"]]
+ assert lengths == [list(x) for x in single["seq_lengths"]]
+
+
+def test_packing_is_refused_where_packed_documents_see_each_other(monkeypatch, tmp_path):
+ import transformers.masking_utils as masking_utils
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ assert mlt._packed_forward_isolated(_base().eval())
+ # Attention that ignores the document boundaries, as Qwen3.5's full attention did on transformers 5.3.
+ monkeypatch.setattr(masking_utils, "find_packed_sequence_indices", lambda position_ids: None)
+ assert not mlt._packed_forward_isolated(_base().eval())
+ seen = _spy_packed(monkeypatch)
+ events, _, _ = _run(monkeypatch, PACKED[:2], max_seq_length = 24)
+ assert seen == []
+ assert all(_member_events(events, m["run_id"])[-1]["type"] == "complete" for m in PACKED[:2])
diff --git a/studio/backend/tests/test_openai_fine_tuning.py b/studio/backend/tests/test_openai_fine_tuning.py
index d81d7457a3f..5b798188299 100644
--- a/studio/backend/tests/test_openai_fine_tuning.py
+++ b/studio/backend/tests/test_openai_fine_tuning.py
@@ -888,6 +888,7 @@ def test_jobs_differing_only_in_member_fields_batch_in_queue_order(batching, tmp
max_steps = 30,
weight_decay = 0.05,
warmup_steps = 10,
+ packing = False,
)
odd = _entry(tmp_path, "c", max_seq_length = 4096)
last = _entry(tmp_path, "d", lora_r = 8, warmup_ratio = 0.1)
@@ -900,7 +901,6 @@ def test_jobs_differing_only_in_member_fields_batch_in_queue_order(batching, tmp
[
{"resume_from_checkpoint": "/runs/old"},
{"eval_steps": 0.1},
- {"packing": True},
{"lora_dropout": 0.05},
{"use_dora": True},
{"use_loftq": True},
@@ -1061,7 +1061,7 @@ def test_compatible_queued_jobs_start_as_one_batch(batch_queue):
jobs = [
await _create(client, uploaded.id, suffix = "a", seed = 1),
await _create(client, uploaded.id, suffix = "b", hyperparameters = {"n_epochs": 3}),
- await _create(client, uploaded.id, suffix = "solo", extra_body = {"packing": True}),
+ await _create(client, uploaded.id, suffix = "solo", extra_body = {"use_dora": True}),
await _create(client, uploaded.id, suffix = "c", extra_body = {"lora_r": 64}),
]
gpu["busy"] = False
@@ -1200,7 +1200,7 @@ def test_a_single_or_incompatible_job_starts_exactly_as_before(batch_queue):
async def flow():
uploaded = await client.files.create(file = ("chats.jsonl", CHATS), purpose = "fine-tune")
- first = await _create(client, uploaded.id, suffix = "first", extra_body = {"packing": True})
+ first = await _create(client, uploaded.id, suffix = "first", extra_body = {"use_dora": True})
second = await _create(client, uploaded.id, suffix = "second")
gpu["busy"] = False
await openai_fine_tuning._drain_once()
@@ -1211,7 +1211,7 @@ def test_a_single_or_incompatible_job_starts_exactly_as_before(batch_queue):
first, second, queued = _run(flow())
assert calls["batch"] == []
assert [q.alias for q in queued] == [second.id]
- assert [(r.project_name, r.packing) for r in calls["start"]] == [
+ assert [(r.project_name, r.use_dora) for r in calls["start"]] == [
("first", True),
("second", False),
]