Repository navigation
feat(imagegen): port Prism Bonsai ternary FLUX.2 Klein (bonsai) - #2667
Merged
Merged
Conversation
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
6 tasks done
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
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
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Reviewed, no change
Verification (merged tree 210e46e, GB10 CUDA,
|
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.
Member
Author
Security and performance reviewScope: what this PR adds on top of the FLUX.2 base (#2660): the packed loader, Fixed
Checked, no change needed
Remaining (shared, out of scope)
Verification
|
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds the
bonsaiimage-generation family forprism-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 throughmlxcel generate-image,mlxcel-server --image-model(/v1/images/generations) and is listed bymlxcel arch --json(image_generate, outputimage). Generation only.src/imagegen/bonsai/readstransformer-packed-mflux/quantization_config.json.formatmust bemlx-packed-affine, andbitsandgroup_sizemust be in mlxcel-core's affine sets; a bad value is rejected by name (the 1-bit binary variant fails onbits (1)). Listed modules load as affineUnifiedLinear(2-bit, group 128, bf16 scales and biases as stored) and everything else loads dense. A listed module without.scalesfails, and so does an unlisted module with.scales. Every packed layer also passes mlxcel-core'svalidate_quantized_packingat load, so mismatched weight/scales/biases shapes fail with an error instead of aborting the server on the first forward pass.Flux2Pipeline::with_linear_sourceinjects the BonsaiLinearSourceand turns off prompt bucketing (upstreambucketed_seq_len=False).LinearSource::check_weightsis a default-accepting hook thatFlux2Transformer::loadcalls. 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 seedseed + i, which is how upstream's server loops for Bonsai.bonsai_manifest_beats_the_flux2_class_nameandpartial_bonsai_manifest_falls_back_to_the_class_name. This PR addsflux2_klein_index_without_a_manifest_is_flux2for the no-manifest case, plus the registration inFAMILIESandSTANDALONE_ARCHITECTURE_FAMILIES.Deviation: the VAE. Upstream Bonsai ignores the checkpoint's
vae/and downloadsblack-forest-labs/FLUX.2-small-decoderat load time, which is a different decoder with channels 96/192/384/384. This port uses the checkpoint's ownvae/, as the issue specifies, and fetches no second repository. The parity fixtures decode withvae/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.pyruns upstream's ownBonsaiImagepipeline, with the Metal-only fused norm-RoPE kernels replaced by their arithmetic (f32 RMSNorm times the gain, interleaved-pair RoPE, cast to bf16).--flux2-transformerloads 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-bitquantized_matmulwith M > 1. Committed fixtures total 1.45 MB.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_faston the same weights.The megakernel cannot be run against
quantized_matmulhere because it is Metal-only. By code reading,QuantizedLinearKernelcallsmx.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=1the case gives 31.21 dB.Real checkpoint (GB10)
n=2, 256x256, seed 54096x512,520x512,max_sequence_length: 0--task editimage model family bonsai does not support task "edit"Changes during review
FAMILIESis now flux2, z_image, bonsai).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 differenthidden_sizethanconfig.jsonstill fails on the first forward pass; fixing it needs the expected input width passed throughLinearSource::load.PackedLinears::config(); pinned the defaultLinearSource::check_weightswith a unit test.docs/supported-models.mdnow 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::registrypasses 16. Removing theFAMILIESrow failsbonsai_is_registered_in_both_tablesanda_bonsai_checkpoint_resolves_to_the_bonsai_loader. The loader and config tests do not exist on main.bonsai::parity --ignored5/5 andflux2::parity --ignored6/6 on the real checkpoints,MLX_ENABLE_TF32=0.--lib --bins --tests --no-deps -D warnings),cargo fmt --check, andmake verify-env-var-docspass. The two test-only variables are allowlisted.quantized_matmul.Closes #2428