mflux-model-porting
Standardizes the workflow for porting ML models into mflux/MLX while maintaining strict output correctness.
Install
mkdir -p .claude/skills/mflux-model-porting && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3349" && unzip -o skill.zip -d .claude/skills/mflux-model-porting && rm skill.zipInstalls to .claude/skills/mflux-model-porting
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Port ML models into mflux/MLX with correctness-first validation, then refactor toward mflux style.Key capabilities
- →Port ML models to mflux/MLX
- →Validate model parity with reference implementations
- →Configure weight loading and mapping
- →Refactor code toward shared mflux components
- →Run deterministic parity tests
How it works
The skill follows a correctness-first workflow, inverting the generation flow to validate components from pixel space backward, followed by deterministic testing and refactoring.
Inputs & outputs
When to use mflux-model-porting
- →Porting diffusers to mflux
- →Validating MLX model parity
- →Initial weight loading configuration
About this skill
mflux model porting
Goal
Provide a repeatable, MLX-focused workflow for porting ML models (typically from diffusers repo located near mflux repo in the system) into mflux with correctness first, then refactor to mflux style.
Principles
- Match the reference implementation first; prove correctness before cleanup.
- Lock correctness with deterministic tests before refactoring.
- During the initial port, avoid premature performance work (e.g.,
mx.compile, kernel fusion tweaks, scheduler micro-optimizations); add optimizations only after correctness is locked. - Refactor toward shared components and clean APIs once tests are green.
- PyTorch and MLX RNGs are different; for strict parity checks, export the exact initial noise/latents from the reference and load them in MLX instead of relying on matching integer seeds.
Workflow (checklist)
- Scope and parity
- Define target parity (outputs, speed, memory) and acceptable tolerances.
- Identify reference files, configs, and checkpoints to mirror.
- Draft a Cursor plan for the port and review it before starting implementation.
- Port fast to reference
- Add the model package skeleton and a variant class + initializer.
- Follow standard mflux initializer/weight-loading style; review recent ports like
z_image_turboandflux2_kleinfor structure and naming. - Wire weight definitions/mappings early so loading is exercised (implement quantization in the initializer, but skip it during early runs).
- Keep the first implementation simple and explicit; defer
mx.compileand other speed-focused changes until deterministic parity is passing. - When defining explicit weight mappings, inspect actual tensor values from the model in the Hugging Face cache to confirm names and shapes.
- Add a minimal hardcoded runner for quick iteration (two tiny scripts: one in the reference repo, one in mflux), seeded with diffusers-style defaults (e.g., 1024×1024, default prompt).
- Add lightweight shape checks close to the code paths.
- Use
mx.save/mx.loadat critical points; it is OK to add these to the reference (without changing logic) to export latents.
- Port order (work backwards from image)
- Typical image generation flow:
prompt → text_encoder → transformer_loop → VAE → image. - For porting, invert the order so you can validate pixel space early.
- Start with VAE decode/encode to validate output images quickly:
- Export packed latents from the reference just before VAE decode.
- Load latents inline and decode to an image for visual inspection.
- Run an encode→decode roundtrip to sanity check reconstruction; a good-looking image reconstruction increases confidence in the implementation.
- Expect small numeric diffs in tensor values; when it is not clear from the numbers alone, always generate images and rely on human visual inspection to judge whether the match is acceptable.
- Then port the transformer loop and its schedulers with intermediate latent checks.
- If the reference uses a novel scheduler, port it; otherwise, reuse the existing mflux scheduler.
- Finish with the text encoder and tokenizer details.
- After each major component is validated (e.g., VAE, transformer, text encoder), commit with a clear milestone message like "VAE done" to preserve progress.
- Once the full port is working, remove any loaded tensors or debug artifacts so no traces remain.
- Typical image generation flow:
- Deterministic validation
- Create a deterministic MLX test (image or tensor) that locks the output.
- Run tests via
MFLUX_PRESERVE_TEST_OUTPUT=1 uv run <test command>. - If MLX OOMs on sensible inputs (e.g., 1024×1024), assume a likely porting mistake and re-check shapes or memory-heavy ops.
- Post-test refactor (explicit step)
- Review commits after the first deterministic test to capture refactoring preferences.
- Consolidate shared components into common modules.
- Remove debug paths and one-off schedulers once validated.
- Move configuration defaults into standard config/scheduler paths.
- Simplify and decompose large files into focused modules once behavior is locked.
- Prefer shared scheduler implementations when they already exist in mflux.
- Ensure CLIs register callbacks via
CallbackManager.register_callbacks(...)so shared features like--stepwise-image-output-dirwork; pass alatent_creatorthat supportsunpack_latents(...). - Keep running the deterministic image test during refactors to avoid regressions.
- Align the variant class with recent ports (
flux2_klein,z_image):prompt_cache, merged_predict, RoPE setup inside predict path,_decode_latentshelper, no verbose comments/docstrings (see repoRULE.md). - Strip dead scaffolding (e.g. unused gradient-checkpointing flags) once training/inference paths are stable.
- Pre-merge polish (after core port works)
- diffusers sanity check: run matched mflux + diffusers generations; use
mflux-debugginglatent injection if outputs disagree but you need to validate transformer/VAE. - Golden tests: pick prompt/seed/settings that are stable on target CI hardware; update reference PNGs only after explicit approval (see
mflux-testing). - img2img: verify latent packing/normalization on the img2img path matches txt2img and training (especially when reusing a shared VAE from another model family).
pack_latentsmust accept the 5D(B, C, 1, H, W)tensor that tiled VAE encode (vae_encode_tiled) returns — squeeze the singleton temporal axis first, asflux2/fibo/z_imagelatent creators do; a 4D-only unpack (or a bare passthroughpack_latents) breaks tiled img2img. This is reachable via--low-ram:MemorySaversetstiling_config = TilingConfig()(vae_encode_tiled=True), so always test img2img with--low-ram, not just the default path (which is safe only becauseVAEUtil.encodesqueezes 5D→4D when tiling is off). - Cross-model touch points: list every file outside
models/<your_model>/; justify shared changes (memory_savertiling guard, shared VAEtiling_config, trainingrunnerwiring). Drop unrelated edits (e.g. personal.gitignoreentries). - README: follow an existing model README structure (e.g. Flux2): hero image, turbo + base examples, feature section (img2img), disk-size warning, Notes, Training. Measure on-disk sizes with
duon HF cache and/ormflux-save+du -shfor quantized sizes. - Training: example JSON under
models/common/training/_example/, un-ignore in.gitignore, fast unit tests for training-adapter preview defaults. - Re-run
make lint,make test-fast, then slow golden tests before merge.
- diffusers sanity check: run matched mflux + diffusers generations; use
- Finalize
- Re-run tests and basic perf checks after polish.
- Add CLI/pipeline defaults and completions later, once core output is stable.
- Ensure the model is wired into the standard surfaces:
ModelConfigentry + aliases- Thin model CLI entrypoint that uses shared parser/config/callback patterns
- README following the structure and tone of existing model READMEs
- Python API example that matches the CLI/defaults
- Document any new mapping rules, shape constraints, or tolerances.
Package layout (reference: flux2)
Use src/mflux/models/flux2/ as the canonical tree. Do not invent flat mlx-vlm-style roots (config.py, scheduler.py, fp8.py, layout.py, monolithic model/transformer.py). Aliases and defaults live in ModelConfig; checkpoint validation belongs in the initializer and/or *WeightDefinition, not a separate layout module.
{model}/
{model}_initializer.py
__init__.py # export variant + initializer
README.md
cli/
{model}_generate.py # (+ edit/turbo CLIs when applicable)
latent_creator/
{model}_latent_creator.py
model/
{model}_text_encoder/ # prompt_encoder.py, tokenizer pieces, text_encoder.py
{model}_transformer/ # attention, blocks, rope, transformer.py (split files)
{model}_vae/ # or reuse shared VAE (e.g. flux2_vae) — document in README
{model}_scheduler/ # only when not covered by models/common/schedulers
variants/
__init__.py # re-export public variant class(es)
txt2img/
__init__.py
{model}.py # e.g. flux2_klein.py, ideogram4.py
edit/ # when the model supports image-conditioned generation
__init__.py
{model}_edit.py
weights/
__init__.py
{model}_weight_definition.py # components, download patterns, tokenizers
{model}_weight_mapping.py # WeightTarget list / key transforms for base weights
{model}_lora_mapping.py # LoRA key aliases (diffusers, PEFT, kohya) — when LoRA is supported
training_adapter/ # when mflux-train is supported
{model}_training_adapter.py
Variants: always place txt2img classes under variants/txt2img/ (even for single-mode models). Use variants/edit/ for edit/img2img variants. Import from the full path in save.py and CLIs, e.g. variants.txt2img.flux2_klein.
Weights: *WeightDefinition is required for every port. Add *WeightMapping when diffusers/HF key names need explicit targets. Add *LoRAMapping when inference or training supports LoRA — wire --lora-paths / --lora-scales through the shared parser and add fast tests that community LoRA filenames map to non-zero keys (see integration checklist below).
Variant class style (post-refactor): match flux2_klein / z_image — prompt_cache, _predict / _decode_latents, thin generate_image, prompt encoding in {model}_text_encoder/prompt_encoder.py.
Skip when not applicable: variants/edit/, training_adapter/, {model}_lora_mapping.py, local VAE package (if reusing another model family’s VAE). Document omitted features in the model README.
Integration surfaces che
Content truncated.
When not to use it
- →When performing performance optimizations before correctness is locked
Prerequisites
Limitations
- →Requires manual visual inspection for numeric diffs
- →Performance work is deferred until tests pass
How it compares
It mandates deterministic parity testing against reference implementations before any architectural refactoring or optimization.
Compared to similar skills
mflux-model-porting side by side with the closest alternatives in the catalog.
Try saying
Example prompts that trigger this skill in your AI assistant.
More by filipstrand
View all by filipstrand →You might also like
llama-cpp
zechenzhangAGI
Runs LLM inference on CPU, Apple Silicon, and consumer GPUs without NVIDIA hardware. Use for edge deployment, M1/M2/M3 Macs, AMD/Intel GPUs, or when CUDA is unavailable. Supports GGUF quantization (1.5-8 bit) for reduced memory and 4-10× speedup vs PyTorch on CPU.
langchain
zechenzhangAGI
Framework for building LLM-powered applications with agents, chains, and RAG. Supports multiple providers (OpenAI, Anthropic, Google), 500+ integrations, ReAct agents, tool calling, memory management, and vector store retrieval. Use for building chatbots, question-answering systems, autonomous agents, or RAG applications. Best for rapid prototyping and production deployments.
unsloth
zechenzhangAGI
Expert guidance for fast fine-tuning with Unsloth - 2-5x faster training, 50-80% less memory, LoRA/QLoRA optimization
llama-factory
zechenzhangAGI
Expert guidance for fine-tuning LLMs with LLaMA-Factory - WebUI no-code, 100+ models, 2/3/4/5/6/8-bit QLoRA, multimodal support
llava
zechenzhangAGI
Large Language and Vision Assistant. Enables visual instruction tuning and image-based conversations. Combines CLIP vision encoder with Vicuna/LLaMA language models. Supports multi-turn image chat, visual question answering, and instruction following. Use for vision-language chatbots or image understanding tasks. Best for conversational image analysis.
cocoindex
cocoindex-io
Comprehensive toolkit for developing with the CocoIndex library. Use when users need to create data transformation pipelines (flows), write custom functions, or operate flows via CLI or API. Covers building ETL workflows for AI data processing, including embedding documents into vector databases, building knowledge graphs, creating search indexes, or processing data streams with incremental updates.