Skip to content

Pin the training precision, video preset and image metadata contracts - #8162

Merged
danielhanchen merged 14 commits into
mainfrom
nv/tests-contracts
Aug 9, 2026
Merged

danielhanchen merged 14 commits into
mainfrom
nv/tests-contracts

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 8, 2026 •

Copy link
Copy Markdown
Member

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 (inference transformer_quant and text_encoder_quant Literals, plus TE_QUANT_MODES) minus sentinels minus the training Literal, which resolves to {nvfp4, fp8_dynamic}. An anchor test pins nvfp4 into 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 whole precisionModes memo from diffusion-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's width 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 _LoadState rather than the request. Two divergent-load scenarios are exercised against the real DiffusionBackend, plus a route-level round-trip capturing the exact dict handed to image_gallery.save, and a freeze on _REQUIRED_META so 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.

Deliberate break Result
modes.append("nvfp4") in train_precision_modes 4 failed
"nvfp4" appended to the frontend fallback array 2 failed
|| m === "nvfp4" added to the frontend filter whitelist 2 failed
"nvfp4" added to the base_precision Literal 2 failed
NVFP4 deleted from images-page.tsx 1 failed, guarding against "fixing" this by removing legitimate inference NVFP4
[1920, 1080] added to FALLBACK_RESOLUTION_PRESETS 1 failed
resolution_presets = () on a family failed with the IndexError message
An LTX-2 preset moved off the /32 grid 2 failed
resolutionPresets memo rebound to the hardcoded fallback 1 failed
_LoadState given the request instead of the engaged value 2 failed
Route persisting the requested quant 1 failed
The three build keys deleted from the route's persist dict 1 failed
"transformer_quant" added to _REQUIRED_META 2 failed, including an old-schema PNG no longer listing
Quant row deleted from RecipePopover 1 failed

One earlier break attempt did not fail, correctly: ImageGenerationRequest has no transformer_quant field, so the code fell through to result.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.

python -m pytest studio/backend/tests -k "contract or precision or video or train" -q \
  --ignore=studio/backend/tests/test_mcp_server.py \
  --ignore=studio/backend/tests/test_rag_ocr_fallback.py

1633 passed, 8 skipped, 16869 deselected

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 torch as a bare ModuleType, which has no __path__, so import torch.nn.functional inside diffusion_eager_patches cannot resolve. It passed locally only because conftest.py seeds real torch through hf_xet_fallback._load_optional into unsloth_zoo.utils, which is installed here and absent on CI. The stubs are now real packages with registered submodules, installed via monkeypatch.setitem so nothing leaks between tests.

Observations, not fixed

  • precisionModes prepends "auto" unconditionally whenever the backend reports a non-empty list, but train_precision_modes() omits "auto" on a pre-Ampere CUDA GPU. Unreachable today, because on such a host bf16_unsupported_reason() fires, every DiT family reports an empty list, and the untrainable branch wins before the prepend runs.
  • test_diffusion_backend.py's fake_runtime fixture has the same bare-ModuleType flaw. 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.

Daniel Han and others added 5 commits August 8, 2026 08:48
… 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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 8, 2026 13:38
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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

- /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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e9b21e9288

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 5d461d7 into main Aug 9, 2026
48 of 55 checks passed
@danielhanchen
danielhanchen deleted the nv/tests-contracts branch August 9, 2026 08:24
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
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