Skip to content

Studio diffusion: the pin budget credits clean mapped page cache inside a capped cgroup - #15642

Merged
danielhanchen merged 4 commits into
mainfrom
pin-budget-reclaimable-cache
Oct 28, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
pin-budget-reclaimable-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Inside a capped cgroup (systemd-run --scope -p MemoryMax=..., a container), the host pin budget that sizes every diffusion pin (_pin_budget_mib) could read anywhere from 0 to several GiB for the same live set. The cause is how utils/host_memory._reclaimable_file_bytes treats mapped file pages:

reclaimable = inactive_file + max(active_file - file_mapped - dirty - writeback, 0)

Mapped pages are credited when they sit on the inactive list and charged as used when they sit on the active list. With MGLRU (default on current Ubuntu kernels) the same mapped pages move between the two lists as generations age, so the reading flips while nothing changes. MiniMax-H3 holds its int8 denoiser host copy as mmap views of the checkpoint (about 19 GB), which makes the swing large: in a 70G scope on a 94 GB host, the H3 pin budget read 7.7 GB on one day and 0 to 1.3 GB on another, on the same commit, and at 0 the streamed blocks run from unpinned memory (12 GB cell: 156.7 s vs 164.2 s).

Change

  • host_memory.cgroup_memory_budgets(..., credit_mapped=False) and _reclaimable_file_bytes(..., credit_mapped=False): with credit_mapped=True the clean mapped pages on the active list count as reclaimable too (dirty and writeback still do not, shmem never does). The default is unchanged, so GGUF admission and /api/system read exactly as before.
  • host_memory.credited_cgroup_headroom_mib(): the binding cgroup headroom with that credit, read once per level.
  • Under a cgroup limit, _pin_budget_mib() takes min(host MemAvailable, that credited headroom) as its available reading, then the same max(4 GiB, 15%) reserve. The reading is taken whole rather than added to the uncredited sample, so pages moving between the lists between two reads cannot be counted twice. Pinning copies replace the checkpoint's mmap views and the kernel reclaims those clean pages under the limit, so this matches what an uncapped host's MemAvailable already counts. Without a limit the budget is unchanged.
  • UNSLOTH_DIFFUSION_PIN_CREDIT_MAPPED=0 turns the credit off.

The integrated GPU refusal (host_pinning_allowed), the WSL/Windows pinned cap, the forced pin switch and the low-RAM reserve all run unchanged before or after the budget.

Evidence (CPU only, systemd-run --user --scope -p MemoryMax=8G -p MemorySwapMax=0, kernel 6.17, MGLRU on)

A 4 GiB file mapped and touched, 1 GiB anon, unrelated streaming reads to age the lists:

pass inactive_file active_file file_mapped before after
0 2907 4118 4095 0 2913
3 6532 494 4096 2501 2908
5 2887 4134 4096 0 2907
unmapped 2887 4134 0 2991 2907

(MiB.) Before, the budget flips between 0 and 2.5 GB with an identical live set; after, it is stable and equal to the unmapped reading. Plain read() page cache was already credited before this change (the budget did not move after reading 4 GiB), so this is about mapped pages only.

Safety: with the file still mapped, allocating the credited budget plus all but 256 MiB of the reserve as anon (no swap) in the same 8G scope finishes with oom_kill 0, and the mapping reads back fine afterwards.

Tests

tests/test_pin_budget_mapped_cache.py (fake cgroup trees): same budget whether the mapped pages sit on the active or inactive list, an earlier uncredited sample is not added to the credited one, kill switch, dirty/writeback stay uncredited, shmem never credited, host MemAvailable still bounds it, an ancestor level still binds, no limit is unchanged, cgroup v1 hierarchical and per-level counters, malformed memory.stat, integrated GPU still never pins.

Touched-area suites (test_host_memory_cgroup, test_diffusion_memory, test_dgx_spark_diffusion_memory, test_integrated_gpu_no_host_pin, test_h3_low_vram_stream, test_video_encoder_exact_pin, test_image_encoder_background_pin, test_h3_host_ram_guard, test_diffusion_measured_placement): 472 passed, 43 skipped on both base and head, no failing IDs on either.

Not proven

  • No GPU wall-time run: the H3 12 GB timing above comes from an external measurement on two days, not from a base vs head pair. Cloud runtimes do not give a capped systemd scope.
  • Not run on classic (non-MGLRU) LRU or on kernel 7.x.
  • If another process in the same scope keeps its own mapping hot, the credit can cost it re-reads from disk (no OOM risk; an uncapped host already behaves this way).

@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-10-28T03:00:39.670173Z d38c08b 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 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: ce41f671a3

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

available = _available_system_memory_mib()
if total is None or available is None:
return None
available = int(available) + _pin_mapped_cache_credit_mib(int(available))

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 Compute credited headroom without adding independently sampled readings

If mapped pages move from the inactive list to the active list between _available_system_memory_mib() and this call, the initial available-memory reading already credits those pages, but mapped_cache_credit_mib() credits them again using a newly sampled baseline. Reproducing that transition with the test's 70 GiB limit, 60 GiB usage, and 20 GiB mapped checkpoint produces a 40,448 MiB pin budget instead of 19,968 MiB, even though the live set never changes. The host MemAvailable cap does not prevent exceeding the tighter cgroup headroom, so this can admit pins that exhaust the reserve and trigger a cgroup OOM. Compute the pin budget directly from the credited cgroup headroom rather than adding a delta to an independently sampled uncredited reading.

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.

Good catch. The pin budget now takes the credited cgroup reading whole (one memory.stat read per level, min with MemAvailable) instead of adding a delta to an earlier sample, so pages moving between the lists between two reads can no longer be counted twice. Added a test for exactly that case (earlier reading 30 GiB, credited 30 GiB: the budget stays 30 GiB less the reserve, not 50).

@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: d38c08b6e1

ℹ️ 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 d128b72 into main Oct 28, 2026
35 of 45 checks passed
@danielhanchen
danielhanchen deleted the pin-budget-reclaimable-cache branch October 28, 2026 07:49
NilayYadav pushed a commit to Lyxot/unsloth that referenced this pull request Oct 28, 2026
…n denoise steps (unslothai#15796)

## Summary

On a 12 GB card MiniMax-H3 streams its whole int8 denoiser, including
the 0.8 GB top-level group (embeddings, `norm_out`, `proj_out`). That
group runs from the first block to the last, so it was offloaded at the
end of every forward and uploaded again at the start of the next. The
compute stream then waited for the whole copy, about 65 ms per step on
an A100, plus another 26 ms for block 0, which could not be prefetched
while the top-level group filled the window.

H3's modular pipeline has no `callback_on_step_end`, so the
cross-forward carry (unslothai#15108) never armed for it. This PR:

- drives the carry from the `scheduler.step` wrapper H3 already uses for
progress (`_scheduler_step_carry`, gated by `_h3_carry_by_scheduler`),
and disarms and drops anything carried at decoder entry as a backstop;
- adds `keep_first` to the H3 prefetcher. When the group that opens the
recorded order also closes the forward, it stays on the card into the
next forward, which starts with it anyway. Everything else (window,
decode drop, interleave and capture checks) is the existing carry logic.

On its own, the carry did nothing for H3. When the top-level group is
offloaded, the forward's compute is already finished, so its re-upload
still sat on the critical path. That measured 4.868 / 4.871 s/step
against 4.868 / 4.869 for base. Keeping the group on the card is what
removes the wait.

Kill switch: `UNSLOTH_H3_STREAM_CARRY=0` (turns off both the carry and
the keep).

## Profile (main `85744ff385`, Colab A100-SXM4-40GB, PCIe gen4 x16,
960x544x124, 20 steps)

Measured with CUDA events around each prefetch wait and copy,
`torch.cuda.set_sync_debug_mode("warn")`, and a torch.profiler trace of
one warm forward:

| | 16 GiB | 12 GiB |
|---|---:|---:|
| resident / streamed groups | top + 8 blocks / 42 | 0-1 / 50 + top |
| H2D per forward | 16.3 GB, 1.33 s at 12.3 GB/s (pinned) | 20.3 GB,
1.64 s |
| copy overlapped with compute | 98% | 94% |
| compute stall on copies per warm forward | 0.1 ms | 92 ms (top group
65 ms + block 0 26 ms) |
| compute-stream idle per forward (trace) | 18 ms | 29 ms |
| host syncs inside a warm forward | 0 | 0 |
| `empty_cache` / allocator segment frees per warm forward | 0 / 0 | 0 /
0 |

There is one forward per step. At 16 GiB, streaming is free once the
blocks are pinned: 4.776-4.793 s/step against 4.789 fully resident on
the same card. With pinning off
(`UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN=0`, which reproduces the log lines
of a host with 0 MiB pinnable), the same cell runs at 4.936 s/step
(+3.3%). That matches the +3% the Oct 27 benchmark measured at 16 GB on
a host whose pin budget was 0, which unslothai#15642 addresses.

## Results (same VM, interleaved base / head processes, 12 GiB ballast +
total cap)

| arm | warm s/step (2 renders) | warm end-to-end (render 2 / 3) |
|---|---|---|
| base (3 processes) | 4.868 4.869, 4.874 4.868, 4.877 4.872 | 108.6
103.2, 107.1 103.1, 108.7 103.2 s |
| head (3 processes) | 4.805 4.794, 4.804 4.798, 4.817 4.802 | 106.9
101.1, 104.7 101.8, 107.9 101.9 s |
| head, `UNSLOTH_H3_STREAM_CARRY=0` | 4.872 4.870 | 108.3 102.3 s |

- Warm s/step: base 4.871 vs head 4.803 (-1.4%). The A/A spread of the
base process means is 0.006 s, the head spread 0.010 s, and the delta is
0.068 s.
- On the head, the 12 GiB cell's per-step time is within 0.3% of the
fully resident one (4.78-4.79).
- Compute stall per warm forward goes from 92 ms to 21 ms (profiled head
arm). H2D per forward goes from 20.25 to 19.45 GB.
- 16 GiB (top-level group resident, nothing to keep): base 4.788, head
4.793 s/step. Frames are identical.
- Warm renders are bit-identical, head vs base, in 6 of 6 pairs, plus
the 16 GiB pair and the kill-switch arm. The first (cold) render of a
process alternates between two outputs on main itself: base vs base
differs at 38.2 dB, and head vs base pairs either match exactly or show
the same 38 dB variant.
- Peak VRAM per render is unchanged (NVML over base: 11339-11341 / 10981
MiB on both). Inside a forward, `max_memory_allocated` is 7311 MiB on
both: the kept group is what the next forward starts with.
- Peak host RAM is unchanged (62.9-63.3 GB cell peak on both).
- 0 OOM, 0 `Recompiling function` lines (`TORCH_LOGS=recompiles`) in
every arm.
- Engagement: every head render logs `video.h3_stream_carry: 34 carried
copies read across forwards`. The kill-switch arm logs none.

## Tests

- New `tests/test_h3_stream_carry.py` (18 tests). They cover H3's loop
shape (20 forwards, 19 `scheduler.step` calls), one call per step, too
few calls (dropped at decode), cancel, the gate (family, streamed, step
callback, env), the kill switch, the top-level group kept and uploaded
once per render while blocks still stream, and release on an aborted
render. With the scheduler-driven step, the decode drop or the keep
reverted, 2, 1 and 1 of them fail.
- Prefetch, cross-forward, H3 stream and residency tests (21 files):
base 1200 passed / 3 failed, head 1218 passed / 3 failed. The same 3
`test_diffusion_multigpu.py` IDs fail on both.

## Not covered

- Only an A100 (PCIe gen4) was measured. The RTX 6000 Ada and the RTX
3090 (PCIe 3.0 x4) from the benchmark were not available, so the 3090
streaming gap is not measured here.
- This PR does not show that the benchmark host now pins. unslothai#15642 targets
that, and Colab has no capped cgroup to reproduce it.
- Block 0 still waits about 21 ms per forward at 12 GiB. Its copy can
only start once the last block is done without raising the window above
the forward-start footprint.
- The render after a residency re-fit (1 block resident, then 0) still
runs its first forward without prefetch: 48 misses, about 1.2 s once.
This PR does not change that.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

1 participant