forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsft.py
More file actions
2075 lines (1829 loc) · 89.3 KB
/
Copy pathsft.py
File metadata and controls
2075 lines (1829 loc) · 89.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""SFT (Supervised Fine-Tuning) trainer — wraps HuggingFace transformers + peft + trl."""
import json
import logging
import math
import os
import time
from pathlib import Path
from typing import Any, Optional, Tuple
from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.stream_setup import StreamingSetupMixin
from soup_cli.utils.gpu import (
bf16_fp16_flags,
estimate_batch_size,
model_size_from_name,
resolve_base_load_dtype,
resolve_device_map,
)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
logger = logging.getLogger(__name__)
console = Console()
# #341's DEFAULT_TRAINING_SEED moved to ``utils.seeding`` in #353, where every
# other task trainer needs the same constant. The multipack default below is
# SFT-local and stays here.
# #341 — what an unset seed gives the multipack FFD sampler. NOT 42: the
# sampler has been seeded 0 since v0.37.0 because ``getattr(tcfg, "seed", 0)``
# never found an attribute, and changing it would silently re-order every
# existing ``multipack: true`` run.
DEFAULT_MULTIPACK_SEED = 0
# Text-token surface TRL's SFTTrainer reads directly off ``processing_class``
# (trl/trainer/sft_trainer.py: ``pad_token`` / ``eos_token`` / ``eos_token_id``
# resolution) — mirrored from a vision processor's nested tokenizer in #302.
_PROCESSOR_TOKEN_ATTRS = (
"pad_token",
"eos_token",
"pad_token_id",
"eos_token_id",
"bos_token",
"bos_token_id",
)
_FINITE_TRAINING_METRICS = (
"loss",
"grad_norm",
"entropy",
"train_loss",
"eval_loss",
)
def _assert_finite_training_state(
log_history: list[dict[str, Any]], model: Any | None = None
) -> None:
"""Refuse the final save when metrics or trainable weights are non-finite.
Only the most recently logged value of each metric is checked. ``log_history``
accumulates one entry per log call over the whole run, and a metric that was
transiently non-finite earlier (e.g. a GradScaler warm-up nan) but recovered
says nothing about the final state; checking every past entry made a
self-corrected run indistinguishable from a genuinely corrupted one.
"""
for metric in _FINITE_TRAINING_METRICS:
for entry in reversed(log_history):
if not isinstance(entry, dict) or metric not in entry:
continue
value = entry[metric]
try:
finite = math.isfinite(float(value))
except (TypeError, ValueError):
break
if finite:
break
step = entry.get("step", "unknown")
raise RuntimeError(
f"non-finite training metric {metric}={value} at step {step}; "
"refusing to save the final model because its weights may be corrupted"
)
if model is None:
return
import torch
for name, parameter in model.named_parameters():
if not parameter.requires_grad or getattr(parameter, "is_meta", False):
continue
if not parameter.is_floating_point():
continue
if torch.isfinite(parameter.detach()).all().item():
continue
raise RuntimeError(
f"non-finite trainable parameter {name!r}; refusing to save the final "
"model because its weights are corrupted"
)
def _map_text_sft_rows(
rows: list[dict],
*,
format_row: Any,
split: str,
max_length: int,
) -> Any:
"""Tokenize text SFT rows and attach their human-facing row number to failures."""
from datasets import Dataset
from soup_cli.data.loss_mask import (
NoCausalLossTargetError,
ensure_causal_loss_target,
)
def checked_format_row(example: dict, row_index: int) -> dict:
try:
formatted = format_row(example)
labels = formatted.get("labels")
if labels is not None:
ensure_causal_loss_target(labels, max_length=max_length)
return formatted
except NoCausalLossTargetError as exc:
raise ValueError(f"{split} row {row_index + 1}: {exc}") from exc
return Dataset.from_list(rows).map(
checked_format_row,
with_indices=True,
remove_columns=["messages"],
)
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 (
NoCausalLossTargetError,
ensure_causal_loss_target,
)
if "labels" not in getattr(dataset, "column_names", ()):
return
for row_index in range(len(dataset)):
try:
ensure_causal_loss_target(
dataset[row_index]["labels"], max_length=max_length
)
except NoCausalLossTargetError as exc:
raise ValueError(f"{split} row {row_index + 1}: {exc}") from exc
def _ensure_vision_processor_pad_token(processor: object) -> None:
"""Mirror a vision processor's nested-tokenizer token surface onto itself.
HF vision processors (Idefics3/SmolVLM, LLaVA, Qwen2-VL, ...) keep the text
tokenizer nested at ``processor.tokenizer`` and do NOT forward token-level
attributes — ``ProcessorMixin`` has no ``__getattr__``. TRL's ``SFTTrainer``
reads ``processing_class.pad_token`` / ``.eos_token`` /
``.convert_tokens_to_ids`` directly, so passing such a processor as
``processing_class`` crashes with e.g. ``'Idefics3Processor' object has no
attribute 'pad_token'`` (#302).
Fix: when the processor exposes a nested ``.tokenizer``, set
``pad_token = eos_token`` on that tokenizer if unset, then copy the token
surface + ``convert_tokens_to_ids`` onto the processor — but only for
attributes it does not already expose, so a processor that already behaves
like a tokenizer (or a plain tokenizer) is left untouched (no LLaVA-path
regression). Best-effort per attribute: a read-only property on either side
is skipped rather than fatal.
"""
tok = getattr(processor, "tokenizer", None)
if tok is None:
# Already tokenizer-like, or an unknown shape — nothing to mirror.
return
# A padless tokenizer trains fine once pad == eos (the standard causal-LM
# convention already used by the text path, sft.py:_setup_transformers).
if getattr(tok, "pad_token", None) is None and getattr(tok, "eos_token", None) is not None:
try:
tok.pad_token = tok.eos_token
except (AttributeError, TypeError):
pass
for attr in _PROCESSOR_TOKEN_ATTRS:
if hasattr(processor, attr):
continue # processor already exposes it — don't clobber
try:
setattr(processor, attr, getattr(tok, attr, None))
except (AttributeError, TypeError):
pass
if not hasattr(processor, "convert_tokens_to_ids"):
inner = getattr(tok, "convert_tokens_to_ids", None)
if callable(inner):
try:
processor.convert_tokens_to_ids = inner
except (AttributeError, TypeError):
pass
def _vision_messages_with_image_parts(
messages: list[dict[str, Any]], image_count: int
) -> list[dict[str, Any]]:
"""Convert Soup's legacy ``<image>`` messages to HF multimodal content.
LLaVA JSON rows reach the trainer with string ``content`` fields. Modern
processors such as Idefics3 only preserve an image placeholder when the
chat message contains a structured ``{"type": "image"}`` part. Passing
the legacy string directly makes ``apply_chat_template`` silently drop the
prompt text and image marker, then the processor rejects the accompanying
image because the rendered text contains zero image tokens (#302).
Existing structured messages are preserved. When an otherwise valid
vision row omits the literal marker, place its image(s) at the start of the
first user turn. Refuse excess markers rather than handing the processor a
misleading image/token-count mismatch.
"""
if image_count < 0:
raise ValueError("image_count must be non-negative")
if not messages:
raise ValueError("Vision sample has no messages")
converted: list[dict[str, Any]] = []
represented_images = 0
for message in messages:
converted_message = dict(message)
content = converted_message.get("content", "")
parts: list[dict[str, Any]] = []
if isinstance(content, list):
for part in content:
if isinstance(part, dict):
copied = dict(part)
else:
copied = {"type": "text", "text": str(part)}
parts.append(copied)
if copied.get("type") == "image":
represented_images += 1
elif isinstance(content, str):
for index, chunk in enumerate(content.split("<image>")):
if index:
parts.append({"type": "image"})
represented_images += 1
text = chunk.strip()
if text:
parts.append({"type": "text", "text": text})
else:
parts.append({"type": "text", "text": str(content)})
converted_message["content"] = parts
converted.append(converted_message)
if represented_images > image_count:
raise ValueError(
"Vision sample contains "
f"{represented_images} image placeholder(s) but only {image_count} image(s)"
)
missing_images = image_count - represented_images
if missing_images:
target = next(
(message for message in converted if message.get("role") == "user"),
converted[0],
)
target["content"] = [
*({"type": "image"} for _ in range(missing_images)),
*target["content"],
]
return converted
def _single_token_id(value: Any) -> Optional[int]:
"""Return a usable token id without accepting bool or tokenizer sentinels."""
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
return None
return value
def _vision_image_token_ids(processor: object) -> frozenset[int]:
"""Resolve image-placeholder ids across current and floor processor APIs."""
tokenizer = getattr(processor, "tokenizer", None)
token_ids: set[int] = set()
for owner in (processor, tokenizer):
if owner is None:
continue
plural = getattr(owner, "image_token_ids", None)
if isinstance(plural, (list, tuple, set, frozenset)):
for value in plural:
token_id = _single_token_id(value)
if token_id is not None:
token_ids.add(token_id)
singular = _single_token_id(getattr(owner, "image_token_id", None))
if singular is not None:
token_ids.add(singular)
convert = getattr(tokenizer, "convert_tokens_to_ids", None)
if callable(convert):
for owner in (processor, tokenizer):
image_token = getattr(owner, "image_token", None)
if not isinstance(image_token, str) or not image_token:
continue
token_id = _single_token_id(convert(image_token))
if token_id is not None:
token_ids.add(token_id)
return frozenset(token_ids)
def _first_token_id(encoded: object) -> Optional[int]:
"""Read the leading id from tokenizer output without importing tensors."""
if hasattr(encoded, "get"):
encoded = encoded.get("input_ids")
if hasattr(encoded, "tolist"):
encoded = encoded.tolist()
if not isinstance(encoded, (list, tuple)) or not encoded:
return None
first = encoded[0]
if isinstance(first, (list, tuple)):
if not first:
return None
first = first[0]
return _single_token_id(first)
def _processor_adds_leading_bos(processor: object, text: str) -> bool:
"""Detect whether ``add_special_tokens=True`` supplies a missing BOS.
Some VLM chat templates (SmolVLM, Qwen2-VL) already render their leading
special token, while LLaVA-1.5 relies on tokenizer defaults. Comparing the
two tokenizer paths on the first real rendered prompt preserves both.
"""
tokenizer = getattr(processor, "tokenizer", None)
bos_token_id = _single_token_id(getattr(tokenizer, "bos_token_id", None))
if not callable(tokenizer) or bos_token_id is None:
return False
try:
plain_first = _first_token_id(tokenizer(text, add_special_tokens=False))
special_first = _first_token_id(tokenizer(text, add_special_tokens=True))
except (TypeError, ValueError):
return False
return plain_first != bos_token_id and special_first == bos_token_id
class VisionLanguageDataCollator:
"""Build a real multimodal batch at data-loader time.
Keeping PIL images and raw messages until collation lets each processor
perform its own image-token expansion and emit architecture-specific
tensors (``pixel_values``, ``pixel_attention_mask``, ``image_grid_thw``,
and so on). This deliberately mirrors TRL's newer VLM collator without
requiring a newer TRL than Soup's declared floor.
"""
def __init__(self, processor: object, max_length: Optional[int]) -> None:
self.processor = processor
self.max_length = max_length
self.image_token_ids = _vision_image_token_ids(processor)
self._add_special_tokens: Optional[bool] = None
def __call__(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
images: list[list[Any]] = []
texts: list[str] = []
for example in examples:
example_images = example.get("images") or []
if not isinstance(example_images, (list, tuple)):
example_images = [example_images]
image_list = list(example_images)
messages = _vision_messages_with_image_parts(
example.get("messages") or [], len(image_list)
)
text = self.processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=False,
)
images.append(image_list)
texts.append(text)
if self._add_special_tokens is None:
self._add_special_tokens = bool(
texts and _processor_adds_leading_bos(self.processor, texts[0])
)
processor_kwargs: dict[str, Any] = {
"images": images,
"text": texts,
"padding": True,
"return_tensors": "pt",
"add_special_tokens": self._add_special_tokens,
}
if self.max_length is not None:
processor_kwargs.update(
truncation=True,
max_length=self.max_length,
)
output = self.processor(**processor_kwargs)
labels = output["input_ids"].clone()
labels[output["attention_mask"] == 0] = -100
for image_token_id in self.image_token_ids:
labels[output["input_ids"] == image_token_id] = -100
output["labels"] = labels
return output
def _make_vision_trainer(
trainer_kwargs: dict[str, Any], processor: object, max_length: Optional[int]
) -> Any:
"""Build the plain HF Trainer used for already-collated vision batches."""
import inspect
from transformers import Trainer
kwargs = dict(trainer_kwargs)
kwargs["data_collator"] = VisionLanguageDataCollator(processor, max_length)
# Transformers renamed Trainer(tokenizer=...) to processing_class. Keep a
# narrow capability shim for downstream Trainer subclasses that still
# expose the legacy constructor name.
if "processing_class" not in inspect.signature(Trainer.__init__).parameters:
kwargs["tokenizer"] = kwargs.pop("processing_class")
return Trainer(**kwargs)
def _maybe_load_pretokenized(
dcfg, base: str, console_obj: Console,
) -> Optional[Tuple[object, object]]:
"""v0.53.7 #86 — short-circuit tokenization when caller pre-tokenized via
``soup data preprocess``.
Returns ``(train_ds, eval_ds)`` when the pre-tokenized path is configured
and valid, otherwise ``None`` (caller falls back to the normal tokenize
pipeline).
Cache-hash gate: when ``<tokenized_path>/metadata.json`` exists, its
``cache_key`` is cross-checked against the current
``(base, max_length, format, train)`` config via
:func:`make_preprocess_cache_key`. Mismatch raises ``ValueError`` with
the keyword ``"cache hash mismatch"`` so users know to re-run
``soup data preprocess``. Missing ``metadata.json`` falls back to
"trusted" mode with a yellow advisory.
"""
if dcfg.format != "pre_tokenized" or not dcfg.tokenized_path:
return None
from soup_cli.utils.data_pipeline import (
load_pretokenized_dataset,
make_preprocess_cache_key,
)
tokenized_path = dcfg.tokenized_path
metadata_path = os.path.join(tokenized_path, "metadata.json")
if os.path.isfile(metadata_path):
try:
with open(metadata_path, encoding="utf-8") as f:
metadata = json.load(f)
except (OSError, ValueError) as exc:
raise ValueError(
f"pre_tokenized metadata.json is unreadable: {exc}"
) from exc
stored_key = metadata.get("cache_key")
current_key = make_preprocess_cache_key(
dataset_path=dcfg.train,
tokenizer_name=base,
max_length=dcfg.max_length,
format_name=dcfg.format,
)
if stored_key != current_key:
raise ValueError(
"pre_tokenized cache hash mismatch: was generated with "
f"{stored_key!r}, current config implies {current_key!r}; "
"re-run `soup data preprocess`"
)
else:
console_obj.print(
"[yellow]pre-tokenized cache has no metadata.json — assuming "
"compatible; consider re-running `soup data preprocess`[/]"
)
console_obj.print(
f"[dim]v0.53.7: skipping tokenization, loading pre-tokenized "
f"Arrow shards from {tokenized_path}[/dim]"
)
arrow_ds = load_pretokenized_dataset(tokenized_path)
# ``load_from_disk`` returns either a Dataset (single split) or a
# DatasetDict (multiple splits). Handle both shapes.
if hasattr(arrow_ds, "keys") and "train" in arrow_ds:
train_ds = arrow_ds["train"]
eval_ds = arrow_ds.get("val") or arrow_ds.get("validation")
else:
train_ds = arrow_ds
eval_ds = None
return train_ds, eval_ds
def is_full_finetune(tcfg) -> bool:
"""Single source of truth: does this run train the base itself (no adapter)?
Three schema-gated spellings (see config/schema.py's
``_validate_unfrozen_parameters`` / ``_validate_lisa*`` /
``_validate_full_finetune`` — all three mutually exclusive with each
other, so at most one is ever true): Spectrum ``unfrozen_parameters``,
LISA ``lisa_enabled``, or the #340 ``lora.r=0`` spelling.
``freeze_layers`` / ``freeze_ratio`` are deliberately NOT part of this.
They reduce what's trainable WITHIN whichever mode is already chosen —
a LoRA run with frozen bottom layers is still LoRA (frozen base,
checkpoint dtype), not full fine-tuning — they do not select the mode.
See ``_setup_transformers``'s "Freeze training" block (runs before the
mode-selection chain, unconditionally) and ``_validate_full_finetune``'s
``mode_conflicts`` (schema.py), which lets ``freeze_layers``/
``freeze_ratio`` combine with EITHER ``lora.r=0`` or plain ``lora.r>0``.
#471 review — this used to be re-derived independently in three places
(this function's own predecessor in ``_resolve_load_dtype``,
``commands/train.py::_build_hardware_fit_input``'s VRAM pre-flight
``peft`` classifier, and this module's ``setup()`` summary-label block),
and two of the three had drifted apart in OPPOSITE directions:
``_build_hardware_fit_input`` didn't check ``lisa_enabled``/``lora.r==0``
(under-predicting VRAM for those runs) and treated bare
``freeze_layers``/``freeze_ratio`` as sufficient on its own (over-
predicting — and falsely refusing launches — for a LoRA run that merely
freezes some layers). Unified here so the two call sites cannot drift
again.
"""
return bool(tcfg.unfrozen_parameters or tcfg.lisa_enabled or tcfg.lora.r == 0)
class SFTTrainerWrapper(StreamingSetupMixin):
"""High-level wrapper that sets up model + tokenizer + trainer from SoupConfig."""
def __init__(
self,
config: SoupConfig,
device: str = "cuda",
report_to: str = "none",
deepspeed_config: Optional[str] = None,
fsdp_config: Optional[dict] = None,
trust_remote_code: bool = False,
):
self.config = config
self.device = device
self.report_to = report_to
self.deepspeed_config = deepspeed_config
self.fsdp_config = fsdp_config
self.trust_remote_code = trust_remote_code
self.model = None
self.tokenizer = None
self.trainer = None
self._is_raft = False # set in setup() when data.format == 'raft'
# Resolve once — raises ValueError if model needs custom code but
# the user did not opt in. Result is cached on the wrapper for use
# by every from_pretrained() call below.
from soup_cli.utils.trust_remote import (
model_requires_trust_remote_code,
resolve_trust_remote_code,
)
requires = model_requires_trust_remote_code(config.base) or False
self._trust_remote_code = resolve_trust_remote_code(
config.base,
requested=trust_remote_code,
console=console,
requires_remote_code=requires,
)
def setup(self, dataset: dict):
"""Load model, tokenizer, apply LoRA, create trainer."""
from transformers import TrainingArguments
from trl import SFTTrainer
# Enable Rich progress bar for HuggingFace downloads
_enable_hf_transfer_progress()
cfg = self.config
tcfg = cfg.training
# #353: seed before the model exists. Threading `seed` into
# TrainingArguments is not enough on its own, because `get_peft_model`
# draws `lora_A` before there is a Trainer to run `set_seed(args.seed)`.
apply_training_seed(tcfg)
use_unsloth = cfg.backend == "unsloth"
use_vision = cfg.modality == "vision"
use_audio = cfg.modality == "audio"
# v0.72.0 BETA — layer streaming replaces the model-load path entirely
# (meta skeleton, never a resident load), so it dispatches ahead of the
# backend branches. The schema already rejects streaming + unsloth/mlx
# and streaming + vision/audio.
use_streaming = bool(getattr(tcfg, "stream_layers", False))
if use_vision:
self._setup_vision_transformers(cfg, tcfg)
elif use_audio:
self._setup_audio_transformers(cfg, tcfg)
elif use_streaming:
self._setup_streaming_transformers(cfg, tcfg)
elif use_unsloth:
self._setup_unsloth(cfg, tcfg)
else:
self._setup_transformers(cfg, tcfg)
# v0.71.23 #266 — the Spectrum full-FT branch leaves a raw (non-PEFT)
# model, which has no get_nb_trainable_parameters(); fall back to a
# direct parameter count.
if hasattr(self.model, "get_nb_trainable_parameters"):
trainable, total = self.model.get_nb_trainable_parameters()
else:
trainable = sum(
p.numel() for p in self.model.parameters() if p.requires_grad
)
total = sum(p.numel() for p in self.model.parameters())
# v0.72.2 — under NF4 streaming PEFT's total is wrong by ~6.5x. It
# special-cases Params4bit as `numel * 2 * quant_storage.itemsize`,
# which is right for a RESIDENT one (whose numel is the packed count)
# but not for our `meta` placeholder, which still carries the LOGICAL
# shape. Measured on SmolLM2-135M: 878,154,048 vs a true 134,515,008.
# The sharder counted the real source elements, so use that.
stream_total = getattr(self._stream_runtime, "total_params", 0)
if stream_total:
total = stream_total
pct = 100 * trainable / total if total else 0.0
# #340 — "LoRA applied" is a false statement on a full-FT run, and this
# is the line an operator screenshots to show what trained.
if tcfg.unfrozen_parameters:
label = "Spectrum targeted FT"
elif tcfg.lisa_enabled:
label = "LISA full fine-tuning"
elif tcfg.lora.r == 0 and cfg.modality == "text" and cfg.backend == "transformers":
label = "Full fine-tuning"
else:
label = "LoRA applied"
console.print(
f"[green]{label}:[/] {trainable:,} trainable"
f" / {total:,} total ({pct:.2f}%)"
)
# --- Batch size ---
batch_size = tcfg.batch_size
if batch_size == "auto":
from soup_cli.utils.batch_probe import pick_batch_size
from soup_cli.utils.gpu import get_gpu_info
gpu_info = get_gpu_info()
model_size = model_size_from_name(cfg.base)
static_estimate = 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,
)
# v0.36.0 Part D: real OOM probe with cache short-circuit. Falls
# back to the static estimate on CPU or when probe_fn unavailable.
gpu_memory_gb_total = int(
(gpu_info.get("memory_total_bytes") or 0) // (1024 ** 3)
)
# v0.40.3 (#64): live CUDA probe_fn — runs ONE forward+backward
# on a synthetic batch per candidate before training. No-op on CPU.
from soup_cli.utils.batch_probe import make_cuda_probe_fn
probe_fn = make_cuda_probe_fn(
self.model,
self.tokenizer,
max_length=cfg.data.max_length,
device=self.device,
)
batch_size = pick_batch_size(
static_estimate=static_estimate,
strategy=tcfg.auto_batch_size_strategy,
base=cfg.base,
max_length=cfg.data.max_length,
quantization=tcfg.quantization,
lora_r=tcfg.lora.r,
gpu_name=str(gpu_info.get("name") or "cpu"),
gpu_memory_gb=gpu_memory_gb_total,
probe_fn=probe_fn,
console=console,
)
console.print(f"[green]Auto batch size:[/] {batch_size}")
# --- Curriculum learning: sort dataset by difficulty ---
if tcfg.curriculum:
from soup_cli.utils.curriculum import sort_by_length
if tcfg.curriculum_metric == "length":
dataset["train"] = sort_by_length(dataset["train"])
console.print(
f"[green]Curriculum learning enabled:[/] "
f"metric=length, buckets={tcfg.curriculum_buckets}"
)
else:
console.print(
f"[yellow]Curriculum metric '{tcfg.curriculum_metric}' "
"requires pre-computed scores. Using length-based sorting.[/]"
)
dataset["train"] = sort_by_length(dataset["train"])
# --- Dataset ---
# v0.53.7 #86 — short-circuit tokenization when caller pre-tokenized
# via `soup data preprocess`. Skips the format_row + tokenizer pass
# entirely; rows already carry input_ids/labels/attention_mask.
# v0.71.10 #199 — RAFT format: golden/distractor-doc rows are NOT
# {messages}; build a pre-tokenised answer-only-mask dataset instead.
self._is_raft = cfg.data.format == "raft"
# v0.71.17 #253 — RAFT epoch-aware shuffle: when on, keep RAW rows so
# the collator re-permutes documents per epoch (vs one baked order).
self._raft_epoch_shuffle = self._is_raft and bool(
getattr(cfg.data, "raft_epoch_shuffle", False)
)
pretok = _maybe_load_pretokenized(cfg.data, cfg.base, console)
if pretok is not None:
train_ds, eval_ds = pretok
_validate_pretokenized_targets(
train_ds, split="train", max_length=cfg.data.max_length
)
if eval_ds is not None:
_validate_pretokenized_targets(
eval_ds, split="validation", max_length=cfg.data.max_length
)
elif self._raft_epoch_shuffle:
train_ds, eval_ds = self._prepare_raft_raw_dataset(dataset, cfg, tcfg)
elif self._is_raft:
train_ds, eval_ds = self._prepare_raft_dataset(dataset, cfg, tcfg)
elif use_vision:
train_ds, eval_ds = self._prepare_vision_dataset(dataset)
elif use_audio:
train_ds, eval_ds = self._prepare_audio_dataset(dataset)
else:
from soup_cli.data.sft_format import build_format_row
format_row = build_format_row(
tokenizer=self.tokenizer,
data_cfg=cfg.data,
console=console,
training_cfg=tcfg,
)
train_ds = _map_text_sft_rows(
dataset["train"],
format_row=format_row,
split="train",
max_length=cfg.data.max_length,
)
eval_ds = None
if "val" in dataset and dataset["val"]:
eval_ds = _map_text_sft_rows(
dataset["val"],
format_row=format_row,
split="validation",
max_length=cfg.data.max_length,
)
# --- Output dir ---
output_dir = Path(cfg.output)
if cfg.experiment_name:
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
# --- Calculate warmup steps from ratio ---
import math
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 ---
# v0.33.0 #58: auto_mixed_precision wires pick_mixed_precision()
# into bf16/fp16 kwargs. Default behaviour (bf16 on CUDA) preserved
# when the auto flag is False.
bf16_flag, fp16_flag = self._resolve_mixed_precision(tcfg, cfg.base)
training_kwargs = {
"output_dir": str(output_dir),
"num_train_epochs": tcfg.epochs,
"per_device_train_batch_size": batch_size,
"gradient_accumulation_steps": tcfg.gradient_accumulation_steps,
"learning_rate": tcfg.lr,
"warmup_steps": warmup_steps,
"weight_decay": tcfg.weight_decay,
"max_grad_norm": tcfg.max_grad_norm,
"optim": tcfg.optimizer,
"lr_scheduler_type": tcfg.scheduler,
"logging_steps": tcfg.logging_steps,
"save_steps": tcfg.save_steps,
"save_total_limit": 3,
"bf16": bf16_flag,
"fp16": fp16_flag,
"report_to": self.report_to,
"remove_unused_columns": False,
"deepspeed": self.deepspeed_config,
# #341: the general training seed. Until this landed there was no
# knob at all, so every run took HF's defaults (seed=42,
# data_seed=None) and replicates of one config differed only by row
# permutation and GPU nondeterminism. `None` means "unset", and
# unset must reproduce the pre-#341 numbers exactly, hence 42 rather
# than a new default. #353 moved the resolution into utils.seeding
# so the other 17 task wrappers resolve it identically.
**training_seed_kwargs(tcfg),
}
# FSDP2 — alternative to DeepSpeed. The helper also enables
# torch.compile when tcfg.use_fsdp2_compile is True.
from soup_cli.utils.fsdp import apply_fsdp_training_kwargs
apply_fsdp_training_kwargs(
training_kwargs,
fsdp_config=self.fsdp_config,
use_fsdp2_compile=tcfg.use_fsdp2_compile,
)
if self.fsdp_config and tcfg.use_fsdp2_compile:
console.print("[green]torch.compile enabled on FSDP2[/]")
# Gradient checkpointing — tiered (v0.28.0): bool or tier string.
# v0.72.0: layer streaming checkpoints every layer itself, so enabling
# HF's too would double-recompute silently (see layer_stream).
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
hf_grad_ckpt = should_enable_hf_gradient_checkpointing(
tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
)
if tcfg.gradient_checkpointing and not hf_grad_ckpt:
console.print(
"[dim]Gradient checkpointing: handled per-layer by layer "
"streaming (HF's own is left off to avoid double recompute)[/]"
)
if hf_grad_ckpt:
from soup_cli.utils.gpu import get_gpu_info
from soup_cli.utils.gradient_ckpt import (
describe_tier,
resolve_gradient_checkpointing,
)
gpu_memory_gb: Optional[float] = None
try:
gpu_memory_gb = get_gpu_info().get(
"memory_total_bytes", 0
) / (1024**3) or None
except (KeyError, TypeError, ZeroDivisionError):
gpu_memory_gb = None
ckpt_kwargs = resolve_gradient_checkpointing(
tcfg.gradient_checkpointing, gpu_memory_gb=gpu_memory_gb,
)
training_kwargs.update(ckpt_kwargs)
if ckpt_kwargs:
console.print(
f"[green]Gradient checkpointing:[/] "
f"{describe_tier(tcfg.gradient_checkpointing, gpu_memory_gb)}"
)
# NEFTune — noisy embeddings for better fine-tuning quality
if tcfg.neftune_alpha is not None:
training_kwargs["neftune_noise_alpha"] = tcfg.neftune_alpha
# LoRA+ — different learning rates for A and B matrices. Not a
# TrainingArguments field: the optimizer is built and attached after the
# trainer exists (attach_loraplus_optimizer), so it must NOT be forwarded
# here (#724).
# GaLore — memory-efficient full-parameter training
if tcfg.use_galore:
from soup_cli.utils.galore import get_galore_optimizer_and_params
if tcfg.optimizer != "adamw_torch":
console.print(
f"[yellow]GaLore overrides optimizer '{tcfg.optimizer}' "
f"with 'galore_adamw'.[/]"
)
galore_kwargs = get_galore_optimizer_and_params(
galore_rank=tcfg.galore_rank,
galore_update_proj_gap=tcfg.galore_update_proj_gap,
galore_scale=tcfg.galore_scale,
)
training_kwargs.update(galore_kwargs)
console.print(
f"[green]GaLore enabled:[/] rank={tcfg.galore_rank}, "
f"update_gap={tcfg.galore_update_proj_gap}, scale={tcfg.galore_scale}"
)
# #78 — only when Soup's own patch actually landed, so an unsupported
# architecture keeps today's warning instead of becoming an HF exception.
if getattr(self, "_liger_applied", False):
training_kwargs["use_liger_kernel"] = True
training_args = TrainingArguments(**training_kwargs)
# #78 — `data.max_length` above 1024 was silently ignored on EVERY SFT run.
# `SFTTrainer.__init__` converts a plain `TrainingArguments` with
# `SFTConfig(**args.to_dict())`, and `max_length` is an SFT-only field that
# `TrainingArguments` does not carry, so it always took SFTConfig's own
# default of 1024. Measured before the fix: max_length=4096 produced 1024
# tokens per sample, with no warning. Building the SFTConfig here mirrors
# TRL's own conversion (including the hub_token dance it does) and adds the
# one field that was being dropped.
training_args = self._as_sft_config(
training_args, cfg.data.max_length, packing=tcfg.packing,
)
# --- Trainer ---
trainer_kwargs = {
"model": self.model,
"args": training_args,
"train_dataset": train_ds,
"eval_dataset": eval_ds,
"processing_class": self.tokenizer,
}
# Sample packing — pack multiple short samples into one sequence
if tcfg.packing:
if cfg.data.max_length < 256:
console.print(
f"[yellow]Warning:[/] packing=true with max_length={cfg.data.max_length} "
"may be suboptimal. Consider increasing max_length for better packing."
)
console.print("[green]Sample packing enabled[/]")
# v0.40.4 #65 — multipack live wiring. ``make_multipack_trainer_class``
# mixes a ``get_train_dataloader`` override into the SFTTrainer MRO
# that returns a DataLoader whose ``batch_sampler`` is the FFD
# bin-packing :class:`MultipackBatchSampler`. The factory is cached
# so two ``multipack: true`` runs against the same base class share
# the same subclass.
use_multipack = bool(getattr(tcfg, "multipack", False))
if self._is_raft:
# v0.71.10 #199 — RAFT uses a plain Trainer + weighted-CE loss
# (answer-only mask via loss_weights; citation-span boost when
# training.citation_faithful is set — #202). The pre-tokenised
# rows + custom collator skip SFTTrainer's text-column processing.
from transformers import Trainer
from soup_cli.trainer.raft import (
RaftDataCollator,
make_raft_trainer_class,
)
raft_cls = make_raft_trainer_class(Trainer)
if self._raft_epoch_shuffle:
# v0.71.17 #253 — RAW rows + per-epoch re-tokenising collator +
# a callback that advances the epoch salt at each epoch start.
from soup_cli.trainer.raft import (
RaftEpochShuffleCollator,
RaftEpochState,
make_raft_epoch_callback,
)
epoch_state = RaftEpochState()
collator = RaftEpochShuffleCollator(
self.tokenizer,
max_length=cfg.data.max_length,
epoch_state=epoch_state,
shuffle_seed=cfg.data.raft_shuffle_seed,
citation_faithful=bool(tcfg.citation_faithful),
citation_style=tcfg.citation_style or "bracket",
)
else:
collator = RaftDataCollator(self.tokenizer)
self.trainer = raft_cls(
model=self.model,
args=training_args,
train_dataset=train_ds,
eval_dataset=eval_ds,
data_collator=collator,
processing_class=self.tokenizer,
)
if self._raft_epoch_shuffle:
self.trainer.add_callback(make_raft_epoch_callback(epoch_state))
console.print(
"[green]RAFT epoch-shuffle:[/] documents re-permuted each "
"epoch (per-epoch salt)"
)
if tcfg.citation_faithful:
console.print(
"[green]RAFT + citation-faithful:[/] answer-only mask "
f"with boosted [{tcfg.citation_style or 'bracket'}] "
"citation spans"
)
else:
console.print("[green]RAFT trainer enabled:[/] answer-only loss mask")
elif use_multipack:
from soup_cli.utils.multipack_sampler import (
validate_multipack_architecture,
)
from soup_cli.utils.multipack_trainer import (
attach_multipack_state,
detect_arch_name,
lengths_from_dataset,
make_multipack_trainer_class,
)
arch = detect_arch_name(self.model)
if arch:
validate_multipack_architecture(arch)
trainer_cls = make_multipack_trainer_class(SFTTrainer)
self.trainer = trainer_cls(**trainer_kwargs)
attach_multipack_state(
self.trainer,
lengths=lengths_from_dataset(train_ds),
max_seq_len=cfg.data.max_length,
batch_size=batch_size,
# #341 — this lookup used to be defensive cover for an
# attribute that did not exist, so it was always 0. The field