Text-to-Image
Diffusers
Safetensors
English
Chinese
flow-matching
qwen-image
ascend
lora
recursive-self-improvement
Instructions to use DALabCommunity/Haidass-Image-Instruct with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use DALabCommunity/Haidass-Image-Instruct with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("DALabCommunity/Haidass-Image-Base-v1_0.6B_512px", dtype=torch.bfloat16, device_map="cuda") pipe.load_lora_weights("DALabCommunity/Haidass-Image-Instruct") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
Release 0.1.0 (same files as staging-0.1.0 @ 90a07ac4)
Browse filesFiles changed (27)
- .gitattributes+3-36
- DETAILS.mdAdded+328
- DETAILS_zh.mdAdded+328
- README.md+77-235
- README_zh.md+77-235
- SHA256SUMSAdded+27
- assets/gallery.jpg
- config.json+5-2
- counting_head/__init__.pyAdded+1
- counting_head/count_n_rank.pyAdded+46
- counting_head/count_parser.pyAdded+60
- counting_head/count_vocab.pyAdded+46
- dit_norm_precision.safetensors → counting_head/head.npzRenamed+2-2
- counting_head/sampling.pyAdded+80
- dit.safetensors+2-2
- inference.py+358-73
- requirements.txt+2-2
- runtime/add_spelling.py+1-1
- runtime/add_spelling_v2.py-1
- runtime/model.py+5-5
- runtime/npu_attention.py+15-15
- runtime/prompt_routing.pyAdded+423
- runtime/routing.py+8-2
- runtime/sequence.py+21-22
- runtime/spelling.py+3-4
- writing_lora/adapter_config.json+6-6
- writing_lora/adapter_model.safetensors+2-2
1234567891011121314151617181920212223241262728293031323334353637234*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/logo.png filter=lfs diff=lfs merge=lfs -textassets/gallery.jpg filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328# Haidass-Image-Instruct 0.1.0 — Technical Details
[← Back to README](README.md) · **English** · [简体中文](DETAILS_zh.md)
This document holds the full technical details moved out of [README.md](README.md): architecture, complete benchmark tables and footnotes, full ≤1B comparison tables with paper links, evaluation notes and known limitations, component breakdowns, the counting `k` curve, training hyperparameters, agent post-training workflow, full inference commands (including PowerShell and `generate_batch`), runtime and hardware, and gallery/version provenance.
## Gallery note
*48 images in `assets/gallery.jpg` were selected from 150 candidates drawn from the evaluation runs (MJHQ-30K, OneIG-Bench, DPG-Bench, CVTG-2K, the held-out counting set, and PixelGen-rewritten GenEval), generated at 512 × 512 on Ascend NPU (batch size as in each evaluation; lettering uses the writing route, and counting images come from the fixed candidate pools via the counting head). The same seed gives a different image on CUDA or CPU because the initial noise is drawn differently.*
## Architecture
| Component | Specification ||---|---|| Generation backbone | Single-stream diffusion transformer (`PackedSingleStreamDiT`, Qwen-Image-2.1 based), flow matching; 34 layers, 9 heads × 128 dim, ~598M parameters; stored as 315 FP32 tensors (`dit.safetensors`, merged EMA from Flow-GRPO update 240) || Text encoder | [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B), frozen, last-layer hidden states, max 256 tokens, right-padded, EOS token for the unconditional branch || VAE | Qwen-Image-2.1 VAE (64-channel latents), frozen || Writing LoRA | PEFT LoRA (`r = 128`, `alpha = 256`, EMA FP32, covering 238 linear layers across all 34 layers); activates automatically with letter-by-letter spelling annotation when the prompt requests quoted English display text || Counting head | Two-layer MLP (hidden size 64) reading 4 × 4 spatially averaged layer-25 features at step 5 of the 50-step schedule to predict 8 object-count classes (`0–6` and `7+`); activates automatically at 50 steps when the prompt specifies one unambiguous object count || Resolution | 512 × 512 |
Default per-prompt routing follows one fixed priority order: if a prompt requests quoted display text (generally in the same sentence as a carrier or writing word), the writing route runs (writing LoRA + letter-by-letter spelling); otherwise, if the prompt parses to one unambiguous object count at 50 sampling steps, the counting route runs (8 initial noises run 5 of 50 steps and the counting head selects one to finish to step 50); all other prompts run a single 50-step pass on the backbone. When a prompt contains both quoted text and a count, the writing route takes precedence.
## Main results
All 0.1.0 numbers below are measured on the **whole model under default inference** (512 × 512, Euler 50 steps, CFG 8.0, timestep shift 1.0, automatic routing, no LLM prompt rewriting). For backbone-only and component-by-component numbers, see [What each part contributes](#what-each-part-contributes).
| Benchmark | Scale / protocol | Base (`60463`) | **Haidass-Image-Instruct 0.1.0** ||---|---|---:|---:|| **Original GenEval** (seed 42, official)¹ | 0–1 (553 × 4) | 0.600 | **0.859** || **Original GenEval** (seed 43)¹ | 0–1 (553 × 4) | — | **0.869** || **Original GenEval** (2 seed batches)¹ | 0–1 (553 × 8) | — | **0.864** || **PixelGen-rephrased GenEval**² (2 seed batches) | 0–100 (553 × 8) | 67.05 | **86.34** || Held-out composition (8 COCO classes unseen in training)³ | 0–100 (400 × 4) | 59.00 | **87.94** || Held-out counting (8 unseen classes, exact count)³ | % (200 × 4) | — | **67.00%** || **DPG-Bench** | 0–100 (1,065 × 4) | 83.98 | **84.28** || **CVTG-2K** word accuracy / NED / CLIPScore | % / 0–1 / 0–1 (2,000) | 0.22% / 0.212 / — | **45.08%** / **0.716** / **0.760** || **OneIG-Bench (EN)** Alignment | 0–100 (695 × 4) | 80.11 | **81.82** || **OneIG-Bench (EN)** Text | 0–100 (200 × 4) | 0.68 | **34.75** || **OneIG-Bench (EN)** Reasoning | 0–100 (225 × 4) | 19.11 | **19.08** || **OneIG-Bench (EN)** Style | 0–100 (114 × 4) | 39.46 | **40.31** || **OneIG-Bench (EN)** Diversity | 0–100 (1,120 × 4) | 26.56 | **17.60** || **OneIG-Bench (EN)** Overall (5-dim avg) | 0–100 (1,120 × 4) | 33.18 | **38.71** || **MJHQ-30K FID ↓** (Sana protocol)⁴ | FID (30,000) | 13.38 | **10.33** || **MJHQ-30K CLIP** | CLIP (30,000) | 25.35 | **26.10** |
¹ Under default inference, counting prompts use 8-pick candidate selection via the counting head and all other prompts use a single draw.² "PixelGen-rephrased GenEval" refers to PixelGen's rewritten 553 GenEval prompts with the leading `"The image shows "` removed.³ Internal evaluation sets built from 8 COCO classes removed from the v4 supervised retraining data, the Flow-GRPO prompts, and the counting-head training data (not removed from the base model's pre-training data or the writing-LoRA data); not included in this repository.⁴ Evaluated under the Sana protocol (512 × 512, JPEG Q75, `pytorch-fid` 2,048-d Inception features). Base `60463` PixelGen-rephrased GenEval (`67.05`; batch-4: `66.93`) and MJHQ (`13.38` / `25.35`) used sequential single-image generation; Base CVTG-2K (`0.22%`) used prompts without spelling annotation.
## Comparison with ≤1B models
External rows below are limited to models published on or after 2026-05-30. Their numbers are verified against each model's primary paper, technical report, or official release page. Parameter counts list the visual generator backbone only. All external models use single-draw generation without prompt rewriting; our model uses BLIP3o-60K with **7,190 near-duplicates removed** (and two sentence-level cleaning scans with zero hits). Single-draw backbone-only scores for 0.1.0 are reported in [What each part contributes](#what-each-part-contributes).
### Original GenEval (553 prompts, 0–1 scale)
| Model | Date | Params | Resolution | Inference mode | BLIP3o-60K | GenEval ↑ ||---|---|---:|---:|---|---|---:|| [RG-T2I-L/16](https://arxiv.org/html/2610.12978) | 2026-10 | 912M | 512 × 512 | single draw | Yes (120K mix) | 0.89 || [MiniT2I-L/16](https://peppaking8.github.io/minit2i/) | 2026-06 | 912M | 512 × 512 | single draw | Yes (120K mix) | 0.883 || [AMD Nitro-P](https://rocm.blogs.amd.com/artificial-intelligence/nitro-p/README.html) | 2026-11 | 679M | 512 × 512 | single draw | Yes (120K mix) | 0.88 || [UNIFIED-L](https://arxiv.org/html/2611.29064) | 2026-11 | 554M | 256 × 256 | single draw | Yes | 0.878 || [HiT-B/16](https://arxiv.org/html/2611.22962) | 2026-11 | 250M | 512 × 512 | single draw | Yes (120K mix) | 0.878 || [HiRAE-24](https://arxiv.org/html/2609.37775) | 2026-09 | 875M | 256 × 256 | single draw | Yes | 0.877 || [JuZhou 1.0](https://arxiv.org/html/2606.28421) | 2026-06 | 385M | 1024 × 1024 | single draw | No | 0.70 || **Haidass-Image-Instruct 0.1.0 (ours)**¹ | 2026-11 | 0.6B | 512 × 512 | counting prompts 8-pick; others single draw | Yes (7,190 near-dups removed) | **0.859** |
¹ **How counting prompts are generated in 0.1.0:** 8 initial noises each run 5 of the 50 steps; the counting head reads step-5 intermediate features (layer 25, 4 × 4 pooled) and predicts how many objects each candidate would end with (classes `0–6` and `7+`); the candidate most likely to show the requested number continues to step 50. The `0.859` row reports official seed 42 (`0.869` on seed 43; `0.864` across two seed batches). External rows use single-draw generation, so 0.1.0's default-inference row is listed separately at the bottom without a single-draw rank. Among ≤1B single-draw models published since 2026-05-30 without BLIP3o-60K or prompt rewriting, the highest score is JuZhou 1.0 (`0.70`); all 10 ≤1B models published since 2026-05-30 that score `0.85–0.89` (the six highest are listed above) fine-tuned on BLIP3o-60K or the MiniT2I 120K mix.
### DPG-Bench (1,065 prompts, 0–100 scale)
| Model | Date | Params | Resolution | Inference mode | BLIP3o-60K | DPG-Bench ↑ ||---|---|---:|---:|---|---|---:|| [RG-T2I-L/16](https://arxiv.org/html/2610.12978) | 2026-10 | 912M | 512 × 512 | single draw | Yes (120K mix) | 87.1 || [Looped-DiT B/16](https://arxiv.org/html/2609.40305) | 2026-09 | 260M | 512 × 512 | single draw | Yes (120K mix) | 87.0 || [HiRAE-24](https://arxiv.org/html/2609.37775) | 2026-09 | 875M | 256 × 256 | single draw | Yes | 86.35 || [AMD Nitro-P](https://rocm.blogs.amd.com/artificial-intelligence/nitro-p/README.html) | 2026-11 | 679M | 512 × 512 | single draw | Yes (120K mix) | 86.33 || [MiniT2I-L/16](https://peppaking8.github.io/minit2i/) | 2026-06 | 912M | 512 × 512 | single draw | Yes (120K mix) | 85.9 || [HiT-B/16](https://arxiv.org/html/2611.22962) | 2026-11 | 250M | 512 × 512 | single draw | Yes (120K mix) | 85.33 || [UNIFIED-L](https://arxiv.org/html/2611.29064) | 2026-11 | 554M | 256 × 256 | single draw | Yes | 84.8 || [NanoGen (FLUX.2-VAE)](https://arxiv.org/html/2606.24888) | 2026-06 | 612M | 256 × 256 | single draw | No | 84.1 || **Haidass-Image-Instruct 0.1.0 (ours)** | 2026-11 | 0.6B | 512 × 512 | default routing (counting 8-pick; writing / backbone single draw) | Yes (7,190 near-dups removed) | **84.28** |
### OneIG-Bench (EN, 0–1 scale), MJHQ-30K FID (Sana protocol), and CVTG-2K
| Benchmark & Model | Date | Params | Resolution | Inference mode | BLIP3o-60K | Score ||---|---|---:|---:|---|---|---:|| **OneIG (EN) Overall ↑** — [AnisoFlow-L/16 + DWD](https://arxiv.org/html/2611.22287) | 2026-11 | 940M | 1024 × 1024 | single draw | No | 0.533 || **OneIG (EN) Overall ↑** — [AnisoFlow-L/16](https://arxiv.org/html/2611.17767) | 2026-11 | 918M | 1024 × 1024 | single draw | No | 0.528 || **OneIG (EN) Overall ↑** — [JiT-L/16-T2I](https://arxiv.org/html/2611.17767) | 2026-11 | 917M | 512 × 512 | single draw | No | 0.512 || **OneIG (EN) Overall ↑** — **Haidass-Image-Instruct 0.1.0 (ours)** | 2026-11 | 0.6B | 512 × 512 | default routing | Yes (7,190 near-dups removed) | **0.387** || **MJHQ-30K FID ↓** — **Haidass-Image-Instruct 0.1.0 (ours)** | 2026-11 | 0.6B | 512 × 512 | default routing | Yes (7,190 near-dups removed) | **10.33** || **CVTG-2K (WA / NED / CLIP) ↑** — **Haidass-Image-Instruct 0.1.0 (ours)** | 2026-11 | 0.6B | 512 × 512 | writing route (single draw) | Yes (7,190 near-dups removed) | **45.08% / 0.716 / 0.760** |
Additional references (>1B models): on OneIG-Bench (EN), [SeFi-Image-1B](https://arxiv.org/html/2606.22568) (2026-06, ~1.18B, 1024 × 1024, single draw, BLIP3o-60K unspecified) scores `0.525` overall (`0.859 / 0.884 / 0.271 / 0.398 / 0.212`). On CVTG-2K, no other ≤1B model reports scores; [SeFi-Image-1B](https://arxiv.org/html/2606.22568) reports `71.8%` word accuracy, `0.862` NED, and `0.810` CLIPScore. On the PixelGen rewritten GenEval prompts, only [Halcyon](https://arxiv.org/html/2610.26863) (2026-10, 256 × 256, pre-trained only, single draw, no BLIP3o-60K) reports numbers (`Halcyon-0.52B` 0.52B: `44.91`; `Halcyon-4.00B + I2T 10%` 4.00B: `55.33`; `JiT-T2I-XXL/16++` 1.11B: `41.79`).
## Evaluation notes
- **Data cleaning and 0.0.1 retirement.** Version 0.0.1's training data overlapped evaluation prompts; 0.1.0 retrains from base `60463` on sentence-level cleaned data (v4, two independent scans with zero hits, and all 8 held-out COCO classes removed). Version 0.0.1 remains archived at git tag `v0.0.1` and its scores are retired.- **Overlap control (`v5-A`).** Removing a further 35,949 images (12.4%) from the v4 pool whose object combination matches an evaluation prompt (same unordered object set, same structure, or left/right swapped) and retraining from base — while keeping per-source sampling totals fixed, so the remaining counting images were drawn 33 times on average versus 21.7 in v4 — yields no statistically significant difference on PixelGen-rephrased GenEval total (`82.79` vs `83.17`, `−0.38`, 95% CI `[−1.56, +0.79]`) or held-out composition (8 unseen classes, `−1.00`), while the PixelGen-rephrased GenEval position sub-score is `3.13` points lower (`[−6.00, −0.25]`). The `−3.13` position result reflects removing the overlapping images together with the changed per-source sampling (33 vs 21.7 draws per counting image); the two cannot be separated in `v5-A`.- **Checkpoint selection.** Among 11 CFG1 EMA RL candidates with completed two-batch PixelGen-rephrased GenEval and held-out composition evaluations, the pre-registered rule dropped any candidate with held-out composition significantly below v4 (zero dropped) and chose the highest two-batch PixelGen-rephrased GenEval: update `240` (`85.73`; updates `280`, `320`, and `334` scored `85.68`, `85.50`, and `85.54`).- **Shared detector and blind visual check.** Flow-GRPO training reward and the GenEval-family benchmarks use the same `Mask2Former` + `CLIP ViT-L/14` detector. In a blind visual review of 60 proportionally sampled flipped image pairs on PixelGen-rephrased GenEval standard seeds (update 240 vs v4), true improvements (~11 images extrapolated) and regressions (~14 images) roughly balanced out, while on the update-240 backbone vs v4, benchmarks with independent scorers — DPG-Bench (`+1.07`), OneIG Alignment (`+0.54`), OneIG Reasoning (`+0.39`), MJHQ-30K FID (`−0.19`), and MJHQ-30K CLIP (`+0.08`) — improved significantly.- **Benchmark definitions and protocols.** "PixelGen-rephrased GenEval" refers to `evaluations/geneval/evaluation_metadata_rephrased.jsonl` from [PixelGen](https://arxiv.org/abs/2602.02493) with `"The image shows "` stripped from each prompt. MJHQ-30K FID uses the Sana protocol (512 × 512, JPEG Q75) and is compared only with our own stages. CVTG-2K reports word accuracy, NED, and CLIPScore (VQAScore and Aesthetic Score are omitted). Held-out composition (400 prompts × 4 images), held-out counting (200 prompts × 4 images), and other internal sets are not released with this repository.- **Cross-seed diversity.** OneIG-Bench (EN) Diversity moves from `26.56` (base `60463`) to `17.74` (v4) to `17.60` (0.1.0; backbone-only update 240 is `17.21`). Post-training makes outputs for the same prompt more consistent across seeds.
### Known limitations
- **English text only and carrier-word routing rule.** Writing supports English text. For general carriers and writing cues (`sign`, `poster`, `reads`, `says`, `labeled`, `cover`, etc.), quoted text must sit in the same sentence as the carrier word (Chinese corner quotes, colon-introduced text, and certain print-design carriers use separate rules): - *Triggers writing route:* `A teal enamel sign reading "OPEN LATE" in a rainy shop window` - *Does not trigger writing route (carrier word in a different sentence):* `A minimalist book cover on a wooden table. Display "MIDNIGHT GARDEN" across the center.` - Unquoted document/title-page prompts also do not trigger the writing route (in OneIG-Bench EN Text, 11 of 200 prompts did not trigger, accounting for 25.9% of target words; routed 189 prompts scored `21.45%` word accuracy vs `0.06%` on the 11 unrouted prompts).- **Digits, punctuation, and complex scenes with text.** On CVTG-2K, word accuracy is `7.69%` for words with digits or punctuation (1,730 words) vs `49.59%` for letters-only words (14,476 words). Because 82% of writing LoRA training data uses flat synthetic layouts, prioritizing clear lettering on quoted-text prompts in complex multi-object scenes can shrink the main subject: on 0.1.0, the whole model scores `84.28` on DPG-Bench, `0.31` lower than the same-batch backbone (`84.58`, `−0.31`, 95% CI `[−0.59, −0.02]`), mainly because the 70 quoted-text DPG prompts take the writing route (another 35 take the counting route) (at RL update 80, those 70 routed prompts gained `+22.00` on `other - text` with `−5.61` on `entity - whole`, shifting overall DPG by `−0.25`). Pass `--writing-lora off` when scene composition matters more than embedded text.- **Counting head scope.** The counting head predicts classes `0–6` and `7+` and runs at 50 sampling steps (other step counts fall back to a single draw). Its gain on long descriptive prompts (~132 words, PixelGen-rephrased GenEval counting, 80 prompts) is `+3.13` pp vs single draw (`95% CI [−1.82, +8.07]`, not statistically significant). When the parser extracts the wrong target count `N`, the head selects for that wrong count (`−37.50` pp vs single draw on 2 misparsed prompts).- **Route priority and cross-device seeds.** When a prompt contains both quoted display text and a parsed count, the writing route wins. Ascend NPU, CUDA, and CPU use different initial-noise generators, so the same seed produces different images across hardware backends.
## What each part contributes
The tables below isolate (1) the formal backbone-only post-training stages, (2) what default routing (writing LoRA + counting head) adds on top of the update-240 backbone, and (3) the counting-head `k = 1 / 4 / 8 / 16` candidate curve (all EMA weights, 512 × 512, Euler 50 steps, CFG 8.0).
### Backbone-only formal scores (batch 4, single draw, no writing LoRA, no counting head)
| Benchmark | Base (`60463`) | v4 cleaned SFT | **0.1.0 Backbone (RL update 240)** | Paired Δ vs v4 [95% CI] ||---|---:|---:|---:|---:|| PixelGen-rephrased GenEval (2 batches, 0–100) | 67.05 | 83.17 | **85.73** | +2.55 [+1.65, +3.46] || Held-out composition (8 unseen classes, 0–100) | 59.00 | 81.56 | **83.56** | +2.00 [+0.90, +3.10] || Original GenEval, seed 42 (0–1) | 0.600 | 0.797 | **0.834** | +0.037 [+0.025, +0.050] || Original GenEval, seed 43 (0–1) | — | 0.804 | **0.848** | +0.044 [+0.032, +0.057] || Original GenEval, 2 batches (0–1) | — | 0.800 | **0.841** | +0.041 [+0.031, +0.051] || Held-out counting (exact-N, %) | — | 46.50% | **52.00%** | +5.50 [+2.63, +8.37] || DPG-Bench (0–100) | 83.98 | 83.53 | **84.60** | +1.07 [+0.68, +1.46] || OneIG (EN) Alignment / Reasoning (0–100) | 80.11 / 19.11 | 81.27 / 18.69 | **81.82 / 19.08** | +0.54 / +0.39 || OneIG (EN) Style / Diversity / Text (0–100) | 39.46 / 26.56 / 0.68 | 40.60 / 17.74 / 0.32 | **40.33 / 17.21 / 0.42** | −0.27 / −0.53 / +0.10 || OneIG (EN) Overall (0–100) | 33.18 | 31.73 | **31.77** | +0.04 [−0.16, +0.26] || MJHQ-30K FID ↓ / CLIP (Sana protocol) | 13.38 / 25.35 | 10.53 / 26.02 | **10.33 / 26.10** | −0.19 / +0.08 || CVTG-2K WA / NED / CLIPScore | 0.22% / 0.212 / — | 0.22% / 0.234 / 0.657 | **0.19% / 0.234 / 0.665** | — |
On PixelGen-rephrased GenEval sub-tasks (v4 → update 240): single object `99.69 → 100.00`, two object `94.07 → 95.08`, counting `59.38 → 63.59` (`+4.22`), colors `92.02 → 94.68` (`+2.66`), position `77.13 → 79.50` (`+2.38`), and color attribution `76.75 → 81.50` (`+4.75`).
### Whole model vs. same-batch backbone (isolating writing LoRA + counting head)
To isolate what the writing LoRA and counting head add without confounding generation batch size, routed prompts were generated one image at a time (`batch_size = 1`) for both the whole model and the same-batch backbone control, while all unrouted prompts reuse the formal `batch_size = 4` images and scores (zero paired difference on unrouted prompts):
| Benchmark | Routed prompts (count / write) | Same-batch backbone | **Whole model (0.1.0)** | Whole − Same-batch [95% CI] ||---|---|---:|---:|---:|| PixelGen-rephrased GenEval (2 batches, 0–100) | 82 / 5 per batch | 85.79 | **86.34** | +0.54 [−0.28, +1.37] || Original GenEval, seed 42 (0–1) | 73 / 0 | 0.838 | **0.859** | +0.021 [+0.011, +0.030] || Original GenEval, seed 43 (0–1) | 73 / 0 | 0.849 | **0.869** | +0.020 [+0.011, +0.030] || Original GenEval, 2 batches (0–1) | 73 / 0 per batch | 0.843 | **0.864** | +0.021 [+0.013, +0.029] || Held-out composition (8 unseen classes, 0–100) | 100 / 0 | 83.50 | **87.94** | +4.44 [+3.04, +5.83] || Held-out counting (exact-N, %) | 200 / 0 | 52.38% | **67.00%** | +14.63 [+10.47, +18.78] || DPG-Bench (0–100) | 35 / 70 | 84.58 | **84.28** | −0.31 [−0.59, −0.02] || OneIG (EN) Alignment (0–100) | 15 / 4 (of 695) | 81.80 | **81.82** | +0.02 [−0.03, +0.06] || OneIG (EN) Text (0–100) | 0 / 189 (of 200) | 0.50 | **34.75** | +34.25 [+17.13, +45.34] || OneIG (EN) Reasoning (0–100) | 0 / 0 (of 225) | 19.08 | **19.08** | 0.00 [0.00, 0.00] || OneIG (EN) Style (0–100) | subset of 1 / 3 (of 114) | 40.32 | **40.31** | −0.02 [−0.04, +0.01] || OneIG (EN) Diversity (0–100) | 15 / 193 (of 1,120) | 17.21 | **17.60** | +0.39 [+0.17, +0.61] || OneIG (EN) Overall (0–100) | 15 / 193 (of 1,120) | 31.78 | **38.71** | +6.93 [+3.52, +9.14] || MJHQ-30K FID ↓ (Sana protocol) | 185 / 0 | 10.335 | **10.335** | −0.001 [−0.008, +0.008] || MJHQ-30K CLIP | 185 / 0 | 26.102 | **26.102** | +0.000 [−0.002, +0.002] || CVTG-2K word accuracy (%) | 0 / 2,000 | 0.22% | **45.08%** | +44.87 [+43.43, +46.35] || CVTG-2K NED | 0 / 2,000 | 0.234 | **0.716** | +0.482 [+0.472, +0.492] || CVTG-2K CLIPScore | 0 / 2,000 | 0.664 | **0.760** | +0.096 [+0.091, +0.102] || CVTG-2K exact image match (%) | 0 / 2,000 | 0.00% | **16.60%** | +16.60 [+15.00, +18.25] |
In the standalone batch-4 writing LoRA evaluation on the same update-240 backbone (`45.11%` overall word accuracy on CVTG-2K; `35.30` on OneIG EN Text), word accuracy by region count is `54.55%` / `50.48%` / `47.44%` / `33.30%` for 2 / 3 / 4 / 5 text regions, and unseen words score `46.45%` vs `50.16%` for seen words (measured at RL update 80).
### Counting head `k = 1 / 4 / 8 / 16` curve (paired on update-240 backbone)
On held-out counting (200 short prompts on 8 unseen classes, shared 16-candidate seed pool; single-draw accuracy in this batch-1 pool is `52.38%`, compared with `52.00%` in the formal batch-4 backbone run above — `+0.38` pp, 95% CI `[−0.69, +1.44]`, using the same 800 seeds and differing only by batch-1 vs batch-4 generation; times below are medians stitched from the shared 16-candidate curve run, `7.99 s` at `k = 8` vs. `7.97 s` in the dedicated `k = 8` run in [Runtime and hardware](#runtime-and-hardware)):
| Candidates (`k`) | Counting head accuracy | Random `k`-pick | Head − Random [95% CI] | Median NPU time (s/img) ||---:|---:|---:|---:|---:|| 1 (single draw) | 52.38% | 52.38% | +0.00 | 5.91 || 4 | 64.50% | 49.62% | +14.88 [+11.13, +18.62] | 6.86 || **8 (default)** | **67.00%** | 52.62% | **+14.37 [+10.36, +18.39]** | **7.99** || 16 | 67.38% | 51.00% | +16.38 [+11.97, +20.78] | 10.25 |
Default `k = 8` gains `+14.63` pp over single draw (`[+10.47, +18.78]`); `k = 16` adds `0.38` pp for ~28% more runtime. On Original GenEval (73/80 triggered counting prompts), the standalone counting-head check (against the formal batch-4 backbone) lifted the counting sub-score from `59.06%` to `72.81%` (`+13.75` pp) on seed 42 and from `64.69%` to `77.19%` (`+12.50` pp) on seed 43, lifting overall scores by `+2.29` pp (`0.834 → 0.857`, `+0.023`) and `+2.08` pp (`0.848 → 0.869`, `+0.021`) — one-sixth of each counting gain (in the all-batch-1 whole-model table above, whole − same-batch backbone is `+2.08` / `+2.03` / `+2.06` pp across seed 42 / seed 43 / two batches). On 15 falsely triggered non-counting PixelGen-rephrased GenEval prompts, accuracy is `92.50%` vs `91.67%` single draw (`+0.83` pp, `[−0.80, +2.47]`).
## Training
All stages ran on Huawei Ascend 910B NPUs starting from `Haidass-Image-Base-v1_0.6B_512px` (`60463`):
| Stage | Data | Key hyperparameters ||---|---|---|| 1. Cleaned retrain (`v4`) | 289,726 rows (two cleaning scans, zero eval hits; 8 held-out classes removed; BLIP3o-60K with 7,190 near-duplicates removed); mix 70% public & compositional / 15% counting / 15% position & color binding | 16 NPUs, global batch 1,024, 2,500 steps; peak LR `5e-5`, 100-step warmup, cosine decay to 10%, weight decay `0.01`, EMA `0.998`; timesteps 90% logit-normal (mean `ln 2`) + 10% uniform; fixed caption-dropout hashing || 2. Flow-GRPO RL (`CFG1` update 240) | 3,600-prompt bank across 6 GenEval skills (zero exact prompt-attribute combination overlap with PixelGen-rephrased GenEval; a later check found 231 RL prompts share object-class pairs with 59 evaluation prompts, and with those 59 removed, update 80 was still `+1.99` overall and `+3.62` on position; 8 held-out classes excluded); Mask2Former + CLIP ViT-L/14 partial-credit reward | Started from `v4` EMA; Flow-Factory GRPO + CPS (10 steps, noise `0.8`, backprop 3 of first 5 steps); 1 update/epoch, 32 groups × 18 = 576 images/update (8 NPUs); rollout CFG `1.0`; AdamW LR `3e-4`, WD `1e-4`, grad clip `1.0`, ratio clip `±1e-4`, adv clip `±5`, v-based KL `0.001`; LoRA `r = 32 / alpha = 64` (FP32 LoRA/AdamW/EMA, BF16 forward), EMA `0.99` every 4 epochs; stopped at 334, merged EMA at update `240` || 3. Writing LoRA v4 | 6 OCR block-filtered sources (line-merged then block-grouped, 200-image blind visual pass per source; 82% flat synthetic layouts) with letter-by-letter spelling captions | Frozen backbone (trained from RL update 80, verified on update 240); PEFT `r = 128`, `alpha = 256`, LR `3e-4`, 4,500 steps cosine, EMA weights; LR and data mix tuned once on CVTG-2K after an initial `1e-4` run || 4. Counting head | 25,448 images (~58 classes, 3 prompt styles, 7-way dedup zero hits, 8 held-out classes excluded); count labels from Qwen2.5-VL (99% agreement on blind visual check) | Step-5, layer-25 4 × 4 pooled features; 2-layer MLP (hidden `64`, L2 `α = 1e-3`, Adam, batch `128`, LR `0.001`, max_iter `60`), float64 scoring with deterministic seed-based tie-breaking |
## How post-training was run by agents
The 0.1.0 post-training pipeline (`v4` cleaned retrain → Flow-GRPO → writing LoRA v4 → counting head) was planned, executed, and audited by a manager agent and executor agents running on 8 Atlas A2 servers (64 × Ascend 910B NPUs). Each stage used pre-registered pass/fail thresholds with paired 95% confidence intervals, an Experience Board recording both successful and discarded runs, an independent automated review of briefs and results, and blind visual checks with a multimodal vision-language model on training data samples and flipped evaluation pairs.
Key empirical findings along the 0.1.0 path: (1) sentence-level cleaning paired with fixed warmup/cosine/weight-decay/EMA training lifted base PixelGen-rephrased GenEval from `67.05` to `83.17` and held-out composition from `59.00` to `81.56`; (2) switching Flow-GRPO to 1 optimizer update per epoch with FP32 LoRA/EMA states resolved policy-ratio clipping bias and yielded steady gains to update 240 (`85.73` PixelGen-rephrased GenEval, `84.60` DPG); (3) block-level OCR filtering with letter-spelled prompts lifted CVTG-2K word accuracy from `0.22%` to `45.08%`; and (4) training the counting head to predict exact object count classes (`0–6`, `7+`) rather than binary pass/fail raised held-out counting from `52.38%` to `67.00%`.
## Inference
Default inference runs the whole 0.1.0 model automatically per prompt:1. **Writing route** (quoted display text, generally with a same-sentence carrier word): activates `writing_lora/`, appends letter-by-letter spelling (e.g., `"OPEN LATE" (spelled: O P E N / L A T E)`), and runs 50 Euler steps. Prompts exceeding 256 tokens after spelling annotation emit a warning and record `truncated: true`.2. **Counting route** (one unambiguous parsed object count at 50 steps, when the writing route does not fire): runs 8 initial noises for 5 of the 50 steps; `counting_head/head.npz` reads step-5 intermediate features (layer 25, 4 × 4 pooled) and predicts how many objects each candidate would end with (classes `0–6` and `7+`); the candidate with the highest `log P(count = N)` continues to step 50. Non-50 step counts emit a notice and fall back to a single draw.3. **Backbone route** (all other prompts): runs 1 initial noise for 50 Euler steps on the backbone.
### Default sampling settings and repository layout
| Setting | Default | Repository file | Purpose ||---|---|---|---|| Resolution | 512 × 512 | `dit.safetensors` | Generation backbone weights (FP32, merged EMA) || Sampler & steps | Euler, 50 steps | `writing_lora/` | Writing LoRA weights (EMA FP32) and PEFT config || Guidance (CFG) | 8.0 (`cfg_norm = none`) | `counting_head/` | Counting head weights (`head.npz`) and parser/ranker || Timestep shift | 1.0 | `vae/` | Qwen-Image-2.1 VAE weights and config || Unconditional prompt | EOS token | `config.json`, `runtime/` | Model, sampling, and routing configuration and code || Precision | BF16 autocast; FP32 latents | `inference.py`, `requirements.txt`, `SHA256SUMS` | CLI / Python entry point, dependencies, and checksums |
Repository download size: **4.15 GB** (3.86 GiB: DiT `2.39 GB`, VAE `1.35 GB`, writing LoRA `401 MB`, counting head `5.02 MB`). Text encoder [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) downloads about **1.52 GB** (1.41 GiB) automatically on first use, or can be supplied locally via `--text-encoder` (see [Offline use](#offline-use)).
### Installation and commands
Download this repository (private access requires a Hugging Face token with read permission), open the model directory containing `inference.py` in an activated Python 3.11+ virtual environment, and install dependencies (`--device auto` checks CUDA, Ascend NPU, then CPU, or specify `cpu`, `cuda[:N]`, `npu[:N]`; Ascend requires compatible `torch_npu` and CANN; MPS is untested, so Mac users can select `cpu`):
```bashpython -m pip install -r requirements.txt```
Run the commands below from the downloaded model directory. Default inference uses `--device auto` and downloads `Qwen/Qwen3-0.6B` automatically on first run. Single-image mode writes (overwrites) the given `--output` PNG path and its matching sidecar JSON (default: `output.png` and `output.json`). Batch `--cases` mode reads a JSON array of objects with `id`, `caption`, and `seed` (plus optional 8-int `candidate_seeds` starting with `seed`, range `0..2,147,483,647`), writes `<output>/<id>/image.png` and `image.json` (default directory: `outputs`), and skips existing images when re-run on the same output directory — only `--cases` skips existing outputs.
Save a 2-row `cases.json` in the model directory for the `--cases` and ablation commands below:
```json[ {"id": "sign", "caption": "A teal enamel sign reading 'OPEN LATE' in a rainy shop window", "seed": 42}, {"id": "apples", "caption": "A photo of four red apples on a wooden table", "seed": 42}]```
#### Bash
```bash# Default whole-model inference (ordinary, writing, and counting routes)python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --seed 42 --output bridge.pngpython inference.py "A teal enamel sign reading 'OPEN LATE' in a rainy shop window" --device auto --seed 42 --output sign.pngpython inference.py "A photo of four red apples on a wooden table" --device auto --seed 42 --output apples.png
# Batch mode with --cases (re-running the same command resumes and skips finished images)python inference.py --device auto --cases cases.json --output ./outputspython inference.py --device auto --cases cases.json --output ./outputs
# Disable individual routespython inference.py --device auto --cases cases.json --count-head off --output ./out-count-offpython inference.py --device auto --cases cases.json --writing-lora off --output ./out-writing-offpython inference.py --device auto --cases cases.json --routing none --output ./out-routing-none```
#### PowerShell
```powershell# Default whole-model inference (ordinary, writing, and counting routes)python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --seed 42 --output bridge.pngpython inference.py "A teal enamel sign reading 'OPEN LATE' in a rainy shop window" --device auto --seed 42 --output sign.pngpython inference.py "A photo of four red apples on a wooden table" --device auto --seed 42 --output apples.png
# Batch mode with --cases (re-running the same command resumes and skips finished images)python inference.py --device auto --cases cases.json --output .\outputspython inference.py --device auto --cases cases.json --output .\outputs
# Disable individual routespython inference.py --device auto --cases cases.json --count-head off --output .\out-count-offpython inference.py --device auto --cases cases.json --writing-lora off --output .\out-writing-offpython inference.py --device auto --cases cases.json --routing none --output .\out-routing-none```
#### Python API
`generate` returns `(PIL.Image, dict)`; `generate_batch` returns a list of PIL images by default, or `(PIL.Image, dict)` tuples when `return_records=True`:
```pythonfrom inference import Generator
model = Generator(device="auto") # downloads Qwen/Qwen3-0.6B on first usewriting_image, writing_info = model.generate( 'A teal enamel sign reading "OPEN LATE" in a rainy shop window', seed=42,)writing_image.save("sign.png")
outputs = model.generate_batch( [ "A sunlit stone bridge over a calm mountain river", "A photo of four red apples on a wooden table", ], [42, 43], return_records=True,)for name, (image, info) in zip(["bridge.png", "apples.png"], outputs): image.save(name)```
#### Offline use
Download this repository and `Qwen/Qwen3-0.6B` beforehand, set `HF_HUB_OFFLINE=1` (or point `HF_HOME` to a pre-populated Hugging Face cache), and pass `--text-encoder` pointing to the local `Qwen3-0.6B` directory (or `Generator(device="auto", text_encoder="<local dir>")` in Python):
```bashexport HF_HUB_OFFLINE=1python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --text-encoder /path/to/Qwen3-0.6B --seed 42 --output bridge.png```
```powershell$env:HF_HUB_OFFLINE = '1'python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --text-encoder .\Qwen3-0.6B --seed 42 --output bridge.png```
### Runtime and hardware
Per-image Ascend 910B NPU times below are medians from dedicated batch-1 runs on a single NPU (including text encoding, denoising, and VAE decoding; the `7.97 s` counting time is from the dedicated `k = 8` run, while the `k = 1 / 4 / 8 / 16` curve above reports `7.99 s` from its stitched 16-candidate run; the first writing image in a process also includes a one-time LoRA load of about 4–5 s):
| Route | Ascend 910B NPU (median / image) ||---|---:|| Backbone (1 × 50 steps) | 5.91 s || Writing (LoRA + 1 × 50 steps) | 9.06 s || Counting (8 × 5 steps + 1 × 45 steps) | 7.97 s |
CPU and CUDA run the same code; their speed was not measured. Because Ascend NPU, CUDA, and CPU use different initial-noise generators, the same `--seed` produces different images across devices.
## Version history (full notes)
- **0.1.0 (2026-11):** Final release. Retrained from `Haidass-Image-Base-v1_0.6B_512px` on sentence-level cleaned data (v4, two scans with zero evaluation hits), followed by Flow-GRPO reinforcement learning (CFG1 branch, update 240, merged EMA, selected by pre-registered rule), integrated with writing LoRA v4 (EMA) and the counting head under unified default routing. Weights are stored in FP32 (`dit.safetensors`).- **0.0.1 (preview, git tag `v0.0.1`):** Initial preview release (earlier post-trained raw weights trained on uncleaned data + writing LoRA v3). Archived at tag `v0.0.1`; its training data overlapped evaluation prompts, and its scores are retired in favor of 0.1.0.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328# Haidass-Image-Instruct 0.1.0 — 完整技术细节
[← 返回 README](README_zh.md) · [English](DETAILS.md) · **简体中文**
本文件收录从 [README_zh.md](README_zh.md) 移出的全部技术细节:模型架构、完整主评测表与脚注、含论文链接的完整 ≤1B 模型对比表、评测说明与已知局限、各部分贡献、计数小头 `k` 曲线、训练超参数、智能体自主后训练流程、完整推理命令(含 PowerShell 与 `generate_batch`)、耗时与硬件,以及画廊与版本详细说明。
## 画廊说明
*`assets/gallery.jpg` 中的 48 张图片从评测运行(MJHQ-30K、OneIG-Bench、DPG-Bench、CVTG-2K、留出计数集及 PixelGen 改写版 GenEval)中抽取 150 张候选并选出,均在昇腾 NPU 上以 512 × 512 生成(采用各评测对应的批大小;文字类走写字路径,计数图来自固定候选池并由计数小头选出)。由于初始噪声采样方式不同,同一种子在 CUDA 或 CPU 上会生成不同的图像。*
## 模型架构
| 组件 | 规格 ||---|---|| 生成主干 | 基于 Qwen-Image-2.1 的单流扩散 Transformer(`PackedSingleStreamDiT`),flow matching 训练;34 层,9 个注意力头 × 128 维,约 598M 参数;以 315 个 FP32 张量存储(`dit.safetensors`,Flow-GRPO 第 240 次合并 EMA) || 文本编码器 | [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B),冻结,取最后一层隐藏状态,最长 256 token,右填充,无条件分支使用 EOS token || VAE | Qwen-Image-2.1 VAE(64 通道潜变量),冻结 || 写字 LoRA | PEFT LoRA(`r = 128`,`alpha = 256`,EMA FP32,覆盖全部 34 层共 238 个线性层);提示包含带引号英文渲染文字时自动激活,并追加逐字母拼写标注 || 计数小头 | 两层 MLP(隐藏维度 64),在 50 步采样的第 5 步读取第 25 层 4 × 4 空间平均特征,预测 8 个数量类别(`0–6` 和 `7+`);50 步采样且提示包含单一明确物体数量时自动激活 || 分辨率 | 512 × 512 |
默认推理按固定优先级逐条路由:若提示要求渲染带引号文字(一般需与载体或写字线索词位于同一句),走写字路径(写字 LoRA + 逐字母拼写标注);否则若在 50 步采样下解析出单一明确物体数量,走计数路径(8 个初始噪声各跑 50 步中的前 5 步,计数小头选出 1 个续跑到第 50 步);其余提示在主干上直接单次跑完 50 步。当提示同时包含引号文字和数量时,优先走写字路径。
## 主评测结果
以下 0.1.0 分数全部在**完整模型默认推理**下测得(512 × 512,Euler 50 步,CFG 8.0,时间步偏移 1.0,自动路由,不使用大模型改写提示)。纯主干和各组件拆分成绩见[各部分贡献](#各部分贡献)。
| 评测 | 刻度 / 协议 | 底模(`60463`) | **Haidass-Image-Instruct 0.1.0** ||---|---|---:|---:|| **原版 GenEval**(种子 42,官方默认)¹ | 0–1(553 × 4) | 0.600 | **0.859** || **原版 GenEval**(种子 43)¹ | 0–1(553 × 4) | — | **0.869** || **原版 GenEval**(两批种子)¹ | 0–1(553 × 8) | — | **0.864** || **PixelGen 改写版 GenEval**²(两批种子) | 0–100(553 × 8) | 67.05 | **86.34** || 留出组合题(训练未见的 8 个 COCO 类别)³ | 0–100(400 × 4) | 59.00 | **87.94** || 留出计数题(8 个未见类别,恰好画对数量)³ | %(200 × 4) | — | **67.00%** || **DPG-Bench** | 0–100(1,065 × 4) | 83.98 | **84.28** || **CVTG-2K** 词准确率 / NED / CLIPScore | % / 0–1 / 0–1(2,000) | 0.22% / 0.212 / — | **45.08%** / **0.716** / **0.760** || **OneIG-Bench(英文)** 对齐 | 0–100(695 × 4) | 80.11 | **81.82** || **OneIG-Bench(英文)** 文字 | 0–100(200 × 4) | 0.68 | **34.75** || **OneIG-Bench(英文)** 推理 | 0–100(225 × 4) | 19.11 | **19.08** || **OneIG-Bench(英文)** 风格 | 0–100(114 × 4) | 39.46 | **40.31** || **OneIG-Bench(英文)** 多样性 | 0–100(1,120 × 4) | 26.56 | **17.60** || **OneIG-Bench(英文)** 五项平均 | 0–100(1,120 × 4) | 33.18 | **38.71** || **MJHQ-30K FID ↓**(Sana 协议)⁴ | FID(30,000) | 13.38 | **10.33** || **MJHQ-30K CLIP** | CLIP(30,000) | 25.35 | **26.10** |
¹ 默认推理下,计数题由计数小头执行 8 选 1,其余题目为单张生成。² 「PixelGen 改写版 GenEval」指 PixelGen 改写过的 553 道 GenEval 题目,每条提示去掉了开头的 `"The image shows "`。³ 内部评测集,使用从 v4 监督重训数据、Flow-GRPO 题库与计数小头训练数据中剔除的 8 个 COCO 类别(未从底模预训练数据或写字 LoRA 数据中剔除);未随本仓库发布。⁴ 采用 Sana 协议计算(512 × 512,JPEG Q75,`pytorch-fid` 2,048 维 Inception 特征)。底模 `60463` 的 PixelGen 改写版 GenEval(`67.05`;批大小 4 为 `66.93`)和 MJHQ(`13.38` / `25.35`)采用逐张顺��生成;底模 CVTG-2K(`0.22%`)使用未拼写拆写的提示。
## 与 ≤1B 模型对比
以下外部模型只收 2026-05-30 及以后发表的,数字均逐一核对原始论文、技术报告或官方发布页。参数量仅计视觉生成主干。所有外部模型均为单张生成且未使用提示改写;我们的模型使用了去除 **7,190 条近重复**后的 BLIP3o-60K(并经两轮逐句扫描零命中)。0.1.0 纯主干单张生成成绩见[各部分贡献](#各部分贡献)。
### 原版 GenEval(553 题,0–1 刻度)
| 模型 | 发布年月 | 参数量 | 分辨率 | 推理模式 | 是否使用 BLIP3o-60K | GenEval ↑ ||---|---|---:|---:|---|---|---:|| [RG-T2I-L/16](https://arxiv.org/html/2610.12978) | 2026-10 | 912M | 512 × 512 | 单张生成 | 是(120K 混合集) | 0.89 || [MiniT2I-L/16](https://peppaking8.github.io/minit2i/) | 2026-06 | 912M | 512 × 512 | 单张生成 | 是(120K 混合集) | 0.883 || [AMD Nitro-P](https://rocm.blogs.amd.com/artificial-intelligence/nitro-p/README.html) | 2026-11 | 679M | 512 × 512 | 单张生成 | 是(120K 混合集) | 0.88 || [UNIFIED-L](https://arxiv.org/html/2611.29064) | 2026-11 | 554M | 256 × 256 | 单张生成 | 是 | 0.878 || [HiT-B/16](https://arxiv.org/html/2611.22962) | 2026-11 | 250M | 512 × 512 | 单张生成 | 是(120K 混合集) | 0.878 || [HiRAE-24](https://arxiv.org/html/2609.37775) | 2026-09 | 875M | 256 × 256 | 单张生成 | 是 | 0.877 || [JuZhou 1.0](https://arxiv.org/html/2606.28421) | 2026-06 | 385M | 1024 × 1024 | 单张生成 | 否 | 0.70 || **Haidass-Image-Instruct 0.1.0(我们)**¹ | 2026-11 | 0.6B | 512 × 512 | 计数题 8 选 1;其余单张生成 | 是(去除 7,190 条近重复) | **0.859** |
¹ **0.1.0 计数题生成方式:** 8 个初始噪声各运行 50 步中的前 5 步;计数小头读取第 5 步中间特征(第 25 层 4 × 4 池化)并预测每个候选最终会画出的物体数量(`0–6` 和 `7+` 共 8 类);预测最可能符合目标数量的候选继续跑到第 50 步。表中 `0.859` 为官方种子 42(种子 43 为 `0.869`,两批合并为 `0.864`)。外部模型行均为单张生成,因此 0.1.0 默认推理行单列于表尾、不计入单张生成排名。2026-05-30 之后发表的 ≤1B 单张生成模型中,未使用 BLIP3o-60K 且无提示改写的最高分是 JuZhou 1.0(`0.70`);2026-05-30 之后发表、得分在 `0.85–0.89` 的 10 个 ≤1B 模型(上表列出最高的 6 个)均使用了 BLIP3o-60K 或 MiniT2I 120K 混合集微调。
### DPG-Bench(1,065 题,0–100 刻度)
| 模型 | 发布年月 | 参数量 | 分辨率 | 推理模式 | 是否使用 BLIP3o-60K | DPG-Bench ↑ ||---|---|---:|---:|---|---|---:|| [RG-T2I-L/16](https://arxiv.org/html/2610.12978) | 2026-10 | 912M | 512 × 512 | 单张生成 | 是(120K 混合集) | 87.1 || [Looped-DiT B/16](https://arxiv.org/html/2609.40305) | 2026-09 | 260M | 512 × 512 | 单张生成 | 是(120K 混合集) | 87.0 || [HiRAE-24](https://arxiv.org/html/2609.37775) | 2026-09 | 875M | 256 × 256 | 单张生成 | 是 | 86.35 || [AMD Nitro-P](https://rocm.blogs.amd.com/artificial-intelligence/nitro-p/README.html) | 2026-11 | 679M | 512 × 512 | 单张生成 | 是(120K 混合集) | 86.33 || [MiniT2I-L/16](https://peppaking8.github.io/minit2i/) | 2026-06 | 912M | 512 × 512 | 单张生成 | 是(120K 混合集) | 85.9 || [HiT-B/16](https://arxiv.org/html/2611.22962) | 2026-11 | 250M | 512 × 512 | 单张生成 | 是(120K 混合集) | 85.33 || [UNIFIED-L](https://arxiv.org/html/2611.29064) | 2026-11 | 554M | 256 × 256 | 单张生成 | 是 | 84.8 || [NanoGen (FLUX.2-VAE)](https://arxiv.org/html/2606.24888) | 2026-06 | 612M | 256 × 256 | 单张生成 | 否 | 84.1 || **Haidass-Image-Instruct 0.1.0(我们)** | 2026-11 | 0.6B | 512 × 512 | 默认路由(计数 8 选 1;写字 / 主干单张) | 是(去除 7,190 条近重复) | **84.28** |
### OneIG-Bench(英文,0–1 刻度)、MJHQ-30K FID(Sana 协议)与 CVTG-2K
| 评测与模型 | 发布年月 | 参数量 | 分辨率 | 推理模式 | 是否使用 BLIP3o-60K | 分数 ||---|---|---:|---:|---|---|---:|| **OneIG(英文)总分 ↑** — [AnisoFlow-L/16 + DWD](https://arxiv.org/html/2611.22287) | 2026-11 | 940M | 1024 × 1024 | 单张生成 | 否 | 0.533 || **OneIG(英文)总分 ↑** — [AnisoFlow-L/16](https://arxiv.org/html/2611.17767) | 2026-11 | 918M | 1024 × 1024 | 单张生成 | 否 | 0.528 || **OneIG(英文)总分 ↑** — [JiT-L/16-T2I](https://arxiv.org/html/2611.17767) | 2026-11 | 917M | 512 × 512 | 单张生成 | 否 | 0.512 || **OneIG(英文)总分 ↑** — **Haidass-Image-Instruct 0.1.0(我们)** | 2026-11 | 0.6B | 512 × 512 | 默认路由 | 是(去除 7,190 条近重复) | **0.387** || **MJHQ-30K FID ↓** — **Haidass-Image-Instruct 0.1.0(我们)** | 2026-11 | 0.6B | 512 × 512 | 默认路由 | 是(去除 7,190 条近重复) | **10.33** || **CVTG-2K(词准 / NED / CLIP)↑** �� **Haidass-Image-Instruct 0.1.0(我们)** | 2026-11 | 0.6B | 512 × 512 | 写字路径(单张生成) | 是(去除 7,190 条近重复) | **45.08% / 0.716 / 0.760** |
超 1B 参考模型:OneIG-Bench(英文)上,[SeFi-Image-1B](https://arxiv.org/html/2606.22568)(2026-06,约 1.18B,1024 × 1024,单张生成,BLIP3o-60K 未说明)总分为 `0.525`(`0.859 / 0.884 / 0.271 / 0.398 / 0.212`)。CVTG-2K 上暂无其他 ≤1B 模型报告分数;[SeFi-Image-1B](https://arxiv.org/html/2606.22568) 词准确率为 `71.8%`、NED 为 `0.862`、CLIPScore 为 `0.810`。PixelGen 改写版 GenEval 上仅 [Halcyon](https://arxiv.org/html/2610.26863)(2026-10,256 × 256,仅预训练,单张生成,未用 BLIP3o-60K)报告过成绩(`Halcyon-0.52B` 0.52B:`44.91`;`Halcyon-4.00B + I2T 10%` 4.00B:`55.33`;`JiT-T2I-XXL/16++` 1.11B:`41.79`)。
## 评测说明
- **数据清洗与 0.0.1 停用。** 0.0.1 的训练数据与评测提示存在重叠;0.1.0 从底模 `60463` 出发在逐句清洗数据(v4,两轮独立扫描零命中,并剔除全部 8 个留出 COCO 类别)上重训。0.0.1 保留于 git 标签 `v0.0.1`,其分数已停用。- **重合数据对照实验(`v5-A`)。** 从 v4 训练池再删去 35,949 张(12.4%)物体组合与评测题匹配的图(无序物体集合相同、结构相同或左右互换)后从底模重训,同时保持各来源抽样总数不变(因此剩余计数图平均被抽 33 次,而 v4 为 21.7 次):PixelGen 改写版 GenEval 总分(`82.79` 对 `83.17`,差值 `−0.38`,95% 区间 `[−1.56, +0.79]`)与 8 个未见类别留出组合题(`−1.00`)均无显著差异,位置分项降低 `3.13` 分(`[−6.00, −0.25]`)。这一 `−3.13` 的位置分项结果反映删去重合图像与每来源抽样频次变化(每张计数图 33 次对比 21.7 次)的共同影响,两者在 `v5-A` 中无法单独拆分。- **检查点选点规则。** 在 11 个完成 PixelGen 改写版 GenEval 两批和留出组合题 评测的 CFG1 EMA 强化学习候选中,按事先写定的规则先剔除留出组合题 显著低于 v4 的候选(无被剔除项),再取两批 PixelGen 改写版 GenEval 最高者:选中第 `240` 次更新(`85.73`;第 `280`、`320`、`334` 次分别为 `85.68`、`85.50`、`85.54`)。- **共用检测器与盲看核对。** Flow-GRPO 奖励与 GenEval 系列评测共用同一套 `Mask2Former` + `CLIP ViT-L/14` 检测器。对 PixelGen 改写版 GenEval 标准种子上检测器判定翻转的图对按比例抽样 60 对做盲看(第 240 次对 v4),实际变好(外推约 11 张)与变差(约 14 张)大致抵消;同时,在第 240 次纯主干相对 v4 上,采用独立评分器的评测——DPG-Bench(`+1.07`)、OneIG 对齐(`+0.54`)、OneIG 推理(`+0.39`)、MJHQ-30K FID(`−0.19`)与 MJHQ-30K CLIP(`+0.08`)——均显著提升。- **评测命名与协议。** 「PixelGen 改写版 GenEval」指 [PixelGen](https://arxiv.org/abs/2602.02493) 中 `evaluations/geneval/evaluation_metadata_rephrased.jsonl` 去掉每条开头 `"The image shows "` 后的称呼。MJHQ-30K FID 采用 Sana 协议(512 × 512,JPEG Q75),仅与我们自身各阶段对照。CVTG-2K 报告词准确率、NED 和 CLIPScore(未测 VQAScore 与 Aesthetic Score)。留出组合题(400 题 × 4 张)、留出计数题(200 题 × 4 张)及其他内部题集未随本仓库发布。- **同题多样性。** OneIG-Bench(英文)多样性从 `26.56`(底模 `60463`)变为 `17.74`(v4),0.1.0 为 `17.60`(第 240 次纯主干为 `17.21`)。后训练使同一提示在不同种子下的生成结果更趋一致。
### 已知局限
- **仅支持英文写字与同句载体词路由规则。** 写字能力面向英文。对常见载体或写字线索词(`sign`、`poster`、`reads`、`says`、`labeled`、`cover` 等),引号文字需与线索词位于同一句才会触发写字路径(中式角引号、冒号引出文字及部分印刷设计载体另有触发规则): - *触发写字路径:* `A teal enamel sign reading "OPEN LATE" in a rainy shop window` - *不触发写字路径(载体词与引号分处两句):* `A minimalist book cover on a wooden table. Display "MIDNIGHT GARDEN" across the center.` - 不带引号的文档或论文首页提示也不会触发写字路径(OneIG 英文文字 200 题中有 11 题未触发,占目标词 25.9%;已路由的 189 题词准确率 `21.45%`,未触发的 11 题为 `0.06%`)。- **数字、标点与复杂带字场景。** CVTG-2K 上含数字或标点的词准确率为 `7.69%`(1,730 词),纯字母词为 `49.59%`(14,476 词)。由于写字 LoRA 训练数据有 82% 为平面合成排版,在含引号文字的复杂多物体场景中优先保证字形清晰时主体画面可能被压缩:在 0.1.0 上,完整模型的 DPG-Bench 为 `84.28`,比同批纯主干(`84.58`)低 `0.31`(`−0.31`,95% 区间 `[−0.59, −0.02]`),主要原因是 70 道带引号文字的 DPG 题走���写字路径(另有 35 道走计数路径)(在强化学习第 80 次上,这 70 道路由题的 `other - text` 提升 `+22.00`、`entity - whole` 变化 `−5.61`,整体 DPG 差值为 `−0.25`)。更看重画面构图时可传入 `--writing-lora off`。- **计数小头适用范围。** 计数小头预测 `0–6` 和 `7+` 共 8 类,并在 50 步采样时启用(其他步数会回退为单张生成)。在长描述计数题上(约 132 词,PixelGen 改写版 GenEval 计数 80 题),相对单张生成为 `+3.13` 个百分点(95% 区间 `[−1.82, +8.07]`,未达显著)。当数量解析出错时,小头会按错误目标 `N` 选图(2 道错解析题相对单张生成为 `−37.50` 个百分点)。- **路由优先级与跨设备种子差异。** 提示同时包含引号文字与可解析数量时,写字路径优先。昇腾 NPU、CUDA 与 CPU 的初始噪声生成器不同,同一种子在不同硬件上会生成不同图像。
## 各部分贡献
下表依次拆分展示:(1)纯主干正式后训练各阶段成绩,(2)默认路由(写字 LoRA + 计数小头)相对第 240 次主干的净贡献,以及(3)计数小头 `k = 1 / 4 / 8 / 16` 候选数曲线(均为 EMA 权重,512 × 512,Euler 50 步,CFG 8.0)。
### 纯主干正式成绩(批大小 4,单张生成,不含写字 LoRA 与计数小头)
| 评测 | 底模(`60463`) | v4 清洗重训 | **0.1.0 主干(强化学习第 240 次)** | 相对 v4 配对差值 [95% 区间] ||---|---:|---:|---:|---:|| PixelGen 改写版 GenEval(两批,0–100) | 67.05 | 83.17 | **85.73** | +2.55 [+1.65, +3.46] || 留出组合题(8 个未见类别,0–100) | 59.00 | 81.56 | **83.56** | +2.00 [+0.90, +3.10] || 原版 GenEval,种子 42(0–1) | 0.600 | 0.797 | **0.834** | +0.037 [+0.025, +0.050] || 原版 GenEval,种子 43(0–1) | — | 0.804 | **0.848** | +0.044 [+0.032, +0.057] || 原版 GenEval,两批合并(0–1) | — | 0.800 | **0.841** | +0.041 [+0.031, +0.051] || 留出计数题(恰好 N,%) | — | 46.50% | **52.00%** | +5.50 [+2.63, +8.37] || DPG-Bench(0–100) | 83.98 | 83.53 | **84.60** | +1.07 [+0.68, +1.46] || OneIG(英文)对齐 / 推理(0–100) | 80.11 / 19.11 | 81.27 / 18.69 | **81.82 / 19.08** | +0.54 / +0.39 || OneIG(英文)风格 / 多样性 / 文字(0–100) | 39.46 / 26.56 / 0.68 | 40.60 / 17.74 / 0.32 | **40.33 / 17.21 / 0.42** | −0.27 / −0.53 / +0.10 || OneIG(英文)五项平均(0–100) | 33.18 | 31.73 | **31.77** | +0.04 [−0.16, +0.26] || MJHQ-30K FID ↓ / CLIP(Sana 协议) | 13.38 / 25.35 | 10.53 / 26.02 | **10.33 / 26.10** | −0.19 / +0.08 || CVTG-2K 词准 / NED / CLIPScore | 0.22% / 0.212 / — | 0.22% / 0.234 / 0.657 | **0.19% / 0.234 / 0.665** | — |
PixelGen 改写版 GenEval 分项(v4 → 第 240 次):单物体 `99.69 → 100.00`,双物体 `94.07 → 95.08`,计数 `59.38 → 63.59`(`+4.22`),颜色 `92.02 → 94.68`(`+2.66`),位置 `77.13 → 79.50`(`+2.38`),颜色绑定 `76.75 → 81.50`(`+4.75`)。
### 完整模型对同批骨干(隔离写字 LoRA + 计数小头的贡献)
为在不混入生成批量差异的前提下隔离写字 LoRA 与计数小头的净贡献,完整模型与同批骨干对照在触发路由的题目上均采用逐张生成(`batch_size = 1`),未触发路由的题目复用正式 `batch_size = 4` 图像与评分(未路由题逐题差值为零):
| 评测 | 路由题数(计数 / 写字) | 同批骨干 | **完整模型(0.1.0)** | 整模 − 同批骨干 [95% 区间] ||---|---|---:|---:|---:|| PixelGen 改写版 GenEval(两批,0–100) | 每批 82 / 5 | 85.79 | **86.34** | +0.54 [−0.28, +1.37] || 原版 GenEval,种子 42(0–1) | 73 / 0 | 0.838 | **0.859** | +0.021 [+0.011, +0.030] || 原版 GenEval,种子 43(0–1) | 73 / 0 | 0.849 | **0.869** | +0.020 [+0.011, +0.030] || 原版 GenEval,两批合并(0–1) | 每批 73 / 0 | 0.843 | **0.864** | +0.021 [+0.013, +0.029] || 留出组合题(8 个未见类别,0–100) | 100 / 0 | 83.50 | **87.94** | +4.44 [+3.04, +5.83] || 留出计数题(恰好 N,%) | 200 / 0 | 52.38% | **67.00%** | +14.63 [+10.47, +18.78] || DPG-Bench(0–100) | 35 / 70 | 84.58 | **84.28** | −0.31 [−0.59, −0.02] || OneIG(英文)对齐(0–100) | 15 / 4(共 695 题) | 81.80 | **81.82** | +0.02 [−0.03, +0.06] || OneIG(英文)文字(0–100) | 0 / 189(共 200 题) | 0.50 | **34.75** | +34.25 [+17.13, +45.34] || OneIG(英文)推理(0–100) | 0 / 0(共 225 题) | 19.08 | **19.08** | 0.00 [0.00, 0.00] || OneIG(英文)风格(0–100) | 1 / 3 的子集(共 114 题) | 40.32 | **40.31** | −0.02 [−0.04, +0.01] || OneIG(英文)多样性(0–100) | 15 / 193(共 1,120 题) | 17.21 | **17.60** | +0.39 [+0.17, +0.61] || OneIG(英文)五项平均(0–100) | 15 / 193(共 1,120 题) | 31.78 | **38.71** | +6.93 [+3.52, +9.14] || MJHQ-30K FID ↓(Sana 协议) | 185 / 0 | 10.335 | **10.335** | −0.001 [−0.008, +0.008] || MJHQ-30K CLIP | 185 / 0 | 26.102 | **26.102** | +0.000 [−0.002, +0.002] || CVTG-2K 词准确率(%) | 0 / 2,000 | 0.22% | **45.08%** | +44.87 [+43.43, +46.35] || CVTG-2K NED | 0 / 2,000 | 0.234 | **0.716** | +0.482 [+0.472, +0.492] || CVTG-2K CLIPScore | 0 / 2,000 | 0.664 | **0.760** | +0.096 [+0.091, +0.102] || CVTG-2K 整图完全正确率(%) | 0 / 2,000 | 0.00% | **16.60%** | +16.60 [+15.00, +18.25] |
在同一第 240 次主干的独立批大小 4 写字 LoRA 评测中(CVTG-2K 总词准确率 `45.11%`,OneIG 英文文字 `35.30`),按文字区域数分项的词准确率为 2 / 3 / 4 / 5 区分别 `54.55%` / `50.48%` / `47.44%` / `33.30%`,未见词准确率为 `46.45%`、见过词为 `50.16%`(测于强化学习第 80 次)。
### 计数小头 `k = 1 / 4 / 8 / 16` 曲线(在第 240 次主干上配对评测)
在留出计数题(200 道 8 个未见类别短句题,共享 16 候选种子池;该逐图批大小 1 池下的不挑基线为 `52.38%`,与上表正式批大小 4 主干 `52.00%` 的差值为 `+0.38` 个百分点、95% 区间 `[−0.69, +1.44]`,两者使用完全相同的 800 个种子,仅因逐图与批大小 4 出图而有细微差异;下表耗时为共享 16 候选曲线运行的拼接中位数,`k = 8` 为 `7.99` 秒,[耗时与硬件](#耗时与硬件)中的独立 `k = 8` 单跑为 `7.97` 秒):
| 候选数(`k`) | 计数小头准确率 | 随机 `k` 选 1 | 小头 − 随机 [95% 区间] | NPU 中位耗时(秒/图) ||---:|---:|---:|---:|---:|| 1(单张生成) | 52.38% | 52.38% | +0.00 | 5.91 || 4 | 64.50% | 49.62% | +14.88 [+11.13, +18.62] | 6.86 || **8(默认)** | **67.00%** | 52.62% | **+14.37 [+10.36, +18.39]** | **7.99** || 16 | 67.38% | 51.00% | +16.38 [+11.97, +20.78] | 10.25 |
默认 `k = 8` 相对单张生成提高 `+14.63` 个百分点(`[+10.47, +18.78]`);`k = 16` 仅多 `0.38` 个百分点但耗时多约 28%。原版 GenEval 上(触发路由的 73/80 道计数题),独立计数小头评测(相对正式批大小 4 主干)将计数分项在种子 42 从 `59.06%` 提到 `72.81%`(`+13.75` 个百分点)、在种子 43 从 `64.69%` 提到 `77.19%`(`+12.50` 个百分点),总分相应提高 `+2.29` 个百分点(`0.834 → 0.857`,`+0.023`)与 `+2.08` 个百分点(`0.848 → 0.869`,`+0.021`)——严格等于计数增幅的六分之一(上表全批大小 1 整模相对同批骨干的差值为种子 42 / 种子 43 / 两批合并 `+2.08` / `+2.03` / `+2.06` 个百分点)。在 15 道误触发的非计数 PixelGen 改写版 GenEval 题上准确率为 `92.50%`,单张生成为 `91.67%`(`+0.83` 个百分点,`[−0.80, +2.47]`)。
## 训练设置
全部阶段均在华为昇腾 910B NPU 上从 `Haidass-Image-Base-v1_0.6B_512px`(`60463`)出发完成:
| 阶段 | 数据 | 关键超参数 ||---|---|---|| 1. 清洗重训(`v4`) | 289,726 行(两轮清洗扫描零命中;剔除 8 个留出类别;BLIP3o-60K 去除 7,190 条近重复);配比 70% 公开图文与组合 / 15% 计数 / 15% 位置与颜色绑定 | 16 张 NPU,全局批量 1,024,2,500 步;峰值学习率 `5e-5`,100 步预热,余弦衰减至 10%,权重衰减 `0.01`,EMA `0.998`;时间步 90% logit-normal(均值 `ln 2`)+ 10% 均匀;修正文字说明丢弃 || 2. Flow-GRPO 强化学习(`CFG1` 第 240 次) | 3,600 题库覆盖 GenEval 6 类技能(与 PixelGen 改写版 GenEval 完整提示属性组合零交集;事后查重发现 231 条强化学习提示与 59 道评测题共享物体类别对,剔除这 59 题后第 80 次更新整体仍 `+1.99`、位置分项 `+3.62`;排除 8 个留出类);Mask2Former + CLIP ViT-L/14 部分分奖励 | 从 `v4` EMA 起训;Flow-Factory GRPO + CPS(10 步,噪声 `0.8`,前 5 步选 3 步反传);每轮更新 1 次,32 组 × 18 = 576 张/更新(8 卡);采样 CFG `1.0`;AdamW 学习率 `3e-4`,权重衰减 `1e-4`,梯度裁剪 `1.0`,ratio 裁剪 `±1e-4`,优势裁剪 `±5`,v-based KL `0.001`;LoRA `r = 32 / alpha = 64`(FP32 LoRA/AdamW/EMA,BF16 前向),EMA `0.99` 每 4 轮更新;停于第 334 次,取第 `240` 次合并 EMA || 3. 写字 LoRA 第四版 | 6 类经 OCR 成块重筛数据(同行合并再成块,每类 200 张盲看通过;82% 为平面合成排版),配逐字母拼写标注 | 冻结主干(自强化学习第 80 次起训,在第 240 次上复验);PEFT `r = 128`,`alpha = 256`,学习率 `3e-4`,4,500 步余弦日程,EMA 权重;首轮 `1e-4` 后按 CVTG-2K 调整过一轮学习率与配比 || 4. 计数小头 | 25,448 张图(约 58 类、3 种写法、七类查重零命中、排除 8 个留出类);数量标签由 Qwen2.5-VL 标注(盲看一致率 99%) | 第 5 步第 25 层 4 × 4 池化特征;两层 MLP(隐藏 `64`,L2 `α = 1e-3`,Adam,批量 `128`,学习率 `0.001`,迭代上限 `60`),float64 打分并按种子确定性打破平分 |
## 智能体自主后训练流程
0.1.0 后训练主线(`v4` 清洗重训 → Flow-GRPO → 写字 LoRA 第四版 → 计数小头)由经理智能体与执行智能体在 8 台 Atlas A2 服务器(64 张昇腾 910B NPU)上自主规划、执行与复核。每个阶段均采用事先写定的成功/失败门槛与配对 95% 置信区间,使用经验看板持续记录成功与废弃方案,并由独立自动审查流程复核派单与结果、由多模态视觉语言模型盲看核验训练数据抽样与翻转评测图对。
0.1.0 路径的关键实测结论:(1)逐句清洗结合修正后的预热、余弦衰减、权重衰减与 EMA 训练,将底模 PixelGen 改写版 GenEval 从 `67.05` 提到 `83.17`、留出组合题 从 `59.00` 提到 `81.56`;(2)Flow-GRPO 改为每轮更新 1 次并使用 FP32 LoRA/EMA 状态后消除了策略比值裁剪偏置,稳定推进至第 240 次更新(PixelGen 改写版 GenEval `85.73`,DPG `84.60`);(3)OCR 成块筛选数据结合逐字母拼写提示将 CVTG-2K 词准确率从 `0.22%` 提到 `45.08%`;(4)计数小头采用数量分类预测(`0–6`、`7+`)替代二分类判对错后,将留出计数题准确率从 `52.38%` 提到 `67.00%`。
## 推理
默认推理按每条提示自动运行完整 0.1.0 模型:1. **写字路径**(带引号待渲染文字,一般与载体词位于同一句):启用 `writing_lora/`,在引号后自动追加逐字母拼写标注(如 `"OPEN LATE" (spelled: O P E N / L A T E)`),运行 50 步 Euler 采样。拼写标注后超过 256 token 会发出警告并在输出记录中标记 `truncated: true`。2. **计数路径**(未触发写字路径、50 步采样且解析出单一明确数量):8 个初始噪声各运行 50 步中的前 5 步;`counting_head/head.npz` 读取第 5 步中间特征(第 25 层 4 × 4 池化)并预测每个候选最终会画出的物体数量(`0–6` 和 `7+` 共 8 类);`log P(数量 = N)` 最高的候选续跑至第 50 步。非 50 步采样会发出提示并退回单张生成。3. **主干路径**(其余提示):1 个初始噪声在主干上运行 50 步 Euler 采样。
### 默认采样设置与仓库文件
| 参数 | 默认值 | 仓库文件 | 用途 ||---|---|---|---|| 分辨率 | 512 × 512 | `dit.safetensors` | 生成主干权重(FP32,合并 EMA) || 采样器与步数 | Euler,50 步 | `writing_lora/` | 写字 LoRA 权重(EMA FP32)与 PEFT 配置 || 引导强度(CFG) | 8.0(`cfg_norm = none`) | `counting_head/` | 计数小头权重(`head.npz`)与解析/排序代码 || 时间步偏移 | 1.0 | `vae/` | Qwen-Image-2.1 VAE 权重与配置 || 无条件提示 | EOS token | `config.json`、`runtime/` | 模型、采样与路由配置及运行代码 || 计算精度 | BF16 autocast;FP32 潜变量 | `inference.py`、`requirements.txt`、`SHA256SUMS` | 命令行 / Python 入口、依赖清单与校验和 |
仓库下载大小:**4.15 GB**(3.86 GiB:DiT `2.39 GB`、VAE `1.35 GB`、写字 LoRA `401 MB`、计数小头 `5.02 MB`)。文本编码器 [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) 首次使用时会自动下载约 **1.52 GB**(1.41 GiB),也可通过 `--text-encoder` 指定本地目录(见[离线用法](#离线用法))。
### 安装与运行命令
下载本仓库(私有访问需提供具备读取权限的 Hugging Face 令牌),在已激活的 Python 3.11+ 虚拟环境中进入包含 `inference.py` 的模型目录并安装依赖(`--device auto` 依次选择 CUDA、昇腾 NPU、CPU,也可指定 `cpu`、`cuda[:N]`、`npu[:N]`;昇腾环境需安装兼容的 `torch_npu` 与 CANN;MPS 未测试,Mac 用户可选 `cpu`):
```bashpython -m pip install -r requirements.txt```
在下载后的模型目录中直接运行以下命令。默认推理使用 `--device auto`,首次运行会自动下载 `Qwen/Qwen3-0.6B`。单图模式会直接写入(覆盖)指定的 `--output` PNG 路径及同名旁路 JSON(默认 `output.png` 与 `output.json`)。批量 `--cases` 模式读取含 `id`、`caption`、`seed`(及可选 8 个互异整数 `candidate_seeds`,首项等于 `seed`,范围 `0..2,147,483,647`)的 JSON 数组,写至 `<output>/<id>/image.png` 与 `image.json`(默认目录 `outputs`),对同一输出目录重新运行同一命令会自动续跑并跳过已有图片——仅 `--cases` 会跳过已有输出。
在模型目录中保存如下 2 行 `cases.json`,用于下方的 `--cases` 批量运行与消融开关示例:
```json[ {"id": "sign", "caption": "A teal enamel sign reading 'OPEN LATE' in a rainy shop window", "seed": 42}, {"id": "apples", "caption": "A photo of four red apples on a wooden table", "seed": 42}]```
#### Bash
```bash# 默认整模推理(分别对应普通、写字与计数三条路径)python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --seed 42 --output bridge.pngpython inference.py "A teal enamel sign reading 'OPEN LATE' in a rainy shop window" --device auto --seed 42 --output sign.pngpython inference.py "A photo of four red apples on a wooden table" --device auto --seed 42 --output apples.png
# 使用 --cases 批量推理(再次执行同一条命令会自动续跑并跳过已完成图片)python inference.py --device auto --cases cases.json --output ./outputspython inference.py --device auto --cases cases.json --output ./outputs
# 关闭指定路由python inference.py --device auto --cases cases.json --count-head off --output ./out-count-offpython inference.py --device auto --cases cases.json --writing-lora off --output ./out-writing-offpython inference.py --device auto --cases cases.json --routing none --output ./out-routing-none```
#### PowerShell
```powershell# 默认整模推理(分别对应普通、写字与计数三条路径)python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --seed 42 --output bridge.pngpython inference.py "A teal enamel sign reading 'OPEN LATE' in a rainy shop window" --device auto --seed 42 --output sign.pngpython inference.py "A photo of four red apples on a wooden table" --device auto --seed 42 --output apples.png
# 使用 --cases 批量推理(再次执行同一条命令会自动续跑并跳过已完成图片)python inference.py --device auto --cases cases.json --output .\outputspython inference.py --device auto --cases cases.json --output .\outputs
# 关闭指定路由python inference.py --device auto --cases cases.json --count-head off --output .\out-count-offpython inference.py --device auto --cases cases.json --writing-lora off --output .\out-writing-offpython inference.py --device auto --cases cases.json --routing none --output .\out-routing-none```
#### Python 接口
`generate` 返回 `(PIL.Image, dict)`;`generate_batch` 默认返回 PIL 图片列表,`return_records=True` 时返回 `(PIL.Image, dict)` 列表:
```pythonfrom inference import Generator
model = Generator(device="auto") # 首次使用会自动下载 Qwen/Qwen3-0.6Bwriting_image, writing_info = model.generate( 'A teal enamel sign reading "OPEN LATE" in a rainy shop window', seed=42,)writing_image.save("sign.png")
outputs = model.generate_batch( [ "A sunlit stone bridge over a calm mountain river", "A photo of four red apples on a wooden table", ], [42, 43], return_records=True,)for name, (image, info) in zip(["bridge.png", "apples.png"], outputs): image.save(name)```
#### 离线用法
离线使用时请先备好本仓库与 `Qwen/Qwen3-0.6B`,设置 `HF_HUB_OFFLINE=1`(或用 `HF_HOME` 指向已预热的 Hugging Face 缓存目录),并通过 `--text-encoder` 指定本地 `Qwen3-0.6B` 目录(Python 接口中传入 `Generator(device="auto", text_encoder="<本地目录>")`):
```bashexport HF_HUB_OFFLINE=1python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --text-encoder /path/to/Qwen3-0.6B --seed 42 --output bridge.png```
```powershell$env:HF_HUB_OFFLINE = '1'python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --text-encoder .\Qwen3-0.6B --seed 42 --output bridge.png```
### 耗时与硬件
下表昇腾 910B NPU 单图耗时为单卡独享批大小 1 实测中位数(计入文本编码、去噪与 VAE 解码;计数 `7.97 秒`来自独立 `k = 8` 单跑,上文 `k = 1 / 4 / 8 / 16` 曲线中的 `7.99 秒`来自 16 候选拼接运行;同一进程的第一张写字图另含约 4–5 秒的一次性 LoRA 加载):
| 路径 | 昇腾 910B NPU(中位数 / 图) ||---|---:|| 主干(1 × 50 步) | 5.91 秒 || 写字(LoRA + 1 × 50 步) | 9.06 秒 || 计数(8 × 5 步 + 1 × 45 步) | 7.97 秒 |
CPU 和 CUDA 运行同一份代码,速度没有实测。由于昇腾 NPU、CUDA 与 CPU 的初始噪声生成器不同,同一 `--seed` 在不同设备上会生成不同图像。
## 版本记录(完整说明)
- **0.1.0(2026-11):** 正式版本。从 `Haidass-Image-Base-v1_0.6B_512px` 在逐句清洗数据(v4,两轮扫描零评测命中)上重训,经 Flow-GRPO 强化学习(CFG1 分支第 240 次更新、合并 EMA,按事先定好的规则选出),与写字 LoRA 第四版(EMA)及计数小头集成并在默认推理下统一路由。权重以 FP32 存于 `dit.safetensors`。- **0.0.1(预览版,git 标签 `v0.0.1`):** 早期预览版本(早期在未清洗数据上后训练的未平滑权重 + 写字 LoRA 第三版)。归档于标签 `v0.0.1`;其训练数据与评测提示存在重叠,原分数已停用并由 0.1.0 替代。13 unmodified lines141516171819171821192023212225232427252629272831293033313235363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621633334353637383940414243444546471661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971984849502012022032045152535420720820921021121221321421521621721821922022122222322422522622722822923023123255565758592346061236237626364656667686970712402412422432442452462477273249747576777879808182838485251868725325425588892579091929394959697989910025926010110226210310426410510610710810926611011126826911211327127227327427527627711411527911611711811912012112212312412512628712712812913013113 unmodified lines- recursive-self-improvement---
<div align="center"> <img src="assets/logo.png" width="560"/></div><div align="center"><img src="assets/logo.png" width="560"/></div>
**English** · [简体中文](README_zh.md)# Haidass-Image-Instruct 0.1.0
**English** · [简体中文](README_zh.md) · [Technical details](DETAILS.md)
*48 images from the released model at 512 × 512, with the recommended settings below. Lettering images use the automatically loaded text LoRA.***Haidass-Image-Instruct 0.1.0** is a single integrated 0.6B text-to-image model at 512 × 512, post-trained from [Haidass-Image-Base-v1_0.6B_512px](https://huggingface.co/DALabCommunity/Haidass-Image-Base-v1_0.6B_512px) (checkpoint `60463`) on Huawei Ascend 910B NPUs. It combines a flow-matching DiT backbone, a writing LoRA for English display text, and a counting head for object-count selection, paired with a frozen [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) text encoder. Default inference selects the appropriate route automatically from each prompt.
Live demo: https://huggingface.co/spaces/HanWangTJU/Haidass-Image-App
## Model## Quick start
**Haidass-Image-Instruct 0.0.1 (preview)** is a compact text-to-image model with a **0.6B generation backbone**. It is post-trained from [Haidass-Image-Base-v1_0.6B_512px](https://huggingface.co/DALabCommunity/Haidass-Image-Base-v1_0.6B_512px), and the whole post-training run was carried out by an autonomous **Recursive Self-Improvement (RSI)** agent system. Post-training lifts PixGenEval from **67.05 to 82.21**. The gain carries over to held-out prompts built from object classes that never appear in training. On the original GenEval it scores **0.82**, ahead of Janus-Pro-7B, Stable Diffusion 3 (8B), FLUX.1-dev and DALL·E 3. A routed text LoRA adds legible English text rendering.Run from the downloaded model directory in Python 3.11+ (`--device auto` checks CUDA, Ascend NPU, then CPU; `Qwen/Qwen3-0.6B` downloads on first use; see [DETAILS.md](DETAILS.md) for the `cases.json` fields and full PowerShell commands):
## Architecture`requirements.txt` installs the standard PyTorch build from PyPI (on Windows this is the CPU build). For an NVIDIA GPU, install the PyTorch build for your CUDA version first; on Ascend NPUs, install into an environment that already has `torch_npu`.
| Component | Value ||---|---|| Generation backbone | Single-stream diffusion transformer, Qwen-Image-2.1 based, flow matching || Backbone size | 34 layers, 9 heads × 128 dim, ~598M parameters || Text encoder | [Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B), frozen, last-layer hidden states, up to 256 tokens || VAE | Qwen-Image-2.1 VAE (64-channel latents), frozen || Text LoRA | Rank 128 / alpha 256 on the attention and MLP projections; loaded only when the prompt contains quoted text || Resolution | 512 × 512 |
## Key features
- **Built entirely on Huawei Ascend NPUs.** Data generation, training, LoRA training and every evaluation run on 8 Atlas A2 servers (64 × Ascend 910B).- **Strong compositional control at 0.6B.** It gets counts, left/right/above/below placement and color binding right, scoring 82.21 on PixGenEval.- **Gains that generalize.** On prompts built only from object classes withheld from all training data, the score rises by +15.7.- **Text rendering with no extra module.** Quoted text is spelled out letter by letter for the frozen encoder, and a LoRA loads only when needed.- **Self-improving training process.** An agent system planned, ran, judged and refined every experiment. See [Recursive Self-Improvement](#recursive-self-improvement).
## Evaluation
| Benchmark | Base | **Haidass-Image-Instruct** | Gain ||---|---:|---:|---:|| **PixGenEval¹** | 67.05 | **82.21** | **+15.2** || Held-out compositional set² | 59.00 | **74.69** | **+15.7** || MJHQ-30K FID ↓ | 13.38 | **10.20** | **−3.18** || MJHQ-30K CLIP score | 25.35 | **26.08** | +0.73 || OneIG-Bench (EN) Text | 0.68 | **17.97** | **+17.3** || CVTG-2K word accuracy | 0.22% | **19.45%** | **88×** || Large English text (50 prompts, exact match) | 0 / 50 | **28 / 50** | **+28** || Unseen-word spelling probe (100 images) | 0% | **88%** | **+88 pts** || OneIG-Bench (EN) Alignment | 80.11 | 80.73 | +0.62 || OneIG-Bench (EN) Style | 39.46 | 40.27 | +0.81 || DPG-Bench | 84.02 | 83.67 | maintained |
¹ GenEval's 553 prompts rewritten into detailed descriptions, as released with [PixelGen](https://arxiv.org/abs/2602.02493). Scoring follows GenEval unchanged.² 400 prompts × 4 images. They use only 8 COCO classes (giraffe, bicycle, umbrella, clock, teddy bear, apple, fire hydrant, suitcase), and all 8 are removed from every training set. See [Keeping the gains honest](#keeping-the-gains-honest).
All scores use the recommended sampling settings below, with the prompt as written (no prompt rewriting). The text LoRA loads only for prompts with quoted text. MJHQ FID / CLIP and the held-out set were measured on the backbone.
| Benchmark | Base | Backbone only | Backbone + routed text LoRA ||---|---:|---:|---:|| PixGenEval | 67.05 | 82.16 | **82.21** || DPG-Bench | 84.02 | 83.79 | 83.67 || OneIG Text | 0.68 | 0.38 | **17.97** || CVTG-2K word accuracy | 0.22% | 0.23% | **19.45%** || Large English text | 0 / 50 | 0 / 50 | **28 / 50** || Unseen-word spelling probe | 0% | 0% | **88%** |
### Comparison on GenEval
Other models publish only the original GenEval, so this table uses the **original GenEval** prompts and overall score. Every number except ours comes from the cited paper or technical report.
| Model | Params | Original GenEval ||---|---:|---:|| **Haidass-Image-Instruct (ours, 512 px)** | **0.6B** | **0.82** || Janus-Pro-7B | 7B | 0.80 || Stable Diffusion 3 (depth 38, DPO) | 8B | 0.74 || Lumina-Image 2.0 | 2.6B | 0.73 || Stable Diffusion 3.5 Large | — | 0.71 || FLUX.1-schnell | 12B | 0.71 || DALL·E 3 | — | 0.67 || FLUX.1-dev | 12B | 0.66 || SANA-1.6B | 1.6B | 0.66 || SANA-0.6B | 0.6B | 0.64 || Hunyuan-DiT | 1.5B | 0.63 || Stable Diffusion 3 Medium | 2B | 0.62 || SDXL | 2.6B | 0.55 || PixArt-Σ (512 px) | 0.6B | 0.52 || PixArt-α (512 px) | 0.6B | 0.48 |
Sources:- Janus-Pro-7B, SD3.5 Large, FLUX.1-dev, SD3 Medium: [Qwen-Image Technical Report, Table 4](https://arxiv.org/abs/2508.02324). Janus-Pro-7B also matches [Janus-Pro](https://arxiv.org/abs/2501.17811).- Stable Diffusion 3 (8B), DALL·E 3: [Esser et al., 2024, Table 5](https://arxiv.org/abs/2403.03206)- Lumina-Image 2.0: [Lumina-Image 2.0, Table 4](https://arxiv.org/abs/2503.21758)- FLUX.1-schnell, SANA-1.6B, SANA-0.6B, Hunyuan-DiT, PixArt-Σ, PixArt-α: [SANA, Tables 7 and 10](https://arxiv.org/abs/2410.10629)- SDXL: [GenEval, Table 2](https://arxiv.org/abs/2310.11513)
## Recursive Self-Improvement
A **manager agent** and several **executor agents** ran the whole post-training run on their own, in about two days of wall-clock time on 8 Ascend servers. The manager improves the model, and it also improves its own working process from one round to the next. That second part is what makes the loop recursive.
```mermaidflowchart LR A[Diagnose<br/>one component at a time] --> B[Plan experiment<br/>+ pre-registered<br/>success / failure rule] B --> C[Dispatch brief<br/>to executor agents] C --> D[Executors on 64 NPUs<br/>data · training · evaluation] D --> E[Score on public benchmarks<br/>+ held-out prompts] E --> F[Manager reviews results<br/>updates Experience Board] F --> G[Lessons Log:<br/>flaws in the agents'<br/>own way of working] G -->|revised checklist for<br/>briefs, planning, reporting| B F -->|next experiment| A H[Idle monitor<br/>any server idle 30 min] -.wakes.-> F```
### How the loop works
- **Manager agent.** It plans experiments, writes self-contained briefs, dispatches them, checks every reported number against its source files and sample images, and decides the next step.- **Executor agents.** They build data, train and evaluate on 8 × 8 Ascend 910B NPUs.- **Pre-registered rules.** Each experiment states in advance what counts as success. All three conditions must hold: 1. the target metric rises: +1.0 on PixGenEval, or +5 points on held-out large text; 2. the held-out compositional set gains at least half as much; 3. guardrails hold: DPG −1 at most, OneIG alignment −1 at most, FID +1.0 at most.- **Experience Board.** It records every success and failure with its exact conditions. A new idea that resembles a past failure must first say what is different this time.- **Lessons Log (the recursive step).** The manager records flaws in its own way of working. Examples: briefs that let executors pause for confirmation; data volumes set before teacher throughput was measured; a hypothesis reported as a conclusion. Each lesson becomes a checklist item that the manager runs before every later brief, plan and report.- **Idle monitor.** A watcher checks the cluster every 10 minutes and wakes the manager whenever a server's NPUs sit idle for 30 minutes, so the hardware never waits on the agents.
The board tracked **29 training and inference experiments: 10 met their pre-registered success rule and 19 did not**. It also recorded 2 pipeline speedups: teacher data generation 1.7× faster and evaluation 2.2× faster. Every failure was kept with its full conditions and used to steer the next round.
### Round by round
| Round | What changed | Why | PixGenEval ||---|---|---|---:|| Base | — | — | 67.05 || S4 | one server, LR 5e-5, 1,000 steps | halving the LR beat 1e-4 by +2.54 in a controlled pair | 70.72 || S6 | S4 + high-noise timestep sampling | diagnosis: layout is decided at high noise, which the base model rarely trained on | 72.60 || R2-A | 4 servers, 1,024 images / step, new compositional data, 1,000 steps | comparable post-training runs use far more image exposures | 76.31 || R2-B | R2-A + high-noise sampling, 1,500 steps | same seed and data order as R2-A, so the gain comes from the one change | 80.02 || R2-B-ext | continued to 2,500 steps (**released backbone**) | still rising at 1,500 steps; chosen by a rule fixed in advance | **82.16** || + text LoRA | routed text LoRA, 5,000 steps (**released system**) | text data hurt composition when trained into the backbone | **82.21** |
### Findings the agents made themselves
**1. Training on high-noise timesteps: +2.9 to +4.5 points.**Before any training, the agents tested components one at a time. Teacher images passed through our VAE scored no lower on GenEval, which ruled out the VAE. Classifying failed images one by one showed that most "position" failures were layout errors, such as overlapping objects or a vertical arrangement where a horizontal one was asked for. Only 24 of 310 were true left/right swaps. Object count and layout are decided at high noise levels, yet base training sampled t > 0.9 only 1.4% of the time. The agents also found that about 75% of the training signal in the initial checkpoint's earlier fine-tuning attempt fell on low-noise steps, which explains why that attempt gained only +1.36 GenEval. The fix was to sample timesteps as 90% sigmoid(N(0,1) + ln 2) plus 10% uniform. On one server it added +1.88 PixGenEval (S4 → S6). At equal steps on four servers, R2-B beat R2-A by **+2.9 to +4.5**, and by +5.3 to +6.5 on the held-out set.
**2. Spelling unseen words: 0% to 96%.**The first text-training runs reproduced words seen in training 85% of the time but unseen words 0% of the time. The agents traced this to the frozen encoder. A linear probe on Qwen3-0.6B's last layer recovers the full spelling of only 9.5% of unseen words, because a word like "Cedar" reaches the transformer as one or two tokens, not five letters. The fix needs no new module and no change to the tokenizer or encoder. Quoted text is spelled out letter by letter in the prompt:
```a shop sign that says "Cedar" → a shop sign that says "Cedar" (spelled: C e d a r)```bashpython -m pip install -r requirements.txtpython inference.py "A sunlit stone bridge over a calm mountain river" --device auto --seed 42 --output bridge.png# Batch mode (Bash; for PowerShell see DETAILS.md): write a small cases.json, then run it and the route switchescat > cases.json <<'EOF'[{"id": "bridge", "caption": "A sunlit stone bridge over a calm mountain river", "seed": 42}, {"id": "sign", "caption": "A teal enamel sign reading \"OPEN LATE\" in a rainy shop window", "seed": 42}, {"id": "apples", "caption": "three red apples on a wooden table", "seed": 42}]EOFpython inference.py --device auto --cases cases.json --output ./outputspython inference.py --device auto --cases cases.json --count-head off --output ./out-count-offpython inference.py --device auto --cases cases.json --writing-lora off --output ./out-writing-offpython inference.py --device auto --cases cases.json --routing none --output ./out-routing-none```
Training on 1M rendered images with a 20k-word vocabulary plus random letter strings raised exact spelling of unseen words from **0% to 96%** (99% character accuracy).
**3. Routing text to a LoRA keeps composition intact.**Mixing text data into the backbone cost 2.1 to 2.8 PixGenEval points in two separate runs. The agents moved text rendering into a LoRA that loads only for prompts with quoted text. PixGenEval holds at 82.21. After multi-word, multi-region and scene-text data were added, CVTG-2K word accuracy rose from 0.23% to **19.45%**.
### Keeping the gains honest
GenEval-style scores are easy to inflate with data that copies the benchmark's templates, so every gain must also show up on prompts the model never trained on.
- Every training sample whose prompt or image matches any evaluation prompt is removed (33,391 evaluation prompts checked).- The first held-out set turned out to overlap the training compositions (94 of 100 counting prompts). The agents caught this and rebuilt the held-out set around **8 whole COCO classes** that are removed from all training and RL data.- On this held-out set, the released backbone rises from 59.00 to **74.69 (+15.7)**, matching its +15.1 gain on PixGenEval.- On a second held-out set of compositions never seen in training, the R2-B checkpoint raises correct relative position from 34% to 67% and correct color binding from 49% to 89%.
## Training
| Setting | Value ||---|---|| Objective | Flow matching, same loss as pre-training || Optimizer | Muon + AdamW, weight decay 0, grad clip 1.0 || Learning rate | 5e-5, constant || Global batch | 1,024 images / step (32 NPUs) || Steps | 2,500 || Timestep sampling | 90% sigmoid(N(0,1) + ln 2) + 10% uniform || Caption dropout | 10% || Max caption length | 256 tokens || Data | 170,833 images: 26,744 compositional images (teacher-generated, kept only when a GenEval detector verified them), 114,089 public high-quality images (DALL·E 3 dataset, BLIP3o-60k subset, ShareGPT-4o-Image subset), 30,000 OCR-verified text images |
The text LoRA was trained from the released backbone for 5,000 steps on one server. Its data: 1M rendered text images with letter-spelled captions, TextAtlas5M real-world text images, and multi-word, multi-region and scene-text images.
## Inference
### Weights and dependenciesOffline use (local copy of Qwen3-0.6B, no network):
```bashhf download DALabCommunity/Haidass-Image-Instruct --local-dir ./Haidass-Image-Instructcd Haidass-Image-Instructpip install -r requirements.txt# On Ascend NPUs, also install a torch_npu build that matches your PyTorch and CANN versions.export HF_HUB_OFFLINE=1python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --text-encoder /path/to/Qwen3-0.6B --seed 42 --output bridge.png```
| File | Purpose ||---|---|| `dit.safetensors` | Post-trained generation backbone (BF16) || `dit_norm_precision.safetensors` | Small BF16 remainder terms; the script adds them to the normalization weights in FP32 || `writing_lora/` | Text-rendering LoRA (PEFT format), loaded automatically for quoted text || `vae/` | Qwen-Image-2.1 VAE weights and configuration || `config.json` | Backbone, text encoder, sampling and routing configuration || `runtime/` | Model code, prompt routing and spelling annotation || `inference.py` | Command-line and Python entry point || `requirements.txt` | Python dependencies |
The text encoder [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) is downloaded from its official repository on first use. To use a local copy, pass `--text-encoder /path/to/Qwen3-0.6B`.
### Recommended sampling settings
These are the defaults in `config.json`, and all reported scores use them.
| Setting | Value ||---|---|| Resolution | 512 × 512 || Sampler | Euler, 50 steps || Classifier-free guidance (CFG) | 8.0, applied at every step || Timestep shift | 1.0 || Unconditional prompt | EOS token || Compute precision | BF16 autocast; FP32 latent updates || Text LoRA | Loaded automatically when the prompt contains quoted text |```powershell$env:HF_HUB_OFFLINE = '1'python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --text-encoder .\Qwen3-0.6B --seed 42 --output bridge.png```
### Command linePython API:
```bashpython inference.py "A red fox listening at the edge of a frosted field, its tail curled over brown leaves." --seed 71204 --output fox.png```pythonfrom inference import Generatormodel = Generator(device="auto") # downloads Qwen/Qwen3-0.6B on first usewriting_image, writing_info = model.generate( 'A teal enamel sign reading "OPEN LATE" in a rainy shop window', seed=42,)writing_image.save("sign.png")```
| Option | Default | Description ||---|---|---|| `prompt` (positional) | — | Text prompt || `--output` | `output.png` | Output PNG path || `--seed` | `0` | Random seed || `--device` | `auto` | `auto`, `cpu`, `cuda`, `cuda:N`, `npu` or `npu:N`. `auto` picks CUDA, then Ascend NPU, then CPU || `--text-encoder` | `Qwen/Qwen3-0.6B` | Local path or Hugging Face copy of Qwen3-0.6B || `--model` | folder of `inference.py` | Model folder |## Results
### Rendering text| Benchmark | Base (checkpoint `60463`) | **0.1.0** ||---|---:|---:|| PixelGen-rephrased GenEval (2 seed batches, 0–100) | 67.05 | **86.34** || Held-out composition (8 COCO classes unseen in training, 0–100) | 59.00 | **87.94** || Held-out counting (8 unseen classes, exact count) | — | **67.00%** || Original GenEval (seed 42, 0–1) | 0.600 | **0.859** || DPG-Bench (0–100) | 83.98 | **84.28** || OneIG-Bench (EN) Overall (0–100) | 33.18 | **38.71** || OneIG-Bench (EN) Text (0–100) | 0.68 | **34.75** || MJHQ-30K FID ↓ (Sana protocol) | 13.38 | **10.33** || CVTG-2K word accuracy | 0.22% | **45.08%** |
Put the text you want in the image inside quotes:Measured on the whole model under default inference (512 × 512, Euler 50 steps, CFG 8.0, no LLM prompt rewriting): on counting prompts, 8 initial noises each run 5 of the 50 steps and the counting head reads step-5 features to pick one candidate to finish to step 50; all other prompts use a single draw.
```bashpython inference.py 'A teal enamel sign reading "OPEN LATE" in a rainy shop window' --seed 41 --output sign.png```## Comparison
When the prompt contains quoted text (`"…"`, `“…”`, `'…'`, `‘…’`, `「…」` or `『…』`), the script automatically:| Model | Params | Resolution | Inference mode | BLIP3o-60K | GenEval ↑ | DPG-Bench ↑ ||---|---:|---:|---|---|---:|---:|| RG-T2I-L/16 (2026-10) | 912M | 512 × 512 | single draw | Yes (120K mix) | 0.89 | 87.1 || MiniT2I-L/16 (2026-06) | 912M | 512 × 512 | single draw | Yes (120K mix) | 0.883 | 85.9 || AMD Nitro-P (2026-11) | 679M | 512 × 512 | single draw | Yes (120K mix) | 0.88 | 86.33 || UNIFIED-L (2026-11) | 554M | 256 × 256 | single draw | Yes | 0.878 | 84.8 || HiRAE-24 (2026-09) | 875M | 256 × 256 | single draw | Yes | 0.877 | 86.35 || JuZhou 1.0 (2026-06) | 385M | 1024 × 1024 | single draw | No | 0.70 | — || NanoGen (FLUX.2-VAE, 2026-06) | 612M | 256 × 256 | single draw | No | — | 84.1 || **Haidass-Image-Instruct 0.1.0 (2026-11)** | **0.6B** | **512 × 512** | **counting 8-pick; others single draw** | **Yes (7,190 near-dups removed)** | **0.859** | **84.28** |
1. loads the text LoRA from `writing_lora/` on top of the backbone, and2. appends a letter-by-letter spelling after each quoted span, for example `"OPEN LATE" (spelled: O P E N / L A T E)`.Models ≤1B published on or after 2026-05-30 (generator parameters; external models use single-draw generation without prompt rewriting). BLIP3o-60K contains 7,190 captions nearly identical to GenEval prompts; the five models listed first (0.877–0.89) fine-tuned on it, and we removed those captions before training.
Write prompts normally. Prompts without quotes run on the backbone alone.## Limitations
### Python- **English text and routing trigger.** Writing supports English text; for standard carriers (`sign`, `poster`, `reads`, `says`, `labeled`, `cover`), quoted text must sit in the same sentence as the carrier word, and unquoted document prompts do not trigger the writing route.- **Digits, punctuation, and complex scenes with text.** CVTG-2K word accuracy is `7.69%` for words with digits or punctuation vs `49.59%` for letters-only words. On complex multi-object scenes with quoted text, prioritizing lettering can shrink the main subject (`84.28` whole-model DPG-Bench vs `84.58` same-batch backbone; 70 quoted-text DPG prompts take the writing route and 35 take the counting route); pass `--writing-lora off` when scene composition matters more than text.- **Counting head scope.** Predicts classes `0–6` and `7+` at 50 sampling steps only (other step counts fall back to a single draw); gains on long descriptive prompts (~132 words, PixelGen-rephrased GenEval counting: `+3.13` pp, `95% CI [−1.82, +8.07]`) are not significant, and a misparsed count `N` selects for that wrong count.- **Route priority and cross-device seeds.** When a prompt has both quoted text and a parsed count, the writing route takes precedence. Ascend NPU, CUDA, and CPU use different initial-noise generators, so the same seed produces different images across devices.
Run from the model folder, or add it to `sys.path`:## Demo
```pythonfrom inference import GeneratorLive Gradio Space by **HanWangTJU**: https://huggingface.co/spaces/HanWangTJU/Haidass-Image-App (currently runs 0.0.1; will serve the full 0.1.0 model once updated to load the 0.1.0 weights and counting head).
generator = Generator(".", device="auto") # model folder, deviceimages = generator.generate_batch( ["A small canoe tied beside an untouched lake, with mirrored spruce silhouettes."], [0], # one seed per prompt)images[0].save("canoe.png")```## Version history
`generate_batch` takes a list of prompts and one seed per prompt, and returns PIL images. Quoted and unquoted prompts must go in separate batches, because a batch runs either with or without the text LoRA. Pass `steps=` to override the number of sampling steps.- **0.1.0 (2026-11):** Final release — retrained from `Haidass-Image-Base-v1_0.6B_512px` on sentence-level cleaned data, followed by Flow-GRPO reinforcement learning (merged EMA weights), the writing LoRA (EMA), and counting head under unified routing.- **0.0.1 (preview, git tag `v0.0.1`):** Archived preview whose training data overlapped evaluation prompts; its scores are retired in favor of 0.1.0.
## Citation
```bibtex@misc{haidass-image-instruct, author={DALabCommunity}, title={Haidass-Image-Instruct: A 0.6B Text-to-Image Model Post-Trained by Recursive Self-Improvement Agents on Ascend 910B}, year={2026}, url={https://huggingface.co/DALabCommunity/Haidass-Image-Instruct}, note={0.0.1 preview. Post-trained from Haidass-Image-Base-v1_0.6B_512px on 64 Ascend 910B NPUs} note={Version 0.1.0. Post-trained from Haidass-Image-Base-v1_0.6B_512px on 64 Ascend 910B NPUs}}```
For architecture, component breakdowns, the counting `k` curve, training hyperparameters, agent post-training workflow, evaluation protocols, full PowerShell commands, runtime, and complete comparison tables, see [DETAILS.md](DETAILS.md).13 unmodified lines141516171819171821192023212225232427252629272831293033313235363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621633334353637383940414243444546471661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971984849502012022032045152535420720820921021121221321421521621721821922022122222322422522622722822923023123255565758592346061236237626364656667686970712402412422432442452462477273249747576777879808182838485251868725325425588892579091929394959697989910025926010110226210310426410510610710810926611011126826911211327127227327427527627711411527911611711811912012112212312412512628712712812913013113 unmodified lines- recursive-self-improvement---
<div align="center"> <img src="assets/logo.png" width="560"/></div><div align="center"><img src="assets/logo.png" width="560"/></div>
[English](README.md) · **简体中文**# Haidass-Image-Instruct 0.1.0
[English](README.md) · **简体中文** · [完整技术细节](DETAILS_zh.md)
*发布版模型生成的 48 张图片,512 × 512,使用下文的推荐采样参数;文字类图片自动加载了写字 LoRA。***Haidass-Image-Instruct 0.1.0** 是一个 512 × 512 的单一完整 0.6B 文生图模型,从 [Haidass-Image-Base-v1_0.6B_512px](https://huggingface.co/DALabCommunity/Haidass-Image-Base-v1_0.6B_512px)(检查点 `60463`)在华为昇腾 910B NPU 上后训练得到。模型集成 flow-matching DiT 主干、用于英文文字渲染的写字 LoRA,以及用于物体数量筛选的计数小头,搭配冻结的 [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) 文本编码器。默认推理会根据每条提示自动选择对应路径。
在线DEMO: https://huggingface.co/spaces/HanWangTJU/Haidass-Image-App
## 模型介绍## 快速开始
**Haidass-Image-Instruct 0.0.1(预览版)** 是一个生成主干参数量约 0.6B 的轻量文生图模型,从 [Haidass-Image-Base-v1_0.6B_512px](https://huggingface.co/DALabCommunity/Haidass-Image-Base-v1_0.6B_512px) 后训练得到。整个后训练由一套自主运行的**递归自我改进(Recursive Self-Improvement,RSI)**智能体系统完成。后训练把 PixGenEval 从 **67.05 提到 82.21**,在用训练中完全没有出现过的物体类别出的留出题上,提升同样成立。在原始 GenEval 上得分 **0.82**,超过 Janus-Pro-7B、Stable Diffusion 3(8B)、FLUX.1-dev 和 DALL·E 3。另配一个按需加载的写字 LoRA,能写出清晰的英文文字。在 Python 3.11+ 环境中进入下载好的模型目录运行以下命令(`--device auto` 依次检测 CUDA、昇腾 NPU、CPU;首次使用会自动下载 `Qwen/Qwen3-0.6B`;`cases.json` 字段说明与完整 PowerShell 命令见 [DETAILS_zh.md](DETAILS_zh.md)):
## 模型架构`requirements.txt` 从 PyPI 安装标准 PyTorch(Windows 上是 CPU 版)。用 NVIDIA 显卡时先按 CUDA 版本装好对应的 PyTorch;用昇腾 NPU 时在已装 `torch_npu` 的环境里安装其余依赖。
| 组件 | 设置 ||---|---|| 生成主干 | 基于 Qwen-Image-2.1 的单流扩散 Transformer,flow matching 训练 || 主干规模 | 34 层,9 个注意力头 × 128 维,约 5.98 亿参数 || 文本编码器 | [Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B),冻结,取最后一层输出,最长 256 token || VAE | Qwen-Image-2.1 VAE(64 通道潜变量),冻结 || 写字 LoRA | rank 128 / alpha 256,作用于注意力和前馈投影层;只在提示里有引号文字时加载 || 分辨率 | 512 × 512 |
## 特色
- **全程在华为昇腾 NPU 上完成。** 数据生成、训练、LoRA 训练和全部评测,都在 8 台 Atlas A2 服务器(64 张昇腾 910B)上完成。- **0.6B 也能精确控制构图。** 数量、上下左右的位置、颜色和物体的对应都能画对,PixGenEval 82.21。- **提升能泛化。** 在只用训练数据里完全剔除的物体类别出的题上,同样提高 15.7 分。- **不加模块就能写字。** 把引号里的字逐个字母拆写后交给冻结的编码器,写字 LoRA 只在需要时加载。- **自我改进的训练过程。** 每个实验都由智能体系统自己规划、执行、评判和改进,见[递归自我改进](#递归自我改进)。
## 评测结果
| 评测 | 原模型 | **Haidass-Image-Instruct** | 提升 ||---|---:|---:|---:|| **PixGenEval¹** | 67.05 | **82.21** | **+15.2** || 留出组合题² | 59.00 | **74.69** | **+15.7** || MJHQ-30K FID ↓ | 13.38 | **10.20** | **−3.18** || MJHQ-30K CLIP 分数 | 25.35 | **26.08** | +0.73 || OneIG-Bench(英文)文字 | 0.68 | **17.97** | **+17.3** || CVTG-2K 词准确率 | 0.22% | **19.45%** | **88 倍** || 英文大字(50 题,完全一致才算对) | 0 / 50 | **28 / 50** | **+28** || 没见过的单词拼写探针(100 张) | 0% | **88%** | **+88 个百分点** || OneIG-Bench(英文)对齐 | 80.11 | 80.73 | +0.62 || OneIG-Bench(英文)画风 | 39.46 | 40.27 | +0.81 || DPG-Bench | 84.02 | 83.67 | 保持 |
¹ 把 GenEval 的 553 道题改写成详细描述,题目取自 [PixelGen](https://arxiv.org/abs/2602.02493) 发布的版本;打分方式和 GenEval 相同。² 400 题 × 4 张,只用 8 个 COCO 类别出题(长颈鹿、自行车、雨伞、时钟、泰迪熊、苹果、消防栓、行李箱),这 8 类从所有训练数据中整类剔除。见[防止背题](#防止背题)。
所有分数都用下文的推荐采样参数,提示原样输入,不做改写。写字 LoRA 只在提示带引号时加载。MJHQ FID / CLIP 和留出组合题在主干上测得。
| 评测 | 原模型 | 只用主干 | 主干 + 按需加载的写字 LoRA ||---|---:|---:|---:|| PixGenEval | 67.05 | 82.16 | **82.21** || DPG-Bench | 84.02 | 83.79 | 83.67 || OneIG 文字 | 0.68 | 0.38 | **17.97** || CVTG-2K 词准确率 | 0.22% | 0.23% | **19.45%** || 英文大字 | 0 / 50 | 0 / 50 | **28 / 50** || 没见过的单词拼写探针 | 0% | 0% | **88%** |
### GenEval 对比
其他模型只公布原始 GenEval,所以这张表用的是**原始 GenEval** 提示下的总分。除我们以外,每个数字都取自所列论文或技术报告。
| 模型 | 参数量 | 原始 GenEval ||---|---:|---:|| **Haidass-Image-Instruct(我们,512 px)** | **0.6B** | **0.82** || Janus-Pro-7B | 7B | 0.80 || Stable Diffusion 3(depth 38,DPO) | 8B | 0.74 || Lumina-Image 2.0 | 2.6B | 0.73 || Stable Diffusion 3.5 Large | — | 0.71 || FLUX.1-schnell | 12B | 0.71 || DALL·E 3 | — | 0.67 || FLUX.1-dev | 12B | 0.66 || SANA-1.6B | 1.6B | 0.66 || SANA-0.6B | 0.6B | 0.64 || Hunyuan-DiT | 1.5B | 0.63 || Stable Diffusion 3 Medium | 2B | 0.62 || SDXL | 2.6B | 0.55 || PixArt-Σ(512 px) | 0.6B | 0.52 || PixArt-α(512 px) | 0.6B | 0.48 |
来源:- Janus-Pro-7B、SD3.5 Large、FLUX.1-dev、SD3 Medium:[Qwen-Image 技术报告,表 4](https://arxiv.org/abs/2508.02324);Janus-Pro-7B 与 [Janus-Pro 原文](https://arxiv.org/abs/2501.17811) 一致- Stable Diffusion 3(8B)、DALL·E 3:[Esser et al., 2024,表 5](https://arxiv.org/abs/2403.03206)- Lumina-Image 2.0:[Lumina-Image 2.0,表 4](https://arxiv.org/abs/2503.21758)- FLUX.1-schnell、SANA-1.6B、SANA-0.6B、Hunyuan-DiT、PixArt-Σ、PixArt-α:[SANA,表 7 和表 10](https://arxiv.org/abs/2410.10629)- SDXL:[GenEval,表 2](https://arxiv.org/abs/2310.11513)
## 递归自我改进
整个后训练由一个**经理智能体**和若干**执行智能体**自主完成,在 8 台昇腾服务器上用了约两天。经理智能体既改进模型,也在每一轮之后改进自己的工作方式。后一点就是「递归」的含义。
```mermaidflowchart LR A[逐个部件诊断] --> B[规划实验<br/>事先写好<br/>成功 / 失败判定规则] B --> C[把简报派给<br/>执行智能体] C --> D[执行智能体在 64 张 NPU 上<br/>造数据 · 训练 · 评测] D --> E[公开评测<br/>+ 留出题打分] E --> F[经理智能体评审结果<br/>更新经验看板] F --> G[教训栏:<br/>记录智能体自己<br/>工作方式的问题] G -->|更新简报、规划、汇报<br/>前的核对清单| B F -->|下一个实验| A H[空闲监视<br/>任一台空闲 30 分钟] -.唤醒.-> F```
### 循环怎么运作
- **经理智能体**:规划实验,写自带全部上下文的简报并派出;把每个回报的数字对回原始结果文件和样图;决定下一步。- **执行智能体**:在 8 × 8 张昇腾 910B 上造数据、训练、评测。- **事先定好的判定规则**:每个实验开跑前写明怎样算成功,以下三条必须同时满足: 1. 目标指标上涨:PixGenEval +1.0,或留出大字题 +5 个百分点; 2. 留出组合题的涨幅至少是主榜的一半; 3. 守线不破:DPG 降不超过 1,OneIG 对齐降不超过 1,FID 升不超过 1.0。- **经验看板**:每个成功和失败都连同完整条件记下来。新想法和过去某次失败相似时,必须先写清这次的条件哪里不同。- **教训栏(递归的那一环)**:经理智能体记录自己工作方式上的问题。例如:简报没写清楚,执行者停下来等确认;没先实测老师模型的生成速度就定了数据量;把假设当成结论汇报。每条教训变成一条核对项,之后每次写简报、定计划、做汇报之前都逐条过一遍。- **空闲监视**:每 10 分钟检查一次集群,任何一台服务器的 NPU 空闲满 30 分钟就唤醒经理智能体派活,机器不等智能体。
看板一共记录了 **29 个训练和推理实验:10 个达到事先定的成功标准,19 个没有达到**。另有 2 项流程提速:老师模型生成数据快 1.7 倍,评测快 2.2 倍。每个失败都连同完整条件保留下来,用来指导下一轮。
### 每轮提升
| 轮次 | 改了什么 | 为什么 | PixGenEval ||---|---|---|---:|| 原模型 | — | — | 67.05 || S4 | 单机,学习率 5e-5,1,000 步 | 对照实验中学习率减半比 1e-4 高 2.54 分 | 70.72 || S6 | S4 + 多练高噪声的时间步分布 | 诊断发现布局在高噪声段决定,原模型很少练这一段 | 72.60 || R2-A | 4 台机器,每步 1,024 张,新组合数据,1,000 步 | 同类后训练用的图片曝光量多得多 | 76.31 || R2-B | R2-A + 多练高噪声,1,500 步 | 种子和数据顺序与 R2-A 完全相同,提升只来自这一项改动 | 80.02 || R2-B-ext | 续训到 2,500 步(**发布的主干**) | 1,500 步时仍在涨;按事先定的规则选出 | **82.16** || + 写字 LoRA | 按需加载的写字 LoRA,5,000 步(**发布的整套系统**) | 写字数据并进主干训练会拖累构图 | **82.21** |
### 智能体自己做出的发现
**1. 多练高噪声:+2.9~4.5 分。**开训之前,智能体先逐个部件验证。老师模型的图经我们的 VAE 编码再解码,GenEval 不降,排除了 VAE。逐张看失败图发现,大多数「位置」题错在布局:物体重叠,或该左右排却画成上下排。310 张失败图里真正左右画反的只有 24 张。物体数量和布局在高噪声段决定,而原训练抽到 t > 0.9 的概率只有 1.4%。智能体还发现,起点检查点早先的一次微调尝试约 75% 的训练信号落在低噪声段,所以那次尝试 GenEval 只涨了 1.36。改法是时间步按 90% sigmoid(N(0,1) + ln 2) 加 10% 均匀分布抽样。单机实验里 PixGenEval 提高 1.88 分(S4 → S6);四台机器同样步数下,R2-B 比 R2-A 高 **2.9~4.5 分**,留出题高 5.3~6.5 分。
**2. 没见过的单词:从 0% 写对到 96%。**最初的写字训练里,训练过的词能写对 85%,没见过的词 0%。智能体把原因定位到冻结的编码器:在 Qwen3-0.6B 最后一层做线性探针,没见过的词只有 9.5% 能完整读出拼写,因为 "Cedar" 这样的词进到 Transformer 时只是一两个 token,不是五个字母。解决办法不加模块,也不改分词器和编码器,只在提示里把引号中的字逐个字母拆写:
```a shop sign that says "Cedar" → a shop sign that says "Cedar" (spelled: C e d a r)```bashpython -m pip install -r requirements.txtpython inference.py "A sunlit stone bridge over a calm mountain river" --device auto --seed 42 --output bridge.png# 批量(Bash 写法,PowerShell 见 DETAILS_zh.md):先写一个小的 cases.json,再跑批量和三个开关cat > cases.json <<'EOF'[{"id": "bridge", "caption": "A sunlit stone bridge over a calm mountain river", "seed": 42}, {"id": "sign", "caption": "A teal enamel sign reading \"OPEN LATE\" in a rainy shop window", "seed": 42}, {"id": "apples", "caption": "three red apples on a wooden table", "seed": 42}]EOFpython inference.py --device auto --cases cases.json --output ./outputspython inference.py --device auto --cases cases.json --count-head off --output ./out-count-offpython inference.py --device auto --cases cases.json --writing-lora off --output ./out-writing-offpython inference.py --device auto --cases cases.json --routing none --output ./out-routing-none```
用 100 万张渲染图(2 万个常用词加随机字母串)训练后,没见过的词整词写对的比例从 **0% 升到 96%**,字符准确率 99%。
**3. 把写字放进 LoRA,构图能力不受影响。**两次独立实验里,把写字数据并进主干训练都让 PixGenEval 掉了 2.1~2.8 分。智能体于是把写字单独做成 LoRA,只在提示带引号时加载。PixGenEval 保持在 82.21;补充多词、多区域和场景文字数据后,CVTG-2K 词准确率从 0.23% 升到 **19.45%**。
### 防止背题
GenEval 一类的分数很容易被照着题型造的数据拉高,所以每一项提升都必须在模型没训练过的题上同样出现。
- 训练数据里,提示或图片和任何评测题相同的样本全部剔除,共比对 33,391 条评测提示。- 第一版留出题后来被发现和训练数据里的组合大量重叠(计数题 100 道里有 94 道)。智能体发现后改为整类留出:**8 个 COCO 类别**从所有训练数据和强化学习数据中剔除,只用这 8 类重新出题。- 在这套留出题上,发布的主干从 59.00 升到 **74.69(+15.7)**,和 PixGenEval 上的 +15.1 相当。- 在另一套训练中没出现过的组合题上,R2-B 检查点把位置画对的比例从 34% 提到 67%,颜色和物体对应正确的比例从 49% 提到 89%。
## 训练设置
| 项目 | 设置 ||---|---|| 训练目标 | Flow matching,与预训练相同的损失 || 优化器 | Muon + AdamW,权重衰减 0,梯度裁剪 1.0 || 学习率 | 5e-5,恒定 || 全局批量 | 每步 1,024 张(32 张 NPU) || 步数 | 2,500 || 时间步抽样 | 90% sigmoid(N(0,1) + ln 2) + 10% 均匀 || 描述置空比例 | 10% || 描述最大长度 | 256 token || 数据 | 共 170,833 张:组合图 26,744 张(老师模型生成,GenEval 检测器判对才保留);公开高质量图 114,089 张(DALL·E 3 数据集、BLIP3o-60k 部分、ShareGPT-4o-Image 部分);经 OCR 核对的文字图 30,000 张 |
写字 LoRA 从发布的主干出发,在单台服务器上训练 5,000 步。数据包括:100 万张描述带逐字母拆写的渲染文字图、TextAtlas5M 的真实含字图,以及多词、多区域和场景文字图。
## 推理方法与��数
### 下载与依赖离线用法(使用本地 Qwen3-0.6B,不联网):
```bashhf download DALabCommunity/Haidass-Image-Instruct --local-dir ./Haidass-Image-Instructcd Haidass-Image-Instructpip install -r requirements.txt# 在昇腾 NPU 上运行时,另装与 PyTorch、CANN 版本匹配的 torch_npu。export HF_HUB_OFFLINE=1python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --text-encoder /path/to/Qwen3-0.6B --seed 42 --output bridge.png```
| 文件 | 用途 ||---|---|| `dit.safetensors` | 后训练后的生成主干权重(BF16) || `dit_norm_precision.safetensors` | 少量 BF16 余项,脚本在 FP32 下把它们加回归一化层权重 || `writing_lora/` | 写字 LoRA(PEFT 格式),提示带引号时自动加载 || `vae/` | Qwen-Image-2.1 VAE 权重和配置 || `config.json` | 主干、文本编码器、采样参数和 LoRA 加载规则的配置 || `runtime/` | 模型代码、提示路由和逐字母拆写 || `inference.py` | 命令行和 Python 调用入口 || `requirements.txt` | Python 依赖 |
文本编码器 [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) 在第一次运行时从其官方仓库下载。已有本地副本时用 `--text-encoder /path/to/Qwen3-0.6B` 指定。
### 推荐采样参数
以下是 `config.json` 里的默认值,所有公布的分数都用这组参数。
| 参数 | 设置 ||---|---|| 分辨率 | 512 × 512 || 采样器 | Euler,50 步 || 无分类器引导(CFG) | 8.0,每一步都使用 || Timestep shift | 1.0 || 无条件提示 | EOS token || 计算精度 | BF16 autocast;FP32 latent 更新 || 写字 LoRA | 提示带引号时自动加载 |```powershell$env:HF_HUB_OFFLINE = '1'python inference.py "A sunlit stone bridge over a calm mountain river" --device auto --text-encoder .\Qwen3-0.6B --seed 42 --output bridge.png```
### 命令行Python 接口:
```bashpython inference.py "A red fox listening at the edge of a frosted field, its tail curled over brown leaves." --seed 71204 --output fox.png```pythonfrom inference import Generatormodel = Generator(device="auto") # 首次使用会自动下载 Qwen/Qwen3-0.6Bwriting_image, writing_info = model.generate( 'A teal enamel sign reading "OPEN LATE" in a rainy shop window', seed=42,)writing_image.save("sign.png")```
| 参数 | 默认值 | 说明 ||---|---|---|| `prompt`(位置参数) | — | 提示词 || `--output` | `output.png` | 输出 PNG 路径 || `--seed` | `0` | 随机种子 || `--device` | `auto` | `auto`、`cpu`、`cuda`、`cuda:N`、`npu` 或 `npu:N`;`auto` 依次尝试 CUDA、昇腾 NPU、CPU || `--text-encoder` | `Qwen/Qwen3-0.6B` | Qwen3-0.6B 的本地路径或 Hugging Face 仓库 || `--model` | `inference.py` 所在目录 | 模型目录 |## 评测结果
### 写字| 评测 | 底模(检查点 `60463`) | **0.1.0** ||---|---:|---:|| PixelGen 改写版 GenEval(两批种子,0–100) | 67.05 | **86.34** || 留出组合题(训练未见的 8 个 COCO 类别,0–100) | 59.00 | **87.94** || 留出计数题(8 个未见类别,恰好画对数量) | — | **67.00%** || 原版 GenEval(种子 42,0–1) | 0.600 | **0.859** || DPG-Bench(0–100) | 83.98 | **84.28** || OneIG-Bench(英文)五项平均(0–100) | 33.18 | **38.71** || OneIG-Bench(英文)文字(0–100) | 0.68 | **34.75** || MJHQ-30K FID ↓(Sana 协议) | 13.38 | **10.33** || CVTG-2K 词准确率 | 0.22% | **45.08%** |
把要写在图上的字放进引号:以上均在完整模型默认推理下测得(512 × 512,Euler 50 步,CFG 8.0,不使用大模型改写提示):遇到计数提示时,8 个初始噪声各运行 50 步中的前 5 步,计数小头读取第 5 步特征并选出 1 个候选续跑至第 50 步;其余提示均为单张生成。
```bashpython inference.py 'A teal enamel sign reading "OPEN LATE" in a rainy shop window' --seed 41 --output sign.png```## 与 ≤1B 模型对比
提示里有引号文字时(`"…"`、`“…”`、`'…'`、`‘…’`、`「…」` 或 `『…』`),脚本会自动:| 模型 | 参数量 | 分辨率 | 推理模式 | BLIP3o-60K | GenEval ↑ | DPG-Bench ↑ ||---|---:|---:|---|---|---:|---:|| RG-T2I-L/16 (2026-10) | 912M | 512 × 512 | 单张生成 | 是(120K 混合集) | 0.89 | 87.1 || MiniT2I-L/16 (2026-06) | 912M | 512 × 512 | 单张生成 | 是(120K 混合集) | 0.883 | 85.9 || AMD Nitro-P (2026-11) | 679M | 512 × 512 | 单张生成 | 是(120K 混合集) | 0.88 | 86.33 || UNIFIED-L (2026-11) | 554M | 256 × 256 | 单张生成 | 是 | 0.878 | 84.8 || HiRAE-24 (2026-09) | 875M | 256 × 256 | 单张生成 | 是 | 0.877 | 86.35 || JuZhou 1.0 (2026-06) | 385M | 1024 × 1024 | 单张生成 | 否 | 0.70 | — || NanoGen (FLUX.2-VAE, 2026-06) | 612M | 256 × 256 | 单张生成 | 否 | — | 84.1 || **Haidass-Image-Instruct 0.1.0 (2026-11)** | **0.6B** | **512 × 512** | **计数 8 选 1;其余单张** | **是(去除 7,190 条近重复)** | **0.859** | **84.28** |
1. 在主干上加载 `writing_lora/` 里的写字 LoRA;2. 在每段引号文字后补上逐字母拆写,例如 `"OPEN LATE" (spelled: O P E N / L A T E)`。仅收 2026-05-30 及以后发表的 ≤1B 模型(仅计视觉生成主干参数;外部模型均为单张生成且无提示改写)。BLIP3o-60K 包含 7,190 条与 GenEval 提示几乎相同的描述;表中前 5 个模型(0.877–0.89)均在其上做过微调,而我们在训练前删去了这些描述。
照常写提示即可。不带引号的提示只用主干生成。## 局限
### Python 调用- **仅支持英文写字与触发规则。** 写字面向英文;对常见载体与写字线索词(`sign`、`poster`、`reads`、`says`、`labeled`、`cover`),引号文字需与载体词位于同一句,不带引号的文档提示也不会触发写字路径。- **数字、标点与复杂带字场景。** CVTG-2K 上含数字或标点的词准确率为 `7.69%`,纯字母词为 `49.59%`。在含引号文字的复杂多物体场景中,优先保证字形清晰可能压缩主体画面(完整模型 DPG-Bench 为 `84.28`,同批纯主干为 `84.58`;70 道带引号文字的 DPG 题走写字路径,另有 35 道走计数路径);更看重画面构图时可传入 `--writing-lora off`。- **计数小头适用范围。** 仅在 50 步采样时预测 `0–6` 和 `7+` 共 8 类(其他步数回退为单张生成);长描述计数题(约 132 词,PixelGen 改写版 GenEval 计数 `+3.13` 个百分点,95% 区间 `[−1.82, +8.07]`)未达显著,且数量解析出错时会按错误目标 `N` 选图。- **路由优先级与跨设备种子差异。** 提示同时含引号文字与可解析数量时,写字路径优先。昇腾 NPU、CUDA 与 CPU 的初始噪声生成器不同,同一种子在不同设备上会生成不同图像。
在模型目录下运行,或把模型目录加进 `sys.path`:## 在线演示
```pythonfrom inference import Generator由 **HanWangTJU** 搭建的在线 Gradio Space:https://huggingface.co/spaces/HanWangTJU/Haidass-Image-App (当前运行 0.0.1,更新以加载 0.1.0 权重与计数小头后将运行完整 0.1.0 模型)。
generator = Generator(".", device="auto") # 模型目录、设备images = generator.generate_batch( ["A small canoe tied beside an untouched lake, with mirrored spruce silhouettes."], [0], # 每条提示一个种子)images[0].save("canoe.png")```## 版本记录
`generate_batch` 接收一组提示和逐条对应的种子,返回 PIL 图片。带引号和不带引号的提示要分成不同的批次,因为同一批要么全部加载写字 LoRA,要么全部不加载。用 `steps=` 可以改采样步数。- **0.1.0(2026-11):** 正式版本——从 `Haidass-Image-Base-v1_0.6B_512px` 在逐句清洗数据上重训,经 Flow-GRPO 强化学习(合并 EMA 权重),并与写字 LoRA(EMA)及计数小头集成,按提示自动选用。- **0.0.1(预览版,git 标签 `v0.0.1`):** 早期预览版本,其训练数据与评测提示存在重叠;原分数已停用并由 0.1.0 替代。
## 引用
```bibtex@misc{haidass-image-instruct, author={DALabCommunity}, title={Haidass-Image-Instruct: A 0.6B Text-to-Image Model Post-Trained by Recursive Self-Improvement Agents on Ascend 910B}, year={2026}, url={https://huggingface.co/DALabCommunity/Haidass-Image-Instruct}, note={0.0.1 preview. Post-trained from Haidass-Image-Base-v1_0.6B_512px on 64 Ascend 910B NPUs} note={Version 0.1.0. Post-trained from Haidass-Image-Base-v1_0.6B_512px on 64 Ascend 910B NPUs}}```
模型架构、各部分贡献、计数 `k` 曲线、训练超参数、智能体后训练流程、评测协议、完整 PowerShell 命令、耗时与硬件及完整对比表见 [DETAILS_zh.md](DETAILS_zh.md)。1234567891011121314151617181920212223242526271a27024dfac4eddc49bd1159aae3e7a6acf37eb3ec2167e12e2b6e4439f9052d .gitattributesf5ef0eb2b3db25a86eaf66f7b82428d3a86a5177b6cdeaa778495dd1075e06eb config.json9cacf29b6df3e108cce2ffe1d8ab909aa44d4d76f38607747a56d087f17749ba counting_head/__init__.py931fab555c805a01ef79562c3ff96d166483fa86570e024daf3e7138ba9649dc counting_head/count_n_rank.py15b5d049659485746564a7fb8b7607ce1183c1416d0e9bf9aa95a604c94ebd21 counting_head/count_parser.pyd5d475d4ce2a08591f9a83d4f3807b73c2bb89bc48843e0c130f1c6f26c10764 counting_head/count_vocab.pyda2efcde191e1aff9a26531fb63b8bcc334d821c77e12b052092fd7f964fd860 counting_head/head.npzcaee736c38dbd7d8275c009ac1be4fd60c10a42d76d6411964c5ebec361a10eb counting_head/sampling.py67d115b32f1699aa5994edeff3e59812a90ec4da90f0d93c8d85b4ed86260d5f dit.safetensorsc926d6af6853e41c42aab503a263483b1aacba34ee6fcef7372c20a059643a1e inference.py5a913a21b267a9fafe0fe62ce20d965d3c951e6cf1a7f366a32414dc810cfa22 requirements.txt0c3143afe2651a2bd3b02b24a4ffc7161d2e725564b17a556c39d44c7030a480 runtime/__init__.pyd40e8397740f136e7aa98fdea5eea129e1caa92e6b47170809af12bd43e8fd3b runtime/add_spelling.py8fbb67844b805daa39e3533756852f8d0fdc3f673c506de1245273233722aa7e runtime/add_spelling_v2.pye9ebde2023d5bb7a2e68dbffc12ce8883fcaa202a7d9d6e8746ccd3d74d3583e runtime/model.py9de2fc13763349f6cd50cf4d6950dd1f233b181f8b23672e271288d60aca1d1c runtime/normalization.pyaeab64258cabcbad4c18e958aab400fc571dab602acd8b40d5214d16cb894859 runtime/npu_attention.py1711362cf6b4cf9a315f59407bc4188ec586a568c2df13791ca877ed50fe5431 runtime/prompt_routing.py1dee0b20b3ea4b4aab21bc83901a93efba5ca9cc182a48ca195f0e04ccdc26d3 runtime/qwenimage21_transformer.py6bd8d9b28f09d6c42533bcf116972383a2668287059bba38d6e915033b983079 runtime/qwenimage21_vae.py92ac2467368813d31047a196e85c9ba9e1f7d3794c8dae6aa9d4ef069460900c runtime/routing.pya7df1f1644a00b23a0d1de5763eafc3ca80ca069a3330a3b34694925137e9cf8 runtime/sequence.py5875ca0cbc12e1f8d8486aab9bc269c9f59de41b0f719d73c77e8e8cb8a9ff24 runtime/spelling.py9785d527b278cb8b210e9f48a8028d92a4190968ce7e24c8fc85d9d1b82f6ba2 vae/config.jsona07a1b7c4ee2966a1b3bdc37de9b4f983d56937e46619f709a80b6e490675417 vae/diffusion_pytorch_model.safetensors73536b716b65c6fd2bcf54a0c7e95dd8f8a3b739d63bf74836d13d6de889b8e7 writing_lora/adapter_config.json055be94f809c4e304407a789b4b8ffec98c2dc04ca62bb5f4a5bbce8ce1d05f0 writing_lora/adapter_model.safetensors34 unmodified lines3536373838394041424344424546474834 unmodified lines "timestep_shift": 1.0, "cfg_lower": 0.0, "cfg_upper": 1.0, "latents": "standard_normal" "latents": "standard_normal", "cfg_norm": "none", "writing_cfg": 8.0, "writing_cfg_norm": "none" }, "routing": { "writing_adapter": "writing_lora", "trigger": "quoted_text", "trigger": "display_text_routing", "spelling": "evaluation" }}1"""Prompt-only counting route for Haidass-Image-Instruct."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Float64 target-count ranking shared by validation and inference."""
import numpy as np
TIE_SEED = 683
def log_prob_from_state(features, state): with np.errstate(under='ignore'): x = np.asarray(features, dtype=np.float64).reshape(len(features), -1) x = (x - state['scaler_mean']) / state['scaler_scale'] hidden = np.maximum(x @ state['w1'] + state['b1'], 0.) logits = hidden @ state['w2'] + state['b2'] delta = logits - logits.max(axis=1, keepdims=True) exp_delta = np.exp(delta) # Remove one maximal term before summing. log1p preserves the tail # even when 1 + tail would round to 1 in float64. exp_delta[np.arange(len(x)), logits.argmax(axis=1)] = 0. log_probability = delta - np.log1p(exp_delta.sum(axis=1, keepdims=True)) if not np.isfinite(log_probability).all(): raise ValueError('Non-finite count-head log probabilities') full = np.full((len(x), 8), -np.inf, dtype=np.float64) full[:, state['classes']] = log_probability return full
def select_index(scores, draw_seed): scores = np.asarray(scores, dtype=np.float64) tied = np.flatnonzero(scores == scores.max()) if len(tied) == 1: return int(tied[0]) rng = np.random.default_rng(np.random.SeedSequence([TIE_SEED, int(draw_seed)])) return int(rng.choice(tied))
class CountRanker: def __init__(self, path): with np.load(path, allow_pickle=False) as state: self.layer = int(state['feature_layer']) self.step = int(state['feature_step']) self.state = {key: state[key].astype(np.float64) for key in ('scaler_mean', 'scaler_scale', 'w1', 'b1', 'w2', 'b2')} self.state['classes'] = state['classes'].astype(int)
def log_prob(self, features): return log_prob_from_state(features, self.state)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Conservative count noun-phrase grammar, frozen before benchmark inspection.
Runtime imports only the shared static vocabulary. It has no benchmark routes,template prefixes, class combinations, annotations, or corpus-derived rules.Recognizes one unique exact quantity + 0..3 adjective tokens + COCO noun phrase."""import reimport unicodedatafrom .count_vocab import FORMS, UNIT_FORMS
NUMBER_WORDS = dict(zip('one two three four five six seven eight nine ten eleven twelve'.split(), range(1, 13)))ADJECTIVES = frozenset('''adult adorable aged ancient angry antique artificial athletic attractive baby beautiful beige big black blank blue blurry bold brass brave bright broad broken bronze brown calm ceramic cheerful clean clear colorful colourful compact concrete cool cotton crowded curved cute dark delicate dense detailed different dirty distant distinct double dried dry dull eager elegant enormous expressive extra fake fancy fast fat female fierce fine flat fluffy folded fresh friendly frozen full funny fuzzy giant glossy golden gray green grey happy hard heavy huge identical individual indoor large lean light little living long loose loud lovely low male massive mature metallic miniature modern narrow natural navy neat new old open orange ordinary outdoor oval painted pale patterned peaceful pink plain plastic playful plump polished porcelain pretty purple quiet real rectangular red reflective ripe round royal rusty sad sandy separate shiny short silver simple single small smooth soft solid spotted square stainless static striped strong sturdy tall tame thin tiny transparent tropical upright varied vibrant vintage visible vivid warm wet white wide wild wooden woolen yellow young zebra-striped'''.split())ADJECTIVES = ADJECTIVES | {'empty', 'sailing'}_SINGULAR_UNITS = '|'.join(re.escape(x) for x in UNIT_FORMS if not x.split()[0].endswith('s'))_NUMBER = re.compile(r'(?<![\w.])(?:a(?=\s+(?:'+_SINGULAR_UNITS+r')(?!\w))|a\s+(?:pair|couple|trio)\s+of|'+ '|'.join(NUMBER_WORDS) +r'|[0-9]+)(?![\w.])')_NOUN = re.compile(r'(?<!\w)(?:'+ '|'.join(re.escape(x) for x in sorted(FORMS,key=lambda x:(-len(x),x))) +r')(?!\w)')_NONEXACT = re.compile(r'\b(?:at least|at most|more than|less than|fewer than|up to|no more than|no fewer than|about|around|roughly|approximately|almost|over|under|between|not|without|minus|plus|or|to|through)\s*$')
def _text(prompt): return re.sub(r'\s+', ' ', unicodedata.normalize('NFKC',prompt).casefold().replace('–','-').replace('—','-')).strip()
def explain_prompt(prompt): """Return diagnostic status without reading any labels or suite information.""" if not isinstance(prompt,str): return {'status':'missing','reason':'not_text','target':None,'candidates':[]} text = _text(prompt) candidates=[] invalid=[] nouns=list(_NOUN.finditer(text)) for number in _NUMBER.finditer(text): # Require spaces within the noun phrase; punctuation cannot be an adjective. possible=[] for noun in nouns: if noun.start() <= number.end(): continue middle=text[number.end():noun.start()] if not re.fullmatch(r'\s+(?:[a-z]+\s+){0,3}',middle): continue adjectives=middle.split() if not all(word in ADJECTIVES for word in adjectives): continue possible.append(noun) if not possible: continue # e.g. "two orange cats": orange is an adjective of cats, not a fruit. noun=max(possible,key=lambda m:(m.end(),-m.start())) surface=number.group() value=({'a':1,'a pair of':2,'a couple of':2,'a trio of':3}.get(surface) or NUMBER_WORDS.get(surface) or (int(surface) if surface.isdigit() else None)) before=text[:number.start()] after=text[noun.end():] if (_NONEXACT.search(before) or re.search(r'[0-9]\s*[-/]\s*$',before) or re.match(r'\s*(?:[-/]\s*[0-9]|or\s+(?:[0-9]+|'+'|'.join(NUMBER_WORDS)+r')\b)',after) or before.endswith(('-', '+'))): invalid.append({'surface':text[number.start():noun.end()],'reason':'non_exact_or_alternative'}) continue candidates.append({'skill':'count','object':FORMS[noun.group()],'count':value}) unique={tuple(sorted(x.items())) for x in candidates} if invalid: return {'status':'ambiguous','reason':'non_exact_quantity','target':None,'candidates':candidates,'rejected':invalid} if len(unique)>1: return {'status':'ambiguous','reason':'multiple_count_targets','target':None,'candidates':candidates} if not unique: return {'status':'missing','reason':'no_supported_count_phrase','target':None,'candidates':[]} return {'status':'parsed','reason':'unique_exact_count','target':candidates[0],'candidates':candidates}
def parse_prompt(prompt): return explain_prompt(prompt)['target']12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Shared static COCO vocabulary; no evaluation content is used or loaded.
Canonical names identify the 80 COCO categories.Aliases cover alternate spellings and common names for those categories.Inflections are generated from those lexical entries, independently of prompts."""import reimport unicodedata
CANONICAL_CLASSES = ('airplane', 'apple', 'backpack', 'banana', 'baseball bat', 'baseball glove', 'bear', 'bed', 'bench', 'bicycle', 'bird', 'boat', 'book', 'bottle', 'bowl', 'broccoli', 'bus', 'cake', 'car', 'carrot', 'cat', 'cell phone', 'chair', 'clock', 'computer keyboard', 'computer mouse', 'couch', 'cow', 'cup', 'dining table', 'dog', 'donut', 'elephant', 'fire hydrant', 'fork', 'frisbee', 'giraffe', 'hair drier', 'handbag', 'horse', 'hot dog', 'kite', 'knife', 'laptop', 'microwave', 'motorcycle', 'orange', 'oven', 'parking meter', 'person', 'pizza', 'potted plant', 'refrigerator', 'sandwich', 'scissors', 'sheep', 'sink', 'skateboard', 'skis', 'snowboard', 'spoon', 'sports ball', 'stop sign', 'suitcase', 'surfboard', 'teddy bear', 'tennis racket', 'tie', 'toaster', 'toilet', 'toothbrush', 'traffic light', 'train', 'truck', 'tv', 'tv remote', 'umbrella', 'vase', 'wine glass', 'zebra')_ALIASES = {'airplane': ('plane', 'planes', 'aeroplane', 'aeroplanes'), 'apple': (), 'backpack': (), 'banana': ('plantain',), 'baseball bat': (), 'baseball glove': ('baseball mitt',), 'bear': (), 'bed': (), 'bench': ('park bench',), 'bicycle': ('bike', 'bikes', 'bicycles'), 'bird': (), 'boat': ('sailboat', 'yacht', 'motorboat'), 'book': ('paperback', 'hardback'), 'bottle': (), 'bowl': (), 'broccoli': (), 'bus': ('city bus', 'motor coach'), 'cake': (), 'car': ('automobile', 'sedan', 'passenger car'), 'carrot': (), 'cat': ('kitten', 'feline'), 'cell phone': ('phone', 'phones', 'mobile phone', 'mobile phones', 'cellphones', 'cellphone', 'smartphone', 'mobile', 'cellular phone'), 'chair': (), 'clock': ('wall clock', 'analog clock', 'digital clock', 'timepiece'), 'computer keyboard': ('keyboard', 'keyboards', 'computer keyboards'), 'computer mouse': ('mouse', 'mice', 'computer mice'), 'couch': ('sofa', 'sofas', 'couches'), 'cow': ('cattle', 'calf'), 'cup': (), 'dining table': ('dinner table', 'dinner tables', 'dining tables'), 'dog': ('puppy', 'canine'), 'donut': ('doughnut', 'doughnuts', 'donuts'), 'elephant': ('pachyderm',), 'fire hydrant': ('hydrant', 'fire plug'), 'fork': (), 'frisbee': (), 'giraffe': (), 'hair drier': ('hair dryer', 'hair dryers', 'hairdryers', 'hairdryer', 'blow dryer', 'blowdryer'), 'handbag': ('purse', 'hand bag'), 'horse': ('pony', 'stallion', 'mare'), 'hot dog': ('hotdog',), 'kite': (), 'knife': (), 'laptop': ('notebook computer', 'laptop computer'), 'microwave': (), 'motorcycle': ('motorbike', 'motorbikes', 'motorcycles'), 'orange': ('mandarin', 'tangerine'), 'oven': (), 'parking meter': (), 'person': ('people', 'persons', 'man', 'men', 'woman', 'women'), 'pizza': (), 'potted plant': ('pot plant', 'pot plants', 'potted plants', 'houseplant', 'potted houseplant'), 'refrigerator': ('fridge',), 'sandwich': (), 'scissors': (), 'sheep': ('lamb', 'ewe', 'ram'), 'sink': ('washbasin', 'wash basin'), 'skateboard': (), 'skis': ('ski',), 'snowboard': (), 'spoon': (), 'sports ball': ('ball', 'balls', 'sports balls', 'soccer ball', 'baseball', 'football', 'tennis ball', 'basketball'), 'stop sign': (), 'suitcase': ('travel case', 'luggage case'), 'surfboard': (), 'teddy bear': ('teddy', 'stuffed bear', 'plush bear'), 'tennis racket': ('racket', 'tennis racquet', 'racquet'), 'tie': ('necktie',), 'toaster': (), 'toilet': ('commode',), 'toothbrush': (), 'traffic light': (), 'train': (), 'truck': ('pickup', 'pickup truck', 'lorry'), 'tv': ('television', 'televisions', 'television set', 'television sets', 'tvs'), 'tv remote': ('remote', 'remotes', 'remote control', 'remote controls', 'tv remotes'), 'umbrella': ('parasol', 'brolly'), 'vase': (), 'wine glass': ('wineglass', 'goblet'), 'zebra': ()}_PLURAL_EXCEPTIONS = {'computer mouse': 'computer mice', 'tv remote': 'tv remotes', 'computer keyboard': 'computer keyboards', 'broccoli': 'broccoli heads', 'hair drier': 'hair driers', 'person': 'people', 'mouse': 'mice', 'knife': 'knives', 'sheep': 'sheep', 'scissors': 'scissors', 'skis': 'skis', 'cattle': 'cattle', 'calf': 'calves', 'man': 'men', 'woman': 'women', 'people': 'people', 'men': 'men', 'women': 'women', 'mice': 'mice', 'persons': 'persons'}
def normalize_surface(value): return ' '.join(re.findall(r'[a-z0-9]+', unicodedata.normalize('NFKC', value).casefold()))
def plural(noun): noun = normalize_surface(noun) if noun in _PLURAL_EXCEPTIONS: return _PLURAL_EXCEPTIONS[noun] if noun.endswith('mice'): return noun if noun.endswith(' mouse'): return noun[:-5]+'mice' if noun.endswith(('s', 'sh', 'ch', 'x', 'z')): return noun+'es' if noun.endswith('y') and len(noun)>1 and noun[-2] not in 'aeiou': return noun[:-1]+'ies' return noun+'s'
FORMS = {}for _canonical in CANONICAL_CLASSES: for _surface in (_canonical, *_ALIASES[_canonical]): FORMS.setdefault(normalize_surface(_surface), _canonical) # Existing plural aliases stay valid; no invented double plurals. if not (_surface.endswith('s') and not _surface.endswith(('bus', 'glass'))): FORMS.setdefault(plural(_surface), _canonical)
# A COCO detection of skis/scissors is a pair; broccoli is counted by heads.# These are lexical noun phrases, so N modifies the unit, not its components.UNIT_FORMS = { 'pair of scissors': 'scissors', 'pairs of scissors': 'scissors', 'pair of skis': 'skis', 'pairs of skis': 'skis', 'head of broccoli': 'broccoli', 'heads of broccoli': 'broccoli',}FORMS.update(UNIT_FORMS)
def class_forms(canonical): canonical = FORMS.get(normalize_surface(canonical), canonical) return tuple(sorted(k for k,v in FORMS.items() if v == canonical))12323version https://git-lfs.github.com/spec/v1oid sha256:f3f9aa1a06f8f933c12cdf330d3e915061f809b99f864fc278d8630560ac196esize 80824oid sha256:da2efcde191e1aff9a26531fb63b8bcc334d821c77e12b052092fd7f964fd860size 50190241234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Step-five feature capture and continuation for the released count head."""
from collections import defaultdictimport random
import numpy as np
from .count_n_rank import select_index
PREFIX_STEPS = 5PREFIX_GROUPS = (1, 3, 4)
class FeatureCapture: def __init__(self, layer, torch): self.layer, self.torch = layer, torch self.step, self.handle, self.values = 0, None, None
def begin(self, model, contexts, spatial): self.h, self.w = spatial self.starts = [] offset = 0 for idx, text in enumerate(contexts): if idx % 2 == 0: self.starts.append(offset + len(text)) offset += len(text) + self.h * self.w self.handle = model.dit.transformer_blocks[self.layer - 1].register_forward_hook(self.capture)
def capture(self, _module, _args, value): if self.step != PREFIX_STEPS: return h, w = self.h, self.w tokens = self.torch.stack([value[idx:idx + h * w, 0] for idx in self.starts]) tiles = tokens.float().reshape(len(self.starts), 4, h // 4, 4, w // 4, -1) self.values = tiles.mean((2, 4)).to(self.torch.float16).cpu().numpy()
def close(self): if self.handle is not None: self.handle.remove()
def candidate_seeds(seed): seeds = [seed] rng = random.Random(seed) while len(seeds) < 8: candidate = rng.randrange(2**31) if candidate not in seeds: seeds.append(candidate) return seeds
def choose_and_finish(generator, caption, seeds, target, emit): head = generator.count_head cache = defaultdict(list) start = 0 for width in PREFIX_GROUPS: tracker = FeatureCapture(head.layer, generator.torch) end = start + width try: latents, contexts = generator._render( [caption] * width, seeds[start:end], False, 50, stop_step=PREFIX_STEPS, capture=tracker, progress=lambda step: emit('prefix_step', step=step, steps=PREFIX_STEPS, first_candidate=start + 1, last_candidate=end)) finally: tracker.close() cache['latents'].extend(latents) cache['contexts'].extend(contexts) cache['features'].extend(tracker.values) for index in range(start, end): emit('prefix', candidate=index + 1, candidates_total=8, steps=PREFIX_STEPS) start = end scores = head.log_prob(np.asarray(cache['features']))[:, min(int(target), 7)] index = select_index(scores, seeds[0]) emit('selected', selected=index, seed=seeds[index]) state = ([cache['latents'][index]], cache['contexts'][2 * index:2 * index + 2]) latents, _ = generator._render([caption], [seeds[index]], False, 50, start_step=PREFIX_STEPS, resume=state, progress=lambda step: emit('step', step=step, steps=50)) return latents[0], index, [float(value) if np.isfinite(value) else None for value in scores]12323version https://git-lfs.github.com/spec/v1oid sha256:a8eede4a3e7c9ab4f574098b87b8640fb2292827317df4a7b8e87f988cd73996size 1195040584oid sha256:67d115b32f1699aa5994edeff3e59812a90ec4da90f0d93c8d85b4ed86260d5fsize 239004344811234567869101112131415161713181920162122232425262728293031323334252635363728383930314041424344454647484950373839404142434451525354555657585960616263646566676869707172737475767778798081828384484985868788899091929313 unmodified lines107108109701101111121131147576115116117118119120121122123124125126127128129130131132133134135136137138787980818283848586871391401411421439091929394951441451461471481491501511521531541551561571581591601611621631641651669716716816917017117217317417517617717811 unmodified lines190191192117193194195196121122197198124125126127128129130131132133134135136137138139140141142143199200201202203204205206207208209210211212213148214215216217218219152220221222223224225226227228229230231232159160233234235236237238239240241242162243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415167168416417418419420421171172422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454175176455456457458459460461462463464"""Generate an RGB PNG from a prompt using the packaged diffusion model.""""""Generate with Haidass-Image-Instruct's default prompt-only routing."""
import argparsefrom contextlib import nullcontextimport jsonimport osfrom tempfile import NamedTemporaryFilefrom pathlib import Pathimport unicodedataimport reimport timeimport warnings
import torchfrom PIL import Imagefrom safetensors.torch import load_filefrom transformers import AutoModel, AutoTokenizer
from runtime import add_spelling_v2from runtime.model import DiTConfig, PackedSingleStreamDiTfrom runtime.prompt_routing import preprocess_and_route_text_promptfrom runtime.qwenimage21_vae import AutoencoderKLQwenImage21from runtime.routing import spell_prompt, triggersfrom runtime.spelling import augment_caption
MAX_SEED = 2**31 - 1
def select_device(name): name = str(name) if re.fullmatch(r'auto|cpu|(?:cuda|npu)(?::\d+)?', name) is None: raise ValueError('Device must be auto, cpu, cuda[:N], or npu[:N]') if name == 'auto' and torch.cuda.is_available(): return torch.device('cuda:0') if name == 'auto' or name.startswith('npu'): try: import torch_npu # Registers the NPU device and its PyTorch kernels. except ImportError: import torch_npu except ImportError as exc: if name != 'auto': raise raise RuntimeError('NPU inference requires torch_npu installed for the current PyTorch and Ascend runtime.') from exc else: if name != 'auto' or torch_npu.npu.is_available(): device = torch.device('npu:0' if name == 'auto' else name) if torch_npu.npu.is_available(): device = torch.device('npu:0' if name in ('auto', 'npu') else name) torch.npu.set_device(device) return device if name != 'auto': raise RuntimeError('No Ascend NPU is available to torch_npu.') if name.startswith('cuda') and not torch.cuda.is_available(): raise RuntimeError('No CUDA device is available to PyTorch.') return torch.device('cpu' if name == 'auto' else name)
def route_prompt(prompt, raw_prompt=None): if not triggers(prompt, 'text'): return prompt, False raw = prompt if raw_prompt is None else raw_prompt spans = add_spelling_v2._quoted_spans(raw) needs_v2 = any(raw[start] in "'‘" or any(ch.isdigit() or unicodedata.category(ch).startswith('P') for ch in target) for start, _, target in spans) return (add_spelling_v2.add_spelling(prompt) if needs_v2 else spell_prompt(prompt, augment_caption)), Truedef route_prompt(prompt, raw_prompt=None, *, mode='routed', apply_spelling=True): """Return (prepared prompt, writing route enabled), including for the legacy Space.""" result = preprocess_and_route_text_prompt( prompt, raw_prompt, apply_spelling=apply_spelling, canonical_spelling=augment_caption ) triggered = bool(result['load_writing_lora']) if mode == 'none': active = False elif mode == 'routed': active = triggered elif mode == 'always': active = True else: raise ValueError(f'Unknown writing routing mode: {mode}') return (result['final_prompt'] if active and triggered else result['normalized_prompt']), active
def validate_seed(seed): if type(seed) is not int or not 0 <= seed <= MAX_SEED: raise ValueError(f'seed must be an integer between 0 and {MAX_SEED}')
def validate_pool(seed, pool): if not isinstance(pool, (tuple, list)) or len(pool) != 8: raise ValueError('candidate_seeds must contain exactly eight seeds') for value in pool: validate_seed(value) if pool[0] != seed or len(set(pool)) != 8: raise ValueError('candidate_seeds must be distinct and begin with the row seed')
class Generator: """Load one released model. `generate` and `generate_batch` use all default routes."""
def __init__(self, directory, device='auto', text_encoder=None, memory_fraction=None): self.directory = Path(directory) def __init__(self, directory=None, device='auto', text_encoder=None, memory_fraction=None): self.directory = Path(directory) if directory is not None else Path(__file__).resolve().parent if text_encoder is not None and not Path(text_encoder).is_dir(): raise FileNotFoundError(f'Local text encoder directory does not exist: {text_encoder}') self.device = select_device(device) self.torch = torch if memory_fraction is not None and self.device.type == 'npu': torch.npu.set_per_process_memory_fraction(memory_fraction, self.device) self.config = json.loads((self.directory/'config.json').read_text(encoding='utf-8'))13 unmodified lines vae_dir = self.directory/'vae' vae_config = json.loads((vae_dir/'config.json').read_text(encoding='utf-8')) self.vae = AutoencoderKLQwenImage21.from_pretrained(str(vae_dir), torch_dtype=component_dtype, local_files_only=True) local_files_only=True) self.vae.to(self.device).eval().requires_grad_(False) self.latent_mean = torch.tensor(vae_config['latents_mean'], device=self.device).view(1, -1, 1, 1) self.latent_std = torch.tensor(vae_config['latents_std'], device=self.device).view(1, -1, 1, 1) self.latent_channels = vae_config['z_dim'] self.latent_size = self.settings['resolution']//vae_config['scale_factor_spatial'] self.base = PackedSingleStreamDiT(DiTConfig(**self.config['dit']), self.latent_size = self.settings['resolution'] // vae_config['scale_factor_spatial'] self.base = self._load_backbone().to(self.device).eval().requires_grad_(False) self.adapter = None # Legacy Space can provide its own PEFT wrapper. self._adapter_load_failed = False self.count_head = self._parse_count = self._choose_count = self._candidate_seeds = None path = self.directory/'counting_head'/'head.npz' if path.is_file(): from counting_head.count_n_rank import CountRanker from counting_head.count_parser import parse_prompt from counting_head.sampling import candidate_seeds, choose_and_finish
self.count_head = CountRanker(path) if self.count_head.step != 5 or self.count_head.layer != 25: raise ValueError('The packaged counting head must use step 5 and layer 25') self._parse_count = parse_prompt self._choose_count = choose_and_finish self._candidate_seeds = candidate_seeds else: warnings.warn('counting_head/head.npz is missing. Counting requests use a single backbone draw.', stacklevel=2)
def _load_backbone(self): with torch.device('cpu'): model = PackedSingleStreamDiT(DiTConfig(**self.config['dit']), backend='ascend' if self.device.type == 'npu' else 'reference') state = load_file(str(self.directory/'dit.safetensors')) precision = self.directory/'dit_norm_precision.safetensors' if precision.is_file(): terms = load_file(str(precision)) for name in {key.rsplit('/', 1)[0] for key in terms}: remainder = terms[f'{name}/0'].float()+terms[f'{name}/1'].float()+terms[f'{name}/2'].float() state[name] = state[name].float()+remainder self.base.load_state_dict(state, strict=True) self.base.to(self.device).eval().requires_grad_(False) self.adapter = None state = load_file(str(self.directory/'dit.safetensors'), device='cpu') model.load_state_dict(state, strict=True) return model
def _model(self, routed): if routed: if self.adapter is None: from peft import PeftModel self.adapter = PeftModel.from_pretrained( self.base, self.directory/self.config['routing']['writing_adapter'], is_trainable=False).eval() return self.adapter, nullcontext() if self._adapter_load_failed: raise RuntimeError('Writing adapter loading failed. Create a new Generator before running inference.') if routed and self.adapter is None: from peft import PeftModel
adapter_dir = self.directory/self.config['routing']['writing_adapter'] for name in ('adapter_config.json', 'adapter_model.safetensors'): path = adapter_dir/name if not path.is_file(): raise FileNotFoundError(f'Missing writing adapter file: {path}') # PEFT can change modules before finishing an adapter load. self._adapter_load_failed = True try: with torch.inference_mode(False), torch.no_grad(): adapter = PeftModel.from_pretrained( self.base, adapter_dir, is_trainable=False, torch_device='cpu' ).to(self.device).eval() assert adapter.get_base_model() is self.base except Exception as exc: raise RuntimeError('Writing adapter loading failed. Create a new Generator before running inference.') from exc self.adapter = adapter self._adapter_load_failed = False if self.adapter is not None: return self.base, self.adapter.disable_adapter() return (self.adapter, nullcontext()) if routed else (self.base, self.adapter.disable_adapter()) return self.base, nullcontext()
def _branch_guidance(self, routed): if routed: return (float(self.settings.get('writing_cfg', self.settings['cfg'])), self.settings.get('writing_cfg_norm', self.settings.get('cfg_norm', 'none'))) return float(self.settings['cfg']), self.settings.get('cfg_norm', 'none')
def _contexts(self, caption): tokenized = self.tokenizer([caption, self.tokenizer.eos_token], padding=True, truncation=True, max_length=self.text['max_length'], return_tensors='pt')11 unmodified lines return torch.randn(shape, device=self.device, generator=rng, dtype=torch.float32)
def _image(self, latent): raw = (latent[None].float() * self.latent_std + self.latent_mean)[:, :, None] raw = (latent[None].float()*self.latent_std + self.latent_mean)[:, :, None] pixels = self.vae.decode(raw.to(next(self.vae.parameters()).dtype)).sample[0, :3, 0].float() if not bool(torch.isfinite(pixels).all()): raise FloatingPointError('The VAE returned non-finite pixels') pixels = ((pixels.clamp(-1, 1)+1)*127.5).byte().permute(1, 2, 0).cpu().numpy() return Image.fromarray(pixels) return Image.fromarray(((pixels.clamp(-1, 1)+1)*127.5).byte().permute(1, 2, 0).cpu().numpy())
@torch.inference_mode() def generate_batch(self, prompts, seeds, *, raw_prompts=None, steps=None): if not prompts or len(prompts) != len(seeds): raise ValueError('Supply the same nonzero number of prompts and seeds') if raw_prompts is None: raw_prompts = [None] * len(prompts) if len(raw_prompts) != len(prompts): raise ValueError('Supply one original prompt per image') processed = [route_prompt(prompt, raw) for prompt, raw in zip(prompts, raw_prompts)] if len({active for _, active in processed}) != 1: raise ValueError('Group quoted and unquoted prompts in separate batches') model, context = self._model(processed[0][1]) contexts, latents = [], [] for (caption, _), seed in zip(processed, seeds): contexts.extend(self._contexts(caption)) latents.append(self._noise(seed)) steps = self.settings['steps'] if steps is None else steps if steps < 1: raise ValueError('Steps must be positive') cfg = self.settings['cfg'] def _render(self, captions, seeds, routed, steps, *, start_step=0, stop_step=None, resume=None, capture=None, progress=None): model, context = self._model(routed) cfg, cfg_norm = self._branch_guidance(routed) if resume is None: contexts, latents = [], [] for caption, seed in zip(captions, seeds): contexts.extend(self._contexts(caption)) latents.append(self._noise(seed)) else: latents, contexts = resume shift = self.settings['timestep_shift'] lower, upper = self.settings['cfg_lower'], self.settings['cfg_upper'] grid = torch.linspace(self.settings['start'], self.settings['end'], steps+1, device=self.device) if shift != 1: grid = shift * grid / (1 + (shift-1) * grid) grid = shift * grid / (1 + (shift - 1) * grid) mask = ((grid > lower) & (grid <= upper)).tolist() if (lower, upper) != (0, 1) else [True]*len(grid) cells = self.latent_size**2 if capture is not None: capture.begin(self.base, contexts, latents[0].shape[-2:]) with context: for active, (timestep, following) in zip(mask, zip(grid[:-1], grid[1:])): for step, (active, (timestep, following)) in enumerate(zip(mask, zip(grid[:-1], grid[1:])), 1): if step <= start_step: continue if stop_step is not None and step > stop_step: break if capture is not None: capture.step = step inputs = [latent for latent in latents for _ in range(2)] with torch.autocast(self.device.type, dtype=self.dtype): predictions = model(inputs, contexts, timestep.expand(len(inputs))).split(cells) updated = [] for i, latent in enumerate(latents): conditional, unconditional = predictions[2*i:2*i+2] velocity = unconditional.float()+cfg*(conditional.float()-unconditional.float()) if active else conditional.float() updated.append(latent+(following-timestep)*velocity.T.reshape_as(latent)) vc_f, vu_f = conditional.float(), unconditional.float() if active: velocity = vu_f + cfg * (vc_f-vu_f) if cfg_norm == 'qwen': velocity = velocity * (torch.norm(vc_f, dim=-1, keepdim=True) / torch.norm(velocity, dim=-1, keepdim=True).clamp(min=1e-8)) else: velocity = vc_f updated.append(latent + (following-timestep) * velocity.T.reshape_as(latent)) latents = updated return [self._image(latent) for latent in latents] if progress is not None: progress(step) return latents, contexts
@torch.inference_mode() def generate(self, prompt, seed=0, *, steps=None, candidate_seeds=None, count_head=True, writing_lora=True, routing='auto', progress=None, raw_prompt=None): """Return `(PIL.Image, record)` using writing, count, or single backbone routing.""" if not isinstance(prompt, str) or not prompt.strip(): raise ValueError('prompt must be non-empty text') validate_seed(seed) if candidate_seeds is not None: validate_pool(seed, candidate_seeds) steps = self.settings['steps'] if steps is None else steps if type(steps) is not int or steps < 1: raise ValueError('steps must be a positive integer') if routing not in ('auto', 'none'): raise ValueError('routing must be auto or none') active = routing != 'none' final_prompt, writing = route_prompt(prompt, raw_prompt, mode='routed' if active and writing_lora else 'none') parsed = self._parse_count(prompt) if active and self._parse_count is not None else None wants_count = not writing and count_head and parsed is not None use_count = wants_count and steps == 50 route = 'writing_lora' if writing else 'count_head' if use_count else 'backbone'
def emit(event, **data): if progress is not None: progress(dict(event=event, route=route, **data))
notes = [] if wants_count and not use_count: notes.append(f'Counting uses the 50-step schedule; steps={steps} falls back to one backbone draw.') truncated = writing and len(self.tokenizer(final_prompt, truncation=False, verbose=False).input_ids) > self.text['max_length'] if truncated: notes.append(f'Spelled prompt exceeds {self.text["max_length"]} tokens and will be truncated.') emit('route', parsed_count=None if parsed is None else parsed['count'], steps=steps) for note in notes: if progress is None: warnings.warn(note, stacklevel=2) else: emit('notice', message=note) if self.device.type == 'npu': torch.npu.synchronize(self.device) started = time.monotonic() seeds, selected, scores = [seed], 0, None if use_count: seeds = list(candidate_seeds) if candidate_seeds is not None else self._candidate_seeds(seed) latent, selected, scores = self._choose_count(self, final_prompt, seeds, parsed['count'], emit) else: latents, _ = self._render([final_prompt], seeds, writing, steps, progress=lambda step: emit('step', step=step, steps=steps)) latent = latents[0] image = self._image(latent) if self.device.type == 'npu': torch.npu.synchronize(self.device) return image, dict(route=route, writing_triggered=writing, parsed=parsed, parsed_count=None if parsed is None else parsed['count'], head_used=use_count, selected=selected, candidates=seeds, seed=seeds[selected], input_seed=seed, log_probabilities_target=scores, truncated=bool(truncated), final_prompt=final_prompt, steps=steps, seconds=time.monotonic()-started, notices=notes)
def generate_batch(self, prompts, seeds, *, steps=None, candidate_seeds=None, count_head=True, writing_lora=True, routing='auto', progress=None, return_records=False, raw_prompts=None): """Route mixed prompts in input order. Set `return_records=True` for `(PIL, record)` pairs.""" if not prompts or len(prompts) != len(seeds): raise ValueError('Supply the same nonzero number of prompts and seeds') if candidate_seeds is None: candidate_seeds = [None] * len(prompts) if raw_prompts is None: raw_prompts = [None] * len(prompts) if len(candidate_seeds) != len(prompts) or len(raw_prompts) != len(prompts): raise ValueError('Supply one candidate-pool and raw-prompt entry per image') results = [self.generate(prompt, seed, steps=steps, candidate_seeds=pool, count_head=count_head, writing_lora=writing_lora, routing=routing, progress=progress, raw_prompt=raw) for prompt, seed, pool, raw in zip(prompts, seeds, candidate_seeds, raw_prompts)] return results if return_records else [image for image, _ in results]
def read_cases(path): rows = json.loads(path.read_text(encoding='utf-8-sig')) if not isinstance(rows, list) or not rows: raise ValueError('Batch JSON must be a non-empty list of objects') errors, identifiers = [], {} reserved = {'CON', 'PRN', 'AUX', 'NUL'} | {f'{prefix}{n}' for prefix in ('COM', 'LPT') for n in range(1, 10)} for number, row in enumerate(rows, 1): if not isinstance(row, dict): errors.append(f'row {number}: expected an object') continue missing = {'id', 'caption', 'seed'} - row.keys() if missing: errors.append(f'row {number}: missing {", ".join(sorted(missing))}') identifier = str(row.get('id')) if 'id' in row: if (type(row['id']) not in (int, str) or re.fullmatch(r'[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}', identifier) is None or identifier.endswith('.') or identifier.split('.')[0].upper() in reserved): errors.append(f'row {number}: id must be a portable file-name component') elif identifier.casefold() in identifiers: errors.append(f'row {number}: duplicate id {identifier!r} from row {identifiers[identifier.casefold()]}') else: identifiers[identifier.casefold()] = number if 'caption' in row and (not isinstance(row['caption'], str) or not row['caption'].strip()): errors.append(f'row {number}: caption must be non-empty text') if 'seed' in row: try: validate_seed(row['seed']) except ValueError as exc: errors.append(f'row {number}: {exc}') if 'candidate_seeds' in row: try: validate_pool(row.get('seed'), row['candidate_seeds']) except ValueError as exc: errors.append(f'row {number}: {exc}') if errors: raise ValueError('Invalid batch input:\n' + '\n'.join(errors)) return rows
def output_sidecar(path, *, overwrite): sidecar = path.with_suffix('.json') if sidecar == path: raise ValueError(f'Image output and JSON sidecar would use the same path: {path}') if path.is_symlink() or (path.exists() and (not overwrite or not path.is_file())): raise FileExistsError(f'Invalid image output path: {path}') if sidecar.is_symlink() or (sidecar.exists() and (not overwrite or not sidecar.is_file())): raise FileExistsError(f'Refusing to replace an existing JSON record: {sidecar}') return sidecar
def _write_record(stream, record): json.dump(record, stream, ensure_ascii=False, allow_nan=False, indent=2) stream.write('\n')
def write_image(image, record, path, *, overwrite=False): sidecar = output_sidecar(path, overwrite=overwrite) path.parent.mkdir(parents=True, exist_ok=True) if overwrite: temporary = [] try: with NamedTemporaryFile(dir=path.parent, delete=False) as stream: temporary.append(Path(stream.name)) image.save(stream, format='PNG') with NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent, delete=False) as stream: temporary.append(Path(stream.name)) _write_record(stream, record) os.replace(temporary[0], path) os.replace(temporary[1], sidecar) finally: for item in temporary: item.unlink(missing_ok=True) return
with path.open('xb') as output: try: image.save(output, format='PNG') with sidecar.open('x', encoding='utf-8') as stream: _write_record(stream, record) except BaseException: output.close() path.unlink() raise
def console_progress(event): if event['event'] == 'prefix': event['message'] = f'prefix {event["candidate"]}/{event["candidates_total"]}' elif event['event'] in ('step', 'prefix_step'): event['message'] = f'{event["event"]} {event["step"]}/{event["steps"]}' print(json.dumps(event, ensure_ascii=False), flush=True)
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('prompt') parser.add_argument('--output', type=Path, default=Path('output.png')) parser.add_argument('prompt', nargs='?') parser.add_argument('--cases', type=Path, help='JSON list with id, caption, seed, and optional candidate_seeds') parser.add_argument('--output', type=Path, help='PNG path, or output directory with --cases') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--steps', type=int) parser.add_argument('--model', type=Path, default=Path(__file__).resolve().parent) parser.add_argument('--device', default='auto', help='auto, cpu, cuda, cuda:N, npu, or npu:N') parser.add_argument('--text-encoder', help='A local or Hugging Face copy of Qwen/Qwen3-0.6B') parser.add_argument('--device', default='auto') parser.add_argument('--text-encoder', type=Path, help='Local Qwen3-0.6B directory') parser.add_argument('--count-head', choices=('on', 'off'), default='on') parser.add_argument('--writing-lora', choices=('on', 'off'), default='on') parser.add_argument('--routing', choices=('auto', 'none'), default='auto') args = parser.parse_args() if (args.prompt is None) == (args.cases is None): parser.error('Supply one prompt or --cases') try: rows = read_cases(args.cases) if args.cases else [dict(id=0, caption=args.prompt, seed=args.seed)] validate_seed(args.seed) if args.steps is not None and args.steps < 1: raise ValueError('steps must be a positive integer') if args.text_encoder is not None and not args.text_encoder.is_dir(): raise ValueError(f'Local text encoder directory does not exist: {args.text_encoder}') except (ValueError, OSError) as exc: parser.error(str(exc)) batch = args.cases is not None base = args.output or Path('outputs' if batch else 'output.png') pending = [] for number, row in enumerate(rows, 1): output = base/str(row['id'])/'image.png' if batch else base if batch and output.is_file(): print(json.dumps(dict(event='skipped', id=row['id'], image=str(output)), ensure_ascii=False), flush=True) continue try: output_sidecar(output, overwrite=not batch) except (ValueError, OSError) as exc: parser.error(f'row {number}: {exc}') pending.append((row, output)) if not pending: return generator = Generator(args.model, args.device, args.text_encoder) args.output.parent.mkdir(parents=True, exist_ok=True) generator.generate_batch([args.prompt], [args.seed])[0].save(args.output, format='PNG') for row, output in pending: image, record = generator.generate(row['caption'], row['seed'], steps=args.steps, candidate_seeds=row.get('candidate_seeds'), count_head=args.count_head == 'on', writing_lora=args.writing_lora == 'on', routing=args.routing, progress=console_progress) record.update(id=row['id']) write_image(image, record, output, overwrite=not batch) print(json.dumps(record, ensure_ascii=False, allow_nan=False), flush=True)
if __name__ == '__main__':1234545678torch>=2.6diffusers>=0.43,<0.44huggingface-hub>=1.32,<3transformers>=5.0peft>=0.20transformers>=5.0,<6peft>=0.20,<1safetensors>=0.5Pillow>=10numpy>=1.2611234"""Add the training-time spelling annotation to quoted English text.""""""Append letter-by-letter spelling annotations to quoted English text."""import re
_QUOTED = re.compile(r'"([^"\n]*)"|“([^”\n]*)”')123345"""Annotate quoted display text while preserving the original prompt.
Drop-in API: add_spelling(prompt: str) -> str.Whitespace separates words; each remaining character (including numbers andpunctuation) is separated by one space. Straight and curly quote pairs arerecognized. Apostrophes inside words do not open or close single-quoted spans.11 unmodified lines1213141515161718114 unmodified lines13313413513613713813613713813914014114214214314414511 unmodified linesfrom torch.nn import functional as F
from . import qwenimage21_transformer as officialfrom .sequence import LanceDocument, LancePackedSequence, LanceSegmentfrom .sequence import PackedDocument, PackedSequence, PackedSegment
@dataclass114 unmodified lines # A shared t=0 embedding is used for every text token, exactly as official causal_condition. rows.extend([len(images)]*length + [i]*count) image_indices.extend(range(offset+length, offset+length+count)) documents.append(LanceDocument(str(i), ( LanceSegment(length, 'causal', 'text', 'generation'), LanceSegment(count, 'full', 'image', 'generation')))) documents.append(PackedDocument(str(i), ( PackedSegment(length, 'causal', 'text', 'generation'), PackedSegment(count, 'full', 'image', 'generation')))) offset += length+count x = torch.cat(hidden)[:, None, :] rotary = tuple(torch.cat([r[i] for r in rope],dim=1) for i in range(2)) schedule = LancePackedSequence(tuple(documents)) schedule = PackedSequence(tuple(documents)) t = torch.cat((timesteps.to(x.dtype), timesteps.new_zeros(1).to(x.dtype))) temb = self.dit.time_text_embed(t, x) row = torch.tensor(rows, device=x.device)5 unmodified lines678991011121213141516171718192021212223243 unmodified lines282930313132333435363738393839404142434344454647464748495027 unmodified lines7879808181828384848586873 unmodified lines919293949495969798999910010110242 unmodified lines1451461471481481491501515 unmodified lines
import torch
from .sequence import AttentionBlock, LancePackedSequencefrom .sequence import AttentionBlock, PackedSequence
class LanceAscendAttentionError(RuntimeError):class AscendAttentionError(RuntimeError): pass
class AscendBlockAttentionBackend: """Callable attention backend matching ``modeling_lance.AttentionBackend``.""" """Compute attention on Ascend using a packed sequence's block schedule."""
def __init__( self, packed_sequence: Optional[LancePackedSequence] = None, packed_sequence: Optional[PackedSequence] = None, torch_npu_module: Any = None, ) -> None: self.packed_sequence = packed_sequence3 unmodified lines try: import torch_npu as torch_npu_module except ImportError as exc: raise LanceAscendAttentionError("native Lance attention requires torch_npu") from exc raise AscendAttentionError("packed attention requires torch_npu") from exc self.torch_npu = torch_npu_module self._causal_masks: Dict[str, torch.Tensor] = {}
def _resolve_schedule( self, attention_metadata: Any, ) -> Tuple[LancePackedSequence, Tuple[Tuple[Tuple[int, int], Tuple[AttentionBlock, ...]], ...]]: if isinstance(attention_metadata, LancePackedSequence): ) -> Tuple[PackedSequence, Tuple[Tuple[Tuple[int, int], Tuple[AttentionBlock, ...]], ...]]: if isinstance(attention_metadata, PackedSequence): packed_sequence = attention_metadata elif self.packed_sequence is not None: # Backward-compatible static mode ignores the dense-mask argument; # production callers should pass LancePackedSequence dynamically. # production callers should pass PackedSequence dynamically. packed_sequence = self.packed_sequence else: raise LanceAscendAttentionError( "dynamic native attention requires LancePackedSequence metadata" raise AscendAttentionError( "dynamic native attention requires PackedSequence metadata" ) if packed_sequence is not self._cached_sequence: self._cached_sequence = packed_sequence27 unmodified lines attention_mask: Any, ) -> torch.Tensor: if query.ndim != 3 or key.ndim != 3 or value.ndim != 3: raise LanceAscendAttentionError("Ascend Lance attention requires TND tensors") raise AscendAttentionError("Ascend packed attention requires TND tensors") packed_sequence, groups = self._resolve_schedule(attention_mask) if query.shape[0] != packed_sequence.length: raise LanceAscendAttentionError( raise AscendAttentionError( "attention tokens do not match the compiled packed-sequence schedule" ) output = torch.empty_like(query)3 unmodified lines for (query_start, query_end), blocks in groups: self_block = blocks[-1] if (self_block.key_start, self_block.key_end) != (query_start, query_end): raise LanceAscendAttentionError("compiled schedule must end with the query self-block") raise AscendAttentionError("compiled schedule must end with the query self-block") causal = self_block.causal batched[causal].append((query_start, query_end, blocks)) covered += query_end - query_start if covered != query.shape[0]: raise LanceAscendAttentionError("compiled attention schedule did not cover every query token") raise AscendAttentionError("compiled attention schedule did not cover every query token")
for causal in (True, False): plans = batched[causal]42 unmodified lines sparse_mode=3 if causal else 0, )[0] if result.shape != packed_query.shape: raise LanceAscendAttentionError( raise AscendAttentionError( "npu_fusion_attention returned {}, expected {}".format( tuple(result.shape), tuple(packed_query.shape) )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423"""Detect quoted display text and prepare its spelling annotations."""from __future__ import annotations
import reimport unicodedata
_CLOSE_QUOTE = { '"': '"', '\u201c': '\u201d', '「': '」', '『': '』', "'": "'", '\u2018': '\u2019',}_ANNOTATION = re.compile(r'\s*\(spelled:\s*[^)\n]*\)')_ESCAPED_CHAR = re.compile(r"""\\(["'\\])""")_COLLOQUIAL_N = re.compile(r"(?<=[a-z]\s)['\u2018]n['\u2019](?=\s+[a-z])")
# Exclusions immediately before a quote, such as work titles and style references._NON_DISPLAY_BEFORE = re.compile( r"(?i)(?:" r"\b(?:in the style of|inspired by|reminiscent of|reimagined version of|" r"evoking|aesthetics? of|atmosphere of|mood of)\b[^.!?\"\u201c\n]{0,55}" r"|\b(?:from|of)\s+the\s+(?:film|movie|game|series|anime|novel|show|franchise|play)\b[^.!?\"\u201c\n]{0,25}" r"|\bthe\s+(?:film|movie|game|series|anime|novel|play)\s*$" r"|\b(?:concept art|artwork|art piece|illustration|sculpture|portrait|" r"painting|photograph|photo|scene|character concept)(?:\s+piece)?\s+" r"(?:entitled|dubbed|titled|called|named)\s*$" r"|\b(?:portraying|capturing|embodying|representing|encapsulating|" r"highlighting|symbolizing|depicting|depict|illustrating)\s+(?:the\s+|a\s+|an\s+)?" r"(?:concept\s+of|theme\s+of|essence\s+of|idea\s+of|notion\s+of|" r"feeling\s+of|sense\s+of|mood\s+of)?\s*$" r"|\b(?:appears?\s+to\s+be|seems?\s+to\s+be|so-called|" r"like\s+(?:a|an|the))\s*$" r")\s*$")
# Exclusions immediately after a quote, such as descriptions of a theme or motif._NON_DISPLAY_AFTER = re.compile( r"(?i)^\s*(?:" r"patterns?|motifs?|concept|theme|style|aesthetics?|" r"vibe|metaphor|mood|atmosphere|" r"from\s+the\s+(?:legend|series|film|movie|game)" r")\b")
# Direct text-rendering verbs and typographic nouns within the same sentence._STRONG_TEXT_CUE = re.compile( r"(?i)\b(?:" r"says|saying|said|reads|reading|read|" r"written|write|writes|writing|handwritten|scrawled|inscribed|inscription|" r"spell|spells|spelled|spelling|" r"engraved|etched|embossed|printed|stamped|stenciled|" r"emblazoned|stitched|embroidered|carved|" r"proclaim|proclaims|proclaiming|declare|declares|declaring|" r"announces|announcing|announced|advertises|advertising|advertised|lists|listing|" r"labeled|labelled|marked|captioned|" r"word|words|text|letter|letters|lettering|phrase|slogan|motto|caption|" r"headline|subheading|subtitle|tagline|heading|acronym|" r"font|script|typography|calligraphy|graffiti|chalk|marker|" r"number|message|watermark|monogram|initials" r")\b")
# Surfaces and media commonly used to display text._DEDICATED_TEXT_SURFACE = re.compile( r"(?i)\b(?:" r"sign|signs|signboard|signpost|signage|billboard|banner|placard|marquee|" r"chalkboard|whiteboard|blackboard|scoreboard|" r"speech\s+bubble|thought\s+bubble|" r"plaque|nameplate|license\s+plate|tombstone|gravestone|" r"storefront|store\s+front|shopfront|" r"book|books|book\s+cover|notebook|diary|journal|page|pages|spine|" r"magazine|newspaper|poster|flyer|brochure|menu|business\s+card|postcard|" r"invitation|ticket|receipt|certificate|diploma|album\s+cover|slide|presentation|" r"advertisement|logo|" r"label|labels|tag|tags|sticker|stickers|badge|patch|stamp" r")\b")
_PRINT_DESIGN_MEDIA = re.compile( r"(?i)\b(?:" r"poster|flyer|brochure|menu|business\s+card|album\s+cover|book\s+cover|" r"magazine\s+cover|newspaper|billboard|banner|signpost|placard|marquee|" r"invitation|postcard|certificate|diploma|ticket|receipt|" r"ppt|slide|presentation|advertisement|logo" r")\b")
# Physical surfaces that can display text when paired with a rendering cue._GENERAL_SURFACE_CUE = re.compile( r"(?i)\b(?:" r"cover|card|envelope|tattoo|bubble|screen|monitor|board|kiosk|booth|backdrop|" r"mural|sidewalk|pavement|plate|" r"jersey|shirt|t-shirt|hoodie|jacket|cap|hat|apron|" r"mug|cup|bottle|jar|can|box|bag|package|packaging|" r"cake|curtain|cloth|" r"boat|truck|car|bus|train|plane|window|door|wall|canvas|paper|" r"clock|calendar|flag|ribbon|trophy|medal" r")\b")
# Phrases that explicitly ask for the quoted content to appear on a surface._EXPLICIT_RENDER_CUE = re.compile( r"(?i)\b(?:" r"display|displays|displaying|displayed|" r"show|shows|showing|shown|showcasing|showcase|" r"featuring|features|feature|featured|bearing|bears|" r"painted|drawn|forming|formed|shaped|arranged|" r"wrapped\s+with|" r"across\s+(?:the|its)\s+(?:chest|front|back|side|top|sky|wall|window)|" r"on\s+(?:the|its)\s+(?:front|back|side|chest|top|cover|spine|page|surface|wall|window|door)" r")\b")
_ZH_TEXT_CUE = re.compile( r"(?:写着|写有|字样|文字|标语|招牌|横幅|海报|标题|书名|印着|印有|刻着|刻有|题字|书法|霓虹|灯牌|" r"牌子|标签|字幕|广告牌|黑板|白板|纸条|信封|书皮|封面|名片|徽章|车牌|路牌|字体|大字|小字)")
# Chinese cues for work titles and references that should not appear as text._ZH_NON_DISPLAY = re.compile( r"(?:名为|模仿|致敬)\s*$")
def _is_escaped(text: str, pos: int) -> bool: start = pos while start and text[start - 1] == '\\': start -= 1 return (pos - start) % 2 == 1
def _is_word_apostrophe(text: str, pos: int) -> bool: return 0 < pos < len(text) - 1 and text[pos - 1].isalnum() and text[pos + 1].isalnum()
def normalize_single_quotes(prompt: str) -> str: out = [] pos = 0 n = len(prompt) while pos < n: if prompt.startswith('(spelled:', pos): end = prompt.find(')', pos + 8) if end >= 0: out.append(prompt[pos:end + 1]) pos = end + 1 continue
ch = prompt[pos]
if ch in ('"', '\u201c', '「', '『') and not _is_escaped(prompt, pos): closer = _CLOSE_QUOTE[ch] end = pos + 1 while end < n and prompt[end] not in '\r\n': if prompt[end] == closer and not _is_escaped(prompt, end): out.append(prompt[pos:end + 1]) pos = end + 1 break end += 1 else: out.append(ch) pos += 1 continue
if ch in ("'", '\u2018') and not _is_escaped(prompt, pos): m_cn = _COLLOQUIAL_N.match(prompt, pos) if m_cn: out.append(m_cn.group(0)) pos = m_cn.end() continue if _is_word_apostrophe(prompt, pos) or (pos > 0 and prompt[pos - 1].isalnum()): out.append(ch) pos += 1 continue
valid_closers = ("'",) if ch == "'" else ('\u2019', "'") end = pos + 1 matched = -1 while end < n and prompt[end] not in '\r\n': if prompt[end] in valid_closers and not _is_escaped(prompt, end): if _is_word_apostrophe(prompt, end): end += 1 continue if end + 1 < n and prompt[end + 1].isalnum(): end += 1 continue matched = end break end += 1 if matched > pos + 1 and prompt[pos + 1:matched].strip(): inner = prompt[pos + 1:matched] out.append('"' + inner + '"') pos = matched + 1 continue
out.append(ch) pos += 1
return ''.join(out)
def find_quoted_spans(prompt: str): pos = 0 n = len(prompt) while pos < n: if prompt.startswith('(spelled:', pos): end = prompt.find(')', pos + 8) if end >= 0: pos = end + 1 continue opener = prompt[pos] if opener not in _CLOSE_QUOTE or _is_escaped(prompt, pos): pos += 1 continue if opener in ("'", '\u2018'): m_cn = _COLLOQUIAL_N.match(prompt, pos) if m_cn: pos = m_cn.end() continue if _is_word_apostrophe(prompt, pos) or (pos > 0 and prompt[pos - 1].isalnum()): pos += 1 continue closer = _CLOSE_QUOTE[opener] valid_closers = (closer, "'") if opener == '\u2018' else (closer,) end = pos + 1 while end < n and prompt[end] not in '\r\n': if prompt[end] in valid_closers and not _is_escaped(prompt, end): if opener in ("'", '\u2018') and (_is_word_apostrophe(prompt, end) or (end + 1 < n and prompt[end + 1].isalnum())): end += 1 continue yield pos, end + 1, prompt[pos + 1:end] pos = end + 1 break end += 1 else: pos += 1
_ABBREV_END = re.compile(r'(?i)\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|St|Mt|Est|No|Co|Inc|Ltd|vs|eg|ie|etc)\.$')
def _sentence_bounds(text: str, start: int, end: int): s_start = 0 for m in re.finditer(r'[.!?。!?\n](?:\s+|$)', text[:start]): if text[m.start()] == '.' and _ABBREV_END.search(text[:m.start() + 1]): continue s_start = m.end() s_end = len(text) for m in re.finditer(r'[.!?。!?\n](?:\s+|$)', text[end:]): abs_dot = end + m.start() if text[abs_dot] == '.' and _ABBREV_END.search(text[:abs_dot + 1]): continue s_end = abs_dot + 1 break return s_start, s_end
def is_display_text_span(prompt: str, start: int, end: int, content: str) -> bool: if not content.strip(): return False
s_start, s_end = _sentence_bounds(prompt, start, end) before_sent = prompt[s_start:start] after_sent = prompt[end:s_end] near_before = before_sent[-70:] near_after = after_sent[:55]
if _NON_DISPLAY_BEFORE.search(near_before) or _NON_DISPLAY_AFTER.search(near_after): return False if prompt[start] in ('\u201c',) and _ZH_NON_DISPLAY.search(near_before): return False
if prompt[start] in ('「', '『'): return True
sent_without_span = before_sent + ' ' + after_sent
if _ZH_TEXT_CUE.search(sent_without_span): return True if _STRONG_TEXT_CUE.search(sent_without_span): return True if _DEDICATED_TEXT_SURFACE.search(sent_without_span): return True if _GENERAL_SURFACE_CUE.search(sent_without_span) and _EXPLICIT_RENDER_CUE.search(sent_without_span): return True if _PRINT_DESIGN_MEDIA.search(prompt): return True if re.search(r':\s*$', near_before): return True
return False
def display_text_spans(prompt: str): return [ (s, e, content) for s, e, content in find_quoted_spans(prompt) if is_display_text_span(prompt, s, e, content) ]
def should_load_writing_lora(prompt: str) -> bool: normalized = normalize_single_quotes(prompt) return bool(display_text_spans(normalized))
def _needs_spelling_v2(raw_prompt: str, spans) -> bool: raw_has_single = any( raw_prompt[s] in ("'", '\u2018') for s, _, _ in find_quoted_spans(raw_prompt) ) if raw_has_single: return True return any( ch.isdigit() or unicodedata.category(ch).startswith('P') for _, _, target in spans for ch in target )
def _format_spelling_v2(target: str) -> str: cleaned = _ESCAPED_CHAR.sub(r'\1', target) return ' / '.join(' '.join(word) for word in cleaned.split())
def _format_spelling_v1(target: str, canonical_spelling) -> str: canonical = f'"{target}"' annotated = canonical_spelling(canonical) return annotated[len(canonical):]
def preprocess_and_route_text_prompt( prompt: str, raw_prompt: str | None = None, *, apply_spelling: bool = True, canonical_spelling=None,): raw = prompt if raw_prompt is None else raw_prompt normalized = normalize_single_quotes(prompt) spans = display_text_spans(normalized) if not spans: return { 'normalized_prompt': normalized, 'final_prompt': normalized, 'load_writing_lora': False, 'spelling_version': None, 'display_spans': [], }
if not apply_spelling: return { 'normalized_prompt': normalized, 'final_prompt': normalized, 'load_writing_lora': True, 'spelling_version': None, 'display_spans': [c for _, _, c in spans], }
use_v2 = _needs_spelling_v2(raw, spans) or canonical_spelling is None pieces = [] cursor = 0 changed = False for start, end, target in spans: if not target.strip() or _ANNOTATION.match(normalized, end): continue if use_v2: suffix = f' (spelled: {_format_spelling_v2(target)})' else: suffix = _format_spelling_v1(target, canonical_spelling) if suffix: pieces.extend((normalized[cursor:end], suffix)) cursor = end changed = True pieces.append(normalized[cursor:]) final_prompt = ''.join(pieces) version = ('v2' if use_v2 else 'v1') if changed else None return { 'normalized_prompt': normalized, 'final_prompt': final_prompt, 'load_writing_lora': True, 'spelling_version': version, 'display_spans': [c for _, _, c in spans], }
def _run_unit_tests(): """Built-in unit tests covering apostrophes, possessive signs, scare quotes, and mixed quotes.""" cases = [ ("It's a sunny day and I don't know why.", "It's a sunny day and I don't know why.", False), ("Blending rock 'n' roll and jazz.", "Blending rock 'n' roll and jazz.", False), ("The cats' toys are on the floor.", "The cats' toys are on the floor.", False), ("A wooden \"Joe's Diner\" sign by the road.", 'A wooden "Joe\'s Diner" sign by the road.', True), ("A rustic sign for 'Joe's Diner' at dusk.", 'A rustic sign for "Joe\'s Diner" at dusk.', True), ("A weathered metal sign outside Joe's \"Diner & Grill\".", 'A weathered metal sign outside Joe\'s "Diner & Grill".', True), ("A polished brass door plaque for Dr. Lee's \"Dental Clinic\".", 'A polished brass door plaque for Dr. Lee\'s "Dental Clinic".', True), ("A cloth-bound book with 'Field Notes' on the spine.", 'A cloth-bound book with "Field Notes" on the spine.', True), ("A golden retriever having the \"best\" day at the beach.", 'A golden retriever having the "best" day at the beach.', False), ("A landscape painted in the style of Monet's 'Impression, Sunrise'.", 'A landscape painted in the style of Monet\'s "Impression, Sunrise".', False), ("A digital painting called \"Autumn Solitude\" by a foggy lake.", 'A digital painting called "Autumn Solitude" by a foggy lake.', False), ("A sign that says 'It's sunny, don't stop!' on the wall.", 'A sign that says "It\'s sunny, don\'t stop!" on the wall.', True), ] for raw, exp_norm, exp_trig in cases: res = preprocess_and_route_text_prompt(raw) assert res['normalized_prompt'] == exp_norm, f"NORM MISMATCH: {raw} -> {res['normalized_prompt']} != {exp_norm}" assert res['load_writing_lora'] == exp_trig, f"TRIG MISMATCH: {raw} -> {res['load_writing_lora']} != {exp_trig}"
mixed = "A sign reading 「OPEN」 and '24/7'" res_mixed = preprocess_and_route_text_prompt(mixed) assert res_mixed['load_writing_lora'] is True assert res_mixed['display_spans'] == ['OPEN', '24/7'], res_mixed assert res_mixed['final_prompt'] == 'A sign reading 「OPEN」 (spelled: O P E N) and "24/7" (spelled: 2 4 / 7)', res_mixed
mixed_zh = "A shop banner showing 「拉面」 and 'RAMEN'" res_zh = preprocess_and_route_text_prompt(mixed_zh) assert res_zh['load_writing_lora'] is True assert res_zh['display_spans'] == ['拉面', 'RAMEN'], res_zh assert '(spelled: 拉 面)' in res_zh['final_prompt'] and '(spelled: R A M E N)' in res_zh['final_prompt'], res_zh
if __name__ == '__main__': _run_unit_tests() print("Prompt routing self-tests passed")1234567891011123 unmodified lines16171813192021221723242526"""Quote routing and spelling-format preservation."""import re
from .prompt_routing import ( normalize_single_quotes, preprocess_and_route_text_prompt, should_load_writing_lora,)
QUOTE_PATTERN = re.compile(r'"([^"\n]+)"|“([^”\n]+)”|「([^」\n]+)」|『([^』\n]+)』|' r'(?<!\w)\x27([^\x27\n]+)\x27(?!\w)|‘([^’\n]+)’')3 unmodified linesdef triggers(prompt, adapter): if adapter != 'text': raise ValueError('Only the writing adapter is available') return any(match[0][1:-1].strip() for match in QUOTE_PATTERN.finditer(prompt)) return should_load_writing_lora(prompt)
def spell_prompt(prompt, canonical_spelling): """Use the training-time spelling format while preserving the original quote marks.""" """Append spelling annotations without changing the original quote marks.""" def annotate(match): quoted = match[0] target = quoted[1:-1]112345345678910121311121314154 unmodified lines20212224232425262729282930311 unmodified line33343537363739383941404143424344451 unmodified line4748495150515352535455575657595859606114 unmodified lines7677788081798081828385848586888788899021 unmodified lines1121131141161151161171188 unmodified lines127128129131130131132133"""Native Lance packed-sequence contracts and dependency-free golden helpers."""Packed sequences and their attention schedules.
Production kernels consume block schedules from this module. The dense mask isdeliberately limited to short sequences and exists only as an unambiguous oraclefor CPU unit tests; it must never be used for the 40K/70K training path.Attention kernels consume block schedules from this module. The dense maskprovides a CPU reference for checking short sequences."""
from dataclasses import dataclassfrom typing import Dict, List, Sequence, Tuple
class LanceSequenceError(ValueError): """Raised when a packed Lance sequence is structurally invalid."""class PackedSequenceError(ValueError): """Raised when a packed sequence is structurally invalid."""
ATTENTION_MODES = ("causal", "full", "noise", "full_noise", "full_noise_target")4 unmodified lines if mode in ("full_noise", "full_noise_target"): return "full" if mode not in ("causal", "full", "noise"): raise LanceSequenceError("unsupported attention mode: {}".format(mode)) raise PackedSequenceError("unsupported attention mode: {}".format(mode)) return mode
@dataclass(frozen=True)class LanceSegment:class PackedSegment: length: int attention_mode: str modality: str1 unmodified line
def __post_init__(self) -> None: if not isinstance(self.length, int) or isinstance(self.length, bool) or self.length <= 0: raise LanceSequenceError("segment length must be a positive integer") raise PackedSequenceError("segment length must be a positive integer") if self.attention_mode not in ATTENTION_MODES: raise LanceSequenceError("unsupported attention mode: {}".format(self.attention_mode)) raise PackedSequenceError("unsupported attention mode: {}".format(self.attention_mode)) if self.expert not in EXPERTS: raise LanceSequenceError("unsupported expert: {}".format(self.expert)) raise PackedSequenceError("unsupported expert: {}".format(self.expert)) if not self.modality: raise LanceSequenceError("segment modality must not be empty") raise PackedSequenceError("segment modality must not be empty")
@property def normalized_attention_mode(self) -> str:1 unmodified line
@dataclass(frozen=True)class LanceDocument:class PackedDocument: sample_id: str segments: Tuple[LanceSegment, ...] segments: Tuple[PackedSegment, ...]
def __post_init__(self) -> None: if not self.sample_id: raise LanceSequenceError("sample_id must not be empty") raise PackedSequenceError("sample_id must not be empty") if not self.segments: raise LanceSequenceError("a document must contain at least one segment") raise PackedSequenceError("a document must contain at least one segment")
@property def length(self) -> int:14 unmodified lines
@dataclass(frozen=True)class LancePackedSequence: documents: Tuple[LanceDocument, ...]class PackedSequence: documents: Tuple[PackedDocument, ...]
def __post_init__(self) -> None: if not self.documents: raise LanceSequenceError("a packed sequence must contain at least one document") raise PackedSequenceError("a packed sequence must contain at least one document") sample_ids = [document.sample_id for document in self.documents] if len(sample_ids) != len(set(sample_ids)): raise LanceSequenceError("sample_id values must be unique inside a packed sequence") raise PackedSequenceError("sample_id values must be unique inside a packed sequence")
@property def length(self) -> int:21 unmodified lines result = {name: tuple(values) for name, values in indexes.items()} combined = sorted(result["understanding"] + result["generation"]) if combined != list(range(self.length)): raise LanceSequenceError("expert routing must cover every packed token exactly once") raise PackedSequenceError("expert routing must cover every packed token exactly once") return result
def block_schedule(self) -> Tuple[AttentionBlock, ...]:8 unmodified lines blocks: List[AttentionBlock] = [] document_offset = 0 for document_index, document in enumerate(self.documents): segment_ranges: List[Tuple[int, int, LanceSegment]] = [] segment_ranges: List[Tuple[int, int, PackedSegment]] = [] cursor = document_offset for segment in document.segments: segment_ranges.append((cursor, cursor + segment.length, segment))112345 unmodified lines1011121314151314151617"""Apply the same annotation as the evaluation pipeline.""""""Add spelling annotations to quoted text."""import refrom .add_spelling import add_spelling
5 unmodified linesdef augment_caption(caption: str) -> str: """Annotate quoted text once, including individual Chinese characters.
English annotations use the training-time spelling function. That function accepts English only, so quoted Chinese and other remaining target text use the same annotation syntax with each character separated by a space. Use the English spelling helper first, then annotate any remaining quoted text with a space between characters and a slash between words. """ if not QUOTED.search(caption): return caption9 unmodified lines101112131314151614 unmodified lines31323334353637383937384039404142433 unmodified lines47484950509 unmodified lines "eva_config": null, "exclude_modules": null, "fan_in_fan_out": false, "inference_mode": true, "inference_mode": false, "init_lora_weights": "gaussian", "layer_replication": null, "layers_pattern": null,14 unmodified lines "rank_pattern": {}, "revision": null, "target_modules": [ "to_q", "gate_layer", "to_out.0", "to_v", "proj", "to_k", "to_out.0", "out", "out" "gate_layer", "to_q" ], "target_parameters": null, "task_type": null,3 unmodified lines "use_qalora": false, "use_rslora": false, "velora_config": null}}12323version https://git-lfs.github.com/spec/v1oid sha256:58184cb1c39fbaf094f371990ac9fcd9cbe27507e9f06d5e230eaa51c80d12d8size 401148288oid sha256:055be94f809c4e304407a789b4b8ffec98c2dc04ca62bb5f4a5bbce8ce1d05f0size 401148304.gitattributes+3-36
DETAILS.mdAdded+328
DETAILS_zh.mdAdded+328
README.md+77-235
README_zh.md+77-235
SHA256SUMSAdded+27
assets/gallery.jpg

Large File Pointer Details
- SHA256: 7422a2aa1e1841e6953df9834c26f5a72c1329fee7a29e69b2d79932f2eaad43
- Pointer size: 132 Bytes
- Size of remote file: 1.08 MB

Large File Pointer Details
- SHA256: cc56a8ad2cc3cd7fb90d51633f82073510c206f9a43cbc133489f87e2a6934e4
- Pointer size: 132 Bytes
- Size of remote file: 1.41 MB
config.json+5-2
counting_head/__init__.pyAdded+1
counting_head/count_n_rank.pyAdded+46
counting_head/count_parser.pyAdded+60
counting_head/count_vocab.pyAdded+46
dit_norm_precision.safetensors → counting_head/head.npzRenamed+2-2
counting_head/sampling.pyAdded+80
dit.safetensors+2-2
inference.py+358-73
requirements.txt+2-2
runtime/add_spelling.py+1-1
runtime/add_spelling_v2.py-1
runtime/model.py+5-5
runtime/npu_attention.py+15-15
runtime/prompt_routing.pyAdded+423
runtime/routing.py+8-2
runtime/sequence.py+21-22
runtime/spelling.py+3-4
writing_lora/adapter_config.json+6-6
writing_lora/adapter_model.safetensors+2-2