Skip to content

feat(imagegen): port Prism Bonsai ternary FLUX.2 Klein (bonsai) - #2667

Merged
inureyes merged 9 commits into
mainfrom
feature/issue-2428-bonsai-ternary
Oct 27, 2026
Merged

inureyes merged 9 commits into
mainfrom
feature/issue-2428-bonsai-ternary

Conversation

@inureyes

@inureyes inureyes commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the bonsai image-generation family for 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. It runs through mlxcel generate-image, mlxcel-server --image-model (/v1/images/generations) and is listed by mlxcel arch --json (image_generate, output image). Generation only.

  • Loader. src/imagegen/bonsai/ reads transformer-packed-mflux/quantization_config.json. format must be mlx-packed-affine, and bits and group_size must be in mlxcel-core's affine sets; a bad value is rejected by name (the 1-bit binary variant fails on bits (1)). Listed modules load as affine UnifiedLinear (2-bit, group 128, bf16 scales and biases as stored) and everything else loads dense. A listed module without .scales fails, and so does an unlisted module with .scales. Every packed layer also passes mlxcel-core's validate_quantized_packing at load, so mismatched weight/scales/biases shapes fail with an error instead of aborting the server on the first forward pass.
  • Pipeline reuse. Flux2Pipeline::with_linear_source injects the Bonsai LinearSource and turns off prompt bucketing (upstream bucketed_seq_len=False). LinearSource::check_weights is a default-accepting hook that Flux2Transformer::load calls. FLUX.2 construction is unchanged, and its parity tests reproduce feat(imagegen): port FLUX.2 Klein text-to-image and editing #2660's numbers exactly.
  • n > 1. Runs image by image with seed seed + i, which is how upstream's server loops for Bonsai.
  • Probe. The manifest rule was already on main from feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341, covered by bonsai_manifest_beats_the_flux2_class_name and partial_bonsai_manifest_falls_back_to_the_class_name. This PR adds flux2_klein_index_without_a_manifest_is_flux2 for the no-manifest case, plus the registration in FAMILIES and STANDALONE_ARCHITECTURE_FAMILIES.

Deviation: the VAE. Upstream Bonsai ignores the checkpoint's vae/ and downloads black-forest-labs/FLUX.2-small-decoder at load time, which is a different decoder with channels 96/192/384/384. This port uses the checkpoint's own vae/, as the issue specifies, and fetches no second repository. The parity fixtures decode with vae/ in both arms. Measured against upstream as shipped (small decoder), the result is 29.82 dB; the two decoders differ by 34.96 dB from each other.

Parity (CUDA oracle)

Oracle: mlx-vlm 0.7.8 at git 73d366ec, mlx 0.32.4, CUDA on GB10, MLX_ENABLE_TF32=0. The case is "A tiny glass bonsai tree on a moonlit desk" at 512x512, 4 steps, seed 9909. tests/fixtures/bonsai/generate_bonsai_fixtures.py runs upstream's own BonsaiImage pipeline, with the Metal-only fused norm-RoPE kernels replaced by their arithmetic (f32 RMSNorm times the gain, interleaved-pair RoPE, cast to bf16). --flux2-transformer loads Bonsai's weights into upstream's FLUX.2 transformer for the f32 check. That check dequantizes the weights, because mlx 0.32.4 CUDA fails f32 2-bit quantized_matmul with M > 1. Committed fixtures total 1.45 MB.

Check Result
Initial noise bit-identical
f32 transformer vs upstream f32, same inputs rel RMS 1.19e-6
One bf16 step on upstream's exact step-0 inputs rel RMS 8.1e-3
VAE decoding upstream's final latents 57.61 dB
End-to-end PNG 31.18 dB
Recorded drift: final latents / prompt embeds 1.0e-1 / 2.3e-2

Following the orchestrator's revised gate, the tests assert PSNR >= 30 dB, bit-identical noise, a 0.2 latent bound (a wrong port scores about 1.4) and 0.1 on the embeddings. The drift is bf16 rounding, not a port error. Upstream's bf16 4-bit conditioner is 1.95e-2 from its own f32 run, and this port is 1.74e-2 from that f32 run, with the same growth along the 448 padding rows. Upstream also disagrees with itself by 3.5e-2 in the final latents when its FLUX.2 transformer replaces klein_fast on the same weights.

The megakernel cannot be run against quantized_matmul here because it is Metal-only. By code reading, QuantizedLinearKernel calls mx.quantized_matmul, and the fused kernels compute the arithmetic described above.

Precision. The transformer is bf16. The VAE and the text encoder follow FLUX.2's policy. Under MLXCEL_CUDA_F16_NORMALIZE=1 the case gives 31.21 dB.

Real checkpoint (GB10)

Run Result PNG
CLI acceptance command 512x512, 11.5 s wall including load, 3.6 GB RSS, 31.18 dB A leafy green bonsai in a dark pot with a glass bulb at the trunk, on a wooden desk in blue moonlight with books at the edges.
Server, same request 200, pixel-identical to the CLI (PSNR inf) Same image.
Server n=2, 256x256, seed 5 seeds 5 and 6, distinct images (10.3 dB apart) A small bonsai under a desk lamp, in two compositions.
Server 4096x512, 520x512, max_sequence_length: 0 400 with the range, multiple-of-16, or option message
CLI --task edit image model family bonsai does not support task "edit"

Changes during review

  • Merged origin/main twice: Z-Image (feat(imagegen): port Z-Image text-to-image and img2img #2662) conflicted in both registries and both docs pages; every main row was kept and Bonsai appended (FAMILIES is now flux2, z_image, bonsai).
  • Security: packed layers are now shape-validated with validate_quantized_packing (three malformed-checkpoint rejection tests added). Open MEDIUM, shared with FLUX.2 and out of scope: a checkpoint whose tensors agree with each other but were packed for a different hidden_size than config.json still fails on the first forward pass; fixing it needs the expected input width passed through LinearSource::load.
  • Removed the unused PackedLinears::config(); pinned the default LinearSource::check_weights with a unit test.
  • docs/supported-models.md now gives both the 31.18 dB (vae/ on both sides) and 29.82 dB (upstream as shipped) figures.

Test plan

  • imagegen:: lib-test filter (220 pass, 15 ignored, includes the bonsai unit tests); models::registry passes 16. Removing the FAMILIES row fails bonsai_is_registered_in_both_tables and a_bonsai_checkpoint_resolves_to_the_bonsai_loader. The loader and config tests do not exist on main.
  • bonsai::parity --ignored 5/5 and flux2::parity --ignored 6/6 on the real checkpoints, MLX_ENABLE_TF32=0.
  • clippy (--lib --bins --tests --no-deps -D warnings), cargo fmt --check, and make verify-env-var-docs pass. The two test-only variables are allowlisted.
  • Not verifiable here: Metal runs, and the megakernel against quantized_matmul.

Closes #2428

Prism Bonsai (prism-ml/bonsai-image-ternary-4B-mlx-2bit) is FLUX.2 Klein 4B with its transformer linears packed as 2-bit MLX affine weights and a 4-bit MLX Qwen3 conditioner. The probe already classifies it as `bonsai` from manifest.json; this adds the family that loads it.

src/imagegen/bonsai/ reads transformer-packed-mflux/quantization_config.json (format mlx-packed-affine, bits and group_size checked against mlxcel-core's affine sets) and supplies a LinearSource that loads the listed modules as affine UnifiedLinears and everything else dense, erroring when the file and the list disagree. Generation reuses the FLUX.2 pipeline through a new Flux2Pipeline::with_linear_source constructor, with prompts padded to max_sequence_length as upstream's bucketed_seq_len=False does; FLUX.2's own construction is unchanged. n images run one at a time with seed + i. The family is registered in imagegen::FAMILIES and mlxcel arch.

Refs #2428
The fixture script runs upstream's own Bonsai pipeline on mlx 0.32.4 CUDA with the Metal-only fused norm-RoPE kernels replaced by their arithmetic and the checkpoint vae/ as decoder, and builds upstream's FLUX.2 transformer with Bonsai's packed weights for an f32 check. The ignored tests measure on the real checkpoint: bit-identical noise, f32 transformer within 1.19e-6, one bf16 step within 8.1e-3, VAE-only 57.61 dB, end to end 31.18 dB. Final latents drift 1.0e-1 and prompt embeddings 2.3e-2; upstream's bf16 conditioner is 1.95e-2 from its f32 run and upstream disagrees with itself by 3.5e-2 across its two transformers, so those are sanity bounds.

The FLUX.2 parity helpers are shared rather than copied, and the loader's per-module checks are folded into one pass. docs/image-generation.md gains a Bonsai section, including why the checkpoint VAE is used instead of upstream's downloaded small decoder.

Refs #2428
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:low Low priority area:models Model architectures, weights, loading, metadata labels Oct 27, 2026
The Bonsai probe acceptance names three cases; the existing tests covered the matching and partial manifests but not a Flux2KleinPipeline index with no manifest.json at all, which takes a different branch in the probe.

Refs #2428
@inureyes inureyes added modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:vlm Vision-language model labels Oct 27, 2026
Z-Image (#2662) landed on main and conflicted with the Bonsai rows in the four files both units edit. The resolution keeps every main row and appends Bonsai after it: `FAMILIES` and `STANDALONE_ARCHITECTURE_FAMILIES` are flux2, z_image, bonsai; docs/image-generation.md lists the three families and gains a `bonsai` row in main's family table; docs/supported-models.md keeps both bullets.

The Bonsai bullet in supported-models.md now says the 31.18 dB uses the checkpoint `vae/` on both sides and gives the 29.82 dB against upstream as shipped (which downloads FLUX.2-small-decoder at load), matching the PR body and the Bonsai section.

Refs #2428
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Run prism-ml/bonsai-image-ternary-4B-mlx-2bit (family bonsai) through the FLUX.2 pipeline with a packed 2-bit affine transformer, generate only, via CLI, server and mlxcel arch.

Findings Addressed

  • Branch conflicted with main after Z-Image (feat(imagegen): port Z-Image text-to-image and img2img #2662) in src/imagegen/registry.rs, src/models/registry.rs and both docs (HIGH). Merged origin/main in 210e46e: main's rows kept, Bonsai appended (flux2, z_image, bonsai); main's family table gains a bonsai row. PR is MERGEABLE again.
  • docs/supported-models.md quoted 31.18 dB "against upstream mlx-vlm" without saying the oracle used the checkpoint vae/ (MEDIUM, fixed in the same commit). It now gives 29.82 dB against upstream as shipped next to it, matching the PR body and the Bonsai section.

Reviewed, no change

  • Loader vs klein_fast/loader.py: upstream treats any linear with sibling .scales as packed and ignores quantized_modules/skip_patterns; the port makes the list authoritative and checks the file against it both ways. On the real checkpoint the 100 .scales modules equal quantized_modules, all weights are uint32, scales and biases are bf16 (upstream casts to bf16; prepare_transformer_weights does the same cast, a no-op here). skip_patterns is implied by the list.
  • VAE: using the checkpoint vae/ instead of upstream's load-time hf_hub_download of FLUX.2-small-decoder is the right call (the issue names vae/, and a download at load is not acceptable). It is disclosed in the PR body, the module doc and both docs pages. An optional local small-decoder path is a possible follow-up.
  • FLUX.2 seam: new delegates to with_linear_source(AffineLinears, bucketed=true), check_weights defaults to accept, transformer_quant had no other reader. flux2::parity --ignored reproduces feat(imagegen): port FLUX.2 Klein text-to-image and editing #2660's numbers on the merged tree.
  • Seeds: upstream's server loops base_seed + index; docs say seed + i with FLUX.2 generation as the documented exception.
  • Fixtures 1.45 MB with the generator script and oracle provenance; step-0 inputs kept out of the repo.
  • LOW, left: PackedLinears::config() has no caller.

Verification (merged tree 210e46e, GB10 CUDA, MLX_ENABLE_TF32=0)

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: models::registry 16/16, imagegen:: 216 pass (15 ignored), bonsai::parity --ignored 5/5 (31.18 dB, f32 1.19e-6, step-0 8.1e-3, VAE 57.61 dB), flux2::parity --ignored 6/6 (32.27 / 40.54 dB, f32 bit-identical), clippy -D warnings, cargo fmt --check, env-var docs check.

A listed packed module was loaded through UnifiedLinear::from_weights_with_mode, which reconciles only the last axes of weight and scales and checks only that .biases exists. A checkpoint whose .biases differ in shape from .scales, whose weight and scales disagree on a leading axis, or whose scales are 1-D loaded cleanly and then tripped MLX validate_quantized_input at the first forward pass, which crosses the cxx bridge as an uncatchable std::terminate and aborts the server on its first request.

load_linear now runs the shared validate_quantized_packing check on every packed layer after the existing bits/group_size comparison, with the input width taken from the scales since this seam has no config width. The rank, leading-axis, packed-width and biases-shape predicates are MLX's own, and the error names the module.

Three new loader tests cover biases shaped unlike scales, a leading-axis mismatch, and 1-D scales; all three fail with the check disabled. The imagegen::bonsai:: filter passes (15 passed, 5 ignored real-checkpoint parity tests), clippy with -D warnings is clean.
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Scope: what this PR adds on top of the FLUX.2 base (#2660): the packed loader, quantization_config.json, the Bonsai request path, and the with_linear_source / check_weights seam.

Fixed

  • HIGH, src/imagegen/bonsai/loader.rs (6e9fead): a listed packed module only had its last axes reconciled and the presence of .biases checked. Three kinds of checkpoint loaded cleanly and then failed MLX validate_quantized_input at the first forward pass: .biases shaped unlike .scales, weight and scales that disagree on a leading axis, and 1-D scales. That failure is an uncatchable std::terminate across the cxx bridge, so it kills mlxcel-server on its first request. load_linear now runs the shared validate_quantized_packing check on every packed layer. Three new loader tests cover these cases, and all three fail when the check is disabled.

Checked, no change needed

  • quantization_config.json: format is pinned. bits and group_size go through the core affine validators. The declared bits and group size must match what the tensor shapes reconcile to. check_weights requires uint32 weights and .scales/.biases for every listed module, and it rejects unlisted .scales. Indexing into raw only happens after a contains_key check.
  • Paths: the component directories are fixed names joined to the operator-supplied root. manifest.json paths are used only for probe set membership and are never opened.
  • Request path: n is limited to 1..=10 and max_sequence_length to 1..=512 (shared validation). Images run one at a time with seed + i, so peak memory equals a single image. Prompt embeddings are cached, so the text encoder is not reloaded for n > 1. Ten 4-step 1024x1024 images fit well within the 900 s worker timeout.
  • FLUX.2 seam: linear_source is used only in ensure_transformer_and_vae, at load time. The default check_weights is a no-op that runs once per load. FLUX.2 still buckets prompts. The forward path has not changed.
  • Error text: the new Bonsai errors name modules and the config file name, not paths. Errors that do contain paths (layout, from_dir) are raised at startup. The lazy transformer load and the text-encoder reload carry the same path-bearing 500 text already recorded in feat(imagegen): port FLUX.2 Klein text-to-image and editing #2660.

Remaining (shared, out of scope)

  • MEDIUM: a checkpoint whose tensors are consistent with each other but packed for a different hidden_size than config.json declares will still abort at the first forward pass. This affects FLUX.2 dense and quantized checkpoints as well as Bonsai, because LinearSource::load does not receive the expected input width. Fixing it needs the transformer to pass widths through the seam.

Verification

imagegen::bonsai:: under gpu-lock: 15 passed, 0 failed, 5 ignored (the ignored tests are real-checkpoint parity). Clippy with -D warnings and fmt are clean. This was a validation-only change, so the bonsai and flux2 parity --ignored runs were not repeated.

…he drift policy

Add a unit test that the default check_weights (AffineLinears) accepts any checkpoint, so Flux2 loading is unaffected by the Bonsai override hook. Note in docs/image-generation.md that the relative RMS figures are reported as non-blocking drift under the epic-wide criterion.

Validation: imagegen:: 220 passed, models::registry 16 passed, bonsai::parity 5 passed, flux2::parity 6 passed (MLX_ENABLE_TF32=0, GB10); fmt, clippy -D warnings and verify-env-var-docs clean.

Refs #2428
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 27, 2026
@inureyes
inureyes marked this pull request as ready for review October 27, 2026 07:11
@inureyes
inureyes merged commit 1c0f3ae into main Oct 27, 2026
30 of 31 checks passed
@inureyes
inureyes deleted the feature/issue-2428-bonsai-ternary branch October 27, 2026 07:11
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata modelsize:small 4-bit checkpoint <= 10GB; fast iteration, safe for smoke tests modeltype:vlm Vision-language model priority:low Low priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Port Prism Bonsai (bonsai) ternary 2-bit FLUX.2 text-to-image

1 participant