Repository navigation
fix(studio): reserve a bounded OS headroom on unified ROCm APUs, not a flat 20% - #7960
danielhanchen merged 13 commits into
Conversation
🌊 Poseidon Review 🐚Reviewed One P2 is open: the log source tag at line 2998 still reports the env-var override as active when the function silently rejected it. One P3 (stale test docstring) is also open. All 25 earlier runs converge on the same P2; it is real, straightforward to fix, and matters because this env var is the only debugging escape hatch for hosts the formula gets wrong. P2 - Log claims env-var source when the override was silently rejected The source tag This env var is the escape hatch for hosts the formula gets wrong (the exact scenario that motivated this PR). A user fighting an OOM who sets it to a bad value will see the log credit their override and look elsewhere for the cause. All 25 earlier runs flagged this. Replicate the tiny validity check at the call site so the tag reflects what the function actually did: _env_accepted = False
if _env_fraction:
try:
_v = float(_env_fraction)
_env_accepted = 0.0 < _v <= 1.0
except (TypeError, ValueError):
passThen at line 2998: f"from {_MEM_FRACTION_ENV}" if _env_accepted else "computed",P3 - Test module docstring does not mention the fraction tests The docstring says """Unit tests for the ROCm OOM-guard: device classification and fraction selection.
Classification paths: (1) canonical gcnArchName, (2) alternate-spelling attr,
(3) all arch attrs absent -> device-name substring match.
Fraction selection: unified Linux reserve crossover, discrete cap, Windows
budget-exact 1.0, and the UNSLOTH_ROCM_MEM_FRACTION env override.
""" |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
The log's source tag tested the raw UNSLOTH_ROCM_MEM_FRACTION string for truthiness, but _rocm_memory_fraction silently drops values that do not parse or fall outside (0.0, 1.0]. A typo'd override printed "from UNSLOTH_ROCM_MEM_FRACTION" next to a computed fraction, which is the worst case for the one escape hatch a mis-sized host has. Pull the validation into _parse_mem_fraction_env so the call site and the helper cannot disagree, and widen the test module docstring to cover fraction selection now that it lives here too.
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
The block over the reserve constants restated _rocm_memory_fraction's own docstring across five lines. Keep only why the constant is 16 GiB, which is not recoverable from the code, and drop the issue numbers from the comments here and in the tests: the reasoning belongs inline, the tracking numbers belong in the PR.
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
🌊 Poseidon Review 🐚Reviewed Twelve findings are open: eight P2 and four P3. The one thing 26 earlier runs all flagged, the log tag that credited P2 - Divide by the total the allocator actually multiplies by
try:
_total_bytes = int(_torch_mem.cuda.mem_get_info(0)[1])
except Exception:
_total_bytes = 0
if _total_bytes <= 0:
_total_bytes = int(getattr(_props, "total_memory", 0) or 0)If you keep P2 - Clamp the unified cap at 0.90 or stop claiming the reserve stays clear of it
The test half is the same claim: Either make the claim structural and extend the test past the boundary: reserve_fraction = min(_UNIFIED_MAX_RESERVE_FRACTION, _UNIFIED_OS_RESERVE_BYTES / total_bytes)
return min(1.0 - reserve_fraction, _DISCRETE_MEM_FRACTION)or state the invariant the code really has, which is the absolute reserve, and assert that instead: @pytest.mark.parametrize("pool_gib", [96, 128, 160, 256])
def test_above_crossover_reserves_the_constant(self, pool_gib: int) -> None:
total = pool_gib * GIB
fraction = _rocm_memory_fraction(total, True, "linux")
assert total - fraction * total == pytest.approx(_UNIFIED_OS_RESERVE_BYTES)P2 - Back the 16 GiB reserve with a measurement, or size it against what is resident On a 128 GiB pool this drops the OS reserve from 25.6 GiB to 16 GiB, and the only datapoint in the comment is that The failure modes are not symmetric: too tight costs the user headroom and a visible Attach one run at the new cap on a real 128 GiB host to the PR (the reporter of #7878 has the box), or fold what is already resident into the reserve: free_bytes, pool_total = torch.cuda.mem_get_info(0)
resident = max(0, pool_total - free_bytes)
reserve = _UNIFIED_OS_RESERVE_BYTES + residentIf neither is available, land the mechanism, leave the default at the historical 20%, and document P2 - Do not log "0.0 of 0.0 GiB allowed" when the device total is unknown
Build the clause conditionally and pass it through a single _allowed = (
f"{_total_bytes * _mem_fraction / 1024**3:.1f} of "
f"{_total_bytes / 1024**3:.1f} GiB allowed"
if _total_bytes > 0
else "device total unreported by this wheel"
)P2 - Warn with the rejected value when UNSLOTH_ROCM_MEM_FRACTION is discarded The source tag is honest now, but a set-and-rejected value still leaves no trace. Keep it at the call site, since _env_fraction = _parse_mem_fraction_env(_env_raw)
if _env_raw and _env_fraction is None:
logger.warning(
"ROCm OOM guard: ignoring %s=%r (needs a float in (0.0, 1.0]); "
"using the computed cap instead",
_MEM_FRACTION_ENV,
_env_raw,
)Then narrow the P2 - Name UNSLOTH_ROCM_MEM_FRACTION in the log on the computed path too The variable is named in the log only in the branch where it was already set, so the person who needs the escape hatch, by definition the one who has not set it, never learns it exists. The reporter in #7878 wants ~25.6 GiB back on a 128 GiB box; after this change 16 GiB is still withheld, so "Fixes #7878" only holds all the way if they discover the override, and their discovery path is reading f"from {_MEM_FRACTION_ENV}" if _env_fraction is not None
else f"computed; override with {_MEM_FRACTION_ENV}",P2 - Keep one source pin on section 1g so the guard's wiring stays covered Converting def test_guard_delegates_to_the_fraction_helper(self) -> None:
source = _WORKER_PY.read_text(encoding = "utf-8")
assert "_mem_fraction = _rocm_memory_fraction(" in source
assert 'getattr(_props, "total_memory", 0)' in source
assert 'if _env_fraction is not None else "computed"' in sourceP3 - Assert the 0.80 floor exactly instead of pytest.approx The comment above the assertion says the cap is "bit-identical to the pre-#7878 flat 0.80", and the arithmetic in assert _rocm_memory_fraction(pool_gib * GIB, True, "linux") == 0.80P3 - Prefix the new ROCm constants with their domain
_ROCM_UNIFIED_OS_RESERVE_BYTES = 16 * 1024**3
_ROCM_UNIFIED_MAX_RESERVE_FRACTION = 0.20
_ROCM_DISCRETE_MEM_FRACTION = 0.90
_ROCM_MEM_FRACTION_ENV = "UNSLOTH_ROCM_MEM_FRACTION"
def _parse_rocm_mem_fraction_env(env_value: str | None) -> float | None:
P3 - Say what the zero-total branch guards, not which wheel you think causes it
if total_bytes <= 0:
# The caller defaults a missing or None total_memory to 0; with no pool
# size there is nothing to solve against, so keep the historical cap.
return 1.0 - _UNIFIED_MAX_RESERVE_FRACTIONP3 - Cut the stale classifier recap from the section 1g header The header still says the cap applies to # ── 1g. ROCm OOM guard ──
# On ROCm, exhausting VRAM can hang the HIP driver instead of raising.
# set_per_process_memory_fraction caps the allocator so PyTorch raises OutOfMemoryError
# first. Unified hosts share GPU+system RAM and need OS headroom, so the cap depends on
# the classification and the pool size (see _rocm_memory_fraction). Skipped if no torch.P3 - Widen the test module docstring to cover the fraction tests The module docstring says """Unit tests for the ROCm OOM-guard: device classification and fraction selection.
Classification paths: (1) canonical gcnArchName, (2) alternate-spelling attr,
(3) all arch attrs absent -> device-name substring match.
Fraction selection: unified Linux reserve crossover, discrete cap, Windows
budget-exact 1.0, and the UNSLOTH_ROCM_MEM_FRACTION env override.
""" |
…he discrete cap Review findings on 96d3ca3, ahead of testing on real APU hardware. The reserve is an absolute 16 GiB, so the denominator matters: the caching allocator multiplies the fraction by mem_get_info's total, while the guard was dividing by props.total_memory. Those agree on a discrete card but are not the same number on a unified host, which is exactly where this PR applies. Size against mem_get_info and keep props as the fallback. Above ~160 GiB the byte reserve is under 10% of the pool, so a unified host got a looser cap than a discrete card and the "never reaches the 0.90 measured as starving" claim was false. Clamp at _DISCRETE_MEM_FRACTION; the old test stopped at 156 GiB, one step short of the boundary, so nothing caught it. Also: warn when UNSLOTH_ROCM_MEM_FRACTION is set but rejected, name the variable on the computed path so the person who needs it can find it, stop printing "0.0 of 0.0 GiB allowed" when the wheel reports no total, assert the historical cap exactly rather than through approx, and re-pin section 1g's wiring since it runs behind IS_ROCM and no CI machine reaches it.
|
Nine of the twelve are fixed in P2 - clamp at 0.90. Correct, and it's the one that mattered. Now P2 - denominator. Taken. The guard now sizes against P2 - P2 - warn on a rejected override. Fixed at the call site, so it fires once per worker start rather than twice. P2 - name the variable on the computed path. Fixed: P2 - source pin on section 1g. Fair, and self-inflicted: I removed those pins in this PR when converting them to direct calls. Added P3 - exact instead of P3 - zero-total comment and P3 - stale classifier recap in the 1g header. Both fixed. The header no longer claims gcnArchName-first when the classifier checks Not doingP2 - back the 16 GiB with a measurement. Agreed in principle, and it is the right thing to ask. It is being tested on real APU hardware before this merges, which is the only thing that settles it. I don't want to take the fallback of landing the mechanism at the historical 20%, since that leaves the reported bug unfixed. If the run shows 16 GiB is too thin, the constant moves. P3 - P3 - test module docstring. Already fixed in Head is |
…ator uses 81b114e switched the guard to size against mem_get_info on a review finding that claimed the caching allocator multiplies the fraction by that total. It does not. c10's CUDACachingAllocator::setMemoryFraction caps at fraction * device_prop.totalGlobalMem with device_prop filled once from cudaGetDeviceProperties, which is exactly props.total_memory. mem_get_info reports a runtime budget on some hosts, so dividing by it while the allocator divides by totalGlobalMem would have made the reserve something other than the 16 GiB this PR is built on -- the very failure the finding warned about, introduced by the fix for it. Restores the original denominator, cites the allocator in the docstring so the claim is checkable rather than asserted, and repoints the section 1g source pin. Every other fix from 81b114e stands.
|
Correcting my previous comment: I took the denominator finding and I should not have. Codex flagged the change on allowed_memory_maximum = static_cast<size_t>(std::round(
fraction * static_cast<double>(device_prop.totalGlobalMem)));
Reverted in Everything else from Head is |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
hogeheer499-commits
left a comment
There was a problem hiding this comment.
Physical gfx1151 data point from a 128 GB Beelink GTR9 Pro. This does not invalidate the policy, but it shows that the result depends on what the installed ROCm/PyTorch wheel exposes as props.total_memory, not on the host/GTT size buyers see.
Ryzen AI MAX+ 395 / Radeon 8060S
Linux 7.0.0-28-generic
torch 2.13.0a0+rocm7.13.0a20260422
HIP 7.13.26154
host RAM: 124.92 GiB
sysfs VRAM total: 0.50 GiB
sysfs GTT total: 128.00 GiB
props.is_integrated: 1
props.total_memory: 62.47 GiB
mem_get_info total: 62.47 GiB
mem_get_info free: 120.00 GiB
Kernel command line includes amdgpu.gttsize=131072; BIOS UMA is 512 MB.
For this real configuration, the PR's bounded-reserve calculation correctly remains at the historical 0.80, because the allocator denominator is below the 80 GiB crossover. It therefore does not return the expected 0.875 or hand back memory on this particular 128 GB Strix Halo setup.
The mem_get_info free value being larger than its reported total is also worth noting, and reinforces why props.total_memory is the right denominator for set_per_process_memory_fraction even though it does not reflect the full sysfs GTT pool here.
I have not done a near-cap training stress run, so this is detection/policy validation only, not evidence that a 16 GiB reserve is safe under load. It does show that the PR remains conservative on at least one current Linux gfx1151 stack, and that docs should avoid implying every 128 GB Strix Halo will automatically move to 0.875.
|
Thank you for taking the time to run this on real hardware, and for reporting it this carefully. Listing sysfs, props and Your reading is right and the behaviour is intended. The crossover is 16 GiB / 0.20 = 80 GiB of On the 62.47 GiB itself: that is half your 124.92 GiB of RAM. The Agreed on the docs point. I will retitle the table column from "pool" to |
|
@danielhanchen if you can test this, one thing to check first: If it is at half your RAM, that is the TTM page limit default rather than the GPU: Above 80 GiB the cap should compute to ~0.8667, reserving exactly 16 GiB. What I am after is a near-cap training run that does not freeze the host. That is the only thing still blocking this: the 16 GiB constant is unmeasured, and per #5301, 0.90 on a 128 GiB pool was measured as OS-starving. |
|
staged latest ci: |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
The docstring claimed props.total_memory is "the same number torch multiplies the
fraction against", citing c10's setMemoryFraction. That holds from torch 2.10 on,
where the allocator caps at fraction * device_prop.totalGlobalMem. Through 2.9 it
caps at fraction * the total from hipMemGetInfo instead:
v2.9.1 / release/2.9 / 2.8 / 2.7 / 2.6:
C10_CUDA_CHECK(cudaMemGetInfo(&device_free, &device_total));
allowed_memory_maximum = fraction * device_total;
release/2.10 / 2.11 / main:
allowed_memory_maximum = round(fraction * device_prop.totalGlobalMem);
install_python_stack.py pins torch>=2.11 only for the rocm7.2 route; the general
ROCm route is torch>=2.4,<2.11, so most unified hosts land on the older
denominator. props.total_memory stays the right thing to divide by, since that is
where torch has settled and mem_get_info's total is a runtime budget rather than
the pool on some hosts, but the unqualified claim was checkable and wrong for the
versions most of these boxes run.
Where the two disagree the absolute reserve is scaled by their ratio, and nothing
said so. Added a note that prints both totals and the headroom that actually
results. Scoped to the unified byte arm: discrete and win32 take a flat fraction,
which no denominator gap can distort, and the Windows budget legitimately differs
from props on every boot. A 1% band keeps rounding quiet, mem_get_info failures
fall back to silence, and the whole thing is inside the guard's existing
try/except.
That gap is not hypothetical on this hardware. ROCm can report VRAM and GTT
summed on gfx1151 (96 GiB carve plus 128 GiB GTT reads as ~220 GiB on a 128 GB
machine), and the field report on this PR has mem_get_info returning free 120.00
GiB against total 62.47 GiB.
|
Pushed What I checkedI could not run ROCm here, so I pulled section 1g out of Invariants asserted on every case: the guard never raises, the fraction is always a float in Result: 7,257 identical, 3,399 changed, 2,604 with no cap set at all, zero violations. Every changed case is either unified Linux above the 80 GiB crossover or an accepted env override. To confirm the harness was not vacuous I injected nine regressions (drop the 0.90 clamp, tag off the raw env string, one-sided env bound, remove the zero-total guard, size against On real hardware the fraction contract holds: on a B200 with torch 2.9.1, every fraction this policy can emit ( The one thing that was wrongThe docstring said
Why the new log lineWhere the two totals disagree the absolute reserve is scaled by their ratio, and nothing reported it:
Not hypothetical on this hardware. ROCm/legacy-rocm-build#6004 has gfx1151 reporting VRAM and GTT summed, 96 GiB carve plus 128 GiB GTT reading as roughly 220 GiB on a 128 GB box, and your own field report has It is scoped to the unified byte arm, so discrete and win32 stay silent (a flat fraction cannot be distorted by a denominator gap, and the Windows budget legitimately differs from props on every boot). A 1% band keeps rounding quiet, a Not changedThe 16 GiB constant. Your reasoning for holding it until a real 128 GiB run is right. One datapoint for that discussion: the policy shipping today already reserves 12.8 GiB on a 64 GiB APU, the same absolute headroom that #5301 measured as OS-starving at 0.90 on 128 GiB, and no freezes have come back from those. It does not settle the question but it narrows what the run has to prove. Also worth a line in the PR body, since it is the first thing anyone will hit: on a host where ROCm reports VRAM and GTT summed, |
Logging the props-vs-driver gap did not correct it. Through torch 2.9 the cap is
enforced as fraction * hipMemGetInfo total, so on a unified APU, where that total
is the GTT-spanning runtime budget rather than the property carve-out, the 16 GiB
reserve came out scaled by the ratio of the two.
_rocm_memory_fraction now takes the allocator's own denominator and re-solves for
the same allowed bytes against it. Bounded on three sides so nothing else moves:
- Only on the byte arm. Below the 80 GiB crossover the policy is a percentage,
which is scale-free, and those small pools are the OOM-prone ones unslothai#5301 added
the guard for. They stay bit-identical to the flat 0.80.
- Floored at that same 0.80. A driver total larger than the property total would
otherwise pull the cap under the value it replaced, and no host should come out
of a loosening change tighter, even at the cost of the exact reserve.
- Still clamped at the discrete cap, so the ordering the guard is built on holds.
_allocator_divides_by_props_total reads the release from torch.__version__ and
answers True for anything unparsable, so a surprise version string keeps today's
denominator rather than silently switching it on hardware nobody can check.
Measured on a 128 GiB property pool with a driver total 2% larger: the reserve was
13.7 GiB, now 16.0 GiB. At a driver total of 220 GiB the floor takes over and the
cap is 0.80, identical to main. Below the crossover nothing changes on either
torch generation.
The gap is normal on this hardware rather than exotic: props.total_memory is the
dedicated carve-out while hipMemGetInfo reports the runtime pool including GTT
(ROCm/hip#348, ggml-org/llama.cpp#18159), and both swing with BIOS UMA and the TTM
page limit.
test_rocm_oom_guard.py: 155 passed. Backend suite: 18904 passed. A 20,940-case
before/after simulation of the guard block over platform x accelerator x pool x
driver total x torch version holds every invariant: never tighter than main, never
looser than the intended reserve unless the floor forced it, never above the
discrete cap, and bit-identical to main outside the byte arm.
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Comment-only pass over the lines this review round added, cutting the two docstrings and four inline blocks to what the code does not already say. Scoped to those hunks rather than the whole file: the earlier passes on this branch already settled the rest, and rewriting them now would churn a diff that has converged. AST-checked as comments only.
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Fixes #7878.
The ROCm OOM guard caps the torch allocator so HIP raises
OutOfMemoryErrorinstead of hanging the ring buffer. On unified-memory APUs that cap is a flat0.80, set in #5301. A flat percentage scales the reserve with the pool, so a 128 GB Strix Halo withholds ~25 GiB, and the reporter has ~30 GB they can't train into.The reserve is now
min(20% of total, 16 GiB):Below the 80 GiB crossover the 20% arm still wins, so small APUs, the ones actually OOM-prone, keep a bit-identical cap. The function is monotonic and floored at 0.80, so this can only loosen, never tighten.
16 GiB is chosen against #5301's own measurement:
0.90 × 128 GBleaves ~13 GB for the system and reproduces the freeze it was added to prevent. The reserve has to stay clear of that, which rules out the tighter constants that would otherwise hand back more.Windows is untouched: the WDDM budget already excludes the OS share, so it stays at
1.0. Discrete stays at0.90.UNSLOTH_ROCM_MEM_FRACTIONoverrides everything when it parses to a float in(0.0, 1.0]; anything else is ignored and never fatal.The fraction is solved in fraction space rather than bytes, because
(total - 0.20 * total) / totalrounds to0.7999999999999999at 12/24/28/48 GiB and would break the never-tighter-than-0.80 guarantee by a ULP.Verification
test_rocm_oom_guard.py: 69 passed. Covers the crossover, the large-pool constant, monotonicity, the 0.80 floor, the sub-0.90 ceiling, the env override including malformed values, and the win32 and discrete paths.