forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_bco.py
More file actions
296 lines (227 loc) · 10.3 KB
/
Copy pathtest_bco.py
File metadata and controls
296 lines (227 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""Tests for BCO (Binary Classifier Optimization) — v0.40.0 Part A.
Mirrors ORPO/SimPO/IPO test layout: schema, data format gate, template,
trainer wrapper init + routing (train + sweep), edge cases.
"""
from __future__ import annotations
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
import pytest
from pydantic import ValidationError
from soup_cli.config.schema import TEMPLATES, SoupConfig
# ─── Schema Tests ───────────────────────────────────────────────────────────
class TestBCOConfig:
"""Test BCO task config validation."""
def test_bco_task_accepted(self):
cfg = SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
)
assert cfg.task == "bco"
def test_bco_beta_default(self):
cfg = SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
)
assert cfg.training.bco_beta == 0.1
def test_bco_beta_custom(self):
cfg = SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
training={"bco_beta": 0.05},
)
assert cfg.training.bco_beta == pytest.approx(0.05)
def test_bco_beta_must_be_positive(self):
with pytest.raises(ValidationError, match="bco_beta"):
SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
training={"bco_beta": 0},
)
def test_bco_beta_negative_rejected(self):
with pytest.raises(ValidationError, match="bco_beta"):
SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
training={"bco_beta": -0.1},
)
def test_bco_full_config(self):
cfg = SoupConfig(
base="meta-llama/Llama-3.1-8B-Instruct",
task="bco",
data={"train": "./data.jsonl", "format": "dpo", "max_length": 2048},
training={
"epochs": 3,
"lr": 1e-5,
"bco_beta": 0.2,
"lora": {"r": 64, "alpha": 16},
"quantization": "4bit",
},
)
assert cfg.task == "bco"
assert cfg.training.bco_beta == pytest.approx(0.2)
# ─── Data Format Tests ──────────────────────────────────────────────────────
class TestBCODataFormat:
"""Test that BCO uses the DPO data format (prompt+chosen+rejected)."""
def test_dpo_format_works_for_bco(self):
from soup_cli.data.formats import detect_format
data = [{"prompt": "Q", "chosen": "A", "rejected": "B"}]
assert detect_format(data) == "dpo"
# ─── Split helper Tests ─────────────────────────────────────────────────────
class TestSplitDpoRowsToBco:
def test_two_rows_become_four_with_correct_labels(self):
from soup_cli.trainer.bco import _split_dpo_rows_to_bco
rows = [
{"prompt": "p1", "chosen": "c1", "rejected": "r1"},
{"prompt": "p2", "chosen": "c2", "rejected": "r2"},
]
out = _split_dpo_rows_to_bco(rows)
assert len(out) == 4
assert out[0] == {"prompt": "p1", "completion": "c1", "label": True}
assert out[1] == {"prompt": "p1", "completion": "r1", "label": False}
assert out[2] == {"prompt": "p2", "completion": "c2", "label": True}
assert out[3] == {"prompt": "p2", "completion": "r2", "label": False}
def test_empty_input_returns_empty_list(self):
from soup_cli.trainer.bco import _split_dpo_rows_to_bco
assert _split_dpo_rows_to_bco([]) == []
@pytest.mark.parametrize(
"row",
[
{"chosen": "c", "rejected": "r"},
{"prompt": "p", "rejected": "r"},
{"prompt": "p", "chosen": "c"},
{},
{"unrelated": "field"},
],
)
def test_missing_required_field_skipped(self, row):
from soup_cli.trainer.bco import _split_dpo_rows_to_bco
assert _split_dpo_rows_to_bco([row]) == []
def test_extra_keys_ignored(self):
from soup_cli.trainer.bco import _split_dpo_rows_to_bco
out = _split_dpo_rows_to_bco(
[{"prompt": "p", "chosen": "c", "rejected": "r", "extra": "x"}]
)
assert len(out) == 2
assert all("extra" not in row for row in out)
def test_skipped_rows_logged_at_debug(self, caplog):
import logging
from soup_cli.trainer.bco import _split_dpo_rows_to_bco
caplog.set_level(logging.DEBUG, logger="soup_cli.trainer.bco")
_split_dpo_rows_to_bco([{"prompt": "p", "chosen": "c"}])
assert any("skipped" in r.message.lower() for r in caplog.records)
# ─── Template Tests ─────────────────────────────────────────────────────────
class TestBCOTemplate:
def test_bco_template_exists(self):
assert "bco" in TEMPLATES
def test_bco_template_valid_yaml(self):
import yaml
config = yaml.safe_load(TEMPLATES["bco"])
assert config["task"] == "bco"
assert config["training"]["bco_beta"] == 0.1
assert config["data"]["format"] == "dpo"
def test_bco_template_valid_config(self):
import yaml
raw = yaml.safe_load(TEMPLATES["bco"])
cfg = SoupConfig(**raw)
assert cfg.task == "bco"
assert cfg.training.bco_beta == 0.1
# ─── Trainer Wrapper Tests ──────────────────────────────────────────────────
class TestBCOTrainerWrapper:
def test_bco_import_exists(self):
from soup_cli.trainer.bco import BCOTrainerWrapper
assert BCOTrainerWrapper is not None
def test_bco_wrapper_init(self):
from soup_cli.trainer.bco import BCOTrainerWrapper
cfg = SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
)
wrapper = BCOTrainerWrapper(cfg, device="cpu")
assert wrapper.config.task == "bco"
assert wrapper.device == "cpu"
assert wrapper.model is None
assert wrapper.trainer is None
def test_bco_wrapper_init_with_options(self):
from soup_cli.trainer.bco import BCOTrainerWrapper
cfg = SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
)
wrapper = BCOTrainerWrapper(
cfg, device="cuda", report_to="wandb", deepspeed_config="ds.json",
)
assert wrapper.report_to == "wandb"
assert wrapper.deepspeed_config == "ds.json"
def test_bco_train_before_setup_raises(self):
from soup_cli.trainer.bco import BCOTrainerWrapper
cfg = SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
)
wrapper = BCOTrainerWrapper(cfg, device="cpu")
with pytest.raises(RuntimeError, match="setup"):
wrapper.train()
# ─── Routing Tests ──────────────────────────────────────────────────────────
class TestBCOTrainRouting:
"""Test that train + sweep route to BCO trainer."""
def test_sweep_routes_to_bco_trainer(self):
from soup_cli.commands.sweep import _run_single
cfg = SoupConfig(
base="some-model",
task="bco",
data={"train": "./data.jsonl", "format": "dpo"},
)
fake_dataset = {
"train": [{"prompt": "Q?", "chosen": "A", "rejected": "B"}],
}
fake_result = {
"initial_loss": 1.0,
"final_loss": 0.5,
"total_steps": 10,
"duration_secs": 60.0,
"output_dir": "./output",
"duration": "1m",
}
fake_gpu_info = {"memory_total": "0 MB", "memory_total_bytes": 0}
with mock_patch(
"soup_cli.data.loader.load_dataset", return_value=fake_dataset,
), mock_patch(
"soup_cli.utils.gpu.detect_device", return_value=("cpu", "CPU"),
), mock_patch(
"soup_cli.utils.gpu.get_gpu_info", return_value=fake_gpu_info,
), mock_patch(
"soup_cli.experiment.tracker.ExperimentTracker",
) as mock_tracker_cls, mock_patch(
"soup_cli.monitoring.display.TrainingDisplay",
), mock_patch(
"soup_cli.trainer.bco.BCOTrainerWrapper.setup",
), mock_patch(
"soup_cli.trainer.bco.BCOTrainerWrapper.train",
return_value=fake_result,
) as mock_train:
mock_tracker = MagicMock()
mock_tracker.start_run.return_value = "run-bco-1"
mock_tracker_cls.return_value = mock_tracker
result = _run_single(cfg, {}, "bco_run_1", None)
mock_train.assert_called_once()
assert result["run_id"] == "run-bco-1"
# ─── Sweep Shortcut Tests ───────────────────────────────────────────────────
class TestBCOSweepParams:
def test_bco_beta_shortcut(self):
from soup_cli.commands.sweep import _set_nested_param
config = {"training": {"bco_beta": 0.1}}
_set_nested_param(config, "bco_beta", 0.05)
assert config["training"]["bco_beta"] == 0.05
def test_bco_beta_shortcut_creates_nested_key(self):
from soup_cli.commands.sweep import _set_nested_param
config = {}
_set_nested_param(config, "bco_beta", 0.2)
assert config["training"]["bco_beta"] == pytest.approx(0.2)