Instructions to use PrunaAI/P-Flux-2-Klein-4B-DWD with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Pruna AI
How to use PrunaAI/P-Flux-2-Klein-4B-DWD with Pruna AI:
from pruna import PrunaModel model = PrunaModel.from_pretrained("PrunaAI/P-Flux-2-Klein-4B-DWD") - Notebooks
- Google Colab
- Kaggle
Download docs/usage.md from PrunaAI/P-Flux-2-Klein-4B-DWD: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD/resolve/main/docs/usage.md
- Command line
-
hf download hf://PrunaAI/P-Flux-2-Klein-4B-DWD/docs/usage.md
-
curl -L -o usage.md https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD/resolve/main/docs/usage.md
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) on 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.
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_outandproj_outare fine-tuned (about 0.5B parameters). - Head. A
Linear(3072 -> 768)reads thenorm_outimage 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_outvelocity, Euler update). At the last step the head predicts the image directly: noproj_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:
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:
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
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
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_outorproj_outchanges 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.
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:
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 savesckpt_000000.pt.--init-from <run>/ckpt_000000.ptreuses another run's fit. - The discriminator (DINO ViT-S/8, downloaded from the Hugging Face Hub;
--dino-pathfor a localmodel.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-batchstays 128. The global batch must be a multiple of micro-batch x number of GPUs (for example--micro-batch 4on 8 GPUs accumulates 4 micro-batches per step). - Resume. A run resumes from
<ckpt-root>/<run-name>/latestwhen started again with the same command.--keepsets how many recent checkpoints are kept (plusckpt_000000.pt);--keep-every Nalso keeps every N-th. - Time limits and preemption.
--max-hoursor 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-stepsconsecutive non-finite steps.torchrunreports 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.--smokeruns a 20-iteration end-to-end check. - Use
--run-name, not--run:torchrunwould match--runagainst its own--run-path.
Run python scripts/train.py --help for every option.
3. Evaluate
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
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
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
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:
@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:
@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 and 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.