Repository navigation
feat(imagegen): support FLUX.3 Image Klein generation and editing - #3727
Open
Jaeyeong-CHOI wants to merge 1 commit into
Open
Jaeyeong-CHOI wants to merge 1 commit into
Jaeyeong-CHOI wants to merge 1 commit into
Conversation
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #3230.
Adds Black Forest Labs' FLUX.3 Image Klein as the image-generation family
flux3: text-to-image, editing with 1 to 10 reference images, and layout boxes, forblack-forest-labs/flux-3-image-klein(distilled flow map, 16 steps, guidance 1) andblack-forest-labs/flux-3-image-klein-base(50 steps, CFG 3.5), throughmlxcel generate-image,POST /v1/images/generationsandPOST /v1/images/edits. It is a port of mlx-vlm'smlx_vlm/models/flux3(Neywa-Labs/mlx-vlm#2537), checked against mlx-vlm at gite8035ae.Before this change, the published package was classified as
flux2(its Diffusersvae/config.jsonnamesAutoencoderKLFlux2), somlxcel generate-image -m models/flux-3-image-klein ...failed withError: FLUX.2 checkpoint is missing models/flux-3-image-klein/transformer,mlxcel generate -mansweredimage generation checkpoint (flux2): use mlxcel generate-image, andmlxcel arch --jsonhad noflux3.What changed
src/imagegen/flux3/(new family module, tests beside each file):config.rs:is_flux3_config,Flux3Config::from_value(BFL'sdit/text_encoder/samplerblocks; a non-emptyquantization, anout_modesother thanimage, and avec_in_dimare refused naming the key;max_tokenscapped at 4096; a nullsampler.guidanceis 1),validate_dimensions(multiples of 16 in[64, 4096]), andFlux3Layout, which lists every missing file.transformer.rs:Flux3Transformerwith the per-mode early streams (content_mode_blocks.image,content_mode_blocks.image_cond,txt_mode_blocks), the joint single stream with per-token single-stream modulation,final_layer.image, the flow-mapref_time_inembedding, and a strict key check (359 tensors for Klein, 357 for base). Blocks modulate an affine-free layer norm in the activation dtype, apply the QK RMS norm and the interleaved RoPE together in f32 and round once, and use FLUX.2'spos_embed,timestep_embedding,layer_norm,modulateandapply_rope.flux3_timestep_embeddingholds the time in the activation dtype and rounds1000 * tto it before the f32 frequencies, as BFL does.conditioner.rs: the 80-multiple padding rule, padding positions (cumsum(mask) - 1, padded tokens at 1), and the layer taps (pre-norm; the final norm only when the last layer is tapped), on the sharedQwen3TextEncoderand FLUX.2's tokenizer wrapper.pipeline.rs:timesteps(same f32 MLX ops as upstream),image_ids,initial_noise(normal((n, L, 128), key(seed))through bf16), the Euler loop in f32 on the bf16 transformer, the base model's CFG pass, the prompt cache (4 entries, encoder evicted after each prompt), and decode (((clip(x, -1, 1) + 1) * 127.5)touint8, crop-back).edit.rs:prepare_reference(single: 4 MP / 4096 px, reflect or symmetric padding to multiples of 16, crop box; several: 1 MP each, centre-cropped), the default edit size, and reference encoding to bf16image_condtokens with ids on layer-1 - index.boxes.rs:to_canvasand the prompt suffix, serialized byte for byte as Python'sjson.dumps(rows, ensure_ascii=False).weights.rs: the strict transformer load (bf16), and a BFL-to-Diffusers name map soae.safetensorsloads into the existingFlux2Vae(f32) instead of a second VAE.mod.rs:Flux3Model(ImageGenerationModel),Flux3Options(max_sequence_length,num_images,boxes,upsample_prompt,prompt_expansion_model), defaults from thesamplerblock,variant()(flux3-klein/flux3-klein-base), andcheck_request.src/imagegen/qwen3_text_encoder.rs:hidden_states_at(the hidden-state walk at explicit[B, T]positions;hidden_statesand every existing caller are unchanged),load_first_layers(loads only the tapped layers, in a chosen dtype, from a Qwen3 or Qwen3-VL directory), andfinal_norm.src/models/qwen3.rs:Attention::forward_at_positionsandTransformerBlock::forward_at_positions, a cache-free prefill at explicit positions that applies rotate-halfcos/sintables in the activation dtype, as mlx-vlm's Qwen3-VL language model applies them. The cached generation path is untouched.flux3inIMAGE_FAMILIES, with the root-config.jsoncheck running before every other probe rule; anImageFamilyrow; aStandaloneArchitectureFamily(image generation,IMAGE_GENERATE, aliasesflux3-klein,flux3-klein-base,flux-3-image-klein).Used by::flux2::attentionispub(crate)forapply_rope; theUsed by:lines of the reused FLUX.2, latent, VAE and test helpers name FLUX.3;mlxcel_core::layers::attention's note now says Qwen3 calls it directly from the explicit-position path (it previously listed Qwen3 under "Not used by").docs/image-generation.md(options, editing, boxes, prompt expansion, parity), the family table and probe order there,docs/supported-models.md, aflux3row indocs/vision-model-scope.md,NOTICE(mlx-vlm and BFL's Apache-2.0 reference),CHANGELOG.mdunder## [Unreleased], and the two test-only variables inscripts/ci/check_env_var_docs.py.tests/fixtures/flux3/generate_flux3_unit_fixtures.py(the upstream values the unit tests embed) andtests/fixtures/flux3/generate_flux3_oracle.py(the real-checkpoint oracle the ignored parity tests read; nothing large is committed).Deviations from the issue
vae/throughFlux2Vaewhen it declares the FLUX.2 class, else a BFL key map forae.safetensors. The package does shipvae/(AutoencoderKLFlux2), but upstream's download set and the issue's file table useae.safetensorsonly, so this loadsae.safetensorsthrough a name map intoFlux2Vaeand does not needvae/. An ignored real-checkpoint test shows the mapped tensors equal thevae/copy tensor for tensor and that both loads encode and decode identically.ImageRequestcarries no "size was given" flag; the CLI and server fill a missing edit size fromdefault_edit_size(first reference), which returns the lone-reference padded canvas. An edit whose size equals that default is therefore treated as unsized: a lone padded reference is cropped back, and several references take the first one's own 1 MP size, as upstream. An explicit size equal to that default behaves the same way.n > 1run once per image with seedseed + i(FLUX.2's convention); upstream's edit path has no image count. Generation batches one noise tensor, as the issue asks.num_imagesmust equalnwhen given (the trait counts images byn).--negative-promptwhen given, else the empty prompt (upstream: always empty). A non-empty negative prompt on the flow map is a 400, since it would be ignored.revised_promptis set when boxes changed the prompt.flow_map,variantandreference_counthave no field in the sharedGeneratedImage/ response types; the variant shows invariant()and error messages only.imagecrate's Lanczos3 is not PIL's LANCZOS, so a reference that has to shrink differs from upstream's by interpolation rounding (references already within budget are byte-identical; see the unit tests).black-forest-labs/flux-3-image-klein-baseis still gated for this account (HTTP 403 /GatedRepoError), so the base run the issue asks to record was not made; the base path is covered only by the tiny-transformer test (no flow map) and unit tests.Maintainer checklist
max_sequence_length0/1/4096/4097; padding for 1, 80, 81 real tokens and a 1-token cap;timesteps(1)andtimesteps(1000); references of 10x7 (symmetric padding), 20x18, 512x512 (no padding), 5000x100 and 3000x2000 (extreme ratio and the 4 MP cap); boxes clamped below 0 and above 1 and rounded half to even.single_geometryshrinks by 0.5% per round and was exercised at 1x9000 and 7000x3. The joint single stream concatenates per-token modulations once per step, not per block.Qwen3TextEncoder::hidden_statesandstacked_prompt_embeds(FLUX.2, Z-Image, Ideogram 4, Bonsai) are unchanged; their tests pass (imagegen::512 passed).Qwen3Modelgeneration and batched decode do not call the new methods (models::qwen3130 passed).Flux2Vae::from_raw_weights,bn_normalize,denormalize_packed_latents,decode,encode,Flux2Tokenizer,pos_embed,timestep_embedding,apply_ropeandFlux2Model::pixelsare reused unchanged.detect_image_family: the new rule returns early only for a rootconfig.jsonthatis_flux3_configaccepts; probe tests for every other family pass.## [Unreleased](the section did not exist after v0.9.0; added).layers::attention"Not used by" note was corrected because Qwen3 now calls it.cargo fmt --all -- --checkon the final tree (see Verification).Verification
All on Linux aarch64, NVIDIA GB10 (sm_121, 121 GB unified memory), CUDA 13, Rust 1.97.1,
MLX_ENABLE_TF32=0, on the tree of this commit.Before the change (
mainat beedecb, the same package):Unit and related tests:
The new unit tests compare against values mlx-vlm's own FLUX.3 code produced (
tests/fixtures/flux3/generate_flux3_unit_fixtures.py, mlx-vlm e8035ae, mlx 0.32.5): the tiny random transformer in f32 (text only, text plus one reference, no flow map) within 2e-6 absolute;timesteps(16, 6.93); the seed-42 noise head and sum;prepare_referencesizes, crops and padded-byte checksums for 512x512, 20x18 (reflect), 10x7 (symmetric), 1000x750, 5000x100 and 3000x2000; andto_canvas/json.dumpsoutput. The Qwen3 encoder tests show the explicit-position path equals the cached path at positions0..T, that padding positions move only the padded rows, and thatload_first_layersmatches a full load layer for layer.Real checkpoint,
black-forest-labs/flux-3-image-kleinat3b767ff9b5261d71645e2ec49d87d298d955238d, against mlx-vlm e8035ae (upsample_prompt=False) on mlx 0.32.5:ae.safetensorsvia the name map vs the package'svae/CLI and server (
test-fastprofile binaries of this tree):Gates:
The two failures are on unmodified
mainas well and are outside this change (neither file is touched here); both are the ones tracked in #3652:tests/mlx_test_guard_coverage.rs::mlx_evaluating_lib_tests_take_mlx_test_guardflagssrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32. None of the new tests is flagged.tests/step3p7_parity.rs::text_decode_delegates_sequence_local_native_batchingfailsassertion failed: !wrapper.supports_padded_prefill().On
mainat beedecb (same host and settings),cargo test --profile test-fast --features cuda --test mlx_test_guard_coverage --test step3p7_parity -- --test-threads=1fails the same two tests with the same messages (the guard scanner flags the same single file and line).The ignored FLUX.3 parity tests were rerun on the same final tree after the gate: 5 passed, same numbers as above.
The commit merges cleanly onto current
origin/main(ac5716b;git merge-tree --write-treeexits 0).Limits
flux-3-image-klein-pup); the issue scopes it out.