Repository navigation
Studio: video component sizes from safetensors headers, measured peaks for every video family - #13537
Conversation
…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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…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.
…or none, streamed index cap, calibration tagged before the fit and keyed on request mode
…ache root, unindexed shards unknown, per-term reconcile, transformer_2 only for MoE
… of cached snapshots, companion folders by family or manifest, sub-byte floats
…xt encoders by family or manifest, loader-matched same-stem order
…r, manifest before Hub failures, loaded-but-unknown terms, loader names only, capped local index, httpx-safe index fetch
…omplete, index fetch bounded by the deadline
… denoiser term, upsampler loaded only when attached, MoE second expert only when shipped
…without the upsampler, attached extras only on the Hub, manifest decides the second expert, calibration keyed on the exact weights
…e request runs, one manifest predicate shared with the loader
…n, allowances for unknown loaded folders, single-file companions from the resolved base, base in the calibration revision, transformers-only stems in transformers folders
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if (sha is not None and age < HUB_REFRESH_SECONDS) or ( | ||
| sha is None and age < HUB_RETRY_SECONDS | ||
| ): | ||
| return sha |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if not out: | ||
| return None |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if state.cache_auto: | ||
| from .diffusion_cache import auto_step_cache_mode | ||
|
|
||
| request_cache_mode = auto_step_cache_mode(steps) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
1 similar comment
|
@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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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.
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, andDiffusionBackend._safetensors_cast_bytes/_safetensors_param_count.ComponentSizesper 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 existingprequant_header_probereader). 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_gbreconciles 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 withHF_HUB_OFFLINEorUNSLOTH_DIFFUSION_HEADER_FETCH=0, time out after 20 s and are not retried for 10 minutes after a failure._video_seed_stays_resident) and the load plan readvideo_components_gb; the LTX-2.5 latent upsampler size comes from its header (ltx25_latent_upsampler_gb, constant as fallback).arm_requestmeasures 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), andvideo_offload_shortfall_messagetakes ameasured_extra_mibthat can only lower the requirement.UNSLOTH_VIDEO_DIT_RESIDENT_MEASURED=0turns 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):
None of these tables change in this PR; the known gaps are pinned with their explanations in
KNOWN_TABLE_DELTASso they cannot drift silently.Testing
tests/test_diffusion_component_sizes.py: 22 pass offline, plus 8 Hub tests behindUNSLOTH_TEST_HUB_HEADERS=1that also pass.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.