Repository navigation
Pin the training precision, video preset and image metadata contracts - #8162
Merged
Merged
Conversation
… schemes The Train panel's base_precision list and the DiT trainer share a quant vocabulary with inference but not the same set: nvfp4 and fp8_dynamic are inference-only, and there is no training path for either. Add a contract test that reads both ends of the chain (the train_precision_modes probe over a simulated GPU matrix, the family_train_infos payload, the base_precision Literal, and the precisionModes memo in diffusion-train-panel.tsx) and reddens if an inference-only scheme appears in any of them, while asserting NVFP4 stays available where it is legitimate on the inference load forms.
The Video tab's Resolution select is populated from status.defaults.resolution_presets, which is VideoFamily.resolution_presets copied through video.py's status(); before a load it falls back to FALLBACK_RESOLUTION_PRESETS in video-page.tsx. Add a contract test that the fallback names only sizes a family actually declares, that the select still reads the backend list rather than the fallback, and that every family declares at least one preset on its own grid, since the generate path indexes resolution_presets[0] unguarded when the request omits width/height.
…equest transformer_quant is a request the loader may decline (no dense source, not enough VRAM, torchao missing) or resolve to a different scheme, so only _LoadState knows what ran. Add a contract test over the whole chain: a load whose requested precision differs from the engaged one must produce a recipe carrying the ENGAGED value, at the backend (generate() reads state.kind / .gguf_filename / .transformer_quant) and at the route (the persisted metadata comes from the generation result). Also pin the build keys out of image_gallery._REQUIRED_META so a PNG written before they existed still lists, and keep the Recipe popover rendering them.
…ntract runs anywhere The two backend halves of the saved-image precision contract loaded a pared-down torch and diffusers into sys.modules as plain ModuleType objects. A plain module has no __path__, so load_pipeline's lazy `from .diffusion_eager_patches import ...` could not resolve `import torch.nn.functional as F` through the stub, and the GGUF prefix-strip shim could not resolve `diffusers.loaders.single_file_model`. They passed on a developer box only by accident of import order: tests/conftest.py loads unsloth_zoo, which imports the real torch, which seeds sys.modules["torch.nn.functional"]. A dotted import short-circuits on that cached entry and never consults the parent's __path__. On a clean CPU-only interpreter nothing seeds it and both tests died with "No module named 'torch.nn'; 'torch' is not a package". Stub torch and diffusers as packages and register torch.nn, torch.nn.functional, diffusers.loaders and diffusers.loaders.single_file_model explicitly, all through monkeypatch.setitem so the previous entries are restored on teardown. The assertions are untouched: the engaged precision, not the requested one, is still what generate() has to report.
The Train panel's precision guard extracted string literals with a double-quote-only regex, and read the reported-mode filter with a `m === "..."` pattern of the same shape. Prettier keeps this file on double quotes, so that held in practice and the tests passed, but the guard's whole claim is that it reddens if anyone drops an inference-only scheme into the panel. It did not: mutation-testing the branch showed a single-quoted `m === 'nvfp4'` arm and a single-quoted entry in the offline fallback array both sailing through a clean run, while the double-quoted spellings of the same two edits failed as intended. A guard that only catches the formatting the formatter happens to produce is not a guard. Accept all three TS quotings, and strip block comments as well as line comments before matching, so a scheme named in prose still cannot be read as an offered option. Re-verified by mutation: single-quoted, backtick and double-quoted insertions now each fail, and a comment-only mention stays green.
Four of these guards could not detect the regression they advertise. The precision contract derived every set from the request schema and the probe, so a mode added to both vanished from the inference-only set and every assertion passed, while DiffusionLoraConfig.normalized() kept its own hardcoded tuple and rejected the run after eviction. That link is now asked of the trainer directly, by driving normalized() over the schema vocabulary, with an inference-only scheme checked to still bounce so a permissive trainer cannot satisfy it either. The Train panel whitelist was compared with a subset check, which passes just as happily when an arm is deleted; the effect of deleting one is the backend reporting a mode the panel silently drops. Now an equality against the advertisable vocabulary minus the separately prepended auto sentinel. The video preset test built VideoGenerationDefaults by hand and so never ran VideoBackend.status(), despite being named for it: a status() that hardcoded a list stayed green. It now goes through the real status() and then the response model. The saved-recipe test asserted only the pre-serialization dict, so a GalleryImage that stopped declaring a build key would have FastAPI strip it from the wire with everything still green. It now also asserts the serialized generate body and the listing model. Also unload the backend after the stubbed load tests. A committed load deliberately keeps its process-wide eager and arch patches installed, and only unload() reverts them; nothing survives today only because diffusers 0.39 does not match the drift guards. Each of the five was confirmed by mutating the code it guards and watching it fail.
Six follow-ups, same class as the last round: each assertion stopped one layer short of the thing that actually reaches the user. The trainer check swallowed any ValueError whose text was not the mode-name message, so a precision blocked at start time by a dense-base, mixed-precision or dataset-path check would have read as accepted. Anything that stops a start is a refusal now. _probe discarded the recommendation, which is what the Train panel seeds basePrecision with, so a recommendation outside the reported list would be an option the user starts on and the select never offered. It is returned and asserted against both the modes and the schema, on every capability in the matrix. Subtracting auto from the whitelist comparison is only sound while the memo prepends it, and nothing asserted that; every memo return that offers anything must now lead with Auto, the untrainable-family empty return aside. The NVFP4 end-to-end guard built only the image request and searched the video page's source, so VideoLoadRequest could drop nvfp4 while video-page.tsx kept offering it and the only symptom would be a 422. It builds the video request too. The video preset test reached VideoBackend.status() but stopped before VideoStatusResponse, the model the route declares, so the outer model dropping defaults would leave the inner assertion happy and the browser with no presets. And baked_loras is load-time build identity like the other three, so it belongs in the additive key set that guards against a build key being promoted into _REQUIRED_META. Confirmed against mutations of the memo's return and of VideoStatusResponse.
- /v1/images/generations builds its own recipe and left out every build key, so an image made through an OpenAI client listed with no quant, no kind and no filename while the contract stayed green. - the fake torch/diffusers fixture let load_pipeline import the eager and arch patch modules under the stubs, so their module globals stayed bound to the fakes for the rest of the process; they are evicted in teardown now.
Member
Author
|
@codex review |
1 similar comment
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
This was referenced Aug 9, 2026
danielhanchen
added a commit
that referenced
this pull request
Aug 9, 2026
…fusal (#8257) Four tests are red on a clean checkout of main. #8165 made a declined EXPLICIT precision refuse the load instead of falling back silently, and made the text-encoder pass return a TEQuantOutcome the loader reads .mode off. Two later squash merges carried branches cut before it: #8162 added the saved-recipe precision contracts, and #8141 added a placement test whose stub returns a bare None. Neither combination was ever run. Fixed on the test side. quantize_text_encoders is annotated -> TEQuantOutcome and every one of its seven returns constructs one, so the None at diffusion.py:3113 only exists because a test monkeypatches the function; and the route only calls assert_precision_available on the diffusers engine, which is DiffusionBackend, which defines it. Neither AttributeError is reachable in a real run, so there is no product guard to add. - opt into UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK where the contract is about what the recipe records once a fallback is allowed, as the routes, backend and video suites already do - assert the decline reason #8165 records instead of the old wording naming what loaded instead. The substantive pair is untouched: off, from explicit - give _EngagedBackend the assert_precision_available gate the route now calls, and return a TEQuantOutcome from the stubbed text-encoder pass
danielhanchen
added a commit
that referenced
this pull request
Aug 9, 2026
…fusal (#8257) Four tests are red on a clean checkout of main. #8165 made a declined EXPLICIT precision refuse the load instead of falling back silently, and made the text-encoder pass return a TEQuantOutcome the loader reads .mode off. Two later squash merges carried branches cut before it: #8162 added the saved-recipe precision contracts, and #8141 added a placement test whose stub returns a bare None. Neither combination was ever run. Fixed on the test side. quantize_text_encoders is annotated -> TEQuantOutcome and every one of its seven returns constructs one, so the None at diffusion.py:3113 only exists because a test monkeypatches the function; and the route only calls assert_precision_available on the diffusers engine, which is DiffusionBackend, which defines it. Neither AttributeError is reachable in a real run, so there is no product guard to add. - opt into UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK where the contract is about what the recipe records once a fallback is allowed, as the routes, backend and video suites already do - assert the decline reason #8165 records instead of the old wording naming what loaded instead. The substantive pair is untouched: off, from explicit - give _EngagedBackend the assert_precision_available gate the route now calls, and return a TEQuantOutcome from the stubbed text-encoder pass
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Tests only, no product changes. An external QA pass flagged several things that turned out to be already correct in the code. This adds regression tests so they stay correct.
What is locked in
The training precision list never gains an inference-only scheme. The report listed the Linux training menu as offering Auto, BF16, NF4, INT8, FP8 and MXFP8 and asked whether NVFP4 leaks in. It does not, and it must not start to.
Rather than hardcoding
nvfp4, the test derives the inference-only set as (inferencetransformer_quantandtext_encoder_quantLiterals, plusTE_QUANT_MODES) minus sentinels minus the training Literal, which resolves to{nvfp4, fp8_dynamic}. An anchor test pinsnvfp4into that set so the derivation can never silently empty out.train_precision_modes()is driven over sm75, 80, 86, 89, 90, 100 and 120, crossed with torchao on and off and no-CUDA, to build the full advertisable vocabulary. The frontend side extracts the wholeprecisionModesmemo fromdiffusion-train-panel.tsx, comments stripped, and asserts every string literal in it, the TS union, the equality whitelist and the fallback array, is a real training precision.Every UI-offered video resolution is a real family preset, and every family declares at least one. The second half matters because a family with an empty tuple would crash
video.py'swidth or fam.resolution_presets[0][0].Saved image metadata records the engaged precision, not the requested one. Images already do this correctly today, sourcing from the committed
_LoadStaterather than the request. Two divergent-load scenarios are exercised against the realDiffusionBackend, plus a route-level round-trip capturing the exact dict handed toimage_gallery.save, and a freeze on_REQUIRED_METAso older PNGs keep listing.Every test was verified to fail when its invariant is broken
A test that passes when the thing it protects is violated is worse than no test, so each was checked by deliberately breaking the subject and reverting.
modes.append("nvfp4")intrain_precision_modes"nvfp4"appended to the frontend fallback array|| m === "nvfp4"added to the frontend filter whitelist"nvfp4"added to thebase_precisionLiteralimages-page.tsx[1920, 1080]added toFALLBACK_RESOLUTION_PRESETSresolution_presets = ()on a familyresolutionPresetsmemo rebound to the hardcoded fallback_LoadStategiven the request instead of the engaged value"transformer_quant"added to_REQUIRED_METARecipePopoverOne earlier break attempt did not fail, correctly:
ImageGenerationRequesthas notransformer_quantfield, so the code fell through toresult.get(...)and behaviour was unchanged. Redone with a real request-sourced value.Testing
Baseline at the base commit, same selection and ignores: 1583 passed, 8 skipped, zero failures, so nothing here is pre-existing-broken.
1633 minus 1583 is exactly the 50 tests added. Cross-platform CI green on ubuntu, macOS and Windows.
One fix was needed after CI. The metadata tests installed
torchas a bareModuleType, which has no__path__, soimport torch.nn.functionalinsidediffusion_eager_patchescannot resolve. It passed locally only becauseconftest.pyseeds real torch throughhf_xet_fallback._load_optionalintounsloth_zoo.utils, which is installed here and absent on CI. The stubs are now real packages with registered submodules, installed viamonkeypatch.setitemso nothing leaks between tests.Observations, not fixed
precisionModesprepends"auto"unconditionally whenever the backend reports a non-empty list, buttrain_precision_modes()omits"auto"on a pre-Ampere CUDA GPU. Unreachable today, because on such a hostbf16_unsupported_reason()fires, every DiT family reports an empty list, and the untrainable branch wins before the prepend runs.test_diffusion_backend.py'sfake_runtimefixture has the same bare-ModuleTypeflaw. It is green because it is not in the CPU-only CI selection, but it will break when it is. Left alone to keep this branch to its three files.