Repository navigation
Studio: keep torchao quantisation from mutating inductor config, and make its int8 GEMM capture-safe - #10525
Conversation
…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).
|
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
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. |
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.
|
@codex security review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
There was a problem hiding this comment.
💡 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".
| # The dense transformer quant above builds quiet configs, so it mutated none of these flags. | ||
| backend_flags_before = snapshot_backend_flags() |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| # The dense transformer quant above builds quiet configs, so it mutated none of these flags. | ||
| backend_flags_before = snapshot_backend_flags() |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
_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.
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 toset_inductor_config=True, so each quantised Linear calledtorchao.quantization.utils.recommended_inductor_config_setter(). That setscoordinate_descent_tuning,coordinate_descent_check_all_directions,force_fuse_int_mm_with_mul,fx_graph_cache,triton.unique_kernel_namesandtorch.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.pyowns the inductor policy; a quantise call should not reset it.diffusion_transformer_quant._quiet_configbuilds a config withset_inductor_config=Falsewhen the class accepts it (signature-guarded, so older or prototype configs without the field are constructed exactly as before). Every torchao config instudio/backendgoes through it, including the text-encoder casts and the DiT trainer'sInt8WeightOnlyConfig.UNSLOTH_TORCHAO_INDUCTOR_CONFIG=1restores the upstream default for A/B benchmarking.snapshot_backend_flags/restore_backend_flagsnow also capture the six inductor flags and the fp32 matmul precision (restored first, since some builds writeallow_tf32from it), as the safety net behind the quiet configs.video.pysnapshots and registers the flags before the transformer quant, the first site in that loader that could mutate them.diffusion.pykeeps 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_mmdecides whether it is being traced with"FakeTensor" in input.__repr__(). On a real CUDA tensorTensor.__repr__formats the values, which copies to host: a device sync per eager int8 W8A8 matmul, andcudaErrorStreamCaptureUnsupportedundertorch.cuda.graph. The patch replaces the probe withtorch._subclasses.fake_tensor.is_fakeand 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=0kill switch.studio/backend/core/inference/diffusion_torchao_patches.pycarries the same body for the diffusion process, which does not importunsloth. The two copies are mutually inert through the patched-function sentinel, and a parity test keeps them identical.safe_int_mmtotorchao.quantization.quantize_.workflows.int8.kernelswith 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-GGUFQ4_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.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
maxtier renders differently across processes with either setting, because max-autotune picks kernels by timing; that is independent of this PR.Upgrade scenario,
defaulttier, 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: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-GGUFQ4_K_M withtransformer_quant=int8), same prompt and seed, driven through the UI and the API byscripts/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 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.
Generating in the UI on the PR head (int8, 1024px, first render includes compile, about 10 s):
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.pysnapshots 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 matchesimport_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.pywiring.Full
studio/backend/testson 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/tests682 passed;tests/test_import_fixes_drift.py32 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 defaultset_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.