forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_part_e.py
More file actions
362 lines (294 loc) · 12.6 KB
/
Copy pathtest_part_e.py
File metadata and controls
362 lines (294 loc) · 12.6 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
"""Part E — v0.32.1 stability live (#56, #57, #58, #59) for v0.33.0.
Covers:
- #56 run_lr_sweep — in-process LR-sweep loop with mocked model + DataLoader.
- #57 SoupTrainerCallback._write_spike_recovery_hint — writes JSON hint
when watchdog fires and loss_spike_recovery is enabled.
- #58 SFTTrainerWrapper._resolve_mixed_precision — wires
pick_mixed_precision into bf16/fp16 flags; preserves legacy default
when auto flag is False.
- #59 SoupTrainerCallback grad-accum advisory — fires once on threshold
crossing.
"""
from __future__ import annotations
import json
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
# ---------------------------------------------------------------------------
# #56 — run_lr_sweep
# ---------------------------------------------------------------------------
class TestRunLRSweep:
def test_empty_schedule_rejected(self):
from soup_cli.utils.lr_finder import run_lr_sweep
with pytest.raises(ValueError, match="schedule must be non-empty"):
run_lr_sweep(
model=MagicMock(), dataloader=iter([]),
schedule=[], optimizer_factory=lambda p: MagicMock(),
)
def test_loop_records_loss_per_step(self):
from soup_cli.utils.lr_finder import run_lr_sweep
# Fake model returning a tensor-like loss
def _fake_loss_value(value):
obj = MagicMock()
obj.detach = MagicMock(return_value=obj)
obj.item = MagicMock(return_value=value)
obj.backward = MagicMock(return_value=None)
return obj
loss_values = [3.0, 2.0, 1.5, 1.0]
class FakeModel:
def __init__(self):
self._idx = 0
def parameters(self):
return []
def __call__(self, **batch):
value = loss_values[self._idx]
self._idx += 1
return {"loss": _fake_loss_value(value)}
model = FakeModel()
# Fake optimizer with mutable param_groups
class FakeOptim:
def __init__(self, _params):
self.param_groups = [{"lr": 0.0}]
def zero_grad(self, set_to_none: bool = False): # noqa: ARG002
pass
def step(self):
pass
dl = iter([{"input_ids": MagicMock()}] * 4)
schedule = [1e-6, 1e-5, 1e-4, 1e-3]
losses = run_lr_sweep(
model=model, dataloader=dl, schedule=schedule,
optimizer_factory=FakeOptim,
)
assert losses == loss_values
def test_diverged_loss_breaks_loop(self):
from soup_cli.utils.lr_finder import run_lr_sweep
loss_values = [3.0, float("inf"), 1.0]
def _wrap(value):
obj = MagicMock()
obj.detach = MagicMock(return_value=obj)
obj.item = MagicMock(return_value=value)
obj.backward = MagicMock(return_value=None)
return obj
class FakeModel:
def __init__(self):
self._idx = 0
def parameters(self):
return []
def __call__(self, **batch):
value = loss_values[self._idx]
self._idx += 1
return {"loss": _wrap(value)}
class FakeOptim:
def __init__(self, _params):
self.param_groups = [{"lr": 0.0}]
def zero_grad(self, set_to_none: bool = False): # noqa: ARG002
pass
def step(self):
pass
dl = iter([{"x": MagicMock()}] * 3)
losses = run_lr_sweep(
model=FakeModel(), dataloader=dl,
schedule=[1e-6, 1e-5, 1e-4],
optimizer_factory=FakeOptim,
)
# Loop terminates after the inf — only the first finite loss kept.
assert losses == [3.0]
# ---------------------------------------------------------------------------
# #58 — auto mixed-precision push
# ---------------------------------------------------------------------------
class TestResolveMixedPrecision:
def test_auto_flag_off_preserves_legacy(self):
from soup_cli.trainer.sft import SFTTrainerWrapper
wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)
wrapper.device = "cuda"
tcfg = SimpleNamespace(auto_mixed_precision=False)
bf16, fp16 = wrapper._resolve_mixed_precision(tcfg, "any")
assert bf16 is True
assert fp16 is False
def test_auto_flag_off_cpu(self):
from soup_cli.trainer.sft import SFTTrainerWrapper
wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)
wrapper.device = "cpu"
tcfg = SimpleNamespace(auto_mixed_precision=False)
bf16, fp16 = wrapper._resolve_mixed_precision(tcfg, "any")
assert (bf16, fp16) == (False, False)
def test_auto_flag_cpu_returns_no(self):
from soup_cli.trainer.sft import SFTTrainerWrapper
wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)
wrapper.device = "cpu"
tcfg = SimpleNamespace(auto_mixed_precision=True)
assert wrapper._resolve_mixed_precision(tcfg, "any") == (False, False)
def test_auto_flag_picks_bf16_on_ampere(self, monkeypatch):
"""Ampere (cc 8.6) + non-quirk model → bf16."""
import torch
from soup_cli.trainer.sft import SFTTrainerWrapper
wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)
wrapper.device = "cuda"
monkeypatch.setattr(
torch.cuda, "get_device_capability",
lambda *_a, **_k: (8, 6),
raising=False,
)
tcfg = SimpleNamespace(auto_mixed_precision=True)
bf16, fp16 = wrapper._resolve_mixed_precision(tcfg, "neutral-model")
assert (bf16, fp16) == (True, False)
def test_auto_flag_picks_fp16_for_qwen2_on_ampere(self, monkeypatch):
import torch
from soup_cli.trainer.sft import SFTTrainerWrapper
wrapper = SFTTrainerWrapper.__new__(SFTTrainerWrapper)
wrapper.device = "cuda"
monkeypatch.setattr(
torch.cuda, "get_device_capability",
lambda *_a, **_k: (8, 6),
raising=False,
)
tcfg = SimpleNamespace(auto_mixed_precision=True)
bf16, fp16 = wrapper._resolve_mixed_precision(
tcfg, "Qwen/Qwen2-7B-Instruct",
)
assert (bf16, fp16) == (False, True)
# ---------------------------------------------------------------------------
# #57 — spike recovery hint
# ---------------------------------------------------------------------------
def _make_callback(tmp_path, **kwargs):
from soup_cli.monitoring.callback import SoupTrainerCallback
display = MagicMock()
return SoupTrainerCallback(
display=display,
tracker=None,
run_id="t",
output_dir=str(tmp_path),
**kwargs,
)
class TestSpikeRecoveryHint:
def test_writes_hint_file(self, tmp_path, monkeypatch):
# Containment guard requires output_dir to live under cwd.
monkeypatch.chdir(tmp_path)
cb = _make_callback(
tmp_path,
spike_recovery=True,
spike_recovery_max_attempts=2,
spike_recovery_lr_decay=0.5,
)
args = SimpleNamespace(
learning_rate=1e-3, output_dir=str(tmp_path),
)
cb._write_spike_recovery_hint(args, loss=10.0)
hint = tmp_path / "spike_recovery.json"
assert hint.exists()
data = json.loads(hint.read_text(encoding="utf-8"))
assert data["previous_lr"] == pytest.approx(1e-3)
assert data["recommended_lr"] == pytest.approx(5e-4)
assert data["should_recover"] is True
assert data["attempts"] == 1
def test_attempts_counter_increments(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
cb = _make_callback(
tmp_path,
spike_recovery=True,
spike_recovery_max_attempts=3,
spike_recovery_lr_decay=0.5,
)
args = SimpleNamespace(
learning_rate=1e-3, output_dir=str(tmp_path),
)
cb._write_spike_recovery_hint(args, loss=10.0)
cb._write_spike_recovery_hint(args, loss=10.0)
data = json.loads((tmp_path / "spike_recovery.json").read_text())
assert data["attempts"] == 2
def test_disabled_when_strategy_not_set(self, tmp_path):
cb = _make_callback(tmp_path, spike_recovery=False)
args = SimpleNamespace(
learning_rate=1e-3, output_dir=str(tmp_path),
)
cb._write_spike_recovery_hint(args, loss=10.0)
# No hint file written.
assert not (tmp_path / "spike_recovery.json").exists()
def test_should_recover_false_at_max_attempts(self, tmp_path, monkeypatch):
"""When attempts have hit max_attempts, should_recover must be False."""
monkeypatch.chdir(tmp_path)
cb = _make_callback(
tmp_path,
spike_recovery=True,
spike_recovery_max_attempts=2,
spike_recovery_lr_decay=0.5,
)
args = SimpleNamespace(
learning_rate=1e-3, output_dir=str(tmp_path),
)
# Bump internal counter to budget cap
cb._spike_recovery_attempts = 2
cb._write_spike_recovery_hint(args, loss=10.0)
data = json.loads((tmp_path / "spike_recovery.json").read_text())
assert data["should_recover"] is False
def test_outside_cwd_skipped(self, tmp_path):
"""Containment guard: when output_dir is outside cwd, skip silently."""
# No monkeypatch.chdir — tmp_path is outside the test's actual cwd.
cb = _make_callback(
tmp_path,
spike_recovery=True,
)
args = SimpleNamespace(
learning_rate=1e-3, output_dir=str(tmp_path),
)
cb._write_spike_recovery_hint(args, loss=10.0)
# No hint written; no exception raised.
assert not (tmp_path / "spike_recovery.json").exists()
# ---------------------------------------------------------------------------
# #59 — grad-accum advisory
# ---------------------------------------------------------------------------
class TestGradAccumAdvisory:
def test_advise_fires_once_under_pressure(self, tmp_path, monkeypatch, capsys):
cb = _make_callback(
tmp_path,
grad_accum_auto_tune=True,
grad_accum_pressure_threshold=0.5,
grad_accum_total_vram_gb=10.0,
grad_accum_current_steps=1,
grad_accum_current_batch=4,
)
# Mock torch presence + memory probe — high pressure (8 GB / 10 GB = 80%).
fake_torch = MagicMock()
fake_torch.cuda.is_available.return_value = True
fake_torch.cuda.max_memory_allocated.return_value = 8 * (1024**3)
monkeypatch.setitem(__import__("sys").modules, "torch", fake_torch)
cb._maybe_advise_grad_accum()
assert cb._grad_accum_advised is True
# Second call is a no-op (one-shot).
cb._grad_accum_monitor.observe = MagicMock()
cb._maybe_advise_grad_accum()
# Already advised, so monitor.observe shouldn't be called.
cb._grad_accum_monitor.observe.assert_not_called()
def test_no_advice_when_under_threshold(self, tmp_path, monkeypatch):
cb = _make_callback(
tmp_path,
grad_accum_auto_tune=True,
grad_accum_pressure_threshold=0.9,
grad_accum_total_vram_gb=10.0,
grad_accum_current_steps=1,
grad_accum_current_batch=4,
)
fake_torch = MagicMock()
fake_torch.cuda.is_available.return_value = True
fake_torch.cuda.max_memory_allocated.return_value = 5 * (1024**3)
monkeypatch.setitem(__import__("sys").modules, "torch", fake_torch)
cb._maybe_advise_grad_accum()
assert cb._grad_accum_advised is False
def test_no_advice_when_disabled(self, tmp_path):
cb = _make_callback(tmp_path, grad_accum_auto_tune=False)
cb._maybe_advise_grad_accum()
assert cb._grad_accum_advised is False
def test_no_advice_when_cuda_unavailable(self, tmp_path, monkeypatch):
cb = _make_callback(
tmp_path,
grad_accum_auto_tune=True,
grad_accum_pressure_threshold=0.5,
grad_accum_total_vram_gb=10.0,
grad_accum_current_steps=1,
grad_accum_current_batch=4,
)
fake_torch = MagicMock()
fake_torch.cuda.is_available.return_value = False
monkeypatch.setitem(__import__("sys").modules, "torch", fake_torch)
cb._maybe_advise_grad_accum()
assert cb._grad_accum_advised is False