sunyijie commited on
Commit
d9673ac
·
1 Parent(s): 1681903

add fg-clip large u16

Browse files
.gitattributes CHANGED
@@ -36,3 +36,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  image_encoder.axmodel filter=lfs diff=lfs merge=lfs -text
37
  text_encoder.axmodel filter=lfs diff=lfs merge=lfs -text
38
  fg-clip2-base/tokenizer.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
36
  image_encoder.axmodel filter=lfs diff=lfs merge=lfs -text
37
  text_encoder.axmodel filter=lfs diff=lfs merge=lfs -text
38
  fg-clip2-base/tokenizer.json filter=lfs diff=lfs merge=lfs -text
39
+ *.json filter=lfs diff=lfs merge=lfs -text
40
+ *.axmodel filter=lfs diff=lfs merge=lfs -text
41
+ *.onnx.data filter=lfs diff=lfs merge=lfs -text
image_encoder.axmodel → fg-clip2-base/image_encoder.axmodel RENAMED
File without changes
run_axmodel.py → fg-clip2-base/run_axmodel.py RENAMED
File without changes
text_encoder.axmodel → fg-clip2-base/text_encoder.axmodel RENAMED
File without changes
fg-clip2-large/.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
fg-clip2-large/README.md ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - zh
5
+ library_name: transformers
6
+ license: apache-2.0
7
+ pipeline_tag: zero-shot-image-classification
8
+ tags:
9
+ - clip
10
+ ---
11
+
12
+ # FG-CLIP 2: A Bilingual Fine-grained Vision-language Alignment Model
13
+
14
+ Code: https://github.com/360CVGroup/FG-CLIP
15
+ Project page: https://360cvgroup.github.io/FG-CLIP
16
+
17
+ FG-CLIP 2 is the foundation model for fine-grained vision-language understanding in both English and Chinese.
18
+ Across 29 datasets and 8 diverse tasks, it consistently surpasses recent strong baselines such as SigLIP 2 and MetaCLIP 2, achieving the best reported performance to date in both languages.
19
+
20
+ **[FG-CLIP 2: A Bilingual Fine-grained Vision-language Alignment Model](https://arxiv.org/abs/2510.10921)**
21
+ </br>
22
+ Chunyu Xie*, Bin Wang*, Fanjing Kong, Jincheng Li, Dawei Liang, Ji Ao, Dawei Leng†, Yuhui Yin(*Equal Contribution, †Corresponding Author)
23
+ </br>
24
+ [![arXiv](https://img.shields.io/badge/arXiv-2510.10921-b31b1b.svg)](https://arxiv.org/abs/2510.10921)
25
+ [![HF-model](https://img.shields.io/badge/Model-Collection🤗-yellow.svg)](https://huggingface.co/collections/qihoo360/fg-clip-2-68ecbf9c548623bb78bc7913)
26
+ [![HF-data](https://img.shields.io/badge/Benchmark-Collection🤗-yellow.svg)](https://huggingface.co/collections/qihoo360/fg-clip-2-68ecbf9c548623bb78bc7913)
27
+ [![API+MCP](https://img.shields.io/badge/API/MCP-FG--CLIPv2-green.svg)](https://research.360.cn/sass/index)
28
+
29
+ **[FG-CLIP: Fine-Grained Visual and Textual Alignment](https://arxiv.org/abs/2505.05071)** ([code branch: v1.0](https://github.com/360CVGroup/FG-CLIP/tree/v1.0))
30
+ </br>
31
+ Chunyu Xie*, Bin Wang*, Fanjing Kong, Jincheng Li, Dawei Liang, Gengshen Zhang, Dawei Leng†, Yuhui Yin (*Equal Contribution, †Corresponding Author)
32
+ </br>
33
+ [![arXiv](https://img.shields.io/badge/arXiv-2505.05071-b31b1b.svg)](https://arxiv.org/abs/2505.05071)
34
+ [![ICML](https://img.shields.io/badge/ICML-2025-blue.svg)](https://icml.cc/Conferences/2025)
35
+ [![HF-model](https://img.shields.io/badge/Model-Collection🤗-yellow.svg)](https://huggingface.co/collections/qihoo360/fg-clip-681da45d4acfb65c240a6d08)
36
+ [![HF-data](https://img.shields.io/badge/Data-FineHARD🤗-yellow.svg)](https://huggingface.co/datasets/qihoo360/FineHARD)
37
+ [![DeepWiki](https://img.shields.io/badge/DeepWiki-FG--CLIP-blue.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAyCAYAAAAnWDnqAAAAAXNSR0IArs4c6QAAA05JREFUaEPtmUtyEzEQhtWTQyQLHNak2AB7ZnyXZMEjXMGeK/AIi+QuHrMnbChYY7MIh8g01fJoopFb0uhhEqqcbWTp06/uv1saEDv4O3n3dV60RfP947Mm9/SQc0ICFQgzfc4CYZoTPAswgSJCCUJUnAAoRHOAUOcATwbmVLWdGoH//PB8mnKqScAhsD0kYP3j/Yt5LPQe2KvcXmGvRHcDnpxfL2zOYJ1mFwrryWTz0advv1Ut4CJgf5uhDuDj5eUcAUoahrdY/56ebRWeraTjMt/00Sh3UDtjgHtQNHwcRGOC98BJEAEymycmYcWwOprTgcB6VZ5JK5TAJ+fXGLBm3FDAmn6oPPjR4rKCAoJCal2eAiQp2x0vxTPB3ALO2CRkwmDy5WohzBDwSEFKRwPbknEggCPB/imwrycgxX2NzoMCHhPkDwqYMr9tRcP5qNrMZHkVnOjRMWwLCcr8ohBVb1OMjxLwGCvjTikrsBOiA6fNyCrm8V1rP93iVPpwaE+gO0SsWmPiXB+jikdf6SizrT5qKasx5j8ABbHpFTx+vFXp9EnYQmLx02h1QTTrl6eDqxLnGjporxl3NL3agEvXdT0WmEost648sQOYAeJS9Q7bfUVoMGnjo4AZdUMQku50McDcMWcBPvr0SzbTAFDfvJqwLzgxwATnCgnp4wDl6Aa+Ax283gghmj+vj7feE2KBBRMW3FzOpLOADl0Isb5587h/U4gGvkt5v60Z1VLG8BhYjbzRwyQZemwAd6cCR5/XFWLYZRIMpX39AR0tjaGGiGzLVyhse5C9RKC6ai42ppWPKiBagOvaYk8lO7DajerabOZP46Lby5wKjw1HCRx7p9sVMOWGzb/vA1hwiWc6jm3MvQDTogQkiqIhJV0nBQBTU+3okKCFDy9WwferkHjtxib7t3xIUQtHxnIwtx4mpg26/HfwVNVDb4oI9RHmx5WGelRVlrtiw43zboCLaxv46AZeB3IlTkwouebTr1y2NjSpHz68WNFjHvupy3q8TFn3Hos2IAk4Ju5dCo8B3wP7VPr/FGaKiG6T+v+TQqIrOqMTL1VdWV1DdmcbO8KXBz6esmYWYKPwDL5b5FA1a0hwapHiom0r/cKaoqr+27/XcrS5UwSMbQAAAABJRU5ErkJggg==)](https://deepwiki.com/360CVGroup/FG-CLIP)
38
+
39
+ <p align="center">
40
+ <img src="https://huggingface.co/qihoo360/fg-clip2-base/resolve/main/FGCLIP2_compare_all_n.png" width="500" height="440"/>
41
+ </p>
42
+
43
+ ## Quick Start 🤗
44
+
45
+ ### Load Model
46
+ ```python
47
+ import torch
48
+ from PIL import Image
49
+ from transformers import (
50
+ AutoImageProcessor,
51
+ AutoTokenizer,
52
+ AutoModelForCausalLM,
53
+ )
54
+
55
+
56
+ model_root = "qihoo360/fg-clip2-large"
57
+ model = AutoModelForCausalLM.from_pretrained(model_root,trust_remote_code=True).cuda()
58
+
59
+ device = model.device
60
+
61
+ tokenizer = AutoTokenizer.from_pretrained(model_root)
62
+ image_processor = AutoImageProcessor.from_pretrained(model_root)
63
+
64
+ ```
65
+
66
+
67
+ ### Retrieval
68
+
69
+ ```python
70
+ def determine_max_value(image):
71
+ w,h = image.size
72
+ max_val = (w//16)*(h//16)
73
+ if max_val > 784:
74
+ return 1024
75
+ elif max_val > 576:
76
+ return 784
77
+ elif max_val > 256:
78
+ return 576
79
+ elif max_val > 128:
80
+ return 256
81
+ else:
82
+ return 128
83
+
84
+ img_root = "cat_dfclor.jpg"
85
+ image = Image.open(img_root).convert("RGB")
86
+
87
+ image_input = image_processor(images=image, max_num_patches=determine_max_value(image), return_tensors="pt").to(device)
88
+
89
+ # NOTE Short captions: max_length=64 walk_type="short"(default)
90
+ # NOTE Long captions: max_length=196 walk_type="long"
91
+
92
+ captions = [
93
+ "一个简约风格的卧室角落,黑色金属衣架上挂着多件米色和白色的衣物,下方架子放着两双浅色鞋子,旁边是一盆绿植,左侧可见一张铺有白色床单和灰色枕���的床。",
94
+ "一个简约风格的卧室角落,黑色金属衣架上挂着多件红色和蓝色的衣物,下方架子放着两双黑色高跟鞋,旁边是一盆绿植,左侧可见一张铺有白色床单和灰色枕头的床。",
95
+ "一个简约风格的卧室角落,黑色金属衣架上挂着多件米色和白色的衣物,下方架子放着两双运动鞋,旁边是一盆仙人掌,左侧可见一张铺有白色床单和灰色枕头的床。",
96
+ "一个繁忙的街头市场,摊位上摆满水果,背景是高楼大厦,人们在喧闹中购物。"
97
+ ]
98
+ captions = [caption.lower() for caption in captions]
99
+
100
+ caption_input = tokenizer(captions, padding="max_length", max_length=196, truncation=True, return_tensors="pt").to(device)
101
+
102
+
103
+ with torch.no_grad():
104
+ image_feature = model.get_image_features(**image_input)
105
+ text_feature = model.get_text_features(**caption_input,walk_type="long")
106
+ image_feature = image_feature / image_feature.norm(p=2, dim=-1, keepdim=True)
107
+ text_feature = text_feature / text_feature.norm(p=2, dim=-1, keepdim=True)
108
+
109
+ logits_per_image = image_feature @ text_feature.T
110
+ logit_scale, logit_bias = model.logit_scale.to(text_feature.device), model.logit_bias.to(text_feature.device)
111
+ logits_per_image = logits_per_image * logit_scale.exp() + logit_bias
112
+ # The original Github example does not print probabilities for retrieval, keeping consistency.
113
+ ```
114
+ <p align="left">
115
+ <img src="https://huggingface.co/qihoo360/fg-clip2-base/resolve/main/cn_re_demo.png" width=100%/>
116
+ </p>
117
+
118
+ ### Dense feature effect display
119
+
120
+ ```python
121
+
122
+ import math
123
+ import matplotlib
124
+ matplotlib.use('Agg')
125
+ import matplotlib.pyplot as plt
126
+
127
+
128
+ img_root = "cat_dfclor.jpg"
129
+ image = Image.open(img_root).convert("RGB")
130
+ # The 'resize_short_edge' function is not defined in the snippet or provided context.
131
+ # Assuming 'cat_dfclor.jpg' is pre-processed or the model handles sizing.
132
+ # image = resize_short_edge(image,target_size=2048)
133
+
134
+ image_input = image_processor(images=image, max_num_patches=16384, return_tensors="pt").to(device)
135
+ captions = ["电脑","黑猫","窗户","window","white cat","book"]
136
+
137
+ with torch.no_grad():
138
+ dense_image_feature = model.get_image_dense_feature(**image_input)
139
+
140
+ spatial_values = image_input["spatial_shapes"][0]
141
+ real_h = spatial_values[0].item()
142
+ real_w = spatial_values[1].item()
143
+ real_pixel_tokens_num = real_w*real_h
144
+ dense_image_feature = dense_image_feature[0][:real_pixel_tokens_num]
145
+ captions = [caption.lower() for caption in captions]
146
+ caption_input = tokenizer(captions, padding="max_length", max_length=64, truncation=True, return_tensors="pt").to(device)
147
+
148
+ text_feature = model.get_text_features(**caption_input, walk_type="box")
149
+ text_feature = text_feature / text_feature.norm(p=2, dim=-1, keepdim=True)
150
+ dense_image_feature = dense_image_feature / dense_image_feature.norm(p=2, dim=-1, keepdim=True)
151
+
152
+ similarity = dense_image_feature @ text_feature.T
153
+ similarity = similarity.cpu()
154
+
155
+
156
+ num_classes = len(captions)
157
+ cols = 3
158
+ rows = (num_classes + cols - 1) // cols
159
+
160
+
161
+ aspect_ratio = real_w / real_h
162
+
163
+ fig_width_inch = 3 * cols
164
+ fig_height_inch = fig_width_inch / aspect_ratio * rows / cols
165
+
166
+ fig, axes = plt.subplots(rows, cols, figsize=(fig_width_inch, fig_height_inch))
167
+ fig.subplots_adjust(wspace=0.01, hspace=0.01)
168
+
169
+ if num_classes == 1:
170
+ axes = [axes]
171
+ else:
172
+ axes = axes.flatten()
173
+
174
+ for cls_index in range(num_classes):
175
+ similarity_map = similarity[:, cls_index].cpu().numpy()
176
+ show_image = similarity_map.reshape((real_h, real_w))
177
+
178
+ ax = axes[cls_index]
179
+ ax.imshow(show_image, cmap='viridis', aspect='equal')
180
+ ax.set_xticks([])
181
+ ax.set_yticks([])
182
+ ax.axis('off')
183
+
184
+
185
+ for idx in range(num_classes, len(axes)):
186
+ axes[idx].axis('off')
187
+
188
+ savename = "FGCLIP2_dfcolor_cat_all_2K.png"
189
+ plt.savefig(savename, dpi=150, bbox_inches='tight', pad_inches=0.05)
190
+ plt.close()
191
+ ```
192
+
193
+ <p align="left">
194
+ <img src="https://huggingface.co/qihoo360/fg-clip2-base/resolve/main/FGCLIP2_dfcolor_cat_all_2K.png" width=100%/>
195
+ </p>
196
+
197
+ ## Citation
198
+ If you find FG-CLIP 2 useful for your research and applications, please cite using this BibTeX:
199
+
200
+ ```
201
+ @article{xie2025fg2,
202
+ title={FG-CLIP 2: A Bilingual Fine-grained Vision-language Alignment Model},
203
+ author={Xie, Chunyu and Wang, Bin and Kong, Fanjing and Li, Jincheng and Liang, Dawei and Ao, Ji and Leng, Dawei and Yin, Yuhui},
204
+ journal={arXiv preprint arXiv:2510.10921},
205
+ year={2025}
206
+ }
207
+ ```
208
+ ```
209
+ @article{xie2025fg,
210
+ title={FG-CLIP: Fine-Grained Visual and Textual Alignment},
211
+ author={Xie, Chunyu and Wang, Bin and Kong, Fanjing and Li, Jincheng and Liang, Dawei and Zhang, Gengshen and Leng, Dawei and Yin, Yuhui},
212
+ journal={arXiv preprint arXiv:2505.05071},
213
+ year={2025}
214
+ }
215
+ ```
216
+
217
+
218
+ ## License
219
+
220
+ This project utilizes certain datasets and checkpoints that are subject to their respective original licenses. Users must comply with all terms and conditions of these original licenses.
221
+ The content of this project itself is licensed under the [Apache license 2.0](https://huggingface.co/qihoo360/fg-clip2-base/resolve/main/cn_re_demo.pngLICENSE).
fg-clip2-large/config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a3921ec33c280cbbad5a61995cd31ef700491f8d088a8a167d67963a16a925c
3
+ size 1110
fg-clip2-large/configuration_fgclip2.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/fgclip2/modular_fgclip2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_fgclip2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The HuggingFace Inc. team.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class Fgclip2TextConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`Fgclip2TextModel`]. It is used to instantiate a
31
+ Fgclip2 text encoder according to the specified arguments, defining the model architecture. Instantiating a
32
+ configuration with the defaults will yield a similar configuration to that of the text encoder of the Fgclip2
33
+ [qihoo360/fg-clip2-base](https://huggingface.co/qihoo360/fg-clip2-base) architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32000):
40
+ Vocabulary size of the Fgclip2 text model. Defines the number of different tokens that can be represented by
41
+ the `inputs_ids` passed when calling [`Fgclip2Model`].
42
+ hidden_size (`int`, *optional*, defaults to 768):
43
+ Dimensionality of the encoder layers and the pooler layer.
44
+ intermediate_size (`int`, *optional*, defaults to 3072):
45
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
46
+ num_hidden_layers (`int`, *optional*, defaults to 12):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 12):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ max_position_embeddings (`int`, *optional*, defaults to 64):
51
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
52
+ just in case (e.g., 512 or 1024 or 2048).
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
54
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
55
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
56
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
57
+ The epsilon used by the layer normalization layers.
58
+ attention_dropout (`float`, *optional*, defaults to 0.0):
59
+ The dropout ratio for the attention probabilities.
60
+ pad_token_id (`int`, *optional*, defaults to 1):
61
+ The id of the padding token in the vocabulary.
62
+ bos_token_id (`int`, *optional*, defaults to 49406):
63
+ The id of the beginning-of-sequence token in the vocabulary.
64
+ eos_token_id (`int`, *optional*, defaults to 49407):
65
+ The id of the end-of-sequence token in the vocabulary.
66
+ projection_size (`int`, *optional*, defaults to `hidden_size`):
67
+ The size of the projection head.
68
+ keep_len (`int`, *optional*, defaults to 20):
69
+ When processing long texts, the retained tokens are used for handling short text lengths.
70
+ For details, please refer to the FG-CLIP 'https://arxiv.org/abs/2505.05071' paper.
71
+ longtext_len (`int`, *optional*, defaults to 196):
72
+ The maximum number of tokens in long texts that can be processed
73
+
74
+
75
+ Example:
76
+
77
+ ```python
78
+ >>> from transformers import Fgclip2TextConfig, Fgclip2TextModel
79
+
80
+ >>> # Initializing a Fgclip2TextConfig with qihoo/fgclip2-base-patch16 style configuration
81
+ >>> configuration = Fgclip2TextConfig()
82
+
83
+ >>> # Initializing a Fgclip2TextModel (with random weights) from the qihoo/fgclip2-base-patch16 style configuration
84
+ >>> model = Fgclip2TextModel(configuration)
85
+
86
+ >>> # Accessing the model configuration
87
+ >>> configuration = model.config
88
+ ```"""
89
+
90
+ model_type = "fgclip2_text_model"
91
+ base_config_key = "text_config"
92
+
93
+ def __init__(
94
+ self,
95
+ vocab_size=32000,
96
+ hidden_size=768,
97
+ intermediate_size=3072,
98
+ num_hidden_layers=12,
99
+ num_attention_heads=12,
100
+ max_position_embeddings=64,
101
+ hidden_act="gelu_pytorch_tanh",
102
+ layer_norm_eps=1e-6,
103
+ attention_dropout=0.0,
104
+ # This differs from `CLIPTokenizer`'s default and from openai/fgclip2
105
+ # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
106
+ pad_token_id=1,
107
+ bos_token_id=49406,
108
+ eos_token_id=49407,
109
+ projection_size=None,
110
+ keep_len=20,
111
+ longtext_len=196,
112
+ **kwargs,
113
+ ):
114
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
115
+
116
+ self.vocab_size = vocab_size
117
+ self.hidden_size = hidden_size
118
+ self.intermediate_size = intermediate_size
119
+ self.num_hidden_layers = num_hidden_layers
120
+ self.num_attention_heads = num_attention_heads
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.layer_norm_eps = layer_norm_eps
123
+ self.hidden_act = hidden_act
124
+ self.attention_dropout = attention_dropout
125
+ self.projection_size = projection_size if projection_size is not None else hidden_size
126
+ self.keep_len = keep_len
127
+ self.longtext_len = longtext_len
128
+
129
+
130
+ class Fgclip2VisionConfig(PretrainedConfig):
131
+ r"""
132
+ This is the configuration class to store the configuration of a [`Fgclip2VisionModel`]. It is used to instantiate a
133
+ Fgclip2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
134
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the Fgclip2
135
+ [qihoo/fgclip2-base-patch16](https://huggingface.co/qihoo/fgclip2-base-patch16) architecture.
136
+
137
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
138
+ documentation from [`PretrainedConfig`] for more information.
139
+
140
+ Args:
141
+ hidden_size (`int`, *optional*, defaults to 768):
142
+ Dimensionality of the encoder layers and the pooler layer.
143
+ intermediate_size (`int`, *optional*, defaults to 3072):
144
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
145
+ num_hidden_layers (`int`, *optional*, defaults to 12):
146
+ Number of hidden layers in the Transformer encoder.
147
+ num_attention_heads (`int`, *optional*, defaults to 12):
148
+ Number of attention heads for each attention layer in the Transformer encoder.
149
+ num_channels (`int`, *optional*, defaults to 3):
150
+ Number of channels in the input images.
151
+ num_patches (`int`, *optional*, defaults to 256):
152
+ The number of patches in the image with the size of (`patch_size`, `patch_size`).
153
+ The image is resized to fill maximum of this number of patches, and to preserve
154
+ the aspect ratio. In case the resulted number of patches is lower, the image is
155
+ padded in "patch" dimension.
156
+ patch_size (`int`, *optional*, defaults to 16):
157
+ The size (resolution) of each patch.
158
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
159
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
160
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
161
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
162
+ The epsilon used by the layer normalization layers.
163
+ attention_dropout (`float`, *optional*, defaults to 0.0):
164
+ The dropout ratio for the attention probabilities.
165
+
166
+ Example:
167
+
168
+ ```python
169
+ >>> from transformers import Fgclip2VisionConfig, Fgclip2VisionModel
170
+
171
+ >>> # Initializing a Fgclip2VisionConfig with qihoo/fgclip2-base-patch16 style configuration
172
+ >>> configuration = Fgclip2VisionConfig()
173
+
174
+ >>> # Initializing a Fgclip2VisionModel (with random weights) from the qihoo/fgclip2-base-patch16 style configuration
175
+ >>> model = Fgclip2VisionModel(configuration)
176
+
177
+ >>> # Accessing the model configuration
178
+ >>> configuration = model.config
179
+ ```"""
180
+
181
+ model_type = "fgclip2_vision_model"
182
+ base_config_key = "vision_config"
183
+
184
+ def __init__(
185
+ self,
186
+ hidden_size=768,
187
+ intermediate_size=3072,
188
+ num_hidden_layers=12,
189
+ num_attention_heads=12,
190
+ num_channels=3,
191
+ num_patches=256,
192
+ patch_size=16,
193
+ hidden_act="gelu_pytorch_tanh",
194
+ layer_norm_eps=1e-6,
195
+ attention_dropout=0.0,
196
+ **kwargs,
197
+ ):
198
+ super().__init__(**kwargs)
199
+
200
+ self.hidden_size = hidden_size
201
+ self.intermediate_size = intermediate_size
202
+ self.num_hidden_layers = num_hidden_layers
203
+ self.num_attention_heads = num_attention_heads
204
+ self.num_channels = num_channels
205
+ self.patch_size = patch_size
206
+ self.attention_dropout = attention_dropout
207
+ self.layer_norm_eps = layer_norm_eps
208
+ self.hidden_act = hidden_act
209
+ self.num_patches = num_patches
210
+
211
+
212
+ class Fgclip2Config(PretrainedConfig):
213
+ r"""
214
+ [`Fgclip2Config`] is the configuration class to store the configuration of a [`Fgclip2Model`]. It is used to
215
+ instantiate a Fgclip2 model according to the specified arguments, defining the text model and vision model configs.
216
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Fgclip2
217
+ [qihoo/fgclip2-base-patch16](https://huggingface.co/qihoo/fgclip2-base-patch16) architecture.
218
+
219
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
220
+ documentation from [`PretrainedConfig`] for more information.
221
+
222
+ Args:
223
+ text_config (`dict`, *optional*):
224
+ Dictionary of configuration options used to initialize [`Fgclip2TextConfig`].
225
+ vision_config (`dict`, *optional*):
226
+ Dictionary of configuration options used to initialize [`Fgclip2VisionConfig`].
227
+ kwargs (*optional*):
228
+ Dictionary of keyword arguments.
229
+
230
+ Example:
231
+
232
+ ```python
233
+ >>> from transformers import Fgclip2Config, Fgclip2Model
234
+
235
+ >>> # Initializing a Fgclip2Config with qihoo/fgclip2-base-patch16 style configuration
236
+ >>> configuration = Fgclip2Config()
237
+
238
+ >>> # Initializing a Fgclip2Model (with random weights) from the qihoo/fgclip2-base-patch16 style configuration
239
+ >>> model = Fgclip2Model(configuration)
240
+
241
+ >>> # Accessing the model configuration
242
+ >>> configuration = model.config
243
+
244
+ >>> # We can also initialize a Fgclip2Config from a Fgclip2TextConfig and a Fgclip2VisionConfig
245
+ >>> from transformers import Fgclip2TextConfig, Fgclip2VisionConfig
246
+
247
+ >>> # Initializing a Fgclip2Text and Fgclip2Vision configuration
248
+ >>> config_text = Fgclip2TextConfig()
249
+ >>> config_vision = Fgclip2VisionConfig()
250
+
251
+ >>> config = Fgclip2Config.from_text_vision_configs(config_text, config_vision)
252
+ ```"""
253
+
254
+ model_type = "fgclip2"
255
+ sub_configs = {"text_config": Fgclip2TextConfig, "vision_config": Fgclip2VisionConfig}
256
+
257
+ def __init__(self, text_config=None, vision_config=None, **kwargs):
258
+ super().__init__(**kwargs)
259
+
260
+ if text_config is None:
261
+ text_config = {}
262
+ logger.info("`text_config` is `None`. Initializing the `Fgclip2TextConfig` with default values.")
263
+
264
+ if vision_config is None:
265
+ vision_config = {}
266
+ logger.info("`vision_config` is `None`. initializing the `Fgclip2VisionConfig` with default values.")
267
+
268
+ self.text_config = Fgclip2TextConfig(**text_config)
269
+ self.vision_config = Fgclip2VisionConfig(**vision_config)
270
+
271
+ self.initializer_factor = 1.0
272
+
273
+
274
+ __all__ = ["Fgclip2Config", "Fgclip2TextConfig", "Fgclip2VisionConfig"]
fg-clip2-large/export_info.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b629685e6dabfc5e195812a4769702089dae5e08dcb51cbbc37036026560f8c
3
+ size 1073
fg-clip2-large/fgclip2_large_image_encoder.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed9961a26494c3d5e51797a96f96d5cffa62b7ed6243f4c1104f94225519855e
3
+ size 341054899
fg-clip2-large/fgclip2_large_image_encoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64f8d087f2e91aa5a4fdeacfbf8e08b8b003cbbab8e918682092e6dffa01b37a
3
+ size 1264302855
fg-clip2-large/fgclip2_large_text_encoder_short.axmodel ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:839099deebbc372bf55cdff8d5bd08a73a572256e3a67c8fe3f0c52a766d431c
3
+ size 852363032
fg-clip2-large/fgclip2_large_text_encoder_short.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52540ff00d2991b1b3b8faa8b388c21ea95c88a7aaaf6bb6e65ca340c7b51759
3
+ size 602037
fg-clip2-large/fgclip2_large_text_encoder_short.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c54658e6f4313f278979f0fcb37d9757a3d526202c896757e271527a642f26a
3
+ size 2262282240
fg-clip2-large/modeling_fgclip2.py ADDED
@@ -0,0 +1,1400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/fgclip2/modular_fgclip2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_fgclip2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The HuggingFace Inc. team.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ import math
22
+ import warnings
23
+ from dataclasses import dataclass
24
+ from typing import Any, Callable, Optional, Union, List
25
+
26
+ import numpy as np
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+ from torch.nn.init import _calculate_fan_in_and_fan_out
31
+ from torchvision.ops import roi_align
32
+
33
+ from transformers.activations import ACT2FN
34
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
35
+ from transformers.modeling_layers import GradientCheckpointingLayer
36
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
37
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from transformers.processing_utils import Unpack
39
+ from transformers.utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, filter_out_non_signature_kwargs
40
+ from transformers.utils.generic import check_model_inputs
41
+ from .configuration_fgclip2 import Fgclip2Config, Fgclip2TextConfig, Fgclip2VisionConfig
42
+
43
+
44
+ @dataclass
45
+ @auto_docstring(
46
+ custom_intro="""
47
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
48
+ """
49
+ )
50
+ class Fgclip2VisionOutput(ModelOutput):
51
+ r"""
52
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
53
+ The image embeddings obtained by applying the projection layer to the pooler_output.
54
+ """
55
+
56
+ image_embeds: Optional[torch.FloatTensor] = None
57
+ last_hidden_state: Optional[torch.FloatTensor] = None
58
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
59
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
60
+
61
+
62
+ @dataclass
63
+ @auto_docstring(
64
+ custom_intro="""
65
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
66
+ """
67
+ )
68
+ class Fgclip2TextOutput(ModelOutput):
69
+ r"""
70
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
71
+ The text embeddings obtained by applying the projection layer to the pooler_output.
72
+ """
73
+
74
+ text_embeds: Optional[torch.FloatTensor] = None
75
+ last_hidden_state: Optional[torch.FloatTensor] = None
76
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
77
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
78
+
79
+
80
+ @dataclass
81
+ @auto_docstring
82
+ class Fgclip2Output(ModelOutput):
83
+ r"""
84
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
85
+ Contrastive loss for image-text similarity.
86
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
87
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
88
+ similarity scores.
89
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
90
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
91
+ similarity scores.
92
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
93
+ The text embeddings obtained by applying the projection layer to the pooled output of [`Fgclip2TextModel`].
94
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
95
+ The image embeddings obtained by applying the projection layer to the pooled output of [`Fgclip2VisionModel`].
96
+ text_model_output (`BaseModelOutputWithPooling`):
97
+ The output of the [`Fgclip2TextModel`].
98
+ vision_model_output (`BaseModelOutputWithPooling`):
99
+ The output of the [`Fgclip2VisionModel`].
100
+ """
101
+
102
+ loss: Optional[torch.FloatTensor] = None
103
+ logits_per_image: Optional[torch.FloatTensor] = None
104
+ logits_per_text: Optional[torch.FloatTensor] = None
105
+ text_embeds: Optional[torch.FloatTensor] = None
106
+ image_embeds: Optional[torch.FloatTensor] = None
107
+ text_model_output: BaseModelOutputWithPooling = None
108
+ vision_model_output: BaseModelOutputWithPooling = None
109
+
110
+ def to_tuple(self) -> tuple[Any]:
111
+ return tuple(
112
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
113
+ for k in self.keys()
114
+ )
115
+
116
+
117
+ class Fgclip2VisionEmbeddings(nn.Module):
118
+ def __init__(self, config: Fgclip2VisionConfig):
119
+ super().__init__()
120
+ self.config = config
121
+ self.embed_dim = config.hidden_size
122
+ self.patch_size = config.patch_size
123
+
124
+ self.patch_embedding = nn.Linear(
125
+ in_features=config.num_channels * self.patch_size * self.patch_size,
126
+ out_features=self.embed_dim,
127
+ )
128
+
129
+ self.num_patches = config.num_patches
130
+ self.position_embedding_size = int(self.num_patches**0.5)
131
+ self.position_embedding = nn.Embedding(self.num_patches, self.embed_dim)
132
+
133
+ @staticmethod
134
+ def resize_positional_embeddings(
135
+ positional_embeddings: torch.Tensor,
136
+ spatial_shapes: torch.LongTensor,
137
+ max_length: int,
138
+ ) -> torch.Tensor:
139
+ """
140
+ Resize positional embeddings to image-specific size and pad to a fixed size.
141
+
142
+ Args:
143
+ positional_embeddings (`torch.Tensor`):
144
+ Position embeddings of shape (height, width, embed_dim)
145
+ spatial_shapes (`torch.LongTensor`):
146
+ Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to
147
+ max_length (`int`):
148
+ Maximum length of the positional embeddings to pad resized positional embeddings to
149
+
150
+ Returns:
151
+ `torch.Tensor`: Embeddings of shape (batch_size, max_length, embed_dim)
152
+ """
153
+ batch_size = spatial_shapes.shape[0]
154
+ embed_dim = positional_embeddings.shape[-1]
155
+ source_dtype = positional_embeddings.dtype
156
+
157
+ resulted_positional_embeddings = torch.empty(
158
+ (batch_size, max_length, embed_dim),
159
+ device=positional_embeddings.device,
160
+ dtype=source_dtype,
161
+ )
162
+
163
+ # (height, width, embed_dim) -> (1, embed_dim, height, width) for interpolation
164
+ positional_embeddings = positional_embeddings.permute(2, 0, 1).unsqueeze(0)
165
+
166
+ # Upcast to float32 on CPU because antialias is not supported for bfloat16/float16 on CPU
167
+ if positional_embeddings.device.type == "cpu":
168
+ positional_embeddings = positional_embeddings.to(torch.float32)
169
+
170
+ for i in range(batch_size):
171
+ # (1, dim, height, width) -> (1, dim, target_height, target_width)
172
+ height, width = spatial_shapes[i]
173
+ resized_embeddings = F.interpolate(
174
+ positional_embeddings,
175
+ size=(height, width),
176
+ mode="bilinear",
177
+ align_corners=False,
178
+ antialias=True,
179
+ )
180
+
181
+ # (1, dim, target_height, target_width) -> (target_height * target_width, dim)
182
+ resized_embeddings = resized_embeddings.reshape(embed_dim, height * width).transpose(0, 1)
183
+
184
+ # Cast to original dtype
185
+ resized_embeddings = resized_embeddings.to(source_dtype)
186
+
187
+ resulted_positional_embeddings[i, : height * width] = resized_embeddings
188
+ resulted_positional_embeddings[i, height * width :] = resized_embeddings[0]
189
+
190
+ return resulted_positional_embeddings
191
+
192
+ def forward(self, pixel_values: torch.FloatTensor, spatial_shapes: torch.LongTensor) -> torch.Tensor:
193
+ """
194
+ Args:
195
+ pixel_values (`torch.FloatTensor`):
196
+ Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size)
197
+ spatial_shapes (`list[tuple[int, int]]`):
198
+ Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to
199
+ """
200
+
201
+ # Apply patch embeddings to already patchified pixel values
202
+ target_dtype = self.patch_embedding.weight.dtype
203
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
204
+
205
+ # Get positional resized and padded positional embeddings
206
+ positional_embeddings = self.position_embedding.weight.reshape(
207
+ self.position_embedding_size, self.position_embedding_size, -1
208
+ )
209
+ resized_positional_embeddings = self.resize_positional_embeddings(
210
+ positional_embeddings, spatial_shapes, max_length=pixel_values.shape[1]
211
+ )
212
+
213
+ # Add positional embeddings to patch embeddings
214
+ embeddings = patch_embeds + resized_positional_embeddings
215
+ return embeddings
216
+
217
+
218
+ def eager_attention_forward(
219
+ module: nn.Module,
220
+ query: torch.Tensor,
221
+ key: torch.Tensor,
222
+ value: torch.Tensor,
223
+ attention_mask: Optional[torch.Tensor],
224
+ scaling: float,
225
+ dropout: float = 0.0,
226
+ **kwargs,
227
+ ):
228
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
229
+ if attention_mask is not None:
230
+ attn_weights = attn_weights + attention_mask
231
+
232
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
233
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
234
+
235
+ attn_output = torch.matmul(attn_weights, value)
236
+ attn_output = attn_output.transpose(1, 2).contiguous()
237
+
238
+ return attn_output, attn_weights
239
+
240
+
241
+ class Fgclip2Attention(nn.Module):
242
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
243
+
244
+ def __init__(self, config):
245
+ super().__init__()
246
+ self.config = config
247
+ self.embed_dim = config.hidden_size
248
+ self.num_heads = config.num_attention_heads
249
+ self.head_dim = self.embed_dim // self.num_heads
250
+ if self.head_dim * self.num_heads != self.embed_dim:
251
+ raise ValueError(
252
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
253
+ f" {self.num_heads})."
254
+ )
255
+ self.scale = self.head_dim**-0.5
256
+ self.dropout = config.attention_dropout
257
+ self.is_causal = False
258
+
259
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
260
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
261
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
262
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
263
+
264
+ def forward(
265
+ self,
266
+ hidden_states: torch.Tensor,
267
+ attention_mask: Optional[torch.Tensor] = None,
268
+ **kwargs,
269
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
270
+ """Input shape: Batch x Time x Channel"""
271
+
272
+ batch_size, seq_length, embed_dim = hidden_states.shape
273
+
274
+ queries = self.q_proj(hidden_states)
275
+ keys = self.k_proj(hidden_states)
276
+ values = self.v_proj(hidden_states)
277
+
278
+ queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
279
+ keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
280
+ values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
281
+
282
+ attention_interface: Callable = eager_attention_forward
283
+ if self.config._attn_implementation != "eager":
284
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
285
+
286
+ attn_output, attn_weights = attention_interface(
287
+ self,
288
+ queries,
289
+ keys,
290
+ values,
291
+ attention_mask,
292
+ is_causal=self.is_causal,
293
+ scaling=self.scale,
294
+ dropout=0.0 if not self.training else self.dropout,
295
+ )
296
+
297
+ attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
298
+ attn_output = self.out_proj(attn_output)
299
+
300
+ return attn_output, attn_weights
301
+
302
+
303
+ class Fgclip2MLP(nn.Module):
304
+ def __init__(self, config):
305
+ super().__init__()
306
+ self.config = config
307
+ self.activation_fn = ACT2FN[config.hidden_act]
308
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
309
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
310
+
311
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
312
+ hidden_states = self.fc1(hidden_states)
313
+ hidden_states = self.activation_fn(hidden_states)
314
+ hidden_states = self.fc2(hidden_states)
315
+ return hidden_states
316
+
317
+
318
+ class Fgclip2EncoderLayer(GradientCheckpointingLayer):
319
+ def __init__(self, config: Union[Fgclip2VisionConfig, Fgclip2TextConfig]):
320
+ super().__init__()
321
+ self.embed_dim = config.hidden_size
322
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
323
+ self.self_attn = Fgclip2Attention(config)
324
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
325
+ self.mlp = Fgclip2MLP(config)
326
+
327
+ @auto_docstring
328
+ def forward(
329
+ self,
330
+ hidden_states: torch.Tensor,
331
+ attention_mask: torch.Tensor,
332
+ **kwargs: Unpack[TransformersKwargs],
333
+ ) -> torch.FloatTensor:
334
+ residual = hidden_states
335
+
336
+ hidden_states = self.layer_norm1(hidden_states)
337
+ hidden_states, _ = self.self_attn(
338
+ hidden_states=hidden_states,
339
+ attention_mask=attention_mask,
340
+ **kwargs,
341
+ )
342
+ hidden_states = residual + hidden_states
343
+
344
+ residual = hidden_states
345
+ hidden_states = self.layer_norm2(hidden_states)
346
+ hidden_states = self.mlp(hidden_states)
347
+ hidden_states = residual + hidden_states
348
+
349
+ return hidden_states
350
+
351
+
352
+ class Fgclip2Encoder(nn.Module):
353
+ """
354
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
355
+ [`Fgclip2EncoderLayer`].
356
+
357
+ Args:
358
+ config: Fgclip2Config
359
+ """
360
+
361
+ def __init__(self, config: Fgclip2Config):
362
+ super().__init__()
363
+ self.config = config
364
+ self.layers = nn.ModuleList([Fgclip2EncoderLayer(config) for _ in range(config.num_hidden_layers)])
365
+ self.gradient_checkpointing = False
366
+
367
+ # Ignore copy
368
+ @auto_docstring
369
+ def forward(
370
+ self,
371
+ inputs_embeds,
372
+ attention_mask: Optional[torch.Tensor] = None,
373
+ **kwargs: Unpack[TransformersKwargs],
374
+ ) -> BaseModelOutput:
375
+ hidden_states = inputs_embeds
376
+ for encoder_layer in self.layers:
377
+ hidden_states = encoder_layer(
378
+ hidden_states,
379
+ attention_mask,
380
+ **kwargs,
381
+ )
382
+
383
+ return BaseModelOutput(last_hidden_state=hidden_states)
384
+
385
+
386
+ class Fgclip2VisionTransformer(nn.Module):
387
+ def __init__(self, config: Fgclip2VisionConfig):
388
+ super().__init__()
389
+ self.config = config
390
+ embed_dim = config.hidden_size
391
+
392
+ self.embeddings = Fgclip2VisionEmbeddings(config)
393
+ self.encoder = Fgclip2Encoder(config)
394
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
395
+ self.use_head = True if not hasattr(config, "vision_use_head") else config.vision_use_head
396
+ if self.use_head:
397
+ self.head = Fgclip2MultiheadAttentionPoolingHead(config)
398
+
399
+ @can_return_tuple
400
+ @auto_docstring
401
+ def forward(
402
+ self,
403
+ pixel_values: torch.FloatTensor,
404
+ attention_mask: torch.Tensor,
405
+ spatial_shapes: torch.LongTensor,
406
+ output_attentions: Optional[bool] = None,
407
+ output_hidden_states: Optional[bool] = None,
408
+ ) -> BaseModelOutputWithPooling:
409
+ r"""
410
+ spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
411
+ Tensor containing the spatial dimensions (height, width) of the input images.
412
+ """
413
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
414
+ output_hidden_states = (
415
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
416
+ )
417
+
418
+ hidden_states = self.embeddings(pixel_values, spatial_shapes)
419
+
420
+ if attention_mask is not None and self.config._attn_implementation != "flash_attention_2":
421
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
422
+ encoder_attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
423
+ else:
424
+ encoder_attention_mask = attention_mask
425
+
426
+ encoder_outputs: BaseModelOutput = self.encoder(
427
+ inputs_embeds=hidden_states,
428
+ attention_mask=encoder_attention_mask,
429
+ output_attentions=output_attentions,
430
+ output_hidden_states=output_hidden_states,
431
+ )
432
+
433
+ last_hidden_state = encoder_outputs.last_hidden_state
434
+ last_hidden_state = self.post_layernorm(last_hidden_state)
435
+
436
+ pooler_output = self.head(last_hidden_state, attention_mask) if self.use_head else None
437
+
438
+ return BaseModelOutputWithPooling(
439
+ last_hidden_state=last_hidden_state,
440
+ pooler_output=pooler_output,
441
+ hidden_states=encoder_outputs.hidden_states,
442
+ attentions=encoder_outputs.attentions,
443
+ )
444
+
445
+
446
+ def _trunc_normal_(tensor, mean, std, a, b):
447
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
448
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
449
+ def norm_cdf(x):
450
+ # Computes standard normal cumulative distribution function
451
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
452
+
453
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
454
+ warnings.warn(
455
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
456
+ "The distribution of values may be incorrect.",
457
+ stacklevel=2,
458
+ )
459
+
460
+ # Values are generated by using a truncated uniform distribution and
461
+ # then using the inverse CDF for the normal distribution.
462
+ # Get upper and lower cdf values
463
+ l = norm_cdf((a - mean) / std)
464
+ u = norm_cdf((b - mean) / std)
465
+
466
+ # Uniformly fill tensor with values from [l, u], then translate to
467
+ # [2l-1, 2u-1].
468
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
469
+
470
+ # Use inverse cdf transform for normal distribution to get truncated
471
+ # standard normal
472
+ tensor.erfinv_()
473
+
474
+ # Transform to proper mean, std
475
+ tensor.mul_(std * math.sqrt(2.0))
476
+ tensor.add_(mean)
477
+
478
+ # Clamp to ensure it's in the proper range
479
+ tensor.clamp_(min=a, max=b)
480
+
481
+
482
+ def trunc_normal_tf_(
483
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
484
+ ) -> torch.Tensor:
485
+ """Fills the input Tensor with values drawn from a truncated
486
+ normal distribution. The values are effectively drawn from the
487
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
488
+ with values outside :math:`[a, b]` redrawn until they are within
489
+ the bounds. The method used for generating the random values works
490
+ best when :math:`a \\leq \text{mean} \\leq b`.
491
+
492
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
493
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
494
+ and the result is subsequently scaled and shifted by the mean and std args.
495
+
496
+ Args:
497
+ tensor: an n-dimensional `torch.Tensor`
498
+ mean: the mean of the normal distribution
499
+ std: the standard deviation of the normal distribution
500
+ a: the minimum cutoff value
501
+ b: the maximum cutoff value
502
+ """
503
+ with torch.no_grad():
504
+ _trunc_normal_(tensor, 0, 1.0, a, b)
505
+ tensor.mul_(std).add_(mean)
506
+
507
+
508
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
509
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
510
+ if mode == "fan_in":
511
+ denom = fan_in
512
+ elif mode == "fan_out":
513
+ denom = fan_out
514
+ elif mode == "fan_avg":
515
+ denom = (fan_in + fan_out) / 2
516
+
517
+ variance = scale / denom
518
+
519
+ if distribution == "truncated_normal":
520
+ # constant is stddev of standard normal truncated to (-2, 2)
521
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
522
+ elif distribution == "normal":
523
+ with torch.no_grad():
524
+ tensor.normal_(std=math.sqrt(variance))
525
+ elif distribution == "uniform":
526
+ bound = math.sqrt(3 * variance)
527
+ with torch.no_grad():
528
+ tensor.uniform_(-bound, bound)
529
+ else:
530
+ raise ValueError(f"invalid distribution {distribution}")
531
+
532
+
533
+ def lecun_normal_(tensor):
534
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
535
+
536
+
537
+ def default_flax_embed_init(tensor):
538
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
539
+
540
+
541
+ @auto_docstring
542
+ class Fgclip2PreTrainedModel(PreTrainedModel):
543
+ config: Fgclip2Config
544
+ base_model_prefix = "fgclip2"
545
+ supports_gradient_checkpointing = True
546
+
547
+ _no_split_modules = [
548
+ "Fgclip2TextEmbeddings",
549
+ "Fgclip2VisionEmbeddings",
550
+ "Fgclip2EncoderLayer",
551
+ "Fgclip2MultiheadAttentionPoolingHead",
552
+ ]
553
+ _supports_flash_attn = True
554
+ _supports_sdpa = True
555
+ _supports_flex_attn = True
556
+ _supports_attention_backend = True
557
+
558
+ _can_record_outputs = {
559
+ "hidden_states": Fgclip2EncoderLayer,
560
+ "attentions": Fgclip2Attention,
561
+ }
562
+
563
+ def _init_weights(self, module):
564
+ """Initialize the weights"""
565
+ if isinstance(module, Fgclip2VisionEmbeddings):
566
+ width = (
567
+ self.config.vision_config.hidden_size
568
+ if isinstance(self.config, Fgclip2Config)
569
+ else self.config.hidden_size
570
+ )
571
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
572
+ elif isinstance(module, nn.Embedding):
573
+ default_flax_embed_init(module.weight)
574
+ elif isinstance(module, Fgclip2Attention):
575
+ nn.init.xavier_uniform_(module.q_proj.weight)
576
+ nn.init.xavier_uniform_(module.k_proj.weight)
577
+ nn.init.xavier_uniform_(module.v_proj.weight)
578
+ nn.init.xavier_uniform_(module.out_proj.weight)
579
+ nn.init.zeros_(module.q_proj.bias)
580
+ nn.init.zeros_(module.k_proj.bias)
581
+ nn.init.zeros_(module.v_proj.bias)
582
+ nn.init.zeros_(module.out_proj.bias)
583
+ elif isinstance(module, Fgclip2MLP):
584
+ nn.init.xavier_uniform_(module.fc1.weight)
585
+ nn.init.xavier_uniform_(module.fc2.weight)
586
+ nn.init.normal_(module.fc1.bias, std=1e-6)
587
+ nn.init.normal_(module.fc2.bias, std=1e-6)
588
+ elif isinstance(module, Fgclip2MultiheadAttentionPoolingHead):
589
+ nn.init.xavier_uniform_(module.probe.data)
590
+ nn.init.xavier_uniform_(module.attention.in_proj_weight.data)
591
+ nn.init.zeros_(module.attention.in_proj_bias.data)
592
+ elif isinstance(module, Fgclip2Model):
593
+ logit_scale_init = torch.log(torch.tensor(1.0))
594
+ module.logit_scale.data.fill_(logit_scale_init)
595
+ module.logit_bias.data.zero_()
596
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
597
+ lecun_normal_(module.weight)
598
+ if module.bias is not None:
599
+ nn.init.zeros_(module.bias)
600
+ elif isinstance(module, nn.LayerNorm):
601
+ module.bias.data.zero_()
602
+ module.weight.data.fill_(1.0)
603
+
604
+
605
+ class Fgclip2TextEmbeddings(nn.Module):
606
+ def __init__(self, config: Fgclip2TextConfig):
607
+ super().__init__()
608
+ embed_dim = config.hidden_size
609
+
610
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
611
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
612
+
613
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
614
+ self.register_buffer(
615
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
616
+ )
617
+
618
+ keep_len = config.keep_len
619
+ longtext_len = config.longtext_len
620
+
621
+ self.position_embedding_res = nn.Embedding(longtext_len, embed_dim)
622
+ self.position_embedding_ori = nn.Embedding(longtext_len, embed_dim)
623
+
624
+ self.mask1 = torch.zeros([longtext_len, 1])
625
+ self.mask1[:keep_len, :] = 1
626
+ self.mask2 = torch.zeros([longtext_len, 1])
627
+ self.mask2[keep_len:, :] = 1
628
+
629
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
630
+ self.register_buffer("position_ids", torch.arange(longtext_len).expand((1, -1)), persistent=False)
631
+
632
+ def forward(
633
+ self,
634
+ input_ids: Optional[torch.LongTensor] = None,
635
+ position_ids: Optional[torch.LongTensor] = None,
636
+ inputs_embeds: Optional[torch.FloatTensor] = None,
637
+ use_short_position_ids: Optional[bool] = True,
638
+ ) -> torch.Tensor:
639
+ r"""
640
+ Args:
641
+ use_short_position_ids (`bool`, optional, defaults to `True`):
642
+ If `True`, applies a positional encoding scheme optimized for **short-text processing** and **local-region description processing**,
643
+ such as phrases or simple sentences. Corresponds to the `"short"` and `"box"` walk type.
644
+ Assumes compact semantic structure and local dependency dominance.
645
+ """
646
+
647
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
648
+
649
+ if position_ids is None:
650
+ position_ids = self.position_ids[:, :seq_length]
651
+
652
+ if inputs_embeds is None:
653
+ inputs_embeds = self.token_embedding(input_ids)
654
+
655
+ if use_short_position_ids:
656
+ position_embeddings = self.position_embedding(position_ids)
657
+ embeddings = inputs_embeds + position_embeddings
658
+ else:
659
+ position_embeddings_res = self.position_embedding_res(position_ids)
660
+ position_embeddings_ori = self.position_embedding_ori(position_ids)
661
+ embeddings = (
662
+ inputs_embeds
663
+ + (position_embeddings_ori * self.mask1.to(inputs_embeds.device))
664
+ .type(inputs_embeds.dtype)
665
+ .to(inputs_embeds.device)
666
+ + (position_embeddings_res * self.mask2.to(inputs_embeds.device))
667
+ .type(inputs_embeds.dtype)
668
+ .to(inputs_embeds.device)
669
+ )
670
+
671
+ return embeddings
672
+
673
+
674
+ class Fgclip2TextTransformer(nn.Module):
675
+ def __init__(self, config: Fgclip2TextConfig):
676
+ super().__init__()
677
+ self.config = config
678
+ embed_dim = config.hidden_size
679
+ self.embeddings = Fgclip2TextEmbeddings(config)
680
+ self.encoder = Fgclip2Encoder(config)
681
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
682
+
683
+ self.head = nn.Linear(embed_dim, config.projection_size)
684
+
685
+ @can_return_tuple
686
+ @auto_docstring
687
+ def forward(
688
+ self,
689
+ input_ids: Optional[torch.Tensor] = None,
690
+ attention_mask: Optional[torch.Tensor] = None,
691
+ position_ids: Optional[torch.Tensor] = None,
692
+ walk_type: str = "short", # Modified: Single parameter
693
+ **kwargs: Unpack[TransformersKwargs],
694
+ ) -> BaseModelOutputWithPooling:
695
+ r"""
696
+ Args:
697
+ walk_type (`str`, optional, defaults to `"short"`):
698
+ The traversal strategy used during feature extraction. Must be one of
699
+ `"short"`, `"box"`, or `"long"`. This controls how contextual information
700
+ is aggregated across the input:
701
+ - `"short"`: Optimized for short-text understanding, focusing on tight semantic coherence
702
+ and direct word interactions. Suitable when the input is a phrase or brief sentence.
703
+ - `"box"`: Designed for local-region description processing, such as grounding in vision-language
704
+ models or processing localized textual descriptions (e.g., object regions or segments).
705
+ Emphasizes dense features within bounded semantic units.
706
+ - `"long"`: Tailored for long-form text processing, enabling modeling of extended dependencies
707
+ and discourse structure. Uses strategies like chunking or hierarchical attention to handle
708
+ longer sequences effectively.
709
+ """
710
+ if input_ids is None:
711
+ raise ValueError("You have to specify input_ids")
712
+
713
+ # Validate walk_type
714
+ walk_type = walk_type.lower()
715
+ if walk_type not in ["short", "box", "long"]:
716
+ raise ValueError(f"Invalid `walk_type`: {walk_type}. Must be one of 'short', 'box', 'long'.")
717
+
718
+ # Convert walk_type to boolean flags for internal logic
719
+ walk_short = walk_type == "short"
720
+ walk_box = walk_type == "box"
721
+ walk_long = walk_type == "long"
722
+
723
+ input_shape = input_ids.size()
724
+ input_ids = input_ids.view(-1, input_shape[-1])
725
+ hidden_states = self.embeddings(
726
+ input_ids=input_ids, position_ids=position_ids, use_short_position_ids=(not walk_long)
727
+ )
728
+ # note: fgclip2's text model does not use a causal mask, unlike the original CLIP model.
729
+ # expand attention_mask
730
+ uses_flash_attention = "flash" in self.config._attn_implementation
731
+ if uses_flash_attention:
732
+ attention_mask = None
733
+ elif attention_mask is not None and not uses_flash_attention:
734
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
735
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
736
+ encoder_outputs: BaseModelOutput = self.encoder(
737
+ inputs_embeds=hidden_states,
738
+ attention_mask=attention_mask,
739
+ **kwargs,
740
+ )
741
+ last_hidden_state = encoder_outputs.last_hidden_state
742
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
743
+ # The model uses the last token's hidden state, which may be padding.
744
+ pooled_output = last_hidden_state[:, -1, :]
745
+ if walk_short == True:
746
+ assert walk_box == False
747
+ assert walk_long == False
748
+ temp_pool_out = []
749
+ for i in range(pooled_output.shape[0]):
750
+ temp_pool_out.append(self.head(pooled_output[i : i + 1]))
751
+ pooled_output = torch.cat(temp_pool_out, dim=0)
752
+ # pooled_output = self.head(pooled_output)
753
+ if walk_box == True:
754
+ assert walk_short == False
755
+ assert walk_long == False
756
+ pooled_output = pooled_output
757
+ if walk_long == True:
758
+ assert walk_short == False
759
+ assert walk_box == False
760
+ pooled_output = pooled_output
761
+ return BaseModelOutputWithPooling(
762
+ last_hidden_state=last_hidden_state,
763
+ pooler_output=pooled_output,
764
+ )
765
+
766
+
767
+ @auto_docstring(
768
+ custom_intro="""
769
+ The text model from Fgclip2 without any head or projection on top.
770
+ """
771
+ )
772
+ class Fgclip2TextModel(Fgclip2PreTrainedModel):
773
+ config: Fgclip2TextConfig
774
+
775
+ def __init__(self, config: Fgclip2TextConfig):
776
+ super().__init__(config)
777
+ self.text_model = Fgclip2TextTransformer(config)
778
+ # Initialize weights and apply final processing
779
+ self.post_init()
780
+
781
+ def get_input_embeddings(self) -> nn.Module:
782
+ return self.text_model.embeddings.token_embedding
783
+
784
+ def set_input_embeddings(self, value):
785
+ self.text_model.embeddings.token_embedding = value
786
+
787
+ @check_model_inputs
788
+ @auto_docstring
789
+ def forward(
790
+ self,
791
+ input_ids: Optional[torch.Tensor] = None,
792
+ attention_mask: Optional[torch.Tensor] = None,
793
+ position_ids: Optional[torch.Tensor] = None,
794
+ walk_type: str = "short", # Modified: Single parameter
795
+ **kwargs: Unpack[TransformersKwargs],
796
+ ) -> BaseModelOutputWithPooling:
797
+ r"""
798
+ Args:
799
+ walk_type (`str`, optional, defaults to `"short"`):
800
+ The traversal strategy used during feature extraction. Must be one of
801
+ `"short"`, `"box"`, or `"long"`. This controls how contextual information
802
+ is aggregated across the input:
803
+ - `"short"`: Optimized for short-text understanding, focusing on tight semantic coherence
804
+ and direct word interactions. Suitable when the input is a phrase or brief sentence.
805
+ - `"box"`: Designed for local-region description processing, such as grounding in vision-language
806
+ models or processing localized textual descriptions (e.g., object regions or segments).
807
+ Emphasizes dense features within bounded semantic units.
808
+ - `"long"`: Tailored for long-form text processing, enabling modeling of extended dependencies
809
+ and discourse structure. Uses strategies like chunking or hierarchical attention to handle
810
+ longer sequences effectively.
811
+ """
812
+ return self.text_model(
813
+ input_ids=input_ids,
814
+ attention_mask=attention_mask,
815
+ position_ids=position_ids,
816
+ walk_type=walk_type, # Modified: Pass single parameter
817
+ **kwargs,
818
+ )
819
+
820
+
821
+ class Fgclip2MultiheadAttentionPoolingHead(nn.Module):
822
+ """Multihead Attention Pooling."""
823
+
824
+ def __init__(self, config: Fgclip2VisionConfig):
825
+ super().__init__()
826
+
827
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
828
+ self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
829
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
830
+ self.mlp = Fgclip2MLP(config)
831
+ self.num_heads = config.num_attention_heads
832
+
833
+ def forward(self, hidden_state: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
834
+ batch_size = hidden_state.shape[0]
835
+ probe = self.probe.repeat(batch_size, 1, 1)
836
+
837
+ if attention_mask is not None:
838
+ target_len, source_len = probe.shape[1], hidden_state.shape[1]
839
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_state.dtype, target_len)
840
+ attention_mask = attention_mask.repeat(1, self.num_heads, target_len, 1)
841
+ attention_mask = attention_mask.reshape(-1, target_len, source_len)
842
+
843
+ group_size = self.num_heads
844
+ outputs = []
845
+ for i in range(batch_size):
846
+ start_idx = i * group_size
847
+ end_idx = start_idx + group_size
848
+ out_i = self.attention(
849
+ probe[i : i + 1],
850
+ hidden_state[i : i + 1],
851
+ hidden_state[i : i + 1],
852
+ attn_mask=attention_mask[start_idx:end_idx] if attention_mask is not None else None,
853
+ )[0]
854
+ outputs.append(out_i)
855
+
856
+ hidden_state = torch.cat(outputs, dim=0)
857
+ residual = hidden_state
858
+ hidden_state = self.layernorm(hidden_state)
859
+
860
+ temp_outs = []
861
+ for k in range(batch_size):
862
+ out_k = self.mlp(hidden_state[k : k + 1])
863
+ temp_outs.append(out_k)
864
+ hidden_state = residual + torch.cat(temp_outs, dim=0)
865
+
866
+ return hidden_state[:, 0]
867
+
868
+
869
+ @auto_docstring(
870
+ custom_intro="""
871
+ The vision model from Fgclip2 without any head or projection on top.
872
+ """
873
+ )
874
+ class Fgclip2VisionModel(Fgclip2PreTrainedModel):
875
+ config: Fgclip2VisionConfig
876
+ main_input_name = "pixel_values"
877
+
878
+ def __init__(self, config: Fgclip2VisionConfig):
879
+ super().__init__(config)
880
+
881
+ self.vision_model = Fgclip2VisionTransformer(config)
882
+
883
+ # Initialize weights and apply final processing
884
+ self.post_init()
885
+
886
+ def get_input_embeddings(self) -> nn.Module:
887
+ return self.vision_model.embeddings.patch_embedding
888
+
889
+ @check_model_inputs
890
+ @auto_docstring
891
+ def forward(
892
+ self,
893
+ pixel_values: torch.FloatTensor,
894
+ pixel_attention_mask: torch.Tensor,
895
+ spatial_shapes: torch.LongTensor,
896
+ output_attentions: Optional[bool] = None,
897
+ output_hidden_states: Optional[bool] = None,
898
+ ) -> BaseModelOutputWithPooling:
899
+ r"""
900
+ pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
901
+ Mask to avoid performing attention on padding pixel indices.
902
+ spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
903
+ Tensor containing the spatial dimensions (height, width) of the input images.
904
+
905
+ Examples:
906
+
907
+ ```python
908
+ >>> from PIL import Image
909
+ >>> import requests
910
+ >>> from transformers import AutoProcessor, Fgclip2VisionModel
911
+
912
+ >>> model = Fgclip2VisionModel.from_pretrained("qihoo360/fg-clip2-base")
913
+ >>> processor = AutoProcessor.from_pretrained("qihoo360/fg-clip2-base")
914
+
915
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
916
+ >>> image = Image.open(requests.get(url, stream=True).raw)
917
+
918
+ >>> inputs = processor(images=image, return_tensors="pt")
919
+
920
+ >>> outputs = model(**inputs)
921
+ >>> last_hidden_state = outputs.last_hidden_state
922
+ >>> pooled_output = outputs.pooler_output # pooled features
923
+ ```"""
924
+ return self.vision_model(
925
+ pixel_values=pixel_values,
926
+ attention_mask=pixel_attention_mask,
927
+ spatial_shapes=spatial_shapes,
928
+ output_attentions=output_attentions,
929
+ output_hidden_states=output_hidden_states,
930
+ )
931
+
932
+
933
+ @auto_docstring
934
+ class Fgclip2Model(Fgclip2PreTrainedModel):
935
+ config: Fgclip2Config
936
+
937
+ def __init__(self, config: Fgclip2Config):
938
+ super().__init__(config)
939
+
940
+ if not isinstance(config.text_config, Fgclip2TextConfig):
941
+ raise TypeError(
942
+ "config.text_config is expected to be of type Fgclip2TextConfig but is of type"
943
+ f" {type(config.text_config)}."
944
+ )
945
+
946
+ if not isinstance(config.vision_config, Fgclip2VisionConfig):
947
+ raise TypeError(
948
+ "config.vision_config is expected to be of type Fgclip2VisionConfig but is of type"
949
+ f" {type(config.vision_config)}."
950
+ )
951
+
952
+ text_config = config.text_config
953
+ vision_config = config.vision_config
954
+
955
+ # First, initialize the text and vision models with proper attention implementation
956
+ text_model = Fgclip2TextModel._from_config(text_config)
957
+ vision_model = Fgclip2VisionModel._from_config(vision_config)
958
+
959
+ # Second, get the text and vision submodules (for backward compatibility)
960
+ self.text_model = text_model.text_model
961
+ self.vision_model = vision_model.vision_model
962
+
963
+ self.logit_scale = nn.Parameter(torch.randn(1))
964
+ self.logit_bias = nn.Parameter(torch.randn(1))
965
+ self.dense_feature_head = Fgclip2MultiheadAttentionPoolingHead(vision_config)
966
+ self.embed_dim = text_config.hidden_size
967
+ self.longtext_head = nn.Linear(self.embed_dim, self.embed_dim)
968
+ self.boxtext_head = nn.Linear(self.embed_dim, self.embed_dim)
969
+
970
+ # Initialize weights and apply final processing
971
+ self.post_init()
972
+
973
+ @filter_out_non_signature_kwargs()
974
+ @auto_docstring
975
+ def get_text_features(
976
+ self,
977
+ input_ids: torch.Tensor,
978
+ attention_mask: Optional[torch.Tensor] = None,
979
+ position_ids: Optional[torch.Tensor] = None,
980
+ walk_type: str = "short",
981
+ ) -> torch.FloatTensor:
982
+ r"""
983
+ Extracts feature representations from the input text.
984
+
985
+ Args:
986
+ input_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`):
987
+ The token IDs of the input sequence, as generated by the tokenizer.
988
+ attention_mask (`torch.Tensor`, optional, of shape `(batch_size, sequence_length)`):
989
+ A mask indicating which tokens are valid (1) and which are padding (0).
990
+ If not provided, all tokens are assumed to be valid.
991
+ position_ids (`torch.Tensor`, optional, of shape `(batch_size, sequence_length)`):
992
+ Position indices for each token in the sequence. If not provided,
993
+ positions are automatically constructed based on `input_ids`.
994
+ walk_type (`str`, optional, defaults to `"short"`):
995
+ The traversal strategy used during feature extraction. Must be one of
996
+ `"short"`, `"box"`, or `"long"`. This controls how contextual information
997
+ is aggregated across the input:
998
+ - `"short"`: Optimized for short-text understanding, focusing on tight semantic coherence
999
+ and direct word interactions. Suitable when the input is a phrase or brief sentence.
1000
+ - `"box"`: Designed for local-region description processing, such as grounding in vision-language
1001
+ models or processing localized textual descriptions (e.g., object regions or segments).
1002
+ Emphasizes dense features within bounded semantic units.
1003
+ - `"long"`: Tailored for long-form text processing, enabling modeling of extended dependencies
1004
+ and discourse structure. Uses strategies like chunking or hierarchical attention to handle
1005
+ longer sequences effectively.
1006
+
1007
+ Returns:
1008
+ `torch.FloatTensor` of shape `(batch_size, hidden_size)` or `(batch_size, sequence_length, hidden_size)`:
1009
+ The extracted feature tensor representing the input text. The output shape depends on
1010
+ whether a pooled representation or per-token embeddings are returned.
1011
+
1012
+ Examples:
1013
+
1014
+ ```python
1015
+ >>> from transformers import AutoTokenizer, AutoModel
1016
+ >>> import torch
1017
+
1018
+ >>> model = AutoModel.from_pretrained("qihoo360/fg-clip2-base")
1019
+ >>> tokenizer = AutoTokenizer.from_pretrained("qihoo360/fg-clip2-base")
1020
+
1021
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
1022
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
1023
+ >>> with torch.no_grad():
1024
+ ... text_features = model.get_text_features(**inputs, walk_type="short")
1025
+ ```"""
1026
+
1027
+ walk_type = walk_type.lower()
1028
+
1029
+ if walk_type not in ["short", "box", "long"]:
1030
+ raise ValueError(f"Invalid `walk_type`: {walk_type}. Must be one of 'short', 'box', 'long'.")
1031
+
1032
+ walk_short = walk_type == "short"
1033
+ walk_box = walk_type == "box"
1034
+ walk_long = walk_type == "long"
1035
+
1036
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
1037
+ input_ids=input_ids,
1038
+ attention_mask=attention_mask,
1039
+ position_ids=position_ids,
1040
+ walk_type=walk_type,
1041
+ )
1042
+
1043
+ if walk_short:
1044
+ pooled_output = text_outputs.pooler_output
1045
+
1046
+ if walk_box:
1047
+ pooled_output = self.boxtext_head(text_outputs.pooler_output)
1048
+
1049
+ if walk_long:
1050
+ pooled_output = self.longtext_head(text_outputs.pooler_output)
1051
+
1052
+ return pooled_output
1053
+
1054
+ @filter_out_non_signature_kwargs()
1055
+ @auto_docstring
1056
+ def get_image_features(
1057
+ self,
1058
+ pixel_values: Optional[torch.FloatTensor] = None,
1059
+ pixel_attention_mask: Optional[torch.Tensor] = None,
1060
+ spatial_shapes: Optional[torch.LongTensor] = None,
1061
+ ) -> torch.FloatTensor:
1062
+ r"""
1063
+ pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
1064
+ Mask to avoid performing attention on padding pixel indices.
1065
+ spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
1066
+ Tensor containing the spatial dimensions (height, width) of the input images.
1067
+
1068
+ Returns:
1069
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
1070
+ applying the projection layer to the pooled output of [`Fgclip2VisionModel`].
1071
+
1072
+ Examples:
1073
+
1074
+ ```python
1075
+ >>> import torch
1076
+ >>> from transformers import AutoProcessor, AutoModel
1077
+ >>> from transformers.image_utils import load_image
1078
+
1079
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1080
+ >>> image = load_image(url)
1081
+
1082
+ >>> model = AutoModel.from_pretrained("qihoo360/fg-clip2-base")
1083
+ >>> processor = AutoProcessor.from_pretrained("qihoo360/fg-clip2-base")
1084
+
1085
+ >>> inputs = processor(images=image, return_tensors="pt")
1086
+
1087
+ >>> with torch.no_grad():
1088
+ ... image_features = model.get_image_features(**inputs)
1089
+ ```
1090
+ """
1091
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
1092
+ pixel_values=pixel_values,
1093
+ attention_mask=pixel_attention_mask,
1094
+ spatial_shapes=spatial_shapes,
1095
+ )
1096
+ pooled_output = vision_outputs.pooler_output
1097
+
1098
+ return pooled_output
1099
+
1100
+ # NOTE: Fgclip2Model uses Pretrained backbones, so we don't need to add `check_model_inputs` here
1101
+ @can_return_tuple
1102
+ @auto_docstring
1103
+ def forward(
1104
+ self,
1105
+ input_ids: Optional[torch.LongTensor] = None,
1106
+ pixel_values: Optional[torch.FloatTensor] = None,
1107
+ pixel_attention_mask: Optional[torch.Tensor] = None,
1108
+ spatial_shapes: Optional[torch.LongTensor] = None,
1109
+ attention_mask: Optional[torch.Tensor] = None,
1110
+ position_ids: Optional[torch.LongTensor] = None,
1111
+ return_loss: Optional[bool] = None,
1112
+ output_attentions: Optional[bool] = None,
1113
+ output_hidden_states: Optional[bool] = None,
1114
+ walk_type: str = "short",
1115
+ ) -> Fgclip2Output:
1116
+ r"""
1117
+ pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
1118
+ Mask to avoid performing attention on padding pixel indices.
1119
+ spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
1120
+ Tensor containing the spatial dimensions (height, width) of the input images.
1121
+ return_loss (`bool`, *optional*):
1122
+ Whether or not to return the contrastive loss.
1123
+ walk_type (`str`, optional, defaults to `"short"`):
1124
+ The traversal strategy used during feature extraction. Must be one of
1125
+ `"short"`, `"box"`, or `"long"`. This controls how contextual information
1126
+ is aggregated across the input:
1127
+ - `"short"`: Optimized for short-text understanding, focusing on tight semantic coherence
1128
+ and direct word interactions. Suitable when the input is a phrase or brief sentence.
1129
+ - `"box"`: Designed for local-region description processing, such as grounding in vision-language
1130
+ models or processing localized textual descriptions (e.g., object regions or segments).
1131
+ Emphasizes dense features within bounded semantic units.
1132
+ - `"long"`: Tailored for long-form text processing, enabling modeling of extended dependencies
1133
+ and discourse structure. Uses strategies like chunking or hierarchical attention to handle
1134
+ longer sequences effectively.
1135
+
1136
+
1137
+ Examples:
1138
+
1139
+ ```python
1140
+ >>> from PIL import Image
1141
+ >>> import requests
1142
+ >>> from transformers import AutoProcessor, AutoModel
1143
+ >>> import torch
1144
+
1145
+ >>> model = AutoModel.from_pretrained("qihoo360/fg-clip2-base")
1146
+ >>> processor = AutoProcessor.from_pretrained("qihoo360/fg-clip2-base")
1147
+
1148
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1149
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1150
+
1151
+ >>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
1152
+ >>> # important: we pass `padding=max_length` since the model was trained with this
1153
+ >>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
1154
+
1155
+ >>> with torch.no_grad():
1156
+ ... outputs = model(**inputs)
1157
+
1158
+ >>> logits_per_image = outputs.logits_per_image
1159
+ >>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
1160
+ >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
1161
+ 31.9% that image 0 is 'a photo of 2 cats'
1162
+ ```
1163
+ """
1164
+ walk_type = walk_type.lower()
1165
+
1166
+ if walk_type not in ["short", "box", "long"]:
1167
+ raise ValueError(f"Invalid `walk_type`: {walk_type}. Must be one of 'short', 'box', 'long'.")
1168
+
1169
+ walk_short = walk_type == "short"
1170
+ walk_box = walk_type == "box"
1171
+ walk_long = walk_type == "long"
1172
+
1173
+ # Use Fgclip2 model's config for some fields (if specified) instead of those of vision & text components.
1174
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1175
+ output_hidden_states = (
1176
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1177
+ )
1178
+
1179
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
1180
+ pixel_values=pixel_values,
1181
+ attention_mask=pixel_attention_mask,
1182
+ spatial_shapes=spatial_shapes,
1183
+ output_attentions=output_attentions,
1184
+ output_hidden_states=output_hidden_states,
1185
+ )
1186
+
1187
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
1188
+ input_ids=input_ids,
1189
+ attention_mask=attention_mask,
1190
+ position_ids=position_ids,
1191
+ output_attentions=output_attentions,
1192
+ output_hidden_states=output_hidden_states,
1193
+ walk_type=walk_type,
1194
+ )
1195
+
1196
+ image_embeds = vision_outputs.pooler_output
1197
+
1198
+ if walk_short:
1199
+ text_embeds = text_outputs.pooler_output
1200
+
1201
+ if walk_box:
1202
+ text_embeds = self.boxtext_head(text_outputs.pooler_output)
1203
+
1204
+ if walk_long:
1205
+ text_embeds = self.longtext_head(text_outputs.pooler_output)
1206
+
1207
+ # normalized features
1208
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1209
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1210
+
1211
+ # cosine similarity as logits
1212
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device))
1213
+
1214
+ logit_scale, logit_bias = self.logit_scale.to(text_embeds.device), self.logit_bias.to(text_embeds.device)
1215
+ logits_per_text = logits_per_text * logit_scale.exp() + logit_bias
1216
+
1217
+ logits_per_image = logits_per_text.t()
1218
+
1219
+ loss = None
1220
+ if return_loss:
1221
+ # Adapted from https://github.com/google-research/big_vision/blob/01edb81a4716f93a48be43b3a4af14e29cdb3a7f/big_vision/trainers/proj/image_text/fgclip2.py#L287
1222
+ eye = torch.eye(logits_per_text.size(0), device=logits_per_text.device)
1223
+ m1_diag1 = -torch.ones_like(logits_per_text) + 2 * eye
1224
+ loglik = torch.nn.functional.logsigmoid(m1_diag1 * logits_per_text)
1225
+ nll = -torch.sum(loglik, dim=-1)
1226
+ loss = nll.mean()
1227
+
1228
+ return Fgclip2Output(
1229
+ loss=loss,
1230
+ logits_per_image=logits_per_image,
1231
+ logits_per_text=logits_per_text,
1232
+ text_embeds=text_embeds,
1233
+ image_embeds=image_embeds,
1234
+ text_model_output=text_outputs,
1235
+ vision_model_output=vision_outputs,
1236
+ )
1237
+
1238
+ # New function: Acquire dense visual features of images with support for dynamic resolution
1239
+ @filter_out_non_signature_kwargs()
1240
+ @auto_docstring
1241
+ def get_image_dense_feature(
1242
+ self,
1243
+ pixel_values: Optional[torch.FloatTensor] = None,
1244
+ pixel_attention_mask: Optional[torch.Tensor] = None,
1245
+ spatial_shapes: Optional[torch.LongTensor] = None,
1246
+ ) -> torch.FloatTensor:
1247
+ r"""
1248
+ Extract dense visual features from input images by forwarding through the vision backbone.
1249
+
1250
+ Args:
1251
+ pixel_values (`torch.FloatTensor`):
1252
+ Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size)
1253
+ pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
1254
+ Mask to avoid performing attention on padding pixel indices.
1255
+ spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
1256
+ Tensor containing the spatial dimensions (height, width) of the input images.
1257
+
1258
+ Returns:
1259
+ `torch.FloatTensor` of shape `(batch_size, max_num_patches, hidden_size)`:
1260
+
1261
+ """
1262
+
1263
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
1264
+ pixel_values=pixel_values,
1265
+ attention_mask=pixel_attention_mask,
1266
+ spatial_shapes=spatial_shapes,
1267
+ )
1268
+
1269
+ probe = vision_outputs.last_hidden_state
1270
+ hidden_state = vision_outputs.last_hidden_state
1271
+ attention_mask = pixel_attention_mask
1272
+
1273
+ if attention_mask is not None:
1274
+ target_len, source_len = probe.shape[1], hidden_state.shape[1]
1275
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_state.dtype, target_len)
1276
+ attention_mask = attention_mask.repeat(1, self.dense_feature_head.num_heads, 1, 1)
1277
+ attention_mask = attention_mask.reshape(-1, target_len, source_len)
1278
+
1279
+ hidden_state = self.dense_feature_head.attention(probe, hidden_state, hidden_state, attn_mask=attention_mask)[
1280
+ 0
1281
+ ]
1282
+ residual = hidden_state
1283
+ hidden_state = self.dense_feature_head.layernorm(hidden_state)
1284
+ hidden_state = residual + self.dense_feature_head.mlp(hidden_state)
1285
+ feature_map = hidden_state
1286
+
1287
+ return feature_map
1288
+
1289
+ # New function: Acquire local features of images, applicable to retrieval, classification, and localization, with support for dynamic resolution
1290
+ @filter_out_non_signature_kwargs()
1291
+ @auto_docstring
1292
+ def get_image_region_features(
1293
+ self,
1294
+ pixel_values: Optional[torch.FloatTensor] = None,
1295
+ pixel_attention_mask: Optional[torch.Tensor] = None,
1296
+ spatial_shapes: Optional[torch.LongTensor] = None,
1297
+ image_sizes: Optional[list[tuple]] = None,
1298
+ region_infos: Optional[list[list[list[float]]]] = None,
1299
+ ) -> list[torch.FloatTensor]:
1300
+ r"""
1301
+ Extract region-of-interest (RoI) features from images using RoI Align.
1302
+ This method supports batched processing of variable-sized images and allows feature extraction
1303
+ from user-specified image regions.
1304
+
1305
+ The input can be either a full image with corresponding region coordinates.
1306
+ Features are extracted per region (e.g., bounding boxes), making this function suitable for tasks such as
1307
+ object detection, referring expression grounding, or vision-language alignment.
1308
+
1309
+ Args:
1310
+ pixel_values (`torch.FloatTensor`):
1311
+ Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size)
1312
+ pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
1313
+ Mask to avoid performing attention on padding pixel indices.
1314
+ spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`):
1315
+ Tensor containing the spatial dimensions (height, width) of the input images.
1316
+ image_sizes (`List[tuple]`, optional, each tuple of form `(int, int)`):
1317
+ Original size (height, width) of each image in the batch before padding or resizing.
1318
+ Required for accurate coordinate projection when region_infos are defined in original image space.
1319
+ region_infos (`List[List[List[float]]]`, optional):
1320
+ Bounding box coordinates for regions of interest in each image. Format:
1321
+ - Outer list: length `batch_size`
1322
+ - Middle list: number of regions per image
1323
+ - Inner list: each contains `[x_min, y_min, x_max, y_max]` in **absolute pixel coordinates**
1324
+ relative to the original image size (as specified in `image_sizes`).
1325
+ These boxes are projected to feature map space using `image_sizes` and `spatial_shapes`,
1326
+ then used to pool features via RoI Align or equivalent.
1327
+
1328
+ Returns:
1329
+ `List[torch.FloatTensor]`:
1330
+ A list of length `batch_size`, where each element is a tensor of shape
1331
+ `(num_boxes, hidden_dim)` containing the extracted visual features for each region
1332
+ in the corresponding image.
1333
+ Example::
1334
+ >>> # For a batch of 2 images
1335
+ >>> region_features = model.get_image_region_features(
1336
+ >>> pixel_values=pixel_values,
1337
+ >>> image_sizes=[(640, 480), (480, 640)],
1338
+ >>> region_infos=[
1339
+ >>> [[100, 100, 200, 200], [300, 300, 400, 400]], # 2 boxes in first image
1340
+ >>> [[50, 50, 150, 150]] # 1 box in second image
1341
+ >>> ]
1342
+ >>> )
1343
+ >>> print(region_features[0].shape) # torch.Size([2, hidden_dim])
1344
+ >>> print(region_features[1].shape) # torch.Size([1, hidden_dim])
1345
+
1346
+ """
1347
+ if region_infos is None or len(region_infos) == 0:
1348
+ return []
1349
+
1350
+ # Get dense feature maps: (B, N, D)
1351
+ dense_feature_map = self.get_image_dense_feature(
1352
+ pixel_values=pixel_values,
1353
+ pixel_attention_mask=pixel_attention_mask,
1354
+ spatial_shapes=spatial_shapes,
1355
+ )
1356
+ bs, _, hidden_dim = dense_feature_map.shape
1357
+
1358
+ all_region_features = []
1359
+
1360
+ for i in range(bs):
1361
+ h, w = spatial_shapes[i].tolist()
1362
+ img_h, img_w = image_sizes[i]
1363
+ bboxes = region_infos[i]
1364
+
1365
+ if not bboxes:
1366
+ all_region_features.append(torch.empty(0, hidden_dim, device=dense_feature_map.device))
1367
+ continue
1368
+
1369
+ # Reshape to (1, C, H', W')
1370
+ num_valid = h * w
1371
+ feat_seq = dense_feature_map[i, :num_valid] # (num_valid, D)
1372
+ feat_map = feat_seq.view(h, w, hidden_dim).permute(2, 0, 1).unsqueeze(0) # (1, D, H', W')
1373
+
1374
+ # Normalize bboxes to feature map coordinates
1375
+ rois = []
1376
+ for x1, y1, x2, y2 in bboxes:
1377
+ nx1 = (x1 / img_w) * w
1378
+ ny1 = (y1 / img_h) * h
1379
+ nx2 = (x2 / img_w) * w
1380
+ ny2 = (y2 / img_h) * h
1381
+ rois.append([0, nx1, ny1, nx2, ny2]) #
1382
+ rois_tensor = torch.tensor(rois, dtype=torch.float32, device=feat_map.device) # (N, 5)
1383
+
1384
+ # RoI Align on single image
1385
+ pooled = roi_align(
1386
+ input=feat_map,
1387
+ boxes=rois_tensor,
1388
+ output_size=(1, 1),
1389
+ spatial_scale=1.0,
1390
+ sampling_ratio=-1,
1391
+ aligned=True,
1392
+ ) # (N, D, 1, 1)
1393
+ region_feats = pooled.squeeze(-1).squeeze(-1) # (N, D)
1394
+
1395
+ all_region_features.append(region_feats)
1396
+
1397
+ return all_region_features
1398
+
1399
+
1400
+ __all__ = ["Fgclip2Model", "Fgclip2PreTrainedModel", "Fgclip2TextModel", "Fgclip2VisionModel"]
fg-clip2-large/preprocessor_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1125703e5446d5b6ff4d5893a33bac128cdd21dc12e3dad2469a648fb0ae3bf7
3
+ size 393
fg-clip2-large/special_tokens_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:baec30ea10906f16adb8c18af7a34023002c1746542612b8b41c9f09e1351351
3
+ size 636
fg-clip2-large/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58a1696e79c9d97937389ed116f552a15c84811d7b8023918b86f4bc5775b1b0
3
+ size 34356304
fg-clip2-large/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2
3
+ size 4241003
fg-clip2-large/tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:607049b4766b302a66e31906a6b4729e01f623597c82262fb52e552f0d4f7fb4
3
+ size 40160
src/export_onnx.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Export FG-CLIP 2 Large (HuggingFace remote-code format) to ONNX.
3
+
4
+ Produces two standalone graphs:
5
+ * image encoder: pixel_values[1,N,768] -> image_features[1,1024]
6
+ * text encoder: input_ids[1,L] -> text_features[1,1024]
7
+
8
+ Input contract (matches the official processor / tokenizer):
9
+ image : Siglip2 patchified input. ``Siglip2ImageProcessor`` returns
10
+ ``pixel_values`` of shape [1, num_patches, 3*patch_size*patch_size].
11
+ This export fixes a square grid (default 16x16 = 256 patches, i.e. a
12
+ 256x256 image), so only ``pixel_values`` is exposed as a graph input.
13
+ text : int64 token ids padded to a fixed length. 64 for walk_type
14
+ ``short``/``box``, 196 for ``long``. The official tokenizer does not
15
+ emit an attention mask, so the graph takes ids only.
16
+
17
+ walk_type selects which text head is baked into the graph:
18
+ short -> text_model's own projection head (default, retrieval)
19
+ long -> longtext_head (long captions)
20
+ box -> boxtext_head (dense / region descriptions)
21
+
22
+ Usage:
23
+ python src/export_onnx.py
24
+ python src/export_onnx.py --walk-type long --text-length 196
25
+ """
26
+
27
+ import argparse
28
+ import json
29
+ import os
30
+ import sys
31
+
32
+ import numpy as np
33
+ import torch
34
+ import torch.nn as nn
35
+ from transformers import AutoModelForCausalLM
36
+
37
+ DEFAULT_MODEL_DIR = os.path.join(
38
+ os.path.dirname(os.path.abspath(__file__)), "..", "fg-clip2-large"
39
+ )
40
+ DEFAULT_OUTPUT_DIR = os.path.join(
41
+ os.path.dirname(os.path.abspath(__file__)), "..", "models"
42
+ )
43
+
44
+
45
+ class ImageEncoder(nn.Module):
46
+ """Vision tower with a fixed grid.
47
+
48
+ ``Fgclip2VisionEmbeddings`` resizes its positional table with
49
+ ``antialias=True``, which maps to ``aten::_upsample_bilinear2d_aa`` and has
50
+ no ONNX symbolic. The resize is an identity when the target grid equals the
51
+ table grid (the default 16x16 case), so the table is baked in directly.
52
+ For other grids we fall back to bilinear interpolation without antialias;
53
+ that differs slightly from the PyTorch default, see export_info.json.
54
+ """
55
+
56
+ def __init__(self, model, grid_h: int, grid_w: int):
57
+ super().__init__()
58
+ self.vision_model = model.vision_model
59
+ emb = model.vision_model.embeddings
60
+ table = emb.position_embedding.weight.reshape(
61
+ emb.position_embedding_size, emb.position_embedding_size, -1
62
+ )
63
+ if (grid_h, grid_w) != (emb.position_embedding_size, emb.position_embedding_size):
64
+ import torch.nn.functional as F
65
+
66
+ resized = F.interpolate(
67
+ table.permute(2, 0, 1).unsqueeze(0),
68
+ size=(grid_h, grid_w),
69
+ mode="bilinear",
70
+ align_corners=False,
71
+ antialias=False,
72
+ )
73
+ table = resized.reshape(table.shape[-1], -1).transpose(0, 1)
74
+ self.register_buffer("pos_table", table.reshape(1, -1, table.shape[-1]).clone(), persistent=False)
75
+
76
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
77
+ vm = self.vision_model
78
+ hidden = vm.embeddings.patch_embedding(pixel_values) + self.pos_table
79
+ hidden = vm.encoder(inputs_embeds=hidden, attention_mask=None).last_hidden_state
80
+ hidden = vm.post_layernorm(hidden)
81
+ return vm.head(hidden, attention_mask=None)
82
+
83
+
84
+ class TextEncoder(nn.Module):
85
+ def __init__(self, model, walk_type: str):
86
+ super().__init__()
87
+ self.text_model = model.text_model
88
+ self.walk_type = walk_type
89
+ if walk_type == "long":
90
+ self.out_head = model.longtext_head
91
+ elif walk_type == "box":
92
+ self.out_head = model.boxtext_head
93
+ else:
94
+ self.out_head = None
95
+
96
+ def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
97
+ pooled = self.text_model(input_ids=input_ids, walk_type=self.walk_type).pooler_output
98
+ if self.out_head is not None:
99
+ pooled = self.out_head(pooled)
100
+ return pooled
101
+
102
+
103
+ def build_model(model_dir: str):
104
+ model = AutoModelForCausalLM.from_pretrained(
105
+ model_dir,
106
+ trust_remote_code=True,
107
+ local_files_only=True,
108
+ )
109
+ model.eval()
110
+ model.requires_grad_(False)
111
+
112
+ # The remote config only propagates the top-level attention backend, and
113
+ # transformers 5 defaults sub-configs to sdpa; force eager everywhere.
114
+ model.config._attn_implementation = "eager"
115
+ model.config.vision_config._attn_implementation = "eager"
116
+ model.config.text_config._attn_implementation = "eager"
117
+ model.vision_model.config._attn_implementation = "eager"
118
+ model.text_model.config._attn_implementation = "eager"
119
+
120
+ # transformers 5 builds non-persistent buffers / plain attributes under a
121
+ # meta-device context. position_ids, mask1 and mask2 are never in the
122
+ # checkpoint, so rebuild them explicitly (same values as __init__).
123
+ emb = model.text_model.embeddings
124
+ cfg = model.config.text_config
125
+ idx = torch.arange(cfg.longtext_len)
126
+ emb.position_ids = idx.unsqueeze(0)
127
+ emb.mask1 = (idx.unsqueeze(1) < cfg.keep_len).to(torch.float32)
128
+ emb.mask2 = (idx.unsqueeze(1) >= cfg.keep_len).to(torch.float32)
129
+
130
+ stale = [n for n, b in model.named_buffers() if b.is_meta]
131
+ stale += [n for n, p in model.named_parameters() if p.is_meta]
132
+ if stale:
133
+ raise RuntimeError(f"unresolved meta tensors after load: {stale[:10]}")
134
+ return model
135
+
136
+
137
+ def export_graph(module, args, path, input_names, output_names, opset):
138
+ print(f"[export] {path}")
139
+ with torch.no_grad():
140
+ torch.onnx.export(
141
+ module,
142
+ args,
143
+ path,
144
+ input_names=input_names,
145
+ output_names=output_names,
146
+ opset_version=opset,
147
+ do_constant_folding=False,
148
+ export_params=True,
149
+ dynamo=False,
150
+ )
151
+
152
+
153
+ def consolidate_external_data(onnx_path):
154
+ """Merge per-tensor side-car weights into a single <model>.onnx.data file."""
155
+ import onnx
156
+
157
+ model = onnx.load(onnx_path, load_external_data=False)
158
+ locations = set()
159
+ for tensor in model.graph.initializer:
160
+ if tensor.data_location != onnx.TensorProto.EXTERNAL:
161
+ continue
162
+ for kv in tensor.external_data:
163
+ if kv.key == "location":
164
+ locations.add(kv.value)
165
+ if not locations:
166
+ return None
167
+
168
+ base = os.path.dirname(onnx_path)
169
+ onnx.external_data_helper.load_external_data_for_model(model, base)
170
+
171
+ data_name = os.path.basename(onnx_path) + ".data"
172
+ onnx.save_model(
173
+ model,
174
+ onnx_path,
175
+ save_as_external_data=True,
176
+ all_tensors_to_one_file=True,
177
+ location=data_name,
178
+ size_threshold=1024,
179
+ )
180
+
181
+ for location in locations:
182
+ stale = os.path.join(base, location)
183
+ if os.path.isfile(stale) and os.path.basename(stale) != data_name:
184
+ os.remove(stale)
185
+
186
+ return os.path.join(base, data_name)
187
+
188
+
189
+ def verify(onnx_path, module, inputs, output_name, atol, rtol):
190
+ import onnxruntime as ort
191
+
192
+ session = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])
193
+ feed = {node.name: x.numpy() for node, x in zip(session.get_inputs(), inputs)}
194
+ ort_out = session.run([output_name], feed)[0]
195
+
196
+ with torch.no_grad():
197
+ ref = module(*inputs).numpy()
198
+
199
+ abs_err = np.abs(ort_out - ref)
200
+ max_abs = float(abs_err.max())
201
+ rel = max_abs / max(float(np.abs(ref).max()), 1e-12)
202
+ ok = np.allclose(ort_out, ref, atol=atol, rtol=rtol)
203
+ print(
204
+ f"[verify] {os.path.basename(onnx_path)}: max_abs={max_abs:.3e} "
205
+ f"rel={rel:.3e} shape={ort_out.shape} -> {'OK' if ok else 'FAIL'}"
206
+ )
207
+ return ok
208
+
209
+
210
+ def main():
211
+ parser = argparse.ArgumentParser(
212
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
213
+ )
214
+ parser.add_argument("--model-dir", default=DEFAULT_MODEL_DIR)
215
+ parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR)
216
+ parser.add_argument(
217
+ "--image-size",
218
+ type=int,
219
+ default=256,
220
+ help="square input size; must be divisible by patch_size (default 256)",
221
+ )
222
+ parser.add_argument("--walk-type", choices=["short", "long", "box"], default="short")
223
+ parser.add_argument(
224
+ "--text-length",
225
+ type=int,
226
+ default=0,
227
+ help="fixed token length (0 = 64 for short/box, 196 for long)",
228
+ )
229
+ parser.add_argument("--opset", type=int, default=14)
230
+ parser.add_argument("--no-verify", action="store_true")
231
+ parser.add_argument("--atol", type=float, default=1e-4)
232
+ parser.add_argument("--rtol", type=float, default=1e-3)
233
+ args = parser.parse_args()
234
+
235
+ model_dir = os.path.abspath(args.model_dir)
236
+ output_dir = os.path.abspath(args.output_dir)
237
+ os.makedirs(output_dir, exist_ok=True)
238
+
239
+ print(f"[load] {model_dir}")
240
+ model = build_model(model_dir)
241
+ vision_cfg = model.config.vision_config
242
+ text_cfg = model.config.text_config
243
+
244
+ patch_size = vision_cfg.patch_size
245
+ if args.image_size % patch_size != 0:
246
+ raise SystemExit(f"image size {args.image_size} is not divisible by patch_size {patch_size}")
247
+ grid = args.image_size // patch_size
248
+ num_patches = grid * grid
249
+ if num_patches > vision_cfg.num_patches:
250
+ raise SystemExit(
251
+ f"grid {grid}x{grid} needs {num_patches} patches, model supports {vision_cfg.num_patches}"
252
+ )
253
+
254
+ text_length = args.text_length or (text_cfg.longtext_len if args.walk_type == "long" else text_cfg.max_position_embeddings)
255
+
256
+ image_encoder = ImageEncoder(model, grid, grid).eval()
257
+ text_encoder = TextEncoder(model, args.walk_type).eval()
258
+
259
+ image_input = torch.randn(
260
+ 1, num_patches, vision_cfg.num_channels * patch_size * patch_size
261
+ )
262
+ text_input = torch.randint(0, text_cfg.vocab_size, (1, text_length), dtype=torch.int64)
263
+
264
+ image_path = os.path.join(output_dir, "fgclip2_large_image_encoder.onnx")
265
+ text_path = os.path.join(output_dir, f"fgclip2_large_text_encoder_{args.walk_type}.onnx")
266
+
267
+ export_graph(
268
+ image_encoder,
269
+ (image_input,),
270
+ image_path,
271
+ ["pixel_values"],
272
+ ["image_features"],
273
+ args.opset,
274
+ )
275
+ export_graph(
276
+ text_encoder,
277
+ (text_input,),
278
+ text_path,
279
+ ["input_ids"],
280
+ ["text_features"],
281
+ args.opset,
282
+ )
283
+
284
+ image_data = consolidate_external_data(image_path)
285
+ text_data = consolidate_external_data(text_path)
286
+
287
+ feature_dim = text_cfg.projection_size
288
+ info = {
289
+ "model_dir": model_dir,
290
+ "opset": args.opset,
291
+ "walk_type": args.walk_type,
292
+ "image_encoder": {
293
+ "file": os.path.basename(image_path),
294
+ "external_data": os.path.basename(image_data) if image_data else None,
295
+ "input": {
296
+ "name": "pixel_values",
297
+ "shape": [1, num_patches, vision_cfg.num_channels * patch_size * patch_size],
298
+ },
299
+ "output": {"name": "image_features", "shape": [1, feature_dim]},
300
+ "preprocess": {
301
+ "image_size": args.image_size,
302
+ "patch_size": patch_size,
303
+ "grid": [grid, grid],
304
+ "mean": [0.5, 0.5, 0.5],
305
+ "std": [0.5, 0.5, 0.5],
306
+ },
307
+ },
308
+ "text_encoder": {
309
+ "file": os.path.basename(text_path),
310
+ "external_data": os.path.basename(text_data) if text_data else None,
311
+ "input": {"name": "input_ids", "shape": [1, text_length], "dtype": "int64"},
312
+ "output": {"name": "text_features", "shape": [1, feature_dim]},
313
+ "walk_type": args.walk_type,
314
+ },
315
+ }
316
+ info_path = os.path.join(output_dir, "export_info.json")
317
+ with open(info_path, "w", encoding="utf-8") as f:
318
+ json.dump(info, f, indent=2)
319
+ print(f"[info] {info_path}")
320
+
321
+ if not args.no_verify:
322
+ ok_image = verify(image_path, image_encoder, [image_input], "image_features", args.atol, args.rtol)
323
+ ok_text = verify(text_path, text_encoder, [text_input], "text_features", args.atol, args.rtol)
324
+ if not (ok_image and ok_text):
325
+ print("[error] verification failed", file=sys.stderr)
326
+ return 1
327
+
328
+ for path, data in ((image_path, image_data), (text_path, text_data)):
329
+ total = os.path.getsize(path) + (os.path.getsize(data) if data else 0)
330
+ suffix = f" + {os.path.basename(data)}" if data else ""
331
+ print(f"[done] {path}{suffix} ({total / 1024**2:.1f} MiB)")
332
+ return 0
333
+
334
+
335
+ if __name__ == "__main__":
336
+ sys.exit(main())
src/gen_image_calibration_data.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate Pulsar2 "Numpy" calibration data for the FG-CLIP 2 image encoder.
3
+
4
+ The image encoder ONNX takes ``pixel_values[1, 256, 768]`` — a patchified
5
+ Siglip2 input, not an NCHW image. Pulsar2's ``Image`` calibration path cannot
6
+ produce it (its input processors only resize/normalize/layout-convert), so the
7
+ samples are preprocessed here and saved as ``.npy`` files.
8
+
9
+ Preprocess matches Siglip2ImageProcessor: RGB, BILINEAR resize to a square
10
+ ``image_size``, /255, (x-0.5)/0.5, then 16x16 patches in (nh, nw, p, p, C)
11
+ order.
12
+ """
13
+
14
+ import argparse
15
+ import os
16
+ import zipfile
17
+
18
+ import numpy as np
19
+ from PIL import Image
20
+
21
+ PATCH_SIZE = 16
22
+ DEFAULT_IMAGES = os.path.join(
23
+ os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "datasets",
24
+ "coco2017val_500",
25
+ )
26
+ DEFAULT_OUTPUT_DIR = os.path.join(
27
+ os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "datasets",
28
+ "fgclip2_image_calibration",
29
+ )
30
+ IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
31
+
32
+
33
+ def list_images(directory, limit):
34
+ names = sorted(n for n in os.listdir(directory) if n.lower().endswith(IMAGE_SUFFIXES))
35
+ if limit:
36
+ names = names[:limit]
37
+ if not names:
38
+ raise SystemExit(f"no images found in {directory}")
39
+ return names
40
+
41
+
42
+ def preprocess(path, image_size):
43
+ image = Image.open(path).convert("RGB")
44
+ resample = getattr(Image, "Resampling", Image).BILINEAR
45
+ image = image.resize((image_size, image_size), resample)
46
+ x = np.asarray(image, dtype=np.float32) / 255.0
47
+ x = (x - 0.5) / 0.5
48
+ grid = image_size // PATCH_SIZE
49
+ patches = x.reshape(grid, PATCH_SIZE, grid, PATCH_SIZE, 3)
50
+ patches = patches.transpose(0, 2, 1, 3, 4).reshape(1, grid * grid, PATCH_SIZE * PATCH_SIZE * 3)
51
+ return np.ascontiguousarray(patches)
52
+
53
+
54
+ def main():
55
+ parser = argparse.ArgumentParser(description=__doc__)
56
+ parser.add_argument("--images", default=DEFAULT_IMAGES)
57
+ parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR)
58
+ parser.add_argument("--zip", dest="zip_path",
59
+ default=os.path.join(os.path.dirname(DEFAULT_OUTPUT_DIR),
60
+ "fgclip2_image_calibration.zip"))
61
+ parser.add_argument("--image-size", type=int, default=256,
62
+ help="must be a multiple of 16 and match the exported grid")
63
+ parser.add_argument("--limit", type=int, default=64, help="max images (0 = all)")
64
+ parser.add_argument("--no-zip", action="store_true")
65
+ args = parser.parse_args()
66
+
67
+ images_dir = os.path.abspath(args.images)
68
+ output_dir = os.path.abspath(args.output_dir)
69
+ zip_path = os.path.abspath(args.zip_path)
70
+ if args.image_size % PATCH_SIZE != 0:
71
+ raise SystemExit(f"image size {args.image_size} is not divisible by {PATCH_SIZE}")
72
+
73
+ names = list_images(images_dir, args.limit)
74
+ os.makedirs(output_dir, exist_ok=True)
75
+ for idx, name in enumerate(names):
76
+ arr = preprocess(os.path.join(images_dir, name), args.image_size)
77
+ np.save(os.path.join(output_dir, f"{idx:06d}.npy"), arr)
78
+ print(f"[write] {len(names)} npy files -> {output_dir}")
79
+
80
+ manifest = output_dir.rstrip(os.sep) + "_manifest.txt"
81
+ with open(manifest, "w", encoding="utf-8") as f:
82
+ for idx, name in enumerate(names):
83
+ f.write(f"{idx:06d}.npy\t{name}\n")
84
+ print(f"[write] manifest -> {manifest}")
85
+
86
+ if not args.no_zip:
87
+ folder = os.path.basename(output_dir.rstrip(os.sep))
88
+ os.makedirs(os.path.dirname(zip_path), exist_ok=True)
89
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
90
+ for name in sorted(os.listdir(output_dir)):
91
+ if name.endswith(".npy"):
92
+ zf.write(os.path.join(output_dir, name), f"{folder}/{name}")
93
+ print(f"[zip] {zip_path} ({os.path.getsize(zip_path) / 1024 ** 2:.2f} MiB)")
94
+
95
+ sample = preprocess(os.path.join(images_dir, names[0]), args.image_size)
96
+ print(f"[info] sample shape={sample.shape} dtype={sample.dtype} "
97
+ f"min={sample.min():.4f} max={sample.max():.4f}")
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
src/gen_text_calibration_data.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate Pulsar2 "Numpy" calibration data for the FG-CLIP 2 text encoder.
3
+
4
+ The text encoder ONNX takes ``input_ids[1, 64]`` int64 token ids (Gemma BPE),
5
+ so calibration samples are tokenized captions saved as ``.npy`` files and
6
+ packed into a zip archive (``calibration_format: "Numpy"``).
7
+
8
+ Do not reuse the Chinese-CLIP calibration zip: it is BertTokenizer output with
9
+ shape [1, 52] and will fail with a shape mismatch.
10
+
11
+ Default corpus: the human-written raw Chinese captions from coco-cn
12
+ (``imageid.human-written-caption.txt``), read directly from the dataset tar.gz.
13
+ """
14
+
15
+ import argparse
16
+ import io
17
+ import os
18
+ import tarfile
19
+ import zipfile
20
+
21
+ import numpy as np
22
+ from transformers import AutoTokenizer
23
+
24
+
25
+ DEFAULT_CAPTIONS = os.path.join(
26
+ os.path.dirname(os.path.abspath(__file__)),
27
+ "..", "..", "..", "datasets", "coco-cn-version1805v1.1.tar.gz",
28
+ )
29
+ DEFAULT_MEMBER = "coco-cn-version1805v1.1/imageid.human-written-caption.txt"
30
+ DEFAULT_MODEL_DIR = os.path.join(
31
+ os.path.dirname(os.path.abspath(__file__)), "..", "fg-clip2-large"
32
+ )
33
+ DEFAULT_OUTPUT_DIR = os.path.join(
34
+ os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "datasets",
35
+ "fgclip2_text_calibration",
36
+ )
37
+
38
+
39
+ def read_lines(path, member=None):
40
+ """Yield text lines from a plain file or a tar/tar.gz member."""
41
+ if tarfile.is_tarfile(path):
42
+ with tarfile.open(path, "r:*") as tar:
43
+ names = [n for n in tar.getnames() if not os.path.basename(n).startswith("._")]
44
+ if member is None:
45
+ member = next(n for n in names if n.endswith(".txt") and "caption" in n)
46
+ if member not in names:
47
+ raise SystemExit(f"member not found in {path}: {member}")
48
+ f = tar.extractfile(member)
49
+ for raw in io.TextIOWrapper(f, encoding="utf-8"):
50
+ yield raw.rstrip("\n")
51
+ else:
52
+ with open(path, encoding="utf-8") as f:
53
+ for raw in f:
54
+ yield raw.rstrip("\n")
55
+
56
+
57
+ def parse_caption(line):
58
+ """Split ``COCO_val2014_000000043734#0<tab>两只黑色的狗...`` into (key, text)."""
59
+ line = line.strip()
60
+ if not line:
61
+ return None
62
+ if "\t" in line:
63
+ key, text = line.split("\t", 1)
64
+ else:
65
+ parts = line.split(None, 1)
66
+ if len(parts) != 2:
67
+ return None
68
+ key, text = parts
69
+ text = text.strip()
70
+ return (key, text) if text else None
71
+
72
+
73
+ def main():
74
+ parser = argparse.ArgumentParser(description=__doc__)
75
+ parser.add_argument("--captions", default=DEFAULT_CAPTIONS,
76
+ help="plain caption .txt or dataset .tar/.tar.gz")
77
+ parser.add_argument("--member", default=DEFAULT_MEMBER,
78
+ help="member path inside the archive")
79
+ parser.add_argument("--model-dir", default=DEFAULT_MODEL_DIR,
80
+ help="directory holding tokenizer.json")
81
+ parser.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR)
82
+ parser.add_argument("--zip", dest="zip_path",
83
+ default=os.path.join(os.path.dirname(DEFAULT_OUTPUT_DIR),
84
+ "fgclip2_text_calibration.zip"))
85
+ parser.add_argument("--text-length", type=int, default=64)
86
+ parser.add_argument("--limit", type=int, default=512,
87
+ help="max samples to write, 0 means all")
88
+ parser.add_argument("--no-zip", action="store_true")
89
+ args = parser.parse_args()
90
+
91
+ captions_path = os.path.abspath(args.captions)
92
+ model_dir = os.path.abspath(args.model_dir)
93
+ output_dir = os.path.abspath(args.output_dir)
94
+ zip_path = os.path.abspath(args.zip_path)
95
+
96
+ tokenizer = AutoTokenizer.from_pretrained(model_dir, local_files_only=True)
97
+
98
+ records = []
99
+ for line in read_lines(captions_path, args.member):
100
+ item = parse_caption(line)
101
+ if item is not None:
102
+ records.append(item)
103
+ if args.limit and len(records) >= args.limit:
104
+ break
105
+ if not records:
106
+ raise SystemExit(f"no captions parsed from {captions_path}")
107
+ print(f"[read] {len(records)} captions from {captions_path}")
108
+
109
+ os.makedirs(output_dir, exist_ok=True)
110
+ _, texts = zip(*records)
111
+ enc = tokenizer(
112
+ list(texts),
113
+ padding="max_length",
114
+ max_length=args.text_length,
115
+ truncation=True,
116
+ return_tensors="np",
117
+ )
118
+ input_ids = enc["input_ids"]
119
+ assert input_ids.shape == (len(records), args.text_length), input_ids.shape
120
+
121
+ for idx in range(len(records)):
122
+ arr = input_ids[idx:idx + 1].astype(np.int64)
123
+ np.save(os.path.join(output_dir, f"{idx:06d}.npy"), arr)
124
+
125
+ manifest = output_dir.rstrip(os.sep) + "_manifest.txt"
126
+ with open(manifest, "w", encoding="utf-8") as f:
127
+ for idx, (key, text) in enumerate(records):
128
+ f.write(f"{idx:06d}.npy\t{key}\t{text}\n")
129
+ print(f"[write] {len(records)} npy files -> {output_dir}")
130
+ print(f"[write] manifest -> {manifest}")
131
+
132
+ if not args.no_zip:
133
+ folder = os.path.basename(output_dir.rstrip(os.sep))
134
+ os.makedirs(os.path.dirname(zip_path), exist_ok=True)
135
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
136
+ for name in sorted(os.listdir(output_dir)):
137
+ if name.endswith(".npy"):
138
+ zf.write(os.path.join(output_dir, name), f"{folder}/{name}")
139
+ print(f"[zip] {zip_path} ({os.path.getsize(zip_path) / 1024 ** 2:.2f} MiB)")
140
+
141
+ print(f"[info] sample shape={input_ids[0:1].shape} dtype=int64 "
142
+ f"ids[:8]={input_ids[0][:8].tolist()}")
143
+
144
+
145
+ if __name__ == "__main__":
146
+ main()
src/infer/fgclip2_infer_axmodel.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run the FG-CLIP 2 Large encoders on AX650 (axmodel).
3
+
4
+ This script is meant for the BOARD. It only needs axengine + numpy + Pillow;
5
+ it never imports onnxruntime, torch or transformers.
6
+
7
+ Two modes:
8
+
9
+ single --image PATH --texts ... quick sanity check, prints similarity
10
+ dataset --dataset DIR batch inference, writes raw features
11
+
12
+ Dataset layout:
13
+ <dataset>/images/*.jpg
14
+ <dataset>/pairs.jsonl # one JSON object per line: {"image": "...", "text": "..."}
15
+
16
+ Input contract (verified against the compiled graph):
17
+ image : patchified Siglip2 input [1, num_patches, 3*patch*patch].
18
+ resize(RGB, BILINEAR) to image-size -> /255 -> (x-0.5)/0.5 -> 16x16 patches.
19
+ text : int64 token ids [1,L] (L=64 for walk_type "short"). Input dtype is
20
+ read from the runtime, i.e. it may become int32 after pulsar2
21
+ rewrites the ONNX int64 input.
22
+
23
+ Usage:
24
+ # single image
25
+ python fgclip2_infer_axmodel.py \
26
+ --image-model fgclip2_large_image_encoder.axmodel \
27
+ --text-model fgclip2_large_text_encoder_short.axmodel \
28
+ --tokenizer tokenizer.json --image bedroom.jpg \
29
+ --texts 一个简约风格的卧室角落 一张铺着白色床单的床
30
+
31
+ # dataset
32
+ python fgclip2_infer_axmodel.py \
33
+ --image-model fgclip2_large_image_encoder.axmodel \
34
+ --text-model fgclip2_large_text_encoder_short.axmodel \
35
+ --tokenizer tokenizer.json \
36
+ --dataset fgclip_eval_64 --output results/axmodel.npz
37
+ """
38
+
39
+ import argparse
40
+ import json
41
+ import os
42
+ import sys
43
+ import time
44
+
45
+ import numpy as np
46
+ from PIL import Image
47
+
48
+ try:
49
+ from tqdm import tqdm
50
+ except ImportError: # board image may not ship tqdm
51
+ tqdm = None
52
+
53
+
54
+ PATCH_SIZE = 16
55
+ IMAGE_MEAN = 0.5
56
+ IMAGE_STD = 0.5
57
+ DEFAULT_TEXTS = ["一个简约风格的卧室角落,黑色金属衣架上挂着衣物。", "一只猫在窗台上晒太阳。"]
58
+ BACKEND = "axmodel"
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Gemma BPE tokenizer (reads tokenizer.json; mirrors the HF fast tokenizer)
63
+ # ---------------------------------------------------------------------------
64
+
65
+ class GemmaBpeTokenizer:
66
+ def __init__(self, tokenizer_file, pad_id=0, eos_id=1, unk_id=3):
67
+ with open(tokenizer_file, encoding="utf-8") as f:
68
+ data = json.load(f)
69
+ self.vocab = data["model"]["vocab"]
70
+ self.rank = {}
71
+ for rank, pair in enumerate(data["model"]["merges"]):
72
+ self.rank[(pair[0], pair[1])] = rank
73
+ added = [(a["content"], a["id"]) for a in data.get("added_tokens", [])]
74
+ added.sort(key=lambda x: -len(x[0]))
75
+ self.added = added
76
+ self.pad_id = pad_id
77
+ self.eos_id = eos_id
78
+ self.unk_id = unk_id
79
+
80
+ def _byte_fallback(self, ch):
81
+ out = []
82
+ for b in ch.encode("utf-8"):
83
+ token = f"<0x{b:02X}>"
84
+ out.append(token if token in self.vocab else None)
85
+ return out
86
+
87
+ def _bpe(self, segment):
88
+ symbols = []
89
+ for ch in segment:
90
+ if ch in self.vocab:
91
+ symbols.append(ch)
92
+ else:
93
+ for token in self._byte_fallback(ch):
94
+ symbols.append(token if token is not None else "<unk>")
95
+
96
+ while len(symbols) > 1:
97
+ best_rank, best_i = None, -1
98
+ for i in range(len(symbols) - 1):
99
+ rank = self.rank.get((symbols[i], symbols[i + 1]))
100
+ if rank is not None and (best_rank is None or rank < best_rank):
101
+ best_rank, best_i = rank, i
102
+ if best_rank is None:
103
+ break
104
+
105
+ pair = (symbols[best_i], symbols[best_i + 1])
106
+ merged, i = [], 0
107
+ while i < len(symbols):
108
+ if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
109
+ merged.append(symbols[i] + symbols[i + 1])
110
+ i += 2
111
+ else:
112
+ merged.append(symbols[i])
113
+ i += 1
114
+ symbols = merged
115
+ return symbols
116
+
117
+ def encode(self, text, max_length, dtype=np.int64):
118
+ text = text.replace(" ", "▁")
119
+ ids, buf, i = [], "", 0
120
+ while i < len(text):
121
+ hit = None
122
+ for content, token_id in self.added:
123
+ if text.startswith(content, i):
124
+ hit = (content, token_id)
125
+ break
126
+ if hit is not None:
127
+ if buf:
128
+ ids.extend(self.vocab.get(t, self.unk_id) for t in self._bpe(buf))
129
+ buf = ""
130
+ ids.append(hit[1])
131
+ i += len(hit[0])
132
+ else:
133
+ buf += text[i]
134
+ i += 1
135
+ if buf:
136
+ ids.extend(self.vocab.get(t, self.unk_id) for t in self._bpe(buf))
137
+
138
+ ids = (ids + [self.eos_id])[:max_length]
139
+ ids += [self.pad_id] * (max_length - len(ids))
140
+ return np.asarray(ids, dtype=dtype).reshape(1, max_length)
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Runtime helpers
145
+ # ---------------------------------------------------------------------------
146
+
147
+ def create_session(path):
148
+ import axengine
149
+ return axengine.InferenceSession(path)
150
+
151
+
152
+ def input_name_and_dtype(sess):
153
+ node = sess.get_inputs()[0]
154
+ dtype = getattr(node, "dtype", None)
155
+ if not isinstance(dtype, np.dtype):
156
+ text = str(getattr(node, "type", ""))
157
+ name = text.split("(")[-1].rstrip(")")
158
+ dtype = np.dtype({
159
+ "float": np.float32, "double": np.float64, "float16": np.float16,
160
+ "int8": np.int8, "uint8": np.uint8, "int16": np.int16,
161
+ "uint16": np.uint16, "int32": np.int32, "uint32": np.uint32,
162
+ "int64": np.int64,
163
+ }.get(name, name))
164
+ return node.name, dtype
165
+
166
+
167
+ def run_feature(sess, x):
168
+ name, dtype = input_name_and_dtype(sess)
169
+ x = np.ascontiguousarray(x, dtype=dtype)
170
+ start = time.perf_counter()
171
+ out = sess.run(None, {name: x})[0]
172
+ elapsed = (time.perf_counter() - start) * 1000.0
173
+ return np.asarray(out, dtype=np.float32).reshape(-1), elapsed
174
+
175
+
176
+ def preprocess_image(path, image_size):
177
+ image = Image.open(path).convert("RGB")
178
+ resample = getattr(Image, "Resampling", Image).BILINEAR
179
+ image = image.resize((image_size, image_size), resample)
180
+ x = np.asarray(image, dtype=np.float32) / 255.0
181
+ x = (x - IMAGE_MEAN) / IMAGE_STD
182
+ grid = image_size // PATCH_SIZE
183
+ patches = x.reshape(grid, PATCH_SIZE, grid, PATCH_SIZE, 3)
184
+ patches = patches.transpose(0, 2, 1, 3, 4).reshape(1, grid * grid, PATCH_SIZE * PATCH_SIZE * 3)
185
+ return np.ascontiguousarray(patches)
186
+
187
+
188
+ def normalize(x):
189
+ return x / (np.linalg.norm(x, axis=-1, keepdims=True) + 1e-12)
190
+
191
+
192
+ def softmax(x):
193
+ x = x - np.max(x)
194
+ e = np.exp(x)
195
+ return e / np.sum(e)
196
+
197
+
198
+ # ---------------------------------------------------------------------------
199
+ # Dataset
200
+ # ---------------------------------------------------------------------------
201
+
202
+ def load_pairs(dataset_dir, pairs_file, limit):
203
+ pairs_path = pairs_file or os.path.join(dataset_dir, "pairs.jsonl")
204
+ if not os.path.isfile(pairs_path):
205
+ raise SystemExit(f"pairs file not found: {pairs_path}")
206
+ pairs = []
207
+ with open(pairs_path, encoding="utf-8") as f:
208
+ for line in f:
209
+ line = line.strip()
210
+ if not line:
211
+ continue
212
+ item = json.loads(line)
213
+ pairs.append((item["image"], item["text"]))
214
+ if limit and len(pairs) >= limit:
215
+ break
216
+ if not pairs:
217
+ raise SystemExit(f"no pairs in {pairs_path}")
218
+ return pairs
219
+
220
+
221
+ def group_pairs(pairs):
222
+ """Deduplicate images, keep the first-seen order, map each text to an image."""
223
+ image_names = []
224
+ image_index = {}
225
+ text_captions = []
226
+ text_image_index = []
227
+ for image_name, text in pairs:
228
+ if image_name not in image_index:
229
+ image_index[image_name] = len(image_names)
230
+ image_names.append(image_name)
231
+ text_captions.append(text)
232
+ text_image_index.append(image_index[image_name])
233
+ return image_names, text_captions, np.asarray(text_image_index, dtype=np.int32)
234
+
235
+
236
+ def save_dump(path, backend, image_model, text_model, image_names, text_captions,
237
+ text_image_index, image_features, text_features,
238
+ image_ms, text_ms, image_pre_ms, text_pre_ms):
239
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
240
+ np.savez(
241
+ path,
242
+ backend=np.asarray(backend),
243
+ image_model=np.asarray(os.path.basename(image_model)),
244
+ text_model=np.asarray(os.path.basename(text_model)),
245
+ image_names=np.asarray(image_names),
246
+ text_captions=np.asarray(text_captions),
247
+ text_image_index=np.asarray(text_image_index, dtype=np.int32),
248
+ image_features=image_features,
249
+ text_features=text_features,
250
+ image_ms=np.asarray(image_ms, dtype=np.float32),
251
+ text_ms=np.asarray(text_ms, dtype=np.float32),
252
+ image_preprocess_ms=np.asarray(image_pre_ms, dtype=np.float32),
253
+ text_tokenize_ms=np.asarray(text_pre_ms, dtype=np.float32),
254
+ )
255
+ print(f"[save] {path}")
256
+
257
+
258
+ # ---------------------------------------------------------------------------
259
+ # Modes
260
+ # ---------------------------------------------------------------------------
261
+
262
+ def run_single(args, tokenizer, image_sess, text_sess):
263
+ start = time.perf_counter()
264
+ pre_start = time.perf_counter()
265
+ x = preprocess_image(args.image, args.image_size)
266
+ pre_ms = (time.perf_counter() - pre_start) * 1000.0
267
+ image_feature, image_ms = run_feature(image_sess, x)
268
+
269
+ text_features = []
270
+ text_ms = []
271
+ for text in args.texts:
272
+ tok_start = time.perf_counter()
273
+ ids = tokenizer.encode(text, args.text_length)
274
+ tok_ms = (time.perf_counter() - tok_start) * 1000.0
275
+ feat, ms = run_feature(text_sess, ids)
276
+ text_features.append(feat)
277
+ text_ms.append(ms)
278
+ if args.verbose:
279
+ print(f"[time] text tokenize={tok_ms:.2f}ms infer={ms:.2f}ms")
280
+ text_features = np.stack(text_features)
281
+ total_ms = (time.perf_counter() - start) * 1000.0
282
+
283
+ print(f"[time] preprocess={pre_ms:.2f}ms image_infer={image_ms:.2f}ms "
284
+ f"text_infer(avg)={np.mean(text_ms):.2f}ms total={total_ms:.2f}ms")
285
+
286
+ sim = normalize(image_feature[None])[0] @ normalize(text_features).T
287
+ probs = softmax(sim * 100.0)
288
+ best = int(np.argmax(probs))
289
+ print("similarity matrix (cosine):")
290
+ for i, text in enumerate(args.texts):
291
+ print(f" {text:<40} sim={sim[i]:.4f} prob={probs[i]:.4f}")
292
+ print(f"[result] top-1: {args.texts[best]} (prob={probs[best]:.4f})")
293
+
294
+ if args.output:
295
+ save_dump(
296
+ args.output, BACKEND, args.image_model, args.text_model,
297
+ [os.path.basename(args.image)], args.texts, np.zeros(len(args.texts)),
298
+ image_feature[None], text_features,
299
+ [image_ms], text_ms, [pre_ms], [0.0] * len(args.texts),
300
+ )
301
+
302
+
303
+ def run_dataset(args, tokenizer, image_sess, text_sess):
304
+ dataset_dir = os.path.abspath(args.dataset)
305
+ pairs = load_pairs(dataset_dir, args.pairs, args.limit)
306
+ image_names, text_captions, text_image_index = group_pairs(pairs)
307
+ print(f"[data] {len(image_names)} images, {len(text_captions)} captions")
308
+
309
+ image_iter = tqdm(image_names, desc="image") if tqdm else image_names
310
+ image_features = None
311
+ image_ms = []
312
+ image_pre_ms = []
313
+ for i, name in enumerate(image_iter):
314
+ pre_start = time.perf_counter()
315
+ x = preprocess_image(os.path.join(dataset_dir, "images", name), args.image_size)
316
+ image_pre_ms.append((time.perf_counter() - pre_start) * 1000.0)
317
+ feat, ms = run_feature(image_sess, x)
318
+ if image_features is None:
319
+ image_features = np.zeros((len(image_names), feat.shape[0]), dtype=np.float32)
320
+ image_features[i] = feat
321
+ image_ms.append(ms)
322
+
323
+ text_iter = tqdm(text_captions, desc="text") if tqdm else text_captions
324
+ text_features = np.zeros((len(text_captions), image_features.shape[1]), dtype=np.float32)
325
+ text_ms = []
326
+ text_pre_ms = []
327
+ for i, caption in enumerate(text_iter):
328
+ pre_start = time.perf_counter()
329
+ ids = tokenizer.encode(caption, args.text_length)
330
+ text_pre_ms.append((time.perf_counter() - pre_start) * 1000.0)
331
+ feat, ms = run_feature(text_sess, ids)
332
+ if feat.shape[0] != text_features.shape[1]:
333
+ raise SystemExit(f"feature size mismatch: "
334
+ f"image={text_features.shape[1]} text={feat.shape[0]}")
335
+ text_features[i] = feat
336
+ text_ms.append(ms)
337
+
338
+ print(f"[time] image preprocess={np.mean(image_pre_ms):.2f}ms "
339
+ f"infer={np.mean(image_ms):.2f}ms/img; "
340
+ f"text tokenize={np.mean(text_pre_ms):.2f}ms "
341
+ f"infer={np.mean(text_ms):.2f}ms/text")
342
+ print(f"[time] image p50={np.percentile(image_ms, 50):.2f}ms "
343
+ f"p90={np.percentile(image_ms, 90):.2f}ms "
344
+ f"p99={np.percentile(image_ms, 99):.2f}ms")
345
+ total_ms = float(np.sum(image_pre_ms) + np.sum(image_ms) + np.sum(text_pre_ms) + np.sum(text_ms))
346
+ print(f"[time] total={total_ms:.2f}ms fps={len(text_captions) / (total_ms / 1000.0):.2f}/s")
347
+
348
+ save_dump(
349
+ args.output, BACKEND, args.image_model, args.text_model,
350
+ image_names, text_captions, text_image_index,
351
+ image_features, text_features,
352
+ image_ms, text_ms, image_pre_ms, text_pre_ms,
353
+ )
354
+
355
+
356
+ # ---------------------------------------------------------------------------
357
+ # Main
358
+ # ---------------------------------------------------------------------------
359
+
360
+ def main():
361
+ parser = argparse.ArgumentParser(
362
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
363
+ allow_abbrev=False)
364
+ parser.add_argument("--image-model", required=True, help="image encoder .axmodel")
365
+ parser.add_argument("--text-model", required=True, help="text encoder .axmodel")
366
+ parser.add_argument("--tokenizer", required=True, help="tokenizer.json path")
367
+ parser.add_argument("--image", default=None, help="single image path (single mode)")
368
+ parser.add_argument("--texts", nargs="+", default=None,
369
+ help=f"candidate texts for single mode (default: {DEFAULT_TEXTS})")
370
+ parser.add_argument("--dataset", default=None, help="dataset directory (dataset mode)")
371
+ parser.add_argument("--pairs", default=None,
372
+ help="pairs.jsonl (default: <dataset>/pairs.jsonl)")
373
+ parser.add_argument("--output", default=None,
374
+ help="output .npz (required in dataset mode, optional in single mode)")
375
+ parser.add_argument("--image-size", type=int, default=256,
376
+ help="square input size, must be a multiple of 16 (default 256)")
377
+ parser.add_argument("--text-length", type=int, default=64,
378
+ help="fixed token length (64 for short/box, 196 for long)")
379
+ parser.add_argument("--limit", type=int, default=0,
380
+ help="only use the first N pairs (dataset mode, 0 = all)")
381
+ parser.add_argument("--verbose", action="store_true",
382
+ help="print tokenize/infer time per text in single mode")
383
+ args = parser.parse_args()
384
+
385
+ if bool(args.image) == bool(args.dataset):
386
+ parser.error("exactly one of --image (single mode) / --dataset (dataset mode) is required")
387
+ if args.dataset and not args.output:
388
+ parser.error("--output is required in dataset mode")
389
+ if args.image and not args.texts:
390
+ args.texts = DEFAULT_TEXTS
391
+
392
+ tokenizer = GemmaBpeTokenizer(args.tokenizer)
393
+ image_sess = create_session(args.image_model)
394
+ text_sess = create_session(args.text_model)
395
+
396
+ if args.image:
397
+ run_single(args, tokenizer, image_sess, text_sess)
398
+ else:
399
+ run_dataset(args, tokenizer, image_sess, text_sess)
400
+
401
+
402
+ if __name__ == "__main__":
403
+ sys.exit(main())
src/infer/fgclip2_infer_onnx.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run the FG-CLIP 2 Large encoders in FP32 ONNX.
3
+
4
+ This script is meant for the DEVELOPMENT HOST. It uses onnxruntime and writes
5
+ the same .npz schema as ``fgclip2_infer_axmodel.py`` so one evaluator can
6
+ compare the two backends.
7
+
8
+ Two modes:
9
+
10
+ single --image PATH --texts ... quick sanity check, prints similarity
11
+ dataset --dataset DIR batch inference, writes raw features
12
+
13
+ Dataset layout:
14
+ <dataset>/images/*.jpg
15
+ <dataset>/pairs.jsonl # one JSON object per line: {"image": "...", "text": "..."}
16
+
17
+ Input contract:
18
+ image : patchified Siglip2 input [1, num_patches, 3*patch*patch].
19
+ resize(RGB, BILINEAR) to image-size -> /255 -> (x-0.5)/0.5 -> 16x16 patches.
20
+ text : int64 token ids [1,L] (L=64 for walk_type "short"). Tokenizer is a
21
+ pure-Python Gemma BPE reader (tokenizer.json); it matches the
22
+ HuggingFace tokenizer and needs no transformers on the board.
23
+
24
+ Usage:
25
+ # single image
26
+ python src/infer/fgclip2_infer_onnx.py \
27
+ --image-model models/fgclip2_large_image_encoder.onnx \
28
+ --text-model models/fgclip2_large_text_encoder_short.onnx \
29
+ --tokenizer fg-clip2-large/tokenizer.json --image bedroom.jpg \
30
+ --texts 一个简约风格的卧室角落 一张铺着白色床单的床
31
+
32
+ # dataset
33
+ python src/infer/fgclip2_infer_onnx.py \
34
+ --image-model models/fgclip2_large_image_encoder.onnx \
35
+ --text-model models/fgclip2_large_text_encoder_short.onnx \
36
+ --tokenizer fg-clip2-large/tokenizer.json \
37
+ --dataset fgclip_eval_64 --output results/onnx.npz
38
+ """
39
+
40
+ import argparse
41
+ import json
42
+ import os
43
+ import sys
44
+ import time
45
+
46
+ import numpy as np
47
+ from PIL import Image
48
+
49
+ try:
50
+ from tqdm import tqdm
51
+ except ImportError: # board image may not ship tqdm
52
+ tqdm = None
53
+
54
+
55
+ PATCH_SIZE = 16
56
+ IMAGE_MEAN = 0.5
57
+ IMAGE_STD = 0.5
58
+ DEFAULT_TEXTS = ["一个简约风格的卧室角落,黑色金属衣架上挂着衣物。", "一只猫在窗台上晒太阳。"]
59
+ BACKEND = "onnx"
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Gemma BPE tokenizer (reads tokenizer.json; mirrors the HF fast tokenizer)
64
+ # ---------------------------------------------------------------------------
65
+
66
+ class GemmaBpeTokenizer:
67
+ def __init__(self, tokenizer_file, pad_id=0, eos_id=1, unk_id=3):
68
+ with open(tokenizer_file, encoding="utf-8") as f:
69
+ data = json.load(f)
70
+ self.vocab = data["model"]["vocab"]
71
+ self.rank = {}
72
+ for rank, pair in enumerate(data["model"]["merges"]):
73
+ self.rank[(pair[0], pair[1])] = rank
74
+ added = [(a["content"], a["id"]) for a in data.get("added_tokens", [])]
75
+ added.sort(key=lambda x: -len(x[0]))
76
+ self.added = added
77
+ self.pad_id = pad_id
78
+ self.eos_id = eos_id
79
+ self.unk_id = unk_id
80
+
81
+ def _byte_fallback(self, ch):
82
+ out = []
83
+ for b in ch.encode("utf-8"):
84
+ token = f"<0x{b:02X}>"
85
+ out.append(token if token in self.vocab else None)
86
+ return out
87
+
88
+ def _bpe(self, segment):
89
+ symbols = []
90
+ for ch in segment:
91
+ if ch in self.vocab:
92
+ symbols.append(ch)
93
+ else:
94
+ for token in self._byte_fallback(ch):
95
+ symbols.append(token if token is not None else "<unk>")
96
+
97
+ while len(symbols) > 1:
98
+ best_rank, best_i = None, -1
99
+ for i in range(len(symbols) - 1):
100
+ rank = self.rank.get((symbols[i], symbols[i + 1]))
101
+ if rank is not None and (best_rank is None or rank < best_rank):
102
+ best_rank, best_i = rank, i
103
+ if best_rank is None:
104
+ break
105
+
106
+ pair = (symbols[best_i], symbols[best_i + 1])
107
+ merged, i = [], 0
108
+ while i < len(symbols):
109
+ if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
110
+ merged.append(symbols[i] + symbols[i + 1])
111
+ i += 2
112
+ else:
113
+ merged.append(symbols[i])
114
+ i += 1
115
+ symbols = merged
116
+ return symbols
117
+
118
+ def encode(self, text, max_length, dtype=np.int64):
119
+ text = text.replace(" ", "▁")
120
+ ids, buf, i = [], "", 0
121
+ while i < len(text):
122
+ hit = None
123
+ for content, token_id in self.added:
124
+ if text.startswith(content, i):
125
+ hit = (content, token_id)
126
+ break
127
+ if hit is not None:
128
+ if buf:
129
+ ids.extend(self.vocab.get(t, self.unk_id) for t in self._bpe(buf))
130
+ buf = ""
131
+ ids.append(hit[1])
132
+ i += len(hit[0])
133
+ else:
134
+ buf += text[i]
135
+ i += 1
136
+ if buf:
137
+ ids.extend(self.vocab.get(t, self.unk_id) for t in self._bpe(buf))
138
+
139
+ ids = (ids + [self.eos_id])[:max_length]
140
+ ids += [self.pad_id] * (max_length - len(ids))
141
+ return np.asarray(ids, dtype=dtype).reshape(1, max_length)
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # Runtime helpers
146
+ # ---------------------------------------------------------------------------
147
+
148
+ def create_session(path):
149
+ import onnxruntime as ort
150
+ return ort.InferenceSession(path, providers=["CPUExecutionProvider"])
151
+
152
+
153
+ def input_name_and_dtype(sess):
154
+ node = sess.get_inputs()[0]
155
+ dtype = getattr(node, "dtype", None)
156
+ if not isinstance(dtype, np.dtype):
157
+ text = str(getattr(node, "type", ""))
158
+ name = text.split("(")[-1].rstrip(")")
159
+ dtype = np.dtype({
160
+ "float": np.float32, "double": np.float64, "float16": np.float16,
161
+ "int8": np.int8, "uint8": np.uint8, "int16": np.int16,
162
+ "uint16": np.uint16, "int32": np.int32, "uint32": np.uint32,
163
+ "int64": np.int64,
164
+ }.get(name, name))
165
+ return node.name, dtype
166
+
167
+
168
+ def run_feature(sess, x):
169
+ name, dtype = input_name_and_dtype(sess)
170
+ x = np.ascontiguousarray(x, dtype=dtype)
171
+ start = time.perf_counter()
172
+ out = sess.run(None, {name: x})[0]
173
+ elapsed = (time.perf_counter() - start) * 1000.0
174
+ return np.asarray(out, dtype=np.float32).reshape(-1), elapsed
175
+
176
+
177
+ def preprocess_image(path, image_size):
178
+ image = Image.open(path).convert("RGB")
179
+ resample = getattr(Image, "Resampling", Image).BILINEAR
180
+ image = image.resize((image_size, image_size), resample)
181
+ x = np.asarray(image, dtype=np.float32) / 255.0
182
+ x = (x - IMAGE_MEAN) / IMAGE_STD
183
+ grid = image_size // PATCH_SIZE
184
+ patches = x.reshape(grid, PATCH_SIZE, grid, PATCH_SIZE, 3)
185
+ patches = patches.transpose(0, 2, 1, 3, 4).reshape(1, grid * grid, PATCH_SIZE * PATCH_SIZE * 3)
186
+ return np.ascontiguousarray(patches)
187
+
188
+
189
+ def normalize(x):
190
+ return x / (np.linalg.norm(x, axis=-1, keepdims=True) + 1e-12)
191
+
192
+
193
+ def softmax(x):
194
+ x = x - np.max(x)
195
+ e = np.exp(x)
196
+ return e / np.sum(e)
197
+
198
+
199
+ # ---------------------------------------------------------------------------
200
+ # Dataset
201
+ # ---------------------------------------------------------------------------
202
+
203
+ def load_pairs(dataset_dir, pairs_file, limit):
204
+ pairs_path = pairs_file or os.path.join(dataset_dir, "pairs.jsonl")
205
+ if not os.path.isfile(pairs_path):
206
+ raise SystemExit(f"pairs file not found: {pairs_path}")
207
+ pairs = []
208
+ with open(pairs_path, encoding="utf-8") as f:
209
+ for line in f:
210
+ line = line.strip()
211
+ if not line:
212
+ continue
213
+ item = json.loads(line)
214
+ pairs.append((item["image"], item["text"]))
215
+ if limit and len(pairs) >= limit:
216
+ break
217
+ if not pairs:
218
+ raise SystemExit(f"no pairs in {pairs_path}")
219
+ return pairs
220
+
221
+
222
+ def group_pairs(pairs):
223
+ """Deduplicate images, keep the first-seen order, map each text to an image."""
224
+ image_names = []
225
+ image_index = {}
226
+ text_captions = []
227
+ text_image_index = []
228
+ for image_name, text in pairs:
229
+ if image_name not in image_index:
230
+ image_index[image_name] = len(image_names)
231
+ image_names.append(image_name)
232
+ text_captions.append(text)
233
+ text_image_index.append(image_index[image_name])
234
+ return image_names, text_captions, np.asarray(text_image_index, dtype=np.int32)
235
+
236
+
237
+ def save_dump(path, backend, image_model, text_model, image_names, text_captions,
238
+ text_image_index, image_features, text_features,
239
+ image_ms, text_ms, image_pre_ms, text_pre_ms):
240
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
241
+ np.savez(
242
+ path,
243
+ backend=np.asarray(backend),
244
+ image_model=np.asarray(os.path.basename(image_model)),
245
+ text_model=np.asarray(os.path.basename(text_model)),
246
+ image_names=np.asarray(image_names),
247
+ text_captions=np.asarray(text_captions),
248
+ text_image_index=np.asarray(text_image_index, dtype=np.int32),
249
+ image_features=image_features,
250
+ text_features=text_features,
251
+ image_ms=np.asarray(image_ms, dtype=np.float32),
252
+ text_ms=np.asarray(text_ms, dtype=np.float32),
253
+ image_preprocess_ms=np.asarray(image_pre_ms, dtype=np.float32),
254
+ text_tokenize_ms=np.asarray(text_pre_ms, dtype=np.float32),
255
+ )
256
+ print(f"[save] {path}")
257
+
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # Modes
261
+ # ---------------------------------------------------------------------------
262
+
263
+ def run_single(args, tokenizer, image_sess, text_sess):
264
+ start = time.perf_counter()
265
+ pre_start = time.perf_counter()
266
+ x = preprocess_image(args.image, args.image_size)
267
+ pre_ms = (time.perf_counter() - pre_start) * 1000.0
268
+ image_feature, image_ms = run_feature(image_sess, x)
269
+
270
+ text_features = []
271
+ text_ms = []
272
+ for text in args.texts:
273
+ ids = tokenizer.encode(text, args.text_length)
274
+ feat, ms = run_feature(text_sess, ids)
275
+ text_features.append(feat)
276
+ text_ms.append(ms)
277
+ text_features = np.stack(text_features)
278
+ total_ms = (time.perf_counter() - start) * 1000.0
279
+
280
+ print(f"[time] preprocess={pre_ms:.2f}ms image_infer={image_ms:.2f}ms "
281
+ f"text_infer(avg)={np.mean(text_ms):.2f}ms total={total_ms:.2f}ms")
282
+
283
+ sim = normalize(image_feature[None])[0] @ normalize(text_features).T
284
+ probs = softmax(sim * 100.0)
285
+ best = int(np.argmax(probs))
286
+ print("similarity matrix (cosine):")
287
+ for i, text in enumerate(args.texts):
288
+ print(f" {text:<40} sim={sim[i]:.4f} prob={probs[i]:.4f}")
289
+ print(f"[result] top-1: {args.texts[best]} (prob={probs[best]:.4f})")
290
+
291
+ if args.output:
292
+ save_dump(
293
+ args.output, BACKEND, args.image_model, args.text_model,
294
+ [os.path.basename(args.image)], args.texts, np.zeros(len(args.texts)),
295
+ image_feature[None], text_features,
296
+ [image_ms], text_ms, [pre_ms], [0.0] * len(args.texts),
297
+ )
298
+
299
+
300
+ def run_dataset(args, tokenizer, image_sess, text_sess):
301
+ dataset_dir = os.path.abspath(args.dataset)
302
+ pairs = load_pairs(dataset_dir, args.pairs, args.limit)
303
+ image_names, text_captions, text_image_index = group_pairs(pairs)
304
+ print(f"[data] {len(image_names)} images, {len(text_captions)} captions")
305
+
306
+ image_iter = tqdm(image_names, desc="image") if tqdm else image_names
307
+ image_features = None
308
+ image_ms = []
309
+ image_pre_ms = []
310
+ for i, name in enumerate(image_iter):
311
+ pre_start = time.perf_counter()
312
+ x = preprocess_image(os.path.join(dataset_dir, "images", name), args.image_size)
313
+ image_pre_ms.append((time.perf_counter() - pre_start) * 1000.0)
314
+ feat, ms = run_feature(image_sess, x)
315
+ if image_features is None:
316
+ image_features = np.zeros((len(image_names), feat.shape[0]), dtype=np.float32)
317
+ image_features[i] = feat
318
+ image_ms.append(ms)
319
+
320
+ text_iter = tqdm(text_captions, desc="text") if tqdm else text_captions
321
+ text_features = np.zeros((len(text_captions), image_features.shape[1]), dtype=np.float32)
322
+ text_ms = []
323
+ text_pre_ms = []
324
+ for i, caption in enumerate(text_iter):
325
+ pre_start = time.perf_counter()
326
+ ids = tokenizer.encode(caption, args.text_length)
327
+ text_pre_ms.append((time.perf_counter() - pre_start) * 1000.0)
328
+ feat, ms = run_feature(text_sess, ids)
329
+ if feat.shape[0] != text_features.shape[1]:
330
+ raise SystemExit(f"feature size mismatch: "
331
+ f"image={text_features.shape[1]} text={feat.shape[0]}")
332
+ text_features[i] = feat
333
+ text_ms.append(ms)
334
+
335
+ print(f"[time] image preprocess={np.mean(image_pre_ms):.2f}ms "
336
+ f"infer={np.mean(image_ms):.2f}ms/img; "
337
+ f"text tokenize={np.mean(text_pre_ms):.2f}ms "
338
+ f"infer={np.mean(text_ms):.2f}ms/text")
339
+ print(f"[time] image p50={np.percentile(image_ms, 50):.2f}ms "
340
+ f"p90={np.percentile(image_ms, 90):.2f}ms "
341
+ f"p99={np.percentile(image_ms, 99):.2f}ms")
342
+ total_ms = float(np.sum(image_pre_ms) + np.sum(image_ms) + np.sum(text_pre_ms) + np.sum(text_ms))
343
+ print(f"[time] total={total_ms:.2f}ms fps={len(text_captions) / (total_ms / 1000.0):.2f}/s")
344
+
345
+ save_dump(
346
+ args.output, BACKEND, args.image_model, args.text_model,
347
+ image_names, text_captions, text_image_index,
348
+ image_features, text_features,
349
+ image_ms, text_ms, image_pre_ms, text_pre_ms,
350
+ )
351
+
352
+
353
+ # ---------------------------------------------------------------------------
354
+ # Main
355
+ # ---------------------------------------------------------------------------
356
+
357
+ def main():
358
+ parser = argparse.ArgumentParser(
359
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
360
+ allow_abbrev=False)
361
+ parser.add_argument("--image-model", required=True, help="image encoder .onnx")
362
+ parser.add_argument("--text-model", required=True, help="text encoder .onnx")
363
+ parser.add_argument("--tokenizer", required=True, help="tokenizer.json path")
364
+ parser.add_argument("--image", default=None, help="single image path (single mode)")
365
+ parser.add_argument("--texts", nargs="+", default=None,
366
+ help=f"candidate texts for single mode (default: {DEFAULT_TEXTS})")
367
+ parser.add_argument("--dataset", default=None, help="dataset directory (dataset mode)")
368
+ parser.add_argument("--pairs", default=None,
369
+ help="pairs.jsonl (default: <dataset>/pairs.jsonl)")
370
+ parser.add_argument("--output", default=None,
371
+ help="output .npz (required in dataset mode, optional in single mode)")
372
+ parser.add_argument("--image-size", type=int, default=256,
373
+ help="square input size, must be a multiple of 16 (default 256)")
374
+ parser.add_argument("--text-length", type=int, default=64,
375
+ help="fixed token length (64 for short/box, 196 for long)")
376
+ parser.add_argument("--limit", type=int, default=0,
377
+ help="only use the first N pairs (dataset mode, 0 = all)")
378
+ args = parser.parse_args()
379
+
380
+ if bool(args.image) == bool(args.dataset):
381
+ parser.error("exactly one of --image (single mode) / --dataset (dataset mode) is required")
382
+ if args.dataset and not args.output:
383
+ parser.error("--output is required in dataset mode")
384
+ if args.image and not args.texts:
385
+ args.texts = DEFAULT_TEXTS
386
+
387
+ tokenizer = GemmaBpeTokenizer(args.tokenizer)
388
+ image_sess = create_session(args.image_model)
389
+ text_sess = create_session(args.text_model)
390
+
391
+ if args.image:
392
+ run_single(args, tokenizer, image_sess, text_sess)
393
+ else:
394
+ run_dataset(args, tokenizer, image_sess, text_sess)
395
+
396
+
397
+ if __name__ == "__main__":
398
+ sys.exit(main())