Repository navigation
Let a pre-quant checkpoint be safetensors instead of a pickle - #11394
Conversation
torchao weight subclasses are wrapper tensors, so every pre-quant artifact
we publish has had to be a torch.save pickle, read under weights_only plus a
constructor allowlist. torchao 0.16 added flatten_tensor_state_dict and
unflatten_tensor_state_dict, the same pair transformers and diffusers use for
their own torchao checkpoints, so the subclass can be split into plain tensors
plus a JSON description and stored in safetensors after all.
Adds core/inference/prequant_safetensors.py, which reads and writes that
container, and teaches the transformer and text encoder loaders to dispatch on
the file extension. Both containers come back as the same
{"format", "state_dict", "metadata"} dict, so every existing check (scheme,
base model, min_features, fast_accum, the fp8 activation floor probe, the
rotation biconditional, the kernel preference pin) runs unchanged on both and
the two formats cannot drift into having different acceptance rules.
What this buys, beyond the file format:
- No constructor allowlist. restricted_prequant_load_supported is a real gate:
video.py refuses a pre-quant checkpoint outright when it answers False, which
is what happens on a torch too old for add_safe_globals or a torchao missing
a scheme's constructors. A safetensors artifact names no constructors, so it
takes the filename now and answers that question for the right container.
- Validation before any weight is read. The scheme probe answers from the
header, a few KB of JSON, rather than parsing a multi-gigabyte pickle.
- mmap, lazy per-tensor reads and the Hub file viewer come with the format.
usable_prequant_source now resolves before it gates, because the answer differs
per container: a repo whose primary artifact is safetensors is usable on an
install that could not open a pickle at all, and asking first returned None for
it, making the pre-quant invisible to memory planning and silently loading dense.
Nothing about existing artifacts moves. The format tags still describe what the
weights mean, so a rotated safetensors checkpoint is still v2 and still refused
by a build that cannot rotate; old builds are kept away from these files by the
filename, since they only ever ask for <Model>-<SCHEME>.pt.
Two upstream limitations are handled rather than hoped about:
- unflatten splits every key on ".", so a root-level tensor writes cleanly and
can never be read back. The builder refuses up front and names the keys.
- Through torchao 0.17 the int8 config still produces the legacy
LinearActivationQuantizedTensor, which cannot be flattened; 0.18 produces
Int8Tensor, which can. Reading is unaffected either way, so this binds the
machine that builds an artifact and now says so instead of surfacing a bare
"Unsupported tensor type" from inside torchao.
build_prequant_checkpoint.py picks the container from the --out extension, and
refuses to publish a safetensors artifact under a name no loader would ask for:
every derived name ends in .pt, so without a family prequant_filenames entry
the upload is a file nothing can reach on a repo that looks like it has one.
Verified on a real save and a fresh safe_open: fp8 and int8 both reconstruct
Float8Tensor / Int8Tensor bit-identically and pass load_state_dict(strict=True),
and the header satisfies torchao's own is_metadata_torchao, so transformers and
diffusers can read these files too. That last assertion is deliberate: torchao
returns its metadata already JSON encoded, and encoding it a second time round
trips perfectly against our own reader while producing a header every Hugging
Face loader rejects.
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. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd5c5a7217
ℹ️ 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 _torchao_helpers() is None: | ||
| return False |
There was a problem hiding this comment.
Reject the Windows ROCm torchao stub
On Windows ROCm, install_torchao_windows_rocm_stub() makes imports under torchao.* succeed by returning fabricated callable classes, so _torchao_helpers() is non-None and this function reports safetensors support whenever the real safetensors package exists. Planning can consequently discard the dense shards, but load_prequant_safetensors() later calls the fake unflatten helper, which returns None, and the prequant load fails with no staged dense fallback. Check core._torchao_stub.is_stubbed("torchao") here, as the pickle capability probe already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 828a9c9. Reproduced by forcing the stub on: install_torchao_windows_rocm_stub installs a meta-path finder, so from torchao.prototype.safetensors.safetensors_support import flatten_tensor_state_dict, unflatten_tensor_state_dict binds two fabricated classes, unflatten_tensor_state_dict({}, {}) returns None, and safetensors_prequant_supported() returned True while restricted_prequant_load_supported('fp8', None) correctly returned False on the same install. The check went into _torchao_helpers rather than safetensors_prequant_supported so the writer is covered too, and the regression test asserts the import really does succeed against the stub before asserting the verdict, so it cannot pass vacuously.
| if getattr(src, "kind", None) == "path" | ||
| else [n for n in (getattr(src, "filename", None), getattr(src, "fallback_filename", None)) if n] | ||
| ) or [None] | ||
| if not any(restricted_prequant_load_supported(scheme, name) for name in candidates): |
There was a problem hiding this comment.
Gate the checkpoint that fallback resolution will actually load
When the declared primary name is .safetensors but only the legacy .pt fallback exists—such as during a repository migration or in an older offline cache—this any(...) succeeds on the absent safetensors name even if the install cannot deserialize pickles. _resolve_checkpoint_path() then selects the existing .pt, loading fails, and callers that trusted this result may already have omitted the dense shards from their plan. Capability needs to be checked against the name that actually resolves, or an unsupported fallback must not make the source usable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in 828a9c9, though at the other end. The declared-name evidence gate here already refuses a DERIVED safetensors guess, so the case that survived was the one you describe: the family declares the safetensors name, the repo is still serving only the legacy .pt, and the install cannot deserialize a pickle. The load itself was always a clean dense fallback; the damage was in the plan, which had already dropped the released shards. _prequant_source_hub_entry is the call that drops them and it now asks both questions of each candidate, whether the repo holds the name and whether this install can open it, so an unreadable artifact reports the miss and the shards stay in the pull.
| if is_safetensors_checkpoint(filename): | ||
| return safetensors_prequant_supported() |
There was a problem hiding this comment.
Pass the resolved filename from video capability checks
The new safetensors branch is unreachable from the video planning gates because video.py still calls restricted_prequant_load_supported(...) without a filename at lines 1139 and 2474. Thus, on precisely the older/stubbed installs this format is intended to support, a video family whose declared checkpoint is .safetensors is still evaluated using the pickle allowlist and keeps or attempts to stage the much larger dense denoiser instead. Those callers need to resolve the source and pass the selected artifact name before committing their download plans.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable, so leaving both call sites as they are. prequant_filenames entries ending in .safetensors exist on exactly one family today, qwen-image-2.1, which is an image family; no video family declares one, and video.py reaches only video families. Both sites are also the conservative direction: they answer the pickle question, which is the stricter of the two, so the outcome is a dense denoiser rather than a wrong load. If a video family ever declares a safetensors artifact these two calls do need the resolved name, and that belongs in the change that adds it, where it can be tested against a family that actually has one.
| if override: | ||
| return override |
There was a problem hiding this comment.
Validate the upload override against the container
When --out is a safetensors file, an explicit --upload-filename ending in .pt returns here before the extension validation below; the inverse mismatch is also accepted. The upload then succeeds under a name that makes every loader dispatch to the wrong reader, wasting the completed quantization build and publishing an unusable artifact. Validate an override's .safetensors suffix against the selected output container before returning it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, fixed in 828a9c9. The override is the escape hatch for a repo the family table does not describe yet, so it keeps skipping the table, but it no longer skips the container: an override is now checked against the extension --out implies, in both directions. The inverse you mention is the same failure, a pickle published as .safetensors is read from a header it does not have, and both upload cleanly, which is what makes this worth refusing before the upload rather than reporting after it.
The first commit made safetensors possible; this makes it the default. The
name a repo is asked for is now a CHAIN, best first:
<Model>-<SCHEME>.safetensors (new, preferred)
<Model>-<SCHEME>.pt (what is hosted today)
transformer_<scheme>.pt (legacy)
Deriving the preference rather than declaring it per family means a repo that
gains a safetensors sibling is picked up with no code change, and a repo that
never does keeps resolving exactly what it resolves today, because the pickle
spellings stay in the chain behind it. Existing repos are unaffected:
unsloth/Qwen-Image-FP8 still resolves Qwen-Image-FP8.pt and transformer_fp8.pt,
and a .pt name still routes to the pickle reader and its constructor allowlist.
PrequantSource grows fallback_filenames plus a candidate_filenames property, so
the downloader, the cache probe and the planner read one ordered list instead of
three hand-maintained pairs. fallback_filename stays as a property returning the
first, because callers outside this module read it by name.
Two things had to change with it, and both would have been silent regressions:
cached_checkpoint_path credited ONLY the primary name. That was right while the
primary was the only name a repo realistically hosted. With the chain leading on
a safetensors name that no repo hosts yet, it would have reported every existing
.pt repo as "this would have to download several GB" and handed the pick to the
GGUF while the checkpoint sat in the cache. It now walks the chain in order,
which keeps the property that motivated primary-only: the better name still wins
whenever it is actually present.
usable_prequant_source would have turned optimistic. Every family now derives a
safetensors candidate, so "is any candidate readable" answers yes even on an
install that cannot open a pickle at all, for a repo that only has .pt. Planning
would budget a 6 GB artifact, the fetch would 404 down to the pickle, the pickle
would be refused, and the load would fall back to dense under a plan that never
budgeted it -- the evict-then-OOM that function exists to prevent. A DERIVED
safetensors name is a guess, so it now counts only with evidence: the family
declared it, or it is already cached. PrequantSource records which names were
declared so the two can be told apart.
candidate_filenames_of() reads the chain off anything shaped like a source,
because planning passes lightweight stand-ins carrying only filename and
fallback_filename; reading the property directly turned one of those into an
AttributeError swallowed into "no prequant plan" and a silent dense fallback.
1171 tests pass. The suites that encoded the old two-name contract are updated
rather than deleted, including the one that asserted primary-only caching, whose
comment now records why that rule changed.
|
Pushed a second commit making safetensors the preferred container rather than an opt-in one. The name a repo is asked for is now a chain, best first: Deriving the preference instead of declaring it per family means a repo that gains a safetensors sibling is picked up with no code change, while a repo that never does keeps resolving exactly what it resolves today. Confirmed against the existing repos: Both Two things had to change with it, and both would have been silent regressions rather than test failures:
1171 tests pass. The suites that encoded the old two-name contract are updated rather than deleted, including the one that asserted primary-only caching, whose comment now records why that rule changed. |
Three places treated the container as settled once the name resolved. The Windows ROCm torchao stub answers every torchao.* import with a fabricated callable, so importing the flatten/unflatten pair succeeded there and reported safetensors support on an install whose unflatten returns None. Planning would drop the dense shards for a checkpoint the loader can never rebuild. The pickle probe already asked is_stubbed; the safetensors one now does too. The download plan committed to the first candidate the repo HELD, which is no longer the same question as the first it can OPEN now that the chain spans two containers. A repo still serving only the legacy pickle, met by an install that cannot restrict that load, spent the download and then refused it with no dense weights left. It now skips a name it cannot read and reports the miss, which keeps the shards in the pull. An explicit --upload-filename skipped the container check as well as the family table, so a safetensors build could be published under .pt and a pickle under .safetensors. Both upload cleanly and neither can ever be opened, after the hours the quantization took. Also updates the Qwen-Image-2512 filename test, which pinned the single derived name and now asserts the whole chain: safetensors first, the .pt the repo actually serves still in it, the legacy spelling last.
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 828a9c948d
ℹ️ 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".
| for index, name in enumerate(names): | ||
| last = index == len(names) - 1 | ||
| try: | ||
| return _download_checkpoint_name( |
There was a problem hiding this comment.
Skip unreadable containers during runtime resolution
When a repository contains both candidates but this installation can deserialize only the later one—for example, safetensors exists but torchao lacks unflatten_tensor_state_dict while the legacy pickle remains readable—this unconditional return selects the first existing file without applying restricted_prequant_load_supported. The planner at diffusion.py:3036 now skips that unreadable file and stages the later candidate, but the runtime resolver can still fetch/select the earlier one, fail in _load_prequant_checkpoint, and fall back only after planning omitted or under-budgeted the dense weights. Filter the runtime candidate chain with the same per-filename capability check.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and the asymmetry was mine from the previous round: I filtered the plan and left the resolver alone. Fixed in 7692c4a. _resolve_checkpoint_path now takes the scheme and applies the same per-filename check, so plan and runtime agree on WHICH artifact and not merely on whether there is one. It filters only when that leaves something: an empty filter means the source should never have been offered, and resolving nothing there would turn a refusal the loader reports into a silent None. The regression test records the names actually requested, so it fails if the unreadable container is fetched at all rather than only if the load fails.
|
|
||
| if src.kind == "repo" and all(is_safetensors_checkpoint(n) for n in readable): | ||
| declared = set(getattr(src, "declared_filenames", ()) or ()) | ||
| if not any(n in declared for n in readable) and cached_checkpoint_path(src) is None: |
There was a problem hiding this comment.
Require the cached evidence itself to be readable
When pickle loading is unsupported and the only readable candidate is a speculative derived .safetensors name, cached_checkpoint_path(src) may still return a cached, unreadable .pt fallback and incorrectly satisfy this evidence gate. usable_prequant_source then reports the source and cache as usable, so offline or memory planning can omit the dense weights even though resolution misses the absent safetensors file and cannot open the cached pickle. The fresh evidence after the Hub-list fix is that this cache probe remains container-agnostic; verify that the cached path corresponds to one of readable rather than accepting any cached candidate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed, fixed in 7692c4a. cached_checkpoint_path walks every candidate by design, so a cached legacy pickle really did satisfy the declared-or-cached gate on an install that cannot open one. It now takes an optional names and the evidence gate passes the readable subset: a cached .pt stays a real hit for sizing, where the question is bytes, and stops being an answer where the question is whether this install could open it. The test asserts both directions, so the gate is not simply closed.
…stion too The plan learned to skip a candidate this install cannot open; the two places that answer alongside it did not, and an asymmetry there is worse than the original gap. _resolve_checkpoint_path took the first name the repo HELD. On a repo hosting both containers the plan would stage the readable one while this fetched the other, spending a second multi-gigabyte download to fail on it and then falling back to dense weights the plan had already left out. It now filters the chain with the same per-filename check, and only when that leaves something, so a source that should never have been offered still reaches the loader's refusal rather than a silent None. cached_checkpoint_path walks every candidate, so a cached legacy pickle satisfied the declared-or-cached evidence gate for an install that cannot open one. The probe is now scoped to the readable names: a cached .pt is a real hit for sizing and a non-answer for this question, and only the caller knows which is being asked.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7692c4a1df
ℹ️ 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 not preferred: | ||
| raise ValueError( | ||
| f"family {getattr(fam, 'name', fam)!r} declares no prequant_filenames entry for " | ||
| f"{scheme!r}, so a rotated checkpoint has no name the loader would ask for. Add the " | ||
| f"{scheme!r}, so {why} has no name the loader would ask for. Add the " | ||
| "entry to the family table, or pass --upload-filename." | ||
| ) |
There was a problem hiding this comment.
Use the derived safetensors name for uploads
When --out is a safetensors file and --upload-repo is used without --upload-filename, every production family lacking a prequant_filenames entry (for example, z-image) is rejected here. This is based on the now-stale assumption that all derived names end in .pt: derived_prequant_filenames() now explicitly makes <Model>-<SCHEME>.safetensors the first name the loader requests. Consequently the builder's normal automatic-upload path cannot publish the new container even though the resulting derived filename is reachable, forcing users to redundantly calculate and pass the override.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and the staleness is precisely as you describe: that refusal was written when every derived name ended in .pt, and derived_prequant_filenames now leads with <Model>-<SCHEME>.safetensors, so the reachability it protects is exactly what the chain supplies. Fixed in 4a5df5f: a PLAIN safetensors build with no declared entry derives from --upload-repo, and the test reads the expected name back out of the resolver rather than restating it, so the builder and the loader cannot drift apart. A ROTATED build still refuses, since no derived spelling carries the marker, which is the other half of why the check exists.
The refusal predates the derived chain. upload_destination rejected a safetensors build for any family with no prequant_filenames entry, on the reasoning that every derived name ends in .pt so nothing would ever ask the Hub for the artifact. derived_prequant_filenames now puts <Model>-<SCHEME>.safetensors ahead of both .pt spellings, so the reachability that refusal was protecting is exactly what the chain supplies, and the builder was making every such family compute and pass an override it could derive itself. Derived from --upload-repo, and the test reads the expected name back out of the resolver rather than restating it, so the two cannot drift. A ROTATED build still refuses: no derived spelling carries the marker, which is the other half of why the refusal exists.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
When a source has both container candidates but this installation can open only one of them, this unfiltered cache probe can report the other, unreadable candidate as the hit. For example, a cached .safetensors file on an install that supports only the pickle fallback makes _uncached_prequant_repo, denoiser_prequant_cached, and _auto_prequant_retry_scheme treat the usable artifact as already staged; an auto/offline plan can then omit dense shards or permit the shortcut, while _resolve_checkpoint_path(..., scheme=...) skips that cached file and finds the readable .pt absent, causing an unexpected multi-GB fetch or an offline load failure. Pass the readable-name subset through this helper, as usable_prequant_source already does for its evidence check.
ℹ️ 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".
| f"{scheme!r}, so {why} has no name the loader would ask for. Add the " | ||
| "entry to the family table, or pass --upload-filename." | ||
| ) | ||
| if safetensors and not preferred.lower().endswith(".safetensors"): |
There was a problem hiding this comment.
Validate family-derived upload names in both directions
The fresh remaining case after the override fix is the family-derived path: when building a rotated pickle (--out ...pt) for a family whose declared filename ends in .safetensors, this one-sided check is skipped and preferred is returned. The upload therefore puts pickle bytes under a safetensors name, and every loader dispatches to safe_open and rejects the artifact. Compare the declared suffix against both output-container choices before returning it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 037fb72. Reproduced it directly: upload_destination(fam, 'fp8', rotated=True, safetensors=False) for a family whose prequant_filenames entry ends in .safetensors returned 'Qwen-Image-2.1-FP8.safetensors', so a rotated pickle would have published torch.save bytes under a safetensors name. The check is now symmetric, comparing the declared suffix against the container --out writes in both directions, and there is a regression test per direction.
The family-derived name was compared against the container only when the build was safetensors, so
the reverse mismatch went through: a rotated pickle build for a family whose prequant_filenames
entry ends in .safetensors returned that name, and torch.save bytes would be published under it.
Every loader dispatches on the extension, hands the file to safe_open and rejects it, so the
artifact is unopenable for a reason that points nowhere near the real mistake.
Reachable as soon as a family moves its entry to a safetensors artifact, which is exactly what the
Qwen-Image-2.1 family does:
upload_destination(fam, 'fp8', rotated=True, safetensors=False)
-> 'Qwen-Image-2.1-FP8.safetensors'
One symmetric check now covers both directions, with the message naming the container --out writes
and the extension the declared name carries. Tests cover each direction.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/backend/core/inference/video.py
Lines 2897 to 2899 in 037fb72
When a video prequant repo's first existing candidate is .safetensors but the current torchao can only read the later pickle candidate, this loop stages the unreadable safetensors file and lets the plan omit the dense denoiser; runtime resolution now filters that name and requests the unstaged .pt, so an offline/download-only load fails and an online load performs an unplanned multi-GB download. Fresh evidence since the earlier dismissal is that derived_prequant_filenames now puts a safetensors name first for every video repo, and the H3 tests expect that derived name, so no video family declaration is required. Apply restricted_prequant_load_supported(scheme, name) before selecting the staged candidate, matching the image planner and runtime resolver.
ℹ️ 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".
| for name in candidate_filenames_of(source): | ||
| if wanted is not None and name not in wanted: | ||
| continue | ||
| for root in roots: | ||
| hit = _cached_in_root(source, root, name) |
There was a problem hiding this comment.
Restrict cache hits to readable candidates
When only a .safetensors candidate is cached on an installation that lacks the torchao safetensors helpers but can read the pickle fallback, the default walk here reports that unreadable file through prequant_checkpoint_cached; image auto-policy, pipeline offline planning, and the analogous video cache probe can consequently commit to prequant and omit dense shards, while _resolve_checkpoint_path(..., scheme=...) filters the cached file and cannot find the uncached .pt. The previous cache fix covered the opposite direction only by passing names=readable from the all-safetensors evidence branch; this inverse case remains for the numerous callers that use the default. Their cache checks need to pass the scheme-readable subset as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 012d46c. Readability is now asked per candidate name inside the cache walk itself, so every caller gets it and not only the one that passed names=readable, and both directions are covered: a cached safetensors on a host without the flatten helpers is as unusable as a cached pickle on a host that cannot restrict the load. The lookup still never raises, so a probe that throws falls back to counting the hit. Regression test: test_a_cached_name_this_install_cannot_open_is_not_a_cache_hit.
There was a problem hiding this comment.
Correct, and the default walk was the half that mattered: every caller that did not pass names could be told a .safetensors this install cannot open is a cache hit, commit to prequant and drop the dense shards, while the resolver then filtered that same file out and found nothing.
cached_checkpoint_path now runs its own candidates through restricted_prequant_load_supported before answering, so the default path gives the answer the resolver would. The lookup is documented as never raising and is wrapped anyway, treating an unexpected raise as readable rather than hiding a file that is fine.
Test: test_a_cached_name_this_install_cannot_open_is_not_a_cache_hit.
| is_safetensors_out = str(args.out).lower().endswith(".safetensors") | ||
| if is_safetensors_out: | ||
| from core.inference.prequant_safetensors import safetensors_prequant_supported | ||
| if not safetensors_prequant_supported(): |
There was a problem hiding this comment.
Reject unsupported INT8 safetensors builds up front
For an INT8 .safetensors build under torchao 0.16 or 0.17, this preflight succeeds because both helpers and the safetensors package exist, but those releases quantize INT8 into the legacy subclass that flatten_tensor_state_dict cannot serialize; save_prequant_safetensors detects that only after the model has been downloaded and the hours-long GPU quantization has completed. Make the writer capability check scheme-aware (or require torchao >=0.18 for INT8) so this known unsupported combination fails before the expensive build.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 012d46c. Confirmed on the installed torchao 0.17 first: Int8DynamicActivationInt8WeightConfig produces LinearActivationQuantizedTensor and flatten_tensor_state_dict raises 'Unsupported tensor type', while safetensors_prequant_supported() returns True, so the preflight passed and the failure landed after the download and the quantize. The builder now probes one tiny CPU Linear with the same config before anything is loaded. A config that cannot be applied returns None, which is treated as no evidence and proceeds, since refusing a build because the probe was unavailable is worse than the late failure.
There was a problem hiding this comment.
Agreed, and the cost is the point: the old preflight only proved the helpers import and the package is present, so an int8 safetensors build on torchao 0.16 or 0.17 failed after the download and after the quantization.
The preflight now calls scheme_is_flattenable, which quantizes a small probe layer with the real scheme and tries to flatten it, so the combination is refused before anything expensive runs. It answers None when the probe itself cannot run, which means proceed rather than refuse, since a probe failure is not evidence about the scheme.
Tests: test_a_scheme_this_torchao_cannot_flatten_is_reported_before_the_build, plus test_the_real_installed_torchao_answers_the_int8_question against whatever torchao is actually installed.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
LocalEntryNotFoundError subclasses EntryNotFoundError, so walking the candidate chain under the base caught an unreachable Hub as if the name were absent: three download attempts instead of one, and the error surfaced was the last candidate's 404 rather than the connection failure. Online it now re-raises as itself; offline, where a cache miss is the only verdict there is, the chain is still walked.
…eme before the build Two gaps with the same shape: a check that passes, then a failure after the expensive part. A cached .safetensors on a host without torchao's flatten helpers was a cache hit, so planning committed to the prequant and dropped the dense shards, while the resolver filtered that very file out and found the other name uncached. The narrowing that fixed the opposite direction only reached the one caller that passed names=readable. Readability is now asked per name in the walk itself, so every caller gets it, and the lookup still never raises. The builder's safetensors preflight asked whether the helpers import, which is not whether this scheme produces something they take: through torchao 0.17 int8 quantises to LinearActivationQuantizedTensor and flatten refuses it, so the build failed after the download and the hours of GPU quantization. Probed on one tiny CPU Linear instead, with an unprobeable config treated as no evidence.
…o studio-prequant-safetensors
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4e0641684b
ℹ️ 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".
| undotted = unsupported_state_dict_keys(state_dict) | ||
| if undotted: |
There was a problem hiding this comment.
Preserve root-level tensors in safetensors checkpoints
When building a .safetensors checkpoint for the supported z-image family (diffusion_families.py:343-347), ZImageTransformer2DModel.state_dict() contains the root-level parameters x_pad_token and cap_pad_token, so this check always raises after the model download and GPU quantization have completed. Root tensors are plain tensors and can be kept outside torchao's reconstruction set, then merged back after unflatten_tensor_state_dict; rejecting every undotted key makes the new container unusable for this current family rather than only guarding a hypothetical future model.
Useful? React with 👍 / 👎.
…i#11573) (Python 3.13, a-k) fails the same four tests on every PR. Bisected on main with the GPU hidden, as on the runner; each is a test that stopped describing the product, not a product regression: - test_download_plan_counts_a_cached_lower_auto_prequant, since unslothai#11394. The plan now skips a pre-quant name this install cannot open, and torchao 0.18, which the shard installs unpinned, has no int8 pickle constructors. The test offers only Qwen-Image-INT8.pt. It now pins the readability answer and also asserts the converse: an unreadable artifact is not budgeted. - test_every_third_party_bf16_pipeline_the_catalog_offers_is_mirrored, since unslothai#11405 offered Qwen/Qwen-Image-2.1. unsloth/Qwen-Image-2.1 is not on the Hub, so a mirror row would 404 every fetch it redirects. Named as a pending mirror that fails once the row lands or the catalog drops it. - test_the_recorded_base_must_be_the_canonical_id_not_just_the_same_tail, added by unslothai#11405. build_prequant_checkpoint.main imports diffusers before reading an argument and the shard has no diffusers. An empty stand-in when it is absent; the refusal lands before any diffusers attribute is read. - test_qwen_image_21_gguf_reaches_sd_cpp_with_its_own_vae_and_a_qwen3vl_encoder, since unslothai#11542 moved the encoder to UD-Q4_K_XL on purpose and pins that name in its own test. This one now reads the declared name and keeps its own claim, that the file is a 4-bit GGUF.
…hai#11394) * Let a pre-quant checkpoint be safetensors instead of a pickle torchao weight subclasses are wrapper tensors, so every pre-quant artifact we publish has had to be a torch.save pickle, read under weights_only plus a constructor allowlist. torchao 0.16 added flatten_tensor_state_dict and unflatten_tensor_state_dict, the same pair transformers and diffusers use for their own torchao checkpoints, so the subclass can be split into plain tensors plus a JSON description and stored in safetensors after all. Adds core/inference/prequant_safetensors.py, which reads and writes that container, and teaches the transformer and text encoder loaders to dispatch on the file extension. Both containers come back as the same {"format", "state_dict", "metadata"} dict, so every existing check (scheme, base model, min_features, fast_accum, the fp8 activation floor probe, the rotation biconditional, the kernel preference pin) runs unchanged on both and the two formats cannot drift into having different acceptance rules. What this buys, beyond the file format: - No constructor allowlist. restricted_prequant_load_supported is a real gate: video.py refuses a pre-quant checkpoint outright when it answers False, which is what happens on a torch too old for add_safe_globals or a torchao missing a scheme's constructors. A safetensors artifact names no constructors, so it takes the filename now and answers that question for the right container. - Validation before any weight is read. The scheme probe answers from the header, a few KB of JSON, rather than parsing a multi-gigabyte pickle. - mmap, lazy per-tensor reads and the Hub file viewer come with the format. usable_prequant_source now resolves before it gates, because the answer differs per container: a repo whose primary artifact is safetensors is usable on an install that could not open a pickle at all, and asking first returned None for it, making the pre-quant invisible to memory planning and silently loading dense. Nothing about existing artifacts moves. The format tags still describe what the weights mean, so a rotated safetensors checkpoint is still v2 and still refused by a build that cannot rotate; old builds are kept away from these files by the filename, since they only ever ask for <Model>-<SCHEME>.pt. Two upstream limitations are handled rather than hoped about: - unflatten splits every key on ".", so a root-level tensor writes cleanly and can never be read back. The builder refuses up front and names the keys. - Through torchao 0.17 the int8 config still produces the legacy LinearActivationQuantizedTensor, which cannot be flattened; 0.18 produces Int8Tensor, which can. Reading is unaffected either way, so this binds the machine that builds an artifact and now says so instead of surfacing a bare "Unsupported tensor type" from inside torchao. build_prequant_checkpoint.py picks the container from the --out extension, and refuses to publish a safetensors artifact under a name no loader would ask for: every derived name ends in .pt, so without a family prequant_filenames entry the upload is a file nothing can reach on a repo that looks like it has one. Verified on a real save and a fresh safe_open: fp8 and int8 both reconstruct Float8Tensor / Int8Tensor bit-identically and pass load_state_dict(strict=True), and the header satisfies torchao's own is_metadata_torchao, so transformers and diffusers can read these files too. That last assertion is deliberate: torchao returns its metadata already JSON encoded, and encoding it a second time round trips perfectly against our own reader while producing a header every Hugging Face loader rejects. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Prefer safetensors over the pickle for every pre-quant repo The first commit made safetensors possible; this makes it the default. The name a repo is asked for is now a CHAIN, best first: <Model>-<SCHEME>.safetensors (new, preferred) <Model>-<SCHEME>.pt (what is hosted today) transformer_<scheme>.pt (legacy) Deriving the preference rather than declaring it per family means a repo that gains a safetensors sibling is picked up with no code change, and a repo that never does keeps resolving exactly what it resolves today, because the pickle spellings stay in the chain behind it. Existing repos are unaffected: unsloth/Qwen-Image-FP8 still resolves Qwen-Image-FP8.pt and transformer_fp8.pt, and a .pt name still routes to the pickle reader and its constructor allowlist. PrequantSource grows fallback_filenames plus a candidate_filenames property, so the downloader, the cache probe and the planner read one ordered list instead of three hand-maintained pairs. fallback_filename stays as a property returning the first, because callers outside this module read it by name. Two things had to change with it, and both would have been silent regressions: cached_checkpoint_path credited ONLY the primary name. That was right while the primary was the only name a repo realistically hosted. With the chain leading on a safetensors name that no repo hosts yet, it would have reported every existing .pt repo as "this would have to download several GB" and handed the pick to the GGUF while the checkpoint sat in the cache. It now walks the chain in order, which keeps the property that motivated primary-only: the better name still wins whenever it is actually present. usable_prequant_source would have turned optimistic. Every family now derives a safetensors candidate, so "is any candidate readable" answers yes even on an install that cannot open a pickle at all, for a repo that only has .pt. Planning would budget a 6 GB artifact, the fetch would 404 down to the pickle, the pickle would be refused, and the load would fall back to dense under a plan that never budgeted it -- the evict-then-OOM that function exists to prevent. A DERIVED safetensors name is a guess, so it now counts only with evidence: the family declared it, or it is already cached. PrequantSource records which names were declared so the two can be told apart. candidate_filenames_of() reads the chain off anything shaped like a source, because planning passes lightweight stand-ins carrying only filename and fallback_filename; reading the property directly turned one of those into an AttributeError swallowed into "no prequant plan" and a silent dense fallback. 1171 tests pass. The suites that encoded the old two-name contract are updated rather than deleted, including the one that asserted primary-only caching, whose comment now records why that rule changed. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Ask whether a pre-quant name is readable, not just whether it exists Three places treated the container as settled once the name resolved. The Windows ROCm torchao stub answers every torchao.* import with a fabricated callable, so importing the flatten/unflatten pair succeeded there and reported safetensors support on an install whose unflatten returns None. Planning would drop the dense shards for a checkpoint the loader can never rebuild. The pickle probe already asked is_stubbed; the safetensors one now does too. The download plan committed to the first candidate the repo HELD, which is no longer the same question as the first it can OPEN now that the chain spans two containers. A repo still serving only the legacy pickle, met by an install that cannot restrict that load, spent the download and then refused it with no dense weights left. It now skips a name it cannot read and reports the miss, which keeps the shards in the pull. An explicit --upload-filename skipped the container check as well as the family table, so a safetensors build could be published under .pt and a pickle under .safetensors. Both upload cleanly and neither can ever be opened, after the hours the quantization took. Also updates the Qwen-Image-2512 filename test, which pinned the single derived name and now asserts the whole chain: safetensors first, the .pt the repo actually serves still in it, the legacy spelling last. * Make the runtime resolver and the cache probe ask the readability question too The plan learned to skip a candidate this install cannot open; the two places that answer alongside it did not, and an asymmetry there is worse than the original gap. _resolve_checkpoint_path took the first name the repo HELD. On a repo hosting both containers the plan would stage the readable one while this fetched the other, spending a second multi-gigabyte download to fail on it and then falling back to dense weights the plan had already left out. It now filters the chain with the same per-filename check, and only when that leaves something, so a source that should never have been offered still reaches the loader's refusal rather than a silent None. cached_checkpoint_path walks every candidate, so a cached legacy pickle satisfied the declared-or-cached evidence gate for an install that cannot open one. The probe is now scoped to the readable names: a cached .pt is a real hit for sizing and a non-answer for this question, and only the caller knows which is being asked. * Let a plain safetensors build use the name the loader now asks for first The refusal predates the derived chain. upload_destination rejected a safetensors build for any family with no prequant_filenames entry, on the reasoning that every derived name ends in .pt so nothing would ever ask the Hub for the artifact. derived_prequant_filenames now puts <Model>-<SCHEME>.safetensors ahead of both .pt spellings, so the reachability that refusal was protecting is exactly what the chain supplies, and the builder was making every such family compute and pass an override it could derive itself. Derived from --upload-repo, and the test reads the expected name back out of the resolver rather than restating it, so the two cannot drift. A ROTATED build still refuses: no derived spelling carries the marker, which is the other half of why the refusal exists. * Check the declared upload name against the container in both directions The family-derived name was compared against the container only when the build was safetensors, so the reverse mismatch went through: a rotated pickle build for a family whose prequant_filenames entry ends in .safetensors returned that name, and torch.save bytes would be published under it. Every loader dispatches on the extension, hands the file to safe_open and rejects it, so the artifact is unopenable for a reason that points nowhere near the real mistake. Reachable as soon as a family moves its entry to a safetensors artifact, which is exactly what the Qwen-Image-2.1 family does: upload_destination(fam, 'fp8', rotated=True, safetensors=False) -> 'Qwen-Image-2.1-FP8.safetensors' One symmetric check now covers both directions, with the message naming the container --out writes and the extension the declared name carries. Tests cover each direction. * Do not blame the last candidate for an unreachable Hub LocalEntryNotFoundError subclasses EntryNotFoundError, so walking the candidate chain under the base caught an unreachable Hub as if the name were absent: three download attempts instead of one, and the error surfaced was the last candidate's 404 rather than the connection failure. Online it now re-raises as itself; offline, where a cache miss is the only verdict there is, the chain is still walked. * Never count a cached name this install cannot open, and probe the scheme before the build Two gaps with the same shape: a check that passes, then a failure after the expensive part. A cached .safetensors on a host without torchao's flatten helpers was a cache hit, so planning committed to the prequant and dropped the dense shards, while the resolver filtered that very file out and found the other name uncached. The narrowing that fixed the opposite direction only reached the one caller that passed names=readable. Readability is now asked per name in the walk itself, so every caller gets it, and the lookup still never raises. The builder's safetensors preflight asked whether the helpers import, which is not whether this scheme produces something they take: through torchao 0.17 int8 quantises to LinearActivationQuantizedTensor and flatten refuses it, so the build failed after the download and the hours of GPU quantization. Probed on one tiny CPU Linear instead, with an unprobeable config treated as no evidence. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…i#11573) (Python 3.13, a-k) fails the same four tests on every PR. Bisected on main with the GPU hidden, as on the runner; each is a test that stopped describing the product, not a product regression: - test_download_plan_counts_a_cached_lower_auto_prequant, since unslothai#11394. The plan now skips a pre-quant name this install cannot open, and torchao 0.18, which the shard installs unpinned, has no int8 pickle constructors. The test offers only Qwen-Image-INT8.pt. It now pins the readability answer and also asserts the converse: an unreadable artifact is not budgeted. - test_every_third_party_bf16_pipeline_the_catalog_offers_is_mirrored, since unslothai#11405 offered Qwen/Qwen-Image-2.1. unsloth/Qwen-Image-2.1 is not on the Hub, so a mirror row would 404 every fetch it redirects. Named as a pending mirror that fails once the row lands or the catalog drops it. - test_the_recorded_base_must_be_the_canonical_id_not_just_the_same_tail, added by unslothai#11405. build_prequant_checkpoint.main imports diffusers before reading an argument and the shard has no diffusers. An empty stand-in when it is absent; the refusal lands before any diffusers attribute is read. - test_qwen_image_21_gguf_reaches_sd_cpp_with_its_own_vae_and_a_qwen3vl_encoder, since unslothai#11542 moved the encoder to UD-Q4_K_XL on purpose and pins that name in its own test. This one now reads the declared name and keeps its own claim, that the file is a 4-bit GGUF.
Every pre-quantized transformer we publish today is a
torch.savepickle, because torchao's weight subclasses are wrapper tensors (several plain tensors plus reconstruction metadata behind one logical weight) and safetensors stores flat tensors only. torchao 0.16 addedflatten_tensor_state_dict/unflatten_tensor_state_dict, the same pairtransformersanddiffusersuse for their own torchao checkpoints, so that is no longer true.This adds
studio/backend/core/inference/prequant_safetensors.pyand teaches the transformer and text-encoder loaders to dispatch on the file extension. Both containers come back as the same{"format", "state_dict", "metadata"}dict, so every check already indiffusion_prequant(scheme, base model,min_features,fast_accum, the fp8 activation-floor probe, the rotation biconditional, the kernel-preference pin) runs unchanged on both, and the two formats cannot drift into having different acceptance rules.Why, beyond the file format
restricted_prequant_load_supportedis a real gate, not a formality:video.pyrefuses a pre-quant checkpoint outright when it answers False, which is what happens on a torch too old foradd_safe_globals, on a torchao missing a scheme's constructors, or on the stubbed torchao used by Windows ROCm. Those installs fall back to dense today. A safetensors artifact names no constructors, so the gate now takes the filename and answers the right question for the container in hand.usable_prequant_sourcenow resolves before it gates, because the answer genuinely differs per container: a repo whose primary artifact is safetensors is usable on an install that could not open a pickle at all, and asking the pickle's question first returnedNonefor it. That made the pre-quant invisible to memory planning and silently loaded dense.On-disk layout
Tensors are exactly what
flatten_tensor_state_dictproduces. The header is torchao's own metadata (tensor_namesplus one JSON entry per weight) with two namespaced keys added:is_metadata_torchaowalkstensor_namesonly, so the extra keys do not disturb it, and these files stay readable by anything that understands torchao checkpoints.No new format tag. The tags describe what the weights mean, not what holds them, so a rotated safetensors artifact is still
v2and still refused by a build that cannot rotate. Old builds are kept away from these files by the FILENAME: they only ever resolve<Model>-<SCHEME>.ptand know nothing of a.safetensorssibling, so a repo can host both and each build reads the one it understands. Nothing about the already-published.ptartifacts moves.Two upstream limitations, handled rather than hoped about
unflatten_tensor_state_dictsplits every key on.to get a module fqn, so a ROOT-level parameter or buffer (pos_embedrather thanembed.weight) writes cleanly and then raises on read. The builder refuses up front and names the offending keys. Every DiT we ship is dotted throughout; this exists so a future one fails at build time rather than in a user's loader.LinearActivationQuantizedTensorover anAffineQuantizedTensor, which cannot be flattened; 0.18 producesInt8Tensor, which can. Reading is unaffected (0.17 reconstructs anInt8Tensorfile fine), so this binds the machine that BUILDS an artifact, and it now says so instead of surfacing a bareUnsupported tensor typefrom inside torchao.Builder
scripts/build_prequant_checkpoint.pypicks the container from the--outextension, so one flag selects the on-disk format, the reachable upload name and the writer, and they cannot be set to disagree. It refuses to publish a safetensors artifact under a name no loader would ask for: every derived name ends in.pt, so without a familyprequant_filenamesentry the upload is a file nothing can reach, sitting on a repo that looks like it has a checkpoint.Verification
Real save, fresh
safe_open, reconstruct, forward:Both reconstruct the subclass, match the pre-save output bit for bit rather than approximately, and pass
load_state_dict(strict=True)against a module quantized the same way. Mixed state dicts (quantized weights, plain sub-threshold linears, biases, buffers) round-trip with every key intact.The
is_metadata_torchaoassertion in the tests is deliberate and is the one trap worth naming: torchao returns its metadata already JSON-encoded, and encoding it a second time round-trips perfectly against our own reader while producing a header every Hugging Face loader rejects. A symmetric-decode test passes; the file breaks on someone else's machine.Suites:
test_prequant_safetensors.py(new, 21 cases), plustest_diffusion_prequant,test_video_prequant,test_diffusion_te_prequant,test_build_prequant_checkpoint,test_diffusion_convrot,test_diffusion_predownload_memory_guard,test_diffusion_pipeline_prequant,test_diffusion_auto_policyall pass (363 passed, 1 skipped; the skip is the int8 round-trip on a torchao that cannot write it, which asserts the error message first).The full backend run on this box also shows 161 pre-existing failures in accounts / blender / chat-generation from a broken local bitsandbytes and a missing pytest-asyncio. I checked rather than assumed: a representative subset gives 23 failed / 158 passed identically on
mainand on this branch.