fomo-iqa 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fomo_iqa-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: fomo-iqa
3
+ Version: 0.1.0
4
+ Summary: FoMo: Forking Moment in Generative Trajectory as a Perceptual Distance — reference-based perceptual distance models trained on diffusion-generated (FLUX) image pairs
5
+ Author: Jaihyun Lew
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/JHLew/FoMo
8
+ Keywords: image-quality-assessment,perceptual-metric,perceptual-loss,IQA
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: torch>=2.1
13
+ Requires-Dist: torchvision
14
+ Requires-Dist: transformers>=4.56
15
+ Requires-Dist: huggingface_hub
16
+ Requires-Dist: lpips>=0.1.4
17
+ Requires-Dist: DISTS-pytorch>=0.1
18
+ Requires-Dist: dreamsim>=0.2.1
19
+ Requires-Dist: peft
20
+ Requires-Dist: numpy
21
+ Requires-Dist: pillow
22
+ Dynamic: license-file
23
+
24
+ # FoMo: Forking Moment in Generative Trajectory as a Perceptual Distance
25
+
26
+ <p align="center">
27
+ <img src="figures/FoMo_main.png" alt="FoMo: data generation from the forking moment of the diffusion trajectory, and ranked-BCE training" width="100%">
28
+ </p>
29
+ <p align="center">
30
+ <img src="figures/FoMo_generated_pairs.png" alt="Examples of generated image pairs at different forking moments" width="100%">
31
+ </p>
32
+
33
+ FoMo trains reference-based perceptual distance metrics **without human labels**. Running a diffusion model (FLUX.1-dev) in img2img mode from a base image, re-entering the trajectory `s` denoising steps before the end, produces a variant whose perceptual deviation from the base grows monotonically with `s` — the *forking moment* of the generative trajectory. The timestep is therefore a free, dense supervision signal: we generate 480k such image sets and train distance models with a pairwise ranking objective on it.
34
+
35
+ Seven models are released, all trained on the same 480k FoMo dataset with the same ranked-BCE objective; only the frozen backbone / trainable part differs:
36
+
37
+ | Name | Architecture | Trained part |
38
+ |---|---|---|
39
+ | `lpips_alex` | LPIPS, AlexNet features | linear calibration weights |
40
+ | `lpips_vgg` | LPIPS, VGG-16 features | linear calibration weights |
41
+ | `dists` | DISTS, VGG-16 features | α / β mixing weights |
42
+ | `dinov3` | frozen DINOv3 ViT-S/16+ + prediction head | 3-layer 2D-RoPE transformer head |
43
+ | `clip` | frozen CLIP ViT-B/32 + prediction head | 3-layer 2D-RoPE transformer head |
44
+ | `mae` | frozen MAE ViT-B/16 + prediction head | 3-layer 2D-RoPE transformer head |
45
+ | `dreamsim` | DreamSim ensemble (DINO + CLIP + OpenCLIP ViT-B/16) | LoRA adapters (r=16) |
46
+
47
+ ## Using the pretrained models
48
+
49
+ ```bash
50
+ pip install fomo-iqa # or, from this repository: pip install -e .
51
+ ```
52
+
53
+ (The distribution is `fomo-iqa` because `fomo` is taken on PyPI; the import name is `fomo`.)
54
+
55
+ ```python
56
+ import fomo
57
+
58
+ # A model is defined by its backbone alone. How the score is presented —
59
+ # `symmetric` and `output` — is chosen per call, so one model serves every use.
60
+
61
+ # --- a CNN model --------------------------------------------------------------
62
+ lpips_alex = fomo.FoMo('lpips_alex')
63
+ d = lpips_alex(img_ref, img_test) # [B]; lower = more similar
64
+ # already non-negative with d(x, x) = 0,
65
+ # and symmetric by construction, so
66
+ # `symmetric` and 'distance' change nothing
67
+
68
+ # --- a prediction-head model --------------------------------------------------
69
+ dinov3 = fomo.FoMo('dinov3')
70
+ d_raw = dinov3(img_ref, img_test, symmetric=True) # 'raw' (default): the
71
+ # published protocol. A ranking
72
+ # score with an arbitrary zero
73
+ # point, so it may be negative
74
+ d_dist = dinov3(img_ref, img_test, symmetric=True, output='distance') # non-negative, d(x, x) ≈ 0,
75
+ # LPIPS-style. Ranks pairs
76
+ # identically to 'raw'
77
+ d_asym = dinov3(img_ref, img_test, symmetric=False) # single order s(x, y)
78
+
79
+ # `symmetric=True` is the default and only affects dinov3 / clip / mae, where the
80
+ # head reads the two images as one sequence: it averages both argument orders
81
+ # from a single backbone pass.
82
+
83
+ # --- as a perceptual loss ------------------------------------------------------
84
+ # differentiable w.r.t. the inputs. output='loss' is hinged at the identity
85
+ # level, so optimization settles once the images are as close as identical
86
+ # instead of continuing past that point.
87
+ loss = dinov3(prediction, target, output='loss').mean()
88
+ loss.backward()
89
+ ```
90
+
91
+ `fomo.load(name)` returns the underlying `DistanceModel` (method `eval_distance`), and `checkpoint='path/to/file.pth'` loads a local file — including a `ckpt_latest.pt` produced by `train.py` (its EMA weights are used). `python example_usage.py --model dinov3 --mode metric|loss` is a runnable demo.
92
+
93
+ **Inputs.** Float tensors `[B, 3, H, W]` in `[0, 1]`. Do **not** normalize — each model applies its own preprocessing (ImageNet statistics for DINOv3 / MAE, CLIP statistics for CLIP, `[-1, 1]` for LPIPS, raw for DISTS, bicubic resize to 224 for DreamSim). Both images of a pair must share a spatial size; any size works (the ViT models zero-pad to their patch grid). Benchmarks are scored at native resolution.
94
+
95
+ **Distance options.**
96
+
97
+ - `lpips_alex`, `lpips_vgg`, `dists` and `dreamsim` compute a symmetric distance directly (DreamSim as the cosine distance of its embeddings). `dinov3`, `clip` and `mae` read the two images as one concatenated token sequence and output a scalar for that ordered pair.
98
+ - `symmetric` (default `True`): for `dinov3` / `clip` / `mae` the output `s(x, y)` need not equal `s(y, x)`, so the score is `½ [s(x, y) + s(y, x)]`, both orders from a single backbone pass. `symmetric=False` returns the single order `s(x, y)`.
99
+ - `output` (default `'raw'`): which of three presentations the score is returned in. `'raw'` and `'distance'` are the same metric in two scales — softplus is strictly increasing, so they rank every pair identically (SROCC and KROCC agree to the last digit). `'loss'` subtracts a per-pair quantity and is shaped for optimization rather than for ranking.
100
+
101
+ | `output` | what it returns | use it for |
102
+ |---|---|---|
103
+ | `'raw'` (default) | the model output, unchanged | reproducing the published numbers |
104
+ | `'distance'` | non-negative, `d(x, x) ≈ 0` | a drop-in LPIPS-style metric |
105
+ | `'loss'` | `relu( d(x, y) − max(d(x, x), d(y, y)) )` | a perceptual loss / image optimization |
106
+
107
+ `'raw'` is the protocol every published number was computed under. For `dinov3` / `clip` / `mae` it is a ranking score whose zero point is arbitrary, so it may be negative; `lpips_alex`, `lpips_vgg`, `dists` and `dreamsim` return a non-negative distance with `d(x, x) = 0` directly.
108
+
109
+ `'distance'` applies softplus to `dinov3` / `clip` / `mae` — mapping their identity level to `≈ 0` and giving a positive output everywhere, with no calibration constant to fit or ship — and leaves the other four untouched, since they already have an exact `d(x, x) = 0` (softplus would move it to `log 2 ≈ 0.693`). The rule differs by model family so that the *semantics* are uniform: all seven are non-negative with `d(x, x) ≈ 0`. Rankings are identical to `'raw'`; use `'raw'` to reproduce the published numbers exactly.
110
+
111
+ `'loss'` is a hinge whose floor sits at the per-pair identity level: full gradient while the images differ, and zero once they are as close as identical, so optimization stops there rather than pushing past it. Softplus is *not* applied — the relu already makes the output non-negative. The anchor is detached, because it depends on the image being optimized: with gradients flowing through it, the optimizer could lower the loss by raising `d(y, y)` rather than matching the reference.
112
+
113
+ **Backbone downloads.** The frozen backbones are fetched from their public sources on first use (torchvision for AlexNet / VGG, HuggingFace for CLIP / MAE / DINOv3, the DreamSim release for its three ViTs, ~1.5 GB into `~/.cache/fomo/dreamsim`, override with `FOMO_DREAMSIM_CACHE`). **DINOv3 is gated:** accept the license of `facebook/dinov3-vits16plus-pretrain-lvd1689m` on HuggingFace and run `huggingface-cli login` before using `dinov3`.
114
+
115
+ ## Repository layout
116
+
117
+ ```
118
+ fomo/ pip package (metric / loss usage)
119
+ ├── model.py DistanceModel — the seven models
120
+ ├── dinov3.py prediction head (2D-RoPE attention, SwiGLU, registers)
121
+ └── hub.py fomo.load() / fomo.FoMo, checkpoint download
122
+ generate_fomo_dataset.py FLUX img2img data generation
123
+ dataset.py FoMoDataset + paired augmentation, benchmark loaders
124
+ train.py ranked-BCE training
125
+ evaluation.py / evaluate.py PIPAL / TID2013 / CSIQ / LIVE metrics, CLI
126
+ example_usage.py metric + loss demo
127
+ checkpoints/ model card for the Hub repo (the .pth files live on the Hub)
128
+ scripts/
129
+ ├── download_fomo_480k.sh fetch the released 480k training set
130
+ ├── generate_fomo_480k.sh …or regenerate it with FLUX
131
+ ├── setup_benchmarks.sh fetch the four evaluation benchmarks
132
+ └── train.sh train one model with the paper's configuration
133
+ ```
134
+
135
+ ## Environment
136
+
137
+ ```bash
138
+ conda env create -f environment.yml # env "fomo": torch 2.9.1, transformers 4.57.3, diffusers 0.37.1
139
+ conda activate fomo
140
+ ```
141
+
142
+ Training assumes a bf16-capable GPU (an L40 / A100 class card runs every recipe at batch 64); evaluation runs on one GPU.
143
+
144
+ ## Data
145
+
146
+ **Download the released dataset** (recommended) — 480,000 samples at 512×512, hosted as 240 tar shards (~550 GB) at [JHLew/fomo_480k](https://huggingface.co/datasets/JHLew/fomo_480k):
147
+
148
+ ```bash
149
+ bash scripts/download_fomo_480k.sh # → ./data/fomo/{train/…, index.json}
150
+ ```
151
+
152
+ Each sample is a base image plus two img2img variants at random timesteps `s ∈ [1, 50]` (FLUX.1-dev, 50 steps, guidance 3.5; the variant files are named by `s`). The `s` used in this repository and in the dataset corresponds to `S − s` in the paper, with `S = 50`. Half of the bases are generated from a blank canvas (`FLUX_*`), half are ImageNet-1k crops (`IN1K_*`). `index.json` lists `{"base": …, "variants": […]}` with paths relative to the dataset root.
153
+
154
+ **Or regenerate it** — this is the data-generation pipeline, the core of the method:
155
+
156
+ ```bash
157
+ huggingface-cli login # FLUX.1-dev is gated
158
+ bash scripts/generate_fomo_480k.sh # STAGE=scratch|in1k|both, shard with IDX_FROM / IDX_TO
159
+ ```
160
+
161
+ `generate_fomo_dataset.py` writes `<out>/train/<TAG>_<idx>/{base.png, <t1>.png, <t2>.png}` and appends to `index.json`. The IN1K stage needs ImageNet-1k at `./imagenet-1k/train/<class>/*.JPEG`. Generation is expensive (2–3 FLUX calls per sample); shard the index range across GPUs.
162
+
163
+ **Benchmarks:**
164
+
165
+ ```bash
166
+ bash scripts/setup_benchmarks.sh # PIPAL, TID2013, CSIQ, LIVE → ./benchmarks/
167
+ ```
168
+
169
+ ## Training
170
+
171
+ One command trains a model with the paper's configuration and evaluates it on the four benchmarks after every epoch:
172
+
173
+ ```bash
174
+ bash scripts/train.sh dino # lpips_alex | lpips_vgg | dists | dino | clip | mae | dreamsim
175
+ ```
176
+
177
+ which runs
178
+
179
+ ```bash
180
+ python train.py --exp_name dino --backbone dino \
181
+ --dataroot ./data/fomo --train_index_file ./data/fomo/index.json \
182
+ --epochs 3 --batch_size 64 --lr 1e-4 --min_crop_size 64 --max_crop_size 256
183
+ ```
184
+
185
+ Each sample yields one training pair: two of its three images in random order (or, with probability 1/51, an image paired with itself), labelled with the FLUX-space value of the larger timestep `s` of the two, recomputed for the sampled resolution. The ranked-BCE loss scores every ordered pair of samples in the batch against this label ordering. Settings:
186
+
187
+ - `lpips_alex` / `lpips_vgg` / `dists`: `--lr 2e-4`, fixed crops `--min_crop_size 256 --max_crop_size 256`.
188
+ - `dino` / `clip` / `mae`: `--lr 1e-4`, random 64–256 crops batched by zero-padding + attention masking.
189
+ - `dreamsim`: `--lr 1e-4`, fixed `--min_crop_size 224 --max_crop_size 224` (fixed-resolution ensemble).
190
+ - Benchmarks are evaluated after every epoch with the **EMA weights at native resolution**; the final epoch is what is reported. Outputs go to `experiments/<exp_name>/` (`ckpt_latest.pt`, `metrics.json`, `train.log`, TensorBoard); rerunning the same command resumes.
191
+
192
+ The final-epoch numbers of such a run land close to the table below. Any checkpoint can be re-scored on its own:
193
+
194
+ ```bash
195
+ python evaluate.py --model dinov3 # released weights
196
+ python evaluate.py --model dinov3 --checkpoint experiments/dino/ckpt_latest.pt # your run
197
+ ```
198
+
199
+ ### Results
200
+
201
+ SROCC / KROCC / PLCC of the released checkpoints (native resolution; PLCC after a 5-parameter logistic fit). `python evaluate.py --model <name>` reproduces every cell:
202
+
203
+ | Model | PIPAL | TID2013 | CSIQ | LIVE |
204
+ |---|---|---|---|---|
205
+ | LPIPS-Alex| 0.739 / 0.541 / 0.773 | 0.782 / 0.583 / 0.813 | 0.940 / 0.784 / 0.946 | 0.949 / 0.794 / 0.943 |
206
+ | LPIPS-VGG | 0.691 / 0.503 / 0.739 | 0.659 / 0.486 / 0.746 | 0.852 / 0.665 / 0.880 | 0.918 / 0.740 / 0.918 |
207
+ | DISTS | 0.616 / 0.437 / 0.657 | 0.692 / 0.513 / 0.771 | 0.919 / 0.750 / 0.931 | 0.954 / 0.804 / 0.949 |
208
+ | DINOv3 | 0.705 / 0.504 / 0.709 | 0.711 / 0.524 / 0.769 | 0.810 / 0.626 / 0.874 | 0.897 / 0.721 / 0.913 |
209
+ | CLIP | 0.668 / 0.479 / 0.679 | 0.744 / 0.556 / 0.800 | 0.911 / 0.735 / 0.928 | 0.935 / 0.770 / 0.936 |
210
+ | MAE | 0.644 / 0.453 / 0.634 | 0.674 / 0.495 / 0.681 | 0.817 / 0.625 / 0.830 | 0.919 / 0.752 / 0.926 |
211
+ | DreamSim | 0.790 / 0.585 / 0.779 | 0.806 / 0.610 / 0.836 | 0.894 / 0.710 / 0.905 | 0.933 / 0.773 / 0.936 |
212
+
213
+ ## Citation
214
+
215
+ The paper is under review; citation information will be added here.
216
+
217
+ ## License
218
+
219
+ Apache 2.0 — see [LICENSE](LICENSE). The backbones (DINOv3, CLIP, MAE, DreamSim's ViTs) and the `lpips` / `DISTS-pytorch` / `dreamsim` packages keep their own upstream licenses.
@@ -0,0 +1,196 @@
1
+ # FoMo: Forking Moment in Generative Trajectory as a Perceptual Distance
2
+
3
+ <p align="center">
4
+ <img src="figures/FoMo_main.png" alt="FoMo: data generation from the forking moment of the diffusion trajectory, and ranked-BCE training" width="100%">
5
+ </p>
6
+ <p align="center">
7
+ <img src="figures/FoMo_generated_pairs.png" alt="Examples of generated image pairs at different forking moments" width="100%">
8
+ </p>
9
+
10
+ FoMo trains reference-based perceptual distance metrics **without human labels**. Running a diffusion model (FLUX.1-dev) in img2img mode from a base image, re-entering the trajectory `s` denoising steps before the end, produces a variant whose perceptual deviation from the base grows monotonically with `s` — the *forking moment* of the generative trajectory. The timestep is therefore a free, dense supervision signal: we generate 480k such image sets and train distance models with a pairwise ranking objective on it.
11
+
12
+ Seven models are released, all trained on the same 480k FoMo dataset with the same ranked-BCE objective; only the frozen backbone / trainable part differs:
13
+
14
+ | Name | Architecture | Trained part |
15
+ |---|---|---|
16
+ | `lpips_alex` | LPIPS, AlexNet features | linear calibration weights |
17
+ | `lpips_vgg` | LPIPS, VGG-16 features | linear calibration weights |
18
+ | `dists` | DISTS, VGG-16 features | α / β mixing weights |
19
+ | `dinov3` | frozen DINOv3 ViT-S/16+ + prediction head | 3-layer 2D-RoPE transformer head |
20
+ | `clip` | frozen CLIP ViT-B/32 + prediction head | 3-layer 2D-RoPE transformer head |
21
+ | `mae` | frozen MAE ViT-B/16 + prediction head | 3-layer 2D-RoPE transformer head |
22
+ | `dreamsim` | DreamSim ensemble (DINO + CLIP + OpenCLIP ViT-B/16) | LoRA adapters (r=16) |
23
+
24
+ ## Using the pretrained models
25
+
26
+ ```bash
27
+ pip install fomo-iqa # or, from this repository: pip install -e .
28
+ ```
29
+
30
+ (The distribution is `fomo-iqa` because `fomo` is taken on PyPI; the import name is `fomo`.)
31
+
32
+ ```python
33
+ import fomo
34
+
35
+ # A model is defined by its backbone alone. How the score is presented —
36
+ # `symmetric` and `output` — is chosen per call, so one model serves every use.
37
+
38
+ # --- a CNN model --------------------------------------------------------------
39
+ lpips_alex = fomo.FoMo('lpips_alex')
40
+ d = lpips_alex(img_ref, img_test) # [B]; lower = more similar
41
+ # already non-negative with d(x, x) = 0,
42
+ # and symmetric by construction, so
43
+ # `symmetric` and 'distance' change nothing
44
+
45
+ # --- a prediction-head model --------------------------------------------------
46
+ dinov3 = fomo.FoMo('dinov3')
47
+ d_raw = dinov3(img_ref, img_test, symmetric=True) # 'raw' (default): the
48
+ # published protocol. A ranking
49
+ # score with an arbitrary zero
50
+ # point, so it may be negative
51
+ d_dist = dinov3(img_ref, img_test, symmetric=True, output='distance') # non-negative, d(x, x) ≈ 0,
52
+ # LPIPS-style. Ranks pairs
53
+ # identically to 'raw'
54
+ d_asym = dinov3(img_ref, img_test, symmetric=False) # single order s(x, y)
55
+
56
+ # `symmetric=True` is the default and only affects dinov3 / clip / mae, where the
57
+ # head reads the two images as one sequence: it averages both argument orders
58
+ # from a single backbone pass.
59
+
60
+ # --- as a perceptual loss ------------------------------------------------------
61
+ # differentiable w.r.t. the inputs. output='loss' is hinged at the identity
62
+ # level, so optimization settles once the images are as close as identical
63
+ # instead of continuing past that point.
64
+ loss = dinov3(prediction, target, output='loss').mean()
65
+ loss.backward()
66
+ ```
67
+
68
+ `fomo.load(name)` returns the underlying `DistanceModel` (method `eval_distance`), and `checkpoint='path/to/file.pth'` loads a local file — including a `ckpt_latest.pt` produced by `train.py` (its EMA weights are used). `python example_usage.py --model dinov3 --mode metric|loss` is a runnable demo.
69
+
70
+ **Inputs.** Float tensors `[B, 3, H, W]` in `[0, 1]`. Do **not** normalize — each model applies its own preprocessing (ImageNet statistics for DINOv3 / MAE, CLIP statistics for CLIP, `[-1, 1]` for LPIPS, raw for DISTS, bicubic resize to 224 for DreamSim). Both images of a pair must share a spatial size; any size works (the ViT models zero-pad to their patch grid). Benchmarks are scored at native resolution.
71
+
72
+ **Distance options.**
73
+
74
+ - `lpips_alex`, `lpips_vgg`, `dists` and `dreamsim` compute a symmetric distance directly (DreamSim as the cosine distance of its embeddings). `dinov3`, `clip` and `mae` read the two images as one concatenated token sequence and output a scalar for that ordered pair.
75
+ - `symmetric` (default `True`): for `dinov3` / `clip` / `mae` the output `s(x, y)` need not equal `s(y, x)`, so the score is `½ [s(x, y) + s(y, x)]`, both orders from a single backbone pass. `symmetric=False` returns the single order `s(x, y)`.
76
+ - `output` (default `'raw'`): which of three presentations the score is returned in. `'raw'` and `'distance'` are the same metric in two scales — softplus is strictly increasing, so they rank every pair identically (SROCC and KROCC agree to the last digit). `'loss'` subtracts a per-pair quantity and is shaped for optimization rather than for ranking.
77
+
78
+ | `output` | what it returns | use it for |
79
+ |---|---|---|
80
+ | `'raw'` (default) | the model output, unchanged | reproducing the published numbers |
81
+ | `'distance'` | non-negative, `d(x, x) ≈ 0` | a drop-in LPIPS-style metric |
82
+ | `'loss'` | `relu( d(x, y) − max(d(x, x), d(y, y)) )` | a perceptual loss / image optimization |
83
+
84
+ `'raw'` is the protocol every published number was computed under. For `dinov3` / `clip` / `mae` it is a ranking score whose zero point is arbitrary, so it may be negative; `lpips_alex`, `lpips_vgg`, `dists` and `dreamsim` return a non-negative distance with `d(x, x) = 0` directly.
85
+
86
+ `'distance'` applies softplus to `dinov3` / `clip` / `mae` — mapping their identity level to `≈ 0` and giving a positive output everywhere, with no calibration constant to fit or ship — and leaves the other four untouched, since they already have an exact `d(x, x) = 0` (softplus would move it to `log 2 ≈ 0.693`). The rule differs by model family so that the *semantics* are uniform: all seven are non-negative with `d(x, x) ≈ 0`. Rankings are identical to `'raw'`; use `'raw'` to reproduce the published numbers exactly.
87
+
88
+ `'loss'` is a hinge whose floor sits at the per-pair identity level: full gradient while the images differ, and zero once they are as close as identical, so optimization stops there rather than pushing past it. Softplus is *not* applied — the relu already makes the output non-negative. The anchor is detached, because it depends on the image being optimized: with gradients flowing through it, the optimizer could lower the loss by raising `d(y, y)` rather than matching the reference.
89
+
90
+ **Backbone downloads.** The frozen backbones are fetched from their public sources on first use (torchvision for AlexNet / VGG, HuggingFace for CLIP / MAE / DINOv3, the DreamSim release for its three ViTs, ~1.5 GB into `~/.cache/fomo/dreamsim`, override with `FOMO_DREAMSIM_CACHE`). **DINOv3 is gated:** accept the license of `facebook/dinov3-vits16plus-pretrain-lvd1689m` on HuggingFace and run `huggingface-cli login` before using `dinov3`.
91
+
92
+ ## Repository layout
93
+
94
+ ```
95
+ fomo/ pip package (metric / loss usage)
96
+ ├── model.py DistanceModel — the seven models
97
+ ├── dinov3.py prediction head (2D-RoPE attention, SwiGLU, registers)
98
+ └── hub.py fomo.load() / fomo.FoMo, checkpoint download
99
+ generate_fomo_dataset.py FLUX img2img data generation
100
+ dataset.py FoMoDataset + paired augmentation, benchmark loaders
101
+ train.py ranked-BCE training
102
+ evaluation.py / evaluate.py PIPAL / TID2013 / CSIQ / LIVE metrics, CLI
103
+ example_usage.py metric + loss demo
104
+ checkpoints/ model card for the Hub repo (the .pth files live on the Hub)
105
+ scripts/
106
+ ├── download_fomo_480k.sh fetch the released 480k training set
107
+ ├── generate_fomo_480k.sh …or regenerate it with FLUX
108
+ ├── setup_benchmarks.sh fetch the four evaluation benchmarks
109
+ └── train.sh train one model with the paper's configuration
110
+ ```
111
+
112
+ ## Environment
113
+
114
+ ```bash
115
+ conda env create -f environment.yml # env "fomo": torch 2.9.1, transformers 4.57.3, diffusers 0.37.1
116
+ conda activate fomo
117
+ ```
118
+
119
+ Training assumes a bf16-capable GPU (an L40 / A100 class card runs every recipe at batch 64); evaluation runs on one GPU.
120
+
121
+ ## Data
122
+
123
+ **Download the released dataset** (recommended) — 480,000 samples at 512×512, hosted as 240 tar shards (~550 GB) at [JHLew/fomo_480k](https://huggingface.co/datasets/JHLew/fomo_480k):
124
+
125
+ ```bash
126
+ bash scripts/download_fomo_480k.sh # → ./data/fomo/{train/…, index.json}
127
+ ```
128
+
129
+ Each sample is a base image plus two img2img variants at random timesteps `s ∈ [1, 50]` (FLUX.1-dev, 50 steps, guidance 3.5; the variant files are named by `s`). The `s` used in this repository and in the dataset corresponds to `S − s` in the paper, with `S = 50`. Half of the bases are generated from a blank canvas (`FLUX_*`), half are ImageNet-1k crops (`IN1K_*`). `index.json` lists `{"base": …, "variants": […]}` with paths relative to the dataset root.
130
+
131
+ **Or regenerate it** — this is the data-generation pipeline, the core of the method:
132
+
133
+ ```bash
134
+ huggingface-cli login # FLUX.1-dev is gated
135
+ bash scripts/generate_fomo_480k.sh # STAGE=scratch|in1k|both, shard with IDX_FROM / IDX_TO
136
+ ```
137
+
138
+ `generate_fomo_dataset.py` writes `<out>/train/<TAG>_<idx>/{base.png, <t1>.png, <t2>.png}` and appends to `index.json`. The IN1K stage needs ImageNet-1k at `./imagenet-1k/train/<class>/*.JPEG`. Generation is expensive (2–3 FLUX calls per sample); shard the index range across GPUs.
139
+
140
+ **Benchmarks:**
141
+
142
+ ```bash
143
+ bash scripts/setup_benchmarks.sh # PIPAL, TID2013, CSIQ, LIVE → ./benchmarks/
144
+ ```
145
+
146
+ ## Training
147
+
148
+ One command trains a model with the paper's configuration and evaluates it on the four benchmarks after every epoch:
149
+
150
+ ```bash
151
+ bash scripts/train.sh dino # lpips_alex | lpips_vgg | dists | dino | clip | mae | dreamsim
152
+ ```
153
+
154
+ which runs
155
+
156
+ ```bash
157
+ python train.py --exp_name dino --backbone dino \
158
+ --dataroot ./data/fomo --train_index_file ./data/fomo/index.json \
159
+ --epochs 3 --batch_size 64 --lr 1e-4 --min_crop_size 64 --max_crop_size 256
160
+ ```
161
+
162
+ Each sample yields one training pair: two of its three images in random order (or, with probability 1/51, an image paired with itself), labelled with the FLUX-space value of the larger timestep `s` of the two, recomputed for the sampled resolution. The ranked-BCE loss scores every ordered pair of samples in the batch against this label ordering. Settings:
163
+
164
+ - `lpips_alex` / `lpips_vgg` / `dists`: `--lr 2e-4`, fixed crops `--min_crop_size 256 --max_crop_size 256`.
165
+ - `dino` / `clip` / `mae`: `--lr 1e-4`, random 64–256 crops batched by zero-padding + attention masking.
166
+ - `dreamsim`: `--lr 1e-4`, fixed `--min_crop_size 224 --max_crop_size 224` (fixed-resolution ensemble).
167
+ - Benchmarks are evaluated after every epoch with the **EMA weights at native resolution**; the final epoch is what is reported. Outputs go to `experiments/<exp_name>/` (`ckpt_latest.pt`, `metrics.json`, `train.log`, TensorBoard); rerunning the same command resumes.
168
+
169
+ The final-epoch numbers of such a run land close to the table below. Any checkpoint can be re-scored on its own:
170
+
171
+ ```bash
172
+ python evaluate.py --model dinov3 # released weights
173
+ python evaluate.py --model dinov3 --checkpoint experiments/dino/ckpt_latest.pt # your run
174
+ ```
175
+
176
+ ### Results
177
+
178
+ SROCC / KROCC / PLCC of the released checkpoints (native resolution; PLCC after a 5-parameter logistic fit). `python evaluate.py --model <name>` reproduces every cell:
179
+
180
+ | Model | PIPAL | TID2013 | CSIQ | LIVE |
181
+ |---|---|---|---|---|
182
+ | LPIPS-Alex| 0.739 / 0.541 / 0.773 | 0.782 / 0.583 / 0.813 | 0.940 / 0.784 / 0.946 | 0.949 / 0.794 / 0.943 |
183
+ | LPIPS-VGG | 0.691 / 0.503 / 0.739 | 0.659 / 0.486 / 0.746 | 0.852 / 0.665 / 0.880 | 0.918 / 0.740 / 0.918 |
184
+ | DISTS | 0.616 / 0.437 / 0.657 | 0.692 / 0.513 / 0.771 | 0.919 / 0.750 / 0.931 | 0.954 / 0.804 / 0.949 |
185
+ | DINOv3 | 0.705 / 0.504 / 0.709 | 0.711 / 0.524 / 0.769 | 0.810 / 0.626 / 0.874 | 0.897 / 0.721 / 0.913 |
186
+ | CLIP | 0.668 / 0.479 / 0.679 | 0.744 / 0.556 / 0.800 | 0.911 / 0.735 / 0.928 | 0.935 / 0.770 / 0.936 |
187
+ | MAE | 0.644 / 0.453 / 0.634 | 0.674 / 0.495 / 0.681 | 0.817 / 0.625 / 0.830 | 0.919 / 0.752 / 0.926 |
188
+ | DreamSim | 0.790 / 0.585 / 0.779 | 0.806 / 0.610 / 0.836 | 0.894 / 0.710 / 0.905 | 0.933 / 0.773 / 0.936 |
189
+
190
+ ## Citation
191
+
192
+ The paper is under review; citation information will be added here.
193
+
194
+ ## License
195
+
196
+ Apache 2.0 — see [LICENSE](LICENSE). The backbones (DINOv3, CLIP, MAE, DreamSim's ViTs) and the `lpips` / `DISTS-pytorch` / `dreamsim` packages keep their own upstream licenses.
@@ -0,0 +1,28 @@
1
+ """
2
+ FoMo — perceptual image distance metrics trained on diffusion-generated
3
+ (FLUX.1-dev) image pairs.
4
+
5
+ import fomo
6
+ metric = fomo.FoMo('dinov3') # downloads + caches the weights
7
+ d = metric(img_ref, img_test) # [B]; lower = more similar
8
+
9
+ Models: lpips_alex, lpips_vgg, dists, dinov3, clip, mae, dreamsim.
10
+ Inputs: float tensors [B, 3, H, W] in [0, 1], not pre-normalized.
11
+ A model is defined by its backbone alone; the score presentation is chosen per
12
+ call. symmetric (default True) averages both argument orders for the
13
+ prediction-head models; output selects one of three presentations —
14
+
15
+ 'raw' (default) the model output; the protocol the published
16
+ numbers use. The prediction-head models (dinov3 / clip / mae)
17
+ score pairs with a ranking value whose zero point is arbitrary,
18
+ so it may be negative.
19
+ 'distance' non-negative with d(x, x) ~ 0, for drop-in LPIPS-style use;
20
+ ranks pairs identically to 'raw'.
21
+ 'loss' hinged at the identity level, for use as a perceptual loss.
22
+ """
23
+
24
+ from fomo.hub import MODELS, FoMo, load
25
+ from fomo.model import DistanceModel
26
+
27
+ __version__ = '0.1.0'
28
+ __all__ = ['FoMo', 'DistanceModel', 'load', 'MODELS', '__version__']