feat(imagegen): add MiniMax-H3-Image (minimax_h3_image) generation and editing

Đang mở
#3,233 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
6/100
Loại issue
Tính năng
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
rust
Lĩnh vực
machine-learning

Hướng nghiên cứu

Start with the family detection in src/imagegen/probe.rs (IMAGE_FAMILIES at line 42, model_types_from_metadata at line 216) and the FAMILIES list in src/imagegen/registry.rs line 47, then read docs/vision-model-scope.md line 79. A first step is registering minimax_h3_image so the probe recognizes the checkpoint. Done means generate-image gets past detection, though the full runtime (conditioner, transformer, VAE) is a multi-week port.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

area:models modelsize:large modeltype:vlm priority:low status:ready type:enhancement

Summary

Add MiniMax-H3-Image (family minimax_h3_image) to the image generation runtime: text-to-image and editing with 1 to 16 ordered reference images, using a Qwen3-VL-32B conditioner, a 33B diffusion transformer with six step-specific output heads (distilled to exactly 6 steps at guidance 1), and a tiled ViT-decoder VAE, generating near 16 MP. Today mlxcel generate-image -m nativ-community/MiniMax-H3-Image-4bit fails because the probe does not know the family. docs/vision-model-scope.md:79 and #524 scoped out only the joint video and audio minimax_h3 release; the image-only release is a different, in-scope product for the existing image runtime, so this issue also corrects that scope record.

Upstream reference

Architecture (from upstream code and the published configs)

  • Detection: model_index.json _class_name: MiniMaxH3ImagePipeline (official) or model_type: minimax_h3_image with mlx_vlm_format: minimax_h3_image (MLX conversions).
  • Transformer (transformer_diffusers/config.json, _class_name MiniMaxH3ImageTransformer2DModel): num_attention_heads 56, attention_head_dim 128, hidden_size 5376, num_layers 50, num_refiner_layers 2, ffn_dim 14336, in_channels 24, patch_size [1, 2, 2] (patch dim 96), text_dim 5120, freq_dim 256, time_embed_hidden_dim 5376, time_embed_dim 2688, rope_freq_dim 16, rope_theta 10000, eps 1e-5 everywhere, num_pdd_heads 6 (must be 6 with a spatial patch, else a load error).
    • proj_in: 96 -> 5376; context_embedder: 5120 -> 5376 then the token_refiner (2 pre-norm blocks: RMSNorm, attention, RMSNorm, SwiGLU FF; final RMSNorm).
    • The packed sequence is text tokens, then reference image tokens, then target image tokens, scattered into a zero tensor at text_indices and image_indices.
    • Timestep embedding: [cos, sin] of t * exp(-ln(10000) * i / 128) in f32 (256), time_embedder (Linear 256 to 5376, SiLU, Linear to 2688).
    • AdaLN: each of the 50 blocks has adaln_proj (Linear(2688 -> 6 * 5376 * 3) on silu(temb)) reshaped to one (shift, scale, gate) x 2 set per (timestep row, modality tag); a token picks row timestep_index * 3 + tag (tags: image 0, text 1, audio 2; the audio slot is unused but present in the weights).
    • Block: x + gate_msa * attn((1 + scale_msa) * RMSNorm(x) + shift_msa), then the same with the FF; attention has q/k/v/out without bias, per-head RMSNorm on q and k, full (unmasked) SDPA at scale 128 ** -0.5, and 3-axis RoPE on the first 96 dims of each head (per axis 1 / theta ** (arange(0, 32, 2) / 32), concatenated over the three axes and duplicated, rotate-half), the last 32 dims passing through. FF: proj: 5376 -> 2 * 14336, h * silu(gate), Linear(14336 -> 5376).
    • Output: norm_out RMSNorm with (shift, scale) chosen by timestep row, then pdd_proj_out[step] (5376 -> 96) on the image rows only.
    • Positions (build_image_layout): text token k is (k, 0, 0); image grid i (references in order, then the target) uses (text_count + i, y, x) with y, x from linspace(left, left + ratio, n, endpoint=False) * 32, ratio = size / sqrt(h * w), left = (1 - ratio) / 2, on the patch grid; computed in f64 and cast to f32.
  • Schedule: fixed SAMPLE_SIGMAS = (1.0, 0.9675236940383911, 0.8875485062599182, 0.75, 0.5327739119529724, 0.23200887441635132, 0.0); step timesteps 1 - sigma in f32; each step's timestep table is [t_step, 0.999] (row 0 for the target, row 1 for references). Exactly 6 steps and guidance 1; anything else, or a negative prompt, is rejected. Upstream materializes the six AdaLN caches once and then drops the AdaLN projection weights (about 26 GB at bf16).
  • Sampling: one key from seed, split before each draw in this order: each reference's VAE posterior sample, the target noise normal((1, 24, 1, lh, lw)), each reference's mixing noise. References enter as 0.999 * z + 0.001 * noise and stay fixed; the target rows take Euler steps rows += (sigma_s - sigma_{s+1}) * velocity in f32.
  • Canvas: scale = max(1, sqrt(min_generation_area / (w * h))) with min_generation_area default 4194304 (valid 1024..16777216), sides rounded to multiples of 32; latent grid canvas / 16; the decoded image is LANCZOS-resized to the requested size. Default size 4096x4096.
  • Conditioner: Qwen3-VL-32B (64 layers, hidden 5120) in text_encoder/ with its vision tower; returns the pre-final-norm hidden state after layer 50. Token sequence with no chat template: for each reference, the tokens of "Picture {i}: " (tag 1), <|vision_start|>, <|image_pad|> times t * h * w / 4, <|vision_end|> (tag 0); then the prompt tokens (tag 1), each part truncated to max_sequence_length (1..4096, default 4096). Conditioner references are resized so the short edge is 1024 (multiples of 32, LANCZOS) and run through the Qwen3-VL image processor. If text_encoder/config.json is absent, model_index.json names a shared repo (MiniMaxAI/MiniMax-H3, subfolder text_encoder).
  • VAE (vae_diffusers/config.json, _class_name AutoencoderKLMiniMaxH3Image): latent_channels 24, block_out_channels [128, 256, 256, 512, 512, 1024], layers_per_block 2, spatial_downsample_factors [2, 2, 2, 2, 1, 1] (16x), causal 3D-conv encoder with reflect spatial padding and GroupNorm 32 (eps 1e-6) run on one frame, a diagonal Gaussian posterior; decoder is a ViT (decoder_num_layers 24, 16 heads of 64, 4 register tokens plus one zero token, FF mult 4, LayerNorm out, eps 1e-5, 2D RoPE on half of each head with theta 100 over positions in [-1, 1]), proj_out to 3 * 16 * 16 per latent and unpatchified, decoded in tiles of 256 output pixels with at least 64 pixels of overlap (_split_tiles works in pixels and slices the latent by the 16x ratio), each tile evaluated on its own, then blended by _stitch_tiles. Latent latents_mean / latents_std from the config normalize encode and decode. Pixels use ImageNet mean and std on both sides.
  • Edit references: 1 to 16; each short edge bounded to [1024, 2048] (multiples of 32, LANCZOS), cropped to multiples of 16, VAE-encoded, posterior sampled, rounded through f16, cropped to even latent sizes, normalized. References keep their aspect ratio and are not resized to the target canvas. Prompts refer to them as <Picture 1>, <Picture 2>, ...
  • Weights: official checkpoints are strict-loaded from transformer_diffusers/ and vae_diffusers/ (the VAE through its sanitize); MLX conversions from transformer/, vae/, text_encoder/ with quantization (affine, group 64) applied to every module whose .scales tensor is present; sensitive projections and the VAE stay at source precision.

Checkpoints and host

Checkpoint Download Notes
nativ-community/MiniMax-H3-Image-4bit 54.48 GB Validation target; not gated
nativ-community/MiniMax-H3-Image-8bit 77.32 GB Second validation checkpoint
MiniMaxAI/MiniMax-H3-Image (bf16) 135.3 GB used (text_encoder/ 66.7 GB, transformer_diffusers/ 66.3 GB, vae_diffusers/ 2.3 GB, tokenizer/, model_index.json, pdd_config.json) The repo totals about 204 GB because it also holds native transformer/ and vae/ duplicates; download only the listed parts, as upstream's download.py does

The 4-bit and 8-bit runs fit a 128 GB machine: the conditioner, transformer and VAE load in turn and the conditioner is freed before the transformer loads. Validate bf16 on a machine with 256 GB or more, since 135 GB of weights plus page cache do not fit a 128 GB box comfortably even though the staged resident peak is about 70 GB. Prompt expansion (MiniMaxAI/MiniMax-H3-Image-PE, 17.9 GB NVFP4 Qwen3.5) is not needed for this issue.

Current behavior

  • src/imagegen/probe.rs:42 (IMAGE_FAMILIES) and src/imagegen/registry.rs:47 (FAMILIES) have no minimax_h3_image; model_types_from_metadata (src/imagegen/probe.rs:216) reads model_type and _class_name, so both detection keys can be added there.
  • docs/vision-model-scope.md:79 lists minimax_h3 as out of scope (video and audio), which is correct for that release but is the only record that mentions H3 at all.
  • Reusable pieces: mlxcel's generative Qwen3-VL (src/models/qwen3_vl.rs, forward_hidden_pre_norm at :1133, used by the Qwen-Image conditioner src/imagegen/qwen_image/text_encoder.rs), which returns the last layer only; the Qwen3-VL image processor path the Qwen-Image and Mage-Flow conditioners use (src/imagegen/mage_flow/conditioner.rs); src/imagegen/pipeline.rs:241 (ImageGenerationModel); the staged load-and-free pattern of MOSS-Image (src/imagegen/moss_image/pipeline.rs); the Ideogram 4 refusal of prompt_expansion_model (src/imagegen/ideogram4/config.rs:264-272).

Proposed solution

New module src/imagegen/minimax_h3_image/ (mod.rs with pub const FAMILY: &str = "minimax_h3_image" and pub fn load, config.rs, conditioner.rs, layout.rs (canvas, short-edge bound, positions, schedule), transformer.rs, adaln.rs (the cache and the weight drop), vae.rs (encoder, posterior, ViT decoder, tiling), pipeline.rs, weights.rs, tests beside each). The shared H3 blocks are ported here under the image family; the video and audio H3 stay out of scope, and if that family is ever ported it should import these blocks rather than copy them.

  • Conditioner: add pub(crate) fn forward_hidden_pre_norm_at_layer(&self, ..., stop_after_layer: usize) to src/models/qwen3_vl.rs beside forward_hidden_pre_norm (the existing function becomes a call with the last layer; Qwen-Image output unchanged), and load only the first 50 decoder layers.
  • Detection: model_types_from_class_name("MiniMaxH3ImagePipeline") and model_type: minimax_h3_image give minimax_h3_image; add the probe name and the registry row, and a StandaloneArchitectureFamily in src/models/registry.rs (category image generation, IMAGE_GENERATE, aliases minimax-h3-image, output image).
  • Requests: defaults 6 steps, guidance 1.0, size 4096x4096; check_request rejects other steps or guidance, negative prompts, more than 16 references, and unknown extra keys (allowed: min_generation_area, max_sequence_length, upsample_prompt, prompt_expansion_model); upsample_prompt: true or prompt_expansion_model returns a 400 naming the reason (prompt expansion is not implemented; pass a detailed English caption), as Ideogram 4 does. Size multiple is 32 at the canvas level; the requested output size is any positive size and is reached by the final resize.
  • Memory: build the six AdaLN caches on the first request, then drop the AdaLN projection weights, and evaluate after every transformer block as upstream does to bound the lazy graph.
  • Response metadata: revised_prompt is the prompt used, plus reference_images.

Scope

In scope: the module, probe and registry rows, generation and editing for the 4-bit, 8-bit and bf16 checkpoints, mlxcel generate-image and /v1/images/generations / /v1/images/edits, docs/image-generation.md (a MiniMax-H3-Image section with options, memory and parity), docs/supported-models.md (Image generation list), and docs/vision-model-scope.md: keep the minimax_h3 row out of scope but state that the image-only minimax_h3_image release is ported under this issue, and add a minimax_h3_image row to the image generation table. Reference #524 in the scope-doc change. NOTICE for the mlx-vlm port.

Out of scope: the joint video and audio minimax_h3 family, prompt expansion through MiniMax-H3-Image-PE (enabled by default upstream; a follow-up should add in-process prompt expansion for this family and FLUX.3 together), num_images > 1, quantizing the official bf16 checkpoint in mlxcel.

Implementation notes

  • Dtype: transformer at checkpoint precision (bf16 or affine-quantized), Euler state f32, positions computed in f64 then f32, reference latents rounded through f16 as upstream does; the bf16 to f16 conversion policy must not touch the quantized conversions' bf16 scales.
  • Edge cases: a reference with a short edge under 32 px (error), above 2048 (shrunk), an extreme aspect ratio, a requested size below min_generation_area (generated larger, then resized), min_generation_area out of range (400), a prompt over 4096 tokens (truncated), a checkpoint without text_encoder/ (resolve the referenced repo locally or fail naming it).
  • Error handling: missing component directories and class-name mismatches name the expected layout (transformer_diffusers/ for official, transformer/ for converted).

Acceptance criteria

  • Unit tests: probe detection for both model_index.json forms; canvas_size for 1024x1024, 4096x4096 and 1000x3000; bound_short_edge; build_image_layout positions for one reference plus a target on small grids against upstream values; sampling_schedule; AdaLN row selection t * 3 + tag; the transformer and token refiner on a tiny random config against upstream formulas; the AdaLN cache path equals the live path before the weights are dropped.
  • VAE tests: a tiny random encoder and ViT decoder against upstream formulas; tiled decode of a 2x2-tile latent equals an untiled decode within the stitching blend.
  • Real-checkpoint parity on nativ-community/MiniMax-H3-Image-4bit against mlx-vlm with upsample_prompt=false on both sides: bit-identical initial noise for seed 42; conditioner hidden state at layer 50 relative error under 1e-2; on upstream's conditioner output, a 1024x1024 generation with min_generation_area 1024 and a single-reference edit at 30 dB PSNR or better; end-to-end numbers recorded in docs/image-generation.md. Repeat the generation on the 8-bit checkpoint and, on a 256 GB machine, the bf16 checkpoint.
  • mlxcel generate-image -m nativ-community/MiniMax-H3-Image-4bit -p "<detailed caption>" --size 4096x4096 --seed 42 -o out.png writes the image; --task edit --image out.png -p "Make the teapot in <Picture 1> blue, preserving its shape, the room, and the lighting" works; mlxcel-server --image-model <path> serves both routes; --steps 8 and upsample_prompt: true return errors.
  • mlxcel arch --json lists minimax_h3_image; docs/vision-model-scope.md states the split between minimax_h3 and minimax_h3_image.
  • Qwen-Image's conditioner output is unchanged after the qwen3_vl.rs change (its parity tests pass).

Verification

cargo test --profile test-fast imagegen::minimax_h3_image
cargo test --profile test-fast imagegen::qwen_image
cargo test --profile test-fast qwen3_vl
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
./target/release/mlxcel generate-image -m models/MiniMax-H3-Image-4bit -p "A red ceramic teapot on a wooden table beside a sunlit window, soft morning light, detailed natural textures" --size 1024x1024 --seed 42 -o /tmp/h3.png --gen-kwargs '{"min_generation_area": 1024}'

Related

  • #524 (vision scope tracking that set minimax_h3 out of scope), image generation runtime #2341 and epic #2348, MOSS-Image (the staged-load precedent), Qwen-Image #2342 (the Qwen3-VL conditioner hook extended here).
  • FLUX.3 #3230 has the same prompt-expansion gap.
Ngôn ngữ chính
Rust
Star
505
Fork
81
Merge trung bình
14 giờ 2 phút
Pull request đã merge (30 ngày)
448

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của lablup/mlxcel

Tất cả issue của lablup/mlxcel

Issue tương tự

Thêm issue về Rust

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.