Skip to content

Studio: stop refusing a diffusion load on a DGX Spark against its own download - #10705

Merged
danielhanchen merged 12 commits into
mainfrom
spark-diffusion-memory
Sep 10, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
spark-diffusion-memory

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Closes #9919.

Before

Image generation on a DGX Spark refuses to load, on a machine with 121 GiB of memory:

{"level": "error", "event": "diffusion.memory: refusing oversized unified-memory load:
 'flux.2-klein' needs about 24 GB of memory for its weights, but only about 0 GB is usable
 on this device (of the 3 GB currently free, after reserving room for the operating system).
 ..."}

The guard itself is right and should stay. On one shared pool, offload moves bytes within that pool and frees nothing, and the failure mode it prevents is the OS killing the process with no Python exception to catch. The reading it was handed was wrong.

Why

cudaMemGetInfo's free half on an integrated CUDA SoC is the kernel's MemFree, which counts the page cache as used. Measured on a GB10, writing a 60 GiB file and deleting it again:

[baseline]                cuda_free=103.25  MemFree=103.25  MemAvailable=115.85  Cached=12.64
[after writing 60GB]      cuda_free= 41.52  MemFree= 41.52  MemAvailable=115.65  Cached=72.64
[after deleting the file] cuda_free=103.30  MemFree=103.30  MemAvailable=115.87  Cached=12.61

cuda_free tracks MemFree exactly and MemAvailable never moves. Downloading a 24 GB diffusion model is that write, so the load that follows is budgeted against a pool that the download appears to have consumed. That is how a 121 GiB machine reports "3 GB currently free", and the 20% unified-memory reserve then takes the usable budget to 0.

After

The reclaimable cache is credited back: max(driver_free, min(MemAvailable, total)). Never below the driver's own figure and never above the device total, so a machine that really is full is refused exactly as it is today. On the box above the snapshot goes from 3 GiB free to 115 GiB, and the load proceeds.

MemAvailable is the kernel's own estimate of what an allocation can have without swapping, which is a floor-style estimate rather than an optimistic one, so this does not turn the guard off.

The reading goes through the llama.cpp backend's _available_system_memory_mib, which caps that same host figure by the process's cgroup remainder. Both readings are host-wide inside a container, but only this one credits memory the load may not have, and a --memory-capped Spark is exactly where an over-credit reaches the OOM kill the guard exists to pre-empt.

Does this touch anything that works today

The credit only runs when the snapshot is already classified unified_memory, which only _cuda_memory sets, and only from cudaDeviceProp::integrated. Discrete VRAM, XPU, Apple MPS and plain CPU all take paths this does not touch.

One case needed excluding, and I would not have found it by reading the code. A ROCm APU sets the same integrated flag, so it reaches unified_memory here too, and its free reading is wrong in the opposite direction (Windows HIP reports free == total, #7072). Crediting host memory on top of an over-report would have enlarged it. The scenario matrix caught it as a 90 GiB to 96 GiB shift on Strix Halo across Linux, Windows and WSL; the credit is now gated on torch.version.hip being unset, and there is a regression test for it.

Verification

A scenario matrix runs 47 host shapes against this branch and against its merge base in separate processes and diffs the JSON:

[Windows, Linux, WSL, Mac] x [NVIDIA discrete, NVIDIA datacenter x2, NVIDIA integrated,
 AMD discrete, AMD APU, AMD APU on pre-6.2 HIP, Intel XPU, Intel iGPU, Apple, CPU-only]
plus: nvidia-smi absent / non-zero exit / [N/A] totals, a reordering CUDA_VISIBLE_DEVICES,
a single-device mask, an empty mask, a UUID mask, 4 GPUs, a mixed inventory, a zero total,
a torch without the property, no torch at all, no psutil, a cgroup-capped container.

identical=37   (the rest are the integrated parts this is for)

The container row is in there on purpose: with a 32 GiB cgroup the credit stops at 32 GiB rather than at the host's 115 GiB.

Backend suites: test_diffusion_memory.py, test_diffusion_predownload_memory_guard.py and the rest, pass. ruff check clean.

Measured on real hardware: NVIDIA GB10, aarch64, Ubuntu 24.04, driver 580.173.02, torch 2.14.0+cu130.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 10, 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-10T11:57:29.861652Z 2e75632 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.

… download

The unified-memory shortfall guard refused flux.2-klein on a 121 GiB machine
with "needs about 24 GB of memory for its weights, but only about 0 GB is usable
on this device (of the 3 GB currently free)". The guard is right to exist:
offload frees nothing on one pool and the OS kills the process with no Python
exception. The reading it was handed was wrong.

cudaMemGetInfo's free half on an integrated CUDA SoC is the kernel's MemFree,
which counts the page cache as used. Measured on a GB10: writing a 60 GiB file
took it from 103.25 GiB to 41.52 GiB while MemAvailable never moved off 115.6
GiB, and deleting the file restored it exactly. Downloading the model is that
same write, so the load that follows is budgeted against a pool the download
appears to have consumed.

Credit that reclaimable cache back, bounded below by the driver's own figure and
above by the device total, so a genuinely full machine is unchanged. Read
through the llama.cpp backend's helper so a memory-capped container is bounded
by its cgroup rather than by host RAM.

A ROCm APU reaches the same unified_memory classification but is excluded: its
free reading is wrong in the opposite direction, and crediting host memory on
top of an over-report would enlarge it further.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c658fc0d05

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

…sion pool

_available_system_memory_mib already caps host MemAvailable by the cgroup
remainder, but reading it only as a lower bound inside max() threw that away
whenever the driver's host-wide MemFree was the larger number, which is the
normal case in a container. The guard this feeds exists because the OS kills an
oversized unified-memory load with no Python exception, and a cgroup boundary is
exactly that kill.

Apply the remainder separately, after the credit, so a memory-capped container
is bounded by its own limit and an unconstrained host keeps the credited pool.
Found while reviewing the same shape in the GGUF context fit.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed ec4536c after reviewing the same shape in #10704.

_available_system_memory_mib already caps host MemAvailable by the cgroup remainder, but this read it only as a lower bound inside max(), which throws that cap away whenever the driver's host-wide MemFree is the larger number. In a container that is the normal case, so the description's claim that a --memory-capped Spark is bounded by its cgroup was not actually true of the code.

The remainder is now applied separately as a ceiling after the credit. An unconstrained host is unchanged, and the scenario matrix is still identical to the merge base on all 37 non-integrated rows.

Regression test: test_unified_free_is_bounded_by_an_enforcing_cgroup, covering a 16 GiB cgroup against a 100 GiB driver reading, the case where the credit itself would have stopped lower, and a host with no enforcing limit.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…p probe

Two review findings.

Capping the free reading by the cgroup remainder left the device total at the
host figure, and _reserve_mib takes 20 percent of the total for a unified pool.
A 32 GiB container on a 121 GiB Spark therefore reserved 24 GiB and left about
8 GiB usable, refusing models that fit the container comfortably. The helper now
returns the capacity alongside the free reading and reports the capped pool as
capacity when, and only when, the limit actually binds. A readable limit that is
merely present says nothing about capacity, so an idle host keeps the device
total unchanged rather than having it collapse to whatever was free at snapshot
time. plan_fits_total_capacity reads the same total, so it is priced correctly
too.

The end-to-end snapshot case stubbed the host memory read but left the cgroup
probe live, so a runner capped below 115 GiB decided the assertion. Confirmed by
running the file with the probe pinned to 16 GiB: only
test_spark_snapshot_is_unified_and_credits_the_cache failed, and it passes now.
The ROCm APU case is stubbed the same way for the same reason.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown

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

Reviewed commit: 2e5d505125

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

…binding

Two review findings on the same lines.

_cgroup_available_memory_mib returns the limit minus the current working set, so
using it as the total reported a pool that shrinks as the container fills: a
64 GiB container holding a 30 GiB model looked like a 34 GiB device, which
shrinks the reserve as memory is used and refuses a replacement model that only
has to fit once the resident one is evicted. The cgroup walk now yields both
numbers and there is a separate reader for the limit, so the remainder stays the
free-memory ceiling and the limit is the capacity. An unreadable limit leaves
the device total alone.

The binding test was strict, but _available_system_memory_mib is itself
cgroup-capped, so credited == remainder is the ordinary result in a container
whenever host MemAvailable exceeds the remainder and the driver's MemFree does
not. Equality now binds, which is the case the finding is about: a 32 GiB
container was still reserving 20 percent of the 121 GiB host total.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The capacity question is separate from the free-memory one, and gating it on
the remainder answered it only when the remainder happened to be the tighter
of the two. With a 64 GiB container whose remainder is 44 GiB but only 16 GiB
of host availability, the pool stayed at the host's 121 GiB, the reserve stayed
at 24 GiB, and the budget came out zero for a model that fits.

A finite limit now bounds capacity on its own, and the free reading is bounded
by that capacity too: the driver's host-wide MemFree can exceed what the
container may charge, and memory that cannot be charged is not free either. A
host with no readable limit is unchanged.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
danielhanchen and others added 2 commits September 10, 2026 04:05
…t read

version.hip alone is not the test for a ROCm build: AMD SDK and Radeon wheels
leave it unset and tag __version__ only, so an integrated APU on one of those
read as NVIDIA and got the host-memory credit. Its free reading is already an
over-report there (Windows HIP reports free == total), so the guard could
approve a load the OS then kills. Uses LlamaCppBackend._torch_is_rocm, which
already encodes this, with the same rule inline for an import that cannot be
satisfied. Reproduced with a wheel of that shape: the APU's 90 GiB free reading
was talked up before, and stands now.

The parameterized cgroup case patched the two availability helpers but not the
capacity one, so under a real memory.max the no-limit row was capped by the
runner. Reproduced by pinning the cgroup walk to a 16 GiB container holding
4 GiB: exactly that row failed, and passes now.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c402d7d2da

ℹ️ 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 and docstring text only, verified with the AST check: no code, and the
tests are unchanged. The installer test file the formatting hook rewrote here
has nothing to do with this change, so it is back as it was.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026

@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: 2e75632c70

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

# remainder is what caps the free reading: a tighter host figure does not make a
# 64 GiB container a 121 GiB device. The LIMIT, never the remainder, which shrinks
# as the container fills and would refuse a model that fits once one is evicted.
limit_mib = _cgroup_memory_limit_mib()

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 Isolate fake integrated-device tests from the host cgroup

When the backend suite runs inside a memory-limited container with its normal dependencies installed, this new live probe replaces the total of every mocked integrated CUDA device with the runner's real memory.max. In test_diffusion_predownload_guard_platforms.py, _classify stubs a 64 GiB device and _system_memory_mib but does not stub either new cgroup helper, so test_an_integrated_gpu_is_the_one_machine_that_is_judged can receive (for example) the runner's 16 GiB total and reject the supposedly fitting model. Stub the cgroup readings in that shared fixture, as the new test module already does, so these existing platform tests remain hermetic.

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.

Confirmed, and it is exactly the case you named. Pinning the cgroup walk to a 16 GiB container reproduces it: all three parameterisations of test_an_integrated_gpu_is_the_one_machine_that_is_judged fail, the other 48 in that file pass.

Fixed in f63635c by stubbing both cgroup readings, and the host availability beside them, in the shared _classify fixture. All 51 pass under the same pin.

pre-commit-ci Bot and others added 2 commits September 10, 2026 11:58
An integrated device is now priced against the host as well, and both of those
readings are live, so the shared _classify fixture let a runner with a real
memory.max decide what its faked 64 GiB machines have. Reproduced by pinning
the cgroup walk to a 16 GiB container: all three parameterisations of
test_an_integrated_gpu_is_the_one_machine_that_is_judged failed, and they pass
now.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the integrated path in studio/backend/core/inference/diffusion_memory.py still budgets against cudaMemGetInfo's MemFree, so a fresh download collapses the reading, and the cgroup ceiling you added in f63635c covers the container case. Will get this reviewed.

@danielhanchen
danielhanchen merged commit 0873389 into main Sep 10, 2026
49 of 50 checks passed
@danielhanchen
danielhanchen deleted the spark-diffusion-memory branch September 10, 2026 13:05
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 10, 2026
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Sep 14, 2026
This branch was cut before unslothai#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).
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.

[Bug] Image generation issue on DGX Spark

1 participant