moss4gb / NOTES.md
AEUPH's picture
moss4gb v0.2.0: NF4 4-bit MOSS-Image-SFT packaging (code, bank, tests, docs, skill)
1533f24 verified
|
Raw History Blame Contribute Delete
12.2 kB
# MOSS-Image 4 GB — state of the build
Continuation notes. Last worked: 2026-10-29.
## What this is
A working inference path for `OpenMOSS-Team/MOSS-Image-SFT` on a GTX 1050 Ti
(4 GB, Pascal sm_61, Windows) that never loads the 9B text encoder:
| Piece | Where | Footprint |
|---|---|---|
| DiT | GPU, bitsandbytes NF4 | 2.76 GB |
| Text encoder | absent at inference | 0 |
| VAE | CPU, fp32 | 250 MB RAM |
| Prompt conditioning | `assets/bank/bank.safetensors` | ~300 KB/entry |
## Measured on this box (not estimated)
| Metric | Value |
|---|---|
| DiT load (streaming, from scratch) | 349-513 s (0.3-0.5 s/layer, I/O bound) |
| DiT VRAM resident | 2.77 GB (`262` Linear -> NF4, 7 kept fp16, 5.08 B params) |
| 256x256, 4 steps, cfg 1 | 11.6 s total, **2.91 s/step** |
| 256x256, 6 steps, cfg 3 | 82.8 s total, **13.8 s/step** |
| Peak VRAM at 256x256 | **2.90 GB** |
| VAE decode 256x256 on CPU | 7.8-28.5 s (machine load dependent) |
| VAE decode 512x512 on CPU | 51.6 s |
| Decode parity vs upstream pipeline | **max abs diff 0.0** (`scripts/decode_parity.py`) |
| Python imports after metadata cache | 23 s (was minutes) |
| Test suite | 26 passed in ~21 s |
Verified end to end: `out/smoke_256.png` and `out/final_256.png`, 256x256,
real image structure (std 50-67, ~62k unique colours), produced from a null
one-token embedding. Unconditioned, so the content is meaningless — but every
stage of the path executed.
## What is verified vs not
Verified:
* NF4 DiT runs on Pascal with fp16 compute, no NaN (`--compute-dtype float16`).
* Streaming loader peaks at ~6.8 GB RSS, never materializes the fp16 model.
* The pipeline runs with `text_encoder=None, tokenizer=None` and `prompt_embeds`.
* CPU decode is bit-identical to upstream's in-pipeline decode.
* Prompt formatting is byte-exact with upstream: `bank build --dry-run` shows
`a wide view of a red bicycle` -> 17 tokens, empty negative -> 10 tokens.
* `python -m pytest tests -q` -> 26 passed in ~21 s, no GPU needed.
Not verified:
* 512x512 on the real model. Attempted twice (2 steps, cfg 3). Both times the
DiT loaded and sampling began, then the process was killed externally with
no traceback — not a Python error and not a CUDA OOM. Observed steady state:
3.89 GB used / 113 MB free, i.e. the card is full and the driver is paging
into shared memory. Try `--cfg 1` (halves the activation peak) with nothing
else on the desktop before concluding 512 does not fit.
* Any *real* prompt. The bank on disk is the null bank — it conditions on
nothing, so images are unrelated to any text.
* fp16 overflow at higher token counts. Watch for NaN/black output; if it
happens use `--compute-dtype float32`, or swap in
`KBlueLeaf/MOSS-Image-FP16-fixed` (`sft/transformer`), which exists for
exactly this reason.
## Trap found: the repo ships a tokenizer with no chat template
`tokenizer/tokenizer_config.json` in the MOSS repo has **no `chat_template`**,
so `MOSSImagePipeline.encode_prompt`'s `apply_chat_template` raises
`ValueError` with the tokenizer the repo ships. The template upstream actually
uses comes from `Qwen/Qwen3.5-9B` (and `model_index.json` points the tokenizer
at `Qwen2Tokenizer`).
It matters because the template decides the exact tokens the DiT was trained
on, including the `enable_thinking=True` branch that appends
`<|im_start|>assistant\n thinking\n`. Get it wrong and conditioning degrades
silently instead of failing.
`bank.load_chat_template()` reads `assets/qwen35_chat_template.jinja` (a copy
of the Qwen3.5-9B template, 7756 chars) and attaches it to the tokenizer when
the bundled one has none. `bank build --dry-run` prints the formatted prompt
and token count without loading any model, so this can be checked on this box.
## The blocking item: the prompt bank
The DiT eats Qwen3.5-9B hidden states (`[B, S, 4096]`). Producing them needs the
16.78 GB encoder **once**, and this machine cannot do it:
* 17.1 GB total RAM, ~6 GB free (the encoder is 16.8 GB bf16).
* `transformers 4.51.0` installed; `Qwen3_5Model` needs **>= 5.3**.
* 27.7 GB free on `Z:`; encoder (17 GB) + DiT (9.5 GB) does not fit together.
So build the bank elsewhere and copy it in:
```bash
# check the prompt formatting first; costs seconds and no model download
python -m moss4gb bank build --dry-run --prompt "a wide view of a red bicycle"
huggingface-cli download OpenMOSS-Team/MOSS-Image-SFT \
--include 'text_encoder/*' --local-dir models/MOSS-Image-SFT
python -m moss4gb bank build --prompt "a wide view of a red bicycle" # needs >=20 GB RAM
python -m moss4gb bank import --source /path/to/bank # on this box
```
`bank build` also encodes the empty prompt into `__negative__`, which CFG needs
whenever `--cfg != 1`.
## Decisions and why
* **NF4 via bitsandbytes, not GGUF.** GGUF wins in ComfyUI because it dequantizes
per layer; here the DiT is a custom class loaded through diffusers, and bnb
drops in without touching the model code. NF4 also keeps `Params4bit.dtype`
at `float16` (our `quant_storage`), which is what lets upstream's
`y.to(self.proj["q"].weight.dtype)` keep working unmodified.
* **Skip list in `quant.py`.** `video_embedder`, `final_linear_video`,
`final_norm_video`, `time_embedding`, `*_modulation`, `text_embedder.proj`,
`rope` stay fp16. Matching must cover child paths: `time_embedding` is an
`nn.Sequential`, so its Linears are named `time_embedding.0` / `.2`. An exact
suffix match missed them and quietly quantized the timestep MLP; the tests
now pin this. `text_embedder.proj` is skipped on purpose: it is the layer
that consumes the prompt embedding, and quantizing it would add error to
every conditioning vector for 25 MB of savings.
* **CPU VAE decode.** 250 MB weights do not need the card, and the pipeline's
decode needs its own BatchNorm fold + 2x2 channel unshuffle, so it lives in
`decode.py` rather than being delegated to a stock decode.
* **`metadata_cache.py`.** diffusers calls
`importlib.metadata.packages_distributions()` at import; on this Python 3.14
install that scan takes minutes (811 distributions). Cached to
`.cache/packages_distributions.json` and monkeypatched. Delete the cache or
set `MOSS4GB_REFRESH_METADATA=1` after installing packages.
## Environment gotchas (cost hours, do not rediscover)
* `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` is **not supported on
Windows** — it warns and is ignored.
* The desktop (Edge, explorer, terminal) holds 0.8-1.3 GB of the 4 GB. Check
`nvidia-smi` before a run; VRAM does return after a killed process, but with
a lag of seconds.
* `if [ "$(nvidia-smi ...)" -gt N ]` loops are the fastest way to wait for it.
* Load is I/O bound: reading the 3 shards in *file order* matters. Walking the
module tree instead scatters 264 reads across 5 GB and takes far longer.
* Background jobs started through the tool get killed after roughly 45-55 min.
Anything that needs the model loaded plus more than ~35 min of sampling has
to be split or given its own terminal.
* `python -m moss4gb ...` works from the project root; a script in `scripts/`
needs the `sys.path.insert` bootstrap (see `scripts/verify.py`).
## Next steps, in order
0. **DONE - the real bank exists.** Built on Colab free tier (T4, int8 encoder)
and imported: `p_157d4f7a84a3` = `blonde female with pink dreadlocks`,
`(17, 4096)`, one entry for `__negative__` `(10, 4096)`. Encoder pass took
93.3 s for both prompts; std 1.99; cosine(prompt, empty) **0.574**.
Archive kept at `assets/bank_from_colab.tgz`; recipe in
`docs/BUILD_BANK_GPU.md`. The blocker was local VRAM, not the model: with
`AlchemyBeta.exe` resident only ~0.75 GB of the 4 GB was free, and the
loader needs ~3 GB (a segfault at cudaMalloc, exit 139).
0b. **Why the old output was garbage: the null bank, not the 4-bit path.**
`assets/bank` used to hold a single all-zeros token, so the DiT got a caption slot it never saw:
one token instead of ~20 (the RoPE frame coordinate for the text is the text
length, so the geometry is wrong too) and zero values instead of Qwen hidden
states. Same seed + same constant conditioning is also why the image is
byte-identical and instant on repeat Queues. See `docs/BUILD_BANK_GPU.md` for
the one remaining step; it needs a borrowed GPU (20 GB bf16 / 9 GB int8),
not anything on this box.
1. **DONE - the 4 GB path renders a correctly conditioned image.**
`generate --bank-id p_157d4f7a84a3 --height 256 --width 256 --steps 20
--cfg 3 --seed 42`: load 621.7 s, 20 steps in 106.0 s (5.30 s/step), peak
VRAM 2.90 GB, CPU decode 7.9 s, `out/real_256.png`. The output is a
recognisable portrait matching "blonde female with pink dreadlocks", so
NF4 weights, real Qwen hidden states and the CPU VAE decode are all correct
end to end - the earlier garbage was the null bank, nothing else.
Constraint learned here: one process owns the whole card. A second run
started while the first was loaded segfaults at load with no traceback, so
`generate` now pre-flights free VRAM and exits with the number instead.
2. **Load-time cache.** 8.5 min per run is the worst part of the UX. Save the
quantized DiT once (bnb `Params4bit` state + `quant_state`) and load it back
in ~1 min; or keep a warm process and generate from a queue.
3. **512x512.** Try it with `--cfg 1` first to halve the activation peak, and
with nothing else running on the desktop. If it pages, 448x448 is the next
step down (both are multiples of 16).
4. **Image conditioning** (the original question). The text slot takes any
`[S, 4096]`; a `Linear(128 -> 4096)` on VAE latents plus LoRA on the two
`_TextProjection` blocks is the minimal bridge. Watch the RoPE coupling: the
image tokens' frame coordinate equals the text length, so swapping a
200-token caption for 64 image tokens moves the target image from frame 200
to frame 64 — train and infer at the same count.
5. **Community shortcuts worth testing**, not yet tried: `lodestones/MOSS-Image-SFT-8-steps-dmd`
(few-step, would cut 20 steps to 8) and `MATLOWAI/MOSS-Image-SFT-DeBand`
(vertical banding, which this model is reported to show).
## Dead ends already paid for (do not retry)
* **llama.cpp + Q4 GGUF encoder on CPU.** `/d/llama-agent` knows `qwen35`, but
`llama-embedding` cannot produce per-token hidden states for the hybrid GDN
model: the example expands `n_parallel` to `llama_max_parallel_sequences()`
(256) and asks for 13.5 GB of recurrent-state cache; with `n_parallel = 1`
patched in, `llama_batch_allocr::init` still rejects the multi-output batch.
The GGUF is also Heretic (abliterated), so it would not match upstream
conditioning anyway.
* **HDC memory for embeddings.** One prompt embedding is 139 KB; the encoder
that makes it is 16.78 GB. Compressing the 0.01% does not help, and
bind/bundle is not invertible, so it cannot produce `[S, 4096]` floats.
* **BitNet / ternary DiT.** No ternary-trained MOSS exists, post-hoc
ternarization of a diffusion transformer destroys it, and there is no sm_61
ternary matmul kernel.
## File map
```
conftest.py puts the project root on sys.path for pytest
assets/qwen35_chat_template.jinja Qwen3.5-9B chat template (the repo ships none)
tests/ CPU-only suite: bank, chat formatting, skip list, decode parity
moss4gb/quant.py streaming NF4 loader (meta skeleton -> file-order shards -> GPU)
moss4gb/decode.py CPU VAE decode: BatchNorm fold + 2x2 channel unshuffle
moss4gb/bank.py bank format, null bank, encoder-side builder
moss4gb/metadata_cache.py importlib.metadata scan cache (diffusers import cost)
moss4gb/vendor.py loads upstream pipeline_moss_image.py from the model dir
moss4gb/cli.py doctor / bank / generate
scripts/decode_parity.py cheap correctness proof against upstream's own decode
scripts/verify.py full acceptance run (parity + 512 run); needs ~20 min
out/ smoke_256.png
models/MOSS-Image-SFT/ transformer (9.5 GB) + vae (250 MB) + configs
```