Skip to content

feat(imagegen): support FLUX.3 Image Klein generation and editing - #3727

Open
Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:feat/3230-flux3-klein
Open

Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:feat/3230-flux3-klein

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

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, for black-forest-labs/flux-3-image-klein (distilled flow map, 16 steps, guidance 1) and black-forest-labs/flux-3-image-klein-base (50 steps, CFG 3.5), through mlxcel generate-image, POST /v1/images/generations and POST /v1/images/edits. It is a port of mlx-vlm's mlx_vlm/models/flux3 (Neywa-Labs/mlx-vlm#2537), checked against mlx-vlm at git e8035ae.

Before this change, the published package was classified as flux2 (its Diffusers vae/config.json names AutoencoderKLFlux2), so mlxcel generate-image -m models/flux-3-image-klein ... failed with Error: FLUX.2 checkpoint is missing models/flux-3-image-klein/transformer, mlxcel generate -m answered image generation checkpoint (flux2): use mlxcel generate-image, and mlxcel arch --json had no flux3.

What changed

  • src/imagegen/flux3/ (new family module, tests beside each file):
    • config.rs: is_flux3_config, Flux3Config::from_value (BFL's dit / text_encoder / sampler blocks; a non-empty quantization, an out_modes other than image, and a vec_in_dim are refused naming the key; max_tokens capped at 4096; a null sampler.guidance is 1), validate_dimensions (multiples of 16 in [64, 4096]), and Flux3Layout, which lists every missing file.
    • transformer.rs: Flux3Transformer with 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-map ref_time_in embedding, 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's pos_embed, timestep_embedding, layer_norm, modulate and apply_rope. flux3_timestep_embedding holds the time in the activation dtype and rounds 1000 * t to 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 shared Qwen3TextEncoder and 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) to uint8, 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 bf16 image_cond tokens with ids on layer -1 - index.
    • boxes.rs: to_canvas and the prompt suffix, serialized byte for byte as Python's json.dumps(rows, ensure_ascii=False).
    • weights.rs: the strict transformer load (bf16), and a BFL-to-Diffusers name map so ae.safetensors loads into the existing Flux2Vae (f32) instead of a second VAE.
    • mod.rs: Flux3Model (ImageGenerationModel), Flux3Options (max_sequence_length, num_images, boxes, upsample_prompt, prompt_expansion_model), defaults from the sampler block, variant() (flux3-klein / flux3-klein-base), and check_request.
  • src/imagegen/qwen3_text_encoder.rs: hidden_states_at (the hidden-state walk at explicit [B, T] positions; hidden_states and every existing caller are unchanged), load_first_layers (loads only the tapped layers, in a chosen dtype, from a Qwen3 or Qwen3-VL directory), and final_norm.
  • src/models/qwen3.rs: Attention::forward_at_positions and TransformerBlock::forward_at_positions, a cache-free prefill at explicit positions that applies rotate-half cos / sin tables in the activation dtype, as mlx-vlm's Qwen3-VL language model applies them. The cached generation path is untouched.
  • Probe and registries: flux3 in IMAGE_FAMILIES, with the root-config.json check running before every other probe rule; an ImageFamily row; a StandaloneArchitectureFamily (image generation, IMAGE_GENERATE, aliases flux3-klein, flux3-klein-base, flux-3-image-klein).
  • Visibility and Used by:: flux2::attention is pub(crate) for apply_rope; the Used 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: a FLUX.3 section in docs/image-generation.md (options, editing, boxes, prompt expansion, parity), the family table and probe order there, docs/supported-models.md, a flux3 row in docs/vision-model-scope.md, NOTICE (mlx-vlm and BFL's Apache-2.0 reference), CHANGELOG.md under ## [Unreleased], and the two test-only variables in scripts/ci/check_env_var_docs.py.
  • Fixture scripts: tests/fixtures/flux3/generate_flux3_unit_fixtures.py (the upstream values the unit tests embed) and tests/fixtures/flux3/generate_flux3_oracle.py (the real-checkpoint oracle the ignored parity tests read; nothing large is committed).

Deviations from the issue

  • VAE path. The issue prefers loading vae/ through Flux2Vae when it declares the FLUX.2 class, else a BFL key map for ae.safetensors. The package does ship vae/ (AutoencoderKLFlux2), but upstream's download set and the issue's file table use ae.safetensors only, so this loads ae.safetensors through a name map into Flux2Vae and does not need vae/. An ignored real-checkpoint test shows the mapped tensors equal the vae/ copy tensor for tensor and that both loads encode and decode identically.
  • Edit size. ImageRequest carries no "size was given" flag; the CLI and server fill a missing edit size from default_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.
  • Edits with n > 1 run once per image with seed seed + i (FLUX.2's convention); upstream's edit path has no image count. Generation batches one noise tensor, as the issue asks.
  • num_images must equal n when given (the trait counts images by n).
  • Negative prompt. The base model's unconditional pass uses --negative-prompt when 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.
  • Response metadata. revised_prompt is set when boxes changed the prompt. flow_map, variant and reference_count have no field in the shared GeneratedImage / response types; the variant shows in variant() and error messages only.
  • Reference resize. The image crate'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).
  • Base checkpoint. black-forest-labs/flux-3-image-klein-base is 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

  1. Boundaries. Sizes 63/64/4096/4097/4112 and non-multiples; references 0, 1, 10, 11; max_sequence_length 0/1/4096/4097; padding for 1, 80, 81 real tokens and a 1-token cap; timesteps(1) and timesteps(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.
  2. Large inputs. Padding positions, reference geometry and padding are linear in their input; single_geometry shrinks 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.
  3. Other callers. Qwen3TextEncoder::hidden_states and stacked_prompt_embeds (FLUX.2, Z-Image, Ideogram 4, Bonsai) are unchanged; their tests pass (imagegen:: 512 passed). Qwen3Model generation and batched decode do not call the new methods (models::qwen3 130 passed). Flux2Vae::from_raw_weights, bn_normalize, denormalize_packed_latents, decode, encode, Flux2Tokenizer, pos_embed, timestep_embedding, apply_rope and Flux2Model::pixels are reused unchanged. detect_image_family: the new rule returns early only for a root config.json that is_flux3_config accepts; probe tests for every other family pass.
  4. CHANGELOG under ## [Unreleased] (the section did not exist after v0.9.0; added).
  5. Comments and messages. No explanatory comment was removed. The layers::attention "Not used by" note was corrected because Qwen3 now calls it.
  6. Format. cargo fmt --all -- --check on 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 (main at beedecb, the same package):

$ mlxcel generate-image -m models/flux-3-image-klein -p "A studio photograph of a red ceramic teapot" --size 512x512 --seed 42 -o teapot.png
Error: FLUX.2 checkpoint is missing models/flux-3-image-klein/transformer
$ mlxcel generate -m models/flux-3-image-klein -p hi
Error: image generation checkpoint (flux2): use mlxcel generate-image
$ mlxcel arch --json        # no family mentions flux3

Unit and related tests:

cargo test --profile test-fast --features cuda --lib imagegen::flux3 -- --test-threads=1      # 43 passed, 5 ignored (real package)
cargo test --profile test-fast --features cuda --lib imagegen:: -- --test-threads=1           # 512 passed, 46 ignored
cargo test --profile test-fast --features cuda --lib models::qwen3 -- --test-threads=1        # 130 passed, 22 ignored
cargo test --profile test-fast --features cuda --lib models::registry -- --test-threads=1     # 22 passed
cargo test --profile test-fast --features cuda --lib server::routes::images -- --test-threads=1  # 18 passed

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_reference sizes, crops and padded-byte checksums for 512x512, 20x18 (reflect), 10x7 (symmetric), 1000x750, 5000x100 and 3000x2000; and to_canvas / json.dumps output. The Qwen3 encoder tests show the explicit-position path equals the cached path at positions 0..T, that padding positions move only the padded rows, and that load_first_layers matches a full load layer for layer.

Real checkpoint, black-forest-labs/flux-3-image-klein at 3b767ff9b5261d71645e2ec49d87d298d955238d, against mlx-vlm e8035ae (upsample_prompt=False) on mlx 0.32.5:

PYTHONPATH=<mlx-vlm> python tests/fixtures/flux3/generate_flux3_oracle.py models/flux-3-image-klein /tmp/flux3-oracle
MLXCEL_TEST_FLUX3_DIR=models/flux-3-image-klein MLXCEL_FLUX3_ORACLE_DIR=/tmp/flux3-oracle \
  cargo test --profile test-fast --features cuda --lib imagegen::flux3::parity_tests -- --ignored --test-threads=1 --nocapture
# 5 passed
Check Result
Token ids and masks (teapot, edit, empty prompts; 80 tokens each) identical
Initial noise, 512x512, seed 42 bit-identical, 0 of 131,072 values differ
Text features, teapot prompt 2.09e-3 relative RMS
Step-0 velocity on upstream's text features 5.74e-3 relative RMS (gate 1e-2)
ae.safetensors via the name map vs the package's vae/ 0 of 250 tensors differ; encode and decode identical
Encoded edit reference vs upstream 1.66e-3 relative RMS
512x512 generate, 16 steps, seed 42, upstream's text features 51.41 dB (gate 30)
512x512 single-reference edit, "Make the teapot cobalt blue", seed 42, upstream's text features 57.60 dB (gate 30)
512x512 generate end to end 47.73 dB

CLI and server (test-fast profile binaries of this tree):

mlxcel generate-image -m models/flux-3-image-klein -p "A studio photograph of a red ceramic teapot" --size 512x512 --seed 42 -o teapot.png
# saved teapot.png (512x512, seed 42); 9.9 s wall including load; 47.73 dB against upstream's image
mlxcel generate-image -m models/flux-3-image-klein --task edit --image teapot.png -p "Make the teapot cobalt blue" --seed 42 -o blue.png
# saved blue.png (512x512, seed 42); 13.7 s wall including load; 45.67 dB against upstream's edit of its own teapot
mlxcel generate -m models/flux-3-image-klein -p hi
# Error: image generation checkpoint (flux3): use mlxcel generate-image
mlxcel arch --json
# {"id": "flux3", "display_name": "FLUX.3 Image Klein", "category": "image generation", "runtimes": ["image_generate"], ...}
mlxcel-server --image-model models/flux-3-image-klein --host 127.0.0.1 --port 18733
# POST /v1/images/generations {"prompt": ..., "size": "512x512", "seed": 42}          -> 200
# POST /v1/images/edits {"prompt": "Make the teapot cobalt blue", "image": [data URL]}  -> 200
# POST /v1/images/generations {..., "upsample_prompt": true}  -> 400 "FLUX.3 upsample_prompt is not supported by mlxcel: prompt expansion through the flux-3-image-klein-pup VLM is not implemented; pass a detailed caption instead"
# POST /v1/images/generations {..., "guidance": 3.5}          -> 400 "The distilled FLUX.3 flow map runs without CFG; use guidance 1, got 3.5"

Gates:

cargo fmt --all -- --check                                                   # clean
cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings  # clean
python3 scripts/ci/check_used_by.py          # OK, 78 top-level pub fn, 57 annotated, 717 caller-file references
bash scripts/ci/check_used_by_test.sh        # all cases passed
python3 scripts/ci/check_env_var_docs.py     # OK, 452 names, 291 documented, 161 allowlisted
python3 scripts/ci/check_binary_assets.py    # OK, 127 declared files
make verify-test-cuda                        # 205 test binaries: 18,925 passed, 2 failed, 572 ignored

The two failures are on unmodified main as 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_guard flags src/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_batching fails assertion failed: !wrapper.supports_padded_prefill().

On main at beedecb (same host and settings), cargo test --profile test-fast --features cuda --test mlx_test_guard_coverage --test step3p7_parity -- --test-threads=1 fails 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-tree exits 0).

Limits

  • No base-model run (gated).
  • No prompt expansion (flux-3-image-klein-pup); the issue scopes it out.
  • Checked on CUDA only (NVIDIA GB10); Metal is marked partial in the registry.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(imagegen): add FLUX.3 Image Klein (flux3) generation and editing

1 participant