Skip to content

fix(studio): reserve a bounded OS headroom on unified ROCm APUs, not a flat 20% - #7960

Merged
danielhanchen merged 13 commits into
unslothai:mainfrom
LeoBorcherding:fix/7878-rocm-linux-unified-mem-cap
Aug 9, 2026
Merged

danielhanchen merged 13 commits into
unslothai:mainfrom
LeoBorcherding:fix/7878-rocm-linux-unified-mem-cap

Conversation

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Fixes #7878.

The ROCm OOM guard caps the torch allocator so HIP raises OutOfMemoryError instead of hanging the ring buffer. On unified-memory APUs that cap is a flat 0.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):

pool before after reserved
≤ 80 GiB 0.80 0.80 20%, unchanged
128 GiB 0.80 0.875 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 GB leaves ~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 at 0.90.

UNSLOTH_ROCM_MEM_FRACTION overrides 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) / total rounds to 0.7999999999999999 at 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.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

🌊 Poseidon Review 🐚

Reviewed d2b6266.

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
studio/backend/core/training/worker.py:2998

The source tag f"from {_MEM_FRACTION_ENV}" if _env_fraction else "computed" checks whether the raw env string is truthy, not whether _rocm_memory_fraction actually accepted it. When UNSLOTH_ROCM_MEM_FRACTION is set to a non-numeric string (O.95, a letter-O typo), 0, or an out-of-range value like 1.5, the function at line 862-868 silently falls through to the computed path, but the log still prints "from UNSLOTH_ROCM_MEM_FRACTION" next to a fraction the user never asked for.

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):
        pass

Then at line 2998:

f"from {_MEM_FRACTION_ENV}" if _env_accepted else "computed",

P3 - Test module docstring does not mention the fraction tests
studio/backend/tests/test_rocm_oom_guard.py:4

The docstring says Unit tests for _rocm_classify_unified_memory (ROCm OOM-guard classifier) and describes only the three classification paths. The file now also tests _rocm_memory_fraction (crossover, env override, discrete cap, Windows budget-exact). The next person opening this file will expect classifier tests only. One earlier run raised this.

"""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.
"""

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: d2b6266097

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@LeoBorcherding LeoBorcherding self-assigned this Aug 7, 2026
LeoBorcherding and others added 4 commits August 8, 2026 01:51
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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 450fd82fd0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 96d3ca367e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

🌊 Poseidon Review 🐚

Reviewed 96d3ca3.

Twelve findings are open: eight P2 and four P3. The one thing 26 earlier runs all flagged, the log tag that credited UNSLOTH_ROCM_MEM_FRACTION for a fraction it did not produce, is fixed at 450fd82 and stays fixed at head, since 96d3ca3 is a comment-only pass. Fix the denominator next: _rocm_memory_fraction divides _UNIFIED_OS_RESERVE_BYTES by props.total_memory while set_per_process_memory_fraction multiplies by the allocator's own total, and if those disagree on a unified host the reserve is not the 16 GiB the whole PR is built on. Caveat on this pass: the checkout was not readable (permission denied on every path under it), so no finding below was re-verified by opening the file at head; states are derived from code the 450fd82 runs quote verbatim plus the author's statement that head changes only comments. Treat the line numbers as approximate.

P2 - Divide by the total the allocator actually multiplies by
studio/backend/core/training/worker.py:3702

_total_bytes is int(getattr(_props, "total_memory", 0) or 0), but the docstring at line 1569 asserts it is "the same number torch multiplies the fraction against", and nothing establishes that. set_per_process_memory_fraction caps at fraction * total where the allocator takes total from its own device query, and this same block reads mem_get_info(0)[1] a dozen lines below for the Windows hint, with a comment calling that value the WDDM budget rather than the physical pool. A percentage does not care about the denominator, an absolute 16 GiB reserve does: if the two totals diverge on any unified host the withheld headroom is driver_total * 16 GiB / props_total, not 16 GiB, and the new %.1f of %.1f GiB allowed clause prints a budget the allocator is not enforcing next to a Windows grants the GPU %.1f GiB line computed from the other total. Four runs of 450fd82 raised this; it is the load-bearing assumption of the change.

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 props.total_memory, drop the "same number torch multiplies the fraction against" clause from the docstring unless you can point at the allocator source for the torch version studio pins.

P2 - Clamp the unified cap at 0.90 or stop claiming the reserve stays clear of it
studio/backend/core/training/worker.py:1596

1.0 - min(0.20, 16 GiB / total) is exactly 0.90 at a 160 GiB pool and 0.9375 at 256 GiB, so above the crossover a unified host gets a looser cap than a discrete card, inverting the ordering the guard is built on. The head commit reworded the constant's comment to "0.90 on that pool was measured as OS-starving, so the reserve stays clear of it", which is still the unconditional claim. This is reachable without a 160 GiB APU: _rocm_classify_unified_memory returns unified for anything with props.is_integrated truthy, not just gfx115x, so nothing bounds total_bytes.

The test half is the same claim: test_never_reaches_the_090_recorded_as_starving parametrises (96, 128, 156), and 156 GiB is the last size where the assertion holds, while test_fraction_is_monotonic_and_floored_at_080 already sweeps range(4, 260, 4) past the crossover and asserts only the 0.80 floor. Ten runs across both commits raised some form of this.

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
studio/backend/core/training/worker.py:1538

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 0.90 on that pool, leaving 12.8 GiB, froze the host. The new default sits 3.2 GiB from a configuration observed to hang the machine, and the comment then spends part of that same 16 GiB on this process's own host-side use (dataset workers, checkpoint writes), which scales with model and dataset rather than with pool size.

The failure modes are not symmetric: too tight costs the user headroom and a visible OutOfMemoryError, too loose costs a whole-machine freeze mid-run, and per the guard's own comment HIP hangs rather than raising. Nobody reviewing this can run the hardware, so an unmeasured constant on the freeze side is the riskiest line in the diff. Note also that set_per_process_memory_fraction caps against total, not against free, so the 16 GiB is only real headroom on an idle pool.

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 + resident

If neither is available, land the mechanism, leave the default at the historical 20%, and document UNSLOTH_ROCM_MEM_FRACTION as the supported way to loosen it.

P2 - Do not log "0.0 of 0.0 GiB allowed" when the device total is unknown
studio/backend/core/training/worker.py:3716

_total_bytes is 0 on exactly the path the total_bytes <= 0 branch at line 1588 exists for, and test_missing_total_falls_back_to_historical_cap pins it. On that path the guard's only diagnostic reads set_per_process_memory_fraction(0.8000) ... 0.0 of 0.0 GiB allowed, computed, which tells a user with a working GPU that the guard capped them to nothing and that their card has no memory. That is the one line they will paste into an issue, from the one host where the props are already untrustworthy. Seven runs raised this.

Build the clause conditionally and pass it through a single %s:

_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
studio/backend/core/training/worker.py:3704

The source tag is honest now, but a set-and-rejected value still leaves no trace. UNSLOTH_ROCM_MEM_FRACTION=O.95 (letter-O typo), 85 (percent instead of a fraction), 1.5 or 0 all produce a line reading computed that never names the variable, so the user cannot tell "parsed and thrown away" from "I misspelled the variable name". This is the only escape hatch for a host the formula gets wrong, and whoever reaches for it is already fighting an OOM on hardware nobody reviewing this can reproduce. Never fatal is the right policy; never says anything is not. Six runs of 450fd82 raised this after the tag fix landed.

Keep it at the call site, since _rocm_memory_fraction parses the raw string again and a warning inside _parse_mem_fraction_env would fire twice per worker start:

_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 TestParseMemFractionEnv docstring: the computed fraction has to be identical to the unset case, the log does not.

P2 - Name UNSLOTH_ROCM_MEM_FRACTION in the log on the computed path too
studio/backend/core/training/worker.py:3718

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 worker.py on GitHub, which is what they had to do the first time. There is no docs or README change in the diff. The guard already teaches the user how to raise a limit fifteen lines below in the Variable Graphics Memory hint, so the precedent is right there.

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
studio/backend/tests/test_rocm_oom_guard.py:251

Converting test_unified_win32_uses_budget_exact_fraction and test_discrete_keeps_090 from source pins to direct calls is the right move for the policy, but those pins were the only coverage of the call site, and the guard runs behind _hw.IS_ROCM on hardware no CI machine has. Nothing now fails if section 1g stops calling _rocm_memory_fraction, swaps _props.total_memory for mem_get_info(0)[1], reorders the positional args, or reverts the tag to if _env_raw, which is the exact line this PR's review thread spent 26 passes on. _WORKER_PY is still in the file for test_win32_unified_logs_vgm_hint, so the idiom is one line away. Five runs raised this.

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 source

P3 - Assert the 0.80 floor exactly instead of pytest.approx
studio/backend/tests/test_rocm_oom_guard.py:276

The comment above the assertion says the cap is "bit-identical to the pre-#7878 flat 0.80", and the arithmetic in _rocm_memory_fraction is deliberately solved in fraction space so that 1.0 - 0.20 stays exact. But pytest.approx(0.80) has a default relative tolerance of 1e-6 and passes happily on 0.7999999999999999, which is precisely the value the production comment at line 1593 exists to prevent. The one regression the design decision guards against is the one thing the test cannot catch. Same at the two zero-total assertions around line 297.

assert _rocm_memory_fraction(pool_gib * GIB, True, "linux") == 0.80

P3 - Prefix the new ROCm constants with their domain
studio/backend/core/training/worker.py:1540

_UNIFIED_OS_RESERVE_BYTES, _UNIFIED_MAX_RESERVE_FRACTION, _DISCRETE_MEM_FRACTION, _MEM_FRACTION_ENV and _parse_mem_fraction_env are ROCm-only but sit at module scope in a file that also carries CUDA, XPU and MLX paths. Every other domain-scoped name here states its domain (_TILELANG_SKIP_ENV, _TVM_FFI_BROKEN_VERSIONS, _MAMBA_SSM_PACKAGE_VERSION), and the functions immediately above and below this block are _rocm_classify_unified_memory and _rocm_memory_fraction. A bare _DISCRETE_MEM_FRACTION = 0.90 is exactly what the next person adding a CUDA memory guard will reach for and reuse.

_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:

test_rocm_oom_guard.py imports _UNIFIED_OS_RESERVE_BYTES and _parse_mem_fraction_env, so update both there too.

P3 - Say what the zero-total branch guards, not which wheel you think causes it
studio/backend/core/training/worker.py:1588

# No usable total (some AMD SDK wheels), echoed by the test's # Some AMD SDK wheels report no total, asserts a packaging fact about total_memory that no linked report backs up. The file's other AMD-wheel notes are about different attributes: torch.version.hip and the gcnArchName family. What the branch actually guards is one screen away and needs no hardware knowledge: the call site writes int(getattr(_props, "total_memory", 0) or 0), so a missing or None total arrives here as 0.

    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_FRACTION

P3 - Cut the stale classifier recap from the section 1g header
studio/backend/core/training/worker.py:3678

The header still says the cap applies to Unified-memory APUs (gfx1150/1151/1152) and that the code classifies via gcnArchName, else device-name markers. Neither matches _rocm_classify_unified_memory, which checks props.is_integrated first and deliberately covers APUs outside the hardcoded set (its own docstring names gfx1103 Phoenix). Line 3685 already points the reader at that function's docstring, so this is a second copy of a contract that lives elsewhere and has drifted from it. A reader working out which devices this PR changes will draw the wrong boundary. The head commit was a comment-only pass but, per the author's note, it targeted the reserve-constant block, not this one.

    # ── 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
studio/backend/tests/test_rocm_oom_guard.py:4

The module docstring says Unit tests for _rocm_classify_unified_memory (ROCm OOM-guard classifier) and describes only the three classification paths. The file now also covers _rocm_memory_fraction and _parse_mem_fraction_env: the reserve crossover, the discrete cap, the Windows budget-exact case and the env override. Two runs of d2b6266 raised this and no later run confirms it was updated, so I am leaving it open; close it if the head commit's comment pass already caught it.

"""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.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Nine of the twelve are fixed in 81b114eb; three I'm leaving, with reasons below.

P2 - clamp at 0.90. Correct, and it's the one that mattered. 1 - min(0.20, 16 GiB / total) crosses 0.90 at exactly 160 GiB and reaches 0.9375 at 256 GiB, so a large unified pool outranked a discrete card and the "never reaches the 0.90 measured as starving" claim was simply false above the boundary. Worse, test_never_reaches_the_090 parametrised (96, 128, 156), and 156 GiB is the last size that passes. The test was fitted to the boundary rather than expressing the invariant.

Now min(1.0 - reserve_fraction, _DISCRETE_MEM_FRACTION), with the test extended to [96, 128, 156, 160, 161, 256, 1024] and asserting <= 0.90. Verified load-bearing: removing the clamp fails 13 tests.

P2 - denominator. Taken. The guard now sizes against mem_get_info(0)[1] with props.total_memory as the fallback. I could not reproduce a divergence between the two, but the only GPU available here is a discrete RX 9060 XT, where they agree by construction and the finding does not apply. The argument stands on its own: a percentage is indifferent to the denominator, an absolute 16 GiB is not, and this block already treats mem_get_info's total as a distinct number in the Windows hint below.

P2 - 0.0 of 0.0 GiB allowed. Fixed. I had judged this cosmetic; the framing that it is the line a user pastes into an issue, from the one host whose props are already suspect, is better than my reasoning. Now prints device total unreported by this wheel.

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: computed; override with UNSLOTH_ROCM_MEM_FRACTION.

P2 - source pin on section 1g. Fair, and self-inflicted: I removed those pins in this PR when converting them to direct calls. Added test_guard_delegates_to_the_fraction_helper, pinning the three things this thread actually turned on: the helper call, mem_get_info as the size source, and the tag keyed off the parsed override.

P3 - exact instead of approx. Correct. approx(0.80) accepts 0.7999999999999999, which is the precise value the fraction-space arithmetic exists to prevent. Now == _HISTORICAL_CAP, same at the zero-total assertions.

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 is_integrated first.

Not doing

P2 - 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 - _ROCM_ prefix on the constants. Reasonable, and the file does use domain prefixes elsewhere. Declining for now: it renames five module-level names plus the test imports for no behaviour change, in a diff that has already been through several review rounds. Worth doing when something else touches this block.

P3 - test module docstring. Already fixed in b139c34, before this pass.

Head is 81b114eb, test_rocm_oom_guard.py at 101 passed.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Correcting my previous comment: I took the denominator finding and I should not have.

Codex flagged the change on 81b114eb, and it's right. c10's CUDACachingAllocator::setMemoryFraction caps at:

allowed_memory_maximum = static_cast<size_t>(std::round(
    fraction * static_cast<double>(device_prop.totalGlobalMem)));

device_prop is filled once from cudaGetDeviceProperties, and props.total_memory is exactly that totalGlobalMem. So the guard was already dividing by the number the allocator multiplies by, and switching to mem_get_info would have introduced the failure the finding described rather than preventing it: on a host where mem_get_info reports a runtime budget rather than the physical pool, the withheld headroom becomes budget * 16 GiB / totalGlobalMem, not 16 GiB.

Reverted in b8bb9d0f. The docstring line I'd been asked to delete unless I could point at the allocator source now carries that citation, so it's checkable instead of asserted, and the section 1g source pin asserts props.total_memory again.

Everything else from 81b114eb stands: the 0.90 clamp, exact assertions on the historical cap, the warning when UNSLOTH_ROCM_MEM_FRACTION is set but rejected, naming the variable on the computed path, and the "device total unreported by this wheel" log path.

Head is b8bb9d0f, test_rocm_oom_guard.py at 101 passed.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: b8bb9d0fe4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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 hogeheer499-commits left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Thank you for taking the time to run this on real hardware, and for reporting it this carefully. Listing sysfs, props and mem_get_info side by side with the kernel cmdline and BIOS UMA is what makes it actionable instead of just a number, and it caught something I could not have found from here. Genuinely appreciated.

Your reading is right and the behaviour is intended. The crossover is 16 GiB / 0.20 = 80 GiB of props.total_memory; at 62.47 GiB the 20% arm wins and the cap stays at exactly 0.80, bit-identical to pre-PR. That validates the classifier and the floor, and as you say it is not evidence the reserve hands memory back.

On the 62.47 GiB itself: that is half your 124.92 GiB of RAM. amdgpu.gttsize=131072 set the sysfs GTT to 128 GiB, but that parameter is deprecated in favour of TTM's page limit, which is still at its RAM/2 default, and that lower number is what reaches totalGlobalMem. It also explains the free > total oddity you flagged: free is read from real system memory, total from the TTM-limited pool. If you ever want the full pool, ttm.pages_limit=31457280 gives ~120 GiB, confirmed via dmesg | grep amdgpu.

The mem_get_info numbers are the most useful part of the report. free 120.00 GiB against total 62.47 GiB is incoherent, and that is exactly what I briefly divided by in 81b114e before reverting in b8bb9d0. I reverted on a reading of c10's setMemoryFraction, which caps at fraction * device_prop.totalGlobalMem. Your box is the first evidence that the alternative is not just wrong in principle but incoherent on a shipping wheel.

Agreed on the docs point. I will retitle the table column from "pool" to props.total_memory and note that it varies with TTM limits, BIOS UMA and wheel version, so a 128 GB machine does not automatically land at 0.875.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

@danielhanchen if you can test this, one thing to check first: torch.cuda.get_device_properties(0).total_memory. The new reserve only engages above 80 GiB, so if it reports below that the changed path never runs and the result is indistinguishable from main. That is what happened on the gfx1151 report above, which came back at 62.47 GiB on a 128 GB box.

If it is at half your RAM, that is the TTM page limit default rather than the GPU: ttm.pages_limit=31457280 gets you ~120 GiB, verify with dmesg | grep amdgpu.

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.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

staged latest ci:

LeoBorcherding#13

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: b8bb9d0fe4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed 4832659 to this branch: one docstring correction and one new log line, no policy change. The fraction table is untouched.

What I checked

I could not run ROCm here, so I pulled section 1g out of worker.py by AST and executed the real source text against synthetic props, platforms and torch semantics, once from origin/main and once from this branch, then compared them. 13,260 cases over the product of [Linux, WSL, Windows, macOS] x [NVIDIA, AMD discrete, AMD unified APU across all three classifier paths, Intel, CPU-only] x 42 pool sizes x 27 env values x both allocator denominators, plus broken-wheel cases (no total_memory, zero, negative, mem_get_info raising, no psutil, get_device_properties raising). Ran on 3.10, 3.11, 3.12 and 3.13 in separate uv venvs.

Invariants asserted on every case: the guard never raises, the fraction is always a float in (0.0, 1.0], the effective ceiling never shrinks against main, a unified host never outranks a discrete card, the log's from UNSLOTH_ROCM_MEM_FRACTION tag appears only when the override was applied, the N of M GiB allowed clause matches what was set, and behaviour is bit-identical to main outside the intended window.

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 mem_get_info, tighten to 25%, return an int, apply the unified reserve on win32, suppress the rejection warning). It caught 9 of 9.

On real hardware the fraction contract holds: on a B200 with torch 2.9.1, every fraction this policy can emit (0.8, 0.8333, 0.8658, 0.875, 0.9, 1.0) is accepted, and bracketing the ceiling puts it exactly at fraction * total (cap 0.875 of 178.35 GiB allocates 147.1 GiB and OOMs at 165.0 GiB), raising OutOfMemoryError rather than hanging. Backend CI in a clean venv: 18,851 passed, 113 skipped, 0 failed. test_rocm_oom_guard.py is at 102.

The one thing that was wrong

The docstring said props.total_memory is "the same number torch multiplies the fraction against", citing CUDACachingAllocator::setMemoryFraction. That is true from torch 2.10 on. Through 2.9 the allocator reads its total from cudaMemGetInfo:

branch denominator
v2.9.1, release/2.9, 2.8, 2.7, 2.6 cudaMemGetInfo(&free, &total) then fraction * total
release/2.10, release/2.11, main 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 are on the older denominator today. Your revert in b8bb9d0f was still the right call, since that is where torch has settled and mem_get_info's total is a runtime budget rather than the pool on some hosts. The claim just needed the version bound, which is what I changed it to.

Why the new log line

Where the two totals disagree the absolute reserve is scaled by their ratio, and nothing reported it:

case props driver cap reserve at 2.10+ reserve through 2.9
totals agree 128 GiB 128 GiB 0.8750 16.0 GiB 16.0 GiB
driver inflated 128 GiB 220 GiB 0.8750 16.0 GiB -64.5 GiB
driver deflated 128 GiB 48 GiB 0.8750 16.0 GiB 86.0 GiB

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 mem_get_info returning free 120.00 GiB against total 62.47 GiB. Main has the same exposure, since an inflated total defeats a percentage just as well, so this is a diagnostic rather than a fix.

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 mem_get_info failure falls back to silence, and it sits inside the existing try/except. Verified it fires on exactly the intended cases and stays quiet on the other nine I tried, including below the crossover and with an override set.

Not changed

The 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, props.total_memory can exceed physical RAM, and neither the old 0.80 nor the new cap protects anything there. The props.total_memory column rename you already planned covers most of it.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 9, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 9, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 9, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 9, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 9, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Aug 9, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 7fb3b4b69d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 4d2bd707f0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@danielhanchen
danielhanchen merged commit 7aa0217 into unslothai:main Aug 9, 2026
36 of 41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Unsloth Studio unable to access sufficient memory on Strix Halo- hard coded to 80%

3 participants