Run this model with HF Jobs

Run PrunaAI/P-Flux-2-Klein-4B-DWD on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
File size: 15,861 Bytes
24baf68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# P-Flux-2-Klein-4B-DWD: FLUX.2 [klein] 4B without a VAE decoder

This repository reproduces DWD ("Decoding Without a Decoder: Direct Pixel Prediction from Diffusion Transformers",
[arXiv 2611.22287](https://arxiv.org/abs/2611.22287)) on
[FLUX.2 [klein] 4B](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B). A fine-tuned copy of the
transformer's last 4 single blocks and a small linear pixel head turn the hidden states of the last sampling step
straight into an RGB image, so the VAE decoder is never run. It contains the inference pipeline, the full training
recipe, data preparation, evaluation, checkpoint export and a latency benchmark.

The Python package is `dwd_klein` (pip distribution `p-flux-2-klein-4b-dwd`). A ComfyUI version, which needs no
Python package and no pinned library versions, is at
[PrunaAI/P-Flux-2-Klein-4B-DWD-Comfy](https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD-Comfy).

## How it works

- **Tail.** FLUX.2 [klein] 4B has 5 double-stream and 20 single-stream blocks. The first 21 blocks stay frozen. The
  last 4 single blocks, their own copies of the time embedding and single-block modulation, `norm_out` and `proj_out`
  are fine-tuned (about 0.5B parameters).
- **Head.** A `Linear(3072 -> 768)` reads the `norm_out` image tokens. Each token becomes one 16x16 pixel patch with 3
  channels of normalized Oklab, which is converted to sRGB. The head is initialized by closed-form least squares.
- **Sampling.** The 4-step sampler runs as usual for steps 0-2 (`proj_out` velocity, Euler update). At the last step
  the head predicts the image directly: no `proj_out`, no final Euler update, no VAE decode.
- **Training.** Real images are noised, run through the frozen prefix and the trainable tail, and the head output is
  compared with the clean image: L1 + LPIPS (VGG) + an adaptive adversarial loss (a DINO ViT-S/8 discriminator on
  random crops, with DiffAugment). A trajectory loss (MSE between the tail's velocity and the original model's
  velocity at high noise levels) keeps steps 0-2 on the original sampling path. A Karras power EMA of the weights is
  exported.

## Results

Released tail: 26k iterations, EMA weights. Measured on 64 prompts (curated prompts and held-out captions) across the
five trained sizes, and on 32 held-out real photos. LPIPS uses VGG features.

| Comparison | PSNR ↑ | LPIPS (VGG) ↓ |
|---|---:|---:|
| DWD head vs the stock VAE image, same prompt and seed (64 prompts) | 25.5 dB | 0.137 |
| Held-out photos, last-step denoising: DWD head vs the real photo | **22.2 dB** | **0.289** |
| Held-out photos, last-step denoising: base model + VAE decode vs the real photo | 20.9 dB | 0.316 |

The first row shows how close the output stays to the stock model's image: close but not identical, and the stock
VAE image can be sharper in fine detail. The last two rows noise each held-out photo to the noise level of the final
sampling step and compare one final step against the real photo: the DWD head recovers it more closely than the base
model's last step followed by the VAE decode. This measures a single step on real photos, not the detail of generated
images. Example images are on the model card.

### Speed

FLUX.2 [klein] 4B on one NVIDIA B200, batch 1, 4 steps, bf16, end to end (text encoder, 4 transformer steps and the
decode, until the uint8 image is on the host), with the full Qwen3 text encoder the stock pipeline runs. Measured with
`scripts/benchmark_latency.py`, which interleaves both paths on the same GPU.

| Mode | Resolution | With VAE decode | With DWD head | Speedup |
|---|---|---:|---:|---:|
| eager | 1024 x 1024 | 316 ms | 234 ms | **1.35x** |
| eager | 1440 x 1440 | 625 ms | 453 ms | **1.38x** |
| `torch.compile` | 1024 x 1024 | 186 ms | 155 ms | **1.20x** |
| `torch.compile` | 1440 x 1440 | 358 ms | 291 ms | **1.23x** |

The VAE decode alone takes 81 ms eager and 25 ms compiled; the head and the Oklab-to-sRGB conversion take about
0.5 ms. Peak activation memory is about 2 GB lower at 1 MP. 1440 x 1440 is outside the training sizes and is listed
for speed only.

## Installation

Python 3.10+ and PyTorch 2.6+. A CUDA GPU is needed for practical use.

The repository holds the code and the trained tail (`dwd_tail.safetensors`, 1.1 GB, stored with Git LFS). Clone it
without the large files and install the code; `from_pretrained` downloads the tail once into the Hugging Face cache on
first use:

```bash
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD
pip install ./P-Flux-2-Klein-4B-DWD
```

Install from a clone: `pip install git+https://huggingface.co/...` does not work, because pip makes a partial clone,
which the Hugging Face git server does not support. For training, the tests or the scripts, install the clone in
editable mode:

```bash
cd P-Flux-2-Klein-4B-DWD
pip install -e .              # inference
pip install -e ".[train]"     # + training and evaluation (LPIPS)
pip install -e ".[data]"      # + Hugging Face dataset input for prepare_data.py
pip install -e ".[dev]"       # + tests
```

`GIT_LFS_SKIP_SMUDGE=1` leaves `dwd_tail.safetensors` and the example images as small pointer files. Without Git LFS
installed nothing large is downloaded either. To use the cloned tail instead, run `git lfs pull --include
dwd_tail.safetensors` and pass the clone directory as `--tail`.

`diffusers` is pinned to 0.41.0 because the model surgery uses its module attribute names. `transformers` is
limited to 5.14.1 (the version the released numbers were measured with) up to 5.24.x; 5.14.1, 5.18.0, 5.23.0 and
5.24.0 give bit-identical images.

## Quickstart

```bash
python scripts/generate.py --prompt "a red fox in fresh snow at sunrise" --out fox.png
```

`--tail` takes a Hugging Face repo id (default `PrunaAI/P-Flux-2-Klein-4B-DWD`), an exported `dwd_tail.safetensors`
file, or a directory holding it. The base model (`black-forest-labs/FLUX.2-klein-4B`, override with `--base`) is
downloaded on first use, without its VAE: the VAE is neither downloaded nor loaded. Other options: `--width`,
`--height`, `--seed`, `--steps`, `--device`, and `--compile` (or `--compile reduce-overhead` for CUDA graphs; the first
image per size is slow). Repeat `--prompt` for several images.

### Python API

```python
from dwd_klein.pipeline import DWDKleinPipeline

pipe = DWDKleinPipeline.from_pretrained("PrunaAI/P-Flux-2-Klein-4B-DWD")   # or a local .safetensors file / directory
image = pipe("a red fox in fresh snow at sunrise", width=1024, height=1024, seed=0)
image.save("fox.png")

# several prompts (seeds 0, 1, ...), numpy output
images = pipe(["a lighthouse at dusk", "a bowl of ramen"], width=1344, height=768, seed=0, output_type="np")

# torch.compile (static shapes, one compile per resolution)
pipe.enable_compile()                    # or pipe.enable_compile("reduce-overhead")
```

`from_pretrained(tail="PrunaAI/P-Flux-2-Klein-4B-DWD", base=..., device=..., compile=...,
truncate_text_encoder=True)` loads the base transformer, moves its last 4 single blocks, `norm_out` and `proj_out`
out, and loads the trained tail in their place, so peak memory stays at one transformer. The text encoder keeps only
the Qwen3 layers the prompt embedding reads; the embeddings are the same as with the full model. To bring your own
modules, use
`DWDKleinPipeline.from_components(transformer, tail, text_encoder, scheduler=None)`. `output_type` is `"pil"`,
`"np"` or `"pt"`. Precomputed `prompt_embeds` can be passed instead of encoding prompts.

### Supported sizes

Width and height must be multiples of 16. The tail was trained for 4 steps at about 1 MP in five aspect buckets
(width x height): 1024 x 1024, 1152 x 896, 896 x 1152, 1344 x 768, 768 x 1344. Other sizes run but their quality has
not been evaluated. The sampler expects the 4 steps the tail was trained for; another `steps` value runs with a
warning.

### Limitations

- Text-to-image only. Image editing and reference-image conditioning are not supported.
- Trained and evaluated at about 1 MP and 4 steps.
- LoRAs are untested. A LoRA that touches the last 4 single blocks, `norm_out` or `proj_out` changes weights the
  tail replaces, so it will not carry over.
- The output is close to, not identical with, the stock VAE image for the same seed.

## Training

### 1. Prepare data

Any images with captions work. `scripts/prepare_data.py` builds bucketed tar shards (images of 1 MP or more,
centre-cropped to the nearest of the five aspect buckets). See [docs/data_format.md](data_format.md).

```bash
python scripts/prepare_data.py --images ./my_images --out ./data          # cat.jpg + cat.txt pairs
python scripts/prepare_data.py --captions-file pairs.jsonl --out ./data   # JSONL / CSV of path + caption
python scripts/prepare_data.py --hf-dataset <user>/<dataset> --image-column image --caption-column caption --out ./data
```

Hugging Face inputs need `pip install -e ".[data]"` (the `datasets` package). The released tail was trained on about 420k real images at 1 MP or
more across five aspect buckets.

### 2. Train

One process per GPU with `torchrun`. The defaults are the full recipe; the flags below spell it out:

```bash
torchrun --standalone --nproc_per_node 8 scripts/train.py \
    --run-name dwd-klein-4b --data-root ./data --ckpt-root ./checkpoints \
    --k 4 --iters 26000 --d-start 2500 --adv-start 3000 \
    --global-batch 128 --micro-batch 16 \
    --lr 1e-4 --head-lr-mult 5 --warmup 100 --clip 200 --lambda-traj 10 \
    --ema-gamma 7 --ckpt-every 500 --keep 2
```

- Without a checkpoint, the run first fits the head by least squares (`--lsq-images`, default 10000) and saves
  `ckpt_000000.pt`. `--init-from <run>/ckpt_000000.pt` reuses another run's fit.
- The discriminator (DINO ViT-S/8, downloaded from the Hugging Face Hub; `--dino-path` for a local
  `model.safetensors`) trains from `--d-start`, and the adversarial loss is added from `--adv-start`.
- **Memory.** On the reference setup (8 GPUs, micro-batch 16, activation checkpointing on) peak memory is about
  115 GB per GPU. On 80 GB cards use a smaller `--micro-batch`: the trainer accumulates gradients so that
  `--global-batch` stays 128. The global batch must be a multiple of micro-batch x number of GPUs (for example
  `--micro-batch 4` on 8 GPUs accumulates 4 micro-batches per step).
- **Resume.** A run resumes from `<ckpt-root>/<run-name>/latest` when started again with the same command. `--keep`
  sets how many recent checkpoints are kept (plus `ckpt_000000.pt`); `--keep-every N` also keeps every N-th.
- **Time limits and preemption.** `--max-hours` or SIGTERM / SIGINT stops the run after writing a checkpoint, with
  exit status 3: run the same command again to resume. Exit status 4 means it aborted after `--max-bad-steps`
  consecutive non-finite steps. `torchrun` reports any worker failure as 1, so the reason is also written to
  `<ckpt-root>/<run-name>/exit_status.json`.
- Logs go to `<ckpt-root>/<run-name>/log.jsonl`. `--smoke` runs a 20-iteration end-to-end check.
- Use `--run-name`, not `--run`: `torchrun` would match `--run` against its own `--run-path`.

Run `python scripts/train.py --help` for every option.

### 3. Evaluate

```bash
python scripts/evaluate.py --ckpt checkpoints/dwd-klein-4b/latest --out eval/dwd-klein-4b --prompts 64 --val-root ./data
```

On one GPU, this generates images from built-in prompts (and held-out captions with `--val-root`) and reports PSNR
and LPIPS (AlexNet, VGG) of the DWD image against the original model's VAE image and the adapted model's own VAE
image, from the same final step. With `--val-root` it also reconstructs held-out real images. It writes
`results.json` and comparison grids to `--out`. `--ckpt` takes a training checkpoint (`.pt`, EMA weights unless
`--no-ema`), a run directory, its `latest` file, or an exported tail.

### 4. Export

```bash
python scripts/export_checkpoint.py --ckpt checkpoints/dwd-klein-4b --out dwd_tail.safetensors
```

Keeps only the tail and head (EMA weights, bf16 by default; `--raw` for the raw weights, `--fp32` for fp32) and
writes metadata the pipeline checks on load (block count, head layout, Oklab constants, base model).

### 5. Latency benchmark

```bash
python scripts/benchmark_latency.py --tail dwd_tail.safetensors --sizes 1024x1024,1440x1440 \
    --modes eager,compile --out latency.json
```

Times the stock VAE path and the DWD path interleaved on the same GPU (median of paired differences with a bootstrap
95% CI), plus component timings and peak activation memory. Modes: `eager`, `eager_cudnn`, `compile`,
`reduce-overhead`. Both paths use the full Qwen3 text encoder, as the stock pipeline does
(`--truncated-text-encoder` times the truncated one instead). It first checks the DWD image against the VAE image (PSNR, `--min-psnr`) and exits with status 1
if the tail looks broken.

## Tests

```bash
pip install -e ".[dev]"
pytest -q
```

The tests run on CPU with tiny random models.

## Repository layout

```
dwd_tail.safetensors   the released tail + head (bf16, EMA weights), loaded by DWDKleinPipeline.from_pretrained
assets/examples/       example images for the model card (stock VAE decode vs DWD head)
src/dwd_klein/
  pipeline.py   DWDKleinPipeline: text-to-image without the VAE
  export.py     training checkpoint -> dwd_tail.safetensors
  model.py      model surgery: frozen prefix, reference tail, trainable tail + head
  color.py      normalized Oklab <-> sRGB, patch layout, latent packing
  schedule.py   klein's timestep shift, 4-step sigmas, training timestep sampling
  losses.py     L1, LPIPS, trajectory MSE, adaptive adversarial weight, GAN losses
  disc.py       DINO ViT-S/8 discriminator + DiffAugment
  ema.py        Karras power EMA
  lsq.py        least-squares head init
  data.py       bucketed tar-shard loader with exact resume
  prepare.py    dataset builder (scripts/prepare_data.py)
  encoders.py   text encoder and VAE wrappers, model download
  build.py      builds the training components, loads trained tails
  trainer.py    training loop, checkpointing, resume
  evaluate.py   sampler and evaluation metrics
scripts/        generate, train, evaluate, export_checkpoint, benchmark_latency, prepare_data
docs/           usage.md (this file), data_format.md
tests/          CPU tests with tiny random models
LICENSE         Apache License 2.0
NOTICE          attributions (FLUX.2 [klein] 4B, RAE, AsymFlow)
CITATION.cff
pyproject.toml
```

## Acknowledgements

- Hansheng Chen, Shengqu Cai, Jan Ackermann, Rayhan Zirvi, Gordon Wetzstein, Xinchen Yan and Leonidas Guibas for
  DWD.
- LakonLab's AsymFlow for the normalized Oklab colour encoding.
- RAE for the DINO discriminator design, and DiffAugment for the discriminator augmentations.
- LPIPS (Zhang et al.) for the perceptual loss and metric.
- Black Forest Labs for FLUX.2 [klein] 4B, and Hugging Face diffusers and transformers.

## Citation

If you use this code or the released weights, please cite the DWD paper:

```bibtex
@article{chen2026dwd,
  title   = {Decoding Without a Decoder: Direct Pixel Prediction from Diffusion Transformers},
  author  = {Chen, Hansheng and Cai, Shengqu and Ackermann, Jan and Zirvi, Rayhan and Wetzstein, Gordon
             and Yan, Xinchen and Guibas, Leonidas},
  journal = {arXiv preprint arXiv:2611.22287},
  year    = {2026}
}
```

and this repository:

```bibtex
@software{p_flux_2_klein_4b_dwd,
  title  = {P-Flux-2-Klein-4B-DWD: Decoding Without a Decoder for FLUX.2 [klein] 4B},
  author = {{Pruna AI}},
  year   = {2026},
  url    = {https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD}
}
```

## License

Apache-2.0, see [LICENSE](../LICENSE) and [NOTICE](../NOTICE). The tail is derived from FLUX.2 [klein] 4B
(Apache-2.0); modified: the last 4 single blocks, the time embedding and modulation copies, `norm_out`, `proj_out`,
plus a new head.