Skip to content

Studio: release a streamed encoder's safetensors mapping once its weights are pinned - #16914

Merged
danielhanchen merged 2 commits into
mainfrom
studio-diffusion-budget-host-ram
Nov 6, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-diffusion-budget-host-ram

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Summary

Real host RAM (MemAvailable) does not change with this PR. The memory released is a clean, file-backed page-cache mapping that the kernel could already reclaim. What drops is the process's own RSS / PSS: the memory Studio appears to use in top, task managers and PSS-based tooling. The open mapping of the model file is also released.

Under a VRAM budget, Studio streams the int8 text encoder from a pinned host copy. The encoder's original safetensors file then stayed mapped and fully resident for the life of the model, on top of the pinned copy. On Qwen-Image-2.1 that is the whole 8.7 GiB int8 encoder file, so the process showed about 28.6 GiB PSS at 8 and 12 GiB budgets when about 19.9 GiB is actually needed.

This PR makes the plain pre-quant loader return tensors that do not hold that mapping. Once the weights are pinned, the file is unmapped. Outputs are bit-identical and per-step speed is unchanged.

What / why

  • What (1): load_plain_prequant_safetensors now returns each tensor as a base-less alias of the same storage (torch.empty(0).set_(storage, offset, size, stride), no copy). _mapped_tensors in the same file already builds its tensors this way.
  • What (2): build_text_encoder in diffusion_comfy_components.py (single-file int8 ConvRot text encoders) had the same leak: codes.to(torch.int8) returns the view itself. It now loads base-less aliases too. The MiniMax-H3 conditioner is not affected: pin_module_in_place already replaces _parameters / _buffers entries instead of using .data, for this reason.
  • Why the mapping leaked:
    • safe_open(...).get_tensor() returns views of one storage that maps the whole file.
    • Int8ConvRotLinear registers weight and weight_scale as buffers. load_state_dict(assign=True) installs those views as they are.
    • Streaming re-points each host weight at its pinned copy with tensor.data = pinned (_GroupPinner, the pin arena). That swaps the storage but keeps the view's _base, so every int8 weight and scale kept the old file storage alive.
    • Parameters were not affected, because nn.Parameter(view) already drops the base. That is why the DiT never leaked and only the buffer-based encoder did.
    • A gc scan at load end on the budget run found 504 CPU tensors (6.5 GiB) still pointing into the file mapping, none of them reachable from Python. These were the view bases.
  • Effect:
    • The mapping is clean page cache, so MemAvailable did not move: the kernel could reclaim those pages.
    • What changes is what Studio reports as its own memory. RSS / PSS / task-manager memory now matches what the process really holds.
    • Each streamed model no longer keeps an 8.7 GiB mapping open. On Windows, an open mapping also keeps the file from being deleted.

Evidence (Colab RTX PRO 6000 G4, one VM, base ccc8a827d2 vs head, fresh process per cell)

Qwen-Image-2.1 t2i 1024^2, 25 steps, VRAM capped by ballast. Cells ran in the order B H H B per budget. Steady-state numbers are taken after 3 renders.

budget arm process-tree PSS GiB main-process file-backed RSS GiB MemAvailable drop GiB denoise s/img (median, renders 2-4)
8 GiB base 30.39 / 28.61 9.27 / 9.27 21.60 / 19.78 3.019 / 3.104
8 GiB head 19.95 / 19.89 0.56 / 0.60 19.76 / 19.73 3.098 / 3.104
12 GiB base 28.59 / 28.60 9.30 / 9.27 19.77 / 19.74 3.019 / 3.011
12 GiB head 19.88 / 19.89 0.60 / 0.56 19.71 / 19.74 3.012 / 3.017
16 GiB base 21.71 / 21.72 9.27 / 9.27 12.78 / 12.77 3.038 / 3.038
16 GiB head 13.00 / 13.00 0.56 / 0.56 12.75 / 12.73 3.037 / 3.037
resident base 4.35 0.56 3.87 3.061
resident head 4.35 0.56 3.89 3.063
Z-Image-Turbo, 8 GiB base / head 16.85 / 16.68 0.63 / 0.59 16.65 / 16.48 1.038 / 1.036
  • The fix engages on every budget cell: the main process's file-backed RSS drops from 9.3 GiB to 0.6 GiB. /proc/self/smaps on base shows the encoder's 8.71 GiB safetensors blob mapped and fully resident. On head it is gone.
  • Outputs: every PNG is md5-identical across base and head, at every budget and in the resident cells (3 prompts each for Qwen-Image-2.1 and Z-Image-Turbo).
  • Speed: per-phase denoise and encode times match within the base A/A spread.
  • Resident and Z-Image-Turbo loads are unchanged. Their encoder goes to the GPU, or is not a buffer-based int8 file, so no mapping was held.

Where the remaining 19.9 GiB at 8 GiB goes (head, smaps):

  • 15.6 GiB is the pinned host copy that streaming needs: 6.75 GiB of DiT slabs and 8.85 GiB for the encoder. There is no pageable duplicate.
  • 2.8 GiB is process anonymous memory, the same as in the resident load.
  • 1.2 GiB PSS is the inductor compile worker pool.

Simulation (CPU, merge base ccc8a827d2 vs head)

A synthetic plain pre-quant file was loaded by the base and head load_plain_prequant_safetensors. It held int8 2-D, fp32 (N, 1), bf16, fp8, a misaligned int8, an empty tensor, a root tensor, and an lm_head loaded with and without skip_names. The run was repeated on torch 2.6.0 + safetensors 0.4.5, torch 2.12.1 and torch 2.14.1 (safetensors 0.8.0).

  • 168 cells per torch version. On all three, the only differences are _base is not None (True -> False, per tensor) and "file still mapped after the .data = re-point" (True -> False).
  • The following are identical on every version:
    • bytes, dtype, shape, stride, storage offset, contiguity, storage size, requires_grad
    • the number of distinct storages
    • torch.save size and round trip
    • safetensors save_file of the loaded dict (succeeds on both)
    • in-place add_ (the tensor changes and the file is untouched, copy-on-write on both)
  • Symbol audit: CLEAN (0 removed, 0 signature-breaking). The two production callers of load_plain_prequant_safetensors are diffusion_te_prequant.load_prequant_text_encoder and video_ltx25_te_worker. Neither reads ._base / is_view, and both only cast (copy) or load_state_dict(assign=True). The text-encoder release snapshot copies before saving (tensor.to("cpu", copy=True)). No code in studio/backend/core reads ._base of a tensor.
  • Windows: an open file mapping blocks deleting the file. Both regression tests now delete the file after the re-point (os.remove), so on Windows they fail on base and pass on head; Linux also checks /proc/self/maps.

Tests

  • New test_int8_convrot_encoder_releases_the_file_once_its_weights_are_repointed in test_diffusion_comfy_components.py. It fails on base and passes on head, with the state dict unchanged.
  • New test_a_buffer_repointed_at_its_pinned_copy_releases_the_file_mapping in studio/backend/tests/test_prequant_safetensors.py. It loads a plain checkpoint, registers the tensor as a buffer, re-points it with .data = the way the pinner does, and checks /proc/self/maps.
    • Base: fails (the file is still mapped).
    • Head: passes, with the values unchanged.
  • test_differential.py against the merge base: DISCRIMINATING, fixed=2, unchanged=107, head_fail=0.
  • Related suites (prequant safetensors, te_prequant x3, comfy components, text-encoder trim, prequant native, video TE quant default): 297 passed, 2 skipped.

Not proven

  • macOS and Windows were not run. The change only swaps a view for an alias of the same storage, and the new test is Linux-only because it reads /proc/self/maps.
  • The single-file int8 ConvRot encoder fix is proven on a tiny Qwen3 encoder on CPU only, not on a GPU budget run.
  • A real small-RAM host (16-32 GB) was not run. The pages freed here were reclaimable page cache, so the actual MemAvailable headroom is unchanged. What changes is the reported footprint and the open mapping.

…ghts are pinned

load_plain_prequant_safetensors returned safetensors' tensors as views of one
whole-file mapping. Registered as buffers (Int8ConvRotLinear's weight and
weight_scale), they keep that view base through the .data re-point that moves
a streamed weight onto its pinned copy, so the whole file stayed mapped and
resident beside the pinned copy for the life of the model (8.7 GiB for
Qwen-Image-2.1's int8 text encoder under a VRAM budget).

Hand back base-less aliases of the same storage instead (no copy).
@danielhanchen danielhanchen self-assigned this Nov 6, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 6, 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-11-06T14:43:13.726811Z a48879c 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: b4e94e93db

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

…rs; test file deletion too

build_text_encoder kept a single-file encoder's int8 ConvRot codes as views of
the safetensors mapping (codes.to(torch.int8) returns the view), so the
streaming pin's .data re-point kept the whole file mapped. Load base-less
aliases instead. The regression tests now also delete the file after the
re-point, which an open mapping refuses on Windows.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a48879c5c9

ℹ️ 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 992185a into main Nov 6, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-budget-host-ram branch November 6, 2026 17:29
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