sofieneb commited on
Commit
35db080
·
0 Parent(s):

OMNI-small: Scaling Multi-Teacher Distillation for Digital Pathology

Browse files
Files changed (7) hide show
  1. .gitattributes +35 -0
  2. README.md +185 -0
  3. config.json +42 -0
  4. eval_thunder.py +156 -0
  5. model.safetensors +3 -0
  6. modeling_omni.py +394 -0
  7. requirements.txt +6 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ library_name: transformers
4
+ pipeline_tag: image-feature-extraction
5
+ tags:
6
+ - histopathology
7
+ - digital-pathology
8
+ - foundation-model
9
+ - vision-transformer
10
+ - mixture-of-experts
11
+ - knowledge-distillation
12
+ - custom_code
13
+ ---
14
+
15
+ # OMNI-S: Scaling Multi-Teacher Distillation for Digital Pathology
16
+
17
+ ## Model Summary
18
+
19
+ **OMNI-S** is a 28.7M-parameter pathology vision encoder distilled from **10 state-of-the-art pathology foundation models** at once. Instead of compressing all teachers into a single CLS token (vanilla multi-teacher distillation), OMNI learns **one token per teacher**, together with a structured attention mask, Mixture-of-Experts (MoE) layers and a per-teacher contrastive loss. This lets distillation keep improving as more teachers are added.
20
+
21
+ By default the model returns the **average of its 10 teacher-specific tokens**, which is the embedding used for all results below. The individual teacher tokens and the patch tokens can also be returned with a flag.
22
+
23
+ - ⚡ **Efficient**: 5.48 GFLOPs per 224×224 tile
24
+ - 🧠 **Distilled from 10 teachers**: H-optimus-1, Virchow2, UNI2-h, Prov-GigaPath, Kaiko-ViT-B/8, CONCH v1.5, Hibou-L, H0-mini, KEEP, DINOv3-ViT-L/16
25
+ - 📚 **Trained on** 10M tiles from 10k TCGA whole-slide images
26
+
27
+ Other sizes of the collection:
28
+
29
+ | Model | Params | Dim | GFLOPs | Tile LP F1 (%) | Slide LP BAcc (%) |
30
+ | ----- | ------ | --- | ------ | -------------- | ----------------- |
31
+ | [OMNI-T](https://huggingface.co/sofieneb/omni-tiny) | 7.3M | 192 | 1.39 | 83.9 | 63.2 |
32
+ | **OMNI-S (this model)** | 28.7M | 384 | 5.48 | 85.3 | 63.1 |
33
+ | [OMNI-B](https://huggingface.co/sofieneb/omni-base) | 114M | 768 | 21.8 | 87.1 | 63.2 |
34
+ | [OMNI-L](https://huggingface.co/sofieneb/omni-large) | 330M | 1024 | 67.45 | 87.8 | 63.5 |
35
+
36
+
37
+ 📄 **Paper**: [*Scaling Multi-Teacher Distillation for Digital Pathology*](TODO) (NeurIPS 2026 Main Track)
38
+
39
+ ---
40
+
41
+ ## Model Details
42
+
43
+ | | |
44
+ | --- | --- |
45
+ | Architecture | ViT-Small/14 with a MoE tail |
46
+ | Embedding dim | 384 |
47
+ | Depth / heads | 12 blocks / 6 heads |
48
+ | MoE | last 3 blocks, 5 experts, top-2 routing |
49
+ | Teacher tokens | 10 (one per teacher) |
50
+ | Input | 224 × 224 RGB, ImageNet normalization |
51
+ | Patch tokens | 16 × 16 = 256 |
52
+
53
+ ## Results
54
+
55
+ Linear probing on THUNDER (tile level, 13 datasets, TCGA datasets removed) and PathoBench (slide level, 25 CPTAC tasks, mean pooling), plus kNN and 16-shot classification on THUNDER:
56
+
57
+ | Tile LP F1 (%) | Slide LP BAcc (%) | kNN F1 (%) | 16-shot F1 (%) |
58
+ | -------------- | ----------------- | ---------- | -------------- |
59
+ | 85.3 | 63.1 | 82.3 | 78.7 |
60
+
61
+ ---
62
+
63
+ ## Usage
64
+
65
+ ```python
66
+ import torch
67
+ from PIL import Image
68
+ from transformers import AutoModel
69
+
70
+ device = "cuda" if torch.cuda.is_available() else "cpu"
71
+
72
+ # Load OMNI-S
73
+ model = AutoModel.from_pretrained("sofieneb/omni-small", trust_remote_code=True).to(device).eval()
74
+ transform = model.get_transform() # resize to 224 + ImageNet normalization
75
+
76
+ image = Image.open("tile.png").convert("RGB")
77
+ x = transform(image).unsqueeze(0).to(device) # (1, 3, 224, 224)
78
+
79
+ with torch.inference_mode():
80
+ embedding = model(x) # average of the 10 teacher tokens
81
+
82
+ print(embedding.shape) # (1, 384)
83
+ ```
84
+
85
+ ### Teacher tokens and patch tokens
86
+
87
+ ```python
88
+ with torch.inference_mode():
89
+ out = model(x, return_teacher_tokens=True, return_patch_tokens=True)
90
+
91
+ out["embedding"] # (1, 384) average of the teacher tokens (same as model(x))
92
+ out["teacher_tokens"] # (1, 10, 384) one token per teacher
93
+ out["patch_tokens"] # (1, 256, 384) 16 x 16 patch tokens
94
+
95
+ # Teacher order of the tokens
96
+ print(model.teachers)
97
+
98
+ # Example: keep the token of a single teacher
99
+ idx = 0 # position of the teacher you want in model.teachers
100
+ single_teacher = out["teacher_tokens"][:, idx] # (1, 384)
101
+ ```
102
+
103
+ Teacher tokens are well separated and complementary, so the simple average works well out of the box. You can also learn a task-specific weighting of the 10 tokens (see Table 2 of the paper).
104
+
105
+ ### Mixed precision
106
+
107
+ ```python
108
+ with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16):
109
+ embedding = model(x)
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Quick evaluation with THUNDER
115
+
116
+ `eval_thunder.py` wraps the model for the [THUNDER benchmark](https://github.com/MICS-Lab/thunder).
117
+
118
+ Install THUNDER and set its data folder, where datasets, embeddings and results are stored:
119
+
120
+ ```bash
121
+ pip install thunder-bench
122
+ export THUNDER_BASE_DATA_FOLDER=/path/to/thunder_data
123
+ hf download sofieneb/omni-small eval_thunder.py --local-dir .
124
+ ```
125
+
126
+ Then run the benchmark, choosing the datasets with `--datasets`. The datasets are downloaded and their splits generated automatically before benchmarking (add `--no-download` to skip this once they are in place):
127
+
128
+ ```bash
129
+ python eval_thunder.py --datasets <dataset> --tasks knn linear_probing
130
+ ```
131
+
132
+ For example, on MHIST:
133
+
134
+ ```bash
135
+ python eval_thunder.py --datasets mhist --tasks knn linear_probing
136
+ ```
137
+
138
+ Results are written to `$THUNDER_BASE_DATA_FOLDER/outputs/res/<dataset>/omni-small/<task>/`. To collect them in one CSV:
139
+
140
+ ```bash
141
+ thunder results-summary
142
+ ```
143
+ ---
144
+
145
+ ## Offline usage (HPC clusters without internet)
146
+
147
+ If compute nodes don't have internet, **always** run jobs with the offline flags:
148
+
149
+ ```bash
150
+ export HF_HUB_OFFLINE=1
151
+ export TRANSFORMERS_OFFLINE=1
152
+ ```
153
+
154
+ Prepare the model **in advance** on a front-end/login node (with internet):
155
+
156
+ ```bash
157
+ hf download sofieneb/omni-small --local-dir ./omni-small
158
+ ```
159
+
160
+ Then in your offline job/script:
161
+
162
+ ```python
163
+ from transformers import AutoModel
164
+ model = AutoModel.from_pretrained(
165
+ "./omni-small", # local path instead of hub ID
166
+ trust_remote_code=True,
167
+ local_files_only=True, # uses local files only
168
+ )
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Citation
174
+
175
+ If our work contributes to your research, please consider citing our paper:
176
+
177
+ ```bibtex
178
+ @inproceedings{boutaj2026omni,
179
+ author = {Boutaj, Sofi{\`e}ne and Marza, Pierre and Belagali, Varun and
180
+ Samaras, Dimitris and Vakalopoulou, Maria and Christodoulidis, Stergios},
181
+ title = {Scaling Multi-Teacher Distillation for Digital Pathology},
182
+ booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
183
+ year = {2026}
184
+ }
185
+ ```
config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "OmniModel"
4
+ ],
5
+ "model_type": "omni",
6
+ "auto_map": {
7
+ "AutoConfig": "modeling_omni.OmniConfig",
8
+ "AutoModel": "modeling_omni.OmniModel"
9
+ },
10
+ "embed_dim": 384,
11
+ "depth": 12,
12
+ "num_heads": 6,
13
+ "mlp_ratio": 3.0,
14
+ "num_moe_layers": 3,
15
+ "num_experts": 5,
16
+ "moe_top_k": 2,
17
+ "img_size": 224,
18
+ "patch_size": 14,
19
+ "teachers": [
20
+ "dinov3vitl16pretrainlvd1689m",
21
+ "hoptimus1",
22
+ "virchow2",
23
+ "uni2h",
24
+ "provgigapath",
25
+ "kaiko_vitb8",
26
+ "titan",
27
+ "hiboul",
28
+ "h0mini",
29
+ "keep"
30
+ ],
31
+ "image_mean": [
32
+ 0.485,
33
+ 0.456,
34
+ 0.406
35
+ ],
36
+ "image_std": [
37
+ 0.229,
38
+ 0.224,
39
+ 0.225
40
+ ],
41
+ "torch_dtype": "float32"
42
+ }
eval_thunder.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Evaluate OMNI encoders on the THUNDER benchmark (https://github.com/MICS-Lab/thunder).
3
+
4
+ Setup (once):
5
+ pip install thunder-bench
6
+ export THUNDER_BASE_DATA_FOLDER=/path/to/thunder_data # empty folder, THUNDER fills it
7
+
8
+ The requested datasets are downloaded and their splits generated automatically
9
+ (skip this with --no-download once they are in place).
10
+
11
+ Usage (Python API):
12
+ python eval_thunder.py --model base --datasets bach mhist --tasks knn linear_probing
13
+ python eval_thunder.py --model large --datasets pannuke --tasks segmentation
14
+ python eval_thunder.py --model sofieneb/omni-small --datasets bach --tasks knn simple_shot
15
+
16
+ Usage (THUNDER CLI, which instantiates the class below with its defaults):
17
+ OMNI_MODEL=base thunder benchmark custom:eval_thunder.py bach knn
18
+ OMNI_MODEL=base thunder benchmark custom:eval_thunder.py bach linear_probing --loading-mode=embedding_pre_loading
19
+
20
+ Results are written to:
21
+ $THUNDER_BASE_DATA_FOLDER/outputs/res/<dataset>/<model>/<task>/<adaptation_type>/outputs.json
22
+ and can be summarised with:
23
+ thunder results-summary
24
+ """
25
+
26
+ import argparse
27
+ import os
28
+
29
+ import torch
30
+ from thunder import benchmark, download_datasets, generate_splits
31
+ from thunder.models import PretrainedModel
32
+ from transformers import AutoModel
33
+
34
+ # Short names -> Hugging Face repos
35
+ OMNI_MODELS = {
36
+ "tiny": "sofieneb/omni-tiny",
37
+ "small": "sofieneb/omni-small",
38
+ "base": "sofieneb/omni-base",
39
+ "large": "sofieneb/omni-large",
40
+ }
41
+ DEFAULT_MODEL = "small"
42
+
43
+ # Tasks that train on pre-computed embeddings (see the THUNDER examples)
44
+ PRELOADED_TASKS = {"linear_probing", "segmentation", "simple_shot"}
45
+
46
+
47
+ def resolve_model(model: str) -> str:
48
+ """Map 'tiny' / 'small' / 'base' / 'large' to a repo id; pass anything else through (repo id or local folder)."""
49
+ return OMNI_MODELS.get(model, model)
50
+
51
+
52
+ class OmniThunder(PretrainedModel):
53
+ """
54
+ THUNDER wrapper around an OMNI encoder.
55
+
56
+ Linear probing / kNN / SimpleShot use the average of the teacher tokens;
57
+ segmentation uses the patch tokens.
58
+
59
+ Args:
60
+ model (str): 'tiny', 'small', 'base', 'large', a Hugging Face repo id or a local folder.
61
+ Defaults to the OMNI_MODEL environment variable, then to 'base'.
62
+ """
63
+
64
+ def __init__(self, model: str | None = None):
65
+ super().__init__()
66
+ repo_id = resolve_model(model or os.environ.get("OMNI_MODEL", DEFAULT_MODEL))
67
+ self.model = AutoModel.from_pretrained(repo_id, trust_remote_code=True).eval()
68
+ self.name = repo_id.rstrip("/").split("/")[-1] # used by THUNDER to name output folders
69
+ self.emb_dim = self.model.config.embed_dim
70
+ self.vlm = False
71
+ self._transform = self.model.get_transform()
72
+
73
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
74
+ """
75
+ Args:
76
+ x (torch.Tensor): Images of shape (B, 3, 224, 224).
77
+
78
+ Returns:
79
+ torch.Tensor: Tile embeddings of shape (B, D).
80
+ """
81
+ return self.model(x)
82
+
83
+ def get_transform(self):
84
+ """Returns the image preprocessing used by OMNI."""
85
+ return self._transform
86
+
87
+ def get_linear_probing_embeddings(self, x: torch.Tensor) -> torch.Tensor:
88
+ """
89
+ Args:
90
+ x (torch.Tensor): Images of shape (B, 3, 224, 224).
91
+
92
+ Returns:
93
+ torch.Tensor: Average of the teacher tokens, shape (B, D).
94
+ """
95
+ return self.model(x)
96
+
97
+ def get_segmentation_embeddings(self, x: torch.Tensor) -> torch.Tensor:
98
+ """
99
+ Args:
100
+ x (torch.Tensor): Images of shape (B, 3, 224, 224).
101
+
102
+ Returns:
103
+ torch.Tensor: Patch tokens of shape (B, 256, D).
104
+ """
105
+ return self.model(x, return_patch_tokens=True)["patch_tokens"]
106
+
107
+
108
+ def main():
109
+ parser = argparse.ArgumentParser(description="Evaluate OMNI encoders on THUNDER.")
110
+ parser.add_argument(
111
+ "--model",
112
+ default=os.environ.get("OMNI_MODEL", DEFAULT_MODEL),
113
+ help="tiny, small, base, large, a Hugging Face repo id or a local folder (default: base).",
114
+ )
115
+ parser.add_argument("--datasets", nargs="+", default=["bach"], help="THUNDER dataset names.")
116
+ parser.add_argument(
117
+ "--tasks",
118
+ nargs="+",
119
+ default=["knn", "linear_probing"],
120
+ help="THUNDER tasks: knn, linear_probing, simple_shot, segmentation, "
121
+ "transformation_invariance, adversarial_attack.",
122
+ )
123
+ parser.add_argument(
124
+ "--no-download",
125
+ dest="download",
126
+ action="store_false",
127
+ help="Skip downloading the datasets and generating their splits (done by default).",
128
+ )
129
+ parser.add_argument(
130
+ "--no-recompute",
131
+ action="store_true",
132
+ help="Re-use embeddings already computed by a previous run.",
133
+ )
134
+ args = parser.parse_args()
135
+
136
+ if not os.environ.get("THUNDER_BASE_DATA_FOLDER"):
137
+ raise SystemExit("Set THUNDER_BASE_DATA_FOLDER first, e.g. export THUNDER_BASE_DATA_FOLDER=/path/to/thunder_data")
138
+
139
+ if args.download:
140
+ download_datasets(args.datasets)
141
+ generate_splits(args.datasets)
142
+
143
+ device = "cuda" if torch.cuda.is_available() else "cpu"
144
+ model = OmniThunder(args.model).to(device).eval()
145
+ print(f"Model: {model.name} (dim {model.emb_dim}) on {device}")
146
+
147
+ for dataset in args.datasets:
148
+ # Embeddings are computed once, then re-used by every task.
149
+ benchmark(model, dataset=dataset, task="pre_computing_embeddings", recomp_embs=not args.no_recompute)
150
+ for task in args.tasks:
151
+ extra = {"loading_mode": "embedding_pre_loading"} if task in PRELOADED_TASKS else {}
152
+ benchmark(model, dataset=dataset, task=task, retrain_model=True, **extra)
153
+
154
+
155
+ if __name__ == "__main__":
156
+ main()
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5d7fbce1f4a60d6e0db5af0400d93d05d108967f509d5df4a1d3ccee3dc6cce
3
+ size 114901000
modeling_omni.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OMNI: Scaling Multi-Teacher Distillation for Digital Pathology.
3
+
4
+ This file contains everything needed to run an OMNI vision encoder with
5
+ Hugging Face `transformers` (`trust_remote_code=True`):
6
+
7
+ - OmniConfig : architecture hyper-parameters (read from `config.json`).
8
+ - OmniModel : ViT backbone with a Mixture-of-Experts (MoE) tail and one
9
+ learnable token per teacher.
10
+
11
+ The model takes a batch of 224x224 RGB tiles and returns, by default, a single
12
+ embedding per tile: the average of its 10 teacher-specific tokens.
13
+
14
+ Example:
15
+ >>> from transformers import AutoModel
16
+ >>> model = AutoModel.from_pretrained("<org>/omni-base", trust_remote_code=True).eval()
17
+ >>> transform = model.get_transform()
18
+ >>> x = transform(pil_image).unsqueeze(0) # (1, 3, 224, 224)
19
+ >>> emb = model(x) # (1, D)
20
+ >>> out = model(x, return_teacher_tokens=True)
21
+ >>> out["embedding"], out["teacher_tokens"] # (1, D), (1, 10, D)
22
+ """
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+ from transformers import PretrainedConfig, PreTrainedModel
28
+
29
+
30
+ # ============================================================
31
+ # Configuration
32
+ # ============================================================
33
+
34
+
35
+ class OmniConfig(PretrainedConfig):
36
+ """
37
+ Configuration of an OMNI encoder.
38
+
39
+ Args:
40
+ embed_dim (int): Token dimension D.
41
+ depth (int): Total number of transformer blocks.
42
+ num_heads (int): Number of attention heads.
43
+ mlp_ratio (float): Hidden size of every feed-forward network / expert, as a multiple of D.
44
+ num_moe_layers (int): Number of final blocks whose FFN is a Mixture-of-Experts layer.
45
+ num_experts (int): Number of experts in each MoE layer.
46
+ moe_top_k (int): Number of experts selected per token.
47
+ img_size (int): Input resolution (square images).
48
+ patch_size (int): Patch size of the patch embedding.
49
+ teachers (list[str]): Teacher names, in the order of the teacher tokens.
50
+ image_mean (list[float]): Normalization mean used at training time.
51
+ image_std (list[float]): Normalization std used at training time.
52
+ """
53
+
54
+ model_type = "omni"
55
+
56
+ def __init__(
57
+ self,
58
+ embed_dim: int = 768,
59
+ depth: int = 12,
60
+ num_heads: int = 12,
61
+ mlp_ratio: float = 3.0,
62
+ num_moe_layers: int = 3,
63
+ num_experts: int = 5,
64
+ moe_top_k: int = 2,
65
+ img_size: int = 224,
66
+ patch_size: int = 14,
67
+ teachers: list = None,
68
+ image_mean: list = (0.485, 0.456, 0.406),
69
+ image_std: list = (0.229, 0.224, 0.225),
70
+ **kwargs,
71
+ ):
72
+ self.embed_dim = embed_dim
73
+ self.depth = depth
74
+ self.num_heads = num_heads
75
+ self.mlp_ratio = mlp_ratio
76
+ self.num_moe_layers = num_moe_layers
77
+ self.num_experts = num_experts
78
+ self.moe_top_k = moe_top_k # not `top_k`: that name is reserved for generation in transformers 4.x
79
+ self.img_size = img_size
80
+ self.patch_size = patch_size
81
+ self.teachers = list(teachers) if teachers is not None else []
82
+ self.image_mean = list(image_mean)
83
+ self.image_std = list(image_std)
84
+ super().__init__(**kwargs)
85
+
86
+
87
+ # ============================================================
88
+ # Building blocks
89
+ # ============================================================
90
+
91
+
92
+ class Attention(nn.Module):
93
+ """
94
+ Multi-head self-attention using PyTorch's fused scaled-dot-product attention.
95
+
96
+ Args:
97
+ dim (int): Token dimension.
98
+ num_heads (int): Number of attention heads.
99
+ qkv_bias (bool): Whether the query/key/value projection has a bias.
100
+ """
101
+
102
+ def __init__(self, dim: int, num_heads: int, qkv_bias: bool):
103
+ super().__init__()
104
+ self.num_heads = num_heads
105
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
106
+ self.proj = nn.Linear(dim, dim)
107
+
108
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor) -> torch.Tensor:
109
+ """
110
+ Args:
111
+ x (torch.Tensor): Tokens of shape (B, N, D).
112
+ attn_mask (torch.Tensor): Additive mask of shape (N, N) (0 = attend, -inf = masked).
113
+
114
+ Returns:
115
+ torch.Tensor: Updated tokens of shape (B, N, D).
116
+ """
117
+ B, N, D = x.shape
118
+ # (B, N, 3*D) -> (3, B, heads, N, head_dim)
119
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, D // self.num_heads).permute(2, 0, 3, 1, 4)
120
+ q, k, v = qkv.unbind(0)
121
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
122
+ return self.proj(x.transpose(1, 2).reshape(B, N, D))
123
+
124
+
125
+ class Mlp(nn.Module):
126
+ """
127
+ Two-layer feed-forward network (Linear -> GELU -> Linear).
128
+
129
+ Args:
130
+ dim (int): Input / output dimension.
131
+ hidden_dim (int): Hidden dimension.
132
+ """
133
+
134
+ def __init__(self, dim: int, hidden_dim: int):
135
+ super().__init__()
136
+ self.fc1 = nn.Linear(dim, hidden_dim)
137
+ self.fc2 = nn.Linear(hidden_dim, dim)
138
+
139
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
140
+ """
141
+ Args:
142
+ x (torch.Tensor): Input of shape (..., dim).
143
+
144
+ Returns:
145
+ torch.Tensor: Output of shape (..., dim).
146
+ """
147
+ return self.fc2(F.gelu(self.fc1(x)))
148
+
149
+
150
+ class MoE(nn.Module):
151
+ """
152
+ Sparse Mixture-of-Experts feed-forward layer with top-k routing.
153
+
154
+ A linear router scores every expert for each token; the top-k experts are
155
+ applied and their outputs are combined with the (re-normalized) router weights.
156
+
157
+ Args:
158
+ dim (int): Token dimension.
159
+ hidden_dim (int): Hidden dimension of each expert.
160
+ num_experts (int): Number of experts.
161
+ top_k (int): Number of experts used per token.
162
+ """
163
+
164
+ def __init__(self, dim: int, hidden_dim: int, num_experts: int, top_k: int):
165
+ super().__init__()
166
+ self.top_k = top_k
167
+ self.router = nn.Linear(dim, num_experts, bias=False)
168
+ self.experts = nn.ModuleList([Mlp(dim, hidden_dim) for _ in range(num_experts)])
169
+
170
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
171
+ """
172
+ Args:
173
+ x (torch.Tensor): Tokens of shape (B, N, D).
174
+
175
+ Returns:
176
+ torch.Tensor: Tokens of shape (B, N, D).
177
+ """
178
+ B, N, D = x.shape
179
+ x = x.reshape(-1, D)
180
+
181
+ # Select the top-k experts per token and re-normalize their weights to sum to 1.
182
+ probs = F.softmax(self.router(x), dim=-1)
183
+ weights, selected = torch.topk(probs, self.top_k, dim=-1)
184
+ weights = weights / weights.sum(dim=-1, keepdim=True)
185
+
186
+ # Run each expert only on the tokens that were routed to it.
187
+ out = torch.zeros_like(x)
188
+ for i, expert in enumerate(self.experts):
189
+ token_idx, slot_idx = torch.where(selected == i)
190
+ if token_idx.numel() > 0:
191
+ w = weights[token_idx, slot_idx].unsqueeze(1)
192
+ # Cast back to the accumulator dtype (expert outputs are half precision under autocast).
193
+ out.index_add_(0, token_idx, (expert(x[token_idx]) * w).to(out.dtype))
194
+ return out.view(B, N, D)
195
+
196
+
197
+ class Block(nn.Module):
198
+ """
199
+ Pre-norm transformer block: x + Attn(LN(x)), then x + FFN(LN(x)).
200
+
201
+ Args:
202
+ dim (int): Token dimension.
203
+ num_heads (int): Number of attention heads.
204
+ mlp_ratio (float): FFN hidden size as a multiple of dim.
205
+ use_moe (bool): If True, the FFN is a MoE layer, otherwise a dense MLP.
206
+ num_experts (int): Number of experts (MoE blocks only).
207
+ top_k (int): Experts per token (MoE blocks only).
208
+ """
209
+
210
+ def __init__(self, dim: int, num_heads: int, mlp_ratio: float, use_moe: bool, num_experts: int, top_k: int):
211
+ super().__init__()
212
+ hidden_dim = int(dim * mlp_ratio)
213
+ self.norm1 = nn.LayerNorm(dim)
214
+ # Note: dense blocks were trained with a qkv bias, MoE blocks without.
215
+ self.attn = Attention(dim, num_heads, qkv_bias=not use_moe)
216
+ self.norm2 = nn.LayerNorm(dim)
217
+ self.ffn = MoE(dim, hidden_dim, num_experts, top_k) if use_moe else Mlp(dim, hidden_dim)
218
+
219
+ def forward(self, x: torch.Tensor, attn_mask: torch.Tensor) -> torch.Tensor:
220
+ """
221
+ Args:
222
+ x (torch.Tensor): Tokens of shape (B, N, D).
223
+ attn_mask (torch.Tensor): Additive attention mask of shape (N, N).
224
+
225
+ Returns:
226
+ torch.Tensor: Tokens of shape (B, N, D).
227
+ """
228
+ x = x + self.attn(self.norm1(x), attn_mask)
229
+ x = x + self.ffn(self.norm2(x))
230
+ return x
231
+
232
+
233
+ # ============================================================
234
+ # OMNI model
235
+ # ============================================================
236
+
237
+
238
+ class OmniModel(PreTrainedModel):
239
+ """
240
+ OMNI vision encoder.
241
+
242
+ The input sequence is [teacher tokens (M) | patch tokens (Np)]. A structured
243
+ attention mask lets each teacher token attend only to itself and to the
244
+ patch tokens, while patch tokens attend only to patch tokens. After the
245
+ final LayerNorm, each teacher token is a teacher-specific representation
246
+ of the tile.
247
+
248
+ Args:
249
+ config (OmniConfig): Model configuration.
250
+ """
251
+
252
+ config_class = OmniConfig
253
+ base_model_prefix = "omni"
254
+ main_input_name = "pixel_values"
255
+
256
+ def __init__(self, config: OmniConfig):
257
+ super().__init__(config)
258
+ D = config.embed_dim
259
+ num_teachers = len(config.teachers)
260
+ num_patches = (config.img_size // config.patch_size) ** 2
261
+
262
+ # Patch embedding + learnable positional embedding of the patch tokens.
263
+ self.patch_embed = nn.Conv2d(3, D, kernel_size=config.patch_size, stride=config.patch_size)
264
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, D))
265
+
266
+ # One learnable token (and positional embedding) per teacher.
267
+ self.teacher_tokens = nn.Parameter(torch.zeros(1, num_teachers, D))
268
+ self.teacher_pos_embed = nn.Parameter(torch.zeros(1, num_teachers, D))
269
+
270
+ # Dense blocks first, MoE blocks for the last `num_moe_layers` blocks.
271
+ first_moe = config.depth - config.num_moe_layers
272
+ self.blocks = nn.ModuleList(
273
+ [
274
+ Block(D, config.num_heads, config.mlp_ratio, i >= first_moe, config.num_experts, config.moe_top_k)
275
+ for i in range(config.depth)
276
+ ]
277
+ )
278
+ self.norm = nn.LayerNorm(D)
279
+
280
+ self.post_init()
281
+
282
+ def _init_weights(self, module: nn.Module):
283
+ """
284
+ Weight initialization (only used for weights missing from the checkpoint).
285
+
286
+ Args:
287
+ module (nn.Module): Module to initialize.
288
+ """
289
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
290
+ nn.init.trunc_normal_(module.weight, std=0.02)
291
+ if module.bias is not None:
292
+ nn.init.zeros_(module.bias)
293
+ elif isinstance(module, nn.LayerNorm):
294
+ nn.init.ones_(module.weight)
295
+ nn.init.zeros_(module.bias)
296
+
297
+ @property
298
+ def teachers(self) -> list:
299
+ """list[str]: Teacher names, in the order of the teacher tokens."""
300
+ return self.config.teachers
301
+
302
+ def get_transform(self):
303
+ """
304
+ Returns the preprocessing used at training time (resize to 224, ImageNet normalization).
305
+
306
+ Returns:
307
+ torchvision.transforms.Compose: Transform mapping a PIL image to a (3, 224, 224) tensor.
308
+ """
309
+ import torchvision.transforms as T
310
+
311
+ return T.Compose(
312
+ [
313
+ T.Resize((self.config.img_size, self.config.img_size)),
314
+ T.ToTensor(),
315
+ T.Normalize(mean=self.config.image_mean, std=self.config.image_std),
316
+ ]
317
+ )
318
+
319
+ def _attention_mask(self, num_teachers: int, num_patches: int, device: torch.device) -> torch.Tensor:
320
+ """
321
+ Builds the structured attention mask (rows = queries, columns = keys).
322
+
323
+ - teacher token -> itself only among teacher tokens (no cross-teacher leakage)
324
+ - teacher token -> all patch tokens
325
+ - patch token -> all patch tokens (patch tokens never see teacher tokens)
326
+
327
+ Args:
328
+ num_teachers (int): Number of teacher tokens M.
329
+ num_patches (int): Number of patch tokens Np.
330
+ device (torch.device): Device of the mask.
331
+
332
+ Returns:
333
+ torch.Tensor: Additive mask of shape (M + Np, M + Np) with 0 (attend) or -inf (masked).
334
+ """
335
+ M, L = num_teachers, num_teachers + num_patches
336
+ allowed = torch.zeros(L, L, dtype=torch.bool, device=device)
337
+ allowed[:M, :M] = torch.eye(M, dtype=torch.bool, device=device)
338
+ allowed[:M, M:] = True
339
+ allowed[M:, M:] = True
340
+ mask = torch.full((L, L), float("-inf"), device=device)
341
+ return mask.masked_fill(allowed, 0.0)
342
+
343
+ def forward(
344
+ self,
345
+ pixel_values: torch.Tensor,
346
+ return_teacher_tokens: bool = False,
347
+ return_patch_tokens: bool = False,
348
+ ):
349
+ """
350
+ Encodes a batch of tiles.
351
+
352
+ Args:
353
+ pixel_values (torch.Tensor): Normalized images of shape (B, 3, 224, 224)
354
+ (see `get_transform`).
355
+ return_teacher_tokens (bool): Also return the M teacher-specific tokens.
356
+ return_patch_tokens (bool): Also return the patch tokens.
357
+
358
+ Returns:
359
+ torch.Tensor: If no flag is set, the tile embedding of shape (B, D), i.e. the
360
+ average of the M teacher tokens.
361
+ dict: If a flag is set, a dict with:
362
+ - "embedding" (B, D): average of the teacher tokens.
363
+ - "teacher_tokens" (B, M, D): one token per teacher, ordered as `model.teachers`
364
+ (only if `return_teacher_tokens`).
365
+ - "patch_tokens" (B, Np, D): patch tokens, Np = 16 x 16 = 256
366
+ (only if `return_patch_tokens`).
367
+ """
368
+ B = pixel_values.shape[0]
369
+
370
+ # Patch tokens: (B, 3, H, W) -> (B, Np, D).
371
+ patches = self.patch_embed(pixel_values).flatten(2).transpose(1, 2) + self.pos_embed
372
+
373
+ # Prepend the teacher tokens: (B, M + Np, D).
374
+ teachers = (self.teacher_tokens + self.teacher_pos_embed).expand(B, -1, -1)
375
+ x = torch.cat([teachers, patches], dim=1)
376
+
377
+ M = teachers.shape[1]
378
+ attn_mask = self._attention_mask(M, patches.shape[1], x.device).to(x.dtype)
379
+ for block in self.blocks:
380
+ x = block(x, attn_mask)
381
+ x = self.norm(x)
382
+
383
+ teacher_tokens, patch_tokens = x[:, :M], x[:, M:]
384
+ embedding = teacher_tokens.mean(dim=1)
385
+
386
+ if not (return_teacher_tokens or return_patch_tokens):
387
+ return embedding
388
+
389
+ out = {"embedding": embedding}
390
+ if return_teacher_tokens:
391
+ out["teacher_tokens"] = teacher_tokens
392
+ if return_patch_tokens:
393
+ out["patch_tokens"] = patch_tokens
394
+ return out
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch>=2.1
2
+ torchvision
3
+ transformers>=4.40
4
+ safetensors
5
+ # for eval_thunder.py
6
+ thunder-bench