Feature Extraction
Transformers
Safetensors
avito_gated_fusion
siglip
siglip2
vision
text
clip
multimodal
image-text-embeddings
pet-recognition
custom_code
Instructions to use AvitoTech/SigLIP2-giant-e5small-v2-gating with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use AvitoTech/SigLIP2-giant-e5small-v2-gating with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="AvitoTech/SigLIP2-giant-e5small-v2-gating", trust_remote_code=True)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("AvitoTech/SigLIP2-giant-e5small-v2-gating", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Fix AutoModel loading, add image processor and Apache-2.0 license
#2
by Slenser0 - opened
- LICENSE +202 -0
- README.md +14 -68
- config.json +62 -48
- configuration_avito_gated.py +51 -0
- modeling_avito_gated.py +129 -0
- preprocessor_config.json +24 -0
- special_tokens_map.json +7 -0
- tokenizer.json +0 -0
- tokenizer_config.json +13 -0
- vocab.txt +0 -0
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
---
|
|
|
|
| 2 |
library_name: transformers
|
| 3 |
tags:
|
| 4 |
- siglip
|
|
@@ -9,7 +10,7 @@ tags:
|
|
| 9 |
- multimodal
|
| 10 |
- image-text-embeddings
|
| 11 |
- pet-recognition
|
| 12 |
-
model_id: AvitoTech/SigLIP2-giant-e5small-v2-gating
|
| 13 |
pipeline_tag: feature-extraction
|
| 14 |
---
|
| 15 |
|
|
@@ -109,87 +110,32 @@ The model has been benchmarked against various vision encoders on multiple pet r
|
|
| 109 |
### Installation
|
| 110 |
|
| 111 |
```bash
|
| 112 |
-
pip install transformers torch pillow
|
| 113 |
```
|
| 114 |
|
| 115 |
### Load Model and Get Embedding
|
| 116 |
|
| 117 |
```python
|
| 118 |
import torch
|
| 119 |
-
import torch.nn as nn
|
| 120 |
-
import torch.nn.functional as F
|
| 121 |
from PIL import Image
|
| 122 |
-
from transformers import
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
def __init__(self, embedding_dim=512):
|
| 129 |
-
super().__init__()
|
| 130 |
-
ckpt = "google/siglip2-giant-opt-patch16-384"
|
| 131 |
-
self.clip = SiglipModel.from_pretrained(ckpt)
|
| 132 |
-
self.processor = SiglipProcessor.from_pretrained(ckpt)
|
| 133 |
-
|
| 134 |
-
text_model_name = "intfloat/e5-small-v2"
|
| 135 |
-
self.text_encoder = AutoModel.from_pretrained(text_model_name)
|
| 136 |
-
self.tokenizer = AutoTokenizer.from_pretrained(text_model_name)
|
| 137 |
-
|
| 138 |
-
img_dim = self.clip.config.vision_config.hidden_size
|
| 139 |
-
text_dim = self.text_encoder.config.hidden_size
|
| 140 |
-
|
| 141 |
-
self.proj_img = nn.Linear(img_dim, embedding_dim)
|
| 142 |
-
self.proj_text = nn.Linear(text_dim, embedding_dim)
|
| 143 |
-
|
| 144 |
-
self.gate = nn.Sequential(
|
| 145 |
-
nn.Linear(embedding_dim * 2, 128),
|
| 146 |
-
nn.ReLU(),
|
| 147 |
-
nn.Linear(128, 2),
|
| 148 |
-
nn.Softmax(dim=-1)
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
def average_pool(self, last_hidden_states, attention_mask):
|
| 152 |
-
last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
|
| 153 |
-
return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
|
| 154 |
-
|
| 155 |
-
def forward(self, images, texts):
|
| 156 |
-
device = next(self.parameters()).device
|
| 157 |
-
|
| 158 |
-
clip_inputs = self.processor(images=images, return_tensors="pt").to(device)
|
| 159 |
-
img_emb = self.clip.get_image_features(**clip_inputs)
|
| 160 |
-
|
| 161 |
-
text_inputs = self.tokenizer(
|
| 162 |
-
texts, padding=True, truncation=True, max_length=512, return_tensors="pt"
|
| 163 |
-
).to(device)
|
| 164 |
-
text_outputs = self.text_encoder(**text_inputs)
|
| 165 |
-
text_emb = self.average_pool(text_outputs.last_hidden_state, text_inputs['attention_mask'])
|
| 166 |
-
|
| 167 |
-
img_proj = self.proj_img(img_emb)
|
| 168 |
-
text_proj = self.proj_text(text_emb)
|
| 169 |
-
|
| 170 |
-
fused = torch.cat([text_proj, img_proj], dim=-1)
|
| 171 |
-
w = self.gate(fused)
|
| 172 |
-
fused_emb = w[:, 0:1] * text_proj + w[:, 1:2] * img_proj
|
| 173 |
-
|
| 174 |
-
return F.normalize(fused_emb, dim=1)
|
| 175 |
-
|
| 176 |
-
# Load model
|
| 177 |
-
model = FaceRecognizer()
|
| 178 |
-
|
| 179 |
-
# Download and load weights from HuggingFace
|
| 180 |
-
weights_path = hf_hub_download(repo_id="AvitoTech/SigLIP2-giant-e5small-v2-gating-for-animal-identification", filename="model.safetensors")
|
| 181 |
-
state_dict = load_file(weights_path)
|
| 182 |
-
model.load_state_dict(state_dict)
|
| 183 |
|
| 184 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 185 |
-
model = model.to(device)
|
| 186 |
|
| 187 |
-
# Get fused embedding
|
| 188 |
image = Image.open("your_image.jpg").convert("RGB")
|
| 189 |
text = "orange cat"
|
| 190 |
|
| 191 |
with torch.no_grad():
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
print(f"Embedding shape: {embedding.shape}") # torch.Size([1, 512])
|
| 195 |
```
|
|
|
|
| 1 |
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
library_name: transformers
|
| 4 |
tags:
|
| 5 |
- siglip
|
|
|
|
| 10 |
- multimodal
|
| 11 |
- image-text-embeddings
|
| 12 |
- pet-recognition
|
| 13 |
+
model_id: AvitoTech/SigLIP2-giant-e5small-v2-gating
|
| 14 |
pipeline_tag: feature-extraction
|
| 15 |
---
|
| 16 |
|
|
|
|
| 110 |
### Installation
|
| 111 |
|
| 112 |
```bash
|
| 113 |
+
pip install transformers torch pillow
|
| 114 |
```
|
| 115 |
|
| 116 |
### Load Model and Get Embedding
|
| 117 |
|
| 118 |
```python
|
| 119 |
import torch
|
|
|
|
|
|
|
| 120 |
from PIL import Image
|
| 121 |
+
from transformers import AutoImageProcessor, AutoModel, AutoTokenizer
|
| 122 |
+
|
| 123 |
+
repo = "AvitoTech/SigLIP2-giant-e5small-v2-gating"
|
| 124 |
+
model = AutoModel.from_pretrained(repo, trust_remote_code=True).eval()
|
| 125 |
+
image_processor = AutoImageProcessor.from_pretrained(repo)
|
| 126 |
+
tokenizer = AutoTokenizer.from_pretrained(repo)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 129 |
+
model = model.to(device)
|
| 130 |
|
|
|
|
| 131 |
image = Image.open("your_image.jpg").convert("RGB")
|
| 132 |
text = "orange cat"
|
| 133 |
|
| 134 |
with torch.no_grad():
|
| 135 |
+
inputs = image_processor(images=[image], return_tensors="pt")
|
| 136 |
+
inputs.update(tokenizer([text], padding=True, truncation=True,
|
| 137 |
+
max_length=512, return_tensors="pt"))
|
| 138 |
+
embedding = model(**inputs.to(device)).embeds
|
| 139 |
|
| 140 |
print(f"Embedding shape: {embedding.shape}") # torch.Size([1, 512])
|
| 141 |
```
|
config.json
CHANGED
|
@@ -1,48 +1,62 @@
|
|
| 1 |
-
{
|
| 2 |
-
"
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
"
|
| 7 |
-
"
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
"
|
| 14 |
-
"
|
| 15 |
-
"
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "avito_gated_fusion",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"AvitoGatedFusionModel"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_avito_gated.AvitoGatedFusionConfig",
|
| 8 |
+
"AutoModel": "modeling_avito_gated.AvitoGatedFusionModel"
|
| 9 |
+
},
|
| 10 |
+
"embedding_dim": 512,
|
| 11 |
+
"gate_hidden_dim": 128,
|
| 12 |
+
"siglip_config": {
|
| 13 |
+
"initializer_factor": 1.0,
|
| 14 |
+
"model_type": "siglip",
|
| 15 |
+
"text_config": {
|
| 16 |
+
"vocab_size": 256000,
|
| 17 |
+
"hidden_size": 1152,
|
| 18 |
+
"intermediate_size": 4304,
|
| 19 |
+
"num_hidden_layers": 27,
|
| 20 |
+
"num_attention_heads": 16,
|
| 21 |
+
"max_position_embeddings": 64,
|
| 22 |
+
"layer_norm_eps": 1e-06,
|
| 23 |
+
"hidden_act": "gelu_pytorch_tanh",
|
| 24 |
+
"attention_dropout": 0.0,
|
| 25 |
+
"projection_size": 1536,
|
| 26 |
+
"model_type": "siglip_text_model"
|
| 27 |
+
},
|
| 28 |
+
"vision_config": {
|
| 29 |
+
"hidden_size": 1536,
|
| 30 |
+
"intermediate_size": 6144,
|
| 31 |
+
"num_hidden_layers": 40,
|
| 32 |
+
"num_attention_heads": 16,
|
| 33 |
+
"num_channels": 3,
|
| 34 |
+
"patch_size": 16,
|
| 35 |
+
"image_size": 384,
|
| 36 |
+
"attention_dropout": 0.0,
|
| 37 |
+
"layer_norm_eps": 1e-06,
|
| 38 |
+
"hidden_act": "gelu_pytorch_tanh",
|
| 39 |
+
"model_type": "siglip_vision_model"
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
"text_config": {
|
| 43 |
+
"pad_token_id": 0,
|
| 44 |
+
"model_type": "bert",
|
| 45 |
+
"vocab_size": 30522,
|
| 46 |
+
"hidden_size": 384,
|
| 47 |
+
"num_hidden_layers": 12,
|
| 48 |
+
"num_attention_heads": 12,
|
| 49 |
+
"hidden_act": "gelu",
|
| 50 |
+
"intermediate_size": 1536,
|
| 51 |
+
"hidden_dropout_prob": 0.1,
|
| 52 |
+
"attention_probs_dropout_prob": 0.1,
|
| 53 |
+
"max_position_embeddings": 512,
|
| 54 |
+
"type_vocab_size": 2,
|
| 55 |
+
"initializer_range": 0.02,
|
| 56 |
+
"layer_norm_eps": 1e-12,
|
| 57 |
+
"position_embedding_type": "absolute",
|
| 58 |
+
"use_cache": true,
|
| 59 |
+
"classifier_dropout": null
|
| 60 |
+
},
|
| 61 |
+
"dtype": "float32"
|
| 62 |
+
}
|
configuration_avito_gated.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration for the SigLIP2-Giant + E5-Small-v2 gated-fusion model."""
|
| 2 |
+
|
| 3 |
+
from transformers import BertConfig, SiglipConfig
|
| 4 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class AvitoGatedFusionConfig(PretrainedConfig):
|
| 8 |
+
"""Config for `AvitoGatedFusionModel`.
|
| 9 |
+
|
| 10 |
+
The model is a composite: a SigLIP2 tower (`siglip_config`) supplies the image
|
| 11 |
+
embedding, a BERT-style tower (`text_config`) supplies the text embedding, both
|
| 12 |
+
are projected to `embedding_dim` and mixed by a learned 2-way gate.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
model_type = "avito_gated_fusion"
|
| 16 |
+
sub_configs = {"siglip_config": SiglipConfig, "text_config": BertConfig}
|
| 17 |
+
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
siglip_config=None,
|
| 21 |
+
text_config=None,
|
| 22 |
+
embedding_dim=512,
|
| 23 |
+
gate_hidden_dim=128,
|
| 24 |
+
**kwargs,
|
| 25 |
+
):
|
| 26 |
+
if siglip_config is None:
|
| 27 |
+
siglip_config = {}
|
| 28 |
+
if text_config is None:
|
| 29 |
+
text_config = {}
|
| 30 |
+
if isinstance(siglip_config, dict):
|
| 31 |
+
siglip_config = SiglipConfig(**siglip_config)
|
| 32 |
+
if isinstance(text_config, dict):
|
| 33 |
+
text_config = BertConfig(**text_config)
|
| 34 |
+
|
| 35 |
+
self.siglip_config = siglip_config
|
| 36 |
+
self.text_config = text_config
|
| 37 |
+
self.embedding_dim = embedding_dim
|
| 38 |
+
self.gate_hidden_dim = gate_hidden_dim
|
| 39 |
+
|
| 40 |
+
super().__init__(**kwargs)
|
| 41 |
+
|
| 42 |
+
@property
|
| 43 |
+
def image_embed_dim(self):
|
| 44 |
+
return self.siglip_config.vision_config.hidden_size
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def text_embed_dim(self):
|
| 48 |
+
return self.text_config.hidden_size
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
__all__ = ["AvitoGatedFusionConfig"]
|
modeling_avito_gated.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SigLIP2-Giant + E5-Small-v2 gated-fusion model for animal identification.
|
| 2 |
+
|
| 3 |
+
This mirrors, one-for-one, the `FaceRecognizer` wrapper the checkpoint was trained
|
| 4 |
+
with (see the model card): the tensor names in `model.safetensors` are exactly the
|
| 5 |
+
attribute names used here, so the published weights load unchanged.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from torch import nn
|
| 14 |
+
from transformers import BertModel, SiglipModel
|
| 15 |
+
from transformers.modeling_outputs import ModelOutput
|
| 16 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 17 |
+
|
| 18 |
+
from .configuration_avito_gated import AvitoGatedFusionConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class AvitoGatedFusionOutput(ModelOutput):
|
| 23 |
+
"""
|
| 24 |
+
Args:
|
| 25 |
+
embeds: L2-normalised fused embedding, `(batch, embedding_dim)`.
|
| 26 |
+
image_embeds: image embedding after `proj_img`, `(batch, embedding_dim)`.
|
| 27 |
+
text_embeds: text embedding after `proj_text`, `(batch, embedding_dim)`.
|
| 28 |
+
gate_weights: gate output, `(batch, 2)`, ordered `[text, image]`.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
embeds: Optional[torch.FloatTensor] = None
|
| 32 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 33 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 34 |
+
gate_weights: Optional[torch.FloatTensor] = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class AvitoGatedFusionModel(PreTrainedModel):
|
| 38 |
+
config_class = AvitoGatedFusionConfig
|
| 39 |
+
# Deliberately not a prefix that appears in the checkpoint, so that the
|
| 40 |
+
# `clip.` / `text_encoder.` keys are loaded verbatim.
|
| 41 |
+
base_model_prefix = "avito_gated_fusion"
|
| 42 |
+
main_input_name = "pixel_values"
|
| 43 |
+
_supports_sdpa = True
|
| 44 |
+
supports_gradient_checkpointing = True
|
| 45 |
+
|
| 46 |
+
def __init__(self, config: AvitoGatedFusionConfig):
|
| 47 |
+
super().__init__(config)
|
| 48 |
+
self.clip = SiglipModel(config.siglip_config)
|
| 49 |
+
self.text_encoder = BertModel(config.text_config)
|
| 50 |
+
self.proj_img = nn.Linear(config.image_embed_dim, config.embedding_dim)
|
| 51 |
+
self.proj_text = nn.Linear(config.text_embed_dim, config.embedding_dim)
|
| 52 |
+
self.gate = nn.Sequential(
|
| 53 |
+
nn.Linear(config.embedding_dim * 2, config.gate_hidden_dim),
|
| 54 |
+
nn.ReLU(),
|
| 55 |
+
nn.Linear(config.gate_hidden_dim, 2),
|
| 56 |
+
nn.Softmax(dim=-1),
|
| 57 |
+
)
|
| 58 |
+
self.post_init()
|
| 59 |
+
|
| 60 |
+
def _init_weights(self, module):
|
| 61 |
+
std = getattr(self.config, "initializer_range", 0.02)
|
| 62 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 63 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 64 |
+
if module.bias is not None:
|
| 65 |
+
module.bias.data.zero_()
|
| 66 |
+
elif isinstance(module, nn.Embedding):
|
| 67 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 68 |
+
if module.padding_idx is not None:
|
| 69 |
+
module.weight.data[module.padding_idx].zero_()
|
| 70 |
+
elif isinstance(module, nn.LayerNorm):
|
| 71 |
+
module.bias.data.zero_()
|
| 72 |
+
module.weight.data.fill_(1.0)
|
| 73 |
+
elif isinstance(module, nn.Parameter):
|
| 74 |
+
module.data.normal_(mean=0.0, std=std)
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def average_pool(last_hidden_states: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
|
| 78 |
+
last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
|
| 79 |
+
return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
|
| 80 |
+
|
| 81 |
+
def get_image_features(self, pixel_values: torch.FloatTensor, **kwargs) -> torch.FloatTensor:
|
| 82 |
+
"""Raw SigLIP2 image embedding, `(batch, image_embed_dim)`."""
|
| 83 |
+
return self.clip.get_image_features(pixel_values=pixel_values, **kwargs)
|
| 84 |
+
|
| 85 |
+
def get_text_features(
|
| 86 |
+
self,
|
| 87 |
+
input_ids: torch.LongTensor,
|
| 88 |
+
attention_mask: torch.Tensor,
|
| 89 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 90 |
+
**kwargs,
|
| 91 |
+
) -> torch.FloatTensor:
|
| 92 |
+
"""Mean-pooled E5 text embedding, `(batch, text_embed_dim)`."""
|
| 93 |
+
outputs = self.text_encoder(
|
| 94 |
+
input_ids=input_ids,
|
| 95 |
+
attention_mask=attention_mask,
|
| 96 |
+
token_type_ids=token_type_ids,
|
| 97 |
+
**kwargs,
|
| 98 |
+
)
|
| 99 |
+
return self.average_pool(outputs.last_hidden_state, attention_mask)
|
| 100 |
+
|
| 101 |
+
def forward(
|
| 102 |
+
self,
|
| 103 |
+
pixel_values: torch.FloatTensor,
|
| 104 |
+
input_ids: torch.LongTensor,
|
| 105 |
+
attention_mask: torch.Tensor,
|
| 106 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 107 |
+
return_dict: Optional[bool] = None,
|
| 108 |
+
):
|
| 109 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 110 |
+
|
| 111 |
+
img_emb = self.get_image_features(pixel_values)
|
| 112 |
+
text_emb = self.get_text_features(input_ids, attention_mask, token_type_ids)
|
| 113 |
+
|
| 114 |
+
img_proj = self.proj_img(img_emb)
|
| 115 |
+
text_proj = self.proj_text(text_emb)
|
| 116 |
+
|
| 117 |
+
fused = torch.cat([text_proj, img_proj], dim=-1)
|
| 118 |
+
w = self.gate(fused)
|
| 119 |
+
fused_emb = w[:, 0:1] * text_proj + w[:, 1:2] * img_proj
|
| 120 |
+
embeds = F.normalize(fused_emb, dim=1)
|
| 121 |
+
|
| 122 |
+
if not return_dict:
|
| 123 |
+
return (embeds, img_proj, text_proj, w)
|
| 124 |
+
return AvitoGatedFusionOutput(
|
| 125 |
+
embeds=embeds, image_embeds=img_proj, text_embeds=text_proj, gate_weights=w
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
__all__ = ["AvitoGatedFusionModel", "AvitoGatedFusionOutput"]
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"do_convert_rgb": null,
|
| 3 |
+
"do_normalize": true,
|
| 4 |
+
"do_rescale": true,
|
| 5 |
+
"do_resize": true,
|
| 6 |
+
"image_mean": [
|
| 7 |
+
0.5,
|
| 8 |
+
0.5,
|
| 9 |
+
0.5
|
| 10 |
+
],
|
| 11 |
+
"image_processor_type": "SiglipImageProcessor",
|
| 12 |
+
"image_std": [
|
| 13 |
+
0.5,
|
| 14 |
+
0.5,
|
| 15 |
+
0.5
|
| 16 |
+
],
|
| 17 |
+
"processor_class": "SiglipProcessor",
|
| 18 |
+
"resample": 2,
|
| 19 |
+
"rescale_factor": 0.00392156862745098,
|
| 20 |
+
"size": {
|
| 21 |
+
"height": 384,
|
| 22 |
+
"width": 384
|
| 23 |
+
}
|
| 24 |
+
}
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cls_token": "[CLS]",
|
| 3 |
+
"mask_token": "[MASK]",
|
| 4 |
+
"pad_token": "[PAD]",
|
| 5 |
+
"sep_token": "[SEP]",
|
| 6 |
+
"unk_token": "[UNK]"
|
| 7 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"clean_up_tokenization_spaces": true,
|
| 3 |
+
"cls_token": "[CLS]",
|
| 4 |
+
"do_lower_case": true,
|
| 5 |
+
"mask_token": "[MASK]",
|
| 6 |
+
"model_max_length": 512,
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"sep_token": "[SEP]",
|
| 9 |
+
"strip_accents": null,
|
| 10 |
+
"tokenize_chinese_chars": true,
|
| 11 |
+
"tokenizer_class": "BertTokenizer",
|
| 12 |
+
"unk_token": "[UNK]"
|
| 13 |
+
}
|
vocab.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|