diff --git a/patch-forcing/.codex b/patch-forcing/.codex
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/patch-forcing/.gitignore b/patch-forcing/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..93bf918eb923920c8c2fc002638986788c6802ad
--- /dev/null
+++ b/patch-forcing/.gitignore
@@ -0,0 +1,16 @@
+sandbox
+checkpoints
+results
+logs
+wandb
+outputs
+
+*__pycache__*
+.idea
+venv
+
+*.DS_Store
+*._.DS_Store
+shardsFaceHQ
+testy.ipynb
+third_party
diff --git a/patch-forcing/README.md b/patch-forcing/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..a8e89d9244e8ea456c31a5d05136c8f3ff7e84f6
--- /dev/null
+++ b/patch-forcing/README.md
@@ -0,0 +1,198 @@
+
+
Denoising, Fast and Slow: Difficulty-Aware Adaptive Sampling for Image Generation
+
+
+ Johannes Schusterbauer* · Ming Gui* · Yusong Li · Pingchuan Ma · Felix Krause · Björn Ommer
+
+
+ CompVis Group @ LMU Munich, Munich Center for Machine Learning (MCML)
+
+
+ CVPR 2026
+
+
+
+
+
+
+[]()
+[](https://github.com/CompVis/patch-forcing)
+
+
* equal contribution
+
+
+
+
+
+
+
+
+# 🚀 TL;DR
+
+
+**Patch Forcing turns denoising into a spatially adaptive process.** During training, different image patches receive heterogeneous timesteps. While conceptually straightforward, this only works well with a dedicated timestep sampler that controls how much clean information is exposed per sample, closing the train–test gap where inference starts from pure noise. This framework enables dynamic sampling strategies, where easy regions can be denoised faster and provide cleaner context for harder ones.
+
+
+🔥 **Contributions**
+- Patch-wise timesteps $\rightarrow$ enables heterogeneous denoising
+- LTG timestep sampler $\rightarrow$ fixes train-test mismatch
+- Patch difficulty-guided sampling $\rightarrow$ allocates compute adaptively
+
+
+
+
+
+# 📖 Overview
+
+
+Natural images are highly spatially heterogeneous: some regions (e.g. backgrounds) are easy to denoise, while others (e.g. fine structures, text) require more refinement and context.
+However, standard diffusion and flow-based models treat all regions equally, applying the same timestep and compute everywhere.
+
+
+**Key idea**: move from global to patch-wise denoising, where different regions follow different noise trajectories.
+
+
+### Training
+
+Naively assigning random timesteps per patch does *not work*. When timesteps are sampled independently and uniformly, most training samples contain a mix of noisy and already partially clean regions. As a result, the model learns to rely on this implicit context, even though such states never occur at inference, where generation starts from pure noise. This creates a clear train–test mismatch.
+
+
+
+
+
+Prior work (SRM) addresses this by controlling the average amount of information per sample. While this partially mitigates the issue, it does not fully resolve it: even if the average is well-behaved, individual patches can still be nearly clean. In practice, this means that almost every training example still contains highly informative regions.
+
+
+Our key idea is to instead **control the maximum information** available in each sample. Concretely, we first sample a maximum timestep and then restrict all patch-wise timesteps to lie below it. This prevents any region from becoming too clean during training and ensures that the model consistently operates in regimes that match inference.
+
+With this simple change, heterogeneous patch-wise denoising works! Even without any adaptive sampling at inference, this training strategy already improves generation quality over standard diffusion models with uniform timesteps.
+
+
+### Inference
+
+To fully leverage patch-wise denoising at inference, we need to decide **which regions should be denoised faster** and **which require more refinement**. For this, we augment the model with a lightweight uncertainty (difficulty) head that predicts, for each patch, how reliable the current denoising velocity prediction is.
+
+
+
+
+
+With heterogeneous denoising and the uncertainty head, we base our adaptive samplers on three key findings:
+
+- **context helps denoising** $\rightarrow$ advancing confident (easy) regions provides cleaner context that improves predictions in harder regions
+- **uncertainty reflects patch difficulty** $\rightarrow$ higher uncertainty correlates with higher validation loss
+- **more context reduces uncertainty** $\rightarrow$ cleaner neighboring regions make difficult patches easier to denoise
+
+These findings naturally lead to adaptive sampling strategies that allocate compute where it is most useful. Instead of denoising all patches uniformly, we use the predicted uncertainty to guide the process: easy regions are advanced more aggressively, while difficult ones receive additional refinement.
+
+
+
+
+
+
+- The **dual-loop** sampler alternates between quickly advancing confident patches and refining uncertain ones with smaller steps.
+- The **look-ahead** sampler goes one step further by explicitly advancing confident patches into the future and using their cleaner states as context for denoising harder regions.
+
+**Together, these strategies turn patch-wise heterogeneity into adaptive inference, improving generation quality under the same compute budget by focusing effort where it matters most.**
+
+
+Please refer to our paper for a more detailed description of our framework. 😉
+
+
+# 🛠️ Code Setup
+
+This codebase is based on Python `3.12` and the packages listed in `requirements.txt`.
+
+First, clone the repository:
+
+```bash
+git clone git@github.com:CompVis/patch-forcing.git
+cd patch-forcing
+```
+
+Then create the environment and install the dependencies:
+
+```bash
+conda create -n pft python=3.12
+conda activate pft
+pip install -r requirements.txt
+```
+
+If the default install fails on your machine, follow the safer install order noted in ?`requirements.txt`: install `torch` and `torchvision` first, then `flash-attn`, then the remaining requirements.
+
+We release two Patch Forcing checkpoints: [PFT-B](https://ommer-lab.com/files/pft/pft-b_step400k_ema.ckpt) and [PFT-XL](https://ommer-lab.com/files/pft/pft-xl_step400k_ema.ckpt). The checkpoints contain the EMA weights, as well as the model config.
+
+### Class-Conditional Generation
+
+#### Inference
+
+To generate class-conditional samples use:
+
+```bash
+python scripts/sample.py \
+ --ckpt /path/to/model.ckpt \
+ --sample-fn-config configs/sampler/dual-loop.yaml \
+ --num-sampling-steps 100 \
+ --cfg-scale 4.0
+ # ... you can add sampler specific args via dot-notation
+```
+
+For FID samples use `scripts/sample_ddp.py`:
+
+```bash
+torchrun --standalone --nproc_per_node=8 scripts/sample_ddp.py \
+ --ckpt /path/to/model.ckpt \
+ --sample-fn-config configs/sampler/euler-pf.yaml \
+ --per-proc-batch-size 64 \
+ --num-fid-samples 50000 \
+ --num-sampling-steps 100 \
+ --cfg-scale 1.0
+```
+
+If your checkpoint comes from training and does not already contain the compact `config` + `state_dict` format expected by the samplers, convert it first:
+
+```bash
+python scripts/convert_ckpt.py /path/to/training.ckpt
+```
+
+
+#### Training
+
+You can train new models via `train.py`. The repository is based on `hydra`, and the base config lives in `configs/config.yaml`. Experiments in `configs/experiment` overwrite this base config. Use CLI overrides to swap configs or change individual fields, for example `python train.py experiment=imnet-pft-b name=imnet/my-run data=dummy256 train_params.max_steps=10000`.
+
+To directly use the ImageNet-256 webdataset file, configure the ImageNet-256 shard locations in `configs/data/imagenet256.yaml`.
+For debugging, use you can use `configs/data/dummy256.yaml`.
+
+Train the main class-conditional experiments with:
+
+```bash
+python train.py experiment=imnet-pft-b
+python train.py experiment=imnet-pft-xl
+```
+
+If you want to use your own dataloader, make sure it returns a dictionary with `image` (bchw tensor normalized to $[-1, 1]$) and `label`.
+
+### Text-to-Image
+
+For text-to-image training, first fill in the gaps in `configs/data/t2i-256.yaml` and then you can train them with
+
+```bash
+python train.py experiment=t2i-pft1.2b-qwen
+```
+
+The batch should contain a dict with `image`, text (set corresponding text key in trainer), and `img_meta` if you want to include crop size conditioning via RoPE (see `patch_flow/data_utils.py` for more info). The default loader uses random caption sampling (as we used multiple caption lengths during training).
+
+You can use `scripts/t2i_sample.py` to sample images based on a text prompt.
+
+
+## 🎓 Citation
+
+If you use our work in your research, please use the following BibTeX entry. 🙂
+
+```bibtex
+@InProceedings{schusterbauer2025patchforcing,
+ title={Denoising, Fast and Slow: Difficulty-Aware Adaptive Sampling for Image Generation},
+ author={Johannes Schusterbauer and Ming Gui and Yusong Li and Pingchuan Ma and Felix Krause and Björn Ommer},
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
+ year={2026}
+}
+```
diff --git a/patch-forcing/assets/denoising-schedule-performance.png b/patch-forcing/assets/denoising-schedule-performance.png
new file mode 100644
index 0000000000000000000000000000000000000000..3163d27b2dfa4350a70bf0f4b862f20c6cdd0efd
--- /dev/null
+++ b/patch-forcing/assets/denoising-schedule-performance.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6233a5d24570c3413d8d44772d91a0315d23c1d29a91da7c2d4c265086b93302
+size 599675
diff --git a/patch-forcing/assets/fpf-inference.png b/patch-forcing/assets/fpf-inference.png
new file mode 100644
index 0000000000000000000000000000000000000000..a893cbebd1723e52888d2a44e9189696830a2a14
--- /dev/null
+++ b/patch-forcing/assets/fpf-inference.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b949a07d68b7ab555454532d16cd338c6d8d89b86cdbea81771342c3ba57e500
+size 1424263
diff --git a/patch-forcing/assets/fpf.png b/patch-forcing/assets/fpf.png
new file mode 100644
index 0000000000000000000000000000000000000000..acb88dd9a57bd0893f9b7ef180bfb0dbda10f001
--- /dev/null
+++ b/patch-forcing/assets/fpf.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:abdda6da181e461cb6b46c9425ce8d7574ef931ebc648af8db86858878cfeb1e
+size 670407
diff --git a/patch-forcing/assets/srm-comparison.png b/patch-forcing/assets/srm-comparison.png
new file mode 100644
index 0000000000000000000000000000000000000000..84a619a6cc7817a959aa259cd385c8d59a402118
--- /dev/null
+++ b/patch-forcing/assets/srm-comparison.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a6ab5c1e2d2dac3805a986daa1320111877414fd319cb93dc863d608304b7ff5
+size 209784
diff --git a/patch-forcing/assets/uncertainty.png b/patch-forcing/assets/uncertainty.png
new file mode 100644
index 0000000000000000000000000000000000000000..dca9b20214529cceb23d8b88a46f4ac65084cd16
--- /dev/null
+++ b/patch-forcing/assets/uncertainty.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e94e2795f85496b88708cee1135aa57e438257bdedb704a888799e4bd2015ea4
+size 1592475
diff --git a/patch-forcing/checkpoints/pft-b_step400k_ema.ckpt b/patch-forcing/checkpoints/pft-b_step400k_ema.ckpt
new file mode 100644
index 0000000000000000000000000000000000000000..f2d9d406fc15e68309a2223b77d55e22b7cdc17d
--- /dev/null
+++ b/patch-forcing/checkpoints/pft-b_step400k_ema.ckpt
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:941eeaf3a9c19639b57b22542614e6bd006b69f58437e825aedbd1baee188b57
+size 522055289
diff --git a/patch-forcing/checkpoints/sd_ae.ckpt b/patch-forcing/checkpoints/sd_ae.ckpt
new file mode 100644
index 0000000000000000000000000000000000000000..dce06e602ec452fc70a994dc2cad6ffb3e489239
--- /dev/null
+++ b/patch-forcing/checkpoints/sd_ae.ckpt
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d06a99897e89e3f973096adb8762fa7e260638157064330c6b8c325594b54ad9
+size 334676563
diff --git a/patch-forcing/checkpoints/sd_ae_full.ckpt b/patch-forcing/checkpoints/sd_ae_full.ckpt
new file mode 100644
index 0000000000000000000000000000000000000000..564371905c2c59bd7a412f590192d4e9693df186
--- /dev/null
+++ b/patch-forcing/checkpoints/sd_ae_full.ckpt
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0b204ad0cae549e0a7e298d803d57e36363760dec71c63109c1da3e1147ec520
+size 334695179
diff --git a/patch-forcing/configs/autoencoder/flux2_ae.yaml b/patch-forcing/configs/autoencoder/flux2_ae.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..cc1c8f5564b0186756eeb5a0356722734b3df450
--- /dev/null
+++ b/patch-forcing/configs/autoencoder/flux2_ae.yaml
@@ -0,0 +1,4 @@
+name: FLUX2AutoencoderKL
+target: jutils.nn.ae_flux2.FLUX2AutoencoderKL # first stage model (KL-Autoencoder from FLUX.2)
+params:
+ ckpt_path: checkpoints/flux2_ae.ckpt
diff --git a/patch-forcing/configs/autoencoder/sd_ae.yaml b/patch-forcing/configs/autoencoder/sd_ae.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f3b17911ca992befc7662ac08ae07f9cc0a1e854
--- /dev/null
+++ b/patch-forcing/configs/autoencoder/sd_ae.yaml
@@ -0,0 +1,4 @@
+name: AutoencoderKL
+target: jutils.nn.kl_autoencoder.AutoencoderKL # first stage model (KL-Autoencoder from LDM)
+params:
+ ckpt_path: checkpoints/sd_ae.ckpt
diff --git a/patch-forcing/configs/autoencoder/tiny_ae.yaml b/patch-forcing/configs/autoencoder/tiny_ae.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f3753b53231c4fccf6382e66ff4fe2f84e9858b2
--- /dev/null
+++ b/patch-forcing/configs/autoencoder/tiny_ae.yaml
@@ -0,0 +1,6 @@
+name: TinyAutoencoderKL
+target: jutils.nn.tiny_autoencoder.TinyAutoencoderKL
+params:
+ encoder_path: checkpoints/taesd_encoder.pth
+ decoder_path: checkpoints/taesd_decoder.pth
+ latent_channels: 4
diff --git a/patch-forcing/configs/config.yaml b/patch-forcing/configs/config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d7a56438999d4356933586a84bc5f4b4828b682d
--- /dev/null
+++ b/patch-forcing/configs/config.yaml
@@ -0,0 +1,93 @@
+defaults:
+ - _self_
+ - model: dit-b
+ - data: dummy256 # dummy data
+ - autoencoder: tiny_ae
+ - lr_scheduler: null
+ - trainer: flow
+ - experiment: null # must be last in defaults list as it can override all others
+
+ # disable hydra logging
+ - override hydra/hydra_logging: disabled
+ - override hydra/job_logging: disabled
+
+# ----------------------------------------
+name: debug/your_exp
+
+# ----------------------------------------
+# logging
+use_wandb: False
+use_wandb_offline: False
+wandb_project: patch-forcing
+
+tags: []
+
+# checkpoint loading
+load_weights: null
+load_strict: True
+# resume_step: 0 # can be used for load_weights to specify step (not required for resume_checkpoint)
+resume_checkpoint: null
+
+# checkpoint saving (lightning callback)
+checkpoint_params: # filename refers to number of gradient updates
+ every_n_train_steps: 10000 # gradient update steps
+ save_top_k: -1 # needs to be -1, otherwise it overwrites
+ verbose: True
+ save_last: True
+ auto_insert_metric_name: False
+
+# ----------------------------------------
+train_params:
+ max_steps: -1
+ max_epochs: -1
+ num_sanity_val_steps: 0
+ accumulate_grad_batches: 1
+ log_every_n_steps: 1 # gradient update steps
+ limit_val_batches: 8 # per GPU
+ val_check_interval: 5000 # steps, regardless of gradient accumulation
+ precision: bf16-mixed
+ clip_grad_norm: 1.0
+
+callbacks:
+ - target: lightning.pytorch.callbacks.LearningRateMonitor
+ params:
+ logging_interval: 'step'
+
+# ----------------------------------------
+# profiling
+profile: false
+profiling:
+ warmup: 40
+ active: 1
+ filename: profile.json
+ cpu: true
+ cuda: true
+ record_shapes: false
+ profile_memory: false
+ with_flops: false
+
+# ----------------------------------------
+# distributed
+num_nodes: 1
+devices: -1
+auto_requeue: False
+tqdm_refresh_rate: 1 # set higher on slurm (otherwise prints tqdm every step)
+deepspeed_stage: 0
+p2p_disable: False
+slurm_id: null
+cuda_prefetch: False
+cuda_prefetch_factor: 2
+ddp_kwargs:
+ find_unused_parameters: False # default: False
+ gradient_as_bucket_view: True # default: False
+ bucket_cap_mb: 100 # default: 25
+ broadcast_buffers: True # default: True
+
+# ----------------------------------------
+user: ${oc.env:USER}
+
+# don't log and save files
+hydra:
+ output_subdir: null
+ run:
+ dir: .
diff --git a/patch-forcing/configs/data/dummy256.yaml b/patch-forcing/configs/data/dummy256.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2966cc887127f933725ab60ac75babf88e87691f
--- /dev/null
+++ b/patch-forcing/configs/data/dummy256.yaml
@@ -0,0 +1,17 @@
+name: Dummy_256
+num_classes: 1000
+target: patch_flow.dataloader.DataModuleFromConfig
+params:
+ batch_size: 16
+ num_workers: 4
+ train:
+ target: patch_flow.dataloader.DummyDataset
+ params:
+ image: [3, 256, 256]
+ label: [1]
+
+ validation:
+ target: patch_flow.dataloader.DummyDataset
+ params:
+ image: [3, 256, 256]
+ label: [1]
diff --git a/patch-forcing/configs/data/imagenet256.yaml b/patch-forcing/configs/data/imagenet256.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..df9365f26c1e651c73f6f10ea7b6c17e65ce5222
--- /dev/null
+++ b/patch-forcing/configs/data/imagenet256.yaml
@@ -0,0 +1,44 @@
+name: ImageNet_256px
+num_classes: 1000
+target: patch_flow.dataloader.WebDataModuleFromConfig
+params:
+ tar_base: ... # TODO: add path to tar files: path/to/tars
+ batch_size: 32
+ num_workers: 4
+ val_num_workers: 1
+ multinode: True
+ train:
+ shards: ... # TODO: add shards like this: 'train/{000000..999999}.tar'
+ shuffle: 100
+ image_key: jpeg
+ rename:
+ image: jpeg
+ label: cls
+ image_transforms:
+ - target: torchvision.transforms.RandomHorizontalFlip
+ params:
+ p: 0.5
+ - target: torchvision.transforms.Resize
+ params:
+ size: 256
+ interpolation: 2
+ antialias: True
+ - target: torchvision.transforms.CenterCrop
+ params:
+ size: 256
+
+ validation:
+ shards: ... # TODO: validation shards:'val/{000000..000100}.tar'
+ image_key: jpeg
+ rename:
+ image: jpeg
+ label: cls
+ image_transforms:
+ - target: torchvision.transforms.Resize
+ params:
+ size: 256
+ interpolation: 2
+ antialias: True
+ - target: torchvision.transforms.CenterCrop
+ params:
+ size: 256
diff --git a/patch-forcing/configs/data/t2i-256.yaml b/patch-forcing/configs/data/t2i-256.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a86b98d4fcfc7d1f5c195c68afc5756b3c505b24
--- /dev/null
+++ b/patch-forcing/configs/data/t2i-256.yaml
@@ -0,0 +1,51 @@
+target: patch_flow.dataloader.WebDataModuleFromConfig
+params:
+ tar_base: ... # TODO: add path to tar files: path/to/tars
+ batch_size: 8
+ num_workers: 8
+ val_batch_size: 16
+ val_num_workers: 1
+ multinode: True
+
+ train:
+ shards: ... # TODO: add shards like this: 'train/{000000..999999}.tar'
+ shuffle: 100
+ image_key: jpg
+ rename:
+ image: jpg
+ dataset_transforms:
+ target: patch_flow.data_utils.TransformComposer
+ params:
+ transforms:
+ # crop-size conditioning via RoPE
+ - target: patch_flow.data_utils.ResizeCropWithMetaInfo
+ params:
+ size: 256
+ img_key: image
+ meta_key: img_meta
+ # if available, caption sampling with probs per caption type/length
+ - target: patch_flow.data_utils.CaptionSampler
+ params:
+ out_txt_key: txt
+ txt_sampling_cfg:
+ txt: 1
+ long: 2
+ medium: 3
+ short: 4
+ keywords: 2
+
+ validation:
+ shards: ... # TODO: validation shards:'val/{000000..000100}.tar'
+ image_key: jpg
+ rename:
+ image: jpg
+ txt: medium # use medium caption for val
+ image_transforms:
+ - target: torchvision.transforms.Resize
+ params:
+ size: 256
+ interpolation: 2
+ antialias: True
+ - target: torchvision.transforms.CenterCrop
+ params:
+ size: 256
diff --git a/patch-forcing/configs/experiment/imnet-dit-b.yaml b/patch-forcing/configs/experiment/imnet-dit-b.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1f2d5e6d5f472cae955208d4135ecc37ba3c3872
--- /dev/null
+++ b/patch-forcing/configs/experiment/imnet-dit-b.yaml
@@ -0,0 +1,24 @@
+# @package _global_
+defaults:
+ - override /trainer: flow
+ - override /data: imagenet256
+ - override /model: dit-b
+ - override /autoencoder: sd_ae
+ - override /lr_scheduler: constant
+
+name: debug/imnet256/dit-b
+
+model:
+ params:
+ compile: true
+
+data:
+ params:
+ batch_size: 64
+ val_batch_size: 32
+
+train_params:
+ max_steps: 400000
+ limit_val_batches: 40
+ val_check_interval: 10000
+ precision: bf16-mixed
diff --git a/patch-forcing/configs/experiment/imnet-dit-b_lognorm.yaml b/patch-forcing/configs/experiment/imnet-dit-b_lognorm.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9a93fd402ba9ca697e144ad656e3897c4bea0db7
--- /dev/null
+++ b/patch-forcing/configs/experiment/imnet-dit-b_lognorm.yaml
@@ -0,0 +1,34 @@
+# @package _global_
+defaults:
+ - override /trainer: flow
+ - override /data: imagenet256
+ - override /model: dit-b
+ - override /autoencoder: sd_ae
+ - override /lr_scheduler: constant
+
+name: debug/imnet256/dit-b/lognorm/l0.0_s1.0
+
+model:
+ params:
+ compile: true
+
+trainer:
+ params:
+ flow:
+ params:
+ timestep_sampler:
+ target: patch_flow.flow.LogitNormalSampler
+ params:
+ loc: 0.0
+ scale: 1.0
+
+data:
+ params:
+ batch_size: 64
+ val_batch_size: 32
+
+train_params:
+ max_steps: 400000
+ limit_val_batches: 40
+ val_check_interval: 10000
+ precision: bf16-mixed
diff --git a/patch-forcing/configs/experiment/imnet-dit-xl.yaml b/patch-forcing/configs/experiment/imnet-dit-xl.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..97a16c677a936d560894a32b4e7dfa88007c03fa
--- /dev/null
+++ b/patch-forcing/configs/experiment/imnet-dit-xl.yaml
@@ -0,0 +1,24 @@
+# @package _global_
+defaults:
+ - override /trainer: flow
+ - override /data: imagenet256
+ - override /model: dit-xl
+ - override /autoencoder: sd_ae
+ - override /lr_scheduler: constant
+
+name: debug/imnet256/dit-xl
+
+model:
+ params:
+ compile: true
+
+data:
+ params:
+ batch_size: 32
+ val_batch_size: 32
+
+train_params:
+ max_steps: 400000
+ limit_val_batches: 40
+ val_check_interval: 10000
+ precision: bf16-mixed
diff --git a/patch-forcing/configs/experiment/imnet-dit-xl_lognorm.yaml b/patch-forcing/configs/experiment/imnet-dit-xl_lognorm.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..6201fcda5d29b4122aff0c43ee30d60ff172f085
--- /dev/null
+++ b/patch-forcing/configs/experiment/imnet-dit-xl_lognorm.yaml
@@ -0,0 +1,34 @@
+# @package _global_
+defaults:
+ - override /trainer: flow
+ - override /data: imagenet256
+ - override /model: dit-xl
+ - override /autoencoder: sd_ae
+ - override /lr_scheduler: constant
+
+name: debug/imnet256/dit-xl/lognorm/l0.0_s1.0
+
+model:
+ params:
+ compile: true
+
+trainer:
+ params:
+ flow:
+ params:
+ timestep_sampler:
+ target: patch_flow.flow.LogitNormalSampler
+ params:
+ loc: 0.0
+ scale: 1.0
+
+data:
+ params:
+ batch_size: 32
+ val_batch_size: 32
+
+train_params:
+ max_steps: 400000
+ limit_val_batches: 40
+ val_check_interval: 10000
+ precision: bf16-mixed
diff --git a/patch-forcing/configs/experiment/imnet-pft-b.yaml b/patch-forcing/configs/experiment/imnet-pft-b.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f9839cef289206cd49b04a99a301a83ce0254013
--- /dev/null
+++ b/patch-forcing/configs/experiment/imnet-pft-b.yaml
@@ -0,0 +1,24 @@
+# @package _global_
+defaults:
+ - override /trainer: patch_flow
+ - override /data: imagenet256
+ - override /model: pft-b
+ - override /autoencoder: sd_ae
+ - override /lr_scheduler: constant
+
+name: debug/imnet256/pft-b
+
+model:
+ params:
+ compile: true
+
+data:
+ params:
+ batch_size: 64
+ val_batch_size: 32
+
+train_params:
+ max_steps: 400000
+ limit_val_batches: 40
+ val_check_interval: 10000
+ precision: bf16-mixed
diff --git a/patch-forcing/configs/experiment/imnet-pft-xl.yaml b/patch-forcing/configs/experiment/imnet-pft-xl.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..705a51a218e21eb86bb16a66184f6b0f5dc8e07a
--- /dev/null
+++ b/patch-forcing/configs/experiment/imnet-pft-xl.yaml
@@ -0,0 +1,24 @@
+# @package _global_
+defaults:
+ - override /trainer: patch_flow
+ - override /data: imagenet256
+ - override /model: pft-xl
+ - override /autoencoder: sd_ae
+ - override /lr_scheduler: constant
+
+name: debug/imnet256/pft-xl
+
+model:
+ params:
+ compile: true
+
+data:
+ params:
+ batch_size: 32
+ val_batch_size: 32
+
+train_params:
+ max_steps: 400000
+ limit_val_batches: 40
+ val_check_interval: 10000
+ precision: bf16-mixed
diff --git a/patch-forcing/configs/experiment/t2i-pft1.2b-qwen.yaml b/patch-forcing/configs/experiment/t2i-pft1.2b-qwen.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..779ac35882e220f67067bbb1a2406b98d667d1e6
--- /dev/null
+++ b/patch-forcing/configs/experiment/t2i-pft1.2b-qwen.yaml
@@ -0,0 +1,34 @@
+# @package _global_
+defaults:
+ - override /trainer: patch_flow_t2i
+ - override /data: t2i-256 # change to your data config
+ - override /model: t2i-pft-1.2b
+ - override /autoencoder: flux2_ae
+ - override /lr_scheduler: constant
+
+name: debug/t2i/coyo/qwen2b/pf-1.2b
+
+compile: true
+
+data:
+ params:
+ batch_size: 32
+ val_batch_size: 32
+ num_workers: 8
+
+model:
+ params:
+ in_dim: 32 # must match latent space dim
+ compile: ${compile}
+
+trainer:
+ params:
+ text_encoder:
+ params:
+ compile: ${compile}
+
+train_params:
+ max_steps: 400000
+ limit_val_batches: 10
+ val_check_interval: 10000
+ precision: bf16-mixed
diff --git a/patch-forcing/configs/lr_scheduler/constant.yaml b/patch-forcing/configs/lr_scheduler/constant.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..cf3329a7588452e06c12b2a789a6de3badb05e85
--- /dev/null
+++ b/patch-forcing/configs/lr_scheduler/constant.yaml
@@ -0,0 +1,4 @@
+name: constant
+target: jutils.nn.lr_schedulers.get_constant_schedule_with_warmup
+params:
+ num_warmup_steps: 1000
\ No newline at end of file
diff --git a/patch-forcing/configs/lr_scheduler/cosine.yaml b/patch-forcing/configs/lr_scheduler/cosine.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0ec555db253ecc3e0914e8d1bd6c1ed899b2d494
--- /dev/null
+++ b/patch-forcing/configs/lr_scheduler/cosine.yaml
@@ -0,0 +1,6 @@
+name: cosine
+target: jutils.nn.lr_schedulers.get_cosine_schedule_with_warmup
+params:
+ num_warmup_steps: 1000
+ num_training_steps: 100000
+ num_cycles: 0.5
\ No newline at end of file
diff --git a/patch-forcing/configs/lr_scheduler/exp.yaml b/patch-forcing/configs/lr_scheduler/exp.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9dff3c76a7aa8cce91aa7db10cce7ff66df7156b
--- /dev/null
+++ b/patch-forcing/configs/lr_scheduler/exp.yaml
@@ -0,0 +1,10 @@
+# Warmup-Stable-Decay (WSD) learning rate schedule according to the paper:
+# 'MiniCPM: Unveiling the Potential of Small Language Models with Scalable Training Strategies'
+# - Hu et al. (2024)
+# Max training steps in WSD annealing phase: 3 * t_decay
+# t_decay should be ~2% of the previous training steps with constant lr
+name: exponential
+target: jutils.nn.lr_schedulers.get_exponential_decay_schedule
+params:
+ num_warmup_steps: 0
+ t_decay: 2000
\ No newline at end of file
diff --git a/patch-forcing/configs/lr_scheduler/iter_exp.yaml b/patch-forcing/configs/lr_scheduler/iter_exp.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..4c1633fe58cc322b7dca61d7f2e8b55414fa0352
--- /dev/null
+++ b/patch-forcing/configs/lr_scheduler/iter_exp.yaml
@@ -0,0 +1,6 @@
+name: iter_exponential
+target: jutils.nn.lr_schedulers.get_iter_exponential_schedule
+params:
+ num_warmup_steps: 1000
+ num_training_steps: 100000
+ final_ratio: 0.05
\ No newline at end of file
diff --git a/patch-forcing/configs/model/dit-b.yaml b/patch-forcing/configs/model/dit-b.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5c2532adf51b5523d074df6c11b495d5b2a40406
--- /dev/null
+++ b/patch-forcing/configs/model/dit-b.yaml
@@ -0,0 +1,10 @@
+target: patch_flow.models.dit.DiT
+params:
+ in_channels: 4
+ input_size: 32
+ depth: 12
+ hidden_size: 768
+ patch_size: 2
+ num_heads: 12
+ num_classes: 1000
+ compile: true
\ No newline at end of file
diff --git a/patch-forcing/configs/model/dit-xl.yaml b/patch-forcing/configs/model/dit-xl.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1c5b39dfd29f77868aafec40f49dfa9b9c75ffe3
--- /dev/null
+++ b/patch-forcing/configs/model/dit-xl.yaml
@@ -0,0 +1,10 @@
+target: patch_flow.models.dit.DiT
+params:
+ in_channels: 4
+ input_size: 32
+ depth: 28
+ hidden_size: 1152
+ patch_size: 2
+ num_heads: 16
+ num_classes: 1000
+ compile: true
\ No newline at end of file
diff --git a/patch-forcing/configs/model/pft-b.yaml b/patch-forcing/configs/model/pft-b.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2bca37544f54c7a359f0417f542bd96f239fdc81
--- /dev/null
+++ b/patch-forcing/configs/model/pft-b.yaml
@@ -0,0 +1,11 @@
+target: patch_flow.models.pf_transformer.PatchForcingDiT
+params:
+ in_channels: 4
+ input_size: 32
+ depth: 12
+ hidden_size: 768
+ patch_size: 2
+ num_heads: 12
+ num_classes: 1000
+ compile: true
+ predict_uncertainty: true
\ No newline at end of file
diff --git a/patch-forcing/configs/model/pft-xl.yaml b/patch-forcing/configs/model/pft-xl.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a710dc2fda51f0164510303f5a3c92df9c490111
--- /dev/null
+++ b/patch-forcing/configs/model/pft-xl.yaml
@@ -0,0 +1,11 @@
+target: patch_flow.models.pf_transformer.PatchForcingDiT
+params:
+ in_channels: 4
+ input_size: 32
+ depth: 28
+ hidden_size: 1152
+ patch_size: 2
+ num_heads: 16
+ num_classes: 1000
+ compile: true
+ predict_uncertainty: true
\ No newline at end of file
diff --git a/patch-forcing/configs/model/t2i-pft-1.2b.yaml b/patch-forcing/configs/model/t2i-pft-1.2b.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..aa589115eadbd0c4c05f356eecdae548f622c107
--- /dev/null
+++ b/patch-forcing/configs/model/t2i-pft-1.2b.yaml
@@ -0,0 +1,16 @@
+# params: 1,239,969,008
+target: patch_flow.models.pf_transformer_t2i.PatchForcingTransformerT2I
+params:
+ in_dim: 4
+ depth: 28
+ hidden_dim: 1536
+ head_dim: 96 # 16 heads
+ mapping_dim: 384
+ mapping_depth: 2
+ patch_size: 2
+ # text things
+ txt_in_dim: 2048 # must match text encoder output dim!
+ txt_refiner_dim: 1536
+ txt_refiner_head_dim: 128 # 12 heads
+ txt_refiner_depth: 2
+ compile: false
\ No newline at end of file
diff --git a/patch-forcing/configs/sampler/dual-loop.yaml b/patch-forcing/configs/sampler/dual-loop.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..6283ba22af525fd2231f3e858ba10c9ba15bb300
--- /dev/null
+++ b/patch-forcing/configs/sampler/dual-loop.yaml
@@ -0,0 +1,5 @@
+target: patch_flow.integrators.DualLoopSampler
+params:
+ p: 0.4
+ n_inner: 4
+ patch_size: 2
diff --git a/patch-forcing/configs/sampler/euler-pf.yaml b/patch-forcing/configs/sampler/euler-pf.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..3346d4de56fe121229e6dd99bce6d11bafc432f2
--- /dev/null
+++ b/patch-forcing/configs/sampler/euler-pf.yaml
@@ -0,0 +1,2 @@
+target: patch_flow.integrators.EulerPF
+params: {}
\ No newline at end of file
diff --git a/patch-forcing/configs/sampler/euler.yaml b/patch-forcing/configs/sampler/euler.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a6ace4f83a11ab7d3d5e6e38c6d66807a2ceb57c
--- /dev/null
+++ b/patch-forcing/configs/sampler/euler.yaml
@@ -0,0 +1,2 @@
+target: patch_flow.integrators.Euler
+params: {}
\ No newline at end of file
diff --git a/patch-forcing/configs/sampler/look-ahead.yaml b/patch-forcing/configs/sampler/look-ahead.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a937af84f2d47860d801ba8dc9544752eee7f92b
--- /dev/null
+++ b/patch-forcing/configs/sampler/look-ahead.yaml
@@ -0,0 +1,5 @@
+target: patch_flow.integrators.LookAheadSampler
+params:
+ p: 0.4
+ patch_size: 2
+ context_t_ratio: 1.4
diff --git a/patch-forcing/configs/trainer/flow.yaml b/patch-forcing/configs/trainer/flow.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b4ce2a97ec1499854c8dc5e67b4d6e0a13a21c5f
--- /dev/null
+++ b/patch-forcing/configs/trainer/flow.yaml
@@ -0,0 +1,19 @@
+target: patch_flow.trainer.LatentFlowTrainer
+params:
+ model: ${oc.select:model, null}
+ first_stage: ${oc.select:autoencoder, null}
+ flow:
+ target: patch_flow.flow.Flow
+ params:
+ timestep_sampler: null
+
+ # learning
+ lr: 1e-4
+ weight_decay: 0.0
+ ema_rate: 0.9999
+ lr_scheduler_cfg: ${oc.select:lr_scheduler, null}
+
+ # sampling
+ sample_kwargs:
+ num_steps: 50
+ progress: False
\ No newline at end of file
diff --git a/patch-forcing/configs/trainer/patch_flow.yaml b/patch-forcing/configs/trainer/patch_flow.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..6baf6e13153a7e8c2b13d08645a57ea1248461f6
--- /dev/null
+++ b/patch-forcing/configs/trainer/patch_flow.yaml
@@ -0,0 +1,28 @@
+target: patch_flow.trainer.LatentPatchForcingTrainer
+
+params:
+ model: ${oc.select:model, null}
+ first_stage: ${oc.select:autoencoder, null}
+
+ # patch flow forcing
+ flow:
+ target: patch_flow.flow_pf.PatchFlowForcing
+ params:
+ patch_size: 2
+ timestep_sampler:
+ target: patch_flow.timestep_schedules.LogitNormalTruncatedGaussian
+ params:
+ std: 0.6
+ loc: 0.7
+ scale: 1.0
+
+ # learning
+ lr: 1e-4
+ weight_decay: 0.0
+ ema_rate: 0.9999
+ lr_scheduler_cfg: ${oc.select:lr_scheduler, null}
+
+ # sampling
+ sample_kwargs:
+ num_steps: 50
+ progress: False
\ No newline at end of file
diff --git a/patch-forcing/configs/trainer/patch_flow_t2i.yaml b/patch-forcing/configs/trainer/patch_flow_t2i.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d29d0371df7bff6576f4797fd673ec0c43bc34dd
--- /dev/null
+++ b/patch-forcing/configs/trainer/patch_flow_t2i.yaml
@@ -0,0 +1,38 @@
+target: patch_flow.trainer_t2i.PatchForcingT2ITrainer
+
+params:
+ model: ${oc.select:model, null}
+ first_stage: ${oc.select:autoencoder, null}
+
+ # patch flow forcing
+ flow:
+ target: patch_flow.flow_pf.PatchFlowForcing
+ params:
+ patch_size: 2
+ timestep_sampler:
+ target: patch_flow.timestep_schedules.LogitNormalTruncatedGaussian
+ params:
+ std: 0.6
+ loc: 0.5
+ scale: 1.0
+
+ # text conditioning
+ text_encoder:
+ target: patch_flow.text_encoder.Qwen3VLEmbedder2B
+ params:
+ compile: true
+ text_dropout_prob: 0.1
+ text_key: txt
+
+ # learning
+ lr: 1e-4
+ weight_decay: 0.0
+ ema_rate: 0.9999
+ lr_scheduler_cfg: ${oc.select:lr_scheduler, null}
+ rope_jittering: true
+ uncertainty_weight: 0.01
+
+ # sampling
+ sample_kwargs:
+ num_steps: 50
+ progress: False
\ No newline at end of file
diff --git a/patch-forcing/logs/debug/train-official/2026-04-22/T230557/events.out.tfevents.1776870357.hk01dgx015.877147.0 b/patch-forcing/logs/debug/train-official/2026-04-22/T230557/events.out.tfevents.1776870357.hk01dgx015.877147.0
new file mode 100644
index 0000000000000000000000000000000000000000..a2e222ed4aed8bda75af2e0f8dd807b0de394879
--- /dev/null
+++ b/patch-forcing/logs/debug/train-official/2026-04-22/T230557/events.out.tfevents.1776870357.hk01dgx015.877147.0
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:63290c0b8c9d9af6d3294511792d3a0cdc1c4be2d31e9a1ec38b932fe6602d9c
+size 88
diff --git a/patch-forcing/logs/debug/train-official/2026-04-22/T230729/events.out.tfevents.1776870449.hk01dgx015.885834.0 b/patch-forcing/logs/debug/train-official/2026-04-22/T230729/events.out.tfevents.1776870449.hk01dgx015.885834.0
new file mode 100644
index 0000000000000000000000000000000000000000..bda094d41c4bc61dfff5cda03ba279c2890df9ec
--- /dev/null
+++ b/patch-forcing/logs/debug/train-official/2026-04-22/T230729/events.out.tfevents.1776870449.hk01dgx015.885834.0
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a23848ee37a3d93543e06d3859c9d702ed5bfa875c5392a59ce431e8f3ebfde9
+size 88
diff --git a/patch-forcing/logs/debug/train-official/2026-04-22/T230841/events.out.tfevents.1776870521.hk01dgx015.890508.0 b/patch-forcing/logs/debug/train-official/2026-04-22/T230841/events.out.tfevents.1776870521.hk01dgx015.890508.0
new file mode 100644
index 0000000000000000000000000000000000000000..ed62fede49817dab7426a43249015c92075ef19d
--- /dev/null
+++ b/patch-forcing/logs/debug/train-official/2026-04-22/T230841/events.out.tfevents.1776870521.hk01dgx015.890508.0
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c9f0c11a0a7f2e5cdb0ae4b64f6153552484d0fe2aa5f3db2396ed046ced5375
+size 88
diff --git a/patch-forcing/logs/debug/train-official/2026-04-22/T230921/config.yaml b/patch-forcing/logs/debug/train-official/2026-04-22/T230921/config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..3818d2d46d712536845e96c4cc62507680028e71
--- /dev/null
+++ b/patch-forcing/logs/debug/train-official/2026-04-22/T230921/config.yaml
@@ -0,0 +1,164 @@
+name: debug/train-official
+use_wandb: false
+use_wandb_offline: false
+wandb_project: patch-forcing
+tags: []
+load_weights: null
+load_strict: true
+resume_checkpoint: null
+checkpoint_params:
+ every_n_train_steps: 10000
+ save_top_k: -1
+ verbose: true
+ save_last: true
+ auto_insert_metric_name: false
+train_params:
+ max_steps: 1
+ max_epochs: -1
+ num_sanity_val_steps: 0
+ accumulate_grad_batches: 1
+ log_every_n_steps: 1
+ limit_val_batches: 0
+ val_check_interval: 10000
+ precision: bf16-mixed
+ clip_grad_norm: 1.0
+callbacks:
+- target: lightning.pytorch.callbacks.LearningRateMonitor
+ params:
+ logging_interval: step
+profile: false
+profiling:
+ warmup: 40
+ active: 1
+ filename: profile.json
+ cpu: true
+ cuda: true
+ record_shapes: false
+ profile_memory: false
+ with_flops: false
+num_nodes: 1
+devices: -1
+auto_requeue: false
+tqdm_refresh_rate: 1
+deepspeed_stage: 0
+p2p_disable: false
+slurm_id: null
+cuda_prefetch: false
+cuda_prefetch_factor: 2
+ddp_kwargs:
+ find_unused_parameters: false
+ gradient_as_bucket_view: true
+ bucket_cap_mb: 100
+ broadcast_buffers: true
+user: dyvm6xrauser11
+model:
+ target: patch_flow.models.pf_transformer.PatchForcingDiT
+ params:
+ in_channels: 4
+ input_size: 32
+ depth: 12
+ hidden_size: 768
+ patch_size: 2
+ num_heads: 12
+ num_classes: 1000
+ compile: false
+ predict_uncertainty: true
+data:
+ name: Dummy_256
+ num_classes: 1000
+ target: patch_flow.dataloader.DataModuleFromConfig
+ params:
+ batch_size: 2
+ num_workers: 0
+ train:
+ target: patch_flow.dataloader.DummyDataset
+ params:
+ image:
+ - 3
+ - 256
+ - 256
+ label:
+ - 1
+ validation:
+ target: patch_flow.dataloader.DummyDataset
+ params:
+ image:
+ - 3
+ - 256
+ - 256
+ label:
+ - 1
+ val_batch_size: 32
+autoencoder:
+ name: AutoencoderKL
+ target: jutils.nn.kl_autoencoder.AutoencoderKL
+ params:
+ ckpt_path: checkpoints/sd_ae.ckpt
+lr_scheduler:
+ name: constant
+ target: jutils.nn.lr_schedulers.get_constant_schedule_with_warmup
+ params:
+ num_warmup_steps: 1000
+trainer:
+ target: patch_flow.trainer.LatentPatchForcingTrainer
+ params:
+ model:
+ target: patch_flow.models.pf_transformer.PatchForcingDiT
+ params:
+ in_channels: 4
+ input_size: 32
+ depth: 12
+ hidden_size: 768
+ patch_size: 2
+ num_heads: 12
+ num_classes: 1000
+ compile: false
+ predict_uncertainty: true
+ first_stage:
+ name: AutoencoderKL
+ target: jutils.nn.kl_autoencoder.AutoencoderKL
+ params:
+ ckpt_path: checkpoints/sd_ae.ckpt
+ flow:
+ target: patch_flow.flow_pf.PatchFlowForcing
+ params:
+ patch_size: 2
+ timestep_sampler:
+ target: patch_flow.timestep_schedules.LogitNormalTruncatedGaussian
+ params:
+ std: 0.6
+ loc: 0.7
+ scale: 1.0
+ lr: 0.0001
+ weight_decay: 0.0
+ ema_rate: 0.9999
+ lr_scheduler_cfg:
+ name: constant
+ target: jutils.nn.lr_schedulers.get_constant_schedule_with_warmup
+ params:
+ num_warmup_steps: 1000
+ sample_kwargs:
+ num_steps: 50
+ progress: false
+
+
+# ----------------------------------------
+# Command : python train.py experiment=imnet-pft-b data=dummy256 autoencoder=sd_ae model.params.compile=false train_params.max_steps=1 train_params.limit_val_batches=0 data.params.batch_size=2 data.params.num_workers=0 name=debug/train-official
+# Name : debug/train-official/2026-04-22/T230921
+# Log dir : logs/debug/train-official/2026-04-22/T230921
+# Trainer Module : patch_flow.trainer.LatentPatchForcingTrainer
+# Params : 130,306,580
+# Data : Dummy_256
+# Batchsize : 2
+# Devices : 1
+# Num nodes : 1
+# Gradient accum : 1
+# Global batchsize: 2
+# Val samples : 0
+# LR : 0.00010
+# LR scheduler : constant
+# Resume ckpt : None
+# Load weights : None
+# Profiling : None
+# Precision : bf16-mixed
+# ----------------------------------------
diff --git a/patch-forcing/logs/debug/train-official/2026-04-22/T230921/events.out.tfevents.1776870561.hk01dgx015.893414.0 b/patch-forcing/logs/debug/train-official/2026-04-22/T230921/events.out.tfevents.1776870561.hk01dgx015.893414.0
new file mode 100644
index 0000000000000000000000000000000000000000..583983bf0457d3433b702bcc2820ddd1e7657644
--- /dev/null
+++ b/patch-forcing/logs/debug/train-official/2026-04-22/T230921/events.out.tfevents.1776870561.hk01dgx015.893414.0
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:34d8ad9baee80b59a43949e8910506bf281afc9f4dd37017cad6083e7aa581a1
+size 4240
diff --git a/patch-forcing/logs/debug/train-official/2026-04-22/T231137/config.yaml b/patch-forcing/logs/debug/train-official/2026-04-22/T231137/config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..20839e734ce352ee50702569213b21a430fd7c6f
--- /dev/null
+++ b/patch-forcing/logs/debug/train-official/2026-04-22/T231137/config.yaml
@@ -0,0 +1,164 @@
+name: debug/train-official
+use_wandb: false
+use_wandb_offline: false
+wandb_project: patch-forcing
+tags: []
+load_weights: null
+load_strict: true
+resume_checkpoint: null
+checkpoint_params:
+ every_n_train_steps: 10000
+ save_top_k: -1
+ verbose: true
+ save_last: true
+ auto_insert_metric_name: false
+train_params:
+ max_steps: 1
+ max_epochs: -1
+ num_sanity_val_steps: 0
+ accumulate_grad_batches: 1
+ log_every_n_steps: 1
+ limit_val_batches: 0
+ val_check_interval: 1000
+ precision: bf16-mixed
+ clip_grad_norm: 1.0
+callbacks:
+- target: lightning.pytorch.callbacks.LearningRateMonitor
+ params:
+ logging_interval: step
+profile: false
+profiling:
+ warmup: 40
+ active: 1
+ filename: profile.json
+ cpu: true
+ cuda: true
+ record_shapes: false
+ profile_memory: false
+ with_flops: false
+num_nodes: 1
+devices: -1
+auto_requeue: false
+tqdm_refresh_rate: 1
+deepspeed_stage: 0
+p2p_disable: false
+slurm_id: null
+cuda_prefetch: false
+cuda_prefetch_factor: 2
+ddp_kwargs:
+ find_unused_parameters: false
+ gradient_as_bucket_view: true
+ bucket_cap_mb: 100
+ broadcast_buffers: true
+user: dyvm6xrauser11
+model:
+ target: patch_flow.models.pf_transformer.PatchForcingDiT
+ params:
+ in_channels: 4
+ input_size: 32
+ depth: 12
+ hidden_size: 768
+ patch_size: 2
+ num_heads: 12
+ num_classes: 1000
+ compile: false
+ predict_uncertainty: true
+data:
+ name: Dummy_256
+ num_classes: 1000
+ target: patch_flow.dataloader.DataModuleFromConfig
+ params:
+ batch_size: 2
+ num_workers: 0
+ train:
+ target: patch_flow.dataloader.DummyDataset
+ params:
+ image:
+ - 3
+ - 256
+ - 256
+ label:
+ - 1
+ validation:
+ target: patch_flow.dataloader.DummyDataset
+ params:
+ image:
+ - 3
+ - 256
+ - 256
+ label:
+ - 1
+ val_batch_size: 32
+autoencoder:
+ name: AutoencoderKL
+ target: jutils.nn.kl_autoencoder.AutoencoderKL
+ params:
+ ckpt_path: checkpoints/sd_ae.ckpt
+lr_scheduler:
+ name: constant
+ target: jutils.nn.lr_schedulers.get_constant_schedule_with_warmup
+ params:
+ num_warmup_steps: 1000
+trainer:
+ target: patch_flow.trainer.LatentPatchForcingTrainer
+ params:
+ model:
+ target: patch_flow.models.pf_transformer.PatchForcingDiT
+ params:
+ in_channels: 4
+ input_size: 32
+ depth: 12
+ hidden_size: 768
+ patch_size: 2
+ num_heads: 12
+ num_classes: 1000
+ compile: false
+ predict_uncertainty: true
+ first_stage:
+ name: AutoencoderKL
+ target: jutils.nn.kl_autoencoder.AutoencoderKL
+ params:
+ ckpt_path: checkpoints/sd_ae.ckpt
+ flow:
+ target: patch_flow.flow_pf.PatchFlowForcing
+ params:
+ patch_size: 2
+ timestep_sampler:
+ target: patch_flow.timestep_schedules.LogitNormalTruncatedGaussian
+ params:
+ std: 0.6
+ loc: 0.7
+ scale: 1.0
+ lr: 0.0001
+ weight_decay: 0.0
+ ema_rate: 0.9999
+ lr_scheduler_cfg:
+ name: constant
+ target: jutils.nn.lr_schedulers.get_constant_schedule_with_warmup
+ params:
+ num_warmup_steps: 1000
+ sample_kwargs:
+ num_steps: 50
+ progress: false
+
+
+# ----------------------------------------
+# Command : python train.py experiment=imnet-pft-b data=dummy256 autoencoder=sd_ae model.params.compile=false train_params.max_steps=100 train_params.val_check_interval=1000 train_params.limit_val_batches=0 data.params.batch_size=4 data.params.num_workers=0 name=debug/train-official train_params.max_steps=1 train_params.limit_val_batches=0 data.params.batch_size=2
+# Name : debug/train-official/2026-04-22/T231137
+# Log dir : logs/debug/train-official/2026-04-22/T231137
+# Trainer Module : patch_flow.trainer.LatentPatchForcingTrainer
+# Params : 130,306,580
+# Data : Dummy_256
+# Batchsize : 2
+# Devices : 1
+# Num nodes : 1
+# Gradient accum : 1
+# Global batchsize: 2
+# Val samples : 0
+# LR : 0.00010
+# LR scheduler : constant
+# Resume ckpt : None
+# Load weights : None
+# Profiling : None
+# Precision : bf16-mixed
+# ----------------------------------------
diff --git a/patch-forcing/logs/debug/train-official/2026-04-22/T231137/events.out.tfevents.1776870697.hk01dgx015.903650.0 b/patch-forcing/logs/debug/train-official/2026-04-22/T231137/events.out.tfevents.1776870697.hk01dgx015.903650.0
new file mode 100644
index 0000000000000000000000000000000000000000..802e9c2975e23e81bf805a3076a056e294f1dc66
--- /dev/null
+++ b/patch-forcing/logs/debug/train-official/2026-04-22/T231137/events.out.tfevents.1776870697.hk01dgx015.903650.0
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:996fddb9ba0dc6174fc3b71dffaef0a062f657e98f88b4ce39029d827c480d7c
+size 4309
diff --git a/patch-forcing/patch_flow/__init__.py b/patch-forcing/patch_flow/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa1425816c30f1b6d5f89b8ba6b8fc90e190b26f
--- /dev/null
+++ b/patch-forcing/patch_flow/__init__.py
@@ -0,0 +1,6 @@
+import os
+import sys
+sys.path.append(os.path.dirname(os.path.abspath(__file__)))
+
+from omegaconf import OmegaConf
+OmegaConf.register_new_resolver("mul", lambda a, b: a * b)
\ No newline at end of file
diff --git a/patch-forcing/patch_flow/__pycache__/__init__.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1aa4c07ea18bd58a31d76eb69f39a084ae34ad57
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/__init__.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/__pycache__/dataloader.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/dataloader.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ec83daaa76ffd208f94530056b03122096fed38
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/dataloader.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/__pycache__/diagonal_gaussian.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/diagonal_gaussian.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5be5719c0b93c84898b887c9e8e1a8fb50cbbac2
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/diagonal_gaussian.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/__pycache__/flow_pf.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/flow_pf.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f58d687cecc278efe47d90b24a3e02fa325df8a
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/flow_pf.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/__pycache__/integrators.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/integrators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96bc30db6b20e587ab8bf42a81d43f398b14964b
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/integrators.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/__pycache__/log_utils.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/log_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d666cfcfdc55152d4a9b35786b64de934b1947a9
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/log_utils.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/__pycache__/metrics.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/metrics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d25036646d6d6d35ba505f6170be04698810682
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/metrics.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/__pycache__/timestep_schedules.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/timestep_schedules.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52e88f1b773e7c0aa7854dd423bc76ada5795439
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/timestep_schedules.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/__pycache__/trainer.cpython-312.pyc b/patch-forcing/patch_flow/__pycache__/trainer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f8c83ceb05711923a84c3fbf07bbe40a7c57ca9
Binary files /dev/null and b/patch-forcing/patch_flow/__pycache__/trainer.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/data_utils.py b/patch-forcing/patch_flow/data_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d021acf2c64c21634a84bdfed65bc3a598644df
--- /dev/null
+++ b/patch-forcing/patch_flow/data_utils.py
@@ -0,0 +1,74 @@
+import torch
+import torchvision
+import random
+from jaxtyping import Float
+
+from jutils import instantiate_from_config
+
+
+class ResizeCropWithMetaInfo:
+ def __init__(self, size: int = 256, antialias: bool = True, img_key: str = "image", meta_key: str = "img_meta"):
+ self.size = int(size)
+ self.resizer = torchvision.transforms.Resize(size=self.size, antialias=antialias)
+ self.img_key = img_key
+ self.meta_key = meta_key
+
+ def resize_crop_image(self, img: Float[torch.Tensor, "c h w"]):
+ """
+ Args:
+ img: (c, h, w) torch tensor in [-1, 1]
+ """
+ assert img.ndim == 3, f"Expected (C,H,W), got {tuple(img.shape)}"
+
+ # resize shorter size to self.size
+ img = self.resizer(img)
+ _, orig_h, orig_w = img.shape
+
+ # random crop
+ top, left = 0, 0
+ if orig_h > self.size:
+ top = random.randint(0, orig_h - self.size)
+ if orig_w > self.size:
+ left = random.randint(0, orig_w - self.size)
+ img_cropped = img[:, top : top + self.size, left : left + self.size]
+
+ img_meta = dict(orig_h=orig_h, orig_w=orig_w, top=top, left=left)
+
+ return img_cropped, img_meta
+
+ def __call__(self, sample: dict):
+ img = sample[self.img_key]
+ img_cropped, img_meta = self.resize_crop_image(img)
+ sample[self.img_key] = img_cropped
+ sample[self.meta_key] = img_meta
+ return sample
+
+
+class CaptionSampler:
+ def __init__(self, txt_sampling_cfg: dict, out_txt_key: str = "txt"):
+ self.out_txt_key = out_txt_key
+ self.text_sampling_cfg = txt_sampling_cfg
+ self.total_ratio = sum(self.text_sampling_cfg.values())
+ self.txt_keys = list(self.text_sampling_cfg.keys())
+ self.txt_probs = [self.text_sampling_cfg[k] / self.total_ratio for k in self.txt_keys]
+
+ def __call__(self, sample: dict):
+ txt_key = random.choices(self.txt_keys, weights=self.txt_probs, k=1)[0]
+ caption = sample[txt_key]
+ if isinstance(caption, bytes):
+ caption = caption.decode()
+ sample[self.out_txt_key] = caption
+ return sample
+
+
+# ===================================================================================================
+
+
+class TransformComposer:
+ def __init__(self, transforms):
+ self.transforms = [instantiate_from_config(t) for t in transforms]
+
+ def __call__(self, sample):
+ for t in self.transforms:
+ sample = t(sample)
+ return sample
diff --git a/patch-forcing/patch_flow/dataloader.py b/patch-forcing/patch_flow/dataloader.py
new file mode 100644
index 0000000000000000000000000000000000000000..004612ecc4182fb11cd85290768af3a56f63838e
--- /dev/null
+++ b/patch-forcing/patch_flow/dataloader.py
@@ -0,0 +1,425 @@
+import os
+import torch
+import numpy as np
+import torchvision
+import webdataset as wds
+from collections import deque
+from omegaconf import OmegaConf
+from omegaconf import ListConfig
+from torch.utils.data import DataLoader, Dataset
+import lightning as pl
+from typing import Dict, Any, Union
+
+from jutils import instantiate_from_config
+from jutils import load_partial_from_config
+
+
+""" WebDataset """
+
+
+def dict_collation_fn(samples, combine_tensors=True, combine_scalars=True):
+ """Take a list of samples (as dictionary) and create a batch, preserving the keys.
+ If `tensors` is True, `ndarray` objects are combined into
+ tensor batches.
+ :param dict samples: list of samples
+ :param bool tensors: whether to turn lists of ndarrays into a single ndarray
+ :returns: single sample consisting of a batch
+ :rtype: dict
+ """
+ keys = set.intersection(*[set(sample.keys()) for sample in samples])
+ batched = {key: [] for key in keys}
+
+ for s in samples:
+ [batched[key].append(s[key]) for key in batched]
+
+ result = {}
+ for key in batched:
+ if isinstance(batched[key][0], (int, float)):
+ if combine_scalars:
+ result[key] = np.array(list(batched[key]))
+ elif isinstance(batched[key][0], torch.Tensor):
+ if combine_tensors:
+ result[key] = torch.stack(list(batched[key]))
+ elif isinstance(batched[key][0], np.ndarray):
+ if combine_tensors:
+ result[key] = np.array(list(batched[key]))
+ else:
+ result[key] = list(batched[key])
+ return result
+
+
+def identity(x):
+ return x
+
+
+def safe_rename(sample, renaming):
+ """
+ Renames keys according to mapping {new_key: old_key}.
+ If the old key is missing, warns and continues (skips that key only).
+ """
+ out = dict(sample) # copy existing keys
+ for new_key, old_key in renaming.items():
+ if old_key in sample:
+ out[new_key] = sample[old_key]
+ if new_key != old_key:
+ out.pop(old_key, None)
+ else:
+ if new_key == "txt":
+ if "short" in sample:
+ out[new_key] = sample["short"]
+ continue
+ if "caption_internvl3_2b_short" in sample:
+ out[new_key] = sample["caption_internvl3_2b_short"]
+ continue
+ wds.warn_and_continue(Exception(f"Could not find alternative keys for missing txt key."))
+ wds.warn_and_continue(Exception(f"Missing key '{old_key}' while renaming to '{new_key}'"))
+ return out
+
+
+class WebDataModuleFromConfig(pl.LightningDataModule):
+ def __init__(
+ self,
+ tar_base, # can be a list of paths or a single path
+ batch_size,
+ val_batch_size=None,
+ train=None,
+ validation=None,
+ test=None,
+ num_workers=4,
+ val_num_workers: int = None,
+ multinode=True,
+ remove_keys: list = None, # list of keys to remove from the sample
+ ):
+ super().__init__()
+ if isinstance(tar_base, str):
+ self.tar_base = tar_base
+ elif isinstance(tar_base, ListConfig) or isinstance(tar_base, list):
+ # check which tar_base exists
+ for path in tar_base:
+ if os.path.exists(path):
+ self.tar_base = path
+ break
+ else:
+ raise FileNotFoundError("Could not find a valid tarbase.")
+ else:
+ raise ValueError(f"Invalid tar_base type {type(tar_base)}")
+ print(f"[WebDataModuleFromConfig] Setting tar base to {self.tar_base}")
+
+ self.batch_size = batch_size
+ self.num_workers = num_workers
+ self.train = train
+ self.validation = validation
+ self.test = test
+ self.multinode = multinode
+ self.val_batch_size = val_batch_size if val_batch_size is not None else batch_size
+ self.val_num_workers = val_num_workers if val_num_workers is not None else num_workers
+ self.rm_keys = remove_keys if remove_keys is not None else []
+
+ def make_loader(self, dataset_config, train=True):
+ image_transforms = []
+ lambda_fn = lambda x: x * 2.0 - 1.0 # normalize to [-1, 1]
+ image_transforms.extend([torchvision.transforms.ToTensor(), torchvision.transforms.Lambda(lambda_fn)])
+ if "image_transforms" in dataset_config:
+ image_transforms.extend([instantiate_from_config(tt) for tt in dataset_config.image_transforms])
+ image_transforms = torchvision.transforms.Compose(image_transforms)
+
+ if "transforms" in dataset_config:
+ transforms_config = OmegaConf.to_container(dataset_config.transforms)
+ else:
+ transforms_config = dict()
+
+ transform_dict = {
+ dkey: (
+ load_partial_from_config(transforms_config[dkey]) if transforms_config[dkey] != "identity" else identity
+ )
+ for dkey in transforms_config
+ }
+ # this is crucial to set correct image key to get the transofrms applied correctly
+ img_key = dataset_config.get("image_key", "image.png")
+ transform_dict.update({img_key: image_transforms})
+
+ if "dataset_transforms" in dataset_config:
+ dataset_transforms = instantiate_from_config(dataset_config["dataset_transforms"])
+ else:
+ dataset_transforms = None
+
+ if "postprocess" in dataset_config:
+ postprocess = instantiate_from_config(dataset_config["postprocess"])
+ else:
+ postprocess = None
+
+ shuffle = dataset_config.get("shuffle", 0)
+ shardshuffle = shuffle > 0
+
+ nodesplitter = wds.shardlists.split_by_node if self.multinode else wds.shardlists.single_node_only
+
+ if isinstance(dataset_config.shards, str):
+ tars = os.path.join(self.tar_base, dataset_config.shards)
+ elif isinstance(dataset_config.shards, list) or isinstance(dataset_config.shards, ListConfig):
+ # decompose into lists of shards
+ # Turn train-{000000..000002}.tar into ['train-000000.tar', 'train-000001.tar', 'train-000002.tar']
+ tars = []
+ for shard in dataset_config.shards:
+ # Assume that the shard starts from 000000
+ if "{" in shard:
+ start, end = shard.split("..")
+ start = start.split("{")[-1]
+ end = end.split("}")[0]
+ start = int(start)
+ end = int(end)
+ tars.extend(
+ [shard.replace(f"{{{start:06d}..{end:06d}}}", f"{i:06d}") for i in range(start, end + 1)]
+ )
+ else:
+ tars.append(shard)
+ tars = [os.path.join(self.tar_base, t) for t in tars]
+ # random shuffle the shards
+ if shardshuffle:
+ np.random.shuffle(tars)
+ else:
+ raise ValueError(f"Invalid shards type {type(dataset_config.shards)}")
+
+ dset = (
+ wds.WebDataset(tars, nodesplitter=nodesplitter, shardshuffle=shardshuffle, handler=wds.warn_and_continue)
+ .repeat()
+ .shuffle(shuffle)
+ )
+ print(f"[WebDataModuleFromConfig] Loading {len(dset.pipeline[0].urls)} shards.")
+
+ dset = (
+ dset.decode("rgb", handler=wds.warn_and_continue)
+ .map(self.filter_out_keys, handler=wds.warn_and_continue)
+ .map_dict(**transform_dict, handler=wds.warn_and_continue)
+ )
+
+ # change name of image key to be consistent with other datasets
+ renaming = dataset_config.get("rename", None)
+ if renaming is not None:
+ # dset = dset.rename(**renaming)
+ dset = dset.map(lambda sample: safe_rename(sample, renaming), handler=wds.warn_and_continue)
+
+ if dataset_transforms is not None:
+ dset = dset.map(dataset_transforms)
+
+ if postprocess is not None:
+ dset = dset.map(postprocess)
+
+ bs = self.batch_size if train else self.val_batch_size
+ nw = self.num_workers if train else self.val_num_workers
+ dset = dset.batched(bs, partial=False, collation_fn=dict_collation_fn)
+ loader = wds.WebLoader(dset, batch_size=None, shuffle=False, num_workers=nw, pin_memory=True)
+
+ return loader
+
+ def filter_out_keys(self, sample):
+ for key in self.rm_keys:
+ sample.pop(key, None)
+ return sample
+
+ def train_dataloader(self):
+ return self.make_loader(self.train)
+
+ def val_dataloader(self):
+ return self.make_loader(self.validation, train=False)
+
+ def test_dataloader(self):
+ return self.make_loader(self.test, train=False)
+
+
+""" Normal Dataset """
+
+
+class DataModuleFromConfig(pl.LightningDataModule):
+ def __init__(
+ self,
+ batch_size: int,
+ val_batch_size: int = None,
+ train: dict = None,
+ validation: dict = None,
+ test: dict = None,
+ shuffle_validation: bool = False,
+ num_workers: int = 0,
+ ):
+ super().__init__()
+ self.batch_size = batch_size
+ self.train = train
+ self.validation = validation
+ self.num_workers = num_workers
+ self.val_batch_size = val_batch_size if val_batch_size is not None else batch_size
+ self.shuffle_validation = shuffle_validation
+
+ self.dataset_configs = {}
+ if train is not None:
+ self.dataset_configs["train"] = train
+ self.train_dataloader = self._train_dataloader
+ if validation is not None:
+ self.dataset_configs["validation"] = validation
+ self.val_dataloader = self._val_dataloader
+ if test is not None:
+ self.dataset_configs["test"] = test
+ self.test_dataloader = self._test_dataloader
+
+ def _train_dataloader(self):
+ return DataLoader(
+ self.datasets["train"], batch_size=self.batch_size, num_workers=self.num_workers, shuffle=True
+ )
+
+ def _val_dataloader(self):
+ return DataLoader(
+ self.datasets["validation"],
+ batch_size=self.val_batch_size,
+ num_workers=self.num_workers,
+ shuffle=self.shuffle_validation,
+ )
+
+ def _test_dataloader(self):
+ return DataLoader(
+ self.datasets["test"],
+ batch_size=self.val_batch_size,
+ num_workers=self.num_workers,
+ shuffle=self.shuffle_validation,
+ )
+
+ def prepare_data(self):
+ for data_cfg in self.dataset_configs.values():
+ instantiate_from_config(data_cfg)
+
+ def setup(self, stage=None):
+ self.datasets = dict((k, instantiate_from_config(self.dataset_configs[k])) for k in self.dataset_configs)
+
+
+class DummyDataset(Dataset):
+ def __init__(self, num_samples=10000000, **kwargs):
+ super().__init__()
+ self.num_samples = num_samples
+ self.keys_shapes = {k: v for k, v in kwargs.items()}
+
+ def __len__(self):
+ return int(self.num_samples)
+
+ def __getitem__(self, idx):
+ return {
+ key: (torch.randn(*shape) if len(shape) > 1 else torch.randint(0, 10, (1,)).squeeze()) # e.g. class labels
+ for key, shape in self.keys_shapes.items()
+ }
+
+
+class CIFAR10(Dataset):
+ def __init__(self, root, train=True, transform=None, target_transform=None, download=False):
+ super().__init__()
+ if transform is None:
+ transform = torchvision.transforms.Compose(
+ [torchvision.transforms.ToTensor(), torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
+ )
+ else:
+ transform = instantiate_from_config(transform)
+
+ if target_transform is not None:
+ target_transform = instantiate_from_config(target_transform)
+ self.dataset = torchvision.datasets.CIFAR10(
+ root, train=train, transform=transform, target_transform=target_transform, download=download
+ )
+
+ def __len__(self):
+ return len(self.dataset)
+
+ def __getitem__(self, idx):
+ img, target = self.dataset[idx]
+ return {"image": img, "label": target}
+
+
+""" Helpers """
+
+
+class MomentsPreprocessor:
+ def __init__(self, moments_key="moments.npy", out_key="latent", scale: float = 0.18215, shift: float = 0.0):
+ self.moments_key = moments_key
+ self.out_key = out_key
+ self.scale = scale
+ self.shift = shift
+
+ def __call__(self, sample):
+ """
+ Helper function for ImageNet first stage sampling using moments.
+ https://github.com/joh-schb/jutils/blob/8440e65b6296897ec23f0c1f13199ca0e1be92e9/jutils/nn/kl_autoencoder.py#L45
+ """
+ moments = torch.tensor(sample[self.moments_key])
+
+ mean, logvar = torch.chunk(moments, 2, dim=0)
+ logvar = torch.clamp(logvar, -30.0, 20.0)
+ std = torch.exp(0.5 * logvar)
+
+ latent = mean + std * torch.randn(mean.shape).to(device=moments.device)
+ latent = (latent + self.shift) * self.scale
+ sample[self.out_key] = latent
+
+ del sample[self.moments_key]
+
+ return sample
+
+
+def dict_to(d: Dict[str, Union[torch.Tensor, Any]], **to_kwargs) -> Dict[str, Union[torch.Tensor, Any]]:
+ return {k: (v.to(**to_kwargs) if isinstance(v, torch.Tensor) else v) for k, v in d.items()}
+
+
+class CUDAPrefetchIterator:
+ """Source from diffusion codebase, thanks!"""
+
+ def __init__(
+ self,
+ iterator,
+ device: torch.device,
+ prefetch_factor: int = 2,
+ enabled: bool = True,
+ target_stream: torch.cuda.Stream = None, # The stream that will use the batch, will be automatically set to torch.cuda.current_stream() in the iterator if not provided
+ ):
+ self.iterator = iterator
+ self.device = device
+ self.prefetch_factor = prefetch_factor
+ assert self.prefetch_factor > 0, "prefetch_factor must be greater than 0"
+ self.enabled = enabled
+ self.target_stream = target_stream
+ if self.target_stream is not None:
+ assert (
+ self.target_stream.device == self.device
+ ), f"Target stream must be on the same device as the iterator. Got {target_stream.device=} and {device=}"
+
+ self._transfer_stream = torch.cuda.Stream(device)
+
+ def __iter__(self):
+ if not self.enabled:
+ # Just return synchronously from the iterator
+ for batch_cpu in self.iterator:
+ yield dict_to(batch_cpu, device=self.device, non_blocking=False)
+ return
+
+ batch_buf: deque[tuple[dict, torch.cuda.Event]] = deque()
+ target_stream = self.target_stream or torch.cuda.current_stream(self.device)
+
+ def enqueue_batch() -> bool:
+ try:
+ batch_cpu = next(self.iterator)
+ except StopIteration:
+ return False
+
+ with torch.cuda.stream(self._transfer_stream):
+ batch_gpu = dict_to(batch_cpu, device=self.device, non_blocking=True)
+ transfer_event = torch.cuda.Event(blocking=False, enable_timing=False)
+ transfer_event.record(self._transfer_stream)
+
+ batch_buf.append((batch_gpu, transfer_event))
+ return True
+
+ # Warmup queue
+ for _ in range(self.prefetch_factor):
+ if not enqueue_batch():
+ break
+ if not batch_buf:
+ return # Iterator was empty
+
+ # Main loop
+ while batch_buf:
+ batch_gpu, ready_event = batch_buf.popleft()
+ target_stream.wait_event(ready_event) # Wait for transfer to complete
+ enqueue_batch()
+ yield batch_gpu
diff --git a/patch-forcing/patch_flow/diagonal_gaussian.py b/patch-forcing/patch_flow/diagonal_gaussian.py
new file mode 100644
index 0000000000000000000000000000000000000000..893ddd9228bf8cc8e343f094541a4626c142e36e
--- /dev/null
+++ b/patch-forcing/patch_flow/diagonal_gaussian.py
@@ -0,0 +1,150 @@
+import torch
+from torch import Tensor
+from jaxtyping import Float
+from typing import Optional
+from math import exp, log, pi
+
+
+class DiagonalGaussian:
+ std_inverval: tuple[float, float]
+ var_interval: tuple[float, float]
+ logvar_interval: tuple[float, float]
+ mean: Float[Tensor, "*batch"]
+ _logvar: Float[Tensor, "*#batch"] | None = None
+ _std: Float[Tensor, "*#batch"] | None = None
+ _var: Float[Tensor, "*#batch"] | None = None
+
+ def __init__(
+ self,
+ mean: Float[Tensor, "*batch"],
+ std: Float[Tensor, "*#batch"] | None = None,
+ var: Float[Tensor, "*#batch"] | None = None,
+ logvar: Float[Tensor, "*#batch"] | None = None,
+ logvar_interval: tuple[float, float] = (-30.0, 20.0),
+ ):
+ assert sum(map(lambda x: int(x is not None), (std, var, logvar))) <= 1
+ self.std_inverval = tuple(exp(0.5 * i) for i in logvar_interval)
+ self.var_interval = tuple(exp(i) for i in logvar_interval)
+ self.logvar_interval = logvar_interval
+ self.mean = mean
+ if std is not None:
+ self.std = std
+ if var is not None:
+ self.var = var
+ if logvar is not None:
+ self.logvar = logvar
+
+ @property
+ def std(self) -> Float[Tensor, "*batch"]:
+ if self._std is None:
+ if self._var is not None:
+ self._std = torch.sqrt(self._var)
+ elif self._logvar is not None:
+ self._std = torch.exp(0.5 * self._logvar)
+ else:
+ return torch.zeros((1,), device=self.device, dtype=self.dtype).expand_as(self.mean)
+ return self._std
+
+ @std.setter
+ def std(self, val: Float[Tensor, "*batch"] | None) -> None:
+ self._std = val if val is None else torch.clamp(val, *self.std_inverval)
+ self._var = self._logvar = None
+
+ @property
+ def var(self) -> Float[Tensor, "*batch"]:
+ if self._var is None:
+ if self._std is not None:
+ self._var = self._std**2
+ elif self._logvar is not None:
+ self._var = torch.exp(self._logvar)
+ else:
+ return torch.zeros((1,), device=self.device, dtype=self.dtype).expand_as(self.mean)
+ return self._var
+
+ @var.setter
+ def var(self, val: Float[Tensor, "*batch"]) -> None:
+ self._var = val if val is None else torch.clamp(val, *self.var_interval)
+ self._std = self._logvar = None
+
+ @property
+ def logvar(self) -> Float[Tensor, "*batch"]:
+ if self._logvar is None:
+ if self._var is not None:
+ self._logvar = torch.log(self._var)
+ elif self._std is not None:
+ self._logvar = 2 * torch.log(self._std)
+ else:
+ raise RuntimeError("Tried accessing logvar of Gaussian with zero variance")
+ return self._logvar
+
+ @logvar.setter
+ def logvar(self, val: Float[Tensor, "*batch"]) -> None:
+ self._logvar = val if val is None else torch.clamp(val, *self.logvar_interval)
+ self._std = self._var = None
+
+ @property
+ def device(self) -> torch.device:
+ return self.mean.device
+
+ @property
+ def dtype(self) -> torch.dtype:
+ return self.mean.dtype
+
+ def mean_detach_(self) -> None:
+ self.mean = self.mean.detach()
+
+ def std_detach_(self) -> None:
+ if self._std is not None:
+ self._std = self._std.detach()
+ if self._var is not None:
+ self._var = self._var.detach()
+ if self._logvar is not None:
+ self._logvar = self._logvar.detach()
+
+ def sample(self, eps: Float[Tensor, "*#batch"] | None = None) -> Float[Tensor, "*batch"]:
+ if eps is None:
+ eps = torch.randn_like(self.mean)
+ return self.mean + self.std * eps
+
+ def mode(self) -> Float[Tensor, "*batch"]:
+ return self.mean
+
+ def kl(self, other: Optional["DiagonalGaussian"] = None) -> Float[Tensor, "*batch"]:
+ if other is None:
+ return 0.5 * (self.mean**2 + self.var - self.logvar - 1.0)
+ logvar_delta = self.logvar - other.logvar
+ return 0.5 * ((self.mean - other.mean) ** 2 / other.var + torch.exp(logvar_delta) - logvar_delta - 1.0)
+
+ def nll(self, sample: Tensor) -> Tensor:
+ return 0.5 * (log(2.0 * pi) + self.logvar + (sample - self.mean) ** 2 / self.var)
+
+ @staticmethod
+ def approx_standard_normal_cdf(x):
+ """
+ A fast approximation of the cumulative distribution function of the standard normal.
+ """
+ return 0.5 * (1.0 + torch.tanh((2.0 / torch.pi) ** 0.5 * (x + 0.044715 * torch.pow(x, 3))))
+
+ def discretized_log_likelihood(
+ self,
+ sample: Float[Tensor, "*batch"],
+ ) -> Float[Tensor, "*batch"]:
+ """
+ Compute the log-likelihood of a Gaussian distribution discretizing to a given image.
+ It is assumed that this was uint8 values, rescaled to the range [-1, 1].
+ Returns a tensor like mean of log probabilities (in nats).
+ """
+ centered_x = sample - self.mean
+ plus_in = (centered_x + 1.0 / 255.0) / self.std
+ cdf_plus = self.approx_standard_normal_cdf(plus_in)
+ min_in = (centered_x - 1.0 / 255.0) / self.std
+ cdf_min = self.approx_standard_normal_cdf(min_in)
+ log_cdf_plus = torch.log(cdf_plus.clamp(min=1e-12))
+ log_one_minus_cdf_min = torch.log((1.0 - cdf_min).clamp(min=1e-12))
+ cdf_delta = cdf_plus - cdf_min
+ log_probs = torch.where(
+ sample < -0.999,
+ log_cdf_plus,
+ torch.where(sample > 0.999, log_one_minus_cdf_min, torch.log(cdf_delta.clamp(min=1e-12))),
+ )
+ return log_probs
diff --git a/patch-forcing/patch_flow/flow.py b/patch-forcing/patch_flow/flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..76d405e9106d7c796adcecff798ef86af505fe42
--- /dev/null
+++ b/patch-forcing/patch_flow/flow.py
@@ -0,0 +1,231 @@
+import torch
+import einops
+import torch.nn as nn
+from tqdm import tqdm
+from torch import Tensor
+from functools import partial
+
+from jutils import instantiate_from_config
+
+
+def exists(x):
+ return x is not None
+
+
+def pad_v_like_x(v_, x_):
+ """
+ Function to reshape the vector by the number of dimensions
+ of x. E.g. x (bs, c, h, w), v (bs) -> v (bs, 1, 1, 1).
+ """
+ if isinstance(v_, float):
+ return v_
+ return v_.reshape(-1, *([1] * (x_.ndim - 1)))
+
+
+def forward_with_cfg(x, t, model, cfg_scale=1.0, uc_cond=None, cond_key="y", **model_kwargs):
+ """Function to include sampling with Classifier-Free Guidance (CFG)"""
+ if cfg_scale == 1.0: # without CFG
+ model_output = model(x, t, **model_kwargs)
+
+ else: # with CFG
+ assert cond_key in model_kwargs, f"Condition key '{cond_key}' for CFG not found in model_kwargs"
+ assert uc_cond is not None, "Unconditional condition not provided for CFG"
+ kwargs = model_kwargs.copy()
+ c = kwargs[cond_key]
+ x_in = torch.cat([x] * 2)
+ t_in = torch.cat([t] * 2)
+ if uc_cond.shape[0] == 1:
+ uc_cond = einops.repeat(uc_cond, "1 ... -> bs ...", bs=x.shape[0])
+ c_in = torch.cat([uc_cond, c])
+ kwargs[cond_key] = c_in
+ model_uc, model_c = model(x_in, t_in, **kwargs).chunk(2)
+ model_output = model_uc + cfg_scale * (model_c - model_uc)
+
+ return model_output
+
+
+""" Timestep Sampler """
+
+
+class LogitNormalSampler:
+ def __init__(self, loc: float = 0.0, scale: float = 1.0):
+ """
+ Logit-Normal sampler from the paper 'Scaling Rectified Flow Transformers
+ for High-Resolution Image Synthesis' - Esser et al. (ICML 2024)
+ """
+ self.loc = loc
+ self.scale = scale
+
+ def __call__(self, n, device="cpu", dtype=torch.float32):
+ return torch.sigmoid(self.loc + self.scale * torch.randn(n)).to(device).to(dtype)
+
+
+""" Flow Model """
+
+
+class Flow:
+ def __init__(
+ self,
+ timestep_sampler: dict = None,
+ ):
+ """
+ Flow Matching, Stochastic Interpolants, or Rectified Flow model. :)
+
+ Args:
+ sigma_min: a float representing the standard deviation of the
+ Gaussian distribution around the mean of the probability
+ path N(t * x1 + (1 - t) * x0, sigma), as used in [1].
+ timestep_sampler: dict, configuration for the training timestep sampler.
+
+ References:
+ [1] Lipman et al. (2023). Flow Matching for Generative Modeling.
+ [2] Tong et al. (2023). Improving and generalizing flow-based
+ generative models with minibatch optimal transport.
+ [3] Ma et al. (2024). SiT: Exploring flow and diffusion-based
+ generative models with scalable interpolant transformers.
+ """
+ if timestep_sampler is not None:
+ self.t_sampler = instantiate_from_config(timestep_sampler)
+ else:
+ self.t_sampler = torch.rand # default: uniform U(0, 1)
+
+ def generate(
+ self,
+ model: nn.Module,
+ x: Tensor,
+ num_steps: int = 50,
+ reverse=False,
+ return_intermediates=False,
+ progress=True,
+ **kwargs,
+ ):
+ """Classic Euler sampling from x0 to x1 in num_steps.
+
+ Args:
+ x: source minibatch (bs, *dim)
+ num_steps: int, number of steps to take
+ reverse: bool, whether to reverse the direction of the flow. If True,
+ we map from x1 -> x0, otherwise we map from x0 -> x1.
+ return_intermediates: bool, if true, return list of samples
+ progress: bool, if true, show tqdm progress bar
+ kwargs: additional arguments for the network (e.g. conditioning information).
+ """
+ bs, dev = x.shape[0], x.device
+
+ # include cfg
+ sample_fn = partial(forward_with_cfg, model=model)
+
+ timesteps = torch.linspace(0, 1, num_steps + 1)
+ if reverse:
+ timesteps = 1 - timesteps
+
+ xt = x
+ intermediates = [xt]
+ for t_curr, t_next in tqdm(zip(timesteps[:-1], timesteps[1:]), disable=not progress, total=len(timesteps) - 1):
+ t = torch.ones((bs,), dtype=x.dtype, device=dev) * t_curr
+ pred = sample_fn(xt, t, **kwargs)
+
+ dt = t_next - t_curr
+ xt = xt + dt * pred
+
+ if return_intermediates:
+ intermediates.append(xt)
+
+ if return_intermediates:
+ return torch.stack(intermediates, 0)
+ return xt
+
+ """ Training """
+
+ def compute_xt(self, x0: Tensor, x1: Tensor, t: Tensor):
+ """
+ Sample from the time-dependent density p_t
+ xt ~ N(alpha_t * x1 + sigma_t * x0, sigma_min * I),
+ according to Eq. (1) in [3] and for the linear schedule Eq. (14) in [2].
+
+ Args:
+ x0 : shape (bs, *dim), represents the source minibatch (noise)
+ x1 : shape (bs, *dim), represents the target minibatch (data)
+ t : shape (bs,) represents the time in [0, 1]
+ Returns:
+ xt : shape (bs, *dim), sampled point along the time-dependent density p_t
+ """
+ t = pad_v_like_x(t, x0)
+ xt = t * x1 + (1 - t) * x0
+ return xt
+
+ def compute_ut(self, x0: Tensor, x1: Tensor, t: Tensor):
+ """
+ Compute the time-dependent conditional vector field
+ ut = alpha_dt_t * x1 + sigma_dt_t * x0,
+ see Eq. (7) in [3].
+
+ Args:
+ x0 : Tensor, shape (bs, *dim), represents the source minibatch (noise)
+ x1 : Tensor, shape (bs, *dim), represents the target minibatch (data)
+ t : FloatTensor, shape (bs,) represents the time in [0, 1]
+ Returns:
+ ut : conditional vector field
+ """
+ return x1 - x0
+
+ def get_interpolants(self, x1: Tensor, x0: Tensor = None, t: Tensor = None):
+ """
+ Args:
+ x1: shape (bs, *dim), represents the target minibatch (data)
+ x0: shape (bs, *dim), represents the source minibatch. If None,
+ we sample x0 from a standard normal distribution.
+ t : shape (bs,), represents the time in [0, 1]. If None,
+ we sample t using self.t_sampler (default: U(0, 1)).
+ Returns:
+ xt: shape (bs, *dim), sampled point along the time-dependent density p_t
+ ut: shape (bs, *dim), conditional vector field
+ t : shape (bs,), represents the time in [0, 1]
+ """
+ if not exists(x0):
+ x0 = torch.randn_like(x1)
+ if not exists(t):
+ t = self.t_sampler(x1.shape[0], device=x1.device, dtype=x1.dtype)
+
+ xt = self.compute_xt(x0=x0, x1=x1, t=t)
+ ut = self.compute_ut(x0=x0, x1=x1, t=t)
+
+ return xt, ut, t
+
+ def training_losses(self, model: nn.Module, x1: Tensor, x0: Tensor = None, **cond_kwargs):
+ """
+ Args:
+ x1: shape (bs, *dim), represents the target minibatch (data)
+ x0: shape (bs, *dim), represents the source minibatch, if None
+ we sample x0 from a standard normal distribution.
+ cond_kwargs: additional arguments for the conditional flow
+ network (e.g. conditioning information)
+ Returns:
+ loss: scalar, the training loss for the flow model
+ """
+ xt, ut, t = self.get_interpolants(x1=x1, x0=x0)
+ vt = model(x=xt, t=t, **cond_kwargs)
+
+ return (vt - ut).square().mean()
+
+ def validation_losses(self, model: nn.Module, x1: Tensor, x0: Tensor = None, num_segments: int = 8, **cond_kwargs):
+ """
+ SD3 & Meta Movie Gen show that val loss correlates well with human quality. They
+ compute the loss in equidistant segments in (0, 1) to reduce variance and average
+ them afterwards. Default number of segments: 8 (Esser et al., page 21, ICML 2024).
+ """
+ assert num_segments > 0, "Number of segments must be greater than 0"
+
+ if not exists(x0):
+ x0 = torch.randn_like(x1)
+ ts = torch.linspace(0, 1, num_segments + 1)[:-1] + 1 / (2 * num_segments)
+
+ losses_per_segment = []
+ for t in ts:
+ t = torch.ones(x1.shape[0], device=x1.device) * t
+ xt, ut, t = self.get_interpolants(x1=x1, x0=x0, t=t)
+ vt = model(x=xt, t=t, **cond_kwargs)
+ losses_per_segment.append((vt - ut).square().mean())
+
+ losses_per_segment = torch.stack(losses_per_segment)
+ return losses_per_segment.mean(), losses_per_segment
diff --git a/patch-forcing/patch_flow/flow_pf.py b/patch-forcing/patch_flow/flow_pf.py
new file mode 100644
index 0000000000000000000000000000000000000000..60d925d51d32e4907543370981df9294dafbce9d
--- /dev/null
+++ b/patch-forcing/patch_flow/flow_pf.py
@@ -0,0 +1,363 @@
+import torch
+import torch.nn as nn
+from torch import Tensor
+
+import einops
+from tqdm import tqdm
+from jaxtyping import Float
+from functools import partial
+from typing import Tuple, Optional
+
+from jutils import instantiate_from_config
+
+
+# ===================================================================================================
+# utility functions
+
+
+def exists(x):
+ return x is not None
+
+
+def pad_v_like_x(v_, x_):
+ """
+ Reshape or broadcast v_ to match the number of dimensions of x_ by appending singleton dims.
+ - x_: (b, c, h, w), v_: (b,) -> (b, 1, 1, 1)
+ - x_: (b, c, f, h, w), v_: (b, 1, f) -> (b, 1, f, 1, 1)
+ """
+ if isinstance(v_, (float, int)):
+ return v_
+ while v_.ndim < x_.ndim:
+ v_ = v_.unsqueeze(-1)
+ return v_
+
+
+def forward_with_cfg(
+ x, t, model, cfg_scale=1.0, uc_cond=None, cond_key="y", t_min: float = None, t_max: float = None, **model_kwargs
+):
+ """Function to include sampling with Classifier-Free Guidance (CFG) and Interval Guidance (IG)"""
+ if cfg_scale == 1.0: # without CFG
+ return model(x, t, **model_kwargs)
+ else: # with CFG
+ if t_min is not None and t_max is not None: # with interval guidance
+ assert torch.allclose(t, t[0]), "Time t should be the same across the batch for interval guidance"
+ assert t_min < t_max, "t_min should be smaller than t_max for interval guidance"
+ t_val = t[0].item()
+ if not t_min <= t_val <= t_max: # no cfg outside of the interval
+ return model(x, t, **model_kwargs)
+ assert cond_key in model_kwargs, f"Condition key '{cond_key}' for CFG not found in model_kwargs"
+ assert uc_cond is not None, "Unconditional condition not provided for CFG"
+ kwargs = model_kwargs.copy()
+ c = kwargs[cond_key]
+ x_in = torch.cat([x] * 2)
+ t_in = torch.cat([t] * 2)
+ if uc_cond.shape[0] == 1:
+ uc_cond = einops.repeat(uc_cond, "1 ... -> bs ...", bs=x.shape[0])
+ c_in = torch.cat([uc_cond, c])
+ kwargs[cond_key] = c_in
+ model_uc, model_c = model(x_in, t_in, **kwargs).chunk(2)
+ return model_uc + cfg_scale * (model_c - model_uc)
+
+
+def compute_xt_patched(
+ x1: Tensor, # (b, c, h, w) data / target
+ t: Tensor, # (b, n) or (b, gh, gw) timesteps in [0, 1]
+ patch_size: Tuple[int, int], # (ph, pw)
+ x0: Optional[Tensor] = None, # (b, c, h, w); if None, sampled ~ N(0, I)
+):
+ assert x1.ndim == 4, f"Expected x1 of shape (b, c, h, w), got {x1.shape}"
+ b, c, h, w = x1.shape
+ if isinstance(patch_size, int):
+ patch_size = (patch_size, patch_size)
+ ph, pw = patch_size
+ assert h % ph == 0 and w % pw == 0, f"h,w must be divisible by patch size; got {(h,w)} vs {(ph,pw)}"
+
+ gh, gw = h // ph, w // pw # grid of patches
+
+ if x0 is None:
+ x0 = torch.randn_like(x1)
+ assert x0.shape == x1.shape, f"x0 must have shape {x1.shape}, got {x0.shape}"
+
+ # normalize t to (b, gh, gw)
+ if t.ndim == 2:
+ n = gh * gw
+ assert t.shape[1] == n, f"t has {t.shape[1]} tokens but expected {n} (gh*gw)"
+ t_grid = t.view(b, gh, gw)
+ elif t.ndim == 3:
+ assert t.shape[1:] == (gh, gw), f"t must be (b, gh, gw); got {t.shape}"
+ t_grid = t
+ else:
+ raise AssertionError(f"t must be (b, n) or (b, gh, gw); got shape {t.shape}")
+
+ # reshape into (b, c, gh, gw, ph, pw)
+ def _patchify(x: Tensor) -> Tensor:
+ x = x.view(b, c, gh, ph, gw, pw) # (b, c, gh, ph, gw, pw)
+ x = x.permute(0, 1, 2, 4, 3, 5) # (b, c, gh, gw, ph, pw)
+ return x
+
+ def _unpatchify(xp: Tensor) -> Tensor:
+ xp = xp.permute(0, 1, 2, 4, 3, 5).contiguous() # (b, c, gh, ph, gw, pw)
+ return xp.view(b, c, h, w)
+
+ x1_p = _patchify(x1)
+ x0_p = _patchify(x0)
+
+ # Broadcast t_grid to patches: (b, 1, gh, gw, 1, 1)
+ t_b = t_grid.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)
+
+ # Interpolate per patch
+ xt_p = t_b * x1_p + (1.0 - t_b) * x0_p
+
+ xt = _unpatchify(xt_p)
+ return xt
+
+
+def pad_v_like_x_patches(
+ v: Tensor, x_like: Tensor, patch_size: Tuple[int, int] # (b, f) or (b, gh, gw) # (b, c, h, w) # (ph, pw)
+) -> Tensor:
+ """
+ Broadcast a per-patch tensor v onto an image-like tensor x_like.
+
+ Returns:
+ v_img: (b, 1, h, w), where each (ph, pw) patch is filled with the
+ corresponding scalar from v.
+ """
+ assert x_like.ndim == 4, f"x_like should be (b,c,h,w), got {x_like.shape}"
+ b, _, h, w = x_like.shape
+ if isinstance(patch_size, int):
+ patch_size = (patch_size, patch_size)
+ ph, pw = patch_size
+ assert h % ph == 0 and w % pw == 0, "h,w must be divisible by patch size"
+ gh, gw = h // ph, w // pw
+
+ if v.ndim == 2:
+ # (b, f) -> (b, gh, gw)
+ f = gh * gw
+ assert v.shape[1] == f, f"v has {v.shape[1]} tokens, expected {f}"
+ v = v.view(b, gh, gw)
+ else:
+ assert v.shape == (b, gh, gw), f"v must be (b, gh, gw), got {v.shape}"
+
+ # expand each token into its spatial patch
+ v_img = (
+ v.unsqueeze(1) # (b, 1, gh, gw)
+ .unsqueeze(-1)
+ .unsqueeze(-1) # (b, 1, gh, gw, 1, 1)
+ .expand(b, 1, gh, gw, ph, pw)
+ )
+ # patch grid back to image
+ v_img = einops.rearrange(v_img, "b 1 gh gw ph pw -> b 1 (gh ph) (gw pw)")
+ return v_img
+
+
+# ===================================================================================================
+# Patchified Diffusion Forcing
+
+
+class PatchFlowForcing:
+ def __init__(self, timestep_sampler: dict = None, patch_size: int = 2):
+ if isinstance(patch_size, int):
+ patch_size = (patch_size, patch_size)
+ self.patch_size = patch_size
+ if timestep_sampler is None:
+ self.t_sampler = torch.rand
+ else:
+ self.t_sampler = instantiate_from_config(timestep_sampler)
+
+ """ Training """
+
+ def compute_xt(self, x0: Tensor, x1: Tensor, t: Tensor):
+ if x0 is None:
+ x0 = torch.randn_like(x1)
+
+ assert x1.shape == x0.shape, f"x0 and x1 must have the same shape, got {x0.shape} vs {x1.shape}"
+ assert x1.ndim == 4, f"Expected x1 of shape (b, c, h, w), got {x1.shape}"
+ b, c, h, w = x1.shape
+
+ ph, pw = self.patch_size
+ assert h % ph == 0 and w % pw == 0, f"(h, w) must be divisible by patch size; got {(h,w)} vs {(ph,pw)}"
+ gh, gw = h // ph, w // pw # grid of patches
+
+ # normalize t to (b, gh, gw)
+ if t.ndim == 2:
+ n = gh * gw
+ assert t.shape[1] == n, f"t has {t.shape[1]} tokens but expected {n} (gh*gw)"
+ t_grid = t.view(b, gh, gw)
+ elif t.ndim == 3:
+ assert t.shape[1:] == (gh, gw), f"t must be (b, gh, gw); got {t.shape}"
+ t_grid = t
+ else:
+ raise AssertionError(f"t must be (b, n) or (b, gh, gw); got shape {t.shape}")
+
+ # reshape into (b, c, gh, gw, ph, pw)
+ def _patchify(x: Tensor) -> Tensor:
+ x = x.view(b, c, gh, ph, gw, pw) # (b, c, gh, ph, gw, pw)
+ x = x.permute(0, 1, 2, 4, 3, 5) # (b, c, gh, gw, ph, pw)
+ return x
+
+ def _unpatchify(xp: Tensor) -> Tensor:
+ xp = xp.permute(0, 1, 2, 4, 3, 5).contiguous() # (b, c, gh, ph, gw, pw)
+ return xp.view(b, c, h, w)
+
+ x1_p = _patchify(x1)
+ x0_p = _patchify(x0)
+
+ # Broadcast t_grid to patches: (b, 1, gh, gw, 1, 1)
+ t_b = t_grid.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)
+
+ # Interpolate per patch
+ xt_p = t_b * x1_p + (1.0 - t_b) * x0_p
+
+ xt = _unpatchify(xt_p)
+ return xt
+
+ def compute_ut(self, x0: Tensor, x1: Tensor, t: Tensor = None):
+ return x1 - x0
+
+ def get_interpolants(self, x1: Tensor, x0: Tensor = None, t: Tensor = None):
+ b, c, h, w = x1.shape
+ if not exists(x0):
+ x0 = torch.randn_like(x1)
+
+ ph, pw = self.patch_size
+ assert h % ph == 0 and w % pw == 0, f"(h, w) must be divisible by patch size; got {(h,w)} vs {(ph,pw)}"
+
+ f = (h // ph) * (w // pw) # number of patches
+ if not exists(t):
+ t = self.t_sampler((b, f), device=x1.device, dtype=x1.dtype)
+ assert t.ndim == 2, f"Expected t to have shape (bs, f), got {t.shape}"
+ assert t.shape[1] == f, f"Expected t to have {f} timesteps, got {t.shape}"
+
+ xt = self.compute_xt(x0, x1, t)
+ ut = self.compute_ut(x0, x1, t)
+
+ return xt, ut, t
+
+ """ Validation and Generation """
+
+ def validation_losses(
+ self,
+ model: nn.Module,
+ x1: Float[Tensor, "bs c h w"],
+ x0: Float[Tensor, "bs c h w"] = None,
+ num_segments: int = 8,
+ **cond_kwargs,
+ ):
+ """
+ SD3 & Meta Movie Gen show that val loss correlates well with human quality. They
+ compute the loss in equidistant segments in (0, 1) to reduce variance and average
+ them afterwards. Default number of segments: 8 (Esser et al., page 21, ICML 2024).
+ """
+ assert num_segments > 0, "Number of segments must be greater than 0"
+
+ bs, c, h, w = x1.shape
+ ph, pw = self.patch_size
+ f = (h // ph) * (w // pw) # number of patches
+
+ if not exists(x0):
+ x0 = torch.randn_like(x1)
+ ts = torch.linspace(0, 1, num_segments + 1)[:-1] + 1 / (2 * num_segments)
+
+ losses_per_segment = []
+ for t in ts:
+ t = torch.ones((bs, f), device=x1.device) * t
+
+ xt, ut, t = self.get_interpolants(x1=x1, x0=x0, t=t)
+ vt = model(x=xt, t=t, **cond_kwargs)
+ losses_per_segment.append((vt - ut).square().mean())
+
+ losses_per_segment = torch.stack(losses_per_segment)
+ return losses_per_segment.mean(), losses_per_segment
+
+ def integrate_conditioning(
+ self,
+ x: Float[Tensor, "bs c h w"],
+ denoise_schedule: Float[Tensor, "t f"],
+ x_cond: Float[Tensor, "bs c h w"] = None,
+ ):
+ first_row = denoise_schedule[0, :] # (f,)
+
+ # complete denoising, no conditioning
+ if torch.all(first_row == 0.0):
+ return x
+
+ assert x_cond is not None, "x_cond must be provided to integrate conditioning information"
+ assert x_cond.shape == x.shape, f"Expected x_cond to have the same shape as x, got {x_cond.shape} and {x.shape}"
+
+ # mix x and x_cond according to the denoising schedule at t=0
+ t_batched = einops.repeat(first_row, "f -> b f", b=x.shape[0])
+ xt = self.compute_xt(x0=x, x1=x_cond, t=t_batched)
+
+ return xt
+
+ def generate(
+ self,
+ model: nn.Module,
+ x: Float[Tensor, "bs c h w"],
+ x_cond: Float[Tensor, "bs c h w"] = None, # clean sample for conditioning
+ num_steps: int = 50,
+ denoise_schedule: Float[Tensor, "t f"] = None,
+ return_intermediates: bool = False,
+ progress: bool = True,
+ allow_negative_dt: bool = False,
+ **kwargs,
+ ):
+ """
+ Classic Euler sampling from x0 to x1 in num_steps.
+
+ Args:
+ model: nn.Module, the flow model to use for sampling
+ x: source minibatch (bs, c, h, w), usually noise
+ x_cond: conditioning minibatch (bs, c, h, w), usually clean sample
+ num_steps: int, number of steps to take (only if denoise_schedule is None)
+ denoise_schedule: shape (num_steps, f), denoise schedule for each step and frame f. If
+ None, it creates a full sequence denoise schedule with num_steps
+ return_intermediates: bool, if true, return list of intermediate samples
+ progress: bool, if true, show tqdm progress bar
+ allow_negative_dt: bool, if true, allow negative time steps (e.g. for reverse sampling),
+ but otherwise clamp them to 0.0 (e.g. when we use predicted frames as conditioning
+ and want to avoid treating them as ground truth)
+ kwargs: additional arguments for the network (e.g. conditioning information)
+ """
+ dev = x.device
+ bs, c, h, w = x.shape
+ ph, pw = self.patch_size
+ f = (h // ph) * (w // pw) # number of patches
+
+ if denoise_schedule is None:
+ denoise_schedule = torch.linspace(0, 1, num_steps + 1)
+ denoise_schedule = einops.repeat(denoise_schedule, "t -> t f", f=f)
+
+ assert (
+ denoise_schedule.shape[1] == f
+ ), f"Expected denoise_schedule to have {f} frames, got {denoise_schedule.shape[1]}"
+ denoise_schedule = denoise_schedule.to(dev)
+
+ # integrate conditioning information (e.g. clean frames)
+ x = self.integrate_conditioning(x=x, x_cond=x_cond, denoise_schedule=denoise_schedule)
+
+ # include cfg
+ sample_fn = partial(forward_with_cfg, model=model)
+
+ xt = x
+ intermediates = [xt]
+ for t_curr, t_next in tqdm(
+ zip(denoise_schedule[:-1], denoise_schedule[1:]), disable=not progress, total=len(denoise_schedule) - 1
+ ):
+ t = torch.ones((bs, 1), dtype=x.dtype, device=dev) * t_curr
+ pred = sample_fn(xt, t, **kwargs)
+
+ dt = t_next - t_curr
+ if not allow_negative_dt:
+ dt = torch.clamp(dt, min=0.0)
+ dt = einops.repeat(dt, "f -> b f", b=bs)
+
+ dt_grid = pad_v_like_x_patches(dt, pred, patch_size=self.patch_size)
+ xt = xt + dt_grid * pred
+
+ if return_intermediates:
+ intermediates.append(xt)
+
+ if return_intermediates:
+ return torch.stack(intermediates, 0)
+ return xt
diff --git a/patch-forcing/patch_flow/integrators.py b/patch-forcing/patch_flow/integrators.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5583c203b24e06af1e4a8182fa191a921eb5a07
--- /dev/null
+++ b/patch-forcing/patch_flow/integrators.py
@@ -0,0 +1,338 @@
+import torch
+import einops
+from tqdm import tqdm
+from functools import partial
+import torch.nn.functional as F
+from abc import ABC, abstractmethod
+
+from patch_flow.flow_pf import pad_v_like_x_patches
+
+
+# ===================================================================================================
+
+
+def forward_with_cfg_and_uncertainty(x, t, model, cfg_scale=1.0, uc_cond=None, cond_key="y", **model_kwargs):
+ """Function to include sampling with Classifier-Free Guidance (CFG)"""
+ if cfg_scale == 1.0: # without CFG
+ model_output = model(x, t, **model_kwargs, return_uncertainty=True)
+ model_vt, model_uq = model_output
+ out = {"vt": model_vt, "uq": model_uq, "uq_uc": None, "uq_c": model_uq, "vt_uc": None, "vt_c": model_vt}
+
+ else: # with CFG
+ assert cond_key in model_kwargs, f"Condition key '{cond_key}' for CFG not found in model_kwargs"
+ assert uc_cond is not None, "Unconditional condition not provided for CFG"
+ kwargs = model_kwargs.copy()
+ c = kwargs[cond_key]
+ x_in = torch.cat([x] * 2)
+ t_in = torch.cat([t] * 2)
+ if uc_cond.shape[0] == 1:
+ uc_cond = einops.repeat(uc_cond, "1 ... -> bs ...", bs=x.shape[0])
+ c_in = torch.cat([uc_cond, c])
+ kwargs[cond_key] = c_in
+ model_output = model(x_in, t_in, **kwargs, return_uncertainty=True)
+ model_vt, model_uq = model_output
+ model_vt_uc, model_vt_c = model_vt.chunk(2)
+ model_uq_uc, model_uq_c = model_uq.chunk(2)
+ guided_vt = model_vt_uc + cfg_scale * (model_vt_c - model_vt_uc)
+ guided_uq = model_uq_uc + cfg_scale * (model_uq_c - model_uq_uc)
+
+ out = {
+ "vt": guided_vt,
+ "uq": guided_uq,
+ "uq_uc": model_uq_uc,
+ "uq_c": model_uq_c,
+ "vt_uc": model_vt_uc,
+ "vt_c": model_vt_c,
+ }
+
+ return out
+
+
+def forward_with_cfg(x, t, model, cfg_scale=1.0, uc_cond=None, cond_key="y", **model_kwargs):
+ """Function to include sampling with Classifier-Free Guidance (CFG)"""
+ if cfg_scale == 1.0: # without CFG
+ model_output = model(x, t, **model_kwargs)
+
+ else: # with CFG
+ assert cond_key in model_kwargs, f"Condition key '{cond_key}' for CFG not found in model_kwargs"
+ assert uc_cond is not None, "Unconditional condition not provided for CFG"
+ kwargs = model_kwargs.copy()
+ c = kwargs[cond_key]
+ x_in = torch.cat([x] * 2)
+ t_in = torch.cat([t] * 2)
+ if uc_cond.shape[0] == 1:
+ uc_cond = einops.repeat(uc_cond, "1 ... -> bs ...", bs=x.shape[0])
+ c_in = torch.cat([uc_cond, c])
+ kwargs[cond_key] = c_in
+ model_uc, model_c = model(x_in, t_in, **kwargs).chunk(2)
+ model_output = model_uc + cfg_scale * (model_c - model_uc)
+
+ return model_output
+
+
+def patch_reduce_pool(x: torch.Tensor, n: int, mode: str = "mean"):
+ """Patch reducing with pooling (downsampling)"""
+ if mode == "mean":
+ return F.avg_pool2d(x, kernel_size=n, stride=n)
+ elif mode == "max":
+ return F.max_pool2d(x, kernel_size=n, stride=n)
+ elif mode == "min":
+ return -F.max_pool2d(-x, kernel_size=n, stride=n)
+ else:
+ raise ValueError("mode must be 'mean', 'max', or 'min'")
+
+
+def patch_reduce(x: torch.Tensor, n: int, mode: str = "mean"):
+ """Patch reduce and upsample to original size"""
+ y = patch_reduce_pool(x, n=n, mode=mode)
+ y = y.repeat_interleave(n, dim=-1).repeat_interleave(n, dim=-2)
+ assert y.shape == x.shape
+ return y
+
+
+# ======================================================================================
+
+
+class SamplerBase(ABC):
+ @abstractmethod
+ def __repr__(self) -> str: ...
+
+ @abstractmethod
+ def __call__(self, model, x, timesteps: list[float], progress: bool = True, **kwargs): ...
+
+
+# ======================================================================================
+# Base samplers
+
+
+def euler(model, x, timesteps: list[float], progress=True, **kwargs):
+ bs, dev = x.shape[0], x.device
+
+ xt = x
+ for t_curr, t_next in tqdm(zip(timesteps[:-1], timesteps[1:]), disable=not progress, total=len(timesteps) - 1):
+ t = torch.ones((bs,), dtype=x.dtype, device=dev) * t_curr
+ pred = model(xt, t, **kwargs)
+
+ dt = t_next - t_curr
+ xt = xt + dt * pred
+
+ return xt
+
+
+class Euler(SamplerBase):
+ def __repr__(self):
+ return "Euler"
+
+ def __call__(self, model, x, timesteps: list[float], progress=True, **kwargs):
+ model_fn = partial(forward_with_cfg, model=model)
+ return euler(model_fn, x, timesteps, progress=progress, **kwargs)
+
+
+# ======================================================================================
+# Patch Forcing samplers
+
+
+class EulerPF(SamplerBase):
+ """Default Euler sampler, ignores uncertainty"""
+
+ def __init__(self, patch_size: int = 2):
+ self.patch_size = patch_size
+
+ def __repr__(self):
+ return "EulerPF"
+
+ def __call__(self, model, x, timesteps: list[float], progress=True, **kwargs):
+ dev = x.device
+ bs, c, h, w = x.shape
+ f = (h // self.patch_size) * (w // self.patch_size)
+
+ # prepare sample function
+ sample_fn = partial(forward_with_cfg_and_uncertainty, model=model)
+
+ xt = x
+ for t_curr, t_next in tqdm(zip(timesteps[:-1], timesteps[1:]), disable=not progress, total=len(timesteps) - 1):
+ t = torch.ones((bs,), dtype=x.dtype, device=dev) * t_curr
+ # Here we broadcast to (b, n)
+ t = einops.repeat(t, "b -> b f", f=f)
+ pred = sample_fn(xt, t, **kwargs)
+ pred = pred["vt"]
+
+ dt = t_next - t_curr
+ xt = xt + dt * pred
+
+ return xt
+
+
+# ======================================================================================
+# Uncertainty-aware samplers
+
+
+class DualLoopSampler(SamplerBase):
+ def __init__(self, p: float = 0.7, n_inner: int = 4, mode: str = "mean", patch_size: int = 2):
+ """
+ Args:
+ p: percentile for thresholding uncertainty. All patches with uncertainty
+ lower than the p-th percentile will be considered certain. So lower
+ p -> more restrictive (fewer certain patches), e.g. p=0.8 means 80%
+ of patches are considered certain (20% uncertain).
+ n_inner: Number of inner steps, per big step.
+ """
+ self.p = p
+ self.n_inner = n_inner # inner steps for uncertain patches
+ self.patch_size = patch_size
+ self.mode = mode
+ assert 0.0 < p < 1.0, "p must be in (0, 1)"
+
+ def __repr__(self):
+ return f"DualLoop-p{self.p*100:.0f}-inner{self.n_inner}"
+
+ def compute_mask(self, uq):
+ uq_flat = uq.reshape(uq.shape[0], -1).double()
+ thresh = torch.quantile(uq_flat, self.p, dim=-1) # (bs,)
+ thresh_exp = einops.repeat(thresh, "b -> b 1 1 1")
+ uq_mask = uq < thresh_exp # 0: uncertain (inner loop), 1: certain (forward)
+ return uq_mask
+
+ def __call__(self, model, x, timesteps: list[float], progress=True, **kwargs):
+ dev = x.device
+ bs, c, h, w = x.shape
+ f = (h // self.patch_size) * (w // self.patch_size)
+
+ # make denoising schedule
+ num_steps = len(timesteps) - 1
+ denoise_schedule = torch.linspace(0, 1, num_steps + 1)
+ denoise_schedule = einops.repeat(denoise_schedule, "t -> t f", f=f).to(dev)
+ assert denoise_schedule.shape[1] == f
+
+ # prepare sample function
+ sample_fn = partial(forward_with_cfg_and_uncertainty, model=model)
+
+ # sampling loop
+ xt = x
+ for t_curr, t_next in tqdm(
+ zip(denoise_schedule[:-1], denoise_schedule[1:]), total=len(denoise_schedule) - 1, disable=not progress
+ ):
+ t = einops.repeat(t_curr, "f -> b f", b=bs)
+
+ model_out = sample_fn(xt, t, **kwargs)
+ pred = model_out["vt"]
+
+ dt = t_next - t_curr
+ dt = torch.clamp(dt, min=0.0)
+ dt = einops.repeat(dt, "f -> b f", b=bs)
+ dt_grid = pad_v_like_x_patches(dt, pred, patch_size=self.patch_size)
+
+ # x1 prediction from xt (not used during inference)
+ # dt_x1 = (1 - t)
+ # dt_x1_grid = pad_v_like_x_patches(dt_x1, pred, patch_size=self.patch_size)
+ # x1_pred = xt + dt_x1_grid * pred
+
+ # # update xt # NORMALLY USE THIS
+ # xt = xt + dt_grid * pred
+
+ # ============================================= inner loop update xt
+ # with mask
+ uq = model_out["uq"].exp()
+ uq = patch_reduce(uq, n=2, mode=self.mode)
+ uq_mask = self.compute_mask(uq)
+
+ dt_inner_grid = dt_grid / self.n_inner
+
+ xt = xt + dt_grid * pred * uq_mask + dt_inner_grid * pred * (~uq_mask)
+
+ t_grid = pad_v_like_x_patches(t, pred, patch_size=self.patch_size)
+ t_grid = t_grid + dt_grid * uq_mask + dt_inner_grid * (~uq_mask)
+
+ for _ in range(self.n_inner - 1):
+ t_inp = patch_reduce_pool(t_grid, n=2, mode="mean")
+ t_inp = einops.rearrange(t_inp, "b 1 h w -> b (h w)")
+ model_out_inner = sample_fn(xt, t_inp, **kwargs)
+ pred = model_out_inner["vt"]
+ xt = xt + dt_inner_grid * pred * (~uq_mask)
+ t_grid = t_grid + dt_inner_grid * (~uq_mask)
+
+ return xt
+
+
+class LookAheadSampler(SamplerBase):
+ def __init__(self, p: float = 0.4, mode: str = "mean", patch_size: int = 2, context_t_ratio: int = 1.5):
+ """
+ Context-guidance on uncertain patches during sampling. For certain patches, use one-step prediction for better context for uncertain patches.
+ """
+ self.p = p
+ self.patch_size = patch_size
+ self.mode = mode
+ self.context_t_ratio = context_t_ratio
+ assert 0.0 < p < 1.0, "p must be in (0, 1)"
+
+ def __repr__(self):
+ return f"LookAheadSampler-p{self.p*100:.0f}-context{self.context_t_ratio:.2f}"
+
+ def compute_mask(self, uq):
+ uq_flat = uq.reshape(uq.shape[0], -1).double()
+ thresh = torch.quantile(uq_flat, self.p, dim=-1) # (bs,)
+ thresh_exp = einops.repeat(thresh, "b -> b 1 1 1")
+ uq_mask = uq < thresh_exp # 0: uncertain (use context), 1: certain (use model)
+ return uq_mask
+
+ def __call__(self, model, x, timesteps: list[float], progress=True, **kwargs):
+ dev = x.device
+ bs, c, h, w = x.shape
+ f = (h // self.patch_size) * (w // self.patch_size)
+
+ # make denoising schedule
+ num_steps = len(timesteps) - 1
+ denoise_schedule = torch.linspace(0, 1, num_steps + 1)
+ denoise_schedule = einops.repeat(denoise_schedule, "t -> t f", f=f).to(dev)
+ assert denoise_schedule.shape[1] == f
+
+ # prepare sample function
+ sample_fn = partial(forward_with_cfg_and_uncertainty, model=model)
+
+ # sampling loop
+ xt = x
+ for t_curr, t_next in tqdm(
+ zip(denoise_schedule[:-1], denoise_schedule[1:]), total=len(denoise_schedule) - 1, disable=not progress
+ ):
+ t = einops.repeat(t_curr, "f -> b f", b=bs)
+
+ # No CFG for context prediction
+ model_out = sample_fn(xt, t, **kwargs)
+ pred = model_out["vt"]
+ pred_c = model_out["vt_c"]
+
+ dt = t_next - t_curr
+ dt = torch.clamp(dt, min=0.0)
+ dt = einops.repeat(dt, "f -> b f", b=bs)
+ dt_grid = pad_v_like_x_patches(dt, pred, patch_size=self.patch_size)
+
+ # normal step, no context guidance
+ if t_curr.mean() <= 0.05:
+ xt = xt + dt_grid * pred_c
+ continue
+
+ # =============================================
+ uq = model_out["uq"].exp()
+ uq = patch_reduce(uq, n=2, mode=self.mode)
+ low_uq_mask = self.compute_mask(uq)
+ high_uq_mask = ~low_uq_mask
+ low_uq_pool_mask = patch_reduce_pool(low_uq_mask.float(), n=self.patch_size, mode=self.mode).bool()
+
+ # one step prediction for certain patches
+ t_context = t_curr * self.context_t_ratio
+ t_context = torch.clamp(t_context, max=1.0)
+ dt_context = t_context - t_curr
+ dt_context = einops.repeat(dt_context, "f -> b f", b=bs)
+ dt_context_grid = pad_v_like_x_patches(dt_context, pred, patch_size=self.patch_size)
+
+ pred_context = pred_c * low_uq_mask
+ xt_context = xt + dt_context_grid * pred_context
+ t_context = t + dt_context * low_uq_pool_mask.view(bs, -1)
+
+ # context prediction
+ pred_context = sample_fn(xt_context, t_context, **kwargs)["vt"]
+
+ # update xt
+ xt = xt + dt_grid * pred * low_uq_mask + dt_grid * pred_context * high_uq_mask
+
+ return xt
diff --git a/patch-forcing/patch_flow/log_utils.py b/patch-forcing/patch_flow/log_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..05d2637609494f24cc01f4370a4c6cc607403e9e
--- /dev/null
+++ b/patch-forcing/patch_flow/log_utils.py
@@ -0,0 +1,91 @@
+import wandb
+import torch
+import einops
+import numpy as np
+from PIL import Image
+from jutils import NullObject
+from jutils import ims_to_grid
+from torch.utils.tensorboard import SummaryWriter
+from lightning.pytorch.loggers import WandbLogger
+from lightning.pytorch.loggers import TensorBoardLogger
+
+
+def log_image(logger, ims, tag, channel_last=True, step=0):
+ """
+ Args:
+ logger: Logger class
+ ims: torch.Tensor or np.ndarray of shape (c, h, w) or (h, w, c) in range [0, 255]
+ tag: str, key to log the image
+ channel_last: bool, whether the channel dimension is last
+ """
+ assert len(ims.shape) == 3, f"ims shape should be (c, h, w) or (h, w, c), got {ims.shape}"
+ if isinstance(ims, torch.Tensor):
+ ims = ims.cpu().numpy()
+
+ if not channel_last:
+ ims = einops.rearrange(ims, "c h w -> h w c")
+ assert ims.shape[-1] in [1, 3], f"ims can have 1 or 3 channels, got {ims.shape[-1]}"
+
+ if isinstance(logger, WandbLogger):
+ ims = Image.fromarray(ims)
+ ims = wandb.Image(ims)
+ logger.experiment.log({tag: ims})
+
+ elif isinstance(logger, (TensorBoardLogger, SummaryWriter)):
+ ims = einops.rearrange(ims, "h w c -> c h w")
+ if hasattr(logger, "experiment"):
+ logger = logger.experiment
+ logger.add_image(tag, ims, global_step=step)
+
+ elif isinstance(logger, NullObject):
+ pass # Do nothing if logger is a NullObject
+
+ else:
+ raise ValueError(f"Unknown logger type: {type(logger)}")
+
+
+def log_images(logger, ims, tag, stack="row", split=4, step=0):
+ """
+ Args:
+ logger: Logger class
+ ims: torch.Tensor or np.ndarray of shape (b, c, h, w) in range [0, 255]
+ tag: str, key to log the images
+ """
+ assert len(ims.shape) == 4, f"ims shape should be (b, c, h, w), got {ims.shape}"
+ assert ims.dtype in [torch.uint8, np.uint8], f"ims dtype should be uint8, got {ims.dtype}"
+ ims = ims_to_grid(ims, stack=stack, split=split)
+ if isinstance(ims, torch.Tensor):
+ ims = ims.cpu().numpy()
+ log_image(logger=logger, ims=ims, tag=tag, channel_last=True, step=step)
+
+
+def log_videos(logger, videos, tag, step=0, fps=4):
+ """
+ Args:
+ logger: Logger class
+ videos: torch.Tensor or np.ndarray of shape (b, f, h, w, c) in range [0, 255]
+ tag: str, key to log the video
+ """
+ assert len(videos.shape) == 5, f"videos shape should be (b, f, h, w, c), got {videos.shape}"
+ assert videos.dtype in [torch.uint8, np.uint8], f"videos dtype should be uint8, got {videos.dtype}"
+
+ if isinstance(logger, WandbLogger):
+ # wandb expects (f c h w) or (b f c h w)
+ videos = einops.rearrange(videos, "b f h w c -> b f c h w")
+ videos = wandb.Video(videos, fps=fps, format="gif")
+ if hasattr(logger, "experiment"):
+ logger = logger.experiment
+ logger.log({tag: videos})
+
+ elif isinstance(logger, (TensorBoardLogger, SummaryWriter)):
+ # convert to numpy and rearrange to (N, T, C, H, W)
+ videos = einops.rearrange(videos, "b f h w c -> b f c h w")
+ if hasattr(logger, "experiment"):
+ logger = logger.experiment
+ logger.add_video(tag, videos, global_step=step, fps=fps)
+
+ elif isinstance(logger, NullObject):
+ pass # Do nothing if logger is a NullObject
+
+ else:
+ raise ValueError(f"Unknown logger type: {type(logger)}")
diff --git a/patch-forcing/patch_flow/metrics.py b/patch-forcing/patch_flow/metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..b04f987467e7fe18d6f6b13b9412698e6b9d8a38
--- /dev/null
+++ b/patch-forcing/patch_flow/metrics.py
@@ -0,0 +1,118 @@
+import torch
+import torch.nn as nn
+
+from torchmetrics import CatMetric
+from torchmetrics import SumMetric # sum over devices
+from torchmetrics.image.fid import FrechetInceptionDistance
+from torchmetrics.multimodal.clip_score import CLIPScore
+
+from jutils.nn import DINOv2, preprocess_for_dinov2
+from jutils.nn.metric_kid import kid_features_to_metric
+
+
+def un_normalize_ims(ims):
+ """Convert from [-1, 1] to [0, 255]"""
+ ims = ((ims * 127.5) + 127.5).clip(0, 255).to(torch.uint8)
+ return ims
+
+
+class ImageMetricTracker(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.total_samples = SumMetric()
+
+ self.fid = FrechetInceptionDistance(
+ feature=2048, reset_real_features=True, normalize=False, sync_on_compute=True
+ )
+
+ def __call__(self, target, pred):
+ """Assumes target and pred in [-1, 1] range"""
+ bs = target.shape[0]
+ real_ims = un_normalize_ims(target)
+ fake_ims = un_normalize_ims(pred)
+
+ self.fid.update(real_ims, real=True)
+ self.fid.update(fake_ims, real=False)
+
+ self.total_samples.update(bs)
+
+ def reset(self):
+ self.fid.reset()
+ self.total_samples.reset()
+
+ def aggregate(self):
+ """Compute the final metrics (automatically synced across devices)"""
+ n_total_samples = int(self.total_samples.compute())
+ return {
+ f"fid-{n_total_samples}": self.fid.compute(),
+ "n_metric_samples": n_total_samples,
+ }
+
+
+class Text2ImageMetricTracker(nn.Module):
+ def __init__(self, kid_subsets: int = 100, kid_subset_size: int = 200):
+ super().__init__()
+ self.total_samples = SumMetric()
+ self.fid = FrechetInceptionDistance(
+ feature=2048, reset_real_features=True, normalize=False, sync_on_compute=True
+ )
+
+ self.clip = CLIPScore(model_name_or_path="openai/clip-vit-base-patch16")
+
+ self.dino = DINOv2(pretrained=True).eval()
+ self.dino_features_real = CatMetric()
+ self.dino_features_fake = CatMetric()
+ self.kid_subsets = kid_subsets
+ self.kid_subset_size = kid_subset_size
+
+ for p in self.parameters():
+ p.requires_grad = False
+
+ @torch.no_grad()
+ def __call__(self, target, pred, txt):
+ """Assumes target and pred in [-1, 1] range"""
+ bs = target.shape[0]
+ real_ims = un_normalize_ims(target)
+ fake_ims = un_normalize_ims(pred)
+
+ self.fid.update(real_ims, real=True)
+ self.fid.update(fake_ims, real=False)
+
+ txt = [t.decode() if isinstance(t, bytes) else t for t in txt]
+ self.clip.update(fake_ims, list(txt))
+
+ real_fts = self.dino(preprocess_for_dinov2(target, safe_mode=False))
+ fake_fts = self.dino(preprocess_for_dinov2(pred, safe_mode=False))
+ self.dino_features_real.update(real_fts)
+ self.dino_features_fake.update(fake_fts)
+
+ self.total_samples.update(bs)
+
+ def reset(self):
+ self.fid.reset()
+ self.clip.reset()
+ self.dino_features_real.reset()
+ self.dino_features_fake.reset()
+ self.total_samples.reset()
+
+ def aggregate(self):
+ """Compute the final metrics (automatically synced across devices)"""
+ n_total_samples = int(self.total_samples.compute())
+
+ # compute KDD
+ real_fts = self.dino_features_real.compute()
+ fake_fts = self.dino_features_fake.compute()
+ kdd = kid_features_to_metric(
+ real_fts,
+ fake_fts,
+ kid_subsets=self.kid_subsets,
+ kid_subset_size=self.kid_subset_size,
+ verbose=False,
+ )
+
+ return {
+ f"fid-{n_total_samples}": self.fid.compute(),
+ f"clip": self.clip.compute(),
+ **kdd,
+ "n_metric_samples": n_total_samples,
+ }
diff --git a/patch-forcing/patch_flow/models/__pycache__/dit.cpython-312.pyc b/patch-forcing/patch_flow/models/__pycache__/dit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b603c5a7c5bb7964f6acaffb11caabae468f1d1
Binary files /dev/null and b/patch-forcing/patch_flow/models/__pycache__/dit.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/models/__pycache__/pf_transformer.cpython-312.pyc b/patch-forcing/patch_flow/models/__pycache__/pf_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..519dd72fdf8a28010b17fb8b9f735ef55ba95154
Binary files /dev/null and b/patch-forcing/patch_flow/models/__pycache__/pf_transformer.cpython-312.pyc differ
diff --git a/patch-forcing/patch_flow/models/dit.py b/patch-forcing/patch_flow/models/dit.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5e719bcc4da746c21aac94288498ae1cafe2e1f
--- /dev/null
+++ b/patch-forcing/patch_flow/models/dit.py
@@ -0,0 +1,389 @@
+import torch
+import math
+import numpy as np
+import torch.nn as nn
+from functools import partial
+from timm.models.vision_transformer import PatchEmbed, Attention, Mlp
+
+
+COMPILE = True
+if torch.cuda.is_available():
+ compile_fn = partial(torch.compile, fullgraph=True, backend='inductor' if torch.cuda.get_device_capability()[0] >= 7 else 'aot_eager')
+else:
+ compile_fn = lambda f: f
+
+
+def modulate(x, shift, scale):
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
+
+
+#################################################################################
+# Embedding Layers for Timesteps and Class Labels #
+#################################################################################
+
+class TimestepEmbedder(nn.Module):
+ """
+ Embeds scalar timesteps into vector representations.
+ """
+ def __init__(self, hidden_size, frequency_embedding_size=256):
+ super().__init__()
+ self.mlp = nn.Sequential(
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
+ nn.SiLU(),
+ nn.Linear(hidden_size, hidden_size, bias=True),
+ )
+ self.frequency_embedding_size = frequency_embedding_size
+
+ if COMPILE: self.forward = compile_fn(self.forward)
+
+ @staticmethod
+ def timestep_embedding(t, dim, max_period=10000):
+ """
+ Create sinusoidal timestep embeddings.
+ :param t: a 1-D Tensor of N indices, one per batch element.
+ These may be fractional.
+ :param dim: the dimension of the output.
+ :param max_period: controls the minimum frequency of the embeddings.
+ :return: an (N, D) Tensor of positional embeddings.
+ """
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
+ half = dim // 2
+ freqs = torch.exp(
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
+ ).to(device=t.device)
+ args = t[:, None].float() * freqs[None]
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ if dim % 2:
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
+ return embedding
+
+ def forward(self, t):
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
+ t_emb = self.mlp(t_freq)
+ return t_emb
+
+
+class LabelEmbedder(nn.Module):
+ """
+ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
+ """
+ def __init__(self, num_classes, hidden_size, dropout_prob):
+ super().__init__()
+ use_cfg_embedding = dropout_prob > 0
+ self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
+ self.num_classes = num_classes
+ self.dropout_prob = dropout_prob
+
+ if COMPILE: self.forward = compile_fn(self.forward)
+
+ def token_drop(self, labels, force_drop_ids=None):
+ """
+ Drops labels to enable classifier-free guidance.
+ """
+ if force_drop_ids is None:
+ drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
+ else:
+ drop_ids = force_drop_ids == 1
+ labels = torch.where(drop_ids, self.num_classes, labels)
+ return labels
+
+ def forward(self, labels, train, force_drop_ids=None):
+ use_dropout = self.dropout_prob > 0
+ if (train and use_dropout) or (force_drop_ids is not None):
+ labels = self.token_drop(labels, force_drop_ids)
+ embeddings = self.embedding_table(labels)
+ return embeddings
+
+
+#################################################################################
+# Core DiT Model #
+#################################################################################
+
+class DiTBlock(nn.Module):
+ """
+ A DiT block with adaptive layer norm zero (adaLN-Zero) conditioning.
+ """
+ def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs):
+ super().__init__()
+ self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs)
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
+ approx_gelu = lambda: nn.GELU(approximate="tanh")
+ self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0)
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(),
+ nn.Linear(hidden_size, 6 * hidden_size, bias=True)
+ )
+
+ if COMPILE: self.forward = compile_fn(self.forward)
+
+ def forward(self, x, c):
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)
+ x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa))
+ x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
+ return x
+
+
+class FinalLayer(nn.Module):
+ """
+ The final layer of DiT.
+ """
+ def __init__(self, hidden_size, patch_size, out_channels):
+ super().__init__()
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(),
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True)
+ )
+
+ if COMPILE: self.forward = compile_fn(self.forward)
+
+ def forward(self, x, c):
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
+ x = modulate(self.norm_final(x), shift, scale)
+ x = self.linear(x)
+ return x
+
+
+class DiT(nn.Module):
+ """
+ Diffusion model with a Transformer backbone.
+ """
+ def __init__(
+ self,
+ input_size=32,
+ patch_size=2,
+ in_channels=4,
+ hidden_size=1152,
+ depth=28,
+ num_heads=16,
+ mlp_ratio=4.0,
+ class_dropout_prob=0.1,
+ num_classes=1000,
+ out_channels=None,
+ learn_sigma=False, # LEGACY (True for DiT and SiT)
+ return_sigma=False, # LEGACY (True for DiT, False for SiT, but not used at all)
+ compile=False,
+ ):
+ super().__init__()
+ global COMPILE
+ COMPILE = compile
+
+ self.learn_sigma = learn_sigma
+ self.return_sigma = return_sigma
+
+ self.in_channels = in_channels
+ if learn_sigma:
+ self.out_channels = in_channels * 2
+ else:
+ self.out_channels = out_channels if out_channels is not None else in_channels
+ self.patch_size = patch_size
+ self.num_heads = num_heads
+ self.hidden_size = hidden_size
+
+ self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)
+ self.t_embedder = TimestepEmbedder(hidden_size)
+ self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)
+ num_patches = self.x_embedder.num_patches
+ # Will use fixed sin-cos embedding:
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
+
+ self.blocks = nn.ModuleList([
+ DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth)
+ ])
+ self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels)
+ self.initialize_weights()
+
+ def initialize_weights(self):
+ # Initialize transformer layers:
+ def _basic_init(module):
+ if isinstance(module, nn.Linear):
+ torch.nn.init.xavier_uniform_(module.weight)
+ if module.bias is not None:
+ nn.init.constant_(module.bias, 0)
+ self.apply(_basic_init)
+
+ # Initialize (and freeze) pos_embed by sin-cos embedding:
+ pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
+
+ # Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
+ w = self.x_embedder.proj.weight.data
+ nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
+ nn.init.constant_(self.x_embedder.proj.bias, 0)
+
+ # Initialize label embedding table:
+ nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
+
+ # Initialize timestep embedding MLP:
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
+
+ # Zero-out adaLN modulation layers in DiT blocks:
+ for block in self.blocks:
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
+
+ # Zero-out output layers:
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
+ nn.init.constant_(self.final_layer.linear.weight, 0)
+ nn.init.constant_(self.final_layer.linear.bias, 0)
+
+ def unpatchify(self, x):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.out_channels
+ p = self.x_embedder.patch_size[0]
+ h = w = int(x.shape[1] ** 0.5)
+ assert h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
+ x = torch.einsum('nhwpqc->nchpwq', x)
+ imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
+ return imgs
+
+ def forward(self, x, t, y):
+ """
+ Forward pass of DiT.
+ x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
+ t: (N,) tensor of diffusion timesteps
+ y: (N,) tensor of class labels
+ """
+ x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2
+ t = self.t_embedder(t) # (N, D)
+ y = self.y_embedder(y, self.training) # (N, D)
+ c = t + y # (N, D)
+ for block in self.blocks:
+ x = block(x, c) # (N, T, D)
+ x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels)
+ x = self.unpatchify(x) # (N, out_channels, H, W)
+ if self.learn_sigma and not self.return_sigma: # LEGACY
+ x, _ = x.chunk(2, dim=1)
+ return x
+
+ def forward_with_cfg(self, x, t, y, cfg_scale):
+ """
+ Forward pass of DiT, but also batches the unconditional forward pass for classifier-free guidance.
+ """
+ # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb
+ half = x[: len(x) // 2]
+ combined = torch.cat([half, half], dim=0)
+ model_out = self.forward(combined, t, y)
+ # For exact reproducibility reasons, we apply classifier-free guidance on only
+ # three channels by default. The standard approach to cfg applies it to all channels.
+ # This can be done by uncommenting the following line and commenting-out the line following that.
+ eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:]
+ # eps, rest = model_out[:, :3], model_out[:, 3:]
+ cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
+ half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
+ eps = torch.cat([half_eps, half_eps], dim=0)
+ return torch.cat([eps, rest], dim=1)
+
+
+#################################################################################
+# Sine/Cosine Positional Embedding Functions #
+#################################################################################
+# https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
+
+def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
+ """
+ grid_size: int of the grid height and width
+ return:
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
+ """
+ grid_h = np.arange(grid_size, dtype=np.float32)
+ grid_w = np.arange(grid_size, dtype=np.float32)
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([2, 1, grid_size, grid_size])
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+
+def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
+ assert embed_dim % 2 == 0
+
+ # use half of dimensions to encode grid_h
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
+
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
+ return emb
+
+
+def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
+ """
+ embed_dim: output dimension for each position
+ pos: a list of positions to be encoded: size (M,)
+ out: (M, D)
+ """
+ assert embed_dim % 2 == 0
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
+ omega /= embed_dim / 2.
+ omega = 1. / 10000**omega # (D/2,)
+
+ pos = pos.reshape(-1) # (M,)
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
+
+ emb_sin = np.sin(out) # (M, D/2)
+ emb_cos = np.cos(out) # (M, D/2)
+
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
+ return emb
+
+
+#################################################################################
+# DiT Configs #
+#################################################################################
+
+def DiT_XL_2(**kwargs):
+ return DiT(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
+
+def DiT_XL_4(**kwargs):
+ return DiT(depth=28, hidden_size=1152, patch_size=4, num_heads=16, **kwargs)
+
+def DiT_XL_8(**kwargs):
+ return DiT(depth=28, hidden_size=1152, patch_size=8, num_heads=16, **kwargs)
+
+def DiT_L_2(**kwargs):
+ return DiT(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
+
+def DiT_L_4(**kwargs):
+ return DiT(depth=24, hidden_size=1024, patch_size=4, num_heads=16, **kwargs)
+
+def DiT_L_8(**kwargs):
+ return DiT(depth=24, hidden_size=1024, patch_size=8, num_heads=16, **kwargs)
+
+def DiT_B_2(**kwargs):
+ return DiT(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
+
+def DiT_B_4(**kwargs):
+ return DiT(depth=12, hidden_size=768, patch_size=4, num_heads=12, **kwargs)
+
+def DiT_B_8(**kwargs):
+ return DiT(depth=12, hidden_size=768, patch_size=8, num_heads=12, **kwargs)
+
+def DiT_S_2(**kwargs):
+ return DiT(depth=12, hidden_size=384, patch_size=2, num_heads=6, **kwargs)
+
+def DiT_S_4(**kwargs):
+ return DiT(depth=12, hidden_size=384, patch_size=4, num_heads=6, **kwargs)
+
+def DiT_S_8(**kwargs):
+ return DiT(depth=12, hidden_size=384, patch_size=8, num_heads=6, **kwargs)
+
+
+DiT_models = {
+ 'DiT-XL/2': DiT_XL_2, 'DiT-XL/4': DiT_XL_4, 'DiT-XL/8': DiT_XL_8,
+ 'DiT-L/2': DiT_L_2, 'DiT-L/4': DiT_L_4, 'DiT-L/8': DiT_L_8,
+ 'DiT-B/2': DiT_B_2, 'DiT-B/4': DiT_B_4, 'DiT-B/8': DiT_B_8,
+ 'DiT-S/2': DiT_S_2, 'DiT-S/4': DiT_S_4, 'DiT-S/8': DiT_S_8,
+}
\ No newline at end of file
diff --git a/patch-forcing/patch_flow/models/dit_t2i.py b/patch-forcing/patch_flow/models/dit_t2i.py
new file mode 100644
index 0000000000000000000000000000000000000000..980f0bd60e91bf7c758ef6b1fc1fbc88e5e45720
--- /dev/null
+++ b/patch-forcing/patch_flow/models/dit_t2i.py
@@ -0,0 +1,177 @@
+import math
+import torch
+import torch.nn as nn
+from jaxtyping import Float
+from einops import rearrange, repeat
+
+from jutils.nn.transformer import TimestepEmbedder
+from jutils.nn.rope import make_axial_pos_2d, AxialRoPEBase
+from jutils.nn.transformer import TransformerLayer, TokenMerge2D, TokenSplitLast2D
+
+
+def make_axial_pos_2d_with_meta(meta, size, device="cpu", latent_ds_factor=8):
+ """
+ Args:
+ meta: dict with keys 'top', 'left', 'orig_h', 'orig_w'
+ size: int, size of the square patch
+ device: device to create the tensor on
+ """
+ top, left = meta["top"], meta["left"]
+ orig_h, orig_w = meta["orig_h"], meta["orig_w"]
+
+ # convert to latent space size
+ top = math.floor(top / latent_ds_factor)
+ left = math.floor(left / latent_ds_factor)
+ orig_h = math.floor(orig_h / latent_ds_factor)
+ orig_w = math.floor(orig_w / latent_ds_factor)
+
+ pos = make_axial_pos_2d(orig_h, orig_w, device=device, align_corners=False, relative_pos=True)
+ pos = rearrange(pos, "(h w) d -> h w d", h=orig_h, w=orig_w)
+ pos = pos[top : top + size, left : left + size, :]
+ return pos
+
+
+class AxialRoPETime(AxialRoPEBase):
+ """
+ Simple 1D RoPE for text/time-like token positions.
+ Uses fixed frequencies (non-learnable), matching standard text RoPE behavior.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ n_heads: int,
+ learnable_freqs: bool = False,
+ relative_canvas: bool = True, # kept for API compatibility
+ in_place: bool = False,
+ half_embedding: bool = True,
+ ):
+ if half_embedding:
+ assert dim % 2 == 0, "Half embedding is only supported for even dimensions"
+ dim //= 2
+ super().__init__(dim, n_heads, in_place=in_place)
+
+ # Best default for text: fixed frequencies, no learned RoPE params.
+ min_freq, max_freq = 1 / 10_000, 1.0
+ log_min = math.log(min_freq)
+ log_max = math.log(max_freq)
+ freqs = torch.linspace(log_min, log_max, n_heads * dim // 2 + 1)[:-1].exp()
+ self.freqs = nn.Parameter(
+ freqs.view(dim // 2, n_heads).T.contiguous(),
+ requires_grad=False,
+ )
+
+ def forward(self, pos):
+ if pos.shape[-1:] == (1,):
+ pos = pos[..., 0]
+ return pos[..., None, None] * self.freqs.to(pos.dtype)
+
+
+class DiTT2I(nn.Module):
+ def __init__(
+ self,
+ in_dim: int = 4,
+ depth: int = 28,
+ hidden_dim: int = 1152,
+ head_dim: int = 72,
+ mapping_dim: int = 384,
+ mapping_depth: int = 2,
+ patch_size: int = 2,
+ txt_in_dim: int = 2048,
+ txt_refiner_dim: int = 1536,
+ txt_refiner_head_dim: int = 128,
+ txt_refiner_depth: int = 2,
+ compile: bool = False,
+ ):
+ super().__init__()
+ self.in_dim = in_dim
+ self.depth = depth
+ self.head_dim = head_dim
+ self.hidden_dim = hidden_dim
+ self.mapping_dim = mapping_dim
+ self.mapping_depth = mapping_depth
+ self.patch_size = patch_size
+
+ # timestep embedding
+ self.t_embedder = TimestepEmbedder(mapping_dim, mapping_depth, dim_mlp=3 * mapping_dim)
+
+ # model
+ self.merge = TokenMerge2D(in_dim, hidden_dim, patch_size)
+ self.blocks = nn.ModuleList(
+ [
+ TransformerLayer(
+ d_model=hidden_dim,
+ d_head=head_dim,
+ d_cond_norm=mapping_dim,
+ d_cross=txt_refiner_dim, # cross attend to refined txt embs
+ ff_expand=3,
+ rope_cls="jutils.nn.rope.AxialRoPE2D",
+ compile=compile,
+ )
+ for _ in range(depth)
+ ]
+ )
+ # predict uncertainty per patch, so we have an additional out dim
+ self.split = TokenSplitLast2D(hidden_dim, in_dim, patch_size)
+
+ # text embedding refiner
+ self.txt_proj = nn.Linear(txt_in_dim, txt_refiner_dim)
+ self.txt_refiner = nn.ModuleList(
+ [
+ TransformerLayer(
+ d_model=txt_refiner_dim,
+ d_head=txt_refiner_head_dim,
+ ff_expand=3,
+ rope_cls="patch_flow.models.pf_transformer_t2i.AxialRoPETime",
+ compile=compile,
+ )
+ for _ in range(txt_refiner_depth)
+ ]
+ )
+
+ def forward(
+ self,
+ x: Float[torch.Tensor, "b c h w"],
+ t: Float[torch.Tensor, "b n"],
+ txt_emb: Float[torch.Tensor, "b n d"],
+ img_meta: dict = None,
+ ):
+ b, c, h, w = x.shape
+
+ # preprocess text with small refiner stack
+ txt_emb = self.txt_proj(txt_emb)
+ pos_txt = torch.arange(txt_emb.shape[1], device=txt_emb.device)
+ pos_txt = repeat(pos_txt, "n -> b n 1", b=txt_emb.shape[0]) # (b, n, 1)
+ for block in self.txt_refiner:
+ txt_emb = block(txt_emb, pos=pos_txt)
+
+ # timestep conditioning
+ t = t[..., None] # (b,) -> (b, n, 1)
+ t_emb = self.t_embedder(t) # (b, n, c)
+
+ # positional embeddings
+ if img_meta is None:
+ pos = make_axial_pos_2d(h, w, device=x.device)
+ pos = repeat(pos, "(h w) d -> b h w d", b=b, h=h, w=w)
+ else:
+ pos = torch.stack([make_axial_pos_2d_with_meta(m, size=h, device=x.device) for m in img_meta], dim=0)
+
+ x = rearrange(x, "b c h w -> b h w c")
+ x, pos = self.merge(x, pos)
+ nh, nw, _ = x.shape[1:]
+ x = rearrange(x, "b h w c -> b (h w) c")
+ pos = rearrange(pos, "b h w d -> b (h w) d")
+ assert x.shape[1] == pos.shape[1], f"x: {x.shape}, pos: {pos.shape}"
+
+ # model
+ for block in self.blocks:
+ x = block(x, pos=pos, cond_norm=t_emb, x_cross=txt_emb)
+ x = rearrange(x, "b (h w) c -> b h w c", h=nh, w=nw)
+
+ # final layer
+ x = self.split(x)
+
+ # switch back to channel first
+ x = rearrange(x, "b h w c -> b c h w")
+
+ return x
diff --git a/patch-forcing/patch_flow/models/pf_transformer.py b/patch-forcing/patch_flow/models/pf_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..53a62a3c8a53fc5cf7643b1e0a67158cbcac8e4e
--- /dev/null
+++ b/patch-forcing/patch_flow/models/pf_transformer.py
@@ -0,0 +1,164 @@
+import torch
+import torch.nn as nn
+
+from einops import repeat
+from functools import partial
+
+from .dit import DiTBlock, DiT, FinalLayer
+
+
+COMPILE = True
+if torch.cuda.is_available():
+ compile_fn = partial(
+ torch.compile, fullgraph=True, backend="inductor" if torch.cuda.get_device_capability()[0] >= 7 else "aot_eager"
+ )
+else:
+ compile_fn = lambda f: f
+
+
+# ===================================================================================================
+
+
+def pf_modulate(x, shift, scale):
+ return x * (1 + scale) + shift
+
+
+class PatchForcingDiTBlock(DiTBlock):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ if COMPILE:
+ self.forward = compile_fn(self.forward)
+
+ def forward(self, x, c):
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=-1)
+ x = x + gate_msa * self.attn(pf_modulate(self.norm1(x), shift_msa, scale_msa))
+ x = x + gate_mlp * self.mlp(pf_modulate(self.norm2(x), shift_mlp, scale_mlp))
+ return x
+
+
+class PatchForcingFinalLayer(FinalLayer):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ if COMPILE:
+ self.forward = compile_fn(self.forward)
+
+ def forward(self, x, c):
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
+ x = pf_modulate(self.norm_final(x), shift, scale)
+ x = self.linear(x)
+ return x
+
+
+class PatchForcingDiT(DiT):
+ def __init__(
+ self,
+ *args,
+ patch_size=2,
+ hidden_size=1152,
+ depth=28,
+ num_heads=16,
+ mlp_ratio: float = 4.0,
+ predict_uncertainty: bool = True,
+ compile: bool = False,
+ **kwargs,
+ ):
+ super().__init__(
+ *args, patch_size=patch_size, hidden_size=hidden_size, depth=depth, num_heads=num_heads, **kwargs
+ )
+ global COMPILE
+ COMPILE = compile
+
+ # predict uncertainty per patch (replace dit blocks and last layer)
+ self.predict_uncertainty = predict_uncertainty
+ if self.predict_uncertainty:
+ assert self.learn_sigma is False, "cannot use both learn_sigma and predict_uncertainty!"
+ assert self.return_sigma is False, "cannot use both return_sigma and predict_uncertainty!"
+
+ # replace DiT blocks
+ self.blocks = nn.ModuleList(
+ [PatchForcingDiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth)]
+ )
+
+ # replace final layer
+ self.out_channels = self.out_channels + 1
+ self.final_layer = PatchForcingFinalLayer(hidden_size, patch_size, self.out_channels)
+
+ self.initialize_weights()
+
+ def forward(self, x, t, y=None, return_uncertainty: bool = False):
+ """
+ Forward pass of DiT.
+ x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
+ t: (N, num_patches) tensor of diffusion timesteps
+ y: (N,) tensor of class labels
+ """
+ x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2
+
+ # patch-level t's
+ if self.predict_uncertainty:
+ assert x.shape[1] == t.shape[1], f"x: {x.shape}, t: {t.shape}: require patch-level t's!"
+ t = t[..., None] # (N, T) -> (N, T, 1)
+ t = self.t_embedder(t) # (N, 1, T, D)
+ t = t.squeeze(1) # (N, T, D) one embedding per patch
+ else:
+ t = self.t_embedder(t) # (N, D)
+
+ cond = t
+ if self.y_embedder is not None:
+ y = self.y_embedder(y, self.training) # (N, D)
+ if self.predict_uncertainty:
+ y = repeat(y, "b c -> b n c", n=x.shape[1]) # (N, D) -> (N, T, D)
+ cond = cond + y # (N, T, D)
+
+ for block in self.blocks:
+ x = block(x, cond) # (N, T, D)
+ x = self.final_layer(x, cond) # (N, T, patch_size ** 2 * out_channels)
+ x = self.unpatchify(x) # (N, out_channels, H, W)
+
+ # split uncertainty
+ if self.predict_uncertainty:
+ logvar_theta = x[:, -1:, :, :] # (b, 1, h, w)
+ x = x[:, :-1, :, :] # (b, c, h, w)
+ if return_uncertainty:
+ return x, logvar_theta
+
+ if self.learn_sigma and not self.return_sigma: # LEGACY
+ x, _ = x.chunk(2, dim=1)
+ return x
+
+
+# ===================================================================================================
+
+
+def PF_XL_2(**kwargs):
+ return PatchForcingDiT(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
+
+
+def PF_L_2(**kwargs):
+ return PatchForcingDiT(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
+
+
+def PF_B_2(**kwargs):
+ return PatchForcingDiT(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
+
+
+PF_models = {
+ "PF-XL/2": PF_XL_2,
+ "PF-L/2": PF_L_2,
+ "PF-B/2": PF_B_2,
+}
+
+
+if __name__ == "__main__":
+ DEV = "cuda" if torch.cuda.is_available() else "cpu"
+ model = PF_models["PF-XL/2"]().to(DEV)
+ print(f"{sum([p.numel() for p in model.parameters() if p.requires_grad]):,}")
+
+ inp = dict(
+ x=torch.randn((2, 4, 32, 32)).to(DEV),
+ t=torch.rand((2,)).to(DEV),
+ y=torch.randint(0, 1000, (2,)).to(DEV),
+ )
+ with torch.no_grad():
+ out = model(**inp)
+ print(out.shape)
diff --git a/patch-forcing/patch_flow/models/pf_transformer_repa.py b/patch-forcing/patch_flow/models/pf_transformer_repa.py
new file mode 100644
index 0000000000000000000000000000000000000000..54af5f8fd84a3e30fa6602a64810e6dfbccda258
--- /dev/null
+++ b/patch-forcing/patch_flow/models/pf_transformer_repa.py
@@ -0,0 +1,91 @@
+import torch
+import torch.nn as nn
+from jaxtyping import Float
+from functools import partial
+from einops import rearrange, repeat
+
+from .pf_transformer import PatchForcingDiT
+
+
+COMPILE = True
+if torch.cuda.is_available():
+ compile_fn = partial(
+ torch.compile, fullgraph=True, backend="inductor" if torch.cuda.get_device_capability()[0] >= 7 else "aot_eager"
+ )
+else:
+ compile_fn = lambda f: f
+
+
+def build_mlp(in_dim, hidden_dim, out_dim):
+ return nn.Sequential(
+ nn.Linear(in_dim, hidden_dim),
+ nn.SiLU(),
+ nn.Linear(hidden_dim, hidden_dim),
+ nn.SiLU(),
+ nn.Linear(hidden_dim, out_dim),
+ )
+
+
+# ===================================================================================================
+
+
+class REPAPatchForcingDiT(PatchForcingDiT):
+ def __init__(self, *args, hidden_size=1152, z_dim=768, encoder_depth=8, projector_dim=2048, **kwargs):
+ super().__init__(*args, hidden_size=hidden_size, **kwargs)
+ self.encoder_depth = encoder_depth
+ self.projector = build_mlp(hidden_size, projector_dim, z_dim)
+ self.initialize_weights()
+
+ assert self.predict_uncertainty, "REPA PatchForcingDiT requires predict_uncertainty=True"
+
+ def forward(self, x, t, y=None, return_uncertainty: bool = False, return_z=False):
+ """
+ Forward pass of DiT.
+ x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
+ t: (N, num_patches) tensor of diffusion timesteps
+ y: (N,) tensor of class labels
+ """
+ x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2
+
+ # patch-level t's
+ if self.predict_uncertainty:
+ assert x.shape[1] == t.shape[1], f"x: {x.shape}, t: {t.shape}: require patch-level t's!"
+ t = t[..., None] # (N, T) -> (N, T, 1)
+ t = self.t_embedder(t) # (N, 1, T, D)
+ t = t.squeeze(1) # (N, T, D) one embedding per patch
+ else:
+ t = self.t_embedder(t) # (N, D)
+
+ cond = t
+ if self.y_embedder is not None:
+ y = self.y_embedder(y, self.training) # (N, D)
+ if self.predict_uncertainty:
+ y = repeat(y, "b c -> b n c", n=x.shape[1]) # (N, D) -> (N, T, D)
+ cond = cond + y # (N, T, D)
+
+ N, T, D = x.shape
+ for i, block in enumerate(self.blocks):
+ x = block(x, cond) # (N, T, D)
+ if (i + 1) == self.encoder_depth:
+ z = self.projector(x.reshape(-1, D)).reshape(N, T, -1) # (N, T, z_dim)
+
+ x = self.final_layer(x, cond) # (N, T, patch_size ** 2 * out_channels)
+ x = self.unpatchify(x) # (N, out_channels, H, W)
+
+ # split uncertainty
+ if self.predict_uncertainty:
+ logvar_theta = x[:, -1:, :, :] # (b, 1, h, w)
+ x = x[:, :-1, :, :] # (b, c, h, w)
+
+ if return_uncertainty and return_z:
+ return x, logvar_theta, z
+ if return_uncertainty:
+ return x, logvar_theta
+
+ if self.learn_sigma and not self.return_sigma: # LEGACY
+ x, _ = x.chunk(2, dim=1)
+ return x
+
+
+if __name__ == "__main__":
+ pass
diff --git a/patch-forcing/patch_flow/models/pf_transformer_t2i.py b/patch-forcing/patch_flow/models/pf_transformer_t2i.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd0510b89bae78fc737b1101369b8cdd8a7f1947
--- /dev/null
+++ b/patch-forcing/patch_flow/models/pf_transformer_t2i.py
@@ -0,0 +1,185 @@
+import math
+import torch
+import torch.nn as nn
+from jaxtyping import Float
+from einops import rearrange, repeat
+
+from jutils.nn.transformer import TimestepEmbedder
+from jutils.nn.rope import make_axial_pos_2d, AxialRoPEBase
+from jutils.nn.transformer import TransformerLayer, TokenMerge2D, TokenSplitLast2D
+
+
+def make_axial_pos_2d_with_meta(meta, size, device="cpu", latent_ds_factor=8):
+ """
+ Args:
+ meta: dict with keys 'top', 'left', 'orig_h', 'orig_w'
+ size: int, size of the square patch
+ device: device to create the tensor on
+ """
+ top, left = meta["top"], meta["left"]
+ orig_h, orig_w = meta["orig_h"], meta["orig_w"]
+
+ # convert to latent space size
+ top = math.floor(top / latent_ds_factor)
+ left = math.floor(left / latent_ds_factor)
+ orig_h = math.floor(orig_h / latent_ds_factor)
+ orig_w = math.floor(orig_w / latent_ds_factor)
+
+ pos = make_axial_pos_2d(orig_h, orig_w, device=device, align_corners=False, relative_pos=True)
+ pos = rearrange(pos, "(h w) d -> h w d", h=orig_h, w=orig_w)
+ pos = pos[top : top + size, left : left + size, :]
+ return pos
+
+
+class AxialRoPETime(AxialRoPEBase):
+ """
+ Simple 1D RoPE for text/time-like token positions.
+ Uses fixed frequencies (non-learnable), matching standard text RoPE behavior.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ n_heads: int,
+ learnable_freqs: bool = False,
+ relative_canvas: bool = True, # kept for API compatibility
+ in_place: bool = False,
+ half_embedding: bool = True,
+ ):
+ if half_embedding:
+ assert dim % 2 == 0, "Half embedding is only supported for even dimensions"
+ dim //= 2
+ super().__init__(dim, n_heads, in_place=in_place)
+
+ # Best default for text: fixed frequencies, no learned RoPE params.
+ min_freq, max_freq = 1 / 10_000, 1.0
+ log_min = math.log(min_freq)
+ log_max = math.log(max_freq)
+ freqs = torch.linspace(log_min, log_max, n_heads * dim // 2 + 1)[:-1].exp()
+ self.freqs = nn.Parameter(
+ freqs.view(dim // 2, n_heads).T.contiguous(),
+ requires_grad=False,
+ )
+
+ def forward(self, pos):
+ if pos.shape[-1:] == (1,):
+ pos = pos[..., 0]
+ return pos[..., None, None] * self.freqs.to(pos.dtype)
+
+
+class PatchForcingTransformerT2I(nn.Module):
+ def __init__(
+ self,
+ in_dim: int = 4,
+ depth: int = 28,
+ hidden_dim: int = 1152,
+ head_dim: int = 72,
+ mapping_dim: int = 384,
+ mapping_depth: int = 2,
+ patch_size: int = 2,
+ txt_in_dim: int = 2048,
+ txt_refiner_dim: int = 1536,
+ txt_refiner_head_dim: int = 128,
+ txt_refiner_depth: int = 2,
+ compile: bool = False,
+ ):
+ super().__init__()
+ self.in_dim = in_dim
+ self.depth = depth
+ self.head_dim = head_dim
+ self.hidden_dim = hidden_dim
+ self.mapping_dim = mapping_dim
+ self.mapping_depth = mapping_depth
+ self.patch_size = patch_size
+
+ # timestep embedding
+ self.t_embedder = TimestepEmbedder(mapping_dim, mapping_depth, dim_mlp=3 * mapping_dim)
+
+ # model
+ self.merge = TokenMerge2D(in_dim, hidden_dim, patch_size)
+ self.blocks = nn.ModuleList(
+ [
+ TransformerLayer(
+ d_model=hidden_dim,
+ d_head=head_dim,
+ d_cond_norm=mapping_dim,
+ d_cross=txt_refiner_dim, # cross attend to refined txt embs
+ ff_expand=3,
+ rope_cls="jutils.nn.rope.AxialRoPE2D",
+ compile=compile,
+ )
+ for _ in range(depth)
+ ]
+ )
+ # predict uncertainty per patch, so we have an additional out dim
+ self.split = TokenSplitLast2D(hidden_dim, in_dim + 1, patch_size)
+
+ # text embedding refiner
+ self.txt_proj = nn.Linear(txt_in_dim, txt_refiner_dim)
+ self.txt_refiner = nn.ModuleList(
+ [
+ TransformerLayer(
+ d_model=txt_refiner_dim,
+ d_head=txt_refiner_head_dim,
+ ff_expand=3,
+ rope_cls="patch_flow.models.pf_transformer_t2i.AxialRoPETime",
+ compile=compile,
+ )
+ for _ in range(txt_refiner_depth)
+ ]
+ )
+
+ def forward(
+ self,
+ x: Float[torch.Tensor, "b c h w"],
+ t: Float[torch.Tensor, "b n"],
+ txt_emb: Float[torch.Tensor, "b n d"],
+ return_uncertainty: bool = False,
+ img_meta: dict = None,
+ ):
+ n_patches = t.shape[1]
+ b, c, h, w = x.shape
+
+ # preprocess text with small refiner stack
+ txt_emb = self.txt_proj(txt_emb)
+ pos_txt = torch.arange(txt_emb.shape[1], device=txt_emb.device)
+ pos_txt = repeat(pos_txt, "n -> b n 1", b=txt_emb.shape[0]) # (b, n, 1)
+ for block in self.txt_refiner:
+ txt_emb = block(txt_emb, pos=pos_txt)
+
+ # timestep conditioning
+ t = t[..., None] # (b, n) -> (b, n, 1)
+ t_emb = self.t_embedder(t) # (b, n, c)
+
+ # positional embeddings
+ if img_meta is None:
+ pos = make_axial_pos_2d(h, w, device=x.device)
+ pos = repeat(pos, "(h w) d -> b h w d", b=b, h=h, w=w)
+ else:
+ pos = torch.stack([make_axial_pos_2d_with_meta(m, size=h, device=x.device) for m in img_meta], dim=0)
+
+ x = rearrange(x, "b c h w -> b h w c")
+ x, pos = self.merge(x, pos)
+ nh, nw, _ = x.shape[1:]
+ x = rearrange(x, "b h w c -> b (h w) c")
+ pos = rearrange(pos, "b h w d -> b (h w) d")
+ assert x.shape[1] == pos.shape[1] == n_patches, f"x: {x.shape}, pos: {pos.shape}, t: {t.shape}"
+
+ # model
+ for block in self.blocks:
+ x = block(x, pos=pos, cond_norm=t_emb, x_cross=txt_emb)
+ x = rearrange(x, "b (h w) c -> b h w c", h=nh, w=nw)
+
+ # final layer
+ x = self.split(x)
+
+ # switch back to channel first
+ x = rearrange(x, "b h w c -> b c h w")
+
+ # split uncertainty head
+ logvar_theta = x[:, -1:, :, :] # (b, 1, h, w)
+ x = x[:, :-1, :, :] # (b, c, h, w)
+ if return_uncertainty:
+ return x, logvar_theta
+
+ return x
diff --git a/patch-forcing/patch_flow/pt_distributed.py b/patch-forcing/patch_flow/pt_distributed.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb88f9f88e96dcbb440abed00919294e9263cfff
--- /dev/null
+++ b/patch-forcing/patch_flow/pt_distributed.py
@@ -0,0 +1,166 @@
+# MIT License Copyright (c) 2022 joh-schb
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+import os
+import torch
+from torch import distributed as dist
+from torch.nn.parallel import DistributedDataParallel
+from torch.utils.data.distributed import DistributedSampler
+
+
+def is_distributed():
+ """
+ Check if the current process is part of a distributed setup.
+ """
+ return "RANK" in os.environ and "WORLD_SIZE" in os.environ
+
+
+def init_process_group(*args, **kwargs):
+ if not is_distributed():
+ return
+ dist.init_process_group(*args, **kwargs)
+
+
+def is_dist_avail_and_initialized():
+ if not dist.is_available():
+ return False
+ if not dist.is_initialized():
+ return False
+ return True
+
+
+def destroy_process_group():
+ if is_dist_avail_and_initialized():
+ dist.destroy_process_group()
+
+
+def cleanup():
+ destroy_process_group()
+
+
+def get_rank():
+ if not is_dist_avail_and_initialized():
+ return 0
+ return dist.get_rank()
+
+
+def get_device():
+ if torch.cuda.is_available():
+ return torch.device(f"cuda:{get_rank()}")
+ return torch.device("cpu")
+
+
+def is_primary():
+ return get_rank() == 0
+
+
+def get_world_size():
+ if not is_dist_avail_and_initialized():
+ return 1
+ return dist.get_world_size()
+
+
+# data loading stuff
+def data_sampler(dataset, distributed, shuffle):
+ if distributed:
+ return DistributedSampler(dataset, shuffle=shuffle)
+ return None
+
+
+# model wrapping
+def prepare_ddp_model(model, device_ids, *args, **kwargs):
+ if get_world_size() > 1:
+ model = DistributedDataParallel(model, device_ids=device_ids, *args, **kwargs)
+ return model
+
+
+# synchronization functions
+def all_reduce(tensor, op="sum"):
+ world_size = get_world_size()
+
+ if world_size == 1:
+ return tensor
+
+ if op == "sum":
+ dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
+ elif op == "avg":
+ dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
+ tensor /= get_world_size()
+ else:
+ raise ValueError(f'"{op}" is an invalid reduce operation!')
+
+ return tensor
+
+
+def reduce(tensor, op=dist.ReduceOp.SUM):
+ world_size = get_world_size()
+
+ if world_size == 1:
+ return tensor
+
+ dist.reduce(tensor, dst=0, op=op)
+
+ return tensor
+
+
+def gather(data, *args, **kwargs):
+ world_size = get_world_size()
+
+ if world_size == 1:
+ return [data]
+
+ output_list = [torch.zeros_like(data) for _ in range(world_size)]
+
+ if is_primary():
+ dist.gather(data, gather_list=output_list, *args, **kwargs)
+ else:
+ dist.gather(data, *args, **kwargs)
+
+ return output_list
+
+
+def sync_params(params):
+ """
+ Synchronize a sequence of Tensors across ranks from rank 0.
+ """
+ if is_dist_avail_and_initialized():
+ for p in params:
+ with torch.no_grad():
+ dist.broadcast(p, 0)
+
+
+def barrier(*args, **kwargs):
+ world_size = get_world_size()
+ if world_size == 1:
+ return
+ dist.barrier(*args, **kwargs)
+
+
+# wrapper with same functionality but better readability as barrier
+def wait_for_everyone(*args, **kwargs):
+ barrier(*args, **kwargs)
+
+
+def print_primary(*args, **kwargs):
+ if is_primary():
+ print(*args, **kwargs)
+
+
+def print0(*args, **kwargs):
+ print_primary(*args, **kwargs)
diff --git a/patch-forcing/patch_flow/text_encoder.py b/patch-forcing/patch_flow/text_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2dca3441e816eece7792b344d850dab76dbf4f0
--- /dev/null
+++ b/patch-forcing/patch_flow/text_encoder.py
@@ -0,0 +1,186 @@
+import os
+import torch
+import math
+from abc import ABC
+import torch.nn as nn
+from typing import List
+from transformers import AutoTokenizer
+from transformers import SiglipTextModel
+from transformers import T5EncoderModel, T5Tokenizer
+from transformers import CLIPTextModel, AutoModel, AutoModelForCausalLM
+from transformers import Qwen3VLForConditionalGeneration
+
+
+class TextEmbedder(ABC, nn.Module):
+ """
+ Abstract base class for text embedders.
+ Subclasses must set: self.model (nn.Module), self.tokenizer, self.emb_dim (int).
+ This class provides a shared forward() that returns hidden states with shape (b, n, d).
+ """
+
+ emb_dim: int # required
+ max_length: int # required
+ tokenizer: object # tokenizer
+ model: nn.Module # HF model (encoder or LM; must support output_hidden_states=True)
+
+ @property
+ def device(self) -> torch.device:
+ return next(self.model.parameters()).device
+
+ @torch.no_grad()
+ def forward(self, txt: List[str]):
+ tok_out = self.tokenizer(
+ txt, return_tensors="pt", padding="max_length", max_length=self.max_length, truncation=True
+ )
+ tok_out = tok_out.to(self.device)
+ txt_emb = self.model(**tok_out, output_hidden_states=True)
+ if hasattr(txt_emb, "last_hidden_state"):
+ return txt_emb.last_hidden_state
+ return txt_emb.hidden_states[-1]
+
+
+# ===================================================================================================
+
+
+class ClipTextEmbedder(TextEmbedder):
+ def __init__(self, max_length: int = 77, compile: bool = False, dtype: torch.dtype = torch.bfloat16):
+ super().__init__()
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ self.emb_dim = 768
+ self.max_length = max_length
+ self.path = "openai/clip-vit-large-patch14"
+
+ self.tokenizer = AutoTokenizer.from_pretrained(self.path)
+ self.model = CLIPTextModel.from_pretrained(self.path, torch_dtype=dtype)
+ self.model.requires_grad_(False)
+ self.model.eval()
+ if compile:
+ torch.compile(self.model)
+
+ print(f"[ClipTextEmbedder] {sum([p.numel() for p in self.parameters()]):,}")
+
+
+class SigLipTextEmbedder(TextEmbedder):
+ def __init__(self, max_length: int = 64, compile: bool = False, dtype: torch.dtype = torch.bfloat16):
+ super().__init__()
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ self.emb_dim = 1152
+ self.max_length = max_length
+ self.path = "google/siglip-so400m-patch14-384"
+
+ self.tokenizer = AutoTokenizer.from_pretrained(self.path)
+ self.model = SiglipTextModel.from_pretrained(self.path, torch_dtype=dtype, attn_implementation="sdpa")
+ self.model.requires_grad_(False)
+ self.model.eval()
+ if compile:
+ torch.compile(self.model)
+
+ print(f"[SigLipTextEmbedder] {sum([p.numel() for p in self.parameters()]):,}")
+
+
+class T5XXL(TextEmbedder):
+ def __init__(self, max_length: int = 512, compile: bool = False, dtype: torch.dtype = torch.bfloat16):
+ super().__init__()
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ self.emb_dim = 4096
+ self.max_length = max_length
+ self.path = "google/t5-xxl-lm-adapt"
+
+ self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(self.path, max_length=max_length)
+ self.model = T5EncoderModel.from_pretrained(self.path, torch_dtype=dtype)
+ self.model.requires_grad_(False)
+ self.model.eval()
+ if compile:
+ torch.compile(self.model)
+
+ print(f"[T5XXL] {sum([p.numel() for p in self.parameters()]):,}")
+
+
+class InternVL3(TextEmbedder):
+ def __init__(self, max_length: int = 160, compile: bool = False, dtype: torch.dtype = torch.bfloat16):
+ super().__init__()
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ self.emb_dim = 896
+ self.max_length = max_length
+ self.path = "OpenGVLab/InternVL3-1B"
+
+ self.tokenizer = AutoTokenizer.from_pretrained(self.path, trust_remote_code=True, use_fast=True)
+ model = AutoModel.from_pretrained(self.path, trust_remote_code=True, torch_dtype=dtype)
+ text_tower = getattr(model, "language_model", None) or getattr(model, "text_model", None)
+ assert text_tower is not None, "Could not find text tower (language_model/text_model)."
+ self.model = text_tower
+ self.model.requires_grad_(False)
+ self.model.eval()
+ if compile:
+ torch.compile(self.model)
+
+ print(f"[InternVL3] {sum([p.numel() for p in self.parameters()]):,}")
+
+
+class Gemma2B(TextEmbedder):
+ def __init__(self, max_length: int = 160, compile: bool = False, dtype: torch.dtype = torch.bfloat16):
+ super().__init__()
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ self.emb_dim = 2048
+ self.max_length = max_length
+ self.path = "google/gemma-2b"
+
+ self.tokenizer = AutoTokenizer.from_pretrained(self.path)
+ self.model = AutoModelForCausalLM.from_pretrained(self.path, torch_dtype=dtype)
+ self.model.requires_grad_(False)
+ self.model.eval()
+ if compile:
+ torch.compile(self.model)
+
+ print(f"[Gemma2B] {sum([p.numel() for p in self.parameters()]):,}")
+
+
+class Qwen3VLEmbedder2B(TextEmbedder):
+ def __init__(
+ self,
+ repo: str = "Qwen/Qwen3-VL-Embedding-2B",
+ max_length: int = 256,
+ compile: bool = False,
+ dtype: torch.dtype = torch.bfloat16,
+ ):
+ super().__init__()
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ self.path = repo
+ self.max_length = max_length
+
+ self.tokenizer = AutoTokenizer.from_pretrained(self.path)
+ full_model = Qwen3VLForConditionalGeneration.from_pretrained(self.path, dtype=dtype)
+ text_tower = full_model.model.language_model
+ del full_model
+
+ self.model = text_tower
+ self.emb_dim = int(self.model.config.hidden_size)
+ self.model.requires_grad_(False)
+ self.model.eval()
+ if compile:
+ self.model = torch.compile(self.model)
+
+ print(f"[Qwen3VLEmbedder2B] {sum([p.numel() for p in self.parameters()]):,}")
+
+
+# ===================================================================================================
+
+
+if __name__ == "__main__":
+ DEV = "cuda:0" if torch.cuda.is_available() else "cpu"
+ batch_text = ["a red cube on a wooden table, studio lighting, 35mm", "image of a dog"]
+
+ def check(model_cls):
+ model = model_cls().to(DEV).eval()
+ with torch.no_grad():
+ out = model(batch_text)
+ print(f"[{model.__class__.__name__}] output shape: {tuple(out.shape)}")
+ assert out.shape[-1] == model.emb_dim, f"Mismatch emb_dim: {model.emb_dim} != {out.shape[-1]}"
+ assert out.shape[1] == model.max_length, f"Mismatch max_length: {model.max_length} != {out.shape[1]}"
+
+ check(ClipTextEmbedder)
+ check(SigLipTextEmbedder)
+ check(T5XXL)
+ check(Gemma2B)
+ check(InternVL3)
+ check(Qwen3VLEmbedder2B)
diff --git a/patch-forcing/patch_flow/timestep_schedules.py b/patch-forcing/patch_flow/timestep_schedules.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ec2f146691f77d9d80ad8afde8cff33478973da
--- /dev/null
+++ b/patch-forcing/patch_flow/timestep_schedules.py
@@ -0,0 +1,156 @@
+import torch
+from torch import Tensor
+from jaxtyping import Float
+from torch.distributions.beta import Beta
+
+
+class ParallelTimeSampler:
+ def __call__(self, shape, device="cpu", dtype=torch.float32):
+ bs = shape[0]
+ t = torch.rand(bs, device=device, dtype=dtype).view(bs, 1).repeat(1, shape[1])
+ return t
+
+
+class ParallelLogitNormalTimeSampler:
+ def __init__(self, loc: float = 0.0, scale: float = 1.0):
+ """
+ Logit-Normal sampler from the paper 'Scaling Rectified Flow Transformers
+ for High-Resolution Image Synthesis' - Esser et al. (ICML 2024)
+ """
+ self.loc = loc
+ self.scale = scale
+
+ def __call__(self, shape, device="cpu", dtype=torch.float32):
+ bs = shape[0]
+ t = torch.sigmoid(self.loc + self.scale * torch.randn(bs, 1)).to(device).to(dtype)
+ t = t.repeat(1, shape[1])
+ return t
+
+
+class SRMSchedule:
+ def __init__(self, beta_sharpness: float = 1.0):
+ self.beta_sharpness = beta_sharpness
+ self.betas: dict[int, Beta] = {}
+
+ def init_betas(self, dim: int) -> None:
+ if dim > 1 and dim not in self.betas:
+ a = b = (dim - 1 - (dim % 2)) ** 1.05 * self.beta_sharpness
+ self.betas[dim] = Beta(a, b)
+ half_dim = dim // 2
+ self.init_betas(half_dim)
+ self.init_betas(dim - half_dim)
+
+ def _get_uniform_l1_conditioned_vector_list(
+ self,
+ l1_norms: Float[Tensor, "batch"],
+ dim: int,
+ ) -> list[Float[Tensor, "batch"]]:
+ if dim == 1:
+ return [l1_norms]
+
+ device = l1_norms.device
+ half_cells = dim // 2
+
+ max_first_contribution = l1_norms.clamp(max=half_cells) # num cells in the first half
+ max_second_contribution = l1_norms.clamp(max=dim - half_cells)
+ min_first_contribution = (l1_norms - max_second_contribution).clamp_(min=0)
+
+ random_matrix = self.betas[dim].sample((l1_norms.shape[0],)).to(device=device)
+ ranges = max_first_contribution - min_first_contribution
+
+ assert ranges.min() >= 0
+ first_contribution = min_first_contribution + ranges * random_matrix
+ second_contribution = l1_norms - first_contribution
+
+ return self._get_uniform_l1_conditioned_vector_list(
+ first_contribution, half_cells
+ ) + self._get_uniform_l1_conditioned_vector_list(second_contribution, dim - half_cells)
+
+ def _sample_time_matrix(self, l1_norms: Float[Tensor, "batch"], dim: int) -> Float[Tensor, "batch dim"]:
+ vector_list = self._get_uniform_l1_conditioned_vector_list(l1_norms, dim)
+ t = torch.stack(vector_list, dim=1) # [batch_size, dim]
+ # shuffle the time matrix (independently for batch elements) to avoid positional biases
+ idx = torch.rand_like(t).argsort()
+ t = t.gather(1, idx)
+ return t
+
+ def get_time_with_mean(self, mean: Float[Tensor, "b"], dim: int) -> Float[Tensor, "b d"]:
+ bs = mean.shape[0]
+ self.init_betas(dim)
+ l1_norms = mean.flatten() * dim
+ t = self._sample_time_matrix(l1_norms, dim)
+ return t.view(bs, -1)
+
+ def get_time(self, shape, device="cpu", dtype=torch.float32):
+ bs, seq_len = shape
+ mean = torch.rand((bs,), device=device, dtype=dtype)
+ return self.get_time_with_mean(mean, dim=seq_len)
+
+ def __call__(self, shape, device="cpu", dtype=torch.float32):
+ return self.get_time(shape, device=device, dtype=dtype)
+
+
+class GaussianSchedule:
+ def __init__(self, std: float = 0.2):
+ self.std = std
+
+ def __call__(self, shape, device="cpu", dtype=torch.float32):
+ bs, dim = shape
+ t_bar = torch.rand(bs, device=device, dtype=dtype)
+ t_i = self.get_time_with_mean(t_bar, dim=dim)
+ return t_i
+
+ def get_time_with_mean(self, mean, dim: int):
+ bs = mean.shape[0]
+ std = torch.min(mean, 1 - mean)
+ std = torch.min(std / 2, torch.full_like(std, self.std))
+ t_i = mean[:, None] + torch.randn(bs, dim, device=mean.device, dtype=mean.dtype) * std[:, None]
+ t_i = t_i.clamp(0, 1)
+ return t_i
+
+
+class TruncatedGaussian:
+ def __init__(self, std: float = 0.2):
+ self.std = std
+
+ def __call__(self, shape, device="cpu", dtype=torch.float32):
+ bs, dim = shape
+ t_bar = torch.rand(bs, device=device, dtype=dtype)
+ t_i = self.get_time_with_mean(t_bar, dim=dim)
+ return t_i
+
+ def get_time_with_mean(self, mean, dim: int):
+ bs = mean.shape[0]
+ std = torch.min(mean / 2, torch.full_like(mean, self.std)) * -1
+ t_i = mean[:, None] + torch.randn(bs, dim, device=mean.device, dtype=mean.dtype).abs() * std[:, None]
+
+ # t_i = t_i.clamp(0, 1) <-- Nah we don't do clamping, we reset negative values to uniform samples
+ rand = torch.rand_like(t_i)
+ t_i = torch.where(t_i < 0, rand * mean[:, None], t_i)
+ return t_i
+
+
+class LogitNormalTruncatedGaussian:
+ def __init__(self, std: float = 0.6, loc: float = 0.7, scale: float = 1.0):
+ self.std = std
+ self.loc = loc
+ self.scale = scale
+
+ def get_t_bar(self, bs, device="cpu", dtype=torch.float32):
+ return torch.sigmoid(self.loc + self.scale * torch.randn(bs, device=device, dtype=dtype))
+
+ def get_time_with_mean(self, mean, dim: int):
+ bs = mean.shape[0]
+ std = torch.min(mean / 2, torch.full_like(mean, self.std)) * -1
+ t_i = mean[:, None] + torch.randn(bs, dim, device=mean.device, dtype=mean.dtype).abs() * std[:, None]
+
+ # t_i = t_i.clamp(0, 1) <-- Nah we don't do clamping, we reset negative values to uniform samples
+ rand = torch.rand_like(t_i)
+ t_i = torch.where(t_i < 0, rand * mean[:, None], t_i)
+ return t_i
+
+ def __call__(self, shape, device="cpu", dtype=torch.float32):
+ bs, dim = shape
+ t_bar = self.get_t_bar(bs, device=device, dtype=dtype)
+ t_i = self.get_time_with_mean(t_bar, dim=dim)
+ return t_i
diff --git a/patch-forcing/patch_flow/trainer.py b/patch-forcing/patch_flow/trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e06d47207b91d6045e39049441ff2553b4ce6f5
--- /dev/null
+++ b/patch-forcing/patch_flow/trainer.py
@@ -0,0 +1,260 @@
+import torch
+import torch.nn as nn
+from typing import Union
+from copy import deepcopy
+from omegaconf import DictConfig
+from collections import OrderedDict
+from lightning import LightningModule
+import warnings
+
+from jutils import instantiate_from_config
+from jutils import load_partial_from_config
+from jutils import exists, freeze, default
+
+from patch_flow.log_utils import log_images
+from patch_flow.metrics import ImageMetricTracker
+from patch_flow.diagonal_gaussian import DiagonalGaussian
+from torchmetrics.aggregation import CatMetric
+
+
+def un_normalize_ims(ims):
+ """Convert from [-1, 1] to [0, 255]"""
+ ims = ((ims * 127.5) + 127.5).clip(0, 255).to(torch.uint8)
+ return ims
+
+
+@torch.no_grad()
+def update_ema(ema_model, model, decay=0.9999):
+ """
+ Step the EMA model towards the current model.
+ """
+ ema_params = OrderedDict(ema_model.named_parameters())
+ model_params = OrderedDict(model.named_parameters())
+
+ for name, param in model_params.items():
+ if not param.requires_grad:
+ continue
+ # unwrap DDP
+ if name.startswith("module."):
+ name = name.replace("module.", "")
+ ema_params[name].mul_(decay).add_(param.data, alpha=1 - decay)
+
+
+def instantiate_if_needed(config_or_obj):
+ if isinstance(config_or_obj, nn.Module):
+ return config_or_obj
+ elif isinstance(config_or_obj, dict) or isinstance(config_or_obj, DictConfig):
+ return instantiate_from_config(config_or_obj)
+ else:
+ raise ValueError(f"Expected nn.Module or config dict, got {type(config_or_obj)}")
+
+
+# ===================================================================================================
+
+
+class LatentFlowTrainer(LightningModule):
+ def __init__(
+ self,
+ model: Union[dict, DictConfig, nn.Module],
+ first_stage: Union[dict, DictConfig, nn.Module],
+ flow: Union[dict, DictConfig, object],
+ # learning
+ lr: float = 1e-4,
+ weight_decay: float = 0.0,
+ ema_rate: float = 0.9999,
+ lr_scheduler_cfg: dict = None,
+ # logging
+ sample_kwargs: dict = None,
+ ):
+ super().__init__()
+
+ # flow logic
+ self.flow = instantiate_if_needed(flow)
+
+ # unet/transformer model
+ self.model = instantiate_if_needed(model)
+
+ # EMA of unet/transformer model
+ self.ema_model = None
+ self.ema_rate = ema_rate
+ if ema_rate > 0:
+ if isinstance(model, nn.Module):
+ warnings.warn("EMA model with deepcopy, might run into issues with compile.")
+ self.ema_model = deepcopy(self.model)
+ else:
+ self.ema_model = instantiate_if_needed(model)
+ self.ema_model.load_state_dict(self.model.state_dict())
+ freeze(self.ema_model)
+ self.ema_model.eval()
+ update_ema(self.ema_model, self.model, decay=0) # ensure EMA is in sync
+
+ # first stage autoencoder
+ self.first_stage = instantiate_if_needed(first_stage)
+ self.first_stage.eval().to(self.device)
+ freeze(self.first_stage)
+
+ # training parameters
+ self.lr = lr
+ self.weight_decay = weight_decay
+ self.lr_scheduler_cfg = lr_scheduler_cfg
+
+ # visualization
+ self.sample_kwargs = sample_kwargs or {}
+ self.generator = torch.Generator()
+
+ # evaluation
+ self.metric_tracker = ImageMetricTracker().to(self.device)
+
+ # SD3 & Meta Movie Gen show that val loss correlates with human quality
+ # and compute the loss in equidistant segments in (0, 1) to reduce variance
+ self.val_losses = CatMetric().to(self.device) # sync across GPUs
+ self.val_images = None
+ self.val_epochs = 0
+
+ self.save_hyperparameters()
+
+ # signal handler for slurm, flag to make sure the signal
+ # is not handled at an incorrect state, e.g. during weights update
+
+ def configure_optimizers(self):
+ opt = torch.optim.AdamW(
+ [p for p in self.parameters() if p.requires_grad], lr=self.lr, weight_decay=self.weight_decay
+ )
+ out = dict(optimizer=opt)
+ if exists(self.lr_scheduler_cfg):
+ sch = load_partial_from_config(self.lr_scheduler_cfg)
+ sch = sch(optimizer=opt)
+ out["lr_scheduler"] = sch
+ return out
+
+ def on_train_batch_end(self, outputs, batch, batch_idx):
+ # first checking for trainer ensures that the module can be also used with accelerate
+ if exists(self._trainer) and exists(self.lr_scheduler_cfg):
+ self.lr_schedulers().step()
+ if exists(self.ema_model):
+ update_ema(self.ema_model, self.model, decay=self.ema_rate)
+
+ # ===================================================================================================
+ # training logic
+
+ @torch.no_grad()
+ def encode(self, x):
+ return self.first_stage.encode(x) if exists(self.first_stage) else x
+
+ @torch.no_grad()
+ def decode(self, z):
+ return self.first_stage.decode(z) if exists(self.first_stage) else z
+
+ def forward(self, batch):
+ ims = batch["image"]
+ latent = batch.get("latent", None)
+ if not exists(latent):
+ latent = self.encode(ims)
+ label = batch.get("label", None)
+
+ # compute loss
+ loss = self.flow.training_losses(model=self.model, x1=latent, y=label)
+
+ return loss
+
+ # ===================================================================================================
+ # validation
+
+ def validation_step(self, batch, batch_idx):
+ ims = batch["image"]
+ label = batch.get("label", None)
+ latent = batch.get("latent", None)
+ if latent is None:
+ latent = self.encode(ims)
+ bs = ims.shape[0]
+
+ g = self.generator.manual_seed(batch_idx + self.global_rank * 16102024)
+ noise = torch.randn(latent.shape, generator=g, dtype=ims.dtype).to(ims.device)
+ sample_model = self.ema_model if exists(self.ema_model) else self.model
+
+ # flow models val loss shows correlation with human quality
+ if hasattr(self.flow, "validation_losses"):
+ latent = default(latent, self.encode(ims))
+ _, val_loss_per_segment = self.flow.validation_losses(model=sample_model, x1=latent, x0=noise, y=label)
+ self.val_losses.update(val_loss_per_segment.unsqueeze(0))
+
+ # sample images
+ samples = self.flow.generate(model=sample_model, x=noise, y=label, **self.sample_kwargs)
+ samples = self.decode(samples)
+
+ # metrics
+ self.metric_tracker(ims, samples)
+
+ # save the images for visualization
+ if self.val_images is None:
+ real_ims = un_normalize_ims(ims)
+ fake_ims = un_normalize_ims(samples)
+ self.val_images = {
+ "real": real_ims[:20],
+ "fake": fake_ims[:20],
+ }
+
+ def on_validation_epoch_end(self):
+ # visualization
+ for key, ims in self.val_images.items():
+ log_images(self.logger, ims, f"val/{key}/samples", stack="row", split=4, step=self.global_step)
+
+ # reset val images
+ self.val_images = None
+
+ # compute metrics
+ metrics = self.metric_tracker.aggregate()
+ for k, v in metrics.items():
+ self.log(f"val/{k}", v, sync_dist=True)
+ self.metric_tracker.reset()
+
+ # compute val loss if available (Flow models)
+ if len(self.val_losses.value) > 0:
+ val_losses = self.val_losses.compute() # (N batches, segments)
+ val_losses = val_losses.mean(0) # mean per segment
+ for i, loss in enumerate(val_losses):
+ self.log(f"val/loss_segment_{i}", loss, sync_dist=True)
+ self.log("val/loss", val_losses.mean(), sync_dist=True)
+ self.val_losses.reset()
+
+ # log some information
+ self.val_epochs += 1
+ self.print(f"Val epoch {self.val_epochs:,} | Optimizer step {self.global_step:,}")
+ metric_str = " | ".join([f"{k}: {v:.4f}" for k, v in metrics.items()])
+ self.print(metric_str)
+
+
+# ===================================================================================================
+
+
+class LatentPatchForcingTrainer(LatentFlowTrainer):
+ def __init__(self, *args, uncertainty_weight: float = 0.01, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.uncertainty_weight = uncertainty_weight
+ assert (
+ hasattr(self.model, "predict_uncertainty") and self.model.predict_uncertainty
+ ), "Model should be PatchForcingDiT with predict_uncertainty=True."
+
+ def forward(self, batch):
+ ims = batch["image"]
+ latent = batch.get("latent", None)
+ if not exists(latent):
+ latent = self.encode(ims)
+ label = batch.get("label", None)
+
+ # compute loss
+ xt, ut, t = self.flow.get_interpolants(x1=latent)
+ vt, logvar_theta = self.model(x=xt, t=t, y=label, return_uncertainty=True)
+
+ # fm loss
+ fm_loss = (vt - ut).square().mean()
+
+ # uncertainty loss following SRM
+ sigma_theta = torch.exp(0.5 * logvar_theta)
+ pred_theta = DiagonalGaussian(mean=vt.detach(), std=sigma_theta)
+ sigma_loss = pred_theta.nll(ut).mean()
+
+ loss = fm_loss + self.uncertainty_weight * sigma_loss
+ loss_dict = {"flow_loss": fm_loss, "sigma_loss": sigma_loss}
+
+ return loss, loss_dict
diff --git a/patch-forcing/patch_flow/trainer_t2i.py b/patch-forcing/patch_flow/trainer_t2i.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c0212efa0b0336d46677cbb464beef8e865609e
--- /dev/null
+++ b/patch-forcing/patch_flow/trainer_t2i.py
@@ -0,0 +1,262 @@
+import torch
+import einops
+import warnings
+import numpy as np
+import torch.nn as nn
+from typing import Union
+from copy import deepcopy
+from omegaconf import DictConfig
+from torchmetrics import CatMetric
+from lightning import LightningModule
+
+from jutils import exists, freeze
+from jutils import load_partial_from_config
+from jutils import tensor2im, text_to_canvas, soft_wrap
+
+from patch_flow.log_utils import log_image
+from patch_flow.metrics import Text2ImageMetricTracker
+from patch_flow.diagonal_gaussian import DiagonalGaussian
+from patch_flow.trainer import update_ema, instantiate_if_needed
+
+
+class PatchForcingT2ITrainer(LightningModule):
+ def __init__(
+ self,
+ model: Union[dict, DictConfig, nn.Module],
+ first_stage: Union[dict, DictConfig, nn.Module],
+ flow: Union[dict, DictConfig, object],
+ # text conditioning
+ text_encoder: Union[dict, DictConfig, nn.Module],
+ text_dropout_prob: float = 0.1,
+ text_key: str = "txt",
+ # learning
+ lr: float = 1e-4,
+ weight_decay: float = 0.0,
+ ema_rate: float = 0.9999,
+ lr_scheduler_cfg: dict = None,
+ rope_jittering: bool = True,
+ uncertainty_weight: float = 0.01,
+ # logging
+ sample_kwargs: dict = None,
+ ):
+ super().__init__()
+
+ # flow logic
+ self.flow = instantiate_if_needed(flow)
+
+ # unet/transformer model
+ self.model = instantiate_if_needed(model)
+
+ # EMA of unet/transformer model
+ self.ema_model = None
+ self.ema_rate = ema_rate
+ if ema_rate > 0:
+ if isinstance(model, nn.Module):
+ warnings.warn("EMA model with deepcopy, might run into issues with compile.")
+ self.ema_model = deepcopy(self.model)
+ else:
+ self.ema_model = instantiate_if_needed(model)
+ self.ema_model.load_state_dict(self.model.state_dict())
+ freeze(self.ema_model)
+ self.ema_model.eval()
+ update_ema(self.ema_model, self.model, decay=0) # ensure EMA is in sync
+
+ # first stage autoencoder
+ self.first_stage = instantiate_if_needed(first_stage)
+ self.first_stage.eval().to(self.device)
+ freeze(self.first_stage)
+
+ # text tower
+ self.text_key = text_key
+ self.text_dropout_prob = text_dropout_prob
+ self.text_encoder = instantiate_if_needed(text_encoder)
+ self.text_encoder.eval().to(self.device)
+ freeze(self.text_encoder)
+
+ # training parameters
+ self.lr = lr
+ self.weight_decay = weight_decay
+ self.lr_scheduler_cfg = lr_scheduler_cfg
+ self.uncertainty_weight = uncertainty_weight
+ self.rope_jittering = rope_jittering
+ self.sample_kwargs = sample_kwargs or {}
+ self.generator = torch.Generator()
+
+ # evaluation
+ self.metric_tracker = Text2ImageMetricTracker().eval().to(self.device)
+
+ # SD3 & Meta Movie Gen show that val loss correlates with human quality
+ # and compute the loss in equidistant segments in (0, 1) to reduce variance
+ self.val_losses = CatMetric().to(self.device) # sync across GPUs
+ self.val_images = None
+ self.val_epochs = 0
+
+ def configure_optimizers(self):
+ opt = torch.optim.AdamW(
+ [p for p in self.parameters() if p.requires_grad], lr=self.lr, weight_decay=self.weight_decay
+ )
+ out = dict(optimizer=opt)
+ if exists(self.lr_scheduler_cfg):
+ sch = load_partial_from_config(self.lr_scheduler_cfg)
+ sch = sch(optimizer=opt)
+ out["lr_scheduler"] = sch
+ return out
+
+ def on_train_batch_end(self, outputs, batch, batch_idx):
+ # first checking for trainer ensures that the module can be also used with accelerate
+ if exists(self._trainer) and exists(self.lr_scheduler_cfg):
+ self.lr_schedulers().step()
+ if exists(self.ema_model):
+ update_ema(self.ema_model, self.model, decay=self.ema_rate)
+
+ # ===================================================================================================
+ # training logic
+
+ @torch.no_grad()
+ def encode(self, x):
+ return self.first_stage.encode(x) if exists(self.first_stage) else x
+
+ @torch.no_grad()
+ def decode(self, z):
+ return self.first_stage.decode(z) if exists(self.first_stage) else z
+
+ def encode_text(self, text):
+ text = [t.decode() if isinstance(t, bytes) else t for t in text]
+ if self.training and self.text_dropout_prob > 0:
+ drop_ids = np.random.rand(len(text)) < self.text_dropout_prob
+ text = ["" if drop else text for drop, text in zip(drop_ids, text)]
+ txt_tokens = self.text_encoder(text) # no grad
+ return txt_tokens
+
+ def forward(self, batch):
+ ims = batch["image"]
+ latent = batch.get("latent", None)
+ if latent is None:
+ latent = self.encode(ims)
+
+ # text encoding
+ txt = batch[self.text_key]
+ txt_emb = self.encode_text(txt)
+
+ # potential rope jit
+ kwargs = dict(txt_emb=txt_emb)
+ if self.rope_jittering:
+ img_meta = batch.get("img_meta", None)
+ assert img_meta is not None, "img_meta must be provided in the batch for rope_jittering."
+ kwargs["img_meta"] = img_meta
+
+ # compute flow matching loss
+ xt, ut, t = self.flow.get_interpolants(x1=latent)
+ vt, logvar_theta = self.model(x=xt, t=t, **kwargs, return_uncertainty=True)
+
+ # flow loss
+ flow_loss = (vt - ut).square().mean()
+
+ # uncertainty loss following SRM
+ sigma_theta = torch.exp(0.5 * logvar_theta)
+ pred_theta = DiagonalGaussian(mean=vt.detach(), std=sigma_theta)
+ sigma_loss = pred_theta.nll(ut).mean()
+
+ loss = flow_loss + self.uncertainty_weight * sigma_loss
+ loss_dict = {"flow_loss": flow_loss, "sigma_loss": sigma_loss}
+
+ return loss, loss_dict
+
+ # ===================================================================================================
+ # validation
+
+ def validation_step(self, batch, batch_idx):
+ ims = batch["image"]
+ latent = batch.get("latent", None)
+ if latent is None:
+ latent = self.encode(ims)
+ bs = ims.shape[0]
+
+ txt = batch[self.text_key]
+ txt_emb = self.encode_text(txt)
+
+ g = self.generator.manual_seed(batch_idx + self.global_rank * 16102024)
+ noise = torch.randn(latent.shape, generator=g, dtype=ims.dtype).to(ims.device)
+ sample_model = self.ema_model if exists(self.ema_model) else self.model
+
+ # flow models val loss shows correlation with human quality
+ _, val_loss_per_segment = self.flow.validation_losses(model=sample_model, x1=latent, x0=noise, txt_emb=txt_emb)
+ self.val_losses.update(val_loss_per_segment.unsqueeze(0))
+
+ # sample images
+ samples = self.flow.generate(model=sample_model, x=noise, txt_emb=txt_emb, **self.sample_kwargs)
+ samples = self.decode(samples)
+
+ # metrics
+ self.metric_tracker(ims, samples, txt)
+
+ # visualization images
+ if self.val_images is None:
+ c, h, w = ims.shape[1:]
+ out_ims = [ims]
+ if exists(self.ema_model):
+ non_ema_samples = self.flow.generate(model=self.model, x=noise, txt_emb=txt_emb, **self.sample_kwargs)
+ non_ema_samples = self.decode(non_ema_samples)
+ out_ims.append(non_ema_samples)
+ out_ims.append(samples)
+
+ # CFG images
+ cfg_scales = [3, 5, 7]
+ uc_txt_emb = self.encode_text([""] * bs)
+ for cfg_scale in cfg_scales:
+ kwargs = dict(**self.sample_kwargs, cfg_scale=cfg_scale, uc_cond=uc_txt_emb, cond_key="txt_emb")
+ samples = self.flow.generate(model=sample_model, x=noise, txt_emb=txt_emb, **kwargs)
+ samples = self.decode(samples)
+ out_ims.append(samples)
+
+ # out images: [real, non-ema, ema, cfg3, ...] stacked over height
+ out_ims = torch.cat(out_ims, dim=2) # (b, c, n*h, w)
+ out_ims = tensor2im(out_ims.float()) # (b, n*h, w, c)
+
+ # generation image with captions
+ caption_ims = np.stack(
+ [
+ text_to_canvas(
+ soft_wrap(t.decode() if isinstance(t, bytes) else t, 50),
+ h,
+ w,
+ font_size=9.5,
+ background=(255, 255, 255),
+ fontcolor=(0, 0, 0),
+ )
+ for t in txt
+ ],
+ axis=0,
+ )
+ out_ims = np.concatenate([out_ims, caption_ims], axis=1) # (b, n*h+1, w, c)
+
+ # one final image for vis, limit to 20
+ out_ims = einops.rearrange(out_ims[:20], "b h w c -> h (b w) c")
+ self.val_images = {"gt_non-ema_ema_cfg3-5-7": out_ims}
+
+ def on_validation_epoch_end(self):
+ # visualization
+ for key, ims in self.val_images.items():
+ log_image(self.logger, ims, f"val/{key}", channel_last=True, step=self.global_step)
+ self.val_images = None
+
+ # compute metrics
+ metrics = self.metric_tracker.aggregate()
+ for k, v in metrics.items():
+ self.log(f"val/{k}", v, sync_dist=True)
+ self.metric_tracker.reset()
+
+ # compute val loss if available (Flow models)
+ if len(self.val_losses.value) > 0:
+ val_losses = self.val_losses.compute() # (N batches, segments)
+ val_losses = val_losses.mean(0) # mean per segment
+ # for i, loss in enumerate(val_losses):
+ # self.log(f"val/loss_segment_{i}", loss, sync_dist=True)
+ self.log("val/loss", val_losses.mean(), sync_dist=True)
+ self.val_losses.reset()
+
+ # log some information
+ self.val_epochs += 1
+ self.print(f"Val epoch {self.val_epochs:,} | Optimizer step {self.global_step:,}")
+ metric_str = " | ".join([f"{k}: {v:.4f}" for k, v in metrics.items()])
+ self.print(metric_str)
diff --git a/patch-forcing/requirements.txt b/patch-forcing/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..cd4e712eed0790f291c0c48678f7f76e5a66face
--- /dev/null
+++ b/patch-forcing/requirements.txt
@@ -0,0 +1,42 @@
+# conda create -n jenv python=3.12
+# conda activate jenv
+
+# sometimes it is safer to
+# (1) install torch and torchvision manually via
+# pip install torch==2.8.0+cu128 torchvision==0.23.0+cu128 --index-url https://download.pytorch.org/whl/cu128
+# (2) and then install flash-attn via
+# pip install flash-attn==2.8.3 --no-build-isolation
+# (3) and then the rest via
+# pip install -r requirements.txt
+
+--extra-index-url https://download.pytorch.org/whl/cu128
+torch==2.8.0+cu128
+--extra-index-url https://download.pytorch.org/whl/cu128
+torchvision==0.23.0+cu128
+
+
+lightning==2.5.6
+accelerate==1.10.1
+timm==1.0.17
+hydra-core
+torch-fidelity
+torchdiffeq
+notebook
+pillow
+matplotlib
+einops
+h5py
+pandas
+webdataset
+tensorboard
+wandb
+pudb
+jaxtyping
+opencv-python
+diffusers[torch]
+transformers
+
+# own util functions
+git+https://github.com/joh-schb/jutils.git#egg=jutils
+# if not working, try afterwards:
+# pip install git+https://github.com/joh-schb/jutils.git#egg=jutils
diff --git a/patch-forcing/scripts/__pycache__/sample.cpython-312.pyc b/patch-forcing/scripts/__pycache__/sample.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab0b3b48e441a430302c0b6ca14ee4dc6c6dfa27
Binary files /dev/null and b/patch-forcing/scripts/__pycache__/sample.cpython-312.pyc differ
diff --git a/patch-forcing/scripts/convert_ckpt.py b/patch-forcing/scripts/convert_ckpt.py
new file mode 100644
index 0000000000000000000000000000000000000000..6384a723c96ce241d4cf1c9da0fcefff1fea7ef3
--- /dev/null
+++ b/patch-forcing/scripts/convert_ckpt.py
@@ -0,0 +1,37 @@
+"""
+Extract model state dict from trainer checkpoint, either "model" or "ema_model",
+and store it in a new checkpoint file with corresponding suffix and model config.
+"""
+
+import torch
+import argparse
+from omegaconf import OmegaConf
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("ckpt_path", type=str, help="Path to the checkpoint file")
+ parser.add_argument(
+ "--prefix", type=str, default="ema_model", help="Prefix for state dict (e.g., 'model' or 'ema_model')"
+ )
+ args = parser.parse_args()
+
+ ckpt = torch.load(args.ckpt_path, map_location="cpu")
+
+ # extract state dict
+ clean_state_dict = {}
+ for k, v in ckpt["state_dict"].items():
+ if k.startswith(args.prefix + "."):
+ new_k = k[len(args.prefix) + 1 :]
+ clean_state_dict[new_k] = v
+ print(f"Extracted {len(clean_state_dict):,} parameters with prefix '{args.prefix}'")
+
+ # extract config
+ config = ckpt["hyper_parameters"]["model"]
+ print("Extracted model config:")
+ print(OmegaConf.to_yaml(config))
+
+ # save model weights and configs
+ new_fp = args.ckpt_path.replace(".ckpt", f"_{args.prefix}.ckpt")
+ torch.save({"state_dict": clean_state_dict, "config": config}, new_fp)
+ print(f"Saved extracted checkpoint to {new_fp}")
diff --git a/patch-forcing/scripts/run_train_official.sh b/patch-forcing/scripts/run_train_official.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c3e79ee63206346eeb639d14a7efcc754a379600
--- /dev/null
+++ b/patch-forcing/scripts/run_train_official.sh
@@ -0,0 +1,155 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+ENV_DIR="${PFT_TRAIN_ENV_DIR:-/tmp/pft-venv-node-full}"
+PYTHON_BIN="${PYTHON_BIN:-/home/dyvm6xra/dyvm6xrauser11/miniforge3/bin/python}"
+PYTHON="${ENV_DIR}/bin/python"
+PIP="${ENV_DIR}/bin/pip"
+
+MODE="${1:-dummy}"
+shift || true
+
+EXTRA_ARGS=("$@")
+
+usage() {
+ cat <<'EOF'
+Usage:
+ scripts/run_train_official.sh [dummy|imnet-pft-b|imnet-pft-xl] [extra hydra overrides...]
+
+Modes:
+ dummy
+ Official Patch Forcing B training stack on dummy256 data.
+ Good for verifying the training pipeline on a single GPU.
+
+ imnet-pft-b
+ Full official ImageNet-256 Patch Forcing B training command.
+ Requires configs/data/imagenet256.yaml to be filled in.
+
+ imnet-pft-xl
+ Full official ImageNet-256 Patch Forcing XL training command.
+ Requires configs/data/imagenet256.yaml to be filled in.
+
+Examples:
+ scripts/run_train_official.sh dummy
+ scripts/run_train_official.sh dummy train_params.max_steps=100 data.params.batch_size=4
+ scripts/run_train_official.sh imnet-pft-b
+
+Recommended flow:
+ 1. On the login node, request a GPU shell:
+ /home/dyvm6xra/dyvm6xrauser11/workspace/cz/debug_apply.sh 1 patch-forcing --debug
+ 2. On the allocated compute node, run this script.
+EOF
+}
+
+if [[ "${MODE}" == "-h" || "${MODE}" == "--help" ]]; then
+ usage
+ exit 0
+fi
+
+require_gpu() {
+ if ! command -v nvidia-smi >/dev/null 2>&1; then
+ echo "nvidia-smi not found. Run this script on a GPU compute node."
+ exit 1
+ fi
+ nvidia-smi >/dev/null
+}
+
+ensure_env() {
+ if [[ ! -x "${PYTHON}" ]]; then
+ rm -rf "${ENV_DIR}"
+ "${PYTHON_BIN}" -m venv "${ENV_DIR}"
+ fi
+
+ if ! "${PYTHON}" - <<'PY' >/dev/null 2>&1
+import accelerate, cv2, diffusers, hydra, jutils, lightning, matplotlib, pandas, tensorboard
+import timm, torch, torch_fidelity, torchvision, wandb, webdataset
+PY
+ then
+ env HTTPS_PROXY= HTTP_PROXY= ALL_PROXY= https_proxy= http_proxy= all_proxy= \
+ "${PIP}" install torch==2.8.0+cu128 torchvision==0.23.0+cu128 --index-url https://download.pytorch.org/whl/cu128
+
+ env HTTPS_PROXY= HTTP_PROXY= ALL_PROXY= https_proxy= http_proxy= all_proxy= \
+ "${PIP}" install \
+ hydra-core lightning accelerate tensorboard webdataset opencv-python h5py pandas \
+ wandb torch-fidelity scipy requests packaging omegaconf PyYAML tqdm einops jaxtyping \
+ termcolor matplotlib ipython
+
+ env HTTPS_PROXY= HTTP_PROXY= ALL_PROXY= https_proxy= http_proxy= all_proxy= \
+ "${PIP}" install --no-deps timm diffusers git+https://github.com/joh-schb/jutils.git#egg=jutils
+ fi
+}
+
+prepare_sd_ae() {
+ mkdir -p "${ROOT_DIR}/checkpoints"
+
+ if [[ ! -f "${ROOT_DIR}/checkpoints/sd_ae_full.ckpt" ]]; then
+ env HTTPS_PROXY= HTTP_PROXY= ALL_PROXY= https_proxy= http_proxy= all_proxy= \
+ curl -L --retry 5 -C - \
+ -o "${ROOT_DIR}/checkpoints/sd_ae_full.ckpt" \
+ https://huggingface.co/stabilityai/sd-vae-ft-ema-original/resolve/main/vae-ft-ema-560000-ema-pruned.ckpt
+ fi
+
+ if [[ ! -f "${ROOT_DIR}/checkpoints/sd_ae.ckpt" ]]; then
+ "${PYTHON}" - <<'PY'
+import torch
+src = "checkpoints/sd_ae_full.ckpt"
+dst = "checkpoints/sd_ae.ckpt"
+ckpt = torch.load(src, map_location="cpu", weights_only=False)
+state_dict = ckpt["state_dict"] if "state_dict" in ckpt else ckpt
+state_dict = {k: v for k, v in state_dict.items() if not k.startswith("model_ema.")}
+torch.save(state_dict, dst)
+print(f"Saved converted SD autoencoder weights to {dst}")
+PY
+ fi
+}
+
+check_imagenet_cfg() {
+ if grep -q "tar_base: ..." "${ROOT_DIR}/configs/data/imagenet256.yaml"; then
+ echo "configs/data/imagenet256.yaml is still unconfigured."
+ echo "Fill tar_base and shard patterns before running ${MODE}."
+ exit 1
+ fi
+}
+
+build_train_cmd() {
+ case "${MODE}" in
+ dummy)
+ cat <<'EOF'
+train.py experiment=imnet-pft-b data=dummy256 autoencoder=sd_ae model.params.compile=false train_params.max_steps=100 train_params.val_check_interval=1000 train_params.limit_val_batches=0 data.params.batch_size=4 data.params.num_workers=0 name=debug/train-official
+EOF
+ ;;
+ imnet-pft-b)
+ check_imagenet_cfg
+ cat <<'EOF'
+train.py experiment=imnet-pft-b
+EOF
+ ;;
+ imnet-pft-xl)
+ check_imagenet_cfg
+ cat <<'EOF'
+train.py experiment=imnet-pft-xl
+EOF
+ ;;
+ *)
+ echo "Unknown mode: ${MODE}"
+ usage
+ exit 1
+ ;;
+ esac
+}
+
+require_gpu
+cd "${ROOT_DIR}"
+ensure_env
+prepare_sd_ae
+
+TRAIN_CMD="$(build_train_cmd)"
+
+echo "Using Python: ${PYTHON}"
+echo "Mode : ${MODE}"
+echo "Train cmd : ${TRAIN_CMD} ${EXTRA_ARGS[*]:-}"
+
+env HTTPS_PROXY= HTTP_PROXY= ALL_PROXY= https_proxy= http_proxy= all_proxy= \
+ LD_LIBRARY_PATH="${LD_LIBRARY_PATH:-}" \
+ "${PYTHON}" ${TRAIN_CMD} "${EXTRA_ARGS[@]}"
diff --git a/patch-forcing/scripts/sample.py b/patch-forcing/scripts/sample.py
new file mode 100644
index 0000000000000000000000000000000000000000..46fc70da525fe15996754fe8f604a7336e4dca35
--- /dev/null
+++ b/patch-forcing/scripts/sample.py
@@ -0,0 +1,120 @@
+import os
+import sys
+import time
+import torch
+import random
+import argparse
+import numpy as np
+from functools import partial
+from omegaconf import OmegaConf
+from contextlib import nullcontext
+from torchvision.utils import save_image
+from diffusers.models import AutoencoderKL
+from jutils import instantiate_from_config
+
+currentdir = os.path.dirname(__file__)
+parentdir = os.path.dirname(currentdir)
+sys.path.insert(0, parentdir)
+
+
+NULL_CLASS = 1000
+DATA_SHAPE = (4, 32, 32) # 256x256 images
+CLASS_LABELS = [207, 360, 387, 974, 88, 979, 417, 279]
+
+
+def unknowns_to_dict(unknown):
+ """Convert a list of 'key=value' strings (dot-notation) into a nested dict."""
+ bad = [u for u in unknown if u.startswith("-") or " " in u or u.strip() != u or "=" not in u]
+ if bad:
+ raise ValueError(f"Invalid override args (expected key=value without spaces): {bad}")
+ if not unknown:
+ return {}
+ conf = OmegaConf.from_dotlist(unknown)
+ return OmegaConf.to_container(conf, resolve=True)
+
+
+def main(args, sample_fn_overrides=None):
+ seed = args.seed
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+
+ assert torch.cuda.is_available(), "CUDA is required to run this script."
+ device = torch.device("cuda")
+ torch.set_grad_enabled(False)
+
+ if args.half_precision:
+ inference_context = torch.autocast("cuda")
+ else:
+ torch.backends.cuda.matmul.allow_tf32 = args.tf32
+ inference_context = nullcontext()
+
+ timesteps = torch.linspace(0, 1, args.num_sampling_steps + 1, device=device)
+ sample_fn_cfg = OmegaConf.load(args.sample_fn_config)
+ if sample_fn_overrides is not None:
+ sample_fn_cfg = OmegaConf.merge(sample_fn_cfg, sample_fn_overrides)
+ sampler = instantiate_from_config(sample_fn_cfg)
+ sample_fn = partial(sampler, timesteps=timesteps)
+
+ ckpt = torch.load(args.ckpt, map_location="cpu")
+ config = ckpt["config"]
+ state_dict = ckpt["state_dict"]
+ model = instantiate_from_config(config).to(device)
+ model.load_state_dict(state_dict)
+ model.eval()
+
+ vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-ema").to(device).eval()
+
+ n = len(CLASS_LABELS)
+ z = torch.randn(n, *DATA_SHAPE, device=device)
+ y = torch.tensor(CLASS_LABELS, device=device)
+ y_null = torch.full((n,), NULL_CLASS, device=device)
+
+ model_kwargs = dict(y=y, uc_cond=y_null, cond_key="y", cfg_scale=args.cfg_scale)
+
+ sampler_name = str(sampler)
+ cfg_name = str(args.cfg_scale).replace("/", "-")
+ save_prefix = f"steps{args.num_sampling_steps}_{sampler_name}_cfg{cfg_name}"
+ save_dir = parentdir
+
+ print("=" * 40)
+ print(f"{'ckpt':20}: {args.ckpt}")
+ print(f"{'output_dir':20}: {save_dir}")
+ print(f"{'save_prefix':20}: {save_prefix}")
+ print(f"{'class_labels':20}: {CLASS_LABELS}")
+ print(f"{'cfg_scale':20}: {args.cfg_scale}")
+ print(f"{'num_steps':20}: {args.num_sampling_steps}")
+ print(OmegaConf.to_yaml(sample_fn_cfg))
+ print("=" * 40)
+
+ start_time = time.time()
+ with inference_context:
+ samples = sample_fn(
+ model=model,
+ x=z,
+ progress=True,
+ **model_kwargs,
+ )
+ samples = vae.decode(samples / 0.18215).sample
+ elapsed = time.time() - start_time
+
+ grid_path = os.path.join(save_dir, f"{save_prefix}_sample.png")
+ save_image(samples, grid_path, nrow=4, normalize=True, value_range=(-1, 1))
+
+ print(f"Sampling took {elapsed:.2f} seconds.")
+ print(f"Saved grid to {grid_path}")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--ckpt", type=str, required=True, help="Path to a checkpoint.")
+ parser.add_argument("--sample-fn-config", type=str, default="configs/sampler/euler-pf.yaml")
+ parser.add_argument("--cfg-scale", type=float, default=4.0)
+ parser.add_argument("--num-sampling-steps", type=int, default=100)
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--tf32", action=argparse.BooleanOptionalAction, default=True, help="Use TF32 matmuls.")
+ parser.add_argument("--half_precision", action="store_true", help="Use this flag to enable bf16.")
+
+ known, unknown = parser.parse_known_args()
+ unknown = unknowns_to_dict(unknown)
+ main(known, unknown)
diff --git a/patch-forcing/scripts/sample_ddp.py b/patch-forcing/scripts/sample_ddp.py
new file mode 100644
index 0000000000000000000000000000000000000000..73b47dd2ff0a8da444f267ea59bb28a77f64257c
--- /dev/null
+++ b/patch-forcing/scripts/sample_ddp.py
@@ -0,0 +1,207 @@
+import os
+import sys
+import math
+import torch
+import random
+import argparse
+import datetime
+import numpy as np
+from tqdm import tqdm
+from PIL import Image
+from functools import partial
+from omegaconf import OmegaConf
+from contextlib import nullcontext
+from jutils import instantiate_from_config
+from diffusers.models import AutoencoderKL
+
+currentdir = os.path.dirname(__file__)
+parentdir = os.path.dirname(currentdir)
+sys.path.insert(0, parentdir)
+
+import patch_flow.pt_distributed as dist
+
+
+NUM_CLASSES = 1000
+DATA_SHAPE = (4, 32, 32) # 256x256 images
+
+
+def create_npz_from_sample_folder(sample_dir, num=50_000):
+ """
+ Builds a single .npz file from a folder of .png samples.
+ """
+ samples = []
+ for i in tqdm(range(num), desc="Building .npz file from samples"):
+ sample_pil = Image.open(f"{sample_dir}/{i:06d}.png")
+ sample_np = np.asarray(sample_pil).astype(np.uint8)
+ samples.append(sample_np)
+ samples = np.stack(samples)
+ assert samples.shape == (num, samples.shape[1], samples.shape[2], 3)
+ npz_path = f"{sample_dir}_N{num}.npz"
+ np.savez(npz_path, arr_0=samples)
+ print(f"Saved .npz file to {npz_path} [shape={samples.shape}].")
+ return npz_path
+
+
+""" Main """
+
+
+def main(args, sample_fn_overrides=None):
+ """Setup distributed"""
+ dist.init_process_group(backend="nccl", init_method="env://", timeout=datetime.timedelta(seconds=90))
+ GLOBAL_RANK = dist.get_rank()
+ LOCAL_RANK = GLOBAL_RANK % torch.cuda.device_count()
+ DEV = torch.device(f"cuda:{LOCAL_RANK}")
+ WORLD_SIZE = dist.get_world_size()
+ is_rank0 = dist.is_primary()
+ print(f"[RANK {GLOBAL_RANK} | {WORLD_SIZE}] Initializing on device: {DEV}")
+
+ seed = args.global_seed * dist.get_world_size() + LOCAL_RANK
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+
+ assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU."
+ if args.half_precision:
+ inference_context = torch.autocast("cuda")
+ else: # DEFAULT from SiT
+ torch.backends.cuda.matmul.allow_tf32 = args.tf32 # True: fast but may lead to some small numerical differences
+ inference_context = nullcontext()
+ torch.set_grad_enabled(False)
+
+ dist.print0(f"Global seed set to {seed}")
+ dist.print0("=" * 40)
+ for k, v in vars(args).items():
+ dist.print0(f"{k:20}: {v}")
+ dist.print0("=" * 40)
+
+ """ sampling function """
+ timesteps = torch.linspace(0, 1, args.num_sampling_steps + 1)
+ sample_fn_cfg = OmegaConf.load(args.sample_fn_config)
+ if sample_fn_overrides is not None: # merge with overrides
+ sample_fn_cfg = OmegaConf.merge(sample_fn_cfg, sample_fn_overrides)
+ sampler = instantiate_from_config(sample_fn_cfg)
+ sample_fn = partial(sampler, timesteps=timesteps)
+ dist.print0(OmegaConf.to_yaml(sample_fn_cfg))
+ dist.print0("=" * 40)
+
+ """ Load model """
+ ckpt = torch.load(args.ckpt, map_location="cpu")
+ config = ckpt["config"]
+ state_dict = ckpt["state_dict"]
+ model = instantiate_from_config(config).to(DEV)
+ model.load_state_dict(state_dict)
+ model.eval() # important!
+
+ vae = AutoencoderKL.from_pretrained(f"stabilityai/sd-vae-ft-ema").to(DEV)
+ assert args.cfg_scale >= 1.0, "In almost all cases, cfg_scale be >= 1.0"
+
+ """ Saving folder """
+ sample_dir = os.path.join(os.path.dirname(args.ckpt), "samples")
+ ckpt_string_name = os.path.basename(args.ckpt).replace(".ckpt", "")
+ sample_fn_postfix = f"{sampler}" # uses __repr__ method of sampler class
+ folder_name = (
+ f"{ckpt_string_name}-"
+ f"cfg-{args.cfg_scale}-"
+ f"{args.num_sampling_steps}_seed{args.global_seed}_{sample_fn_postfix}"
+ )
+ sample_folder_dir = f"{sample_dir}/{folder_name}"
+ os.makedirs(sample_folder_dir, exist_ok=True)
+ dist.print0(f"Saving samples to {sample_folder_dir}")
+ dist.barrier()
+
+ # Figure out how many samples we need to generate on each GPU and how many iterations we need to run:
+ n = args.per_proc_batch_size
+ global_batch_size = n * dist.get_world_size()
+ total_samples = int(math.ceil(args.num_fid_samples / global_batch_size) * global_batch_size)
+ dist.print0(f"Total number of images that will be sampled: {total_samples}")
+ assert total_samples % dist.get_world_size() == 0, "total_samples must be divisible by world_size"
+ samples_needed_this_gpu = int(total_samples // dist.get_world_size())
+ assert samples_needed_this_gpu % n == 0, "samples_needed_this_gpu must be divisible by the per-GPU batch size"
+ iterations = int(samples_needed_this_gpu // n)
+ pbar = range(iterations)
+ pbar = tqdm(pbar) if is_rank0 else pbar
+ total = 0
+
+ all_samples = []
+ for i in pbar:
+ # Sample inputs:
+ z = torch.randn(n, *DATA_SHAPE, device=DEV)
+ y = torch.randint(0, NUM_CLASSES, (n,), device=DEV)
+ y_null = torch.tensor([1000] * n, device=DEV) # for cfg
+
+ model_kwargs = dict(y=y, uc_cond=y_null, cond_key="y", cfg_scale=args.cfg_scale)
+
+ with inference_context:
+ samples = sample_fn(
+ model=model,
+ x=z,
+ progress=False,
+ **model_kwargs,
+ )
+ samples = vae.decode(samples / 0.18215).sample
+
+ samples = torch.clamp(127.5 * samples + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()
+ all_samples.append(samples)
+ total += global_batch_size
+ dist.barrier()
+
+ # Make sure all processes have finished saving their samples before attempting to convert to .npz
+ dist.barrier()
+ all_samples = np.concatenate(all_samples, axis=0)
+
+ # gather all samples over GPUs
+ all_samples = torch.tensor(all_samples).to(DEV).contiguous()
+ gathered_samples = dist.gather(all_samples)
+ gathered_samples = torch.cat(gathered_samples, dim=0).cpu().numpy()
+
+ # build the npz file
+ if is_rank0:
+ # store the desired number of samples
+ npz_path = f"{sample_folder_dir}_N{args.num_fid_samples}.npz"
+ arr_0 = gathered_samples[: args.num_fid_samples]
+ assert arr_0.shape[0] == args.num_fid_samples, f"Expected {args.num_fid_samples} samples, got {arr_0.shape[0]}"
+ np.savez(npz_path, arr_0=arr_0)
+ print(f"Saved .npz file to {npz_path} [shape={arr_0.shape}].")
+
+ # store 10k samples
+ if args.num_fid_samples > 10000 and gathered_samples.shape[0] > 10000:
+ npz_path = f"{sample_folder_dir}_N10000.npz"
+ np.savez(npz_path, arr_0=gathered_samples[:10000])
+ print(f"Saved .npz file to {npz_path} [shape={gathered_samples[:10000].shape}].")
+ dist.barrier()
+ dist.destroy_process_group()
+
+
+""" Parsing utils """
+
+
+def unknowns_to_dict(unknown):
+ """Convert a list of 'key=value' strings (dot-notation) into a nested dict."""
+ bad = [u for u in unknown if u.startswith("-") or " " in u or u.strip() != u or "=" not in u]
+ if bad:
+ raise ValueError(f"Invalid override args (expected key=value without spaces): {bad}")
+ if not unknown:
+ return {}
+ # OmegaConf parses values (int, float, bool, lists, null) automatically
+ conf = OmegaConf.from_dotlist(unknown)
+ return OmegaConf.to_container(conf, resolve=True)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--ckpt", type=str, required=True, help="Path to a checkpoint.")
+ parser.add_argument("--sample-fn-config", type=str, default="configs/sampler/euler-pf.yaml")
+ parser.add_argument("--per-proc-batch-size", type=int, default=64)
+ parser.add_argument("--num-fid-samples", type=int, default=10_000)
+ parser.add_argument("--cfg-scale", type=float, default=1.0)
+ parser.add_argument("--num-sampling-steps", type=int, default=100)
+ parser.add_argument("--global-seed", type=int, default=0)
+ parser.add_argument("--tf32", action=argparse.BooleanOptionalAction, default=True, help="Use TF32 matmuls.")
+ parser.add_argument("--half_precision", action="store_true", help="Use this flag to enable bf16.")
+
+ # Unknown args will be passed as overrides to the sample function config, e.g. following
+ # dot-notation you can pass, e.g. params.p=0.4
+
+ known, unknown = parser.parse_known_args()
+ unknown = unknowns_to_dict(unknown)
+ main(known, unknown)
diff --git a/patch-forcing/scripts/t2i_sample.py b/patch-forcing/scripts/t2i_sample.py
new file mode 100644
index 0000000000000000000000000000000000000000..098627119283d5157b2f5d938d6e92556fb4c3af
--- /dev/null
+++ b/patch-forcing/scripts/t2i_sample.py
@@ -0,0 +1,159 @@
+import os
+import sys
+import torch
+import torch.nn as nn
+import random
+import einops
+import argparse
+import numpy as np
+from PIL import Image
+from typing import List
+from functools import partial
+from omegaconf import OmegaConf
+
+from transformers import AutoTokenizer
+from transformers import Qwen3VLForConditionalGeneration
+
+from jutils.nn import FLUX2AutoencoderKL
+from jutils import instantiate_from_config
+
+pdir = os.path.dirname(os.path.dirname(__file__))
+sys.path.insert(0, pdir)
+
+LATENT_CHANNELS = 32
+
+
+# ===================================================================================================
+
+
+class Qwen3VLEmbedder2B(nn.Module):
+ def __init__(
+ self,
+ repo: str = "Qwen/Qwen3-VL-Embedding-2B",
+ max_length: int = 256,
+ dtype: torch.dtype = torch.bfloat16,
+ ):
+ super().__init__()
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ self.path = repo
+ self.max_length = max_length
+
+ self.tokenizer = AutoTokenizer.from_pretrained(self.path)
+ full_model = Qwen3VLForConditionalGeneration.from_pretrained(self.path, dtype=dtype)
+ text_tower = full_model.model.language_model
+ del full_model
+
+ self.model = text_tower
+ self.emb_dim = int(self.model.config.hidden_size)
+ self.model.requires_grad_(False)
+ self.model.eval()
+
+ @property
+ def device(self) -> torch.device:
+ return next(self.model.parameters()).device
+
+ @torch.no_grad()
+ def forward(self, txt: List[str]):
+ tok_out = self.tokenizer(
+ txt, return_tensors="pt", padding="max_length", max_length=self.max_length, truncation=True
+ )
+ tok_out = tok_out.to(self.device)
+ txt_emb = self.model(**tok_out, output_hidden_states=True)
+ if hasattr(txt_emb, "last_hidden_state"):
+ return txt_emb.last_hidden_state
+ return txt_emb.hidden_states[-1]
+
+
+def unknowns_to_dict(unknown):
+ """Convert a list of 'key=value' strings (dot-notation) into a nested dict."""
+ bad = [u for u in unknown if u.startswith("-") or " " in u or u.strip() != u or "=" not in u]
+ if bad:
+ raise ValueError(f"Invalid override args (expected key=value without spaces): {bad}")
+ if not unknown:
+ return {}
+ # OmegaConf parses values (int, float, bool, lists, null) automatically
+ conf = OmegaConf.from_dotlist(unknown)
+ return OmegaConf.to_container(conf, resolve=True)
+
+
+# ===================================================================================================
+
+
+def main(args, sample_fn_overrides=None):
+ seed = args.seed
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+
+ assert torch.cuda.is_available(), "CUDA is required to run this script."
+ DEV = torch.device("cuda")
+
+ # first stage autoencoder
+ vae = FLUX2AutoencoderKL(ckpt_path="checkpoints/flux2_ae.ckpt").to(DEV).eval()
+ print(f"{'Autoencoder':<16}: {sum([p.numel() for p in vae.parameters()]):,}")
+
+ # text tower
+ text_embedder = Qwen3VLEmbedder2B().to(DEV).eval()
+ print(f"{'Text Embedder':<16}: {sum([p.numel() for p in text_embedder.parameters()]):,}")
+
+ # model
+ ckpt = torch.load(args.ckpt, map_location="cpu")
+ config = ckpt["config"]
+ state_dict = ckpt["state_dict"]
+ model = instantiate_from_config(config).to(DEV)
+ model.load_state_dict(state_dict)
+ model.eval() # important!
+ print(f"{'Model':<16}: {sum([p.numel() for p in model.parameters()]):,}")
+
+ # sampling function
+ timesteps = torch.linspace(0, 1, args.num_steps + 1)
+ sample_fn_cfg = OmegaConf.load(args.sample_fn_config)
+ if sample_fn_overrides is not None: # merge with overrides
+ sample_fn_cfg = OmegaConf.merge(sample_fn_cfg, sample_fn_overrides)
+ sampler = instantiate_from_config(sample_fn_cfg)
+ sample_fn = partial(sampler, timesteps=timesteps)
+ print("=" * 40)
+ print(OmegaConf.to_yaml(sample_fn_cfg))
+ print("=" * 40)
+
+ # sampling
+ prompt = [args.prompt] * args.num_samples
+ latent_shape = (LATENT_CHANNELS, args.resolution // 8, args.resolution // 8)
+ noise = torch.randn((args.num_samples, *latent_shape), device=DEV)
+
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
+ txt_emb = text_embedder(prompt)
+ null_txt_emb = text_embedder("")
+ samples = sample_fn(
+ model=model,
+ x=noise,
+ txt_emb=txt_emb,
+ uc_cond=null_txt_emb,
+ progress=True,
+ cond_key="txt_emb",
+ cfg_scale=args.cfg_scale,
+ )
+ samples = vae.decode(samples)
+
+ samples = einops.rearrange(samples, "b c h w -> b h w c")
+ samples = torch.clamp(127.5 * samples + 128.0, 0, 255).cpu().to(torch.uint8).numpy()
+
+ clean_prompt = args.prompt.replace(" ", "-").replace(",", "-")
+ save_fn = f"{clean_prompt[:100]}_cfg{args.cfg_scale}_nfe{args.num_steps}_seed{args.seed}"
+ for i, img in enumerate(samples):
+ Image.fromarray(img).save(f"{save_fn}_{i}.png")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--ckpt", type=str, required=True)
+ parser.add_argument("--prompt", type=str, required=True)
+ parser.add_argument("--num-samples", type=int, default=4)
+ parser.add_argument("--num-steps", type=int, default=50)
+ parser.add_argument("--cfg-scale", type=float, default=4.0)
+ parser.add_argument("--sample-fn-config", type=str, default="configs/sampler/euler-pf.yaml")
+ parser.add_argument("--resolution", type=int, default=256)
+ parser.add_argument("--seed", type=int, default=2026)
+ known, unknown = parser.parse_known_args()
+ unknown = unknowns_to_dict(unknown)
+ main(known, unknown)
diff --git a/patch-forcing/steps100_DualLoop-p40-inner4_cfg4.0_sample.png b/patch-forcing/steps100_DualLoop-p40-inner4_cfg4.0_sample.png
new file mode 100644
index 0000000000000000000000000000000000000000..2df8162d9575be249ef96311f3d1e4c1d3dafde1
--- /dev/null
+++ b/patch-forcing/steps100_DualLoop-p40-inner4_cfg4.0_sample.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5794aa4b68a636c707de9c033a3444d2c5c389e960da52953ca9e2b86d0b9c48
+size 912377
diff --git a/patch-forcing/train.py b/patch-forcing/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..036fd64f0aba1951d28cbb8f98570c4b46537cac
--- /dev/null
+++ b/patch-forcing/train.py
@@ -0,0 +1,482 @@
+import os
+import sys
+import time
+import hydra
+import torch
+import datetime
+from types import MethodType
+from functools import partial
+from tqdm import tqdm as tqdm_
+from lightning import seed_everything
+from contextlib import contextmanager
+from torch.utils.tensorboard import SummaryWriter
+from omegaconf import OmegaConf, DictConfig, ListConfig
+from torch.profiler import ProfilerActivity, profile, record_function
+
+from jutils import NullObject
+from jutils import instantiate_from_config
+from jutils import count_parameters, exists
+import patch_flow # dummy to add omegaconf resolver
+from patch_flow.dataloader import CUDAPrefetchIterator
+
+from accelerate import Accelerator
+from accelerate.utils import DistributedDataParallelKwargs
+
+
+# tqdm bar format
+BAR_FORMAT = "{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_noinv_fmt}{postfix}]"
+tqdm = partial(tqdm_, bar_format=BAR_FORMAT, dynamic_ncols=True)
+
+
+# recursive check for `_target_` used with hydra's instantiate (not yet implemented)
+def check_for_instantiate_key(cfg_node, path=""):
+ if isinstance(cfg_node, dict) or isinstance(cfg_node, DictConfig):
+ for k, v in cfg_node.items():
+ full_path = f"{path}.{k}" if path else k
+ if k == "_target_":
+ raise NotImplementedError(
+ f"Unexpected '_target_' key found in config at: '{full_path}'. Hydra instantiate not yet implemented."
+ )
+ check_for_instantiate_key(v, full_path)
+ elif isinstance(cfg_node, (list, ListConfig)):
+ for i, item in enumerate(cfg_node):
+ check_for_instantiate_key(item, f"{path}[{i}]")
+
+
+def check_config(cfg):
+ if cfg.get("auto_requeue", False):
+ raise NotImplementedError("Auto-requeuing not working yet!")
+ if exists(cfg.get("resume_checkpoint", None)) and exists(cfg.get("load_weights", None)):
+ raise ValueError("Can't resume checkpoint and load weights at the same time.")
+ if "experiment" in cfg:
+ raise ValueError("Experiment config not merged successfully!")
+ if cfg.use_wandb and cfg.use_wandb_offline:
+ raise ValueError("Decide either for Online or Offline wandb, not both.")
+ check_for_instantiate_key(cfg)
+
+ # check for quick_train missing features
+ assert cfg.use_wandb is False, "Wandb is not supported in quick_train.py"
+ assert cfg.use_wandb_offline is False, "Wandb is not supported in quick_train.py"
+ assert cfg.trainer.params.get("log_grad_norm", False) is False, "Log grad norm is not supported in quick_train.py"
+ assert cfg.auto_requeue is False, "Auto-requeue is not supported in quick_train.py"
+ assert cfg.deepspeed_stage == 0, "Deepspeed is not supported in quick_train.py"
+
+
+""" lightning replacement functions """
+
+
+def log_accelerate(name, value, step=None, writer=None, **kwargs):
+ assert exists(writer), "Writer not passed to log function."
+ if isinstance(value, torch.Tensor):
+ value = value.item()
+ if isinstance(value, (float, int)):
+ writer.add_scalar(name, value, global_step=step)
+
+
+def add_global_step_setter(lightning_module):
+ """
+ Add a global step setter to the lightning module, s.t. we can
+ use `self.global_step` within the module hooks.
+ """
+
+ @property
+ def global_step(self):
+ return self._global_step
+
+ @global_step.setter
+ def global_step(self, value):
+ self._global_step = value
+
+ # apply new property to the instance
+ lightning_module.__class__.global_step = global_step
+
+
+@contextmanager
+def temporary_logger(module, logger):
+ """create subclass with property override for self.logger"""
+ original_class = module.__class__
+
+ def get_logger(self):
+ return logger
+
+ TempClass = type(f"Patched{original_class.__name__}", (original_class,), {"logger": property(get_logger)})
+
+ module.__class__ = TempClass
+ try:
+ yield module
+ finally:
+ # Restore the original class
+ module.__class__ = original_class
+
+
+def unwrap_model(model: torch.nn.Module) -> torch.nn.Module:
+ """
+ Recursively unwraps a model from potential containers (as used in distributed training).
+ """
+ if hasattr(model, "module"):
+ return unwrap_model(model.module)
+ else:
+ return model
+
+
+""" main function """
+
+
+@hydra.main(config_path="configs", config_name="config", version_base=None)
+def main(cfg: DictConfig):
+ """Check config"""
+ cfg = OmegaConf.create(OmegaConf.to_container(cfg, resolve=True))
+ check_config(cfg)
+
+ """ Setup accelerate """
+ # translate precision of lightning to accelerate
+ lightning_to_accelerate_prec = {
+ "16-mixed": "fp16",
+ 16: "fp16",
+ "32-true": "no",
+ 32: "no",
+ "bf16": "bf16",
+ "bf16-mixed": "bf16",
+ }
+ # ddp kwargs
+ ddp_kwargs = DistributedDataParallelKwargs(
+ find_unused_parameters=cfg.ddp_kwargs.get("find_unused_parameters", False),
+ gradient_as_bucket_view=cfg.ddp_kwargs.get("gradient_as_bucket_view", False),
+ bucket_cap_mb=cfg.ddp_kwargs.get("bucket_cap_mb", 25),
+ broadcast_buffers=cfg.ddp_kwargs.get("broadcast_buffers", True),
+ )
+ accelerator = Accelerator(
+ mixed_precision=lightning_to_accelerate_prec[cfg.train_params.precision],
+ gradient_accumulation_steps=cfg.train_params.accumulate_grad_batches,
+ kwargs_handlers=[ddp_kwargs],
+ )
+ seed_everything(2025 + accelerator.process_index)
+ is_rank0 = accelerator.is_main_process
+ device = accelerator.device
+
+ """ Setup Logging """
+ # we store the experiment under: logs///
+ day = datetime.datetime.now().strftime("%Y-%m-%d")
+ postfix = str(cfg.slurm_id) if exists(cfg.slurm_id) else datetime.datetime.now().strftime("T%H%M%S")
+ exp_name = os.path.join(cfg.name, day, postfix)
+ log_dir = os.path.join("logs", exp_name)
+ ckpt_dir = os.path.join(log_dir, "checkpoints")
+ os.makedirs(ckpt_dir, exist_ok=True)
+
+ if is_rank0:
+ logger = SummaryWriter(log_dir=log_dir)
+ else:
+ logger = NullObject()
+
+ """ Setup dataloader """
+ data = instantiate_from_config(cfg.data)
+ if hasattr(data, "prepare_data"):
+ data.prepare_data()
+ if hasattr(data, "setup"):
+ data.setup(None)
+ train_loader = data.train_dataloader()
+ val_loader = data.val_dataloader()
+
+ """ Setup module """
+ module = instantiate_from_config(cfg.trainer)
+ module = module.to(device).train()
+
+ """ Patch lightning logging methods """
+ add_global_step_setter(module)
+
+ # printing
+ def patched_print(self, *args, **kwargs):
+ accelerator.print(*args, **kwargs)
+
+ module.print = MethodType(patched_print, module)
+
+ # logging
+ def patched_log(self, name, value, **kwargs):
+ log_accelerate(name, value, step=self.global_step, writer=logger, **kwargs)
+
+ module.log = MethodType(patched_log, module)
+
+ """ Setup optimizer """
+ out = module.configure_optimizers()
+ optimizer = out["optimizer"]
+ scheduler = out.get("lr_scheduler", None)
+
+ """ Load from checkpoint """
+ resume_step = 0
+ if exists(cfg.resume_checkpoint):
+ ckpt = torch.load(cfg.resume_checkpoint, map_location=device, weights_only=False)
+ resume_step = ckpt["global_step"]
+ module.load_state_dict(ckpt["state_dict"], strict=cfg.get("load_strict", True))
+ assert len(ckpt["optimizer_states"]) == 1, "Checkpoint should only contain one optimizer state dict."
+ optimizer.load_state_dict(ckpt["optimizer_states"][0])
+ if exists(scheduler) and len(ckpt["lr_schedulers"]) > 0:
+ assert len(ckpt["lr_schedulers"]) == 1, "Checkpoint should only contain one scheduler state dict."
+ scheduler.load_state_dict(ckpt["lr_schedulers"][0])
+ print(
+ f"Rank {accelerator.process_index} ({accelerator.num_processes}): Resumed from checkpoint at step {resume_step}"
+ )
+
+ if exists(cfg.load_weights):
+ ckpt = torch.load(cfg.load_weights, map_location=device, weights_only=False)
+ module.load_state_dict(ckpt["state_dict"], strict=cfg.get("load_strict", True))
+ print(f"Rank {accelerator.process_index} ({accelerator.num_processes}): Loaded weights from {cfg.load_weights}")
+ if "resume_step" in cfg and cfg.resume_step > 0:
+ resume_step = cfg.resume_step
+ print(f"Rank {accelerator.process_index} ({accelerator.num_processes}): Set resume step to {resume_step}")
+
+ """ Setup DDP """
+ module, optimizer, train_loader, val_loader = accelerator.prepare(module, optimizer, train_loader, val_loader)
+
+ """ Profiling """
+ profile_fn = NullObject()
+ profile_record_fn = NullObject()
+ if cfg.profile:
+ profile_fn = partial(
+ profile,
+ activities=[
+ *((ProfilerActivity.CPU,) if cfg.profiling.cpu else ()),
+ *((ProfilerActivity.CUDA,) if cfg.profiling.cuda else ()),
+ ],
+ record_shapes=cfg.profiling.record_shapes,
+ profile_memory=cfg.profiling.profile_memory,
+ with_flops=cfg.profiling.with_flops,
+ with_stack=True,
+ )
+ profile_record_fn = record_function
+
+ """ print information """
+ # log trainer module
+ if is_rank0:
+ print("-" * 40)
+ print(OmegaConf.to_yaml(cfg.trainer))
+ bs = cfg.data.params.batch_size
+ bs = bs * accelerator.num_processes # num nodes * num gpus
+ bs = bs * cfg.train_params.accumulate_grad_batches # global batch size
+ assert accelerator.num_processes % cfg.num_nodes == 0, "Processes not divisible by nodes."
+ # val batch size
+ bs_val = cfg.data.params.get("val_batch_size", cfg.data.params.batch_size)
+ bs_val = bs_val * accelerator.num_processes
+ bs_val = bs_val * cfg.train_params.limit_val_batches
+ some_info = {
+ "Command": " ".join(["python"] + sys.argv),
+ "Name": exp_name,
+ "Log dir": log_dir,
+ "Trainer Module": cfg.trainer.target,
+ "Params": count_parameters(module),
+ "Data": cfg.data.get("name", "not set"),
+ "Batchsize": cfg.data.params.batch_size,
+ "Devices": accelerator.num_processes // cfg.num_nodes,
+ "Num nodes": cfg.num_nodes,
+ "Gradient accum": cfg.train_params.accumulate_grad_batches,
+ "Global batchsize": bs,
+ "Val samples": bs_val,
+ "LR": cfg.trainer.params.lr,
+ "LR scheduler": cfg.lr_scheduler.get("name", "no name") if "lr_scheduler" in cfg else "None",
+ "Resume ckpt": cfg.resume_checkpoint,
+ "Load weights": cfg.load_weights,
+ "Profiling": f"Step {cfg.profiling.warmup}" if cfg.profile else "None",
+ "Precision": cfg.train_params.precision,
+ }
+ if is_rank0:
+ OmegaConf.save(cfg, f"{log_dir}/config.yaml")
+
+ # log hyperparameters to tensorboard
+ logger.add_text("config", OmegaConf.to_yaml(cfg))
+ logger.add_text("summary", OmegaConf.to_yaml(some_info))
+
+ # print and write some info to the config
+ with open(f"{log_dir}/config.yaml", "a") as f:
+ f.write("\n\n")
+
+ def flush_txt(txt):
+ print(f"{txt}")
+ f.write(f"# {txt}\n")
+
+ flush_txt("-" * 40)
+ for k, v in some_info.items():
+ if isinstance(v, float):
+ flush_txt(f"{k:<16}: {v:.5f}")
+ elif isinstance(v, int):
+ flush_txt(f"{k:<16}: {v:,}")
+ elif isinstance(v, bool):
+ flush_txt(f"{k:<16}: {'True' if v else 'False'}")
+ else:
+ flush_txt(f"{k:<16}: {v}")
+ flush_txt("-" * 40)
+
+ """ Setup training loop """
+ global_step = resume_step
+ max_steps = cfg.train_params.get("max_steps", -1)
+ use_cuda_prefetch = bool(cfg.get("cuda_prefetch", False)) and device.type == "cuda"
+ train_iterable = (
+ CUDAPrefetchIterator(
+ iterator=iter(train_loader),
+ device=device,
+ enabled=True,
+ prefetch_factor=cfg.get("cuda_prefetch_factor", 2),
+ )
+ if use_cuda_prefetch
+ else train_loader
+ )
+
+ # Loop
+ for step, batch in enumerate(
+ tqdm(train_iterable, desc="Training", miniters=cfg.tqdm_refresh_rate, disable=(not is_rank0))
+ ):
+
+ if max_steps > 0 and global_step >= max_steps:
+ accelerator.print(f"Finish training after {global_step} steps.")
+ accelerator.wait_for_everyone()
+ break
+
+ t0 = time.time()
+ # ===================== #
+ # Training #
+ # ===================== #
+ with profile_fn() if cfg.profile and global_step == cfg.profiling.warmup else NullObject() as prof:
+
+ with accelerator.accumulate(module):
+ # forward
+ with profile_record_fn(f"step_{global_step}/fwd"):
+ with accelerator.autocast():
+ if not use_cuda_prefetch:
+ batch = {
+ k: v.to(device, non_blocking=True) if isinstance(v, torch.Tensor) else v
+ for k, v in batch.items()
+ }
+ loss = module.forward(batch)
+
+ if isinstance(loss, tuple):
+ assert len(loss) == 2, "Loss tuple should be of length 2, shall be (loss, dict)."
+ loss, loss_dict = loss
+ else:
+ loss_dict = {}
+
+ # backward
+ with profile_record_fn(f"step_{global_step}/bwd"):
+ accelerator.backward(loss)
+
+ # optimizer step
+ with profile_record_fn(f"step_{global_step}/opt"):
+ if accelerator.sync_gradients:
+ grad_norm = accelerator.clip_grad_norm_(
+ module.parameters(), max_norm=cfg.train_params.clip_grad_norm
+ )
+ optimizer.step()
+ optimizer.zero_grad()
+
+ if accelerator.sync_gradients:
+ if exists(scheduler):
+ scheduler.step()
+ unwrap_model(module).on_train_batch_end(loss, batch, step) # no sync needed
+ global_step += 1
+ module.global_step = global_step
+ step_time = time.time() - t0
+
+ # logging
+ if accelerator.sync_gradients and global_step % cfg.train_params.log_every_n_steps == 0:
+ logger.add_scalar("train/loss", loss.item(), global_step=global_step)
+ for k, v in loss_dict.items():
+ logger.add_scalar(f"train/{k}", v.item(), global_step=global_step)
+ logger.add_scalar("train/grad_norm", grad_norm.item(), global_step=global_step)
+ logger.add_scalar("train/step_time", step_time, global_step=global_step)
+ logger.add_scalar("train/it_per_sec", 1.0 / step_time, global_step=global_step)
+ logger.add_scalar("train/throughput", bs / step_time, global_step=global_step)
+ if exists(scheduler):
+ logger.add_scalar("train/lr-AdamW", scheduler.get_last_lr()[0], global_step=global_step)
+
+ if not accelerator.sync_gradients:
+ continue
+
+ # ===================== #
+ # Profiling #
+ # ===================== #
+ if cfg.profile and not isinstance(prof, NullObject):
+ accelerator.wait_for_everyone()
+ if is_rank0:
+ print(f"[Profiling] Enabled after {cfg.profiling.warmup} steps.")
+ fn = os.path.join(log_dir, cfg.profiling.filename)
+ prof.export_chrome_trace(fn)
+ print(f"[Profiling] Exported '{fn}'")
+ accelerator.wait_for_everyone()
+ break
+
+ # ===================== #
+ # Checkpoint #
+ # ===================== #
+ if global_step % cfg.checkpoint_params.every_n_train_steps == 0 and global_step > 0:
+ accelerator.wait_for_everyone()
+ if is_rank0:
+ fn = os.path.join(ckpt_dir, f"step{global_step:06d}.ckpt")
+ lightning_module = unwrap_model(module)
+ lightning_module.eval()
+ # align with lightning checkpoints
+ checkpoint = {
+ "epoch": 0,
+ "global_step": global_step,
+ "pytorch-lightning_version": "2.5.0.post0",
+ "state_dict": lightning_module.state_dict(),
+ # 'loops': {}, # TODO
+ # 'callbacks': {}, # TODO
+ "optimizer_states": [optimizer.state_dict()],
+ "lr_schedulers": [scheduler.state_dict()] if exists(scheduler) else [],
+ "hparams_name": "kwargs",
+ "hyper_parameters": OmegaConf.to_object(cfg.trainer.params),
+ }
+ torch.save(checkpoint, fn)
+ print(f"Save checkpoint to {fn}")
+ # symlink latest checkpoint
+ last_ckpt_symlink = os.path.join(ckpt_dir, "last.ckpt")
+ try:
+ if os.path.islink(last_ckpt_symlink) or os.path.exists(last_ckpt_symlink):
+ os.remove(last_ckpt_symlink)
+ relative_ckpt_path = os.path.relpath(fn, start=ckpt_dir)
+ os.symlink(relative_ckpt_path, last_ckpt_symlink)
+ except OSError as e:
+ print(f"Failed to update symlink for last.ckpt: {e}")
+ lightning_module.train()
+ accelerator.wait_for_everyone()
+
+ # ===================== #
+ # Validation #
+ # ===================== #
+ if global_step % cfg.train_params.val_check_interval == 0 and global_step > 0:
+
+ module.eval()
+ n_val_steps = cfg.train_params.limit_val_batches
+ sample_module = unwrap_model(module)
+ sample_module.global_step = global_step
+
+ for val_step, val_batch in enumerate(
+ tqdm(val_loader, desc=f"Validation {global_step}", disable=(not is_rank0), total=n_val_steps)
+ ):
+ if val_step == n_val_steps:
+ break
+
+ val_batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in val_batch.items()}
+ with torch.no_grad(), accelerator.autocast():
+ sample_module.validation_step(val_batch, val_step)
+
+ # gather metrics and log them
+ with temporary_logger(sample_module, logger):
+ sample_module.on_validation_epoch_end()
+
+ accelerator.wait_for_everyone()
+ module.train()
+
+ accelerator.wait_for_everyone()
+ accelerator.end_training()
+
+
+if __name__ == "__main__":
+ torch.backends.cuda.matmul.allow_tf32 = True
+ torch.backends.cudnn.allow_tf32 = True
+ from einops._torch_specific import allow_ops_in_compiled_graph
+
+ allow_ops_in_compiled_graph()
+
+ try:
+ main()
+ except KeyboardInterrupt:
+ print("[KeyboardInterrupt] Interrupted by user.")
+ exit()