diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bad1fa82..5fb169c7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [Unreleased] + +### Added + +- **FLUX.3 Image Klein** (`flux3`, #3230). `black-forest-labs/flux-3-image-klein` (16-step distilled flow map, guidance 1) and `-klein-base` (50 steps, CFG 3.5) run in `mlxcel generate-image` and on `/v1/images/generations` and `/v1/images/edits`: text-to-image, editing with 1 to 10 reference images, and layout boxes appended to the prompt. The transformer is new (three early streams, a joint single stream, a flow-map target-time embedding); it reuses FLUX.2's RoPE and time embedding, the shared Qwen3 conditioner (now with explicit positions, for FLUX.3's padded tokens, and a load that stops at the deepest tapped layer) and the FLUX.2 VAE, which loads `ae.safetensors` through a BFL-to-Diffusers name map. The probe recognizes the package's root `config.json` before any component, since its `vae/` would otherwise read as `flux2`. Prompt expansion through `flux-3-image-klein-pup` is not implemented: `upsample_prompt: true` is a 400. On GB10 against mlx-vlm the 512x512 Klein image is 47.73 dB end to end and 51.41 dB on upstream's text features (single-reference edit 57.60 dB), with bit-identical initial noise and token ids; the base checkpoint was not run (gated). + ## [v0.9.0] - 2026-11-30 ### Added diff --git a/NOTICE b/NOTICE index d16c7176d..56da96a70 100644 --- a/NOTICE +++ b/NOTICE @@ -54,6 +54,19 @@ moss-image-mlx NOTICE file, as required by Apache License 2.0 Section 4(d): torch_randn.py and the strip-decoding VAE are adapted from felix-ab/flux3-mlx (Apache License 2.0). +FLUX.3 Image Klein (mlx-vlm, Black Forest Labs) +----------------------------------------------- + +The FLUX.3 Image Klein port under src/imagegen/flux3/ derives from +mlx-vlm's mlx_vlm/models/flux3 (Blaizzy/mlx-vlm#2537), covered by the MIT +notice in the mlx-lm, mlx-vlm, and mlx-audio section below. mlx-vlm in turn +credits Black Forest Labs' reference implementation, +https://github.com/black-forest-labs/flux-3-image-klein, Copyright Black +Forest Labs, licensed under the Apache License, Version 2.0. The FLUX.3 model +weights are not distributed with mlxcel; they are published under the FLUX +Kommunity License and are gated on the Hugging Face Hub. + + mlx-lm, mlx-vlm, and mlx-audio ------------------------------ diff --git a/docs/image-generation.md b/docs/image-generation.md index 788716a20..53f9c4d78 100644 --- a/docs/image-generation.md +++ b/docs/image-generation.md @@ -2,11 +2,12 @@ mlxcel generates and edits images through `mlxcel generate-image` and the OpenAI-compatible `POST /v1/images/generations` and `POST /v1/images/edits` server routes. This page covers the model-independent runtime in `src/imagegen/`: the request types, the checkpoint probe, the scheduler, latent packing, the FLUX.2 VAE, the Z-Image DiT blocks, PNG output, the CLI, the server routes, and how a model issue registers a family. -**Current status.** Registered families: `flux2` ([FLUX.2 Klein](#flux2-klein-flux2)), `z_image` ([Z-Image](#z-image)), `bonsai` ([Prism Bonsai](#prism-bonsai-bonsai)), `ernie_image` ([ERNIE-Image](#ernie-image-ernie_image)), `mage_flow` ([Mage-Flow](#mage-flow-mage_flow)), `qwen_image` ([Qwen-Image](#qwen-image-qwen_image)), `ideogram4` ([Ideogram 4](#ideogram-4-ideogram4)), `ming_image` ([Ming-Image](#ming-image-ming_image)), `llada_image` ([LLaDA-Image](#llada-image-llada_image)) and `moss_image` ([MOSS-Image](#moss-image-moss_image)). Each model in the image-generation epic (`lablup/mlxcel#2348`) adds its transformer and text conditioner and one row to the family table. A checkpoint the probe recognizes but `FAMILIES` does not list fails with `image generation family is not supported by this build`, and `mlxcel-server --image-model` fails at startup for it, by design (see [Server](#server)). +**Current status.** Registered families: `flux2` ([FLUX.2 Klein](#flux2-klein-flux2)), `flux3` ([FLUX.3 Image Klein](#flux3-image-klein-flux3)), `z_image` ([Z-Image](#z-image)), `bonsai` ([Prism Bonsai](#prism-bonsai-bonsai)), `ernie_image` ([ERNIE-Image](#ernie-image-ernie_image)), `mage_flow` ([Mage-Flow](#mage-flow-mage_flow)), `qwen_image` ([Qwen-Image](#qwen-image-qwen_image)), `ideogram4` ([Ideogram 4](#ideogram-4-ideogram4)), `ming_image` ([Ming-Image](#ming-image-ming_image)), `llada_image` ([LLaDA-Image](#llada-image-llada_image)) and `moss_image` ([MOSS-Image](#moss-image-moss_image)). Each model in the image-generation epic (`lablup/mlxcel#2348`) adds its transformer and text conditioner and one row to the family table. A checkpoint the probe recognizes but `FAMILIES` does not list fails with `image generation family is not supported by this build`, and `mlxcel-server --image-model` fails at startup for it, by design (see [Server](#server)). | Family | Checkpoints | Tasks | Default steps / guidance | |--------|-------------|-------|--------------------------| | `flux2` | FLUX.2 Klein 4B, 9B, base-4B, base-9B, 9b-kv (Diffusers tree) and the mlx-community 4-bit conversions | generate, edit (reference images) | distilled 4 / 1.0; base 50 / 4.0 | +| `flux3` | `black-forest-labs/flux-3-image-klein`, `-klein-base` (BFL package, bf16; gated) | generate, edit (1 to 10 references), layout boxes | Klein 16 / 1.0 (flow map); base 50 / 3.5 | | `z_image` | Tongyi-MAI Z-Image-Turbo, Z-Image (raw Diffusers tree or an mlx-vlm conversion) | generate, edit (img2img) | Turbo 8 / 0; base 50 / 4 | | `bonsai` | Prism Bonsai ternary 2-bit FLUX.2 Klein 4B (`prism-ml/bonsai-image-ternary-4B-mlx-2bit`) | generate | 4 / 1.0 | | `ernie_image` | Baidu ERNIE-Image-Turbo, ERNIE-Image (raw Diffusers tree) | generate, edit (SDEdit img2img) | Turbo 8 / 1.0 (edit 8 / 3.0); base 50 / 4.0 | @@ -21,12 +22,13 @@ mlxcel generates and edits images through `mlxcel generate-image` and the OpenAI `mlxcel::imagegen::detect_image_family(path)` classifies a checkpoint directory from small JSON files; it never reads weights. It is a port of `_local_image_model_types` in `Blaizzy/mlx-vlm` (`mlx_vlm/generate/image.py`). In order, it reads: +0. The root `config.json` of a FLUX.3 package: BFL's layout names no `model_type`, so a `dit` block whose `in_channels` lists `image`, `image_cond` and `text` under a `model` starting with `flux-3-image` (upstream `is_flux3_config`) is `flux3` before any other rule runs. The package's Diffusers `vae/config.json` declares `AutoencoderKLFlux2`, which the class-name scan below would otherwise call `flux2`. 1. `manifest.json`: a manifest listing `transformer-packed-mflux/diffusion_pytorch_model.safetensors`, `text_encoder-mlx-4bit/model.safetensors` and `tokenizer/tokenizer.json` is `bonsai`. This is checked first because Bonsai ships a `Flux2KleinPipeline` `model_index.json`, which the class-name scan would call `flux2`. 2. `model_index.json` and `config.json`: `model_type`, `_class_name`, and the class names of the `transformer`, `vae`, `scheduler` and `text_encoder` components. 3. The transformer `weight_map` (`transformer/model.safetensors.index.json`, else `transformer/diffusion_pytorch_model.safetensors.index.json`), matched against marker key sets. A `z_image` transformer is `ming_image` when `mllm/config.json` exists. 4. Each `/config.json`. -The first candidate that names a family in `IMAGE_FAMILIES` wins: `bonsai`, `flux2`, `z_image`, `ming_image`, `ernie_image`, `qwen_image`, `mage_flow`, `ideogram4`, `llada_image`. Candidates come in the order above, so `Ideogram4Pipeline` in `model_index.json` wins over the FLUX.2 VAE class in `vae/config.json`. A path that does not exist, is not a directory, or carries no image metadata yields `None`; unparseable JSON is skipped. +The first candidate that names a family in `IMAGE_FAMILIES` wins: `bonsai`, `flux2`, `flux3`, `z_image`, `ming_image`, `ernie_image`, `qwen_image`, `mage_flow`, `ideogram4`, `llada_image`. Candidates come in the order above, so `Ideogram4Pipeline` in `model_index.json` wins over the FLUX.2 VAE class in `vae/config.json`. A path that does not exist, is not a directory, or carries no image metadata yields `None`; unparseable JSON is skipped. `mlxcel generate` and `mlxcel serve -m` on an image checkpoint fail with `image generation checkpoint (): use mlxcel generate-image` instead of `model_type not found` or a bare missing-`config.json` error. The hook sits in `src/models/detection.rs` and only fires when the directory has no top-level `model_type`, so no text checkpoint is affected. @@ -585,6 +587,67 @@ Components: the Qwen3.5-9B language backbone as the prompt conditioner (`text_en No numeric parity against the reference has been measured, and no checkpoint-gated test exists in this module yet. The contributor rendered `VisualInference/MOSS-Image-SFT-MLX-compact` end to end through `mlxcel-server --image-model` on an M4 (512x512, 12 steps, CFG 3.0 renders legible prompt text). The same checkpoint also renders on ROCm (gfx1151, `mlxcel generate-image`, 512x512, 12 steps, CFG 3.0, about 2 minutes including load); with the same seed, the decode before the batch-norm denormalization fix gave a washed-out image (pixel std 37.6) and the fixed decode gives full contrast (pixel std 64.4) with the prompt text spelled correctly. The unit tests cover the schedule, the probe, the chat template, the RoPE table, and the load-time weight shape checks, which turn a mis-shaped or mismatched checkpoint into an error before any MLX op runs. +## FLUX.3 Image Klein (`flux3`) + +A port of `mlx_vlm/models/flux3` (`Blaizzy/mlx-vlm#2537`; checked against mlx-vlm at git e8035ae), in `src/imagegen/flux3/`. mlx-vlm credits Black Forest Labs' Apache-2.0 reference code; the weights are under the FLUX Kommunity License and the repositories are gated, so accept the terms on the Hub and download with a token. + +| Checkpoint | Variant | Steps | Guidance | Notes | +|------------|---------|-------|----------|-------| +| `black-forest-labs/flux-3-image-klein` | `flux3-klein` | 16 | 1.0 | Distilled flow map: each step also embeds its target time, and guidance must be 1. | +| `black-forest-labs/flux-3-image-klein-base` | `flux3-klein-base` | 50 | 3.5 | Guidance other than 1 runs a second pass on the empty prompt (or `--negative-prompt`) and mixes `uncond + g * (cond - uncond)`. | + +Each repository is about 43 GB because it also ships a Diffusers `transformer/` copy and CUDA-only `variants/`. mlxcel reads the root package only: `config.json`, `model.safetensors` (11.1 GB, bf16), `ae.safetensors` (0.34 GB) and `text_encoder/` (8.9 GB), about 20.4 GB: + +```bash +hf download black-forest-labs/flux-3-image-klein --local-dir models/flux-3-image-klein \ + --include config.json manifest.json model.safetensors ae.safetensors 'text_encoder/*' +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 +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 +``` + +A missing file fails at load with every missing path listed. + +- **Architecture.** Three independent early streams (`image`, `image_cond` for references, `text`), five blocks each with their own modulation and RoPE, then 28 joint single-stream blocks in which each token takes its own mode's modulation. Every block modulates an affine-free layer norm, applies a QK RMS norm and an interleaved RoPE together in f32 (rounded once to bf16), and adds attention and a parallel SwiGLU behind one gate. FLUX.2's 4-axis RoPE, time embedding and text ids are reused; the time is held in bf16 and `1000 * t` is rounded to bf16 before it meets the frequencies, as BFL does. +- **Conditioner.** The Qwen3-VL-4B text backbone in `text_encoder/` (vision tower skipped, layers after 32 not loaded) in bf16. The prompt is one user turn through the chat template with the generation prompt, right-padded to a multiple of 80 tokens and truncated at 4096 (`max_tokens` is capped there). Real tokens sit at positions `0..n` and every padded token at position 1; the hidden states after layers 4, 8, ..., 32 are concatenated to `[1, T, 20480]`. The encoder is evicted after each prompt and four prompts are cached; the transformer and VAE load on the first request and stay resident. +- **Sampler.** `t = linspace(1, 0, steps + 1)` mapped through `alpha * t / (1 + (alpha - 1) * t)` (`alpha` 6.93), Euler steps in f32 on the bf16 transformer, initial noise `normal((n, H/16 * W/16, 128), key(seed))` rounded through bf16. +- **VAE.** `ae.safetensors` is the FLUX.2 autoencoder under BFL's tensor names; it loads into the shared `Flux2Vae` through a name map (decoder levels renumbered, 1x1 attention kernels as linear weights) and runs in f32. Its encode and decode are identical to the package's Diffusers `vae/` copy (see Parity), which is not read. Output pixels are `((clip(x, -1, 1) + 1) * 127.5)` truncated to `uint8`. +- **Sizes.** Width and height multiples of 16 in `64..=4096`. +- **Editing.** One to ten references. A lone reference keeps its aspect ratio within 4 MP and 4096 px per side, is Lanczos-resized when it has to shrink and reflect-padded (symmetric below 17 px) to multiples of 16; several references are each capped at 1 MP and center-cropped to multiples of 16. Each is VAE-encoded as the `image_cond` stream on its own RoPE layer (`-1 - index`). Without a size the output takes the first reference's padded size, and a lone padded reference is cropped back to its own area; several references take the first one's 1 MP size. The CLI and the server fill a missing size from the first reference before the model sees the request, so an explicit size equal to that default is treated the same way. The resize uses the `image` crate's Lanczos3 filter, not PIL's, so a reference that has to shrink differs from upstream's by interpolation rounding. Edits run once per image with seed `seed + i`. +- **Batches.** Generation draws `n` images from one noise tensor of batch `n` and reports `seed` for each, as [FLUX.2](#batched-seeds) does. +- **Layout boxes.** `boxes: [{"id", "desc", "bbox": [top, left, bottom, right]}]` in `0..1` (or `src_bbox` / `tgt_bbox` with `from` for edits) are mapped to the `0..1000` canvas and appended to the prompt as one space and their JSON, written as Python's `json.dumps(..., ensure_ascii=False)` writes it. The response's `revised_prompt` is the prompt actually encoded when boxes changed it. +- **Prompt expansion.** Upstream rewrites every prompt through the `flux-3-image-klein-pup` VLM by default. That is not implemented: `upsample_prompt: true` or a `prompt_expansion_model` is a 400 that says so, and every run is upstream's `upsample_prompt=False` path, so pass a detailed caption. +- **`--gen-kwargs` / `extra`.** `max_sequence_length` (1 to 4096), `boxes`, `upsample_prompt` (`false` only), and `num_images`, which must equal `n` when given. + +### FLUX.3 parity + +Against upstream mlx-vlm at git e8035ae on mlx 0.32.5, CUDA, NVIDIA GB10, `MLX_ENABLE_TF32=0`, with `upsample_prompt=False` on both sides and the `black-forest-labs/flux-3-image-klein` package at revision `3b767ff9`. `tests/fixtures/flux3/generate_flux3_oracle.py` writes the upstream oracle (nothing large is committed); the `#[ignore]` tests in `src/imagegen/flux3/parity_tests.rs` read it from `MLXCEL_FLUX3_ORACLE_DIR` and the package from `MLXCEL_TEST_FLUX3_DIR` (default `models/flux-3-image-klein`), and skip when either is absent: + +```bash +PYTHONPATH= python tests/fixtures/flux3/generate_flux3_oracle.py \ + models/flux-3-image-klein /tmp/flux3-oracle +MLXCEL_FLUX3_ORACLE_DIR=/tmp/flux3-oracle MLX_ENABLE_TF32=0 \ + cargo test --profile test-fast --features cuda --lib imagegen::flux3::parity_tests \ + -- --ignored --test-threads=1 --nocapture +``` + +| Check | Result | +|-------|--------| +| Token ids and masks (the teapot, edit and empty prompts, 80 tokens each) | identical | +| Initial noise, 512x512, seed 42 | bit-identical (131,072 values) | +| Text features of the teapot prompt | 2.09e-3 relative RMS | +| Step-0 velocity on upstream's text features | 5.74e-3 relative RMS | +| `ae.safetensors` through the name map against the package's Diffusers `vae/` | 250 of 250 tensors identical; encode and decode identical | +| Encoded edit reference (bf16 tokens against upstream's f32 encoder output) | 1.66e-3 relative RMS | +| Klein 512x512 generate, 16 steps, seed 42, on upstream's text features | 51.41 dB | +| Klein 512x512 edit of upstream's teapot, "Make the teapot cobalt blue", seed 42, on upstream's text features | 57.60 dB | +| Klein 512x512 generate end to end, on mlxcel's text features | 47.73 dB | + +The unit tests check the rest against values upstream's own code produced (`tests/fixtures/flux3/generate_flux3_unit_fixtures.py`): a two-early, two-single-block random transformer in f32 within 2e-6 of upstream on text only, text plus one reference, and a non-flow-map config; `timesteps(16, 6.93)`; the seed-42 noise head; and `prepare_reference` sizes, crops and padded bytes. + +The base model (`flux-3-image-klein-base`, 50 steps, guidance 3.5) has not been run against upstream: its repository was still gated for the account that produced these numbers. Only its transformer path without the flow-map embedding is covered, by the tiny-model unit test; the CFG pass has not run on real weights. + ## Verification ```bash diff --git a/docs/supported-models.md b/docs/supported-models.md index 80cfc9ab0..20930b694 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -844,6 +844,7 @@ CLI implementation. `mlxcel generate-image` and `mlxcel-server --image-model` (`POST /v1/images/generations`, `POST /v1/images/edits`) run diffusion checkpoints in the Diffusers layout; see [Image generation](image-generation.md) for the CLI, the routes and each family's options. `mlxcel arch --json` lists each family under the `image_generate` runtime with `image` output. - FLUX.2 Klein (`flux2`): `black-forest-labs/FLUX.2-klein-4B`, `-9B`, `-base-4B`, `-base-9B` and `-9b-kv` (Diffusers bf16 trees), and `mlx-community/flux2-klein-4b-4bit` and `-9b-4bit`. Text-to-image and reference-image editing; the 9b-kv checkpoint caches the reference tokens' K/V during edits. Validated on CUDA (NVIDIA GB10) against upstream mlx-vlm with seed-fixed parity: 32.27 dB generate and 40.54 dB edit on the 4B checkpoint, bit-identical initial noise, and a bit-identical f32 transformer. Metal runs are not recorded. +- FLUX.3 Image Klein (`flux3`): `black-forest-labs/flux-3-image-klein` (16-step flow map, guidance 1) and `-klein-base` (50 steps, guidance 3.5), BFL's root package (`model.safetensors`, `ae.safetensors`, `text_encoder/`; gated). Text-to-image, editing with 1 to 10 references, and layout boxes. Prompt expansion (`upsample_prompt`) is not implemented. Validated on CUDA (NVIDIA GB10) against upstream mlx-vlm with `upsample_prompt=False`: 51.41 dB generate and 57.60 dB single-reference edit at 512x512 on upstream's text features, 47.73 dB end to end, bit-identical initial noise and token ids. The base checkpoint is not recorded (gated). Metal runs are not recorded. - Z-Image (`z_image`): Tongyi-MAI Z-Image-Turbo and Z-Image, as the raw Diffusers tree or an mlx-vlm conversion (affine, mxfp4, mxfp8, nvfp4). Text-to-image and img2img; defaults are 8 steps / guidance 0 for Turbo and 50 / 4 for the base model. - Prism Bonsai (`bonsai`): `prism-ml/bonsai-image-ternary-4B-mlx-2bit`, FLUX.2 Klein 4B with ternary transformer linears packed as 2-bit MLX affine weights and a 4-bit Qwen3 text encoder. Text-to-image only. Validated on CUDA (NVIDIA GB10) against upstream mlx-vlm with the checkpoint `vae/` on both sides: 31.18 dB (29.82 dB against upstream as shipped, which downloads `black-forest-labs/FLUX.2-small-decoder` at load; this port never downloads), bit-identical initial noise, and the f32 transformer within 1.2e-6 relative RMS. Metal runs are not recorded. - ERNIE-Image (`ernie_image`): `baidu/ERNIE-Image-Turbo` and `baidu/ERNIE-Image` (Diffusers bf16 trees), with the bundled Ministral 3 text encoder and the optional `pe/` prompt enhancer, whose rewrite is returned as `revised_prompt`. Text-to-image and SDEdit img2img; defaults are 8 steps / guidance 1 for Turbo (guidance 3 for edits) and 50 / 4 for the base model. Validated on CUDA (NVIDIA GB10) against upstream mlx-vlm at 1024x1024: Turbo bit-exact (57.00 dB), Turbo edit 32.23 dB, base 24.24 dB at 50 steps, below the 30 dB criterion (batch-2 GEMM rounding amplified over 50 steps; the 8-step control is 31.43 dB, see the parity section), bit-identical initial noise. Metal runs are not recorded. diff --git a/docs/vision-model-scope.md b/docs/vision-model-scope.md index 756d9e9ce..4a733f5a1 100644 --- a/docs/vision-model-scope.md +++ b/docs/vision-model-scope.md @@ -35,7 +35,7 @@ The maintainer asked for image generation, depth, pose and 3D support, so these ### Image generation, epic `lablup/mlxcel#2348` -The shared runtime from `lablup/mlxcel#2341` (PR `lablup/mlxcel#2497`) is merged. `src/imagegen/registry.rs::FAMILIES` registers `z_image` (`lablup/mlxcel#2425`), `ernie_image` (`lablup/mlxcel#2345`), `mage_flow` (`lablup/mlxcel#2426`), `qwen_image` (`lablup/mlxcel#2342`), `ideogram4` (`lablup/mlxcel#2427`) and `ming_image` (`lablup/mlxcel#2347`). `src/imagegen/probe.rs::IMAGE_FAMILIES` recognizes `bonsai`, `flux2`, `z_image`, `ming_image`, `ernie_image`, `qwen_image`, `mage_flow` and `ideogram4`. A recognized checkpoint of an unregistered family therefore fails in one of two ways depending on the command: +The shared runtime from `lablup/mlxcel#2341` (PR `lablup/mlxcel#2497`) is merged. `src/imagegen/registry.rs::FAMILIES` registers `z_image` (`lablup/mlxcel#2425`), `ernie_image` (`lablup/mlxcel#2345`), `mage_flow` (`lablup/mlxcel#2426`), `qwen_image` (`lablup/mlxcel#2342`), `ideogram4` (`lablup/mlxcel#2427`), `ming_image` (`lablup/mlxcel#2347`) and `flux3` (`lablup/mlxcel#3230`). `src/imagegen/probe.rs::IMAGE_FAMILIES` recognizes `bonsai`, `flux2`, `flux3`, `z_image`, `ming_image`, `ernie_image`, `qwen_image`, `mage_flow` and `ideogram4`. A recognized checkpoint of an unregistered family therefore fails in one of two ways depending on the command: - `mlxcel generate`, `mlxcel serve` and the other text-model loaders stop in `src/models/detection.rs` with `image generation checkpoint (): use mlxcel generate-image` (`src/imagegen/probe.rs::image_checkpoint_redirect_error`). - `mlxcel generate-image` fails with `image generation family is not supported by this build` (`src/imagegen/registry.rs::resolve_family`) until the port issue registers the family. @@ -45,6 +45,7 @@ A checkpoint the probe does not recognize keeps the `model_type not found` or fi | Family | Port issue | What it is | Probe today | |---|---|---|---| | `flux2` | `lablup/mlxcel#2424` | FLUX.2 Klein (4B, 9B): dual-stream plus single-stream MMDiT flow-matching text-to-image and editing, bundled text encoder, VAE. | Recognized, not registered. | +| `flux3` | `lablup/mlxcel#3230` | FLUX.3 Image Klein (distilled flow map and base): three per-mode early streams and a joint single stream, Qwen3-VL conditioner tapping eight layers, FLUX.2 VAE. | Registered: `mlxcel generate-image` and `mlxcel-server --image-model` run text-to-image and editing with 1 to 10 references (no prompt expansion). | | `z_image` | `lablup/mlxcel#2425` | Z-Image / Z-Image-Turbo: Qwen3-style text encoder, diffusion transformer, VAE, flow-matching scheduler. | Registered: `mlxcel generate-image` and `mlxcel-server --image-model` run text-to-image and img2img. | | `mage_flow` | `lablup/mlxcel#2426` | Mage-Flow and Mage-Flow-Edit (4B, six variants): Qwen3-VL conditioner, NR-MMDiT transformer, Mage-VAE, flow-matching sampler. | Registered: `mlxcel generate-image` and `mlxcel-server --image-model` run text-to-image or editing, fixed by the variant. | | `ideogram4` | `lablup/mlxcel#2427` | Ideogram 4: 34-layer DiT over VAE latents with an external LLM text encoder; FP8, license-gated checkpoint keyed by `model_index.json`. | Registered: `mlxcel generate-image` and `mlxcel-server --image-model` run text-to-image (generation only). | diff --git a/scripts/ci/check_env_var_docs.py b/scripts/ci/check_env_var_docs.py index 1b40b5e4b..5c6d77873 100755 --- a/scripts/ci/check_env_var_docs.py +++ b/scripts/ci/check_env_var_docs.py @@ -325,6 +325,12 @@ "tests in imagegen/flux2/parity_tests.rs", ( "MLXCEL_TEST_FLUX2_DIR", )), + ("test-only: package and upstream-oracle directories of the FLUX.3 " + "real-checkpoint parity tests in imagegen/flux3/parity_tests.rs, " + "documented in docs/image-generation.md", ( + "MLXCEL_TEST_FLUX3_DIR", + "MLXCEL_FLUX3_ORACLE_DIR", + )), ("test-only: checkpoint directory and upstream step-0 tensor file of the " "Bonsai real-checkpoint parity tests in imagegen/bonsai/parity_tests.rs", ( "MLXCEL_TEST_BONSAI_DIR", diff --git a/src/imagegen/flux2/attention.rs b/src/imagegen/flux2/attention.rs index e8ca86268..a6baa5d25 100644 --- a/src/imagegen/flux2/attention.rs +++ b/src/imagegen/flux2/attention.rs @@ -20,7 +20,7 @@ //! Heads are `[B, H, S, D]`. q/k RMS norms and RoPE run in f32 and cast back; //! the RoPE tables are `[S, D/2]` and rotate adjacent pairs. //! -//! Used by: Flux2, Bonsai. +//! Used by: Flux2, Bonsai, and Flux3 ([`apply_rope`] only). use anyhow::{Context, Result}; use mlxcel_core::weights::WeightMap; @@ -86,6 +86,9 @@ fn cat_seq(parts: &[&MlxArray]) -> UniquePtr { /// `AttentionUtils.apply_rope_bshd`: rotate adjacent pairs of `x` in f32 by /// `cos`/`sin` (`[S, D/2]`) and cast back to `x`'s dtype. +/// +/// Used by: Flux2, Bonsai, Flux3 (on f32 QK-normed heads, so the cast back +/// is to f32 and the FLUX.3 block rounds once afterwards). pub fn apply_rope(x: &MlxArray, cos: &MlxArray, sin: &MlxArray) -> UniquePtr { let out_dtype = mlxcel_core::array_dtype(x); let shape = mlxcel_core::array_shape(x); diff --git a/src/imagegen/flux2/embeddings.rs b/src/imagegen/flux2/embeddings.rs index cb9f2756a..ee0c6a6be 100644 --- a/src/imagegen/flux2/embeddings.rs +++ b/src/imagegen/flux2/embeddings.rs @@ -22,7 +22,8 @@ //! Every scalar constant is created in the dtype of the array it meets, so the //! MLX promotion here matches upstream's weakly typed Python scalars. //! -//! Used by: Flux2, Bonsai. +//! Used by: Flux2, Bonsai, and Flux3 (`timestep_embedding`, `pos_embed`, +//! `layer_norm`, `modulate`, `split_last`). use anyhow::{Context, Result, anyhow}; use mlxcel_core::layers::UnifiedLinear; diff --git a/src/imagegen/flux2/mod.rs b/src/imagegen/flux2/mod.rs index 4ee3d5fb8..1c267e3eb 100644 --- a/src/imagegen/flux2/mod.rs +++ b/src/imagegen/flux2/mod.rs @@ -25,7 +25,7 @@ //! so every image reports `seed`, and image `i` is not what `seed + i` gives //! alone. Edits run once per image with seed `seed + i`. -mod attention; +pub(crate) mod attention; mod blocks; pub mod config; mod edit; @@ -130,7 +130,7 @@ impl Flux2Model { /// Image `index` of a `[B, H, W, 3]` u8 batch as `(pixels, width, height)`. /// - /// Used by: Flux2, Bonsai. + /// Used by: Flux2, Bonsai, Flux3. pub(crate) fn pixels(array: &mlxcel_core::MlxArray, index: i32) -> Result<(Vec, u32, u32)> { let s = mlxcel_core::array_shape(array); if s.len() != 4 || s[3] != 3 { diff --git a/src/imagegen/flux2/parity_tests.rs b/src/imagegen/flux2/parity_tests.rs index 503077290..cbd492a7c 100644 --- a/src/imagegen/flux2/parity_tests.rs +++ b/src/imagegen/flux2/parity_tests.rs @@ -72,7 +72,7 @@ fn bf16_fixture(file: &str, key: &str) -> (Vec, Vec) { /// [`bf16_fixture`] for a safetensors file at any path. /// -/// Used by: Flux2 and Bonsai parity tests. +/// Used by: Flux2, Bonsai and Flux3 parity tests. pub(crate) fn bf16_tensor(path: &Path, key: &str) -> (Vec, Vec) { let bytes = std::fs::read(path).unwrap(); let tensors = safetensors::SafeTensors::deserialize(&bytes).unwrap(); @@ -91,7 +91,7 @@ fn f32_fixture(file: &str, key: &str) -> Vec { /// [`f32_fixture`] for a safetensors file at any path. /// -/// Used by: Flux2 and Bonsai parity tests. +/// Used by: Flux2, Bonsai and Flux3 parity tests. pub(crate) fn f32_tensor(path: &Path, key: &str) -> Vec { let bytes = std::fs::read(path).unwrap(); let tensors = safetensors::SafeTensors::deserialize(&bytes).unwrap(); diff --git a/src/imagegen/flux2/prompt.rs b/src/imagegen/flux2/prompt.rs index f1625afd2..0a2335d6a 100644 --- a/src/imagegen/flux2/prompt.rs +++ b/src/imagegen/flux2/prompt.rs @@ -24,7 +24,7 @@ //! `max_sequence_length`, and the conditioning is the Qwen3 hidden states of //! layers 9, 18 and 27 stacked into `[B, T, 3 * H]`. //! -//! Used by: Flux2, Bonsai. +//! Used by: Flux2, Bonsai, and Flux3 (`Flux2Tokenizer`, `prepare_text_ids`). use std::path::Path; diff --git a/src/imagegen/flux3/boxes.rs b/src/imagegen/flux3/boxes.rs new file mode 100644 index 000000000..9c4b35674 --- /dev/null +++ b/src/imagegen/flux3/boxes.rs @@ -0,0 +1,190 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! FLUX.3 layout boxes. +//! +//! A port of `to_canvas` in +//! +//! and of the no-expansion branch of `Flux3Image._prepare_prompt` in +//! `flux3/pipeline.py`: boxes normalized to `0..1` are mapped to the `0..1000` +//! canvas and appended to the prompt as one space plus their JSON, written the +//! way Python's `json.dumps(rows, ensure_ascii=False)` writes it (`", "` and +//! `": "` separators, non-ASCII kept), because those bytes are what the text +//! encoder reads. + +use anyhow::{Result, bail}; +use serde_json::Value; + +/// Side of the box canvas. +pub const SCALE: f64 = 1000.0; + +/// One canvas row: a target box, or an edit's source and target boxes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CanvasRow { + Box { + id: String, + bbox: [i64; 4], + desc: String, + }, + Edit { + id: String, + from: String, + src_bbox: Option<[i64; 4]>, + tgt_bbox: Option<[i64; 4]>, + desc: String, + }, +} + +/// Python truthiness of an optional JSON value. +fn truthy(v: Option<&Value>) -> bool { + match v { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(Value::Number(n)) => n.as_f64() != Some(0.0), + Some(Value::String(s)) => !s.is_empty(), + Some(Value::Array(a)) => !a.is_empty(), + Some(Value::Object(o)) => !o.is_empty(), + } +} + +/// `str(value or default)`. +fn text_or(v: Option<&Value>, default: &str) -> String { + if !truthy(v) { + return default.to_string(); + } + match v { + Some(Value::String(s)) => s.clone(), + Some(Value::Bool(true)) => "True".to_string(), + Some(other) => other.to_string(), + None => default.to_string(), + } +} + +/// `grid(box)`: `round(clamp(v, 0, 1) * 1000)` per coordinate, Python's +/// round-half-to-even; `None` for a missing or empty box. +fn grid(index: usize, value: Option<&Value>) -> Result> { + if !truthy(value) { + return Ok(None); + } + let Some(Value::Array(items)) = value else { + bail!( + "box {index}: a box is [y_min, x_min, y_max, x_max], got {}", + value.unwrap_or(&Value::Null) + ); + }; + if items.len() != 4 { + bail!( + "box {index}: a box is [y_min, x_min, y_max, x_max], got {}", + Value::Array(items.clone()) + ); + } + let mut out = [0_i64; 4]; + for (slot, item) in out.iter_mut().zip(items) { + let Some(v) = item.as_f64() else { + bail!("box {index}: box coordinates must be numbers, got {item}"); + }; + *slot = (v.clamp(0.0, 1.0) * SCALE).round_ties_even() as i64; + } + Ok(Some(out)) +} + +/// Upstream `to_canvas`: `0..1` boxes to rows on the `0..1000` canvas. +pub fn to_canvas(boxes: &[Value]) -> Result> { + let mut rows = Vec::with_capacity(boxes.len()); + for (i, b) in boxes.iter().enumerate() { + let Some(map) = b.as_object() else { + bail!("box {i} must be an object, got {b}"); + }; + let id = text_or(map.get("id"), &format!("obj_{}", i + 1)); + let desc = text_or(map.get("desc"), ""); + if truthy(map.get("bbox")) { + let bbox = grid(i, map.get("bbox"))?.expect("truthy box"); + rows.push(CanvasRow::Box { id, bbox, desc }); + } else if truthy(map.get("src_bbox")) || truthy(map.get("tgt_bbox")) { + rows.push(CanvasRow::Edit { + id, + from: text_or(map.get("from"), ""), + src_bbox: grid(i, map.get("src_bbox"))?, + tgt_bbox: grid(i, map.get("tgt_bbox"))?, + desc, + }); + } else { + bail!("box {i} has neither bbox nor src_bbox/tgt_bbox"); + } + } + Ok(rows) +} + +/// A JSON string literal as Python's `json.dumps(..., ensure_ascii=False)` +/// writes it: the same escapes as `serde_json` (`\"`, `\\`, `\n`, `\r`, `\t`, +/// `\b`, `\f` and lowercase `\u00XX` for other control characters). +fn py_string(s: &str) -> String { + serde_json::to_string(s).expect("a string always serializes") +} + +fn py_box(b: Option<&[i64; 4]>) -> String { + match b { + None => "null".to_string(), + Some(b) => format!("[{}, {}, {}, {}]", b[0], b[1], b[2], b[3]), + } +} + +/// `json.dumps(rows, ensure_ascii=False)`. +#[must_use] +pub fn rows_json(rows: &[CanvasRow]) -> String { + let items: Vec = rows + .iter() + .map(|row| match row { + CanvasRow::Box { id, bbox, desc } => format!( + "{{\"id\": {}, \"bbox\": {}, \"desc\": {}}}", + py_string(id), + py_box(Some(bbox)), + py_string(desc) + ), + CanvasRow::Edit { + id, + from, + src_bbox, + tgt_bbox, + desc, + } => format!( + "{{\"id\": {}, \"from\": {}, \"src_bbox\": {}, \"tgt_bbox\": {}, \"desc\": {}}}", + py_string(id), + py_string(from), + py_box(src_bbox.as_ref()), + py_box(tgt_bbox.as_ref()), + py_string(desc) + ), + }) + .collect(); + format!("[{}]", items.join(", ")) +} + +/// The prompt the text encoder reads: unchanged without boxes, else +/// `f"{prompt.rstrip()} {json}"`. +pub fn prompt_with_boxes(prompt: &str, boxes: &[Value]) -> Result { + if boxes.is_empty() { + return Ok(prompt.to_string()); + } + let rows = to_canvas(boxes)?; + // Python's `str.rstrip()` also strips the separators U+001C..U+001F, + // which Rust does not count as whitespace. + let stripped = + prompt.trim_end_matches(|c: char| c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)); + Ok(format!("{stripped} {}", rows_json(&rows))) +} + +#[cfg(test)] +#[path = "boxes_tests.rs"] +mod tests; diff --git a/src/imagegen/flux3/boxes_tests.rs b/src/imagegen/flux3/boxes_tests.rs new file mode 100644 index 000000000..5fda59678 --- /dev/null +++ b/src/imagegen/flux3/boxes_tests.rs @@ -0,0 +1,127 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use serde_json::json; + +use super::*; + +fn boxes(v: Value) -> Vec { + v.as_array().unwrap().clone() +} + +#[test] +fn to_canvas_clamps_and_rounds_half_to_even() { + let rows = to_canvas(&boxes(json!([ + {"id": "cat", "desc": "a cat", "bbox": [-0.2, 0.0005, 0.0015, 1.7]}, + {"bbox": [0.25, 0.5, 0.75, 1.0]} + ]))) + .unwrap(); + assert_eq!( + rows, + vec![ + // -0.2 -> 0, 0.5 -> 0 (half to even), 1.5 -> 2, 1.7 -> 1000. + CanvasRow::Box { + id: "cat".into(), + bbox: [0, 0, 2, 1000], + desc: "a cat".into() + }, + // A missing id is `obj_{i + 1}`, a missing desc empty. + CanvasRow::Box { + id: "obj_2".into(), + bbox: [250, 500, 750, 1000], + desc: String::new() + }, + ] + ); +} + +#[test] +fn edit_rows_keep_missing_boxes_as_null() { + let rows = to_canvas(&boxes(json!([ + {"id": "mug", "from": "ref_image_1", "src_bbox": [0.1, 0.1, 0.2, 0.2], "desc": "move it"}, + {"tgt_bbox": [0, 0, 1, 1]} + ]))) + .unwrap(); + assert_eq!( + rows_json(&rows), + "[{\"id\": \"mug\", \"from\": \"ref_image_1\", \"src_bbox\": [100, 100, 200, 200], \ + \"tgt_bbox\": null, \"desc\": \"move it\"}, {\"id\": \"obj_2\", \"from\": \"\", \ + \"src_bbox\": null, \"tgt_bbox\": [0, 0, 1000, 1000], \"desc\": \"\"}]" + ); +} + +#[test] +fn malformed_boxes_are_errors() { + for (value, needle) in [ + ( + json!([{"bbox": [0.1, 0.2, 0.3]}]), + "[y_min, x_min, y_max, x_max]", + ), + ( + json!([{"desc": "nothing"}]), + "neither bbox nor src_bbox/tgt_bbox", + ), + (json!([{"bbox": [0.1, "a", 0.3, 0.4]}]), "must be numbers"), + (json!(["not a box"]), "must be an object"), + // An empty bbox is falsy, as upstream, so it needs src/tgt boxes. + (json!([{"bbox": []}]), "neither bbox"), + ] { + let e = to_canvas(&boxes(value)).unwrap_err().to_string(); + assert!(e.contains(needle), "{e}"); + } +} + +#[test] +fn the_json_is_written_as_python_json_dumps() { + // `ensure_ascii=False`: non-ASCII kept; quotes, backslashes and control + // characters escaped; ", " and ": " separators. + let rows = to_canvas(&boxes(json!([ + {"id": "주전자", "desc": "a \"blue\"\\teapot\n\u{1}", "bbox": [0, 0, 0.5, 0.5]} + ]))) + .unwrap(); + assert_eq!( + rows_json(&rows), + "[{\"id\": \"주전자\", \"bbox\": [0, 0, 500, 500], \"desc\": \"a \\\"blue\\\"\\\\teapot\\n\\u0001\"}]" + ); +} + +#[test] +fn the_prompt_gets_one_space_and_the_rows() { + let b = boxes(json!([{"id": "a", "bbox": [0, 0, 1, 1], "desc": "x"}])); + assert_eq!( + prompt_with_boxes("A teapot \n", &b).unwrap(), + "A teapot [{\"id\": \"a\", \"bbox\": [0, 0, 1000, 1000], \"desc\": \"x\"}]" + ); + // Without boxes the prompt is untouched, trailing whitespace included. + assert_eq!(prompt_with_boxes("A teapot ", &[]).unwrap(), "A teapot "); + // Python's rstrip also removes U+001C..U+001F. + assert!(prompt_with_boxes("p\u{1f}", &b).unwrap().starts_with("p [")); +} + +#[test] +fn non_string_ids_are_stringified_and_falsy_ones_defaulted() { + let rows = to_canvas(&boxes(json!([ + {"id": 7, "bbox": [0, 0, 1, 1]}, + {"id": "", "bbox": [0, 0, 1, 1]}, + {"id": 0, "bbox": [0, 0, 1, 1]} + ]))) + .unwrap(); + let ids: Vec<&str> = rows + .iter() + .map(|r| match r { + CanvasRow::Box { id, .. } | CanvasRow::Edit { id, .. } => id.as_str(), + }) + .collect(); + assert_eq!(ids, ["7", "obj_2", "obj_3"]); +} diff --git a/src/imagegen/flux3/conditioner.rs b/src/imagegen/flux3/conditioner.rs new file mode 100644 index 000000000..90a53eca0 --- /dev/null +++ b/src/imagegen/flux3/conditioner.rs @@ -0,0 +1,192 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! FLUX.3 prompt conditioning. +//! +//! A port of `Flux3Tokenizer` and `Flux3TextEncoder.get_prompt_embeds` in +//! . +//! The prompt is one user turn through the tokenizer's chat template with the +//! generation prompt, right-padded to `ceil(real / 80) * 80` tokens (capped, +//! truncating, at the request's `max_sequence_length` and 4096). Real tokens +//! sit at positions `0..n` and every padded token at position 1 +//! (`cumsum(mask) - 1`, padding set to 1), under a causal mask that also +//! hides padded keys. The hidden states after the tapped layers (pre-norm; +//! the final norm only when the last layer is tapped) are concatenated to +//! `[1, T, 8 * 2560]` and cast to bf16. +//! +//! The Qwen3-VL text backbone loads only up to the deepest tapped layer, in +//! bf16, as upstream's `load_text_encoder` does. + +use std::path::Path; + +use anyhow::{Result, bail}; +use mlxcel_core::{MlxArray, UniquePtr, dtype}; + +use super::config::Flux3Config; +use crate::imagegen::flux2::prompt::{Flux2Tokenizer, prepare_text_ids}; +use crate::imagegen::qwen3_text_encoder::Qwen3TextEncoder; + +/// Upstream `Flux3Tokenizer.tokenize`'s padded length: the real token count, +/// capped at `cap`, rounded up to a multiple of `pad_multiple`, capped again. +#[must_use] +pub fn padded_length(real_tokens: usize, pad_multiple: usize, cap: usize) -> usize { + let real = real_tokens.min(cap); + (real.div_ceil(pad_multiple) * pad_multiple).min(cap) +} + +/// `cumsum(mask) - 1`, with every padded position set to 1. +#[must_use] +pub fn padding_positions(attention_mask: &[i32]) -> Vec { + let mut seen = 0; + attention_mask + .iter() + .map(|&m| { + seen += m; + if m == 0 { 1 } else { seen - 1 } + }) + .collect() +} + +/// Encoded prompt features and their text ids. +pub struct PromptFeatures { + /// `[1, T, len(text_layers) * hidden]` bf16. + pub embeds: UniquePtr, + /// `[T, 4]` int32 `(0, 0, 0, i)`. + pub text_ids: UniquePtr, +} + +/// The tokenizer of `text_encoder/` and the padding rule. +pub struct Flux3Tokenizer { + inner: Flux2Tokenizer, + pad_multiple: usize, + max_tokens: usize, +} + +impl Flux3Tokenizer { + /// Load `/tokenizer.json` and its chat template. + /// + /// FLUX.2's tokenizer wrapper renders the template with + /// `enable_thinking=False`; the Qwen3-VL template reads no such variable, + /// so the rendered prompt is upstream's. + pub fn load(text_encoder: &Path, config: &Flux3Config) -> Result { + Ok(Self { + inner: Flux2Tokenizer::load(text_encoder)?, + pad_multiple: config.pad_multiple, + max_tokens: config.max_tokens, + }) + } + + /// Unpadded token count of the formatted prompt. + pub fn count_tokens(&self, prompt: &str) -> Result { + self.inner.count_tokens(prompt) + } + + /// Token ids and mask, padded per [`padded_length`] with the cap + /// `min(max_sequence_length, max_tokens)`. + pub fn tokenize( + &self, + prompt: &str, + max_sequence_length: Option, + ) -> Result<(Vec, Vec)> { + let cap = max_sequence_length + .unwrap_or(self.max_tokens) + .min(self.max_tokens); + if cap == 0 { + bail!("max_sequence_length must be positive"); + } + let length = padded_length(self.count_tokens(prompt)?, self.pad_multiple, cap); + let tokens = self.inner.tokenize(prompt, length)?; + Ok((tokens.input_ids, tokens.attention_mask)) + } +} + +/// The truncated Qwen3-VL text backbone. +pub struct Flux3TextEncoder { + encoder: Qwen3TextEncoder, + layers: Vec, + /// Depth of the full backbone: the final norm applies at this layer. + total_layers: usize, +} + +impl Flux3TextEncoder { + /// Load layers `1..=max(text_layers)` of `text_encoder/` in bf16. + pub fn load(text_encoder: &Path, config: &Flux3Config) -> Result { + let total_layers = backbone_depth(text_encoder)?; + let last = config.last_text_layer(); + if last > total_layers { + bail!( + "FLUX.3 text feature layers {:?} are outside the {total_layers}-layer text backbone", + config.text_layers + ); + } + let encoder = Qwen3TextEncoder::load_first_layers(text_encoder, last, dtype::BFLOAT16)?; + Ok(Self { + encoder, + layers: config.text_layers.clone(), + total_layers, + }) + } + + /// Upstream `get_prompt_embeds` for one prompt. + pub fn prompt_features( + &self, + input_ids: &[i32], + attention_mask: &[i32], + ) -> Result { + let t = i32::try_from(input_ids.len())?; + let ids = mlxcel_core::from_slice_i32(input_ids, &[1, t]); + let mask = mlxcel_core::from_slice_i32(attention_mask, &[1, t]); + let positions = mlxcel_core::from_slice_i32(&padding_positions(attention_mask), &[1, t]); + let states = self + .encoder + .hidden_states_at(&ids, Some(&mask), &positions)?; + let features: Vec> = self + .layers + .iter() + .map(|&layer| { + if layer == self.total_layers { + self.encoder.final_norm(&states[layer]) + } else { + mlxcel_core::copy(&states[layer]) + } + }) + .collect(); + let embeds = mlxcel_core::astype( + &mlxcel_core::concatenate_many(&features.iter().map(|a| &**a).collect::>(), -1), + dtype::BFLOAT16, + ); + mlxcel_core::eval(&embeds); + let text_ids = mlxcel_core::reshape(&prepare_text_ids(1, t), &[t, 4]); + mlxcel_core::eval(&text_ids); + Ok(PromptFeatures { embeds, text_ids }) + } +} + +/// `text_config.num_hidden_layers` (or the top-level field) of `config.json`. +fn backbone_depth(text_encoder: &Path) -> Result { + let path = text_encoder.join("config.json"); + let text = std::fs::read_to_string(&path) + .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", path.display()))?; + let config: serde_json::Value = serde_json::from_str(&text)?; + let inner = config.get("text_config").unwrap_or(&config); + inner + .get("num_hidden_layers") + .and_then(serde_json::Value::as_u64) + .map(|n| n as usize) + .ok_or_else(|| anyhow::anyhow!("{} has no num_hidden_layers", path.display())) +} + +#[cfg(test)] +#[path = "conditioner_tests.rs"] +mod tests; diff --git a/src/imagegen/flux3/conditioner_tests.rs b/src/imagegen/flux3/conditioner_tests.rs new file mode 100644 index 000000000..18f255bd4 --- /dev/null +++ b/src/imagegen/flux3/conditioner_tests.rs @@ -0,0 +1,52 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::*; + +#[test] +fn prompts_pad_to_multiples_of_80() { + // 1, 80 and 81 real tokens. + assert_eq!(padded_length(1, 80, 4096), 80); + assert_eq!(padded_length(80, 80, 4096), 80); + assert_eq!(padded_length(81, 80, 4096), 160); + // The cap truncates and is not rounded up past. + assert_eq!(padded_length(81, 80, 100), 100); + assert_eq!(padded_length(5000, 80, 4096), 4096); + assert_eq!(padded_length(4090, 80, 4096), 4096); + assert_eq!(padded_length(4000, 80, 4096), 4000); + // A pad multiple of 1 keeps the real length. + assert_eq!(padded_length(37, 1, 4096), 37); + // A one-token cap. + assert_eq!(padded_length(81, 80, 1), 1); +} + +#[test] +fn padded_tokens_sit_at_position_1() { + assert_eq!(padding_positions(&[1, 1, 1, 0, 0]), [0, 1, 2, 1, 1]); + assert_eq!(padding_positions(&[1]), [0]); + assert_eq!(padding_positions(&[1, 1, 1]), [0, 1, 2]); + assert!(padding_positions(&[]).is_empty()); + // A fully padded row (never produced, since a prompt has chat tokens). + assert_eq!(padding_positions(&[0, 0]), [1, 1]); +} + +#[test] +fn padding_positions_scale_linearly() { + // 4096 tokens, the cap, in one pass. + let mut mask = vec![1; 3000]; + mask.resize(4096, 0); + let positions = padding_positions(&mask); + assert_eq!(positions[2999], 2999); + assert!(positions[3000..].iter().all(|&p| p == 1)); +} diff --git a/src/imagegen/flux3/config.rs b/src/imagegen/flux3/config.rs new file mode 100644 index 000000000..e05775bd1 --- /dev/null +++ b/src/imagegen/flux3/config.rs @@ -0,0 +1,470 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! FLUX.3 package configuration and layout. +//! +//! A port of `Flux3Config.from_dict`, `is_flux3_config` and +//! `validate_dimensions` in +//! +//! and of `validate_model_layout` in `flux3/download.py`. The root +//! `config.json` is BFL's package description, not a transformers config: it +//! names no `model_type`, so the probe recognizes it with [`is_flux3_config`] +//! before any other rule runs. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use serde_json::Value; + +/// The reference encoder truncates prompts at this many tokens, chat tokens +/// included, whatever `text_encoder.max_tokens` says. +pub const MAX_TEXT_TOKENS: usize = 4096; +/// Smallest and largest output side, in pixels. +pub const MIN_IMAGE_SIDE: u32 = 64; +pub const MAX_IMAGE_SIDE: u32 = 4096; +/// Output sides must be multiples of this. +pub const SIZE_MULTIPLE: u32 = 16; + +/// Upstream `is_flux3_config`: a `dit` object whose `in_channels` names the +/// `image`, `image_cond` and `text` modes, and a `model` starting with +/// `flux-3-image`. +#[must_use] +pub fn is_flux3_config(metadata: &Value) -> bool { + let Some(dit) = metadata.get("dit").and_then(Value::as_object) else { + return false; + }; + let modes = dit.get("in_channels").and_then(Value::as_object); + let has_modes = modes.is_some_and(|m| { + ["image", "image_cond", "text"] + .iter() + .all(|k| m.contains_key(*k)) + }); + has_modes + && metadata + .get("model") + .and_then(Value::as_str) + .is_some_and(|m| m.starts_with("flux-3-image")) +} + +/// Upstream `validate_dimensions`: both sides multiples of 16 in `[64, 4096]`. +pub fn validate_dimensions(width: u32, height: u32) -> Result<()> { + if [width, height].iter().any(|&v| { + !(MIN_IMAGE_SIDE..=MAX_IMAGE_SIDE).contains(&v) || !v.is_multiple_of(SIZE_MULTIPLE) + }) { + bail!( + "FLUX.3 width and height must be multiples of {SIZE_MULTIPLE} in \ + [{MIN_IMAGE_SIDE}, {MAX_IMAGE_SIDE}], got {width}x{height}" + ); + } + Ok(()) +} + +/// Per-mode input widths of the transformer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct InChannels { + pub image: i32, + pub image_cond: i32, + pub text: i32, +} + +/// `Flux3Config`: the transformer, conditioner and sampler settings. +#[derive(Debug, Clone, PartialEq)] +pub struct Flux3Config { + pub hidden: i32, + pub heads: i32, + /// Early blocks per stream. + pub depth: usize, + /// Joint single-stream blocks. + pub depth_single: usize, + pub mlp_ratio: f64, + pub axes_dim: Vec, + pub theta: f32, + pub in_channels: InChannels, + pub image_rope_scale: f32, + /// Distilled flow map (Klein): a target-time embedding and no CFG. + pub flow_map: bool, + /// 1-based Qwen3-VL layers whose hidden states are concatenated. + pub text_layers: Vec, + pub pad_multiple: usize, + /// `min(text_encoder.max_tokens, 4096)`. + pub max_tokens: usize, + pub default_steps: u32, + pub default_guidance: f32, + /// Shift of the sampling schedule. + pub alpha: f64, +} + +impl Default for Flux3Config { + fn default() -> Self { + Self { + hidden: 3072, + heads: 24, + depth: 5, + depth_single: 28, + mlp_ratio: 3.0, + axes_dim: vec![32, 32, 32, 32], + theta: 10000.0, + in_channels: InChannels { + image: 128, + image_cond: 128, + text: 20480, + }, + image_rope_scale: 0.5, + flow_map: true, + text_layers: vec![4, 8, 12, 16, 20, 24, 28, 32], + pad_multiple: 80, + max_tokens: MAX_TEXT_TOKENS, + default_steps: 16, + default_guidance: 1.0, + alpha: 6.93, + } + } +} + +fn int_field(map: &serde_json::Map, key: &str, path: &str) -> Result> { + match map.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_i64() + .map(Some) + .with_context(|| format!("FLUX.3 config.json `{path}` must be an integer, got {v}")), + } +} + +fn float_field(map: &serde_json::Map, key: &str, path: &str) -> Result> { + match map.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .map(Some) + .with_context(|| format!("FLUX.3 config.json `{path}` must be a number, got {v}")), + } +} + +fn positive(value: i64, path: &str) -> Result { + if value < 1 { + bail!("FLUX.3 config.json `{path}` must be positive, got {value}"); + } + Ok(value) +} + +impl Flux3Config { + /// Upstream `Flux3Config.from_dict` plus `__post_init__`, with every + /// refusal naming the key it rejects. + pub fn from_value(metadata: &Value) -> Result { + let empty = serde_json::Map::new(); + if let Some(q) = metadata.get("quantization") + && !is_empty_json(q) + { + bail!( + "FLUX.3 config.json `quantization` is set ({q}); only the root bf16 package is \ + supported" + ); + } + let dit = match metadata.get("dit") { + None => &empty, + Some(Value::Object(map)) => map, + Some(v) => bail!("FLUX.3 config.json `dit` must be an object, got {v}"), + }; + match dit.get("out_modes") { + None | Some(Value::Null) => {} + Some(Value::Array(modes)) => { + if let Some(bad) = modes.iter().find(|m| m.as_str() != Some("image")) { + bail!( + "FLUX.3 config.json `dit.out_modes` lists {bad}; only the `image` output \ + mode is supported" + ); + } + } + Some(v) => bail!("FLUX.3 config.json `dit.out_modes` must be a list, got {v}"), + } + if let Some(v) = dit.get("vec_in_dim") + && !v.is_null() + { + bail!( + "FLUX.3 config.json `dit.vec_in_dim` is {v}; vector conditioning is not supported" + ); + } + + let mut config = Self::default(); + if let Some(v) = int_field(dit, "hidden", "dit.hidden")? { + config.hidden = i32::try_from(positive(v, "dit.hidden")?)?; + } + if let Some(v) = int_field(dit, "heads", "dit.heads")? { + config.heads = i32::try_from(positive(v, "dit.heads")?)?; + } + if let Some(v) = int_field(dit, "depth", "dit.depth")? { + config.depth = + usize::try_from(v).context("FLUX.3 config.json `dit.depth` is negative")?; + } + if let Some(v) = int_field(dit, "depth_single", "dit.depth_single")? { + config.depth_single = + usize::try_from(v).context("FLUX.3 config.json `dit.depth_single` is negative")?; + } + if let Some(v) = float_field(dit, "mlp_ratio", "dit.mlp_ratio")? { + config.mlp_ratio = v; + } + if let Some(v) = dit.get("axes_dim").filter(|v| !v.is_null()) { + config.axes_dim = v + .as_array() + .and_then(|a| { + a.iter() + .map(|x| x.as_i64().and_then(|x| i32::try_from(x).ok())) + .collect::>>() + }) + .with_context(|| { + format!("FLUX.3 config.json `dit.axes_dim` must be a list of integers, got {v}") + })?; + } + if let Some(v) = float_field(dit, "theta", "dit.theta")? { + config.theta = v as f32; + } + if let Some(v) = dit.get("in_channels").filter(|v| !v.is_null()) { + let map = v.as_object().with_context(|| { + format!("FLUX.3 config.json `dit.in_channels` must be an object, got {v}") + })?; + let mode = |key: &str, default: i32| -> Result { + match int_field(map, key, &format!("dit.in_channels.{key}"))? { + None => Ok(default), + Some(v) => Ok(i32::try_from(positive( + v, + &format!("dit.in_channels.{key}"), + )?)?), + } + }; + config.in_channels = InChannels { + image: mode("image", config.in_channels.image)?, + image_cond: mode("image_cond", config.in_channels.image_cond)?, + text: mode("text", config.in_channels.text)?, + }; + } + if let Some(v) = float_field(dit, "image_rope_scale", "dit.image_rope_scale")? { + config.image_rope_scale = v as f32; + } + match dit.get("flow_map") { + None | Some(Value::Null) => {} + Some(Value::Bool(b)) => config.flow_map = *b, + Some(v) => bail!("FLUX.3 config.json `dit.flow_map` must be true or false, got {v}"), + } + + let text = match metadata.get("text_encoder") { + None | Some(Value::Null) => &empty, + Some(Value::Object(map)) => map, + Some(v) => bail!("FLUX.3 config.json `text_encoder` must be an object, got {v}"), + }; + if let Some(v) = text.get("layers").filter(|v| !v.is_null()) { + config.text_layers = v + .as_array() + .and_then(|a| { + a.iter() + .map(|x| x.as_u64().and_then(|x| usize::try_from(x).ok())) + .collect::>>() + }) + .with_context(|| { + format!( + "FLUX.3 config.json `text_encoder.layers` must be a list of layer \ + numbers, got {v}" + ) + })?; + } + if let Some(v) = int_field(text, "pad_multiple", "text_encoder.pad_multiple")? { + config.pad_multiple = usize::try_from(positive(v, "text_encoder.pad_multiple")?)?; + } + if let Some(v) = int_field(text, "max_tokens", "text_encoder.max_tokens")? { + let v = usize::try_from(positive(v, "text_encoder.max_tokens")?)?; + config.max_tokens = v.min(MAX_TEXT_TOKENS); + } + + let sampler = match metadata.get("sampler") { + None | Some(Value::Null) => &empty, + Some(Value::Object(map)) => map, + Some(v) => bail!("FLUX.3 config.json `sampler` must be an object, got {v}"), + }; + if let Some(v) = int_field(sampler, "steps", "sampler.steps")? { + config.default_steps = u32::try_from(positive(v, "sampler.steps")?)?; + } + if let Some(v) = float_field(sampler, "guidance", "sampler.guidance")? { + config.default_guidance = v as f32; + } + if let Some(v) = float_field(sampler, "alpha", "sampler.alpha")? { + config.alpha = v; + } + config.validate()?; + Ok(config) + } + + /// `__post_init__` plus the checks the loader and sampler rely on. + pub fn validate(&self) -> Result<()> { + if self.hidden % self.heads != 0 + || self.axes_dim.iter().sum::() != self.hidden / self.heads + { + bail!( + "FLUX.3 config.json `dit.axes_dim` {:?} must sum to the attention head dimension \ + ({} / {})", + self.axes_dim, + self.hidden, + self.heads + ); + } + if self.axes_dim.iter().any(|&d| d <= 0 || d % 2 != 0) { + bail!( + "FLUX.3 config.json `dit.axes_dim` {:?} must hold positive even sizes", + self.axes_dim + ); + } + if !(self.mlp_ratio.is_finite() && self.mlp_ratio > 0.0) || self.mlp_hidden() < 1 { + bail!( + "FLUX.3 config.json `dit.mlp_ratio` must be positive, got {}", + self.mlp_ratio + ); + } + if !(self.theta.is_finite() && self.theta > 0.0) { + bail!( + "FLUX.3 config.json `dit.theta` must be positive, got {}", + self.theta + ); + } + if !self.image_rope_scale.is_finite() { + bail!( + "FLUX.3 config.json `dit.image_rope_scale` must be finite, got {}", + self.image_rope_scale + ); + } + if self.text_layers.is_empty() || self.text_layers.contains(&0) { + bail!( + "FLUX.3 config.json `text_encoder.layers` must list layer numbers from 1, got {:?}", + self.text_layers + ); + } + if !(self.default_guidance.is_finite() && self.default_guidance >= 0.0) { + bail!( + "FLUX.3 config.json `sampler.guidance` must be finite and non-negative, got {}", + self.default_guidance + ); + } + if !(self.alpha.is_finite() && self.alpha > 0.0) { + bail!( + "FLUX.3 config.json `sampler.alpha` must be positive, got {}", + self.alpha + ); + } + Ok(()) + } + + /// Read `/config.json`, refusing a package that is not FLUX.3. + pub fn from_dir(dir: &Path) -> Result { + let path = dir.join("config.json"); + let text = std::fs::read_to_string(&path) + .with_context(|| format!("cannot read {}", path.display()))?; + let metadata: Value = serde_json::from_str(&text) + .with_context(|| format!("cannot parse {}", path.display()))?; + if !is_flux3_config(&metadata) { + bail!("Not a FLUX.3 model package: {}", dir.display()); + } + Self::from_value(&metadata) + } + + /// Width of the SwiGLU hidden layer: `int(hidden * mlp_ratio)`. + #[must_use] + pub fn mlp_hidden(&self) -> i32 { + (f64::from(self.hidden) * self.mlp_ratio) as i32 + } + + /// Attention head width. + #[must_use] + pub fn head_dim(&self) -> i32 { + self.hidden / self.heads + } + + /// The deepest tapped text layer: later layers are never loaded. + #[must_use] + pub fn last_text_layer(&self) -> usize { + self.text_layers.iter().copied().max().unwrap_or(0) + } + + /// `flux3-klein` for a flow map, `flux3-klein-base` otherwise. + #[must_use] + pub fn variant(&self) -> &'static str { + if self.flow_map { + "flux3-klein" + } else { + "flux3-klein-base" + } + } +} + +/// Python truthiness of a JSON value, for `if metadata.get("quantization")`. +fn is_empty_json(v: &Value) -> bool { + match v { + Value::Null => true, + Value::Bool(b) => !b, + Value::Number(n) => n.as_f64() == Some(0.0), + Value::String(s) => s.is_empty(), + Value::Array(a) => a.is_empty(), + Value::Object(o) => o.is_empty(), + } +} + +/// Files a FLUX.3 package needs, as upstream `validate_model_layout` lists them. +pub struct Flux3Layout { + pub root: PathBuf, + pub transformer: PathBuf, + pub vae: PathBuf, + pub text_encoder: PathBuf, +} + +impl Flux3Layout { + /// Check every required file and report all the missing ones at once. + pub fn from_dir(root: &Path) -> Result { + let text_encoder = root.join("text_encoder"); + let has_shard = std::fs::read_dir(&text_encoder) + .map(|entries| { + entries + .filter_map(|e| e.ok()) + .any(|e| e.path().extension().is_some_and(|x| x == "safetensors")) + }) + .unwrap_or(false); + let mut missing: Vec<&str> = Vec::new(); + for (path, label) in [ + ("model.safetensors", "model.safetensors"), + ("ae.safetensors", "ae.safetensors"), + ("text_encoder/config.json", "text_encoder/config.json"), + ("text_encoder/tokenizer.json", "text_encoder/tokenizer.json"), + ] { + if !root.join(path).is_file() { + missing.push(label); + } + } + if !has_shard { + missing.push("text_encoder/*.safetensors"); + } + if !missing.is_empty() { + bail!( + "Missing FLUX.3 files under {}: {}", + root.display(), + missing.join(", ") + ); + } + Ok(Self { + root: root.to_path_buf(), + transformer: root.join("model.safetensors"), + vae: root.join("ae.safetensors"), + text_encoder, + }) + } +} + +#[cfg(test)] +#[path = "config_tests.rs"] +mod tests; diff --git a/src/imagegen/flux3/config_tests.rs b/src/imagegen/flux3/config_tests.rs new file mode 100644 index 000000000..c4db9e8cd --- /dev/null +++ b/src/imagegen/flux3/config_tests.rs @@ -0,0 +1,232 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use serde_json::json; + +use super::*; + +/// The root `config.json` of `black-forest-labs/flux-3-image-klein` at +/// revision 3b767ff9. +fn published() -> Value { + json!({ + "format_version": 1, + "model": "flux-3-image-klein", + "quantization": null, + "torch_dtype": "bfloat16", + "dit": { + "hidden": 3072, "heads": 24, "depth": 5, "depth_single": 28, + "mlp_ratio": 3.0, "axes_dim": [32, 32, 32, 32], "theta": 10000, + "in_channels": {"image": 128, "image_cond": 128, "text": 20480}, + "out_modes": ["image"], "vec_in_dim": null, + "image_rope_scale": 0.5, "flow_map": true + }, + "text_encoder": { + "path": "text_encoder", "tokenizer": "text_encoder", + "layers": [4, 8, 12, 16, 20, 24, 28, 32], + "pad_multiple": 80, "max_tokens": 8192, "dtype": "bfloat16" + }, + "vae": {"path": "ae.safetensors", "dtype": "float32"}, + "sampler": {"steps": 16, "guidance": null, "alpha": 6.93, "size": [1024, 1024]} + }) +} + +fn err(v: &Value) -> String { + format!("{:#}", Flux3Config::from_value(v).unwrap_err()) +} + +#[test] +fn the_published_klein_package_is_flux3() { + assert!(is_flux3_config(&published())); + let config = Flux3Config::from_value(&published()).unwrap(); + assert_eq!(config, Flux3Config::default()); + assert_eq!(config.variant(), "flux3-klein"); + assert_eq!(config.mlp_hidden(), 9216); + assert_eq!(config.head_dim(), 128); + assert_eq!(config.last_text_layer(), 32); + // `max_tokens` 8192 is capped to the reference encoder's 4096. + assert_eq!(config.max_tokens, MAX_TEXT_TOKENS); + // A null `sampler.guidance` is 1. + assert_eq!(config.default_guidance, 1.0); +} + +#[test] +fn the_base_package_takes_its_sampler_block() { + let mut base = published(); + base["model"] = json!("flux-3-image-klein-base"); + base["dit"]["flow_map"] = json!(false); + base["sampler"] = json!({"steps": 50, "guidance": 3.5, "alpha": 6.93}); + let config = Flux3Config::from_value(&base).unwrap(); + assert!(!config.flow_map); + assert_eq!(config.variant(), "flux3-klein-base"); + assert_eq!((config.default_steps, config.default_guidance), (50, 3.5)); +} + +#[test] +fn flux2_and_other_configs_are_not_flux3() { + // A FLUX.2 Klein transformer config. + assert!(!is_flux3_config(&json!({ + "_class_name": "Flux2Transformer2DModel", + "in_channels": 128, "num_layers": 5 + }))); + // A FLUX.2 pipeline index. + assert!(!is_flux3_config( + &json!({"_class_name": "Flux2KleinPipeline"}) + )); + // The right model name without the three input modes. + let mut no_cond = published(); + no_cond["dit"]["in_channels"] = json!({"image": 128, "text": 20480}); + assert!(!is_flux3_config(&no_cond)); + // The right modes under another model name. + let mut renamed = published(); + renamed["model"] = json!("flux-2-klein"); + assert!(!is_flux3_config(&renamed)); + // No `dit` block, or one that is not an object. + assert!(!is_flux3_config(&json!({"model": "flux-3-image-klein"}))); + assert!(!is_flux3_config( + &json!({"model": "flux-3-image-klein", "dit": []}) + )); +} + +#[test] +fn refusals_name_the_key() { + let mut quantized = published(); + quantized["quantization"] = json!({"bits": 4}); + assert!( + err(&quantized).contains("`quantization`"), + "{}", + err(&quantized) + ); + // An empty quantization block is no quantization, as upstream's truthiness test. + let mut empty = published(); + empty["quantization"] = json!({}); + assert!(Flux3Config::from_value(&empty).is_ok()); + + let mut modes = published(); + modes["dit"]["out_modes"] = json!(["image", "depth"]); + assert!(err(&modes).contains("`dit.out_modes`"), "{}", err(&modes)); + + let mut vec_in = published(); + vec_in["dit"]["vec_in_dim"] = json!(768); + assert!( + err(&vec_in).contains("`dit.vec_in_dim`"), + "{}", + err(&vec_in) + ); + + let mut axes = published(); + axes["dit"]["axes_dim"] = json!([32, 32, 32, 30]); + assert!(err(&axes).contains("`dit.axes_dim`"), "{}", err(&axes)); + + let mut odd = published(); + odd["dit"]["axes_dim"] = json!([33, 31, 32, 32]); + assert!(err(&odd).contains("even"), "{}", err(&odd)); + + let mut layers = published(); + layers["text_encoder"]["layers"] = json!([0, 8]); + assert!( + err(&layers).contains("`text_encoder.layers`"), + "{}", + err(&layers) + ); + + let mut no_layers = published(); + no_layers["text_encoder"]["layers"] = json!([]); + assert!(err(&no_layers).contains("`text_encoder.layers`")); + + let mut steps = published(); + steps["sampler"]["steps"] = json!(0); + assert!(err(&steps).contains("`sampler.steps`"), "{}", err(&steps)); + + let mut guidance = published(); + guidance["sampler"]["guidance"] = json!(-1.0); + assert!(err(&guidance).contains("`sampler.guidance`")); + + let mut alpha = published(); + alpha["sampler"]["alpha"] = json!(0.0); + assert!(err(&alpha).contains("`sampler.alpha`")); + + let mut pad = published(); + pad["text_encoder"]["pad_multiple"] = json!(0); + assert!(err(&pad).contains("`text_encoder.pad_multiple`")); + + let mut kind = published(); + kind["dit"]["hidden"] = json!("wide"); + assert!(err(&kind).contains("`dit.hidden`"), "{}", err(&kind)); +} + +#[test] +fn a_small_max_tokens_is_kept() { + let mut small = published(); + small["text_encoder"]["max_tokens"] = json!(1); + assert_eq!(Flux3Config::from_value(&small).unwrap().max_tokens, 1); + small["text_encoder"]["max_tokens"] = json!(4097); + assert_eq!(Flux3Config::from_value(&small).unwrap().max_tokens, 4096); +} + +#[test] +fn dimensions_are_multiples_of_16_in_64_to_4096() { + for (w, h) in [(64, 64), (4096, 4096), (512, 1024), (80, 4080)] { + assert!(validate_dimensions(w, h).is_ok(), "{w}x{h}"); + } + for (w, h) in [ + (0, 512), + (48, 512), + (63, 512), + (512, 4112), + (520, 512), + (512, 100), + ] { + let e = validate_dimensions(w, h).unwrap_err().to_string(); + assert!(e.contains("multiples of 16 in [64, 4096]"), "{w}x{h}: {e}"); + } +} + +#[test] +fn a_missing_layout_lists_every_missing_file() { + let dir = tempfile::tempdir().unwrap(); + let e = format!("{:#}", Flux3Layout::from_dir(dir.path()).err().unwrap()); + for f in [ + "model.safetensors", + "ae.safetensors", + "text_encoder/config.json", + "text_encoder/tokenizer.json", + "text_encoder/*.safetensors", + ] { + assert!(e.contains(f), "{f} missing from: {e}"); + } + std::fs::write(dir.path().join("model.safetensors"), b"").unwrap(); + std::fs::write(dir.path().join("ae.safetensors"), b"").unwrap(); + std::fs::create_dir(dir.path().join("text_encoder")).unwrap(); + for f in [ + "config.json", + "tokenizer.json", + "model-00001-of-00002.safetensors", + ] { + std::fs::write(dir.path().join("text_encoder").join(f), b"").unwrap(); + } + let layout = Flux3Layout::from_dir(dir.path()).unwrap(); + assert_eq!(layout.vae, dir.path().join("ae.safetensors")); +} + +#[test] +fn from_dir_refuses_a_package_that_is_not_flux3() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("config.json"), + json!({"model_type": "qwen3"}).to_string(), + ) + .unwrap(); + let e = Flux3Config::from_dir(dir.path()).unwrap_err().to_string(); + assert!(e.contains("Not a FLUX.3 model package"), "{e}"); +} diff --git a/src/imagegen/flux3/edit.rs b/src/imagegen/flux3/edit.rs new file mode 100644 index 000000000..cc1659b29 --- /dev/null +++ b/src/imagegen/flux3/edit.rs @@ -0,0 +1,229 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! FLUX.3 reference images. +//! +//! A port of `prepare_reference` and the reference branch of +//! `Flux3Image._run` in +//! . +//! One reference keeps its aspect ratio within 4 MP and 4096 px per side, is +//! Lanczos-resized and reflect-padded (symmetric below 17 px) to multiples of +//! 16, and the output is cropped back to the unpadded area when no size is +//! requested. Several references are each capped at 1 MP and center-cropped +//! to multiples of 16. Each prepared reference is VAE-encoded to bf16 tokens +//! of the `image_cond` stream, with ids on its own `-1 - index` layer. +//! +//! The caller turns references upright by their EXIF orientation when it +//! decodes them (`open_upright` on the CLI, the server's image decoder); +//! `to_rgb8` then drops any alpha channel, as PIL's `convert("RGB")` does. +//! The resize uses the `image` crate's Lanczos3 filter, not PIL's, so a +//! resized reference differs from upstream's by interpolation rounding. + +use anyhow::Result; +use image::imageops::FilterType; +use image::{DynamicImage, RgbImage}; +use mlxcel_core::{MlxArray, UniquePtr, dtype}; + +use super::pipeline::image_ids; +use crate::imagegen::Flux2Vae; +use crate::imagegen::latent::{pack_latents, patchify_latents}; + +/// Pixel budget of a lone reference and of each of several. +pub const SINGLE_REFERENCE_PIXELS: f64 = 4.0 * 1024.0 * 1024.0; +pub const MULTI_REFERENCE_PIXELS: f64 = 1024.0 * 1024.0; +/// Most reference images one edit takes. +pub const MAX_REFERENCES: usize = 10; + +/// `(left, top, right, bottom)` in pixels. +pub type CropBox = (u32, u32, u32, u32); + +/// Geometry of a lone reference: the resized size inside the padded canvas. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SingleGeometry { + pub fit: (u32, u32), + pub canvas: (u32, u32), +} + +impl SingleGeometry { + /// Where the fitted image sits on the canvas, when padding was added. + #[must_use] + pub fn crop(&self) -> Option { + if self.canvas == self.fit { + return None; + } + let left = (self.canvas.0 - self.fit.0) / 2; + let top = (self.canvas.1 - self.fit.1) / 2; + Some((left, top, left + self.fit.0, top + self.fit.1)) + } +} + +/// `math.ceil(v / 16) * 16` clamped to `[64, 4096]`. +fn canvas_side(v: u32) -> u32 { + (v.div_ceil(16) * 16).clamp(64, 4096) +} + +/// The single-reference branch of `prepare_reference`, sizes only. +#[must_use] +pub fn single_geometry(width: u32, height: u32) -> SingleGeometry { + let (w, h) = (f64::from(width), f64::from(height)); + let mut scale = 1.0_f64 + .min((SINGLE_REFERENCE_PIXELS / (w * h)).sqrt()) + .min(4096.0 / w.max(h)); + loop { + // Python's `round` rounds half to even. + let fit = ( + ((w * scale).round_ties_even() as u32).max(1), + ((h * scale).round_ties_even() as u32).max(1), + ); + let canvas = (canvas_side(fit.0), canvas_side(fit.1)); + if f64::from(canvas.0) * f64::from(canvas.1) <= SINGLE_REFERENCE_PIXELS { + return SingleGeometry { fit, canvas }; + } + scale *= 0.995; + } +} + +/// The multi-reference branch of `prepare_reference`, sizes only: the resized +/// size and the centered crop to multiples of 16. +#[must_use] +pub fn multi_geometry(width: u32, height: u32) -> ((u32, u32), CropBox) { + let (w, h) = (f64::from(width), f64::from(height)); + let scale = 1.0_f64.min((MULTI_REFERENCE_PIXELS / (w * h)).sqrt()); + // `int()` truncates. + let rw = ((w * scale) as u32).max(16); + let rh = ((h * scale) as u32).max(16); + let left = (rw % 16) / 2; + let top = (rh % 16) / 2; + ( + (rw, rh), + (left, top, left + rw / 16 * 16, top + rh / 16 * 16), + ) +} + +/// The output size of an edit that names none: the first reference's padded +/// canvas, as upstream takes `references[0].size` for a lone reference. +#[must_use] +pub fn default_edit_size(width: u32, height: u32) -> (u32, u32) { + single_geometry(width, height).canvas +} + +/// `np.pad(mode="reflect")` index for any pad width. +fn reflect_index(i: i64, n: i64) -> u32 { + if n == 1 { + return 0; + } + let period = 2 * (n - 1); + let i = i.rem_euclid(period); + (if i >= n { period - i } else { i }) as u32 +} + +/// `np.pad(mode="symmetric")` index for any pad width. +fn symmetric_index(i: i64, n: i64) -> u32 { + let period = 2 * n; + let i = i.rem_euclid(period); + (if i >= n { period - 1 - i } else { i }) as u32 +} + +/// A prepared reference and, for a lone padded one, the area to crop back to. +pub struct PreparedReference { + pub image: RgbImage, + pub crop: Option, +} + +fn resize(rgb: RgbImage, size: (u32, u32)) -> RgbImage { + if rgb.dimensions() == size { + return rgb; + } + image::imageops::resize(&rgb, size.0, size.1, FilterType::Lanczos3) +} + +/// Upstream `prepare_reference(image, multi=...)`. +#[must_use] +pub fn prepare_reference(image: &DynamicImage, multi: bool) -> PreparedReference { + let rgb = image.to_rgb8(); + let (w, h) = rgb.dimensions(); + if multi { + let (size, (left, top, right, bottom)) = multi_geometry(w, h); + let resized = resize(rgb, size); + let cropped = + image::imageops::crop_imm(&resized, left, top, right - left, bottom - top).to_image(); + return PreparedReference { + image: cropped, + crop: None, + }; + } + let geometry = single_geometry(w, h); + let fitted = resize(rgb, geometry.fit); + let (fw, fh) = geometry.fit; + let (cw, ch) = geometry.canvas; + let left = i64::from((cw - fw) / 2); + let top = i64::from((ch - fh) / 2); + let index: fn(i64, i64) -> u32 = if fw.min(fh) > 16 { + reflect_index + } else { + symmetric_index + }; + let padded = RgbImage::from_fn(cw, ch, |x, y| { + let sx = index(i64::from(x) - left, i64::from(fw)); + let sy = index(i64::from(y) - top, i64::from(fh)); + *fitted.get_pixel(sx, sy) + }); + PreparedReference { + image: padded, + crop: geometry.crop(), + } +} + +/// `np.asarray(image) / 127.5 - 1` in f32, as `[1, 3, H, W]` for the VAE. +fn pixels_nchw(image: &RgbImage) -> UniquePtr { + let (w, h) = (image.width() as usize, image.height() as usize); + let mut chw = vec![0.0_f32; 3 * w * h]; + for (i, px) in image.pixels().enumerate() { + for c in 0..3 { + chw[c * w * h + i] = f32::from(px[c]) / 127.5 - 1.0; + } + } + mlxcel_core::from_slice_f32(&chw, &[1, 3, h as i32, w as i32]) +} + +/// `vae.encode(pixels).astype(bf16)` for every reference, concatenated, and +/// their ids: `([1, sum L_r, 128], [sum L_r, 4])`. +pub fn encode_references( + vae: &Flux2Vae, + references: &[RgbImage], + rope_scale: f32, +) -> Result<(UniquePtr, UniquePtr)> { + let mut tokens = Vec::with_capacity(references.len()); + let mut ids = Vec::with_capacity(references.len()); + for (index, reference) in references.iter().enumerate() { + let mean = vae.encode(&pixels_nchw(reference))?; + let normalized = vae.bn_normalize(&*patchify_latents(&mean)?)?; + let packed = pack_latents(&normalized)?; + tokens.push(mlxcel_core::astype(&packed, dtype::BFLOAT16)); + ids.push(image_ids( + reference.height(), + reference.width(), + Some(index), + rope_scale, + )); + } + let tokens = mlxcel_core::concatenate_many(&tokens.iter().map(|a| &**a).collect::>(), 1); + let ids = mlxcel_core::concatenate_many(&ids.iter().map(|a| &**a).collect::>(), 0); + mlxcel_core::eval(&tokens); + Ok((tokens, ids)) +} + +#[cfg(test)] +#[path = "edit_tests.rs"] +mod tests; diff --git a/src/imagegen/flux3/edit_tests.rs b/src/imagegen/flux3/edit_tests.rs new file mode 100644 index 000000000..f382a3574 --- /dev/null +++ b/src/imagegen/flux3/edit_tests.rs @@ -0,0 +1,142 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Expected sizes, crops and checksums come from upstream `prepare_reference` +//! (`tests/fixtures/flux3/generate_flux3_unit_fixtures.py`, mlx-vlm e8035ae) +//! on the synthetic picture [`picture`]. + +use image::{DynamicImage, Rgb, RgbImage, RgbaImage}; + +use super::*; + +/// Pixel `(x, y)` = `((7x + 13y) % 256, (3x + 5y) % 256, (x + y) % 256)`. +fn picture(w: u32, h: u32) -> DynamicImage { + DynamicImage::ImageRgb8(RgbImage::from_fn(w, h, |x, y| { + Rgb([ + ((x * 7 + y * 13) % 256) as u8, + ((x * 3 + y * 5) % 256) as u8, + ((x + y) % 256) as u8, + ]) + })) +} + +/// `sum(pixel[i] * (i % 9973))` over the HWC bytes. +fn checksum(image: &RgbImage) -> i64 { + image + .as_raw() + .iter() + .enumerate() + .map(|(i, &v)| i64::from(v) * (i as i64 % 9973)) + .sum() +} + +/// `(source size, single canvas, crop, multi size)` from upstream. +const GEOMETRY: &[((u32, u32), (u32, u32), Option, (u32, u32))] = &[ + ((512, 512), (512, 512), None, (512, 512)), + ((20, 18), (64, 64), Some((22, 23, 42, 41)), (16, 16)), + ((10, 7), (64, 64), Some((27, 28, 37, 35)), (16, 16)), + ( + (1000, 750), + (1008, 752), + Some((4, 1, 1004, 751)), + (992, 736), + ), + ((5000, 100), (4096, 96), Some((0, 7, 4096, 89)), (4992, 96)), + ((3000, 2000), (2496, 1664), None, (1248, 832)), +]; + +#[test] +fn reference_sizes_match_upstream() { + for &(size, canvas, crop, multi) in GEOMETRY { + let single = single_geometry(size.0, size.1); + assert_eq!(single.canvas, canvas, "{size:?} canvas"); + assert_eq!(single.crop(), crop, "{size:?} crop"); + assert_eq!( + default_edit_size(size.0, size.1), + canvas, + "{size:?} default" + ); + let ((rw, rh), (l, t, r, b)) = multi_geometry(size.0, size.1); + assert!(rw >= r && rh >= b, "{size:?} crop inside the resized image"); + assert_eq!((r - l, b - t), multi, "{size:?} multi"); + } +} + +#[test] +fn single_canvases_stay_within_the_pixel_budget() { + for (w, h) in [ + (1, 1), + (1, 9000), + (4096, 4096), + (2049, 2049), + (7000, 3), + (16, 16), + ] { + let g = single_geometry(w, h); + assert!( + g.canvas.0.is_multiple_of(16) && g.canvas.1.is_multiple_of(16), + "{w}x{h}" + ); + assert!((64..=4096).contains(&g.canvas.0) && (64..=4096).contains(&g.canvas.1)); + assert!(u64::from(g.canvas.0) * u64::from(g.canvas.1) <= 4 * 1024 * 1024); + assert!(g.fit.0 <= g.canvas.0 && g.fit.1 <= g.canvas.1); + } +} + +#[test] +fn padded_pixels_match_upstream() { + // Sources that need no resize, so the bytes are upstream's exactly: + // reflect padding (20x18, 1000x750), symmetric padding below 17 px (10x7), + // and no padding (512x512). + for (size, want) in [ + ((512, 512), 498_798_440_851_i64), + ((20, 18), 4_052_491_028), + ((10, 7), 1_948_614_504), + ((1000, 750), 1_445_630_626_294), + ] { + let prepared = prepare_reference(&picture(size.0, size.1), false); + assert_eq!(checksum(&prepared.image), want, "{size:?}"); + } +} + +#[test] +fn the_crop_recovers_the_unpadded_reference() { + let source = picture(20, 18); + let prepared = prepare_reference(&source, false); + let (l, t, r, b) = prepared.crop.unwrap(); + let back = image::imageops::crop_imm(&prepared.image, l, t, r - l, b - t).to_image(); + assert_eq!(back, source.to_rgb8()); +} + +#[test] +fn several_references_are_center_cropped_to_multiples_of_16() { + let prepared = prepare_reference(&picture(20, 18), true); + assert_eq!(prepared.image.dimensions(), (16, 16)); + assert!(prepared.crop.is_none()); + // (20 % 16) / 2 = 2 columns and (18 % 16) / 2 = 1 row are cut on the left + // and top. + assert_eq!( + prepared.image.get_pixel(0, 0), + picture(20, 18).to_rgb8().get_pixel(2, 1) + ); +} + +#[test] +fn a_transparent_reference_drops_its_alpha() { + let rgba = DynamicImage::ImageRgba8(RgbaImage::from_fn(64, 64, |x, _| { + image::Rgba([x as u8, 10, 20, 0]) + })); + let prepared = prepare_reference(&rgba, false); + assert_eq!(prepared.image.get_pixel(5, 0), &Rgb([5, 10, 20])); +} diff --git a/src/imagegen/flux3/mod.rs b/src/imagegen/flux3/mod.rs new file mode 100644 index 000000000..d9aa19da1 --- /dev/null +++ b/src/imagegen/flux3/mod.rs @@ -0,0 +1,338 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! FLUX.3 Image Klein text-to-image and editing (family `flux3`). +//! +//! A port of +//! (which credits BFL's Apache-2.0 reference, +//! ) 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): generation, editing with 1 to 10 references, and layout boxes. +//! See `docs/image-generation.md`. +//! +//! The transformer is new (three early streams, a joint single stream, a +//! flow-map target-time embedding), so this is its own family rather than a +//! FLUX.2 variant; it reuses FLUX.2's RoPE, time embedding, text ids, latent +//! packing, tokenizer wrapper and VAE, and the shared Qwen3 conditioner. +//! +//! Prompt expansion through the `flux-3-image-klein-pup` VLM, which upstream +//! enables by default, is not implemented: `upsample_prompt: true` and +//! `prompt_expansion_model` are refused, and every run is upstream's +//! `upsample_prompt=False` path. +//! +//! Generation batches `n` images from one noise tensor and reports `seed` for +//! each, as FLUX.2 does; edits run once per image with seed `seed + i`. + +pub mod boxes; +pub mod conditioner; +pub mod config; +pub mod edit; +pub mod pipeline; +pub mod transformer; +pub mod weights; + +#[cfg(test)] +mod parity_tests; + +use std::path::Path; + +use anyhow::{Result, bail}; +use image::DynamicImage; +use serde_json::{Map, Value}; + +use self::config::{Flux3Config, Flux3Layout, MAX_TEXT_TOKENS, validate_dimensions}; +use self::edit::{MAX_REFERENCES, PreparedReference, default_edit_size, prepare_reference}; +use self::pipeline::{Flux3Pipeline, RunSpec}; +use super::flux2::Flux2Model; +use super::pipeline::{ + GeneratedImage, ImageGenerationModel, ImageRequest, ImageSamplingDefaults, ImageTask, +}; + +/// Probe family name. +pub const FAMILY: &str = "flux3"; + +/// Request options read from `extra` (`--gen-kwargs`). +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Flux3Options { + /// Prompt token cap, `1..=4096`; `None` is the package's `max_tokens`. + pub max_sequence_length: Option, + /// Layout boxes, appended to the prompt on the `0..1000` canvas. + pub boxes: Vec, +} + +impl Flux3Options { + /// Parse and check `extra` against a request for `n` images. + pub fn from_extra(extra: &Map, n: u32) -> Result { + let max_sequence_length = match extra.get("max_sequence_length") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64() { + Some(n) if (1..=MAX_TEXT_TOKENS as u64).contains(&n) => Some(n as usize), + _ => bail!( + "max_sequence_length must be an integer between 1 and {MAX_TEXT_TOKENS}, \ + got {v}" + ), + }, + }; + match extra.get("num_images") { + None | Some(Value::Null) => {} + Some(v) if v.as_u64() == Some(u64::from(n)) => {} + Some(v) => bail!( + "num_images is the request's image count (n = {n}) and must match it, got {v}" + ), + } + match extra.get("upsample_prompt") { + None | Some(Value::Null) | Some(Value::Bool(false)) => {} + Some(Value::Bool(true)) => bail!( + "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" + ), + Some(v) => bail!("upsample_prompt must be true or false, got {v}"), + } + if let Some(v) = extra.get("prompt_expansion_model") + && !v.is_null() + { + bail!( + "FLUX.3 prompt_expansion_model is not supported by mlxcel: prompt expansion is \ + not implemented; pass a detailed caption instead" + ); + } + let boxes = match extra.get("boxes") { + None | Some(Value::Null) => Vec::new(), + Some(Value::Array(items)) => items.clone(), + Some(v) => bail!("boxes must be a list of box objects, got {v}"), + }; + // Malformed boxes are the caller's fault: reject them before any work. + boxes::to_canvas(&boxes)?; + Ok(Self { + max_sequence_length, + boxes, + }) + } +} + +/// A loaded FLUX.3 package. +pub struct Flux3Model { + pipeline: Flux3Pipeline, +} + +impl Flux3Model { + /// Check the layout and config and read the tokenizer. The text encoder, + /// transformer and VAE load on the first request, as upstream does. + pub fn load(path: &Path) -> Result { + let config = Flux3Config::from_dir(path)?; + let layout = Flux3Layout::from_dir(path)?; + Ok(Self { + pipeline: Flux3Pipeline::new(layout, config)?, + }) + } + + #[must_use] + pub fn pipeline(&self) -> &Flux3Pipeline { + &self.pipeline + } + + fn config(&self) -> &Flux3Config { + self.pipeline.config() + } + + /// Prepare the references, choose the output size and the crop-back. + /// + /// The CLI and the server fill an edit's missing size from + /// [`ImageGenerationModel::default_edit_size`], which sees only the first + /// reference: a lone reference's padded canvas. A size equal to that + /// default is therefore read as "no size requested": a lone padded + /// reference is cropped back to its unpadded area, and several + /// references take the first one's own (1 MP) size, as upstream does. + fn plan_edit(references: &[DynamicImage], width: u32, height: u32) -> Result { + let Some(first) = references.first() else { + bail!("FLUX.3 editing requires at least one reference image"); + }; + let multi = references.len() > 1; + let prepared: Vec = references + .iter() + .map(|r| prepare_reference(r, multi)) + .collect(); + let defaulted = (width, height) == default_edit_size(first.width(), first.height()); + let size = if multi && defaulted { + prepared[0].image.dimensions() + } else { + (width, height) + }; + validate_dimensions(size.0, size.1)?; + let crop = if multi || !defaulted { + None + } else { + prepared[0].crop + }; + Ok(EditPlan { + references: prepared.into_iter().map(|p| p.image).collect(), + size, + crop, + }) + } +} + +/// Prepared references, the size to sample at and the area to return. +pub struct EditPlan { + pub references: Vec, + pub size: (u32, u32), + pub crop: Option, +} + +impl Flux3Model { + /// [`Self::plan_edit`] for a request, for tests. + #[cfg(test)] + pub(crate) fn plan(req: &ImageRequest) -> Result { + Self::plan_edit(&req.reference_images, req.width, req.height) + } +} + +/// [`super::registry::FAMILIES`] constructor. +pub fn load(path: &Path) -> Result> { + Ok(Box::new(Flux3Model::load(path)?)) +} + +impl ImageGenerationModel for Flux3Model { + fn family(&self) -> &'static str { + FAMILY + } + + fn supports(&self, _task: ImageTask) -> bool { + true + } + + fn variant(&self) -> Option<&'static str> { + Some(self.config().variant()) + } + + fn defaults(&self, _task: ImageTask) -> ImageSamplingDefaults { + ImageSamplingDefaults { + steps: self.config().default_steps, + guidance: self.config().default_guidance, + } + } + + fn default_edit_size(&self) -> fn(u32, u32) -> (u32, u32) { + default_edit_size + } + + /// Sizes, the `extra` options, the reference count and the guidance a + /// flow map accepts, checked before anything runs. + fn check_request(&self, req: &ImageRequest) -> Result<()> { + validate_dimensions(req.width, req.height)?; + Flux3Options::from_extra(&req.extra, req.n)?; + if req.task == ImageTask::Edit + && !(1..=MAX_REFERENCES).contains(&req.reference_images.len()) + { + bail!( + "FLUX.3 editing requires between 1 and {MAX_REFERENCES} reference images, got {}", + req.reference_images.len() + ); + } + let guidance = req.resolve_guidance(self.defaults(req.task)); + if self.config().flow_map { + if guidance != 1.0 { + bail!( + "The distilled FLUX.3 flow map runs without CFG; use guidance 1, got {guidance}" + ); + } + if req + .negative_prompt + .as_deref() + .is_some_and(|p| !p.trim().is_empty()) + { + bail!( + "The distilled FLUX.3 flow map runs without CFG and takes no negative prompt" + ); + } + } + Ok(()) + } + + fn generate(&self, req: &ImageRequest) -> Result> { + self.check_request(req)?; + let defaults = self.defaults(req.task); + let steps = req.resolve_steps(defaults); + let guidance = req.resolve_guidance(defaults); + let options = Flux3Options::from_extra(&req.extra, req.n)?; + let prompt = boxes::prompt_with_boxes(&req.prompt, &options.boxes)?; + let revised_prompt = (prompt != req.prompt).then(|| prompt.clone()); + let negative = req.negative_prompt.as_deref().unwrap_or(""); + let image = + |pixels: &mlxcel_core::MlxArray, index: i32, seed: u64| -> Result { + let (pixels, width, height) = Flux2Model::pixels(pixels, index)?; + Ok(GeneratedImage { + pixels, + width, + height, + channels: 3, + seed, + revised_prompt: revised_prompt.clone(), + }) + }; + let mut out = Vec::with_capacity(req.n as usize); + match req.task { + ImageTask::Generate => { + let batch = i32::try_from(req.n)?; + let pixels = self.pipeline.run(&RunSpec { + prompt: &prompt, + negative, + references: &[], + seed: req.seed, + steps, + width: req.width, + height: req.height, + guidance, + batch, + max_sequence_length: options.max_sequence_length, + crop: None, + })?; + for i in 0..batch { + out.push(image(&pixels, i, req.seed)?); + } + } + ImageTask::Edit => { + let EditPlan { + references, + size: (width, height), + crop, + } = Self::plan_edit(&req.reference_images, req.width, req.height)?; + for i in 0..req.n { + let seed = req.seed_for(i); + let pixels = self.pipeline.run(&RunSpec { + prompt: &prompt, + negative, + references: &references, + seed, + steps, + width, + height, + guidance, + batch: 1, + max_sequence_length: options.max_sequence_length, + crop, + })?; + out.push(image(&pixels, 0, seed)?); + } + } + } + Ok(out) + } +} + +#[cfg(test)] +#[path = "mod_tests.rs"] +mod tests; diff --git a/src/imagegen/flux3/mod_tests.rs b/src/imagegen/flux3/mod_tests.rs new file mode 100644 index 000000000..f956116ce --- /dev/null +++ b/src/imagegen/flux3/mod_tests.rs @@ -0,0 +1,140 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use image::{Rgb, RgbImage}; +use serde_json::json; + +use super::*; + +fn extra(v: Value) -> Map { + v.as_object().unwrap().clone() +} + +fn options_err(v: Value, n: u32) -> String { + format!("{:#}", Flux3Options::from_extra(&extra(v), n).unwrap_err()) +} + +#[test] +fn options_default_to_upstreams_no_expansion_path() { + let o = Flux3Options::from_extra(&Map::new(), 1).unwrap(); + assert_eq!(o, Flux3Options::default()); + let o = Flux3Options::from_extra( + &extra(json!({ + "max_sequence_length": 4096, + "num_images": 3, + "upsample_prompt": false, + "prompt_expansion_model": null, + "boxes": [{"bbox": [0, 0, 1, 1]}], + "tiled_vae": true + })), + 3, + ) + .unwrap(); + assert_eq!(o.max_sequence_length, Some(4096)); + assert_eq!(o.boxes.len(), 1); +} + +#[test] +fn prompt_expansion_is_refused_with_the_reason() { + let e = options_err(json!({"upsample_prompt": true}), 1); + assert!(e.contains("upsample_prompt is not supported"), "{e}"); + assert!(e.contains("flux-3-image-klein-pup"), "{e}"); + assert!(e.contains("detailed caption"), "{e}"); + let e = options_err(json!({"prompt_expansion_model": "org/pup"}), 1); + assert!(e.contains("prompt_expansion_model is not supported"), "{e}"); + let e = options_err(json!({"upsample_prompt": "yes"}), 1); + assert!(e.contains("true or false"), "{e}"); +} + +#[test] +fn option_bounds() { + for bad in [json!(0), json!(4097), json!(-1), json!(1.5), json!("80")] { + let e = options_err(json!({ "max_sequence_length": bad }), 1); + assert!(e.contains("between 1 and 4096"), "{e}"); + } + let one = Flux3Options::from_extra(&extra(json!({"max_sequence_length": 1})), 1).unwrap(); + assert_eq!(one.max_sequence_length, Some(1)); + let e = options_err(json!({"num_images": 2}), 1); + assert!(e.contains("num_images") && e.contains("n = 1"), "{e}"); + let e = options_err(json!({"boxes": {"bbox": [0, 0, 1, 1]}}), 1); + assert!(e.contains("list of box objects"), "{e}"); + let e = options_err(json!({"boxes": [{"bbox": [0, 0, 1]}]}), 1); + assert!(e.contains("[y_min, x_min, y_max, x_max]"), "{e}"); +} + +fn picture(w: u32, h: u32) -> DynamicImage { + DynamicImage::ImageRgb8(RgbImage::from_fn(w, h, |x, y| { + Rgb([(x % 256) as u8, (y % 256) as u8, 7]) + })) +} + +fn edit(references: Vec, size: (u32, u32)) -> ImageRequest { + let mut req = ImageRequest::generate("Make it blue", 42); + req.task = ImageTask::Edit; + req.reference_images = references; + (req.width, req.height) = size; + req +} + +#[test] +fn a_lone_reference_without_a_size_is_cropped_back() { + // 1000x750 pads to 1008x752; the default edit size is that canvas. + let size = default_edit_size(1000, 750); + assert_eq!(size, (1008, 752)); + let plan = Flux3Model::plan(&edit(vec![picture(1000, 750)], size)).unwrap(); + assert_eq!(plan.size, (1008, 752)); + assert_eq!(plan.crop, Some((4, 1, 1004, 751))); + // An explicit other size samples at that size and keeps it. + let plan = Flux3Model::plan(&edit(vec![picture(1000, 750)], (512, 512))).unwrap(); + assert_eq!((plan.size, plan.crop), ((512, 512), None)); + // A reference already on the grid has nothing to crop. + let plan = Flux3Model::plan(&edit(vec![picture(512, 512)], (512, 512))).unwrap(); + assert_eq!((plan.size, plan.crop), ((512, 512), None)); +} + +#[test] +fn several_references_default_to_the_first_ones_own_size() { + let refs = vec![picture(3000, 2000), picture(64, 64)]; + let plan = Flux3Model::plan(&edit(refs, default_edit_size(3000, 2000))).unwrap(); + assert_eq!(plan.size, (1248, 832)); + assert_eq!(plan.crop, None); + assert_eq!(plan.references[0].dimensions(), (1248, 832)); + assert_eq!(plan.references[1].dimensions(), (64, 64)); + // Ten references are accepted by the planner; the count is checked in + // check_request. + let ten: Vec = (0..10).map(|_| picture(64, 64)).collect(); + assert_eq!( + Flux3Model::plan(&edit(ten, (64, 64))) + .unwrap() + .references + .len(), + 10 + ); +} + +#[test] +fn a_plan_too_small_for_the_model_is_an_error() { + // Two tiny references: the first one's own 16x16 size is below 64. + let refs = vec![picture(10, 7), picture(10, 7)]; + let e = Flux3Model::plan(&edit(refs, default_edit_size(10, 7))) + .err() + .unwrap() + .to_string(); + assert!(e.contains("[64, 4096]"), "{e}"); + let e = Flux3Model::plan(&edit(Vec::new(), (64, 64))) + .err() + .unwrap() + .to_string(); + assert!(e.contains("at least one reference"), "{e}"); +} diff --git a/src/imagegen/flux3/parity_tests.rs b/src/imagegen/flux3/parity_tests.rs new file mode 100644 index 000000000..84963c789 --- /dev/null +++ b/src/imagegen/flux3/parity_tests.rs @@ -0,0 +1,363 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Seed-fixed parity against upstream mlx-vlm on the real Klein package. +//! +//! The tests are `#[ignore]`: they need the +//! `black-forest-labs/flux-3-image-klein` package (`MLXCEL_TEST_FLUX3_DIR`, +//! default `models/flux-3-image-klein`), the upstream oracle written by +//! `tests/fixtures/flux3/generate_flux3_oracle.py` (`MLXCEL_FLUX3_ORACLE_DIR`), +//! a GPU, and `MLX_ENABLE_TF32=0`. Each skips when its inputs are absent. +//! +//! The image cases condition on upstream's own text features, as the issue +//! asks, so the bound measures the transformer, sampler and VAE; the +//! end-to-end case on mlxcel's own features is reported alongside. + +use std::path::{Path, PathBuf}; + +use image::GenericImageView; + +use super::conditioner::PromptFeatures; +use super::pipeline::{RunSpec, f32_values, image_ids, initial_noise, timesteps}; +use super::transformer::{Flux3Inputs, ModeInput}; +use super::weights::load_vae; +use super::*; +use crate::imagegen::Flux2Vae; +use crate::imagegen::flux2::parity_tests::{bf16_tensor, f32_tensor}; +use crate::imagegen::testing::{psnr, rel_rms}; + +const TEAPOT: &str = "A studio photograph of a red ceramic teapot"; +const EDIT: &str = "Make the teapot cobalt blue"; +const PSNR_MIN: f64 = 30.0; +const VELOCITY_REL_MAX: f64 = 1e-2; + +fn root() -> &'static Path { + Path::new(env!("CARGO_MANIFEST_DIR")) +} + +fn package() -> Option { + let dir = std::env::var_os("MLXCEL_TEST_FLUX3_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| root().join("models/flux-3-image-klein")); + dir.join("model.safetensors").is_file().then_some(dir) +} + +fn oracle() -> Option { + let dir = PathBuf::from(std::env::var_os("MLXCEL_FLUX3_ORACLE_DIR")?); + dir.join("tokens.json").is_file().then_some(dir) +} + +fn inputs() -> Option<(PathBuf, PathBuf)> { + match (package(), oracle()) { + (Some(p), Some(o)) => Some((p, o)), + _ => { + eprintln!("skipping: the FLUX.3 package or the upstream oracle is absent"); + None + } + } +} + +/// Upstream's text features as a cache entry. +fn upstream_features(oracle: &Path, name: &str) -> PromptFeatures { + let path = oracle.join(format!("{name}_features.safetensors")); + let (raw, values) = bf16_tensor(&path, "embeds_bf16_bits"); + let bytes = std::fs::read(&path).unwrap(); + let tensors = safetensors::SafeTensors::deserialize(&bytes).unwrap(); + let shape: Vec = tensors + .tensor("embeds_bf16_bits") + .unwrap() + .shape() + .iter() + .map(|&d| d as i32) + .collect(); + assert_eq!(raw.len(), values.len() * 2); + let embeds = mlxcel_core::astype( + &mlxcel_core::from_slice_f32(&values, &shape), + mlxcel_core::dtype::BFLOAT16, + ); + let ids: Vec = tensors + .tensor("text_ids") + .unwrap() + .data() + .chunks_exact(4) + .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + let t = shape[1]; + let text_ids = mlxcel_core::from_slice_i32(&ids, &[t, 4]); + PromptFeatures { embeds, text_ids } +} + +fn png(path: &Path) -> Vec { + image::open(path).unwrap().to_rgb8().into_raw() +} + +fn bytes(a: &mlxcel_core::MlxArray) -> Vec { + let a = mlxcel_core::copy(a); + mlxcel_core::eval(&a); + mlxcel_core::array_to_raw_bytes(&a).to_vec() +} + +fn tokens_json(oracle: &Path) -> serde_json::Value { + serde_json::from_str(&std::fs::read_to_string(oracle.join("tokens.json")).unwrap()).unwrap() +} + +fn as_i32(v: &serde_json::Value) -> Vec { + v.as_array() + .unwrap() + .iter() + .map(|x| x.as_i64().unwrap() as i32) + .collect() +} + +#[test] +#[ignore = "needs the flux-3-image-klein package, the upstream oracle and a GPU"] +fn tokens_and_noise_match_upstream() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let Some((dir, oracle)) = inputs() else { + return; + }; + let model = Flux3Model::load(&dir).unwrap(); + let tokens = tokens_json(&oracle); + for name in ["teapot", "edit", "empty"] { + let prompt = match name { + "teapot" => TEAPOT, + "edit" => EDIT, + _ => "", + }; + let (ids, mask) = model.pipeline().tokenizer.tokenize(prompt, None).unwrap(); + assert_eq!(ids, as_i32(&tokens[name]["input_ids"]), "{name} ids"); + assert_eq!(mask, as_i32(&tokens[name]["attention_mask"]), "{name} mask"); + assert_eq!(ids.len() % 80, 0, "{name} padded to a multiple of 80"); + } + let want = f32_tensor(&oracle.join("noise_512_seed42.safetensors"), "noise"); + let got = f32_values(&initial_noise(42, 1, 512, 512, 128)); + let mismatches = got + .iter() + .zip(&want) + .filter(|(g, w)| g.to_bits() != w.to_bits()) + .count(); + eprintln!("flux3 noise: {mismatches} of {} values differ", got.len()); + assert_eq!(mismatches, 0, "initial noise is not bit-identical"); +} + +#[test] +#[ignore = "needs the flux-3-image-klein package, the upstream oracle and a GPU"] +fn text_features_and_one_step_match_upstream() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let Some((dir, oracle)) = inputs() else { + return; + }; + let model = Flux3Model::load(&dir).unwrap(); + let pipeline = model.pipeline(); + let upstream = upstream_features(&oracle, "teapot"); + let ours = pipeline.encode(TEAPOT, None).unwrap(); + let features_rel = rel_rms(&f32_values(&ours.embeds), &f32_values(&upstream.embeds)); + eprintln!("flux3 text features rel RMS vs upstream: {features_rel:.3e}"); + assert!(features_rel < 5e-2, "text features rel RMS {features_rel}"); + + pipeline.ensure_transformer_and_vae().unwrap(); + let transformer = pipeline.transformer.borrow(); + let transformer = transformer.as_ref().unwrap(); + let noise = initial_noise(42, 1, 512, 512, 128); + let ids = image_ids(512, 512, None, 0.5); + let schedule = timesteps(16, pipeline.config().alpha).unwrap(); + let step = oracle.join("step0.safetensors"); + let t = f32_tensor(&step, "t"); + assert_eq!(t, schedule[..2]); + let velocity = transformer + .forward( + &Flux3Inputs { + image: ModeInput { + tokens: &noise, + ids: &ids, + }, + image_cond: None, + text: ModeInput { + tokens: &upstream.embeds, + ids: &upstream.text_ids, + }, + }, + schedule[0], + Some(schedule[1]), + ) + .unwrap(); + let rel = rel_rms(&f32_values(&velocity), &f32_tensor(&step, "velocity")); + eprintln!("flux3 step-0 velocity rel RMS vs upstream: {rel:.3e}"); + assert!(rel < VELOCITY_REL_MAX, "velocity rel RMS {rel}"); +} + +#[test] +#[ignore = "needs the flux-3-image-klein package, the upstream oracle and a GPU"] +fn generation_and_edit_match_upstream() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let Some((dir, oracle)) = inputs() else { + return; + }; + let model = Flux3Model::load(&dir).unwrap(); + let pipeline = model.pipeline(); + let spec = |prompt, references, crop| RunSpec { + prompt, + negative: "", + references, + seed: 42, + steps: 16, + width: 512, + height: 512, + guidance: 1.0, + batch: 1, + max_sequence_length: None, + crop, + }; + + // Generation on upstream's features. + pipeline.prime_prompt(TEAPOT, None, upstream_features(&oracle, "teapot")); + let image = pipeline.run(&spec(TEAPOT, &[], None)).unwrap(); + let want = png(&oracle.join("teapot_512.png")); + let generate_psnr = psnr(&bytes(&image), &want); + eprintln!("flux3 512x512 generate on upstream features: {generate_psnr:.2} dB"); + + // The edit of upstream's teapot, on upstream's features. + let reference = image::open(oracle.join("teapot_512.png")).unwrap(); + assert_eq!(reference.dimensions(), (512, 512)); + let plan = Flux3Model::plan_edit(std::slice::from_ref(&reference), 512, 512).unwrap(); + assert_eq!((plan.size, plan.crop), ((512, 512), None)); + pipeline.prime_prompt(EDIT, None, upstream_features(&oracle, "edit")); + let edited = pipeline.run(&spec(EDIT, &plan.references, None)).unwrap(); + let edit_psnr = psnr(&bytes(&edited), &png(&oracle.join("edit_512.png"))); + eprintln!("flux3 512x512 single-reference edit on upstream features: {edit_psnr:.2} dB"); + + // The encoded reference itself. + let vae = pipeline.vae.borrow(); + let (tokens, _) = + super::edit::encode_references(vae.as_ref().unwrap(), &plan.references, 0.5).unwrap(); + drop(vae); + let want_tokens = f32_tensor(&oracle.join("edit_reference_tokens.safetensors"), "tokens"); + // Upstream's oracle tokens are the f32 encoder output; ours are rounded + // to bf16 for the transformer, as upstream rounds them too. + let tokens_rel = rel_rms(&f32_values(&tokens), &want_tokens); + eprintln!("flux3 reference tokens rel RMS vs upstream: {tokens_rel:.3e}"); + + // End to end, on mlxcel's own text features. + let own = Flux3Model::load(&dir).unwrap(); + let image = own.pipeline().run(&spec(TEAPOT, &[], None)).unwrap(); + let end_to_end = psnr(&bytes(&image), &want); + eprintln!("flux3 512x512 generate end to end: {end_to_end:.2} dB"); + + assert!(generate_psnr >= PSNR_MIN, "generate {generate_psnr:.2} dB"); + assert!(edit_psnr >= PSNR_MIN, "edit {edit_psnr:.2} dB"); + assert!(tokens_rel < 1e-2, "reference tokens rel RMS {tokens_rel}"); +} + +#[test] +#[ignore = "needs the flux-3-image-klein package and a GPU"] +fn the_autoencoder_map_reproduces_the_diffusers_copy() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let Some(dir) = package() else { + eprintln!("skipping: the FLUX.3 package is absent"); + return; + }; + if !dir + .join("vae/diffusion_pytorch_model.safetensors") + .is_file() + { + eprintln!("skipping: the package has no Diffusers vae/ copy"); + return; + } + // Tensor for tensor. + let bfl = mlxcel_core::weights::load_safetensors(dir.join("ae.safetensors")).unwrap(); + let mapped = super::weights::bfl_vae_to_diffusers(bfl, 4).unwrap(); + let diffusers = + mlxcel_core::weights::load_safetensors(dir.join("vae/diffusion_pytorch_model.safetensors")) + .unwrap(); + let mut mapped_keys: Vec<&String> = mapped.keys().collect(); + let mut diffusers_keys: Vec<&String> = diffusers + .keys() + .filter(|k| !k.ends_with("num_batches_tracked")) + .collect(); + mapped_keys.sort(); + diffusers_keys.sort(); + assert_eq!(mapped_keys, diffusers_keys, "key sets differ"); + let mut differing = 0; + for (key, value) in &mapped { + let other = &diffusers[key]; + assert_eq!( + mlxcel_core::array_shape(value), + mlxcel_core::array_shape(other), + "{key}" + ); + if f32_values(value) != f32_values(other) { + differing += 1; + } + } + eprintln!( + "flux3 ae.safetensors vs vae/: {differing} of {} tensors differ", + mapped.len() + ); + assert_eq!(differing, 0); + + // And the two loads encode and decode alike. + let ours = load_vae(&dir.join("ae.safetensors")).unwrap(); + let theirs = Flux2Vae::load_with_dtype(&dir, true, mlxcel_core::dtype::FLOAT32).unwrap(); + let pixels: Vec = (0..3 * 64 * 64) + .map(|i| ((i * 37 % 255) as f32) / 127.5 - 1.0) + .collect(); + let pixels = mlxcel_core::from_slice_f32(&pixels, &[1, 3, 64, 64]); + let a = f32_values(&ours.encode(&pixels).unwrap()); + let b = f32_values(&theirs.encode(&pixels).unwrap()); + assert_eq!(a, b, "encode differs"); + let latents = mlxcel_core::from_slice_f32( + &(0..32 * 8 * 8) + .map(|i| ((i % 17) as f32 - 8.0) / 8.0) + .collect::>(), + &[1, 32, 8, 8], + ); + let a = f32_values(&ours.decode(&latents).unwrap()); + let b = f32_values(&theirs.decode(&latents).unwrap()); + assert_eq!(a, b, "decode differs"); +} + +#[test] +#[ignore = "needs the flux-3-image-klein package"] +fn requests_are_checked_against_the_real_package() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let Some(dir) = package() else { + eprintln!("skipping: the FLUX.3 package is absent"); + return; + }; + let model = Flux3Model::load(&dir).unwrap(); + assert_eq!(model.family(), "flux3"); + assert_eq!(model.variant(), Some("flux3-klein")); + let defaults = model.defaults(ImageTask::Generate); + assert_eq!((defaults.steps, defaults.guidance), (16, 1.0)); + let mut req = ImageRequest::generate(TEAPOT, 42); + assert!(model.check_request(&req).is_ok()); + req.extra + .insert("upsample_prompt".into(), serde_json::Value::Bool(true)); + let e = model.check_request(&req).unwrap_err().to_string(); + assert!(e.contains("upsample_prompt"), "{e}"); + let mut req = ImageRequest::generate(TEAPOT, 42); + req.guidance = Some(3.5); + let e = model.check_request(&req).unwrap_err().to_string(); + assert!(e.contains("guidance 1"), "{e}"); + let mut req = ImageRequest::generate(TEAPOT, 42); + req.negative_prompt = Some("blurry".into()); + assert!(model.check_request(&req).is_err()); + let mut req = ImageRequest::generate(TEAPOT, 42); + req.task = ImageTask::Edit; + req.reference_images = (0..11) + .map(|_| image::DynamicImage::new_rgb8(64, 64)) + .collect(); + let e = model.check_request(&req).unwrap_err().to_string(); + assert!(e.contains("between 1 and 10"), "{e}"); +} diff --git a/src/imagegen/flux3/pipeline.rs b/src/imagegen/flux3/pipeline.rs new file mode 100644 index 000000000..e4c58d7f7 --- /dev/null +++ b/src/imagegen/flux3/pipeline.rs @@ -0,0 +1,386 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The FLUX.3 pipeline: components, prompt cache, sampling and decode. +//! +//! A port of `timesteps`, `image_ids` and `Flux3Image._run` / +//! `_encode_prompt` in +//! . +//! As upstream: the text encoder loads for an unseen prompt and is evicted +//! after encoding, at most four encoded prompts are kept, and the transformer +//! and VAE load on the first request and stay resident. +//! +//! Sampling: `t = linspace(1, 0, steps + 1)` mapped through +//! `alpha * t / (1 + (alpha - 1) * t)`, Euler steps in f32 on a bf16 +//! transformer, initial noise `normal((n, L, 128), key(seed))` rounded through +//! bf16. A flow map gets each step's target time; the base model runs an +//! unconditional pass when guidance is not 1. + +use std::cell::RefCell; + +use anyhow::{Context, Result, bail}; +use image::RgbImage; +use mlxcel_core::{MlxArray, UniquePtr, dtype}; + +use super::conditioner::{Flux3TextEncoder, Flux3Tokenizer, PromptFeatures}; +use super::config::{Flux3Config, Flux3Layout}; +use super::edit::{CropBox, encode_references}; +use super::transformer::{Flux3Inputs, Flux3Transformer, ModeInput}; +use super::weights::{load_transformer, load_vae}; +use crate::imagegen::Flux2Vae; +use crate::imagegen::latent::unpack_latents; + +/// Encoded prompts kept per pipeline, as upstream bounds its cache. +const PROMPT_CACHE_ENTRIES: usize = 4; +/// Pixels per latent token side (8x VAE, 2x2 patches). +pub const TOKEN_PIXELS: u32 = 16; +/// The transformer's dtype on every backend. +pub const TRANSFORMER_DTYPE: i32 = dtype::BFLOAT16; + +/// Upstream `timesteps(steps, alpha)`, computed with the same f32 MLX ops. +pub fn timesteps(steps: u32, alpha: f64) -> Result> { + if steps < 1 || !alpha.is_finite() || alpha <= 0.0 { + bail!("steps and alpha must be positive"); + } + let n = i32::try_from(steps)? + 1; + let t = mlxcel_core::linspace(1.0, 0.0, n, dtype::FLOAT32); + let scalar = |v: f64| mlxcel_core::full_f32(&[1], v as f32, dtype::FLOAT32); + let numerator = mlxcel_core::multiply(&scalar(alpha), &t); + let denominator = mlxcel_core::add( + &scalar(1.0), + &mlxcel_core::multiply(&scalar(alpha - 1.0), &t), + ); + let out = mlxcel_core::divide(&numerator, &denominator); + mlxcel_core::eval(&out); + Ok(f32_values(&out)) +} + +/// The f32 values of an f32 array. +pub(crate) fn f32_values(a: &MlxArray) -> Vec { + let a = mlxcel_core::astype(a, dtype::FLOAT32); + mlxcel_core::eval(&a); + mlxcel_core::array_to_raw_bytes(&a) + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() +} + +/// Upstream `image_ids`: FLUX.2's `(t, h, w, layer)` grid over the +/// `(H/16, W/16)` tokens at `t = 0`, times `[1, scale, scale, 1]`, plus +/// `[0, 0, 0, -1 - r]` for reference `r`. `[L, 4]` f32. +#[must_use] +pub fn image_ids( + height: u32, + width: u32, + reference: Option, + scale: f32, +) -> UniquePtr { + let (h, w) = (height / TOKEN_PIXELS, width / TOKEN_PIXELS); + let layer = reference.map_or(0.0, |r| -1.0 - r as f32); + let mut coords = Vec::with_capacity((h * w * 4) as usize); + for y in 0..h { + for x in 0..w { + coords.extend_from_slice(&[0.0, y as f32 * scale, x as f32 * scale, layer]); + } + } + mlxcel_core::from_slice_f32(&coords, &[(h * w) as i32, 4]) +} + +/// `normal((n, L, channels), key(seed))` rounded through bf16, in f32. +pub fn initial_noise( + seed: u64, + batch: i32, + height: u32, + width: u32, + channels: i32, +) -> UniquePtr { + let tokens = ((height / TOKEN_PIXELS) * (width / TOKEN_PIXELS)) as i32; + let key = mlxcel_core::random_key(seed); + // SAFETY: `key` is a live array for the duration of the call. + let noise = + unsafe { mlxcel_core::random_normal(&[batch, tokens, channels], dtype::FLOAT32, &*key) }; + mlxcel_core::astype( + &mlxcel_core::astype(&noise, dtype::BFLOAT16), + dtype::FLOAT32, + ) +} + +/// The transformer inputs of one step. +fn step_inputs<'a>( + latents: &'a MlxArray, + image_ids: &'a MlxArray, + cond: Option<(&'a MlxArray, &'a MlxArray)>, + text: &'a MlxArray, + text_ids: &'a MlxArray, +) -> Flux3Inputs<'a> { + Flux3Inputs { + image: ModeInput { + tokens: latents, + ids: image_ids, + }, + image_cond: cond.map(|(tokens, ids)| ModeInput { tokens, ids }), + text: ModeInput { + tokens: text, + ids: text_ids, + }, + } +} + +/// One sampling run. +pub struct RunSpec<'a> { + /// The prompt the text encoder reads (boxes already appended). + pub prompt: &'a str, + /// The unconditional prompt for the base model's CFG pass. + pub negative: &'a str, + pub references: &'a [RgbImage], + pub seed: u64, + pub steps: u32, + pub width: u32, + pub height: u32, + pub guidance: f32, + pub batch: i32, + pub max_sequence_length: Option, + pub crop: Option, +} + +/// Components of one FLUX.3 package. +pub struct Flux3Pipeline { + pub(super) layout: Flux3Layout, + pub(super) config: Flux3Config, + pub(super) tokenizer: Flux3Tokenizer, + text_encoder: RefCell>, + pub(super) transformer: RefCell>, + pub(super) vae: RefCell>, + prompt_cache: RefCell), PromptFeatures)>>, +} + +fn clone_features(p: &PromptFeatures) -> PromptFeatures { + PromptFeatures { + embeds: mlxcel_core::copy(&p.embeds), + text_ids: mlxcel_core::copy(&p.text_ids), + } +} + +impl Flux3Pipeline { + /// Read the tokenizer; the networks load on demand. + pub fn new(layout: Flux3Layout, config: Flux3Config) -> Result { + let tokenizer = Flux3Tokenizer::load(&layout.text_encoder, &config)?; + Ok(Self { + layout, + config, + tokenizer, + text_encoder: RefCell::new(None), + transformer: RefCell::new(None), + vae: RefCell::new(None), + prompt_cache: RefCell::new(Vec::new()), + }) + } + + #[must_use] + pub fn config(&self) -> &Flux3Config { + &self.config + } + + /// Upstream `_encode_prompt`: cached, then the text encoder is evicted. + pub fn encode( + &self, + prompt: &str, + max_sequence_length: Option, + ) -> Result { + let key = (prompt.to_string(), max_sequence_length); + if let Some((_, hit)) = self.prompt_cache.borrow().iter().find(|(k, _)| *k == key) { + return Ok(clone_features(hit)); + } + let (ids, mask) = self.tokenizer.tokenize(prompt, max_sequence_length)?; + let mut slot = self.text_encoder.borrow_mut(); + if slot.is_none() { + *slot = Some(Flux3TextEncoder::load( + &self.layout.text_encoder, + &self.config, + )?); + } + let encoder = slot.as_ref().context("text encoder slot is empty")?; + let features = encoder.prompt_features(&ids, &mask)?; + // evict_text_encoder=True + *slot = None; + drop(slot); + mlxcel_core::clear_memory_cache(); + let mut cache = self.prompt_cache.borrow_mut(); + if cache.len() >= PROMPT_CACHE_ENTRIES { + cache.remove(0); + } + cache.push((key, clone_features(&features))); + Ok(features) + } + + /// Put `features` in the prompt cache, so a run conditions on them + /// instead of this encoder's (the parity tests feed upstream's). + #[cfg(test)] + pub(crate) fn prime_prompt( + &self, + prompt: &str, + max_sequence_length: Option, + features: PromptFeatures, + ) { + let mut cache = self.prompt_cache.borrow_mut(); + cache.retain(|(k, _)| k.0 != prompt || k.1 != max_sequence_length); + cache.push(((prompt.to_string(), max_sequence_length), features)); + } + + /// Load the transformer and the VAE if they are not resident. + pub fn ensure_transformer_and_vae(&self) -> Result<()> { + if self.transformer.borrow().is_none() { + let transformer = + load_transformer(&self.layout.transformer, &self.config, TRANSFORMER_DTYPE)?; + *self.transformer.borrow_mut() = Some(transformer); + } + if self.vae.borrow().is_none() { + *self.vae.borrow_mut() = Some(load_vae(&self.layout.vae)?); + } + Ok(()) + } + + /// The denoising loop: final latent tokens `[n, L, 128]` f32. + pub fn sample(&self, spec: &RunSpec<'_>) -> Result> { + let positive = self.encode(spec.prompt, spec.max_sequence_length)?; + let negative = if !self.config.flow_map && spec.guidance != 1.0 { + Some(self.encode(spec.negative, spec.max_sequence_length)?) + } else { + None + }; + self.ensure_transformer_and_vae()?; + let references = if spec.references.is_empty() { + None + } else { + let vae = self.vae.borrow(); + let vae = vae.as_ref().context("VAE is not loaded")?; + Some(encode_references( + vae, + spec.references, + self.config.image_rope_scale, + )?) + }; + let batch = spec.batch; + let broadcast = |a: &MlxArray| { + let s = mlxcel_core::array_shape(a); + if s[0] == batch { + mlxcel_core::copy(a) + } else { + mlxcel_core::broadcast_to(a, &[batch, s[1], s[2]]) + } + }; + let text = broadcast(&positive.embeds); + let negative_text = negative.as_ref().map(|n| broadcast(&n.embeds)); + let cond = references.as_ref().map(|(tokens, _)| broadcast(tokens)); + let image_ids = image_ids(spec.height, spec.width, None, self.config.image_rope_scale); + let mut latents = initial_noise( + spec.seed, + batch, + spec.height, + spec.width, + self.config.in_channels.image, + ); + let schedule = timesteps(spec.steps, self.config.alpha)?; + let transformer = self.transformer.borrow(); + let transformer = transformer.as_ref().context("transformer is not loaded")?; + let cond_input = cond + .as_ref() + .zip(references.as_ref()) + .map(|(c, (_, ids))| (&**c, &**ids)); + for pair in schedule.windows(2) { + let (t, target) = (pair[0], pair[1]); + let flow_target = self.config.flow_map.then_some(target); + let mut velocity = transformer.forward( + &step_inputs(&latents, &image_ids, cond_input, &text, &positive.text_ids), + t, + flow_target, + )?; + if let (Some(neg_text), Some(neg)) = (&negative_text, &negative) { + let uncond = transformer.forward( + &step_inputs(&latents, &image_ids, cond_input, neg_text, &neg.text_ids), + t, + None, + )?; + let diff = mlxcel_core::subtract(&velocity, &uncond); + let g = mlxcel_core::full_f32(&[1], spec.guidance, mlxcel_core::array_dtype(&diff)); + velocity = mlxcel_core::add(&uncond, &mlxcel_core::multiply(&g, &diff)); + } + // `(target - t)` is a Python float; it meets f32 state as f32. + let dt = (f64::from(target) - f64::from(t)) as f32; + let step = mlxcel_core::multiply( + &mlxcel_core::full_f32(&[1], dt, dtype::FLOAT32), + &mlxcel_core::astype(&velocity, dtype::FLOAT32), + ); + latents = mlxcel_core::add(&latents, &step); + mlxcel_core::eval(&latents); + } + Ok(latents) + } + + /// Decode latent tokens to `[n, H, W, 3]` u8 pixels, image by image: + /// denormalize, unpatchify, decode in f32, then + /// `((clip(x, -1, 1) + 1) * 127.5).astype(uint8)`, cropped to `crop`. + pub fn decode( + &self, + latents: &MlxArray, + height: u32, + width: u32, + crop: Option, + ) -> Result> { + let vae = self.vae.borrow(); + let vae = vae.as_ref().context("VAE is not loaded")?; + let (h, w) = ( + (height / TOKEN_PIXELS) as i32, + (width / TOKEN_PIXELS) as i32, + ); + let s = mlxcel_core::array_shape(latents); + let mut images = Vec::with_capacity(s[0] as usize); + for b in 0..s[0] { + let one = mlxcel_core::slice(latents, &[b, 0, 0], &[b + 1, s[1], s[2]]); + let one = mlxcel_core::astype(&one, dtype::FLOAT32); + let grid = unpack_latents(&one, h, w)?; + let decoded = vae.decode(&*vae.denormalize_packed_latents(&grid)?)?; + let nhwc = mlxcel_core::transpose_axes(&decoded, &[0, 2, 3, 1]); + let f = |v: f32| mlxcel_core::full_f32(&[1], v, dtype::FLOAT32); + let x = mlxcel_core::clip(&nhwc, &f(-1.0), &f(1.0)); + let x = mlxcel_core::multiply(&mlxcel_core::add(&x, &f(1.0)), &f(127.5)); + let mut pixels = mlxcel_core::astype(&x, dtype::UINT8); + if let Some((left, top, right, bottom)) = crop { + let ps = mlxcel_core::array_shape(&pixels); + pixels = mlxcel_core::slice( + &pixels, + &[0, top as i32, left as i32, 0], + &[ps[0], bottom as i32, right as i32, ps[3]], + ); + } + let pixels = mlxcel_core::copy(&pixels); + mlxcel_core::eval(&pixels); + images.push(pixels); + } + Ok(mlxcel_core::concatenate_many( + &images.iter().map(|a| &**a).collect::>(), + 0, + )) + } + + /// [`Self::sample`] then [`Self::decode`]. + pub fn run(&self, spec: &RunSpec<'_>) -> Result> { + let latents = self.sample(spec)?; + self.decode(&latents, spec.height, spec.width, spec.crop) + } +} + +#[cfg(test)] +#[path = "pipeline_tests.rs"] +mod tests; diff --git a/src/imagegen/flux3/pipeline_tests.rs b/src/imagegen/flux3/pipeline_tests.rs new file mode 100644 index 000000000..33cb73874 --- /dev/null +++ b/src/imagegen/flux3/pipeline_tests.rs @@ -0,0 +1,119 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Expected values come from mlx-vlm e8035ae +//! (`tests/fixtures/flux3/generate_flux3_unit_fixtures.py`, mlx 0.32.5, CUDA). + +use super::*; +use crate::imagegen::testing::{assert_noise_head, noise_checksum_is_exact}; + +/// Upstream `timesteps(16, 6.93).tolist()`. +const TIMESTEPS_16: [f32; 17] = [ + 1.0, 0.99047166, 0.9798021, 0.96777314, 0.9541074, 0.9384464, 0.9203186, 0.8990919, 0.8738966, + 0.8435055, 0.8061264, 0.75903606, 0.69788516, 0.61527073, 0.49748743, 0.31600547, 0.0, +]; + +/// The first eight values of `normal((1, 16, 128), key(42))` through bf16, +/// and the sum of all 2048. +const NOISE_HEAD: [f32; 8] = [ + 0.00011253357, + -0.10205078, + 1.078125, + -2.125, + -2.3125, + 0.15039062, + -0.0005378723, + -0.6875, +]; +const NOISE_SUM: f64 = 1.3665170669555664; + +#[test] +fn the_schedule_matches_upstream() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + // Bit-identical on CUDA, where the values were drawn; elementwise f32 + // division may differ in the last bit on other backends. + let max_ulps = if noise_checksum_is_exact() { 0 } else { 2 }; + assert_noise_head( + ×teps(16, 6.93).unwrap(), + &TIMESTEPS_16, + 0, + max_ulps, + "timesteps", + ); + // One step goes straight from 1 to 0. + assert_eq!(timesteps(1, 6.93).unwrap(), [1.0, 0.0]); + // alpha 1 is the identity schedule. + let identity = timesteps(4, 1.0).unwrap(); + assert_eq!(identity, [1.0, 0.75, 0.5, 0.25, 0.0]); + // The schedule is monotone for a long run too. + let long = timesteps(1000, 6.93).unwrap(); + assert_eq!(long.len(), 1001); + assert!(long.windows(2).all(|w| w[0] > w[1])); +} + +#[test] +fn bad_schedules_are_errors() { + for (steps, alpha) in [ + (0, 6.93), + (16, 0.0), + (16, -1.0), + (16, f64::NAN), + (16, f64::INFINITY), + ] { + assert!(timesteps(steps, alpha).is_err(), "{steps} {alpha}"); + } +} + +#[test] +fn image_and_reference_ids_on_a_3x4_grid() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + // 48x64 pixels is a 3x4 token grid. + let ids = image_ids(48, 64, None, 0.5); + assert_eq!(mlxcel_core::array_shape(&ids), vec![12, 4]); + let v = f32_values(&ids); + let row = |i: usize| &v[i * 4..i * 4 + 4]; + assert_eq!(row(0), [0.0, 0.0, 0.0, 0.0]); + assert_eq!(row(1), [0.0, 0.0, 0.5, 0.0]); + assert_eq!(row(4), [0.0, 0.5, 0.0, 0.0]); + assert_eq!(row(11), [0.0, 1.0, 1.5, 0.0]); + // Reference r adds -1 - r on the last axis. + let r0 = f32_values(&image_ids(48, 64, Some(0), 0.5)); + let r2 = f32_values(&image_ids(48, 64, Some(2), 0.5)); + assert_eq!(&r0[44..48], [0.0, 1.0, 1.5, -1.0]); + assert_eq!(&r2[44..48], [0.0, 1.0, 1.5, -3.0]); + // The scale is the config's. + let unscaled = f32_values(&image_ids(48, 64, None, 1.0)); + assert_eq!(&unscaled[44..48], [0.0, 2.0, 3.0, 0.0]); +} + +#[test] +fn initial_noise_is_upstreams() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let noise = initial_noise(42, 1, 64, 64, 128); + assert_eq!(mlxcel_core::array_shape(&noise), vec![1, 16, 128]); + assert_eq!(mlxcel_core::array_dtype(&noise), dtype::FLOAT32); + let v = f32_values(&noise); + assert_noise_head(&v[..8], &NOISE_HEAD, 16, 1, "noise head"); + let sum: f64 = v.iter().map(|x| f64::from(*x)).sum(); + if noise_checksum_is_exact() { + // Bit-identical to upstream's draw on CUDA. + assert_eq!(v[..8], NOISE_HEAD); + assert!((sum - NOISE_SUM).abs() < 1e-9, "sum {sum}"); + } + // Every value is a bf16. + assert!(v.iter().all(|x| x.to_bits() & 0xffff == 0)); + // A batch draws one tensor: its first image is not the single draw. + let batch = f32_values(&initial_noise(42, 2, 64, 64, 128)); + assert_eq!(batch.len(), 2 * v.len()); +} diff --git a/src/imagegen/flux3/transformer.rs b/src/imagegen/flux3/transformer.rs new file mode 100644 index 000000000..3a01e7570 --- /dev/null +++ b/src/imagegen/flux3/transformer.rs @@ -0,0 +1,553 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The FLUX.3 transformer: independent early streams, then one joint stream. +//! +//! A port of `Flux3Transformer` in +//! . +//! Each present mode (`image`, `image_cond`, `text`) is projected to the +//! hidden width and runs its own early blocks under its own modulation and +//! RoPE; the modes are then concatenated in that order and run through the +//! single blocks, each token modulated by its own mode's single-stream +//! modulation. Only the image tokens are projected out. +//! +//! Every block is the same: an affine-free layer norm modulated in the +//! activation dtype, bias-free q/k/v, a QK RMS norm and an interleaved RoPE +//! applied together in f32 and rounded once, attention at scale +//! `head_dim ** -0.5`, and a parallel SwiGLU MLP, all behind one gate. +//! +//! FLUX.2's `pos_embed`, `timestep_embedding`, `layer_norm`, `modulate` and +//! `apply_rope` are reused where their arithmetic is the reference's; see +//! [`flux3_timestep_embedding`] for the one difference in the time embedding. + +use std::collections::BTreeSet; + +use anyhow::{Context, Result, bail}; +use mlxcel_core::layers::UnifiedLinear; +use mlxcel_core::weights::WeightMap; +use mlxcel_core::{MlxArray, UniquePtr, dtype}; + +use super::config::Flux3Config; +use crate::imagegen::flux2::attention::apply_rope; +use crate::imagegen::flux2::embeddings::{ + layer_norm, modulate, pos_embed, split_last, timestep_embedding, +}; + +/// Width of the sinusoidal time embedding. +pub const TIME_EMBED_DIM: i32 = 256; +/// Epsilon of the QK RMS norm. +const QK_NORM_EPS: f32 = 1e-6; + +/// A stream of the transformer, in the order the joint stream concatenates. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + Image, + ImageCond, + Text, +} + +impl Mode { + pub const ALL: [Mode; 3] = [Mode::Image, Mode::ImageCond, Mode::Text]; + + /// The key of the mode's modulations (`txt` for text). + #[must_use] + pub fn modulation_key(self) -> &'static str { + match self { + Mode::Image => "image", + Mode::ImageCond => "image_cond", + Mode::Text => "txt", + } + } + + fn index(self) -> usize { + match self { + Mode::Image => 0, + Mode::ImageCond => 1, + Mode::Text => 2, + } + } +} + +/// `timestep_embedding` of the reference: the timestep is held in the +/// activation dtype, `1000 * t` is rounded to that dtype before it meets the +/// f32 frequencies (BFL's order), and the `[cos, sin]` result is cast back. +/// +/// `t` is `[B]` in the activation dtype; returns `[B, 1, 256]`. +#[must_use] +pub fn flux3_timestep_embedding(t: &MlxArray) -> UniquePtr { + let dt = mlxcel_core::array_dtype(t); + let scaled = mlxcel_core::multiply(t, &mlxcel_core::full_f32(&[1], 1000.0, dt)); + let emb = timestep_embedding( + &mlxcel_core::astype(&scaled, dtype::FLOAT32), + TIME_EMBED_DIM, + ); + let b = mlxcel_core::array_shape(&emb)[0]; + mlxcel_core::astype(&mlxcel_core::reshape(&emb, &[b, 1, TIME_EMBED_DIM]), dt) +} + +/// A bias-free dense projection. +struct Linear(UnifiedLinear); + +impl Linear { + fn load(weights: &WeightMap, prefix: &str) -> Result { + let layer = UnifiedLinear::from_weights(weights, prefix, 64, 4) + .map_err(anyhow::Error::msg) + .with_context(|| format!("FLUX.3 transformer weight {prefix}"))?; + Ok(Self(layer)) + } + + fn forward(&self, x: &MlxArray) -> UniquePtr { + self.0.forward(x) + } +} + +fn tensor(weights: &WeightMap, key: &str) -> Result> { + weights + .get(key) + .map(|w| mlxcel_core::copy(w)) + .with_context(|| format!("FLUX.3 transformer weight not found: {key}")) +} + +/// `MLPEmbedder`: `out_layer(silu(in_layer(x)))`. +struct MlpEmbedder { + in_layer: Linear, + out_layer: Linear, +} + +impl MlpEmbedder { + fn load(weights: &WeightMap, prefix: &str) -> Result { + Ok(Self { + in_layer: Linear::load(weights, &format!("{prefix}.in_layer"))?, + out_layer: Linear::load(weights, &format!("{prefix}.out_layer"))?, + }) + } + + fn forward(&self, x: &MlxArray) -> UniquePtr { + self.out_layer + .forward(&mlxcel_core::silu(&self.in_layer.forward(x))) + } +} + +/// `(shift, scale, gate)`. +pub type Modulation = [UniquePtr; 3]; + +/// `ModeModulation`: `split(lin(silu(vec)), 3)`. +struct ModeModulation { + lin: Linear, +} + +impl ModeModulation { + fn load(weights: &WeightMap, prefix: &str) -> Result { + Ok(Self { + lin: Linear::load(weights, &format!("{prefix}.lin"))?, + }) + } + + fn forward(&self, vec: &MlxArray) -> Modulation { + let m = self.lin.forward(&mlxcel_core::silu(vec)); + let shape = mlxcel_core::array_shape(&m); + let third = shape[shape.len() - 1] / 3; + let mut parts = split_last(&m, &[third, third, third]).into_iter(); + let mut next = || parts.next().expect("three chunks"); + [next(), next(), next()] + } +} + +/// `Block`: one early or single-stream block. +struct Block { + q_proj: Linear, + k_proj: Linear, + v_proj: Linear, + mlp_in: Linear, + attn_out: Linear, + mlp_out: Linear, + /// QK RMS-norm weights, in f32. + query_norm: UniquePtr, + key_norm: UniquePtr, + heads: i32, + head_dim: i32, + mlp_hidden: i32, +} + +impl Block { + fn load(weights: &WeightMap, prefix: &str, config: &Flux3Config) -> Result { + let f32_norm = |key: &str| -> Result> { + Ok(mlxcel_core::astype( + &*tensor(weights, &format!("{prefix}.norm.{key}.scale"))?, + dtype::FLOAT32, + )) + }; + Ok(Self { + q_proj: Linear::load(weights, &format!("{prefix}.q_proj"))?, + k_proj: Linear::load(weights, &format!("{prefix}.k_proj"))?, + v_proj: Linear::load(weights, &format!("{prefix}.v_proj"))?, + mlp_in: Linear::load(weights, &format!("{prefix}.mlp_in"))?, + attn_out: Linear::load(weights, &format!("{prefix}.attn_out"))?, + mlp_out: Linear::load(weights, &format!("{prefix}.mlp_out"))?, + query_norm: f32_norm("query_norm")?, + key_norm: f32_norm("key_norm")?, + heads: config.heads, + head_dim: config.head_dim(), + mlp_hidden: config.mlp_hidden(), + }) + } + + /// `[B, L, hidden]` to heads `[B, heads, L, head_dim]`. + fn split(&self, t: &MlxArray) -> UniquePtr { + let s = mlxcel_core::array_shape(t); + let t = mlxcel_core::reshape(t, &[s[0], s[1], self.heads, self.head_dim]); + mlxcel_core::transpose_axes(&t, &[0, 2, 1, 3]) + } + + /// `QKNorm._apply`: RMS norm and RoPE in f32, rounded once to `x`'s dtype. + fn norm_rope( + x: &MlxArray, + weight: &MlxArray, + rope: &(UniquePtr, UniquePtr), + ) -> UniquePtr { + let y = mlxcel_core::fast_rms_norm( + &mlxcel_core::astype(x, dtype::FLOAT32), + weight, + QK_NORM_EPS, + ); + mlxcel_core::astype( + &apply_rope(&y, &rope.0, &rope.1), + mlxcel_core::array_dtype(x), + ) + } + + fn forward( + &self, + x: &MlxArray, + rope: &(UniquePtr, UniquePtr), + modulation: &Modulation, + ) -> UniquePtr { + let [shift, scale, gate] = modulation; + let h = modulate(&layer_norm(x), shift, scale); + let s = mlxcel_core::array_shape(&h); + let (b, length, hidden) = (s[0], s[1], s[2]); + let q = Self::norm_rope( + &self.split(&self.q_proj.forward(&h)), + &self.query_norm, + rope, + ); + let k = Self::norm_rope(&self.split(&self.k_proj.forward(&h)), &self.key_norm, rope); + let v = self.split(&self.v_proj.forward(&h)); + let scale = (f64::from(self.head_dim)).powf(-0.5) as f32; + let attn = mlxcel_core::layers::attention(&q, &k, &v, scale, None, 0.0, 0); + let attn = mlxcel_core::reshape( + &mlxcel_core::transpose_axes(&attn, &[0, 2, 1, 3]), + &[b, length, hidden], + ); + let mlp = split_last( + &self.mlp_in.forward(&h), + &[self.mlp_hidden, self.mlp_hidden], + ); + let mlp = self + .mlp_out + .forward(&mlxcel_core::multiply(&mlxcel_core::silu(&mlp[0]), &mlp[1])); + let branch = mlxcel_core::add(&self.attn_out.forward(&attn), &mlp); + mlxcel_core::add(x, &mlxcel_core::multiply(gate, &branch)) + } +} + +/// `LastLayer`: `linear(modulate(x, scale, shift))` with +/// `(shift, scale) = split(adaLN_modulation(silu(vec)), 2)`. +struct LastLayer { + linear: Linear, + ada: Linear, +} + +impl LastLayer { + fn forward(&self, x: &MlxArray, vec: &MlxArray) -> UniquePtr { + let m = self.ada.forward(&mlxcel_core::silu(vec)); + let shape = mlxcel_core::array_shape(&m); + let half = shape[shape.len() - 1] / 2; + let parts = split_last(&m, &[half, half]); + self.linear + .forward(&modulate(&layer_norm(x), &parts[0], &parts[1])) + } +} + +/// One mode's tokens `[B, L, C]` and its position ids `[L, 4]`. +pub struct ModeInput<'a> { + pub tokens: &'a MlxArray, + pub ids: &'a MlxArray, +} + +/// The transformer's inputs; the image stream is always present. +pub struct Flux3Inputs<'a> { + pub image: ModeInput<'a>, + pub image_cond: Option>, + pub text: ModeInput<'a>, +} + +impl<'a> Flux3Inputs<'a> { + /// Modes with at least one token, in joint-stream order. + fn active(&self) -> Vec<(Mode, &ModeInput<'a>)> { + let mut out = vec![(Mode::Image, &self.image)]; + if let Some(cond) = &self.image_cond { + out.push((Mode::ImageCond, cond)); + } + out.push((Mode::Text, &self.text)); + out.into_iter() + .filter(|(_, m)| mlxcel_core::array_shape(m.tokens)[1] > 0) + .collect() + } +} + +/// `Flux3Transformer`. +pub struct Flux3Transformer { + config: Flux3Config, + dtype: i32, + emb_in: [Linear; 2], + txt_in: Linear, + time_in: MlpEmbedder, + ref_time_in: Option, + early: [ModeModulation; 3], + single: [ModeModulation; 3], + /// Early blocks of `image`, `image_cond` and `text`. + mode_blocks: [Vec; 3], + single_blocks: Vec, + final_layer: LastLayer, +} + +/// Names of every tensor a package must hold, and nothing else. +#[must_use] +pub fn expected_keys(config: &Flux3Config) -> BTreeSet { + let mut keys = BTreeSet::new(); + let mut block = |prefix: String| { + for p in [ + "q_proj", "k_proj", "v_proj", "mlp_in", "attn_out", "mlp_out", + ] { + keys.insert(format!("{prefix}.{p}.weight")); + } + keys.insert(format!("{prefix}.norm.query_norm.scale")); + keys.insert(format!("{prefix}.norm.key_norm.scale")); + }; + for i in 0..config.depth { + block(format!("content_mode_blocks.image.{i}")); + block(format!("content_mode_blocks.image_cond.{i}")); + block(format!("txt_mode_blocks.{i}")); + } + for i in 0..config.depth_single { + block(format!("single_blocks.{i}")); + } + for key in [ + "emb_in.image.weight", + "emb_in.image_cond.weight", + "txt_in.weight", + "time_in.in_layer.weight", + "time_in.out_layer.weight", + "final_layer.image.linear.weight", + "final_layer.image.adaLN_modulation.1.weight", + ] { + keys.insert(key.to_string()); + } + if config.flow_map { + keys.insert("ref_time_in.in_layer.weight".to_string()); + keys.insert("ref_time_in.out_layer.weight".to_string()); + } + for m in Mode::ALL { + keys.insert(format!( + "early_stream_modulations.{}.lin.weight", + m.modulation_key() + )); + keys.insert(format!( + "single_stream_modulations.{}.lin.weight", + m.modulation_key() + )); + } + keys +} + +/// Upstream `load_weights(strict=True)`: every expected tensor present and no +/// other, reporting all mismatches at once. +pub fn check_keys(config: &Flux3Config, weights: &WeightMap) -> Result<()> { + let expected = expected_keys(config); + let mut missing: Vec<&str> = expected + .iter() + .filter(|k| !weights.contains_key(*k)) + .map(String::as_str) + .collect(); + let mut unexpected: Vec<&str> = weights + .keys() + .filter(|k| !expected.contains(*k)) + .map(String::as_str) + .collect(); + if missing.is_empty() && unexpected.is_empty() { + return Ok(()); + } + missing.sort_unstable(); + unexpected.sort_unstable(); + let show = |v: &[&str]| { + let head: Vec<&str> = v.iter().take(8).copied().collect(); + let more = v.len().saturating_sub(head.len()); + if more > 0 { + format!("{} (and {more} more)", head.join(", ")) + } else { + head.join(", ") + } + }; + bail!( + "FLUX.3 transformer weights do not match the config: missing [{}], unexpected [{}]", + show(&missing), + show(&unexpected) + ); +} + +impl Flux3Transformer { + /// Build from checkpoint tensors, casting every one to `compute_dtype`. + pub fn from_weights(config: Flux3Config, raw: WeightMap, compute_dtype: i32) -> Result { + check_keys(&config, &raw)?; + let weights: WeightMap = raw + .into_iter() + .map(|(k, v)| { + let v = if mlxcel_core::array_dtype(&v) == compute_dtype { + v + } else { + mlxcel_core::astype(&v, compute_dtype) + }; + (k, v) + }) + .collect(); + let w = &weights; + let blocks = |prefix: &str, n: usize| -> Result> { + (0..n) + .map(|i| Block::load(w, &format!("{prefix}.{i}"), &config)) + .collect() + }; + let modulations = |group: &str| -> Result<[ModeModulation; 3]> { + Ok([ + ModeModulation::load(w, &format!("{group}.image"))?, + ModeModulation::load(w, &format!("{group}.image_cond"))?, + ModeModulation::load(w, &format!("{group}.txt"))?, + ]) + }; + Ok(Self { + emb_in: [ + Linear::load(w, "emb_in.image")?, + Linear::load(w, "emb_in.image_cond")?, + ], + txt_in: Linear::load(w, "txt_in")?, + time_in: MlpEmbedder::load(w, "time_in")?, + ref_time_in: config + .flow_map + .then(|| MlpEmbedder::load(w, "ref_time_in")) + .transpose()?, + early: modulations("early_stream_modulations")?, + single: modulations("single_stream_modulations")?, + mode_blocks: [ + blocks("content_mode_blocks.image", config.depth)?, + blocks("content_mode_blocks.image_cond", config.depth)?, + blocks("txt_mode_blocks", config.depth)?, + ], + single_blocks: blocks("single_blocks", config.depth_single)?, + final_layer: LastLayer { + linear: Linear::load(w, "final_layer.image.linear")?, + ada: Linear::load(w, "final_layer.image.adaLN_modulation.1")?, + }, + config, + dtype: compute_dtype, + }) + } + + #[must_use] + pub fn config(&self) -> &Flux3Config { + &self.config + } + + /// The activation dtype. + #[must_use] + pub fn dtype(&self) -> i32 { + self.dtype + } + + /// `time_in(emb(t))`, `[B, 1, hidden]`. + fn time_vec(&self, embedder: &MlpEmbedder, t: f32, batch: i32) -> UniquePtr { + let t = mlxcel_core::full_f32(&[batch], t, self.dtype); + embedder.forward(&flux3_timestep_embedding(&t)) + } + + /// Velocity of the image tokens, `[B, L_image, in_channels.image]` in the + /// activation dtype. `target` is the flow map's target time and must be + /// given exactly when the checkpoint is a flow map. + pub fn forward( + &self, + inputs: &Flux3Inputs<'_>, + timestep: f32, + target: Option, + ) -> Result> { + if target.is_some() != self.config.flow_map { + bail!("target_timestep is required only for a FLUX.3 flow-map checkpoint"); + } + let batch = mlxcel_core::array_shape(inputs.image.tokens)[0]; + let reference = match (&self.ref_time_in, target) { + (Some(embedder), Some(target)) => Some(self.time_vec(embedder, target, batch)), + _ => None, + }; + let active = inputs.active(); + let mut xs = Vec::with_capacity(active.len()); + let mut vecs = Vec::with_capacity(active.len()); + let mut singles = Vec::with_capacity(active.len()); + let mut ropes = Vec::with_capacity(active.len()); + for (mode, input) in &active { + let t = if *mode == Mode::Image { timestep } else { 0.0 }; + let mut vec = self.time_vec(&self.time_in, t, batch); + if let Some(r) = &reference { + vec = mlxcel_core::add(&vec, r); + } + let early = self.early[mode.index()].forward(&vec); + singles.push(self.single[mode.index()].forward(&vec)); + let tokens = mlxcel_core::astype(input.tokens, self.dtype); + let mut x = match mode { + Mode::Text => self.txt_in.forward(&tokens), + Mode::Image => self.emb_in[0].forward(&tokens), + Mode::ImageCond => self.emb_in[1].forward(&tokens), + }; + let rope = pos_embed(input.ids, self.config.theta, &self.config.axes_dim); + for block in &self.mode_blocks[mode.index()] { + x = block.forward(&x, &rope, &early); + } + xs.push(x); + vecs.push(vec); + ropes.push(rope); + } + let cat = |parts: Vec<&MlxArray>, axis: i32| mlxcel_core::concatenate_many(&parts, axis); + let mut h = cat(xs.iter().map(|a| &**a).collect(), 1); + let joint_rope = ( + cat(ropes.iter().map(|r| &*r.0).collect(), 0), + cat(ropes.iter().map(|r| &*r.1).collect(), 0), + ); + let joint_mod: Modulation = std::array::from_fn(|i| { + let parts: Vec> = singles + .iter() + .zip(&xs) + .map(|(m, x)| mlxcel_core::broadcast_to(&m[i], &mlxcel_core::array_shape(x))) + .collect(); + cat(parts.iter().map(|a| &**a).collect(), 1) + }); + for block in &self.single_blocks { + h = block.forward(&h, &joint_rope, &joint_mod); + } + let s = mlxcel_core::array_shape(&h); + let n_image = mlxcel_core::array_shape(&xs[0])[1]; + let image = mlxcel_core::slice(&h, &[0, 0, 0], &[s[0], n_image, s[2]]); + Ok(self.final_layer.forward(&image, &vecs[0])) + } +} + +#[cfg(test)] +#[path = "transformer_tests.rs"] +mod tests; diff --git a/src/imagegen/flux3/transformer_tests.rs b/src/imagegen/flux3/transformer_tests.rs new file mode 100644 index 000000000..287b5846d --- /dev/null +++ b/src/imagegen/flux3/transformer_tests.rs @@ -0,0 +1,439 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The tiny transformer (hidden 32, two heads, two early and two single +//! blocks) against upstream's `Flux3Transformer` run in f32 on the same +//! closed-form weights and inputs +//! (`tests/fixtures/flux3/generate_flux3_unit_fixtures.py`, mlx-vlm e8035ae, +//! mlx 0.32.5 on CUDA). + +use serde_json::json; + +use super::*; +use crate::imagegen::flux2::prompt::prepare_text_ids; +use crate::imagegen::flux3::pipeline::{f32_values, image_ids}; + +/// Largest absolute difference to upstream's f32 output. +const F32_TOL: f32 = 2e-6; + +const TEXT_ONLY: [f32; 48] = [ + -0.040383007, + 0.06815505, + -0.21934871, + -0.030426612, + 0.036689263, + -0.088907346, + 0.11099311, + 0.06557587, + 0.14486197, + 0.079868495, + 0.023727277, + 0.041236956, + -0.08028561, + -0.12379945, + -0.016294345, + 0.003125458, + 0.029181222, + -0.02373375, + 0.13588555, + 0.06272204, + -0.0011326522, + 0.037120454, + -0.07393238, + -0.051565405, + 0.035431266, + 0.06312043, + -0.13219026, + -0.046769775, + -0.036931373, + -0.09694448, + 0.06925233, + 0.056973174, + 0.13613816, + 0.06489733, + 0.055260442, + 0.052407272, + -0.07154801, + -0.10060672, + -0.0329722, + -0.010305762, + 0.027590372, + -0.024754215, + 0.13612452, + 0.062478174, + -0.00019982457, + 0.038708564, + -0.0740286, + -0.05179169, +]; + +const WITH_REFERENCE: [f32; 48] = [ + -0.04039464, + 0.06815605, + -0.21932814, + -0.030436516, + 0.03667918, + -0.08890036, + 0.11100228, + 0.06556994, + 0.14481576, + 0.079883955, + 0.02379406, + 0.041193306, + -0.080329165, + -0.12378503, + -0.01624422, + 0.0031068008, + 0.029170197, + -0.023731798, + 0.1359022, + 0.06271337, + -0.0011411458, + 0.037125636, + -0.073922805, + -0.05157044, + 0.03541772, + 0.063122146, + -0.13217236, + -0.046780005, + -0.036940247, + -0.0969379, + 0.06926347, + 0.05696777, + 0.13609621, + 0.06491209, + 0.055325747, + 0.05236748, + -0.071589656, + -0.10059348, + -0.03292625, + -0.010324255, + 0.027579848, + -0.024752356, + 0.13614032, + 0.06246996, + -0.0002078563, + 0.038713507, + -0.07401947, + -0.05179646, +]; + +const BASE_TEXT_ONLY: [f32; 48] = [ + -0.04242853, + 0.07064815, + -0.22033152, + -0.03208273, + 0.03989867, + -0.09205873, + 0.11156313, + 0.067058176, + 0.14945695, + 0.07633496, + 0.023056082, + 0.04387919, + -0.08294552, + -0.12139275, + -0.013943467, + -0.0019835224, + 0.03334337, + -0.02856987, + 0.13888444, + 0.06373749, + -0.0037133023, + 0.04185174, + -0.072967105, + -0.055268697, + 0.034952372, + 0.065016456, + -0.13496962, + -0.046689004, + -0.03471911, + -0.10033111, + 0.07085741, + 0.056920655, + 0.14110456, + 0.060657322, + 0.055390067, + 0.055010006, + -0.07461244, + -0.09730911, + -0.030791625, + -0.015633555, + 0.031723, + -0.029573537, + 0.13914533, + 0.06346613, + -0.0027563795, + 0.043432113, + -0.07307912, + -0.05545705, +]; + +fn tiny_config(flow_map: bool) -> Flux3Config { + Flux3Config::from_value(&json!({ + "model": "flux-3-image-klein", + "dit": { + "hidden": 32, "heads": 2, "depth": 2, "depth_single": 2, "mlp_ratio": 3.0, + "axes_dim": [4, 4, 4, 4], "theta": 10000, + "in_channels": {"image": 8, "image_cond": 8, "text": 12}, + "image_rope_scale": 0.5, "flow_map": flow_map + } + })) + .unwrap() +} + +/// `((i * 7919 + k * 104729) % 2001 - 1000) / 1000 * scale` as f32. +fn formula(count: usize, k: usize, scale: f64) -> Vec { + (0..count as i64) + .map(|i| { + let v = ((i * 7919 + k as i64 * 104_729) % 2001 - 1000) as f64 / 1000.0 * scale; + v as f32 + }) + .collect() +} + +/// The shape of every tensor of the tiny model, keyed as the package names it. +fn shapes(config: &Flux3Config) -> Vec<(String, Vec)> { + let h = config.hidden; + let mlp = config.mlp_hidden(); + let d = config.head_dim(); + expected_keys(config) + .into_iter() + .map(|key| { + let shape = if key.ends_with("_norm.scale") { + vec![d] + } else if key.ends_with("mlp_in.weight") { + vec![2 * mlp, h] + } else if key.ends_with("mlp_out.weight") { + vec![h, mlp] + } else if key.ends_with(".lin.weight") { + vec![3 * h, h] + } else if key.ends_with("adaLN_modulation.1.weight") { + vec![2 * h, h] + } else if key.ends_with("in_layer.weight") { + vec![h, TIME_EMBED_DIM] + } else if key == "emb_in.image.weight" || key == "emb_in.image_cond.weight" { + vec![h, 8] + } else if key == "txt_in.weight" { + vec![h, 12] + } else if key == "final_layer.image.linear.weight" { + vec![8, h] + } else { + vec![h, h] + }; + (key, shape) + }) + .collect() +} + +/// The closed-form weights, tensor `k` in sorted key order. +fn tiny_weights(config: &Flux3Config) -> WeightMap { + shapes(config) + .into_iter() + .enumerate() + .map(|(k, (key, shape))| { + let n: i32 = shape.iter().product(); + ( + key, + mlxcel_core::from_slice_f32(&formula(n as usize, k, 0.05), &shape), + ) + }) + .collect() +} + +fn tokens(shape: &[i32], k: usize) -> UniquePtr { + let n: i32 = shape.iter().product(); + mlxcel_core::from_slice_f32(&formula(n as usize, k, 1.0), shape) +} + +fn tiny(flow_map: bool) -> Flux3Transformer { + let config = tiny_config(flow_map); + let weights = tiny_weights(&config); + Flux3Transformer::from_weights(config, weights, dtype::FLOAT32).unwrap() +} + +fn assert_close(got: &MlxArray, want: &[f32], label: &str) { + let got = f32_values(got); + assert_eq!(got.len(), want.len(), "{label}"); + let worst = got + .iter() + .zip(want) + .map(|(g, w)| (g - w).abs()) + .fold(0.0_f32, f32::max); + assert!(worst <= F32_TOL, "{label}: max abs diff {worst}"); +} + +struct Case { + text: UniquePtr, + text_ids: UniquePtr, + image: UniquePtr, + image_ids: UniquePtr, + cond: UniquePtr, + cond_ids: UniquePtr, +} + +impl Case { + fn new() -> Self { + Self { + text: tokens(&[1, 5, 12], 1001), + text_ids: mlxcel_core::reshape(&prepare_text_ids(1, 5), &[5, 4]), + image: tokens(&[1, 6, 8], 1002), + image_ids: image_ids(32, 48, None, 0.5), + cond: tokens(&[1, 4, 8], 1003), + cond_ids: image_ids(32, 32, Some(0), 0.5), + } + } + + fn inputs(&self, with_reference: bool) -> Flux3Inputs<'_> { + Flux3Inputs { + image: ModeInput { + tokens: &self.image, + ids: &self.image_ids, + }, + image_cond: with_reference.then(|| ModeInput { + tokens: &self.cond, + ids: &self.cond_ids, + }), + text: ModeInput { + tokens: &self.text, + ids: &self.text_ids, + }, + } + } +} + +#[test] +fn the_tiny_transformer_matches_upstream() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let case = Case::new(); + let flow = tiny(true); + let text_only = flow.forward(&case.inputs(false), 0.7, Some(0.55)).unwrap(); + assert_eq!(mlxcel_core::array_shape(&text_only), vec![1, 6, 8]); + assert_close(&text_only, &TEXT_ONLY, "text only"); + let with_reference = flow.forward(&case.inputs(true), 0.7, Some(0.55)).unwrap(); + assert_close(&with_reference, &WITH_REFERENCE, "text and one reference"); + let base = tiny(false).forward(&case.inputs(false), 0.7, None).unwrap(); + assert_close(&base, &BASE_TEXT_ONLY, "no flow map"); +} + +#[test] +fn the_cases_are_distinguishable() { + // The tolerance is far below the differences the reference stream and the + // flow-map embedding make, so each case checks its own path. + let gap = |a: &[f32], b: &[f32]| { + a.iter() + .zip(b) + .map(|(x, y)| (x - y).abs()) + .fold(0.0_f32, f32::max) + }; + assert!(gap(&TEXT_ONLY, &WITH_REFERENCE) > 20.0 * F32_TOL); + assert!(gap(&TEXT_ONLY, &BASE_TEXT_ONLY) > 1000.0 * F32_TOL); +} + +#[test] +fn the_target_time_goes_with_the_flow_map_only() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let case = Case::new(); + let e = tiny(true) + .forward(&case.inputs(false), 0.7, None) + .err() + .unwrap(); + assert!(e.to_string().contains("flow-map"), "{e}"); + let e = tiny(false) + .forward(&case.inputs(false), 0.7, Some(0.5)) + .err() + .unwrap(); + assert!(e.to_string().contains("flow-map"), "{e}"); + // The flow map's output moves with the target time. + let flow = tiny(true); + let a = f32_values(&flow.forward(&case.inputs(false), 0.7, Some(0.55)).unwrap()); + let b = f32_values(&flow.forward(&case.inputs(false), 0.7, Some(0.1)).unwrap()); + assert_ne!(a, b); +} + +#[test] +fn timestep_embedding_rounds_the_scaled_time_to_bf16() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + // bf16(0.3) = 0.30078125; 1000 * that = 300.78125, which bf16 rounds to + // 300. The embedding's first frequency is 1, so its first two lanes are + // cos(300) and sin(300), not cos(300.78...). + let t = mlxcel_core::full_f32(&[1], 0.3, dtype::BFLOAT16); + let emb = flux3_timestep_embedding(&t); + assert_eq!(mlxcel_core::array_shape(&emb), vec![1, 1, 256]); + assert_eq!(mlxcel_core::array_dtype(&emb), dtype::BFLOAT16); + let v = f32_values(&emb); + // Round to the nearest bf16, ties to even. + let bf16 = |x: f32| { + let b = x.to_bits(); + f32::from_bits((b + 0x7fff + ((b >> 16) & 1)) & 0xffff_0000) + }; + assert_eq!(v[0], bf16(300.0_f32.cos())); + assert_eq!(v[128], bf16(300.0_f32.sin())); + assert_ne!(v[0], bf16(300.78125_f32.cos())); + // In f32 nothing is rounded: 1000 * 0.3 = 300.0 (f32), exactly. + let t = mlxcel_core::full_f32(&[2], 0.25, dtype::FLOAT32); + let emb = flux3_timestep_embedding(&t); + assert_eq!(mlxcel_core::array_shape(&emb), vec![2, 1, 256]); + let v = f32_values(&emb); + assert!((v[0] - 250.0_f32.cos()).abs() < 1e-6); +} + +#[test] +fn the_published_package_has_359_tensors() { + // `manifest.json` of flux-3-image-klein: "tensors": 359; the base model + // has no `ref_time_in`. + assert_eq!(expected_keys(&Flux3Config::default()).len(), 359); + let base = Flux3Config { + flow_map: false, + ..Flux3Config::default() + }; + assert_eq!(expected_keys(&base).len(), 357); +} + +#[test] +fn a_mismatched_package_names_missing_and_unexpected_tensors() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let config = tiny_config(true); + let mut weights = tiny_weights(&config); + weights.remove("txt_in.weight"); + weights.insert( + "transformer.extra.weight".into(), + mlxcel_core::zeros(&[1], dtype::FLOAT32), + ); + let e = Flux3Transformer::from_weights(config, weights, dtype::FLOAT32) + .err() + .unwrap() + .to_string(); + assert!(e.contains("missing [txt_in.weight]"), "{e}"); + assert!(e.contains("unexpected [transformer.extra.weight]"), "{e}"); +} + +#[test] +fn bf16_weights_run_in_bf16() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let config = tiny_config(true); + let weights = tiny_weights(&config); + let model = Flux3Transformer::from_weights(config, weights, dtype::BFLOAT16).unwrap(); + let case = Case::new(); + let out = model.forward(&case.inputs(true), 0.7, Some(0.55)).unwrap(); + assert_eq!(mlxcel_core::array_dtype(&out), dtype::BFLOAT16); + // bf16 stays near the f32 reference. + let got = f32_values(&out); + let worst = got + .iter() + .zip(&WITH_REFERENCE) + .map(|(g, w)| (g - w).abs()) + .fold(0.0_f32, f32::max); + assert!(worst < 0.02, "bf16 vs f32 {worst}"); +} diff --git a/src/imagegen/flux3/weights.rs b/src/imagegen/flux3/weights.rs new file mode 100644 index 000000000..4baede89a --- /dev/null +++ b/src/imagegen/flux3/weights.rs @@ -0,0 +1,183 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! FLUX.3 weight loading. +//! +//! A port of `load_transformer` and `load_vae` in +//! . +//! The transformer is the root `model.safetensors` under BFL's names, loaded +//! strictly and cast to bf16. The autoencoder is `ae.safetensors`, also under +//! BFL's names; its architecture is the FLUX.2 VAE, so instead of a second +//! implementation its tensors are renamed to the Diffusers names +//! [`Flux2Vae`] reads (`vae/config.json` in the published package declares +//! `AutoencoderKLFlux2`), the 1x1 attention convolutions become the linear +//! projections Diffusers stores, `num_batches_tracked` is dropped, and the +//! VAE runs in f32. + +use std::path::Path; + +use anyhow::{Context, Result, bail}; +use mlxcel_core::weights::WeightMap; +use mlxcel_core::{UniquePtr, dtype}; + +use super::config::Flux3Config; +use super::transformer::Flux3Transformer; +use crate::imagegen::{Flux2Vae, Flux2VaeConfig}; + +/// Load `model.safetensors` strictly, as `compute_dtype`. +pub fn load_transformer( + path: &Path, + config: &Flux3Config, + compute_dtype: i32, +) -> Result { + let raw = mlxcel_core::weights::load_safetensors(path) + .map_err(anyhow::Error::msg) + .with_context(|| format!("cannot load FLUX.3 transformer weights {}", path.display()))?; + Flux3Transformer::from_weights(config.clone(), raw, compute_dtype) +} + +/// The Diffusers name of an `ae.safetensors` tensor, `Ok(None)` for one the +/// VAE does not use (`num_batches_tracked`). `levels` is the number of +/// resolution levels (4); BFL numbers the decoder's levels from the output +/// side, Diffusers from the input side. +pub fn bfl_vae_key(key: &str, levels: usize) -> Result> { + if key.ends_with(".num_batches_tracked") { + return Ok(None); + } + let parts: Vec<&str> = key.split('.').collect(); + let unknown = || anyhow::anyhow!("unknown FLUX.3 autoencoder tensor {key}"); + let resnet = |rest: &[&str]| -> String { + let mut rest: Vec<&str> = rest.to_vec(); + if rest.first() == Some(&"nin_shortcut") { + rest[0] = "conv_shortcut"; + } + rest.join(".") + }; + let mapped = match parts.as_slice() { + ["bn", rest @ ..] => format!("bn.{}", rest.join(".")), + ["encoder", "quant_conv", rest @ ..] => format!("quant_conv.{}", rest.join(".")), + ["decoder", "post_quant_conv", rest @ ..] => format!("post_quant_conv.{}", rest.join(".")), + [ + side @ ("encoder" | "decoder"), + name @ ("conv_in" | "conv_out"), + rest @ .., + ] => { + format!("{side}.{name}.{}", rest.join(".")) + } + [side @ ("encoder" | "decoder"), "norm_out", rest @ ..] => { + format!("{side}.conv_norm_out.{}", rest.join(".")) + } + [ + side @ ("encoder" | "decoder"), + "mid", + block @ ("block_1" | "block_2"), + rest @ .., + ] => { + let index = if *block == "block_1" { 0 } else { 1 }; + format!("{side}.mid_block.resnets.{index}.{}", resnet(rest)) + } + [ + side @ ("encoder" | "decoder"), + "mid", + "attn_1", + name, + rest @ .., + ] => { + let name = match *name { + "norm" => "group_norm", + "q" => "to_q", + "k" => "to_k", + "v" => "to_v", + "proj_out" => "to_out.0", + _ => return Err(unknown()), + }; + format!("{side}.mid_block.attentions.0.{name}.{}", rest.join(".")) + } + ["encoder", "down", level, "block", j, rest @ ..] => { + format!("encoder.down_blocks.{level}.resnets.{j}.{}", resnet(rest)) + } + ["encoder", "down", level, "downsample", "conv", rest @ ..] => { + format!( + "encoder.down_blocks.{level}.downsamplers.0.conv.{}", + rest.join(".") + ) + } + [ + "decoder", + "up", + level, + kind @ ("block" | "upsample"), + rest @ .., + ] => { + let level: usize = level.parse().map_err(|_| unknown())?; + if level >= levels { + return Err(unknown()); + } + let flipped = levels - 1 - level; + match (*kind, rest) { + ("block", [j, rest @ ..]) => { + format!("decoder.up_blocks.{flipped}.resnets.{j}.{}", resnet(rest)) + } + ("upsample", ["conv", rest @ ..]) => { + format!( + "decoder.up_blocks.{flipped}.upsamplers.0.conv.{}", + rest.join(".") + ) + } + _ => return Err(unknown()), + } + } + _ => return Err(unknown()), + }; + Ok(Some(mapped)) +} + +/// Rename `ae.safetensors` tensors to Diffusers names; the attention's 1x1 +/// convolution kernels `[C, C, 1, 1]` become `[C, C]` linear weights. +pub fn bfl_vae_to_diffusers(raw: WeightMap, levels: usize) -> Result { + let mut out = WeightMap::new(); + for (key, value) in raw { + let Some(name) = bfl_vae_key(&key, levels)? else { + continue; + }; + let is_attention_proj = name.contains(".attentions.0.to_") && name.ends_with(".weight"); + let shape = mlxcel_core::array_shape(&value); + let value: UniquePtr<_> = if is_attention_proj && shape.len() == 4 { + if shape[2] != 1 || shape[3] != 1 { + bail!("FLUX.3 autoencoder tensor {key} is not a 1x1 kernel: {shape:?}"); + } + mlxcel_core::reshape(&value, &[shape[0], shape[1]]) + } else { + value + }; + if out.insert(name.clone(), value).is_some() { + bail!("two FLUX.3 autoencoder tensors map to {name}"); + } + } + Ok(out) +} + +/// Load `ae.safetensors` as the FLUX.2 VAE (with its encoder) in f32. +pub fn load_vae(path: &Path) -> Result { + let raw = mlxcel_core::weights::load_safetensors(path) + .map_err(anyhow::Error::msg) + .with_context(|| format!("cannot load FLUX.3 autoencoder {}", path.display()))?; + let config = Flux2VaeConfig::default(); + let weights = bfl_vae_to_diffusers(raw, config.block_out_channels.len())?; + Flux2Vae::from_raw_weights(config, weights, true, dtype::FLOAT32) +} + +#[cfg(test)] +#[path = "weights_tests.rs"] +mod tests; diff --git a/src/imagegen/flux3/weights_tests.rs b/src/imagegen/flux3/weights_tests.rs new file mode 100644 index 000000000..226248bc7 --- /dev/null +++ b/src/imagegen/flux3/weights_tests.rs @@ -0,0 +1,133 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The name map is checked here; that it reproduces the published Diffusers +//! `vae/` tensors and their encode and decode is checked on the real package +//! in `parity_tests.rs`. + +use super::*; + +fn map(key: &str) -> Option { + bfl_vae_key(key, 4).unwrap() +} + +#[test] +fn bfl_autoencoder_names_map_to_diffusers() { + for (bfl, diffusers) in [ + ("bn.running_mean", "bn.running_mean"), + ("bn.running_var", "bn.running_var"), + ("encoder.quant_conv.weight", "quant_conv.weight"), + ("decoder.post_quant_conv.bias", "post_quant_conv.bias"), + ("encoder.conv_in.weight", "encoder.conv_in.weight"), + ("decoder.conv_out.bias", "decoder.conv_out.bias"), + ("encoder.norm_out.weight", "encoder.conv_norm_out.weight"), + ("decoder.norm_out.bias", "decoder.conv_norm_out.bias"), + ( + "encoder.mid.block_1.conv1.weight", + "encoder.mid_block.resnets.0.conv1.weight", + ), + ( + "decoder.mid.block_2.norm2.bias", + "decoder.mid_block.resnets.1.norm2.bias", + ), + ( + "encoder.mid.attn_1.norm.weight", + "encoder.mid_block.attentions.0.group_norm.weight", + ), + ( + "decoder.mid.attn_1.q.weight", + "decoder.mid_block.attentions.0.to_q.weight", + ), + ( + "decoder.mid.attn_1.proj_out.bias", + "decoder.mid_block.attentions.0.to_out.0.bias", + ), + ( + "encoder.down.1.block.0.nin_shortcut.weight", + "encoder.down_blocks.1.resnets.0.conv_shortcut.weight", + ), + ( + "encoder.down.2.downsample.conv.weight", + "encoder.down_blocks.2.downsamplers.0.conv.weight", + ), + // BFL counts decoder levels from the output; Diffusers from the input. + ( + "decoder.up.0.block.2.conv2.weight", + "decoder.up_blocks.3.resnets.2.conv2.weight", + ), + ( + "decoder.up.3.upsample.conv.bias", + "decoder.up_blocks.0.upsamplers.0.conv.bias", + ), + ( + "decoder.up.0.block.0.nin_shortcut.bias", + "decoder.up_blocks.3.resnets.0.conv_shortcut.bias", + ), + ] { + assert_eq!(map(bfl).as_deref(), Some(diffusers), "{bfl}"); + } + assert_eq!(map("bn.num_batches_tracked"), None); +} + +#[test] +fn unknown_autoencoder_names_are_errors() { + for key in [ + "encoder.mid.attn_1.out.weight", + "decoder.up.4.block.0.conv1.weight", + "decoder.up.x.block.0.conv1.weight", + "decoder.up.1.downsample.conv.weight", + "vae.encoder.conv_in.weight", + "transformer.blocks.0.weight", + ] { + let e = bfl_vae_key(key, 4).unwrap_err().to_string(); + assert!(e.contains(key), "{e}"); + } +} + +#[test] +fn attention_kernels_become_linear_weights() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let mut raw = WeightMap::new(); + raw.insert( + "encoder.mid.attn_1.k.weight".into(), + mlxcel_core::zeros(&[8, 8, 1, 1], dtype::FLOAT32), + ); + raw.insert( + "encoder.conv_in.weight".into(), + mlxcel_core::zeros(&[8, 3, 3, 3], dtype::FLOAT32), + ); + raw.insert( + "bn.num_batches_tracked".into(), + mlxcel_core::zeros(&[1], dtype::INT32), + ); + let out = bfl_vae_to_diffusers(raw, 4).unwrap(); + assert_eq!(out.len(), 2); + assert_eq!( + mlxcel_core::array_shape(&out["encoder.mid_block.attentions.0.to_k.weight"]), + vec![8, 8] + ); + // Convolutions keep their kernels; the VAE loader transposes them. + assert_eq!( + mlxcel_core::array_shape(&out["encoder.conv_in.weight"]), + vec![8, 3, 3, 3] + ); + + let mut bad = WeightMap::new(); + bad.insert( + "encoder.mid.attn_1.q.weight".into(), + mlxcel_core::zeros(&[8, 8, 3, 3], dtype::FLOAT32), + ); + let e = bfl_vae_to_diffusers(bad, 4).err().unwrap().to_string(); + assert!(e.contains("1x1"), "{e}"); +} diff --git a/src/imagegen/latent.rs b/src/imagegen/latent.rs index a3ae83a1b..95af2c5a4 100644 --- a/src/imagegen/latent.rs +++ b/src/imagegen/latent.rs @@ -25,7 +25,7 @@ //! [`prepare_packed_latents`] and [`prepare_grid_ids`] port the noise and //! position-id helpers of the same file (`#L38-L71`). //! -//! Used by: ErnieImage, LLaDAImage, Flux2, Bonsai. +//! Used by: ErnieImage, LLaDAImage, Flux2, Bonsai, Flux3. use anyhow::{Result, bail}; use mlxcel_core::{MlxArray, UniquePtr}; diff --git a/src/imagegen/mod.rs b/src/imagegen/mod.rs index 17b0a3215..5d0066522 100644 --- a/src/imagegen/mod.rs +++ b/src/imagegen/mod.rs @@ -28,6 +28,7 @@ pub mod bonsai; pub mod dit_blocks; pub mod ernie_image; pub mod flux2; +pub mod flux3; pub mod ideogram4; pub mod latent; pub mod llada_image; diff --git a/src/imagegen/probe.rs b/src/imagegen/probe.rs index 9b1172b67..c36209fd1 100644 --- a/src/imagegen/probe.rs +++ b/src/imagegen/probe.rs @@ -21,6 +21,11 @@ //! and usually no top-level `config.json` `model_type`, so they cannot be //! classified the way text checkpoints are. The probe reads, in order: //! +//! 0. the root `config.json` of a FLUX.3 package (BFL's layout, no +//! `model_type`), recognized by +//! [`is_flux3_config`](super::flux3::config::is_flux3_config) before any +//! other rule: its `vae/config.json` names `AutoencoderKLFlux2`, which the +//! class-name rule would otherwise read as `flux2`; //! 1. `manifest.json`, which identifies Bonsai before any class name does, //! because Bonsai ships a `Flux2KleinPipeline` `model_index.json`; //! 2. `model_index.json` and `config.json` (`model_type`, `_class_name` and @@ -42,6 +47,7 @@ use serde_json::Value; pub const IMAGE_FAMILIES: &[&str] = &[ "bonsai", "flux2", + "flux3", "z_image", "ming_image", "ernie_image", @@ -88,6 +94,11 @@ pub fn detect_image_family(path: &Path) -> Result> { if !path.is_dir() { return Ok(None); } + if load_json_object(&path.join("config.json")) + .is_some_and(|config| super::flux3::config::is_flux3_config(&config)) + { + return Ok(Some(super::flux3::FAMILY)); + } let mut candidates: Vec = Vec::new(); if let Some(manifest) = load_json_object(&path.join("manifest.json")) { diff --git a/src/imagegen/probe_tests.rs b/src/imagegen/probe_tests.rs index a5b627e3f..b8963d148 100644 --- a/src/imagegen/probe_tests.rs +++ b/src/imagegen/probe_tests.rs @@ -382,3 +382,61 @@ fn moss_image_from_the_pipeline_class_name() { ); assert_eq!(probe(&dir), Some("moss_image")); } + +/// The published `black-forest-labs/flux-3-image-klein` layout: BFL's root +/// `config.json` (no `model_type`), a FLUX.2 VAE copy under `vae/` and a +/// Qwen3-VL text encoder. Without the explicit root check the VAE's +/// `AutoencoderKLFlux2` class name reads as `flux2`. +fn write_flux3_package(dir: &std::path::Path, model: &str) { + write( + dir, + "config.json", + json!({ + "format_version": 1, + "model": model, + "dit": {"in_channels": {"image": 128, "image_cond": 128, "text": 20480}} + }), + ); + write( + dir, + "manifest.json", + json!({"kind": "f3_dit_export", "tensors": 359}), + ); + write( + dir, + "vae/config.json", + json!({"_class_name": "AutoencoderKLFlux2"}), + ); + write( + dir, + "text_encoder/config.json", + json!({"model_type": "qwen3_vl", "architectures": ["Qwen3VLForConditionalGeneration"]}), + ); +} + +#[test] +fn flux3_from_the_root_config_before_any_component() { + let dir = TempDir::new().unwrap(); + write_flux3_package(dir.path(), "flux-3-image-klein"); + assert_eq!(probe(&dir), Some("flux3")); + let base = TempDir::new().unwrap(); + write_flux3_package(base.path(), "flux-3-image-klein-base"); + assert_eq!(probe(&base), Some("flux3")); +} + +#[test] +fn a_flux2_tree_is_not_flux3() { + let dir = TempDir::new().unwrap(); + // FLUX.2's root config is a transformers config, not BFL's package. + write( + dir.path(), + "config.json", + json!({"model": "flux-2-klein", "dit": {}}), + ); + write( + dir.path(), + "vae/config.json", + json!({"_class_name": "AutoencoderKLFlux2"}), + ); + assert_eq!(probe(&dir), Some("flux2")); +} diff --git a/src/imagegen/qwen3_text_encoder.rs b/src/imagegen/qwen3_text_encoder.rs index 7601522c8..6004eea90 100644 --- a/src/imagegen/qwen3_text_encoder.rs +++ b/src/imagegen/qwen3_text_encoder.rs @@ -32,7 +32,12 @@ //! [`Qwen3TextEncoder::stacked_prompt_embeds`] stacks chosen entries into the //! `[B, T, n * H]` layout FLUX.2 uses. //! -//! Used by: Flux2, ZImage, Ideogram4, Bonsai. +//! [`Qwen3TextEncoder::hidden_states_at`] is the same walk at caller-chosen +//! positions (FLUX.3 puts every padded token at position 1), and +//! [`Qwen3TextEncoder::load_first_layers`] builds only the layers a +//! conditioner taps. +//! +//! Used by: Flux2, ZImage, Ideogram4, Bonsai, Flux3. use std::path::Path; @@ -114,6 +119,15 @@ fn language_config(config: &Value) -> Result { pub struct Qwen3TextEncoder { model: Qwen3Model, hidden_size: i32, + head_dim: i32, + rope_theta: f32, +} + +/// The decoder layer a weight belongs to, for a key [`text_key`] keeps. +fn layer_of(key: &str) -> Option { + let rest = text_key(key)?; + let rest = rest.strip_prefix("model.layers.")?; + rest.split('.').next()?.parse().ok() } impl Qwen3TextEncoder { @@ -155,6 +169,8 @@ impl Qwen3TextEncoder { args.tie_word_embeddings = true; let weights = normalize_weights(weights); let hidden_size = args.hidden_size as i32; + let head_dim = args.head_dim as i32; + let rope_theta = args.rope_theta; // Upstream mlx-vlm `models/flux2/qwen/attention.py:148-162` (git // 73d366ec) casts q, k and v to f32 for SDPA and the output back to // the query dtype; this encoder keeps the activation dtype. Measured @@ -168,7 +184,73 @@ impl Qwen3TextEncoder { let model = Qwen3Model::from_weights(&weights, &args) .map_err(anyhow::Error::msg) .context("cannot build the Qwen3 text encoder")?; - Ok(Self { model, hidden_size }) + Ok(Self { + model, + hidden_size, + head_dim, + rope_theta, + }) + } + + /// Load only decoder layers `1..=num_layers` of a text-encoder directory, + /// with every floating tensor cast to `compute_dtype`. + /// + /// A conditioner that taps hidden states up to layer `n` never needs the + /// layers after it; their tensors (and every non-text tensor) are not + /// read. The final norm is kept, so [`Self::final_norm`] still works when + /// `num_layers` is the full depth. + /// + /// Used by: Flux3 (`imagegen::flux3::conditioner`). + pub fn load_first_layers(dir: &Path, num_layers: usize, compute_dtype: i32) -> Result { + let config_path = dir.join("config.json"); + let text = std::fs::read_to_string(&config_path) + .with_context(|| format!("cannot read {}", config_path.display()))?; + let mut config: Value = + serde_json::from_str(&crate::models::sanitize_config_json(&text)) + .with_context(|| format!("cannot parse {}", config_path.display()))?; + let nested = config.get("text_config").is_some_and(Value::is_object); + let target = if nested { + config.get_mut("text_config").expect("checked above") + } else { + &mut config + }; + let total = target + .get("num_hidden_layers") + .and_then(Value::as_u64) + .context("text encoder config.json has no num_hidden_layers")?; + if num_layers == 0 || num_layers as u64 > total { + bail!("text feature layer {num_layers} is outside the {total}-layer text backbone"); + } + target["num_hidden_layers"] = Value::from(num_layers as u64); + let weights = mlxcel_core::weights::load_weights_from_dir_filtered(dir, |key| { + text_key(key).is_some() && layer_of(key).is_none_or(|layer| layer < num_layers) + }) + .map_err(anyhow::Error::msg) + .with_context(|| format!("cannot load text encoder weights from {}", dir.display()))?; + let weights = weights + .into_iter() + .map(|(k, v)| { + let floating = matches!( + mlxcel_core::array_dtype(&v), + dtype::FLOAT16 | dtype::FLOAT32 | dtype::BFLOAT16 + ); + let v = if floating && mlxcel_core::array_dtype(&v) != compute_dtype { + mlxcel_core::astype(&v, compute_dtype) + } else { + v + }; + (k, v) + }) + .collect(); + Self::from_weights(&config, weights) + } + + /// The model's final RMS norm. + /// + /// Used by: Flux3 (applied only when the last layer is tapped). + #[must_use] + pub fn final_norm(&self, h: &MlxArray) -> UniquePtr { + self.model.norm.forward(h) } /// Number of decoder layers. @@ -239,6 +321,88 @@ impl Qwen3TextEncoder { Ok(self.model.forward_all_hidden(input_ids, Some(&bias))) } + /// [`Self::hidden_states`] at explicit `position_ids` (`[B, T]` int32) + /// instead of `0..T`. + /// + /// The rotation follows mlx-vlm's Qwen3-VL language model with the same + /// position on all three M-RoPE axes (text only, where the sections + /// collapse to ordinary RoPE): angles `position * inv_freq` in f32 with + /// `inv_freq = 1 / theta^(2i / head_dim)`, `cos` and `sin` of the doubled + /// table cast to the activation dtype, then `q * cos + rotate_half(q) * sin`. + /// + /// Used by: Flux3 (padded tokens at position 1). + pub fn hidden_states_at( + &self, + input_ids: &MlxArray, + attention_mask: Option<&MlxArray>, + position_ids: &MlxArray, + ) -> Result>> { + let shape = mlxcel_core::array_shape(input_ids); + if shape.len() != 2 { + bail!("input_ids must be [B, T], got {shape:?}"); + } + for (name, other) in [ + ("attention_mask", attention_mask), + ("position_ids", Some(position_ids)), + ] { + if let Some(other) = other { + let other_shape = mlxcel_core::array_shape(other); + if other_shape != shape { + bail!("{name} {other_shape:?} must match input_ids {shape:?}"); + } + } + } + let (b, t) = (shape[0], shape[1]); + let bias = Self::attention_bias(attention_mask, b, t); + let mut h = self.model.embed_tokens.forward(input_ids); + let (cos, sin) = self.rope_tables(position_ids, mlxcel_core::array_dtype(&h)); + let mut states = Vec::with_capacity(self.model.layers.len() + 1); + states.push(mlxcel_core::copy(&h)); + for layer in &self.model.layers { + h = layer.forward_at_positions(&h, &cos, &sin, Some(&bias)); + states.push(mlxcel_core::copy(&h)); + } + Ok(states) + } + + /// `[B, 1, T, head_dim]` rotate-half `cos` and `sin` tables in `out_dtype`. + fn rope_tables( + &self, + position_ids: &MlxArray, + out_dtype: i32, + ) -> (UniquePtr, UniquePtr) { + let half = self.head_dim / 2; + let shape = mlxcel_core::array_shape(position_ids); + let (b, t) = (shape[0], shape[1]); + let exponent = mlxcel_core::divide( + &mlxcel_core::astype( + &mlxcel_core::arange_i32(0, self.head_dim, 2), + dtype::FLOAT32, + ), + &mlxcel_core::full_f32(&[1], self.head_dim as f32, dtype::FLOAT32), + ); + let inv_freq = mlxcel_core::divide( + &mlxcel_core::full_f32(&[1], 1.0, dtype::FLOAT32), + &mlxcel_core::power( + &mlxcel_core::full_f32(&[1], self.rope_theta, dtype::FLOAT32), + &exponent, + ), + ); + let positions = mlxcel_core::astype(position_ids, dtype::FLOAT32); + let freqs = mlxcel_core::multiply( + &mlxcel_core::reshape(&positions, &[b, t, 1]), + &mlxcel_core::reshape(&inv_freq, &[1, 1, half]), + ); + let emb = mlxcel_core::concatenate(&freqs, &freqs, -1); + let table = |a: UniquePtr| { + mlxcel_core::reshape( + &mlxcel_core::astype(&a, out_dtype), + &[b, 1, t, self.head_dim], + ) + }; + (table(mlxcel_core::cos(&emb)), table(mlxcel_core::sin(&emb))) + } + /// Stack the hidden states at `layers` into `[B, T, layers.len() * H]`. /// /// Entries are indexed as in [`Self::hidden_states`] (0 = embeddings), and diff --git a/src/imagegen/qwen3_text_encoder_tests.rs b/src/imagegen/qwen3_text_encoder_tests.rs index 2d2eac328..41babcb20 100644 --- a/src/imagegen/qwen3_text_encoder_tests.rs +++ b/src/imagegen/qwen3_text_encoder_tests.rs @@ -528,3 +528,120 @@ fn real_qwen3_hidden_states_reproduce_the_generation_logits() { "greedy tokens must agree" ); } + +/// Positions `0..T` for every row of a `[B, T]` batch. +fn ordinal_positions(b: i32, t: i32) -> UniquePtr { + let flat: Vec = (0..b).flat_map(|_| 0..t).collect(); + mlxcel_core::from_slice_i32(&flat, &[b, t]) +} + +#[test] +fn explicit_ordinal_positions_match_the_cached_path() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let enc = encoder(); + let batch = ids(&[&[3, 10, 7, 22, 5, 9], &[4, 8, 15, 2, 0, 0]]); + let mask = mlxcel_core::from_slice_i32(&[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], &[2, 6]); + let cached = enc.hidden_states(&batch, Some(&mask)).unwrap(); + let explicit = enc + .hidden_states_at(&batch, Some(&mask), &ordinal_positions(2, 6)) + .unwrap(); + assert_eq!(cached.len(), explicit.len()); + for (i, (c, e)) in cached.iter().zip(&explicit).enumerate() { + let err = rel_rms(e, c); + assert!( + err < TOL, + "layer {i}: explicit positions differ, rel-RMS {err}" + ); + } +} + +#[test] +fn padding_positions_move_only_the_padded_rows() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let enc = encoder(); + let batch = ids(&[&[4, 8, 15, 2, 0, 0]]); + let mask = mlxcel_core::from_slice_i32(&[1, 1, 1, 1, 0, 0], &[1, 6]); + // FLUX.3: `cumsum(mask) - 1`, padding at position 1. + let positions = mlxcel_core::from_slice_i32(&[0, 1, 2, 3, 1, 1], &[1, 6]); + let ordinal = enc + .hidden_states_at(&batch, Some(&mask), &ordinal_positions(1, 6)) + .unwrap(); + let padded = enc + .hidden_states_at(&batch, Some(&mask), &positions) + .unwrap(); + let last = enc.num_layers(); + // Real tokens never see a padded key, so their states do not move. + let err = rel_rms(&head(&padded[last], 4), &head(&ordinal[last], 4)); + assert!(err < TOL, "real rows moved, rel-RMS {err}"); + // A padded query is rotated to another position, so its state moves. + let tail = |a: &MlxArray| mlxcel_core::slice(a, &[0, 4, 0], &[1, 6, HIDDEN]); + let moved = rel_rms(&tail(&padded[last]), &tail(&ordinal[last])); + assert!(moved > 1e-3, "padded rows did not move, rel-RMS {moved}"); + // The two padded tokens share a position and the same visible keys + // except themselves, so both are finite. + assert!(to_vec(&padded[last]).iter().all(|v| v.is_finite())); +} + +#[test] +fn explicit_positions_must_match_the_ids_shape() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let enc = encoder(); + let batch = ids(&[&[4, 8, 15]]); + let err = enc + .hidden_states_at(&batch, None, &ordinal_positions(1, 4)) + .err() + .expect("a [1, 4] position table for [1, 3] ids is an error") + .to_string(); + assert!(err.contains("position_ids"), "{err}"); +} + +#[test] +fn load_first_layers_builds_only_the_tapped_layers() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let dir = tempfile::tempdir().unwrap(); + // A Qwen3-VL layout: nested text_config and `model.language_model.` keys, + // plus a vision tensor the loader must skip. + let mut weights = weights_with("model.language_model."); + weights.insert( + "model.visual.patch_embed.proj.weight".into(), + mlxcel_core::zeros(&[4, 4], mlxcel_core::dtype::FLOAT32), + ); + crate::imagegen::testing::write_bf16_safetensors( + &dir.path().join("model.safetensors"), + &weights, + ); + let config = json!({"model_type": "qwen3_vl", "text_config": config()}); + std::fs::write(dir.path().join("config.json"), config.to_string()).unwrap(); + + let two = + Qwen3TextEncoder::load_first_layers(dir.path(), 2, mlxcel_core::dtype::BFLOAT16).unwrap(); + assert_eq!(two.num_layers(), 2); + let full = + Qwen3TextEncoder::load_first_layers(dir.path(), LAYERS, mlxcel_core::dtype::BFLOAT16) + .unwrap(); + assert_eq!(full.num_layers(), LAYERS); + let batch = ids(&[&[3, 10, 7, 22]]); + let positions = ordinal_positions(1, 4); + let a = two.hidden_states_at(&batch, None, &positions).unwrap(); + let b = full.hidden_states_at(&batch, None, &positions).unwrap(); + assert_eq!(a.len(), 3); + for i in 0..3 { + assert_eq!( + mlxcel_core::array_dtype(&a[i]), + mlxcel_core::dtype::BFLOAT16 + ); + assert_eq!(to_vec(&a[i]), to_vec(&b[i]), "layer {i}"); + } + // The final norm is kept for a full-depth load. + let normed = full.final_norm(&b[LAYERS]); + assert_eq!(mlxcel_core::array_shape(&normed), vec![1, 4, HIDDEN]); + + for bad in [0, LAYERS + 1] { + let err = + Qwen3TextEncoder::load_first_layers(dir.path(), bad, mlxcel_core::dtype::BFLOAT16) + .err() + .expect("an out-of-range depth is an error") + .to_string(); + assert!(err.contains("outside"), "{err}"); + } +} diff --git a/src/imagegen/registry.rs b/src/imagegen/registry.rs index d184b0333..161f80c69 100644 --- a/src/imagegen/registry.rs +++ b/src/imagegen/registry.rs @@ -49,6 +49,10 @@ pub static FAMILIES: &[ImageFamily] = &[ name: "flux2", load: super::flux2::load, }, + ImageFamily { + name: "flux3", + load: super::flux3::load, + }, ImageFamily { name: "z_image", load: super::z_image::load, diff --git a/src/imagegen/testing.rs b/src/imagegen/testing.rs index a8d113c08..26232b7cc 100644 --- a/src/imagegen/testing.rs +++ b/src/imagegen/testing.rs @@ -247,7 +247,7 @@ pub(crate) fn values(a: &mlxcel_core::MlxArray) -> Vec { /// `||a - b|| / ||b||`. /// -/// Used by: the ERNIE-Image parity tests. +/// Used by: the ERNIE-Image and FLUX.3 parity tests. pub(crate) fn rel_rms(a: &[f32], b: &[f32]) -> f64 { assert_eq!(a.len(), b.len()); let num: f64 = a.iter().zip(b).map(|(x, y)| f64::from(x - y).powi(2)).sum(); @@ -257,7 +257,7 @@ pub(crate) fn rel_rms(a: &[f32], b: &[f32]) -> f64 { /// Peak signal-to-noise ratio of two 8-bit images, in dB. /// -/// Used by: the ERNIE-Image parity tests. +/// Used by: the ERNIE-Image and FLUX.3 parity tests. pub(crate) fn psnr(a: &[u8], b: &[u8]) -> f64 { assert_eq!(a.len(), b.len()); let mse = a @@ -287,7 +287,8 @@ pub(crate) fn fnv1a32_bytes(bytes: &[u8]) -> u32 { /// (`shift` 0 for f32, 16 for bf16 values widened to f32); `u32::MAX` when /// the signs differ, which no ulp bound should accept. /// -/// Used by: the Qwen-Image and Ming-Image parity tests. +/// Used by: the Qwen-Image and Ming-Image parity tests, and the FLUX.3 +/// pipeline tests through [`assert_noise_head`]. pub(crate) fn ulps(a: f32, b: f32, shift: u32) -> u32 { if a == b { return 0; @@ -308,7 +309,8 @@ pub(crate) fn ulps(a: f32, b: f32, shift: u32) -> u32 { /// or sampling order still shows in the head, which [`assert_noise_head`] /// gates to a few ulps everywhere. /// -/// Used by: the Qwen-Image and Ming-Image parity tests. +/// Used by: the Qwen-Image and Ming-Image parity tests, the FLUX.3 pipeline +/// tests. pub(crate) fn noise_checksum_is_exact() -> bool { use mlxcel_core::hardware::{GpuBackendKind, gpu_backend_kind}; matches!(gpu_backend_kind(), GpuBackendKind::Cuda) @@ -316,7 +318,8 @@ pub(crate) fn noise_checksum_is_exact() -> bool { /// `got` within `max_ulps` of `want`, element by element (see [`ulps`]). /// -/// Used by: the Qwen-Image and Ming-Image parity tests. +/// Used by: the Qwen-Image and Ming-Image parity tests, the FLUX.3 pipeline +/// tests. pub(crate) fn assert_noise_head(got: &[f32], want: &[f32], shift: u32, max_ulps: u32, label: &str) { assert_eq!(got.len(), want.len(), "{label}"); for (i, (g, w)) in got.iter().zip(want).enumerate() { diff --git a/src/imagegen/vae/mod.rs b/src/imagegen/vae/mod.rs index cf4ca6a82..b7ebac082 100644 --- a/src/imagegen/vae/mod.rs +++ b/src/imagegen/vae/mod.rs @@ -18,7 +18,7 @@ //! , //! loaded from `/vae/`. Tiled decode (`flux2/tiling.py`) is out of scope. //! -//! Used by: ErnieImage, LLaDAImage, ZImage, Ideogram4 (and FLUX.2 itself). The conv and +//! Used by: ErnieImage, LLaDAImage, ZImage, Ideogram4, Flux3 (and FLUX.2 itself). The conv and //! group-norm layers and the conv-layout probe are also used by MageFlow. mod config; diff --git a/src/imagegen/vae/model.rs b/src/imagegen/vae/model.rs index f82e75c6e..4c6754e26 100644 --- a/src/imagegen/vae/model.rs +++ b/src/imagegen/vae/model.rs @@ -438,7 +438,7 @@ impl Flux2Vae { /// normalization of patchified latents `[B, 4C, H, W]` and unpatchify them /// to `[B, C, 2H, 2W]`, ready for [`Self::decode`] (whole or tiled). /// - /// Used by: Flux2, Bonsai (tiled decode), and `decode_packed_latents`. + /// Used by: Flux2, Bonsai (tiled decode), Flux3, and `decode_packed_latents`. pub fn denormalize_packed_latents(&self, packed: &MlxArray) -> Result> { let packed = squeeze_frames(packed)?; let (mean, std) = self.bn_mean_std()?; @@ -449,7 +449,7 @@ impl Flux2Vae { /// Upstream `_bn_normalize_vae_encoded_latents`: `(x - mean) / std` on /// patchified encoder latents, with the statistics cast to `x`'s dtype. /// - /// Used by: Flux2 (edit reference latents), Bonsai, ErnieImage. + /// Used by: Flux2 (edit reference latents), Bonsai, ErnieImage, Flux3. pub fn bn_normalize(&self, latents: &MlxArray) -> Result> { let (mean, std) = self.bn_mean_std()?; let dt = mlxcel_core::array_dtype(latents); diff --git a/src/lib/mlxcel-core/src/layers.rs b/src/lib/mlxcel-core/src/layers.rs index 2960d48a7..5ef5a3cfe 100644 --- a/src/lib/mlxcel-core/src/layers.rs +++ b/src/lib/mlxcel-core/src/layers.rs @@ -5790,11 +5790,13 @@ pub fn metal4_causal_attention( /// (`mla/decode.rs`, `mla/prefill.rs`), `prefill_sdpa.rs`, `window_sdpa.rs`, /// the image-generation blocks, the encoder-only models (BERT, ModernBERT, /// EmbeddingGemma2, MistralContrastive), Gemma4, LLaDA2-MoE, Qwen3-Next, Qwen4-Exp, and several -/// vision encoders and detectors. +/// vision encoders and detectors. Qwen3 calls it directly only from its +/// cache-free explicit-position path (`Attention::forward_at_positions`, the +/// FLUX.3 text conditioner); its generation path goes through `cache.attend`. /// -/// Not used by Llama3, Qwen3, Gemma2 or Gemma3 directly: the first, second -/// and fourth call `cache.attend`, and Gemma2 calls [`attention_from_ptr`] and -/// `causal_attention`. A change here still reaches all four. +/// Not used by Llama3, Gemma2 or Gemma3 directly: the first and third call +/// `cache.attend`, and Gemma2 calls [`attention_from_ptr`] and +/// `causal_attention`. A change here still reaches all three. /// /// The direct caller set is too large to enumerate by name without going /// stale, so the groups above are a summary. Regenerate the exact list with diff --git a/src/models/qwen3.rs b/src/models/qwen3.rs index 588598c8b..6955b3543 100644 --- a/src/models/qwen3.rs +++ b/src/models/qwen3.rs @@ -362,6 +362,53 @@ impl Attention { self.o_proj.forward(&attn_out) } + /// One-shot attention over the whole sequence at explicit positions, with + /// no KV cache: `cos` and `sin` are `[B, 1, T, head_dim]` rotate-half + /// tables in the activation dtype (see + /// [`Qwen3TextEncoder::hidden_states_at`](crate::imagegen::Qwen3TextEncoder::hidden_states_at)), + /// applied as `q * cos + rotate_half(q) * sin` in that dtype, which is how + /// mlx-vlm's Qwen3-VL language model applies a position table. `mask` is + /// an additive `[B, 1, T, T]` bias. The tables replace this layer's own + /// RoPE settings: `rope_freqs` and `rope_mscale` are not applied, so a + /// caller with a scaled RoPE builds them into the tables. + /// + /// Used by: `TransformerBlock::forward_at_positions` (image-generation + /// text conditioners whose padded tokens sit at chosen positions). + pub fn forward_at_positions( + &self, + x: &MlxArray, + cos: &MlxArray, + sin: &MlxArray, + mask: Option<&MlxArray>, + ) -> UniquePtr { + let shape = mlxcel_core::array_shape(x); + let (b, l) = (shape[0], shape[1]); + let (q, k, v) = self.qkv_proj.forward(x); + let q = mlxcel_core::reshape(&q, &[b, l, self.num_heads, self.head_dim]); + let k = mlxcel_core::reshape(&k, &[b, l, self.num_kv_heads, self.head_dim]); + let v = mlxcel_core::reshape(&v, &[b, l, self.num_kv_heads, self.head_dim]); + let q = mlxcel_core::transpose_axes(&self.q_norm.forward(&q), &[0, 2, 1, 3]); + let k = mlxcel_core::transpose_axes(&self.k_norm.forward(&k), &[0, 2, 1, 3]); + let v = mlxcel_core::transpose_axes(&v, &[0, 2, 1, 3]); + let rotate = |t: &MlxArray| { + let half = self.head_dim / 2; + let s = mlxcel_core::array_shape(t); + let x1 = mlxcel_core::slice(t, &[0, 0, 0, 0], &[s[0], s[1], s[2], half]); + let x2 = mlxcel_core::slice(t, &[0, 0, 0, half], &[s[0], s[1], s[2], s[3]]); + let rotated = mlxcel_core::concatenate(&mlxcel_core::negative(&x2), &x1, -1); + mlxcel_core::add( + &mlxcel_core::multiply(t, cos), + &mlxcel_core::multiply(&rotated, sin), + ) + }; + let (q, k) = (rotate(&q), rotate(&k)); + let mask = mask.map(|m| mlxcel_core::astype(m, mlxcel_core::array_dtype(&q))); + let out = mlxcel_core::layers::attention(&q, &k, &v, self.scale, mask.as_deref(), 0.0, 0); + let out = mlxcel_core::transpose_axes(&out, &[0, 2, 1, 3]); + let out = mlxcel_core::reshape(&out, &[b, l, self.num_heads * self.head_dim]); + self.o_proj.forward(&out) + } + pub fn from_weights( weights: &WeightMap, args: &ModelArgs, @@ -520,6 +567,25 @@ impl TransformerBlock { mlxcel_core::add(&h, &ff_out) } + /// [`Self::forward`] with the attention at explicit positions and no KV + /// cache; see [`Attention::forward_at_positions`]. + /// + /// Used by: `imagegen::Qwen3TextEncoder::hidden_states_at` (FLUX.3). + pub fn forward_at_positions( + &self, + x: &MlxArray, + cos: &MlxArray, + sin: &MlxArray, + mask: Option<&MlxArray>, + ) -> UniquePtr { + let normed = self.input_layernorm.forward(x); + let attn_out = self.self_attn.forward_at_positions(&normed, cos, sin, mask); + let h = mlxcel_core::add(x, &attn_out); + let normed = self.post_attention_layernorm.forward(&h); + let ff_out = self.mlp.forward(&normed); + mlxcel_core::add(&h, &ff_out) + } + /// Batched forward: batch norms + projections + FFN, per-sequence attention. /// /// `x` has shape `[B, T, hidden_dim]`, `caches[i]` is the KVCache for diff --git a/src/models/registry.rs b/src/models/registry.rs index c2fa139a9..e311228e2 100644 --- a/src/models/registry.rs +++ b/src/models/registry.rs @@ -478,6 +478,26 @@ const STANDALONE_ARCHITECTURE_FAMILIES: &[StandaloneArchitectureFamily] = &[ drafters: NO_DRAFTERS, kv_modes: KV_FP16, }, + // Checked against mlx-vlm on CUDA (GB10) only, so Metal is partial. + StandaloneArchitectureFamily { + id: "flux3", + display_name: "FLUX.3 Image Klein", + category: "image generation", + model_types: &["flux3"], + aliases: &["flux3-klein", "flux3-klein-base", "flux-3-image-klein"], + runtimes: IMAGE_GENERATE, + modalities_in: TEXT_IMAGE, + output: OutputKind::Image, + backends: BackendSupport { + metal: BackendStatus::Partial, + cuda: BackendStatus::Supported, + rocm: ROCM_FIRST_PASS, + }, + tensor_parallel: false, + pipeline_parallel: false, + drafters: NO_DRAFTERS, + kv_modes: KV_FP16, + }, StandaloneArchitectureFamily { id: "z_image", display_name: "Z-Image", diff --git a/tests/fixtures/flux3/generate_flux3_oracle.py b/tests/fixtures/flux3/generate_flux3_oracle.py new file mode 100644 index 000000000..3b73d1dcb --- /dev/null +++ b/tests/fixtures/flux3/generate_flux3_oracle.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# Copyright 2025-2026 Lablup Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Write the upstream oracle the ignored FLUX.3 parity tests read. + +Runs mlx-vlm's ``Flux3Image`` (``upsample_prompt=False``) on a local package +and writes, into ``OUT``: + +- ``tokens.json``: token ids and masks of the test prompts; +- ``teapot_features.safetensors`` / ``edit_features.safetensors``: upstream's + text features (bf16 bits as uint16) and text ids; +- ``noise_512_seed42.safetensors``: the initial noise of a 512x512 image; +- ``step0.safetensors``: the first step's velocity on that noise and the + teapot features, with ``t`` and the target time; +- ``teapot_512.png``: the 16-step 512x512 Klein image, seed 42; +- ``edit_512.png`` and ``edit_reference_tokens.safetensors``: the edit of + that image ("Make the teapot cobalt blue", seed 42) and its encoded + reference; +- ``base_512.png`` when ``--base`` names a base package. + +Usage: + + python generate_flux3_oracle.py MODEL_DIR OUT [--base BASE_DIR] +""" + +import argparse +import json +from pathlib import Path + +import mlx.core as mx +import numpy as np +from PIL import Image + +from mlx_vlm.models.flux3.pipeline import Flux3Image, image_ids, timesteps + +TEAPOT = "A studio photograph of a red ceramic teapot" +EDIT = "Make the teapot cobalt blue" + + +def bf16_bits(a): + return np.array(a.astype(mx.bfloat16).view(mx.uint16)) + + +def save(path, **arrays): + mx.save_safetensors(str(path), {k: mx.array(v) for k, v in arrays.items()}) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("model") + parser.add_argument("out") + parser.add_argument("--base") + args = parser.parse_args() + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + + pipe = Flux3Image(args.model, upsample_prompt=False) + tokens = {} + for name, prompt in (("teapot", TEAPOT), ("edit", EDIT), ("empty", "")): + ids, mask = pipe.tokenizer.tokenize(prompt) + tokens[name] = { + "input_ids": np.array(ids)[0].tolist(), + "attention_mask": np.array(mask)[0].tolist(), + } + (out / "tokens.json").write_text(json.dumps(tokens)) + + for name, prompt in (("teapot", TEAPOT), ("edit", EDIT)): + embeds, ids = pipe._encode_prompt(prompt) + save( + out / f"{name}_features.safetensors", + embeds_bf16_bits=bf16_bits(embeds), + text_ids=np.array(ids).astype(np.int32), + ) + + noise = ( + mx.random.normal((1, 32 * 32, 128), key=mx.random.key(42)) + .astype(mx.bfloat16) + .astype(mx.float32) + ) + save(out / "noise_512_seed42.safetensors", noise=np.array(noise)) + + from mlx_vlm.models.flux3.weights import load_transformer, load_vae + + pipe.transformer = load_transformer(pipe.model_path, pipe.config) + pipe.vae = load_vae(pipe.model_path) + embeds, text_ids = pipe._encode_prompt(TEAPOT) + schedule = timesteps(16, pipe.config.alpha).tolist() + velocity = pipe.transformer( + {"image": noise, "text": embeds}, + {"image": image_ids(512, 512), "text": text_ids}, + schedule[0], + target_timestep=schedule[1], + ) + save( + out / "step0.safetensors", + velocity=np.array(velocity.astype(mx.float32)), + t=np.array([schedule[0], schedule[1]], dtype=np.float32), + ) + + teapot = pipe.generate(TEAPOT, seed=42, width=512, height=512) + teapot.save(out / "teapot_512.png") + + with Image.open(out / "teapot_512.png") as reference: + pixels = mx.array(np.asarray(reference.convert("RGB")).astype(np.float32) / 127.5 - 1) + save( + out / "edit_reference_tokens.safetensors", + tokens=np.array(pipe.vae.encode(pixels[None]).astype(mx.float32)), + ) + edited = pipe.edit(EDIT, [str(out / "teapot_512.png")], seed=42) + edited.save(out / "edit_512.png") + + if args.base: + pipe = None + mx.clear_cache() + base = Flux3Image(args.base, upsample_prompt=False) + image = base.generate(TEAPOT, seed=42, width=512, height=512) + image.save(out / "base_512.png") + + +if __name__ == "__main__": + main() diff --git a/tests/fixtures/flux3/generate_flux3_unit_fixtures.py b/tests/fixtures/flux3/generate_flux3_unit_fixtures.py new file mode 100644 index 000000000..b2496e773 --- /dev/null +++ b/tests/fixtures/flux3/generate_flux3_unit_fixtures.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +# Copyright 2025-2026 Lablup Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Print the upstream values the FLUX.3 unit tests embed. + +Runs mlx-vlm's own FLUX.3 code (``mlx_vlm.models.flux3``) on inputs both sides +can build without a checkpoint: + +- ``timesteps(16, 6.93)``; +- the first values and the sum of ``normal((1, 16, 128), key(42))`` rounded + through bf16 (the initial noise of a 64x64 image, seed 42); +- the tiny random transformer (2 early and 2 single blocks, hidden 32) in f32, + with every weight ``w[i] = ((i * 7919 + k * 104729) % 2001 - 1000) / 1000 * + 0.05`` for the ``k``-th tensor in sorted key order, on three cases: text + only and text plus one reference on a flow map, and text only without one; +- ``prepare_reference`` sizes, crops and a pixel checksum for synthetic + references. + +Usage (mlx-vlm checkout on PYTHONPATH): + + python tests/fixtures/flux3/generate_flux3_unit_fixtures.py +""" + +import json +import math + +import mlx.core as mx +import numpy as np +from mlx.utils import tree_flatten +from PIL import Image + +from mlx_vlm.models.flux2.latent import prepare_grid_ids # noqa: F401 +from mlx_vlm.models.flux2.prompt import prepare_text_ids +from mlx_vlm.models.flux3.config import Flux3Config +from mlx_vlm.models.flux3.pipeline import image_ids, prepare_reference, timesteps +from mlx_vlm.models.flux3.transformer import Flux3Transformer + +TINY = dict( + hidden=32, + heads=2, + depth=2, + depth_single=2, + mlp_ratio=3.0, + axes_dim=(4, 4, 4, 4), + theta=10000, + in_channels={"image": 8, "image_cond": 8, "text": 12}, + image_rope_scale=0.5, +) + + +def formula(count, k, scale=0.05): + i = np.arange(count, dtype=np.int64) + return (((i * 7919 + k * 104729) % 2001 - 1000) / 1000 * scale).astype(np.float32) + + +def tiny_model(flow_map): + model = Flux3Transformer(Flux3Config(**TINY, flow_map=flow_map)) + params = dict(tree_flatten(model.parameters())) + weights = [] + for k, name in enumerate(sorted(_bfl_name(n) for n in params)): + shape = params[_module_name(name)].shape + weights.append( + (_module_name(name), mx.array(formula(math.prod(shape), k).reshape(shape))) + ) + model.load_weights(weights, strict=True) + return model + + +def _bfl_name(name): + return name.replace("adaLN_modulation.layers.1.", "adaLN_modulation.1.") + + +def _module_name(name): + return name.replace("adaLN_modulation.1.", "adaLN_modulation.layers.1.") + + +def tokens(shape, k): + return mx.array(formula(math.prod(shape), k, scale=1.0).reshape(shape)) + + +def tiny_cases(): + out = {} + text = tokens((1, 5, 12), 1001) + text_ids = prepare_text_ids(text) + image = tokens((1, 6, 8), 1002) + ids_image = image_ids(32, 48) + cond = tokens((1, 4, 8), 1003) + ids_cond = image_ids(32, 32, reference=0) + flow = tiny_model(True) + base = tiny_model(False) + out["text_only"] = flow( + {"image": image, "text": text}, + {"image": ids_image, "text": text_ids}, + 0.7, + target_timestep=0.55, + ) + out["with_reference"] = flow( + {"image": image, "image_cond": cond, "text": text}, + {"image": ids_image, "image_cond": ids_cond, "text": text_ids}, + 0.7, + target_timestep=0.55, + ) + out["base_text_only"] = base( + {"image": image, "text": text}, + {"image": ids_image, "text": text_ids}, + 0.7, + ) + return {k: np.array(v.astype(mx.float32)).reshape(-1).tolist() for k, v in out.items()} + + +def references(): + out = [] + for w, h in [(512, 512), (20, 18), (10, 7), (1000, 750), (5000, 100), (3000, 2000)]: + x, y = np.meshgrid(np.arange(w), np.arange(h)) + rgb = np.stack([(x * 7 + y * 13) % 256, (x * 3 + y * 5) % 256, (x + y) % 256], -1) + image = Image.fromarray(rgb.astype(np.uint8)) + single, crop = prepare_reference(image) + multi, _ = prepare_reference(image, multi=True) + arr = np.asarray(single).astype(np.int64) + weights = (np.arange(arr.size, dtype=np.int64) % 9973).reshape(arr.shape) + out.append( + dict( + size=(w, h), + single=single.size, + crop=crop, + multi=multi.size, + checksum=int((arr * weights).sum()) if w * h <= 1024 * 1024 else None, + ) + ) + return out + + +def main(): + noise = ( + mx.random.normal((1, 16, 128), key=mx.random.key(42)) + .astype(mx.bfloat16) + .astype(mx.float32) + ) + noise = np.array(noise).reshape(-1) + print( + json.dumps( + dict( + timesteps=timesteps(16, 6.93).tolist(), + noise_head=noise[:8].tolist(), + noise_sum=float(noise.astype(np.float64).sum()), + tiny=tiny_cases(), + references=references(), + ) + ) + ) + + +if __name__ == "__main__": + main()