Repository navigation
Studio: fix FLUX.2 Klein LoRA training quality - #8267
danielhanchen merged 18 commits into
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5da8ab594a
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Reconciliation with #8263Heads up on ordering first: #8263 merged as Overlap 1, identical. Both add Overlap 2, and this one is not identical. Both make training resolve the dense size from the base the run actually trains from rather than the family number. #8263 landed
So the clean resolution is: drop both hunks from this PR and rebase onto main. On the rest of the PREverything below is verified, not read off the diff. Target modules. This is the part I got wrong in #8263, where I wrote off the missing single-block target_modules = ["to_k", "to_q", "to_v", "to_out.0"] + [
"to_qkv_mlp_proj",
*[f"single_transformer_blocks.{i}.attn.to_out" for i in range(24)],
]and
The 56 for klein-base-9B is the same number my 500 step run produced, so the harness agrees with the live run. On the 4B the four targets for blocks 20 to 23 match nothing, PEFT ignores them silently because other targets hit, and the comment in the diff already says so. Worth noting this fixes Base versus distilled training checkpoint. Also correct, and it is worth recording that the references disagree here: the diffusers README actually exports Generation defaults. Both match the vendor cards. Two things I would still change
What this PR does not coverOf the divergences I listed against the references, this fixes the training base and the target modules. Still open: the 500 steps at 512 with grad-accum 1 default against the reference's 1024 with grad-accum 4, and the inert warmup default, which turns out to affect four families and is now #8269. One correction to my own earlier note, since it would otherwise send someone down a dead end. I had flagged Cross-family audit in the next comment. |
Cross-family auditI took the defect classes this PR and #8263 are about and checked every LoRA training path Studio has, so we know whether Klein was special or the tip of something. Families enumerated from Method, so the confidence level per row is clear. Sizes are the summed Class A: one
|
| family | checkpoints in family | transformer bf16 | verdict |
|---|---|---|---|
| sdxl | SDXL base 1.0 | n/a, own mixed_precision path, no dense_bf16_gb |
clean (source) |
| flux.1 | FLUX.1-dev | 23.80 GB vs spec 23.8 | clean (measured) |
| qwen-image | Qwen-Image, Qwen-Image-2512 | 40.86 GB and 40.86 GB vs spec 41.0 | clean, both sizes identical (measured) |
| z-image | Z-Image-Turbo | 12.3 GB resident, 24.62 GB on disk because it ships fp32, and _FAMILY_HUB_DOWNLOAD_FACTOR already carries the 2.0 |
clean (measured) |
| krea-2 | Krea-2-Raw, Krea-2-Turbo | 26.28 GB and 26.28 GB vs spec 26.3 | clean, both sizes identical (measured) |
| flux.2-klein | base-4B, base-9B, 4B, 9B | 7.75 GB vs 18.16 GB | the bug, fixed by #8263 (measured) |
| flux.2-dev | FLUX.2-dev | 64.45 GB vs spec 64.5 | clean (measured) |
Klein is the only multi-size family. Nothing else to chase.
Class B: a per-base override present on one side and missing on the other
_BASE_REPO_BF16_GB holds exactly two entries, both Klein 9B, and since #8263 the DiT trainer reads that same table through _dense_bf16_gb, so the two sides cannot drift by construction. Every other family is single-size and needs no override. Clean everywhere (source, plus the regression tests in #8263).
Class C: target modules that do not match, or silently match nothing
| family | targets | linear modules | wrapped | matching nothing | verdict |
|---|---|---|---|---|---|
| sdxl | to_k, to_q, to_v, to_out.0 |
743 | 560 | none | clean (measured) |
| flux.1 | 8 incl. add_*_proj, to_add_out |
504 | 266 | none | clean (measured) |
| qwen-image | same 8 | 846 | 480 | none | clean (measured) |
| z-image | to_k, to_q, to_v, to_out.0 |
276 | 136 | none | clean (measured), and identical to the upstream train_dreambooth_lora_z_image.py list |
| krea-2 | 15, incl. ff.up/down, text_fusion.projector, time_mod_proj |
264 | 232 | none, all 15 live | clean (measured) |
| flux.2-klein | main misses the single-block to_out |
153 (9B) | 56, this PR 80 | 4 dead on the 4B, harmless | fixed by this PR (measured) |
| flux.2-dev | same gap | 203 | 80, this PR 128 | none | fixed by this PR (measured) |
Worth calling out that krea-2's 15-name list is fully live, including the singletons: img_in, final_layer.linear, text_fusion.projector, txt_in.linear_1/2, time_embed.linear_1/2, time_mod_proj each wrap exactly one module. Nothing there is a typo that silently drops.
Class D: lr_warmup_steps set with a scheduler that ignores it
| family | warmup default | default scheduler | verdict |
|---|---|---|---|
| sdxl | none | constant | clean |
| flux.1 | 20 | constant | no-op |
| qwen-image | 20 | constant | no-op |
| z-image | none | constant | clean |
| krea-2 | none | constant | clean |
| flux.2-klein | 20 | constant | no-op |
| flux.2-dev | 20 | constant | no-op |
Measured. get_scheduler returns schedule_func(optimizer) for SchedulerType.CONSTANT before it looks at num_warmup_steps, so with warmup 20 over 500 steps at base LR 1e-4 the LR is 1.00e-04 at step 1, while constant_with_warmup gives 5.00e-06. Filed as #8269 with the full trace and the two candidate fixes. Not Klein-specific and not something this PR needs to absorb.
Class E: flow_shift fixed where the scheduler uses dynamic shifting
| family | use_dynamic_shifting |
Studio default | verdict |
|---|---|---|---|
| sdxl | n/a, EulerDiscreteScheduler, not flow matching |
n/a | clean (measured) |
| flux.1 | true | 1.0 | matches the reference (measured) |
| qwen-image | true | "auto" |
the only family that shifts, a deliberate departure from upstream |
| z-image | false, static shift baked into sigmas at init |
1.0 | correct, 1.0 returns the already-shifted table (measured) |
| krea-2 | true, Raw and Turbo identical | 1.0 | matches the reference (measured) |
| flux.2-klein | true | 1.0 | matches the reference (measured) |
| flux.2-dev | true | 1.0 | matches the reference (measured) |
This class produced nothing, and it retracts my earlier claim rather than confirming it. The upstream DreamBooth scripts for Klein, FLUX.2-dev and Qwen-Image all read noise_scheduler_copy.sigmas unshifted, so five families having use_dynamic_shifting: true with flow_shift=1.0 is upstream convention, not a defect. Z-Image is the interesting one in the opposite direction: because its shift is static it is baked in at init, so 1.0 is not "no shift" there, it is the family's own shift, which is what _training_sigma_table's docstring already says.
Class F: default base pointing at a distilled checkpoint
| family | train base | distilled? | verdict |
|---|---|---|---|
| sdxl | SDXL base 1.0 | no | clean (source) |
| flux.1 | FLUX.1-dev | no | clean (source) |
| qwen-image | Qwen-Image plus its nf4 mirror | no | clean (source) |
| z-image | Z-Image-Turbo only | yes | defect, see below |
| krea-2 | Krea-2-Raw, previews on Turbo | no | clean, and the precedent this PR follows (source) |
| flux.2-klein | klein-4B, distilled | yes | fixed by this PR |
| flux.2-dev | FLUX.2-dev | no | clean (source) |
Z-Image is the one genuine finding outside Klein. train_base_repos is ("unsloth/Z-Image-Turbo-unsloth-bnb-4bit", "Tongyi-MAI/Z-Image-Turbo"), both distilled, while every training block in the upstream README_z_image.md exports MODEL_NAME="Tongyi-MAI/Z-Image". That base repo exists, is ungated, apache-2.0, same ZImagePipeline and ZImageTransformer2DModel, same in_channels, full pipeline layout, and it differs from Turbo only in the scheduler's static shift, 6.0 against 3.0, which flow_shift=1.0 already handles. It is also absent from _TRUSTED_NON_GGUF_REPOS, so a user cannot even reach it by typing it into the custom-base field. Filed as #8270. It needs the same treatment this PR gives Klein, and I have not trained it end to end, so unlike Klein there is no quality measurement behind it yet, only the reference mismatch.
Summary
Two of the six classes fire. Class A is Klein alone and is already merged. Class C is Klein and FLUX.2-dev, and this PR fixes both correctly against the reference. Class D is a four-family no-op that nobody has hit yet because the UI never seeds the field, now #8269. Class F is Klein, which this PR fixes, and Z-Image, now #8270. Classes B and E are clean across all seven paths, and E in fact retracts one of my earlier claims.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0cd2201711
ℹ️ 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".
| normalized_cfg.fetch_base_model or normalized_cfg.base_model, | ||
| normalized_cfg.hf_token, |
There was a problem hiding this comment.
Preserve the gated-base check before starting the child
When FLUX.1-dev or FLUX.2-dev is started without an HF token, prefer_ungated_mirror makes this preflight probe the public mirror and succeed, but run_dit_lora_training still calls _assert_gated_access with the canonical gated ID and raises. The route therefore returns success, evicts the resident GPU models, and only then reports a failed training job instead of rejecting the request before eviction; either preflight the canonical access requirement as well or make the child consistently accept the mirror.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in bb39f3f93. The route preflights the fetch repo while run_dit_lora_training checked the canonical id, so FLUX.1-dev or FLUX.2-dev without a token gets a 200, loses the resident models, and only then hits the name check in the child. Took your second option: the child now checks cfg.fetch_base_model or cfg.base_model, so a mirror-backed run proceeds and the two agree. When no mirror is selected the canonical id is still what gets checked, so a genuinely gated fetch keeps failing in the route before anything is evicted. Both directions are asserted in test_the_gate_reads_the_repo_the_run_will_fetch, and restoring the canonical id fails it.
| resolution = int(cfg.resolution), | ||
| kind = kind, | ||
| base_revision = source_revision(cfg.base_model), | ||
| base_revision = source_revision(revision_base_model), |
There was a problem hiding this comment.
Keep resume revisions stable across mirror selection
When a checkpoint is resumed after the upstream Hub cache was removed or on another host, normalization can switch the same canonical base from the upstream repo to its byte-identical mirror. source_revision records repository commit SHAs rather than weight content, so the mirror has a different rev-* value and mismatch_reason refuses the checkpoint as a different base revision; this also affects pre-existing FLUX.1, Qwen, and Krea checkpoints created before training began using mirrors. Derive a stable revision identity for canonical/mirror pairs rather than recording whichever fetch repository happens to be selected from the local cache state.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in bb39f3f93. prefer_ungated_mirror chooses on local cache state, so the recorded revision moved when the upstream snapshot was evicted or the run changed machine, and pre-mirror checkpoints hold the canonical value anyway. Rather than derive a shared identity for the pair, identity_for_config and the post-load with_resolved_revision both go back to the canonical id: the two repos are byte identical, so the canonical commit is a valid marker for either, and a canonical repo with no local ref records "unresolved", which mismatch_reason already skips. test_a_mirror_backed_run_records_the_canonical_revision asserts the two identities do not refuse each other; reading the fetch repo fails it.
|
Went through the three open items and re-baselined this branch. All three are already handled on the current head, so this is confirmation rather than new work. The three itemsMirror the new 9B training base before loading. Handled. The swap at Split the 9B training metadata from the 4B entry. Handled. Update the existing OpenAI default test. Handled. Backend evidenceHead against this branch's merge base ( FAILED and ERROR line sets identical. The +6 passed are this branch's own tests. Merged main inThe Python 3.12 and 3.13 checks were red and the 3.10 and 3.11 ones were cancelled at the 15 minute timeout, which Re-ran the whole suite on the merged head: |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0cd2201711
ℹ️ 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".
| # Families with several train/deploy pairs cannot use the scalar above. | ||
| "deploy_bases": deploy_bases, | ||
| # Checkpoint-specific facts overlay the family facts in the Train UI. | ||
| "base_specs": base_specs, |
There was a problem hiding this comment.
Preserve the GPU-block reason for the 9B base
When dit_block is set on a CPU-only or pre-Ampere host, the family-level chip fields are intentionally cleared so the Train UI displays vram_note containing the actionable hardware reason. However, this still publishes the 9B base_specs; after the user selects Klein base-9B, resolveDiffusionTrainingFacts restores the 9B/18 GB chips, causing FamilyFacts to skip vram_note. The UI then shows only the generic “cannot train” message instead of explaining whether CUDA or native bf16 support is missing. Suppress base_specs while dit_block is active, or ensure the client continues rendering the block reason.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and confirmed in both halves of the path. Fixed in b737169cb.
Backend: params, qlora_vram_gb, gated and note are all cleared on a dit_block, but base_specs went out unconditionally.
Frontend: resolveDiffusionTrainingFacts gives the per-base entry priority over the family facts, and base_specs entries carry non-null params and qlora_vram_gb, so the chips come back. FamilyFacts then computes hasChips = Boolean(facts.params || facts.qlora_vram_gb || facts.gated) and only renders vram_note in the !hasChips branch. So on a CPU-only or pre-Ampere host, selecting Klein base-9B swaps "no bfloat16 on this GPU" for a 9B chip and a QLoRA 18GB+ VRAM chip, neither of which the user can act on.
base_specs feeds nothing but those chips (resolveDiffusionTrainingFacts is its only consumer, in the panel and in its own test), so clearing it on the same condition costs nothing else.
The test pins a bf16-unsupported host and asserts the overlay is empty and vram_note still carries the reason. It also asserts a per-base overlay exists on an unblocked host before doing that, so it cannot pass because the fixture happened to produce none. Fails with the fix reverted, passes with it; test_diffusion_base_precision.py 43 passed, and the diffusion training suites 176 passed.
|
Screenshots for the user-visible half, two isolated installs, merge base The Base model list2 options to 3: the single distilled The facts chips, after picking the 9B base
Worth being explicit about what this second shot required, because it is the part that could have been faked without anyone noticing: the family-level Numbers from the same servers that were photographed
The |
…he UI A dit_block clears the family-level chip fields (params, qlora_vram_gb, gated, note) precisely so FamilyFacts falls through to vram_note, which carries the actionable reason: no CUDA, or no native bf16 on this GPU. base_specs was still published though, and the per-base entry wins in resolveDiffusionTrainingFacts, so selecting Klein base-9B on a blocked host put the 9B and 18 GB chips straight back. FamilyFacts renders vram_note only when there are no chips, so the user lost the explanation and got a generic refusal plus a size they cannot act on. Clear base_specs on the same condition. The overlay only ever feeds those chips (resolveDiffusionTrainingFacts is its sole consumer), so nothing functional depends on it being present. Covered by a test that pins a bf16-unsupported host and asserts both halves: the overlay is empty and vram_note still carries the reason. It also asserts a per-base overlay exists on an unblocked host first, so it cannot pass vacuously. Verified it fails with the fix reverted.
Two consequences of routing the fetch through prefer_ungated_mirror that the mirror was not meant to have. The gated-repo name check ran on the canonical id while the start route preflighted the fetch repo. For FLUX.1-dev or FLUX.2-dev without a token that means the route probes the public mirror, answers 200, frees the resident models, and only then does the child refuse the run by name. It now checks the repo the run will actually fetch, so the two agree: a mirror-backed run proceeds, and a genuinely gated fetch still fails in the route, before anything is evicted. base_revision was reading the fetch repo too. Which repo that is depends on local cache state, so the same base records a different rev- value once the upstream snapshot is evicted or the run moves to another machine, and mismatch_reason then refuses the checkpoint as a different base revision though the weights are byte identical. Every checkpoint written before mirrors existed holds the canonical value, so those would be refused as well. Both identity_for_config and the post-load re-read go back to the canonical id; a canonical repo with no local ref records "unresolved", which is already treated as not comparable. Tests, both mutation checked: the gate assertion fails when the canonical id is restored, and the revision assertion fails when the fetch repo is.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bb39f3f930
ℹ️ 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".
| fetch_base_model = ( | ||
| prefer_ungated_mirror(self.base_model, token or None) | ||
| if resolved_family != "sdxl" |
There was a problem hiding this comment.
Route cached upstream bases through the ungated mirror
When a user without BFL access has any upstream Klein-base weight in the HF cache, the current normalization still calls prefer_ungated_mirror without a file list, so its cache probe treats that single weight as a hit and keeps the vendor ID. The start route then unconditionally HEADs that vendor repo and returns 400 on its 401/403, even if the cached snapshot is complete; if it is partial, the trainer would also need unavailable vendor files. Thus the new ungated training path remains unusable after an interrupted or previously authenticated upstream download; training should force the public mirror here or make both mirror selection and preflight aware of a complete offline snapshot.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. prefer_ungated_mirror decides on cache state, and _upstream_is_cached without an explicit file list counts any cached weight as a hit, so a single leftover shard from an earlier authenticated pull keeps a token-less run pointed at the gated vendor repo and it 401s on the files it still needs.
fb87d80 overrides the cache preference when there is no token: only gated repos are in the mirror table, so a mirror existing means the upstream needs credentials this run does not have. UNSLOTH_DIFFUSION_NO_MIRROR still wins, exactly as it does inside prefer_ungated_mirror, so the documented way to pin the vendor repo is unchanged. SDXL keeps its untouched path.
test_a_tokenless_run_takes_the_mirror_even_with_the_vendor_repo_cached, parametrized on the NO_MIRROR pin. Mutation checked both ways: dropping the override fails on the mirror assertion, ignoring the pin fails on the inverse.
| train_base_repos = ( | ||
| "black-forest-labs/FLUX.2-klein-base-4B", | ||
| "black-forest-labs/FLUX.2-klein-base-9B", |
There was a problem hiding this comment.
Map the loaded 9B checkpoint to its 9B training base
When Create currently has a distilled Klein 9B model loaded and the user opens Train, adding this second training base does not make the preselection choose it: DiffusionTrainPanel only preserves loadedBaseRepo when it exactly equals an entry in base_repos, but the loaded repo is ...klein-9B while this list contains ...klein-base-9B. It consequently falls back to the first entry, base-4B, so the workflow intended to train the currently loaded 9B variant silently starts from 4B unless the user notices and changes the selector. Use the inverse deploy pairing when seeding the training base.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. The distilled half of a pair is not trainable, so it is never in base_repos, and the preselect chain fell from an exact match straight to base_repos[0]. For FLUX.2 Klein that is the 4B base, so opening Train with the 9B model loaded quietly started a 9B workflow on 4B weights unless the user noticed the selector.
fb87d80 adds resolveDiffusionTrainingBase, the inverse of resolveDiffusionDeployBase, and puts it between the exact match and base_repos[0]. It reads deploy_bases off the family the backend reports, not the static presets, and returns a repo only when the family declares the pairing AND the paired training repo is actually offered, so it cannot invent a base the backend would refuse. An older backend reports no pairings and keeps today behaviour.
Four assertions in diffusion-train-deploy.test.ts plus a source-level check that the panel preselect sits between the two fallbacks. Mutation checked: dropping the base_repos filter makes the null case return unsloth/FLUX.2-klein-base-9B, and removing the panel wiring fails the preselect check.
|
Merged
Worth noting for anyone reading the two together: #8291 added |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b1dc7bbf01
ℹ️ 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".
| @@ -2007,7 +2025,7 @@ def _train_dit( | |||
|
|
|||
There was a problem hiding this comment.
Record the fetched revision for mirror-backed checkpoints
Fresh evidence in the current head is that the transformer is now loaded from fetch_cfg, while checkpoint pinning still calls with_resolved_revision(identity, cfg.base_model) on the canonical repo. When the upstream is uncached—the normal condition that selects the mirror—the canonical repo never enters the cache, so every saved checkpoint retains an unresolved revision; if the mirror advances before a resume, mismatch_reason skips the revision comparison and restores the old adapter and optimizer state onto different frozen weights. Preserve a stable, comparable identity derived from the fetched revision or weight content rather than discarding revision validation for mirror-backed runs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it was my own regression. Reverting to the canonical repo did not weaken the check, it removed it: prefer_ungated_mirror picks the mirror precisely WHEN the canonical repo is not cached, so source_revision(canonical) returns "unresolved" on every mirror-backed host, and mismatch_reason skips non-comparable revisions. Both sides read "unresolved" and a mirror that advanced under a resume went unnoticed.
Fixed in fb87d80 by recording both halves rather than choosing between them. identity_for_config now reads the revision from the FETCH repo and stores which repo that was in a new base_revision_repo field, and mismatch_reason skips the base_revision comparison only when the two identities read their revisions from different repos. A moved mirror is caught again, a legitimate cross-repo resume of byte-identical weights is not refused, and a bundle written before the field existed has base_revision_repo of None, falls back to base_model, and compares exactly as it did.
test_a_mirror_backed_run_pairs_the_revision_with_the_repo_it_came_from covers all of it, including the from_dict(as_dict()) round trip. Mutation checked twice: dropping the repo-pair guard fails on the cross-repo case, and reading the canonical repo again fails on seen == [mirror].
A mirror-backed run resolves the revision from the mirror, so recording the canonical repo's revision instead lost validation entirely: source_revision(canonical) is "unresolved" on exactly the hosts a mirror is selected for, and mismatch_reason skips non-comparable revisions, so the check silently never fired. Record both halves and compare them only when the repos match, which still catches a moved mirror and no longer refuses a legitimate cross-repo resume. Bundles written before the field exist keep comparing as they did. Also take the mirror on a token-less run even when the vendor repo is cached: only gated repos are in the mirror table, so a mirror existing means the upstream needs credentials this run does not have. UNSLOTH_DIFFUSION_NO_MIRROR still pins the vendor repo. And preselect the training base a family pairs with a loaded distilled checkpoint: the distilled half is never in base_repos, so opening Train with the 9B model loaded seeded the 4B base.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 13740c6359
ℹ️ 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 token and not os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip(): | ||
| fetch_base_model = mirror_repo(self.base_model) or fetch_base_model |
There was a problem hiding this comment.
Preserve cached ungated bases without a token
When a tokenless user already has a complete upstream cache for an ungated mirrored DiT base such as black-forest-labs/FLUX.2-klein-base-4B, this override discards the cache-aware result from prefer_ungated_mirror and forces a new unsloth/* fetch. The mirror table explicitly labels these entries as ungated in diffusion_families.py:548-560, so the premise that every mirrored upstream needs credentials is false; offline training then fails after GPU eviction, while online training needlessly redownloads several GB. Restrict this forced rewrite to genuinely gated training repos.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and my justifying comment was simply false. The mirror table stopped being gated-only when the redistributable bases were added to it: black-forest-labs/FLUX.2-klein-base-4B, Z-Image-Turbo, the Qwen-Image family, HiDream, Lumina, SDXL are all mirrored purely to keep the fetch inside unsloth/*, and every one of them answers anonymously upstream. Klein base-4B is the worst case, since it is both a default trainable base and mirrored, so a token-less user with a complete local cache was re-pulling it.
Fixed by splitting the table rather than adding a second list to keep in sync. _GATED_MIRROR_PAIRS now holds only the 12 repos the Hub actually refuses without accepted terms; the redistributable ones moved to _UNGATED_MIRROR_PAIRS. mirror_repo and canonical_base build from the union, so redirection and the base-keyed table normalisation are unchanged, and a new upstream_is_gated() reads the gated half. The token-less override is now conditioned on it, so an ungated base keeps prefer_ungated_mirror cache-aware answer and an offline run with a complete snapshot still trains.
test_a_tokenless_run_keeps_a_cached_ungated_base, parametrized on the NO_MIRROR pin, with preconditions asserting the base is mirrored AND ungated so the test cannot quietly pass by the table moving underneath it. The gated case keeps its own test. Mutation checked: dropping the upstream_is_gated condition fails with assert unsloth/FLUX.2-klein-base-4B == black-forest-labs/FLUX.2-klein-base-4B.
| if field == "base_revision" and _revision_repo(self) != _revision_repo(other): | ||
| continue |
There was a problem hiding this comment.
Keep revision checks across mirror switches
When a resume switches between the canonical repo and its mirror while one repo has advanced or the mirror is temporarily lagging, this branch accepts the checkpoint solely because the repo names differ, even though both sides have comparable but different revisions. The fresh evidence in the current diff is this explicit cross-repo continue: it can restore the adapter and optimizer state onto different frozen weights and silently corrupt the resumed trajectory. Use a stable content/release identity for canonical-mirror pairs instead of dropping revision validation across them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining this one. The mechanism is described accurately, but the remedy would reinstate the exact refusal that started this thread, and the identity it asks for does not exist in the metadata available here.
base_revision is a Hub commit SHA. Two repos never share one, even when their weights are byte identical, which is the whole point of the mirrors. So "both sides have comparable but different revisions" across a canonical-mirror pair is not evidence of drift, it is the normal case: comparing them refuses 100 percent of legitimate cross-repo resumes, which is what the P1 above this one was raised about. Skipping is not "accepting because the names differ", it is declining to draw a conclusion from two values that carry no information about each other.
Nor would normalising through canonical_base() help. It would make the two read as the same repo and then compare their necessarily different SHAs, which is the refusing behaviour with extra steps.
I also considered resolving the RECORDED repo revision as it stands on this machine and comparing that, independent of what the run fetches. It works in principle but it is worse in practice: it refuses a resume on the basis of a repo the run is not using, so a cached mirror moving would block a canonical run whose weights are fine.
What is true is the residual gap: within one repo, drift is caught, and across the pair nothing is. Closing it needs a content identity we publish ourselves, for example recording the upstream revision each mirror was copied from in the mirror card metadata, so both sides can be reduced to a common value. That is a mirror re-publish plus a metadata read, not a change to this comparison, and I have opened it as a follow-up rather than leaving a check here that cannot work.
Worth noting the direction of travel: before this PR the branch recorded the canonical revision, which read "unresolved" on every mirror-backed host and skipped the comparison in ALL cases, cross-repo and same-repo alike. The pairing restores same-repo validation. The gap you are describing is narrower than what shipped, not wider.
The mirror table stopped being gated-only when the redistributable bases joined it, so "a mirror exists" no longer implies "the upstream needs credentials". Klein base-4B is both a default trainable base and mirrored, and the Hub serves it anonymously, so a token-less run with a complete local cache was re-pulling it from the mirror and an offline run failed outright. Split the table rather than keep a second list in sync: the 12 genuinely gated pairs stay in _GATED_MIRROR_PAIRS, the redistributable ones move to _UNGATED_MIRROR_PAIRS, and mirror_repo and canonical_base build from the union so redirection and the base-keyed table normalisation are unchanged. upstream_is_gated reads the gated half, and the token-less override now asks it.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 671f271a4b
ℹ️ 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".
| not token | ||
| and upstream_is_gated(self.base_model) | ||
| and not os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip() | ||
| ): | ||
| fetch_base_model = mirror_repo(self.base_model) or fetch_base_model |
There was a problem hiding this comment.
Preserve local gated-base clones before forcing mirrors
When base_model is an existing relative pipeline path that happens to equal a gated vendor ID, such as a local clone at black-forest-labs/FLUX.1-dev, prefer_ungated_mirror deliberately preserves that local path, but this override subsequently replaces it with the Hub mirror whenever no token is set. Training then ignores the user's local weights and may download a different repository or fail offline; apply the forced gated rewrite only when base_model is not an existing local path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and the carve-out was missing. prefer_ungated_mirror declines for _is_local_path(base) on purpose (a base can be a directory named exactly like the vendor id, and the loaders resolve it on disk), but the token-less gated override did not repeat that test, so a local clone at black-forest-labs/FLUX.1-dev was rewritten to unsloth/FLUX.1-dev and the run fetched the Hub instead of the weights already present, or failed offline.
Fixed in 93039bc: the override now also requires not _is_local_path(self.base_model), the same predicate and the same reason as in prefer_ungated_mirror, so the two sites cannot drift.
Test: test_a_tokenless_run_keeps_a_local_clone_named_like_a_gated_base chdirs into a tmp dir holding a real black-forest-labs/FLUX.1-dev directory and asserts fetch_base_model stays the local path with no token and no UNSLOTH_DIFFUSION_NO_MIRROR. Mutation-checked: dropping the new condition makes it fail with unsloth/FLUX.1-dev; restored, the five token-less mirror tests pass.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 93039bc5f0
ℹ️ 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".
| return ( | ||
| family.base_repos.find((repo) => normalizedRepo(repo) === normalizedRepo(trainingRepo)) ?? null |
There was a problem hiding this comment.
Map mirror-loaded Klein checkpoints back to offered bases
When the directly loaded pipeline is unsloth/FLUX.2-klein-9B, inference preserves that mirror ID as status.base_repo, and this lookup selects the mirror mapping whose training side is unsloth/FLUX.2-klein-base-9B. Because /diffusion/info offers only the canonical vendor IDs in base_repos, the final find returns null and the Train panel falls back to the first, 4B base. Thus the remaining mirror-loaded 9B path still silently seeds 4B training; map the mirror inference ID to its canonical offered training base, or include the mirror base among the offered repos.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and this is Deploy's own doing: a LoRA trained on unsloth/FLUX.2-klein-base-9B deploys onto unsloth/FLUX.2-klein-9B, so that mirror id is what /images/status reports afterwards. The reverse lookup then matched the mirror pairing, whose training half is unsloth/FLUX.2-klein-base-9B, which base_repos does not offer, and the panel fell through to the first base: 4B, seeding a 9B workflow from 4B weights. Exactly the mix-up the function exists to prevent, reached one hop later.
Fixed in 427859e: when the paired training repo is not offered, the resolver folds to the repo NAME, which a mirror keeps unchanged from its upstream, and returns the offered vendor base. It still only ever returns something in base_repos, so it cannot invent a base the backend would refuse.
I also corrected the assertion that pinned the old behaviour: resolveDiffusionTrainingBase(klein, "unsloth/FLUX.2-klein-9B") now returns black-forest-labs/FLUX.2-klein-base-9B instead of null, plus a case-insensitive variant, and the null case is now a name that matches nothing offered. Mutation-checked: dropping the name fold makes the new test fail. tsc clean, 6 tests in the file pass.
| await asyncio.to_thread( | ||
| _preflight_gated_base, config.get("base_model", ""), config.get("hf_token") | ||
| _preflight_gated_base, | ||
| normalized_cfg.fetch_base_model or normalized_cfg.base_model, | ||
| normalized_cfg.hf_token, |
There was a problem hiding this comment.
Exempt preserved local clones from remote access checks
Fresh evidence in the current head is that normalization deliberately preserves an existing relative clone such as black-forest-labs/FLUX.1-dev, but this changed preflight passes that same org/name string to _preflight_gated_base, which treats it as remote and returns 400 on the tokenless Hub HEAD. If the HEAD is unavailable and passes best-effort, the child still rejects the same local path by name in _assert_gated_access. Consequently the local-clone exception remains unusable without a token; apply the existing local-path check before both remote access gates.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, the exception was only half applied. _preflight_gated_base splits remote from local by string shape (one slash, no leading ., / or ~), and a relative clone at black-forest-labs/FLUX.1-dev satisfies all of it, so the route HEADed the gated repo token-less and 400d a run whose weights never leave disk. _assert_gated_access then matched the same string against _GATED_TRAIN_REPOS by name in the child.
Fixed in 427859e: both gates now take the existing _is_local_path test first, the same predicate prefer_ungated_mirror and the normalization use, so all three sites answer identically.
Tests: test_the_start_preflight_never_heads_the_hub_for_a_local_clone fails the test outright if urlopen is reached, and test_the_gate_lets_a_local_clone_named_like_a_gated_repo_through asserts the child gate passes a real on-disk clone with no token. Both mutation-checked: removing either guard makes its test fail. Full test_diffusion_training.py + test_diffusion_dit_trainer.py: 161 passed.
| # a fetch, but only a GATED upstream justifies overriding a user's existing cache: for these | ||
| # the upstream is reachable without credentials, so a complete local snapshot must keep being | ||
| # used rather than re-pulled from the mirror. | ||
| _UNGATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = ( |
There was a problem hiding this comment.
Keep ungated mirrors in the companion-base registry
Moving these rows into _UNGATED_MIRROR_PAIRS leaves hub/utils/companion_assets.py:_mirror_pair_ids() importing only _GATED_MIRROR_PAIRS. As a result, non-default variants such as Klein base-4B, HiDream Dev/Fast, and SDXL Turbo disappear from _curated_base_ids; before a recorded companion link exists, the cleanup and deletion guards no longer recognize those cached bases and can allow an installed GGUF checkpoint's companions to be removed. Update that consumer to use the combined _MIRROR_PAIRS table.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it is a regression the split introduced. _mirror_pair_ids() imported _GATED_MIRROR_PAIRS back when that name WAS the whole table; after the split it saw 12 of 24 pairs. Enumerated against the live tables, the ids that fell out of _curated_base_ids and are not recovered from _FAMILIES were: Qwen-Image-2512 (both sides), Klein base-4B (both sides), HiDream-I1-Dev and -Fast (both sides), sdxl-turbo (both sides), and the unsloth halves of Qwen-Image, Qwen-Image-Edit-2511, Klein 4B, Z-Image-Turbo, Lumina-Image-2.0, HiDream-I1-Full and stable-diffusion-xl-base-1.0.
Fixed in 427859e: that consumer now imports _MIRROR_PAIRS. Gating decides whether a fetch may override a user's cache; it says nothing about whether a base can strand companions.
Test: test_the_curated_bases_carry_the_whole_mirror_table in hub/tests asserts every id on both sides of _MIRROR_PAIRS is curated, so the next table change cannot reopen it. Mutation-checked: pointing the import back at the gated half makes it fail.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
One conflict, in test_diffusion_training.py, additive on both sides: this branch appended the clip-refusal ordering cases while #8267 appended its normalized fetch-mirror preflight cases in the same place. Kept both. 131 passed in that file, 593 across the diffusion, H3 and video suites, frontend 1599 passed with tsc clean.


Summary
FLUX.2 Klein LoRA training used a distilled checkpoint and omitted the single-stream attention output projections used by the upstream trainer. On the built-in dog dataset, the resulting adapter produced smooth generic puppies instead of the training subject.
This PR trains on the official 4B or 9B base checkpoint, targets the complete upstream LoRA module set, and previews the adapter on the matching distilled checkpoint.
What changed
Testing
Runtime validation
Trained the built-in five-image dog dataset for 500 steps on FLUX.2 Klein base 4B, then loaded the adapter on the distilled 4B checkpoint. Fixed-seed generations at 4 steps and guidance 1 reproduced the corgi's upright ears, markings, and photographic detail across seeds 42, 43, and 44. Average training loss improved from 0.6725 to 0.6275 with the same 8.66 GB peak VRAM.
Comparison
The rows show the training images, the previous distilled-training flow, and this PR using the same prompt and seeds 42, 43, and 44.