forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_batch_probe.py
More file actions
568 lines (444 loc) · 18.1 KB
/
Copy pathtest_batch_probe.py
File metadata and controls
568 lines (444 loc) · 18.1 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
"""Tests for OOM-probe auto batch-size (v0.36.0 Part D).
Replaces sft.py's static-formula auto-batch with a real try/halve probe and
a per-machine cache so repeat runs short-circuit. Mirrors LlamaFactory and
Axolotl behaviour.
"""
from __future__ import annotations
import json
import pytest
class _OOMError(Exception):
"""Stand-in for ``torch.cuda.OutOfMemoryError`` in unit tests."""
# ---------------------------------------------------------------------------
# Schema field
# ---------------------------------------------------------------------------
class TestSchemaField:
def test_default_is_auto(self):
from soup_cli.config.schema import TrainingConfig
tcfg = TrainingConfig()
assert tcfg.auto_batch_size_strategy == "auto"
def test_accepts_static(self):
from soup_cli.config.schema import TrainingConfig
tcfg = TrainingConfig(auto_batch_size_strategy="static")
assert tcfg.auto_batch_size_strategy == "static"
def test_accepts_probe(self):
from soup_cli.config.schema import TrainingConfig
tcfg = TrainingConfig(auto_batch_size_strategy="probe")
assert tcfg.auto_batch_size_strategy == "probe"
def test_rejects_unknown_value(self):
from soup_cli.config.schema import TrainingConfig
with pytest.raises(ValueError):
TrainingConfig(auto_batch_size_strategy="random")
# ---------------------------------------------------------------------------
# Pure binary search
# ---------------------------------------------------------------------------
class TestProbeLoop:
def test_converges_when_capacity_below_start(self):
"""Capacity 3, start 4 → halves to 2 (largest power of two that
fits). Doubling probe(4) re-OOMs, so we stay at 2. Power-of-two
granularity is a deliberate choice: we trade exactness for fewer
probe steps (each step is a real GPU forward+backward)."""
from soup_cli.utils.batch_probe import probe_batch_size
capacity = 3
def probe(b: int) -> bool:
if b > capacity:
raise _OOMError("simulated")
return True
out = probe_batch_size(
probe,
start=4,
ceiling=16,
oom_exceptions=(_OOMError,),
)
assert out == 2
def test_converges_when_capacity_above_start(self):
"""Start 2, capacity 8 → doubles 2→4→8→16(OOM), back off → 8."""
from soup_cli.utils.batch_probe import probe_batch_size
capacity = 8
def probe(b: int) -> bool:
if b > capacity:
raise _OOMError("simulated")
return True
out = probe_batch_size(
probe,
start=2,
ceiling=64,
oom_exceptions=(_OOMError,),
)
assert out == capacity
def test_ceiling_caps_at_4x_static(self):
"""Capacity 1000, ceiling 8 → returns 8 (never tries higher)."""
from soup_cli.utils.batch_probe import probe_batch_size
def probe(b: int) -> bool:
return True # never OOMs
out = probe_batch_size(
probe,
start=2,
ceiling=8,
oom_exceptions=(_OOMError,),
)
assert out == 8
def test_starts_oom_halves_to_one(self):
"""Even start=1 OOMs → returns 1 (never go below 1)."""
from soup_cli.utils.batch_probe import probe_batch_size
def probe(b: int) -> bool:
raise _OOMError("starved")
with pytest.raises(RuntimeError, match="batch_size=1"):
probe_batch_size(
probe,
start=2,
ceiling=16,
oom_exceptions=(_OOMError,),
)
def test_max_doublings_capped(self):
"""Search must not run forever — cap at 8 doublings."""
from soup_cli.utils.batch_probe import probe_batch_size
calls: list[int] = []
def probe(b: int) -> bool:
calls.append(b)
return True
probe_batch_size(
probe,
start=1,
ceiling=10**6,
oom_exceptions=(_OOMError,),
max_doublings=8,
)
# At most 8 successful doublings + initial = 9 successful probes.
assert len(calls) <= 12
def test_rejects_invalid_start(self):
from soup_cli.utils.batch_probe import probe_batch_size
with pytest.raises(ValueError, match="start"):
probe_batch_size(
lambda b: True,
start=0,
ceiling=8,
oom_exceptions=(_OOMError,),
)
def test_rejects_invalid_ceiling(self):
from soup_cli.utils.batch_probe import probe_batch_size
with pytest.raises(ValueError, match="ceiling"):
probe_batch_size(
lambda b: True,
start=4,
ceiling=2, # < start
oom_exceptions=(_OOMError,),
)
def test_unrelated_exception_propagates(self):
"""A non-OOM exception must propagate, not be swallowed as OOM."""
from soup_cli.utils.batch_probe import probe_batch_size
def probe(b: int) -> bool:
raise RuntimeError("model bug")
with pytest.raises(RuntimeError, match="model bug"):
probe_batch_size(
probe,
start=2,
ceiling=16,
oom_exceptions=(_OOMError,),
)
# ---------------------------------------------------------------------------
# Cache layer
# ---------------------------------------------------------------------------
class TestCache:
def test_key_normalizes(self):
from soup_cli.utils.batch_probe import make_cache_key
a = make_cache_key(
base="meta-llama/Llama-3.2-1B",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="NVIDIA A100-SXM4-80GB",
gpu_memory_gb=80,
)
b = make_cache_key(
base="meta-llama/Llama-3.2-1B",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="NVIDIA A100-SXM4-80GB",
gpu_memory_gb=80,
)
assert a == b
def test_key_differs_on_quantization(self):
from soup_cli.utils.batch_probe import make_cache_key
a = make_cache_key("m", 2048, "4bit", 64, "gpu", 80)
b = make_cache_key("m", 2048, "8bit", 64, "gpu", 80)
assert a != b
def test_key_rejects_bool_inputs(self):
"""v0.30.0 Candidate convention: bool is a subclass of int — guard."""
from soup_cli.utils.batch_probe import make_cache_key
with pytest.raises(ValueError, match="max_length"):
make_cache_key("m", True, "4bit", 64, "gpu", 80)
with pytest.raises(ValueError, match="lora_r"):
make_cache_key("m", 2048, "4bit", True, "gpu", 80)
with pytest.raises(ValueError, match="gpu_memory_gb"):
make_cache_key("m", 2048, "4bit", 64, "gpu", True)
def test_save_and_load_roundtrip(self, tmp_path, monkeypatch):
from soup_cli.utils.batch_probe import (
load_cache,
make_cache_key,
save_cache_entry,
)
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
key = make_cache_key("m", 2048, "4bit", 64, "gpu", 80)
save_cache_entry(key, 8)
cache = load_cache()
assert cache.get(key) == 8
def test_load_corrupt_returns_empty(self, tmp_path, monkeypatch):
from soup_cli.utils.batch_probe import load_cache
cache_path = tmp_path / "batch_cache.json"
cache_path.write_text("not json", encoding="utf-8")
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
assert load_cache() == {}
def test_load_missing_returns_empty(self, tmp_path, monkeypatch):
from soup_cli.utils.batch_probe import load_cache
cache_path = tmp_path / "missing.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
assert load_cache() == {}
def test_save_rejects_non_positive_value(self, tmp_path, monkeypatch):
from soup_cli.utils.batch_probe import make_cache_key, save_cache_entry
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
key = make_cache_key("m", 2048, "4bit", 64, "gpu", 80)
with pytest.raises(ValueError):
save_cache_entry(key, 0)
with pytest.raises(ValueError):
save_cache_entry(key, -1)
def test_save_rejects_bool_value(self, tmp_path, monkeypatch):
"""``bool`` is a subclass of int — guard like v0.30.0 Candidate."""
from soup_cli.utils.batch_probe import make_cache_key, save_cache_entry
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
key = make_cache_key("m", 2048, "4bit", 64, "gpu", 80)
with pytest.raises(ValueError):
save_cache_entry(key, True)
# ---------------------------------------------------------------------------
# pick_batch_size — main entry point
# ---------------------------------------------------------------------------
class TestPickBatchSize:
def test_static_strategy_returns_static_estimate(self, tmp_path, monkeypatch):
from soup_cli.utils.batch_probe import pick_batch_size
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
out = pick_batch_size(
static_estimate=4,
strategy="static",
base="m",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="cpu",
gpu_memory_gb=0,
probe_fn=None,
)
assert out == 4
def test_cache_hit_short_circuits_probe(self, tmp_path, monkeypatch):
from soup_cli.utils.batch_probe import (
make_cache_key,
pick_batch_size,
save_cache_entry,
)
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
key = make_cache_key("m", 2048, "4bit", 64, "gpu", 80)
save_cache_entry(key, 16)
called: list[int] = []
def probe(b):
called.append(b)
return True
out = pick_batch_size(
static_estimate=4,
strategy="probe",
base="m",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="gpu",
gpu_memory_gb=80,
probe_fn=probe,
)
assert out == 16
assert called == [] # probe was not invoked
def test_probe_strategy_runs_probe_and_caches(self, tmp_path, monkeypatch):
from soup_cli.utils.batch_probe import (
load_cache,
make_cache_key,
pick_batch_size,
)
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
capacity = 8
def probe(b):
if b > capacity:
raise _OOMError("oom")
return True
out = pick_batch_size(
static_estimate=4,
strategy="probe",
base="m",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="gpu",
gpu_memory_gb=80,
probe_fn=probe,
oom_exceptions=(_OOMError,),
)
assert out == capacity
# Cache write happened.
cache = load_cache()
key = make_cache_key("m", 2048, "4bit", 64, "gpu", 80)
assert cache[key] == capacity
def test_probe_without_callable_falls_back_to_static(self, tmp_path, monkeypatch):
"""No probe_fn supplied (e.g. CPU run) → use static estimate."""
from soup_cli.utils.batch_probe import pick_batch_size
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
out = pick_batch_size(
static_estimate=4,
strategy="probe",
base="m",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="cpu",
gpu_memory_gb=0,
probe_fn=None,
)
assert out == 4
def test_auto_strategy_uses_probe_when_probe_fn_supplied(
self, tmp_path, monkeypatch
):
from soup_cli.utils.batch_probe import pick_batch_size
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
capacity = 4
def probe(b):
if b > capacity:
raise _OOMError("oom")
return True
out = pick_batch_size(
static_estimate=2,
strategy="auto",
base="m",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="gpu",
gpu_memory_gb=80,
probe_fn=probe,
oom_exceptions=(_OOMError,),
)
assert out == capacity
def test_cache_corruption_does_not_block_probe(self, tmp_path, monkeypatch):
"""Corrupt cache file → silently re-probe; ceiling = static * 4."""
from soup_cli.utils.batch_probe import pick_batch_size
cache_path = tmp_path / "batch_cache.json"
cache_path.write_text("garbage", encoding="utf-8")
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
out = pick_batch_size(
static_estimate=4,
strategy="probe",
base="m",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="gpu",
gpu_memory_gb=80,
probe_fn=lambda b: True,
oom_exceptions=(_OOMError,),
)
# Probe ran; with no OOMs and ceiling = 4*4 = 16, lands at 16.
assert out == 16
def test_runtime_error_propagates_when_bs1_ooms(self, tmp_path, monkeypatch):
"""All-OOM probe → RuntimeError surfaces to caller."""
from soup_cli.utils.batch_probe import pick_batch_size
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
def always_oom(b):
raise _OOMError("oom")
with pytest.raises(RuntimeError, match="batch_size=1"):
pick_batch_size(
static_estimate=2,
strategy="probe",
base="m",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="gpu",
gpu_memory_gb=80,
probe_fn=always_oom,
oom_exceptions=(_OOMError,),
)
def test_explicit_probe_no_probe_fn_emits_warning(
self, tmp_path, monkeypatch
):
"""strategy='probe' with probe_fn=None → console warning fires."""
from io import StringIO
from rich.console import Console
from soup_cli.utils.batch_probe import pick_batch_size
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
buf = StringIO()
console = Console(file=buf, force_terminal=False)
out = pick_batch_size(
static_estimate=4,
strategy="probe",
base="m",
max_length=2048,
quantization="4bit",
lora_r=64,
gpu_name="cpu",
gpu_memory_gb=0,
probe_fn=None,
console=console,
)
assert out == 4
assert "probe_fn" in buf.getvalue() or "static" in buf.getvalue()
# ---------------------------------------------------------------------------
# Cache-path containment (security review fix)
# ---------------------------------------------------------------------------
class TestCachePathContainment:
def test_out_of_bounds_override_falls_back_to_default(
self, tmp_path, monkeypatch
):
"""Env var pointing outside home/cwd/tmp → ignored, default used."""
import os
from soup_cli.utils.batch_probe import _cache_path
# Use a sibling-of-temp path that is guaranteed outside any anchor —
# an absolute root we cannot write to is equally fine, since the
# function only resolves+rejects, no I/O.
if os.name == "nt":
evil = "C:\\evil-bound\\batch.json"
else:
evil = "/etc/cron.d/soup_evil"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", evil)
path = _cache_path()
# Fall-through path — must NOT be the evil override.
assert os.path.realpath(path) != os.path.realpath(evil)
assert path.endswith("batch_cache.json")
def test_in_bounds_override_honoured(self, tmp_path, monkeypatch):
import os
from soup_cli.utils.batch_probe import _cache_path
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
# tmp_path is under tempfile.gettempdir() — allowed. Compare via
# realpath to normalise across short-name / forward-slash forms.
assert os.path.realpath(_cache_path()) == os.path.realpath(str(cache_path))
# ---------------------------------------------------------------------------
# Cache file integrity guard
# ---------------------------------------------------------------------------
class TestCacheFileShape:
def test_cache_is_dict_of_str_int(self, tmp_path, monkeypatch):
from soup_cli.utils.batch_probe import make_cache_key, save_cache_entry
cache_path = tmp_path / "batch_cache.json"
monkeypatch.setenv("SOUP_BATCH_CACHE_PATH", str(cache_path))
key = make_cache_key("m", 2048, "4bit", 64, "gpu", 80)
save_cache_entry(key, 8)
with open(cache_path, encoding="utf-8") as f:
data = json.load(f)
assert isinstance(data, dict)
for k, v in data.items():
assert isinstance(k, str)
assert isinstance(v, int)
assert v > 0