pfzhu commited on
Commit
071945c
•
1 Parent(s): a0fd4bb

Upload folder using huggingface_hub

Browse files
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 LY Corporation
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,76 @@
1
  ---
 
2
  license: apache-2.0
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language: ja
3
  license: apache-2.0
4
+ tags:
5
+ - clip
6
+ - japanese-clip
7
+ pipeline_tag: feature-extraction
8
  ---
9
+
10
+ # clip-japanese-base
11
+
12
+ This is a Japanese [CLIP (Contrastive Language-Image Pre-training)](https://arxiv.org/abs/2103.00020) model developed by [LY Corporation](https://www.lycorp.co.jp/en/). This model was trained on ~1B web-collected image-text pairs, and it is applicable to various visual tasks including zero-shot image classification, text-to-image or image-to-text retrieval.
13
+
14
+ ## How to use
15
+ 1. Install packages
16
+ ```
17
+ pip install pillow requests sentencepiece transformers torch timm
18
+ ```
19
+ 2. Run
20
+ ```python
21
+ import io
22
+ import requests
23
+ from PIL import Image
24
+ import torch
25
+ from transformers import AutoImageProcessor, AutoModel, AutoTokenizer
26
+
27
+ HF_MODEL_PATH = 'line-corporation/clip-japanese-base'
28
+ tokenizer = AutoTokenizer.from_pretrained(HF_MODEL_PATH, trust_remote_code=True)
29
+ processor = AutoImageProcessor.from_pretrained(HF_MODEL_PATH, trust_remote_code=True)
30
+ model = AutoModel.from_pretrained(HF_MODEL_PATH, trust_remote_code=True)
31
+ device = "cuda" if torch.cuda.is_available() else "cpu"
32
+
33
+ image = Image.open(io.BytesIO(requests.get('https://images.pexels.com/photos/2253275/pexels-photo-2253275.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260').content))
34
+ image = processor(image, return_tensors="pt")
35
+ text = tokenizer(["犬", "猫", "象"])
36
+
37
+ with torch.no_grad():
38
+ image_features = model.get_image_features(**image)
39
+ text_features = model.get_text_features(**text)
40
+ text_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1)
41
+
42
+ print("Label probs:", text_probs)
43
+ # [[1., 0., 0.]]
44
+ ```
45
+
46
+ ## Model architecture
47
+
48
+ The model uses an [Eva02-B](https://huggingface.co/timm/eva02_base_patch16_clip_224.merged2b_s8b_b131k) Transformer architecture as the image encoder and a 12-layer BERT as the text encoder. The text encoder was initialized from [rinna/japanese-clip-vit-b-16](https://huggingface.co/rinna/japanese-clip-vit-b-16).
49
+
50
+ ## Evaluation
51
+ ### Dataset
52
+ - [STAIR Captions](http://captions.stair.center/) (v2014 val set of MSCOCO) for image-to-text (i2t) and text-to-image (t2i) retrieval. We measure performance using R@1, which is the average recall of i2t and t2i retrieval.
53
+ - [Recruit Datasets](https://huggingface.co/datasets/recruit-jp/japanese-image-classification-evaluation-dataset) for image classification.
54
+ - [ImageNet-1K](https://www.image-net.org/download.php) for image classification. We translated all classnames into Japanese. The classnames and templates can be found in `ja-imagenet-1k-classnames.txt` and `ja-imagenet-1k-templates.txt`.
55
+
56
+ ### Result
57
+ | Model | Image Encoder Params | Text Encoder params | STAIR Captions (R@1) | Recruit Datasets (acc@1) | ImageNet-1K (acc@1) |
58
+ |-------------------|----------------------|---------------------|----------------|------------------|-----------------|
59
+ | [Ours](https://huggingface.co/line-corporation/clip-japanese-base) | 86M(Eva02-B) | 100M(BERT) | **0.30** | **0.89** | 0.58 |
60
+ | [Stable-ja-clip](https://huggingface.co/stabilityai/japanese-stable-clip-vit-l-16) | 307M(ViT-L) | 100M(BERT) | 0.24 | 0.77 | **0.68** |
61
+ | [Rinna-ja-clip](https://huggingface.co/rinna/japanese-clip-vit-b-16) | 86M(ViT-B) | 100M(BERT) | 0.13 | 0.54 | 0.56 |
62
+ | [Laion-clip](https://huggingface.co/laion/CLIP-ViT-H-14-frozen-xlm-roberta-large-laion5B-s13B-b90k) | 632M(ViT-H) | 561M(XLM-RoBERTa) | **0.30** | 0.83 | 0.58 |
63
+ | [Hakuhodo-ja-clip](https://huggingface.co/hakuhodo-tech/japanese-clip-vit-h-14-bert-wider) | 632M(ViT-H) | 100M(BERT) | 0.21 | 0.82 | 0.46 |
64
+
65
+ ## Licenses
66
+
67
+ [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0)
68
+
69
+ ## Citation
70
+ ```
71
+ @misc{clip-japanese-base,
72
+ title = {CLIP Japanese Base},
73
+ author={Shuhei Yokoo, Shuntaro Okada, Peifei Zhu, Shuhei Nishimura and Naoki Takayama}
74
+ url = {https://huggingface.co/line-corporation/clip-japanese-base},
75
+ }
76
+ ```
config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./lycorp/clyp-eva02-b-16",
3
+ "architectures": [
4
+ "CLYPModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_clyp.CLYPConfig",
8
+ "AutoModel": "modeling_clyp.CLYPModel"
9
+ },
10
+ "itc_loss_config": null,
11
+ "learn_temperature": true,
12
+ "model_type": "clyp",
13
+ "temperature_init": 0.07,
14
+ "temperature_max": 1000.0,
15
+ "temperature_min": 0.01,
16
+ "text_encoder_config": {
17
+ "backbone_config": {
18
+ "model_name": "rinna/japanese-clip-vit-b-16"
19
+ },
20
+ "neck_config": {
21
+ "bias": false,
22
+ "in_channels": 768,
23
+ "out_channels": 512
24
+ },
25
+ "pooler_config": {
26
+ "input_type": "huggingface",
27
+ "return_patch_features": false
28
+ }
29
+ },
30
+ "torch_dtype": "float32",
31
+ "transformers_version": "4.39.1",
32
+ "vision_encoder_config": {
33
+ "backbone_config": {
34
+ "extra_kwargs": {},
35
+ "model_name": "eva02_base_patch16_clip_224.merged2b",
36
+ "pretrained": true
37
+ },
38
+ "neck_config": {
39
+ "bias": false,
40
+ "in_channels": 768,
41
+ "out_channels": 512
42
+ },
43
+ "pooler_config": {
44
+ "input_type": "timm",
45
+ "return_patch_features": false
46
+ }
47
+ }
48
+ }
configuration_clyp.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+ # Copyright 2024 LY Corporation.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from __future__ import annotations
17
+
18
+ from typing import Any, Literal, Optional
19
+
20
+ from transformers import PretrainedConfig
21
+
22
+
23
+ class CLYPConfig(PretrainedConfig):
24
+ model_type = "clyp"
25
+
26
+ def __init__(
27
+ self,
28
+ vision_encoder_config: Optional[dict] = None,
29
+ text_encoder_config: Optional[dict] = None,
30
+ itc_loss_config: Optional[dict] = None,
31
+ learn_temperature: bool = True,
32
+ temperature_init: float = 0.07,
33
+ temperature_min: float = 0.01,
34
+ temperature_max: float = 1000.0,
35
+ **kwargs,
36
+ ) -> None:
37
+ super().__init__(**kwargs)
38
+ vision_encoder_config = vision_encoder_config or {}
39
+ text_encoder_config = text_encoder_config or {}
40
+ self.vision_encoder_config = CLYPVisionEncoderConfig(**vision_encoder_config)
41
+ self.text_encoder_config = CLYPTextEncoderConfig(**text_encoder_config)
42
+ self.itc_loss_config = (
43
+ CLYPLossConfig(**itc_loss_config) if itc_loss_config else None
44
+ )
45
+ self.learn_temperature = learn_temperature
46
+ self.temperature_init = temperature_init
47
+ self.temperature_min = temperature_min
48
+ self.temperature_max = temperature_max
49
+
50
+ def to_diff_dict(self) -> dict[str, Any]:
51
+ serializable_config_dict = super().to_diff_dict()
52
+ sub_serializable_config_dict = {
53
+ "vision_encoder_config": _to_diff_dict(self.vision_encoder_config),
54
+ "text_encoder_config": _to_diff_dict(self.text_encoder_config),
55
+ }
56
+ self.dict_torch_dtype_to_str(sub_serializable_config_dict)
57
+ serializable_config_dict.update(sub_serializable_config_dict)
58
+ return serializable_config_dict
59
+
60
+
61
+ class CLYPVisionEncoderConfig(PretrainedConfig):
62
+ def __init__(
63
+ self,
64
+ backbone_config: Optional[dict] = None,
65
+ pooler_config: Optional[dict] = None,
66
+ neck_config: Optional[dict] = None,
67
+ **kwargs,
68
+ ) -> None:
69
+ super().__init__(**kwargs)
70
+ backbone_config = backbone_config or {}
71
+ pooler_config = pooler_config or {"input_type": "timm"}
72
+ neck_config = neck_config or {}
73
+ self.backbone_config = CLYPVisionBackboneConfig(**backbone_config)
74
+ self.pooler_config = CLYPPoolerConfig(**pooler_config)
75
+ self.neck_config = CLYPNeckConfig(**neck_config)
76
+
77
+ def to_diff_dict(self) -> dict[str, Any]:
78
+ serializable_config_dict = {
79
+ "backbone_config": _to_diff_dict(self.backbone_config),
80
+ "pooler_config": _to_diff_dict(self.pooler_config),
81
+ "neck_config": _to_diff_dict(self.neck_config),
82
+ }
83
+ self.dict_torch_dtype_to_str(serializable_config_dict)
84
+ return serializable_config_dict
85
+
86
+
87
+ class CLYPTextEncoderConfig(PretrainedConfig):
88
+ def __init__(
89
+ self,
90
+ backbone_config: Optional[dict] = None,
91
+ pooler_config: Optional[dict] = None,
92
+ neck_config: Optional[dict] = None,
93
+ **kwargs,
94
+ ) -> None:
95
+ super().__init__(**kwargs)
96
+ backbone_config = backbone_config or {}
97
+ pooler_config = pooler_config or {"input_type": "huggingface"}
98
+ neck_config = neck_config or {}
99
+ self.backbone_config = CLYPTextBackboneConfig(**backbone_config)
100
+ self.pooler_config = CLYPPoolerConfig(**pooler_config)
101
+ self.neck_config = CLYPNeckConfig(**neck_config)
102
+
103
+ def to_diff_dict(self) -> dict[str, Any]:
104
+ serializable_config_dict = {
105
+ "backbone_config": _to_diff_dict(self.backbone_config),
106
+ "pooler_config": _to_diff_dict(self.pooler_config),
107
+ "neck_config": _to_diff_dict(self.neck_config),
108
+ }
109
+ self.dict_torch_dtype_to_str(serializable_config_dict)
110
+ return serializable_config_dict
111
+
112
+
113
+ class CLYPVisionBackboneConfig(PretrainedConfig):
114
+ def __init__(
115
+ self,
116
+ model_name: str = "eva02_base_patch16_clip_224.merged2b",
117
+ pretrained: bool = True,
118
+ extra_kwargs: Optional[dict] = None,
119
+ **kwargs,
120
+ ) -> None:
121
+ super().__init__(**kwargs)
122
+ self.model_name = model_name
123
+ self.pretrained = pretrained
124
+ self.extra_kwargs = extra_kwargs or {}
125
+
126
+
127
+ class CLYPTextBackboneConfig(PretrainedConfig):
128
+ def __init__(
129
+ self,
130
+ model_name: str = "rinna/japanese-clip-vit-b-16",
131
+ **kwargs,
132
+ ) -> None:
133
+ super().__init__(**kwargs)
134
+ self.model_name = model_name
135
+
136
+
137
+ class CLYPPoolerConfig(PretrainedConfig):
138
+ def __init__(
139
+ self,
140
+ input_type: Literal["timm", "huggingface"] | None = None,
141
+ return_patch_features: bool = False,
142
+ **kwargs,
143
+ ) -> None:
144
+ super().__init__(**kwargs)
145
+ self.input_type = input_type
146
+ self.return_patch_features = return_patch_features
147
+
148
+
149
+ class CLYPNeckConfig(PretrainedConfig):
150
+ def __init__(
151
+ self,
152
+ in_channels: int = 768,
153
+ out_channels: int = 512,
154
+ bias: bool = False,
155
+ **kwargs,
156
+ ) -> None:
157
+ super().__init__(**kwargs)
158
+ self.in_channels = in_channels
159
+ self.out_channels = out_channels
160
+ self.bias = bias
161
+
162
+
163
+ class CLYPLossConfig(PretrainedConfig):
164
+ def __init__(
165
+ self,
166
+ learn_temperature: bool = True,
167
+ init_temperature: float = 0.07,
168
+ max_temperature: Optional[float] = None,
169
+ min_temperature: Optional[float] = None,
170
+ label_smoothing: float = 0.0,
171
+ gather_with_grad: bool = True,
172
+ **kwargs,
173
+ ) -> None:
174
+ super().__init__(**kwargs)
175
+ self.learn_temperature = learn_temperature
176
+ self.init_temperature = init_temperature
177
+ self.max_temperature = max_temperature
178
+ self.min_temperature = min_temperature
179
+ self.label_smoothing = label_smoothing
180
+ self.gather_with_grad = gather_with_grad
181
+
182
+
183
+ def _to_diff_dict(c: PretrainedConfig) -> dict:
184
+ """Function to override PretrainedConfig.to_diff_dict()
185
+
186
+ NOTE
187
+ ----
188
+ In transformers==4.38.1,
189
+ PretrainedConfig.__repr__ may not be able to show configs that has some sub-configs
190
+ """
191
+ d = c.to_diff_dict()
192
+ if "transformers_version" in d:
193
+ d.pop("transformers_version")
194
+ return d
195
+
196
+
197
+ if __name__ == "__main__":
198
+ conf = CLYPConfig.from_pretrained("config.json")
199
+ print(conf)
image_processing_clyp.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+ # Copyright 2024 LY Corporation.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from __future__ import annotations
17
+
18
+ from typing import Literal, Optional
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torchvision.transforms as T
23
+ import torchvision.transforms.functional as F
24
+ from PIL import Image
25
+ from timm.data import (
26
+ IMAGENET_INCEPTION_MEAN,
27
+ IMAGENET_INCEPTION_STD,
28
+ OPENAI_CLIP_MEAN,
29
+ OPENAI_CLIP_STD,
30
+ )
31
+ from timm.data.transforms_factory import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
32
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
33
+ from transformers.image_utils import ImageInput, make_list_of_images
34
+ from transformers.utils import TensorType
35
+
36
+ NormalizationType = Literal["imagenet", "imagenet_inception", "openai_clip"]
37
+
38
+
39
+ class CLYPImageProcessor(BaseImageProcessor):
40
+ def __init__(
41
+ self,
42
+ image_size: int = 224,
43
+ normalization_type: NormalizationType = "imagenet",
44
+ **kwargs,
45
+ ):
46
+ super().__init__(**kwargs)
47
+ self.image_size = image_size
48
+ self.normalization_type: NormalizationType = normalization_type
49
+
50
+ def preprocess(
51
+ self,
52
+ images: ImageInput | list[ImageInput],
53
+ return_tensors: Optional[str | TensorType] = None,
54
+ **kwargs,
55
+ ) -> BatchFeature:
56
+ images = make_list_of_images(images, expected_ndims=3)
57
+ # TODO: Support train
58
+ transforms = TestTransform(
59
+ self.image_size, normalization_type=self.normalization_type
60
+ )
61
+ images = [transforms(image).numpy() for image in images]
62
+ return BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
63
+
64
+
65
+ class TrainTransform:
66
+ def __init__(
67
+ self,
68
+ image_size: int,
69
+ scale_range_min: float,
70
+ scale_range_max: float,
71
+ normalization_type: NormalizationType = "imagenet",
72
+ ) -> None:
73
+ """
74
+ Args:
75
+ image_size (int): output-image size.
76
+ scale_range_min (float): minimum value of the scale to crop an input image.
77
+ scale_range_max (float): maximum value of the scale to crop an input image.
78
+ normalization_type (str): select mean and std for normalization (see get_mean_and_std).
79
+ """
80
+ scale = (scale_range_min, scale_range_max)
81
+ mean_and_std = get_mean_and_std(normalization_type)
82
+
83
+ self.transform = T.Compose(
84
+ [
85
+ T.RandomResizedCrop(
86
+ image_size, scale=scale, interpolation=T.InterpolationMode.BICUBIC
87
+ ),
88
+ _convert_to_rgb,
89
+ T.ToTensor(),
90
+ T.Normalize(**mean_and_std),
91
+ ]
92
+ )
93
+
94
+ def __call__(self, img):
95
+ return self.transform(img)
96
+
97
+
98
+ class TestTransform:
99
+ def __init__(
100
+ self, image_size: int, normalization_type: NormalizationType = "imagenet"
101
+ ) -> None:
102
+ """
103
+ Args:
104
+ image_size (int): output-image size.
105
+ normalization_type (str): select mean and std for normalization (see get_mean_and_std).
106
+ """
107
+ mean_and_std = get_mean_and_std(normalization_type)
108
+
109
+ self.transform = T.Compose(
110
+ [
111
+ ResizeMaxSize(image_size, fill=0),
112
+ T.CenterCrop(image_size),
113
+ _convert_to_rgb,
114
+ T.ToTensor(),
115
+ T.Normalize(**mean_and_std),
116
+ ]
117
+ )
118
+
119
+ def __call__(self, img):
120
+ return self.transform(img)
121
+
122
+
123
+ class SmallestMaxSize(T.Resize):
124
+ """Resize shorter side of an input image.
125
+
126
+ The shorter side of an input image is resized to the max_size.
127
+ Note that an large part of the input image is discarded when an aspect-ratio value of the input image is extremely small or large.
128
+ """
129
+
130
+ def __init__(self, max_size: int, **kwargs):
131
+ super().__init__(max_size, **kwargs)
132
+
133
+ @staticmethod
134
+ def target_size(w: int, h: int, size: int) -> tuple[int, int]:
135
+ if h < w:
136
+ w, h = int(size * w / h), size
137
+ else:
138
+ w, h = size, int(size * h / w)
139
+ return (h, w)
140
+
141
+ def __call__(self, img):
142
+ size = self.size
143
+ assert isinstance(size, int)
144
+ w, h = img.size
145
+ target_size = self.target_size(w, h, size)
146
+ return F.resize(img, list(target_size), self.interpolation)
147
+
148
+
149
+ class ResizeMaxSize(nn.Module):
150
+ """Resize longer side of an input image.
151
+
152
+ The longer side of an input image is resized to the max_size.
153
+ Note that an large part of the output image is padded when an aspect-ration value of the input image is extremely small or large.
154
+ Adapted from https://github.com/mlfoundations/open_clip/blob/main/src/open_clip/transform.py
155
+ """
156
+
157
+ def __init__(
158
+ self,
159
+ max_size: int,
160
+ interpolation: T.InterpolationMode = T.InterpolationMode.BICUBIC,
161
+ fn: str = "max",
162
+ fill: int = 0,
163
+ ):
164
+ super().__init__()
165
+ if not isinstance(max_size, int):
166
+ raise TypeError(f"Size should be int. Got {type(max_size)}")
167
+ self.max_size = max_size
168
+ self.interpolation = interpolation
169
+ self.fn = min if fn == "min" else min
170
+ self.fill = fill
171
+
172
+ def forward(self, img):
173
+ if isinstance(img, torch.Tensor):
174
+ height, width = img.shape[:2]
175
+ else:
176
+ width, height = img.size
177
+ scale = self.max_size / float(max(height, width))
178
+ if scale != 1.0:
179
+ new_size = tuple(round(dim * scale) for dim in (height, width))
180
+ img = F.resize(img, new_size, self.interpolation) # type: ignore
181
+ pad_h = self.max_size - new_size[0]
182
+ pad_w = self.max_size - new_size[1]
183
+ img = F.pad(
184
+ img,
185
+ padding=[
186
+ pad_w // 2,
187
+ pad_h // 2,
188
+ pad_w - pad_w // 2,
189
+ pad_h - pad_h // 2,
190
+ ],
191
+ fill=self.fill,
192
+ )
193
+ return img
194
+
195
+
196
+ def get_mean_and_std(normalization_type: NormalizationType) -> dict:
197
+ """Return mean and std tensors for T.Normalize()
198
+ NOTE:
199
+ IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
200
+ IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
201
+ IMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5)
202
+ IMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5)
203
+ OPENAI_CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073)
204
+ OPENAI_CLIP_STD = (0.26862954, 0.26130258, 0.27577711)
205
+ """
206
+ if normalization_type == "imagenet":
207
+ return {
208
+ "mean": torch.tensor(IMAGENET_DEFAULT_MEAN),
209
+ "std": torch.tensor(IMAGENET_DEFAULT_STD),
210
+ }
211
+ elif normalization_type == "imagenet_inception":
212
+ return {
213
+ "mean": torch.tensor(IMAGENET_INCEPTION_MEAN),
214
+ "std": torch.tensor(IMAGENET_INCEPTION_STD),
215
+ }
216
+ elif normalization_type == "openai_clip":
217
+ return {
218
+ "mean": torch.tensor(OPENAI_CLIP_MEAN),
219
+ "std": torch.tensor(OPENAI_CLIP_STD),
220
+ }
221
+ else:
222
+ raise ValueError(normalization_type)
223
+
224
+
225
+ def _convert_to_rgb(image: Image.Image) -> Image.Image:
226
+ return image.convert("RGB")
ja-imagenet-1k-classnames.txt ADDED
@@ -0,0 +1,1000 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ テンチ
2
+ 金魚
3
+ ホホジロザメ
4
+ イタチザメ
5
+ シュモクザメ
6
+ シビレエイ
7
+ アカエイ
8
+ 雄鶏,おんどり
9
+ 雌鶏,めんどり
10
+ ダチョウ
11
+ アトリ
12
+ ゴシキヒワ
13
+ メキシコマシコ
14
+ ユキヒメドリ
15
+ ルリノジコ
16
+ コマツグミ
17
+ 目黒
18
+ カケス
19
+ カササギ
20
+ 四十雀,シジュウカラ
21
+ カワガラス
22
+ トビ
23
+ ハクトウワシ,白頭鷲
24
+ ハゲワシ
25
+ カラフトフクロウ
26
+ ファイアサラマンダー
27
+ スベイモリ,オビイモリ
28
+ イモリ
29
+ スポテッドサラマンダー,キボシサンショウウオ
30
+ アホロートル
31
+ ウシガエル
32
+ アマガエル
33
+ オガエル
34
+ アカウミガメ
35
+ オサガメ
36
+ 鼈,ドロガメ
37
+ スッポン
38
+ ハコガメ
39
+ バンドトカゲモドキ
40
+ イグアナ
41
+ グリーンアノール
42
+ ハシリトカゲ
43
+ アガマトカゲ
44
+ エリマキトカゲ
45
+ アシナシトカゲ
46
+ アメリカドクトカゲ
47
+ ミドリカナヘビ
48
+ カメレオン
49
+ コモドオオトカゲ
50
+ ナイルワニ
51
+ ミシシッピワニ
52
+ トリケラトプス
53
+ 盲蛇,ミミズヘビ
54
+ リングネックスネーク
55
+ トウブシシバナヘビ
56
+ 緑のヘビ
57
+ キングスネーク
58
+ ガータースネーク
59
+ ミズヘビ
60
+ ツルヘビ
61
+ 夜行性のヘビ
62
+ ボアコンストリクター
63
+ アフリカニシキヘビ
64
+ インドコブラ
65
+ グリーンマンバ
66
+ ウミヘビ
67
+ サハラツノクサリヘビ
68
+ ダイヤガラガラヘビ
69
+ ヨコバイガラガラヘビ
70
+ 三葉虫
71
+ ザトウムシ
72
+ サソリ
73
+ コガネグモ
74
+ 納屋クモ
75
+ オニグモ
76
+ クロゴケグモ
77
+ タランチュラ
78
+ ドクグモ
79
+ ダニ
80
+ ムカデ
81
+ クロライチョウ
82
+ ライチョウ,雷鳥
83
+ エリマキライチョウ
84
+ 茶色の斑紋のあるライチョウ
85
+ クジャク
86
+ ウズラ
87
+ ヤマウズラ
88
+ ヨウム
89
+ コンゴウインコ
90
+ キバタン
91
+ ヒインコ
92
+ バンケン
93
+ ハチクイ
94
+ サイチョウ
95
+ ハチドリ
96
+ キリハシ,錐嘴
97
+ オオハシ
98
+ アヒル
99
+ ウミアイサ
100
+ ガチョウ
101
+ コクチョウ,黒鳥
102
+ 牙を持つ動物
103
+ ハリモグラ
104
+ カモノハシ
105
+ ワラビー
106
+ コアラ
107
+ ウォンバット
108
+ クラゲ
109
+ イソギンチャク
110
+ 脳珊瑚
111
+ 扁形動物
112
+ 線虫
113
+ ホラガイ,巻き貝
114
+ カタツムリ
115
+ ナメクジ
116
+ ウミウシ
117
+ ヒザラガイ,多板綱
118
+ オウムガイ
119
+ アメリカイチョウガニ
120
+ イワガニ
121
+ シオマネキ
122
+ タラバガニ
123
+ アメリカンロブスター
124
+ 伊勢エビ
125
+ ザリガニ
126
+ ヤドカリ
127
+ ワラジムシ,等脚類
128
+ コウノトリ
129
+ ナベコウ
130
+ ヘラサギ
131
+ フラミンゴ
132
+ ヒメアカクロサギ
133
+ ダイサギ
134
+ ヨシゴイ
135
+ ツル
136
+ ツルモドキ
137
+ バン,鷭
138
+ アメリカオオバン
139
+ ノガン
140
+ キョウジョシギ
141
+ ハマシギ
142
+ アカアシシギ
143
+ オオハシシギ
144
+ ミヤコドリ
145
+ ペリカン
146
+ キングペンギン
147
+ アホウドリ,アルバトロス
148
+ コククジラ
149
+ シャチ,鯱
150
+ ジュゴン
151
+ アシカ
152
+ チワワ
153
+ 狆
154
+ マルチーズ
155
+ ペキニーズ
156
+ シーズー
157
+ キングチャールズスパニエル
158
+ パピヨン
159
+ トイテリア
160
+ ローデシアン・リッジバック
161
+ アフガンハウンド
162
+ バセットハウンド
163
+ ビーグル
164
+ ブラッドハウンド
165
+ ブルーティッククーンハウンド
166
+ ブラック・アンド・タン・クーンハウンド
167
+ ツリーイング・ウォーカー・クーンハウンド
168
+ イングリッシュ・フォックスハウンド
169
+ レッドボーン・クーンハウンド
170
+ ボルゾイ
171
+ アイリッシュウルフハウンド
172
+ イタリアン・グレーハウンド
173
+ ウィペット
174
+ イビサン・ハウンド
175
+ ノルウェージャン・エルクハウンド
176
+ オッターハウンド
177
+ サルーキ
178
+ スコティッシュ・ディアハウンド
179
+ ワイマラナー
180
+ スタッフォードシャーブルテリア
181
+