Spaces:
Running
Running
yu-rp
commited on
Commit
·
c64fb9f
1
Parent(s):
9106da3
init
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- API_CLIP/clip_prs/.gitignore +6 -0
- API_CLIP/clip_prs/LICENSE.txt +400 -0
- API_CLIP/clip_prs/README.md +104 -0
- API_CLIP/clip_prs/environment.yml +19 -0
- API_CLIP/clip_prs/utils/__init__.py +10 -0
- API_CLIP/clip_prs/utils/binary_waterbirds.py +52 -0
- API_CLIP/clip_prs/utils/constants.py +2 -0
- API_CLIP/clip_prs/utils/cub_classes.py +2 -0
- API_CLIP/clip_prs/utils/factory.py +382 -0
- API_CLIP/clip_prs/utils/hook.py +91 -0
- API_CLIP/clip_prs/utils/imagenet_classes.py +1 -0
- API_CLIP/clip_prs/utils/imagenet_segmentation.py +50 -0
- API_CLIP/clip_prs/utils/misc.py +114 -0
- API_CLIP/clip_prs/utils/model.py +407 -0
- API_CLIP/clip_prs/utils/model_configs/EVA01-g-14-plus.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/EVA01-g-14.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/EVA02-B-16.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/EVA02-E-14-plus.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/EVA02-E-14.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/EVA02-L-14-336.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/EVA02-L-14.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus-240.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-B-16.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-B-32-plus-256.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-B-32-quickgelu.json +17 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-B-32.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-H-14.json +17 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-H-16.json +17 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-L-14-280.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-L-14-336.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-L-14.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-L-16-320.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-L-16.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-M-16-alt.json +17 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-M-16.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-M-32-alt.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-M-32.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-S-16-alt.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-S-16.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-S-32-alt.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-S-32.json +16 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-bigG-14.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-e-14.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/ViT-g-14.json +18 -0
- API_CLIP/clip_prs/utils/model_configs/coca_ViT-B-32.json +30 -0
- API_CLIP/clip_prs/utils/model_configs/coca_ViT-L-14.json +30 -0
- API_CLIP/clip_prs/utils/model_configs/coca_base.json +31 -0
- API_CLIP/clip_prs/utils/model_configs/coca_roberta-ViT-B-32.json +24 -0
- API_CLIP/clip_prs/utils/model_configs/mt5-base-ViT-B-32.json +15 -0
API_CLIP/clip_prs/.gitignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.ipynb_checkpoints/
|
2 |
+
__pycache__/
|
3 |
+
*/*.mat
|
4 |
+
utils/__pycache__
|
5 |
+
imagenet_seg/
|
6 |
+
run/
|
API_CLIP/clip_prs/LICENSE.txt
ADDED
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
Attribution-NonCommercial 4.0 International
|
3 |
+
|
4 |
+
=======================================================================
|
5 |
+
|
6 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
7 |
+
does not provide legal services or legal advice. Distribution of
|
8 |
+
Creative Commons public licenses does not create a lawyer-client or
|
9 |
+
other relationship. Creative Commons makes its licenses and related
|
10 |
+
information available on an "as-is" basis. Creative Commons gives no
|
11 |
+
warranties regarding its licenses, any material licensed under their
|
12 |
+
terms and conditions, or any related information. Creative Commons
|
13 |
+
disclaims all liability for damages resulting from their use to the
|
14 |
+
fullest extent possible.
|
15 |
+
|
16 |
+
Using Creative Commons Public Licenses
|
17 |
+
|
18 |
+
Creative Commons public licenses provide a standard set of terms and
|
19 |
+
conditions that creators and other rights holders may use to share
|
20 |
+
original works of authorship and other material subject to copyright
|
21 |
+
and certain other rights specified in the public license below. The
|
22 |
+
following considerations are for informational purposes only, are not
|
23 |
+
exhaustive, and do not form part of our licenses.
|
24 |
+
|
25 |
+
Considerations for licensors: Our public licenses are
|
26 |
+
intended for use by those authorized to give the public
|
27 |
+
permission to use material in ways otherwise restricted by
|
28 |
+
copyright and certain other rights. Our licenses are
|
29 |
+
irrevocable. Licensors should read and understand the terms
|
30 |
+
and conditions of the license they choose before applying it.
|
31 |
+
Licensors should also secure all rights necessary before
|
32 |
+
applying our licenses so that the public can reuse the
|
33 |
+
material as expected. Licensors should clearly mark any
|
34 |
+
material not subject to the license. This includes other CC-
|
35 |
+
licensed material, or material used under an exception or
|
36 |
+
limitation to copyright. More considerations for licensors:
|
37 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
38 |
+
|
39 |
+
Considerations for the public: By using one of our public
|
40 |
+
licenses, a licensor grants the public permission to use the
|
41 |
+
licensed material under specified terms and conditions. If
|
42 |
+
the licensor's permission is not necessary for any reason--for
|
43 |
+
example, because of any applicable exception or limitation to
|
44 |
+
copyright--then that use is not regulated by the license. Our
|
45 |
+
licenses grant only permissions under copyright and certain
|
46 |
+
other rights that a licensor has authority to grant. Use of
|
47 |
+
the licensed material may still be restricted for other
|
48 |
+
reasons, including because others have copyright or other
|
49 |
+
rights in the material. A licensor may make special requests,
|
50 |
+
such as asking that all changes be marked or described.
|
51 |
+
Although not required by our licenses, you are encouraged to
|
52 |
+
respect those requests where reasonable. More_considerations
|
53 |
+
for the public:
|
54 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
55 |
+
|
56 |
+
=======================================================================
|
57 |
+
|
58 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
59 |
+
License
|
60 |
+
|
61 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
62 |
+
to be bound by the terms and conditions of this Creative Commons
|
63 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
64 |
+
License"). To the extent this Public License may be interpreted as a
|
65 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
66 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
67 |
+
such rights in consideration of benefits the Licensor receives from
|
68 |
+
making the Licensed Material available under these terms and
|
69 |
+
conditions.
|
70 |
+
|
71 |
+
Section 1 -- Definitions.
|
72 |
+
|
73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
74 |
+
Rights that is derived from or based upon the Licensed Material
|
75 |
+
and in which the Licensed Material is translated, altered,
|
76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
77 |
+
permission under the Copyright and Similar Rights held by the
|
78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
79 |
+
Material is a musical work, performance, or sound recording,
|
80 |
+
Adapted Material is always produced where the Licensed Material is
|
81 |
+
synched in timed relation with a moving image.
|
82 |
+
|
83 |
+
b. Adapter's License means the license You apply to Your Copyright
|
84 |
+
and Similar Rights in Your contributions to Adapted Material in
|
85 |
+
accordance with the terms and conditions of this Public License.
|
86 |
+
|
87 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
88 |
+
closely related to copyright including, without limitation,
|
89 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
90 |
+
Rights, without regard to how the rights are labeled or
|
91 |
+
categorized. For purposes of this Public License, the rights
|
92 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
93 |
+
Rights.
|
94 |
+
d. Effective Technological Measures means those measures that, in the
|
95 |
+
absence of proper authority, may not be circumvented under laws
|
96 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
97 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
98 |
+
agreements.
|
99 |
+
|
100 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
101 |
+
any other exception or limitation to Copyright and Similar Rights
|
102 |
+
that applies to Your use of the Licensed Material.
|
103 |
+
|
104 |
+
f. Licensed Material means the artistic or literary work, database,
|
105 |
+
or other material to which the Licensor applied this Public
|
106 |
+
License.
|
107 |
+
|
108 |
+
g. Licensed Rights means the rights granted to You subject to the
|
109 |
+
terms and conditions of this Public License, which are limited to
|
110 |
+
all Copyright and Similar Rights that apply to Your use of the
|
111 |
+
Licensed Material and that the Licensor has authority to license.
|
112 |
+
|
113 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
114 |
+
under this Public License.
|
115 |
+
|
116 |
+
i. NonCommercial means not primarily intended for or directed towards
|
117 |
+
commercial advantage or monetary compensation. For purposes of
|
118 |
+
this Public License, the exchange of the Licensed Material for
|
119 |
+
other material subject to Copyright and Similar Rights by digital
|
120 |
+
file-sharing or similar means is NonCommercial provided there is
|
121 |
+
no payment of monetary compensation in connection with the
|
122 |
+
exchange.
|
123 |
+
|
124 |
+
j. Share means to provide material to the public by any means or
|
125 |
+
process that requires permission under the Licensed Rights, such
|
126 |
+
as reproduction, public display, public performance, distribution,
|
127 |
+
dissemination, communication, or importation, and to make material
|
128 |
+
available to the public including in ways that members of the
|
129 |
+
public may access the material from a place and at a time
|
130 |
+
individually chosen by them.
|
131 |
+
|
132 |
+
k. Sui Generis Database Rights means rights other than copyright
|
133 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
134 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
135 |
+
as amended and/or succeeded, as well as other essentially
|
136 |
+
equivalent rights anywhere in the world.
|
137 |
+
|
138 |
+
l. You means the individual or entity exercising the Licensed Rights
|
139 |
+
under this Public License. Your has a corresponding meaning.
|
140 |
+
|
141 |
+
Section 2 -- Scope.
|
142 |
+
|
143 |
+
a. License grant.
|
144 |
+
|
145 |
+
1. Subject to the terms and conditions of this Public License,
|
146 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
147 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
148 |
+
exercise the Licensed Rights in the Licensed Material to:
|
149 |
+
|
150 |
+
a. reproduce and Share the Licensed Material, in whole or
|
151 |
+
in part, for NonCommercial purposes only; and
|
152 |
+
|
153 |
+
b. produce, reproduce, and Share Adapted Material for
|
154 |
+
NonCommercial purposes only.
|
155 |
+
|
156 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
157 |
+
Exceptions and Limitations apply to Your use, this Public
|
158 |
+
License does not apply, and You do not need to comply with
|
159 |
+
its terms and conditions.
|
160 |
+
|
161 |
+
3. Term. The term of this Public License is specified in Section
|
162 |
+
6(a).
|
163 |
+
|
164 |
+
4. Media and formats; technical modifications allowed. The
|
165 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
166 |
+
all media and formats whether now known or hereafter created,
|
167 |
+
and to make technical modifications necessary to do so. The
|
168 |
+
Licensor waives and/or agrees not to assert any right or
|
169 |
+
authority to forbid You from making technical modifications
|
170 |
+
necessary to exercise the Licensed Rights, including
|
171 |
+
technical modifications necessary to circumvent Effective
|
172 |
+
Technological Measures. For purposes of this Public License,
|
173 |
+
simply making modifications authorized by this Section 2(a)
|
174 |
+
(4) never produces Adapted Material.
|
175 |
+
|
176 |
+
5. Downstream recipients.
|
177 |
+
|
178 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
179 |
+
recipient of the Licensed Material automatically
|
180 |
+
receives an offer from the Licensor to exercise the
|
181 |
+
Licensed Rights under the terms and conditions of this
|
182 |
+
Public License.
|
183 |
+
|
184 |
+
b. No downstream restrictions. You may not offer or impose
|
185 |
+
any additional or different terms or conditions on, or
|
186 |
+
apply any Effective Technological Measures to, the
|
187 |
+
Licensed Material if doing so restricts exercise of the
|
188 |
+
Licensed Rights by any recipient of the Licensed
|
189 |
+
Material.
|
190 |
+
|
191 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
192 |
+
may be construed as permission to assert or imply that You
|
193 |
+
are, or that Your use of the Licensed Material is, connected
|
194 |
+
with, or sponsored, endorsed, or granted official status by,
|
195 |
+
the Licensor or others designated to receive attribution as
|
196 |
+
provided in Section 3(a)(1)(A)(i).
|
197 |
+
|
198 |
+
b. Other rights.
|
199 |
+
|
200 |
+
1. Moral rights, such as the right of integrity, are not
|
201 |
+
licensed under this Public License, nor are publicity,
|
202 |
+
privacy, and/or other similar personality rights; however, to
|
203 |
+
the extent possible, the Licensor waives and/or agrees not to
|
204 |
+
assert any such rights held by the Licensor to the limited
|
205 |
+
extent necessary to allow You to exercise the Licensed
|
206 |
+
Rights, but not otherwise.
|
207 |
+
|
208 |
+
2. Patent and trademark rights are not licensed under this
|
209 |
+
Public License.
|
210 |
+
|
211 |
+
3. To the extent possible, the Licensor waives any right to
|
212 |
+
collect royalties from You for the exercise of the Licensed
|
213 |
+
Rights, whether directly or through a collecting society
|
214 |
+
under any voluntary or waivable statutory or compulsory
|
215 |
+
licensing scheme. In all other cases the Licensor expressly
|
216 |
+
reserves any right to collect such royalties, including when
|
217 |
+
the Licensed Material is used other than for NonCommercial
|
218 |
+
purposes.
|
219 |
+
|
220 |
+
Section 3 -- License Conditions.
|
221 |
+
|
222 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
223 |
+
following conditions.
|
224 |
+
|
225 |
+
a. Attribution.
|
226 |
+
|
227 |
+
1. If You Share the Licensed Material (including in modified
|
228 |
+
form), You must:
|
229 |
+
|
230 |
+
a. retain the following if it is supplied by the Licensor
|
231 |
+
with the Licensed Material:
|
232 |
+
|
233 |
+
i. identification of the creator(s) of the Licensed
|
234 |
+
Material and any others designated to receive
|
235 |
+
attribution, in any reasonable manner requested by
|
236 |
+
the Licensor (including by pseudonym if
|
237 |
+
designated);
|
238 |
+
|
239 |
+
ii. a copyright notice;
|
240 |
+
|
241 |
+
iii. a notice that refers to this Public License;
|
242 |
+
|
243 |
+
iv. a notice that refers to the disclaimer of
|
244 |
+
warranties;
|
245 |
+
|
246 |
+
v. a URI or hyperlink to the Licensed Material to the
|
247 |
+
extent reasonably practicable;
|
248 |
+
|
249 |
+
b. indicate if You modified the Licensed Material and
|
250 |
+
retain an indication of any previous modifications; and
|
251 |
+
|
252 |
+
c. indicate the Licensed Material is licensed under this
|
253 |
+
Public License, and include the text of, or the URI or
|
254 |
+
hyperlink to, this Public License.
|
255 |
+
|
256 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
257 |
+
reasonable manner based on the medium, means, and context in
|
258 |
+
which You Share the Licensed Material. For example, it may be
|
259 |
+
reasonable to satisfy the conditions by providing a URI or
|
260 |
+
hyperlink to a resource that includes the required
|
261 |
+
information.
|
262 |
+
|
263 |
+
3. If requested by the Licensor, You must remove any of the
|
264 |
+
information required by Section 3(a)(1)(A) to the extent
|
265 |
+
reasonably practicable.
|
266 |
+
|
267 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
268 |
+
License You apply must not prevent recipients of the Adapted
|
269 |
+
Material from complying with this Public License.
|
270 |
+
|
271 |
+
Section 4 -- Sui Generis Database Rights.
|
272 |
+
|
273 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
274 |
+
apply to Your use of the Licensed Material:
|
275 |
+
|
276 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
277 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
278 |
+
portion of the contents of the database for NonCommercial purposes
|
279 |
+
only;
|
280 |
+
|
281 |
+
b. if You include all or a substantial portion of the database
|
282 |
+
contents in a database in which You have Sui Generis Database
|
283 |
+
Rights, then the database in which You have Sui Generis Database
|
284 |
+
Rights (but not its individual contents) is Adapted Material; and
|
285 |
+
|
286 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
287 |
+
all or a substantial portion of the contents of the database.
|
288 |
+
|
289 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
290 |
+
replace Your obligations under this Public License where the Licensed
|
291 |
+
Rights include other Copyright and Similar Rights.
|
292 |
+
|
293 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
294 |
+
|
295 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
296 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
297 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
298 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
299 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
300 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
301 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
302 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
303 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
304 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
305 |
+
|
306 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
307 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
308 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
309 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
310 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
311 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
312 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
313 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
314 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
315 |
+
|
316 |
+
c. The disclaimer of warranties and limitation of liability provided
|
317 |
+
above shall be interpreted in a manner that, to the extent
|
318 |
+
possible, most closely approximates an absolute disclaimer and
|
319 |
+
waiver of all liability.
|
320 |
+
|
321 |
+
Section 6 -- Term and Termination.
|
322 |
+
|
323 |
+
a. This Public License applies for the term of the Copyright and
|
324 |
+
Similar Rights licensed here. However, if You fail to comply with
|
325 |
+
this Public License, then Your rights under this Public License
|
326 |
+
terminate automatically.
|
327 |
+
|
328 |
+
b. Where Your right to use the Licensed Material has terminated under
|
329 |
+
Section 6(a), it reinstates:
|
330 |
+
|
331 |
+
1. automatically as of the date the violation is cured, provided
|
332 |
+
it is cured within 30 days of Your discovery of the
|
333 |
+
violation; or
|
334 |
+
|
335 |
+
2. upon express reinstatement by the Licensor.
|
336 |
+
|
337 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
338 |
+
right the Licensor may have to seek remedies for Your violations
|
339 |
+
of this Public License.
|
340 |
+
|
341 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
342 |
+
Licensed Material under separate terms or conditions or stop
|
343 |
+
distributing the Licensed Material at any time; however, doing so
|
344 |
+
will not terminate this Public License.
|
345 |
+
|
346 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
347 |
+
License.
|
348 |
+
|
349 |
+
Section 7 -- Other Terms and Conditions.
|
350 |
+
|
351 |
+
a. The Licensor shall not be bound by any additional or different
|
352 |
+
terms or conditions communicated by You unless expressly agreed.
|
353 |
+
|
354 |
+
b. Any arrangements, understandings, or agreements regarding the
|
355 |
+
Licensed Material not stated herein are separate from and
|
356 |
+
independent of the terms and conditions of this Public License.
|
357 |
+
|
358 |
+
Section 8 -- Interpretation.
|
359 |
+
|
360 |
+
a. For the avoidance of doubt, this Public License does not, and
|
361 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
362 |
+
conditions on any use of the Licensed Material that could lawfully
|
363 |
+
be made without permission under this Public License.
|
364 |
+
|
365 |
+
b. To the extent possible, if any provision of this Public License is
|
366 |
+
deemed unenforceable, it shall be automatically reformed to the
|
367 |
+
minimum extent necessary to make it enforceable. If the provision
|
368 |
+
cannot be reformed, it shall be severed from this Public License
|
369 |
+
without affecting the enforceability of the remaining terms and
|
370 |
+
conditions.
|
371 |
+
|
372 |
+
c. No term or condition of this Public License will be waived and no
|
373 |
+
failure to comply consented to unless expressly agreed to by the
|
374 |
+
Licensor.
|
375 |
+
|
376 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
377 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
378 |
+
that apply to the Licensor or You, including from the legal
|
379 |
+
processes of any jurisdiction or authority.
|
380 |
+
|
381 |
+
=======================================================================
|
382 |
+
|
383 |
+
Creative Commons is not a party to its public
|
384 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
385 |
+
its public licenses to material it publishes and in those instances
|
386 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
387 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
388 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
389 |
+
material is shared under a Creative Commons public license or as
|
390 |
+
otherwise permitted by the Creative Commons policies published at
|
391 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
392 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
393 |
+
of Creative Commons without its prior written consent including,
|
394 |
+
without limitation, in connection with any unauthorized modifications
|
395 |
+
to any of its public licenses or any other arrangements,
|
396 |
+
understandings, or agreements concerning use of licensed material. For
|
397 |
+
the avoidance of doubt, this paragraph does not form part of the
|
398 |
+
public licenses.
|
399 |
+
|
400 |
+
Creative Commons may be contacted at creativecommons.org.
|
API_CLIP/clip_prs/README.md
ADDED
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Interpreting CLIP's Image Representation via Text-Based Decomposition
|
2 |
+
Official PyTorch Implementation
|
3 |
+
|
4 |
+
### [Paper](https://arxiv.org/abs/2310.05916) | [Project Page](https://yossigandelsman.github.io/clip_decomposition/)
|
5 |
+
|
6 |
+
[Yossi Gandelsman](https://yossigandelsman.github.io/), [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros/) and [Jacob Steinhardt](https://jsteinhardt.stat.berkeley.edu/)
|
7 |
+
|
8 |
+
![Teaser](images/teaser.png)
|
9 |
+
|
10 |
+
### Setup
|
11 |
+
We provide an [`environment.yml`](environment.yml) file that can be used to create a Conda environment:
|
12 |
+
|
13 |
+
```bash
|
14 |
+
conda env create -f environment.yml
|
15 |
+
conda activate prsclip
|
16 |
+
```
|
17 |
+
### Preprocessing
|
18 |
+
To obtain the projected residual stream components for the ImageNet validation set, including the contributions from multi-head attentions and MLPs, please run one of the following instructions:
|
19 |
+
|
20 |
+
```bash
|
21 |
+
python compute_prs.py --dataset imagenet --device cuda:0 --model ViT-H-14 --pretrained laion2b_s32b_b79k --data_path <PATH>
|
22 |
+
python compute_prs.py --dataset imagenet --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k --data_path <PATH>
|
23 |
+
python compute_prs.py --dataset imagenet --device cuda:0 --model ViT-B-16 --pretrained laion2b_s34b_b88k --data_path <PATH>
|
24 |
+
```
|
25 |
+
|
26 |
+
To obtain the precomputed text representations of the ImageNet classes, please run:
|
27 |
+
```bash
|
28 |
+
python compute_text_projection.py --dataset imagenet --device cuda:0 --model ViT-H-14 --pretrained laion2b_s32b_b79k
|
29 |
+
python compute_text_projection.py --dataset imagenet --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k
|
30 |
+
python compute_text_projection.py --dataset imagenet --device cuda:0 --model ViT-B-16 --pretrained laion2b_s34b_b88k
|
31 |
+
```
|
32 |
+
|
33 |
+
### Mean-ablations
|
34 |
+
To verify that the MLPs and the attention from the class token to itself can be mean-ablated, please run:
|
35 |
+
|
36 |
+
```bash
|
37 |
+
python compute_ablations.py --model ViT-H-14
|
38 |
+
python compute_ablations.py --model ViT-L-14
|
39 |
+
python compute_ablations.py --model ViT-B-16
|
40 |
+
```
|
41 |
+
|
42 |
+
### Convert text labels to represntation
|
43 |
+
To convert the text labels for <i>TextSpan</i> to CLIP text representations, please run:
|
44 |
+
|
45 |
+
```bash
|
46 |
+
python compute_text_set_projection.py --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k --data_path text_descriptions/google_3498_english.txt
|
47 |
+
python compute_text_set_projection.py --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k --data_path text_descriptions/image_descriptions_general.txt
|
48 |
+
```
|
49 |
+
|
50 |
+
### ImageNet segmentation
|
51 |
+
Please download the dataset from [here](http://calvin-vision.net/bigstuff/proj-imagenet/data/gtsegs_ijcv.mat):
|
52 |
+
|
53 |
+
```bash
|
54 |
+
mkdir imagenet_seg
|
55 |
+
cd imagenet_seg
|
56 |
+
wget http://calvin-vision.net/bigstuff/proj-imagenet/data/gtsegs_ijcv.mat
|
57 |
+
```
|
58 |
+
|
59 |
+
To get the evaluation results, please run:
|
60 |
+
|
61 |
+
```bash
|
62 |
+
python compute_segmentations.py --device cuda:0 --model ViT-H-14 --pretrained laion2b_s32b_b79k --data_path imagenet_seg/gtsegs_ijcv.mat --save_img
|
63 |
+
python compute_segmentations.py --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k --data_path imagenet_seg/gtsegs_ijcv.mat --save_img
|
64 |
+
python compute_segmentations.py --device cuda:0 --model ViT-B-16 --pretrained laion2b_s34b_b88k --data_path imagenet_seg/gtsegs_ijcv.mat --save_img
|
65 |
+
```
|
66 |
+
Save the results with the `--save_img` flag.
|
67 |
+
|
68 |
+
|
69 |
+
### TextSpan
|
70 |
+
|
71 |
+
To find meaningful directions for all the attenion heads, run:
|
72 |
+
```bash
|
73 |
+
python compute_complete_text_set.py --device cuda:0 --model ViT-B-16 --texts_per_head 20 --num_of_last_layers 4 --text_descriptions image_descriptions_general
|
74 |
+
python compute_complete_text_set.py --device cuda:0 --model ViT-L-14 --texts_per_head 20 --num_of_last_layers 4 --text_descriptions image_descriptions_general
|
75 |
+
python compute_complete_text_set.py --device cuda:0 --model ViT-H-14 --texts_per_head 20 --num_of_last_layers 4 --text_descriptions image_descriptions_general
|
76 |
+
```
|
77 |
+
|
78 |
+
### Other datasets
|
79 |
+
To download the Waterbirds datasets, run:
|
80 |
+
```bash
|
81 |
+
wget https://nlp.stanford.edu/data/dro/waterbird_complete95_forest2water2.tar.gz
|
82 |
+
tar -xf waterbird_complete95_forest2water2.tar.gz
|
83 |
+
```
|
84 |
+
To compute the overall accuracy, run:
|
85 |
+
```bash
|
86 |
+
python compute_text_projection.py --dataset binary_waterbirds --device cuda:0 --model ViT-L-14 --pretrained laion2b_s32b_b82k
|
87 |
+
python compute_use_specific_heads.py --model ViT-L-14 --dataset binary_waterbirds
|
88 |
+
```
|
89 |
+
|
90 |
+
### Spatial decomposition
|
91 |
+
Please see a demo for the spatial decomposition of CLIP in `demo.ipynb`.
|
92 |
+
|
93 |
+
### BibTeX
|
94 |
+
|
95 |
+
```bibtex
|
96 |
+
@misc{gandelsman2023interpreting,
|
97 |
+
title={Interpreting CLIP's Image Representation via Text-Based Decomposition},
|
98 |
+
author={Yossi Gandelsman and Alexei A. Efros and Jacob Steinhardt},
|
99 |
+
year={2023},
|
100 |
+
eprint={2310.05916},
|
101 |
+
archivePrefix={arXiv},
|
102 |
+
primaryClass={cs.CV}
|
103 |
+
}
|
104 |
+
```
|
API_CLIP/clip_prs/environment.yml
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: prsclip
|
2 |
+
channels:
|
3 |
+
- pytorch
|
4 |
+
- nvidia
|
5 |
+
dependencies:
|
6 |
+
- python >= 3.8
|
7 |
+
- pytorch >= 1.13
|
8 |
+
- torchvision
|
9 |
+
- pytorch-cuda=11.7
|
10 |
+
- pip:
|
11 |
+
- timm
|
12 |
+
- einops
|
13 |
+
- ftfy
|
14 |
+
- scipy
|
15 |
+
- imageio
|
16 |
+
- h5py
|
17 |
+
- scikit-image
|
18 |
+
- scikit-learn
|
19 |
+
- opencv-python
|
API_CLIP/clip_prs/utils/__init__.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
sys.path.append('API_CLIP/clip_prs')
|
3 |
+
from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
|
4 |
+
from utils.factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer, create_loss
|
5 |
+
from utils.factory import list_models, add_model_config, get_model_config, load_checkpoint
|
6 |
+
from utils.pretrained import list_pretrained, list_pretrained_models_by_tag, list_pretrained_tags_by_model, \
|
7 |
+
get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained
|
8 |
+
from utils.tokenizer import SimpleTokenizer, tokenize, decode
|
9 |
+
from utils.transform import image_transform, AugmentationCfg
|
10 |
+
from utils.openai_templates import OPENAI_IMAGENET_TEMPLATES
|
API_CLIP/clip_prs/utils/binary_waterbirds.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import os.path
|
3 |
+
from typing import Any, Callable, cast, Dict, List, Optional, Tuple
|
4 |
+
from typing import Union
|
5 |
+
|
6 |
+
from PIL import Image
|
7 |
+
import pandas as pd
|
8 |
+
from torchvision.datasets import VisionDataset
|
9 |
+
import torch
|
10 |
+
|
11 |
+
|
12 |
+
def pil_loader(path: str) -> Image.Image:
|
13 |
+
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
|
14 |
+
with open(path, "rb") as f:
|
15 |
+
img = Image.open(f)
|
16 |
+
return img.convert("RGB")
|
17 |
+
|
18 |
+
class BinaryWaterbirds(VisionDataset):
|
19 |
+
def __init__(
|
20 |
+
self,
|
21 |
+
root: str,
|
22 |
+
split: str,
|
23 |
+
loader: Callable[[str], Any] = pil_loader,
|
24 |
+
transform: Optional[Callable] = None,
|
25 |
+
target_transform: Optional[Callable] = None,
|
26 |
+
) -> None:
|
27 |
+
super().__init__(root, transform=transform, target_transform=target_transform)
|
28 |
+
|
29 |
+
self.loader = loader
|
30 |
+
csv = pd.read_csv(os.path.join(root, 'metadata.csv'))
|
31 |
+
split = {'test': 2, 'valid': 1, 'train': 0}[split]
|
32 |
+
csv = csv[csv['split'] == split]
|
33 |
+
self.samples = [(os.path.join(root, csv.iloc[i]['img_filename']), csv.iloc[i]['y']) for i in range(len(csv))]
|
34 |
+
|
35 |
+
def __getitem__(self, index: int) -> Tuple[Any, Any]:
|
36 |
+
"""
|
37 |
+
Args:
|
38 |
+
index (int): Index
|
39 |
+
Returns:
|
40 |
+
tuple: (sample, target) where target is class_index of the target class.
|
41 |
+
"""
|
42 |
+
path, target = self.samples[index]
|
43 |
+
sample = self.loader(path)
|
44 |
+
if self.transform is not None:
|
45 |
+
sample = self.transform(sample)
|
46 |
+
if self.target_transform is not None:
|
47 |
+
target = self.target_transform(target)
|
48 |
+
|
49 |
+
return sample, target
|
50 |
+
|
51 |
+
def __len__(self) -> int:
|
52 |
+
return len(self.samples)
|
API_CLIP/clip_prs/utils/constants.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)
|
2 |
+
OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711)
|
API_CLIP/clip_prs/utils/cub_classes.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
cub_classes = ['Black footed Albatross', 'Laysan Albatross', 'Sooty Albatross', 'Groove billed Ani', 'Crested Auklet', 'Least Auklet', 'Parakeet Auklet', 'Rhinoceros Auklet', 'Brewer Blackbird', 'Red winged Blackbird', 'Rusty Blackbird', 'Yellow headed Blackbird', 'Bobolink', 'Indigo Bunting', 'Lazuli Bunting', 'Painted Bunting', 'Cardinal', 'Spotted Catbird', 'Gray Catbird', 'Yellow breasted Chat', 'Eastern Towhee', 'Chuck will Widow', 'Brandt Cormorant', 'Red faced Cormorant', 'Pelagic Cormorant', 'Bronzed Cowbird', 'Shiny Cowbird', 'Brown Creeper', 'American Crow', 'Fish Crow', 'Black billed Cuckoo', 'Mangrove Cuckoo', 'Yellow billed Cuckoo', 'Gray crowned Rosy Finch', 'Purple Finch', 'Northern Flicker', 'Acadian Flycatcher', 'Great Crested Flycatcher', 'Least Flycatcher', 'Olive sided Flycatcher', 'Scissor tailed Flycatcher', 'Vermilion Flycatcher', 'Yellow bellied Flycatcher', 'Frigatebird', 'Northern Fulmar', 'Gadwall', 'American Goldfinch', 'European Goldfinch', 'Boat tailed Grackle', 'Eared Grebe', 'Horned Grebe', 'Pied billed Grebe', 'Western Grebe', 'Blue Grosbeak', 'Evening Grosbeak', 'Pine Grosbeak', 'Rose breasted Grosbeak', 'Pigeon Guillemot', 'California Gull', 'Glaucous winged Gull', 'Heermann Gull', 'Herring Gull', 'Ivory Gull', 'Ring billed Gull', 'Slaty backed Gull', 'Western Gull', 'Anna Hummingbird', 'Ruby throated Hummingbird', 'Rufous Hummingbird', 'Green Violetear', 'Long tailed Jaeger', 'Pomarine Jaeger', 'Blue Jay', 'Florida Jay', 'Green Jay', 'Dark eyed Junco', 'Tropical Kingbird', 'Gray Kingbird', 'Belted Kingfisher', 'Green Kingfisher', 'Pied Kingfisher', 'Ringed Kingfisher', 'White breasted Kingfisher', 'Red legged Kittiwake', 'Horned Lark', 'Pacific Loon', 'Mallard', 'Western Meadowlark', 'Hooded Merganser', 'Red breasted Merganser', 'Mockingbird', 'Nighthawk', 'Clark Nutcracker', 'White breasted Nuthatch', 'Baltimore Oriole', 'Hooded Oriole', 'Orchard Oriole', 'Scott Oriole', 'Ovenbird', 'Brown Pelican', 'White Pelican', 'Western Wood Pewee', 'Sayornis', 'American Pipit', 'Whip poor Will', 'Horned Puffin', 'Common Raven', 'White necked Raven', 'American Redstart', 'Geococcyx', 'Loggerhead Shrike', 'Great Grey Shrike', 'Baird Sparrow', 'Black throated Sparrow', 'Brewer Sparrow', 'Chipping Sparrow', 'Clay colored Sparrow', 'House Sparrow', 'Field Sparrow', 'Fox Sparrow', 'Grasshopper Sparrow', 'Harris Sparrow', 'Henslow Sparrow', 'Le Conte Sparrow', 'Lincoln Sparrow', 'Nelson Sharp tailed Sparrow', 'Savannah Sparrow', 'Seaside Sparrow', 'Song Sparrow', 'Tree Sparrow', 'Vesper Sparrow', 'White crowned Sparrow', 'White throated Sparrow', 'Cape Glossy Starling', 'Bank Swallow', 'Barn Swallow', 'Cliff Swallow', 'Tree Swallow', 'Scarlet Tanager', 'Summer Tanager', 'Artic Tern', 'Black Tern', 'Caspian Tern', 'Common Tern', 'Elegant Tern', 'Forsters Tern', 'Least Tern', 'Green tailed Towhee', 'Brown Thrasher', 'Sage Thrasher', 'Black capped Vireo', 'Blue headed Vireo', 'Philadelphia Vireo', 'Red eyed Vireo', 'Warbling Vireo', 'White eyed Vireo', 'Yellow throated Vireo', 'Bay breasted Warbler', 'Black and white Warbler', 'Black throated Blue Warbler', 'Blue winged Warbler', 'Canada Warbler', 'Cape May Warbler', 'Cerulean Warbler', 'Chestnut sided Warbler', 'Golden winged Warbler', 'Hooded Warbler', 'Kentucky Warbler', 'Magnolia Warbler', 'Mourning Warbler', 'Myrtle Warbler', 'Nashville Warbler', 'Orange crowned Warbler', 'Palm Warbler', 'Pine Warbler', 'Prairie Warbler', 'Prothonotary Warbler', 'Swainson Warbler', 'Tennessee Warbler', 'Wilson Warbler', 'Worm eating Warbler', 'Yellow Warbler', 'Northern Waterthrush', 'Louisiana Waterthrush', 'Bohemian Waxwing', 'Cedar Waxwing', 'American Three toed Woodpecker', 'Pileated Woodpecker', 'Red bellied Woodpecker', 'Red cockaded Woodpecker', 'Red headed Woodpecker', 'Downy Woodpecker', 'Bewick Wren', 'Cactus Wren', 'Carolina Wren', 'House Wren', 'Marsh Wren', 'Rock Wren', 'Winter Wren', 'Common Yellowthroat']
|
2 |
+
waterbird_classes = ['landbird', 'waterbird']
|
API_CLIP/clip_prs/utils/factory.py
ADDED
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import logging
|
3 |
+
import os
|
4 |
+
import pathlib
|
5 |
+
import re
|
6 |
+
from copy import deepcopy
|
7 |
+
from pathlib import Path
|
8 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
9 |
+
|
10 |
+
import torch
|
11 |
+
|
12 |
+
from utils.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
|
13 |
+
from utils.model import CLIP, convert_to_custom_text_state_dict,\
|
14 |
+
resize_pos_embed, get_cast_dtype
|
15 |
+
from utils.openai_models import load_openai_model
|
16 |
+
from utils.pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained,\
|
17 |
+
list_pretrained_tags_by_model, download_pretrained_from_hf
|
18 |
+
from utils.transform import image_transform, AugmentationCfg
|
19 |
+
from utils.tokenizer import HFTokenizer, tokenize
|
20 |
+
|
21 |
+
|
22 |
+
HF_HUB_PREFIX = 'hf-hub:'
|
23 |
+
_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
|
24 |
+
_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
|
25 |
+
|
26 |
+
|
27 |
+
def _natural_key(string_):
|
28 |
+
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())]
|
29 |
+
|
30 |
+
|
31 |
+
def _rescan_model_configs():
|
32 |
+
global _MODEL_CONFIGS
|
33 |
+
|
34 |
+
config_ext = ('.json',)
|
35 |
+
config_files = []
|
36 |
+
for config_path in _MODEL_CONFIG_PATHS:
|
37 |
+
if config_path.is_file() and config_path.suffix in config_ext:
|
38 |
+
config_files.append(config_path)
|
39 |
+
elif config_path.is_dir():
|
40 |
+
for ext in config_ext:
|
41 |
+
config_files.extend(config_path.glob(f'*{ext}'))
|
42 |
+
|
43 |
+
for cf in config_files:
|
44 |
+
with open(cf, 'r') as f:
|
45 |
+
model_cfg = json.load(f)
|
46 |
+
if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')):
|
47 |
+
_MODEL_CONFIGS[cf.stem] = model_cfg
|
48 |
+
|
49 |
+
_MODEL_CONFIGS = {k: v for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))}
|
50 |
+
|
51 |
+
|
52 |
+
_rescan_model_configs() # initial populate of model config registry
|
53 |
+
|
54 |
+
|
55 |
+
def list_models():
|
56 |
+
""" enumerate available model architectures based on config files """
|
57 |
+
return list(_MODEL_CONFIGS.keys())
|
58 |
+
|
59 |
+
|
60 |
+
def add_model_config(path):
|
61 |
+
""" add model config path or file and update registry """
|
62 |
+
if not isinstance(path, Path):
|
63 |
+
path = Path(path)
|
64 |
+
_MODEL_CONFIG_PATHS.append(path)
|
65 |
+
_rescan_model_configs()
|
66 |
+
|
67 |
+
|
68 |
+
def get_model_config(model_name):
|
69 |
+
if model_name in _MODEL_CONFIGS:
|
70 |
+
return deepcopy(_MODEL_CONFIGS[model_name])
|
71 |
+
else:
|
72 |
+
return None
|
73 |
+
|
74 |
+
|
75 |
+
def get_tokenizer(model_name):
|
76 |
+
if model_name.startswith(HF_HUB_PREFIX):
|
77 |
+
tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):])
|
78 |
+
else:
|
79 |
+
config = get_model_config(model_name)
|
80 |
+
tokenizer = HFTokenizer(
|
81 |
+
config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize
|
82 |
+
return tokenizer
|
83 |
+
|
84 |
+
|
85 |
+
def load_state_dict(checkpoint_path: str, map_location='cpu'):
|
86 |
+
checkpoint = torch.load(checkpoint_path, map_location=map_location)
|
87 |
+
if isinstance(checkpoint, dict) and 'state_dict' in checkpoint:
|
88 |
+
state_dict = checkpoint['state_dict']
|
89 |
+
else:
|
90 |
+
state_dict = checkpoint
|
91 |
+
if next(iter(state_dict.items()))[0].startswith('module'):
|
92 |
+
state_dict = {k[7:]: v for k, v in state_dict.items()}
|
93 |
+
return state_dict
|
94 |
+
|
95 |
+
|
96 |
+
def load_checkpoint(model, checkpoint_path, strict=True):
|
97 |
+
state_dict = load_state_dict(checkpoint_path)
|
98 |
+
# detect old format and make compatible with new format
|
99 |
+
if 'positional_embedding' in state_dict and not hasattr(model, 'positional_embedding'):
|
100 |
+
state_dict = convert_to_custom_text_state_dict(state_dict)
|
101 |
+
resize_pos_embed(state_dict, model)
|
102 |
+
incompatible_keys = model.load_state_dict(state_dict, strict=strict)
|
103 |
+
return incompatible_keys
|
104 |
+
|
105 |
+
|
106 |
+
def create_model(
|
107 |
+
model_name: str,
|
108 |
+
pretrained: Optional[str] = None,
|
109 |
+
precision: str = 'fp32',
|
110 |
+
device: Union[str, torch.device] = 'cpu',
|
111 |
+
jit: bool = False,
|
112 |
+
force_quick_gelu: bool = False,
|
113 |
+
force_custom_text: bool = False,
|
114 |
+
force_patch_dropout: Optional[float] = None,
|
115 |
+
force_image_size: Optional[Union[int, Tuple[int, int]]] = None,
|
116 |
+
pretrained_image: bool = False,
|
117 |
+
pretrained_hf: bool = True,
|
118 |
+
cache_dir: Optional[str] = None,
|
119 |
+
output_dict: Optional[bool] = None,
|
120 |
+
require_pretrained: bool = False,
|
121 |
+
):
|
122 |
+
has_hf_hub_prefix = model_name.startswith(HF_HUB_PREFIX)
|
123 |
+
if has_hf_hub_prefix:
|
124 |
+
model_id = model_name[len(HF_HUB_PREFIX):]
|
125 |
+
checkpoint_path = download_pretrained_from_hf(model_id, cache_dir=cache_dir)
|
126 |
+
config_path = download_pretrained_from_hf(model_id, filename='open_clip_config.json', cache_dir=cache_dir)
|
127 |
+
|
128 |
+
with open(config_path, 'r', encoding='utf-8') as f:
|
129 |
+
config = json.load(f)
|
130 |
+
pretrained_cfg = config['preprocess_cfg']
|
131 |
+
model_cfg = config['model_cfg']
|
132 |
+
else:
|
133 |
+
model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names
|
134 |
+
checkpoint_path = None
|
135 |
+
pretrained_cfg = {}
|
136 |
+
model_cfg = None
|
137 |
+
|
138 |
+
if isinstance(device, str):
|
139 |
+
device = torch.device(device)
|
140 |
+
|
141 |
+
if pretrained and pretrained.lower() == 'openai':
|
142 |
+
logging.info(f'Loading pretrained {model_name} from OpenAI.')
|
143 |
+
model = load_openai_model(
|
144 |
+
model_name,
|
145 |
+
precision=precision,
|
146 |
+
device=device,
|
147 |
+
cache_dir=cache_dir,
|
148 |
+
)
|
149 |
+
else:
|
150 |
+
model_cfg = model_cfg or get_model_config(model_name)
|
151 |
+
if model_cfg is not None:
|
152 |
+
logging.info(f'Loaded {model_name} model config.')
|
153 |
+
else:
|
154 |
+
logging.error(f'Model config for {model_name} not found; available models {list_models()}.')
|
155 |
+
raise RuntimeError(f'Model config for {model_name} not found.')
|
156 |
+
|
157 |
+
if force_quick_gelu:
|
158 |
+
# override for use of QuickGELU on non-OpenAI transformer models
|
159 |
+
model_cfg["quick_gelu"] = True
|
160 |
+
|
161 |
+
if force_patch_dropout is not None:
|
162 |
+
# override the default patch dropout value
|
163 |
+
model_cfg["vision_cfg"]["patch_dropout"] = force_patch_dropout
|
164 |
+
|
165 |
+
if force_image_size is not None:
|
166 |
+
# override model config's image size
|
167 |
+
model_cfg["vision_cfg"]["image_size"] = force_image_size
|
168 |
+
|
169 |
+
is_timm_model = 'timm_model_name' in model_cfg.get('vision_cfg', {})
|
170 |
+
if pretrained_image:
|
171 |
+
if is_timm_model:
|
172 |
+
# pretrained weight loading for timm models set via vision_cfg
|
173 |
+
model_cfg['vision_cfg']['timm_model_pretrained'] = True
|
174 |
+
else:
|
175 |
+
assert False, 'pretrained image towers currently only supported for timm models'
|
176 |
+
|
177 |
+
# cast_dtype set for fp16 and bf16 (manual mixed-precision), not set for 'amp' or 'pure' modes
|
178 |
+
cast_dtype = get_cast_dtype(precision)
|
179 |
+
is_hf_model = 'hf_model_name' in model_cfg.get('text_cfg', {})
|
180 |
+
custom_text = model_cfg.pop('custom_text', False) or force_custom_text or is_hf_model
|
181 |
+
|
182 |
+
if custom_text:
|
183 |
+
if is_hf_model:
|
184 |
+
model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf
|
185 |
+
if "coca" in model_name:
|
186 |
+
raise ValueError('Coca is not implemented')
|
187 |
+
model = CoCa(**model_cfg, cast_dtype=cast_dtype)
|
188 |
+
else:
|
189 |
+
raise ValueError('CustomTextCLIP is not implemented')
|
190 |
+
model = CustomTextCLIP(**model_cfg, cast_dtype=cast_dtype)
|
191 |
+
else:
|
192 |
+
model = CLIP(**model_cfg, cast_dtype=cast_dtype)
|
193 |
+
|
194 |
+
if precision in ("fp16", "bf16"):
|
195 |
+
dtype = torch.float16 if 'fp16' in precision else torch.bfloat16
|
196 |
+
# manual mixed precision that matches original OpenAI behaviour
|
197 |
+
if is_timm_model:
|
198 |
+
# FIXME this is a bit janky, create timm based model in low-precision and
|
199 |
+
# then cast only LayerNormFp32 instances back to float32 so they don't break.
|
200 |
+
# Why? The convert_weights_to_lp fn only works with native models.
|
201 |
+
model.to(device=device, dtype=dtype)
|
202 |
+
from transformer import LayerNormFp32
|
203 |
+
def _convert_ln(m):
|
204 |
+
if isinstance(m, LayerNormFp32):
|
205 |
+
m.weight.data = m.weight.data.to(torch.float32)
|
206 |
+
m.bias.data = m.bias.data.to(torch.float32)
|
207 |
+
model.apply(_convert_ln)
|
208 |
+
else:
|
209 |
+
model.to(device=device)
|
210 |
+
convert_weights_to_lp(model, dtype=dtype)
|
211 |
+
elif precision in ("pure_fp16", "pure_bf16"):
|
212 |
+
dtype = torch.float16 if 'fp16' in precision else torch.bfloat16
|
213 |
+
model.to(device=device, dtype=dtype)
|
214 |
+
else:
|
215 |
+
model.to(device=device)
|
216 |
+
|
217 |
+
pretrained_loaded = False
|
218 |
+
if pretrained:
|
219 |
+
checkpoint_path = ''
|
220 |
+
pretrained_cfg = get_pretrained_cfg(model_name, pretrained)
|
221 |
+
if pretrained_cfg:
|
222 |
+
checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir)
|
223 |
+
elif os.path.exists(pretrained):
|
224 |
+
checkpoint_path = pretrained
|
225 |
+
|
226 |
+
if checkpoint_path:
|
227 |
+
logging.info(f'Loading pretrained {model_name} weights ({pretrained}).')
|
228 |
+
load_checkpoint(model, checkpoint_path)
|
229 |
+
else:
|
230 |
+
error_str = (
|
231 |
+
f'Pretrained weights ({pretrained}) not found for model {model_name}.'
|
232 |
+
f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.')
|
233 |
+
logging.warning(error_str)
|
234 |
+
raise RuntimeError(error_str)
|
235 |
+
pretrained_loaded = True
|
236 |
+
elif has_hf_hub_prefix:
|
237 |
+
logging.info(f'Loading pretrained {model_name} weights ({pretrained}).')
|
238 |
+
load_checkpoint(model, checkpoint_path)
|
239 |
+
pretrained_loaded = True
|
240 |
+
|
241 |
+
if require_pretrained and not pretrained_loaded:
|
242 |
+
# callers of create_model_from_pretrained always expect pretrained weights
|
243 |
+
raise RuntimeError(
|
244 |
+
f'Pretrained weights were required for (model: {model_name}, pretrained: {pretrained}) but not loaded.')
|
245 |
+
|
246 |
+
# set image / mean metadata from pretrained_cfg if available, or use default
|
247 |
+
model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN
|
248 |
+
model.visual.image_std = pretrained_cfg.get('std', None) or OPENAI_DATASET_STD
|
249 |
+
|
250 |
+
if output_dict and hasattr(model, "output_dict"):
|
251 |
+
model.output_dict = True
|
252 |
+
|
253 |
+
if jit:
|
254 |
+
model = torch.jit.script(model)
|
255 |
+
|
256 |
+
return model
|
257 |
+
|
258 |
+
|
259 |
+
def create_loss(args):
|
260 |
+
if args.distill:
|
261 |
+
return DistillClipLoss(
|
262 |
+
local_loss=args.local_loss,
|
263 |
+
gather_with_grad=args.gather_with_grad,
|
264 |
+
cache_labels=True,
|
265 |
+
rank=args.rank,
|
266 |
+
world_size=args.world_size,
|
267 |
+
use_horovod=args.horovod,
|
268 |
+
)
|
269 |
+
elif "coca" in args.model.lower():
|
270 |
+
return CoCaLoss(
|
271 |
+
caption_loss_weight=args.coca_caption_loss_weight,
|
272 |
+
clip_loss_weight=args.coca_contrastive_loss_weight,
|
273 |
+
local_loss=args.local_loss,
|
274 |
+
gather_with_grad=args.gather_with_grad,
|
275 |
+
cache_labels=True,
|
276 |
+
rank=args.rank,
|
277 |
+
world_size=args.world_size,
|
278 |
+
use_horovod=args.horovod,
|
279 |
+
)
|
280 |
+
return ClipLoss(
|
281 |
+
local_loss=args.local_loss,
|
282 |
+
gather_with_grad=args.gather_with_grad,
|
283 |
+
cache_labels=True,
|
284 |
+
rank=args.rank,
|
285 |
+
world_size=args.world_size,
|
286 |
+
use_horovod=args.horovod,
|
287 |
+
)
|
288 |
+
|
289 |
+
|
290 |
+
def create_model_and_transforms(
|
291 |
+
model_name: str,
|
292 |
+
pretrained: Optional[str] = None,
|
293 |
+
precision: str = 'fp32',
|
294 |
+
device: Union[str, torch.device] = 'cpu',
|
295 |
+
jit: bool = False,
|
296 |
+
force_quick_gelu: bool = False,
|
297 |
+
force_custom_text: bool = False,
|
298 |
+
force_patch_dropout: Optional[float] = None,
|
299 |
+
force_image_size: Optional[Union[int, Tuple[int, int]]] = None,
|
300 |
+
pretrained_image: bool = False,
|
301 |
+
pretrained_hf: bool = True,
|
302 |
+
image_mean: Optional[Tuple[float, ...]] = None,
|
303 |
+
image_std: Optional[Tuple[float, ...]] = None,
|
304 |
+
aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None,
|
305 |
+
cache_dir: Optional[str] = None,
|
306 |
+
output_dict: Optional[bool] = None,
|
307 |
+
):
|
308 |
+
model = create_model(
|
309 |
+
model_name,
|
310 |
+
pretrained,
|
311 |
+
precision=precision,
|
312 |
+
device=device,
|
313 |
+
jit=jit,
|
314 |
+
force_quick_gelu=force_quick_gelu,
|
315 |
+
force_custom_text=force_custom_text,
|
316 |
+
force_patch_dropout=force_patch_dropout,
|
317 |
+
force_image_size=force_image_size,
|
318 |
+
pretrained_image=pretrained_image,
|
319 |
+
pretrained_hf=pretrained_hf,
|
320 |
+
cache_dir=cache_dir,
|
321 |
+
output_dict=output_dict,
|
322 |
+
)
|
323 |
+
|
324 |
+
image_mean = image_mean or getattr(model.visual, 'image_mean', None)
|
325 |
+
image_std = image_std or getattr(model.visual, 'image_std', None)
|
326 |
+
preprocess_train = image_transform(
|
327 |
+
model.visual.image_size,
|
328 |
+
is_train=True,
|
329 |
+
mean=image_mean,
|
330 |
+
std=image_std,
|
331 |
+
aug_cfg=aug_cfg,
|
332 |
+
)
|
333 |
+
preprocess_val = image_transform(
|
334 |
+
model.visual.image_size,
|
335 |
+
is_train=False,
|
336 |
+
mean=image_mean,
|
337 |
+
std=image_std,
|
338 |
+
)
|
339 |
+
|
340 |
+
return model, preprocess_train, preprocess_val
|
341 |
+
|
342 |
+
|
343 |
+
def create_model_from_pretrained(
|
344 |
+
model_name: str,
|
345 |
+
pretrained: Optional[str] = None,
|
346 |
+
precision: str = 'fp32',
|
347 |
+
device: Union[str, torch.device] = 'cpu',
|
348 |
+
jit: bool = False,
|
349 |
+
force_quick_gelu: bool = False,
|
350 |
+
force_custom_text: bool = False,
|
351 |
+
force_image_size: Optional[Union[int, Tuple[int, int]]] = None,
|
352 |
+
return_transform: bool = True,
|
353 |
+
image_mean: Optional[Tuple[float, ...]] = None,
|
354 |
+
image_std: Optional[Tuple[float, ...]] = None,
|
355 |
+
cache_dir: Optional[str] = None,
|
356 |
+
):
|
357 |
+
model = create_model(
|
358 |
+
model_name,
|
359 |
+
pretrained,
|
360 |
+
precision=precision,
|
361 |
+
device=device,
|
362 |
+
jit=jit,
|
363 |
+
force_quick_gelu=force_quick_gelu,
|
364 |
+
force_custom_text=force_custom_text,
|
365 |
+
force_image_size=force_image_size,
|
366 |
+
cache_dir=cache_dir,
|
367 |
+
require_pretrained=True,
|
368 |
+
)
|
369 |
+
|
370 |
+
if not return_transform:
|
371 |
+
return model
|
372 |
+
|
373 |
+
image_mean = image_mean or getattr(model.visual, 'image_mean', None)
|
374 |
+
image_std = image_std or getattr(model.visual, 'image_std', None)
|
375 |
+
preprocess = image_transform(
|
376 |
+
model.visual.image_size,
|
377 |
+
is_train=False,
|
378 |
+
mean=image_mean,
|
379 |
+
std=image_std,
|
380 |
+
)
|
381 |
+
|
382 |
+
return model, preprocess
|
API_CLIP/clip_prs/utils/hook.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, Text, Callable, List
|
2 |
+
from collections import defaultdict
|
3 |
+
|
4 |
+
|
5 |
+
class HookManager(object):
|
6 |
+
def __init__(self, hook_dict: Dict[Text, List[Callable]] = None):
|
7 |
+
self.hook_dict = hook_dict or defaultdict(list)
|
8 |
+
self.called = defaultdict(int)
|
9 |
+
self.forks = dict()
|
10 |
+
|
11 |
+
def register(self, name: Text, func: Callable):
|
12 |
+
assert name
|
13 |
+
found_successor = False
|
14 |
+
for header, d in self.forks.items():
|
15 |
+
if name.startswith(header.split('.')[0]+'.'):
|
16 |
+
next_ = name[len(header.split('.')[0]+'.'):].split('.')[0]
|
17 |
+
prev_ = header.split('.')[0]
|
18 |
+
if next_.isnumeric():
|
19 |
+
if prev_ + '.' + next_ == header:
|
20 |
+
d.register(name[len(header)+1:], func)
|
21 |
+
found_successor = True
|
22 |
+
else:
|
23 |
+
if next_ == '*':
|
24 |
+
d.register(name[len(prev_ + '.*')+1:], func)
|
25 |
+
found_successor = True
|
26 |
+
else:
|
27 |
+
d.register(name[len(header)+1:], func)
|
28 |
+
found_successor = True
|
29 |
+
if not found_successor:
|
30 |
+
self.hook_dict[name].append(func)
|
31 |
+
|
32 |
+
def unregister(self, name: Text, func: Callable):
|
33 |
+
assert name
|
34 |
+
found_successor = False
|
35 |
+
for header, d in self.forks.items():
|
36 |
+
if name.startswith(header.split('.')[0]+'.'):
|
37 |
+
next_ = name[len(header.split('.')[0]+'.'):].split('.')[0]
|
38 |
+
prev_ = header.split('.')[0]
|
39 |
+
if next_.isnumeric() and prev_ + '.' + next_ == header:
|
40 |
+
d.register(name[len(header)+1:], func)
|
41 |
+
elif next_ == '*':
|
42 |
+
d.register(name[len(prev_ + '.*')+1:], func)
|
43 |
+
else:
|
44 |
+
d.register(name[len(header)+1:], func)
|
45 |
+
found_successor = True
|
46 |
+
if not found_successor and func in self.hook_dict[name]:
|
47 |
+
self.hook_dict[name].remove(func)
|
48 |
+
|
49 |
+
def __call__(self, name: Text, **kwargs):
|
50 |
+
if name in self.hook_dict:
|
51 |
+
self.called[name] += 1
|
52 |
+
for function in self.hook_dict[name]:
|
53 |
+
ret = function(**kwargs)
|
54 |
+
if len(self.hook_dict[name]) > 1:
|
55 |
+
last = self.hook_dict[name][-1]
|
56 |
+
print(f'The last returned value comes from func {last}')
|
57 |
+
return ret
|
58 |
+
else:
|
59 |
+
return kwargs['ret']
|
60 |
+
|
61 |
+
def fork(self, name):
|
62 |
+
if name in self.forks:
|
63 |
+
raise ValueError(f'Forking with the same name is not allowed. Already forked with {name}.')
|
64 |
+
filtered_hooks = [(k[len(name)+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.')]
|
65 |
+
filtered_hooks_d = defaultdict(list)
|
66 |
+
for i, j in filtered_hooks:
|
67 |
+
if isinstance(j, list):
|
68 |
+
filtered_hooks_d[i].extend(j)
|
69 |
+
else:
|
70 |
+
filtered_hooks_d[i].append(j)
|
71 |
+
new_hook = HookManager(filtered_hooks_d)
|
72 |
+
self.forks[name] = new_hook
|
73 |
+
return new_hook
|
74 |
+
|
75 |
+
def fork_iterative(self, name, iteration):
|
76 |
+
filtered_hooks = [(k[len(name+'.'+str(iteration))+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.'+str(iteration)+'.')]
|
77 |
+
filtered_hooks += [(k[len(name+'.*')+1:], v) for k, v in self.hook_dict.items() if k.startswith(name+'.*.')]
|
78 |
+
filtered_hooks_d = defaultdict(list)
|
79 |
+
for i, j in filtered_hooks:
|
80 |
+
if isinstance(j, list):
|
81 |
+
filtered_hooks_d[i].extend(j)
|
82 |
+
else:
|
83 |
+
filtered_hooks_d[i].append(j)
|
84 |
+
new_hook = HookManager(filtered_hooks_d)
|
85 |
+
self.forks[name+'.'+str(iteration)] = new_hook
|
86 |
+
return new_hook
|
87 |
+
|
88 |
+
def finalize(self):
|
89 |
+
for name in self.hook_dict.keys():
|
90 |
+
if self.called[name] == 0:
|
91 |
+
raise ValueError(f'Hook {name} was registered but never used!')
|
API_CLIP/clip_prs/utils/imagenet_classes.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
imagenet_classes = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "green iguana", "Carolina anole", "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", "American alligator", "triceratops", "worm snake", "ring-necked snake", "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", "freight car", "French horn", "frying pan", "fur coat", "garbage truck", "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"]
|
API_CLIP/clip_prs/utils/imagenet_segmentation.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
import torch.utils.data as data
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
from torchvision.datasets import ImageNet
|
7 |
+
|
8 |
+
from PIL import Image, ImageFilter
|
9 |
+
import h5py
|
10 |
+
from glob import glob
|
11 |
+
|
12 |
+
|
13 |
+
class ImagenetSegmentation(data.Dataset):
|
14 |
+
CLASSES = 2
|
15 |
+
|
16 |
+
def __init__(self,
|
17 |
+
path,
|
18 |
+
transform=None,
|
19 |
+
target_transform=None):
|
20 |
+
self.path = path
|
21 |
+
self.transform = transform
|
22 |
+
self.target_transform = target_transform
|
23 |
+
self.h5py = None
|
24 |
+
tmp = h5py.File(path, 'r')
|
25 |
+
self.data_length = len(tmp['/value/img'])
|
26 |
+
tmp.close()
|
27 |
+
del tmp
|
28 |
+
|
29 |
+
def __getitem__(self, index):
|
30 |
+
|
31 |
+
if self.h5py is None:
|
32 |
+
self.h5py = h5py.File(self.path, 'r')
|
33 |
+
|
34 |
+
img = np.array(self.h5py[self.h5py['/value/img'][index, 0]]).transpose((2, 1, 0))
|
35 |
+
target = np.array(self.h5py[self.h5py[self.h5py['/value/gt'][index, 0]][0, 0]]).transpose((1, 0))
|
36 |
+
|
37 |
+
img = Image.fromarray(img).convert('RGB')
|
38 |
+
target = Image.fromarray(target)
|
39 |
+
|
40 |
+
if self.transform is not None:
|
41 |
+
img = self.transform(img)
|
42 |
+
|
43 |
+
if self.target_transform is not None:
|
44 |
+
target = np.array(self.target_transform(target)).astype('int32')
|
45 |
+
target = torch.from_numpy(target).long()
|
46 |
+
|
47 |
+
return img, target
|
48 |
+
|
49 |
+
def __len__(self):
|
50 |
+
return self.data_length
|
API_CLIP/clip_prs/utils/misc.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import repeat
|
2 |
+
import collections.abc
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch import nn as nn
|
6 |
+
from torchvision.ops.misc import FrozenBatchNorm2d
|
7 |
+
|
8 |
+
|
9 |
+
def freeze_batch_norm_2d(module, module_match={}, name=''):
|
10 |
+
"""
|
11 |
+
Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
|
12 |
+
itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and
|
13 |
+
returned. Otherwise, the module is walked recursively and submodules are converted in place.
|
14 |
+
|
15 |
+
Args:
|
16 |
+
module (torch.nn.Module): Any PyTorch module.
|
17 |
+
module_match (dict): Dictionary of full module names to freeze (all if empty)
|
18 |
+
name (str): Full module name (prefix)
|
19 |
+
|
20 |
+
Returns:
|
21 |
+
torch.nn.Module: Resulting module
|
22 |
+
|
23 |
+
Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762
|
24 |
+
"""
|
25 |
+
res = module
|
26 |
+
is_match = True
|
27 |
+
if module_match:
|
28 |
+
is_match = name in module_match
|
29 |
+
if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)):
|
30 |
+
res = FrozenBatchNorm2d(module.num_features)
|
31 |
+
res.num_features = module.num_features
|
32 |
+
res.affine = module.affine
|
33 |
+
if module.affine:
|
34 |
+
res.weight.data = module.weight.data.clone().detach()
|
35 |
+
res.bias.data = module.bias.data.clone().detach()
|
36 |
+
res.running_mean.data = module.running_mean.data
|
37 |
+
res.running_var.data = module.running_var.data
|
38 |
+
res.eps = module.eps
|
39 |
+
else:
|
40 |
+
for child_name, child in module.named_children():
|
41 |
+
full_child_name = '.'.join([name, child_name]) if name else child_name
|
42 |
+
new_child = freeze_batch_norm_2d(child, module_match, full_child_name)
|
43 |
+
if new_child is not child:
|
44 |
+
res.add_module(child_name, new_child)
|
45 |
+
return res
|
46 |
+
|
47 |
+
|
48 |
+
# From PyTorch internals
|
49 |
+
def _ntuple(n):
|
50 |
+
def parse(x):
|
51 |
+
if isinstance(x, collections.abc.Iterable):
|
52 |
+
return x
|
53 |
+
return tuple(repeat(x, n))
|
54 |
+
return parse
|
55 |
+
|
56 |
+
|
57 |
+
to_1tuple = _ntuple(1)
|
58 |
+
to_2tuple = _ntuple(2)
|
59 |
+
to_3tuple = _ntuple(3)
|
60 |
+
to_4tuple = _ntuple(4)
|
61 |
+
to_ntuple = lambda n, x: _ntuple(n)(x)
|
62 |
+
|
63 |
+
# Replaces all linear layers with linear_replacement
|
64 |
+
# TODO: add int8 support for other linear layers including attn and convnets
|
65 |
+
def replace_linear(model, linear_replacement, include_modules=['c_fc', 'c_proj'], copy_weights=True):
|
66 |
+
for name, module in model.named_children():
|
67 |
+
if len(list(module.children())) > 0:
|
68 |
+
replace_linear(module, linear_replacement, include_modules, copy_weights)
|
69 |
+
|
70 |
+
if isinstance(module, torch.nn.Linear) and name in include_modules:
|
71 |
+
old_module = model._modules[name]
|
72 |
+
model._modules[name] = linear_replacement(
|
73 |
+
module.in_features,
|
74 |
+
module.out_features,
|
75 |
+
module.bias is not None,
|
76 |
+
)
|
77 |
+
if copy_weights:
|
78 |
+
model._modules[name].weight.data.copy_(old_module.weight.data)
|
79 |
+
if model._modules[name].bias is not None:
|
80 |
+
model._modules[name].bias.data.copy_(old_module.bias)
|
81 |
+
|
82 |
+
return model
|
83 |
+
|
84 |
+
def convert_int8_model_to_inference_mode(model):
|
85 |
+
for m in model.modules():
|
86 |
+
if hasattr(m, 'prepare_for_eval'):
|
87 |
+
int8_original_dtype = m.weight.dtype
|
88 |
+
m.prepare_for_eval()
|
89 |
+
m.int8_original_dtype = int8_original_dtype
|
90 |
+
|
91 |
+
|
92 |
+
def accuracy(output, target, topk=(1,)):
|
93 |
+
"""
|
94 |
+
Compute top-k accuracy
|
95 |
+
|
96 |
+
output: torch.Tensor
|
97 |
+
shape (N, C) where N is the number of examples, C the number of classes.
|
98 |
+
these are the logits.
|
99 |
+
|
100 |
+
target: torch.Tensor
|
101 |
+
shape (N,) where N is the number of examples. Groundtruth class id of each example.
|
102 |
+
|
103 |
+
topk: tuple
|
104 |
+
which topk to compute, e.g., topk=(1,5) will compute top-1 and top-5 accuracies
|
105 |
+
|
106 |
+
Returns
|
107 |
+
-------
|
108 |
+
|
109 |
+
list of top-k accuracies in the same order as `topk`
|
110 |
+
"""
|
111 |
+
pred = output.topk(max(topk), 1, True, True)[1].t()
|
112 |
+
correct = pred.eq(target.view(1, -1).expand_as(pred))
|
113 |
+
n = len(target)
|
114 |
+
return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) / n for k in topk]
|
API_CLIP/clip_prs/utils/model.py
ADDED
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" CLIP Model
|
2 |
+
|
3 |
+
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
|
4 |
+
"""
|
5 |
+
from dataclasses import dataclass
|
6 |
+
import logging
|
7 |
+
import math
|
8 |
+
from typing import Optional, Tuple, Union, Text
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
import torch
|
12 |
+
import torch.nn.functional as F
|
13 |
+
from torch import nn
|
14 |
+
from torch.utils.checkpoint import checkpoint
|
15 |
+
|
16 |
+
|
17 |
+
from utils.modified_resnet import ModifiedResNet
|
18 |
+
from utils.timm_model import TimmModel
|
19 |
+
from utils.transformer import LayerNorm, QuickGELU, VisionTransformer, TextTransformer, Attention
|
20 |
+
from utils.misc import to_2tuple
|
21 |
+
from utils.hook import HookManager
|
22 |
+
|
23 |
+
|
24 |
+
@dataclass
|
25 |
+
class CLIPVisionCfg:
|
26 |
+
layers: Union[Tuple[int, int, int, int], int] = 12
|
27 |
+
width: int = 768
|
28 |
+
head_width: int = 64
|
29 |
+
mlp_ratio: float = 4.0
|
30 |
+
patch_size: int = 16
|
31 |
+
image_size: Union[Tuple[int, int], int] = 224
|
32 |
+
|
33 |
+
ls_init_value: Optional[float] = None # layer scale initial value
|
34 |
+
patch_dropout: float = 0. # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results
|
35 |
+
input_patchnorm: bool = False # whether to use dual patchnorm - would only apply the input layernorm on each patch, as post-layernorm already exist in original clip vit design
|
36 |
+
global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580)
|
37 |
+
attentional_pool: bool = False # whether to use attentional pooler in the last embedding layer
|
38 |
+
n_queries: int = 256 # n_queries for attentional pooler
|
39 |
+
attn_pooler_heads: int = 8 # n heads for attentional_pooling
|
40 |
+
output_tokens: bool = False
|
41 |
+
|
42 |
+
timm_model_name: str = None # a valid model name overrides layers, width, patch_size
|
43 |
+
timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model
|
44 |
+
timm_pool: str = 'avg' # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
|
45 |
+
timm_proj: str = 'linear' # linear projection for timm model output ('linear', 'mlp', '')
|
46 |
+
timm_proj_bias: bool = False # enable bias final projection
|
47 |
+
timm_drop: float = 0. # head dropout
|
48 |
+
timm_drop_path: Optional[float] = None # backbone stochastic depth
|
49 |
+
|
50 |
+
|
51 |
+
|
52 |
+
|
53 |
+
def convert_weights_to_lp(model: nn.Module, dtype=torch.float16):
|
54 |
+
"""Convert applicable model parameters to low-precision (bf16 or fp16)"""
|
55 |
+
|
56 |
+
def _convert_weights(l):
|
57 |
+
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
|
58 |
+
l.weight.data = l.weight.data.to(dtype)
|
59 |
+
if l.bias is not None:
|
60 |
+
l.bias.data = l.bias.data.to(dtype)
|
61 |
+
|
62 |
+
if isinstance(l, (nn.MultiheadAttention, Attention)):
|
63 |
+
for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
|
64 |
+
tensor = getattr(l, attr)
|
65 |
+
if tensor is not None:
|
66 |
+
tensor.data = tensor.data.to(dtype)
|
67 |
+
|
68 |
+
if isinstance(l, (CLIP, TextTransformer)):
|
69 |
+
# convert text nn.Parameter projections
|
70 |
+
attr = getattr(l, "text_projection", None)
|
71 |
+
if attr is not None:
|
72 |
+
attr.data = attr.data.to(dtype)
|
73 |
+
|
74 |
+
if isinstance(l, VisionTransformer):
|
75 |
+
# convert vision nn.Parameter projections
|
76 |
+
attr = getattr(l, "proj", None)
|
77 |
+
if attr is not None:
|
78 |
+
attr.data = attr.data.to(dtype)
|
79 |
+
|
80 |
+
model.apply(_convert_weights)
|
81 |
+
|
82 |
+
convert_weights_to_fp16 = convert_weights_to_lp # backwards compat
|
83 |
+
|
84 |
+
|
85 |
+
@dataclass
|
86 |
+
class CLIPTextCfg:
|
87 |
+
context_length: int = 77
|
88 |
+
vocab_size: int = 49408
|
89 |
+
width: int = 512
|
90 |
+
heads: int = 8
|
91 |
+
layers: int = 12
|
92 |
+
ls_init_value: Optional[float] = None # layer scale initial value
|
93 |
+
hf_model_name: str = None
|
94 |
+
hf_tokenizer_name: str = None
|
95 |
+
hf_model_pretrained: bool = True
|
96 |
+
proj: str = 'mlp'
|
97 |
+
pooler_type: str = 'mean_pooler'
|
98 |
+
embed_cls: bool = False
|
99 |
+
pad_id: int = 0
|
100 |
+
output_tokens: bool = False
|
101 |
+
|
102 |
+
|
103 |
+
def get_cast_dtype(precision: str):
|
104 |
+
cast_dtype = None
|
105 |
+
if precision == 'bf16':
|
106 |
+
cast_dtype = torch.bfloat16
|
107 |
+
elif precision == 'fp16':
|
108 |
+
cast_dtype = torch.float16
|
109 |
+
return cast_dtype
|
110 |
+
|
111 |
+
|
112 |
+
def get_input_dtype(precision: str):
|
113 |
+
input_dtype = None
|
114 |
+
if precision in ('bf16', 'pure_bf16'):
|
115 |
+
input_dtype = torch.bfloat16
|
116 |
+
elif precision in ('fp16', 'pure_fp16'):
|
117 |
+
input_dtype = torch.float16
|
118 |
+
return input_dtype
|
119 |
+
|
120 |
+
|
121 |
+
def _build_vision_tower(
|
122 |
+
embed_dim: int,
|
123 |
+
vision_cfg: CLIPVisionCfg,
|
124 |
+
quick_gelu: bool = False,
|
125 |
+
cast_dtype: Optional[torch.dtype] = None,
|
126 |
+
hook: Optional[HookManager]= None,
|
127 |
+
):
|
128 |
+
if isinstance(vision_cfg, dict):
|
129 |
+
vision_cfg = CLIPVisionCfg(**vision_cfg)
|
130 |
+
|
131 |
+
# OpenAI models are pretrained w/ QuickGELU but native nn.GELU is both faster and more
|
132 |
+
# memory efficient in recent PyTorch releases (>= 1.10).
|
133 |
+
# NOTE: timm models always use native GELU regardless of quick_gelu flag.
|
134 |
+
act_layer = QuickGELU if quick_gelu else nn.GELU
|
135 |
+
|
136 |
+
if vision_cfg.timm_model_name:
|
137 |
+
visual = TimmModel(
|
138 |
+
vision_cfg.timm_model_name,
|
139 |
+
pretrained=vision_cfg.timm_model_pretrained,
|
140 |
+
pool=vision_cfg.timm_pool,
|
141 |
+
proj=vision_cfg.timm_proj,
|
142 |
+
proj_bias=vision_cfg.timm_proj_bias,
|
143 |
+
drop=vision_cfg.timm_drop,
|
144 |
+
drop_path=vision_cfg.timm_drop_path,
|
145 |
+
patch_drop=vision_cfg.patch_dropout if vision_cfg.patch_dropout > 0 else None,
|
146 |
+
embed_dim=embed_dim,
|
147 |
+
image_size=vision_cfg.image_size,
|
148 |
+
hook=hook,
|
149 |
+
)
|
150 |
+
elif isinstance(vision_cfg.layers, (tuple, list)):
|
151 |
+
vision_heads = vision_cfg.width * 32 // vision_cfg.head_width
|
152 |
+
visual = ModifiedResNet(
|
153 |
+
layers=vision_cfg.layers,
|
154 |
+
output_dim=embed_dim,
|
155 |
+
heads=vision_heads,
|
156 |
+
image_size=vision_cfg.image_size,
|
157 |
+
width=vision_cfg.width,
|
158 |
+
hook=hook,
|
159 |
+
)
|
160 |
+
else:
|
161 |
+
vision_heads = vision_cfg.width // vision_cfg.head_width
|
162 |
+
norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
|
163 |
+
visual = VisionTransformer(
|
164 |
+
image_size=vision_cfg.image_size,
|
165 |
+
patch_size=vision_cfg.patch_size,
|
166 |
+
width=vision_cfg.width,
|
167 |
+
layers=vision_cfg.layers,
|
168 |
+
heads=vision_heads,
|
169 |
+
mlp_ratio=vision_cfg.mlp_ratio,
|
170 |
+
ls_init_value=vision_cfg.ls_init_value,
|
171 |
+
patch_dropout=vision_cfg.patch_dropout,
|
172 |
+
input_patchnorm=vision_cfg.input_patchnorm,
|
173 |
+
global_average_pool=vision_cfg.global_average_pool,
|
174 |
+
attentional_pool=vision_cfg.attentional_pool,
|
175 |
+
n_queries=vision_cfg.n_queries,
|
176 |
+
attn_pooler_heads=vision_cfg.attn_pooler_heads,
|
177 |
+
output_tokens=vision_cfg.output_tokens,
|
178 |
+
output_dim=embed_dim,
|
179 |
+
act_layer=act_layer,
|
180 |
+
norm_layer=norm_layer,
|
181 |
+
hook=hook,
|
182 |
+
)
|
183 |
+
|
184 |
+
return visual
|
185 |
+
|
186 |
+
|
187 |
+
def _build_text_tower(
|
188 |
+
embed_dim: int,
|
189 |
+
text_cfg: CLIPTextCfg,
|
190 |
+
quick_gelu: bool = False,
|
191 |
+
cast_dtype: Optional[torch.dtype] = None,
|
192 |
+
hook: Optional[HookManager] = None,
|
193 |
+
):
|
194 |
+
if isinstance(text_cfg, dict):
|
195 |
+
text_cfg = CLIPTextCfg(**text_cfg)
|
196 |
+
|
197 |
+
if text_cfg.hf_model_name:
|
198 |
+
from hf_model import HFTextEncoder
|
199 |
+
text = HFTextEncoder(
|
200 |
+
text_cfg.hf_model_name,
|
201 |
+
output_dim=embed_dim,
|
202 |
+
proj=text_cfg.proj,
|
203 |
+
pooler_type=text_cfg.pooler_type,
|
204 |
+
pretrained=text_cfg.hf_model_pretrained,
|
205 |
+
output_tokens=text_cfg.output_tokens,
|
206 |
+
)
|
207 |
+
else:
|
208 |
+
act_layer = QuickGELU if quick_gelu else nn.GELU
|
209 |
+
norm_layer = LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
|
210 |
+
|
211 |
+
text = TextTransformer(
|
212 |
+
context_length=text_cfg.context_length,
|
213 |
+
vocab_size=text_cfg.vocab_size,
|
214 |
+
width=text_cfg.width,
|
215 |
+
heads=text_cfg.heads,
|
216 |
+
layers=text_cfg.layers,
|
217 |
+
ls_init_value=text_cfg.ls_init_value,
|
218 |
+
output_dim=embed_dim,
|
219 |
+
embed_cls=text_cfg.embed_cls,
|
220 |
+
output_tokens=text_cfg.output_tokens,
|
221 |
+
pad_id=text_cfg.pad_id,
|
222 |
+
act_layer=act_layer,
|
223 |
+
norm_layer=norm_layer,
|
224 |
+
)
|
225 |
+
return text
|
226 |
+
|
227 |
+
|
228 |
+
class CLIP(nn.Module):
|
229 |
+
output_dict: torch.jit.Final[bool]
|
230 |
+
|
231 |
+
def __init__(
|
232 |
+
self,
|
233 |
+
embed_dim: int,
|
234 |
+
vision_cfg: CLIPVisionCfg,
|
235 |
+
text_cfg: CLIPTextCfg,
|
236 |
+
quick_gelu: bool = False,
|
237 |
+
cast_dtype: Optional[torch.dtype] = None,
|
238 |
+
output_dict: bool = False,
|
239 |
+
hook: Optional[HookManager] = None,
|
240 |
+
):
|
241 |
+
super().__init__()
|
242 |
+
self.hook_manager = hook or HookManager()
|
243 |
+
self.output_dict = output_dict
|
244 |
+
self.visual = _build_vision_tower(embed_dim, vision_cfg, quick_gelu, cast_dtype, self.hook_manager.fork('visual'))
|
245 |
+
|
246 |
+
text = _build_text_tower(embed_dim, text_cfg, quick_gelu, cast_dtype, self.hook_manager.fork('textual'))
|
247 |
+
self.transformer = text.transformer
|
248 |
+
self.context_length = text.context_length
|
249 |
+
self.vocab_size = text.vocab_size
|
250 |
+
self.token_embedding = text.token_embedding
|
251 |
+
self.positional_embedding = text.positional_embedding
|
252 |
+
self.ln_final = text.ln_final
|
253 |
+
self.text_projection = text.text_projection
|
254 |
+
self.register_buffer('attn_mask', text.attn_mask, persistent=False)
|
255 |
+
|
256 |
+
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
|
257 |
+
|
258 |
+
@torch.jit.ignore
|
259 |
+
def set_grad_checkpointing(self, enable=True):
|
260 |
+
self.visual.set_grad_checkpointing(enable)
|
261 |
+
self.transformer.grad_checkpointing = enable
|
262 |
+
|
263 |
+
def encode_image(self, image, normalize: bool = False, attn_method: Text = 'direct'):
|
264 |
+
features = self.visual(image, attn_method=attn_method)
|
265 |
+
return F.normalize(features, dim=-1) if normalize else features
|
266 |
+
|
267 |
+
def encode_text(self, text, normalize: bool = False):
|
268 |
+
cast_dtype = self.transformer.get_cast_dtype()
|
269 |
+
|
270 |
+
x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
|
271 |
+
|
272 |
+
x = x + self.positional_embedding.to(cast_dtype)
|
273 |
+
# x = x.permute(1, 0, 2) # NLD -> LND
|
274 |
+
x = self.transformer(x, attn_mask=self.attn_mask)
|
275 |
+
# x = x.permute(1, 0, 2) # LND -> NLD
|
276 |
+
x = self.ln_final(x) # [batch_size, n_ctx, transformer.width]
|
277 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
278 |
+
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
|
279 |
+
return F.normalize(x, dim=-1) if normalize else x
|
280 |
+
|
281 |
+
def forward(
|
282 |
+
self,
|
283 |
+
image: Optional[torch.Tensor] = None,
|
284 |
+
text: Optional[torch.Tensor] = None,
|
285 |
+
):
|
286 |
+
image_features = self.encode_image(image, normalize=True) if image is not None else None
|
287 |
+
text_features = self.encode_text(text, normalize=True) if text is not None else None
|
288 |
+
if self.output_dict:
|
289 |
+
return {
|
290 |
+
"image_features": image_features,
|
291 |
+
"text_features": text_features,
|
292 |
+
"logit_scale": self.logit_scale.exp()
|
293 |
+
}
|
294 |
+
return image_features, text_features, self.logit_scale.exp()
|
295 |
+
|
296 |
+
|
297 |
+
# used to maintain checkpoint compatibility
|
298 |
+
def convert_to_custom_text_state_dict(state_dict: dict):
|
299 |
+
if 'text_projection' in state_dict:
|
300 |
+
# old format state_dict, move text tower -> .text
|
301 |
+
new_state_dict = {}
|
302 |
+
for k, v in state_dict.items():
|
303 |
+
if any(k.startswith(p) for p in (
|
304 |
+
'text_projection',
|
305 |
+
'positional_embedding',
|
306 |
+
'token_embedding',
|
307 |
+
'transformer',
|
308 |
+
'ln_final',
|
309 |
+
)):
|
310 |
+
k = 'text.' + k
|
311 |
+
new_state_dict[k] = v
|
312 |
+
return new_state_dict
|
313 |
+
return state_dict
|
314 |
+
|
315 |
+
|
316 |
+
def build_model_from_openai_state_dict(
|
317 |
+
state_dict: dict,
|
318 |
+
quick_gelu=True,
|
319 |
+
cast_dtype=torch.float16,
|
320 |
+
):
|
321 |
+
vit = "visual.proj" in state_dict
|
322 |
+
|
323 |
+
if vit:
|
324 |
+
vision_width = state_dict["visual.conv1.weight"].shape[0]
|
325 |
+
vision_layers = len(
|
326 |
+
[k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
|
327 |
+
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
|
328 |
+
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
|
329 |
+
image_size = vision_patch_size * grid_size
|
330 |
+
else:
|
331 |
+
counts: list = [
|
332 |
+
len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
|
333 |
+
vision_layers = tuple(counts)
|
334 |
+
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
|
335 |
+
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
|
336 |
+
vision_patch_size = None
|
337 |
+
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
|
338 |
+
image_size = output_width * 32
|
339 |
+
|
340 |
+
embed_dim = state_dict["text_projection"].shape[1]
|
341 |
+
context_length = state_dict["positional_embedding"].shape[0]
|
342 |
+
vocab_size = state_dict["token_embedding.weight"].shape[0]
|
343 |
+
transformer_width = state_dict["ln_final.weight"].shape[0]
|
344 |
+
transformer_heads = transformer_width // 64
|
345 |
+
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
|
346 |
+
|
347 |
+
vision_cfg = CLIPVisionCfg(
|
348 |
+
layers=vision_layers,
|
349 |
+
width=vision_width,
|
350 |
+
patch_size=vision_patch_size,
|
351 |
+
image_size=image_size,
|
352 |
+
)
|
353 |
+
text_cfg = CLIPTextCfg(
|
354 |
+
context_length=context_length,
|
355 |
+
vocab_size=vocab_size,
|
356 |
+
width=transformer_width,
|
357 |
+
heads=transformer_heads,
|
358 |
+
layers=transformer_layers,
|
359 |
+
)
|
360 |
+
model = CLIP(
|
361 |
+
embed_dim,
|
362 |
+
vision_cfg=vision_cfg,
|
363 |
+
text_cfg=text_cfg,
|
364 |
+
quick_gelu=quick_gelu, # OpenAI models were trained with QuickGELU
|
365 |
+
cast_dtype=cast_dtype,
|
366 |
+
)
|
367 |
+
|
368 |
+
for key in ["input_resolution", "context_length", "vocab_size"]:
|
369 |
+
state_dict.pop(key, None)
|
370 |
+
|
371 |
+
convert_weights_to_fp16(model) # OpenAI state dicts are partially converted to float16
|
372 |
+
model.load_state_dict(state_dict)
|
373 |
+
return model.eval()
|
374 |
+
|
375 |
+
|
376 |
+
def resize_pos_embed(state_dict, model, interpolation: str = 'bicubic', antialias: bool = True):
|
377 |
+
# Rescale the grid of position embeddings when loading from state_dict
|
378 |
+
old_pos_embed = state_dict.get('visual.positional_embedding', None)
|
379 |
+
if old_pos_embed is None or not hasattr(model.visual, 'grid_size'):
|
380 |
+
return
|
381 |
+
grid_size = to_2tuple(model.visual.grid_size)
|
382 |
+
extra_tokens = 1 # FIXME detect different token configs (ie no class token, or more)
|
383 |
+
new_seq_len = grid_size[0] * grid_size[1] + extra_tokens
|
384 |
+
if new_seq_len == old_pos_embed.shape[0]:
|
385 |
+
return
|
386 |
+
|
387 |
+
if extra_tokens:
|
388 |
+
pos_emb_tok, pos_emb_img = old_pos_embed[:extra_tokens], old_pos_embed[extra_tokens:]
|
389 |
+
else:
|
390 |
+
pos_emb_tok, pos_emb_img = None, old_pos_embed
|
391 |
+
old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img))))
|
392 |
+
|
393 |
+
logging.info('Resizing position embedding grid-size from %s to %s', old_grid_size, grid_size)
|
394 |
+
pos_emb_img = pos_emb_img.reshape(1, old_grid_size[0], old_grid_size[1], -1).permute(0, 3, 1, 2)
|
395 |
+
pos_emb_img = F.interpolate(
|
396 |
+
pos_emb_img,
|
397 |
+
size=grid_size,
|
398 |
+
mode=interpolation,
|
399 |
+
antialias=antialias,
|
400 |
+
align_corners=False,
|
401 |
+
)
|
402 |
+
pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape(1, grid_size[0] * grid_size[1], -1)[0]
|
403 |
+
if pos_emb_tok is not None:
|
404 |
+
new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0)
|
405 |
+
else:
|
406 |
+
new_pos_embed = pos_emb_img
|
407 |
+
state_dict['visual.positional_embedding'] = new_pos_embed
|
API_CLIP/clip_prs/utils/model_configs/EVA01-g-14-plus.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1024,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"timm_model_name": "eva_giant_patch14_224",
|
6 |
+
"timm_model_pretrained": false,
|
7 |
+
"timm_pool": "token",
|
8 |
+
"timm_proj": null
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 1024,
|
14 |
+
"heads": 16,
|
15 |
+
"layers": 24
|
16 |
+
},
|
17 |
+
"custom_text": true
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/EVA01-g-14.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1024,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"timm_model_name": "eva_giant_patch14_224",
|
6 |
+
"timm_model_pretrained": false,
|
7 |
+
"timm_pool": "token",
|
8 |
+
"timm_proj": null
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 768,
|
14 |
+
"heads": 12,
|
15 |
+
"layers": 12
|
16 |
+
},
|
17 |
+
"custom_text": true
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/EVA02-B-16.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"timm_model_name": "eva02_base_patch16_clip_224",
|
6 |
+
"timm_model_pretrained": false,
|
7 |
+
"timm_pool": "token",
|
8 |
+
"timm_proj": null
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 512,
|
14 |
+
"heads": 8,
|
15 |
+
"layers": 12
|
16 |
+
},
|
17 |
+
"custom_text": true
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/EVA02-E-14-plus.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1024,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"timm_model_name": "eva02_enormous_patch14_clip_224",
|
6 |
+
"timm_model_pretrained": false,
|
7 |
+
"timm_pool": "token",
|
8 |
+
"timm_proj": null
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 1280,
|
14 |
+
"heads": 20,
|
15 |
+
"layers": 32
|
16 |
+
},
|
17 |
+
"custom_text": true
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/EVA02-E-14.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1024,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"timm_model_name": "eva02_enormous_patch14_clip_224",
|
6 |
+
"timm_model_pretrained": false,
|
7 |
+
"timm_pool": "token",
|
8 |
+
"timm_proj": null
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 1024,
|
14 |
+
"heads": 16,
|
15 |
+
"layers": 24
|
16 |
+
},
|
17 |
+
"custom_text": true
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/EVA02-L-14-336.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 336,
|
5 |
+
"timm_model_name": "eva02_large_patch14_clip_336",
|
6 |
+
"timm_model_pretrained": false,
|
7 |
+
"timm_pool": "token",
|
8 |
+
"timm_proj": null
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 768,
|
14 |
+
"heads": 12,
|
15 |
+
"layers": 12
|
16 |
+
},
|
17 |
+
"custom_text": true
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/EVA02-L-14.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"timm_model_name": "eva02_large_patch14_clip_224",
|
6 |
+
"timm_model_pretrained": false,
|
7 |
+
"timm_pool": "token",
|
8 |
+
"timm_proj": null
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 768,
|
14 |
+
"heads": 12,
|
15 |
+
"layers": 12
|
16 |
+
},
|
17 |
+
"custom_text": true
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus-240.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 640,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 240,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 896,
|
7 |
+
"patch_size": 16
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 640,
|
13 |
+
"heads": 10,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-B-16-plus.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 640,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 896,
|
7 |
+
"patch_size": 16
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 640,
|
13 |
+
"heads": 10,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-B-16.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 768,
|
7 |
+
"patch_size": 16
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 512,
|
13 |
+
"heads": 8,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-B-32-plus-256.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 640,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 256,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 896,
|
7 |
+
"patch_size": 32
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 640,
|
13 |
+
"heads": 10,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-B-32-quickgelu.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"quick_gelu": true,
|
4 |
+
"vision_cfg": {
|
5 |
+
"image_size": 224,
|
6 |
+
"layers": 12,
|
7 |
+
"width": 768,
|
8 |
+
"patch_size": 32
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 512,
|
14 |
+
"heads": 8,
|
15 |
+
"layers": 12
|
16 |
+
}
|
17 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-B-32.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 768,
|
7 |
+
"patch_size": 32
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 512,
|
13 |
+
"heads": 8,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-H-14.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1024,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 32,
|
6 |
+
"width": 1280,
|
7 |
+
"head_width": 80,
|
8 |
+
"patch_size": 14
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 1024,
|
14 |
+
"heads": 16,
|
15 |
+
"layers": 24
|
16 |
+
}
|
17 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-H-16.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1024,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 32,
|
6 |
+
"width": 1280,
|
7 |
+
"head_width": 80,
|
8 |
+
"patch_size": 16
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 1024,
|
14 |
+
"heads": 16,
|
15 |
+
"layers": 24
|
16 |
+
}
|
17 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-L-14-280.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 280,
|
5 |
+
"layers": 24,
|
6 |
+
"width": 1024,
|
7 |
+
"patch_size": 14
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 768,
|
13 |
+
"heads": 12,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-L-14-336.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 336,
|
5 |
+
"layers": 24,
|
6 |
+
"width": 1024,
|
7 |
+
"patch_size": 14
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 768,
|
13 |
+
"heads": 12,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-L-14.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 24,
|
6 |
+
"width": 1024,
|
7 |
+
"patch_size": 14
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 768,
|
13 |
+
"heads": 12,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-L-16-320.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 320,
|
5 |
+
"layers": 24,
|
6 |
+
"width": 1024,
|
7 |
+
"patch_size": 16
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 768,
|
13 |
+
"heads": 12,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-L-16.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 24,
|
6 |
+
"width": 1024,
|
7 |
+
"patch_size": 16
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 768,
|
13 |
+
"heads": 12,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-M-16-alt.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 384,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 512,
|
7 |
+
"patch_size": 16,
|
8 |
+
"ls_init_value": 1e-4
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"context_length": 77,
|
12 |
+
"vocab_size": 49408,
|
13 |
+
"width": 384,
|
14 |
+
"heads": 6,
|
15 |
+
"layers": 12
|
16 |
+
}
|
17 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-M-16.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 512,
|
7 |
+
"patch_size": 16
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 512,
|
13 |
+
"heads": 8,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-M-32-alt.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 384,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 512,
|
7 |
+
"patch_size": 32
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 384,
|
13 |
+
"heads": 6,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-M-32.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 512,
|
7 |
+
"patch_size": 32
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 512,
|
13 |
+
"heads": 8,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-S-16-alt.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 256,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 384,
|
7 |
+
"patch_size": 16
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 256,
|
13 |
+
"heads": 4,
|
14 |
+
"layers": 10
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-S-16.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 384,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 384,
|
7 |
+
"patch_size": 16
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 384,
|
13 |
+
"heads": 6,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-S-32-alt.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 256,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 384,
|
7 |
+
"patch_size": 32
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 256,
|
13 |
+
"heads": 4,
|
14 |
+
"layers": 10
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-S-32.json
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 384,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 384,
|
7 |
+
"patch_size": 32
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"context_length": 77,
|
11 |
+
"vocab_size": 49408,
|
12 |
+
"width": 384,
|
13 |
+
"heads": 6,
|
14 |
+
"layers": 12
|
15 |
+
}
|
16 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-bigG-14.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1280,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 48,
|
6 |
+
"width": 1664,
|
7 |
+
"head_width": 104,
|
8 |
+
"mlp_ratio": 4.9231,
|
9 |
+
"patch_size": 14
|
10 |
+
},
|
11 |
+
"text_cfg": {
|
12 |
+
"context_length": 77,
|
13 |
+
"vocab_size": 49408,
|
14 |
+
"width": 1280,
|
15 |
+
"heads": 20,
|
16 |
+
"layers": 32
|
17 |
+
}
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-e-14.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1280,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 56,
|
6 |
+
"width": 1792,
|
7 |
+
"head_width": 112,
|
8 |
+
"mlp_ratio": 8.5715,
|
9 |
+
"patch_size": 14
|
10 |
+
},
|
11 |
+
"text_cfg": {
|
12 |
+
"context_length": 77,
|
13 |
+
"vocab_size": 49408,
|
14 |
+
"width": 1280,
|
15 |
+
"heads": 20,
|
16 |
+
"layers": 36
|
17 |
+
}
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/ViT-g-14.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 1024,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 40,
|
6 |
+
"width": 1408,
|
7 |
+
"head_width": 88,
|
8 |
+
"mlp_ratio": 4.3637,
|
9 |
+
"patch_size": 14
|
10 |
+
},
|
11 |
+
"text_cfg": {
|
12 |
+
"context_length": 77,
|
13 |
+
"vocab_size": 49408,
|
14 |
+
"width": 1024,
|
15 |
+
"heads": 16,
|
16 |
+
"layers": 24
|
17 |
+
}
|
18 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/coca_ViT-B-32.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 768,
|
7 |
+
"patch_size": 32,
|
8 |
+
"attentional_pool": true,
|
9 |
+
"attn_pooler_heads": 8,
|
10 |
+
"output_tokens": true
|
11 |
+
},
|
12 |
+
"text_cfg": {
|
13 |
+
"context_length": 76,
|
14 |
+
"vocab_size": 49408,
|
15 |
+
"width": 512,
|
16 |
+
"heads": 8,
|
17 |
+
"layers": 12,
|
18 |
+
"embed_cls": true,
|
19 |
+
"output_tokens": true
|
20 |
+
},
|
21 |
+
"multimodal_cfg": {
|
22 |
+
"context_length": 76,
|
23 |
+
"vocab_size": 49408,
|
24 |
+
"width": 512,
|
25 |
+
"heads": 8,
|
26 |
+
"layers": 12,
|
27 |
+
"attn_pooler_heads": 8
|
28 |
+
},
|
29 |
+
"custom_text": true
|
30 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/coca_ViT-L-14.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 768,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 24,
|
6 |
+
"width": 1024,
|
7 |
+
"patch_size": 14,
|
8 |
+
"attentional_pool": true,
|
9 |
+
"attn_pooler_heads": 8,
|
10 |
+
"output_tokens": true
|
11 |
+
},
|
12 |
+
"text_cfg": {
|
13 |
+
"context_length": 76,
|
14 |
+
"vocab_size": 49408,
|
15 |
+
"width": 768,
|
16 |
+
"heads": 12,
|
17 |
+
"layers": 12,
|
18 |
+
"embed_cls": true,
|
19 |
+
"output_tokens": true
|
20 |
+
},
|
21 |
+
"multimodal_cfg": {
|
22 |
+
"context_length": 76,
|
23 |
+
"vocab_size": 49408,
|
24 |
+
"width": 768,
|
25 |
+
"heads": 12,
|
26 |
+
"layers": 12,
|
27 |
+
"attn_pooler_heads": 12
|
28 |
+
},
|
29 |
+
"custom_text": true
|
30 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/coca_base.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"multimodal_cfg": {
|
4 |
+
"width": 768,
|
5 |
+
"context_length": 76,
|
6 |
+
"vocab_size": 64000,
|
7 |
+
"mlp_ratio": 4,
|
8 |
+
"layers": 12,
|
9 |
+
"dim_head": 64,
|
10 |
+
"heads": 12,
|
11 |
+
"n_queries": 256,
|
12 |
+
"attn_pooler_heads": 8
|
13 |
+
},
|
14 |
+
"vision_cfg": {
|
15 |
+
"image_size": 288,
|
16 |
+
"layers": 12,
|
17 |
+
"width": 768,
|
18 |
+
"patch_size": 18,
|
19 |
+
"output_tokens": true
|
20 |
+
},
|
21 |
+
"text_cfg": {
|
22 |
+
"context_length": 76,
|
23 |
+
"vocab_size": 64000,
|
24 |
+
"layers": 12,
|
25 |
+
"heads": 12,
|
26 |
+
"width": 768,
|
27 |
+
"embed_cls": true,
|
28 |
+
"output_tokens": true
|
29 |
+
},
|
30 |
+
"custom_text": true
|
31 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/coca_roberta-ViT-B-32.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 768,
|
7 |
+
"patch_size": 32,
|
8 |
+
"output_tokens": true
|
9 |
+
},
|
10 |
+
"text_cfg": {
|
11 |
+
"hf_model_name": "roberta-base",
|
12 |
+
"hf_tokenizer_name": "roberta-base",
|
13 |
+
"proj": "linear",
|
14 |
+
"width": 768,
|
15 |
+
"output_tokens": true
|
16 |
+
},
|
17 |
+
"multimodal_cfg": {
|
18 |
+
"context_length": 76,
|
19 |
+
"width": 768,
|
20 |
+
"heads": 8,
|
21 |
+
"layers": 12
|
22 |
+
},
|
23 |
+
"custom_text": true
|
24 |
+
}
|
API_CLIP/clip_prs/utils/model_configs/mt5-base-ViT-B-32.json
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"embed_dim": 512,
|
3 |
+
"vision_cfg": {
|
4 |
+
"image_size": 224,
|
5 |
+
"layers": 12,
|
6 |
+
"width": 768,
|
7 |
+
"patch_size": 32
|
8 |
+
},
|
9 |
+
"text_cfg": {
|
10 |
+
"hf_model_name": "google/mt5-base",
|
11 |
+
"hf_tokenizer_name": "google/mt5-base",
|
12 |
+
"proj": "mlp",
|
13 |
+
"pooler_type": "mean_pooler"
|
14 |
+
}
|
15 |
+
}
|