Files
OBLITERATUS/tests/test_phase_memory_helpers.py
Joseph MaglyandClaude Opus 5.5 e5db2ed089 test(gpu): fit admission tests in the PR core budget
Run real-peak admission tests at four CPU threads in the PR suite, with the
one- and eight-thread variants marked slow, and shrink their geometry to
the smallest size that still discriminates the modelled workspace terms.
Evaluate the differential matrix per handle so every combination keeps its
invariant at a fraction of the cost. The PR core selection had grown past
its ten-minute limit.

The smaller geometries exposed CPU estimate gaps, now modelled: autocast
parameter-copy staging, SDPA operand casts under CPU autocast and per-worker
reduced-precision GEMM scratch. These stay estimate-only; CUDA calibrated
numbers are unchanged.

Refs #245

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:27:38 -04:00

100 lines
3.3 KiB
Python

"""Portable CPU phase-peak measurements, including native kernel temporaries.
Track allocator events, not tensor outputs or process RSS. Only allocations
created inside the measurement contribute; freeing older resident tensors must
not subtract from the phase peak. Shape recording is deliberately disabled: it
can keep tensors alive and change the lifetimes being measured.
"""
from contextlib import contextmanager
import gc
import pytest
import torch
@contextmanager
def torch_thread_count(threads):
previous = torch.get_num_threads()
torch.set_num_threads(threads)
try:
yield
finally:
torch.set_num_threads(previous)
CPU_THREAD_PARAMS = (
pytest.param(4, id="threads4"),
pytest.param(1, id="threads1", marks=pytest.mark.slow),
pytest.param(8, id="threads8", marks=pytest.mark.slow),
)
@pytest.fixture(params=CPU_THREAD_PARAMS)
def cpu_threads(request):
"""Pin PR peaks to four workers; retain one/eight-worker robustness in slow."""
with torch_thread_count(request.param):
yield request.param
@contextmanager
def cpu_memory_profile():
# Remove unreachable models from earlier tests before starting the allocator
# trace. Address tracking below still handles explicit frees of resident data.
gc.collect()
with torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CPU], profile_memory=True,
record_shapes=False, with_stack=False,
) as profile:
yield profile
def cpu_peak_bytes(profile):
"""Peak live CPU allocations born in this scope, independent of prior frees."""
events = []
pending = list(profile.profiler.kineto_results.experimental_event_tree())
while pending:
event = pending.pop()
pending.extend(event.children)
if event.name == "[memory]" and event.extra_fields.device.type == "cpu":
fields = event.extra_fields
events.append((event.start_time_ns, fields.ptr, fields.alloc_size))
live = {}
current = peak = 0
for _, address, size in sorted(events, key=lambda item: item[0]):
if size > 0:
assert address not in live, "allocator address reused without a free event"
live[address] = size
current += size
peak = max(peak, current)
elif size < 0:
current -= live.pop(address, 0)
return peak
def test_peak_ignores_frees_of_preexisting_resident_allocations(cpu_threads):
resident = torch.empty(10_000, dtype=torch.float32)
with cpu_memory_profile() as profile:
first = torch.empty(20, dtype=torch.float32)
del resident
second = torch.empty(30, dtype=torch.float32)
assert cpu_peak_bytes(profile) == (first.numel() + second.numel()) * 4
def test_peak_counts_sequential_allocations_as_peak_not_sum(cpu_threads):
with cpu_memory_profile() as profile:
first = torch.empty(128, dtype=torch.float32)
del first
second = torch.empty(64, dtype=torch.float32)
assert second.numel() == 64
assert cpu_peak_bytes(profile) == 128 * 4
def test_thread_context_restores_after_failure():
previous = torch.get_num_threads()
with pytest.raises(RuntimeError, match="test failure"):
with torch_thread_count(4):
assert torch.get_num_threads() == 4
raise RuntimeError("test failure")
assert torch.get_num_threads() == previous