Skip to content

Studio: keep torchao quantisation from mutating inductor config, and make its int8 GEMM capture-safe - #10525

Merged
danielhanchen merged 10 commits into
mainfrom
studio-torchao-quiet-inductor
Sep 9, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
studio-torchao-quiet-inductor

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Two fixes on Studio's torchao int8 / fp8 diffusion path, both found while measuring CUDA-graph capture of the int8 transformer.

1. torchao quantize_ no longer rewrites inductor config for the whole process. Every torchao config Studio builds (Int8DynamicActivationInt8WeightConfig, Float8DynamicActivationFloat8WeightConfig, Int8WeightOnlyConfig) defaults to set_inductor_config=True, so each quantised Linear called torchao.quantization.utils.recommended_inductor_config_setter(). That sets coordinate_descent_tuning, coordinate_descent_check_all_directions, force_fuse_int_mm_with_mul, fx_graph_cache, triton.unique_kernel_names and torch.set_float32_matmul_precision("high"), process-wide and permanently, and it also fired from the smoke probe before the user had chosen a precision. The fp32 matmul precision change reaches every fp32 op in the pipeline, not just the quantised layers, and the compile flags outlive the load that caused them. diffusion_speed.py owns the inductor policy; a quantise call should not reset it.

  • diffusion_transformer_quant._quiet_config builds a config with set_inductor_config=False when the class accepts it (signature-guarded, so older or prototype configs without the field are constructed exactly as before). Every torchao config in studio/backend goes through it, including the text-encoder casts and the DiT trainer's Int8WeightOnlyConfig. UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1 restores the upstream default for A/B benchmarking.
  • snapshot_backend_flags / restore_backend_flags now also capture the six inductor flags and the fp32 matmul precision (restored first, since some builds write allow_tf32 from it), as the safety net behind the quiet configs.
  • video.py snapshots and registers the flags before the transformer quant, the first site in that loader that could mutate them. diffusion.py keeps its snapshot adjacent to the try/finally that restores it and documents why.

2. torchao's int8 GEMM no longer syncs the device on every call, and it can be CUDA-graph captured. torchao/kernel/intmm.py::safe_int_mm decides whether it is being traced with "FakeTensor" in input.__repr__(). On a real CUDA tensor Tensor.__repr__ formats the values, which copies to host: a device sync per eager int8 W8A8 matmul, and cudaErrorStreamCaptureUnsupported under torch.cuda.graph. The patch replaces the probe with torch._subclasses.fake_tensor.is_fake and is otherwise a verbatim copy of the torchao 0.17 body; it is bit-identical on the bare GEMM, a compiled Linear and a whole compiled transformer. Present in torchao 0.17.0 and 0.18.0.

  • unsloth/import_fixes.py::fix_torchao_safe_int_mm_repr_probe, wired from _gpu_init.py, in the style of the other torchao fixes: structural gate on the upstream body (refuses to patch a body it does not recognise), a meta-path finder so a torchao imported later is still covered, UNSLOTH_TORCHAO_INT_MM_FIX=0 kill switch.
  • studio/backend/core/inference/diffusion_torchao_patches.py carries the same body for the diffusion process, which does not import unsloth. The two copies are mutually inert through the patched-function sentinel, and a parity test keeps them identical.
  • torchao main has moved safe_int_mm to torchao.quantization.quantize_.workflows.int8.kernels with the probe intact (the body is otherwise the same from 0.10.0 through 0.18.0 and on main), so the finder and the install-time sweep cover both module names.

Measurements

z-image Turbo, unsloth/Z-Image-Turbo-GGUF Q4_K_M with the dense transformer quant engaged, 1024px, 9 steps, seed 12345, B200, scripts/diffusion_bench.py, six generations per process (first one includes compile). ON is torchao's default (UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1), OFF is this PR. Each process has its own cold inductor cache.

scheme, speed arm first render (compile) steady-state median image vs ON run 1
fp8, default ON x2 7.07 s, 6.82 s 0.540 s, 0.551 s identical
fp8, default OFF x2 7.56 s, 7.71 s 0.552 s, 0.558 s identical
int8, default ON x2 8.39 s, 8.63 s 0.530 s, 0.535 s identical
int8, default OFF x2 9.00 s, 8.35 s 0.532 s, 0.549 s identical
fp8, max ON x2 25.1 s, 23.9 s 0.538 s, 0.534 s differ (20.8 dB)
fp8, max OFF x2 26.9 s, 26.2 s 0.544 s, 0.530 s differ (22.4 / 20.2 dB)
int8, max ON x2 30.7 s, 33.2 s 0.522 s, 0.522 s identical
int8, max OFF x2 30.7 s, 32.7 s 0.519 s, 0.523 s differ (20.1 / 39.6 dB)

Coordinate descent OFF costs nothing measurable: steady state is within the ON run-to-run spread (ON repeats differ by 1 to 2% themselves) and compile time is unchanged. The max tier renders differently across processes with either setting, because max-autotune picks kernels by timing; that is independent of this PR.

Upgrade scenario, default tier, an inductor cache first populated by two torchao-default processes and then reused by two processes with this PR, plus two with their own fresh cache: all six render the identical image, steady state within -0.5% to +3.3% of the seeded run.

Cross-process instability was observed when the machine-wide default inductor cache (/tmp/torchinductor_<user>) was shared with other processes: the same seed rendered a different image after a restart under torchao's default (int8 default 23.4 dB, fp8 max 25.1 dB apart) while runs with this PR reproduced the first image. That series is not fully controlled and is reported as observed; the controlled series above is the basis for the speed claim.

Fix 2, scripts/g832/bench832.py, z-image int8, CUDA-graph capture of the denoiser step, output bit-identical to eager:

resolution eager graphed gain
512px 0.296 s 0.199 s 1.49x
1024px 0.518 s 0.500 s 1.04x

Without the patch the capture fails at the first int8 linear.

Live Studio, before and after

Two Studio installs on this machine, PR merge base and PR head, same model (unsloth/Z-Image-Turbo-GGUF Q4_K_M with transformer_quant=int8), same prompt and seed, driven through the UI and the API by scripts/pr_ui_scenes/int8_determinism.py. Each side renders the seed in one process, then stops that Studio, starts it again, loads the same model and renders the seed once more. Decoded pixels compared.

run side process 1 (UI, API, API repeat) process 2 after restart pixel diff vs process 1
1 merge base identical different max 206, mean 5.04
1 this PR identical identical 0
2 merge base identical identical 0
2 this PR one API render differs identical max 6, mean 0.10 on the odd render

Run 1 is the divergence this PR removes: on the merge base the restarted process compiled different reduction kernels and the same seed rendered a visibly different picture (see composite). Run 2 on the merge base reproduced the first image, which the scene documents as a null: the divergence depends on the inductor cache state torchao's config churn leaves behind, so it does not fire every time. The odd render in run 2 on the PR head is a max 6 out of 255 wobble on a quarter of the pixels inside one process with no recompile in between, which is ordinary CUDA kernel nondeterminism and not the compile-time effect this PR addresses; it happened once in sixteen renders across both runs.

restart evidence

Generating in the UI on the PR head (int8, 1024px, first render includes compile, about 10 s):

ui recording

Tests

  • studio/backend/tests/test_diffusion_transformer_quant.py: quiet configs against stubbed and real torchao, env override, unintrospectable class, prototype configs unchanged.
  • studio/backend/tests/test_diffusion_speed.py: snapshot and restore of the new flags, restore order, tolerant of builds lacking them, video.py snapshots before it quantises (lineno check).
  • studio/backend/tests/test_diffusion_precision.py: text-encoder casts go through the factory; AST guard that no torchao config is constructed outside _quiet_config.
  • studio/backend/tests/test_torchao_intmm_patch_wiring.py: the patch is installed at every torchao entrypoint, the Studio copy matches import_fixes.py, both module names are covered, idempotence, refusal on an unrecognised body, CPU bit-identity.
  • tests/test_import_fixes_drift.py: canary that upstream still has the probe (so the fix can be retired when it is gone), body markers, bit-identity, idempotence, late-import coverage under either module name, the installer against a copy registered under the new name, _gpu_init.py wiring.

Full studio/backend/tests on this branch: 38382 passed, 126 failed, 215 skipped. Every failing file fails with the same counts on the merge base (bd1228fbd) when run file by file, so none of the failures come from this PR; hub/tests 682 passed; tests/test_import_fixes_drift.py 32 passed, 4 skipped.

Cross-platform, the changed test files under the CUDA spoof on a staging fork: macos-14 green, windows-latest green, Studio Playwright smoke green; ubuntu-latest was still queued behind the fork's runner backlog when this was written and is covered by the full local run above.

Not changed

The LM-side QAT path (unsloth/models/_utils.py) also passes a torchao config with the default set_inductor_config=True. It fires at QAT convert on a model about to be exported, which is the workload those flags are tuned for, and the LM trainer has no bit-identity contract, so it is left alone here.

…se, and snapshot the inductor flags torchao flips

torchao's Int8DynamicActivationInt8WeightConfig, Float8DynamicActivationFloat8WeightConfig and
Int8WeightOnlyConfig default to set_inductor_config=True, so each quantised Linear called
recommended_inductor_config_setter(): coordinate_descent_tuning,
coordinate_descent_check_all_directions, force_fuse_int_mm_with_mul, fx_graph_cache,
triton.unique_kernel_names and torch.set_float32_matmul_precision("high"), process-wide and
permanent. Coordinate-descent tuning picks reduction kernels by timing, so two identical
processes compiled different kernels for the norms and the same seed rendered differently
(max abs 0.83 on the z-image transformer output; bit-identical with the flags left alone).
The leak also fired from the smoke probe before any user opted into quantisation.

- diffusion_transformer_quant._quiet_config builds a config with set_inductor_config=False
  when the class accepts it (signature-guarded; the prototype NVFP4 / MX configs lack the
  field and never call the setter). Every constructor in Studio goes through it, including
  the text-encoder casts and the DiT trainer's Int8WeightOnlyConfig.
  UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1 restores the upstream default for A/B benchmarking.
- diffusion_speed.snapshot_backend_flags / restore_backend_flags now also capture the six
  inductor flags and the fp32 matmul precision (restored first, since some builds write
  allow_tf32 from it), as the safety net behind the quiet configs.
- video.py snapshots and registers the flags before the transformer quant, the first site
  in that loader that could mutate them; diffusion.py keeps its snapshot adjacent to the
  try/finally that restores it and documents why.

Tests: quiet configs (stubbed and real torchao, env override, unintrospectable class,
prototype configs untouched), an AST guard that no torchao config is constructed outside
_quiet_config, snapshot/restore round trips for the new flags and the restore order, and a
lineno check that video.py snapshots before it quantises.
… nor breaks CUDA-graph capture

torchao/kernel/intmm.py::safe_int_mm decides whether it is being traced with
`dynamo_is_compiling() or "FakeTensor" in input.__repr__()`. Tensor.__repr__ formats the
values, so on a real CUDA tensor every eager int8 W8A8 matmul pays a host copy (a device
sync), and under torch.cuda.graph the same call raises cudaErrorStreamCaptureUnsupported,
which is what stopped Studio's int8 diffusion transformer from being captured. Asking
torch._subclasses.fake_tensor.is_fake answers the same question without touching the data;
the replacement is otherwise a verbatim copy of the torchao 0.17 body and is bit-identical
on the bare GEMM, a compiled Linear and a whole compiled transformer. Present in torchao
0.17.0 and 0.18.0.

- unsloth/import_fixes.py: fix_torchao_safe_int_mm_repr_probe, wired from _gpu_init.py.
  Structural gate on the upstream body (every verified landmark must be present, else it
  is left alone), rebinding on the module and on the torchao re-exports, a meta path
  finder so a torchao imported later is covered (the int8 prequant path only torch.loads
  torchao subclasses and never calls quantize_), UNSLOTH_TORCHAO_INT_MM_FIX=0 kill switch.
- studio/backend/core/inference/diffusion_torchao_patches.py: the same body for the
  diffusion process, which does not import unsloth. Installed at module level in
  diffusion.py, video.py, diffusion_transformer_quant.py (so the spawned smoke-probe child
  gets it) and diffusion_train_common.py. The two copies are mutually inert through the
  patched-function sentinel.

Tests: tests/test_import_fixes_drift.py (canary that upstream still has the probe, body
markers, CPU bit-identity, idempotence, refusal on an unrecognised body, late-import
coverage in a subprocess, _gpu_init wiring) and
studio/backend/tests/test_torchao_intmm_patch_wiring.py (all four entrypoints install it,
AST parity between the two copies, idempotence, refusal, real-torchao bit-identity).
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the torchao configs in studio/backend all defaulted to set_inductor_config=True so a quantise call reset the process-wide inductor policy that diffusion_speed.py owns, and the safe_int_mm repr probe does sync per call. Will get this reviewed once it is out of draft.

torchao main moved safe_int_mm from torchao/kernel/intmm.py into
torchao/quantization/quantize_/workflows/int8/kernels.py with the
__repr__ probe intact, so a finder that only knew the old dotted name
would lose the fix on the next release. Both module names are now
covered by the finder and by the install-time sweep, in both homes of
the patch. The body is the same from torchao 0.10.0 through 0.18.0 and
on main, so the structural gate is unchanged.

Tests follow whichever module the installed torchao defines, and two
new tests pin the module table and exercise the installer against a
copy registered under the new name.
…nto studio-torchao-quiet-inductor

# Conflicts:
#	studio/backend/core/inference/diffusion_torchao_patches.py
#	unsloth/import_fixes.py
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review September 8, 2026 17:24
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-09T07:26:57.851987Z b91d486 Manual request
ℹ️ About Codex in GitHub

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

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

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Second pass over the comments this branch adds: delete the ones that only restate the code, and collapse the rest to one line each. The safe_int_mm replacement body is edited identically in both copies, so unsloth/import_fixes.py and the Studio copy stay interchangeable.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 5b6397c350

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b91d486d1c

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +4329 to 4330
# The dense transformer quant above builds quiet configs, so it mutated none of these flags.
backend_flags_before = snapshot_backend_flags()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Snapshot flags before image transformer quantization

When UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1 is set—or _quiet_config cannot inspect a config class—the earlier _load_dense_quant_pipeline call constructs a config with set_inductor_config=True, so quantize_transformer mutates the process-wide Inductor and matmul settings before this snapshot. The snapshot therefore records the mutated values, and unloading or rolling back the image load restores those values rather than the pre-load state, affecting later pipelines. The video loader already avoids this by snapshotting before transformer quantization; the image loader needs the same ordering.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked specifically: every config the image loader builds before the snapshot goes through quiet_config (both quantize sites call _make_quant_config, which returns _quiet_config on every branch, and _load_dense_quant_pipeline calls nothing else in torchao), those classes are plain dataclasses in torchao 0.10 through 0.18 and main so inspect.signature never raises, and every recommended_inductor_config_setter call in quant_api.py is gated on config.set_inductor_config. The only way to reach the mutation is UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1, the documented A/B override, and the text-encoder casts already run after the snapshot.

Comment on lines +4329 to 4330
# The dense transformer quant above builds quiet configs, so it mutated none of these flags.
backend_flags_before = snapshot_backend_flags()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Snapshot flags before image transformer quantization

When UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1 is set—or _quiet_config cannot inspect a config class—the earlier _load_dense_quant_pipeline call constructs a config with set_inductor_config=True, so quantize_transformer mutates the process-wide Inductor and matmul settings before this snapshot. The snapshot therefore records the mutated values, and unloading or rolling back the image load restores those values rather than the pre-load state Genius IRequest, affecting later pipelines. The video loader already avoids this by snapshotting before transformer quantization; the image loader needs the same ordering.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked specifically: every config the image loader builds before the snapshot goes through quiet_config (both quantize sites call _make_quant_config, which returns _quiet_config on every branch, and _load_dense_quant_pipeline calls nothing else in torchao), those classes are plain dataclasses in torchao 0.10 through 0.18 and main so inspect.signature never raises, and every recommended_inductor_config_setter call in quant_api.py is gated on config.set_inductor_config. The only way to reach the mutation is UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1, the documented A/B override, and the text-encoder casts already run after the snapshot.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 9, 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b91d486d1c

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines 80 to +84
inductor_cfg = _inductor_config()
if inductor_cfg is not None and hasattr(inductor_cfg, "emulate_precision_casts"):
state["inductor_emulate_precision_casts"] = bool(inductor_cfg.emulate_precision_casts)
if inductor_cfg is not None:
for attr, key in _INDUCTOR_FLAGS:
if hasattr(inductor_cfg, attr):
state[key] = bool(getattr(inductor_cfg, attr))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Import Inductor before snapshotting its flags

In a fresh server process where torch._inductor has not yet been imported, _inductor_config() returns None, so this newly added block records none of the Inductor settings. The video loader now deliberately takes this snapshot before its first quantize_; if UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1 is enabled, or a config class cannot be introspected and retains the upstream default, that quantization can import Inductor and mutate these process-wide flags, but unload/rollback has no saved keys with which to restore them. Ensure the snapshot loads torch._inductor.config (defensively) before reading the new flags, or otherwise initialize it before the pre-quant snapshot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_inductor_config() does not only look in sys.modules: _inductor is in torch.init's _lazy_modules in torch 2.6 through 2.10 and main, so getattr(torch, "_inductor", None) runs importlib.import_module and the snapshot imports inductor itself. Verified in a process where torch was not yet imported: all six inductor keys are captured and torch._inductor.config enters sys.modules during the snapshot. A real load has also already imported it through torchao.quantization, and the attribute form is deliberate so a stubbed torch reports None rather than a stale sys.modules hit.

@danielhanchen
danielhanchen merged commit ff9206a into main Sep 9, 2026
44 of 45 checks passed
@danielhanchen
danielhanchen deleted the studio-torchao-quiet-inductor branch September 9, 2026 07:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant