fomo-iqa 1.0.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-1.0.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,172 @@
1
+ Metadata-Version: 2.4
2
+ Name: fomo-iqa
3
+ Version: 1.0.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: Jihyong 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
+ 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.
27
+
28
+ 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:
29
+
30
+ | Name | Architecture | Trained part |
31
+ |---|---|---|
32
+ | `lpips_alex` | LPIPS, AlexNet features | linear calibration weights |
33
+ | `lpips_vgg` | LPIPS, VGG-16 features | linear calibration weights |
34
+ | `dists` | DISTS, VGG-16 features | α / β mixing weights |
35
+ | `dinov3` | frozen DINOv3 ViT-S/16+ + prediction head | 3-layer 2D-RoPE transformer head |
36
+ | `clip` | frozen CLIP ViT-B/32 + prediction head | 3-layer 2D-RoPE transformer head |
37
+ | `mae` | frozen MAE ViT-B/16 + prediction head | 3-layer 2D-RoPE transformer head |
38
+ | `dreamsim` | DreamSim ensemble (DINO + CLIP + OpenCLIP ViT-B/16) | LoRA adapters (r=16) |
39
+
40
+ ## Using the pretrained models
41
+
42
+ ```bash
43
+ pip install fomo-iqa # or, from this repository: pip install -e .
44
+ ```
45
+
46
+ (The distribution is `fomo-iqa` because `fomo` is taken on PyPI; the import name is `fomo`.)
47
+
48
+ ```python
49
+ import fomo
50
+
51
+ metric = fomo.FoMo('dinov3') # downloads + caches the checkpoint (HF Hub: JHLew/FoMo)
52
+ d = metric(img_ref, img_test) # [B] distances; lower = more similar
53
+
54
+ # as a perceptual loss, LPIPS-style — differentiable w.r.t. the inputs
55
+ loss = metric(prediction, target).mean()
56
+ loss.backward()
57
+ ```
58
+
59
+ `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.
60
+
61
+ **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.
62
+
63
+ **What the distance is.** `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, so their output `s(x, y)` need not equal `s(y, x)`; the score is `½ [s(x, y) + s(y, x)]`, both orders from a single backbone pass (`symmetric=False` returns the single order). Training and evaluation use the raw model output, so scores can be negative; `zeroing=True` (`fomo.FoMo(name, zeroing=True)` or per call) returns `relu( d(x, y) − max(d(x, x), d(y, y)) )` instead, a non-negative distance with `d(x, x) = 0`.
64
+
65
+ **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`.
66
+
67
+ ## Repository layout
68
+
69
+ ```
70
+ fomo/ pip package (metric / loss usage)
71
+ ├── model.py DistanceModel — the seven models
72
+ ├── dinov3.py prediction head (2D-RoPE attention, SwiGLU, registers)
73
+ └── hub.py fomo.load() / fomo.FoMo, checkpoint download
74
+ generate_fomo_dataset.py FLUX img2img data generation
75
+ dataset.py FoMoDataset + paired augmentation, benchmark loaders
76
+ train.py ranked-BCE training
77
+ evaluation.py / evaluate.py PIPAL / TID2013 / CSIQ / LIVE metrics, CLI
78
+ example_usage.py metric + loss demo
79
+ checkpoints/ released weights (metadata + model card tracked; .pth on the Hub)
80
+ scripts/
81
+ ├── download_fomo_480k.sh fetch the released 480k training set
82
+ ├── generate_fomo_480k.sh …or regenerate it with FLUX
83
+ ├── setup_benchmarks.sh fetch the four evaluation benchmarks
84
+ └── train.sh train one model with the paper's configuration
85
+ ```
86
+
87
+ ## Environment
88
+
89
+ ```bash
90
+ conda env create -f environment.yml # env "fomo": torch 2.9.1, transformers 4.57.3, diffusers 0.37.1
91
+ conda activate fomo
92
+ ```
93
+
94
+ Training assumes a bf16-capable GPU (an L40 / A100 class card runs every recipe at batch 64); evaluation runs on one GPU.
95
+
96
+ ## Data
97
+
98
+ **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):
99
+
100
+ ```bash
101
+ bash scripts/download_fomo_480k.sh # → ./data/fomo/{train/…, index.json}
102
+ ```
103
+
104
+ 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.
105
+
106
+ **Or regenerate it** — this is the data-generation pipeline, the core of the method:
107
+
108
+ ```bash
109
+ huggingface-cli login # FLUX.1-dev is gated
110
+ bash scripts/generate_fomo_480k.sh # STAGE=scratch|in1k|both, shard with IDX_FROM / IDX_TO
111
+ ```
112
+
113
+ `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.
114
+
115
+ **Benchmarks:**
116
+
117
+ ```bash
118
+ bash scripts/setup_benchmarks.sh # PIPAL, TID2013, CSIQ, LIVE → ./benchmarks/
119
+ ```
120
+
121
+ ## Training
122
+
123
+ One command trains a model with the paper's configuration and evaluates it on the four benchmarks after every epoch:
124
+
125
+ ```bash
126
+ bash scripts/train.sh dino # lpips_alex | lpips_vgg | dists | dino | clip | mae | dreamsim
127
+ ```
128
+
129
+ which runs
130
+
131
+ ```bash
132
+ python train.py --exp_name dino --backbone dino \
133
+ --dataroot ./data/fomo --train_index_file ./data/fomo/index.json \
134
+ --epochs 3 --batch_size 64 --lr 1e-4 --min_crop_size 64 --max_crop_size 256
135
+ ```
136
+
137
+ 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:
138
+
139
+ - `lpips_alex` / `lpips_vgg` / `dists`: `--lr 2e-4`, fixed crops `--min_crop_size 256 --max_crop_size 256`.
140
+ - `dino` / `clip` / `mae`: `--lr 1e-4`, random 64–256 crops batched by zero-padding + attention masking.
141
+ - `dreamsim`: `--lr 1e-4`, fixed `--min_crop_size 224 --max_crop_size 224` (fixed-resolution ensemble).
142
+ - 3 epochs (22.5k updates), batch 64, constant lr, weight decay 1e-8, EMA 0.999, bf16 autocast.
143
+ - 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.
144
+
145
+ The final-epoch numbers of such a run land close to the table below. Any checkpoint can be re-scored on its own:
146
+
147
+ ```bash
148
+ python evaluate.py --model dinov3 # released weights
149
+ python evaluate.py --model dinov3 --checkpoint experiments/dino/ckpt_latest.pt # your run
150
+ ```
151
+
152
+ ### Results
153
+
154
+ SROCC / KROCC / PLCC of the released checkpoints (native resolution; PLCC after a 5-parameter logistic fit). `python evaluate.py --model <name>` reproduces every cell:
155
+
156
+ | Model | PIPAL | TID2013 | CSIQ | LIVE |
157
+ |---|---|---|---|---|
158
+ | 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 |
159
+ | 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 |
160
+ | 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 |
161
+ | 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 |
162
+ | 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 |
163
+ | 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 |
164
+ | 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 |
165
+
166
+ ## Citation
167
+
168
+ The paper is under review; citation information will be added here.
169
+
170
+ ## License
171
+
172
+ 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,149 @@
1
+ # FoMo: Forking Moment in Generative Trajectory as a Perceptual Distance
2
+
3
+ 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.
4
+
5
+ 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:
6
+
7
+ | Name | Architecture | Trained part |
8
+ |---|---|---|
9
+ | `lpips_alex` | LPIPS, AlexNet features | linear calibration weights |
10
+ | `lpips_vgg` | LPIPS, VGG-16 features | linear calibration weights |
11
+ | `dists` | DISTS, VGG-16 features | α / β mixing weights |
12
+ | `dinov3` | frozen DINOv3 ViT-S/16+ + prediction head | 3-layer 2D-RoPE transformer head |
13
+ | `clip` | frozen CLIP ViT-B/32 + prediction head | 3-layer 2D-RoPE transformer head |
14
+ | `mae` | frozen MAE ViT-B/16 + prediction head | 3-layer 2D-RoPE transformer head |
15
+ | `dreamsim` | DreamSim ensemble (DINO + CLIP + OpenCLIP ViT-B/16) | LoRA adapters (r=16) |
16
+
17
+ ## Using the pretrained models
18
+
19
+ ```bash
20
+ pip install fomo-iqa # or, from this repository: pip install -e .
21
+ ```
22
+
23
+ (The distribution is `fomo-iqa` because `fomo` is taken on PyPI; the import name is `fomo`.)
24
+
25
+ ```python
26
+ import fomo
27
+
28
+ metric = fomo.FoMo('dinov3') # downloads + caches the checkpoint (HF Hub: JHLew/FoMo)
29
+ d = metric(img_ref, img_test) # [B] distances; lower = more similar
30
+
31
+ # as a perceptual loss, LPIPS-style — differentiable w.r.t. the inputs
32
+ loss = metric(prediction, target).mean()
33
+ loss.backward()
34
+ ```
35
+
36
+ `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.
37
+
38
+ **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.
39
+
40
+ **What the distance is.** `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, so their output `s(x, y)` need not equal `s(y, x)`; the score is `½ [s(x, y) + s(y, x)]`, both orders from a single backbone pass (`symmetric=False` returns the single order). Training and evaluation use the raw model output, so scores can be negative; `zeroing=True` (`fomo.FoMo(name, zeroing=True)` or per call) returns `relu( d(x, y) − max(d(x, x), d(y, y)) )` instead, a non-negative distance with `d(x, x) = 0`.
41
+
42
+ **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`.
43
+
44
+ ## Repository layout
45
+
46
+ ```
47
+ fomo/ pip package (metric / loss usage)
48
+ ├── model.py DistanceModel — the seven models
49
+ ├── dinov3.py prediction head (2D-RoPE attention, SwiGLU, registers)
50
+ └── hub.py fomo.load() / fomo.FoMo, checkpoint download
51
+ generate_fomo_dataset.py FLUX img2img data generation
52
+ dataset.py FoMoDataset + paired augmentation, benchmark loaders
53
+ train.py ranked-BCE training
54
+ evaluation.py / evaluate.py PIPAL / TID2013 / CSIQ / LIVE metrics, CLI
55
+ example_usage.py metric + loss demo
56
+ checkpoints/ released weights (metadata + model card tracked; .pth on the Hub)
57
+ scripts/
58
+ ├── download_fomo_480k.sh fetch the released 480k training set
59
+ ├── generate_fomo_480k.sh …or regenerate it with FLUX
60
+ ├── setup_benchmarks.sh fetch the four evaluation benchmarks
61
+ └── train.sh train one model with the paper's configuration
62
+ ```
63
+
64
+ ## Environment
65
+
66
+ ```bash
67
+ conda env create -f environment.yml # env "fomo": torch 2.9.1, transformers 4.57.3, diffusers 0.37.1
68
+ conda activate fomo
69
+ ```
70
+
71
+ Training assumes a bf16-capable GPU (an L40 / A100 class card runs every recipe at batch 64); evaluation runs on one GPU.
72
+
73
+ ## Data
74
+
75
+ **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):
76
+
77
+ ```bash
78
+ bash scripts/download_fomo_480k.sh # → ./data/fomo/{train/…, index.json}
79
+ ```
80
+
81
+ 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.
82
+
83
+ **Or regenerate it** — this is the data-generation pipeline, the core of the method:
84
+
85
+ ```bash
86
+ huggingface-cli login # FLUX.1-dev is gated
87
+ bash scripts/generate_fomo_480k.sh # STAGE=scratch|in1k|both, shard with IDX_FROM / IDX_TO
88
+ ```
89
+
90
+ `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.
91
+
92
+ **Benchmarks:**
93
+
94
+ ```bash
95
+ bash scripts/setup_benchmarks.sh # PIPAL, TID2013, CSIQ, LIVE → ./benchmarks/
96
+ ```
97
+
98
+ ## Training
99
+
100
+ One command trains a model with the paper's configuration and evaluates it on the four benchmarks after every epoch:
101
+
102
+ ```bash
103
+ bash scripts/train.sh dino # lpips_alex | lpips_vgg | dists | dino | clip | mae | dreamsim
104
+ ```
105
+
106
+ which runs
107
+
108
+ ```bash
109
+ python train.py --exp_name dino --backbone dino \
110
+ --dataroot ./data/fomo --train_index_file ./data/fomo/index.json \
111
+ --epochs 3 --batch_size 64 --lr 1e-4 --min_crop_size 64 --max_crop_size 256
112
+ ```
113
+
114
+ 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:
115
+
116
+ - `lpips_alex` / `lpips_vgg` / `dists`: `--lr 2e-4`, fixed crops `--min_crop_size 256 --max_crop_size 256`.
117
+ - `dino` / `clip` / `mae`: `--lr 1e-4`, random 64–256 crops batched by zero-padding + attention masking.
118
+ - `dreamsim`: `--lr 1e-4`, fixed `--min_crop_size 224 --max_crop_size 224` (fixed-resolution ensemble).
119
+ - 3 epochs (22.5k updates), batch 64, constant lr, weight decay 1e-8, EMA 0.999, bf16 autocast.
120
+ - 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.
121
+
122
+ The final-epoch numbers of such a run land close to the table below. Any checkpoint can be re-scored on its own:
123
+
124
+ ```bash
125
+ python evaluate.py --model dinov3 # released weights
126
+ python evaluate.py --model dinov3 --checkpoint experiments/dino/ckpt_latest.pt # your run
127
+ ```
128
+
129
+ ### Results
130
+
131
+ SROCC / KROCC / PLCC of the released checkpoints (native resolution; PLCC after a 5-parameter logistic fit). `python evaluate.py --model <name>` reproduces every cell:
132
+
133
+ | Model | PIPAL | TID2013 | CSIQ | LIVE |
134
+ |---|---|---|---|---|
135
+ | 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 |
136
+ | 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 |
137
+ | 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 |
138
+ | 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 |
139
+ | 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 |
140
+ | 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 |
141
+ | 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 |
142
+
143
+ ## Citation
144
+
145
+ The paper is under review; citation information will be added here.
146
+
147
+ ## License
148
+
149
+ 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,21 @@
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
+ Options (constructor or per call): symmetric (default True) averages both
12
+ argument orders for the prediction-head models; zeroing (default False)
13
+ returns relu(d(x, y) − max(d(x, x), d(y, y))) — non-negative, d(x, x) = 0 —
14
+ instead of the raw output.
15
+ """
16
+
17
+ from fomo.hub import MODELS, FoMo, load
18
+ from fomo.model import DistanceModel
19
+
20
+ __version__ = '1.0.0'
21
+ __all__ = ['FoMo', 'DistanceModel', 'load', 'MODELS', '__version__']