forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_bugfixes.py
More file actions
1302 lines (970 loc) · 45.5 KB
/
Copy pathtest_bugfixes.py
File metadata and controls
1302 lines (970 loc) · 45.5 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
"""Tests for v0.10.1-v0.14.2 bug fixes - Unicode, PPO, dtype, CPU, trl API, validate, UI."""
from pathlib import Path
from unittest.mock import patch
import pytest
from soup_cli.config.schema import SoupConfig
# --- BUG-001: Windows UnicodeEncodeError (no Unicode arrows/dashes in output) ---
class TestNoUnicodeInOutput:
"""Verify user-facing output uses only ASCII-safe characters."""
def test_config_loader_error_uses_ascii_arrow(self):
"""Config validation errors should use -> not Unicode arrow."""
from soup_cli.config.loader import load_config_from_string
with pytest.raises(ValueError) as exc_info:
load_config_from_string("base: x\ntask: invalid_task\n")
# Error message should use -> not the Unicode arrow
msg = str(exc_info.value)
assert "\u2192" not in msg # no Unicode right arrow
def test_loss_format_uses_ascii(self):
"""Loss formatting in runs should use -> not Unicode arrow."""
from soup_cli.commands.runs import _fmt_loss
run = {"initial_loss": 1.5, "final_loss": 0.5}
result = _fmt_loss(run)
assert "->" in result
assert "\u2192" not in result # no Unicode right arrow
def test_loss_format_missing_returns_ascii(self):
"""Missing loss should return ASCII dash, not em dash."""
from soup_cli.commands.runs import _fmt_loss
result = _fmt_loss({})
assert result == "-"
assert "\u2014" not in result # no em dash
def test_fmt_float_missing_returns_ascii(self):
"""Missing float should return ASCII dash."""
from soup_cli.commands.runs import _fmt_float
result = _fmt_float(None)
assert result == "-"
assert "\u2014" not in result
def test_fmt_duration_missing_returns_ascii(self):
"""Missing duration should return ASCII dash."""
from soup_cli.commands.runs import _fmt_duration
result = _fmt_duration(None)
assert result == "-"
assert "\u2014" not in result
def test_formats_empty_dataset_error_ascii(self):
"""Empty dataset error should use ASCII dash."""
from soup_cli.data.formats import detect_format
with pytest.raises(ValueError, match="Empty dataset"):
detect_format([])
# --- BUG-002: PPO ppo_epochs parameter compatibility ---
class TestPPOParamCompat:
"""Test PPO trainer handles trl version differences."""
def test_ppo_config_uses_inspect(self):
"""PPO setup should use inspect to detect valid parameter names."""
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
training={
"ppo_epochs": 3,
"ppo_clip_ratio": 0.15,
"ppo_kl_penalty": 0.03,
},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
assert wrapper.config.training.ppo_epochs == 3
assert wrapper.config.training.ppo_clip_ratio == pytest.approx(0.15)
assert wrapper.config.training.ppo_kl_penalty == pytest.approx(0.03)
# --- BUG-003: Reward Model dtype mismatch ---
class TestComputeDtype:
"""Test get_compute_dtype returns correct dtype for device."""
def test_cpu_returns_float32(self):
"""CPU should use float32, not bfloat16."""
import torch
from soup_cli.utils.gpu import get_compute_dtype
with patch("torch.cuda.is_available", return_value=False):
dtype = get_compute_dtype()
assert dtype == torch.float32
def test_cuda_with_bf16_returns_bfloat16(self):
"""CUDA with bf16 support should use bfloat16."""
import torch
from soup_cli.utils.gpu import get_compute_dtype
with patch("torch.cuda.is_available", return_value=True), \
patch("torch.cuda.is_bf16_supported", return_value=True):
dtype = get_compute_dtype()
assert dtype == torch.bfloat16
def test_cuda_without_bf16_returns_float16(self):
"""CUDA without bf16 support should fall back to float16."""
import torch
from soup_cli.utils.gpu import get_compute_dtype
with patch("torch.cuda.is_available", return_value=True), \
patch("torch.cuda.is_bf16_supported", return_value=False):
dtype = get_compute_dtype()
assert dtype == torch.float16
# --- BUG-005: diff load dtype spelling (#478) ---
class TestDiffModelLoading:
"""Test diff command uses Transformers kwargs compatible with the floor."""
def test_load_model_uses_torch_dtype(self):
"""_load_model keeps the guarded Transformers load-kwarg policy (#478)."""
import inspect
from soup_cli.commands.diff import _load_model
source = inspect.getsource(_load_model)
assert "torch_dtype=torch.float16" in source
# Substring-safe: torch_dtype=... contains the letters dtype=
bare = source.replace("torch_dtype=", "")
assert "dtype=" not in bare
# --- BUG-006: wandb version pin ---
class TestWandbVersionPin:
"""Test wandb dependency is version-pinned."""
def test_wandb_upper_bound_in_pyproject(self):
"""pyproject.toml should pin wandb below 0.18.0."""
pyproject = Path(__file__).parent.parent / "pyproject.toml"
content = pyproject.read_text(encoding="utf-8")
assert "<0.18.0" in content or "< 0.18.0" in content
# --- BUG-004: CPU quantization warning ---
class TestCPUQuantWarning:
"""Test that CPU + quantization produces a warning and downgrades."""
def test_train_auto_disables_quant_on_cpu(self):
"""gpu.py resolve_quantization should auto-disable quantization on CPU."""
import inspect
from soup_cli.utils import gpu
from soup_cli.utils.gpu import resolve_quantization
# Retargeted from commands/train.py to utils/gpu.py after extraction (#423)
source = inspect.getsource(gpu)
assert "quantization is not" in source
# Behavioral assertions on pure resolve_quantization function
resolved, warning = resolve_quantization(
device="cpu", backend=None, quantization="4bit"
)
assert resolved == "none"
assert warning is not None
assert "quantization is not supported on CPU" in warning
# MLX preserves 4bit without downgrade
assert resolve_quantization(
device="cpu", backend="mlx", quantization="4bit"
)[0] == "4bit"
# --- v0.10.2: Display progress bar uses ASCII ---
class TestDisplayASCII:
"""Test that training display uses ASCII-safe progress bars."""
def test_progress_bar_uses_ascii_chars(self):
"""Progress bar should use # and - instead of Unicode blocks."""
import inspect
from soup_cli.monitoring.display import TrainingDisplay
source = inspect.getsource(TrainingDisplay)
assert '"#"' in source
assert '"-"' in source
assert "\\u2588" not in source
assert "\\u2591" not in source
# --- v0.10.2: Plotext UnicodeEncodeError handling ---
class TestPlotextFallback:
"""Test that plotext errors are caught gracefully."""
def test_stats_catches_unicode_error(self):
"""data stats should catch UnicodeEncodeError from plotext."""
import inspect
from soup_cli.commands import data
source = inspect.getsource(data)
assert "UnicodeEncodeError" in source
# --- v0.10.2: Error messages for CPU issues ---
class TestCPUErrorMessages:
"""Test friendly error messages for CPU-specific failures."""
def test_tensor_size_error_mapped(self):
"""Tensor expansion error should have a friendly GRPO/PPO CPU message."""
from soup_cli.utils.errors import ERROR_MAP
for pattern, msg, _ in ERROR_MAP:
if "expanded size" in pattern:
assert "GRPO" in msg or "PPO" in msg
break
else:
pytest.fail("expanded size pattern not found in ERROR_MAP")
def test_dtype_mismatch_error_mapped(self):
"""Dtype mismatch error should have a friendly message."""
from soup_cli.utils.errors import ERROR_MAP
patterns = [pattern for pattern, _, _ in ERROR_MAP]
assert any("same dtype" in p for p in patterns)
def test_bf16_error_mapped(self):
"""bf16 GPU error should have a friendly message."""
from soup_cli.utils.errors import ERROR_MAP
patterns = [pattern for pattern, _, _ in ERROR_MAP]
assert any("bf16" in p for p in patterns)
def test_torchvision_error_mapped(self):
"""torchvision nms error should have a friendly message."""
from soup_cli.utils.errors import ERROR_MAP
patterns = [pattern for pattern, _, _ in ERROR_MAP]
assert any("nms" in p for p in patterns)
# --- v0.10.2: Doctor torchvision check ---
class TestDoctorTorchvisionCheck:
"""Test that soup doctor checks torchvision compatibility."""
def test_doctor_has_torchvision_check(self):
"""doctor.py should have torchvision compatibility check."""
import inspect
from soup_cli.commands import doctor
source = inspect.getsource(doctor)
assert "_check_torchvision_compat" in source
# --- v0.10.3: PPO use_cpu support ---
class TestPPOUseCPU:
"""Test PPO trainer sets use_cpu=True on CPU devices."""
def test_ppo_setup_has_use_cpu_logic(self):
"""PPO setup should check for use_cpu param and set it on CPU."""
import inspect
from soup_cli.trainer import ppo
source = inspect.getsource(ppo)
assert "use_cpu" in source
assert 'self.device == "cpu"' in source
def test_ppo_wrapper_stores_device(self):
"""PPOTrainerWrapper should store the device parameter."""
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
assert wrapper.device == "cpu"
wrapper_gpu = PPOTrainerWrapper(cfg, device="cuda")
assert wrapper_gpu.device == "cuda"
def test_ppo_supports_args_and_config_api(self):
"""PPO trainer should detect trl API: args= (>=0.28) vs config= (<0.28)."""
import inspect
from soup_cli.trainer import ppo
source = inspect.getsource(ppo)
# Must handle both trl APIs
assert '"args"' in source
assert '"config"' in source
assert "ppo_trainer_cls.__init__" in source
def test_ppo_train_detects_builtin_vs_manual(self):
"""PPO train() should detect built-in .train() vs manual loop."""
import inspect
from soup_cli.trainer import ppo
source = inspect.getsource(ppo)
assert "_train_builtin" in source
assert "_train_manual" in source
# --- v0.10.3: GRPO CPU warning ---
class TestGRPOCPUWarning:
"""Test GRPO trainer warns on CPU and sets use_cpu."""
def test_grpo_setup_has_cpu_warning(self):
"""GRPO setup should warn about CPU limitations."""
import inspect
from soup_cli.trainer import grpo
source = inspect.getsource(grpo)
assert "GRPO on CPU is experimental" in source
def test_grpo_setup_has_use_cpu_logic(self):
"""GRPO setup should set use_cpu=True on CPU when supported."""
import inspect
from soup_cli.trainer import grpo
source = inspect.getsource(grpo)
assert "use_cpu" in source
def test_grpo_wrapper_stores_device(self):
"""GRPOTrainerWrapper should store the device parameter."""
from soup_cli.trainer.grpo import GRPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="grpo",
data={"train": "./data.jsonl"},
training={"reward_fn": "accuracy"},
)
wrapper = GRPOTrainerWrapper(cfg, device="cpu")
assert wrapper.device == "cpu"
# --- v0.10.3: use_cpu error message ---
class TestUseCPUErrorMessage:
"""Test that use_cpu error is mapped to a friendly message."""
def test_use_cpu_error_mapped(self):
"""use_cpu error should have a friendly message."""
from soup_cli.utils.errors import ERROR_MAP
patterns = [pattern for pattern, _, _ in ERROR_MAP]
assert any("use_cpu" in p for p in patterns)
# --- v0.10.5: PPO dataset parameter compatibility (trl >=0.28) ---
class TestPPODatasetCompat:
"""Test PPO trainer handles dataset param removal in newer trl versions."""
def test_ppo_setup_checks_dataset_in_constructor(self):
"""PPO setup should check whether dataset/train_dataset is accepted."""
import inspect
from soup_cli.trainer import ppo
source = inspect.getsource(ppo)
# Must check both train_dataset and dataset params
assert '"train_dataset" in ppo_trainer_params' in source
assert '"dataset" in ppo_trainer_params' in source
# Must track whether dataset was passed to constructor
assert "_dataset_in_constructor" in source
def test_ppo_train_sets_dataset_if_not_in_constructor(self):
"""PPO _train_builtin should set dataset on trainer if not in init."""
import inspect
from soup_cli.trainer.ppo import PPOTrainerWrapper
source = inspect.getsource(PPOTrainerWrapper._train_builtin)
assert "_dataset_in_constructor" in source
assert "train_dataset" in source
def test_ppo_dataset_in_constructor_flag(self):
"""PPOTrainerWrapper should track _dataset_in_constructor after setup."""
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
# Real class whose __init__ does NOT accept dataset/train_dataset
class FakePPOTrainer:
def __init__(self, *, model=None, args=None,
processing_class=None, reward_funcs=None):
pass
class FakePPOConfig:
def __init__(self, **kwargs):
pass
dataset = {
"train": [
{"prompt": "What is 2+2?", "answer": "4"},
]
}
with mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_reward"), \
mock_patch(
"soup_cli.trainer.ppo.PPOTrainerWrapper._setup_transformers"
), mock_patch(
"soup_cli.trainer.ppo._import_ppo_classes",
return_value=(FakePPOTrainer, FakePPOConfig, False),
):
wrapper.model = MagicMock()
wrapper.model.get_nb_trainable_parameters.return_value = (100, 1000)
mock_tokenizer = MagicMock()
mock_tokenizer.pad_token = "pad"
mock_tokenizer.side_effect = lambda texts, **kw: {
"input_ids": [[1, 2, 3]] * (len(texts) if isinstance(texts, list) else 1),
"attention_mask": [[1, 1, 1]] * (len(texts) if isinstance(texts, list) else 1),
}
wrapper.tokenizer = mock_tokenizer
wrapper.setup(dataset)
# dataset should NOT be in constructor since FakePPOTrainer
# doesn't accept it (uses "args" path but no train_dataset param)
assert wrapper._dataset_in_constructor is False
def test_ppo_dataset_in_constructor_when_accepted(self):
"""_dataset_in_constructor should be True when train_dataset is accepted."""
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
# Real class whose __init__ DOES accept train_dataset
class FakePPOTrainer:
def __init__(self, *, model=None, args=None,
processing_class=None, train_dataset=None,
reward_funcs=None):
pass
class FakePPOConfig:
def __init__(self, **kwargs):
pass
dataset = {
"train": [
{"prompt": "What is 2+2?", "answer": "4"},
]
}
with mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_reward"), \
mock_patch(
"soup_cli.trainer.ppo.PPOTrainerWrapper._setup_transformers"
), mock_patch(
"soup_cli.trainer.ppo._import_ppo_classes",
return_value=(FakePPOTrainer, FakePPOConfig, False),
):
wrapper.model = MagicMock()
wrapper.model.get_nb_trainable_parameters.return_value = (100, 1000)
mock_tokenizer = MagicMock()
mock_tokenizer.pad_token = "pad"
mock_tokenizer.side_effect = lambda texts, **kw: {
"input_ids": [[1, 2, 3]] * (len(texts) if isinstance(texts, list) else 1),
"attention_mask": [[1, 1, 1]] * (len(texts) if isinstance(texts, list) else 1),
}
wrapper.tokenizer = mock_tokenizer
wrapper.setup(dataset)
assert wrapper._dataset_in_constructor is True
# --- BUG-007: PPO trl >=0.28 experimental API missing positional args (v0.10.6) ---
class TestPPOExperimentalImport:
"""Test _import_ppo_classes handles both trl paths."""
def test_import_ppo_classes_returns_tuple(self):
"""_import_ppo_classes should return (PPOTrainer, PPOConfig, bool)."""
from soup_cli.trainer.ppo import _import_ppo_classes
result = _import_ppo_classes()
assert isinstance(result, tuple)
assert len(result) == 3
trainer_cls, config_cls, is_exp = result
assert trainer_cls is not None
assert config_cls is not None
assert isinstance(is_exp, bool)
def test_import_experimental_fallback(self):
"""When trl.experimental is unavailable, should fall back to trl."""
import soup_cli.trainer.ppo as ppo_mod
# Just verify the function works without error (it handles
# ImportError from trl.experimental internally)
result = ppo_mod._import_ppo_classes()
assert len(result) == 3
class TestPPOExperimentalSetup:
"""Test PPO setup handles experimental API with required positional args."""
def test_experimental_api_passes_required_args(self):
"""When is_experimental=True, setup should pass ref_model, reward_model,
train_dataset, and value_model to PPOTrainer."""
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
dataset = {"train": [{"prompt": "What is 2+2?", "answer": "4"}]}
# Track what args PPOTrainer receives
captured_kwargs = {}
class FakePPOTrainer:
def __init__(self, **kwargs):
captured_kwargs.update(kwargs)
class FakePPOConfig:
def __init__(self, **kwargs):
pass
fake_reward_model = MagicMock()
fake_value_model = MagicMock()
with mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_reward"), \
mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_transformers"), \
mock_patch(
"soup_cli.trainer.ppo._import_ppo_classes",
return_value=(FakePPOTrainer, FakePPOConfig, True),
), \
mock_patch(
"soup_cli.trainer.ppo.PPOTrainerWrapper._get_or_create_reward_model",
return_value=fake_reward_model,
), \
mock_patch(
"soup_cli.trainer.ppo.PPOTrainerWrapper._create_value_model",
return_value=fake_value_model,
):
wrapper.model = MagicMock()
wrapper.model.get_nb_trainable_parameters.return_value = (100, 1000)
mock_tokenizer = MagicMock()
mock_tokenizer.pad_token = "pad"
mock_tokenizer.side_effect = lambda texts, **kw: {
"input_ids": [[1, 2, 3]] * (len(texts) if isinstance(texts, list) else 1),
"attention_mask": [[1, 1, 1]] * (len(texts) if isinstance(texts, list) else 1),
}
wrapper.tokenizer = mock_tokenizer
wrapper.setup(dataset)
# Verify required positional args were passed
assert "ref_model" in captured_kwargs
assert captured_kwargs["ref_model"] is None # auto-create
assert "reward_model" in captured_kwargs
assert captured_kwargs["reward_model"] is fake_reward_model
assert "train_dataset" in captured_kwargs
assert "value_model" in captured_kwargs
assert captured_kwargs["value_model"] is fake_value_model
assert "args" in captured_kwargs
assert "processing_class" in captured_kwargs
assert wrapper._dataset_in_constructor is True
def test_legacy_api_no_positional_args(self):
"""When is_experimental=False and no args param, should use old API."""
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
dataset = {"train": [{"prompt": "What is 2+2?", "answer": "4"}]}
captured_kwargs = {}
class FakePPOTrainer:
def __init__(self, **kwargs):
captured_kwargs.update(kwargs)
class FakePPOConfig:
def __init__(self, **kwargs):
pass
with mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_reward"), \
mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_transformers"), \
mock_patch(
"soup_cli.trainer.ppo._import_ppo_classes",
return_value=(FakePPOTrainer, FakePPOConfig, False),
):
wrapper.model = MagicMock()
wrapper.model.get_nb_trainable_parameters.return_value = (100, 1000)
mock_tokenizer = MagicMock()
mock_tokenizer.pad_token = "pad"
mock_tokenizer.side_effect = lambda texts, **kw: {
"input_ids": [[1, 2, 3]] * (len(texts) if isinstance(texts, list) else 1),
"attention_mask": [[1, 1, 1]] * (len(texts) if isinstance(texts, list) else 1),
}
wrapper.tokenizer = mock_tokenizer
wrapper.setup(dataset)
# Old API uses config= and tokenizer=
assert "config" in captured_kwargs
assert "tokenizer" in captured_kwargs
assert "dataset" in captured_kwargs
assert "ref_model" not in captured_kwargs
assert "value_model" not in captured_kwargs
# --- BUG-008: GRPO CPU empty generation tensor mismatch (v0.10.6) ---
def _trl_grpo_importable() -> bool:
"""Detect whether trl.trainer.grpo_trainer can be imported on this host.
Upstream trl occasionally ships source files that read auxiliary data
without an explicit encoding. On Windows with the default cp1252
(``charmap``) codec this fails at import time with a ``UnicodeDecodeError``.
Our CI forces ``PYTHONUTF8=1`` for safety; this helper is a belt-and-braces
check so the test skips cleanly instead of erroring out if the env var is
missing locally.
"""
try:
import trl # noqa: F401
import trl.trainer.grpo_trainer # noqa: F401
except (UnicodeDecodeError, ImportError, RuntimeError):
return False
return True
class TestGRPOCPUMinNewTokens:
"""Test GRPO CPU workaround: generation_kwargs with min_new_tokens."""
def test_cpu_adds_generation_kwargs(self):
"""On CPU, GRPO setup should add generation_kwargs with min_new_tokens."""
if not _trl_grpo_importable():
pytest.skip(
"trl.trainer.grpo_trainer not importable on this host "
"(likely Windows cp1252 without PYTHONUTF8=1)"
)
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
from soup_cli.trainer.grpo import GRPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="grpo",
data={"train": "./data.jsonl"},
)
wrapper = GRPOTrainerWrapper(cfg, device="cpu")
dataset = {"train": [{"prompt": "What is 2+2?", "answer": "4"}]}
captured_config_kwargs = {}
class FakeGRPOConfig:
def __init__(self, use_cpu=None, generation_kwargs=None, **kwargs):
captured_config_kwargs.update(kwargs)
if use_cpu is not None:
captured_config_kwargs["use_cpu"] = use_cpu
if generation_kwargs is not None:
captured_config_kwargs["generation_kwargs"] = generation_kwargs
class FakeGRPOTrainer:
def __init__(self, **kwargs):
pass
with mock_patch("soup_cli.trainer.grpo.GRPOTrainerWrapper._setup_transformers"), \
mock_patch("trl.GRPOConfig", FakeGRPOConfig), \
mock_patch("trl.GRPOTrainer", FakeGRPOTrainer):
wrapper.model = MagicMock()
wrapper.model.get_nb_trainable_parameters.return_value = (100, 1000)
wrapper.tokenizer = MagicMock()
wrapper.tokenizer.pad_token = "pad"
wrapper.setup(dataset)
# Should have generation_kwargs with min_new_tokens on CPU
gen_kwargs = captured_config_kwargs.get("generation_kwargs", {})
assert gen_kwargs.get("min_new_tokens") == 1
def test_gpu_no_generation_kwargs(self):
"""On GPU, GRPO setup should NOT add generation_kwargs for min_new_tokens."""
if not _trl_grpo_importable():
pytest.skip(
"trl.trainer.grpo_trainer not importable on this host "
"(likely Windows cp1252 without PYTHONUTF8=1)"
)
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
from soup_cli.trainer.grpo import GRPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="grpo",
data={"train": "./data.jsonl"},
)
wrapper = GRPOTrainerWrapper(cfg, device="cuda")
dataset = {"train": [{"prompt": "What is 2+2?", "answer": "4"}]}
captured_config_kwargs = {}
class FakeGRPOConfig:
def __init__(self, use_cpu=None, generation_kwargs=None, **kwargs):
captured_config_kwargs.update(kwargs)
if use_cpu is not None:
captured_config_kwargs["use_cpu"] = use_cpu
if generation_kwargs is not None:
captured_config_kwargs["generation_kwargs"] = generation_kwargs
class FakeGRPOTrainer:
def __init__(self, **kwargs):
pass
with mock_patch("soup_cli.trainer.grpo.GRPOTrainerWrapper._setup_transformers"), \
mock_patch("trl.GRPOConfig", FakeGRPOConfig), \
mock_patch("trl.GRPOTrainer", FakeGRPOTrainer):
wrapper.model = MagicMock()
wrapper.model.get_nb_trainable_parameters.return_value = (100, 1000)
wrapper.tokenizer = MagicMock()
wrapper.tokenizer.pad_token = "pad"
wrapper.setup(dataset)
# Should NOT have generation_kwargs on GPU
assert "generation_kwargs" not in captured_config_kwargs
# --- BUG-009: PPO train() rejects resume_from_checkpoint (v0.10.7) ---
class TestPPOResumeCheckpoint:
"""Test PPO _train_builtin skips resume_from_checkpoint for experimental API."""
def test_train_builtin_skips_resume_when_unsupported(self):
"""_train_builtin should call train() without resume_from_checkpoint
when the trainer's .train() method doesn't accept it."""
from unittest.mock import MagicMock
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
wrapper._output_dir = "/tmp/test"
wrapper._dataset_in_constructor = True
wrapper._train_ds = MagicMock()
# Create a real callable with no params (like experimental PPOTrainer.train)
call_log = []
def no_args_train():
call_log.append("called")
mock_trainer = MagicMock()
mock_trainer.train = no_args_train
mock_trainer.state.log_history = [{"loss": 0.5}]
mock_trainer.state.global_step = 10
wrapper.trainer = mock_trainer
wrapper.tokenizer = MagicMock()
result = wrapper._train_builtin(
display=None, tracker=None, run_id="",
resume_from_checkpoint="/tmp/ckpt",
)
# Should call train() without resume_from_checkpoint
assert call_log == ["called"]
assert result["total_steps"] == 10
def test_train_builtin_passes_resume_when_supported(self):
"""_train_builtin should pass resume_from_checkpoint when supported."""
from unittest.mock import MagicMock
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
wrapper._output_dir = "/tmp/test"
wrapper._dataset_in_constructor = True
wrapper._train_ds = MagicMock()
# Create a real callable that accepts resume_from_checkpoint
call_log = []
def resume_train(resume_from_checkpoint=None):
call_log.append(resume_from_checkpoint)
mock_trainer = MagicMock()
mock_trainer.train = resume_train
mock_trainer.state.log_history = [{"loss": 0.5}]
mock_trainer.state.global_step = 10
wrapper.trainer = mock_trainer
wrapper.tokenizer = MagicMock()
wrapper._train_builtin(
display=None, tracker=None, run_id="",
resume_from_checkpoint="/tmp/ckpt",
)
assert call_log == ["/tmp/ckpt"]
def test_train_builtin_no_resume_calls_train_directly(self):
"""_train_builtin should call train() directly when resume is None."""
from unittest.mock import MagicMock
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
wrapper._output_dir = "/tmp/test"
wrapper._dataset_in_constructor = True
wrapper._train_ds = MagicMock()
call_log = []
def no_args_train():
call_log.append("called")
mock_trainer = MagicMock()
mock_trainer.train = no_args_train
mock_trainer.state.log_history = []
mock_trainer.state.global_step = 0
wrapper.trainer = mock_trainer
wrapper.tokenizer = MagicMock()
wrapper._train_builtin(
display=None, tracker=None, run_id="",
resume_from_checkpoint=None,
)
# resume is None/falsy so it should just call train()
assert call_log == ["called"]
def test_is_experimental_stored_on_setup(self):
"""setup() should store _is_experimental flag on the wrapper."""
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
from soup_cli.trainer.ppo import PPOTrainerWrapper
cfg = SoupConfig(
base="test-model",
task="ppo",
data={"train": "./data.jsonl"},
)
wrapper = PPOTrainerWrapper(cfg, device="cpu")
class FakePPOTrainer:
def __init__(self, **kwargs):
pass
class FakePPOConfig:
def __init__(self, **kwargs):
pass
dataset = {"train": [{"prompt": "Q?", "answer": "A"}]}
with mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_reward"), \
mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_transformers"), \
mock_patch(
"soup_cli.trainer.ppo._import_ppo_classes",
return_value=(FakePPOTrainer, FakePPOConfig, True),
), \
mock_patch(
"soup_cli.trainer.ppo.PPOTrainerWrapper._get_or_create_reward_model",
return_value=MagicMock(),
), \
mock_patch(
"soup_cli.trainer.ppo.PPOTrainerWrapper._create_value_model",
return_value=MagicMock(),
):
wrapper.model = MagicMock()
wrapper.model.get_nb_trainable_parameters.return_value = (100, 1000)
mock_tokenizer = MagicMock()
mock_tokenizer.pad_token = "pad"
mock_tokenizer.side_effect = lambda texts, **kw: {
"input_ids": [[1, 2, 3]] * (len(texts) if isinstance(texts, list) else 1),
"attention_mask": [[1, 1, 1]] * (len(texts) if isinstance(texts, list) else 1),
}
wrapper.tokenizer = mock_tokenizer
wrapper.setup(dataset)
assert wrapper._is_experimental is True
# --- BUG-010: Meta tensor on CPU from device_map="auto" (v0.10.7) ---
class TestCPUDeviceMap:
"""BUG-010: `device_map="auto"` produces meta tensors on CPU, so the CPU path
must never receive it.
Rewritten. Each test used to read the function's source and assert the
literal `'"cpu"'` appeared in it. Once the device map moved behind
`utils/gpu.resolve_device_map` (so a distributed launch pins one GPU per rank
instead of asking every rank to shard across all of them), that check stopped
describing behaviour: for grpo / ppo / sft / dpo it was satisfied by the
leftover comment `# On CPU, use device_map="cpu" ...`, i.e. it would have
passed on a function that had lost the behaviour entirely, and for
reward_model and PPO's `_load_reward_model` it failed on a function that had
kept it. Both halves are the same defect: a string in the source is not the
property.
What is asserted now: every one of these loaders takes its device map from
the one helper, and none of them hardcodes `"auto"`; plus the helper itself
still maps CPU to `"cpu"`, which is the actual bug this class was opened for.
"""
#: (module, dotted attribute) for every loader that picks a device map.
LOADERS = [
("soup_cli.trainer.grpo", "GRPOTrainerWrapper._setup_transformers"),
("soup_cli.trainer.ppo", "PPOTrainerWrapper._setup_transformers"),
("soup_cli.trainer.ppo", "PPOTrainerWrapper._get_or_create_reward_model"),
("soup_cli.trainer.ppo", "PPOTrainerWrapper._create_value_model"),
("soup_cli.trainer.ppo", "_load_reward_model"),
("soup_cli.trainer.sft", "SFTTrainerWrapper._setup_transformers"),
("soup_cli.trainer.dpo", "DPOTrainerWrapper._setup_transformers"),