Skip to content

Size memory budgets correctly on unified-memory NVIDIA parts - #10283

Closed
danielhanchen wants to merge 12 commits into
mainfrom
uma-memory-budgets
Closed

danielhanchen wants to merge 12 commits into
mainfrom
uma-memory-budgets

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

What this is

On a unified-memory NVIDIA part, every VRAM figure we read is wrong as a budget, and the two sources are wrong in opposite directions. This fixes both. It is independent of the Windows-on-ARM installer work and applies on Linux and inside WSL as well as on Windows.

The problem

Measured on an RTX Spark N1X (GB10 class), which reaches this code the same way on Windows and inside WSL:

Reading Says Truth Effect
nvidia-smi, which drives llama.cpp context fitting 8128 MiB total, 7929 free 46477 MiB pool 5.7x under report, shrinks or refuses loads the machine runs comfortably
CUDA driver / torch, which drives the UI, the merge budget, slot fitting 46297 MiB free host had 39 GiB spare, 5 GiB with a container resident over-commits, a load sized to it pushes the host into swap

Neither is a driver defect. nvidia-smi reports the carve-out it is meant to report and CUDA reports a pool it really can address. They are wrong only as budgets, because on these parts the pool is system RAM and the host is spending it too. The usable figure is min(pool, available RAM) less a host reserve.

The under report is not theoretical. Studio believed 7.7 GB was available on a machine that had just served a 17.5 GiB model with the GPU at 95 percent utilization.

Inside WSL the over report is worse: the driver offers a 45.39 GiB pool to a VM that has 29.31 GiB in total.

Approach

We already do exactly the right thing for AMD APUs: classify the part, cap against available system RAM, hold back the iGPU host reserve, and report total as 0 so the fit uses the free-fraction form rather than treating a shared pool as a card's capacity. All of that was reachable only from the ROCm branch, and NVIDIA unified parts hit the nvidia-smi branch first, so none of it applied.

Classification asks the CUDA driver directly through ctypes: cuInit, cuDeviceGetAttribute with CU_DEVICE_ATTRIBUTE_INTEGRATED, and cuDeviceTotalMem for the pool size. Milliseconds, and it works on Windows (nvcuda.dll) and Linux (libcuda.so.1), including in WSL.

Deliberately not torch. torch.cuda.get_device_properties initialises CUDA and holds a primary context for the life of the process, and on a unified-memory part that context is system RAM the model then cannot have. The driver answers both questions without creating one. nvidia-smi --query-gpu=addressing_mode would have been the obvious route but is Linux only and returns [N/A] on Windows.

Changes

  • _get_gpu_memory substitutes the real pool for nvidia-smi's carve-out on integrated devices, caps it against available RAM, keeps the existing host reserve and reports it as a shared pool. Measured on this machine: [(0, 7929, 8128)] becomes [(0, 41227, 0)], a fitting budget of 39990 MiB instead of about 7500.
  • trusted_mem_get_info, already the one place a Windows ROCm over report is capped, now caps a unified part's free against what the host can spare. total is left alone, since the pool really is that big and callers reasoning about capacity rather than this moment's headroom want it.
  • The LoRA merge in save.py budgeted at total_memory * maximum_memory_usage while a second budget over the same bytes was computed from psutil for the RAM path. Two budgets over one pool. It now caps against available RAM on unified parts, reusing the existing is_integrated_unified_memory_gpu so the package keeps one definition of what these parts are.

Safety

Every correction applies only where the driver positively classifies a device as integrated. No driver, an error, ROCm (which has its own APU classifier and keeps it), or a discrete card all decline, and the reading is passed through untouched. That is what most of the 14 new tests in tests/studio/test_cuda_unified_memory_budget.py check, including a mixed host where only the integrated device is rewritten and a visibility mask where physical ids must be translated to driver ordinals before asking about a device.

The effect is visible in both directions on the same machine: with a WSL container holding 27.9 GB, Studio now reports 4.65 GB free instead of 45.21 GB, which is what the OS could actually give.

Verification

New tests pass, and no regressions across tests/studio/install, the hardware and dispatch suites, and tests/studio/load_freeze: the failure set is identical to the pre-change baseline measured in the same venv, with nothing new and nothing masked.

One test-hygiene note for whoever touches these suites next. Several studio tests leave CUDA_VISIBLE_DEVICES="" in the environment and pop utils.hardware.hardware from sys.modules, so a GPU-probe test needs to clear the visibility variables and resolve that module per test, or it fails for reasons unrelated to what it is testing. The new file does both.

Left alone on purpose

The training banner still prints Max memory = 45.39 GB. That figure is capacity rather than headroom, and 45.39 GB genuinely is what CUDA can address, so changing it would make the banner disagree with both nvidia-smi and the pool size for no gain. Everything that decides something now caps against real host availability.

Screenshots: the discrete path is untouched

Settings > System is where these numbers reach a user. Both halves below are that panel, from two separate installs built from this PR's merge base (a6766d2c0) and from its head, driven by the same script.

Settings > System, merge base against head, on a discrete NVIDIA B200

This is a PARITY pair, and identical halves are the claim rather than the failure. Everything here is gated on the driver's integrated flag, so on a discrete card the change must be a no-op, and the GPU row holds exactly still: NVIDIA B200, GPU 0, CUDA, 42% VRAM, 74.5 GiB used | 104.5 GiB free | 179.1 GiB total on both sides, with the VRAM tile reading 74.5 GiB / 179.1 GiB on both. Read from the same servers that were photographed, /api/system returns one device with vram_total_gb 179.06 on both sides.

Two things do differ, and neither is the PR: the Live monitor's CPU percentage and the RAM free figure are sampled at the instant of each shot (1683.4 GiB against 1682.3 GiB on a box with other tenants). They are recorded separately from the comparison for that reason.

What this pair does NOT show is the positive effect on a GB10 / N1X, because this host has no integrated NVIDIA part. Stubbing the driver probe to fake one would have produced a screenshot of the stub rather than of this change, so that evidence still rests on @dyuan311's DGX Spark measurements.

On a unified-memory GPU the two obvious sources of a VRAM figure disagree, and
both are wrong as a budget, in opposite directions. Measured on an RTX Spark
N1X, which reaches this code the same way on Windows and inside WSL:

* nvidia-smi reports a carve-out of 8128 MiB total, 7929 free. That drives
  llama.cpp context fitting, so we size context and offload against 7.7 GiB on a
  machine that serves a 17.5 GiB model with the GPU at 95 percent. A 5.7x under
  report, which shrinks or refuses loads that run comfortably.
* the CUDA driver reports the whole pool, 46477 MiB, and calls almost all of it
  free. That drives the UI, the merge budget and slot fitting. It is more than
  the host can spare (39 GiB available, and 5 GiB with a container resident), so
  a load sized to it pushes the host into swap. Inside WSL it is worse: the
  driver offers a 45.39 GiB pool to a VM that has 29.31 GiB in total.

Neither is a driver defect. nvidia-smi reports the carve-out it is meant to and
CUDA reports a pool it really can address. They are wrong only as budgets,
because the pool is system RAM and the host is spending it too, so the usable
figure is min(pool, available RAM) less a host reserve.

We already do exactly this for AMD APUs: classify the part, cap against
available system RAM, hold back the iGPU host reserve, and report total as 0 so
the fit uses the free-fraction form rather than treating a shared pool as a
card's capacity. All of it was reachable only from the ROCm branch, and NVIDIA
unified parts hit the nvidia-smi branch first.

Classification asks the CUDA driver directly through ctypes
(CU_DEVICE_ATTRIBUTE_INTEGRATED, plus cuDeviceTotalMem for the pool size), which
takes milliseconds and works on Windows and Linux. Deliberately not torch:
get_device_properties initialises CUDA and holds a primary context for the life
of the process, and on a unified part that context is system RAM the model then
cannot have.

Corrections apply only where the driver positively classifies a device as
integrated. No driver, an error, ROCm, or a discrete card all decline and the
reading is passed through untouched, which is what most of the new tests check.

* _get_gpu_memory substitutes the real pool for nvidia-smi's carve-out on
  integrated devices, caps it against available RAM, keeps the existing host
  reserve and reports it as a shared pool. Measured: [(0, 7929, 8128)] becomes
  [(0, 41227, 0)], a fitting budget of 39990 MiB instead of about 7500.
* trusted_mem_get_info, already the one place a Windows ROCm over-report is
  capped, now caps a unified part's free against what the host can spare. Total
  is left alone, since the pool really is that big and callers reasoning about
  capacity rather than this moment's headroom want it.
* the LoRA merge in save.py budgeted at total_memory * maximum_memory_usage
  while a second budget over the same bytes was computed from psutil for the RAM
  path. Two budgets over one pool. It now caps against available RAM on unified
  parts, reusing is_integrated_unified_memory_gpu so the package keeps one
  definition of what these parts are.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-14T09:31:59.519342Z 0b91fec Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 3 commits September 4, 2026 04:07
…bus id

Review turned up one blocker in the first commit, plus two correctness holes. All
three are in code this PR adds.

The blocker: cuInit poisoned fork for every NVIDIA host, not just unified ones.
_get_gpu_memory's nvidia-smi branch exists so the backend can read VRAM WITHOUT
touching the driver, and the classifier called cuInit right there, before it knew
whether the device was even integrated. A process that has initialised the CUDA
driver cannot usefully fork: the child's own cuInit returns
CUDA_ERROR_NOT_INITIALIZED, which torch surfaces as cuda.is_available() == False.
Studio's backend is long lived and spawns workers, so this reached every discrete
NVIDIA host on Linux. Measured on a GB10 laptop with a three-leg experiment: with no
probe the forked child computed on the GPU; with the in-process probe it could not
see the GPU at all; with the probe moved to a child process it computes again. The
same trap is on record in vllm-project/vllm#32611 (pynvml initialising the driver
before a fork) and in numba's explicit "CUDA initialized before forking" error.

So the probe now runs in a short lived child: one spawn enumerates every device,
the result is cached for the process, and the hosting process never loads the driver
at all. A test asserts this against the AST rather than the text, so the driver
entry points may appear only inside the string the child runs.

Devices are matched to the driver's view of them by PCI bus id. Index and driver
ordinal agree only by luck once a host has more than one card: nvidia-smi enumerates
by bus id, while CUDA's default CUDA_DEVICE_ORDER is FASTEST_FIRST. Ordinal
translation stays as the fallback where no bus id is available, and a bus id the
driver did not report is passed through rather than guessed at.

The two sources also spell a bus id differently -- for one device nvidia-smi prints
0000000F:01:00.0 and the driver prints 000f:01:00.0 -- so both sides go through one
canonicaliser. Found by watching the correction stop firing on the machine it was
written for after the bus-id match went in.

IS_ROCM is re-read on every lookup rather than only inside the cache. Hardware
detection clears that flag and sets it again a few lines later, and a probe landing
in that window on a ROCm host that also has an NVIDIA driver loadable would have
cached an answer from the wrong vendor for the rest of the process.

Verified: 22 tests here, and a simulated matrix of [Windows, Linux, WSL, macOS] x
[discrete NVIDIA, unified NVIDIA, AMD ROCm, Intel XPU, CPU only, unreadable driver]
confirms that only a positively classified unified part sees any change, in both the
llama.cpp probe and trusted_mem_get_info, with XPU reaching neither.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed a follow-up commit. The review found a blocker in the first commit that reached well beyond the hardware this PR is about, so recording it here rather than leaving it in a commit message.

The blocker: cuInit poisoned fork, on every NVIDIA host

_get_gpu_memory's nvidia-smi branch exists precisely so the backend can read VRAM without touching the driver. The classifier called cuInit right there, before it knew whether the device was integrated at all, so it ran on discrete cards too.

A process that has initialised the CUDA driver cannot usefully fork: the child's own cuInit returns CUDA_ERROR_NOT_INITIALIZED, which torch surfaces as cuda.is_available() == False. Studio's backend is long lived and spawns workers, so on Linux this reached every discrete NVIDIA host.

Measured on the GB10 laptop, three legs, same script:

parent does forked child
nothing (control) OK, computed on the GPU
the in-process probe FAILED, cuda.is_available() is False
the probe as it now ships OK, computed on the GPU

The same trap is on record in vllm-project/vllm#32611, where pynvml initialised the driver before a fork, and numba raises an explicit CUDA initialized before forking for it.

The probe now runs in a short-lived child: one spawn enumerates every device, the answer is cached for the process, and the hosting process never loads the driver. A test asserts this on the AST, not the text, so the driver entry points may appear only inside the string the child runs. Editing the comments cannot break it, and moving a call back into the process fails it.

Devices are matched by PCI bus id now

Index and driver ordinal agree only by luck once a host has more than one card: nvidia-smi enumerates by bus id, while CUDA's default CUDA_DEVICE_ORDER is FASTEST_FIRST. Ordinal translation stays as the fallback where no bus id is available, and a bus id the driver did not report is passed through rather than guessed at.

That change immediately broke the correction on the machine it was written for, which is how the next bug surfaced: the two sources spell a bus id differently. For one device nvidia-smi prints 0000000F:01:00.0 and the driver prints 000f:01:00.0. Both sides now go through one canonicaliser, and a test pins that exact pair.

ROCm re-check

IS_ROCM is re-read on every lookup rather than only inside the cache. Hardware detection clears that flag and sets it again a few lines later, and a probe landing in that window on a ROCm host that also has an NVIDIA driver loadable would have cached an answer from the wrong vendor for the rest of the process.

What was checked and found clean

A simulated matrix of [Windows, Linux, WSL, macOS] x [discrete NVIDIA, unified NVIDIA, AMD ROCm, Intel XPU, CPU only, unreadable driver] confirms only a positively classified unified part sees any change, in both the llama.cpp probe and trusted_mem_get_info:

  • Intel XPU passes module=torch.xpu and fails the mod is torch.cuda identity check, so it never enters the new block.
  • AMD ROCm, Linux and Windows, reaches torch.cuda but is excluded by IS_ROCM, and the pre-existing Windows ROCm cap receives byte-identical input.
  • Apple MLX / MPS and CPU-only hosts cannot reach any new path: each is gated behind a successful mem_get_info, an nvidia-smi returncode of 0, or dev.type == "cuda". Even if reached, no libcuda or nvcuda is loadable and the probe declines.
  • Discrete NVIDIA now gets the same numbers it always did, and no longer pays a driver init.
  • unsloth/save.py cannot raise: psutil is module-scope and a hard dependency, and the classifier is wrapped. Discrete budgets are bit-identical.

One deliberate blast-radius note

Jetson and Orin also report CU_DEVICE_ATTRIBUTE_INTEGRATED == 1, so their budgets change too. That is the correct answer for them for the same reason it is correct here, their memory really is the host's, but it is a behaviour change on existing installs and should be a conscious call rather than a surprise.

Worth flagging separately: UNSLOTH_FORCE_UMA=1 is documented in _uma_safetensors.py as a test override, and with this change it also moves the real merge budget on a discrete host. Left as is, since that is arguably what an override is for, but happy to narrow it to the loader if you would rather it stayed test-only.

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed9618819b

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

@staticmethod
def _apply_cuda_unified_memory_correction(
gpus: list[tuple[int, int, int]],
bus_ids: dict[int, str] | None = None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use a Python 3.9-compatible union annotation

The project declares support for Python 3.9 in pyproject.toml, but this module does not enable postponed annotation evaluation. On Python 3.9, evaluating dict[int, str] | None while defining the class raises TypeError, so importing the llama.cpp backend fails before Studio can start. Use Optional[dict[int, str]], quote the annotation, or enable from __future__ import annotations.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not reproducible at the reviewed commit. The annotation there is already Optional[dict[int, str]]; there is no PEP 604 union anywhere in the file, so Python 3.9 is unaffected. from __future__ import annotations would also defer it even if there were.

The python floor gate is a ratchet: 36 studio files evaluating a PEP 604 union on
the declared floor, up from 35, and llama_cpp.py was the new one. The annotation
this PR added, dict[int, str] | None, is evaluated at def time and needs 3.10.

The gate's own advice is to add `from __future__ import annotations`, but that
changes annotation semantics for a nine thousand line module whose runtime
introspection is not in scope for this PR. Optional[dict[int, str]] is exact on
the floor, is what the rest of the file already uses, and leaves the ratchet at
35 rather than carving out an exemption.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The out-of-process integrated-memory probe passed text = True with no encoding, so
its stdout was decoded with locale.getencoding(): the ANSI codepage on Windows and
ASCII under a C locale, which containers and CI runners routinely have. Every
other subprocess probe in this file already names utf-8 and replaces on error,
and test_text_io_names_its_encoding holds the file to it. Same idiom here.

The probe prints only integers and a PCI bus id, so nothing non-ASCII is expected;
naming the encoding is about not depending on the host's locale at all.
test_python_children_are_told_to_emit_utf8 holds every sys.executable spawn to
setting the child's own stdio encoding, and the integrated-memory probe only set
the parent's decode side. On a Windows host the child would print in the ANSI
codepage and the parent would decode it as utf-8.

The child runs under -I, which implies -E and ignores every PYTHON* variable, so
PYTHONIOENCODING alone would not reach it. Verified on this box: under a C locale
with PYTHONIOENCODING=latin-1, `-I` reports cp1252 and `-X utf8 -I` reports
utf-8. The child gets -X utf8, and its env goes through utf8_child_env() like
every other spawn in the backend, which is what the guard keys on.

The probe prints integers and a PCI bus id, so nothing non-ASCII is expected;
this is about not depending on the host's locale at all.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Three follow-up commits since the review comment above, all from the CI matrix, none changing behaviour on a discrete card:

  • 34c59d7: dict[int, str] | None is a PEP 604 union evaluated at def time and needs 3.10; the python floor gate is a ratchet at 35 studio files and this made 36. Spelled Optional[dict[int, str]], which is what the rest of the file already uses, rather than adding a file-wide from __future__ import annotations to a nine thousand line module.
  • 6bb9b50: the probe's subprocess.run passed text = True with no encoding, so its stdout was decoded with locale.getencoding(), the ANSI codepage on Windows. Every other probe in the file names utf-8 and replaces on error; same idiom here.
  • f6eccf0: the child is now told to emit utf-8 as well as being decoded as it. The child runs under -I, which implies -E and ignores PYTHONIOENCODING; measured on this box under a C locale, -I reports cp1252 and -X utf8 -I reports utf-8. So the child gets -X utf8, and its env goes through utf8_child_env() like every other spawn in the backend.

Core's unsloth_zoo @ main step failed once in between on zoo's own drift: zoo 08f7e15 changed the getsource guard, this ran against it, and zoo 4a1f75d fixed the test three hours later. Nothing in this PR.

All 21 workflows green at f6eccf0.

@danielhanchen

Copy link
Copy Markdown
Member Author

Tried this on a DGX Spark (GB10, sm_121a, aarch64, CUDA 13) and I do not think it corrects this machine, which seems worth flagging given what the PR is named for.

nvidia-smi --query-gpu=memory.free,memory.total,memory.used returns this here, on both of the two machines I have:

memory.free [MiB], memory.total [MiB], memory.used [MiB]
[N/A], [N/A], [N/A]

Per-process residency still works fine (--query-compute-apps=used_memory returns real values), so this is specifically the per-GPU memory queries.

_apply_cuda_unified_memory_correction runs over rows nvidia-smi returned. Here there are no rows: the parse drops them on int("[N/A]") and the code falls through to the torch fallback, so the correction is unreachable and total stays at the full 121.69 GiB pool rather than the shared-pool signal this PR argues for. The machine does get partial coverage from the other change in this branch, where trusted_mem_get_info caps free against host RAM, but that path deliberately leaves total alone.

I think the underlying issue is that the PR was measured on an N1X, where nvidia-smi returned a parseable 8128 / 7929 MiB. A GB10 is not an under-reporting part, it is a non-reporting one, and those need different handling: one wants a value corrected, the other wants a missing value synthesised. If it would help I can run any probe you want on this hardware and post the output.

One other thing I noticed while reading this next to #9872. The two branches detect the same predicate two different ways: #9872 and current main use torch props.is_integrated in-process, while this PR uses a ctypes cuInit probe in a short-lived child and argues in its own comments that the in-process torch route is unsafe, because a primary context costs system RAM on a unified part and cuInit before a fork breaks workers. Both cannot be right, and on this box it is not academic: since nvidia-smi returns nothing, the torch fallback is the only route to any GPU reading, so the backend already takes a primary CUDA context out of the same 121.69 GiB on every load. Worth settling on one definition, especially since this branch adds a fourth implementation beside _uma_safetensors and _integrated_cuda_gpu_ids.

This branch was cut before #10705 merged, so it no longer applies. Three
conflicts, one of which is a trap.

`_get_gpu_memory`'s nvidia-smi arm conflicts because main added
`_GPU_IDS_ARE_PCI_INDICES = True` exactly where this branch added its call to
`_apply_cuda_unified_memory_correction`. Both sides are load-bearing and both
naive resolutions are silently wrong:

  keep main's   -> the correction never runs, so this entire branch does nothing
  keep ours     -> the flag is never set, and callers that feed these ids back as
                   CUDA_VISIBLE_DEVICES read PCI indices as torch ordinals

Resolved by doing both. The correction rewrites the numbers and never the ids,
so the flag stays true through it.

The "keep both sides" resolution is the dangerous one, because it produces

    LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = True
    return gpus
    return LlamaCppBackend._apply_cuda_unified_memory_correction(...)

which parses, imports, and passes every test that does not load a Spark. I did
that on a trial merge and the whole branch went quiet. Two tests now pin it: one
asserts the returned numbers are the corrected ones rather than nvidia-smi's
carve-out, the other asserts the flag is still set. The first fails against that
exact resolution.

The remaining two conflicts are mechanical: main reflowed the
`trusted_mem_get_info` docstring (taking main's), and two unrelated new methods
landed at the same point in llama_cpp.py (keeping both).
@danielhanchen

Copy link
Copy Markdown
Member Author

Merged main in, so this applies again. It was cut before #10705 landed and had gone stale.

Three conflicts. Two are mechanical: main reflowed the trusted_mem_get_info docstring, and two unrelated new methods arrived at the same point in llama_cpp.py. The third is a trap worth describing, because every obvious resolution is wrong in a way that does not announce itself.

main added _GPU_IDS_ARE_PCI_INDICES = True at exactly the line this branch added its call to _apply_cuda_unified_memory_correction:

<<<<<<< HEAD
                    return LlamaCppBackend._apply_cuda_unified_memory_correction(
                        gpus, bus_ids = bus_ids
                    )
=======
                    LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = True
                    return gpus
>>>>>>> origin/main
  • Keep main's side and the correction never runs, so this entire branch does nothing.
  • Keep this branch's side and the flag is never set, so callers that feed these ids back as CUDA_VISIBLE_DEVICES read PCI indices as torch ordinals.
  • Keep BOTH sides, which is the natural thing to do with two additions, and you get return gpus followed by an unreachable return ...correction(...). It parses, it imports, and it passes every test that does not load a Spark.

I hit the third one on a trial merge and did not notice until a scenario matrix showed all six of this branch's cases silently reverting to main. Resolved by doing both: the correction rewrites the numbers and never the ids, so the flag stays true through it.

Two tests now pin it. test_the_probe_actually_calls_the_correction asserts the caller receives the corrected numbers rather than nvidia-smi's carve-out, and fails against that exact bad resolution (verified by injecting it). test_the_probe_still_reports_pci_index_ids covers the other half.

How it was checked

A scenario matrix over 58 host shapes, [Linux, Windows, WSL, macOS] x [NVIDIA, AMD, CPU] plus mixed, MIG, vGPU, container, mask and old-torch cases, against main, this branch, #10704, and both merged. The ctypes probe is faked at the subprocess boundary it actually uses, not through torch, so the child-process design is exercised rather than bypassed.

  • 39 of 58 identical everywhere; discrete NVIDIA, AMD, CPU-only and every mask form are untouched.
  • This branch accounts for 6 of the moves, all on hosts where nvidia-smi answers: the carve-out case goes 7929 / 8128 to 37976 / 0, and the over-report case correctly clamps to what the host can spare.
  • Composition with Studio: do not lose a DGX Spark's memory pool to the page cache when fitting context #10704 is clean, 0 problems: the effect sets are disjoint, since the nvidia-smi arm returns before the torch arm.

Fail-safes I tried to break and could not: an nvidia-smi that rejects the new pci.bus_id field (falls through, host preserved), [N/A] bus ids (ordinal fallback), a driver reporting a zero pool (passed through), no libcuda at all, the domain-width and case mismatch between 0000000F:01:00.0 and 000f:01:00.0, and FASTEST_FIRST ordinal reordering on a mixed host.

CU_DEVICE_ATTRIBUTE_INTEGRATED = 18 checks out against NVIDIA's driver-API docs, and using the driver enum rather than the runtime one is right: the two number differently, and hardcoding 18 against cudaDeviceGetAttribute would misclassify.

Test scope, stated rather than implied

The box is shared and the OOM killer took the full backend suite four times, so there is no whole-suite comparison from here. What I ran, this branch against main, comparing by failing test id: 9 files covering _get_gpu_memory, trusted_mem_get_info, the APU and iGPU paths, diffusion memory, the arch gate and Windows detection. 590 passed on both sides, identical failing sets. The 3 failures are pre-existing in my venv (no python-multipart). Org CI is the authoritative run.

Separately

There are now three integrated-device detectors in the tree: _uma_safetensors.is_integrated_unified_memory_gpu, llama_cpp._integrated_cuda_gpu_ids and this branch's hardware.cuda_device_is_unified_memory, plus two host reserves and two available-RAM readers. They do not disagree today, and the matrix says so, but that is three places to keep true rather than one. Worth folding together once both this and #10704 are in.

pre-commit-ci Bot and others added 2 commits September 14, 2026 08:09
Six findings from the review round, all on hosts where a GPU's "VRAM" and the
host's RAM are the same bytes.

The planner credited an integrated NVIDIA pool twice. `_fit_derived_load_mode`
built its `shared` set from Vulkan ids plus the ROCm APUs only, so a GB10 class
part had its free figure and the host RAM that figure is carved from both
counted, and a model roughly twice the size of the machine read as a fit.
Integrated CUDA ids now join `shared` the same way, per device, so a discrete
card beside an integrated part keeps the pool it really has. `total` is left
alone: the pool is that big, and callers reasoning about capacity want it.

Classifying those devices no longer costs a CUDA context.
`_integrated_cuda_gpu_ids` answers from the out-of-process driver probe when it
is available, falling back to `get_device_properties` only when it is not.
Asking used to create a ~700 MiB primary context on every device, which on a
plain discrete host is pure loss for an answer that is always empty.

`_cuda_ordinal_for` read anything that names a device without an ordinal as
device 0, while `mem_get_info` resolves the same argument to the CURRENT device.
On a host whose current device is not 0 the unified-memory clamp was decided
from a different card than the one being measured, and video.py reaches here
that way. Resolved to `current_device()` now; an explicit index still wins.

`available_system_memory_bytes()` had no cgroup cap, unlike its llama.cpp twin.
psutil and /proc/meminfo both report the HOST, so in a container with a tighter
limit it handed back RAM the process may not charge. It now reuses the backend's
cgroup remainder rather than re-walking the tree, so the two cannot drift; an
unreadable cap leaves the host figure exactly as before.

The merge budget in save.py asked a process-wide question for a per-device
answer. `is_integrated_unified_memory_gpu()` is true only when EVERY visible
device is integrated, which is right for the loader patch but skipped the cap on
a mixed box, on exactly the device whose pool is host RAM. Added
`device_is_integrated_unified_memory(index)` and pointed the budget at it.

That budget also mixed units. It is an absolute ceiling, compared against
`memory_allocated(device) + W.nbytes`, but `virtual_memory().available` is the
headroom LEFT and already excludes everything resident, so the resident bytes
were charged twice: 8 GiB on the device with 10 GiB spare capped at ~9 GiB and
allowed ~1 GiB more before the whole merge fell to the slow disk path. The
arithmetic moved to `_unified_memory_vram_budget` and is anchored to what is
already allocated.

15 tests added, all 15 failing without this commit. The targeted backend sweep
(163 files, 7231 tests) reports an identical set of 45 pre-existing failures
before and after, none of them in this area.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
The previous commit folded integrated CUDA into the shared set inside
`_fit_derived_load_mode` only, which left the launch guard behind.
`_shared_gpu_ids` is still empty for every non-Vulkan launch, so
`_launch_host_shortfall_message` goes on subtracting a GB10's free figure as
VRAM and then charging the rest to available RAM: a 30 GiB model on a machine
with 20 GiB of pool read as 19 GiB of VRAM plus 20 GiB of RAM, the shortfall
came out negative, and the pageable-load safeguard never fired on a load that
the host cannot hold.

Marked at the source instead, so the fit predicate and the launch guard cannot
disagree about the same machine.

The id space is the reason this is recorded rather than recomputed. nvidia-smi
enumerates by bus id while CUDA's default order is FASTEST_FIRST, so the rows
the smi leg returns carry indices that `_integrated_cuda_gpu_ids` does not
speak. Re-deriving the classification at each consumer would name a different
card on any host where the two orders differ, which is the case this PR's bus-id
join exists for. `_apply_cuda_unified_memory_correction` already knows exactly
which rows it rewrote, so it records them, and `_unified_memory_gpu_ids` hands
back whichever set matches the leg that answered: the recorded smi ids, or the
physical ids of the torch fallback.

Reading `total <= 0` as the marker off Vulkan would have been simpler and wrong.
MIG, vGPU and the two-column probe all report no total without being unified
memory, and that would have dragged discrete cards into the shared pool.

6 tests added. 5 fail without this commit; the sixth drives the launch guard
against a real backend and passes at both states, because it pins the consumer
contract rather than the wiring. The targeted backend sweep (163 files, 7231
tests) again reports an identical set of 45 pre-existing failures before and
after.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two more readings of one pool on the save path.

`max_ram` was raw `psutil.virtual_memory().available`, which reports the HOST
inside a container, so a merge in a 4 GB pod on a 512 GB box sized itself to the
box and was OOM-killed. It is now the tighter of that and the cgroup remainder.
The reader is the one `dataset_num_proc` already uses rather than another walk
of /sys/fs/cgroup: it handles v1 against v2, the innermost-first path walk, the
"unlimited" sentinels, and the ancestor pairing that stops a leaf's usage being
matched to a slice's limit. Outside a cgroup it answers None and the figure is
what it was.

The unified-memory ceiling then re-derived its headroom from raw availability,
which quietly re-credited the serialization workspace. `max_ram` has already had
`sharded_ram_usage` taken out and the usage fraction applied, and on a unified
part the retained tensors and that workspace are the same bytes: a 46 GiB
machine with 39 GiB spare could retain about 35 GiB and leave under one shard's
room for the final `save_pretrained`. `_unified_memory_vram_budget` now takes
that budget directly, so there is one figure and the fraction is applied once.

The lazy import is wrapped in `except Exception`, which is right at runtime and
dangerous at review time, since a rename would be swallowed and the cap would
silently stop being applied. A test pins the name.

6 tests added or rewritten, all 6 failing without this commit.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0b91fec37a

ℹ️ 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 thread unsloth/save.py
Comment on lines +1204 to +1211
budget = _unified_memory_vram_budget(
budget,
allocated_bytes = int(torch.cuda.memory_allocated(idx)),
# `max_ram`, not a fresh reading: it is already bounded by
# the cgroup, already has the shard workspace reserved and
# already has the fraction applied, and on one pool those
# reservations have to bind the GPU side too.
host_headroom_bytes = max_ram,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resample host headroom before anchoring the UMA ceiling

When the embedding conversion at line 1168 or a merged bias allocates unified memory after max_ram was sampled, this anchor includes those new bytes in memory_allocated while still adding the stale pre-allocation headroom. Those allocations are therefore treated as both already resident and still spendable; for example, a dtype-converted large vocabulary embedding can overstate the merge ceiling by roughly its full size and defeat the new swap/OOM protection on a tight UMA host. Snapshot the allocator alongside the host reading, or refresh/reduce host headroom before constructing this absolute ceiling.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Closing this: main has since grown its own answer to the same problem, and the one place the two still disagree turns out to favour main.

What landed upstream while this sat

  • _widen_integrated_cuda_rows and _integrated_cuda_pool_total_mib in studio/backend/core/inference/llama_cpp.py, which re-price an integrated CUDA row against props.total_memory instead of the nvidia-smi carve-out. That is the same 8128 MiB against 46477 MiB N1X correction this PR was opened for.
  • trusted_mem_get_info in studio/backend/utils/hardware/hardware.py.
  • unsloth/models/_uma_safetensors.py and tests/test_uma_safetensors_load.py.

Main also caps the widened figure against psutil MemAvailable and applies the same _IGPU_HOST_RESERVE_MIB of 1024 MiB that the iGPU paths keep, and it carries about 29 tests for the path across test_unified_memory_carve_out_vram.py and test_dgx_spark_gguf_context.py. This branch is 376 commits behind and its _apply_cuda_unified_memory_correction is a second implementation of that work.

The one real disagreement, measured

This PR reports total as 0 for an integrated part so the fit uses the free * frac form, as the Vulkan iGPU and ROCm APU branches do. Main deliberately keeps a real total, and says why at llama_cpp.py:13304:

ROCm publishes 0 because that "total" is system RAM of unknown scope. An integrated part's total IS the pool, so it is a real ceiling; zeroing it would drop the fit to free*frac.

Rather than argue it, I drove both shapes through main's own _vram_usable_mib on the measured N1X pool of 46477 MiB at the shipping 0.97 fraction, sweeping the free reading across the range host pressure actually produces:

free MiB main, real total this PR, total 0 difference
46477 45082.7 45082.7 0.0
32768 31373.7 31785.0 -411.3
16384 14989.7 15892.5 -902.8
8192 6797.7 7946.2 -1148.6
2048 653.7 1986.6 -1332.9
1024 -370.3 993.3 -1363.6

Two findings. Main never offers more than is actually free, in 0 of 14 cells, so it cannot over-promise into an OOM. And main is the more conservative of the two in 13 of 14 cells, by a gap that widens as the pool fills.

The last row is the interesting one. With a real total, the budget goes negative on a nearly full pool, and _fit_context_to_vram clamps that to a refusal. With total = 0 the fit would instead offer 993 MiB of the last 1024 MiB free, which is permissive in exactly the place where being permissive is dangerous. So the behaviour this PR would change is not a bug in main; the 1394 MiB absolute reserve is llama.cpp's own margin and main is right to charge it.

The remaining difference is that this branch joins nvidia-smi rows to CUDA devices by PCI bus id, where main declines the join unless CUDA_DEVICE_ORDER is PCI_BUS_ID. That is moot in practice, since studio/main.py sets PCI_BUS_ID itself, which main's own comment notes.

Nothing here is lost by closing, so closing rather than carrying a 376 commit merge for a second implementation of work that is already in and better tested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant