forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.py
More file actions
7053 lines (6607 loc) · 278 KB
/
Copy pathschema.py
File metadata and controls
7053 lines (6607 loc) · 278 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
"""Pydantic schemas for soup.yaml config — single source of truth."""
import re
from typing import Any, Dict, List, Literal, Optional, Union
from pydantic import BaseModel, Field, field_validator, model_validator
# Buffer bounds live with the streaming planner so the schema bound and the
# runtime validator's message can never disagree (layer_stream has no torch).
from soup_cli.utils.layer_stream import (
DEFAULT_STREAM_BUFFERS,
MAX_STREAM_BUFFERS,
MIN_STREAM_BUFFERS,
)
from soup_cli.utils.layer_stream import (
ROLLOUT_STREAM_TASKS as _STREAM_ROLLOUT_TASKS,
)
from soup_cli.utils.layer_stream import (
SUPPORTED_STREAM_TASKS as _STREAM_SUPPORTED_TASKS,
)
# Noise-floor bounds live with the ship verdict so the schema bound and the
# `--noise-floor` CLI validator can never disagree (ship_verdict has no torch,
# same reasoning as stream_buffers importing its bounds from layer_stream).
from soup_cli.utils.ship_verdict import (
MAX_NOISE_FLOOR_RUNS,
MIN_NOISE_FLOOR_RUNS,
)
# v0.39.0 Part C — per-pattern LoRA rank/alpha bounds
_MAX_LORA_RANK_PATTERN_KEYS = 256
_MAX_LORA_RANK_PATTERN_VALUE = 1024
_MAX_LORA_TARGET_PARAMETERS = 256
_MAX_LORA_TARGET_PARAMETER_LEN = 512
# v0.71.23 #266 — Spectrum targeted-training unfrozen-parameter caps
_MAX_UNFROZEN_PARAMETERS = 50_000
_MAX_UNFROZEN_PATTERN_LEN = 512
# Reject nested-unbounded-quantifier regexes — e.g. ``(x+)+y`` / ``(a*)*`` —
# which catastrophically backtrack (ReDoS) when re.search'd against parameter
# names in apply_unfrozen_parameters. soup.yaml is shareable config, so the
# pattern *class* is rejected at parse time, not just compile failures.
_UNFROZEN_REDOS_RE = re.compile(r"\([^)]*[+*][^)]*\)\s*[+*]")
# v0.71.34 #267 / #307 — tasks whose transformers trainer wires LisaCallback.
# LISA is full-FT of a rotating set of decoder layers, so a task only belongs
# here once its trainer skips PEFT, keeps the model trainable, and calls
# ``attach_lisa_callback``. Adding a task to this tuple without that wiring
# would accept a config the trainer silently ignores.
_LISA_SUPPORTED_TASKS = ("sft", "pretrain")
class LoraConfig(BaseModel):
# #340 — `r: 0` is the first-class full-fine-tuning switch: no
# adapter is applied and the base weights train directly. It is the
# spelling `trainer/classifier.py` has read as "no adapter" since
# v0.71.12 (#146) and the one `commands/card.py::_is_adapter` already
# resolves to "dense model". Before #340 a rank of 0 reached peft and
# died with "`r` should be a positive integer value", so nothing that
# worked before changes meaning. `ge=0` closes the pre-existing hole
# where a NEGATIVE rank parsed and failed the same way, deep in peft.
r: int = Field(
default=64,
ge=0,
description=(
"LoRA rank. 0 = full fine-tuning: no adapter, every base "
"parameter trains (sft / embedding + transformers + text + "
"quantization='none' only)."
),
)
alpha: int = Field(default=16, description="LoRA alpha")
dropout: float = Field(default=0.05, description="LoRA dropout")
target_modules: Union[str, List[str]] = Field(
default="auto",
description="Target modules for LoRA. 'auto' = let peft decide.",
)
target_parameters: Optional[Union[Literal["auto"], List[str]]] = Field(
default=None,
description=(
"Raw 2-D/3-D nn.Parameter tensors to adapt with PEFT LoRA. "
"Use 'auto' to select architecture-specific parameter targets "
"(currently Qwen4-Exp routed experts), a list of parameter-name "
"suffixes for explicit control, or omit to disable. Requires "
"dropout=0 and is wired for transformers SFT/pretrain."
),
)
use_dora: bool = Field(
default=False,
description="Enable DoRA (Weight-Decomposed Low-Rank Adaptation)",
)
use_rslora: bool = Field(
default=False,
description="Enable rank-stabilized LoRA scaling (better for high ranks)",
)
use_vera: bool = Field(
default=False,
description=(
"Enable VeRA (Vector-based Random Matrix Adaptation). "
"Shared random matrices — much smaller memory than LoRA. "
"Mutually exclusive with use_dora and use_olora."
),
)
use_olora: bool = Field(
default=False,
description=(
"Enable OLoRA (Orthogonal LoRA init via QR decomposition). "
"Passes init_lora_weights='olora' to peft. "
"Mutually exclusive with use_dora and use_vera. "
"Equivalent to init_strategy='olora'."
),
)
rank_pattern: Optional[Dict[str, int]] = Field(
default=None,
description=(
"Per-target-module-pattern LoRA rank override. Maps module name "
"patterns (e.g. 'q_proj', 'experts.*.w1') to integer rank values. "
"Useful for MoE configs where expert FFNs need lower rank than attn. "
"Incompatible with use_vera (VeRA shares one rank across modules)."
),
)
alpha_pattern: Optional[Dict[str, int]] = Field(
default=None,
description=(
"Per-target-module-pattern LoRA alpha override. Maps module name "
"patterns to integer alpha values. Pairs with rank_pattern. "
"Incompatible with use_vera."
),
)
init_strategy: Literal["random", "pissa", "olora", "loftq"] = Field(
default="random",
description=(
"LoRA init strategy. 'random' (default) is standard Kaiming init. "
"'pissa' (PiSSA) initializes A/B from the SVD of the base weight — "
"faster early convergence but adds an SVD pass on the first epoch. "
"'olora' is equivalent to use_olora=True (orthogonal QR init). "
"'loftq' (v0.41.0) initialises A/B + a low-bit base together, "
"useful with QLoRA. Cannot be combined with use_dora or use_vera."
),
)
# v0.41.0 Part C — LoftQ tuning knobs (used only when init_strategy='loftq').
loftq_iter: int = Field(
default=1, ge=1, le=10,
description=(
"LoftQ iteration count (1-10). Higher = better quant-aware init "
"at the cost of one-time setup latency. Used only when "
"init_strategy='loftq'."
),
)
loftq_bits: Literal[2, 4, 8] = Field(
default=4,
description=(
"LoftQ target bitwidth — must be one of {2, 4, 8}. Used only "
"when init_strategy='loftq'."
),
)
@model_validator(mode="after")
def _validate_peft_exclusivity(self) -> "LoraConfig":
enabled = [
name for name, value in (
("use_dora", self.use_dora),
("use_vera", self.use_vera),
("use_olora", self.use_olora),
)
if value
]
if len(enabled) > 1:
raise ValueError(
f"PEFT methods are mutually exclusive, got multiple enabled: "
f"{', '.join(enabled)}. Pick at most one of use_dora, "
f"use_vera, use_olora."
)
return self
@model_validator(mode="before")
@classmethod
def _backcompat_align_olora(cls, values):
"""Back-compat: pre-validation, align init_strategy='olora' when only use_olora was set."""
if not isinstance(values, dict):
return values
# Copy to avoid mutating the caller's dict (matches v0.33.0 #47
# CrossDocCollator immutability fix).
if values.get("use_olora") and "init_strategy" not in values:
values = dict(values)
values["init_strategy"] = "olora"
return values
@model_validator(mode="after")
def _validate_init_strategy(self) -> "LoraConfig":
# use_olora=True must agree with init_strategy when both are explicit
if self.use_olora and self.init_strategy != "olora":
raise ValueError(
f"use_olora=True conflicts with init_strategy={self.init_strategy!r}. "
f"Either set init_strategy='olora' (or omit it), or set use_olora=False."
)
# init_strategy='pissa' is incompatible with DoRA / VeRA
if self.init_strategy == "pissa" and (self.use_dora or self.use_vera):
other = "use_dora" if self.use_dora else "use_vera"
raise ValueError(
f"init_strategy='pissa' is incompatible with {other}=True. "
f"PiSSA initializes the LoRA pair via SVD; combine with plain LoRA "
f"(or rsLoRA) only."
)
# v0.41.0 Part C — init_strategy='loftq' is incompatible with DoRA / VeRA
if self.init_strategy == "loftq" and (self.use_dora or self.use_vera):
other = "use_dora" if self.use_dora else "use_vera"
raise ValueError(
f"init_strategy='loftq' is incompatible with {other}=True. "
f"LoftQ jointly initialises A/B with quantised base weights; "
f"combine with plain LoRA only."
)
return self
@field_validator("rank_pattern", "alpha_pattern", mode="before")
@classmethod
def _validate_pattern_dict(cls, value) -> Optional[Dict[str, int]]:
if value is None:
return None
if not isinstance(value, dict):
raise ValueError("rank_pattern/alpha_pattern must be a dict[str, int]")
if len(value) > _MAX_LORA_RANK_PATTERN_KEYS:
raise ValueError(
f"rank_pattern/alpha_pattern caps at {_MAX_LORA_RANK_PATTERN_KEYS} keys, "
f"got {len(value)}"
)
cleaned: Dict[str, int] = {}
for key, val in value.items():
if not isinstance(key, str) or not key:
raise ValueError(
"rank_pattern/alpha_pattern keys must be non-empty strings"
)
if "\x00" in key:
raise ValueError("rank_pattern/alpha_pattern keys cannot contain null bytes")
if isinstance(val, bool) or not isinstance(val, int):
raise ValueError(
f"rank_pattern/alpha_pattern values must be int, "
f"got {type(val).__name__} for {key!r}"
)
if val <= 0 or val > _MAX_LORA_RANK_PATTERN_VALUE:
raise ValueError(
f"rank_pattern/alpha_pattern values must be in (0, "
f"{_MAX_LORA_RANK_PATTERN_VALUE}], got {val} for {key!r}"
)
cleaned[key] = val
return cleaned
@field_validator("target_parameters", mode="before")
@classmethod
def _validate_target_parameters(cls, value):
if value is None or value == "auto":
return value
if not isinstance(value, list):
raise ValueError("target_parameters must be 'auto', a list[str], or null")
if len(value) > _MAX_LORA_TARGET_PARAMETERS:
raise ValueError(
f"target_parameters caps at {_MAX_LORA_TARGET_PARAMETERS} entries, "
f"got {len(value)}"
)
cleaned: List[str] = []
seen = set()
for index, entry in enumerate(value):
if not isinstance(entry, str) or not entry.strip():
raise ValueError(
f"target_parameters[{index}] must be a non-empty string"
)
target = entry.strip()
if target == "auto":
raise ValueError(
"target_parameters: use scalar 'auto', not ['auto']"
)
if "\x00" in target:
raise ValueError("target_parameters entries cannot contain null bytes")
if len(target) > _MAX_LORA_TARGET_PARAMETER_LEN:
raise ValueError(
"target_parameters entries cap at "
f"{_MAX_LORA_TARGET_PARAMETER_LEN} characters"
)
if target not in seen:
cleaned.append(target)
seen.add(target)
return cleaned
@model_validator(mode="after")
def _validate_target_parameter_compat(self) -> "LoraConfig":
if not self.target_parameters:
return self
if self.dropout != 0:
raise ValueError(
"target_parameters requires lora.dropout=0 because PEFT cannot "
"apply dropout correctly to raw nn.Parameter tensors"
)
if self.use_dora:
raise ValueError(
"target_parameters is incompatible with use_dora=True in PEFT"
)
if self.use_vera:
raise ValueError(
"target_parameters is a LoRA-only PEFT feature and is incompatible "
"with use_vera=True"
)
if self.init_strategy != "random":
raise ValueError(
"target_parameters currently requires init_strategy='random'; "
"PiSSA, OLoRA, and LoftQ are not validated for raw 3-D parameters"
)
return self
@model_validator(mode="after")
def _validate_pattern_vera_exclusivity(self) -> "LoraConfig":
if self.use_vera and self.rank_pattern:
raise ValueError(
"rank_pattern is incompatible with use_vera=True (VeRA shares "
"a single rank across all target modules). Disable use_vera or "
"remove rank_pattern."
)
if self.use_vera and self.alpha_pattern:
raise ValueError(
"alpha_pattern is incompatible with use_vera=True. Disable "
"use_vera or remove alpha_pattern."
)
return self
class DataConfig(BaseModel):
train: Union[str, List[str]] = Field(
...,
description=(
"Path to training data or HF dataset name, or a list of >= 2 "
"local file paths to combine via data.interleave. (#443)"
),
)
@field_validator("train", mode="before")
@classmethod
def _validate_train_shape(cls, v):
if isinstance(v, str):
return v
if isinstance(v, list):
if len(v) == 0:
raise ValueError("data.train list must not be empty")
if len(v) == 1:
raise ValueError(
"data.train list must have >= 2 entries for "
"data.interleave — use a single string path for one "
"dataset"
)
for i, entry in enumerate(v):
if not isinstance(entry, str) or not entry.strip():
raise ValueError(
f"data.train[{i}] must be a non-empty string"
)
return v
raise ValueError(
"data.train must be a string or a list of strings "
f"(got {type(v).__name__})"
)
format: Literal[
"alpaca", "sharegpt", "chatml", "dpo", "kto", "llava", "sharegpt4v",
"plaintext", "embedding", "audio", "tool-calling", "auto",
# v0.42.0 — Data Pipeline Pro
"prm", "pre_tokenized", "input_output", "video", "multimodal",
# v0.62.0 Part A — RAFT (Retrieval-Augmented Fine-Tuning)
"raft",
# v0.71.32 — ASR (Whisper): rows are {"audio": path, "text": transcript}
"asr",
] = Field(
default="auto",
description="Data format",
)
val_split: float = Field(default=0.1, ge=0.0, le=0.5, description="Validation split ratio")
max_length: int = Field(
default=2048, ge=64, le=1048576,
description="Max sequence length in tokens",
)
image_dir: Optional[str] = Field(
default=None,
description="Base directory for resolving relative image paths in vision datasets",
)
audio_dir: Optional[str] = Field(
default=None,
description="Base directory for resolving relative audio paths in audio datasets",
)
train_on_responses_only: bool = Field(
default=True,
description=(
"Mask non-assistant tokens with IGNORE_INDEX (-100). When True, "
"only assistant content contributes to the SFT loss. Mirrors "
"LlamaFactory + Axolotl default — replaces TRL's heuristic. (v0.36.0)"
),
)
train_on_messages_with_train_field: bool = Field(
default=False,
description=(
"Per-message training mask via messages[i].train: bool. "
"Mutually exclusive with train_on_responses_only. (v0.36.0)"
),
)
chat_template: Optional[str] = Field(
default=None,
description=(
"Override the tokenizer chat template. Accepts a registered "
"name (chatml, llama3, qwen2.5, mistral, gemma3, phi4, "
"deepseek-r1) or a raw Jinja string. None = use the tokenizer's "
"shipped template (errors loudly if absent). (v0.36.0)"
),
)
raft_shuffle_seed: Optional[int] = Field(
default=None,
ge=0,
le=2_147_483_647,
description=(
"Seed for the RAFT golden/distractor document shuffle "
"(data.format='raft'). Documents are always shuffled for "
"distractor robustness; this knob fixes which reproducible "
"permutation. None = seed 0. (v0.71.10 #199)"
),
)
@field_validator("raft_shuffle_seed", mode="before")
@classmethod
def _validate_raft_shuffle_seed(cls, v):
# Bool is a subclass of int — reject before Pydantic coerces True->1
# (project bool-as-int policy).
if isinstance(v, bool):
raise ValueError("raft_shuffle_seed must not be a bool")
return v
raft_epoch_shuffle: bool = Field(
default=False,
description=(
"Re-permute RAFT golden/distractor documents EACH training epoch "
"(data.format='raft'). When False (default) the document order is "
"baked once at tokenisation time and fixed across epochs; when "
"True the trainer re-composes + re-tokenises rows per epoch with "
"an epoch salt so the model cannot memorise a fixed golden-doc "
"slot. (v0.71.17 #253)"
),
)
# --- v0.71.36 Data Moat II: continual-learning rehearsal ---------------
replay: Optional[str] = Field(
default=None,
description=(
"Path to an OLD dataset to interleave into training as "
"continual-learning rehearsal, so fine-tuning on a new task does "
"not erase the previous one. Rows are mixed into train ONLY "
"(never val, which stays pure new-task). sft / pretrain only; "
"incompatible with packing / multipack. (v0.71.36)"
),
)
replay_ratio: float = Field(
default=0.1,
gt=0.0,
le=0.5,
description=(
"Fraction of the FINAL mixed train set that is replay rows: "
"n_replay = round(r/(1-r) * n_new). At 0.1 over 1000 new rows "
"that is 111 replay rows -> 1111 total -> 10.0%. (v0.71.36)"
),
)
replay_seed: Optional[int] = Field(
default=None,
ge=0,
le=2_147_483_647,
description=(
"Seed for the replay sample + interleave. None = seed 0. "
"(v0.71.36)"
),
)
@field_validator("replay")
@classmethod
def _validate_replay_path(cls, v):
if v is None:
return None
if not isinstance(v, str):
raise ValueError("data.replay must be a string path")
cleaned = v.strip()
if not cleaned:
raise ValueError("data.replay must be a non-empty path")
if "\x00" in cleaned:
raise ValueError("data.replay must not contain null bytes")
if len(cleaned) > 4096:
raise ValueError("data.replay path too long (max 4096 chars)")
return cleaned
@field_validator("replay_ratio", mode="before")
@classmethod
def _validate_replay_ratio(cls, v):
# Bool is a subclass of int/float — reject before coercion.
if isinstance(v, bool):
raise ValueError("data.replay_ratio must not be a bool")
return v
@field_validator("replay_seed", mode="before")
@classmethod
def _validate_replay_seed(cls, v):
if isinstance(v, bool):
raise ValueError("data.replay_seed must not be a bool")
return v
# --- v0.42.0 Data Pipeline Pro -----------------------------------------
video_dir: Optional[str] = Field(
default=None,
description=(
"Base directory for resolving relative video paths in video "
"datasets. Mirrors image_dir / audio_dir. (v0.42.0 Part A)"
),
)
tokenized_path: Optional[str] = Field(
default=None,
description=(
"Path to a pre-tokenized cache produced by `soup data preprocess`. "
"When set, the trainer skips the tokenize stage and reads tensors "
"directly. Mirrors LF tokenized_path / Axolotl `empty` type. "
"(v0.42.0 Part C)"
),
)
streaming: bool = Field(
default=False,
description=(
"Pass-through to HF datasets `streaming=True`. Use for datasets "
"that don't fit on disk. Pairs with `buffer_size`. (v0.42.0 Part B)"
),
)
buffer_size: Optional[int] = Field(
default=None,
description=(
"Shuffle buffer size for streaming datasets. None = HF default. "
"Bounds [1, 1_000_000]. (v0.42.0 Part B)"
),
)
shards: Optional[int] = Field(
default=None,
description=(
"Number of shards for HF dataset splits (axolotl `shards`). "
"Bounds [1, 1024]. (v0.42.0 Part B)"
),
)
interleave: Optional[Union[str, Dict]] = Field(
default=None,
description=(
"Multi-dataset interleave strategy: 'concat' / 'under' / 'over' / "
"{strategy: 'probs', probs: [...]}. (v0.42.0 Part D)"
),
)
mask_history: bool = Field(
default=False,
description=(
"LF mask_history — mask all but the last assistant turn during "
"loss computation. (v0.42.0 Part D)"
),
)
train_on_prompt: bool = Field(
default=False,
description=(
"LF train_on_prompt — include the prompt tokens in the loss. "
"Inverse of train_on_responses_only. (v0.42.0 Part D)"
),
)
eval_on_each_dataset: bool = Field(
default=False,
description=(
"LF eval_on_each_dataset — when interleaving, run eval on every "
"constituent dataset separately. (v0.42.0 Part D)"
),
)
split_thinking: bool = Field(
default=False,
description=(
"Axolotl split_thinking — separate `<think>` reasoning blocks "
"from the final answer for fine-grained masking. Qwen3-style. "
"(v0.42.0 Part D)"
),
)
image_min_pixels: Optional[int] = Field(
default=None,
description="Per-image min pixel count for vision data. (v0.42.0 Part D)",
)
image_max_pixels: Optional[int] = Field(
default=None,
description="Per-image max pixel count for vision data. (v0.42.0 Part D)",
)
image_resize_algorithm: Optional[
Literal["nearest", "bilinear", "bicubic", "lanczos"]
] = Field(
default=None,
description="Pillow resize algorithm for image preprocessing. (v0.42.0 Part D)",
)
video_fps: Optional[float] = Field(
default=None,
description=(
"Target frames-per-second for video preprocessing. (v0.42.0 Part D)"
),
)
video_maxlen: Optional[int] = Field(
default=None,
description=(
"Max number of frames per video clip. Bounds (0, 4096]. "
"(v0.42.0 Part D)"
),
)
add_new_tokens: Optional[List[str]] = Field(
default=None,
description=(
"Add these tokens to the tokenizer vocab + resize embeddings. "
"Cap 10_000 entries; per-token <= 256 chars; no duplicates. "
"(v0.42.0 Part E)"
),
)
new_special_tokens: Optional[List[str]] = Field(
default=None,
description=(
"Like add_new_tokens but registered as additional_special_tokens "
"so they are not split by the tokenizer. (v0.42.0 Part E)"
),
)
resize_vocab: bool = Field(
default=False,
description=(
"Resize the model's input/output embedding matrix when "
"add_new_tokens / new_special_tokens grew the vocab. "
"(v0.42.0 Part E)"
),
)
extend_conversation: bool = Field(
default=False,
description=(
"Unsloth-style conversation extension — extend the last assistant "
"turn with N more tokens for 'continue' prompts. (v0.42.0 Part E)"
),
)
skip_prepare_dataset: bool = Field(
default=False,
description=(
"Axolotl skip_prepare_dataset — escape hatch when the input is "
"already in the trainer's expected schema. (v0.42.0 Part E)"
),
)
remove_unused_columns: bool = Field(
default=True,
description=(
"HF Trainer remove_unused_columns. Set False when feeding "
"extra cols to a custom collator. (v0.42.0 Part E)"
),
)
prompt_strategy: Optional[str] = Field(
default=None,
description=(
"Axolotl-style 'module.path:function_name' Python transform. "
"Schema-only in v0.42.0 — runtime invocation lands in v0.42.1. "
"(v0.42.0 Part E)"
),
)
# ---- v0.61.0 Part A — Unlearning data sources --------------------------
forget_set: Optional[str] = Field(
default=None,
description=(
"Path or HF dataset name for the forget set (rows to unlearn). "
"Required when task='unlearn'. Null-byte rejected, capped at "
"4096 chars. Containment is deferred to the trainer-side loader "
"so HF dataset IDs (e.g. ``locuslab/TOFU``) still pass schema. "
"(v0.61.0 Part A)"
),
)
retain_set: Optional[str] = Field(
default=None,
description=(
"Path or HF dataset name for the retain set (rows whose "
"performance must be preserved). Optional but recommended — "
"NPO/SimNPO/RMU all degrade without one. Same validation as "
"forget_set. (v0.61.0 Part A)"
),
)
@field_validator("forget_set", "retain_set")
@classmethod
def _validate_unlearn_dataset_path(cls, value: Optional[str]) -> Optional[str]:
"""v0.61.0 Part A — shape-only validation for forget/retain refs.
Accepts None, an HF dataset id (e.g. ``locuslab/TOFU``), or a
local relative path. Null-byte rejected, oversize rejected.
Containment check is deliberately deferred to the trainer-side
loader so legitimate HF dataset IDs (which look like file paths
with a slash) still pass schema-load — mirrors v0.40.5
``reward_model`` policy.
"""
if value is None:
return None
if not isinstance(value, str):
raise ValueError("forget_set / retain_set must be a string")
if not value:
return None
if "\x00" in value:
raise ValueError(
"forget_set / retain_set must not contain null bytes"
)
if len(value) > 4096:
raise ValueError(
"forget_set / retain_set must be <= 4096 chars"
)
return value
@field_validator("video_dir", "tokenized_path")
@classmethod
def _validate_v042_optional_path(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return None
if not isinstance(value, str):
raise ValueError("path must be a string")
if not value:
return None
if "\x00" in value:
raise ValueError("path must not contain null bytes")
if len(value) > 4096:
raise ValueError("path must be <= 4096 chars")
# Schema-level containment via shared `is_under_cwd` (os.path.realpath
# + commonpath). Rejects arbitrary system paths at config load so a
# crafted soup.yaml fails fast instead of at first filesystem read.
from soup_cli.utils.paths import is_under_cwd
if not is_under_cwd(value):
raise ValueError(
"path must stay under the current working directory "
"(absolute paths outside cwd are rejected at config load)."
)
return value
@field_validator("buffer_size")
@classmethod
def _validate_buffer_size_v042(cls, value: Optional[int]) -> Optional[int]:
from soup_cli.utils.data_pipeline import validate_buffer_size
return validate_buffer_size(value)
@field_validator("shards")
@classmethod
def _validate_shards_v042(cls, value: Optional[int]) -> Optional[int]:
from soup_cli.utils.data_pipeline import validate_shards
return validate_shards(value)
@field_validator("image_min_pixels", "image_max_pixels")
@classmethod
def _validate_image_pixels_v042(cls, value, info):
from soup_cli.utils.data_pipeline import validate_image_pixels
return validate_image_pixels(info.field_name, value)
@field_validator("video_fps")
@classmethod
def _validate_video_fps_v042(cls, value: Optional[float]) -> Optional[float]:
from soup_cli.utils.data_pipeline import validate_video_fps
return validate_video_fps(value)
@field_validator("video_maxlen")
@classmethod
def _validate_video_maxlen_v042(cls, value: Optional[int]) -> Optional[int]:
from soup_cli.utils.data_pipeline import validate_video_maxlen
return validate_video_maxlen(value)
@field_validator("add_new_tokens", "new_special_tokens")
@classmethod
def _validate_new_tokens_v042(
cls, value: Optional[List[str]]
) -> Optional[List[str]]:
from soup_cli.utils.data_pipeline import validate_new_tokens
return validate_new_tokens(value)
@field_validator("prompt_strategy")
@classmethod
def _validate_prompt_strategy_v042(cls, value: Optional[str]) -> Optional[str]:
from soup_cli.utils.data_pipeline import validate_prompt_strategy
return validate_prompt_strategy(value)
@field_validator("interleave")
@classmethod
def _validate_interleave_v042(cls, value):
# Shape validation only, independent of `train`. We accept None /
# str / dict here and reject obvious type errors so a YAML like
# ``data.interleave: 99`` fails loudly at config load. The full
# parse (which needs num_datasets = len(data.train)) now happens
# in SoupConfig._validate_interleave_compat below — num_datasets is
# a parse-time constant since #443 widened data.train to accept a
# list.
if value is None:
return None
if isinstance(value, str):
from soup_cli.utils.data_pipeline import INTERLEAVE_STRATEGIES
if value not in INTERLEAVE_STRATEGIES:
raise ValueError(
f"interleave must be one of {sorted(INTERLEAVE_STRATEGIES)} "
f"or a dict — got {value!r}"
)
if value == "probs":
# Probs requires the dict form so the per-dataset weights are
# supplied — bare "probs" is meaningless.
raise ValueError(
"interleave='probs' requires a 'probs' list — use "
"{strategy: probs, probs: [...]} dict form."
)
return value
if isinstance(value, dict):
if "strategy" not in value:
raise ValueError(
"interleave dict form must include 'strategy' key"
)
return value
raise ValueError(
f"interleave must be None, a string, or a dict (got "
f"{type(value).__name__})"
)
@field_validator("chat_template")
@classmethod
def _validate_chat_template(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return None
if not isinstance(value, str):
raise ValueError("chat_template must be a string")
if not value:
return None
if "\x00" in value:
raise ValueError("chat_template must not contain null bytes")
if len(value) > 65536:
raise ValueError("chat_template must be <= 64KB")
# Block Jinja directives that touch the filesystem or load arbitrary
# modules. Only control-flow + variable interpolation are allowed
# for raw chat-template strings (v0.36.0 security review fix).
lower = value.lower()
for tag in ("{%- include", "{% include", "{%- import", "{% import",
"{%- from", "{% from", "{%- macro", "{% macro",
"{%- extends", "{% extends"):
if tag in lower:
directive = tag.split(None, 1)[-1]
raise ValueError(
f"chat_template may not use Jinja '{directive}' directive — "
f"only control-flow and variable interpolation are allowed."
)
return value
@model_validator(mode="after")
def _validate_loss_mask_exclusivity(self) -> "DataConfig":
if self.train_on_responses_only and self.train_on_messages_with_train_field:
raise ValueError(
"train_on_responses_only and train_on_messages_with_train_field "
"are mutually exclusive. Disable one. The per-message 'train' "
"field is opt-in for fine-grained per-message control."
)
return self
@model_validator(mode="after")
def _validate_v042_train_on_prompt(self) -> "DataConfig":
# train_on_prompt is the inverse semantics of train_on_responses_only —
# both True is contradictory. Match v0.36.0 loss-mask exclusivity policy.
if self.train_on_prompt and self.train_on_responses_only:
raise ValueError(
"train_on_prompt and train_on_responses_only are mutually "
"exclusive — train_on_prompt opts INTO prompt-token loss, "
"train_on_responses_only opts OUT. Pick one."
)
return self
@model_validator(mode="after")
def _validate_v042_image_pixel_range(self) -> "DataConfig":
if (
self.image_min_pixels is not None
and self.image_max_pixels is not None
and self.image_min_pixels > self.image_max_pixels
):
raise ValueError(
"image_min_pixels must be <= image_max_pixels"
)
return self
@model_validator(mode="after")
def _validate_v042_streaming_buffer(self) -> "DataConfig":
# buffer_size only meaningful when streaming=True — surface the
# mismatch loudly (mirrors v0.32.0 spike-recovery / loss-watchdog
# cross-validator policy).
if self.buffer_size is not None and not self.streaming:
raise ValueError(
"buffer_size requires streaming=True (HF datasets only "
"supports a shuffle buffer in streaming mode)."
)
return self
@model_validator(mode="after")
def _validate_v042_video_fields(self) -> "DataConfig":
# Video-only fields must not be set when format != 'video' to avoid
# silent no-ops (Axolotl-mode footgun this validator prevents).
video_fields = (
("video_fps", self.video_fps),
("video_maxlen", self.video_maxlen),
("video_dir", self.video_dir),
)
any_set = any(v is not None for _, v in video_fields)
if any_set and self.format not in ("video", "multimodal", "auto"):
names = [n for n, v in video_fields if v is not None]
raise ValueError(
f"video-related fields {names} require format in "
"{video, multimodal, auto} (got "
f"{self.format!r})."
)
return self
@model_validator(mode="after")
def _validate_v042_resize_vocab_requires_tokens(self) -> "DataConfig":
if self.resize_vocab and not (
self.add_new_tokens or self.new_special_tokens
):
raise ValueError(
"resize_vocab=True requires add_new_tokens or "
"new_special_tokens to be non-empty — otherwise the resize is "
"a no-op."
)
return self
@model_validator(mode="after")
def _validate_v042_pre_tokenized_path(self) -> "DataConfig":
# tokenized_path is meaningful regardless of format (Axolotl `empty`
# type expects the cache to be the source of truth). But the
# pre_tokenized format implies the path must be set.
if self.format == "pre_tokenized" and not self.tokenized_path:
raise ValueError(
"format='pre_tokenized' requires data.tokenized_path to point "
"at a cache directory produced by `soup data preprocess`."
)
return self
class AdviseConfig(BaseModel):
"""Pre-flight decision config (v0.54.0 — schema-only).
Surfaces the `soup advise` knobs through the central config schema so a
`soup.yaml` can carry persistent advise settings (e.g. a frozen goal
string + history-log path override). Live consumption is owned by
``soup_cli/commands/advise.py``; this field is informational on
``SoupConfig`` only.
"""
goal: Optional[str] = Field(
default=None,
max_length=4096,
description=(
"Default goal string for `soup advise`. Sharpens task "
"classification when set."
),
)
probe: bool = Field(
default=False,
description=(
"Run the 10-minute ROI probe by default when `soup advise` is "
"invoked through this config. Heuristic stubs in v0.54.0."
),
)
record: bool = Field(
default=False,
description=(
"Append every verdict from this config to "
"~/.soup/advise_history.jsonl with accepted=True."
),
)
@field_validator("goal")
@classmethod
def _goal_no_null_byte(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return value
if not isinstance(value, str):
raise TypeError("advise.goal must be a string")
if "\x00" in value:
raise ValueError("advise.goal must not contain null bytes")
return value
class EvalGateConfig(BaseModel):
"""Eval-Gated Training config (v0.26.0 Part B).
Runs a declarative eval suite at epoch boundaries and halts training
if any task regresses below ``regression_threshold`` vs the baseline.
"""
enabled: bool = Field(
default=False,
description="Turn the eval gate on",
)
suite: Optional[str] = Field(
default=None,
description="Path to eval-suite YAML (evals/gate.yaml)",
)
every_n_epochs: int = Field(
default=1, ge=1, le=100,
description="Run gate every N epochs (1-100)",
)