Skip to content

Studio: video component sizes from safetensors headers, measured peaks for every video family - #13537

Merged
danielhanchen merged 18 commits into
mainfrom
studio-video-header-sizes
Oct 13, 2026
Merged

danielhanchen merged 18 commits into
mainfrom
studio-video-header-sizes

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Third step of the diffusion auto-optimizer: video component sizes come from safetensors headers, as image already did, and measured peak calibration works for every video family instead of Wan only.

  • One header reader (core/inference/diffusion_component_sizes.py) with a byte cap. Four places that parsed safetensors headers on their own now call it, each with its own cap: diffusion_memory.safetensors_prefix_mib, diffusion_small_host._safetensors_bytes_by_dtype, and DiffusionBackend._safetensors_cast_bytes / _safetensors_param_count.
  • ComponentSizes per component (stored bytes, float params, non-float bytes, resident bytes at a dtype), from a local snapshot or, before download, from header-only range reads on the Hub (the existing prequant_header_probe reader). File selection follows what the loader reads (default variant, complete index preferred, model.* for text encoders); a partly downloaded component counts as unknown, never smaller.
  • video_components_gb reconciles headers with the family table: for a family's base repo the table always wins and a disagreement is only logged; for a variant, finetune or local copy the larger of header and table is used per term, so plans never shrink; with no table the headers are used. MiniMax-H3 (modular layout) stays on its table. Hub reads only happen when no table describes the repo, are off with HF_HUB_OFFLINE or UNSLOTH_DIFFUSION_HEADER_FETCH=0, time out after 20 s and are not retried for 10 minutes after a failure.
  • Call sites: the pre-download auto scheme (_video_seed_stays_resident) and the load plan read video_components_gb; the LTX-2.5 latent upsampler size comes from its header (ltx25_latent_upsampler_gb, constant as fallback).
  • Calibration: arm_request measures the peak for every video family on CUDA, recorded peaks are reused on a reload of the same model (keyed by family, repo, offload policy, device and quant settings), and video_offload_shortfall_message takes a measured_extra_mib that can only lower the requirement. UNSLOTH_VIDEO_DIT_RESIDENT_MEASURED=0 turns reuse off.

Memory plans for every existing family are unchanged, because the table still decides for base repos.

Headers vs tables

Decimal GB, bf16 resident, from the local cache and Hub headers (denoiser / text encoders / VAE + audio):

Family Table Headers
wan2.2-ti2v-5b 10.0 / 11.4 / 2.8 10.00 / 11.36 / 2.82 agree
wan2.2-t2v-a14b 57.2 / 11.4 / 0.5 57.15 / 11.36 / 0.51 agree
wan2.1-t2v-1.3b 2.8 / 11.4 / 0.5 2.84 / 11.36 / 0.51 agree
wan2.1-t2v-14b 28.6 / 11.4 / 0.5 28.58 / 11.36 / 0.51 agree
ltx-2 37.8 / 24.4 / 5.5 37.75 / 24.37 / 5.53 agree
ltx-2.5 42.0 / 23.9 / 9.2 37.98 / 23.92 / 9.16 table counts the 4.0 GB of connectors twice
hunyuanvideo-1.5 16.6 / 14.8 / 2.4 16.65 / 14.58 / 2.52 split between terms differs, total about equal
minimax-h3 66.3 / 66.8 / 11.1 66.25 / 66.71 / 11.02 encoder 0.1 high
z-image (image) 12.3 / 8.0 / 0.2 12.31 / 8.05 / 0.17 agree
qwen-image-2.1 (image) 14.2 / 17.5 / 1.4 14.23 / 17.53 / 0.68 table holds the VAE's fp32 file size

None of these tables change in this PR; the known gaps are pinned with their explanations in KNOWN_TABLE_DELTAS so they cannot drift silently.

Testing

  • New tests/test_diffusion_component_sizes.py: 22 pass offline, plus 8 Hub tests behind UNSLOTH_TEST_HUB_HEADERS=1 that also pass.
  • After rebasing on current main: component sizes, diffusion memory, LTX-2.5, video backend and the autoopt parity and core tests give 816 passed, 14 skipped, 0 failed.
  • Full backend suite, one pytest process per file: no failing test ID that is not also failing on main. Two VAE tile files hit the per-file timeout under load and pass on rerun, as slowly as on main.

Not covered: the generalised calibration has unit tests only (faked CUDA memory calls), not a real GPU run, and the image planners still read _FAMILY_BF16_GB.

…eak calibration

One bounded safetensors header parser shared by the size helpers, ComponentSizes
from a local snapshot or ranged Hub header reads before download, and the video
family tables kept as the offline fallback (table wins for the base repo, the
larger per term for a variant). Measured request peaks are recorded for every
video family and reused by the offload refusal and across reloads.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 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-13T12:44:42.892211Z 6a583cb 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 October 13, 2026 06:05
…alidation, required roles, float8

Forward the load's hf_token to the ranged header reads, key measured peaks on the
whole load configuration (artifact, dtype, attention, speed, cache, quant, card),
revalidate cached sizes read through a mutable ref by resolved commit, decide local
completeness from the family's required roles only, and count float8 tensors as
floating parameters.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ache root, unindexed shards unknown, per-term reconcile, transformer_2 only for MoE
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… of cached snapshots, companion folders by family or manifest, sub-byte floats
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…xt encoders by family or manifest, loader-matched same-stem order
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…r, manifest before Hub failures, loaded-but-unknown terms, loader names only, capped local index, httpx-safe index fetch
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…omplete, index fetch bounded by the deadline
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… denoiser term, upsampler loaded only when attached, MoE second expert only when shipped
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…without the upsampler, attached extras only on the Hub, manifest decides the second expert, calibration keyed on the exact weights
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…e request runs, one manifest predicate shared with the loader
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…n, allowances for unknown loaded folders, single-file companions from the resolved base, base in the calibration revision, transformers-only stems in transformers folders
@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: 368309a88a

ℹ️ 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 on lines +569 to +572
if (sha is not None and age < HUB_REFRESH_SECONDS) or (
sha is None and age < HUB_RETRY_SECONDS
):
return sha

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 Revalidate mutable refs before accepting cached snapshots

When a mutable non-base repo moves within HUB_REFRESH_SECONDS of the previous sizing call, this returns the cached SHA without contacting the Hub, so component_sizes() accepts the old snapshot while the pre-download path's independent model_info() calls can stage the new commit. A larger replacement is then loaded under the old component budget and can OOM. Fresh evidence after the earlier revalidation fix is that _hub_component_sizes() populates _REF_CACHE, allowing this positive-cache branch to bypass revalidation for 600 seconds; only pinned revisions should reuse a cached SHA for this safety check.

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 changing this. Hitting it needs a non-base repo to push new weights within the 10 minute ref window between sizing and staging, and even then the plan is never below the family table: reconcile_with_table takes the per-term max for non-base repos. A per-call Hub round trip for that race costs every load a request.

Comment on lines +339 to +340
if not out:
return 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.

P2 Badge Preserve sizing results containing only unknown components

When a valid local pipeline stores all loaded components as supported .bin checkpoints, the loop records every folder and its byte allowance in unknown/unknown_bytes, but this return discards that information solely because no safetensors header populated out. The identical check in _read_hub_sizes() has the same effect for an all-.bin Hub repository. A larger derivative consequently falls back to the smaller family table instead of applying the recorded per-folder allowances; return ComponentSizes whenever either known or unknown loaded weights were found.

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 changing this. An all-.bin video pipeline has no headers to read, so it takes the family table, which is what main does for every repo. reconcile_with_table never returns a term below the table for a non-base repo, so this cannot under-budget relative to today.

Comment on lines +721 to +722
if any(n.endswith(".safetensors") or _INDEX_RE.match(n) for n in files):
return None # safetensors weights this read cannot select (index unreadable / incomplete)

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 Keep Hub sizing when only auxiliary safetensors are unselected

When a loaded component has its actual checkpoint under a .bin default name and also contains an auxiliary file such as adapter_model.safetensors, _pick_files() correctly selects nothing, but this broad suffix check treats the auxiliary file like a malformed default checkpoint and rejects the entire Hub result. That loses valid header sizes from all other components and falls back to the family table, potentially under-budgeting a larger variant; distinguish malformed recognized stems/indexes from unrelated safetensors and record this folder as unknown using its .bin bytes.

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 changing this. A loaded video component that keeps its weights in .bin next to an unrelated adapter_model.safetensors is not a layout any supported family ships. The fallback is the family table (main's behaviour), never a smaller plan.

Comment on lines +365 to +370
def _manifest_from_text(text: str) -> Optional[frozenset]:
try:
data = json.loads(text)
if not isinstance(data, dict):
return None
return frozenset(k for k, v in data.items() if manifest_entry_loaded(k, v))

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 Apply model-index ignored files during sizing

When model_index.json uses _ignore_files to suppress a stale default checkpoint or index, this parser retains only the component names and discards that file list. The definitive staging path in _pipeline_components_from_index() preserves _ignore_files and _pipeline_selected_file() excludes those paths, but local and Hub sizing still pass them to _pick_files(); for example, an ignored stale text_encoder/model.safetensors can be sized instead of the active index that is actually staged, producing an incorrect memory plan. Preserve the ignored paths from the manifest and filter them before checkpoint selection.

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 changing this. None of the supported video families' model_index.json uses _ignore_files, and a stale checkpoint left beside the active one would size at or above the staged one in practice. The result is still max'd with the family table for non-base repos.

Comment on lines +9909 to +9912
if state.cache_auto:
from .diffusion_cache import auto_step_cache_mode

request_cache_mode = auto_step_cache_mode(steps)

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 Resolve the actual cache mode before reusing calibrated peaks

When a previous long request left FBCache engaged and a later short request should disable it, this predicts an uncached request and can reuse a smaller uncached peak for the residency fit and hard-refusal calculation. However, maybe_toggle_step_cache() runs only afterward and explicitly returns TC_FBCACHE if hook teardown fails, so that request can actually retain the additional cache allocations and OOM under the relaxed uncached budget; retagging at that point only fixes where the new peak is recorded. Fresh evidence after the earlier cache-key fix is this disable-failure path, so settle the actual toggle before consulting the calibration.

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 changing this. It needs FBCache hook teardown itself to fail, which is an error path, not a well-formed request. On a normal disable the calibration key and the toggle agree, and the recorded peak is retagged to the real mode.

Comment on lines +827 to +833
def _role_loaded(fam: Any, manifest: Optional[frozenset], name: str) -> bool:
"""Whether a load of ``fam`` uses folder ``name``: a family rule, or model_index.json naming it (Studio-attached
extras are decided by ``attached_extras``)."""
rule = VIDEO_COMPANION_RULES.get(name)
if rule is not None and rule(fam):
return True
return manifest is not None and name in manifest

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 Count present optional roles when the manifest is unavailable

When the Hub model_index.json fetch transiently fails but metadata and header reads succeed, _read_hub_sizes() deliberately keeps every requested folder and returns manifest=None; this predicate nevertheless treats optional folders such as text_encoder_3, connectors, or a non-family vocoder as unloaded unless a hard-coded family rule covers them. The later staging fetch can succeed and load those manifest components, while sizing ignores even the headers already present in sizes.components, potentially admitting an OOM. When no manifest was read, conservatively use component or unknown-folder presence, as _second_expert_loaded() already does.

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 changing this. It needs the model_index.json fetch to fail transiently while the header reads in the same call succeed. Optional roles then fall back to the family table rule, and the plan is never below the table for a non-base repo.

vae_itemsize = 4 if bool(getattr(fam, "vae_force_fp32", False)) else 2
return (
_part((primary, "transformer_2"), lambda n: 2),
_part(VIDEO_ROLE_TEXT, lambda n: 2),

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 Account for text-encoder modules retained in FP32

For a non-base Wan variant using UMT5, Transformers keeps designated modules such as overflowing wo layers in FP32 even when the requested pipeline dtype is BF16; the existing small-host code explicitly accounts for this expansion. This term instead prices every text-encoder floating tensor at two bytes, so an enlarged variant whose header term wins over the family table can still be several GB below its actual resident encoder and receive an unsafe placement plan. Derive the kept-FP32 patterns from the component config or add a conservative allowance before reconciling variant headers.

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 changing this. Transformers applies _keep_in_fp32_modules only when the load dtype is float16 (modeling_utils: dtype == torch.float16 or hf_quantizer.use_keep_in_fp32_modules). Only _keep_in_fp32_modules_strict also applies at bfloat16, and UMT5 declares wo in the non-strict list. Video text encoders load at bf16, so wo is bf16 and two bytes per element is correct.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 368309a88a

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

…torch

arm_request reads the device through torch, so on a runner without torch it tags nothing by design; the
mode-blind half of the test still runs there.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 13, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6a583cbf72

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

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