{"owner":"filipstrand","repo":"mflux","hasSkills":true,"totalSkillsCount":31,"totalTokensCount":24916,"categories":["anthropic-skill","root-instruction","claude-rule"],"hasMcp":false,"mcpConfig":null,"found":[".cursor/skills/mflux-cli/SKILL.md",".agents/skills/remediating-dependabot/SKILL.md",".cursor/skills/mflux-dev-env/SKILL.md",".cursor/skills/mflux-model-porting/SKILL.md",".cursor/skills/mflux-pr-docs/SKILL.md",".cursor/skills/mflux-model-tiny-test/SKILL.md",".cursor/skills/mflux-pr/SKILL.md",".cursor/skills/mflux-release/SKILL.md",".cursor/skills/mflux-testing/SKILL.md",".cursor/skills/asd-ste100/SKILL.md",".cursor/skills/mflux-manual-testing/SKILL.md",".cursor/skills/mflux-debugging/SKILL.md","AGENTS.md",".claude/skills/asd-ste100",".claude/skills/mflux-cli",".claude/skills/mflux-debugging",".claude/skills/mflux-dev-env",".claude/skills/mflux-manual-testing",".claude/skills/mflux-model-porting",".claude/skills/mflux-model-tiny-test",".claude/skills/mflux-pr",".claude/skills/mflux-pr-docs",".claude/skills/mflux-release",".claude/skills/mflux-testing",".cursor/rules/RULE.md",".cursor/skills/asd-ste100/README.md",".cursor/skills/mflux-pr-docs/pr-what-prompt.md",".cursor/skills/mflux-pr-docs/release-note-prompt.md",".cursor/skills/asd-ste100/examples/before-after.md",".cursor/skills/asd-ste100/examples/linter-edge-cases.md",".cursor/skills/asd-ste100/references/writing-rules.md"],"skills":{".cursor/skills/mflux-cli/SKILL.md":"---\nname: mflux-cli\ndescription: Navigate MFLUX CLI capabilities, locate commands by area, and summarize supported features.\n---\n# mflux CLI navigation\n\nUse this skill to inventory CLI capabilities, summarize what the CLI supports, and guide where to look\nfor commands without relying on brittle file paths.\nBecause README examples can drift, prefer verifying support against the current CLI entrypoints.\n\n## When to use\n\n- You need to list supported CLI features or commands.\n- You need to find where a capability is implemented in the CLI.\n- You are documenting or refactoring CLI features and want a stable map.\n- A user asks for CLI help, e.g., “Can you help me generate an image using z-image?”, “Which model is best?”, etc.\n\n## How to find commands (structure, not exact paths)\n\n- Common/shared CLI arguments live in the central CLI parser module.\n- Model-specific CLI entrypoints live under each model's CLI package.\n- Repo-level CLI helpers (completions, defaults) live under the shared CLI package.\n- Utilities may add standalone CLIs (e.g., metadata info, LoRA library).\n\n## Best practices when constructing CLI calls\n\n- **Inference steps**: When constructing a CLI call for any model, *always* check `MODEL_INFERENCE_STEPS` and use the model's default/recommended step count unless the user explicitly asks for a different value. This is especially important for distilled/non-base variants (for example `fibo-lite`, `z-image-turbo`, and other `*-turbo`/`*-lite` models), where using full/base-model step counts is usually counterproductive.\n- **Resource/inspection flags**: Mention `--low-ram` to reduce memory usage and `--stepwise-image-output-dir` for stepwise outputs when useful.\n- **Python API requests**: If a user asks for the Python API, treat the equivalent CLI script as the best starting reference for the underlying parameters and defaults.\n- **CLI implementation changes**: When adding or changing CLI behavior, prefer extending shared parser methods and shared helpers before adding manual one-off arguments or save paths in a model CLI.\n- **Docs/examples drift**: If CLI defaults, supported flags, or recommended usage changed, update the matching README examples in the same pass.\n\n## Capability inventory (current)\n\n### Core generation\n\n- Text-to-image across Flux, Flux2, FLUX 3 Image Klein, Iris-3B, SenseNova-U1.5, DreamLite, Qwen, Z-Image Turbo, FIBO.\n- Image-to-image where supported (Flux, Qwen, Z-Image Turbo, FIBO).\n\n### Editing and conditioning\n\n- Kontext image conditioning.\n- In-context editing and reference-image workflows.\n- CATVTON (virtual try-on).\n- Redux multi-image conditioning.\n- ControlNet (Canny).\n- Depth conditioning.\n- Fill / inpainting.\n- Flux2 Edit, FLUX 3 Image Klein edit (1-10 reference images) and Qwen Edit (multi-image edit).\n- DreamLite edit (one image, instruction-based).\n\n### Upscaling\n\n- SeedVR2 diffusion upscaler (preferred).\n- Flux ControlNet upscaler (legacy).\n\n### Model management\n\n- Quantized inference and saving quantized models.\n- Local model path loading (with base-model hints when needed).\n\n### LoRA\n\n- Load LoRAs, multi-LoRA, scale control.\n- In-context style LoRA shortcuts.\n- LoRA library lookup tool.\n\n### Metadata and reproducibility\n\n- Export JSON metadata per image.\n- Reuse prior parameters from metadata config files.\n- Inspect metadata from existing images.\n\n### Prompt tooling\n\n- Prompt files.\n- Negative prompts where supported (not supported for Flux2, FLUX 3 Image Klein or SenseNova-U1.5; Iris-3B uses them only on the base model).\n\n### Training\n\n- LoRA finetuning.\n\n### Utilities\n\n- DepthPro depth-map extraction.\n- FIBO VLM prompt inspire/refine tools.\n",".agents/skills/remediating-dependabot/SKILL.md":"---\nname: remediating-dependabot\ndescription: Remediates GitHub Dependabot alerts for mflux in one dependency-security change. Use when auditing, clamping, or upgrading Python dependencies in pyproject.toml and uv.lock, or when validating whether a branch will close Dependabot findings before opening a PR.\n---\n\n# Remediating Dependabot\n\nResolve actionable Dependabot alerts with the smallest compatible dependency update and prove the local lock is outside every reported vulnerable range.\n\n## Scope\n\n- Use `gh api` as the source of truth for open alerts in `mflux-community/mflux`.\n- Keep dependency changes in `pyproject.toml` and `uv.lock` unless compatibility requires source changes.\n- Preserve supported Python and platform markers.\n- Avoid unrelated package upgrades when regenerating the lock.\n- Treat dependency optionality or loading refactors as separate work unless explicitly requested.\n\n## Workflow\n\n1. Confirm the current branch and working tree before editing.\n2. Fetch all open Dependabot alerts, following pagination:\n\n   ```bash\n   gh api --method GET --paginate \\\n     -H \"Accept: application/vnd.github+json\" \\\n     repos/mflux-community/mflux/dependabot/alerts \\\n     -f state=open\n   ```\n\n3. Group alerts by manifest, package, severity, vulnerable range, and first patched version. Distinguish direct requirements from transitive lock entries.\n4. Inspect `pyproject.toml`, `uv.lock`, supported Python versions, and platform markers before choosing a fix.\n5. Prefer, in order:\n   - removing dependencies that are no longer needed;\n   - raising a direct lower bound to the first secure compatible release;\n   - upgrading only affected transitive packages in the lock;\n   - adding or changing environment markers only when compatibility actually differs by Python or platform.\n6. Use one requirement when a release supports the full project matrix. Do not introduce overlapping marker-specific requirements without evidence that they are necessary.\n7. Regenerate the lock with targeted upgrades:\n\n   ```bash\n   uv lock --upgrade-package <package> [--upgrade-package <package> ...]\n   ```\n\n8. Review the lock diff. Explain large platform-specific resolver changes, especially PyTorch CUDA package transitions, rather than assuming they are accidental.\n\n## Security verification\n\nDo not infer alert closure solely from package names or Dependabot's hosted UI.\n\n1. Run lock and advisory checks:\n\n   ```bash\n   uv lock --check\n   uv audit --preview-features audit-command\n   ```\n\n2. Parse every resolved version in `uv.lock` and compare it with every open alert's `security_vulnerability.vulnerable_version_range`. Canonicalize names with `packaging.utils.canonicalize_name` and use `packaging.specifiers.SpecifierSet` so matching follows Python package name and version semantics.\n3. Confirm that each alert is resolved by either:\n   - no matching package remaining in the lock; or\n   - every matching locked version falling outside the vulnerable range.\n4. Run Dependabot Core against the local checkout before opening a PR:\n\n   ```bash\n   tmp_dir=\"$(mktemp -d)\"\n   trap 'rm -rf \"$tmp_dir\"' EXIT\n   job=\"$tmp_dir/job.yml\"\n   output=\"$tmp_dir/output.yml\"\n\n   # Build the security job at \"$job\" before running these commands.\n   dependabot graph uv mflux-community/mflux --local \"$PWD\"\n   dependabot update --local \"$PWD\" -f \"$job\" -o \"$output\" --pull=false --timeout 20m\n   ```\n\n   `graph` is experimental and may return an incomplete dependency list. Both commands snapshot the directory passed to `--local`, including modified and untracked files, so confirm that the working tree contains only the intended updater input.\n\n   Build the temporary `uv` security job from the exact package names and advisory ranges returned by GitHub. Parse the YAML output rather than relying on the command's exit status:\n\n   ```bash\n   uv run python - \"$output\" <<'PY'\n   import sys\n\n   import yaml\n\n   with open(sys.argv[1]) as output_file:\n       actions = {entry[\"type\"] for entry in yaml.safe_load(output_file)[\"output\"]}\n\n   if \"mark_as_processed\" not in actions:\n       raise SystemExit(\"Dependabot did not mark the job as processed\")\n\n   pull_request_actions = actions & {\"create_pull_request\", \"update_pull_request\"}\n   if pull_request_actions:\n       raise SystemExit(f\"Dependabot still proposes actions: {sorted(pull_request_actions)}\")\n   PY\n   ```\n\n   Do not pin Dependabot CLI to one release. Verify the installed CLI exposes the commands and flags used here before running the job.\n5. Keep temporary Dependabot job and output files outside the committed change, and remove them after verification.\n6. If the hosted alert remains open while the local lock is already outside its vulnerable range, report it as pending or stale until GitHub rescans. Do not force an unnecessary upgrade just to change the lock entry.\n\n## Project verification\n\nRun the repository workflows after the lock is secure:\n\n```bash\njust lint\njust lint-justfile\njust typecheck\njust test-fast\njust test\njust build\ngit diff --check\n```\n\nUse `uv lock --upgrade --dry-run` to check that a fresh universal resolution succeeds. It may report unrelated newer releases; do not add them unless they are needed for the remediation.\n\n## Reporting\n\nReport:\n\n- total open findings expected to close, grouped by severity and package;\n- direct requirement changes and noteworthy lock-only changes;\n- packages removed from the lock;\n- exact results from range comparison, Dependabot Core, `uv audit`, and project checks;\n- any alerts whose final hosted closure depends on GitHub rescanning the merged lockfile.\n",".cursor/skills/mflux-dev-env/SKILL.md":"---\nname: mflux-dev-env\ndescription: Set up and work in the mflux dev environment (arm64 expectation, uv, justfile recipes, lint/format/test).\n---\n# mflux dev environment\n\nThis repo expects macOS arm64 and prefers `uv` + justfile recipes.\n\n## When to Use\n\n- You’re setting up the repo locally or diagnosing environment/setup issues.\n- You need the canonical way to run lint/format/check/build/test.\n\n## Instructions\n\n- Prereq: `just` ≥ 1.50 (`brew install just`). CI lints the justfile with `just --fmt --check`; run `just fmt-justfile` to auto-fix formatting.\n- Prefer justfile recipes:\n  - Install: `just install`\n  - Lint: `just lint`\n  - Format: `just format`\n  - Pre-commit suite: `just check`\n  - Build: `just build`\n- Prefer `uv run ...` for running Python commands to ensure the correct environment.\n- When running tests, keep `MFLUX_PRESERVE_TEST_OUTPUT=1` enabled (the justfile test recipes already do this).\n\n## Type checking (ty)\n\n- The type checker is astral's `ty`, pinned exactly in `pyproject.toml` dev deps (mirrored in `.pre-commit-config.yaml` and run in CI). Run it with `just typecheck` (or `uv run ty check`).\n- `[tool.ty.rules]` in `pyproject.toml` carries a one-time migration baseline (mypy → ty): every rule listed there had pre-existing violations and is set to `\"ignore\"`, with violation counts in comments.\n- **Planned burn-down**: we intend to re-enable these rules piecemeal — delete one ignore line, fix all resulting `ty check` errors, commit, repeat. Prefer starting with low-count rules. Do not add new ignore lines; new code must pass all rules not in the baseline.\n\n",".cursor/skills/mflux-model-porting/SKILL.md":"---\nname: mflux-model-porting\ndescription: Port ML models into mflux/MLX with correctness-first validation, then refactor toward mflux style.\n---\n# mflux model porting\n\n## Goal\nProvide 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.\n\n## Principles\n- Match the reference implementation first; prove correctness before cleanup.\n- Lock correctness with deterministic tests before refactoring.\n- 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.\n- Refactor toward shared components and clean APIs once tests are green.\n- 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.\n\n## Workflow (checklist)\n1. **Scope and parity**\n   - Define target parity (outputs, speed, memory) and acceptable tolerances.\n   - Identify reference files, configs, and checkpoints to mirror.\n   - Draft a Cursor plan for the port and review it before starting implementation.\n2. **Port fast to reference**\n   - Add the model package skeleton and a variant class + initializer.\n   - Follow standard mflux initializer/weight-loading style; review recent ports like `z_image_turbo` and `flux2_klein` for structure and naming.\n   - Wire weight definitions/mappings early so loading is exercised (implement quantization in the initializer, but skip it during early runs).\n   - Keep the first implementation simple and explicit; defer `mx.compile` and other speed-focused changes until deterministic parity is passing.\n   - When defining explicit weight mappings, inspect actual tensor values from the model in the Hugging Face cache to confirm names and shapes.\n   - 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).\n   - Add lightweight shape checks close to the code paths.\n   - Use `mx.save`/`mx.load` at critical points; it is OK to add these to the reference (without changing logic) to export latents.\n3. **Port order (work backwards from image)**\n   - Typical image generation flow: `prompt → text_encoder → transformer_loop → VAE → image`.\n   - For porting, invert the order so you can validate pixel space early.\n   - Start with VAE decode/encode to validate output images quickly:\n     - Export packed latents from the reference just before VAE decode.\n     - Load latents inline and decode to an image for visual inspection.\n     - Run an encode→decode roundtrip to sanity check reconstruction; a good-looking image reconstruction increases confidence in the implementation.\n     - 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.\n   - Then port the transformer loop and its schedulers with intermediate latent checks.\n     - If the reference uses a novel scheduler, port it; otherwise, reuse the existing mflux scheduler.\n   - Finish with the text encoder and tokenizer details.\n   - After each major component is validated (e.g., VAE, transformer, text encoder), commit with a clear milestone message like \"VAE done\" to preserve progress.\n    - Once the full port is working, remove any loaded tensors or debug artifacts so no traces remain.\n4. **Deterministic validation**\n   - Create a deterministic MLX test (image or tensor) that locks the output.\n   - Run tests via `MFLUX_PRESERVE_TEST_OUTPUT=1 uv run <test command>`.\n   - If MLX OOMs on sensible inputs (e.g., 1024×1024), assume a likely porting mistake and re-check shapes or memory-heavy ops.\n5. **Post-test refactor (explicit step)**\n   - Review commits after the first deterministic test to capture refactoring preferences.\n   - Consolidate shared components into common modules.\n   - Remove debug paths and one-off schedulers once validated.\n   - Move configuration defaults into standard config/scheduler paths.\n    - Simplify and decompose large files into focused modules once behavior is locked.\n    - Prefer shared scheduler implementations when they already exist in mflux.\n    - Ensure CLIs register callbacks via `CallbackManager.register_callbacks(...)` so shared features like `--stepwise-image-output-dir` work; pass a `latent_creator` that supports `unpack_latents(...)`.\n    - Keep running the deterministic image test during refactors to avoid regressions.\n   - Align the variant class with recent ports (`flux2_klein`, `z_image`): `prompt_cache`, merged `_predict`, RoPE setup inside predict path, `_decode_latents` helper, no verbose comments/docstrings (see repo `RULE.md`).\n   - Strip dead scaffolding (e.g. unused gradient-checkpointing flags) once training/inference paths are stable.\n6. **Pre-merge polish (after core port works)**\n   - **diffusers sanity check**: run matched mflux + diffusers generations; use `mflux-debugging` latent injection if outputs disagree but you need to validate transformer/VAE.\n   - **Golden tests**: pick prompt/seed/settings that are stable on target CI hardware; update reference PNGs only after explicit approval (see `mflux-testing`).\n   - **img2img**: verify latent packing/normalization on the img2img path matches txt2img and training (especially when reusing a shared VAE from another model family). `pack_latents` must accept the 5D `(B, C, 1, H, W)` tensor that tiled VAE encode (`vae_encode_tiled`) returns — squeeze the singleton temporal axis first, as `flux2`/`fibo`/`z_image` latent creators do; a 4D-only unpack (or a bare passthrough `pack_latents`) breaks tiled img2img. This is reachable via `--low-ram`: `MemorySaver` sets `tiling_config = TilingConfig()` (`vae_encode_tiled=True`), so always test img2img with `--low-ram`, not just the default path (which is safe only because `VAEUtil.encode` squeezes 5D→4D when tiling is off).\n   - **Cross-model touch points**: list every file outside `models/<your_model>/`; justify shared changes (`memory_saver` tiling guard, shared VAE `tiling_config`, training `runner` wiring). Drop unrelated edits (e.g. personal `.gitignore` entries).\n   - **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 `du` on HF cache and/or `mflux-save` + `du -sh` for quantized sizes.\n   - **Training**: example JSON under `models/common/training/_example/`, un-ignore in `.gitignore`, fast unit tests for training-adapter preview defaults.\n   - Re-run `just lint`, `just test-fast`, then slow golden tests before merge.\n7. **Finalize**\n   - Re-run tests and basic perf checks after polish.\n   - Add CLI/pipeline defaults and completions later, once core output is stable.\n   - Ensure the model is wired into the standard surfaces:\n     - `ModelConfig` entry + aliases\n     - Thin model CLI entrypoint that uses shared parser/config/callback patterns and a command class with `validate`, `load` and `generate` (see [Command class](#command-class-validate-load-generate))\n     - README following the structure and tone of existing model READMEs\n     - Python API example that matches the CLI/defaults\n   - Document any new mapping rules, shape constraints, or tolerances.\n\n## Package layout (reference: `flux2`)\n\nUse `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.\n\n```\n{model}/\n  {model}_initializer.py\n  __init__.py                    # export variant + initializer\n  README.md\n  cli/\n    {model}_generate.py          # (+ edit/turbo CLIs when applicable)\n  latent_creator/\n    {model}_latent_creator.py\n  model/\n    {model}_text_encoder/        # prompt_encoder.py, tokenizer pieces, text_encoder.py\n    {model}_transformer/         # attention, blocks, rope, transformer.py (split files)\n    {model}_vae/                 # or reuse shared VAE (e.g. flux2_vae) — document in README\n    {model}_scheduler/           # only when not covered by models/common/schedulers\n  variants/\n    __init__.py                  # re-export public variant class(es)\n    txt2img/\n      __init__.py\n      {model}.py                 # e.g. flux2_klein.py, ideogram4.py\n    edit/                        # when the model supports image-conditioned generation\n      __init__.py\n      {model}_edit.py\n  weights/\n    __init__.py\n    {model}_weight_definition.py # components, download patterns, tokenizers\n    {model}_weight_mapping.py    # WeightTarget list / key transforms for base weights\n    {model}_lora_mapping.py      # LoRA key aliases (diffusers, PEFT, kohya) — when LoRA is supported\n  training_adapter/              # when mflux-train is supported\n    {model}_training_adapter.py\n```\n\n**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`.\n\n**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).\n\n**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`.\n\n**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.\n\n## Integration surfaces checklist (don’t forget)\n\nPast [closed PRs](https://github.com/mflux-community/mflux/pulls?q=is%3Apr+is%3Aclosed) show the same wiring gaps recurring on every new model. Use this as a **tick list** alongside the workflow above — not every row applies to every model (e.g. skip vision-encoder rows for txt2img-only), but scan it before opening a port PR.\n\n### Repo wiring (required for every new model family)\n\n| Surface | What to do |\n|---|---|\n| `pyproject.toml` | Register `mflux-generate-<model>` (and edit/turbo variants if separate) |\n| `ModelConfig` | Entry in `AVAILABLE_MODELS`: aliases, HF repo id, `num_train_steps`, guidance support, sigma shift, `transformer_overrides`, distilled vs base step defaults |\n| `models/common/resolution/model_revisions.py` | Pin every HF repo the model downloads (`model_name`, ControlNet, helper repos) to the full commit hash its golden references were generated with. `tests/resolution/test_model_revisions.py` fails for a registry repo without a pin. |\n| `scripts/ci_extract_models.py` | Add an `OVERLAY` row for every new `AVAILABLE_MODELS` key: taxonomy, CLI/tool commands, status, and quantization support. Use `EXTRA_ENTRIES` only for standalone tools with no `ModelConfig` entry. Run `just ci-extract` and confirm the model is present in `.ci_cache/models_mflux.json`. |\n| `cli/defaults/defaults.py` | `MODEL_INFERENCE_STEPS` (keyed by the canonical `AVAILABLE_MODELS` key — the `--model` choices derive from the registry, nothing to add there) |\n| `models/common/cli/save.py` | Route `mflux-save` to the **correct variant class** (txt2img vs edit vs turbo — wrong class silently drops weights; see [#405](https://github.com/mflux-community/mflux/pull/405)) |\n| Main `README.md` | Model table row + attribution line |\n| `src/mflux/models/<model>/README.md` | Examples aligned with Flux2-style layout; disk sizes measured (`du`, `mflux-save`) |\n| `src/mflux/assets/` | Hero/showcase image if other models have one (`git add -f` when `*.jpg` is gitignored) |\n\n### Weights, tokenizer, download scope\n\n| Surface | What to do |\n|---|---|\n| `*WeightDefinition` | `get_components()`, `get_download_patterns()`, `get_tokenizers()` — **only** list artifacts mflux actually loads |\n| Weight mapping | Explicit `WeightTarget` list; verify tensor names/shapes against HF cache blobs |\n| Tokenizer | Exercise local-path load, partial HF cache, and any special formats (protobuf, sentencepiece, etc.) — see [#383](https://github.com/mflux-community/mflux/pull/383), [#389](https://github.com/mflux-community/mflux/pull/389), [#390](https://github.com/mflux-community/mflux/pull/390) |\n| Optional reference components | Document in README what the upstream pipeline includes but mflux omits (extra encoders, preprocessors, etc.) |\n\n### LoRA\n\n| Surface | What to do |\n|---|---|\n| `*LoRAMapping` | Support **multiple export key conventions** (diffusers, PEFT `.default.weight`, kohya/`diffusion_model.*` aliases) — silent zero-key loads were fixed repeatedly ([#376](https://github.com/mflux-community/mflux/pull/376), [#374](https://github.com/mflux-community/mflux/pull/374), [#397](https://github.com/mflux-community/mflux/pull/397)) |\n| Tests | Fast tests that real community LoRA filenames map to non-zero keys |\n| Inference CLI | `--lora` via shared parser (no bespoke loader). `--lora-paths` / `--lora-scales` are deprecated. |\n\n### Inference CLI & shared features\n\n| Surface | What to do |\n|---|---|\n| Thin CLI | `build_parser()` with `CommandLineParser` + `CallbackManager.register_callbacks(...)` |\n| Command class | **Required.** Put the CLI work in `<Model>Command` with `validate`, `load`, `generate` and `latent_creator`. `main()` only calls these steps. See below. |\n| `DimensionResolver` | Use in generate/edit CLIs when width/height can be omitted (API/OpenWebUI paths) — [#378](https://github.com/mflux-community/mflux/pull/378) |\n| `latent_creator` | `pack_latents` / `unpack_latents`; img2img path must match txt2img normalization (BN, scale factor) |\n| `tiling_config` | If initializer sets custom tiling, ensure `MemorySaver` does not overwrite it |\n| Guidance defaults | Distilled vs base: match `ModelConfig`, CLI default, README, and training preview adapter |\n| `mflux-save` round-trip | Save quantized model → load from local path → generate; confirm `model.safetensors.index.json` if sharded |\n\n### Command class: validate, load, generate\n\nUse this pattern for every new generate CLI. Do not put the full flow in one `main()`. Plugins under `mflux.extras` call these steps. A CLI without them cannot support plugins. See `docs/plugins.md` and `docs/validate-load-generate.md`.\n\nCopy the structure of `src/mflux/models/qwen/cli/qwen_image_generate.py`:\n\n| Member | Rule |\n|---|---|\n| `latent_creator` | Class attribute. `main()` passes it to `CallbackManager.register_callbacks(...)`. |\n| `validate(args) -> ModelConfig` | Static. Do not load weights. Resolve `--model` with `ConfigResolution.resolve_restricted(...)`. If the command has rules for flag combinations, sizes or output formats, test them here and raise `ValueError`. |\n| `load(args) -> Model` | Static. Call `validate(args)` first. Then make the model with `quantize`, `model_path` and `**lora_init_kwargs_from_args(args)`. |\n| `generate(model, args, seed, prompt) -> GeneratedImage` | Static. Make one image for one seed and one prompt. Apply the command defaults here, for example guidance and `DimensionResolver`. A direct caller must get the same image as `main()`. Do not save the image. |\n\n`main()` only parses the arguments, calls `load`, registers the callbacks, calls `generate` for each seed and saves each image.\n\n### Training (if supported)\n\n| Surface | What to do |\n|---|---|\n| `training/runner.py` | Register `*TrainingAdapter`; handle `low_ram` / tiling like other models |\n| Example JSON | `models/common/training/_example/train_<model>.json` + `.gitignore` un-ignore |\n| Preview generation | Adapter should use canonical steps/guidance for distilled vs base (unit test this) |\n| Local `model_path` | Confirm `mflux-train` works with saved local weights — [#370](https://github.com/mflux-community/mflux/pull/370) |\n\n### Tests & CI\n\n| Surface | What to do |\n|---|---|\n| Slow golden test | `tests/image_generation/test_generate_image_<model>.py` + `reference_*.png` on CI hardware |\n| Fast tests | LoRA mapping, training-adapter preview defaults, argparser if new CLI flags |\n| `just ci-extract` | Required after changing `AVAILABLE_MODELS` or `OVERLAY`; verifies every registry key has CI-manifest metadata |\n| `just lint` / `just test-fast` | Before slow tests |\n\nWhen fixing a gap for model *N*, ask whether the same gap exists for other recent models and whether a **shared** fix belongs in `models/common/` (preferred over copy-paste per model).\n\n## Tooling expectations\n- Use `uv` for running scripts and tests: `uv run <command>`.\n- Prefer `uv run python -m <module>` for local modules.\n\n## Deliverables\n- Deterministic MLX test that verifies correctness.\n- Documented weight mapping, shape constraints, and any known tolerances.\n- Cleaned, shared components aligned with mflux style.\n- Standard mflux surfaces in place: config aliases, thin CLI with a `validate` / `load` / `generate` command class, and a README/examples pass aligned with the final behavior.\n",".cursor/skills/mflux-pr-docs/SKILL.md":"---\nname: mflux-pr-docs\ndescription: Write the PR body for the current mflux branch and show it to the developer for approval. Fills the What section, the release-note block and the Verification section of the PR template. Use when the developer asks to write, fill or update a PR description or a release note.\n---\n\n# mflux PR docs\n\nWrite the PR body for the current branch. The developer must approve the body before it goes to GitHub.\n\n## Inputs\n\n- The current branch. The base branch is `main`.\n- Optional: the PR number, if the PR is open.\n\n## Steps\n\n1. Collect the facts. Use only these sources:\n   - `git log --oneline main..HEAD`\n   - `git diff --stat main...HEAD`\n   - `git diff main...HEAD`\n   - If the PR is open: `gh pr view <n> --json title,body,closingIssuesReferences` and `gh pr checks <n>`.\n2. Copy `.github/pull_request_template.md` to `tmp-PR-content.md`. If `tmp-PR-content.md` exists, ask the developer before you replace it.\n   - Add this heading as the first line: `# Draft PR Content`.\n   - Add the line `Title: ` below the heading. Add an empty line after it.\n   - If the PR is open, put its title from step 1 after `Title: `.\n   - If the PR is open, `gh pr edit --body-file` replaces the existing body. Copy each existing section and link that the template does not have into `tmp-PR-content.md`. Get them from the `body` field of step 1. If you do not copy them, ask the developer to confirm before you discard them.\n3. Write the `What` section. Obey `pr-what-prompt.md` in this folder. Use the diff from step 1 if the PR is not open. Add `Fixes #<n>` for each linked issue.\n   - If the PR is not open, write the PR title after `Title: `. Use one short line that names the change.\n   - If the PR is open, keep its title. Change the title only if the developer asks.\n4. Write the release note. Obey `release-note-prompt.md` in this folder.\n   - Put the note on the lines below the opening fence. Do not put text on the fence line.\n   - Tell the developer which PR label the PR needs.\n5. Write the `Verification` section. List only the commands that ran, with the result of each command. If no command ran, write `TODO: add the commands that you ran.` Do not write a result that you did not see.\n6. Do not tick the boxes in the `Checklist` section. The developer ticks them.\n7. Examine the text that you wrote. Do not examine the template text.\n   - Apply the `asd-ste100` skill in STE-flavored mode.\n   - Put the text that you wrote in a temporary file. Do not put the `Title:` line in it. Run `python3 .cursor/skills/asd-ste100/scripts/ste-lint.py --disable synonym-rotation <file>`.\n   - Fix each hard violation.\n8. Run the CI check on `tmp-PR-content.md`. Fix `tmp-PR-content.md` until the check passes:\n   ```sh\n   python3 - tmp-PR-content.md <<'PY'\n   import re, sys\n   body = open(sys.argv[1], newline=\"\").read()\n   m = re.search(r\"^```release-note[ \\t\\r]*\\n(.*?)^```[ \\t\\r]*$\", body, re.DOTALL | re.IGNORECASE | re.MULTILINE)\n   sys.exit(0 if m and m.group(1).strip() else \"FAIL: no complete release-note block\")\n   PY\n   ```\n9. Ask the developer to approve the PR content:\n   - Open `tmp-PR-content.md` in the editor. Use `code tmp-PR-content.md` or `cursor tmp-PR-content.md`. If neither command works, give the developer the file path.\n   - Tell the developer to edit the file in the editor, or to ask for changes in the chat.\n   - Tell the developer to write `approve` in the chat when the content is ready.\n   - Do not continue until the developer writes `approve`.\n10. Read `tmp-PR-content.md` again after the developer approves it. The developer can edit the file before approval. Do step 8 again.\n    - Make sure that line 1 is `# Draft PR Content` and line 2 is the `Title:` line. Put them back if the developer moved them.\n    - Make sure that the `Title:` line has a title. If it is empty, ask the developer for the title. Write the title after `Title: ` in `tmp-PR-content.md`.\n11. Send the PR content to GitHub:\n    - If the PR is not open, push the branch first. Ask for permission before you push. Obey the `mflux-pr` skill.\n    - Run this block as one command. If the PR is open, replace the last line with `gh pr edit <n> --title \"$title\" --body-file tmp-PR-body.md`.\n      ```sh\n      title=\"$(awk 'NR <= 2 && sub(/^Title: */, \"\") { print; exit }' tmp-PR-content.md)\"\n      awk 'NR == 1 && /^# Draft PR Content$/ { next } NR == 2 && /^Title:/ { next } { print }' tmp-PR-content.md > tmp-PR-body.md\n      gh pr create --title \"$title\" --body-file tmp-PR-body.md\n      ```\n    - The shell reads the title from the file. Do not type the title into the command. Backticks and `$` in a typed title run as shell code.\n    - GitHub does not get the `# Draft PR Content` line or the `Title:` line. Other lines that start with `Title:` stay in the body.\n12. Delete `tmp-PR-content.md` and `tmp-PR-body.md`.\n\n## Rules\n\n- Do not invent facts, numbers or test results.\n- Do not change the code or the commits.\n- Do not use `gh pr create --body` or `--fill`. GitHub must get the body that you checked, without the two draft lines.\n- Keep the regex in step 8 the same as `.github/workflows/release-note.yml` and `_FENCE` in `src/mflux/release/release_notes.py`.\n",".cursor/skills/mflux-model-tiny-test/SKILL.md":"---\nname: mflux-model-tiny-test\ndescription: Write a hermetic \"tiny\" model-saving test for an mflux model — a fast twin of the slow save/load test that runs the real ModelSaver/WeightLoader/WeightApplier seam on real component classes at toy dimensions, with no downloads or image generation. Use when asked to \"make tiny test for <model>\".\n---\n# mflux tiny model-saving test\n\nA tiny test proves a model's quantized checkpoint survives a save/load roundtrip byte-for-byte, in about a second, without downloading anything. It builds the model's **real** component classes at toy dimensions and pushes them through the **real** save/load code path.\n\n## When to Use\n\n- You're asked to \"make tiny test for `<model>`\" or add a fast twin of a slow save/load test.\n- You ported a new model (see `mflux-model-porting`) and want cheap checkpoint coverage.\n\nRelated: `mflux-testing` for running the suite and golden-image rules.\n\n## Reference implementations\n\nRead these before writing a new one — they are the source of truth:\n\n- `tests/model_saving/tiny_checkpoint_helper.py` — the shared harness\n- `tests/model_saving/test_tiny_model_saving_ernie_image.py` — components take explicit kwargs\n- `tests/model_saving/test_tiny_model_saving_ideogram4.py` — components take a Config dataclass\n\nDo not trust code quoted in this skill over those files. The pattern landed as an RFC (PR #599, \"proposal + demo on 2 models\") and is expected to evolve.\n\n**Models that already have tiny tests:** `ernie_image`, `ideogram4`.\n\n## What you write\n\nOne file, no `src/` changes:\n\n```text\ntests/model_saving/test_tiny_model_saving_<model>.py\n```\n\nThe whole test is a single call into `TinyCheckpointRoundtrip`. The real work is figuring out how to build that model's components small. Match the two examples exactly:\n\n- class `TestTiny<Model>ModelSaving`\n- method `test_tiny_quantized_checkpoint_roundtrips_exactly`, decorated `@pytest.mark.fast`\n- a `@staticmethod _tiny_components()` returning the component dict\n- a comment naming the slow twin it mirrors\n\n## Instructions\n\n### 1. Read the weight definition — it is the contract\n\n```text\nsrc/mflux/models/<model>/weights/<model>_weight_definition.py\n```\n\n`get_components()` is authoritative: it gives the exact set of component **names** you must produce, and how many. While there, note two things:\n\n- **`quantization_group_size`** — a class attribute on the weight definition. Defaults to 64 but is not always 64 (`boogu` uses 32). Every tiny dimension must be a multiple of *this model's* value. Check with `grep -n \"quantization_group_size\" src/mflux/models/<model>/weights/*.py`.\n- **`skip_quantization=True`** on any component (`krea2` and `qwen` each have one). In production, `WeightApplier._quantize` honors this flag and leaves the component unquantized. **`TinyCheckpointRoundtrip._quantize` does not** — it calls `nn.quantize` on every saved component regardless of the flag, so a `skip_quantization` component comes out of the \"saved\" side quantized (with `scales`/`biases`) while the reloaded \"fresh\" side stays unquantized (no `scales`/`biases`). The helper's exact key-set comparison (`saved_weights.keys() == fresh_weights.keys()`) will then fail for that component. This is a real gap in `tiny_checkpoint_helper.py`, not a quirk to work around in the test file — if you're writing a tiny test for `krea2`, `qwen`, or any other model with a `skip_quantization` component, stop and fix `TinyCheckpointRoundtrip._quantize` to skip those components (mirroring `WeightApplier._quantize`) rather than special-casing it in the test.\n\n### 2. Find each component's real class and read its `__init__`\n\nDerive the shrink knobs from the actual constructor. Do not pattern-match one example — they differ deliberately: ERNIE's components take explicit kwargs (`hidden_size=`, `num_layers=`), Ideogram 4's transformer takes an `Ideogram4Config` dataclass.\n\nLook under `src/mflux/models/<model>/model/`. Shrink layer counts to 2, hidden and intermediate sizes to 128, head counts to 2, vocab to 128.\n\n### 3. Use `TinyVAEStandIn` for the VAE\n\nThe real VAEs are fixed-size (~170M param) architectures with no dimension knobs, so they cannot be shrunk. `ModelSaver`/`WeightLoader` treat every component as an opaque parameter tree, so the stand-in walks the identical code path. Don't spend a loop trying to shrink a real VAE.\n\n### 4. Respect interlocking dimension constraints\n\nDimensions are not independent. Look for constraints in the component's `__init__` and attention/rope code:\n\n- `rope_axes_dim` must **sum to** `head_dim` (ERNIE: `[16, 24, 24]` → 64)\n- `head_dim` must be consistent with `hidden_size / num_attention_heads`\n- `num_key_value_heads` must divide `num_attention_heads`\n\n### 5. Choose `tensors_per_shard`\n\nStart with `tensors_per_shard=8`. It forces shard boundaries so the `index.json` / `weight_map` multi-shard paths get exercised — the production size-based split (≥1 GB) never shards test-sized tensors.\n\nThe helper asserts `len(shard_files) > component_count`. If a model's tiny components have too few parameter tensors to clear that bar, **lower the number until it passes** — do not drop the argument, that silently removes multi-shard coverage.\n\n### 6. Name the slow twin — after checking it exists\n\nThe examples carry `Fast twin of tests/model_saving/test_model_saving_<model>.py`. Several models have weight definitions but **no** slow save test. Verify with `ls tests/model_saving/` and adapt the comment rather than pointing at a file that isn't there.\n\n## Constraints that will bite you\n\n- **Key the dict by `component.name`, not `model_attr`.** The helper does a bare `components[component.name]` lookup, so a missing or misnamed key is a raw `KeyError`, not a helpful message. Most common first-try failure. Every component in `get_components()` needs an entry.\n- **Do not collapse the two seeds.** The harness randomizes saved components with `seed=0` and fresh ones with `seed=1`. That difference is exactly what makes the final equality assertion prove values came off disk. Unifying them leaves the test green and meaningless.\n- **Do not edit `WeightDefinitionType`.** The helper types `weight_definition` as plain `type` on purpose — that `TYPE_CHECKING` union has drifted and omits several definitions. Widening a src type alias is out of scope; see the helper's comment.\n- **Do not modify `src/`.** A tiny test is a test-only addition. If a model appears to genuinely require a src change to be testable, stop and report that rather than making it.\n\n## Verify\n\n```sh\nuv run --no-sync python -m pytest tests/model_saving/test_tiny_model_saving_<model>.py -v\n```\n\nThen confirm nothing else broke with `just test-fast` (see `mflux-testing`).\n\nThe test should run in roughly a second. If it takes noticeably longer, or the network is touched, something is loading a real checkpoint — investigate rather than accepting it.\n\n### Do you need to check that quantization actually happened?\n\n**No.** Verified empirically: MLX raises loudly on a bad dimension rather than silently skipping —\n\n```text\nValueError: [quantize] The last dimension of the matrix needs to be divisible\nby the quantization group size 64. However the provided matrix has shape (100,100)\n```\n\nso a dimension that isn't a clean multiple of the group size fails the test outright. It cannot leave a green-but-weak twin.\n\nRelatedly, when inspecting a quantized tree you'll see some `.weight` entries with no matching `.scales`. Confirmed benign: those are 1-D norm weights and `Conv2d` layers, which `nn.quantize` correctly leaves alone. Only `Linear`-style layers quantize. Don't chase these.\n\n## Troubleshooting\n\n| Symptom | Cause |\n|---|---|\n| `KeyError: '<name>'` | `_tiny_components()` is missing a component, or keyed it by `model_attr` instead of `name` |\n| `ValueError: [quantize] ... divisible by the quantization group size` | A dimension isn't a multiple of this model's `quantization_group_size` |\n| `assert len(shard_files) > component_count` | Lower `tensors_per_shard` (step 5) |\n| Values differ after reload | A real save/load bug — report it, do not weaken the assertion |\n| Shape assertion inside a component's `__init__`/forward | An interlocking dimension constraint (step 4) |\n",".cursor/skills/mflux-pr/SKILL.md":"---\nname: mflux-pr\ndescription: Make a clean PR in mflux (inspect diff, quick verification, commit, push, open PR) using repo conventions.\n---\n# mflux pull request workflow\n\n## When to Use\n\n- You’re about to open a PR (or want a safe sequence to do it).\n\n## Instructions\n\n- If you run tests as part of PR hygiene, prefer fast tests first:\n  - `just test-fast`\n- Keep commits focused and messages consistent with repo history.\n- If the PR changes CLI defaults, public APIs, or model behavior, check for README/example drift before opening the PR.\n- **Always ask for permission** before pushing to the remote repository.\n- If `gh` isn’t available, fall back to the GitHub web UI (or stop and ask).\n\n## PR body and release note (required)\n\nThe `release-note` CI check fails the PR if the body has no complete release-note block.\n\nUse the `mflux-pr-docs` skill to write the PR body. That skill writes the `What` section and the release-note block, runs the CI check, and gets the approval of the developer.\n\nIf the check fails on an open PR, use the `mflux-pr-docs` skill again. It edits the body of the open PR. The check runs again on an edit. You do not need a new commit.\n\n## Pre-merge checklist (model port PRs)\n\nUse after the core port lands and you are polishing for merge. For the full **integration surfaces** tick list (LoRA key formats, save routing, tokenizer edge cases, etc. learned from past closed PRs), see `mflux-model-porting` → *Integration surfaces checklist*.\n\n### Correctness\n\n1. `just lint` and `just test-fast`\n2. `just ci-extract` after changing `AVAILABLE_MODELS` or `scripts/ci_extract_models.py`\n3. Slow golden tests for the new model:\n   ```sh\n   MFLUX_PRESERVE_TEST_OUTPUT=1 uv run pytest tests/image_generation/test_generate_image_<model>.py -m slow -v\n   ```\n4. Optional but high-signal: diffusers side-by-side + latent injection (`mflux-debugging`, `mflux-manual-testing`)\n\n### Cross-model diff audit\n\nList files changed outside `src/mflux/models/<model>/`:\n\n| Category | Expected |\n|---|---|\n| `pyproject.toml`, `cli/defaults/defaults.py`, `ModelConfig`, `mflux-save` routing | Required wiring |\n| `scripts/ci_extract_models.py` `OVERLAY` / `EXTRA_ENTRIES` | Required CI-manifest wiring for every new model key or standalone tool |\n| `README.md` table + attribution | Required |\n| Training `runner.py`, example JSON, `.gitignore` JSON exceptions | If training supported |\n| Shared VAE/callback/training one-liners | Only if required; document blast radius in PR |\n| Personal `.gitignore`, unrelated formatting | **Remove** |\n\nVerify quantized README disk claims with measurement:\n```sh\ndu -sh ~/.cache/huggingface/hub/models--<org>--<Model>*\nmflux-save --model <alias> --quantize 8 --path /tmp/model-q8 && du -sh /tmp/model-q8\n```\n\n### Docs / examples\n\n- Model README matches a recent port (e.g. Flux2): hero image, turbo + base CLI, feature section, disk warning, Notes, Training.\n- Main `README.md` model table row (correct release date).\n- Showcase asset if other models have one (`src/mflux/assets/`; may need `git add -f` when `*.jpg` is gitignored).\n\n### PR description callouts\n\n- Shared code touched and why (shared VAE, callbacks, training runner, etc.).\n- Reference pipeline features intentionally **not** ported (optional preprocessors, extra encoders, components omitted from mflux weight downloads).\n- Known non-parity with diffusers (RNG, sigma schedule, optional modules) if golden tests lock mflux-native sampling.\n\n",".cursor/skills/mflux-release/SKILL.md":"---\nname: mflux-release\ndescription: Prepare a release in mflux (version bump + uv lock; release notes are harvested from PR release-note blocks and live in GitHub Releases). Use when preparing a release branch or release PR.\n---\n# mflux release prep\n\nReleases are prepared in-repo; tagging/publishing is handled by GitHub Actions\n(`release.yml`, dispatched from main with the `publish` confirmation).\n\n## How notes work now (#685)\n\n- Every PR carries a fenced ` ```release-note ` block in its body (CI enforces it;\n  every PR gets a note, and contributors do not write `none`). That block is the only source of release notes.\n- On dispatch, the ungated `draft-notes` job harvests the blocks for every PR whose\n  squash commit is in `previous-tag..HEAD` and fills a DRAFT GitHub release, grouped\n  by label.\n- Whoever approves the `pypi` deployment reads and edits that draft (fixing any\n  `[needs edit]` lines, adding contributor thanks if wanted); the gated job publishes\n  it exactly as edited. A re-dispatch never overwrites an existing draft; delete the\n  draft to re-harvest.\n- There is no `CHANGELOG.md`: the notes live in GitHub Releases (https://github.com/mflux-community/mflux/releases).\n\n## Release-prep PR checklist\n\n- Bump version in `pyproject.toml`\n- Update lockfile: `uv lock`\n- Release-note block of the prep PR itself: a note for contributors, for example `Prepare the <version> release.` Give the PR the `chore` label.\n- Prefer one commit named `release: prepare <version>`\n- Sanity checks (optional unless requested): `just test-fast`, `just build`\n- Do not tag releases locally unless explicitly requested (normally handled by CI)\n",".cursor/skills/mflux-testing/SKILL.md":"---\nname: mflux-testing\ndescription: Run tests in mflux (fast/slow/full), preserve image outputs, and handle golden image diffs safely.\n---\n# mflux testing\n\nThis repo uses pytest with image-producing tests. Always preserve outputs for inspection and **never** update reference images unless explicitly asked.\n\n## When to Use\n\n- You need to run tests (fast/slow/full) or debug failing tests.\n- There are image/golden mismatches and you need to report paths/output for review.\n\n## Instructions\n\n- Prefer the justfile test recipes:\n  - `just test-fast` (fast tests, no image generation)\n  - `just test-slow` (slow tests, image generation)\n  - `just test` (default selection, skips slow model tests)\n  - `just test-all` (all except high-memory tests; slow tests download model weights)\n- Always keep `MFLUX_PRESERVE_TEST_OUTPUT=1` on test runs (already built into the justfile test recipes).\n- If a change affects defaults, config resolution, metadata fields, or CLI behavior, add or update tests that cover the changed behavior directly instead of relying only on manual verification.\n- If tests fail:\n  - Summarize the failing test names and the key assertion output.\n  - Point to any generated images/artifacts on disk for manual review.\n- Do **not** regenerate/replace reference (“golden”) images unless the user explicitly requests it.\n\n## Updating golden images (new model or hardware refresh)\n\nGolden tests compare generated PNGs to `tests/resources/reference_*.png` (typically 15% mismatch threshold).\n\n**When to update** (only with explicit user approval):\n- After validating the port on target hardware (CI Mac) via slow tests with `MFLUX_PRESERVE_TEST_OUTPUT=1`\n- After choosing a stable prompt/seed/settings via diffusers comparison and/or latent-injection confidence (`mflux-debugging`)\n- When old references used a bad prompt (e.g. ambiguous subject) or wrong seed for mflux’s RNG\n\n**Workflow**:\n1. Run slow test → inspect `tests/resources/output_*.png` vs `reference_*.png`\n2. If output is correct but reference is stale, re-run generation with same test parameters and replace reference PNGs\n3. Commit test + reference images together with a clear message (e.g. `test(<model>): update golden images for local hardware`)\n\n**Important**: Golden tests lock **mflux-native** sampling (`mx.random` + mflux schedulers), not diffusers pixel parity. A good diffusers side-by-side or injected-latent run builds confidence in the model code; the golden still reflects mflux’s full recipe on CI hardware.\n\n## Manual validation (config resolution + local model paths)\n\nUse when a change touches model config resolution, `mflux-save`, or the model’s generate CLI, or when a PR fixes local model-path handling for the model under investigation. Refer to the `mflux-cli` skill to find the correct generate command for the model you are testing.\n\n- Run a local-path quantize/save:\n  - Use the `mflux-cli` skill to look up the correct command and flags.\n  - Verify CLI usage with the command’s `--help` before running it.\n  - Save to a known location (e.g., Desktop) to make follow-up steps explicit.\n- Run generation from the saved model using the correct model-specific generate CLI:\n  - Use the `mflux-cli` skill to find the generate command and required flags.\n  - Verify CLI usage with the command’s `--help` before running it.\n- If the model has multiple size variants, repeat the above for each variant to confirm the correct overrides are applied.\n- Do not commit output artifacts; delete or leave them untracked.\n",".cursor/skills/asd-ste100/SKILL.md":"---\nname: asd-ste100\ndescription: \"Use when English text must be parsed without a human to resolve ambiguity — tool descriptions, error messages, inter-agent instructions, system prompts, status reports — and misreading has a real cost, or when text reads as dense, hedged, or easy to misparse. Triggers: disambiguate, STE100 rewrite, apply Simplified Technical English, plain-language rewrite, controlled-language rewrite, rewrite so an agent cannot misread this. Not for creative or marketing copy.\"\nmetadata:\n  version: 0.4.0\n---\n\n# Simplified Technical English (ASD-STE100)\n\nASD-STE100 is a controlled-language standard built by the aerospace and defense industry (ASD, the AeroSpace and Defense Industries Association of Europe) to stop maintenance technicians from misreading English instructions. The standard removes the two biggest sources of misreading: words with more than one meaning, and sentences with more than one possible structure.\n\nThis skill borrows that same discipline for a different reader: an **AI agent or a downstream system** that has to parse an English string — an error message, a tool description, an inter-agent instruction, a status report — without a human in the loop to resolve ambiguity. If a maintenance technician can misread \"close the valve\" as an adjective (\"the valve that is near\") instead of a command, so can a language model.\n\n## When to Use This Skill\n\n- An agent's output (explanation, instruction, log message, tool description) reads as dense, jargon-heavy, or ambiguous.\n- Text will be consumed by another agent, a translation pipeline, or a non-native English reader, and misparsing has a real cost.\n- You are writing a prompt, system message, or tool description and want to remove ambiguity before a model ever sees it.\n- You want a **before/after** comparison showing exactly which rule was violated and how the rewrite fixes it. Ask for it — the default output is the rewritten text alone (see Output Format).\n\nThis skill is not for creative or marketing copy — STE is deliberately flat and literal. Do not apply it to text where voice, nuance, or persuasion is the point.\n\n## Two Modes\n\nPick a mode before rewriting. If the user does not say which, infer it from the text type. Keep the choice internal unless the user asks for the rule table (see Output Format).\n\n**Strict** — procedures, error messages, tool and function descriptions, inter-agent instructions, safety text. Anywhere a wrong reading has a cost. Apply every rule below, including the hard length caps and one-word-one-meaning discipline.\n\n**STE-flavored** — READMEs, PR descriptions, changelogs, explanatory prose. Apply the structural rules in full and treat the lexical rules as advisory (see Core Rewrite Rules for that split). In practice that means keeping the sentence length caps, active voice, simple tenses, no phrasal verbs, no semicolons, no nominalization and no marketing adjectives, while dropping the one-word-one-meaning lockdown: prose needs some range, and a strict rewrite of prose reads as a personality transplant rather than a clarification.\n\nThe two modes and the structural/lexical split are the same distinction seen from two directions. The split says which rules this skill can verify without ASD's dictionary. The modes say which of them to enforce for a given kind of text.\n\n## Source and Scope\n\nThis skill encodes the **rule categories** of ASD-STE100 Issue 9 (Jan 2025): 53 writing rules across 9 sections covering word choice, grammar, sentence structure, and style, backed by a dictionary of ~900 approved words (one meaning, one part of speech each) and ~1,200 words to avoid with suggested replacements. See `references/writing-rules.md` for the full rule summary and citations.\n\nIt does **not** reproduce ASD's ~900-word approved dictionary verbatim. ASD-STE100 is free to obtain, but it is not free to redistribute: Issue 9, page 2 states that \"no reproduction or publication of it, in whole or in part, shall be made without the written authority of an officer of ASD,\" and grants free reproduction rights only to eight listed categories (ASD/AIA/AIAC member associations and their member companies and customers, member-state defence ministries, A4A, airworthiness authorities, and universities and research institutes for educational purposes). This project is in none of them, so the dictionary stays out of this repo.\n\nInstead, this skill applies the *underlying principle* (pick the plainest, most common word available and use it the same way every time) rather than checking against a fixed word list. When exact ASD-approved wording matters (e.g. actual aircraft maintenance documentation), get the standard and check word-by-word against the real dictionary. Request it from the [official downloads page](https://www.asd-ste100.org/STE_downloads.html) — note that this is a request form that emails you a link, not a direct download.\n\n## Core Rewrite Rules\n\nSTE's rules divide into two kinds, and this skill can only fully deliver one of them. **Structural rules** are self-contained: they describe sentence shape, and you can apply them from the description alone. **Lexical rules** are defined entirely by the official ~900-word dictionary, which this skill deliberately does not reproduce (see Source and Scope). Without that dictionary, the lexical rules degrade from a checkable standard into a preference for plain words.\n\nApply the structural rules with confidence. Apply the lexical rules as a direction of travel, and say so in your output rather than implying dictionary compliance you cannot verify.\n\n### Structural rules — apply these\n\n| Rule | Do | Don't |\n|---|---|---|\n| Active voice | \"The agent deletes the file.\" | \"The file is deleted (by the agent).\" — unless the actor is genuinely unknown or irrelevant |\n| No phrasal verbs (Rule 9.3) | \"Remove the panel.\" / \"Start the job.\" | \"Take off the panel.\" / \"Spin up the job.\" — a two-word verb has meanings the parts do not predict |\n| One instruction per sentence | \"Open the file. Read line 3.\" | \"Open the file and read line 3, then check if it matches.\" |\n| Sentence length | ≤20 words for instructions/procedures, ≤25 words for descriptions | Long compound/subordinate-clause sentences |\n| No semicolons (Rule 8.1) | Split into separate sentences | Any semicolon at all — STE bans the mark outright, not only as a clause join. (Rule 8.1 permits every other standard punctuation mark. The em dash is *not* banned by STE, though it often signals a sentence that should be split.) |\n| Noun clusters | ≤3 words stacked as a noun phrase (\"fuel pump valve\") | 4+ word noun stacks (\"high pressure fuel pump inlet valve assembly\") |\n| No ellipsis | Keep the subject, verb, and article explicit even if it reads longer | Drop words to save space (\"Files not backed up will be lost\" → ambiguous which files) |\n| Keep modality | \"The request **may have** failed.\" stays \"may have\" | Promote a hedge to a fact (\"The request failed.\") or invent a certainty the source did not state |\n| Paragraph limits | One topic per paragraph, ≤6 sentences | Multi-topic paragraphs |\n| Lists for sequences | Use a numbered or bulleted list for 3+ steps or conditions | Bury a sequence inside one prose sentence |\n\n### Lexical rules — direction of travel only\n\n| Rule | Do | Don't | Why it is weaker here |\n|---|---|---|---|\n| One word, one meaning | Pick one verb for one action and reuse it every time (e.g. always \"check\", never mix \"check\"/\"verify\"/\"confirm\" for the same action) | Rotate synonyms for the same idea across a document | Consistency within a document is checkable. Which word is the *approved* one is not, without the dictionary. |\n| One part of speech per word | \"Apply oil to the valve\" (oil = noun) | \"Oil the valve\" (oil = verb) | Whether \"oil\" is approved as a noun only is a dictionary fact. Prefer the noun form when both read equally well. Do not claim compliance. |\n| Verb, not noun (Rule 3.7) | \"Analyze the log.\" | \"Perform an analysis of the log.\" — a noun form of an action makes the sentence longer and hides who acts | Rule 3.7 says \"use an **approved** verb to describe an action.\" Preferring the verb form is safe to apply anywhere. Knowing which verb is the approved one needs the dictionary. |\n| Domain terms | Keep necessary technical nouns/verbs, but define them once if not common English (STE allows a project-specific glossary beyond its base dictionary) | Use jargon without ever defining it | The glossary allowance is real STE, but the base dictionary it extends is absent. |\n\n### Simple tenses — apply with one exception\n\nSTE permits infinitive, imperative, simple present, simple past, simple future, and past participle as adjective. It excludes present perfect and other compound forms: \"we received the report\", not \"we have received the report\".\n\nAircraft manuals never need present perfect, so the exclusion costs the standard nothing. Other text is not always so lucky. \"The job has completed\" (and its output is available now) and \"the job completed\" (at some past point) are different statements, and status text frequently needs the first. **Where the compound form carries information the simple form cannot — current relevance, or a hedge as in \"may have failed\" — keep it and flag the departure.** Elsewhere, follow the rule.\n\n## Scan Checklist\n\nThese six habits cover most of what makes machine-written English hard to parse. Each one is mechanical: you can point at the exact word or punctuation mark that breaks the rule, with no judgment call. Scan for all six before you rewrite anything.\n\n1. **Synonym rotation** — the same thing gets several names in one document (\"the user\", \"the customer\", \"the client\"). The reader cannot tell whether they are one thing or three. Fix: pick one name, use it every time.\n2. **Hedge stacking** — helper verbs and qualifiers pile up until the sentence asserts nothing (\"it is important to note that this may potentially help to improve\"). Fix: state the claim, or delete it.\n3. **Nominalization** — an action frozen into a noun (\"perform an analysis of\", \"provides assistance to\"). Fix: use the verb (\"analyze\", \"helps\").\n4. **Marketing adjectives** — words that claim quality instead of showing it: seamless, robust, powerful, cutting-edge, effortless, blazing-fast. Fix: delete, or replace with the measurement that earns the claim.\n5. **Run-on sentences** — several ideas joined by semicolons or em dashes. Fix: one idea per sentence.\n6. **Soft phrasal verbs** — spin up, reach out, dive into, kick off. Fix: use the single plain verb (start, contact, read, begin).\n\n## Process\n\n1. Pick the mode (Strict or STE-flavored). Say which only when the user asked for the rule table — see Output Format.\n2. Read the input text once for meaning — do not start rewriting before you understand what it must still say afterward.\n3. Walk it sentence by sentence. Flag every rule violation from the Core Rewrite Rules tables and every habit from the Scan Checklist. In STE-flavored mode, flag the lexical rules but do not enforce them. For a mechanical first pass over the structural rules, run `scripts/ste-lint.py` (stdin or file args, `--json` for structured output); it checks semicolons, sentence length, phrasal verbs, nominalization, marketing adjectives, synonym rotation, dangling-conjunction in supported list items, passive voice, and compound tenses, and by design never flags hedges or modality. `--baseline N` tolerates N hard violations (for adopting on existing docs); `--disable rule1,rule2` silences named rules.\n4. Rewrite each flagged sentence to fix the violation while preserving the original meaning exactly. If a rewrite would drop necessary precision (a safety condition, a scope qualifier, a number), keep the longer phrasing and flag it instead of silently simplifying.\n   - **Check modality before you commit to a rewrite.** Hedges (\"may\", \"could\", \"sometimes\", \"is likely to\") carry the author's confidence, and confidence is content. A shorter sentence that upgrades a hedge to a fact is not a simplification — it is a different claim. This is the most common way a well-intentioned STE rewrite goes wrong, because hedges are exactly what a length cap tempts you to cut.\n   - Never add a fact the source did not state. A rewrite that reads better because it supplies a cause, a frequency, or a mechanism has stopped being a rewrite.\n5. Output the rewritten text (see Output Format). Keep the mode choice and the rule analysis internal unless the user asked to see them.\n6. If the input already complies, say so — do not force changes onto compliant text.\n\n## Output Format\n\n**Default: the rewritten text, and nothing else.** Most callers want a result they can paste straight into a tool description, an error string, or a prompt. Print the simplified text on its own. Do not add a preamble about this skill, a mode announcement, a violation count, a summary of what changed, a rule table, or a closing offer to explain further.\n\nThe one permitted addition: if step 4 kept a longer phrasing on purpose, add a single line after the text, prefixed `Kept as-is:`, naming the phrase and the precision that would have been lost. Omit the line when there is nothing to report.\n\n**On request: the rule table.** When the user asks to see the reasoning — \"show the diff\", \"which rules did it break\", \"explain the changes\", \"before/after\" — output this table instead:\n\n```markdown\n| Rule violated | Original | Simplified |\n|---|---|---|\n| Present perfect tense | \"We have received your request.\" | \"We received your request.\" |\n| Noun cluster (4+ words) | \"the agent task queue priority handler\" | \"the handler that sets task-queue priority\" |\n\nMode: Strict. 7 violations found.\n```\n\nFollow the table with a one-line note on anything you deliberately did **not** simplify, and why (usually: simplifying would lose required precision).\n\n## Boundaries\n\n**Will:**\n- Rewrite ambiguous or dense English into short, single-meaning, active-voice sentences.\n- Return the rewritten text alone by default, and name the rules it applied when the user asks.\n- Preserve every fact, condition, and scope qualifier in the original.\n- Preserve the strength of every hedge, and add no claim the source did not make.\n- Suggest a one-line glossary entry for domain terms that must stay.\n\n**Will not:**\n- Reproduce ASD's official ~900-word dictionary as if it were memorized verbatim — always treat the official download as the source of truth for exact approved wording.\n- Simplify creative, marketing, or persuasive copy where voice and nuance are the point.\n- Silently drop a safety condition, exception, or scope qualifier to shorten a sentence — it will flag the trade-off instead.\n- Convert \"may have failed\" into \"failed\", or \"could be caused by X\" into \"X is the cause\" — losing a hedge changes the claim.\n- Guarantee an aerospace/defense-grade STE-compliant document. This is a general-purpose clarity tool inspired by STE, not a certified STE authoring tool.\n- Make weak content true or useful. STE fixes the *form* of a text, not its substance. A hollow paragraph rewritten under these rules becomes a clean, short, well-punctuated hollow paragraph. If the text has nothing to say, no rewrite fixes that — say so instead of polishing it.\n- Shorten past the point of clarity. Cutting words is not the goal. Removing ambiguity is the goal. Past a certain point compression starts costing the reader time rather than saving it, so stop when the sentence is unambiguous, not when it is shortest.\n\n## Additional Resources\n\n- **`references/writing-rules.md`** — fuller summary of the 9 rule sections and dictionary structure, with citations to the official standard and secondary sources.\n- **`examples/before-after.md`** — worked examples, including official STE examples and agent-output examples built for this skill.\n- **`scripts/ste-lint.py`** — deterministic, stdlib-only linter for the structural rules, including dangling-conjunction in supported list items, plus a synonym-rotation check (one word, one meaning) scoped per file. Exit 1 when hard violations exceed `--baseline` (default 0); advisory findings (passive voice, compound tenses) never fail the run; `--disable` silences named rules. It never flags hedges or modality: those are content, not style, and `--selftest` asserts that \"may have failed\" passes clean.\n",".cursor/skills/mflux-manual-testing/SKILL.md":"---\nname: mflux-manual-testing\ndescription: Manually validate mflux CLIs by exercising the changed paths and reviewing output images/artifacts.\n---\n# mflux manual testing\n\nSome regressions (especially in CLIs and image IO) are easiest to catch by running the commands and visually inspecting outputs. This skill provides a lightweight, change-driven manual test checklist.\n\n## When to Use\n\n- You changed any CLI entrypoint(s) under `src/mflux/models/**/cli/`.\n- You touched callbacks (e.g. stepwise output, memory saver) or metadata/image saving.\n- Tests are green but you want confidence in real command usage.\n\n## Strategy (change-driven)\n\n- Identify what changed on your branch (new flags, default behavior changes, new callbacks, new models).\n- Only run manual checks for the touched areas; don’t try to exercise every CLI.\n- Prefer 1–2 seeds and a small step count (e.g. 4) for fast iteration, unless the change affects convergence/quality.\n- Before manual CLI testing, **reinstall the local tool executables** so you’re testing the latest code:\n\n```bash\nuv tool install --force --editable --reinstall .\n```\n\n## Core CLI checks (pick what’s relevant)\n\n- **Basic generation**: run the CLI once with a representative prompt and confirm the output is not “all noise”.\n- **Model saving** (if relevant): if you touched weight loading/saving or model definitions, run `mflux-save` for the affected model(s) and verify:\n  - the output directory is created\n  - the command completes without missing-file errors\n- **Run from disk** (if relevant): if you touched save/load paths or model resolution, generate from a locally saved model directory by passing `--model /full/path/to/saved-model` and confirm it runs and produces a sane image.\n- **Stepwise outputs** (if relevant): run with `--stepwise-image-output-dir` and confirm:\n  - step images are written for each step\n  - the final step image matches the final output image qualitatively\n  - the composite image is created\n- **Low-RAM path** (if relevant): run with `--low-ram` and confirm:\n  - generation completes\n  - output quality is sane (no unexpected all-noise output)\n- **Metadata** (if relevant): run with `--make-conf` and confirm that the CLI writes the `.metadata.json` sidecar and that it looks consistent.\n\n## Output review (human-in-the-loop)\n\n- Always point the human reviewer at:\n  - the final output image path\n  - any stepwise directory / composites\n  - any metadata JSON files\n- Ask the human to visually confirm “looks correct” rather than attempting pixel-perfect parity manually.\n\n## diffusers reference comparison (new model ports)\n\nmflux does not install diffusers; use a sibling clone (commonly `../diffusers` on Desktop).\n\n**When**: validating a new MLX port before merge, or when golden tests / visuals look wrong.\n\n**Match settings**: same prompt, width, height, seed, steps, guidance. For fair speed comparisons, match precision (mflux bf16 vs diffusers bf16, not `-q 8` vs bf16).\n\n**diffusers setup tips** (read the reference pipeline first):\n- Compare `model_index.json` / `from_pretrained` kwargs with mflux `get_download_patterns()` — disable or pass `None` for components mflux does not load\n- `local_files_only=True` / `HF_HUB_OFFLINE=1` to use cache and surface missing files early\n- Distilled vs base variants are often the same pipeline class with different checkpoint + steps/guidance\n\n**Run both**:\n```sh\n# mflux\nuv run mflux-generate-<model> --prompt \"...\" --width 640 --height 368 --seed 7 --steps 8 --guidance 1.0 --output /tmp/mflux.png\n\n# diffusers (from diffusers repo)\ncd ../diffusers && HF_HUB_OFFLINE=1 uv run python -c \"...\"  # inline script; see mflux-debugging\n```\n\n**If visuals differ**: do not assume the port is broken. Run the **latent injection** workflow in `mflux-debugging` to separate (a) transformer/VAE quality from (b) RNG/scheduler differences.\n\nSave comparison PNGs to explicit paths; report `/usr/bin/time -p` totals. Do not commit comparison artifacts.\n\n## Notes\n\n- If the installed `uv tool` executable behaves differently from `uv run python -m ...`, prefer the local module run to isolate environment/tooling issues.\n- If you need to reinstall the local tool executables, see the repo rules for the current recommended command.\n\n",".cursor/skills/mflux-debugging/SKILL.md":"---\nname: mflux-debugging\ndescription: Debug MLX ports by comparing against a PyTorch/diffusers reference via exported tensors/images (export-then-compare).\n---\n# mflux debugging (MLX parity vs PyTorch/diffusers)\n\nUse this skill when you are porting a model to MLX and need to **prove numerical parity** (or isolate where it diverges) versus a **PyTorch reference implementation** (often from diffusers).\n\nThis skill defaults to **export-then-compare**:\n- Run the reference once and **export deterministic artifacts** (tensors + optional images).\n- Load those artifacts in MLX and compare with clear thresholds.\n\n## When to Use\n\n- You suspect a port mismatch (wrong shapes/layout, RoPE, scheduler math, dtype casting, etc).\n- You want a repeatable workflow to narrow down the first layer/block where outputs diverge.\n- You need evidence of correctness before refactoring (see `mflux-model-porting`).\n\n## Ground Rules (repo norms)\n\n- Use `uv` to run Python: `uv run python -m ...`\n- If you run pytest, preserve outputs: `MFLUX_PRESERVE_TEST_OUTPUT=1` (see `mflux-testing` and the justfile test recipes).\n- Do **not** update or replace reference (“golden”) images unless explicitly asked.\n- Debug artifacts (tensor dumps) should live in a local folder and **must not be committed** unless explicitly asked.\n- If you need the broader porting workflow (milestones, ordering, when to refactor), follow `mflux-model-porting`.\n- **RNG warning**: PyTorch and MLX RNGs are different. Matching the same integer `seed` is not enough for parity—export the *exact* initial noise/latents from the reference and load them in MLX.\n- Practical setup: the PyTorch reference repo (often `diffusers/`) and `mflux/` are frequently **next to each other** on disk (e.g. both on your Desktop). Use absolute paths when in doubt.\n\n## Default Workflow (export-then-compare)\n\n### Preferred workflow: two tiny scripts + inline dumps\n\nFor day-to-day debugging, prefer a **minimal paired repro**:\n- One simple script in the reference repo (often `diffusers/`), e.g. `diffusers/flux2_klein_edit_debug.py`\n- One simple script in `mflux/`, e.g. `mflux/flux2_klein_edit_debug.py`\n\nKeep them “boring”: hardcoded variables, no cli, no framework, and just a few `np.savez(...)` / `mx.save(...)` lines at the right spot.\n\nThe key trick for RNG parity:\n- In the reference script, **compute latents once**, save them, then **pass them back into the pipeline** (`latents=...`) so the run definitely uses the dumped tensor.\n- In rare cases where a tensor needs to be saved from within a loop, make sure its name reflects the loop conditions (e.g the 4th noise predcition in a 10 step loop etc).\n- In the MLX script, **load that same latents file** and feed it into the MLX run (do not rely on matching integer seeds).\n\n### 1) Pick a single deterministic repro\n\n- Fix **seed(s)**, **prompt(s)**, **height/width**, **steps**, **guidance**, and any **input image** paths.\n- Keep the first repro small if possible (fewer steps, smaller resolution) to iterate quickly.\n\n### 2) Decide your checkpoints (what to dump)\n\nStart coarse, then narrow:\n- **VAE**: packed latents before decode; optional intermediate activations for one block if needed.\n- **Transformer**: hidden states at entry/exit of the model, then per-block (or every N blocks), then inside attention/MLP.\n- **Text encoder**: token ids + attention mask, embeddings output, then per-layer hidden states if needed.\n- **Scheduler**: timesteps/sigmas/alphas and the predicted noise/velocity per step.\n\nTip: work “backwards from pixels” like `mflux-model-porting` suggests: validate VAE decode first with exported latents, then the diffusion/transformer loop, then text encoder.\n\n### 3) Export artifacts from the PyTorch reference (no logic changes)\n\nCreate a run directory like:\n- `./debug_artifacts/<run_id>/ref/`\n\nExport with one of these patterns:\n- **NumPy**: `np.savez(path, **tensors_as_numpy)`\n- **PyTorch**: `torch.save(dict_of_tensors, path)`\n\n### 4) Run the MLX side with the same inputs and compare\n\nCreate a matching run directory:\n- `./debug_artifacts/<run_id>/mlx/`\n\nLoad and compare tensors. For each checkpoint, report:\n- **Shape + dtype**\n- **max_abs_diff**, **mean_abs_diff**\n- **max_rel_diff** (guarding division by zero)\n- Pass/fail with a clearly stated **rtol/atol**\n- It is **more important to inspect actual tensor values** (e.g., first 10 elements) than rely on summary stats.\n- Statistics can mislead; small-looking stats can hide systematic drift or sign flips.\n- Prefer **runtime tensor dumps** over code reading; code can use different conventions yet still represent the same math.\n\nSuggested tolerance starting points (adjust per component):\n- **fp32 comparisons**: `atol=1e-5`, `rtol=1e-5`\n- **fp16/bf16 comparisons**: `atol=1e-2`, `rtol=1e-2`\n- If comparing images: compare both (a) tensor space before final clamp and (b) saved `png` visually, since tiny numeric diffs can look identical.\n\nIf a checkpoint fails:\n- Add an **earlier** checkpoint and repeat (binary search through the forward path).\n\n## Common Causes of Divergence (high-signal checklist)\n\n- **Layout mistakes**: NCHW vs NHWC, transposes around convs/attention, flatten/reshape ordering. Some operations like convolutions can have different conventions between libraries.\n- **Broadcasting**: scale/shift vectors applied on the wrong axis (common in RoPE and modulation).\n- **Dtype casting**: reference silently upcasts to fp32 for norm/softmax; MLX path stays in fp16.\n- **RoPE details**: position ids, reshape order, whether cos/sin are broadcast over heads vs sequence.\n- **Scheduler math**: timestep indexing, sigma/alpha definitions, and off-by-one step order.\n- **Scheduler config**: compare sigma schedules directly.\n- **Seed/RNG**: ensure you aren’t comparing stochastic paths (dropout, noise sampling) without controlling RNG.\n- **Device dtype**: MPS `float16` can produce NaNs; prefer `bfloat16` for reference dumps if you see NaNs.\n- **Do not use CPU** for comparisons; always keep reference runs on MPS to avoid misleading behavior.\n\n## Artifact Hygiene\n\n- Prefer `debug_artifacts/<run_id>/...` at repo root.\n- Do not commit `debug_artifacts/` unless explicitly asked.\n- If you convert the parity check into a test, follow the repo’s testing conventions and preserve outputs (see `mflux-testing`).\n- Clean up old artifacts when they are no longer needed, only focus on the current problem and avoid confusion with older artifacts that are not relevant for the current task.\n\n## Isolate transformer + VAE (inject reference initial latents)\n\nWhen full end-to-end images differ between mflux and diffusers but you need to trust the **core model** (transformer, text encoder, VAE decode), export the reference **initial noise** and run mflux denoising from that tensor. If injected-latent mflux looks good while native-seed runs differ, the forward path is likely sound and any gap is probably RNG, scheduler, or optional reference-only components.\n\n**Do not commit** these scripts or Desktop `.npy` files unless asked. Use inline `uv run python <<'PY' ... PY` heredocs in the reference repo and in `mflux/`.\n\n### Step 1 — Export initial latents from diffusers\n\nRun from the local `diffusers/` clone (often next to `mflux/` on Desktop). Match mflux settings: height, width, seed, dtype (`bfloat16` on MPS).\n\nLoad the reference pipeline the same way you would for a normal generation, but **disable optional subsystems** that mflux does not implement or download (check `model_index.json` vs mflux `get_download_patterns()` / weight definition). Pass `None` for unused components, set pipeline flags to skip them, and use `local_files_only=True` so missing weights surface immediately instead of downloading extras.\n\nThen export noise with the same shape helper the pipeline uses internally:\n\n```python\nfrom diffusers.utils.torch_utils import randn_tensor\n\npipe = <ReferencePipeline>.from_pretrained(\n    \"<org/model>\",\n    torch_dtype=torch.bfloat16,\n    local_files_only=True,\n    # plus any kwargs to omit optional reference-only modules\n)\nlatent_h = height // pipe.vae_scale_factor  # or read from pipeline/config\nlatent_w = width // pipe.vae_scale_factor\nch = pipe.transformer.config.in_channels    # name varies by architecture\ngenerator = torch.Generator(device=\"mps\").manual_seed(seed)\nlatents = randn_tensor(\n    (1, ch, latent_h, latent_w),\n    generator=generator,\n    device=\"mps\",\n    dtype=torch.bfloat16,\n)\nnp.save(\"/path/to/init_latent.npy\", latents.detach().cpu().float().numpy())\n```\n\n### Step 2 — Denoise in mflux from the loaded latent\n\nIf `generate_image()` has no `latents=` argument, **inline the denoising loop** from the variant class instead of patching production code:\n\n1. `latents = mx.array(np.load(path)).astype(mx.bfloat16)`\n2. Text encode step from the variant (e.g. `_encode_prompts`, prompt cache, etc.)\n3. Any position encoding / conditioning setup the variant does before the loop\n4. Denoise loop: noise prediction + `config.scheduler.step(...)` over `config.time_steps`\n5. VAE decode + `ImageUtil.to_image(...)` (or the variant’s decode helper) → save PNG\n\nAlso run one `generate_image(seed=...)` baseline on the same prompt for side-by-side.\n\n### How to read results\n\n| Comparison | What it tells you |\n|---|---|\n| mflux native seed vs itself (re-run) | Sampling is deterministic on this hardware |\n| mflux + diffusers latent vs diffusers full run | Transformer + VAE + CFG path quality |\n| mflux native seed vs diffusers full run | **Not** a parity test — different RNG (`mx.random` vs `torch.Generator`) and often different sigma schedules |\n| mflux + diffusers latent vs mflux native seed | Large diff is **expected** if schedulers/sigmas differ, even with identical starting noise |\n\nIf **injected-latent mflux** looks good, the port’s core forward path is trustworthy. Golden CI tests should still lock **mflux-native** sampling (see `mflux-testing`), not diffusers pixel parity.\n\n## diffusers reference runs (side-by-side images)\n\n- mflux does **not** depend on diffusers; run reference scripts from a sibling `diffusers/` clone with `cd .../diffusers && uv run python`.\n- Use `HF_HUB_OFFLINE=1` when weights are cached to catch missing components the reference pipeline expects but mflux omits from its download patterns.\n- Compare at matched resolution, steps, guidance, seed, and precision when possible (note mflux `-q 8` vs diffusers bf16 is not apples-to-apples for speed or pixels).\n- Save outputs to explicit paths (e.g. Desktop) and report wall time with `/usr/bin/time -p`.\n\n## See Also\n\n- `mflux-model-porting`: correctness-first workflow (validate components and lock behavior before refactor).\n- `mflux-testing`: how to run tests safely and handle image outputs/goldens.\n\n","AGENTS.md":"# AI Agent Protocol & Instructions\n\nPath: `AGENTS.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/AGENTS.md)",".claude/skills/asd-ste100":"# Claude Directive: asd-ste100\n\nPath: `.claude/skills/asd-ste100`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/asd-ste100)",".claude/skills/mflux-cli":"# Claude Directive: mflux-cli\n\nPath: `.claude/skills/mflux-cli`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-cli)",".claude/skills/mflux-debugging":"# Claude Directive: mflux-debugging\n\nPath: `.claude/skills/mflux-debugging`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-debugging)",".claude/skills/mflux-dev-env":"# Claude Directive: mflux-dev-env\n\nPath: `.claude/skills/mflux-dev-env`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-dev-env)",".claude/skills/mflux-manual-testing":"# Claude Directive: mflux-manual-testing\n\nPath: `.claude/skills/mflux-manual-testing`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-manual-testing)",".claude/skills/mflux-model-porting":"# Claude Directive: mflux-model-porting\n\nPath: `.claude/skills/mflux-model-porting`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-porting)",".claude/skills/mflux-model-tiny-test":"# Claude Directive: mflux-model-tiny-test\n\nPath: `.claude/skills/mflux-model-tiny-test`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-tiny-test)",".claude/skills/mflux-pr":"# Claude Directive: mflux-pr\n\nPath: `.claude/skills/mflux-pr`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr)",".claude/skills/mflux-pr-docs":"# Claude Directive: mflux-pr-docs\n\nPath: `.claude/skills/mflux-pr-docs`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr-docs)",".claude/skills/mflux-release":"# Claude Directive: mflux-release\n\nPath: `.claude/skills/mflux-release`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-release)",".claude/skills/mflux-testing":"# Claude Directive: mflux-testing\n\nPath: `.claude/skills/mflux-testing`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-testing)",".cursor/rules/RULE.md":"# Rules Skill\n\nPath: `.cursor/rules/RULE.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/rules/RULE.md)",".cursor/skills/asd-ste100/README.md":"# Asd-ste100 Skill\n\nPath: `.cursor/skills/asd-ste100/README.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/README.md)",".cursor/skills/mflux-pr-docs/pr-what-prompt.md":"# Mflux-pr-docs Skill\n\nPath: `.cursor/skills/mflux-pr-docs/pr-what-prompt.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/pr-what-prompt.md)",".cursor/skills/mflux-pr-docs/release-note-prompt.md":"# Mflux-pr-docs Skill\n\nPath: `.cursor/skills/mflux-pr-docs/release-note-prompt.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/release-note-prompt.md)",".cursor/skills/asd-ste100/examples/before-after.md":"# Examples Skill\n\nPath: `.cursor/skills/asd-ste100/examples/before-after.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/before-after.md)",".cursor/skills/asd-ste100/examples/linter-edge-cases.md":"# Examples Skill\n\nPath: `.cursor/skills/asd-ste100/examples/linter-edge-cases.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/linter-edge-cases.md)",".cursor/skills/asd-ste100/references/writing-rules.md":"# References Skill\n\nPath: `.cursor/skills/asd-ste100/references/writing-rules.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/references/writing-rules.md)"},"files":{".cursor/skills/mflux-cli/SKILL.md":"---\nname: mflux-cli\ndescription: Navigate MFLUX CLI capabilities, locate commands by area, and summarize supported features.\n---\n# mflux CLI navigation\n\nUse this skill to inventory CLI capabilities, summarize what the CLI supports, and guide where to look\nfor commands without relying on brittle file paths.\nBecause README examples can drift, prefer verifying support against the current CLI entrypoints.\n\n## When to use\n\n- You need to list supported CLI features or commands.\n- You need to find where a capability is implemented in the CLI.\n- You are documenting or refactoring CLI features and want a stable map.\n- A user asks for CLI help, e.g., “Can you help me generate an image using z-image?”, “Which model is best?”, etc.\n\n## How to find commands (structure, not exact paths)\n\n- Common/shared CLI arguments live in the central CLI parser module.\n- Model-specific CLI entrypoints live under each model's CLI package.\n- Repo-level CLI helpers (completions, defaults) live under the shared CLI package.\n- Utilities may add standalone CLIs (e.g., metadata info, LoRA library).\n\n## Best practices when constructing CLI calls\n\n- **Inference steps**: When constructing a CLI call for any model, *always* check `MODEL_INFERENCE_STEPS` and use the model's default/recommended step count unless the user explicitly asks for a different value. This is especially important for distilled/non-base variants (for example `fibo-lite`, `z-image-turbo`, and other `*-turbo`/`*-lite` models), where using full/base-model step counts is usually counterproductive.\n- **Resource/inspection flags**: Mention `--low-ram` to reduce memory usage and `--stepwise-image-output-dir` for stepwise outputs when useful.\n- **Python API requests**: If a user asks for the Python API, treat the equivalent CLI script as the best starting reference for the underlying parameters and defaults.\n- **CLI implementation changes**: When adding or changing CLI behavior, prefer extending shared parser methods and shared helpers before adding manual one-off arguments or save paths in a model CLI.\n- **Docs/examples drift**: If CLI defaults, supported flags, or recommended usage changed, update the matching README examples in the same pass.\n\n## Capability inventory (current)\n\n### Core generation\n\n- Text-to-image across Flux, Flux2, FLUX 3 Image Klein, Iris-3B, SenseNova-U1.5, DreamLite, Qwen, Z-Image Turbo, FIBO.\n- Image-to-image where supported (Flux, Qwen, Z-Image Turbo, FIBO).\n\n### Editing and conditioning\n\n- Kontext image conditioning.\n- In-context editing and reference-image workflows.\n- CATVTON (virtual try-on).\n- Redux multi-image conditioning.\n- ControlNet (Canny).\n- Depth conditioning.\n- Fill / inpainting.\n- Flux2 Edit, FLUX 3 Image Klein edit (1-10 reference images) and Qwen Edit (multi-image edit).\n- DreamLite edit (one image, instruction-based).\n\n### Upscaling\n\n- SeedVR2 diffusion upscaler (preferred).\n- Flux ControlNet upscaler (legacy).\n\n### Model management\n\n- Quantized inference and saving quantized models.\n- Local model path loading (with base-model hints when needed).\n\n### LoRA\n\n- Load LoRAs, multi-LoRA, scale control.\n- In-context style LoRA shortcuts.\n- LoRA library lookup tool.\n\n### Metadata and reproducibility\n\n- Export JSON metadata per image.\n- Reuse prior parameters from metadata config files.\n- Inspect metadata from existing images.\n\n### Prompt tooling\n\n- Prompt files.\n- Negative prompts where supported (not supported for Flux2, FLUX 3 Image Klein or SenseNova-U1.5; Iris-3B uses them only on the base model).\n\n### Training\n\n- LoRA finetuning.\n\n### Utilities\n\n- DepthPro depth-map extraction.\n- FIBO VLM prompt inspire/refine tools.\n",".agents/skills/remediating-dependabot/SKILL.md":"---\nname: remediating-dependabot\ndescription: Remediates GitHub Dependabot alerts for mflux in one dependency-security change. Use when auditing, clamping, or upgrading Python dependencies in pyproject.toml and uv.lock, or when validating whether a branch will close Dependabot findings before opening a PR.\n---\n\n# Remediating Dependabot\n\nResolve actionable Dependabot alerts with the smallest compatible dependency update and prove the local lock is outside every reported vulnerable range.\n\n## Scope\n\n- Use `gh api` as the source of truth for open alerts in `mflux-community/mflux`.\n- Keep dependency changes in `pyproject.toml` and `uv.lock` unless compatibility requires source changes.\n- Preserve supported Python and platform markers.\n- Avoid unrelated package upgrades when regenerating the lock.\n- Treat dependency optionality or loading refactors as separate work unless explicitly requested.\n\n## Workflow\n\n1. Confirm the current branch and working tree before editing.\n2. Fetch all open Dependabot alerts, following pagination:\n\n   ```bash\n   gh api --method GET --paginate \\\n     -H \"Accept: application/vnd.github+json\" \\\n     repos/mflux-community/mflux/dependabot/alerts \\\n     -f state=open\n   ```\n\n3. Group alerts by manifest, package, severity, vulnerable range, and first patched version. Distinguish direct requirements from transitive lock entries.\n4. Inspect `pyproject.toml`, `uv.lock`, supported Python versions, and platform markers before choosing a fix.\n5. Prefer, in order:\n   - removing dependencies that are no longer needed;\n   - raising a direct lower bound to the first secure compatible release;\n   - upgrading only affected transitive packages in the lock;\n   - adding or changing environment markers only when compatibility actually differs by Python or platform.\n6. Use one requirement when a release supports the full project matrix. Do not introduce overlapping marker-specific requirements without evidence that they are necessary.\n7. Regenerate the lock with targeted upgrades:\n\n   ```bash\n   uv lock --upgrade-package <package> [--upgrade-package <package> ...]\n   ```\n\n8. Review the lock diff. Explain large platform-specific resolver changes, especially PyTorch CUDA package transitions, rather than assuming they are accidental.\n\n## Security verification\n\nDo not infer alert closure solely from package names or Dependabot's hosted UI.\n\n1. Run lock and advisory checks:\n\n   ```bash\n   uv lock --check\n   uv audit --preview-features audit-command\n   ```\n\n2. Parse every resolved version in `uv.lock` and compare it with every open alert's `security_vulnerability.vulnerable_version_range`. Canonicalize names with `packaging.utils.canonicalize_name` and use `packaging.specifiers.SpecifierSet` so matching follows Python package name and version semantics.\n3. Confirm that each alert is resolved by either:\n   - no matching package remaining in the lock; or\n   - every matching locked version falling outside the vulnerable range.\n4. Run Dependabot Core against the local checkout before opening a PR:\n\n   ```bash\n   tmp_dir=\"$(mktemp -d)\"\n   trap 'rm -rf \"$tmp_dir\"' EXIT\n   job=\"$tmp_dir/job.yml\"\n   output=\"$tmp_dir/output.yml\"\n\n   # Build the security job at \"$job\" before running these commands.\n   dependabot graph uv mflux-community/mflux --local \"$PWD\"\n   dependabot update --local \"$PWD\" -f \"$job\" -o \"$output\" --pull=false --timeout 20m\n   ```\n\n   `graph` is experimental and may return an incomplete dependency list. Both commands snapshot the directory passed to `--local`, including modified and untracked files, so confirm that the working tree contains only the intended updater input.\n\n   Build the temporary `uv` security job from the exact package names and advisory ranges returned by GitHub. Parse the YAML output rather than relying on the command's exit status:\n\n   ```bash\n   uv run python - \"$output\" <<'PY'\n   import sys\n\n   import yaml\n\n   with open(sys.argv[1]) as output_file:\n       actions = {entry[\"type\"] for entry in yaml.safe_load(output_file)[\"output\"]}\n\n   if \"mark_as_processed\" not in actions:\n       raise SystemExit(\"Dependabot did not mark the job as processed\")\n\n   pull_request_actions = actions & {\"create_pull_request\", \"update_pull_request\"}\n   if pull_request_actions:\n       raise SystemExit(f\"Dependabot still proposes actions: {sorted(pull_request_actions)}\")\n   PY\n   ```\n\n   Do not pin Dependabot CLI to one release. Verify the installed CLI exposes the commands and flags used here before running the job.\n5. Keep temporary Dependabot job and output files outside the committed change, and remove them after verification.\n6. If the hosted alert remains open while the local lock is already outside its vulnerable range, report it as pending or stale until GitHub rescans. Do not force an unnecessary upgrade just to change the lock entry.\n\n## Project verification\n\nRun the repository workflows after the lock is secure:\n\n```bash\njust lint\njust lint-justfile\njust typecheck\njust test-fast\njust test\njust build\ngit diff --check\n```\n\nUse `uv lock --upgrade --dry-run` to check that a fresh universal resolution succeeds. It may report unrelated newer releases; do not add them unless they are needed for the remediation.\n\n## Reporting\n\nReport:\n\n- total open findings expected to close, grouped by severity and package;\n- direct requirement changes and noteworthy lock-only changes;\n- packages removed from the lock;\n- exact results from range comparison, Dependabot Core, `uv audit`, and project checks;\n- any alerts whose final hosted closure depends on GitHub rescanning the merged lockfile.\n",".cursor/skills/mflux-dev-env/SKILL.md":"---\nname: mflux-dev-env\ndescription: Set up and work in the mflux dev environment (arm64 expectation, uv, justfile recipes, lint/format/test).\n---\n# mflux dev environment\n\nThis repo expects macOS arm64 and prefers `uv` + justfile recipes.\n\n## When to Use\n\n- You’re setting up the repo locally or diagnosing environment/setup issues.\n- You need the canonical way to run lint/format/check/build/test.\n\n## Instructions\n\n- Prereq: `just` ≥ 1.50 (`brew install just`). CI lints the justfile with `just --fmt --check`; run `just fmt-justfile` to auto-fix formatting.\n- Prefer justfile recipes:\n  - Install: `just install`\n  - Lint: `just lint`\n  - Format: `just format`\n  - Pre-commit suite: `just check`\n  - Build: `just build`\n- Prefer `uv run ...` for running Python commands to ensure the correct environment.\n- When running tests, keep `MFLUX_PRESERVE_TEST_OUTPUT=1` enabled (the justfile test recipes already do this).\n\n## Type checking (ty)\n\n- The type checker is astral's `ty`, pinned exactly in `pyproject.toml` dev deps (mirrored in `.pre-commit-config.yaml` and run in CI). Run it with `just typecheck` (or `uv run ty check`).\n- `[tool.ty.rules]` in `pyproject.toml` carries a one-time migration baseline (mypy → ty): every rule listed there had pre-existing violations and is set to `\"ignore\"`, with violation counts in comments.\n- **Planned burn-down**: we intend to re-enable these rules piecemeal — delete one ignore line, fix all resulting `ty check` errors, commit, repeat. Prefer starting with low-count rules. Do not add new ignore lines; new code must pass all rules not in the baseline.\n\n",".cursor/skills/mflux-model-porting/SKILL.md":"---\nname: mflux-model-porting\ndescription: Port ML models into mflux/MLX with correctness-first validation, then refactor toward mflux style.\n---\n# mflux model porting\n\n## Goal\nProvide 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.\n\n## Principles\n- Match the reference implementation first; prove correctness before cleanup.\n- Lock correctness with deterministic tests before refactoring.\n- 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.\n- Refactor toward shared components and clean APIs once tests are green.\n- 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.\n\n## Workflow (checklist)\n1. **Scope and parity**\n   - Define target parity (outputs, speed, memory) and acceptable tolerances.\n   - Identify reference files, configs, and checkpoints to mirror.\n   - Draft a Cursor plan for the port and review it before starting implementation.\n2. **Port fast to reference**\n   - Add the model package skeleton and a variant class + initializer.\n   - Follow standard mflux initializer/weight-loading style; review recent ports like `z_image_turbo` and `flux2_klein` for structure and naming.\n   - Wire weight definitions/mappings early so loading is exercised (implement quantization in the initializer, but skip it during early runs).\n   - Keep the first implementation simple and explicit; defer `mx.compile` and other speed-focused changes until deterministic parity is passing.\n   - When defining explicit weight mappings, inspect actual tensor values from the model in the Hugging Face cache to confirm names and shapes.\n   - 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).\n   - Add lightweight shape checks close to the code paths.\n   - Use `mx.save`/`mx.load` at critical points; it is OK to add these to the reference (without changing logic) to export latents.\n3. **Port order (work backwards from image)**\n   - Typical image generation flow: `prompt → text_encoder → transformer_loop → VAE → image`.\n   - For porting, invert the order so you can validate pixel space early.\n   - Start with VAE decode/encode to validate output images quickly:\n     - Export packed latents from the reference just before VAE decode.\n     - Load latents inline and decode to an image for visual inspection.\n     - Run an encode→decode roundtrip to sanity check reconstruction; a good-looking image reconstruction increases confidence in the implementation.\n     - 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.\n   - Then port the transformer loop and its schedulers with intermediate latent checks.\n     - If the reference uses a novel scheduler, port it; otherwise, reuse the existing mflux scheduler.\n   - Finish with the text encoder and tokenizer details.\n   - After each major component is validated (e.g., VAE, transformer, text encoder), commit with a clear milestone message like \"VAE done\" to preserve progress.\n    - Once the full port is working, remove any loaded tensors or debug artifacts so no traces remain.\n4. **Deterministic validation**\n   - Create a deterministic MLX test (image or tensor) that locks the output.\n   - Run tests via `MFLUX_PRESERVE_TEST_OUTPUT=1 uv run <test command>`.\n   - If MLX OOMs on sensible inputs (e.g., 1024×1024), assume a likely porting mistake and re-check shapes or memory-heavy ops.\n5. **Post-test refactor (explicit step)**\n   - Review commits after the first deterministic test to capture refactoring preferences.\n   - Consolidate shared components into common modules.\n   - Remove debug paths and one-off schedulers once validated.\n   - Move configuration defaults into standard config/scheduler paths.\n    - Simplify and decompose large files into focused modules once behavior is locked.\n    - Prefer shared scheduler implementations when they already exist in mflux.\n    - Ensure CLIs register callbacks via `CallbackManager.register_callbacks(...)` so shared features like `--stepwise-image-output-dir` work; pass a `latent_creator` that supports `unpack_latents(...)`.\n    - Keep running the deterministic image test during refactors to avoid regressions.\n   - Align the variant class with recent ports (`flux2_klein`, `z_image`): `prompt_cache`, merged `_predict`, RoPE setup inside predict path, `_decode_latents` helper, no verbose comments/docstrings (see repo `RULE.md`).\n   - Strip dead scaffolding (e.g. unused gradient-checkpointing flags) once training/inference paths are stable.\n6. **Pre-merge polish (after core port works)**\n   - **diffusers sanity check**: run matched mflux + diffusers generations; use `mflux-debugging` latent injection if outputs disagree but you need to validate transformer/VAE.\n   - **Golden tests**: pick prompt/seed/settings that are stable on target CI hardware; update reference PNGs only after explicit approval (see `mflux-testing`).\n   - **img2img**: verify latent packing/normalization on the img2img path matches txt2img and training (especially when reusing a shared VAE from another model family). `pack_latents` must accept the 5D `(B, C, 1, H, W)` tensor that tiled VAE encode (`vae_encode_tiled`) returns — squeeze the singleton temporal axis first, as `flux2`/`fibo`/`z_image` latent creators do; a 4D-only unpack (or a bare passthrough `pack_latents`) breaks tiled img2img. This is reachable via `--low-ram`: `MemorySaver` sets `tiling_config = TilingConfig()` (`vae_encode_tiled=True`), so always test img2img with `--low-ram`, not just the default path (which is safe only because `VAEUtil.encode` squeezes 5D→4D when tiling is off).\n   - **Cross-model touch points**: list every file outside `models/<your_model>/`; justify shared changes (`memory_saver` tiling guard, shared VAE `tiling_config`, training `runner` wiring). Drop unrelated edits (e.g. personal `.gitignore` entries).\n   - **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 `du` on HF cache and/or `mflux-save` + `du -sh` for quantized sizes.\n   - **Training**: example JSON under `models/common/training/_example/`, un-ignore in `.gitignore`, fast unit tests for training-adapter preview defaults.\n   - Re-run `just lint`, `just test-fast`, then slow golden tests before merge.\n7. **Finalize**\n   - Re-run tests and basic perf checks after polish.\n   - Add CLI/pipeline defaults and completions later, once core output is stable.\n   - Ensure the model is wired into the standard surfaces:\n     - `ModelConfig` entry + aliases\n     - Thin model CLI entrypoint that uses shared parser/config/callback patterns and a command class with `validate`, `load` and `generate` (see [Command class](#command-class-validate-load-generate))\n     - README following the structure and tone of existing model READMEs\n     - Python API example that matches the CLI/defaults\n   - Document any new mapping rules, shape constraints, or tolerances.\n\n## Package layout (reference: `flux2`)\n\nUse `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.\n\n```\n{model}/\n  {model}_initializer.py\n  __init__.py                    # export variant + initializer\n  README.md\n  cli/\n    {model}_generate.py          # (+ edit/turbo CLIs when applicable)\n  latent_creator/\n    {model}_latent_creator.py\n  model/\n    {model}_text_encoder/        # prompt_encoder.py, tokenizer pieces, text_encoder.py\n    {model}_transformer/         # attention, blocks, rope, transformer.py (split files)\n    {model}_vae/                 # or reuse shared VAE (e.g. flux2_vae) — document in README\n    {model}_scheduler/           # only when not covered by models/common/schedulers\n  variants/\n    __init__.py                  # re-export public variant class(es)\n    txt2img/\n      __init__.py\n      {model}.py                 # e.g. flux2_klein.py, ideogram4.py\n    edit/                        # when the model supports image-conditioned generation\n      __init__.py\n      {model}_edit.py\n  weights/\n    __init__.py\n    {model}_weight_definition.py # components, download patterns, tokenizers\n    {model}_weight_mapping.py    # WeightTarget list / key transforms for base weights\n    {model}_lora_mapping.py      # LoRA key aliases (diffusers, PEFT, kohya) — when LoRA is supported\n  training_adapter/              # when mflux-train is supported\n    {model}_training_adapter.py\n```\n\n**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`.\n\n**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).\n\n**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`.\n\n**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.\n\n## Integration surfaces checklist (don’t forget)\n\nPast [closed PRs](https://github.com/mflux-community/mflux/pulls?q=is%3Apr+is%3Aclosed) show the same wiring gaps recurring on every new model. Use this as a **tick list** alongside the workflow above — not every row applies to every model (e.g. skip vision-encoder rows for txt2img-only), but scan it before opening a port PR.\n\n### Repo wiring (required for every new model family)\n\n| Surface | What to do |\n|---|---|\n| `pyproject.toml` | Register `mflux-generate-<model>` (and edit/turbo variants if separate) |\n| `ModelConfig` | Entry in `AVAILABLE_MODELS`: aliases, HF repo id, `num_train_steps`, guidance support, sigma shift, `transformer_overrides`, distilled vs base step defaults |\n| `models/common/resolution/model_revisions.py` | Pin every HF repo the model downloads (`model_name`, ControlNet, helper repos) to the full commit hash its golden references were generated with. `tests/resolution/test_model_revisions.py` fails for a registry repo without a pin. |\n| `scripts/ci_extract_models.py` | Add an `OVERLAY` row for every new `AVAILABLE_MODELS` key: taxonomy, CLI/tool commands, status, and quantization support. Use `EXTRA_ENTRIES` only for standalone tools with no `ModelConfig` entry. Run `just ci-extract` and confirm the model is present in `.ci_cache/models_mflux.json`. |\n| `cli/defaults/defaults.py` | `MODEL_INFERENCE_STEPS` (keyed by the canonical `AVAILABLE_MODELS` key — the `--model` choices derive from the registry, nothing to add there) |\n| `models/common/cli/save.py` | Route `mflux-save` to the **correct variant class** (txt2img vs edit vs turbo — wrong class silently drops weights; see [#405](https://github.com/mflux-community/mflux/pull/405)) |\n| Main `README.md` | Model table row + attribution line |\n| `src/mflux/models/<model>/README.md` | Examples aligned with Flux2-style layout; disk sizes measured (`du`, `mflux-save`) |\n| `src/mflux/assets/` | Hero/showcase image if other models have one (`git add -f` when `*.jpg` is gitignored) |\n\n### Weights, tokenizer, download scope\n\n| Surface | What to do |\n|---|---|\n| `*WeightDefinition` | `get_components()`, `get_download_patterns()`, `get_tokenizers()` — **only** list artifacts mflux actually loads |\n| Weight mapping | Explicit `WeightTarget` list; verify tensor names/shapes against HF cache blobs |\n| Tokenizer | Exercise local-path load, partial HF cache, and any special formats (protobuf, sentencepiece, etc.) — see [#383](https://github.com/mflux-community/mflux/pull/383), [#389](https://github.com/mflux-community/mflux/pull/389), [#390](https://github.com/mflux-community/mflux/pull/390) |\n| Optional reference components | Document in README what the upstream pipeline includes but mflux omits (extra encoders, preprocessors, etc.) |\n\n### LoRA\n\n| Surface | What to do |\n|---|---|\n| `*LoRAMapping` | Support **multiple export key conventions** (diffusers, PEFT `.default.weight`, kohya/`diffusion_model.*` aliases) — silent zero-key loads were fixed repeatedly ([#376](https://github.com/mflux-community/mflux/pull/376), [#374](https://github.com/mflux-community/mflux/pull/374), [#397](https://github.com/mflux-community/mflux/pull/397)) |\n| Tests | Fast tests that real community LoRA filenames map to non-zero keys |\n| Inference CLI | `--lora` via shared parser (no bespoke loader). `--lora-paths` / `--lora-scales` are deprecated. |\n\n### Inference CLI & shared features\n\n| Surface | What to do |\n|---|---|\n| Thin CLI | `build_parser()` with `CommandLineParser` + `CallbackManager.register_callbacks(...)` |\n| Command class | **Required.** Put the CLI work in `<Model>Command` with `validate`, `load`, `generate` and `latent_creator`. `main()` only calls these steps. See below. |\n| `DimensionResolver` | Use in generate/edit CLIs when width/height can be omitted (API/OpenWebUI paths) — [#378](https://github.com/mflux-community/mflux/pull/378) |\n| `latent_creator` | `pack_latents` / `unpack_latents`; img2img path must match txt2img normalization (BN, scale factor) |\n| `tiling_config` | If initializer sets custom tiling, ensure `MemorySaver` does not overwrite it |\n| Guidance defaults | Distilled vs base: match `ModelConfig`, CLI default, README, and training preview adapter |\n| `mflux-save` round-trip | Save quantized model → load from local path → generate; confirm `model.safetensors.index.json` if sharded |\n\n### Command class: validate, load, generate\n\nUse this pattern for every new generate CLI. Do not put the full flow in one `main()`. Plugins under `mflux.extras` call these steps. A CLI without them cannot support plugins. See `docs/plugins.md` and `docs/validate-load-generate.md`.\n\nCopy the structure of `src/mflux/models/qwen/cli/qwen_image_generate.py`:\n\n| Member | Rule |\n|---|---|\n| `latent_creator` | Class attribute. `main()` passes it to `CallbackManager.register_callbacks(...)`. |\n| `validate(args) -> ModelConfig` | Static. Do not load weights. Resolve `--model` with `ConfigResolution.resolve_restricted(...)`. If the command has rules for flag combinations, sizes or output formats, test them here and raise `ValueError`. |\n| `load(args) -> Model` | Static. Call `validate(args)` first. Then make the model with `quantize`, `model_path` and `**lora_init_kwargs_from_args(args)`. |\n| `generate(model, args, seed, prompt) -> GeneratedImage` | Static. Make one image for one seed and one prompt. Apply the command defaults here, for example guidance and `DimensionResolver`. A direct caller must get the same image as `main()`. Do not save the image. |\n\n`main()` only parses the arguments, calls `load`, registers the callbacks, calls `generate` for each seed and saves each image.\n\n### Training (if supported)\n\n| Surface | What to do |\n|---|---|\n| `training/runner.py` | Register `*TrainingAdapter`; handle `low_ram` / tiling like other models |\n| Example JSON | `models/common/training/_example/train_<model>.json` + `.gitignore` un-ignore |\n| Preview generation | Adapter should use canonical steps/guidance for distilled vs base (unit test this) |\n| Local `model_path` | Confirm `mflux-train` works with saved local weights — [#370](https://github.com/mflux-community/mflux/pull/370) |\n\n### Tests & CI\n\n| Surface | What to do |\n|---|---|\n| Slow golden test | `tests/image_generation/test_generate_image_<model>.py` + `reference_*.png` on CI hardware |\n| Fast tests | LoRA mapping, training-adapter preview defaults, argparser if new CLI flags |\n| `just ci-extract` | Required after changing `AVAILABLE_MODELS` or `OVERLAY`; verifies every registry key has CI-manifest metadata |\n| `just lint` / `just test-fast` | Before slow tests |\n\nWhen fixing a gap for model *N*, ask whether the same gap exists for other recent models and whether a **shared** fix belongs in `models/common/` (preferred over copy-paste per model).\n\n## Tooling expectations\n- Use `uv` for running scripts and tests: `uv run <command>`.\n- Prefer `uv run python -m <module>` for local modules.\n\n## Deliverables\n- Deterministic MLX test that verifies correctness.\n- Documented weight mapping, shape constraints, and any known tolerances.\n- Cleaned, shared components aligned with mflux style.\n- Standard mflux surfaces in place: config aliases, thin CLI with a `validate` / `load` / `generate` command class, and a README/examples pass aligned with the final behavior.\n",".cursor/skills/mflux-pr-docs/SKILL.md":"---\nname: mflux-pr-docs\ndescription: Write the PR body for the current mflux branch and show it to the developer for approval. Fills the What section, the release-note block and the Verification section of the PR template. Use when the developer asks to write, fill or update a PR description or a release note.\n---\n\n# mflux PR docs\n\nWrite the PR body for the current branch. The developer must approve the body before it goes to GitHub.\n\n## Inputs\n\n- The current branch. The base branch is `main`.\n- Optional: the PR number, if the PR is open.\n\n## Steps\n\n1. Collect the facts. Use only these sources:\n   - `git log --oneline main..HEAD`\n   - `git diff --stat main...HEAD`\n   - `git diff main...HEAD`\n   - If the PR is open: `gh pr view <n> --json title,body,closingIssuesReferences` and `gh pr checks <n>`.\n2. Copy `.github/pull_request_template.md` to `tmp-PR-content.md`. If `tmp-PR-content.md` exists, ask the developer before you replace it.\n   - Add this heading as the first line: `# Draft PR Content`.\n   - Add the line `Title: ` below the heading. Add an empty line after it.\n   - If the PR is open, put its title from step 1 after `Title: `.\n   - If the PR is open, `gh pr edit --body-file` replaces the existing body. Copy each existing section and link that the template does not have into `tmp-PR-content.md`. Get them from the `body` field of step 1. If you do not copy them, ask the developer to confirm before you discard them.\n3. Write the `What` section. Obey `pr-what-prompt.md` in this folder. Use the diff from step 1 if the PR is not open. Add `Fixes #<n>` for each linked issue.\n   - If the PR is not open, write the PR title after `Title: `. Use one short line that names the change.\n   - If the PR is open, keep its title. Change the title only if the developer asks.\n4. Write the release note. Obey `release-note-prompt.md` in this folder.\n   - Put the note on the lines below the opening fence. Do not put text on the fence line.\n   - Tell the developer which PR label the PR needs.\n5. Write the `Verification` section. List only the commands that ran, with the result of each command. If no command ran, write `TODO: add the commands that you ran.` Do not write a result that you did not see.\n6. Do not tick the boxes in the `Checklist` section. The developer ticks them.\n7. Examine the text that you wrote. Do not examine the template text.\n   - Apply the `asd-ste100` skill in STE-flavored mode.\n   - Put the text that you wrote in a temporary file. Do not put the `Title:` line in it. Run `python3 .cursor/skills/asd-ste100/scripts/ste-lint.py --disable synonym-rotation <file>`.\n   - Fix each hard violation.\n8. Run the CI check on `tmp-PR-content.md`. Fix `tmp-PR-content.md` until the check passes:\n   ```sh\n   python3 - tmp-PR-content.md <<'PY'\n   import re, sys\n   body = open(sys.argv[1], newline=\"\").read()\n   m = re.search(r\"^```release-note[ \\t\\r]*\\n(.*?)^```[ \\t\\r]*$\", body, re.DOTALL | re.IGNORECASE | re.MULTILINE)\n   sys.exit(0 if m and m.group(1).strip() else \"FAIL: no complete release-note block\")\n   PY\n   ```\n9. Ask the developer to approve the PR content:\n   - Open `tmp-PR-content.md` in the editor. Use `code tmp-PR-content.md` or `cursor tmp-PR-content.md`. If neither command works, give the developer the file path.\n   - Tell the developer to edit the file in the editor, or to ask for changes in the chat.\n   - Tell the developer to write `approve` in the chat when the content is ready.\n   - Do not continue until the developer writes `approve`.\n10. Read `tmp-PR-content.md` again after the developer approves it. The developer can edit the file before approval. Do step 8 again.\n    - Make sure that line 1 is `# Draft PR Content` and line 2 is the `Title:` line. Put them back if the developer moved them.\n    - Make sure that the `Title:` line has a title. If it is empty, ask the developer for the title. Write the title after `Title: ` in `tmp-PR-content.md`.\n11. Send the PR content to GitHub:\n    - If the PR is not open, push the branch first. Ask for permission before you push. Obey the `mflux-pr` skill.\n    - Run this block as one command. If the PR is open, replace the last line with `gh pr edit <n> --title \"$title\" --body-file tmp-PR-body.md`.\n      ```sh\n      title=\"$(awk 'NR <= 2 && sub(/^Title: */, \"\") { print; exit }' tmp-PR-content.md)\"\n      awk 'NR == 1 && /^# Draft PR Content$/ { next } NR == 2 && /^Title:/ { next } { print }' tmp-PR-content.md > tmp-PR-body.md\n      gh pr create --title \"$title\" --body-file tmp-PR-body.md\n      ```\n    - The shell reads the title from the file. Do not type the title into the command. Backticks and `$` in a typed title run as shell code.\n    - GitHub does not get the `# Draft PR Content` line or the `Title:` line. Other lines that start with `Title:` stay in the body.\n12. Delete `tmp-PR-content.md` and `tmp-PR-body.md`.\n\n## Rules\n\n- Do not invent facts, numbers or test results.\n- Do not change the code or the commits.\n- Do not use `gh pr create --body` or `--fill`. GitHub must get the body that you checked, without the two draft lines.\n- Keep the regex in step 8 the same as `.github/workflows/release-note.yml` and `_FENCE` in `src/mflux/release/release_notes.py`.\n",".cursor/skills/mflux-model-tiny-test/SKILL.md":"---\nname: mflux-model-tiny-test\ndescription: Write a hermetic \"tiny\" model-saving test for an mflux model — a fast twin of the slow save/load test that runs the real ModelSaver/WeightLoader/WeightApplier seam on real component classes at toy dimensions, with no downloads or image generation. Use when asked to \"make tiny test for <model>\".\n---\n# mflux tiny model-saving test\n\nA tiny test proves a model's quantized checkpoint survives a save/load roundtrip byte-for-byte, in about a second, without downloading anything. It builds the model's **real** component classes at toy dimensions and pushes them through the **real** save/load code path.\n\n## When to Use\n\n- You're asked to \"make tiny test for `<model>`\" or add a fast twin of a slow save/load test.\n- You ported a new model (see `mflux-model-porting`) and want cheap checkpoint coverage.\n\nRelated: `mflux-testing` for running the suite and golden-image rules.\n\n## Reference implementations\n\nRead these before writing a new one — they are the source of truth:\n\n- `tests/model_saving/tiny_checkpoint_helper.py` — the shared harness\n- `tests/model_saving/test_tiny_model_saving_ernie_image.py` — components take explicit kwargs\n- `tests/model_saving/test_tiny_model_saving_ideogram4.py` — components take a Config dataclass\n\nDo not trust code quoted in this skill over those files. The pattern landed as an RFC (PR #599, \"proposal + demo on 2 models\") and is expected to evolve.\n\n**Models that already have tiny tests:** `ernie_image`, `ideogram4`.\n\n## What you write\n\nOne file, no `src/` changes:\n\n```text\ntests/model_saving/test_tiny_model_saving_<model>.py\n```\n\nThe whole test is a single call into `TinyCheckpointRoundtrip`. The real work is figuring out how to build that model's components small. Match the two examples exactly:\n\n- class `TestTiny<Model>ModelSaving`\n- method `test_tiny_quantized_checkpoint_roundtrips_exactly`, decorated `@pytest.mark.fast`\n- a `@staticmethod _tiny_components()` returning the component dict\n- a comment naming the slow twin it mirrors\n\n## Instructions\n\n### 1. Read the weight definition — it is the contract\n\n```text\nsrc/mflux/models/<model>/weights/<model>_weight_definition.py\n```\n\n`get_components()` is authoritative: it gives the exact set of component **names** you must produce, and how many. While there, note two things:\n\n- **`quantization_group_size`** — a class attribute on the weight definition. Defaults to 64 but is not always 64 (`boogu` uses 32). Every tiny dimension must be a multiple of *this model's* value. Check with `grep -n \"quantization_group_size\" src/mflux/models/<model>/weights/*.py`.\n- **`skip_quantization=True`** on any component (`krea2` and `qwen` each have one). In production, `WeightApplier._quantize` honors this flag and leaves the component unquantized. **`TinyCheckpointRoundtrip._quantize` does not** — it calls `nn.quantize` on every saved component regardless of the flag, so a `skip_quantization` component comes out of the \"saved\" side quantized (with `scales`/`biases`) while the reloaded \"fresh\" side stays unquantized (no `scales`/`biases`). The helper's exact key-set comparison (`saved_weights.keys() == fresh_weights.keys()`) will then fail for that component. This is a real gap in `tiny_checkpoint_helper.py`, not a quirk to work around in the test file — if you're writing a tiny test for `krea2`, `qwen`, or any other model with a `skip_quantization` component, stop and fix `TinyCheckpointRoundtrip._quantize` to skip those components (mirroring `WeightApplier._quantize`) rather than special-casing it in the test.\n\n### 2. Find each component's real class and read its `__init__`\n\nDerive the shrink knobs from the actual constructor. Do not pattern-match one example — they differ deliberately: ERNIE's components take explicit kwargs (`hidden_size=`, `num_layers=`), Ideogram 4's transformer takes an `Ideogram4Config` dataclass.\n\nLook under `src/mflux/models/<model>/model/`. Shrink layer counts to 2, hidden and intermediate sizes to 128, head counts to 2, vocab to 128.\n\n### 3. Use `TinyVAEStandIn` for the VAE\n\nThe real VAEs are fixed-size (~170M param) architectures with no dimension knobs, so they cannot be shrunk. `ModelSaver`/`WeightLoader` treat every component as an opaque parameter tree, so the stand-in walks the identical code path. Don't spend a loop trying to shrink a real VAE.\n\n### 4. Respect interlocking dimension constraints\n\nDimensions are not independent. Look for constraints in the component's `__init__` and attention/rope code:\n\n- `rope_axes_dim` must **sum to** `head_dim` (ERNIE: `[16, 24, 24]` → 64)\n- `head_dim` must be consistent with `hidden_size / num_attention_heads`\n- `num_key_value_heads` must divide `num_attention_heads`\n\n### 5. Choose `tensors_per_shard`\n\nStart with `tensors_per_shard=8`. It forces shard boundaries so the `index.json` / `weight_map` multi-shard paths get exercised — the production size-based split (≥1 GB) never shards test-sized tensors.\n\nThe helper asserts `len(shard_files) > component_count`. If a model's tiny components have too few parameter tensors to clear that bar, **lower the number until it passes** — do not drop the argument, that silently removes multi-shard coverage.\n\n### 6. Name the slow twin — after checking it exists\n\nThe examples carry `Fast twin of tests/model_saving/test_model_saving_<model>.py`. Several models have weight definitions but **no** slow save test. Verify with `ls tests/model_saving/` and adapt the comment rather than pointing at a file that isn't there.\n\n## Constraints that will bite you\n\n- **Key the dict by `component.name`, not `model_attr`.** The helper does a bare `components[component.name]` lookup, so a missing or misnamed key is a raw `KeyError`, not a helpful message. Most common first-try failure. Every component in `get_components()` needs an entry.\n- **Do not collapse the two seeds.** The harness randomizes saved components with `seed=0` and fresh ones with `seed=1`. That difference is exactly what makes the final equality assertion prove values came off disk. Unifying them leaves the test green and meaningless.\n- **Do not edit `WeightDefinitionType`.** The helper types `weight_definition` as plain `type` on purpose — that `TYPE_CHECKING` union has drifted and omits several definitions. Widening a src type alias is out of scope; see the helper's comment.\n- **Do not modify `src/`.** A tiny test is a test-only addition. If a model appears to genuinely require a src change to be testable, stop and report that rather than making it.\n\n## Verify\n\n```sh\nuv run --no-sync python -m pytest tests/model_saving/test_tiny_model_saving_<model>.py -v\n```\n\nThen confirm nothing else broke with `just test-fast` (see `mflux-testing`).\n\nThe test should run in roughly a second. If it takes noticeably longer, or the network is touched, something is loading a real checkpoint — investigate rather than accepting it.\n\n### Do you need to check that quantization actually happened?\n\n**No.** Verified empirically: MLX raises loudly on a bad dimension rather than silently skipping —\n\n```text\nValueError: [quantize] The last dimension of the matrix needs to be divisible\nby the quantization group size 64. However the provided matrix has shape (100,100)\n```\n\nso a dimension that isn't a clean multiple of the group size fails the test outright. It cannot leave a green-but-weak twin.\n\nRelatedly, when inspecting a quantized tree you'll see some `.weight` entries with no matching `.scales`. Confirmed benign: those are 1-D norm weights and `Conv2d` layers, which `nn.quantize` correctly leaves alone. Only `Linear`-style layers quantize. Don't chase these.\n\n## Troubleshooting\n\n| Symptom | Cause |\n|---|---|\n| `KeyError: '<name>'` | `_tiny_components()` is missing a component, or keyed it by `model_attr` instead of `name` |\n| `ValueError: [quantize] ... divisible by the quantization group size` | A dimension isn't a multiple of this model's `quantization_group_size` |\n| `assert len(shard_files) > component_count` | Lower `tensors_per_shard` (step 5) |\n| Values differ after reload | A real save/load bug — report it, do not weaken the assertion |\n| Shape assertion inside a component's `__init__`/forward | An interlocking dimension constraint (step 4) |\n",".cursor/skills/mflux-pr/SKILL.md":"---\nname: mflux-pr\ndescription: Make a clean PR in mflux (inspect diff, quick verification, commit, push, open PR) using repo conventions.\n---\n# mflux pull request workflow\n\n## When to Use\n\n- You’re about to open a PR (or want a safe sequence to do it).\n\n## Instructions\n\n- If you run tests as part of PR hygiene, prefer fast tests first:\n  - `just test-fast`\n- Keep commits focused and messages consistent with repo history.\n- If the PR changes CLI defaults, public APIs, or model behavior, check for README/example drift before opening the PR.\n- **Always ask for permission** before pushing to the remote repository.\n- If `gh` isn’t available, fall back to the GitHub web UI (or stop and ask).\n\n## PR body and release note (required)\n\nThe `release-note` CI check fails the PR if the body has no complete release-note block.\n\nUse the `mflux-pr-docs` skill to write the PR body. That skill writes the `What` section and the release-note block, runs the CI check, and gets the approval of the developer.\n\nIf the check fails on an open PR, use the `mflux-pr-docs` skill again. It edits the body of the open PR. The check runs again on an edit. You do not need a new commit.\n\n## Pre-merge checklist (model port PRs)\n\nUse after the core port lands and you are polishing for merge. For the full **integration surfaces** tick list (LoRA key formats, save routing, tokenizer edge cases, etc. learned from past closed PRs), see `mflux-model-porting` → *Integration surfaces checklist*.\n\n### Correctness\n\n1. `just lint` and `just test-fast`\n2. `just ci-extract` after changing `AVAILABLE_MODELS` or `scripts/ci_extract_models.py`\n3. Slow golden tests for the new model:\n   ```sh\n   MFLUX_PRESERVE_TEST_OUTPUT=1 uv run pytest tests/image_generation/test_generate_image_<model>.py -m slow -v\n   ```\n4. Optional but high-signal: diffusers side-by-side + latent injection (`mflux-debugging`, `mflux-manual-testing`)\n\n### Cross-model diff audit\n\nList files changed outside `src/mflux/models/<model>/`:\n\n| Category | Expected |\n|---|---|\n| `pyproject.toml`, `cli/defaults/defaults.py`, `ModelConfig`, `mflux-save` routing | Required wiring |\n| `scripts/ci_extract_models.py` `OVERLAY` / `EXTRA_ENTRIES` | Required CI-manifest wiring for every new model key or standalone tool |\n| `README.md` table + attribution | Required |\n| Training `runner.py`, example JSON, `.gitignore` JSON exceptions | If training supported |\n| Shared VAE/callback/training one-liners | Only if required; document blast radius in PR |\n| Personal `.gitignore`, unrelated formatting | **Remove** |\n\nVerify quantized README disk claims with measurement:\n```sh\ndu -sh ~/.cache/huggingface/hub/models--<org>--<Model>*\nmflux-save --model <alias> --quantize 8 --path /tmp/model-q8 && du -sh /tmp/model-q8\n```\n\n### Docs / examples\n\n- Model README matches a recent port (e.g. Flux2): hero image, turbo + base CLI, feature section, disk warning, Notes, Training.\n- Main `README.md` model table row (correct release date).\n- Showcase asset if other models have one (`src/mflux/assets/`; may need `git add -f` when `*.jpg` is gitignored).\n\n### PR description callouts\n\n- Shared code touched and why (shared VAE, callbacks, training runner, etc.).\n- Reference pipeline features intentionally **not** ported (optional preprocessors, extra encoders, components omitted from mflux weight downloads).\n- Known non-parity with diffusers (RNG, sigma schedule, optional modules) if golden tests lock mflux-native sampling.\n\n",".cursor/skills/mflux-release/SKILL.md":"---\nname: mflux-release\ndescription: Prepare a release in mflux (version bump + uv lock; release notes are harvested from PR release-note blocks and live in GitHub Releases). Use when preparing a release branch or release PR.\n---\n# mflux release prep\n\nReleases are prepared in-repo; tagging/publishing is handled by GitHub Actions\n(`release.yml`, dispatched from main with the `publish` confirmation).\n\n## How notes work now (#685)\n\n- Every PR carries a fenced ` ```release-note ` block in its body (CI enforces it;\n  every PR gets a note, and contributors do not write `none`). That block is the only source of release notes.\n- On dispatch, the ungated `draft-notes` job harvests the blocks for every PR whose\n  squash commit is in `previous-tag..HEAD` and fills a DRAFT GitHub release, grouped\n  by label.\n- Whoever approves the `pypi` deployment reads and edits that draft (fixing any\n  `[needs edit]` lines, adding contributor thanks if wanted); the gated job publishes\n  it exactly as edited. A re-dispatch never overwrites an existing draft; delete the\n  draft to re-harvest.\n- There is no `CHANGELOG.md`: the notes live in GitHub Releases (https://github.com/mflux-community/mflux/releases).\n\n## Release-prep PR checklist\n\n- Bump version in `pyproject.toml`\n- Update lockfile: `uv lock`\n- Release-note block of the prep PR itself: a note for contributors, for example `Prepare the <version> release.` Give the PR the `chore` label.\n- Prefer one commit named `release: prepare <version>`\n- Sanity checks (optional unless requested): `just test-fast`, `just build`\n- Do not tag releases locally unless explicitly requested (normally handled by CI)\n",".cursor/skills/mflux-testing/SKILL.md":"---\nname: mflux-testing\ndescription: Run tests in mflux (fast/slow/full), preserve image outputs, and handle golden image diffs safely.\n---\n# mflux testing\n\nThis repo uses pytest with image-producing tests. Always preserve outputs for inspection and **never** update reference images unless explicitly asked.\n\n## When to Use\n\n- You need to run tests (fast/slow/full) or debug failing tests.\n- There are image/golden mismatches and you need to report paths/output for review.\n\n## Instructions\n\n- Prefer the justfile test recipes:\n  - `just test-fast` (fast tests, no image generation)\n  - `just test-slow` (slow tests, image generation)\n  - `just test` (default selection, skips slow model tests)\n  - `just test-all` (all except high-memory tests; slow tests download model weights)\n- Always keep `MFLUX_PRESERVE_TEST_OUTPUT=1` on test runs (already built into the justfile test recipes).\n- If a change affects defaults, config resolution, metadata fields, or CLI behavior, add or update tests that cover the changed behavior directly instead of relying only on manual verification.\n- If tests fail:\n  - Summarize the failing test names and the key assertion output.\n  - Point to any generated images/artifacts on disk for manual review.\n- Do **not** regenerate/replace reference (“golden”) images unless the user explicitly requests it.\n\n## Updating golden images (new model or hardware refresh)\n\nGolden tests compare generated PNGs to `tests/resources/reference_*.png` (typically 15% mismatch threshold).\n\n**When to update** (only with explicit user approval):\n- After validating the port on target hardware (CI Mac) via slow tests with `MFLUX_PRESERVE_TEST_OUTPUT=1`\n- After choosing a stable prompt/seed/settings via diffusers comparison and/or latent-injection confidence (`mflux-debugging`)\n- When old references used a bad prompt (e.g. ambiguous subject) or wrong seed for mflux’s RNG\n\n**Workflow**:\n1. Run slow test → inspect `tests/resources/output_*.png` vs `reference_*.png`\n2. If output is correct but reference is stale, re-run generation with same test parameters and replace reference PNGs\n3. Commit test + reference images together with a clear message (e.g. `test(<model>): update golden images for local hardware`)\n\n**Important**: Golden tests lock **mflux-native** sampling (`mx.random` + mflux schedulers), not diffusers pixel parity. A good diffusers side-by-side or injected-latent run builds confidence in the model code; the golden still reflects mflux’s full recipe on CI hardware.\n\n## Manual validation (config resolution + local model paths)\n\nUse when a change touches model config resolution, `mflux-save`, or the model’s generate CLI, or when a PR fixes local model-path handling for the model under investigation. Refer to the `mflux-cli` skill to find the correct generate command for the model you are testing.\n\n- Run a local-path quantize/save:\n  - Use the `mflux-cli` skill to look up the correct command and flags.\n  - Verify CLI usage with the command’s `--help` before running it.\n  - Save to a known location (e.g., Desktop) to make follow-up steps explicit.\n- Run generation from the saved model using the correct model-specific generate CLI:\n  - Use the `mflux-cli` skill to find the generate command and required flags.\n  - Verify CLI usage with the command’s `--help` before running it.\n- If the model has multiple size variants, repeat the above for each variant to confirm the correct overrides are applied.\n- Do not commit output artifacts; delete or leave them untracked.\n",".cursor/skills/asd-ste100/SKILL.md":"---\nname: asd-ste100\ndescription: \"Use when English text must be parsed without a human to resolve ambiguity — tool descriptions, error messages, inter-agent instructions, system prompts, status reports — and misreading has a real cost, or when text reads as dense, hedged, or easy to misparse. Triggers: disambiguate, STE100 rewrite, apply Simplified Technical English, plain-language rewrite, controlled-language rewrite, rewrite so an agent cannot misread this. Not for creative or marketing copy.\"\nmetadata:\n  version: 0.4.0\n---\n\n# Simplified Technical English (ASD-STE100)\n\nASD-STE100 is a controlled-language standard built by the aerospace and defense industry (ASD, the AeroSpace and Defense Industries Association of Europe) to stop maintenance technicians from misreading English instructions. The standard removes the two biggest sources of misreading: words with more than one meaning, and sentences with more than one possible structure.\n\nThis skill borrows that same discipline for a different reader: an **AI agent or a downstream system** that has to parse an English string — an error message, a tool description, an inter-agent instruction, a status report — without a human in the loop to resolve ambiguity. If a maintenance technician can misread \"close the valve\" as an adjective (\"the valve that is near\") instead of a command, so can a language model.\n\n## When to Use This Skill\n\n- An agent's output (explanation, instruction, log message, tool description) reads as dense, jargon-heavy, or ambiguous.\n- Text will be consumed by another agent, a translation pipeline, or a non-native English reader, and misparsing has a real cost.\n- You are writing a prompt, system message, or tool description and want to remove ambiguity before a model ever sees it.\n- You want a **before/after** comparison showing exactly which rule was violated and how the rewrite fixes it. Ask for it — the default output is the rewritten text alone (see Output Format).\n\nThis skill is not for creative or marketing copy — STE is deliberately flat and literal. Do not apply it to text where voice, nuance, or persuasion is the point.\n\n## Two Modes\n\nPick a mode before rewriting. If the user does not say which, infer it from the text type. Keep the choice internal unless the user asks for the rule table (see Output Format).\n\n**Strict** — procedures, error messages, tool and function descriptions, inter-agent instructions, safety text. Anywhere a wrong reading has a cost. Apply every rule below, including the hard length caps and one-word-one-meaning discipline.\n\n**STE-flavored** — READMEs, PR descriptions, changelogs, explanatory prose. Apply the structural rules in full and treat the lexical rules as advisory (see Core Rewrite Rules for that split). In practice that means keeping the sentence length caps, active voice, simple tenses, no phrasal verbs, no semicolons, no nominalization and no marketing adjectives, while dropping the one-word-one-meaning lockdown: prose needs some range, and a strict rewrite of prose reads as a personality transplant rather than a clarification.\n\nThe two modes and the structural/lexical split are the same distinction seen from two directions. The split says which rules this skill can verify without ASD's dictionary. The modes say which of them to enforce for a given kind of text.\n\n## Source and Scope\n\nThis skill encodes the **rule categories** of ASD-STE100 Issue 9 (Jan 2025): 53 writing rules across 9 sections covering word choice, grammar, sentence structure, and style, backed by a dictionary of ~900 approved words (one meaning, one part of speech each) and ~1,200 words to avoid with suggested replacements. See `references/writing-rules.md` for the full rule summary and citations.\n\nIt does **not** reproduce ASD's ~900-word approved dictionary verbatim. ASD-STE100 is free to obtain, but it is not free to redistribute: Issue 9, page 2 states that \"no reproduction or publication of it, in whole or in part, shall be made without the written authority of an officer of ASD,\" and grants free reproduction rights only to eight listed categories (ASD/AIA/AIAC member associations and their member companies and customers, member-state defence ministries, A4A, airworthiness authorities, and universities and research institutes for educational purposes). This project is in none of them, so the dictionary stays out of this repo.\n\nInstead, this skill applies the *underlying principle* (pick the plainest, most common word available and use it the same way every time) rather than checking against a fixed word list. When exact ASD-approved wording matters (e.g. actual aircraft maintenance documentation), get the standard and check word-by-word against the real dictionary. Request it from the [official downloads page](https://www.asd-ste100.org/STE_downloads.html) — note that this is a request form that emails you a link, not a direct download.\n\n## Core Rewrite Rules\n\nSTE's rules divide into two kinds, and this skill can only fully deliver one of them. **Structural rules** are self-contained: they describe sentence shape, and you can apply them from the description alone. **Lexical rules** are defined entirely by the official ~900-word dictionary, which this skill deliberately does not reproduce (see Source and Scope). Without that dictionary, the lexical rules degrade from a checkable standard into a preference for plain words.\n\nApply the structural rules with confidence. Apply the lexical rules as a direction of travel, and say so in your output rather than implying dictionary compliance you cannot verify.\n\n### Structural rules — apply these\n\n| Rule | Do | Don't |\n|---|---|---|\n| Active voice | \"The agent deletes the file.\" | \"The file is deleted (by the agent).\" — unless the actor is genuinely unknown or irrelevant |\n| No phrasal verbs (Rule 9.3) | \"Remove the panel.\" / \"Start the job.\" | \"Take off the panel.\" / \"Spin up the job.\" — a two-word verb has meanings the parts do not predict |\n| One instruction per sentence | \"Open the file. Read line 3.\" | \"Open the file and read line 3, then check if it matches.\" |\n| Sentence length | ≤20 words for instructions/procedures, ≤25 words for descriptions | Long compound/subordinate-clause sentences |\n| No semicolons (Rule 8.1) | Split into separate sentences | Any semicolon at all — STE bans the mark outright, not only as a clause join. (Rule 8.1 permits every other standard punctuation mark. The em dash is *not* banned by STE, though it often signals a sentence that should be split.) |\n| Noun clusters | ≤3 words stacked as a noun phrase (\"fuel pump valve\") | 4+ word noun stacks (\"high pressure fuel pump inlet valve assembly\") |\n| No ellipsis | Keep the subject, verb, and article explicit even if it reads longer | Drop words to save space (\"Files not backed up will be lost\" → ambiguous which files) |\n| Keep modality | \"The request **may have** failed.\" stays \"may have\" | Promote a hedge to a fact (\"The request failed.\") or invent a certainty the source did not state |\n| Paragraph limits | One topic per paragraph, ≤6 sentences | Multi-topic paragraphs |\n| Lists for sequences | Use a numbered or bulleted list for 3+ steps or conditions | Bury a sequence inside one prose sentence |\n\n### Lexical rules — direction of travel only\n\n| Rule | Do | Don't | Why it is weaker here |\n|---|---|---|---|\n| One word, one meaning | Pick one verb for one action and reuse it every time (e.g. always \"check\", never mix \"check\"/\"verify\"/\"confirm\" for the same action) | Rotate synonyms for the same idea across a document | Consistency within a document is checkable. Which word is the *approved* one is not, without the dictionary. |\n| One part of speech per word | \"Apply oil to the valve\" (oil = noun) | \"Oil the valve\" (oil = verb) | Whether \"oil\" is approved as a noun only is a dictionary fact. Prefer the noun form when both read equally well. Do not claim compliance. |\n| Verb, not noun (Rule 3.7) | \"Analyze the log.\" | \"Perform an analysis of the log.\" — a noun form of an action makes the sentence longer and hides who acts | Rule 3.7 says \"use an **approved** verb to describe an action.\" Preferring the verb form is safe to apply anywhere. Knowing which verb is the approved one needs the dictionary. |\n| Domain terms | Keep necessary technical nouns/verbs, but define them once if not common English (STE allows a project-specific glossary beyond its base dictionary) | Use jargon without ever defining it | The glossary allowance is real STE, but the base dictionary it extends is absent. |\n\n### Simple tenses — apply with one exception\n\nSTE permits infinitive, imperative, simple present, simple past, simple future, and past participle as adjective. It excludes present perfect and other compound forms: \"we received the report\", not \"we have received the report\".\n\nAircraft manuals never need present perfect, so the exclusion costs the standard nothing. Other text is not always so lucky. \"The job has completed\" (and its output is available now) and \"the job completed\" (at some past point) are different statements, and status text frequently needs the first. **Where the compound form carries information the simple form cannot — current relevance, or a hedge as in \"may have failed\" — keep it and flag the departure.** Elsewhere, follow the rule.\n\n## Scan Checklist\n\nThese six habits cover most of what makes machine-written English hard to parse. Each one is mechanical: you can point at the exact word or punctuation mark that breaks the rule, with no judgment call. Scan for all six before you rewrite anything.\n\n1. **Synonym rotation** — the same thing gets several names in one document (\"the user\", \"the customer\", \"the client\"). The reader cannot tell whether they are one thing or three. Fix: pick one name, use it every time.\n2. **Hedge stacking** — helper verbs and qualifiers pile up until the sentence asserts nothing (\"it is important to note that this may potentially help to improve\"). Fix: state the claim, or delete it.\n3. **Nominalization** — an action frozen into a noun (\"perform an analysis of\", \"provides assistance to\"). Fix: use the verb (\"analyze\", \"helps\").\n4. **Marketing adjectives** — words that claim quality instead of showing it: seamless, robust, powerful, cutting-edge, effortless, blazing-fast. Fix: delete, or replace with the measurement that earns the claim.\n5. **Run-on sentences** — several ideas joined by semicolons or em dashes. Fix: one idea per sentence.\n6. **Soft phrasal verbs** — spin up, reach out, dive into, kick off. Fix: use the single plain verb (start, contact, read, begin).\n\n## Process\n\n1. Pick the mode (Strict or STE-flavored). Say which only when the user asked for the rule table — see Output Format.\n2. Read the input text once for meaning — do not start rewriting before you understand what it must still say afterward.\n3. Walk it sentence by sentence. Flag every rule violation from the Core Rewrite Rules tables and every habit from the Scan Checklist. In STE-flavored mode, flag the lexical rules but do not enforce them. For a mechanical first pass over the structural rules, run `scripts/ste-lint.py` (stdin or file args, `--json` for structured output); it checks semicolons, sentence length, phrasal verbs, nominalization, marketing adjectives, synonym rotation, dangling-conjunction in supported list items, passive voice, and compound tenses, and by design never flags hedges or modality. `--baseline N` tolerates N hard violations (for adopting on existing docs); `--disable rule1,rule2` silences named rules.\n4. Rewrite each flagged sentence to fix the violation while preserving the original meaning exactly. If a rewrite would drop necessary precision (a safety condition, a scope qualifier, a number), keep the longer phrasing and flag it instead of silently simplifying.\n   - **Check modality before you commit to a rewrite.** Hedges (\"may\", \"could\", \"sometimes\", \"is likely to\") carry the author's confidence, and confidence is content. A shorter sentence that upgrades a hedge to a fact is not a simplification — it is a different claim. This is the most common way a well-intentioned STE rewrite goes wrong, because hedges are exactly what a length cap tempts you to cut.\n   - Never add a fact the source did not state. A rewrite that reads better because it supplies a cause, a frequency, or a mechanism has stopped being a rewrite.\n5. Output the rewritten text (see Output Format). Keep the mode choice and the rule analysis internal unless the user asked to see them.\n6. If the input already complies, say so — do not force changes onto compliant text.\n\n## Output Format\n\n**Default: the rewritten text, and nothing else.** Most callers want a result they can paste straight into a tool description, an error string, or a prompt. Print the simplified text on its own. Do not add a preamble about this skill, a mode announcement, a violation count, a summary of what changed, a rule table, or a closing offer to explain further.\n\nThe one permitted addition: if step 4 kept a longer phrasing on purpose, add a single line after the text, prefixed `Kept as-is:`, naming the phrase and the precision that would have been lost. Omit the line when there is nothing to report.\n\n**On request: the rule table.** When the user asks to see the reasoning — \"show the diff\", \"which rules did it break\", \"explain the changes\", \"before/after\" — output this table instead:\n\n```markdown\n| Rule violated | Original | Simplified |\n|---|---|---|\n| Present perfect tense | \"We have received your request.\" | \"We received your request.\" |\n| Noun cluster (4+ words) | \"the agent task queue priority handler\" | \"the handler that sets task-queue priority\" |\n\nMode: Strict. 7 violations found.\n```\n\nFollow the table with a one-line note on anything you deliberately did **not** simplify, and why (usually: simplifying would lose required precision).\n\n## Boundaries\n\n**Will:**\n- Rewrite ambiguous or dense English into short, single-meaning, active-voice sentences.\n- Return the rewritten text alone by default, and name the rules it applied when the user asks.\n- Preserve every fact, condition, and scope qualifier in the original.\n- Preserve the strength of every hedge, and add no claim the source did not make.\n- Suggest a one-line glossary entry for domain terms that must stay.\n\n**Will not:**\n- Reproduce ASD's official ~900-word dictionary as if it were memorized verbatim — always treat the official download as the source of truth for exact approved wording.\n- Simplify creative, marketing, or persuasive copy where voice and nuance are the point.\n- Silently drop a safety condition, exception, or scope qualifier to shorten a sentence — it will flag the trade-off instead.\n- Convert \"may have failed\" into \"failed\", or \"could be caused by X\" into \"X is the cause\" — losing a hedge changes the claim.\n- Guarantee an aerospace/defense-grade STE-compliant document. This is a general-purpose clarity tool inspired by STE, not a certified STE authoring tool.\n- Make weak content true or useful. STE fixes the *form* of a text, not its substance. A hollow paragraph rewritten under these rules becomes a clean, short, well-punctuated hollow paragraph. If the text has nothing to say, no rewrite fixes that — say so instead of polishing it.\n- Shorten past the point of clarity. Cutting words is not the goal. Removing ambiguity is the goal. Past a certain point compression starts costing the reader time rather than saving it, so stop when the sentence is unambiguous, not when it is shortest.\n\n## Additional Resources\n\n- **`references/writing-rules.md`** — fuller summary of the 9 rule sections and dictionary structure, with citations to the official standard and secondary sources.\n- **`examples/before-after.md`** — worked examples, including official STE examples and agent-output examples built for this skill.\n- **`scripts/ste-lint.py`** — deterministic, stdlib-only linter for the structural rules, including dangling-conjunction in supported list items, plus a synonym-rotation check (one word, one meaning) scoped per file. Exit 1 when hard violations exceed `--baseline` (default 0); advisory findings (passive voice, compound tenses) never fail the run; `--disable` silences named rules. It never flags hedges or modality: those are content, not style, and `--selftest` asserts that \"may have failed\" passes clean.\n",".cursor/skills/mflux-manual-testing/SKILL.md":"---\nname: mflux-manual-testing\ndescription: Manually validate mflux CLIs by exercising the changed paths and reviewing output images/artifacts.\n---\n# mflux manual testing\n\nSome regressions (especially in CLIs and image IO) are easiest to catch by running the commands and visually inspecting outputs. This skill provides a lightweight, change-driven manual test checklist.\n\n## When to Use\n\n- You changed any CLI entrypoint(s) under `src/mflux/models/**/cli/`.\n- You touched callbacks (e.g. stepwise output, memory saver) or metadata/image saving.\n- Tests are green but you want confidence in real command usage.\n\n## Strategy (change-driven)\n\n- Identify what changed on your branch (new flags, default behavior changes, new callbacks, new models).\n- Only run manual checks for the touched areas; don’t try to exercise every CLI.\n- Prefer 1–2 seeds and a small step count (e.g. 4) for fast iteration, unless the change affects convergence/quality.\n- Before manual CLI testing, **reinstall the local tool executables** so you’re testing the latest code:\n\n```bash\nuv tool install --force --editable --reinstall .\n```\n\n## Core CLI checks (pick what’s relevant)\n\n- **Basic generation**: run the CLI once with a representative prompt and confirm the output is not “all noise”.\n- **Model saving** (if relevant): if you touched weight loading/saving or model definitions, run `mflux-save` for the affected model(s) and verify:\n  - the output directory is created\n  - the command completes without missing-file errors\n- **Run from disk** (if relevant): if you touched save/load paths or model resolution, generate from a locally saved model directory by passing `--model /full/path/to/saved-model` and confirm it runs and produces a sane image.\n- **Stepwise outputs** (if relevant): run with `--stepwise-image-output-dir` and confirm:\n  - step images are written for each step\n  - the final step image matches the final output image qualitatively\n  - the composite image is created\n- **Low-RAM path** (if relevant): run with `--low-ram` and confirm:\n  - generation completes\n  - output quality is sane (no unexpected all-noise output)\n- **Metadata** (if relevant): run with `--make-conf` and confirm that the CLI writes the `.metadata.json` sidecar and that it looks consistent.\n\n## Output review (human-in-the-loop)\n\n- Always point the human reviewer at:\n  - the final output image path\n  - any stepwise directory / composites\n  - any metadata JSON files\n- Ask the human to visually confirm “looks correct” rather than attempting pixel-perfect parity manually.\n\n## diffusers reference comparison (new model ports)\n\nmflux does not install diffusers; use a sibling clone (commonly `../diffusers` on Desktop).\n\n**When**: validating a new MLX port before merge, or when golden tests / visuals look wrong.\n\n**Match settings**: same prompt, width, height, seed, steps, guidance. For fair speed comparisons, match precision (mflux bf16 vs diffusers bf16, not `-q 8` vs bf16).\n\n**diffusers setup tips** (read the reference pipeline first):\n- Compare `model_index.json` / `from_pretrained` kwargs with mflux `get_download_patterns()` — disable or pass `None` for components mflux does not load\n- `local_files_only=True` / `HF_HUB_OFFLINE=1` to use cache and surface missing files early\n- Distilled vs base variants are often the same pipeline class with different checkpoint + steps/guidance\n\n**Run both**:\n```sh\n# mflux\nuv run mflux-generate-<model> --prompt \"...\" --width 640 --height 368 --seed 7 --steps 8 --guidance 1.0 --output /tmp/mflux.png\n\n# diffusers (from diffusers repo)\ncd ../diffusers && HF_HUB_OFFLINE=1 uv run python -c \"...\"  # inline script; see mflux-debugging\n```\n\n**If visuals differ**: do not assume the port is broken. Run the **latent injection** workflow in `mflux-debugging` to separate (a) transformer/VAE quality from (b) RNG/scheduler differences.\n\nSave comparison PNGs to explicit paths; report `/usr/bin/time -p` totals. Do not commit comparison artifacts.\n\n## Notes\n\n- If the installed `uv tool` executable behaves differently from `uv run python -m ...`, prefer the local module run to isolate environment/tooling issues.\n- If you need to reinstall the local tool executables, see the repo rules for the current recommended command.\n\n",".cursor/skills/mflux-debugging/SKILL.md":"---\nname: mflux-debugging\ndescription: Debug MLX ports by comparing against a PyTorch/diffusers reference via exported tensors/images (export-then-compare).\n---\n# mflux debugging (MLX parity vs PyTorch/diffusers)\n\nUse this skill when you are porting a model to MLX and need to **prove numerical parity** (or isolate where it diverges) versus a **PyTorch reference implementation** (often from diffusers).\n\nThis skill defaults to **export-then-compare**:\n- Run the reference once and **export deterministic artifacts** (tensors + optional images).\n- Load those artifacts in MLX and compare with clear thresholds.\n\n## When to Use\n\n- You suspect a port mismatch (wrong shapes/layout, RoPE, scheduler math, dtype casting, etc).\n- You want a repeatable workflow to narrow down the first layer/block where outputs diverge.\n- You need evidence of correctness before refactoring (see `mflux-model-porting`).\n\n## Ground Rules (repo norms)\n\n- Use `uv` to run Python: `uv run python -m ...`\n- If you run pytest, preserve outputs: `MFLUX_PRESERVE_TEST_OUTPUT=1` (see `mflux-testing` and the justfile test recipes).\n- Do **not** update or replace reference (“golden”) images unless explicitly asked.\n- Debug artifacts (tensor dumps) should live in a local folder and **must not be committed** unless explicitly asked.\n- If you need the broader porting workflow (milestones, ordering, when to refactor), follow `mflux-model-porting`.\n- **RNG warning**: PyTorch and MLX RNGs are different. Matching the same integer `seed` is not enough for parity—export the *exact* initial noise/latents from the reference and load them in MLX.\n- Practical setup: the PyTorch reference repo (often `diffusers/`) and `mflux/` are frequently **next to each other** on disk (e.g. both on your Desktop). Use absolute paths when in doubt.\n\n## Default Workflow (export-then-compare)\n\n### Preferred workflow: two tiny scripts + inline dumps\n\nFor day-to-day debugging, prefer a **minimal paired repro**:\n- One simple script in the reference repo (often `diffusers/`), e.g. `diffusers/flux2_klein_edit_debug.py`\n- One simple script in `mflux/`, e.g. `mflux/flux2_klein_edit_debug.py`\n\nKeep them “boring”: hardcoded variables, no cli, no framework, and just a few `np.savez(...)` / `mx.save(...)` lines at the right spot.\n\nThe key trick for RNG parity:\n- In the reference script, **compute latents once**, save them, then **pass them back into the pipeline** (`latents=...`) so the run definitely uses the dumped tensor.\n- In rare cases where a tensor needs to be saved from within a loop, make sure its name reflects the loop conditions (e.g the 4th noise predcition in a 10 step loop etc).\n- In the MLX script, **load that same latents file** and feed it into the MLX run (do not rely on matching integer seeds).\n\n### 1) Pick a single deterministic repro\n\n- Fix **seed(s)**, **prompt(s)**, **height/width**, **steps**, **guidance**, and any **input image** paths.\n- Keep the first repro small if possible (fewer steps, smaller resolution) to iterate quickly.\n\n### 2) Decide your checkpoints (what to dump)\n\nStart coarse, then narrow:\n- **VAE**: packed latents before decode; optional intermediate activations for one block if needed.\n- **Transformer**: hidden states at entry/exit of the model, then per-block (or every N blocks), then inside attention/MLP.\n- **Text encoder**: token ids + attention mask, embeddings output, then per-layer hidden states if needed.\n- **Scheduler**: timesteps/sigmas/alphas and the predicted noise/velocity per step.\n\nTip: work “backwards from pixels” like `mflux-model-porting` suggests: validate VAE decode first with exported latents, then the diffusion/transformer loop, then text encoder.\n\n### 3) Export artifacts from the PyTorch reference (no logic changes)\n\nCreate a run directory like:\n- `./debug_artifacts/<run_id>/ref/`\n\nExport with one of these patterns:\n- **NumPy**: `np.savez(path, **tensors_as_numpy)`\n- **PyTorch**: `torch.save(dict_of_tensors, path)`\n\n### 4) Run the MLX side with the same inputs and compare\n\nCreate a matching run directory:\n- `./debug_artifacts/<run_id>/mlx/`\n\nLoad and compare tensors. For each checkpoint, report:\n- **Shape + dtype**\n- **max_abs_diff**, **mean_abs_diff**\n- **max_rel_diff** (guarding division by zero)\n- Pass/fail with a clearly stated **rtol/atol**\n- It is **more important to inspect actual tensor values** (e.g., first 10 elements) than rely on summary stats.\n- Statistics can mislead; small-looking stats can hide systematic drift or sign flips.\n- Prefer **runtime tensor dumps** over code reading; code can use different conventions yet still represent the same math.\n\nSuggested tolerance starting points (adjust per component):\n- **fp32 comparisons**: `atol=1e-5`, `rtol=1e-5`\n- **fp16/bf16 comparisons**: `atol=1e-2`, `rtol=1e-2`\n- If comparing images: compare both (a) tensor space before final clamp and (b) saved `png` visually, since tiny numeric diffs can look identical.\n\nIf a checkpoint fails:\n- Add an **earlier** checkpoint and repeat (binary search through the forward path).\n\n## Common Causes of Divergence (high-signal checklist)\n\n- **Layout mistakes**: NCHW vs NHWC, transposes around convs/attention, flatten/reshape ordering. Some operations like convolutions can have different conventions between libraries.\n- **Broadcasting**: scale/shift vectors applied on the wrong axis (common in RoPE and modulation).\n- **Dtype casting**: reference silently upcasts to fp32 for norm/softmax; MLX path stays in fp16.\n- **RoPE details**: position ids, reshape order, whether cos/sin are broadcast over heads vs sequence.\n- **Scheduler math**: timestep indexing, sigma/alpha definitions, and off-by-one step order.\n- **Scheduler config**: compare sigma schedules directly.\n- **Seed/RNG**: ensure you aren’t comparing stochastic paths (dropout, noise sampling) without controlling RNG.\n- **Device dtype**: MPS `float16` can produce NaNs; prefer `bfloat16` for reference dumps if you see NaNs.\n- **Do not use CPU** for comparisons; always keep reference runs on MPS to avoid misleading behavior.\n\n## Artifact Hygiene\n\n- Prefer `debug_artifacts/<run_id>/...` at repo root.\n- Do not commit `debug_artifacts/` unless explicitly asked.\n- If you convert the parity check into a test, follow the repo’s testing conventions and preserve outputs (see `mflux-testing`).\n- Clean up old artifacts when they are no longer needed, only focus on the current problem and avoid confusion with older artifacts that are not relevant for the current task.\n\n## Isolate transformer + VAE (inject reference initial latents)\n\nWhen full end-to-end images differ between mflux and diffusers but you need to trust the **core model** (transformer, text encoder, VAE decode), export the reference **initial noise** and run mflux denoising from that tensor. If injected-latent mflux looks good while native-seed runs differ, the forward path is likely sound and any gap is probably RNG, scheduler, or optional reference-only components.\n\n**Do not commit** these scripts or Desktop `.npy` files unless asked. Use inline `uv run python <<'PY' ... PY` heredocs in the reference repo and in `mflux/`.\n\n### Step 1 — Export initial latents from diffusers\n\nRun from the local `diffusers/` clone (often next to `mflux/` on Desktop). Match mflux settings: height, width, seed, dtype (`bfloat16` on MPS).\n\nLoad the reference pipeline the same way you would for a normal generation, but **disable optional subsystems** that mflux does not implement or download (check `model_index.json` vs mflux `get_download_patterns()` / weight definition). Pass `None` for unused components, set pipeline flags to skip them, and use `local_files_only=True` so missing weights surface immediately instead of downloading extras.\n\nThen export noise with the same shape helper the pipeline uses internally:\n\n```python\nfrom diffusers.utils.torch_utils import randn_tensor\n\npipe = <ReferencePipeline>.from_pretrained(\n    \"<org/model>\",\n    torch_dtype=torch.bfloat16,\n    local_files_only=True,\n    # plus any kwargs to omit optional reference-only modules\n)\nlatent_h = height // pipe.vae_scale_factor  # or read from pipeline/config\nlatent_w = width // pipe.vae_scale_factor\nch = pipe.transformer.config.in_channels    # name varies by architecture\ngenerator = torch.Generator(device=\"mps\").manual_seed(seed)\nlatents = randn_tensor(\n    (1, ch, latent_h, latent_w),\n    generator=generator,\n    device=\"mps\",\n    dtype=torch.bfloat16,\n)\nnp.save(\"/path/to/init_latent.npy\", latents.detach().cpu().float().numpy())\n```\n\n### Step 2 — Denoise in mflux from the loaded latent\n\nIf `generate_image()` has no `latents=` argument, **inline the denoising loop** from the variant class instead of patching production code:\n\n1. `latents = mx.array(np.load(path)).astype(mx.bfloat16)`\n2. Text encode step from the variant (e.g. `_encode_prompts`, prompt cache, etc.)\n3. Any position encoding / conditioning setup the variant does before the loop\n4. Denoise loop: noise prediction + `config.scheduler.step(...)` over `config.time_steps`\n5. VAE decode + `ImageUtil.to_image(...)` (or the variant’s decode helper) → save PNG\n\nAlso run one `generate_image(seed=...)` baseline on the same prompt for side-by-side.\n\n### How to read results\n\n| Comparison | What it tells you |\n|---|---|\n| mflux native seed vs itself (re-run) | Sampling is deterministic on this hardware |\n| mflux + diffusers latent vs diffusers full run | Transformer + VAE + CFG path quality |\n| mflux native seed vs diffusers full run | **Not** a parity test — different RNG (`mx.random` vs `torch.Generator`) and often different sigma schedules |\n| mflux + diffusers latent vs mflux native seed | Large diff is **expected** if schedulers/sigmas differ, even with identical starting noise |\n\nIf **injected-latent mflux** looks good, the port’s core forward path is trustworthy. Golden CI tests should still lock **mflux-native** sampling (see `mflux-testing`), not diffusers pixel parity.\n\n## diffusers reference runs (side-by-side images)\n\n- mflux does **not** depend on diffusers; run reference scripts from a sibling `diffusers/` clone with `cd .../diffusers && uv run python`.\n- Use `HF_HUB_OFFLINE=1` when weights are cached to catch missing components the reference pipeline expects but mflux omits from its download patterns.\n- Compare at matched resolution, steps, guidance, seed, and precision when possible (note mflux `-q 8` vs diffusers bf16 is not apples-to-apples for speed or pixels).\n- Save outputs to explicit paths (e.g. Desktop) and report wall time with `/usr/bin/time -p`.\n\n## See Also\n\n- `mflux-model-porting`: correctness-first workflow (validate components and lock behavior before refactor).\n- `mflux-testing`: how to run tests safely and handle image outputs/goldens.\n\n","AGENTS.md":"# AI Agent Protocol & Instructions\n\nPath: `AGENTS.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/AGENTS.md)",".claude/skills/asd-ste100":"# Claude Directive: asd-ste100\n\nPath: `.claude/skills/asd-ste100`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/asd-ste100)",".claude/skills/mflux-cli":"# Claude Directive: mflux-cli\n\nPath: `.claude/skills/mflux-cli`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-cli)",".claude/skills/mflux-debugging":"# Claude Directive: mflux-debugging\n\nPath: `.claude/skills/mflux-debugging`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-debugging)",".claude/skills/mflux-dev-env":"# Claude Directive: mflux-dev-env\n\nPath: `.claude/skills/mflux-dev-env`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-dev-env)",".claude/skills/mflux-manual-testing":"# Claude Directive: mflux-manual-testing\n\nPath: `.claude/skills/mflux-manual-testing`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-manual-testing)",".claude/skills/mflux-model-porting":"# Claude Directive: mflux-model-porting\n\nPath: `.claude/skills/mflux-model-porting`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-porting)",".claude/skills/mflux-model-tiny-test":"# Claude Directive: mflux-model-tiny-test\n\nPath: `.claude/skills/mflux-model-tiny-test`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-tiny-test)",".claude/skills/mflux-pr":"# Claude Directive: mflux-pr\n\nPath: `.claude/skills/mflux-pr`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr)",".claude/skills/mflux-pr-docs":"# Claude Directive: mflux-pr-docs\n\nPath: `.claude/skills/mflux-pr-docs`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr-docs)",".claude/skills/mflux-release":"# Claude Directive: mflux-release\n\nPath: `.claude/skills/mflux-release`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-release)",".claude/skills/mflux-testing":"# Claude Directive: mflux-testing\n\nPath: `.claude/skills/mflux-testing`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-testing)",".cursor/rules/RULE.md":"# Rules Skill\n\nPath: `.cursor/rules/RULE.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/rules/RULE.md)",".cursor/skills/asd-ste100/README.md":"# Asd-ste100 Skill\n\nPath: `.cursor/skills/asd-ste100/README.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/README.md)",".cursor/skills/mflux-pr-docs/pr-what-prompt.md":"# Mflux-pr-docs Skill\n\nPath: `.cursor/skills/mflux-pr-docs/pr-what-prompt.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/pr-what-prompt.md)",".cursor/skills/mflux-pr-docs/release-note-prompt.md":"# Mflux-pr-docs Skill\n\nPath: `.cursor/skills/mflux-pr-docs/release-note-prompt.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/release-note-prompt.md)",".cursor/skills/asd-ste100/examples/before-after.md":"# Examples Skill\n\nPath: `.cursor/skills/asd-ste100/examples/before-after.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/before-after.md)",".cursor/skills/asd-ste100/examples/linter-edge-cases.md":"# Examples Skill\n\nPath: `.cursor/skills/asd-ste100/examples/linter-edge-cases.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/linter-edge-cases.md)",".cursor/skills/asd-ste100/references/writing-rules.md":"# References Skill\n\nPath: `.cursor/skills/asd-ste100/references/writing-rules.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/references/writing-rules.md)"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/AGENTS.md","title":"AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","content":"# AI Agent Protocol & Instructions\n\nPath: `AGENTS.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/AGENTS.md)","tokens":300,"sizeBytes":151},{"name":"SKILL.md","path":".agents/skills/remediating-dependabot/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.agents/skills/remediating-dependabot/SKILL.md","title":"remediating-dependabot","category":"anthropic-skill","format":"markdown","content":"---\nname: remediating-dependabot\ndescription: Remediates GitHub Dependabot alerts for mflux in one dependency-security change. Use when auditing, clamping, or upgrading Python dependencies in pyproject.toml and uv.lock, or when validating whether a branch will close Dependabot findings before opening a PR.\n---\n\n# Remediating Dependabot\n\nResolve actionable Dependabot alerts with the smallest compatible dependency update and prove the local lock is outside every reported vulnerable range.\n\n## Scope\n\n- Use `gh api` as the source of truth for open alerts in `mflux-community/mflux`.\n- Keep dependency changes in `pyproject.toml` and `uv.lock` unless compatibility requires source changes.\n- Preserve supported Python and platform markers.\n- Avoid unrelated package upgrades when regenerating the lock.\n- Treat dependency optionality or loading refactors as separate work unless explicitly requested.\n\n## Workflow\n\n1. Confirm the current branch and working tree before editing.\n2. Fetch all open Dependabot alerts, following pagination:\n\n   ```bash\n   gh api --method GET --paginate \\\n     -H \"Accept: application/vnd.github+json\" \\\n     repos/mflux-community/mflux/dependabot/alerts \\\n     -f state=open\n   ```\n\n3. Group alerts by manifest, package, severity, vulnerable range, and first patched version. Distinguish direct requirements from transitive lock entries.\n4. Inspect `pyproject.toml`, `uv.lock`, supported Python versions, and platform markers before choosing a fix.\n5. Prefer, in order:\n   - removing dependencies that are no longer needed;\n   - raising a direct lower bound to the first secure compatible release;\n   - upgrading only affected transitive packages in the lock;\n   - adding or changing environment markers only when compatibility actually differs by Python or platform.\n6. Use one requirement when a release supports the full project matrix. Do not introduce overlapping marker-specific requirements without evidence that they are necessary.\n7. Regenerate the lock with targeted upgrades:\n\n   ```bash\n   uv lock --upgrade-package <package> [--upgrade-package <package> ...]\n   ```\n\n8. Review the lock diff. Explain large platform-specific resolver changes, especially PyTorch CUDA package transitions, rather than assuming they are accidental.\n\n## Security verification\n\nDo not infer alert closure solely from package names or Dependabot's hosted UI.\n\n1. Run lock and advisory checks:\n\n   ```bash\n   uv lock --check\n   uv audit --preview-features audit-command\n   ```\n\n2. Parse every resolved version in `uv.lock` and compare it with every open alert's `security_vulnerability.vulnerable_version_range`. Canonicalize names with `packaging.utils.canonicalize_name` and use `packaging.specifiers.SpecifierSet` so matching follows Python package name and version semantics.\n3. Confirm that each alert is resolved by either:\n   - no matching package remaining in the lock; or\n   - every matching locked version falling outside the vulnerable range.\n4. Run Dependabot Core against the local checkout before opening a PR:\n\n   ```bash\n   tmp_dir=\"$(mktemp -d)\"\n   trap 'rm -rf \"$tmp_dir\"' EXIT\n   job=\"$tmp_dir/job.yml\"\n   output=\"$tmp_dir/output.yml\"\n\n   # Build the security job at \"$job\" before running these commands.\n   dependabot graph uv mflux-community/mflux --local \"$PWD\"\n   dependabot update --local \"$PWD\" -f \"$job\" -o \"$output\" --pull=false --timeout 20m\n   ```\n\n   `graph` is experimental and may return an incomplete dependency list. Both commands snapshot the directory passed to `--local`, including modified and untracked files, so confirm that the working tree contains only the intended updater input.\n\n   Build the temporary `uv` security job from the exact package names and advisory ranges returned by GitHub. Parse the YAML output rather than relying on the command's exit status:\n\n   ```bash\n   uv run python - \"$output\" <<'PY'\n   import sys\n\n   import yaml\n\n   with open(sys.argv[1]) as output_file:\n       actions = {entry[\"type\"] for entry in yaml.safe_load(output_file)[\"output\"]}\n\n   if \"mark_as_processed\" not in actions:\n       raise SystemExit(\"Dependabot did not mark the job as processed\")\n\n   pull_request_actions = actions & {\"create_pull_request\", \"update_pull_request\"}\n   if pull_request_actions:\n       raise SystemExit(f\"Dependabot still proposes actions: {sorted(pull_request_actions)}\")\n   PY\n   ```\n\n   Do not pin Dependabot CLI to one release. Verify the installed CLI exposes the commands and flags used here before running the job.\n5. Keep temporary Dependabot job and output files outside the committed change, and remove them after verification.\n6. If the hosted alert remains open while the local lock is already outside its vulnerable range, report it as pending or stale until GitHub rescans. Do not force an unnecessary upgrade just to change the lock entry.\n\n## Project verification\n\nRun the repository workflows after the lock is secure:\n\n```bash\njust lint\njust lint-justfile\njust typecheck\njust test-fast\njust test\njust build\ngit diff --check\n```\n\nUse `uv lock --upgrade --dry-run` to check that a fresh universal resolution succeeds. It may report unrelated newer releases; do not add them unless they are needed for the remediation.\n\n## Reporting\n\nReport:\n\n- total open findings expected to close, grouped by severity and package;\n- direct requirement changes and noteworthy lock-only changes;\n- packages removed from the lock;\n- exact results from range comparison, Dependabot Core, `uv audit`, and project checks;\n- any alerts whose final hosted closure depends on GitHub rescanning the merged lockfile.\n","frontmatter":{"name":"remediating-dependabot","description":"Remediates GitHub Dependabot alerts for mflux in one dependency-security change. Use when auditing, clamping, or upgrading Python dependencies in pyproject.toml and uv.lock, or when validating whether a branch will close Dependabot findings before opening a PR."},"isInternal":false,"tokens":1201,"sizeBytes":5587},{"name":"RULE.md","path":".cursor/rules/RULE.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/rules/RULE.md","title":"Rules Skill","category":"anthropic-skill","format":"markdown","content":"# Rules Skill\n\nPath: `.cursor/rules/RULE.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/rules/RULE.md)","tokens":300,"sizeBytes":154},{"name":"before-after.md","path":".cursor/skills/asd-ste100/examples/before-after.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/before-after.md","title":"Examples Skill","category":"anthropic-skill","format":"markdown","content":"# Examples Skill\n\nPath: `.cursor/skills/asd-ste100/examples/before-after.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/before-after.md)","tokens":300,"sizeBytes":215},{"name":"linter-edge-cases.md","path":".cursor/skills/asd-ste100/examples/linter-edge-cases.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/linter-edge-cases.md","title":"Examples Skill","category":"anthropic-skill","format":"markdown","content":"# Examples Skill\n\nPath: `.cursor/skills/asd-ste100/examples/linter-edge-cases.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/linter-edge-cases.md)","tokens":300,"sizeBytes":225},{"name":"README.md","path":".cursor/skills/asd-ste100/README.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/README.md","title":"Asd-ste100 Skill","category":"anthropic-skill","format":"markdown","content":"# Asd-ste100 Skill\n\nPath: `.cursor/skills/asd-ste100/README.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/README.md)","tokens":300,"sizeBytes":187},{"name":"writing-rules.md","path":".cursor/skills/asd-ste100/references/writing-rules.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/references/writing-rules.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# References Skill\n\nPath: `.cursor/skills/asd-ste100/references/writing-rules.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/references/writing-rules.md)","tokens":300,"sizeBytes":223},{"name":"SKILL.md","path":".cursor/skills/asd-ste100/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/SKILL.md","title":"asd-ste100","category":"anthropic-skill","format":"markdown","content":"---\nname: asd-ste100\ndescription: \"Use when English text must be parsed without a human to resolve ambiguity — tool descriptions, error messages, inter-agent instructions, system prompts, status reports — and misreading has a real cost, or when text reads as dense, hedged, or easy to misparse. Triggers: disambiguate, STE100 rewrite, apply Simplified Technical English, plain-language rewrite, controlled-language rewrite, rewrite so an agent cannot misread this. Not for creative or marketing copy.\"\nmetadata:\n  version: 0.4.0\n---\n\n# Simplified Technical English (ASD-STE100)\n\nASD-STE100 is a controlled-language standard built by the aerospace and defense industry (ASD, the AeroSpace and Defense Industries Association of Europe) to stop maintenance technicians from misreading English instructions. The standard removes the two biggest sources of misreading: words with more than one meaning, and sentences with more than one possible structure.\n\nThis skill borrows that same discipline for a different reader: an **AI agent or a downstream system** that has to parse an English string — an error message, a tool description, an inter-agent instruction, a status report — without a human in the loop to resolve ambiguity. If a maintenance technician can misread \"close the valve\" as an adjective (\"the valve that is near\") instead of a command, so can a language model.\n\n## When to Use This Skill\n\n- An agent's output (explanation, instruction, log message, tool description) reads as dense, jargon-heavy, or ambiguous.\n- Text will be consumed by another agent, a translation pipeline, or a non-native English reader, and misparsing has a real cost.\n- You are writing a prompt, system message, or tool description and want to remove ambiguity before a model ever sees it.\n- You want a **before/after** comparison showing exactly which rule was violated and how the rewrite fixes it. Ask for it — the default output is the rewritten text alone (see Output Format).\n\nThis skill is not for creative or marketing copy — STE is deliberately flat and literal. Do not apply it to text where voice, nuance, or persuasion is the point.\n\n## Two Modes\n\nPick a mode before rewriting. If the user does not say which, infer it from the text type. Keep the choice internal unless the user asks for the rule table (see Output Format).\n\n**Strict** — procedures, error messages, tool and function descriptions, inter-agent instructions, safety text. Anywhere a wrong reading has a cost. Apply every rule below, including the hard length caps and one-word-one-meaning discipline.\n\n**STE-flavored** — READMEs, PR descriptions, changelogs, explanatory prose. Apply the structural rules in full and treat the lexical rules as advisory (see Core Rewrite Rules for that split). In practice that means keeping the sentence length caps, active voice, simple tenses, no phrasal verbs, no semicolons, no nominalization and no marketing adjectives, while dropping the one-word-one-meaning lockdown: prose needs some range, and a strict rewrite of prose reads as a personality transplant rather than a clarification.\n\nThe two modes and the structural/lexical split are the same distinction seen from two directions. The split says which rules this skill can verify without ASD's dictionary. The modes say which of them to enforce for a given kind of text.\n\n## Source and Scope\n\nThis skill encodes the **rule categories** of ASD-STE100 Issue 9 (Jan 2025): 53 writing rules across 9 sections covering word choice, grammar, sentence structure, and style, backed by a dictionary of ~900 approved words (one meaning, one part of speech each) and ~1,200 words to avoid with suggested replacements. See `references/writing-rules.md` for the full rule summary and citations.\n\nIt does **not** reproduce ASD's ~900-word approved dictionary verbatim. ASD-STE100 is free to obtain, but it is not free to redistribute: Issue 9, page 2 states that \"no reproduction or publication of it, in whole or in part, shall be made without the written authority of an officer of ASD,\" and grants free reproduction rights only to eight listed categories (ASD/AIA/AIAC member associations and their member companies and customers, member-state defence ministries, A4A, airworthiness authorities, and universities and research institutes for educational purposes). This project is in none of them, so the dictionary stays out of this repo.\n\nInstead, this skill applies the *underlying principle* (pick the plainest, most common word available and use it the same way every time) rather than checking against a fixed word list. When exact ASD-approved wording matters (e.g. actual aircraft maintenance documentation), get the standard and check word-by-word against the real dictionary. Request it from the [official downloads page](https://www.asd-ste100.org/STE_downloads.html) — note that this is a request form that emails you a link, not a direct download.\n\n## Core Rewrite Rules\n\nSTE's rules divide into two kinds, and this skill can only fully deliver one of them. **Structural rules** are self-contained: they describe sentence shape, and you can apply them from the description alone. **Lexical rules** are defined entirely by the official ~900-word dictionary, which this skill deliberately does not reproduce (see Source and Scope). Without that dictionary, the lexical rules degrade from a checkable standard into a preference for plain words.\n\nApply the structural rules with confidence. Apply the lexical rules as a direction of travel, and say so in your output rather than implying dictionary compliance you cannot verify.\n\n### Structural rules — apply these\n\n| Rule | Do | Don't |\n|---|---|---|\n| Active voice | \"The agent deletes the file.\" | \"The file is deleted (by the agent).\" — unless the actor is genuinely unknown or irrelevant |\n| No phrasal verbs (Rule 9.3) | \"Remove the panel.\" / \"Start the job.\" | \"Take off the panel.\" / \"Spin up the job.\" — a two-word verb has meanings the parts do not predict |\n| One instruction per sentence | \"Open the file. Read line 3.\" | \"Open the file and read line 3, then check if it matches.\" |\n| Sentence length | ≤20 words for instructions/procedures, ≤25 words for descriptions | Long compound/subordinate-clause sentences |\n| No semicolons (Rule 8.1) | Split into separate sentences | Any semicolon at all — STE bans the mark outright, not only as a clause join. (Rule 8.1 permits every other standard punctuation mark. The em dash is *not* banned by STE, though it often signals a sentence that should be split.) |\n| Noun clusters | ≤3 words stacked as a noun phrase (\"fuel pump valve\") | 4+ word noun stacks (\"high pressure fuel pump inlet valve assembly\") |\n| No ellipsis | Keep the subject, verb, and article explicit even if it reads longer | Drop words to save space (\"Files not backed up will be lost\" → ambiguous which files) |\n| Keep modality | \"The request **may have** failed.\" stays \"may have\" | Promote a hedge to a fact (\"The request failed.\") or invent a certainty the source did not state |\n| Paragraph limits | One topic per paragraph, ≤6 sentences | Multi-topic paragraphs |\n| Lists for sequences | Use a numbered or bulleted list for 3+ steps or conditions | Bury a sequence inside one prose sentence |\n\n### Lexical rules — direction of travel only\n\n| Rule | Do | Don't | Why it is weaker here |\n|---|---|---|---|\n| One word, one meaning | Pick one verb for one action and reuse it every time (e.g. always \"check\", never mix \"check\"/\"verify\"/\"confirm\" for the same action) | Rotate synonyms for the same idea across a document | Consistency within a document is checkable. Which word is the *approved* one is not, without the dictionary. |\n| One part of speech per word | \"Apply oil to the valve\" (oil = noun) | \"Oil the valve\" (oil = verb) | Whether \"oil\" is approved as a noun only is a dictionary fact. Prefer the noun form when both read equally well. Do not claim compliance. |\n| Verb, not noun (Rule 3.7) | \"Analyze the log.\" | \"Perform an analysis of the log.\" — a noun form of an action makes the sentence longer and hides who acts | Rule 3.7 says \"use an **approved** verb to describe an action.\" Preferring the verb form is safe to apply anywhere. Knowing which verb is the approved one needs the dictionary. |\n| Domain terms | Keep necessary technical nouns/verbs, but define them once if not common English (STE allows a project-specific glossary beyond its base dictionary) | Use jargon without ever defining it | The glossary allowance is real STE, but the base dictionary it extends is absent. |\n\n### Simple tenses — apply with one exception\n\nSTE permits infinitive, imperative, simple present, simple past, simple future, and past participle as adjective. It excludes present perfect and other compound forms: \"we received the report\", not \"we have received the report\".\n\nAircraft manuals never need present perfect, so the exclusion costs the standard nothing. Other text is not always so lucky. \"The job has completed\" (and its output is available now) and \"the job completed\" (at some past point) are different statements, and status text frequently needs the first. **Where the compound form carries information the simple form cannot — current relevance, or a hedge as in \"may have failed\" — keep it and flag the departure.** Elsewhere, follow the rule.\n\n## Scan Checklist\n\nThese six habits cover most of what makes machine-written English hard to parse. Each one is mechanical: you can point at the exact word or punctuation mark that breaks the rule, with no judgment call. Scan for all six before you rewrite anything.\n\n1. **Synonym rotation** — the same thing gets several names in one document (\"the user\", \"the customer\", \"the client\"). The reader cannot tell whether they are one thing or three. Fix: pick one name, use it every time.\n2. **Hedge stacking** — helper verbs and qualifiers pile up until the sentence asserts nothing (\"it is important to note that this may potentially help to improve\"). Fix: state the claim, or delete it.\n3. **Nominalization** — an action frozen into a noun (\"perform an analysis of\", \"provides assistance to\"). Fix: use the verb (\"analyze\", \"helps\").\n4. **Marketing adjectives** — words that claim quality instead of showing it: seamless, robust, powerful, cutting-edge, effortless, blazing-fast. Fix: delete, or replace with the measurement that earns the claim.\n5. **Run-on sentences** — several ideas joined by semicolons or em dashes. Fix: one idea per sentence.\n6. **Soft phrasal verbs** — spin up, reach out, dive into, kick off. Fix: use the single plain verb (start, contact, read, begin).\n\n## Process\n\n1. Pick the mode (Strict or STE-flavored). Say which only when the user asked for the rule table — see Output Format.\n2. Read the input text once for meaning — do not start rewriting before you understand what it must still say afterward.\n3. Walk it sentence by sentence. Flag every rule violation from the Core Rewrite Rules tables and every habit from the Scan Checklist. In STE-flavored mode, flag the lexical rules but do not enforce them. For a mechanical first pass over the structural rules, run `scripts/ste-lint.py` (stdin or file args, `--json` for structured output); it checks semicolons, sentence length, phrasal verbs, nominalization, marketing adjectives, synonym rotation, dangling-conjunction in supported list items, passive voice, and compound tenses, and by design never flags hedges or modality. `--baseline N` tolerates N hard violations (for adopting on existing docs); `--disable rule1,rule2` silences named rules.\n4. Rewrite each flagged sentence to fix the violation while preserving the original meaning exactly. If a rewrite would drop necessary precision (a safety condition, a scope qualifier, a number), keep the longer phrasing and flag it instead of silently simplifying.\n   - **Check modality before you commit to a rewrite.** Hedges (\"may\", \"could\", \"sometimes\", \"is likely to\") carry the author's confidence, and confidence is content. A shorter sentence that upgrades a hedge to a fact is not a simplification — it is a different claim. This is the most common way a well-intentioned STE rewrite goes wrong, because hedges are exactly what a length cap tempts you to cut.\n   - Never add a fact the source did not state. A rewrite that reads better because it supplies a cause, a frequency, or a mechanism has stopped being a rewrite.\n5. Output the rewritten text (see Output Format). Keep the mode choice and the rule analysis internal unless the user asked to see them.\n6. If the input already complies, say so — do not force changes onto compliant text.\n\n## Output Format\n\n**Default: the rewritten text, and nothing else.** Most callers want a result they can paste straight into a tool description, an error string, or a prompt. Print the simplified text on its own. Do not add a preamble about this skill, a mode announcement, a violation count, a summary of what changed, a rule table, or a closing offer to explain further.\n\nThe one permitted addition: if step 4 kept a longer phrasing on purpose, add a single line after the text, prefixed `Kept as-is:`, naming the phrase and the precision that would have been lost. Omit the line when there is nothing to report.\n\n**On request: the rule table.** When the user asks to see the reasoning — \"show the diff\", \"which rules did it break\", \"explain the changes\", \"before/after\" — output this table instead:\n\n```markdown\n| Rule violated | Original | Simplified |\n|---|---|---|\n| Present perfect tense | \"We have received your request.\" | \"We received your request.\" |\n| Noun cluster (4+ words) | \"the agent task queue priority handler\" | \"the handler that sets task-queue priority\" |\n\nMode: Strict. 7 violations found.\n```\n\nFollow the table with a one-line note on anything you deliberately did **not** simplify, and why (usually: simplifying would lose required precision).\n\n## Boundaries\n\n**Will:**\n- Rewrite ambiguous or dense English into short, single-meaning, active-voice sentences.\n- Return the rewritten text alone by default, and name the rules it applied when the user asks.\n- Preserve every fact, condition, and scope qualifier in the original.\n- Preserve the strength of every hedge, and add no claim the source did not make.\n- Suggest a one-line glossary entry for domain terms that must stay.\n\n**Will not:**\n- Reproduce ASD's official ~900-word dictionary as if it were memorized verbatim — always treat the official download as the source of truth for exact approved wording.\n- Simplify creative, marketing, or persuasive copy where voice and nuance are the point.\n- Silently drop a safety condition, exception, or scope qualifier to shorten a sentence — it will flag the trade-off instead.\n- Convert \"may have failed\" into \"failed\", or \"could be caused by X\" into \"X is the cause\" — losing a hedge changes the claim.\n- Guarantee an aerospace/defense-grade STE-compliant document. This is a general-purpose clarity tool inspired by STE, not a certified STE authoring tool.\n- Make weak content true or useful. STE fixes the *form* of a text, not its substance. A hollow paragraph rewritten under these rules becomes a clean, short, well-punctuated hollow paragraph. If the text has nothing to say, no rewrite fixes that — say so instead of polishing it.\n- Shorten past the point of clarity. Cutting words is not the goal. Removing ambiguity is the goal. Past a certain point compression starts costing the reader time rather than saving it, so stop when the sentence is unambiguous, not when it is shortest.\n\n## Additional Resources\n\n- **`references/writing-rules.md`** — fuller summary of the 9 rule sections and dictionary structure, with citations to the official standard and secondary sources.\n- **`examples/before-after.md`** — worked examples, including official STE examples and agent-output examples built for this skill.\n- **`scripts/ste-lint.py`** — deterministic, stdlib-only linter for the structural rules, including dangling-conjunction in supported list items, plus a synonym-rotation check (one word, one meaning) scoped per file. Exit 1 when hard violations exceed `--baseline` (default 0); advisory findings (passive voice, compound tenses) never fail the run; `--disable` silences named rules. It never flags hedges or modality: those are content, not style, and `--selftest` asserts that \"may have failed\" passes clean.\n","frontmatter":{"name":"asd-ste100","description":"Use when English text must be parsed without a human to resolve ambiguity — tool descriptions, error messages, inter-agent instructions, system prompts, status reports — and misreading has a real cost, or when text reads as dense, hedged, or easy to misparse. Triggers: disambiguate, STE100 rewrite, apply Simplified Technical English, plain-language rewrite, controlled-language rewrite, rewrite so an agent cannot misread this. Not for creative or marketing copy.","metadata":{"version":"0.4.0"}},"isInternal":false,"tokens":3620,"sizeBytes":16430},{"name":"SKILL.md","path":".cursor/skills/mflux-cli/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-cli/SKILL.md","title":"mflux-cli","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-cli\ndescription: Navigate MFLUX CLI capabilities, locate commands by area, and summarize supported features.\n---\n# mflux CLI navigation\n\nUse this skill to inventory CLI capabilities, summarize what the CLI supports, and guide where to look\nfor commands without relying on brittle file paths.\nBecause README examples can drift, prefer verifying support against the current CLI entrypoints.\n\n## When to use\n\n- You need to list supported CLI features or commands.\n- You need to find where a capability is implemented in the CLI.\n- You are documenting or refactoring CLI features and want a stable map.\n- A user asks for CLI help, e.g., “Can you help me generate an image using z-image?”, “Which model is best?”, etc.\n\n## How to find commands (structure, not exact paths)\n\n- Common/shared CLI arguments live in the central CLI parser module.\n- Model-specific CLI entrypoints live under each model's CLI package.\n- Repo-level CLI helpers (completions, defaults) live under the shared CLI package.\n- Utilities may add standalone CLIs (e.g., metadata info, LoRA library).\n\n## Best practices when constructing CLI calls\n\n- **Inference steps**: When constructing a CLI call for any model, *always* check `MODEL_INFERENCE_STEPS` and use the model's default/recommended step count unless the user explicitly asks for a different value. This is especially important for distilled/non-base variants (for example `fibo-lite`, `z-image-turbo`, and other `*-turbo`/`*-lite` models), where using full/base-model step counts is usually counterproductive.\n- **Resource/inspection flags**: Mention `--low-ram` to reduce memory usage and `--stepwise-image-output-dir` for stepwise outputs when useful.\n- **Python API requests**: If a user asks for the Python API, treat the equivalent CLI script as the best starting reference for the underlying parameters and defaults.\n- **CLI implementation changes**: When adding or changing CLI behavior, prefer extending shared parser methods and shared helpers before adding manual one-off arguments or save paths in a model CLI.\n- **Docs/examples drift**: If CLI defaults, supported flags, or recommended usage changed, update the matching README examples in the same pass.\n\n## Capability inventory (current)\n\n### Core generation\n\n- Text-to-image across Flux, Flux2, FLUX 3 Image Klein, Iris-3B, SenseNova-U1.5, DreamLite, Qwen, Z-Image Turbo, FIBO.\n- Image-to-image where supported (Flux, Qwen, Z-Image Turbo, FIBO).\n\n### Editing and conditioning\n\n- Kontext image conditioning.\n- In-context editing and reference-image workflows.\n- CATVTON (virtual try-on).\n- Redux multi-image conditioning.\n- ControlNet (Canny).\n- Depth conditioning.\n- Fill / inpainting.\n- Flux2 Edit, FLUX 3 Image Klein edit (1-10 reference images) and Qwen Edit (multi-image edit).\n- DreamLite edit (one image, instruction-based).\n\n### Upscaling\n\n- SeedVR2 diffusion upscaler (preferred).\n- Flux ControlNet upscaler (legacy).\n\n### Model management\n\n- Quantized inference and saving quantized models.\n- Local model path loading (with base-model hints when needed).\n\n### LoRA\n\n- Load LoRAs, multi-LoRA, scale control.\n- In-context style LoRA shortcuts.\n- LoRA library lookup tool.\n\n### Metadata and reproducibility\n\n- Export JSON metadata per image.\n- Reuse prior parameters from metadata config files.\n- Inspect metadata from existing images.\n\n### Prompt tooling\n\n- Prompt files.\n- Negative prompts where supported (not supported for Flux2, FLUX 3 Image Klein or SenseNova-U1.5; Iris-3B uses them only on the base model).\n\n### Training\n\n- LoRA finetuning.\n\n### Utilities\n\n- DepthPro depth-map extraction.\n- FIBO VLM prompt inspire/refine tools.\n","frontmatter":{"name":"mflux-cli","description":"Navigate MFLUX CLI capabilities, locate commands by area, and summarize supported features."},"isInternal":false,"tokens":828,"sizeBytes":3660},{"name":"SKILL.md","path":".cursor/skills/mflux-debugging/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-debugging/SKILL.md","title":"mflux-debugging","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-debugging\ndescription: Debug MLX ports by comparing against a PyTorch/diffusers reference via exported tensors/images (export-then-compare).\n---\n# mflux debugging (MLX parity vs PyTorch/diffusers)\n\nUse this skill when you are porting a model to MLX and need to **prove numerical parity** (or isolate where it diverges) versus a **PyTorch reference implementation** (often from diffusers).\n\nThis skill defaults to **export-then-compare**:\n- Run the reference once and **export deterministic artifacts** (tensors + optional images).\n- Load those artifacts in MLX and compare with clear thresholds.\n\n## When to Use\n\n- You suspect a port mismatch (wrong shapes/layout, RoPE, scheduler math, dtype casting, etc).\n- You want a repeatable workflow to narrow down the first layer/block where outputs diverge.\n- You need evidence of correctness before refactoring (see `mflux-model-porting`).\n\n## Ground Rules (repo norms)\n\n- Use `uv` to run Python: `uv run python -m ...`\n- If you run pytest, preserve outputs: `MFLUX_PRESERVE_TEST_OUTPUT=1` (see `mflux-testing` and the justfile test recipes).\n- Do **not** update or replace reference (“golden”) images unless explicitly asked.\n- Debug artifacts (tensor dumps) should live in a local folder and **must not be committed** unless explicitly asked.\n- If you need the broader porting workflow (milestones, ordering, when to refactor), follow `mflux-model-porting`.\n- **RNG warning**: PyTorch and MLX RNGs are different. Matching the same integer `seed` is not enough for parity—export the *exact* initial noise/latents from the reference and load them in MLX.\n- Practical setup: the PyTorch reference repo (often `diffusers/`) and `mflux/` are frequently **next to each other** on disk (e.g. both on your Desktop). Use absolute paths when in doubt.\n\n## Default Workflow (export-then-compare)\n\n### Preferred workflow: two tiny scripts + inline dumps\n\nFor day-to-day debugging, prefer a **minimal paired repro**:\n- One simple script in the reference repo (often `diffusers/`), e.g. `diffusers/flux2_klein_edit_debug.py`\n- One simple script in `mflux/`, e.g. `mflux/flux2_klein_edit_debug.py`\n\nKeep them “boring”: hardcoded variables, no cli, no framework, and just a few `np.savez(...)` / `mx.save(...)` lines at the right spot.\n\nThe key trick for RNG parity:\n- In the reference script, **compute latents once**, save them, then **pass them back into the pipeline** (`latents=...`) so the run definitely uses the dumped tensor.\n- In rare cases where a tensor needs to be saved from within a loop, make sure its name reflects the loop conditions (e.g the 4th noise predcition in a 10 step loop etc).\n- In the MLX script, **load that same latents file** and feed it into the MLX run (do not rely on matching integer seeds).\n\n### 1) Pick a single deterministic repro\n\n- Fix **seed(s)**, **prompt(s)**, **height/width**, **steps**, **guidance**, and any **input image** paths.\n- Keep the first repro small if possible (fewer steps, smaller resolution) to iterate quickly.\n\n### 2) Decide your checkpoints (what to dump)\n\nStart coarse, then narrow:\n- **VAE**: packed latents before decode; optional intermediate activations for one block if needed.\n- **Transformer**: hidden states at entry/exit of the model, then per-block (or every N blocks), then inside attention/MLP.\n- **Text encoder**: token ids + attention mask, embeddings output, then per-layer hidden states if needed.\n- **Scheduler**: timesteps/sigmas/alphas and the predicted noise/velocity per step.\n\nTip: work “backwards from pixels” like `mflux-model-porting` suggests: validate VAE decode first with exported latents, then the diffusion/transformer loop, then text encoder.\n\n### 3) Export artifacts from the PyTorch reference (no logic changes)\n\nCreate a run directory like:\n- `./debug_artifacts/<run_id>/ref/`\n\nExport with one of these patterns:\n- **NumPy**: `np.savez(path, **tensors_as_numpy)`\n- **PyTorch**: `torch.save(dict_of_tensors, path)`\n\n### 4) Run the MLX side with the same inputs and compare\n\nCreate a matching run directory:\n- `./debug_artifacts/<run_id>/mlx/`\n\nLoad and compare tensors. For each checkpoint, report:\n- **Shape + dtype**\n- **max_abs_diff**, **mean_abs_diff**\n- **max_rel_diff** (guarding division by zero)\n- Pass/fail with a clearly stated **rtol/atol**\n- It is **more important to inspect actual tensor values** (e.g., first 10 elements) than rely on summary stats.\n- Statistics can mislead; small-looking stats can hide systematic drift or sign flips.\n- Prefer **runtime tensor dumps** over code reading; code can use different conventions yet still represent the same math.\n\nSuggested tolerance starting points (adjust per component):\n- **fp32 comparisons**: `atol=1e-5`, `rtol=1e-5`\n- **fp16/bf16 comparisons**: `atol=1e-2`, `rtol=1e-2`\n- If comparing images: compare both (a) tensor space before final clamp and (b) saved `png` visually, since tiny numeric diffs can look identical.\n\nIf a checkpoint fails:\n- Add an **earlier** checkpoint and repeat (binary search through the forward path).\n\n## Common Causes of Divergence (high-signal checklist)\n\n- **Layout mistakes**: NCHW vs NHWC, transposes around convs/attention, flatten/reshape ordering. Some operations like convolutions can have different conventions between libraries.\n- **Broadcasting**: scale/shift vectors applied on the wrong axis (common in RoPE and modulation).\n- **Dtype casting**: reference silently upcasts to fp32 for norm/softmax; MLX path stays in fp16.\n- **RoPE details**: position ids, reshape order, whether cos/sin are broadcast over heads vs sequence.\n- **Scheduler math**: timestep indexing, sigma/alpha definitions, and off-by-one step order.\n- **Scheduler config**: compare sigma schedules directly.\n- **Seed/RNG**: ensure you aren’t comparing stochastic paths (dropout, noise sampling) without controlling RNG.\n- **Device dtype**: MPS `float16` can produce NaNs; prefer `bfloat16` for reference dumps if you see NaNs.\n- **Do not use CPU** for comparisons; always keep reference runs on MPS to avoid misleading behavior.\n\n## Artifact Hygiene\n\n- Prefer `debug_artifacts/<run_id>/...` at repo root.\n- Do not commit `debug_artifacts/` unless explicitly asked.\n- If you convert the parity check into a test, follow the repo’s testing conventions and preserve outputs (see `mflux-testing`).\n- Clean up old artifacts when they are no longer needed, only focus on the current problem and avoid confusion with older artifacts that are not relevant for the current task.\n\n## Isolate transformer + VAE (inject reference initial latents)\n\nWhen full end-to-end images differ between mflux and diffusers but you need to trust the **core model** (transformer, text encoder, VAE decode), export the reference **initial noise** and run mflux denoising from that tensor. If injected-latent mflux looks good while native-seed runs differ, the forward path is likely sound and any gap is probably RNG, scheduler, or optional reference-only components.\n\n**Do not commit** these scripts or Desktop `.npy` files unless asked. Use inline `uv run python <<'PY' ... PY` heredocs in the reference repo and in `mflux/`.\n\n### Step 1 — Export initial latents from diffusers\n\nRun from the local `diffusers/` clone (often next to `mflux/` on Desktop). Match mflux settings: height, width, seed, dtype (`bfloat16` on MPS).\n\nLoad the reference pipeline the same way you would for a normal generation, but **disable optional subsystems** that mflux does not implement or download (check `model_index.json` vs mflux `get_download_patterns()` / weight definition). Pass `None` for unused components, set pipeline flags to skip them, and use `local_files_only=True` so missing weights surface immediately instead of downloading extras.\n\nThen export noise with the same shape helper the pipeline uses internally:\n\n```python\nfrom diffusers.utils.torch_utils import randn_tensor\n\npipe = <ReferencePipeline>.from_pretrained(\n    \"<org/model>\",\n    torch_dtype=torch.bfloat16,\n    local_files_only=True,\n    # plus any kwargs to omit optional reference-only modules\n)\nlatent_h = height // pipe.vae_scale_factor  # or read from pipeline/config\nlatent_w = width // pipe.vae_scale_factor\nch = pipe.transformer.config.in_channels    # name varies by architecture\ngenerator = torch.Generator(device=\"mps\").manual_seed(seed)\nlatents = randn_tensor(\n    (1, ch, latent_h, latent_w),\n    generator=generator,\n    device=\"mps\",\n    dtype=torch.bfloat16,\n)\nnp.save(\"/path/to/init_latent.npy\", latents.detach().cpu().float().numpy())\n```\n\n### Step 2 — Denoise in mflux from the loaded latent\n\nIf `generate_image()` has no `latents=` argument, **inline the denoising loop** from the variant class instead of patching production code:\n\n1. `latents = mx.array(np.load(path)).astype(mx.bfloat16)`\n2. Text encode step from the variant (e.g. `_encode_prompts`, prompt cache, etc.)\n3. Any position encoding / conditioning setup the variant does before the loop\n4. Denoise loop: noise prediction + `config.scheduler.step(...)` over `config.time_steps`\n5. VAE decode + `ImageUtil.to_image(...)` (or the variant’s decode helper) → save PNG\n\nAlso run one `generate_image(seed=...)` baseline on the same prompt for side-by-side.\n\n### How to read results\n\n| Comparison | What it tells you |\n|---|---|\n| mflux native seed vs itself (re-run) | Sampling is deterministic on this hardware |\n| mflux + diffusers latent vs diffusers full run | Transformer + VAE + CFG path quality |\n| mflux native seed vs diffusers full run | **Not** a parity test — different RNG (`mx.random` vs `torch.Generator`) and often different sigma schedules |\n| mflux + diffusers latent vs mflux native seed | Large diff is **expected** if schedulers/sigmas differ, even with identical starting noise |\n\nIf **injected-latent mflux** looks good, the port’s core forward path is trustworthy. Golden CI tests should still lock **mflux-native** sampling (see `mflux-testing`), not diffusers pixel parity.\n\n## diffusers reference runs (side-by-side images)\n\n- mflux does **not** depend on diffusers; run reference scripts from a sibling `diffusers/` clone with `cd .../diffusers && uv run python`.\n- Use `HF_HUB_OFFLINE=1` when weights are cached to catch missing components the reference pipeline expects but mflux omits from its download patterns.\n- Compare at matched resolution, steps, guidance, seed, and precision when possible (note mflux `-q 8` vs diffusers bf16 is not apples-to-apples for speed or pixels).\n- Save outputs to explicit paths (e.g. Desktop) and report wall time with `/usr/bin/time -p`.\n\n## See Also\n\n- `mflux-model-porting`: correctness-first workflow (validate components and lock behavior before refactor).\n- `mflux-testing`: how to run tests safely and handle image outputs/goldens.\n\n","frontmatter":{"name":"mflux-debugging","description":"Debug MLX ports by comparing against a PyTorch/diffusers reference via exported tensors/images (export-then-compare)."},"isInternal":false,"tokens":2565,"sizeBytes":10775},{"name":"SKILL.md","path":".cursor/skills/mflux-dev-env/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-dev-env/SKILL.md","title":"mflux-dev-env","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-dev-env\ndescription: Set up and work in the mflux dev environment (arm64 expectation, uv, justfile recipes, lint/format/test).\n---\n# mflux dev environment\n\nThis repo expects macOS arm64 and prefers `uv` + justfile recipes.\n\n## When to Use\n\n- You’re setting up the repo locally or diagnosing environment/setup issues.\n- You need the canonical way to run lint/format/check/build/test.\n\n## Instructions\n\n- Prereq: `just` ≥ 1.50 (`brew install just`). CI lints the justfile with `just --fmt --check`; run `just fmt-justfile` to auto-fix formatting.\n- Prefer justfile recipes:\n  - Install: `just install`\n  - Lint: `just lint`\n  - Format: `just format`\n  - Pre-commit suite: `just check`\n  - Build: `just build`\n- Prefer `uv run ...` for running Python commands to ensure the correct environment.\n- When running tests, keep `MFLUX_PRESERVE_TEST_OUTPUT=1` enabled (the justfile test recipes already do this).\n\n## Type checking (ty)\n\n- The type checker is astral's `ty`, pinned exactly in `pyproject.toml` dev deps (mirrored in `.pre-commit-config.yaml` and run in CI). Run it with `just typecheck` (or `uv run ty check`).\n- `[tool.ty.rules]` in `pyproject.toml` carries a one-time migration baseline (mypy → ty): every rule listed there had pre-existing violations and is set to `\"ignore\"`, with violation counts in comments.\n- **Planned burn-down**: we intend to re-enable these rules piecemeal — delete one ignore line, fix all resulting `ty check` errors, commit, repeat. Prefer starting with low-count rules. Do not add new ignore lines; new code must pass all rules not in the baseline.\n\n","frontmatter":{"name":"mflux-dev-env","description":"Set up and work in the mflux dev environment (arm64 expectation, uv, justfile recipes, lint/format/test)."},"isInternal":false,"tokens":406,"sizeBytes":1611},{"name":"SKILL.md","path":".cursor/skills/mflux-manual-testing/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-manual-testing/SKILL.md","title":"mflux-manual-testing","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-manual-testing\ndescription: Manually validate mflux CLIs by exercising the changed paths and reviewing output images/artifacts.\n---\n# mflux manual testing\n\nSome regressions (especially in CLIs and image IO) are easiest to catch by running the commands and visually inspecting outputs. This skill provides a lightweight, change-driven manual test checklist.\n\n## When to Use\n\n- You changed any CLI entrypoint(s) under `src/mflux/models/**/cli/`.\n- You touched callbacks (e.g. stepwise output, memory saver) or metadata/image saving.\n- Tests are green but you want confidence in real command usage.\n\n## Strategy (change-driven)\n\n- Identify what changed on your branch (new flags, default behavior changes, new callbacks, new models).\n- Only run manual checks for the touched areas; don’t try to exercise every CLI.\n- Prefer 1–2 seeds and a small step count (e.g. 4) for fast iteration, unless the change affects convergence/quality.\n- Before manual CLI testing, **reinstall the local tool executables** so you’re testing the latest code:\n\n```bash\nuv tool install --force --editable --reinstall .\n```\n\n## Core CLI checks (pick what’s relevant)\n\n- **Basic generation**: run the CLI once with a representative prompt and confirm the output is not “all noise”.\n- **Model saving** (if relevant): if you touched weight loading/saving or model definitions, run `mflux-save` for the affected model(s) and verify:\n  - the output directory is created\n  - the command completes without missing-file errors\n- **Run from disk** (if relevant): if you touched save/load paths or model resolution, generate from a locally saved model directory by passing `--model /full/path/to/saved-model` and confirm it runs and produces a sane image.\n- **Stepwise outputs** (if relevant): run with `--stepwise-image-output-dir` and confirm:\n  - step images are written for each step\n  - the final step image matches the final output image qualitatively\n  - the composite image is created\n- **Low-RAM path** (if relevant): run with `--low-ram` and confirm:\n  - generation completes\n  - output quality is sane (no unexpected all-noise output)\n- **Metadata** (if relevant): run with `--make-conf` and confirm that the CLI writes the `.metadata.json` sidecar and that it looks consistent.\n\n## Output review (human-in-the-loop)\n\n- Always point the human reviewer at:\n  - the final output image path\n  - any stepwise directory / composites\n  - any metadata JSON files\n- Ask the human to visually confirm “looks correct” rather than attempting pixel-perfect parity manually.\n\n## diffusers reference comparison (new model ports)\n\nmflux does not install diffusers; use a sibling clone (commonly `../diffusers` on Desktop).\n\n**When**: validating a new MLX port before merge, or when golden tests / visuals look wrong.\n\n**Match settings**: same prompt, width, height, seed, steps, guidance. For fair speed comparisons, match precision (mflux bf16 vs diffusers bf16, not `-q 8` vs bf16).\n\n**diffusers setup tips** (read the reference pipeline first):\n- Compare `model_index.json` / `from_pretrained` kwargs with mflux `get_download_patterns()` — disable or pass `None` for components mflux does not load\n- `local_files_only=True` / `HF_HUB_OFFLINE=1` to use cache and surface missing files early\n- Distilled vs base variants are often the same pipeline class with different checkpoint + steps/guidance\n\n**Run both**:\n```sh\n# mflux\nuv run mflux-generate-<model> --prompt \"...\" --width 640 --height 368 --seed 7 --steps 8 --guidance 1.0 --output /tmp/mflux.png\n\n# diffusers (from diffusers repo)\ncd ../diffusers && HF_HUB_OFFLINE=1 uv run python -c \"...\"  # inline script; see mflux-debugging\n```\n\n**If visuals differ**: do not assume the port is broken. Run the **latent injection** workflow in `mflux-debugging` to separate (a) transformer/VAE quality from (b) RNG/scheduler differences.\n\nSave comparison PNGs to explicit paths; report `/usr/bin/time -p` totals. Do not commit comparison artifacts.\n\n## Notes\n\n- If the installed `uv tool` executable behaves differently from `uv run python -m ...`, prefer the local module run to isolate environment/tooling issues.\n- If you need to reinstall the local tool executables, see the repo rules for the current recommended command.\n\n","frontmatter":{"name":"mflux-manual-testing","description":"Manually validate mflux CLIs by exercising the changed paths and reviewing output images/artifacts."},"isInternal":false,"tokens":999,"sizeBytes":4268},{"name":"SKILL.md","path":".cursor/skills/mflux-model-porting/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-model-porting/SKILL.md","title":"mflux-model-porting","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-model-porting\ndescription: Port ML models into mflux/MLX with correctness-first validation, then refactor toward mflux style.\n---\n# mflux model porting\n\n## Goal\nProvide 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.\n\n## Principles\n- Match the reference implementation first; prove correctness before cleanup.\n- Lock correctness with deterministic tests before refactoring.\n- 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.\n- Refactor toward shared components and clean APIs once tests are green.\n- 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.\n\n## Workflow (checklist)\n1. **Scope and parity**\n   - Define target parity (outputs, speed, memory) and acceptable tolerances.\n   - Identify reference files, configs, and checkpoints to mirror.\n   - Draft a Cursor plan for the port and review it before starting implementation.\n2. **Port fast to reference**\n   - Add the model package skeleton and a variant class + initializer.\n   - Follow standard mflux initializer/weight-loading style; review recent ports like `z_image_turbo` and `flux2_klein` for structure and naming.\n   - Wire weight definitions/mappings early so loading is exercised (implement quantization in the initializer, but skip it during early runs).\n   - Keep the first implementation simple and explicit; defer `mx.compile` and other speed-focused changes until deterministic parity is passing.\n   - When defining explicit weight mappings, inspect actual tensor values from the model in the Hugging Face cache to confirm names and shapes.\n   - 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).\n   - Add lightweight shape checks close to the code paths.\n   - Use `mx.save`/`mx.load` at critical points; it is OK to add these to the reference (without changing logic) to export latents.\n3. **Port order (work backwards from image)**\n   - Typical image generation flow: `prompt → text_encoder → transformer_loop → VAE → image`.\n   - For porting, invert the order so you can validate pixel space early.\n   - Start with VAE decode/encode to validate output images quickly:\n     - Export packed latents from the reference just before VAE decode.\n     - Load latents inline and decode to an image for visual inspection.\n     - Run an encode→decode roundtrip to sanity check reconstruction; a good-looking image reconstruction increases confidence in the implementation.\n     - 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.\n   - Then port the transformer loop and its schedulers with intermediate latent checks.\n     - If the reference uses a novel scheduler, port it; otherwise, reuse the existing mflux scheduler.\n   - Finish with the text encoder and tokenizer details.\n   - After each major component is validated (e.g., VAE, transformer, text encoder), commit with a clear milestone message like \"VAE done\" to preserve progress.\n    - Once the full port is working, remove any loaded tensors or debug artifacts so no traces remain.\n4. **Deterministic validation**\n   - Create a deterministic MLX test (image or tensor) that locks the output.\n   - Run tests via `MFLUX_PRESERVE_TEST_OUTPUT=1 uv run <test command>`.\n   - If MLX OOMs on sensible inputs (e.g., 1024×1024), assume a likely porting mistake and re-check shapes or memory-heavy ops.\n5. **Post-test refactor (explicit step)**\n   - Review commits after the first deterministic test to capture refactoring preferences.\n   - Consolidate shared components into common modules.\n   - Remove debug paths and one-off schedulers once validated.\n   - Move configuration defaults into standard config/scheduler paths.\n    - Simplify and decompose large files into focused modules once behavior is locked.\n    - Prefer shared scheduler implementations when they already exist in mflux.\n    - Ensure CLIs register callbacks via `CallbackManager.register_callbacks(...)` so shared features like `--stepwise-image-output-dir` work; pass a `latent_creator` that supports `unpack_latents(...)`.\n    - Keep running the deterministic image test during refactors to avoid regressions.\n   - Align the variant class with recent ports (`flux2_klein`, `z_image`): `prompt_cache`, merged `_predict`, RoPE setup inside predict path, `_decode_latents` helper, no verbose comments/docstrings (see repo `RULE.md`).\n   - Strip dead scaffolding (e.g. unused gradient-checkpointing flags) once training/inference paths are stable.\n6. **Pre-merge polish (after core port works)**\n   - **diffusers sanity check**: run matched mflux + diffusers generations; use `mflux-debugging` latent injection if outputs disagree but you need to validate transformer/VAE.\n   - **Golden tests**: pick prompt/seed/settings that are stable on target CI hardware; update reference PNGs only after explicit approval (see `mflux-testing`).\n   - **img2img**: verify latent packing/normalization on the img2img path matches txt2img and training (especially when reusing a shared VAE from another model family). `pack_latents` must accept the 5D `(B, C, 1, H, W)` tensor that tiled VAE encode (`vae_encode_tiled`) returns — squeeze the singleton temporal axis first, as `flux2`/`fibo`/`z_image` latent creators do; a 4D-only unpack (or a bare passthrough `pack_latents`) breaks tiled img2img. This is reachable via `--low-ram`: `MemorySaver` sets `tiling_config = TilingConfig()` (`vae_encode_tiled=True`), so always test img2img with `--low-ram`, not just the default path (which is safe only because `VAEUtil.encode` squeezes 5D→4D when tiling is off).\n   - **Cross-model touch points**: list every file outside `models/<your_model>/`; justify shared changes (`memory_saver` tiling guard, shared VAE `tiling_config`, training `runner` wiring). Drop unrelated edits (e.g. personal `.gitignore` entries).\n   - **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 `du` on HF cache and/or `mflux-save` + `du -sh` for quantized sizes.\n   - **Training**: example JSON under `models/common/training/_example/`, un-ignore in `.gitignore`, fast unit tests for training-adapter preview defaults.\n   - Re-run `just lint`, `just test-fast`, then slow golden tests before merge.\n7. **Finalize**\n   - Re-run tests and basic perf checks after polish.\n   - Add CLI/pipeline defaults and completions later, once core output is stable.\n   - Ensure the model is wired into the standard surfaces:\n     - `ModelConfig` entry + aliases\n     - Thin model CLI entrypoint that uses shared parser/config/callback patterns and a command class with `validate`, `load` and `generate` (see [Command class](#command-class-validate-load-generate))\n     - README following the structure and tone of existing model READMEs\n     - Python API example that matches the CLI/defaults\n   - Document any new mapping rules, shape constraints, or tolerances.\n\n## Package layout (reference: `flux2`)\n\nUse `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.\n\n```\n{model}/\n  {model}_initializer.py\n  __init__.py                    # export variant + initializer\n  README.md\n  cli/\n    {model}_generate.py          # (+ edit/turbo CLIs when applicable)\n  latent_creator/\n    {model}_latent_creator.py\n  model/\n    {model}_text_encoder/        # prompt_encoder.py, tokenizer pieces, text_encoder.py\n    {model}_transformer/         # attention, blocks, rope, transformer.py (split files)\n    {model}_vae/                 # or reuse shared VAE (e.g. flux2_vae) — document in README\n    {model}_scheduler/           # only when not covered by models/common/schedulers\n  variants/\n    __init__.py                  # re-export public variant class(es)\n    txt2img/\n      __init__.py\n      {model}.py                 # e.g. flux2_klein.py, ideogram4.py\n    edit/                        # when the model supports image-conditioned generation\n      __init__.py\n      {model}_edit.py\n  weights/\n    __init__.py\n    {model}_weight_definition.py # components, download patterns, tokenizers\n    {model}_weight_mapping.py    # WeightTarget list / key transforms for base weights\n    {model}_lora_mapping.py      # LoRA key aliases (diffusers, PEFT, kohya) — when LoRA is supported\n  training_adapter/              # when mflux-train is supported\n    {model}_training_adapter.py\n```\n\n**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`.\n\n**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).\n\n**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`.\n\n**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.\n\n## Integration surfaces checklist (don’t forget)\n\nPast [closed PRs](https://github.com/mflux-community/mflux/pulls?q=is%3Apr+is%3Aclosed) show the same wiring gaps recurring on every new model. Use this as a **tick list** alongside the workflow above — not every row applies to every model (e.g. skip vision-encoder rows for txt2img-only), but scan it before opening a port PR.\n\n### Repo wiring (required for every new model family)\n\n| Surface | What to do |\n|---|---|\n| `pyproject.toml` | Register `mflux-generate-<model>` (and edit/turbo variants if separate) |\n| `ModelConfig` | Entry in `AVAILABLE_MODELS`: aliases, HF repo id, `num_train_steps`, guidance support, sigma shift, `transformer_overrides`, distilled vs base step defaults |\n| `models/common/resolution/model_revisions.py` | Pin every HF repo the model downloads (`model_name`, ControlNet, helper repos) to the full commit hash its golden references were generated with. `tests/resolution/test_model_revisions.py` fails for a registry repo without a pin. |\n| `scripts/ci_extract_models.py` | Add an `OVERLAY` row for every new `AVAILABLE_MODELS` key: taxonomy, CLI/tool commands, status, and quantization support. Use `EXTRA_ENTRIES` only for standalone tools with no `ModelConfig` entry. Run `just ci-extract` and confirm the model is present in `.ci_cache/models_mflux.json`. |\n| `cli/defaults/defaults.py` | `MODEL_INFERENCE_STEPS` (keyed by the canonical `AVAILABLE_MODELS` key — the `--model` choices derive from the registry, nothing to add there) |\n| `models/common/cli/save.py` | Route `mflux-save` to the **correct variant class** (txt2img vs edit vs turbo — wrong class silently drops weights; see [#405](https://github.com/mflux-community/mflux/pull/405)) |\n| Main `README.md` | Model table row + attribution line |\n| `src/mflux/models/<model>/README.md` | Examples aligned with Flux2-style layout; disk sizes measured (`du`, `mflux-save`) |\n| `src/mflux/assets/` | Hero/showcase image if other models have one (`git add -f` when `*.jpg` is gitignored) |\n\n### Weights, tokenizer, download scope\n\n| Surface | What to do |\n|---|---|\n| `*WeightDefinition` | `get_components()`, `get_download_patterns()`, `get_tokenizers()` — **only** list artifacts mflux actually loads |\n| Weight mapping | Explicit `WeightTarget` list; verify tensor names/shapes against HF cache blobs |\n| Tokenizer | Exercise local-path load, partial HF cache, and any special formats (protobuf, sentencepiece, etc.) — see [#383](https://github.com/mflux-community/mflux/pull/383), [#389](https://github.com/mflux-community/mflux/pull/389), [#390](https://github.com/mflux-community/mflux/pull/390) |\n| Optional reference components | Document in README what the upstream pipeline includes but mflux omits (extra encoders, preprocessors, etc.) |\n\n### LoRA\n\n| Surface | What to do |\n|---|---|\n| `*LoRAMapping` | Support **multiple export key conventions** (diffusers, PEFT `.default.weight`, kohya/`diffusion_model.*` aliases) — silent zero-key loads were fixed repeatedly ([#376](https://github.com/mflux-community/mflux/pull/376), [#374](https://github.com/mflux-community/mflux/pull/374), [#397](https://github.com/mflux-community/mflux/pull/397)) |\n| Tests | Fast tests that real community LoRA filenames map to non-zero keys |\n| Inference CLI | `--lora` via shared parser (no bespoke loader). `--lora-paths` / `--lora-scales` are deprecated. |\n\n### Inference CLI & shared features\n\n| Surface | What to do |\n|---|---|\n| Thin CLI | `build_parser()` with `CommandLineParser` + `CallbackManager.register_callbacks(...)` |\n| Command class | **Required.** Put the CLI work in `<Model>Command` with `validate`, `load`, `generate` and `latent_creator`. `main()` only calls these steps. See below. |\n| `DimensionResolver` | Use in generate/edit CLIs when width/height can be omitted (API/OpenWebUI paths) — [#378](https://github.com/mflux-community/mflux/pull/378) |\n| `latent_creator` | `pack_latents` / `unpack_latents`; img2img path must match txt2img normalization (BN, scale factor) |\n| `tiling_config` | If initializer sets custom tiling, ensure `MemorySaver` does not overwrite it |\n| Guidance defaults | Distilled vs base: match `ModelConfig`, CLI default, README, and training preview adapter |\n| `mflux-save` round-trip | Save quantized model → load from local path → generate; confirm `model.safetensors.index.json` if sharded |\n\n### Command class: validate, load, generate\n\nUse this pattern for every new generate CLI. Do not put the full flow in one `main()`. Plugins under `mflux.extras` call these steps. A CLI without them cannot support plugins. See `docs/plugins.md` and `docs/validate-load-generate.md`.\n\nCopy the structure of `src/mflux/models/qwen/cli/qwen_image_generate.py`:\n\n| Member | Rule |\n|---|---|\n| `latent_creator` | Class attribute. `main()` passes it to `CallbackManager.register_callbacks(...)`. |\n| `validate(args) -> ModelConfig` | Static. Do not load weights. Resolve `--model` with `ConfigResolution.resolve_restricted(...)`. If the command has rules for flag combinations, sizes or output formats, test them here and raise `ValueError`. |\n| `load(args) -> Model` | Static. Call `validate(args)` first. Then make the model with `quantize`, `model_path` and `**lora_init_kwargs_from_args(args)`. |\n| `generate(model, args, seed, prompt) -> GeneratedImage` | Static. Make one image for one seed and one prompt. Apply the command defaults here, for example guidance and `DimensionResolver`. A direct caller must get the same image as `main()`. Do not save the image. |\n\n`main()` only parses the arguments, calls `load`, registers the callbacks, calls `generate` for each seed and saves each image.\n\n### Training (if supported)\n\n| Surface | What to do |\n|---|---|\n| `training/runner.py` | Register `*TrainingAdapter`; handle `low_ram` / tiling like other models |\n| Example JSON | `models/common/training/_example/train_<model>.json` + `.gitignore` un-ignore |\n| Preview generation | Adapter should use canonical steps/guidance for distilled vs base (unit test this) |\n| Local `model_path` | Confirm `mflux-train` works with saved local weights — [#370](https://github.com/mflux-community/mflux/pull/370) |\n\n### Tests & CI\n\n| Surface | What to do |\n|---|---|\n| Slow golden test | `tests/image_generation/test_generate_image_<model>.py` + `reference_*.png` on CI hardware |\n| Fast tests | LoRA mapping, training-adapter preview defaults, argparser if new CLI flags |\n| `just ci-extract` | Required after changing `AVAILABLE_MODELS` or `OVERLAY`; verifies every registry key has CI-manifest metadata |\n| `just lint` / `just test-fast` | Before slow tests |\n\nWhen fixing a gap for model *N*, ask whether the same gap exists for other recent models and whether a **shared** fix belongs in `models/common/` (preferred over copy-paste per model).\n\n## Tooling expectations\n- Use `uv` for running scripts and tests: `uv run <command>`.\n- Prefer `uv run python -m <module>` for local modules.\n\n## Deliverables\n- Deterministic MLX test that verifies correctness.\n- Documented weight mapping, shape constraints, and any known tolerances.\n- Cleaned, shared components aligned with mflux style.\n- Standard mflux surfaces in place: config aliases, thin CLI with a `validate` / `load` / `generate` command class, and a README/examples pass aligned with the final behavior.\n","frontmatter":{"name":"mflux-model-porting","description":"Port ML models into mflux/MLX with correctness-first validation, then refactor toward mflux style."},"isInternal":false,"tokens":4190,"sizeBytes":17619},{"name":"SKILL.md","path":".cursor/skills/mflux-model-tiny-test/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-model-tiny-test/SKILL.md","title":"mflux-model-tiny-test","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-model-tiny-test\ndescription: Write a hermetic \"tiny\" model-saving test for an mflux model — a fast twin of the slow save/load test that runs the real ModelSaver/WeightLoader/WeightApplier seam on real component classes at toy dimensions, with no downloads or image generation. Use when asked to \"make tiny test for <model>\".\n---\n# mflux tiny model-saving test\n\nA tiny test proves a model's quantized checkpoint survives a save/load roundtrip byte-for-byte, in about a second, without downloading anything. It builds the model's **real** component classes at toy dimensions and pushes them through the **real** save/load code path.\n\n## When to Use\n\n- You're asked to \"make tiny test for `<model>`\" or add a fast twin of a slow save/load test.\n- You ported a new model (see `mflux-model-porting`) and want cheap checkpoint coverage.\n\nRelated: `mflux-testing` for running the suite and golden-image rules.\n\n## Reference implementations\n\nRead these before writing a new one — they are the source of truth:\n\n- `tests/model_saving/tiny_checkpoint_helper.py` — the shared harness\n- `tests/model_saving/test_tiny_model_saving_ernie_image.py` — components take explicit kwargs\n- `tests/model_saving/test_tiny_model_saving_ideogram4.py` — components take a Config dataclass\n\nDo not trust code quoted in this skill over those files. The pattern landed as an RFC (PR #599, \"proposal + demo on 2 models\") and is expected to evolve.\n\n**Models that already have tiny tests:** `ernie_image`, `ideogram4`.\n\n## What you write\n\nOne file, no `src/` changes:\n\n```text\ntests/model_saving/test_tiny_model_saving_<model>.py\n```\n\nThe whole test is a single call into `TinyCheckpointRoundtrip`. The real work is figuring out how to build that model's components small. Match the two examples exactly:\n\n- class `TestTiny<Model>ModelSaving`\n- method `test_tiny_quantized_checkpoint_roundtrips_exactly`, decorated `@pytest.mark.fast`\n- a `@staticmethod _tiny_components()` returning the component dict\n- a comment naming the slow twin it mirrors\n\n## Instructions\n\n### 1. Read the weight definition — it is the contract\n\n```text\nsrc/mflux/models/<model>/weights/<model>_weight_definition.py\n```\n\n`get_components()` is authoritative: it gives the exact set of component **names** you must produce, and how many. While there, note two things:\n\n- **`quantization_group_size`** — a class attribute on the weight definition. Defaults to 64 but is not always 64 (`boogu` uses 32). Every tiny dimension must be a multiple of *this model's* value. Check with `grep -n \"quantization_group_size\" src/mflux/models/<model>/weights/*.py`.\n- **`skip_quantization=True`** on any component (`krea2` and `qwen` each have one). In production, `WeightApplier._quantize` honors this flag and leaves the component unquantized. **`TinyCheckpointRoundtrip._quantize` does not** — it calls `nn.quantize` on every saved component regardless of the flag, so a `skip_quantization` component comes out of the \"saved\" side quantized (with `scales`/`biases`) while the reloaded \"fresh\" side stays unquantized (no `scales`/`biases`). The helper's exact key-set comparison (`saved_weights.keys() == fresh_weights.keys()`) will then fail for that component. This is a real gap in `tiny_checkpoint_helper.py`, not a quirk to work around in the test file — if you're writing a tiny test for `krea2`, `qwen`, or any other model with a `skip_quantization` component, stop and fix `TinyCheckpointRoundtrip._quantize` to skip those components (mirroring `WeightApplier._quantize`) rather than special-casing it in the test.\n\n### 2. Find each component's real class and read its `__init__`\n\nDerive the shrink knobs from the actual constructor. Do not pattern-match one example — they differ deliberately: ERNIE's components take explicit kwargs (`hidden_size=`, `num_layers=`), Ideogram 4's transformer takes an `Ideogram4Config` dataclass.\n\nLook under `src/mflux/models/<model>/model/`. Shrink layer counts to 2, hidden and intermediate sizes to 128, head counts to 2, vocab to 128.\n\n### 3. Use `TinyVAEStandIn` for the VAE\n\nThe real VAEs are fixed-size (~170M param) architectures with no dimension knobs, so they cannot be shrunk. `ModelSaver`/`WeightLoader` treat every component as an opaque parameter tree, so the stand-in walks the identical code path. Don't spend a loop trying to shrink a real VAE.\n\n### 4. Respect interlocking dimension constraints\n\nDimensions are not independent. Look for constraints in the component's `__init__` and attention/rope code:\n\n- `rope_axes_dim` must **sum to** `head_dim` (ERNIE: `[16, 24, 24]` → 64)\n- `head_dim` must be consistent with `hidden_size / num_attention_heads`\n- `num_key_value_heads` must divide `num_attention_heads`\n\n### 5. Choose `tensors_per_shard`\n\nStart with `tensors_per_shard=8`. It forces shard boundaries so the `index.json` / `weight_map` multi-shard paths get exercised — the production size-based split (≥1 GB) never shards test-sized tensors.\n\nThe helper asserts `len(shard_files) > component_count`. If a model's tiny components have too few parameter tensors to clear that bar, **lower the number until it passes** — do not drop the argument, that silently removes multi-shard coverage.\n\n### 6. Name the slow twin — after checking it exists\n\nThe examples carry `Fast twin of tests/model_saving/test_model_saving_<model>.py`. Several models have weight definitions but **no** slow save test. Verify with `ls tests/model_saving/` and adapt the comment rather than pointing at a file that isn't there.\n\n## Constraints that will bite you\n\n- **Key the dict by `component.name`, not `model_attr`.** The helper does a bare `components[component.name]` lookup, so a missing or misnamed key is a raw `KeyError`, not a helpful message. Most common first-try failure. Every component in `get_components()` needs an entry.\n- **Do not collapse the two seeds.** The harness randomizes saved components with `seed=0` and fresh ones with `seed=1`. That difference is exactly what makes the final equality assertion prove values came off disk. Unifying them leaves the test green and meaningless.\n- **Do not edit `WeightDefinitionType`.** The helper types `weight_definition` as plain `type` on purpose — that `TYPE_CHECKING` union has drifted and omits several definitions. Widening a src type alias is out of scope; see the helper's comment.\n- **Do not modify `src/`.** A tiny test is a test-only addition. If a model appears to genuinely require a src change to be testable, stop and report that rather than making it.\n\n## Verify\n\n```sh\nuv run --no-sync python -m pytest tests/model_saving/test_tiny_model_saving_<model>.py -v\n```\n\nThen confirm nothing else broke with `just test-fast` (see `mflux-testing`).\n\nThe test should run in roughly a second. If it takes noticeably longer, or the network is touched, something is loading a real checkpoint — investigate rather than accepting it.\n\n### Do you need to check that quantization actually happened?\n\n**No.** Verified empirically: MLX raises loudly on a bad dimension rather than silently skipping —\n\n```text\nValueError: [quantize] The last dimension of the matrix needs to be divisible\nby the quantization group size 64. However the provided matrix has shape (100,100)\n```\n\nso a dimension that isn't a clean multiple of the group size fails the test outright. It cannot leave a green-but-weak twin.\n\nRelatedly, when inspecting a quantized tree you'll see some `.weight` entries with no matching `.scales`. Confirmed benign: those are 1-D norm weights and `Conv2d` layers, which `nn.quantize` correctly leaves alone. Only `Linear`-style layers quantize. Don't chase these.\n\n## Troubleshooting\n\n| Symptom | Cause |\n|---|---|\n| `KeyError: '<name>'` | `_tiny_components()` is missing a component, or keyed it by `model_attr` instead of `name` |\n| `ValueError: [quantize] ... divisible by the quantization group size` | A dimension isn't a multiple of this model's `quantization_group_size` |\n| `assert len(shard_files) > component_count` | Lower `tensors_per_shard` (step 5) |\n| Values differ after reload | A real save/load bug — report it, do not weaken the assertion |\n| Shape assertion inside a component's `__init__`/forward | An interlocking dimension constraint (step 4) |\n","frontmatter":{"name":"mflux-model-tiny-test","description":"Write a hermetic \"tiny\" model-saving test for an mflux model — a fast twin of the slow save/load test that runs the real ModelSaver/WeightLoader/WeightApplier seam on real component classes at toy dimensions, with no downloads or image generation. Use when asked to \"make tiny test for <model>\"."},"isInternal":false,"tokens":2005,"sizeBytes":8270},{"name":"pr-what-prompt.md","path":".cursor/skills/mflux-pr-docs/pr-what-prompt.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/pr-what-prompt.md","title":"Mflux-pr-docs Skill","category":"anthropic-skill","format":"markdown","content":"# Mflux-pr-docs Skill\n\nPath: `.cursor/skills/mflux-pr-docs/pr-what-prompt.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/pr-what-prompt.md)","tokens":300,"sizeBytes":212},{"name":"release-note-prompt.md","path":".cursor/skills/mflux-pr-docs/release-note-prompt.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/release-note-prompt.md","title":"Mflux-pr-docs Skill","category":"anthropic-skill","format":"markdown","content":"# Mflux-pr-docs Skill\n\nPath: `.cursor/skills/mflux-pr-docs/release-note-prompt.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/release-note-prompt.md)","tokens":300,"sizeBytes":222},{"name":"SKILL.md","path":".cursor/skills/mflux-pr-docs/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/SKILL.md","title":"mflux-pr-docs","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-pr-docs\ndescription: Write the PR body for the current mflux branch and show it to the developer for approval. Fills the What section, the release-note block and the Verification section of the PR template. Use when the developer asks to write, fill or update a PR description or a release note.\n---\n\n# mflux PR docs\n\nWrite the PR body for the current branch. The developer must approve the body before it goes to GitHub.\n\n## Inputs\n\n- The current branch. The base branch is `main`.\n- Optional: the PR number, if the PR is open.\n\n## Steps\n\n1. Collect the facts. Use only these sources:\n   - `git log --oneline main..HEAD`\n   - `git diff --stat main...HEAD`\n   - `git diff main...HEAD`\n   - If the PR is open: `gh pr view <n> --json title,body,closingIssuesReferences` and `gh pr checks <n>`.\n2. Copy `.github/pull_request_template.md` to `tmp-PR-content.md`. If `tmp-PR-content.md` exists, ask the developer before you replace it.\n   - Add this heading as the first line: `# Draft PR Content`.\n   - Add the line `Title: ` below the heading. Add an empty line after it.\n   - If the PR is open, put its title from step 1 after `Title: `.\n   - If the PR is open, `gh pr edit --body-file` replaces the existing body. Copy each existing section and link that the template does not have into `tmp-PR-content.md`. Get them from the `body` field of step 1. If you do not copy them, ask the developer to confirm before you discard them.\n3. Write the `What` section. Obey `pr-what-prompt.md` in this folder. Use the diff from step 1 if the PR is not open. Add `Fixes #<n>` for each linked issue.\n   - If the PR is not open, write the PR title after `Title: `. Use one short line that names the change.\n   - If the PR is open, keep its title. Change the title only if the developer asks.\n4. Write the release note. Obey `release-note-prompt.md` in this folder.\n   - Put the note on the lines below the opening fence. Do not put text on the fence line.\n   - Tell the developer which PR label the PR needs.\n5. Write the `Verification` section. List only the commands that ran, with the result of each command. If no command ran, write `TODO: add the commands that you ran.` Do not write a result that you did not see.\n6. Do not tick the boxes in the `Checklist` section. The developer ticks them.\n7. Examine the text that you wrote. Do not examine the template text.\n   - Apply the `asd-ste100` skill in STE-flavored mode.\n   - Put the text that you wrote in a temporary file. Do not put the `Title:` line in it. Run `python3 .cursor/skills/asd-ste100/scripts/ste-lint.py --disable synonym-rotation <file>`.\n   - Fix each hard violation.\n8. Run the CI check on `tmp-PR-content.md`. Fix `tmp-PR-content.md` until the check passes:\n   ```sh\n   python3 - tmp-PR-content.md <<'PY'\n   import re, sys\n   body = open(sys.argv[1], newline=\"\").read()\n   m = re.search(r\"^```release-note[ \\t\\r]*\\n(.*?)^```[ \\t\\r]*$\", body, re.DOTALL | re.IGNORECASE | re.MULTILINE)\n   sys.exit(0 if m and m.group(1).strip() else \"FAIL: no complete release-note block\")\n   PY\n   ```\n9. Ask the developer to approve the PR content:\n   - Open `tmp-PR-content.md` in the editor. Use `code tmp-PR-content.md` or `cursor tmp-PR-content.md`. If neither command works, give the developer the file path.\n   - Tell the developer to edit the file in the editor, or to ask for changes in the chat.\n   - Tell the developer to write `approve` in the chat when the content is ready.\n   - Do not continue until the developer writes `approve`.\n10. Read `tmp-PR-content.md` again after the developer approves it. The developer can edit the file before approval. Do step 8 again.\n    - Make sure that line 1 is `# Draft PR Content` and line 2 is the `Title:` line. Put them back if the developer moved them.\n    - Make sure that the `Title:` line has a title. If it is empty, ask the developer for the title. Write the title after `Title: ` in `tmp-PR-content.md`.\n11. Send the PR content to GitHub:\n    - If the PR is not open, push the branch first. Ask for permission before you push. Obey the `mflux-pr` skill.\n    - Run this block as one command. If the PR is open, replace the last line with `gh pr edit <n> --title \"$title\" --body-file tmp-PR-body.md`.\n      ```sh\n      title=\"$(awk 'NR <= 2 && sub(/^Title: */, \"\") { print; exit }' tmp-PR-content.md)\"\n      awk 'NR == 1 && /^# Draft PR Content$/ { next } NR == 2 && /^Title:/ { next } { print }' tmp-PR-content.md > tmp-PR-body.md\n      gh pr create --title \"$title\" --body-file tmp-PR-body.md\n      ```\n    - The shell reads the title from the file. Do not type the title into the command. Backticks and `$` in a typed title run as shell code.\n    - GitHub does not get the `# Draft PR Content` line or the `Title:` line. Other lines that start with `Title:` stay in the body.\n12. Delete `tmp-PR-content.md` and `tmp-PR-body.md`.\n\n## Rules\n\n- Do not invent facts, numbers or test results.\n- Do not change the code or the commits.\n- Do not use `gh pr create --body` or `--fill`. GitHub must get the body that you checked, without the two draft lines.\n- Keep the regex in step 8 the same as `.github/workflows/release-note.yml` and `_FENCE` in `src/mflux/release/release_notes.py`.\n","frontmatter":{"name":"mflux-pr-docs","description":"Write the PR body for the current mflux branch and show it to the developer for approval. Fills the What section, the release-note block and the Verification section of the PR template. Use when the developer asks to write, fill or update a PR description or a release note."},"isInternal":false,"tokens":1386,"sizeBytes":5199},{"name":"SKILL.md","path":".cursor/skills/mflux-pr/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr/SKILL.md","title":"mflux-pr","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-pr\ndescription: Make a clean PR in mflux (inspect diff, quick verification, commit, push, open PR) using repo conventions.\n---\n# mflux pull request workflow\n\n## When to Use\n\n- You’re about to open a PR (or want a safe sequence to do it).\n\n## Instructions\n\n- If you run tests as part of PR hygiene, prefer fast tests first:\n  - `just test-fast`\n- Keep commits focused and messages consistent with repo history.\n- If the PR changes CLI defaults, public APIs, or model behavior, check for README/example drift before opening the PR.\n- **Always ask for permission** before pushing to the remote repository.\n- If `gh` isn’t available, fall back to the GitHub web UI (or stop and ask).\n\n## PR body and release note (required)\n\nThe `release-note` CI check fails the PR if the body has no complete release-note block.\n\nUse the `mflux-pr-docs` skill to write the PR body. That skill writes the `What` section and the release-note block, runs the CI check, and gets the approval of the developer.\n\nIf the check fails on an open PR, use the `mflux-pr-docs` skill again. It edits the body of the open PR. The check runs again on an edit. You do not need a new commit.\n\n## Pre-merge checklist (model port PRs)\n\nUse after the core port lands and you are polishing for merge. For the full **integration surfaces** tick list (LoRA key formats, save routing, tokenizer edge cases, etc. learned from past closed PRs), see `mflux-model-porting` → *Integration surfaces checklist*.\n\n### Correctness\n\n1. `just lint` and `just test-fast`\n2. `just ci-extract` after changing `AVAILABLE_MODELS` or `scripts/ci_extract_models.py`\n3. Slow golden tests for the new model:\n   ```sh\n   MFLUX_PRESERVE_TEST_OUTPUT=1 uv run pytest tests/image_generation/test_generate_image_<model>.py -m slow -v\n   ```\n4. Optional but high-signal: diffusers side-by-side + latent injection (`mflux-debugging`, `mflux-manual-testing`)\n\n### Cross-model diff audit\n\nList files changed outside `src/mflux/models/<model>/`:\n\n| Category | Expected |\n|---|---|\n| `pyproject.toml`, `cli/defaults/defaults.py`, `ModelConfig`, `mflux-save` routing | Required wiring |\n| `scripts/ci_extract_models.py` `OVERLAY` / `EXTRA_ENTRIES` | Required CI-manifest wiring for every new model key or standalone tool |\n| `README.md` table + attribution | Required |\n| Training `runner.py`, example JSON, `.gitignore` JSON exceptions | If training supported |\n| Shared VAE/callback/training one-liners | Only if required; document blast radius in PR |\n| Personal `.gitignore`, unrelated formatting | **Remove** |\n\nVerify quantized README disk claims with measurement:\n```sh\ndu -sh ~/.cache/huggingface/hub/models--<org>--<Model>*\nmflux-save --model <alias> --quantize 8 --path /tmp/model-q8 && du -sh /tmp/model-q8\n```\n\n### Docs / examples\n\n- Model README matches a recent port (e.g. Flux2): hero image, turbo + base CLI, feature section, disk warning, Notes, Training.\n- Main `README.md` model table row (correct release date).\n- Showcase asset if other models have one (`src/mflux/assets/`; may need `git add -f` when `*.jpg` is gitignored).\n\n### PR description callouts\n\n- Shared code touched and why (shared VAE, callbacks, training runner, etc.).\n- Reference pipeline features intentionally **not** ported (optional preprocessors, extra encoders, components omitted from mflux weight downloads).\n- Known non-parity with diffusers (RNG, sigma schedule, optional modules) if golden tests lock mflux-native sampling.\n\n","frontmatter":{"name":"mflux-pr","description":"Make a clean PR in mflux (inspect diff, quick verification, commit, push, open PR) using repo conventions."},"isInternal":false,"tokens":850,"sizeBytes":3469},{"name":"SKILL.md","path":".cursor/skills/mflux-release/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-release/SKILL.md","title":"mflux-release","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-release\ndescription: Prepare a release in mflux (version bump + uv lock; release notes are harvested from PR release-note blocks and live in GitHub Releases). Use when preparing a release branch or release PR.\n---\n# mflux release prep\n\nReleases are prepared in-repo; tagging/publishing is handled by GitHub Actions\n(`release.yml`, dispatched from main with the `publish` confirmation).\n\n## How notes work now (#685)\n\n- Every PR carries a fenced ` ```release-note ` block in its body (CI enforces it;\n  every PR gets a note, and contributors do not write `none`). That block is the only source of release notes.\n- On dispatch, the ungated `draft-notes` job harvests the blocks for every PR whose\n  squash commit is in `previous-tag..HEAD` and fills a DRAFT GitHub release, grouped\n  by label.\n- Whoever approves the `pypi` deployment reads and edits that draft (fixing any\n  `[needs edit]` lines, adding contributor thanks if wanted); the gated job publishes\n  it exactly as edited. A re-dispatch never overwrites an existing draft; delete the\n  draft to re-harvest.\n- There is no `CHANGELOG.md`: the notes live in GitHub Releases (https://github.com/mflux-community/mflux/releases).\n\n## Release-prep PR checklist\n\n- Bump version in `pyproject.toml`\n- Update lockfile: `uv lock`\n- Release-note block of the prep PR itself: a note for contributors, for example `Prepare the <version> release.` Give the PR the `chore` label.\n- Prefer one commit named `release: prepare <version>`\n- Sanity checks (optional unless requested): `just test-fast`, `just build`\n- Do not tag releases locally unless explicitly requested (normally handled by CI)\n","frontmatter":{"name":"mflux-release","description":"Prepare a release in mflux (version bump + uv lock; release notes are harvested from PR release-note blocks and live in GitHub Releases). Use when preparing a release branch or release PR."},"isInternal":false,"tokens":385,"sizeBytes":1653},{"name":"SKILL.md","path":".cursor/skills/mflux-testing/SKILL.md","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-testing/SKILL.md","title":"mflux-testing","category":"anthropic-skill","format":"markdown","content":"---\nname: mflux-testing\ndescription: Run tests in mflux (fast/slow/full), preserve image outputs, and handle golden image diffs safely.\n---\n# mflux testing\n\nThis repo uses pytest with image-producing tests. Always preserve outputs for inspection and **never** update reference images unless explicitly asked.\n\n## When to Use\n\n- You need to run tests (fast/slow/full) or debug failing tests.\n- There are image/golden mismatches and you need to report paths/output for review.\n\n## Instructions\n\n- Prefer the justfile test recipes:\n  - `just test-fast` (fast tests, no image generation)\n  - `just test-slow` (slow tests, image generation)\n  - `just test` (default selection, skips slow model tests)\n  - `just test-all` (all except high-memory tests; slow tests download model weights)\n- Always keep `MFLUX_PRESERVE_TEST_OUTPUT=1` on test runs (already built into the justfile test recipes).\n- If a change affects defaults, config resolution, metadata fields, or CLI behavior, add or update tests that cover the changed behavior directly instead of relying only on manual verification.\n- If tests fail:\n  - Summarize the failing test names and the key assertion output.\n  - Point to any generated images/artifacts on disk for manual review.\n- Do **not** regenerate/replace reference (“golden”) images unless the user explicitly requests it.\n\n## Updating golden images (new model or hardware refresh)\n\nGolden tests compare generated PNGs to `tests/resources/reference_*.png` (typically 15% mismatch threshold).\n\n**When to update** (only with explicit user approval):\n- After validating the port on target hardware (CI Mac) via slow tests with `MFLUX_PRESERVE_TEST_OUTPUT=1`\n- After choosing a stable prompt/seed/settings via diffusers comparison and/or latent-injection confidence (`mflux-debugging`)\n- When old references used a bad prompt (e.g. ambiguous subject) or wrong seed for mflux’s RNG\n\n**Workflow**:\n1. Run slow test → inspect `tests/resources/output_*.png` vs `reference_*.png`\n2. If output is correct but reference is stale, re-run generation with same test parameters and replace reference PNGs\n3. Commit test + reference images together with a clear message (e.g. `test(<model>): update golden images for local hardware`)\n\n**Important**: Golden tests lock **mflux-native** sampling (`mx.random` + mflux schedulers), not diffusers pixel parity. A good diffusers side-by-side or injected-latent run builds confidence in the model code; the golden still reflects mflux’s full recipe on CI hardware.\n\n## Manual validation (config resolution + local model paths)\n\nUse when a change touches model config resolution, `mflux-save`, or the model’s generate CLI, or when a PR fixes local model-path handling for the model under investigation. Refer to the `mflux-cli` skill to find the correct generate command for the model you are testing.\n\n- Run a local-path quantize/save:\n  - Use the `mflux-cli` skill to look up the correct command and flags.\n  - Verify CLI usage with the command’s `--help` before running it.\n  - Save to a known location (e.g., Desktop) to make follow-up steps explicit.\n- Run generation from the saved model using the correct model-specific generate CLI:\n  - Use the `mflux-cli` skill to find the generate command and required flags.\n  - Verify CLI usage with the command’s `--help` before running it.\n- If the model has multiple size variants, repeat the above for each variant to confirm the correct overrides are applied.\n- Do not commit output artifacts; delete or leave them untracked.\n","frontmatter":{"name":"mflux-testing","description":"Run tests in mflux (fast/slow/full), preserve image outputs, and handle golden image diffs safely."},"isInternal":false,"tokens":781,"sizeBytes":3533},{"name":"asd-ste100","path":".claude/skills/asd-ste100","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/asd-ste100","title":"Claude Directive: asd-ste100","category":"claude-rule","format":"markdown","content":"# Claude Directive: asd-ste100\n\nPath: `.claude/skills/asd-ste100`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/asd-ste100)","tokens":300,"sizeBytes":179},{"name":"mflux-cli","path":".claude/skills/mflux-cli","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-cli","title":"Claude Directive: mflux-cli","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-cli\n\nPath: `.claude/skills/mflux-cli`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-cli)","tokens":300,"sizeBytes":176},{"name":"mflux-debugging","path":".claude/skills/mflux-debugging","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-debugging","title":"Claude Directive: mflux-debugging","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-debugging\n\nPath: `.claude/skills/mflux-debugging`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-debugging)","tokens":300,"sizeBytes":194},{"name":"mflux-dev-env","path":".claude/skills/mflux-dev-env","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-dev-env","title":"Claude Directive: mflux-dev-env","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-dev-env\n\nPath: `.claude/skills/mflux-dev-env`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-dev-env)","tokens":300,"sizeBytes":188},{"name":"mflux-manual-testing","path":".claude/skills/mflux-manual-testing","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-manual-testing","title":"Claude Directive: mflux-manual-testing","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-manual-testing\n\nPath: `.claude/skills/mflux-manual-testing`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-manual-testing)","tokens":300,"sizeBytes":209},{"name":"mflux-model-porting","path":".claude/skills/mflux-model-porting","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-porting","title":"Claude Directive: mflux-model-porting","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-model-porting\n\nPath: `.claude/skills/mflux-model-porting`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-porting)","tokens":300,"sizeBytes":206},{"name":"mflux-model-tiny-test","path":".claude/skills/mflux-model-tiny-test","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-tiny-test","title":"Claude Directive: mflux-model-tiny-test","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-model-tiny-test\n\nPath: `.claude/skills/mflux-model-tiny-test`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-tiny-test)","tokens":300,"sizeBytes":212},{"name":"mflux-pr","path":".claude/skills/mflux-pr","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr","title":"Claude Directive: mflux-pr","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-pr\n\nPath: `.claude/skills/mflux-pr`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr)","tokens":300,"sizeBytes":173},{"name":"mflux-pr-docs","path":".claude/skills/mflux-pr-docs","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr-docs","title":"Claude Directive: mflux-pr-docs","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-pr-docs\n\nPath: `.claude/skills/mflux-pr-docs`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr-docs)","tokens":300,"sizeBytes":188},{"name":"mflux-release","path":".claude/skills/mflux-release","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-release","title":"Claude Directive: mflux-release","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-release\n\nPath: `.claude/skills/mflux-release`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-release)","tokens":300,"sizeBytes":188},{"name":"mflux-testing","path":".claude/skills/mflux-testing","rawUrl":"https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-testing","title":"Claude Directive: mflux-testing","category":"claude-rule","format":"markdown","content":"# Claude Directive: mflux-testing\n\nPath: `.claude/skills/mflux-testing`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-testing)","tokens":300,"sizeBytes":188}],"systemPromptSnippet":"<yakaai_skills repo=\"filipstrand/mflux\">\n<!-- File: AGENTS.md (Tokens: ~300 | Category: root-instruction) -->\n# AI Agent Protocol & Instructions\n\nPath: `AGENTS.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/AGENTS.md)\n\n<!-- File: .agents/skills/remediating-dependabot/SKILL.md (Tokens: ~1201 | Category: anthropic-skill) -->\n---\nname: remediating-dependabot\ndescription: Remediates GitHub Dependabot alerts for mflux in one dependency-security change. Use when auditing, clamping, or upgrading Python dependencies in pyproject.toml and uv.lock, or when validating whether a branch will close Dependabot findings before opening a PR.\n---\n\n# Remediating Dependabot\n\nResolve actionable Dependabot alerts with the smallest compatible dependency update and prove the local lock is outside every reported vulnerable range.\n\n## Scope\n\n- Use `gh api` as the source of truth for open alerts in `mflux-community/mflux`.\n- Keep dependency changes in `pyproject.toml` and `uv.lock` unless compatibility requires source changes.\n- Preserve supported Python and platform markers.\n- Avoid unrelated package upgrades when regenerating the lock.\n- Treat dependency optionality or loading refactors as separate work unless explicitly requested.\n\n## Workflow\n\n1. Confirm the current branch and working tree before editing.\n2. Fetch all open Dependabot alerts, following pagination:\n\n   ```bash\n   gh api --method GET --paginate \\\n     -H \"Accept: application/vnd.github+json\" \\\n     repos/mflux-community/mflux/dependabot/alerts \\\n     -f state=open\n   ```\n\n3. Group alerts by manifest, package, severity, vulnerable range, and first patched version. Distinguish direct requirements from transitive lock entries.\n4. Inspect `pyproject.toml`, `uv.lock`, supported Python versions, and platform markers before choosing a fix.\n5. Prefer, in order:\n   - removing dependencies that are no longer needed;\n   - raising a direct lower bound to the first secure compatible release;\n   - upgrading only affected transitive packages in the lock;\n   - adding or changing environment markers only when compatibility actually differs by Python or platform.\n6. Use one requirement when a release supports the full project matrix. Do not introduce overlapping marker-specific requirements without evidence that they are necessary.\n7. Regenerate the lock with targeted upgrades:\n\n   ```bash\n   uv lock --upgrade-package <package> [--upgrade-package <package> ...]\n   ```\n\n8. Review the lock diff. Explain large platform-specific resolver changes, especially PyTorch CUDA package transitions, rather than assuming they are accidental.\n\n## Security verification\n\nDo not infer alert closure solely from package names or Dependabot's hosted UI.\n\n1. Run lock and advisory checks:\n\n   ```bash\n   uv lock --check\n   uv audit --preview-features audit-command\n   ```\n\n2. Parse every resolved version in `uv.lock` and compare it with every open alert's `security_vulnerability.vulnerable_version_range`. Canonicalize names with `packaging.utils.canonicalize_name` and use `packaging.specifiers.SpecifierSet` so matching follows Python package name and version semantics.\n3. Confirm that each alert is resolved by either:\n   - no matching package remaining in the lock; or\n   - every matching locked version falling outside the vulnerable range.\n4. Run Dependabot Core against the local checkout before opening a PR:\n\n   ```bash\n   tmp_dir=\"$(mktemp -d)\"\n   trap 'rm -rf \"$tmp_dir\"' EXIT\n   job=\"$tmp_dir/job.yml\"\n   output=\"$tmp_dir/output.yml\"\n\n   # Build the security job at \"$job\" before running these commands.\n   dependabot graph uv mflux-community/mflux --local \"$PWD\"\n   dependabot update --local \"$PWD\" -f \"$job\" -o \"$output\" --pull=false --timeout 20m\n   ```\n\n   `graph` is experimental and may return an incomplete dependency list. Both commands snapshot the directory passed to `--local`, including modified and untracked files, so confirm that the working tree contains only the intended updater input.\n\n   Build the temporary `uv` security job from the exact package names and advisory ranges returned by GitHub. Parse the YAML output rather than relying on the command's exit status:\n\n   ```bash\n   uv run python - \"$output\" <<'PY'\n   import sys\n\n   import yaml\n\n   with open(sys.argv[1]) as output_file:\n       actions = {entry[\"type\"] for entry in yaml.safe_load(output_file)[\"output\"]}\n\n   if \"mark_as_processed\" not in actions:\n       raise SystemExit(\"Dependabot did not mark the job as processed\")\n\n   pull_request_actions = actions & {\"create_pull_request\", \"update_pull_request\"}\n   if pull_request_actions:\n       raise SystemExit(f\"Dependabot still proposes actions: {sorted(pull_request_actions)}\")\n   PY\n   ```\n\n   Do not pin Dependabot CLI to one release. Verify the installed CLI exposes the commands and flags used here before running the job.\n5. Keep temporary Dependabot job and output files outside the committed change, and remove them after verification.\n6. If the hosted alert remains open while the local lock is already outside its vulnerable range, report it as pending or stale until GitHub rescans. Do not force an unnecessary upgrade just to change the lock entry.\n\n## Project verification\n\nRun the repository workflows after the lock is secure:\n\n```bash\njust lint\njust lint-justfile\njust typecheck\njust test-fast\njust test\njust build\ngit diff --check\n```\n\nUse `uv lock --upgrade --dry-run` to check that a fresh universal resolution succeeds. It may report unrelated newer releases; do not add them unless they are needed for the remediation.\n\n## Reporting\n\nReport:\n\n- total open findings expected to close, grouped by severity and package;\n- direct requirement changes and noteworthy lock-only changes;\n- packages removed from the lock;\n- exact results from range comparison, Dependabot Core, `uv audit`, and project checks;\n- any alerts whose final hosted closure depends on GitHub rescanning the merged lockfile.\n\n<!-- File: .cursor/rules/RULE.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Rules Skill\n\nPath: `.cursor/rules/RULE.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/rules/RULE.md)\n\n<!-- File: .cursor/skills/asd-ste100/examples/before-after.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Examples Skill\n\nPath: `.cursor/skills/asd-ste100/examples/before-after.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/before-after.md)\n\n<!-- File: .cursor/skills/asd-ste100/examples/linter-edge-cases.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Examples Skill\n\nPath: `.cursor/skills/asd-ste100/examples/linter-edge-cases.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/examples/linter-edge-cases.md)\n\n<!-- File: .cursor/skills/asd-ste100/README.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Asd-ste100 Skill\n\nPath: `.cursor/skills/asd-ste100/README.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/README.md)\n\n<!-- File: .cursor/skills/asd-ste100/references/writing-rules.md (Tokens: ~300 | Category: anthropic-skill) -->\n# References Skill\n\nPath: `.cursor/skills/asd-ste100/references/writing-rules.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/asd-ste100/references/writing-rules.md)\n\n<!-- File: .cursor/skills/asd-ste100/SKILL.md (Tokens: ~3620 | Category: anthropic-skill) -->\n---\nname: asd-ste100\ndescription: \"Use when English text must be parsed without a human to resolve ambiguity — tool descriptions, error messages, inter-agent instructions, system prompts, status reports — and misreading has a real cost, or when text reads as dense, hedged, or easy to misparse. Triggers: disambiguate, STE100 rewrite, apply Simplified Technical English, plain-language rewrite, controlled-language rewrite, rewrite so an agent cannot misread this. Not for creative or marketing copy.\"\nmetadata:\n  version: 0.4.0\n---\n\n# Simplified Technical English (ASD-STE100)\n\nASD-STE100 is a controlled-language standard built by the aerospace and defense industry (ASD, the AeroSpace and Defense Industries Association of Europe) to stop maintenance technicians from misreading English instructions. The standard removes the two biggest sources of misreading: words with more than one meaning, and sentences with more than one possible structure.\n\nThis skill borrows that same discipline for a different reader: an **AI agent or a downstream system** that has to parse an English string — an error message, a tool description, an inter-agent instruction, a status report — without a human in the loop to resolve ambiguity. If a maintenance technician can misread \"close the valve\" as an adjective (\"the valve that is near\") instead of a command, so can a language model.\n\n## When to Use This Skill\n\n- An agent's output (explanation, instruction, log message, tool description) reads as dense, jargon-heavy, or ambiguous.\n- Text will be consumed by another agent, a translation pipeline, or a non-native English reader, and misparsing has a real cost.\n- You are writing a prompt, system message, or tool description and want to remove ambiguity before a model ever sees it.\n- You want a **before/after** comparison showing exactly which rule was violated and how the rewrite fixes it. Ask for it — the default output is the rewritten text alone (see Output Format).\n\nThis skill is not for creative or marketing copy — STE is deliberately flat and literal. Do not apply it to text where voice, nuance, or persuasion is the point.\n\n## Two Modes\n\nPick a mode before rewriting. If the user does not say which, infer it from the text type. Keep the choice internal unless the user asks for the rule table (see Output Format).\n\n**Strict** — procedures, error messages, tool and function descriptions, inter-agent instructions, safety text. Anywhere a wrong reading has a cost. Apply every rule below, including the hard length caps and one-word-one-meaning discipline.\n\n**STE-flavored** — READMEs, PR descriptions, changelogs, explanatory prose. Apply the structural rules in full and treat the lexical rules as advisory (see Core Rewrite Rules for that split). In practice that means keeping the sentence length caps, active voice, simple tenses, no phrasal verbs, no semicolons, no nominalization and no marketing adjectives, while dropping the one-word-one-meaning lockdown: prose needs some range, and a strict rewrite of prose reads as a personality transplant rather than a clarification.\n\nThe two modes and the structural/lexical split are the same distinction seen from two directions. The split says which rules this skill can verify without ASD's dictionary. The modes say which of them to enforce for a given kind of text.\n\n## Source and Scope\n\nThis skill encodes the **rule categories** of ASD-STE100 Issue 9 (Jan 2025): 53 writing rules across 9 sections covering word choice, grammar, sentence structure, and style, backed by a dictionary of ~900 approved words (one meaning, one part of speech each) and ~1,200 words to avoid with suggested replacements. See `references/writing-rules.md` for the full rule summary and citations.\n\nIt does **not** reproduce ASD's ~900-word approved dictionary verbatim. ASD-STE100 is free to obtain, but it is not free to redistribute: Issue 9, page 2 states that \"no reproduction or publication of it, in whole or in part, shall be made without the written authority of an officer of ASD,\" and grants free reproduction rights only to eight listed categories (ASD/AIA/AIAC member associations and their member companies and customers, member-state defence ministries, A4A, airworthiness authorities, and universities and research institutes for educational purposes). This project is in none of them, so the dictionary stays out of this repo.\n\nInstead, this skill applies the *underlying principle* (pick the plainest, most common word available and use it the same way every time) rather than checking against a fixed word list. When exact ASD-approved wording matters (e.g. actual aircraft maintenance documentation), get the standard and check word-by-word against the real dictionary. Request it from the [official downloads page](https://www.asd-ste100.org/STE_downloads.html) — note that this is a request form that emails you a link, not a direct download.\n\n## Core Rewrite Rules\n\nSTE's rules divide into two kinds, and this skill can only fully deliver one of them. **Structural rules** are self-contained: they describe sentence shape, and you can apply them from the description alone. **Lexical rules** are defined entirely by the official ~900-word dictionary, which this skill deliberately does not reproduce (see Source and Scope). Without that dictionary, the lexical rules degrade from a checkable standard into a preference for plain words.\n\nApply the structural rules with confidence. Apply the lexical rules as a direction of travel, and say so in your output rather than implying dictionary compliance you cannot verify.\n\n### Structural rules — apply these\n\n| Rule | Do | Don't |\n|---|---|---|\n| Active voice | \"The agent deletes the file.\" | \"The file is deleted (by the agent).\" — unless the actor is genuinely unknown or irrelevant |\n| No phrasal verbs (Rule 9.3) | \"Remove the panel.\" / \"Start the job.\" | \"Take off the panel.\" / \"Spin up the job.\" — a two-word verb has meanings the parts do not predict |\n| One instruction per sentence | \"Open the file. Read line 3.\" | \"Open the file and read line 3, then check if it matches.\" |\n| Sentence length | ≤20 words for instructions/procedures, ≤25 words for descriptions | Long compound/subordinate-clause sentences |\n| No semicolons (Rule 8.1) | Split into separate sentences | Any semicolon at all — STE bans the mark outright, not only as a clause join. (Rule 8.1 permits every other standard punctuation mark. The em dash is *not* banned by STE, though it often signals a sentence that should be split.) |\n| Noun clusters | ≤3 words stacked as a noun phrase (\"fuel pump valve\") | 4+ word noun stacks (\"high pressure fuel pump inlet valve assembly\") |\n| No ellipsis | Keep the subject, verb, and article explicit even if it reads longer | Drop words to save space (\"Files not backed up will be lost\" → ambiguous which files) |\n| Keep modality | \"The request **may have** failed.\" stays \"may have\" | Promote a hedge to a fact (\"The request failed.\") or invent a certainty the source did not state |\n| Paragraph limits | One topic per paragraph, ≤6 sentences | Multi-topic paragraphs |\n| Lists for sequences | Use a numbered or bulleted list for 3+ steps or conditions | Bury a sequence inside one prose sentence |\n\n### Lexical rules — direction of travel only\n\n| Rule | Do | Don't | Why it is weaker here |\n|---|---|---|---|\n| One word, one meaning | Pick one verb for one action and reuse it every time (e.g. always \"check\", never mix \"check\"/\"verify\"/\"confirm\" for the same action) | Rotate synonyms for the same idea across a document | Consistency within a document is checkable. Which word is the *approved* one is not, without the dictionary. |\n| One part of speech per word | \"Apply oil to the valve\" (oil = noun) | \"Oil the valve\" (oil = verb) | Whether \"oil\" is approved as a noun only is a dictionary fact. Prefer the noun form when both read equally well. Do not claim compliance. |\n| Verb, not noun (Rule 3.7) | \"Analyze the log.\" | \"Perform an analysis of the log.\" — a noun form of an action makes the sentence longer and hides who acts | Rule 3.7 says \"use an **approved** verb to describe an action.\" Preferring the verb form is safe to apply anywhere. Knowing which verb is the approved one needs the dictionary. |\n| Domain terms | Keep necessary technical nouns/verbs, but define them once if not common English (STE allows a project-specific glossary beyond its base dictionary) | Use jargon without ever defining it | The glossary allowance is real STE, but the base dictionary it extends is absent. |\n\n### Simple tenses — apply with one exception\n\nSTE permits infinitive, imperative, simple present, simple past, simple future, and past participle as adjective. It excludes present perfect and other compound forms: \"we received the report\", not \"we have received the report\".\n\nAircraft manuals never need present perfect, so the exclusion costs the standard nothing. Other text is not always so lucky. \"The job has completed\" (and its output is available now) and \"the job completed\" (at some past point) are different statements, and status text frequently needs the first. **Where the compound form carries information the simple form cannot — current relevance, or a hedge as in \"may have failed\" — keep it and flag the departure.** Elsewhere, follow the rule.\n\n## Scan Checklist\n\nThese six habits cover most of what makes machine-written English hard to parse. Each one is mechanical: you can point at the exact word or punctuation mark that breaks the rule, with no judgment call. Scan for all six before you rewrite anything.\n\n1. **Synonym rotation** — the same thing gets several names in one document (\"the user\", \"the customer\", \"the client\"). The reader cannot tell whether they are one thing or three. Fix: pick one name, use it every time.\n2. **Hedge stacking** — helper verbs and qualifiers pile up until the sentence asserts nothing (\"it is important to note that this may potentially help to improve\"). Fix: state the claim, or delete it.\n3. **Nominalization** — an action frozen into a noun (\"perform an analysis of\", \"provides assistance to\"). Fix: use the verb (\"analyze\", \"helps\").\n4. **Marketing adjectives** — words that claim quality instead of showing it: seamless, robust, powerful, cutting-edge, effortless, blazing-fast. Fix: delete, or replace with the measurement that earns the claim.\n5. **Run-on sentences** — several ideas joined by semicolons or em dashes. Fix: one idea per sentence.\n6. **Soft phrasal verbs** — spin up, reach out, dive into, kick off. Fix: use the single plain verb (start, contact, read, begin).\n\n## Process\n\n1. Pick the mode (Strict or STE-flavored). Say which only when the user asked for the rule table — see Output Format.\n2. Read the input text once for meaning — do not start rewriting before you understand what it must still say afterward.\n3. Walk it sentence by sentence. Flag every rule violation from the Core Rewrite Rules tables and every habit from the Scan Checklist. In STE-flavored mode, flag the lexical rules but do not enforce them. For a mechanical first pass over the structural rules, run `scripts/ste-lint.py` (stdin or file args, `--json` for structured output); it checks semicolons, sentence length, phrasal verbs, nominalization, marketing adjectives, synonym rotation, dangling-conjunction in supported list items, passive voice, and compound tenses, and by design never flags hedges or modality. `--baseline N` tolerates N hard violations (for adopting on existing docs); `--disable rule1,rule2` silences named rules.\n4. Rewrite each flagged sentence to fix the violation while preserving the original meaning exactly. If a rewrite would drop necessary precision (a safety condition, a scope qualifier, a number), keep the longer phrasing and flag it instead of silently simplifying.\n   - **Check modality before you commit to a rewrite.** Hedges (\"may\", \"could\", \"sometimes\", \"is likely to\") carry the author's confidence, and confidence is content. A shorter sentence that upgrades a hedge to a fact is not a simplification — it is a different claim. This is the most common way a well-intentioned STE rewrite goes wrong, because hedges are exactly what a length cap tempts you to cut.\n   - Never add a fact the source did not state. A rewrite that reads better because it supplies a cause, a frequency, or a mechanism has stopped being a rewrite.\n5. Output the rewritten text (see Output Format). Keep the mode choice and the rule analysis internal unless the user asked to see them.\n6. If the input already complies, say so — do not force changes onto compliant text.\n\n## Output Format\n\n**Default: the rewritten text, and nothing else.** Most callers want a result they can paste straight into a tool description, an error string, or a prompt. Print the simplified text on its own. Do not add a preamble about this skill, a mode announcement, a violation count, a summary of what changed, a rule table, or a closing offer to explain further.\n\nThe one permitted addition: if step 4 kept a longer phrasing on purpose, add a single line after the text, prefixed `Kept as-is:`, naming the phrase and the precision that would have been lost. Omit the line when there is nothing to report.\n\n**On request: the rule table.** When the user asks to see the reasoning — \"show the diff\", \"which rules did it break\", \"explain the changes\", \"before/after\" — output this table instead:\n\n```markdown\n| Rule violated | Original | Simplified |\n|---|---|---|\n| Present perfect tense | \"We have received your request.\" | \"We received your request.\" |\n| Noun cluster (4+ words) | \"the agent task queue priority handler\" | \"the handler that sets task-queue priority\" |\n\nMode: Strict. 7 violations found.\n```\n\nFollow the table with a one-line note on anything you deliberately did **not** simplify, and why (usually: simplifying would lose required precision).\n\n## Boundaries\n\n**Will:**\n- Rewrite ambiguous or dense English into short, single-meaning, active-voice sentences.\n- Return the rewritten text alone by default, and name the rules it applied when the user asks.\n- Preserve every fact, condition, and scope qualifier in the original.\n- Preserve the strength of every hedge, and add no claim the source did not make.\n- Suggest a one-line glossary entry for domain terms that must stay.\n\n**Will not:**\n- Reproduce ASD's official ~900-word dictionary as if it were memorized verbatim — always treat the official download as the source of truth for exact approved wording.\n- Simplify creative, marketing, or persuasive copy where voice and nuance are the point.\n- Silently drop a safety condition, exception, or scope qualifier to shorten a sentence — it will flag the trade-off instead.\n- Convert \"may have failed\" into \"failed\", or \"could be caused by X\" into \"X is the cause\" — losing a hedge changes the claim.\n- Guarantee an aerospace/defense-grade STE-compliant document. This is a general-purpose clarity tool inspired by STE, not a certified STE authoring tool.\n- Make weak content true or useful. STE fixes the *form* of a text, not its substance. A hollow paragraph rewritten under these rules becomes a clean, short, well-punctuated hollow paragraph. If the text has nothing to say, no rewrite fixes that — say so instead of polishing it.\n- Shorten past the point of clarity. Cutting words is not the goal. Removing ambiguity is the goal. Past a certain point compression starts costing the reader time rather than saving it, so stop when the sentence is unambiguous, not when it is shortest.\n\n## Additional Resources\n\n- **`references/writing-rules.md`** — fuller summary of the 9 rule sections and dictionary structure, with citations to the official standard and secondary sources.\n- **`examples/before-after.md`** — worked examples, including official STE examples and agent-output examples built for this skill.\n- **`scripts/ste-lint.py`** — deterministic, stdlib-only linter for the structural rules, including dangling-conjunction in supported list items, plus a synonym-rotation check (one word, one meaning) scoped per file. Exit 1 when hard violations exceed `--baseline` (default 0); advisory findings (passive voice, compound tenses) never fail the run; `--disable` silences named rules. It never flags hedges or modality: those are content, not style, and `--selftest` asserts that \"may have failed\" passes clean.\n\n<!-- File: .cursor/skills/mflux-cli/SKILL.md (Tokens: ~828 | Category: anthropic-skill) -->\n---\nname: mflux-cli\ndescription: Navigate MFLUX CLI capabilities, locate commands by area, and summarize supported features.\n---\n# mflux CLI navigation\n\nUse this skill to inventory CLI capabilities, summarize what the CLI supports, and guide where to look\nfor commands without relying on brittle file paths.\nBecause README examples can drift, prefer verifying support against the current CLI entrypoints.\n\n## When to use\n\n- You need to list supported CLI features or commands.\n- You need to find where a capability is implemented in the CLI.\n- You are documenting or refactoring CLI features and want a stable map.\n- A user asks for CLI help, e.g., “Can you help me generate an image using z-image?”, “Which model is best?”, etc.\n\n## How to find commands (structure, not exact paths)\n\n- Common/shared CLI arguments live in the central CLI parser module.\n- Model-specific CLI entrypoints live under each model's CLI package.\n- Repo-level CLI helpers (completions, defaults) live under the shared CLI package.\n- Utilities may add standalone CLIs (e.g., metadata info, LoRA library).\n\n## Best practices when constructing CLI calls\n\n- **Inference steps**: When constructing a CLI call for any model, *always* check `MODEL_INFERENCE_STEPS` and use the model's default/recommended step count unless the user explicitly asks for a different value. This is especially important for distilled/non-base variants (for example `fibo-lite`, `z-image-turbo`, and other `*-turbo`/`*-lite` models), where using full/base-model step counts is usually counterproductive.\n- **Resource/inspection flags**: Mention `--low-ram` to reduce memory usage and `--stepwise-image-output-dir` for stepwise outputs when useful.\n- **Python API requests**: If a user asks for the Python API, treat the equivalent CLI script as the best starting reference for the underlying parameters and defaults.\n- **CLI implementation changes**: When adding or changing CLI behavior, prefer extending shared parser methods and shared helpers before adding manual one-off arguments or save paths in a model CLI.\n- **Docs/examples drift**: If CLI defaults, supported flags, or recommended usage changed, update the matching README examples in the same pass.\n\n## Capability inventory (current)\n\n### Core generation\n\n- Text-to-image across Flux, Flux2, FLUX 3 Image Klein, Iris-3B, SenseNova-U1.5, DreamLite, Qwen, Z-Image Turbo, FIBO.\n- Image-to-image where supported (Flux, Qwen, Z-Image Turbo, FIBO).\n\n### Editing and conditioning\n\n- Kontext image conditioning.\n- In-context editing and reference-image workflows.\n- CATVTON (virtual try-on).\n- Redux multi-image conditioning.\n- ControlNet (Canny).\n- Depth conditioning.\n- Fill / inpainting.\n- Flux2 Edit, FLUX 3 Image Klein edit (1-10 reference images) and Qwen Edit (multi-image edit).\n- DreamLite edit (one image, instruction-based).\n\n### Upscaling\n\n- SeedVR2 diffusion upscaler (preferred).\n- Flux ControlNet upscaler (legacy).\n\n### Model management\n\n- Quantized inference and saving quantized models.\n- Local model path loading (with base-model hints when needed).\n\n### LoRA\n\n- Load LoRAs, multi-LoRA, scale control.\n- In-context style LoRA shortcuts.\n- LoRA library lookup tool.\n\n### Metadata and reproducibility\n\n- Export JSON metadata per image.\n- Reuse prior parameters from metadata config files.\n- Inspect metadata from existing images.\n\n### Prompt tooling\n\n- Prompt files.\n- Negative prompts where supported (not supported for Flux2, FLUX 3 Image Klein or SenseNova-U1.5; Iris-3B uses them only on the base model).\n\n### Training\n\n- LoRA finetuning.\n\n### Utilities\n\n- DepthPro depth-map extraction.\n- FIBO VLM prompt inspire/refine tools.\n\n<!-- File: .cursor/skills/mflux-debugging/SKILL.md (Tokens: ~2565 | Category: anthropic-skill) -->\n---\nname: mflux-debugging\ndescription: Debug MLX ports by comparing against a PyTorch/diffusers reference via exported tensors/images (export-then-compare).\n---\n# mflux debugging (MLX parity vs PyTorch/diffusers)\n\nUse this skill when you are porting a model to MLX and need to **prove numerical parity** (or isolate where it diverges) versus a **PyTorch reference implementation** (often from diffusers).\n\nThis skill defaults to **export-then-compare**:\n- Run the reference once and **export deterministic artifacts** (tensors + optional images).\n- Load those artifacts in MLX and compare with clear thresholds.\n\n## When to Use\n\n- You suspect a port mismatch (wrong shapes/layout, RoPE, scheduler math, dtype casting, etc).\n- You want a repeatable workflow to narrow down the first layer/block where outputs diverge.\n- You need evidence of correctness before refactoring (see `mflux-model-porting`).\n\n## Ground Rules (repo norms)\n\n- Use `uv` to run Python: `uv run python -m ...`\n- If you run pytest, preserve outputs: `MFLUX_PRESERVE_TEST_OUTPUT=1` (see `mflux-testing` and the justfile test recipes).\n- Do **not** update or replace reference (“golden”) images unless explicitly asked.\n- Debug artifacts (tensor dumps) should live in a local folder and **must not be committed** unless explicitly asked.\n- If you need the broader porting workflow (milestones, ordering, when to refactor), follow `mflux-model-porting`.\n- **RNG warning**: PyTorch and MLX RNGs are different. Matching the same integer `seed` is not enough for parity—export the *exact* initial noise/latents from the reference and load them in MLX.\n- Practical setup: the PyTorch reference repo (often `diffusers/`) and `mflux/` are frequently **next to each other** on disk (e.g. both on your Desktop). Use absolute paths when in doubt.\n\n## Default Workflow (export-then-compare)\n\n### Preferred workflow: two tiny scripts + inline dumps\n\nFor day-to-day debugging, prefer a **minimal paired repro**:\n- One simple script in the reference repo (often `diffusers/`), e.g. `diffusers/flux2_klein_edit_debug.py`\n- One simple script in `mflux/`, e.g. `mflux/flux2_klein_edit_debug.py`\n\nKeep them “boring”: hardcoded variables, no cli, no framework, and just a few `np.savez(...)` / `mx.save(...)` lines at the right spot.\n\nThe key trick for RNG parity:\n- In the reference script, **compute latents once**, save them, then **pass them back into the pipeline** (`latents=...`) so the run definitely uses the dumped tensor.\n- In rare cases where a tensor needs to be saved from within a loop, make sure its name reflects the loop conditions (e.g the 4th noise predcition in a 10 step loop etc).\n- In the MLX script, **load that same latents file** and feed it into the MLX run (do not rely on matching integer seeds).\n\n### 1) Pick a single deterministic repro\n\n- Fix **seed(s)**, **prompt(s)**, **height/width**, **steps**, **guidance**, and any **input image** paths.\n- Keep the first repro small if possible (fewer steps, smaller resolution) to iterate quickly.\n\n### 2) Decide your checkpoints (what to dump)\n\nStart coarse, then narrow:\n- **VAE**: packed latents before decode; optional intermediate activations for one block if needed.\n- **Transformer**: hidden states at entry/exit of the model, then per-block (or every N blocks), then inside attention/MLP.\n- **Text encoder**: token ids + attention mask, embeddings output, then per-layer hidden states if needed.\n- **Scheduler**: timesteps/sigmas/alphas and the predicted noise/velocity per step.\n\nTip: work “backwards from pixels” like `mflux-model-porting` suggests: validate VAE decode first with exported latents, then the diffusion/transformer loop, then text encoder.\n\n### 3) Export artifacts from the PyTorch reference (no logic changes)\n\nCreate a run directory like:\n- `./debug_artifacts/<run_id>/ref/`\n\nExport with one of these patterns:\n- **NumPy**: `np.savez(path, **tensors_as_numpy)`\n- **PyTorch**: `torch.save(dict_of_tensors, path)`\n\n### 4) Run the MLX side with the same inputs and compare\n\nCreate a matching run directory:\n- `./debug_artifacts/<run_id>/mlx/`\n\nLoad and compare tensors. For each checkpoint, report:\n- **Shape + dtype**\n- **max_abs_diff**, **mean_abs_diff**\n- **max_rel_diff** (guarding division by zero)\n- Pass/fail with a clearly stated **rtol/atol**\n- It is **more important to inspect actual tensor values** (e.g., first 10 elements) than rely on summary stats.\n- Statistics can mislead; small-looking stats can hide systematic drift or sign flips.\n- Prefer **runtime tensor dumps** over code reading; code can use different conventions yet still represent the same math.\n\nSuggested tolerance starting points (adjust per component):\n- **fp32 comparisons**: `atol=1e-5`, `rtol=1e-5`\n- **fp16/bf16 comparisons**: `atol=1e-2`, `rtol=1e-2`\n- If comparing images: compare both (a) tensor space before final clamp and (b) saved `png` visually, since tiny numeric diffs can look identical.\n\nIf a checkpoint fails:\n- Add an **earlier** checkpoint and repeat (binary search through the forward path).\n\n## Common Causes of Divergence (high-signal checklist)\n\n- **Layout mistakes**: NCHW vs NHWC, transposes around convs/attention, flatten/reshape ordering. Some operations like convolutions can have different conventions between libraries.\n- **Broadcasting**: scale/shift vectors applied on the wrong axis (common in RoPE and modulation).\n- **Dtype casting**: reference silently upcasts to fp32 for norm/softmax; MLX path stays in fp16.\n- **RoPE details**: position ids, reshape order, whether cos/sin are broadcast over heads vs sequence.\n- **Scheduler math**: timestep indexing, sigma/alpha definitions, and off-by-one step order.\n- **Scheduler config**: compare sigma schedules directly.\n- **Seed/RNG**: ensure you aren’t comparing stochastic paths (dropout, noise sampling) without controlling RNG.\n- **Device dtype**: MPS `float16` can produce NaNs; prefer `bfloat16` for reference dumps if you see NaNs.\n- **Do not use CPU** for comparisons; always keep reference runs on MPS to avoid misleading behavior.\n\n## Artifact Hygiene\n\n- Prefer `debug_artifacts/<run_id>/...` at repo root.\n- Do not commit `debug_artifacts/` unless explicitly asked.\n- If you convert the parity check into a test, follow the repo’s testing conventions and preserve outputs (see `mflux-testing`).\n- Clean up old artifacts when they are no longer needed, only focus on the current problem and avoid confusion with older artifacts that are not relevant for the current task.\n\n## Isolate transformer + VAE (inject reference initial latents)\n\nWhen full end-to-end images differ between mflux and diffusers but you need to trust the **core model** (transformer, text encoder, VAE decode), export the reference **initial noise** and run mflux denoising from that tensor. If injected-latent mflux looks good while native-seed runs differ, the forward path is likely sound and any gap is probably RNG, scheduler, or optional reference-only components.\n\n**Do not commit** these scripts or Desktop `.npy` files unless asked. Use inline `uv run python <<'PY' ... PY` heredocs in the reference repo and in `mflux/`.\n\n### Step 1 — Export initial latents from diffusers\n\nRun from the local `diffusers/` clone (often next to `mflux/` on Desktop). Match mflux settings: height, width, seed, dtype (`bfloat16` on MPS).\n\nLoad the reference pipeline the same way you would for a normal generation, but **disable optional subsystems** that mflux does not implement or download (check `model_index.json` vs mflux `get_download_patterns()` / weight definition). Pass `None` for unused components, set pipeline flags to skip them, and use `local_files_only=True` so missing weights surface immediately instead of downloading extras.\n\nThen export noise with the same shape helper the pipeline uses internally:\n\n```python\nfrom diffusers.utils.torch_utils import randn_tensor\n\npipe = <ReferencePipeline>.from_pretrained(\n    \"<org/model>\",\n    torch_dtype=torch.bfloat16,\n    local_files_only=True,\n    # plus any kwargs to omit optional reference-only modules\n)\nlatent_h = height // pipe.vae_scale_factor  # or read from pipeline/config\nlatent_w = width // pipe.vae_scale_factor\nch = pipe.transformer.config.in_channels    # name varies by architecture\ngenerator = torch.Generator(device=\"mps\").manual_seed(seed)\nlatents = randn_tensor(\n    (1, ch, latent_h, latent_w),\n    generator=generator,\n    device=\"mps\",\n    dtype=torch.bfloat16,\n)\nnp.save(\"/path/to/init_latent.npy\", latents.detach().cpu().float().numpy())\n```\n\n### Step 2 — Denoise in mflux from the loaded latent\n\nIf `generate_image()` has no `latents=` argument, **inline the denoising loop** from the variant class instead of patching production code:\n\n1. `latents = mx.array(np.load(path)).astype(mx.bfloat16)`\n2. Text encode step from the variant (e.g. `_encode_prompts`, prompt cache, etc.)\n3. Any position encoding / conditioning setup the variant does before the loop\n4. Denoise loop: noise prediction + `config.scheduler.step(...)` over `config.time_steps`\n5. VAE decode + `ImageUtil.to_image(...)` (or the variant’s decode helper) → save PNG\n\nAlso run one `generate_image(seed=...)` baseline on the same prompt for side-by-side.\n\n### How to read results\n\n| Comparison | What it tells you |\n|---|---|\n| mflux native seed vs itself (re-run) | Sampling is deterministic on this hardware |\n| mflux + diffusers latent vs diffusers full run | Transformer + VAE + CFG path quality |\n| mflux native seed vs diffusers full run | **Not** a parity test — different RNG (`mx.random` vs `torch.Generator`) and often different sigma schedules |\n| mflux + diffusers latent vs mflux native seed | Large diff is **expected** if schedulers/sigmas differ, even with identical starting noise |\n\nIf **injected-latent mflux** looks good, the port’s core forward path is trustworthy. Golden CI tests should still lock **mflux-native** sampling (see `mflux-testing`), not diffusers pixel parity.\n\n## diffusers reference runs (side-by-side images)\n\n- mflux does **not** depend on diffusers; run reference scripts from a sibling `diffusers/` clone with `cd .../diffusers && uv run python`.\n- Use `HF_HUB_OFFLINE=1` when weights are cached to catch missing components the reference pipeline expects but mflux omits from its download patterns.\n- Compare at matched resolution, steps, guidance, seed, and precision when possible (note mflux `-q 8` vs diffusers bf16 is not apples-to-apples for speed or pixels).\n- Save outputs to explicit paths (e.g. Desktop) and report wall time with `/usr/bin/time -p`.\n\n## See Also\n\n- `mflux-model-porting`: correctness-first workflow (validate components and lock behavior before refactor).\n- `mflux-testing`: how to run tests safely and handle image outputs/goldens.\n\n<!-- File: .cursor/skills/mflux-dev-env/SKILL.md (Tokens: ~406 | Category: anthropic-skill) -->\n---\nname: mflux-dev-env\ndescription: Set up and work in the mflux dev environment (arm64 expectation, uv, justfile recipes, lint/format/test).\n---\n# mflux dev environment\n\nThis repo expects macOS arm64 and prefers `uv` + justfile recipes.\n\n## When to Use\n\n- You’re setting up the repo locally or diagnosing environment/setup issues.\n- You need the canonical way to run lint/format/check/build/test.\n\n## Instructions\n\n- Prereq: `just` ≥ 1.50 (`brew install just`). CI lints the justfile with `just --fmt --check`; run `just fmt-justfile` to auto-fix formatting.\n- Prefer justfile recipes:\n  - Install: `just install`\n  - Lint: `just lint`\n  - Format: `just format`\n  - Pre-commit suite: `just check`\n  - Build: `just build`\n- Prefer `uv run ...` for running Python commands to ensure the correct environment.\n- When running tests, keep `MFLUX_PRESERVE_TEST_OUTPUT=1` enabled (the justfile test recipes already do this).\n\n## Type checking (ty)\n\n- The type checker is astral's `ty`, pinned exactly in `pyproject.toml` dev deps (mirrored in `.pre-commit-config.yaml` and run in CI). Run it with `just typecheck` (or `uv run ty check`).\n- `[tool.ty.rules]` in `pyproject.toml` carries a one-time migration baseline (mypy → ty): every rule listed there had pre-existing violations and is set to `\"ignore\"`, with violation counts in comments.\n- **Planned burn-down**: we intend to re-enable these rules piecemeal — delete one ignore line, fix all resulting `ty check` errors, commit, repeat. Prefer starting with low-count rules. Do not add new ignore lines; new code must pass all rules not in the baseline.\n\n<!-- File: .cursor/skills/mflux-manual-testing/SKILL.md (Tokens: ~999 | Category: anthropic-skill) -->\n---\nname: mflux-manual-testing\ndescription: Manually validate mflux CLIs by exercising the changed paths and reviewing output images/artifacts.\n---\n# mflux manual testing\n\nSome regressions (especially in CLIs and image IO) are easiest to catch by running the commands and visually inspecting outputs. This skill provides a lightweight, change-driven manual test checklist.\n\n## When to Use\n\n- You changed any CLI entrypoint(s) under `src/mflux/models/**/cli/`.\n- You touched callbacks (e.g. stepwise output, memory saver) or metadata/image saving.\n- Tests are green but you want confidence in real command usage.\n\n## Strategy (change-driven)\n\n- Identify what changed on your branch (new flags, default behavior changes, new callbacks, new models).\n- Only run manual checks for the touched areas; don’t try to exercise every CLI.\n- Prefer 1–2 seeds and a small step count (e.g. 4) for fast iteration, unless the change affects convergence/quality.\n- Before manual CLI testing, **reinstall the local tool executables** so you’re testing the latest code:\n\n```bash\nuv tool install --force --editable --reinstall .\n```\n\n## Core CLI checks (pick what’s relevant)\n\n- **Basic generation**: run the CLI once with a representative prompt and confirm the output is not “all noise”.\n- **Model saving** (if relevant): if you touched weight loading/saving or model definitions, run `mflux-save` for the affected model(s) and verify:\n  - the output directory is created\n  - the command completes without missing-file errors\n- **Run from disk** (if relevant): if you touched save/load paths or model resolution, generate from a locally saved model directory by passing `--model /full/path/to/saved-model` and confirm it runs and produces a sane image.\n- **Stepwise outputs** (if relevant): run with `--stepwise-image-output-dir` and confirm:\n  - step images are written for each step\n  - the final step image matches the final output image qualitatively\n  - the composite image is created\n- **Low-RAM path** (if relevant): run with `--low-ram` and confirm:\n  - generation completes\n  - output quality is sane (no unexpected all-noise output)\n- **Metadata** (if relevant): run with `--make-conf` and confirm that the CLI writes the `.metadata.json` sidecar and that it looks consistent.\n\n## Output review (human-in-the-loop)\n\n- Always point the human reviewer at:\n  - the final output image path\n  - any stepwise directory / composites\n  - any metadata JSON files\n- Ask the human to visually confirm “looks correct” rather than attempting pixel-perfect parity manually.\n\n## diffusers reference comparison (new model ports)\n\nmflux does not install diffusers; use a sibling clone (commonly `../diffusers` on Desktop).\n\n**When**: validating a new MLX port before merge, or when golden tests / visuals look wrong.\n\n**Match settings**: same prompt, width, height, seed, steps, guidance. For fair speed comparisons, match precision (mflux bf16 vs diffusers bf16, not `-q 8` vs bf16).\n\n**diffusers setup tips** (read the reference pipeline first):\n- Compare `model_index.json` / `from_pretrained` kwargs with mflux `get_download_patterns()` — disable or pass `None` for components mflux does not load\n- `local_files_only=True` / `HF_HUB_OFFLINE=1` to use cache and surface missing files early\n- Distilled vs base variants are often the same pipeline class with different checkpoint + steps/guidance\n\n**Run both**:\n```sh\n# mflux\nuv run mflux-generate-<model> --prompt \"...\" --width 640 --height 368 --seed 7 --steps 8 --guidance 1.0 --output /tmp/mflux.png\n\n# diffusers (from diffusers repo)\ncd ../diffusers && HF_HUB_OFFLINE=1 uv run python -c \"...\"  # inline script; see mflux-debugging\n```\n\n**If visuals differ**: do not assume the port is broken. Run the **latent injection** workflow in `mflux-debugging` to separate (a) transformer/VAE quality from (b) RNG/scheduler differences.\n\nSave comparison PNGs to explicit paths; report `/usr/bin/time -p` totals. Do not commit comparison artifacts.\n\n## Notes\n\n- If the installed `uv tool` executable behaves differently from `uv run python -m ...`, prefer the local module run to isolate environment/tooling issues.\n- If you need to reinstall the local tool executables, see the repo rules for the current recommended command.\n\n<!-- File: .cursor/skills/mflux-model-porting/SKILL.md (Tokens: ~4190 | Category: anthropic-skill) -->\n---\nname: mflux-model-porting\ndescription: Port ML models into mflux/MLX with correctness-first validation, then refactor toward mflux style.\n---\n# mflux model porting\n\n## Goal\nProvide 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.\n\n## Principles\n- Match the reference implementation first; prove correctness before cleanup.\n- Lock correctness with deterministic tests before refactoring.\n- 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.\n- Refactor toward shared components and clean APIs once tests are green.\n- 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.\n\n## Workflow (checklist)\n1. **Scope and parity**\n   - Define target parity (outputs, speed, memory) and acceptable tolerances.\n   - Identify reference files, configs, and checkpoints to mirror.\n   - Draft a Cursor plan for the port and review it before starting implementation.\n2. **Port fast to reference**\n   - Add the model package skeleton and a variant class + initializer.\n   - Follow standard mflux initializer/weight-loading style; review recent ports like `z_image_turbo` and `flux2_klein` for structure and naming.\n   - Wire weight definitions/mappings early so loading is exercised (implement quantization in the initializer, but skip it during early runs).\n   - Keep the first implementation simple and explicit; defer `mx.compile` and other speed-focused changes until deterministic parity is passing.\n   - When defining explicit weight mappings, inspect actual tensor values from the model in the Hugging Face cache to confirm names and shapes.\n   - 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).\n   - Add lightweight shape checks close to the code paths.\n   - Use `mx.save`/`mx.load` at critical points; it is OK to add these to the reference (without changing logic) to export latents.\n3. **Port order (work backwards from image)**\n   - Typical image generation flow: `prompt → text_encoder → transformer_loop → VAE → image`.\n   - For porting, invert the order so you can validate pixel space early.\n   - Start with VAE decode/encode to validate output images quickly:\n     - Export packed latents from the reference just before VAE decode.\n     - Load latents inline and decode to an image for visual inspection.\n     - Run an encode→decode roundtrip to sanity check reconstruction; a good-looking image reconstruction increases confidence in the implementation.\n     - 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.\n   - Then port the transformer loop and its schedulers with intermediate latent checks.\n     - If the reference uses a novel scheduler, port it; otherwise, reuse the existing mflux scheduler.\n   - Finish with the text encoder and tokenizer details.\n   - After each major component is validated (e.g., VAE, transformer, text encoder), commit with a clear milestone message like \"VAE done\" to preserve progress.\n    - Once the full port is working, remove any loaded tensors or debug artifacts so no traces remain.\n4. **Deterministic validation**\n   - Create a deterministic MLX test (image or tensor) that locks the output.\n   - Run tests via `MFLUX_PRESERVE_TEST_OUTPUT=1 uv run <test command>`.\n   - If MLX OOMs on sensible inputs (e.g., 1024×1024), assume a likely porting mistake and re-check shapes or memory-heavy ops.\n5. **Post-test refactor (explicit step)**\n   - Review commits after the first deterministic test to capture refactoring preferences.\n   - Consolidate shared components into common modules.\n   - Remove debug paths and one-off schedulers once validated.\n   - Move configuration defaults into standard config/scheduler paths.\n    - Simplify and decompose large files into focused modules once behavior is locked.\n    - Prefer shared scheduler implementations when they already exist in mflux.\n    - Ensure CLIs register callbacks via `CallbackManager.register_callbacks(...)` so shared features like `--stepwise-image-output-dir` work; pass a `latent_creator` that supports `unpack_latents(...)`.\n    - Keep running the deterministic image test during refactors to avoid regressions.\n   - Align the variant class with recent ports (`flux2_klein`, `z_image`): `prompt_cache`, merged `_predict`, RoPE setup inside predict path, `_decode_latents` helper, no verbose comments/docstrings (see repo `RULE.md`).\n   - Strip dead scaffolding (e.g. unused gradient-checkpointing flags) once training/inference paths are stable.\n6. **Pre-merge polish (after core port works)**\n   - **diffusers sanity check**: run matched mflux + diffusers generations; use `mflux-debugging` latent injection if outputs disagree but you need to validate transformer/VAE.\n   - **Golden tests**: pick prompt/seed/settings that are stable on target CI hardware; update reference PNGs only after explicit approval (see `mflux-testing`).\n   - **img2img**: verify latent packing/normalization on the img2img path matches txt2img and training (especially when reusing a shared VAE from another model family). `pack_latents` must accept the 5D `(B, C, 1, H, W)` tensor that tiled VAE encode (`vae_encode_tiled`) returns — squeeze the singleton temporal axis first, as `flux2`/`fibo`/`z_image` latent creators do; a 4D-only unpack (or a bare passthrough `pack_latents`) breaks tiled img2img. This is reachable via `--low-ram`: `MemorySaver` sets `tiling_config = TilingConfig()` (`vae_encode_tiled=True`), so always test img2img with `--low-ram`, not just the default path (which is safe only because `VAEUtil.encode` squeezes 5D→4D when tiling is off).\n   - **Cross-model touch points**: list every file outside `models/<your_model>/`; justify shared changes (`memory_saver` tiling guard, shared VAE `tiling_config`, training `runner` wiring). Drop unrelated edits (e.g. personal `.gitignore` entries).\n   - **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 `du` on HF cache and/or `mflux-save` + `du -sh` for quantized sizes.\n   - **Training**: example JSON under `models/common/training/_example/`, un-ignore in `.gitignore`, fast unit tests for training-adapter preview defaults.\n   - Re-run `just lint`, `just test-fast`, then slow golden tests before merge.\n7. **Finalize**\n   - Re-run tests and basic perf checks after polish.\n   - Add CLI/pipeline defaults and completions later, once core output is stable.\n   - Ensure the model is wired into the standard surfaces:\n     - `ModelConfig` entry + aliases\n     - Thin model CLI entrypoint that uses shared parser/config/callback patterns and a command class with `validate`, `load` and `generate` (see [Command class](#command-class-validate-load-generate))\n     - README following the structure and tone of existing model READMEs\n     - Python API example that matches the CLI/defaults\n   - Document any new mapping rules, shape constraints, or tolerances.\n\n## Package layout (reference: `flux2`)\n\nUse `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.\n\n```\n{model}/\n  {model}_initializer.py\n  __init__.py                    # export variant + initializer\n  README.md\n  cli/\n    {model}_generate.py          # (+ edit/turbo CLIs when applicable)\n  latent_creator/\n    {model}_latent_creator.py\n  model/\n    {model}_text_encoder/        # prompt_encoder.py, tokenizer pieces, text_encoder.py\n    {model}_transformer/         # attention, blocks, rope, transformer.py (split files)\n    {model}_vae/                 # or reuse shared VAE (e.g. flux2_vae) — document in README\n    {model}_scheduler/           # only when not covered by models/common/schedulers\n  variants/\n    __init__.py                  # re-export public variant class(es)\n    txt2img/\n      __init__.py\n      {model}.py                 # e.g. flux2_klein.py, ideogram4.py\n    edit/                        # when the model supports image-conditioned generation\n      __init__.py\n      {model}_edit.py\n  weights/\n    __init__.py\n    {model}_weight_definition.py # components, download patterns, tokenizers\n    {model}_weight_mapping.py    # WeightTarget list / key transforms for base weights\n    {model}_lora_mapping.py      # LoRA key aliases (diffusers, PEFT, kohya) — when LoRA is supported\n  training_adapter/              # when mflux-train is supported\n    {model}_training_adapter.py\n```\n\n**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`.\n\n**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).\n\n**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`.\n\n**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.\n\n## Integration surfaces checklist (don’t forget)\n\nPast [closed PRs](https://github.com/mflux-community/mflux/pulls?q=is%3Apr+is%3Aclosed) show the same wiring gaps recurring on every new model. Use this as a **tick list** alongside the workflow above — not every row applies to every model (e.g. skip vision-encoder rows for txt2img-only), but scan it before opening a port PR.\n\n### Repo wiring (required for every new model family)\n\n| Surface | What to do |\n|---|---|\n| `pyproject.toml` | Register `mflux-generate-<model>` (and edit/turbo variants if separate) |\n| `ModelConfig` | Entry in `AVAILABLE_MODELS`: aliases, HF repo id, `num_train_steps`, guidance support, sigma shift, `transformer_overrides`, distilled vs base step defaults |\n| `models/common/resolution/model_revisions.py` | Pin every HF repo the model downloads (`model_name`, ControlNet, helper repos) to the full commit hash its golden references were generated with. `tests/resolution/test_model_revisions.py` fails for a registry repo without a pin. |\n| `scripts/ci_extract_models.py` | Add an `OVERLAY` row for every new `AVAILABLE_MODELS` key: taxonomy, CLI/tool commands, status, and quantization support. Use `EXTRA_ENTRIES` only for standalone tools with no `ModelConfig` entry. Run `just ci-extract` and confirm the model is present in `.ci_cache/models_mflux.json`. |\n| `cli/defaults/defaults.py` | `MODEL_INFERENCE_STEPS` (keyed by the canonical `AVAILABLE_MODELS` key — the `--model` choices derive from the registry, nothing to add there) |\n| `models/common/cli/save.py` | Route `mflux-save` to the **correct variant class** (txt2img vs edit vs turbo — wrong class silently drops weights; see [#405](https://github.com/mflux-community/mflux/pull/405)) |\n| Main `README.md` | Model table row + attribution line |\n| `src/mflux/models/<model>/README.md` | Examples aligned with Flux2-style layout; disk sizes measured (`du`, `mflux-save`) |\n| `src/mflux/assets/` | Hero/showcase image if other models have one (`git add -f` when `*.jpg` is gitignored) |\n\n### Weights, tokenizer, download scope\n\n| Surface | What to do |\n|---|---|\n| `*WeightDefinition` | `get_components()`, `get_download_patterns()`, `get_tokenizers()` — **only** list artifacts mflux actually loads |\n| Weight mapping | Explicit `WeightTarget` list; verify tensor names/shapes against HF cache blobs |\n| Tokenizer | Exercise local-path load, partial HF cache, and any special formats (protobuf, sentencepiece, etc.) — see [#383](https://github.com/mflux-community/mflux/pull/383), [#389](https://github.com/mflux-community/mflux/pull/389), [#390](https://github.com/mflux-community/mflux/pull/390) |\n| Optional reference components | Document in README what the upstream pipeline includes but mflux omits (extra encoders, preprocessors, etc.) |\n\n### LoRA\n\n| Surface | What to do |\n|---|---|\n| `*LoRAMapping` | Support **multiple export key conventions** (diffusers, PEFT `.default.weight`, kohya/`diffusion_model.*` aliases) — silent zero-key loads were fixed repeatedly ([#376](https://github.com/mflux-community/mflux/pull/376), [#374](https://github.com/mflux-community/mflux/pull/374), [#397](https://github.com/mflux-community/mflux/pull/397)) |\n| Tests | Fast tests that real community LoRA filenames map to non-zero keys |\n| Inference CLI | `--lora` via shared parser (no bespoke loader). `--lora-paths` / `--lora-scales` are deprecated. |\n\n### Inference CLI & shared features\n\n| Surface | What to do |\n|---|---|\n| Thin CLI | `build_parser()` with `CommandLineParser` + `CallbackManager.register_callbacks(...)` |\n| Command class | **Required.** Put the CLI work in `<Model>Command` with `validate`, `load`, `generate` and `latent_creator`. `main()` only calls these steps. See below. |\n| `DimensionResolver` | Use in generate/edit CLIs when width/height can be omitted (API/OpenWebUI paths) — [#378](https://github.com/mflux-community/mflux/pull/378) |\n| `latent_creator` | `pack_latents` / `unpack_latents`; img2img path must match txt2img normalization (BN, scale factor) |\n| `tiling_config` | If initializer sets custom tiling, ensure `MemorySaver` does not overwrite it |\n| Guidance defaults | Distilled vs base: match `ModelConfig`, CLI default, README, and training preview adapter |\n| `mflux-save` round-trip | Save quantized model → load from local path → generate; confirm `model.safetensors.index.json` if sharded |\n\n### Command class: validate, load, generate\n\nUse this pattern for every new generate CLI. Do not put the full flow in one `main()`. Plugins under `mflux.extras` call these steps. A CLI without them cannot support plugins. See `docs/plugins.md` and `docs/validate-load-generate.md`.\n\nCopy the structure of `src/mflux/models/qwen/cli/qwen_image_generate.py`:\n\n| Member | Rule |\n|---|---|\n| `latent_creator` | Class attribute. `main()` passes it to `CallbackManager.register_callbacks(...)`. |\n| `validate(args) -> ModelConfig` | Static. Do not load weights. Resolve `--model` with `ConfigResolution.resolve_restricted(...)`. If the command has rules for flag combinations, sizes or output formats, test them here and raise `ValueError`. |\n| `load(args) -> Model` | Static. Call `validate(args)` first. Then make the model with `quantize`, `model_path` and `**lora_init_kwargs_from_args(args)`. |\n| `generate(model, args, seed, prompt) -> GeneratedImage` | Static. Make one image for one seed and one prompt. Apply the command defaults here, for example guidance and `DimensionResolver`. A direct caller must get the same image as `main()`. Do not save the image. |\n\n`main()` only parses the arguments, calls `load`, registers the callbacks, calls `generate` for each seed and saves each image.\n\n### Training (if supported)\n\n| Surface | What to do |\n|---|---|\n| `training/runner.py` | Register `*TrainingAdapter`; handle `low_ram` / tiling like other models |\n| Example JSON | `models/common/training/_example/train_<model>.json` + `.gitignore` un-ignore |\n| Preview generation | Adapter should use canonical steps/guidance for distilled vs base (unit test this) |\n| Local `model_path` | Confirm `mflux-train` works with saved local weights — [#370](https://github.com/mflux-community/mflux/pull/370) |\n\n### Tests & CI\n\n| Surface | What to do |\n|---|---|\n| Slow golden test | `tests/image_generation/test_generate_image_<model>.py` + `reference_*.png` on CI hardware |\n| Fast tests | LoRA mapping, training-adapter preview defaults, argparser if new CLI flags |\n| `just ci-extract` | Required after changing `AVAILABLE_MODELS` or `OVERLAY`; verifies every registry key has CI-manifest metadata |\n| `just lint` / `just test-fast` | Before slow tests |\n\nWhen fixing a gap for model *N*, ask whether the same gap exists for other recent models and whether a **shared** fix belongs in `models/common/` (preferred over copy-paste per model).\n\n## Tooling expectations\n- Use `uv` for running scripts and tests: `uv run <command>`.\n- Prefer `uv run python -m <module>` for local modules.\n\n## Deliverables\n- Deterministic MLX test that verifies correctness.\n- Documented weight mapping, shape constraints, and any known tolerances.\n- Cleaned, shared components aligned with mflux style.\n- Standard mflux surfaces in place: config aliases, thin CLI with a `validate` / `load` / `generate` command class, and a README/examples pass aligned with the final behavior.\n\n<!-- File: .cursor/skills/mflux-model-tiny-test/SKILL.md (Tokens: ~2005 | Category: anthropic-skill) -->\n---\nname: mflux-model-tiny-test\ndescription: Write a hermetic \"tiny\" model-saving test for an mflux model — a fast twin of the slow save/load test that runs the real ModelSaver/WeightLoader/WeightApplier seam on real component classes at toy dimensions, with no downloads or image generation. Use when asked to \"make tiny test for <model>\".\n---\n# mflux tiny model-saving test\n\nA tiny test proves a model's quantized checkpoint survives a save/load roundtrip byte-for-byte, in about a second, without downloading anything. It builds the model's **real** component classes at toy dimensions and pushes them through the **real** save/load code path.\n\n## When to Use\n\n- You're asked to \"make tiny test for `<model>`\" or add a fast twin of a slow save/load test.\n- You ported a new model (see `mflux-model-porting`) and want cheap checkpoint coverage.\n\nRelated: `mflux-testing` for running the suite and golden-image rules.\n\n## Reference implementations\n\nRead these before writing a new one — they are the source of truth:\n\n- `tests/model_saving/tiny_checkpoint_helper.py` — the shared harness\n- `tests/model_saving/test_tiny_model_saving_ernie_image.py` — components take explicit kwargs\n- `tests/model_saving/test_tiny_model_saving_ideogram4.py` — components take a Config dataclass\n\nDo not trust code quoted in this skill over those files. The pattern landed as an RFC (PR #599, \"proposal + demo on 2 models\") and is expected to evolve.\n\n**Models that already have tiny tests:** `ernie_image`, `ideogram4`.\n\n## What you write\n\nOne file, no `src/` changes:\n\n```text\ntests/model_saving/test_tiny_model_saving_<model>.py\n```\n\nThe whole test is a single call into `TinyCheckpointRoundtrip`. The real work is figuring out how to build that model's components small. Match the two examples exactly:\n\n- class `TestTiny<Model>ModelSaving`\n- method `test_tiny_quantized_checkpoint_roundtrips_exactly`, decorated `@pytest.mark.fast`\n- a `@staticmethod _tiny_components()` returning the component dict\n- a comment naming the slow twin it mirrors\n\n## Instructions\n\n### 1. Read the weight definition — it is the contract\n\n```text\nsrc/mflux/models/<model>/weights/<model>_weight_definition.py\n```\n\n`get_components()` is authoritative: it gives the exact set of component **names** you must produce, and how many. While there, note two things:\n\n- **`quantization_group_size`** — a class attribute on the weight definition. Defaults to 64 but is not always 64 (`boogu` uses 32). Every tiny dimension must be a multiple of *this model's* value. Check with `grep -n \"quantization_group_size\" src/mflux/models/<model>/weights/*.py`.\n- **`skip_quantization=True`** on any component (`krea2` and `qwen` each have one). In production, `WeightApplier._quantize` honors this flag and leaves the component unquantized. **`TinyCheckpointRoundtrip._quantize` does not** — it calls `nn.quantize` on every saved component regardless of the flag, so a `skip_quantization` component comes out of the \"saved\" side quantized (with `scales`/`biases`) while the reloaded \"fresh\" side stays unquantized (no `scales`/`biases`). The helper's exact key-set comparison (`saved_weights.keys() == fresh_weights.keys()`) will then fail for that component. This is a real gap in `tiny_checkpoint_helper.py`, not a quirk to work around in the test file — if you're writing a tiny test for `krea2`, `qwen`, or any other model with a `skip_quantization` component, stop and fix `TinyCheckpointRoundtrip._quantize` to skip those components (mirroring `WeightApplier._quantize`) rather than special-casing it in the test.\n\n### 2. Find each component's real class and read its `__init__`\n\nDerive the shrink knobs from the actual constructor. Do not pattern-match one example — they differ deliberately: ERNIE's components take explicit kwargs (`hidden_size=`, `num_layers=`), Ideogram 4's transformer takes an `Ideogram4Config` dataclass.\n\nLook under `src/mflux/models/<model>/model/`. Shrink layer counts to 2, hidden and intermediate sizes to 128, head counts to 2, vocab to 128.\n\n### 3. Use `TinyVAEStandIn` for the VAE\n\nThe real VAEs are fixed-size (~170M param) architectures with no dimension knobs, so they cannot be shrunk. `ModelSaver`/`WeightLoader` treat every component as an opaque parameter tree, so the stand-in walks the identical code path. Don't spend a loop trying to shrink a real VAE.\n\n### 4. Respect interlocking dimension constraints\n\nDimensions are not independent. Look for constraints in the component's `__init__` and attention/rope code:\n\n- `rope_axes_dim` must **sum to** `head_dim` (ERNIE: `[16, 24, 24]` → 64)\n- `head_dim` must be consistent with `hidden_size / num_attention_heads`\n- `num_key_value_heads` must divide `num_attention_heads`\n\n### 5. Choose `tensors_per_shard`\n\nStart with `tensors_per_shard=8`. It forces shard boundaries so the `index.json` / `weight_map` multi-shard paths get exercised — the production size-based split (≥1 GB) never shards test-sized tensors.\n\nThe helper asserts `len(shard_files) > component_count`. If a model's tiny components have too few parameter tensors to clear that bar, **lower the number until it passes** — do not drop the argument, that silently removes multi-shard coverage.\n\n### 6. Name the slow twin — after checking it exists\n\nThe examples carry `Fast twin of tests/model_saving/test_model_saving_<model>.py`. Several models have weight definitions but **no** slow save test. Verify with `ls tests/model_saving/` and adapt the comment rather than pointing at a file that isn't there.\n\n## Constraints that will bite you\n\n- **Key the dict by `component.name`, not `model_attr`.** The helper does a bare `components[component.name]` lookup, so a missing or misnamed key is a raw `KeyError`, not a helpful message. Most common first-try failure. Every component in `get_components()` needs an entry.\n- **Do not collapse the two seeds.** The harness randomizes saved components with `seed=0` and fresh ones with `seed=1`. That difference is exactly what makes the final equality assertion prove values came off disk. Unifying them leaves the test green and meaningless.\n- **Do not edit `WeightDefinitionType`.** The helper types `weight_definition` as plain `type` on purpose — that `TYPE_CHECKING` union has drifted and omits several definitions. Widening a src type alias is out of scope; see the helper's comment.\n- **Do not modify `src/`.** A tiny test is a test-only addition. If a model appears to genuinely require a src change to be testable, stop and report that rather than making it.\n\n## Verify\n\n```sh\nuv run --no-sync python -m pytest tests/model_saving/test_tiny_model_saving_<model>.py -v\n```\n\nThen confirm nothing else broke with `just test-fast` (see `mflux-testing`).\n\nThe test should run in roughly a second. If it takes noticeably longer, or the network is touched, something is loading a real checkpoint — investigate rather than accepting it.\n\n### Do you need to check that quantization actually happened?\n\n**No.** Verified empirically: MLX raises loudly on a bad dimension rather than silently skipping —\n\n```text\nValueError: [quantize] The last dimension of the matrix needs to be divisible\nby the quantization group size 64. However the provided matrix has shape (100,100)\n```\n\nso a dimension that isn't a clean multiple of the group size fails the test outright. It cannot leave a green-but-weak twin.\n\nRelatedly, when inspecting a quantized tree you'll see some `.weight` entries with no matching `.scales`. Confirmed benign: those are 1-D norm weights and `Conv2d` layers, which `nn.quantize` correctly leaves alone. Only `Linear`-style layers quantize. Don't chase these.\n\n## Troubleshooting\n\n| Symptom | Cause |\n|---|---|\n| `KeyError: '<name>'` | `_tiny_components()` is missing a component, or keyed it by `model_attr` instead of `name` |\n| `ValueError: [quantize] ... divisible by the quantization group size` | A dimension isn't a multiple of this model's `quantization_group_size` |\n| `assert len(shard_files) > component_count` | Lower `tensors_per_shard` (step 5) |\n| Values differ after reload | A real save/load bug — report it, do not weaken the assertion |\n| Shape assertion inside a component's `__init__`/forward | An interlocking dimension constraint (step 4) |\n\n<!-- File: .cursor/skills/mflux-pr-docs/pr-what-prompt.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Mflux-pr-docs Skill\n\nPath: `.cursor/skills/mflux-pr-docs/pr-what-prompt.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/pr-what-prompt.md)\n\n<!-- File: .cursor/skills/mflux-pr-docs/release-note-prompt.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Mflux-pr-docs Skill\n\nPath: `.cursor/skills/mflux-pr-docs/release-note-prompt.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.cursor/skills/mflux-pr-docs/release-note-prompt.md)\n\n<!-- File: .cursor/skills/mflux-pr-docs/SKILL.md (Tokens: ~1386 | Category: anthropic-skill) -->\n---\nname: mflux-pr-docs\ndescription: Write the PR body for the current mflux branch and show it to the developer for approval. Fills the What section, the release-note block and the Verification section of the PR template. Use when the developer asks to write, fill or update a PR description or a release note.\n---\n\n# mflux PR docs\n\nWrite the PR body for the current branch. The developer must approve the body before it goes to GitHub.\n\n## Inputs\n\n- The current branch. The base branch is `main`.\n- Optional: the PR number, if the PR is open.\n\n## Steps\n\n1. Collect the facts. Use only these sources:\n   - `git log --oneline main..HEAD`\n   - `git diff --stat main...HEAD`\n   - `git diff main...HEAD`\n   - If the PR is open: `gh pr view <n> --json title,body,closingIssuesReferences` and `gh pr checks <n>`.\n2. Copy `.github/pull_request_template.md` to `tmp-PR-content.md`. If `tmp-PR-content.md` exists, ask the developer before you replace it.\n   - Add this heading as the first line: `# Draft PR Content`.\n   - Add the line `Title: ` below the heading. Add an empty line after it.\n   - If the PR is open, put its title from step 1 after `Title: `.\n   - If the PR is open, `gh pr edit --body-file` replaces the existing body. Copy each existing section and link that the template does not have into `tmp-PR-content.md`. Get them from the `body` field of step 1. If you do not copy them, ask the developer to confirm before you discard them.\n3. Write the `What` section. Obey `pr-what-prompt.md` in this folder. Use the diff from step 1 if the PR is not open. Add `Fixes #<n>` for each linked issue.\n   - If the PR is not open, write the PR title after `Title: `. Use one short line that names the change.\n   - If the PR is open, keep its title. Change the title only if the developer asks.\n4. Write the release note. Obey `release-note-prompt.md` in this folder.\n   - Put the note on the lines below the opening fence. Do not put text on the fence line.\n   - Tell the developer which PR label the PR needs.\n5. Write the `Verification` section. List only the commands that ran, with the result of each command. If no command ran, write `TODO: add the commands that you ran.` Do not write a result that you did not see.\n6. Do not tick the boxes in the `Checklist` section. The developer ticks them.\n7. Examine the text that you wrote. Do not examine the template text.\n   - Apply the `asd-ste100` skill in STE-flavored mode.\n   - Put the text that you wrote in a temporary file. Do not put the `Title:` line in it. Run `python3 .cursor/skills/asd-ste100/scripts/ste-lint.py --disable synonym-rotation <file>`.\n   - Fix each hard violation.\n8. Run the CI check on `tmp-PR-content.md`. Fix `tmp-PR-content.md` until the check passes:\n   ```sh\n   python3 - tmp-PR-content.md <<'PY'\n   import re, sys\n   body = open(sys.argv[1], newline=\"\").read()\n   m = re.search(r\"^```release-note[ \\t\\r]*\\n(.*?)^```[ \\t\\r]*$\", body, re.DOTALL | re.IGNORECASE | re.MULTILINE)\n   sys.exit(0 if m and m.group(1).strip() else \"FAIL: no complete release-note block\")\n   PY\n   ```\n9. Ask the developer to approve the PR content:\n   - Open `tmp-PR-content.md` in the editor. Use `code tmp-PR-content.md` or `cursor tmp-PR-content.md`. If neither command works, give the developer the file path.\n   - Tell the developer to edit the file in the editor, or to ask for changes in the chat.\n   - Tell the developer to write `approve` in the chat when the content is ready.\n   - Do not continue until the developer writes `approve`.\n10. Read `tmp-PR-content.md` again after the developer approves it. The developer can edit the file before approval. Do step 8 again.\n    - Make sure that line 1 is `# Draft PR Content` and line 2 is the `Title:` line. Put them back if the developer moved them.\n    - Make sure that the `Title:` line has a title. If it is empty, ask the developer for the title. Write the title after `Title: ` in `tmp-PR-content.md`.\n11. Send the PR content to GitHub:\n    - If the PR is not open, push the branch first. Ask for permission before you push. Obey the `mflux-pr` skill.\n    - Run this block as one command. If the PR is open, replace the last line with `gh pr edit <n> --title \"$title\" --body-file tmp-PR-body.md`.\n      ```sh\n      title=\"$(awk 'NR <= 2 && sub(/^Title: */, \"\") { print; exit }' tmp-PR-content.md)\"\n      awk 'NR == 1 && /^# Draft PR Content$/ { next } NR == 2 && /^Title:/ { next } { print }' tmp-PR-content.md > tmp-PR-body.md\n      gh pr create --title \"$title\" --body-file tmp-PR-body.md\n      ```\n    - The shell reads the title from the file. Do not type the title into the command. Backticks and `$` in a typed title run as shell code.\n    - GitHub does not get the `# Draft PR Content` line or the `Title:` line. Other lines that start with `Title:` stay in the body.\n12. Delete `tmp-PR-content.md` and `tmp-PR-body.md`.\n\n## Rules\n\n- Do not invent facts, numbers or test results.\n- Do not change the code or the commits.\n- Do not use `gh pr create --body` or `--fill`. GitHub must get the body that you checked, without the two draft lines.\n- Keep the regex in step 8 the same as `.github/workflows/release-note.yml` and `_FENCE` in `src/mflux/release/release_notes.py`.\n\n<!-- File: .cursor/skills/mflux-pr/SKILL.md (Tokens: ~850 | Category: anthropic-skill) -->\n---\nname: mflux-pr\ndescription: Make a clean PR in mflux (inspect diff, quick verification, commit, push, open PR) using repo conventions.\n---\n# mflux pull request workflow\n\n## When to Use\n\n- You’re about to open a PR (or want a safe sequence to do it).\n\n## Instructions\n\n- If you run tests as part of PR hygiene, prefer fast tests first:\n  - `just test-fast`\n- Keep commits focused and messages consistent with repo history.\n- If the PR changes CLI defaults, public APIs, or model behavior, check for README/example drift before opening the PR.\n- **Always ask for permission** before pushing to the remote repository.\n- If `gh` isn’t available, fall back to the GitHub web UI (or stop and ask).\n\n## PR body and release note (required)\n\nThe `release-note` CI check fails the PR if the body has no complete release-note block.\n\nUse the `mflux-pr-docs` skill to write the PR body. That skill writes the `What` section and the release-note block, runs the CI check, and gets the approval of the developer.\n\nIf the check fails on an open PR, use the `mflux-pr-docs` skill again. It edits the body of the open PR. The check runs again on an edit. You do not need a new commit.\n\n## Pre-merge checklist (model port PRs)\n\nUse after the core port lands and you are polishing for merge. For the full **integration surfaces** tick list (LoRA key formats, save routing, tokenizer edge cases, etc. learned from past closed PRs), see `mflux-model-porting` → *Integration surfaces checklist*.\n\n### Correctness\n\n1. `just lint` and `just test-fast`\n2. `just ci-extract` after changing `AVAILABLE_MODELS` or `scripts/ci_extract_models.py`\n3. Slow golden tests for the new model:\n   ```sh\n   MFLUX_PRESERVE_TEST_OUTPUT=1 uv run pytest tests/image_generation/test_generate_image_<model>.py -m slow -v\n   ```\n4. Optional but high-signal: diffusers side-by-side + latent injection (`mflux-debugging`, `mflux-manual-testing`)\n\n### Cross-model diff audit\n\nList files changed outside `src/mflux/models/<model>/`:\n\n| Category | Expected |\n|---|---|\n| `pyproject.toml`, `cli/defaults/defaults.py`, `ModelConfig`, `mflux-save` routing | Required wiring |\n| `scripts/ci_extract_models.py` `OVERLAY` / `EXTRA_ENTRIES` | Required CI-manifest wiring for every new model key or standalone tool |\n| `README.md` table + attribution | Required |\n| Training `runner.py`, example JSON, `.gitignore` JSON exceptions | If training supported |\n| Shared VAE/callback/training one-liners | Only if required; document blast radius in PR |\n| Personal `.gitignore`, unrelated formatting | **Remove** |\n\nVerify quantized README disk claims with measurement:\n```sh\ndu -sh ~/.cache/huggingface/hub/models--<org>--<Model>*\nmflux-save --model <alias> --quantize 8 --path /tmp/model-q8 && du -sh /tmp/model-q8\n```\n\n### Docs / examples\n\n- Model README matches a recent port (e.g. Flux2): hero image, turbo + base CLI, feature section, disk warning, Notes, Training.\n- Main `README.md` model table row (correct release date).\n- Showcase asset if other models have one (`src/mflux/assets/`; may need `git add -f` when `*.jpg` is gitignored).\n\n### PR description callouts\n\n- Shared code touched and why (shared VAE, callbacks, training runner, etc.).\n- Reference pipeline features intentionally **not** ported (optional preprocessors, extra encoders, components omitted from mflux weight downloads).\n- Known non-parity with diffusers (RNG, sigma schedule, optional modules) if golden tests lock mflux-native sampling.\n\n<!-- File: .cursor/skills/mflux-release/SKILL.md (Tokens: ~385 | Category: anthropic-skill) -->\n---\nname: mflux-release\ndescription: Prepare a release in mflux (version bump + uv lock; release notes are harvested from PR release-note blocks and live in GitHub Releases). Use when preparing a release branch or release PR.\n---\n# mflux release prep\n\nReleases are prepared in-repo; tagging/publishing is handled by GitHub Actions\n(`release.yml`, dispatched from main with the `publish` confirmation).\n\n## How notes work now (#685)\n\n- Every PR carries a fenced ` ```release-note ` block in its body (CI enforces it;\n  every PR gets a note, and contributors do not write `none`). That block is the only source of release notes.\n- On dispatch, the ungated `draft-notes` job harvests the blocks for every PR whose\n  squash commit is in `previous-tag..HEAD` and fills a DRAFT GitHub release, grouped\n  by label.\n- Whoever approves the `pypi` deployment reads and edits that draft (fixing any\n  `[needs edit]` lines, adding contributor thanks if wanted); the gated job publishes\n  it exactly as edited. A re-dispatch never overwrites an existing draft; delete the\n  draft to re-harvest.\n- There is no `CHANGELOG.md`: the notes live in GitHub Releases (https://github.com/mflux-community/mflux/releases).\n\n## Release-prep PR checklist\n\n- Bump version in `pyproject.toml`\n- Update lockfile: `uv lock`\n- Release-note block of the prep PR itself: a note for contributors, for example `Prepare the <version> release.` Give the PR the `chore` label.\n- Prefer one commit named `release: prepare <version>`\n- Sanity checks (optional unless requested): `just test-fast`, `just build`\n- Do not tag releases locally unless explicitly requested (normally handled by CI)\n\n<!-- File: .cursor/skills/mflux-testing/SKILL.md (Tokens: ~781 | Category: anthropic-skill) -->\n---\nname: mflux-testing\ndescription: Run tests in mflux (fast/slow/full), preserve image outputs, and handle golden image diffs safely.\n---\n# mflux testing\n\nThis repo uses pytest with image-producing tests. Always preserve outputs for inspection and **never** update reference images unless explicitly asked.\n\n## When to Use\n\n- You need to run tests (fast/slow/full) or debug failing tests.\n- There are image/golden mismatches and you need to report paths/output for review.\n\n## Instructions\n\n- Prefer the justfile test recipes:\n  - `just test-fast` (fast tests, no image generation)\n  - `just test-slow` (slow tests, image generation)\n  - `just test` (default selection, skips slow model tests)\n  - `just test-all` (all except high-memory tests; slow tests download model weights)\n- Always keep `MFLUX_PRESERVE_TEST_OUTPUT=1` on test runs (already built into the justfile test recipes).\n- If a change affects defaults, config resolution, metadata fields, or CLI behavior, add or update tests that cover the changed behavior directly instead of relying only on manual verification.\n- If tests fail:\n  - Summarize the failing test names and the key assertion output.\n  - Point to any generated images/artifacts on disk for manual review.\n- Do **not** regenerate/replace reference (“golden”) images unless the user explicitly requests it.\n\n## Updating golden images (new model or hardware refresh)\n\nGolden tests compare generated PNGs to `tests/resources/reference_*.png` (typically 15% mismatch threshold).\n\n**When to update** (only with explicit user approval):\n- After validating the port on target hardware (CI Mac) via slow tests with `MFLUX_PRESERVE_TEST_OUTPUT=1`\n- After choosing a stable prompt/seed/settings via diffusers comparison and/or latent-injection confidence (`mflux-debugging`)\n- When old references used a bad prompt (e.g. ambiguous subject) or wrong seed for mflux’s RNG\n\n**Workflow**:\n1. Run slow test → inspect `tests/resources/output_*.png` vs `reference_*.png`\n2. If output is correct but reference is stale, re-run generation with same test parameters and replace reference PNGs\n3. Commit test + reference images together with a clear message (e.g. `test(<model>): update golden images for local hardware`)\n\n**Important**: Golden tests lock **mflux-native** sampling (`mx.random` + mflux schedulers), not diffusers pixel parity. A good diffusers side-by-side or injected-latent run builds confidence in the model code; the golden still reflects mflux’s full recipe on CI hardware.\n\n## Manual validation (config resolution + local model paths)\n\nUse when a change touches model config resolution, `mflux-save`, or the model’s generate CLI, or when a PR fixes local model-path handling for the model under investigation. Refer to the `mflux-cli` skill to find the correct generate command for the model you are testing.\n\n- Run a local-path quantize/save:\n  - Use the `mflux-cli` skill to look up the correct command and flags.\n  - Verify CLI usage with the command’s `--help` before running it.\n  - Save to a known location (e.g., Desktop) to make follow-up steps explicit.\n- Run generation from the saved model using the correct model-specific generate CLI:\n  - Use the `mflux-cli` skill to find the generate command and required flags.\n  - Verify CLI usage with the command’s `--help` before running it.\n- If the model has multiple size variants, repeat the above for each variant to confirm the correct overrides are applied.\n- Do not commit output artifacts; delete or leave them untracked.\n\n<!-- File: .claude/skills/asd-ste100 (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: asd-ste100\n\nPath: `.claude/skills/asd-ste100`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/asd-ste100)\n\n<!-- File: .claude/skills/mflux-cli (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-cli\n\nPath: `.claude/skills/mflux-cli`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-cli)\n\n<!-- File: .claude/skills/mflux-debugging (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-debugging\n\nPath: `.claude/skills/mflux-debugging`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-debugging)\n\n<!-- File: .claude/skills/mflux-dev-env (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-dev-env\n\nPath: `.claude/skills/mflux-dev-env`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-dev-env)\n\n<!-- File: .claude/skills/mflux-manual-testing (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-manual-testing\n\nPath: `.claude/skills/mflux-manual-testing`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-manual-testing)\n\n<!-- File: .claude/skills/mflux-model-porting (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-model-porting\n\nPath: `.claude/skills/mflux-model-porting`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-porting)\n\n<!-- File: .claude/skills/mflux-model-tiny-test (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-model-tiny-test\n\nPath: `.claude/skills/mflux-model-tiny-test`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-model-tiny-test)\n\n<!-- File: .claude/skills/mflux-pr (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-pr\n\nPath: `.claude/skills/mflux-pr`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr)\n\n<!-- File: .claude/skills/mflux-pr-docs (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-pr-docs\n\nPath: `.claude/skills/mflux-pr-docs`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-pr-docs)\n\n<!-- File: .claude/skills/mflux-release (Tokens: ~300 | Category: claude-rule) -->\n# Claude Directive: mflux-release\n\nPath: `.claude/skills/mflux-release`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/filipstrand/mflux/HEAD/.claude/skills/mflux-release)\n\n<!-- ... +1 more modular skills available via /api/skills/filipstrand/mflux?path={path} -->\n</yakaai_skills>"}