Skip to content

Studio: do not lose a DGX Spark's memory pool to the page cache when fitting context - #10704

Merged
danielhanchen merged 15 commits into
mainfrom
spark-gguf-context
Sep 14, 2026
Merged

danielhanchen merged 15 commits into
mainfrom
spark-gguf-context

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Closes #9889.

Before

On a DGX Spark, a model with a 262144 native context comes up capped at 8192, and the setting the user changes has no effect:

$ curl -s http://127.0.0.1:8888/v1/models | python3 -m json.tool
"max_context_length": 8192,
"native_context_length": 262144

with tens of GiB still unused. 8192 is _FIT_MIN_CTX, the floor the fit search settles on when the KV budget is exhausted, so the report is really "the fitter thinks this machine has no memory left".

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 GGUF is that write, and so is mmap'ing it at load time, so the context gets fitted against the bytes the model's own weights left in the cache. The kernel reclaims that cache on demand, so those bytes were always available to the allocation.

_get_gpu_memory's nvidia-smi branch cannot answer on this host either (memory.free is [N/A], so every row fails to parse and the probe falls through to torch), and the torch branch treated an integrated part as a discrete card. Its ROCm twin two lines above already caps a shared pool by system RAM; this is the same idea for the other vendor, in the other direction.

After

Verified on the Spark by taking the same 60 GiB write underneath a live probe:

[baseline]             driver_free=92742MiB  _get_gpu_memory=[(0, 117452, 124609)]
[after a 60GiB write]  driver_free=29509MiB  _get_gpu_memory=[(0, 117242, 124609)]
[cache dropped]        driver_free=92730MiB  _get_gpu_memory=[(0, 117436, 124609)]

The reported budget holds at ~117 GiB while the driver's own free reading collapses to 29.5 GiB and comes back.

MemAvailable is the kernel's own estimate of what an allocation can have without swapping, and it is a floor-style estimate rather than an optimistic one. It is clamped below by the driver's figure and above by the pool, so a genuinely full machine is unchanged, and the same 1 GiB host reserve a shared pool already pays is charged on top.

An integrated CUDA part keeps its total, unlike the ROCm shared pool which publishes 0. That total is not a carve-out of unknown scope here, it is the whole pool, so it is the one honest ceiling to reserve against; zeroing it would drop the fit to the free*frac fallback.

Does this touch anything that works today

The nvidia-smi branch returns first on every host whose CLI answers, so a discrete NVIDIA machine never reaches the changed code at all. Inside the torch fallback:

  • ROCm is unreachable: _integrated_cuda_gpu_ids() already returns an empty set on HIP, and the new arm is an elif under the existing ROCm arm, so a shared AMD pool keeps min(free, MemAvailable) and total = 0 exactly as before.
  • A discrete card keeps its whole free reading and pays no host reserve.
  • Vulkan, amd-smi, Apple and CPU-only return before this point.
  • A zero total is treated as a probe that could not size the pool rather than a pool of zero, so it cannot cap the device to nothing.

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.

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

Every AMD row, on Linux, Windows and WSL, is byte-identical to the merge base. An earlier revision of this work was not, and the matrix is how I found it.

Backend suites: every file touching _get_gpu_memory, 2774 tests, pass. ruff check clean.

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

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 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 this change: the Live monitor's CPU percentage and the RAM free figure are sampled at the instant of each shot (1671.9 GiB against 1677.9 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, and stubbing the driver probe to fake one would have photographed the stub rather than this change.

@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-14T08:19:14.478139Z c0b6187 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.

…fitting context

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 or mmap'ing a GGUF
is that same write, so a model the machine can hold gets its context fitted
against the bytes its own weights left in cache, and a 262k-native model comes
up at the 8192 fit floor with tens of GiB still free.

The kernel reclaims that cache on demand, so MemAvailable, its own estimate of
what an allocation can have without swapping, is the honest reading. Never below
the driver's own figure and never above the pool, and the shared-pool host
reserve is charged the same way it is for a ROCm APU.

The ROCm branch beside it is untouched: its free reading is wrong in the
opposite direction, and _integrated_cuda_gpu_ids is already empty on HIP.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request 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[bot]

This comment was marked as resolved.

…unified preflight

Two things the credited pool needs before it is exposed as GPU capacity.

_available_system_memory_mib already caps host MemAvailable by the cgroup
remainder, but reading it only as a lower bound threw that away whenever the
driver's host-wide MemFree was larger, which is the normal case in a container.
Apply the cgroup as a separate ceiling: host-backed GPU allocations are charged
to it here, so a fit sized above it is killed at memory.max rather than merely
slow.

The unified-memory oversize preflight was AMD-only, so an integrated CUDA SoC
never reached it. _shared_gpu_ids is populated for Vulkan alone, so the guard
downstream credits the SoC's reported pool against the weights, finds no spill
and abstains, and an unmapped oversize load that would have been remapped by
_page_an_oversized_unmapped_load is not. Use the same helper the tensor-spill
guard already uses for this hardware, and name the part in the message: a Spark
is not an APU, and the WSL hint cannot apply to one.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ic tests

Three review findings, all reproduced first.

The new preflight predicate ran _integrated_cuda_gpu_ids() on any non-AMD
host, and that calls get_device_properties() on every visible card, which
initialises CUDA and pins a primary context per device in the long-lived
backend process. The launch budget is snapshotted before the preflight, so
on an ordinary discrete NVIDIA box this could take capacity away from a
tightly fitted child for an answer that was always going to be False. Gate
it on a free signal: CUDA already initialised in this load (the Spark path,
where nvidia-smi reports N/A and the memory probe already fell through to
torch), or an ARM machine, which is the only place cudaDeviceProp::integrated
is ever set.

_reprice_after_dropping_pinned_projector() rebuilt the shortfall notice with
the default part, so a Spark whose CPU-pinned projector was dropped by the
text-only fallback had its notice rewritten from SoC to APU, complete with
the .wslconfig advice that cannot apply to a Jetson or a Spark. The part now
travels with the message and the figure it was priced against.

The Spark helper cases stubbed the host memory read but not the cgroup probe
beside it, so under a container with a memory.max below the mocked pool the
real remainder capped the result and two cases failed while claiming to be
hermetic. Confirmed by running the suite with the probe pinned to 16 GiB:
test_gguf_fit_does_not_lose_the_pool_to_the_page_cache and
test_gguf_fit_never_exceeds_the_pool both failed, and both pass now. The
cgroup value is a helper argument, so the two cases that are about the cgroup
still supply their own.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 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[bot]

This comment was marked as resolved.

…y paid for

The architecture and is-initialised heuristics were both wrong in the same
direction. An ARM host with discrete cards, a GH200, still reached the property
probe and lost a primary context per card for an answer that is False; and
torch.cuda.is_initialized() is process-wide, so an x86 backend that had
initialised one GPU let the probe create contexts on all the others. Either way
the budget for this launch was snapshotted first, so a tightly fitted child can
OOM against a stale figure.

So the preflight no longer probes at all. It reads the answer only when one is
already cached for the current visibility mask, and _get_gpu_memory fills that
cache on its torch arm before it reads any free or total figure, which puts the
cost inside the snapshot that follows rather than after it. That arm is the one
an integrated SoC takes anyway: nvidia-smi reports N/A for both memory columns
on a Spark, so the CLI probe parses nothing and falls through. A host whose
nvidia-smi answers never reaches the probe and never pays for it.

The cache is keyed by the mask, since that is what decides which devices the
answer is about, and a probe that raised is not cached, since an empty answer
from a failed probe would otherwise be permanent.
@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
@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
@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: 73c9bc3bd8

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

# larger, the normal case in a container. Allocations here are
# charged to the cgroup, so an oversized fit dies at memory.max.
cgroup_mib = LlamaCppBackend._cgroup_available_memory_mib()
if cgroup_mib is not None and cgroup_mib < raw_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 Mark equality with the cgroup ceiling as cgroup-bound

When host MemAvailable exceeds the cgroup remainder but the driver's MemFree is at or below it, _available_system_memory_mib() supplies exactly cgroup_mib, so the preceding max makes raw_mib == cgroup_mib. This strict comparison then leaves cgroup_bound false and publishes the host-wide GPU total, causing _vram_usable_mib to reserve several GiB against memory the container cannot access. Fresh evidence beyond the prior comment is that the new cgroup fix misses this equality case, which occurs for every constrained Spark whose driver-free value is no greater than its cgroup remainder.

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.

Right, and it is the same equality case the diffusion side already had. _available_system_memory_mib is cgroup-capped itself, so it hands back exactly the remainder whenever MemAvailable exceeds it, and the max then lands on it for any constrained Spark whose driver-free reading is no larger.

Fixed in 6fb4501, with a test at driver-free 8 GiB against a 16 GiB remainder: free is the container's and the row publishes no total.

pre-commit-ci Bot and others added 2 commits September 10, 2026 12:22
_available_system_memory_mib is itself cgroup-capped, so it hands back exactly
the remainder whenever MemAvailable exceeds it. On a constrained Spark whose
driver-free reading is no larger, the max therefore lands on the remainder and
the strict comparison read that as unbound, publishing the host-wide total and
reserving several GiB the container cannot reach. Same equality case the
diffusion side already fixed.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the torch fallback in studio/backend/core/inference/llama_cpp.py was fitting context against MemFree on an integrated part, so the page cache left by the model's own download caps the budget and the chosen context never takes effect; the cgroup ceiling follow-up in 6fb4501 looks right, will get this reviewed.

@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

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the torch arm in studio/backend/core/inference/llama_cpp.py still caps an integrated CUDA part off MemFree, so the page cache the model's own download left behind eats the fit, and this looks like it also covers #6757. Will get this reviewed.

Every figure the integrated arm computes is a WHOLE-HOST figure: MemAvailable,
the cgroup remainder, the driver's pool total. The loop then hands each
integrated device that same figure, so two of them report

    [(0, 60826, 124610), (1, 60826, 124610)]

out of one 61850 MiB pool. A caller that sums across cards commits the same
bytes twice and the fit sizes a load against memory that does not exist.

Divide by the number of integrated devices the arch gate keeps, counted once
from the same set the loop tests so the count and the per-device decision cannot
disagree and produce a division by zero. No shipping product pairs two
integrated SoCs, so this is a guard rather than a reproduction, and it is a
division by 1 on every machine that exists today: the single-device case is
asserted unchanged.

Found by a scenario matrix over 58 host shapes; the new test fails without the
change.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed one change: the integrated arm hands the same whole-host figure to every integrated device.

MemAvailable, the cgroup remainder and the driver's pool total all describe the host, not a card. The loop applies them per device, so two integrated devices report

[(0, 60826, 124610), (1, 60826, 124610)]

out of one 61850 MiB pool. Anything that sums across cards then commits the same bytes twice, and the fit sizes a load against memory that does not exist. Now divided by the number of integrated devices the arch gate keeps, counted once from the same set the loop tests so the count and the per-device decision cannot disagree into a division by zero.

No shipping product pairs two integrated SoCs, so this is a guard rather than a reproduction, and it is a division by 1 everywhere real. The single-device case is asserted unchanged.

My first attempt at it mis-nested and swallowed cgroup_bound = True into the wrong branch. test_a_cgroup_bound_row_publishes_no_total and test_an_equal_cgroup_remainder_is_still_the_ceiling both caught it immediately, which is a good sign about this branch's coverage.

How it was checked

A scenario matrix over 58 host shapes, [Linux, Windows, WSL, macOS] x [NVIDIA, AMD, CPU] plus mixed, MIG, vGPU, container, visibility-mask and old-torch cases, run against main, this branch, #10283, and both merged together. The real _get_gpu_memory runs in each; only torch, nvidia-smi, psutil and the cgroup readers are injected.

  • 39 of 58 identical everywhere. Discrete NVIDIA, AMD ROCm and APU, CPU-only, every mask form and old torch are untouched.
  • The 19 that move are exactly the integrated devices, and this branch accounts for 10 of them: 1590 -> 60826 idle, 1200 -> 115976 with a warm page cache, 8000 -> 47825 with total = 0 in a 48 GiB container.
  • Composition with Size memory budgets correctly on unified-memory NVIDIA parts #10283 is clean, 0 problems. The effect sets are disjoint because the nvidia-smi arm returns before the torch arm is reached, so each PR acts on the host the other cannot see.

Worth knowing if you test this branch yourself: _INTEGRATED_CUDA_IDS memoises on the visibility-mask tuple, which is correct in production and false in a harness that swaps a fake torch between cases. My first run showed this branch integrated-treating discrete cards and even AMD under ROCm, purely because of that cache. Clearing it per case made it clean. _forget_the_last_machine already does the right thing for the test file.

Test scope, stated rather than implied

The box running this is shared and the OOM killer took the full backend suite four times, at 2% of the way through on the last attempt, so I could not get a whole-suite comparison here. What I did run, on this branch against its pre-change head, comparing by failing test id: 8 files covering _get_gpu_memory, the APU and iGPU carve-out paths, the arch gate and the Spark inventory. 497 passed before, 499 after, identical failing sets, the +2 being the tests added here. The 3 failures are pre-existing in my venv (no python-multipart).

That is a narrower claim than "the suite passes". Org CI is the authoritative run.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c0b6187c90

ℹ️ 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

On the red Core jobs: they are not this branch. All three variants (HF=default + TRL=default, HF=4.57.6 + TRL<1, HF=latest + TRL=latest) fail in the same step, unsloth_zoo @ main - full pytest (CPU), and main itself fails the identical step at fa16bf759.

Compared by failing test id rather than by count, the two sets are the same 13 and nothing else:

tests/test_temporary_patches_imports.py::test_xet_submodule_import_does_not_query_free_device_memory
tests/test_alloc_conf_platform_matrix.py  (12 ids across TestBoundary, TestWindowsWslFallback,
                                           TestUserPrecedence and TestBackendIsolation)

Nothing in that file touches this change, which is confined to the llama.cpp GPU-memory probe and the hardware helpers. The set is identical on main and on this head, with nothing new and nothing masked, so the breakage is upstream in unsloth_zoo and wants its own fix rather than a rebase here.

@danielhanchen
danielhanchen merged commit 61eefe6 into main Sep 14, 2026
50 of 53 checks passed
@danielhanchen
danielhanchen deleted the spark-gguf-context branch September 14, 2026 12:25
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] Issue with context limit on DGX Spark

1 participant