forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
2249 lines (2023 loc) · 88.2 KB
/
Copy pathtrain.py
File metadata and controls
2249 lines (2023 loc) · 88.2 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
"""soup train — the main training command."""
from __future__ import annotations
import contextlib
import os
import re
from pathlib import Path
from typing import TYPE_CHECKING
import typer
from rich.console import Console
from rich.markup import escape as markup_escape
from rich.panel import Panel
from soup_cli.config.loader import load_config
from soup_cli.data.loader import load_dataset
from soup_cli.monitoring.display import TrainingDisplay
from soup_cli.utils.gpu import detect_device, get_gpu_info, resolve_quantization
if TYPE_CHECKING: # pragma: no cover - type hints only, no runtime import
from soup_cli.config.schema import SoupConfig
from soup_cli.utils.energy import EnergyMeasurement
console = Console()
# Optimizers the analytical hardware-fit predictor understands (mirror of
# hardware_fit._VALID_OPTIMIZERS); an unknown optimizer maps to the
# highest-state default so the estimate stays conservative.
_HW_FIT_OPTIMIZERS = frozenset({
"adamw_torch", "adamw_torch_fused", "adafactor", "sgd",
"adamw_bnb_8bit", "paged_adamw_8bit", "lion_8bit",
"lomo", "adalomo", "schedule_free_adamw",
})
def _build_hardware_fit_input(cfg):
"""Best-effort ``HardwareFitInput`` from a ``SoupConfig``.
Returns ``None`` when the run is not statically predictable (batch_size
``"auto"``, unknown model size, unsupported quant, out-of-range dims), in
which case the caller skips the gate rather than guess.
"""
from soup_cli.trainer.sft import is_full_finetune
from soup_cli.utils.gpu import model_size_from_name
from soup_cli.utils.hardware_fit import HardwareFitInput
tcfg = cfg.training
bs = getattr(tcfg, "batch_size", None)
if not isinstance(bs, int) or isinstance(bs, bool):
return None # "auto" resolves later — can't predict yet
params_b = model_size_from_name(getattr(cfg, "base", "") or "")
if not isinstance(params_b, (int, float)) or params_b <= 0:
return None
seq_len = getattr(cfg.data, "max_length", None)
if not isinstance(seq_len, int) or isinstance(seq_len, bool):
return None
quant = {"none": "none", "4bit": "4bit", "8bit": "8bit"}.get(
str(getattr(tcfg, "quantization", "none") or "none")
)
if quant is None:
return None
if quant == "4bit":
peft = "qlora"
elif is_full_finetune(tcfg):
# #471 — was an independent, hand-maintained check
# (unfrozen_parameters / freeze_layers / freeze_ratio) that had
# drifted from sft.py's real full-FT decision in BOTH directions:
# it missed lisa_enabled/lora.r==0 (under-predicting VRAM for those
# runs) and treated bare freeze_layers/freeze_ratio as sufficient on
# its own even with lora.r>0 still on (over-predicting — and able to
# falsely refuse a launch that would fit, since freeze_layers/
# freeze_ratio only reduce what's trainable WITHIN LoRA or full-FT,
# they don't select the mode). Now shares is_full_finetune with
# sft.py's SFTTrainerWrapper._resolve_load_dtype so the two cannot
# disagree again.
#
# #377 — lisa_train_embeddings=false freezes the always-on group and
# lowers real VRAM, but LISA stays "full" here on purpose: the analytical
# predictor has no measured constant for the frozen-embeddings trainable
# set, and over-predicting is the safe failure (under-predicting is a
# silent WDDM spill on Windows). A frozen-embeddings run that would fit
# can therefore still be refused by pre-flight; --allow-oom-attempt is
# the documented bypass, and crediting the saving is a hardware follow-up.
peft = "full"
else:
peft = "lora"
optimizer = str(getattr(tcfg, "optimizer", "adamw_torch") or "adamw_torch")
if optimizer not in _HW_FIT_OPTIMIZERS:
optimizer = "adamw_torch"
gc = bool(getattr(tcfg, "gradient_checkpointing", False))
try:
return HardwareFitInput(
params_b=float(params_b),
seq_len=int(seq_len),
batch_size=int(bs),
optimizer=optimizer,
quant=quant,
peft=peft,
gradient_checkpointing=gc,
)
except (ValueError, TypeError):
return None # dims out of the predictor's supported range
def _hardware_fit_preflight(cfg, gpu_info, *, allow_oom_attempt: bool) -> None:
"""Refuse (or warn) before launch when the predicted peak VRAM won't fit.
Skips silently on CPU / when VRAM is unknown / when the run isn't
statically predictable, so CI and small runs are unaffected. Honors the
documented ``--allow-oom-attempt`` opt-out.
"""
# v0.72.0 — layer streaming bounds peak VRAM by ONE decoder layer, so the
# resident prediction (full weights + optimizer + grads on the card) is the
# wrong model entirely: it refuses exactly the runs streaming exists to
# enable. The streaming path runs its own pre-flight instead (RAM-tier fit
# + the plan panel in _setup_streaming_transformers).
if getattr(cfg.training, "stream_layers", False):
return
# MLX uses Apple unified memory and its own runtime allocator, so the
# CUDA-shaped analytical VRAM predictor is skipped. On a non-Apple host,
# ``backend: mlx`` still skips harmlessly: ``resolve_trainer`` fails on
# the ``mlx_lm`` import before training starts, so there is no silent
# hazard from bypassing the gate.
if getattr(cfg, "backend", None) == "mlx":
return
total_bytes = 0
try:
total_bytes = int(gpu_info.get("memory_total_bytes", 0) or 0)
except (AttributeError, TypeError, ValueError):
return
if total_bytes <= 0:
return # no CUDA VRAM to predict against
inp = _build_hardware_fit_input(cfg)
if inp is None:
return
from soup_cli.utils.hardware_fit import VRAM_SAFETY_MARGIN, decide_hardware_fit
report = decide_hardware_fit(inp, available_vram_gb=total_bytes / 1e9)
if report.ok:
return
b = report.breakdown
tail = (
"[yellow]--allow-oom-attempt set: launching anyway.[/]"
if allow_oom_attempt
else "Reduce batch_size / max_length, enable gradient_checkpointing or "
"quantization, or pass [bold]--allow-oom-attempt[/] to try anyway."
)
console.print(
Panel(
f"Predicted peak VRAM [bold]{report.peak_vram_gb:.1f} GB[/] "
f"(+{int(VRAM_SAFETY_MARGIN * 100)}% margin = "
f"{report.required_with_margin_gb:.1f} GB) exceeds "
f"{report.available_vram_gb:.1f} GB available.\n"
f"weights {b.weights_gb:.1f} | optim {b.optimizer_gb:.1f} | "
f"grads {b.gradients_gb:.1f} | activations {b.activations_gb:.1f} "
f"| overhead {b.overhead_gb:.1f} GB\n\n" + tail,
title=(
"[yellow]Hardware-fit warning[/]"
if allow_oom_attempt
else "[bold red]Hardware-fit gate[/]"
),
border_style="yellow" if allow_oom_attempt else "red",
)
)
if not allow_oom_attempt:
raise typer.Exit(1)
def _apply_replay_overrides(cfg, *, replay, replay_ratio, replay_seed=None):
"""Apply the ``--replay*`` flags, then RE-VALIDATE.
Re-validation is the point: a CLI override must clear the same
cross-validators as YAML, or ``--replay`` on ``task='dpo'`` would slip
past ``_validate_replay_compat``. Rebuilding the model (rather than
mutating in place) is what re-runs them, and leaves the caller's config
untouched.
"""
if replay is None and replay_ratio is None and replay_seed is None:
return cfg
payload = cfg.model_dump()
if replay is not None:
payload["data"]["replay"] = replay
if replay_ratio is not None:
payload["data"]["replay_ratio"] = replay_ratio
if replay_seed is not None:
payload["data"]["replay_seed"] = replay_seed
return type(cfg)(**payload)
def train(
config: str = typer.Option(
"soup.yaml",
"--config",
"-c",
help="Path to soup.yaml config file",
),
name: str = typer.Option(
None,
"--name",
"-n",
help="Experiment name (auto-generated if not set)",
),
dry_run: bool = typer.Option(
False,
"--dry-run",
help="Validate config and data without training",
),
resume: str = typer.Option(
None,
"--resume",
"-r",
help="Resume from checkpoint: path to checkpoint dir ('auto' for latest); "
"on the MLX backend, a path to a .safetensors adapter file instead",
),
wandb: bool = typer.Option(
False,
"--wandb",
help="Enable Weights & Biases logging",
),
tensorboard: bool = typer.Option(
False,
"--tensorboard",
help="Enable TensorBoard logging (logs to output_dir/runs/)",
),
tracker: str = typer.Option(
None,
"--tracker",
help=(
"Experiment tracker: mlflow / swanlab / trackio (v0.43.0). "
"Mutually exclusive with --wandb / --tensorboard."
),
),
deepspeed: str = typer.Option(
None,
"--deepspeed",
help=(
"Enable DeepSpeed: zero2, zero3, zero2_offload, zero3_offload "
"(stage 3 + CPU parameter offload), zero++ (ZeRO++), "
"or path to config JSON"
),
),
fsdp: str = typer.Option(
None,
"--fsdp",
help="Enable FSDP2: full_shard, shard_grad, or full_offload",
),
gpus: str = typer.Option(
None,
"--gpus",
help="Number of GPUs for distributed training ('auto' or integer)",
),
no_reexec: bool = typer.Option(
False,
"--no-reexec",
help=(
"When --gpus N>1, print the accelerate launch command instead "
"of auto-reexec under it (v0.33.0 #37 default behaviour: reexec)"
),
),
gate: str = typer.Option(
None,
"--gate",
help=(
"Enable eval-gated training with a suite file "
"(shortcut for training.eval_gate.enabled=true + suite=<path>)"
),
),
push_as: str = typer.Option(
None,
"--push-as",
help=(
"Auto-push each save_steps checkpoint to HF Hub as "
"'checkpoint-<step>' branch of the given repo (e.g. user/my-model)"
),
),
hf_resume: bool = typer.Option(
False,
"--hf-resume",
help=(
"Download the latest checkpoint branch from the --push-as repo "
"and resume from it. Requires --push-as."
),
),
find_lr: bool = typer.Option(
False,
"--find-lr",
help=(
"LR range finder (v0.32.0): run a short geometric LR sweep, write "
"a JSON report with the recommended LR, then exit without training."
),
),
find_lr_start: float = typer.Option(
1e-7,
"--find-lr-start",
help="LR range finder: starting LR (default 1e-7)",
),
find_lr_end: float = typer.Option(
1e-1,
"--find-lr-end",
help="LR range finder: ending LR (default 1e-1)",
),
find_lr_steps: int = typer.Option(
100,
"--find-lr-steps",
help="LR range finder: number of sweep steps (default 100)",
),
find_lr_output: str = typer.Option(
"lr_finder.json",
"--find-lr-output",
help="LR range finder: JSON report path (default ./lr_finder.json)",
),
yes: bool = typer.Option(
False,
"--yes",
"-y",
help="Skip confirmation prompt",
),
trust_remote_code: bool = typer.Option(
False,
"--trust-remote-code",
help=(
"Allow loading models that ship custom Python via auto_map. "
"Default deny (v0.36.0). Only enable if you trust the source."
),
),
echo_trap_tokenizer_aware: bool = typer.Option(
False,
"--echo-trap-tokenizer-aware",
help=(
"Use tokenizer-id n-grams for echo-trap scoring. Requires "
"training.echo_trap_enabled=true on grpo/ppo."
),
),
reward_hack_detector: str = typer.Option(
None,
"--reward-hack-detector",
help=(
"Reward-hacking detector for GRPO/PPO: info_rm | rm_ensemble. "
"Overrides training.reward_hack_detector. (v0.71.26)"
),
),
reward_hack_halt: bool = typer.Option(
False,
"--reward-hack-halt",
help=(
"Auto-halt training on a HACK verdict. Requires "
"--reward-hack-detector (or training.reward_hack_detector). (v0.71.26)"
),
),
replay: str = typer.Option(
None, "--replay",
help=(
"Old dataset to interleave as continual-learning rehearsal, so "
"training on the new task does not erase the previous one. "
"sft/pretrain only; incompatible with packing/multipack. "
"Overrides data.replay. (v0.71.36)"
),
),
replay_ratio: float = typer.Option(
None, "--replay-ratio",
help=(
"Fraction of the FINAL mixed train set that is replay rows "
"(default 0.1). Overrides data.replay_ratio. (v0.71.36)"
),
),
replay_seed: int = typer.Option(
None, "--replay-seed",
help=(
"Seed for the replay sample + interleave. Overrides "
"data.replay_seed. (v0.71.36)"
),
),
reward_hack_mitigation: str = typer.Option(
None,
"--reward-hack-mitigation",
help=(
"Closed-loop reward-hacking mitigation mode: off | log_only | "
"kl_control | pid_lagrangian. Requires training.reward_hack_detector "
"on grpo/ppo. Overrides training.reward_hack_mitigation. (v0.71.26)"
),
),
minillm_on_policy: bool = typer.Option(
False,
"--minillm-on-policy",
help=(
"Use the TRUE on-policy MiniLLM teacher-mixed rollout (v0.71.18 "
"#257) instead of the offline distribution blend. Requires "
"training.minillm_enabled=true on task='distill'."
),
),
profile_run: bool = typer.Option(
False,
"--profile",
help=(
"Record a torch.profiler trace (Chrome trace JSON) during early "
"training steps. Output: <output>/profiles/<run_id>.trace.json"
),
),
allow_oom_attempt: bool = typer.Option(
False,
"--allow-oom-attempt",
help=(
"Bypass the analytical hardware-fit VRAM gate and launch even when "
"the run is predicted to run out of GPU memory (opt-out)."
),
),
diagnose_gate: str = typer.Option(
None,
"--diagnose-gate",
help=(
"After training, run `soup diagnose` against the supplied evidence "
"JSON (or scratch evidence). Refuses to mark the run successful "
"if any of the 6 v0.56.0 failure modes returns MAJOR."
),
),
annex_xi: str = typer.Option(
None,
"--annex-xi",
help=(
"After training, render an EU AI Act Annex XI/XII auto-doc to the "
"given output path (cwd-contained). Markdown body now; PDF in v0.59.1."
),
),
repro_receipt: str = typer.Option(
None,
"--repro-receipt",
help=(
"After training, write an SR 11-7-style reproducibility receipt "
"(seeds + kernel versions + GPU + OS) to the given path. v0.59.0."
),
),
capture_activations: str = typer.Option(
None,
"--capture-activations",
help=(
"After training, capture residual-stream activations at the named "
"decoder layer (e.g. model.layers.5) on --capture-prompts and write "
"them to <output>/activations/activations.json for soup probe "
"sae-diff / sleeper. v0.71.8 #219."
),
),
capture_prompts: str = typer.Option(
None,
"--capture-prompts",
help=(
"JSONL (or .txt) of prompts to run for --capture-activations "
"(one prompt per line; 'prompt'/'text' field or raw text)."
),
),
track_energy: bool = typer.Option(
False,
"--track-energy",
help=(
"Measure the training window's energy + CO2 via codecarbon "
"(offline; requires `pip install soup-cli\\[carbon]`). Feeds the "
"kWh / CO2 into --annex-xi. v0.71.3."
),
),
energy_country: str = typer.Option(
"USA",
"--energy-country",
help=(
"ISO 3166-1 alpha-3 country code for the CO2 grid-intensity "
"estimate used by --track-energy (default USA)."
),
),
energy_out: str = typer.Option(
None,
"--energy-out",
help=(
"Write the --track-energy measurement to this JSON file (cwd-"
"contained) so `soup bom emit --energy <path>` can consume it. "
"v0.71.15."
),
),
cloud: str = typer.Option(
None,
"--cloud",
help=(
"Train on a cloud GPU instead of locally (v0.71.18 #16). Supported: "
"modal, lambda (runpod is planned). Renders a cloud app stub from the config "
"(plan-only); use --cloud-submit to submit live."
),
),
gpu: str = typer.Option(
"a100",
"--gpu",
help=(
"Cloud GPU type for --cloud (t4 / l4 / a10 / a10g / a100 / a100-80gb / "
"l40s / h100 / a6000). Default a100. Provider-specific allowlists apply."
),
),
cloud_submit: bool = typer.Option(
False,
"--cloud-submit",
help=(
"With --cloud, submit the rendered run live via the cloud's SDK or API "
"(gated on respective provider token/API key). Default is plan-only "
"(render + print the command). Lambda requires a registered SSH key."
),
),
):
"""Start training from a soup.yaml config."""
config_path = Path(config)
if not config_path.exists():
console.print(f"[red]Config not found: {config_path}[/]")
console.print("Run [bold]soup init[/] to create one.")
raise typer.Exit(1)
# --- LR range finder fast path ---
if find_lr:
from soup_cli.utils.lr_finder import (
compute_lr_schedule,
save_lr_finder_report,
)
try:
schedule = compute_lr_schedule(
start_lr=find_lr_start,
end_lr=find_lr_end,
num_steps=find_lr_steps,
)
except ValueError as exc:
console.print(f"[red]Invalid --find-lr range:[/] {exc}")
raise typer.Exit(1) from exc
# v0.33.0 #56: live LR-sweep training loop. Falls back to a
# synthetic curve only when the real loop cannot run (no torch /
# config load failure) so users still get a parseable report.
losses_for_report = _run_live_lr_sweep_or_synth(
config_path, schedule,
)
try:
save_lr_finder_report(schedule, losses_for_report, find_lr_output)
except ValueError as exc:
console.print(f"[red]Invalid --find-lr-output:[/] {exc}")
raise typer.Exit(1) from exc
console.print(f"[green]LR finder report written to:[/] {find_lr_output}")
raise typer.Exit(0)
# Load & validate config
console.print(f"[dim]Loading config from {config_path}...[/]")
cfg = load_config(config_path)
# --- v0.71.36 replay passthrough ---
try:
cfg = _apply_replay_overrides(
cfg,
replay=replay,
replay_ratio=replay_ratio,
replay_seed=replay_seed,
)
except Exception as exc: # noqa: BLE001 — pydantic ValidationError et al.
console.print(f"[red]{markup_escape(str(exc))}[/]")
raise typer.Exit(code=2) from exc
# v0.72.3 — --resume / --hf-resume now work with layer streaming. v0.72.0-.2
# refused them because a streamed model's `named_parameters()` carry an
# `.inner.` segment that `load_state_dict` narrows away, so PEFT matched
# NOTHING and silently continued with a freshly initialised adapter (measured:
# 0 of 12 tensors, and a resumed loss curve byte-identical to a from-scratch
# one). `StreamedDecoderLayer` now redirects canonical keys at load time,
# mirroring the v0.72.1 save-side delegation.
# --- RA-DIT generator-stage auto-link (v0.71.10 #200) ---
# When a generator stage has no retriever model set, splice in the latest
# RA-DIT retriever output from the Registry. A manual value always wins.
if getattr(cfg.training, "ra_dit_stage", None) == "generator":
from soup_cli.utils.ra_dit_run import autolink_generator_retriever
advisory = autolink_generator_retriever(cfg)
if advisory:
# `advisory` embeds a Registry-derived `output` path — escape it
# before printing into the Rich-markup console (security MEDIUM).
console.print(f"[yellow]RA-DIT:[/] {markup_escape(advisory)}")
# --- Echo-trap tokenizer-aware shortcut ---
if echo_trap_tokenizer_aware:
if not cfg.training.echo_trap_enabled:
console.print(
"[red]--echo-trap-tokenizer-aware requires "
"training.echo_trap_enabled=true[/]"
)
raise typer.Exit(1)
cfg.training.echo_trap_tokenizer_aware = True
console.print("[green]Echo-trap tokenizer-aware scoring enabled[/]")
# --- Reward-hack detector / halt shortcut (v0.71.26) ---
if reward_hack_detector is not None:
if reward_hack_detector not in ("info_rm", "rm_ensemble"):
console.print(
"[red]--reward-hack-detector must be info_rm or rm_ensemble[/]"
)
raise typer.Exit(1)
cfg.training.reward_hack_detector = reward_hack_detector
console.print(f"[green]Reward-hack detector:[/] {reward_hack_detector}")
if reward_hack_halt:
if cfg.training.reward_hack_detector is None:
console.print(
"[red]--reward-hack-halt requires --reward-hack-detector "
"(or training.reward_hack_detector)[/]"
)
raise typer.Exit(1)
cfg.training.reward_hack_halt = True
console.print("[green]Reward-hack auto-halt enabled[/]")
# --- Reward-hack mitigation shortcut (v0.71.26) ---
if reward_hack_mitigation is not None:
valid_modes = ("off", "log_only", "kl_control", "pid_lagrangian")
if reward_hack_mitigation not in valid_modes:
console.print(
"[red]--reward-hack-mitigation must be one of "
f"{', '.join(valid_modes)}[/]"
)
raise typer.Exit(1)
if (
reward_hack_mitigation != "off"
and cfg.training.reward_hack_detector is None
):
console.print(
"[red]--reward-hack-mitigation requires "
"training.reward_hack_detector to be set (the signal source)[/]"
)
raise typer.Exit(1)
cfg.training.reward_hack_mitigation = reward_hack_mitigation
console.print(
f"[green]Reward-hack mitigation:[/] {reward_hack_mitigation}"
)
# --- MiniLLM on-policy rollout shortcut (v0.71.18 #257) ---
if minillm_on_policy:
if not cfg.training.minillm_enabled:
console.print(
"[red]--minillm-on-policy requires "
"training.minillm_enabled=true (task='distill')[/]"
)
raise typer.Exit(1)
cfg.training.minillm_on_policy = True
console.print("[green]MiniLLM on-policy rollout enabled[/]")
# --- Cloud GPU training (v0.71.18 #16, v0.71.22 #264) ---
if cloud:
from soup_cli import __version__ as _soup_version
cloud = cloud.lower()
if cloud == "runpod":
console.print(
"[yellow]RunPod cloud training is not yet live; use --cloud modal or lambda.[/]"
)
raise typer.Exit(2)
elif cloud == "modal":
from soup_cli.cloud import modal as cloud_mod
elif cloud == "lambda":
from soup_cli.cloud import lambda_labs as cloud_mod
else:
console.print(
f"[red]Invalid --cloud:[/] {markup_escape(cloud)}. "
"Supported: modal, lambda (runpod is planned)."
)
raise typer.Exit(2)
try:
cloud_mod.validate_cloud(cloud)
cloud_mod.validate_gpu(gpu)
except ValueError as exc:
console.print(
f"[red]Invalid --cloud / --gpu:[/] {markup_escape(str(exc))}"
)
raise typer.Exit(2) from exc
try:
# We call the generic-shaped plan function dynamically
plan_func = getattr(cloud_mod, f"plan_{cloud}_run", None)
if plan_func is None:
raise ValueError(f"cloud backend {cloud!r} has no plan function")
plan = plan_func(
str(config_path),
gpu=gpu,
output_dir=cfg.output,
soup_version=_soup_version,
)
stub_realpath = cloud_mod.write_stub(plan)
except (ValueError, TypeError) as exc:
console.print(f"[red]Cloud plan failed:[/] {markup_escape(str(exc))}")
raise typer.Exit(2) from exc
console.print(
Panel(
f"Cloud: [bold]{markup_escape(cloud)}[/]\n"
f"GPU: [bold]{markup_escape(plan.gpu)}[/]\n"
f"Stub: [bold]{markup_escape(os.path.relpath(stub_realpath))}[/]\n"
f"Output: [bold]{markup_escape(plan.output_dir)}[/]\n\n"
f"[bold]Run:[/] {markup_escape(plan.run_command)}",
title=f"[bold green]soup train --cloud {markup_escape(cloud)}[/]",
)
)
if cloud_submit:
try:
submit_func = getattr(cloud_mod, f"submit_{cloud}_run", None)
if submit_func is None:
raise RuntimeError(f"cloud backend {cloud!r} has no submit function")
rc = submit_func(plan)
except RuntimeError as exc:
console.print(
f"[yellow]{cloud.title()} submit unavailable:[/] "
f"{markup_escape(str(exc))}"
)
raise typer.Exit(1) from exc
raise typer.Exit(rc)
console.print(
f"[yellow]Note:[/] plan-only. Authenticate with {cloud}, then run the "
"command above (or re-run with --cloud-submit)."
)
raise typer.Exit(0)
# --- --push-as / --hf-resume validation ---
if push_as:
from soup_cli.utils.hf import validate_repo_id
try:
validate_repo_id(push_as)
except ValueError as exc:
console.print(f"[red]Invalid --push-as repo id:[/] {exc}")
raise typer.Exit(1) from exc
if hf_resume and not push_as:
console.print("[red]--hf-resume requires --push-as <repo>[/]")
raise typer.Exit(1)
# --- Eval-gate shortcut: --gate <path> sets training.eval_gate ---
if gate:
from soup_cli.config.schema import EvalGateConfig
from soup_cli.eval.gate import load_suite
try:
# Validate the suite path up-front (path containment + parse).
load_suite(gate)
except (FileNotFoundError, ValueError) as exc:
console.print(f"[red]Invalid --gate suite: {exc}[/]")
raise typer.Exit(1) from exc
cfg.training.eval_gate = EvalGateConfig(enabled=True, suite=gate)
console.print(f"[green]Eval gate enabled[/] with suite: {gate}")
# Honesty guard: these knobs are accepted (and `soup autopilot` turns them
# on by default) but are not enforced mid-training in this build — the eval
# gate wired above is the live safety net. Warn instead of silently no-op'ing
# so a "zero-config" run does not advertise protection it does not have.
_unwired_gates = [
name
for name, on in (
("forgetting_detection", cfg.training.forgetting_detection),
("checkpoint_intelligence", cfg.training.checkpoint_intelligence),
("early_stop_on_regression", cfg.training.early_stop_on_regression),
("convergence_detection", cfg.training.convergence_detection),
)
if on
]
if _unwired_gates:
console.print(
"[yellow]Note:[/] "
+ ", ".join(_unwired_gates)
+ " are set but not enforced during training in this build. "
"Use [bold]--gate <suite.yaml>[/] for a live eval gate, or run "
"[bold]soup eval[/] / [bold]soup diagnose[/] after training."
)
# --- Resolve resume checkpoint (fail fast before heavy operations) ---
resume_from = _resolve_resume_or_exit(resume, cfg)
# --- HF auto-resume: pull latest checkpoint branch into output dir ---
if hf_resume and push_as and resume_from is None:
from soup_cli.monitoring.hf_push import prepare_hf_resume
from soup_cli.utils.hf import resolve_endpoint, resolve_token
try:
hf_endpoint = resolve_endpoint()
except ValueError as exc:
console.print(f"[red]--hf-resume: {exc}[/]")
raise typer.Exit(1) from exc
hf_token = resolve_token()
if hf_token is None:
console.print(
"[yellow]--hf-resume: no HF token available; skipping auto-resume[/]"
)
else:
local_ckpt = prepare_hf_resume(
repo_id=push_as,
output_dir=cfg.output,
token=hf_token,
endpoint=hf_endpoint,
)
if local_ckpt:
resume_from = local_ckpt
console.print(f"[green]Resumed from HF:[/] {local_ckpt}")
else:
console.print(
"[yellow]--hf-resume: no checkpoint branch found; starting fresh[/]"
)
# --- Validate logging flags ---
if wandb and tensorboard:
console.print(
"[red]Cannot use --wandb and --tensorboard together. Pick one.[/]"
)
raise typer.Exit(1)
# --- TensorBoard setup ---
if tensorboard:
try:
import tensorboard # noqa: F401
console.print("[green]TensorBoard logging enabled[/]")
except ImportError:
console.print(
"[red]TensorBoard not installed.[/]\n"
"Run: [bold]pip install tensorboard[/]"
)
raise typer.Exit(1)
# --- W&B setup (fail fast if wandb not installed) ---
if wandb:
try:
import wandb as _wandb # noqa: F401
console.print("[green]W&B logging enabled[/]")
except ImportError:
console.print(
"[red]wandb not installed.[/]\n"
"Run: [bold]pip install \"soup-cli\\[wandb]\"[/]"
)
raise typer.Exit(1)
except Exception as wandb_err:
console.print(
f"[red]wandb import error:[/] {wandb_err}\n"
"Try: [bold]pip install 'wandb>=0.15.0,<0.18.0'[/]"
)
raise typer.Exit(1)
# --- DeepSpeed setup ---
ds_config_path = None
if deepspeed:
ds_config_path = _resolve_deepspeed(deepspeed)
if ds_config_path:
console.print(f"[green]DeepSpeed enabled:[/] {deepspeed}")
# --- FSDP2 setup ---
fsdp_kwargs = None
if fsdp:
from soup_cli.utils.fsdp import FSDP_CONFIGS, get_fsdp_training_args
if fsdp not in FSDP_CONFIGS:
console.print(
f"[red]Invalid FSDP preset: {fsdp}[/]\n"
f"Options: {', '.join(FSDP_CONFIGS.keys())}"
)
raise typer.Exit(1)
fsdp_kwargs = get_fsdp_training_args(fsdp)
console.print(f"[green]FSDP2 enabled:[/] {fsdp}")
# #350 — BNB's default uint8 quant storage is not merely slow under FSDP:
# FSDP cannot flatten it. Resolve storage to the exact BNB compute dtype
# before any trainer builds its BitsAndBytesConfig. This updates the
# effective config shared by every wrapper and the reproducibility receipt.
from soup_cli.utils.quant_menu import resolve_fsdp_qlora_quant_storage
original_quant_storage = cfg.training.bnb_4bit_quant_storage
resolved_training = resolve_fsdp_qlora_quant_storage(
cfg.training,
fsdp=bool(fsdp),
)
if resolved_training is not cfg.training:
cfg = cfg.model_copy(update={"training": resolved_training})
action = "selected" if original_quant_storage is None else "overrode"
console.print(
f"[green]FSDP QLoRA:[/] {action} bnb_4bit_quant_storage="
f"{resolved_training.bnb_4bit_quant_storage} to match compute dtype"
)
# --- v0.38.0 Quant Menu × multi-GPU compatibility check ---
from soup_cli.utils.quant_menu import check_quant_distributed_compat
quant_problems = check_quant_distributed_compat(
quantization=cfg.training.quantization,
deepspeed=deepspeed,
fsdp=bool(fsdp),
bnb_4bit_quant_storage=cfg.training.bnb_4bit_quant_storage,
)
if quant_problems:
hard = [p for p in quant_problems if not p.lower().startswith("warning")]
warn = [p for p in quant_problems if p.lower().startswith("warning")]
for problem in hard:
console.print(f"[red]Quant compat:[/] {problem}")
for problem in warn:
console.print(f"[yellow]{problem}[/]")
if hard:
raise typer.Exit(1)
# --- Multi-GPU topology + --gpus resolution ---
num_gpus = None
if gpus:
from soup_cli.utils.topology import detect_topology, resolve_num_gpus
try:
num_gpus = resolve_num_gpus(gpus)
except ValueError as exc:
console.print(f"[red]Invalid --gpus:[/] {exc}")
raise typer.Exit(1) from exc
topo = detect_topology()
if num_gpus is not None and num_gpus < 1:
# --gpus auto on CPU / no-CUDA box — explicit, not silent.
console.print(
"[yellow]--gpus auto detected 0 GPUs; continuing as a "
"single-process CPU run.[/]"
)
elif num_gpus is not None and num_gpus > 1:
from soup_cli.utils.launcher import (
build_accelerate_argv,
build_train_reexec_argv,
collect_reexec_passthrough,
format_advice,
hint_argv_from_reexec,
is_in_distributed,
)
if dry_run and not is_in_distributed():
# --dry-run must NEVER os.execvp into a real multi-GPU run.
# Without this guard the re-exec fired before the dry_run check
# (~350 lines below), so `soup train --dry-run --gpus N` launched
# a full accelerate run instead of just validating.
console.print(
f"[dim]--dry-run: skipping accelerate re-exec "
f"({num_gpus} GPUs, {topo['interconnect']}).[/]"
)
elif not is_in_distributed():
# v0.33.0 #37 — auto-reexec under accelerate launch unless
# --no-reexec was passed. Reexec uses os.execvp so the new
# accelerate process replaces this process; no leftover PID
# tree, stdio passes through unchanged.
# #372 — one argv builder for both the re-exec and the printed
# hint, so they cannot drift. collect_reexec_passthrough is the
# only list of "flags the user typed" that survive a launch.
script_args = build_train_reexec_argv(
config,
collect_reexec_passthrough(
name=name,
fsdp=fsdp,
deepspeed=deepspeed,
resume=resume,
wandb=wandb,
tensorboard=tensorboard,
echo_trap_tokenizer_aware=echo_trap_tokenizer_aware,
reward_hack_detector=reward_hack_detector,
reward_hack_halt=reward_hack_halt,
reward_hack_mitigation=reward_hack_mitigation,
gate=gate,
push_as=push_as,
hf_resume=hf_resume,
trust_remote_code=trust_remote_code,
tracker=tracker,
diagnose_gate=diagnose_gate,
annex_xi=annex_xi,
repro_receipt=repro_receipt,
profile_run=profile_run,
allow_oom_attempt=allow_oom_attempt,
track_energy=track_energy,
energy_country=energy_country,
energy_out=energy_out,
yes=yes,
minillm_on_policy=minillm_on_policy,
capture_activations=capture_activations,
capture_prompts=capture_prompts,
replay=replay,
replay_ratio=replay_ratio,
replay_seed=replay_seed,
),
)
if no_reexec:
hint_args = hint_argv_from_reexec(script_args)
console.print(
Panel(
markup_escape(format_advice(num_gpus, hint_args)),
title="[yellow]Multi-GPU launch required[/]",
)
)
console.print(
f"[dim]Detected topology: {topo['gpu_count']} GPUs, "
f"{topo['interconnect']}[/]"
)
raise typer.Exit(1)
argv = build_accelerate_argv(
num_processes=num_gpus, script_args=script_args,
)
console.print(
f"[green]Auto-reexec under accelerate "
f"({num_gpus} GPUs, {topo['interconnect']})[/]"
)
console.print(f"[dim]argv: {' '.join(argv)}[/]")
# os.execvp replaces the current process — does not return.
# On Windows execvp creates a new process and returns the
# child's return code; we don't loop because the parent