immanuelpeter commited on
Commit
c0ea94b
·
verified ·
1 Parent(s): 8520180

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. LICENSE +245 -0
  2. NOTICE +9 -0
  3. README.md +18 -0
  4. config.json +35 -0
  5. export_manifest.json +6 -0
  6. model.safetensors +3 -0
  7. modeling_hy4.py +164 -0
LICENSE ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Tencent Hy License, Version 1.0
2
+
3
+ This License is derived from the Apache License, Version 2.0
4
+ (http://www.apache.org/licenses/LICENSE-2.0), with modifications, mainly
5
+ the additional commercial terms for large Model-as-a-Service ("MaaS")
6
+ businesses in Section 10. This License is not the Apache License,
7
+ Version 2.0, and is not endorsed by or affiliated with the Apache
8
+ Software Foundation.
9
+
10
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11
+
12
+ 1. Definitions.
13
+
14
+ "License" shall mean the terms and conditions for use, reproduction,
15
+ and distribution as defined by Sections 1 through 10 of this document.
16
+
17
+ "Licensor" shall mean the copyright owner or entity authorized by
18
+ the copyright owner that is granting the License.
19
+
20
+ "Legal Entity" shall mean the union of the acting entity and all
21
+ other entities that control, are controlled by, or are under common
22
+ control with that entity. For the purposes of this definition,
23
+ "control" means (i) the power, direct or indirect, to cause the
24
+ direction or management of such entity, whether by contract or
25
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
+ outstanding shares, or (iii) beneficial ownership of such entity.
27
+
28
+ "You" (or "Your") shall mean an individual or Legal Entity
29
+ exercising permissions granted by this License.
30
+
31
+ "Source" form shall mean the preferred form for making modifications,
32
+ including but not limited to software source code, documentation
33
+ source, and configuration files.
34
+
35
+ "Object" form shall mean any form resulting from mechanical
36
+ transformation or translation of a Source form, including but
37
+ not limited to compiled object code, generated documentation,
38
+ and conversions to other media types.
39
+
40
+ "Work" shall mean the work of authorship, whether in Source or
41
+ Object form, made available under the License, as indicated by a
42
+ copyright notice that is included in or attached to the work
43
+ (an example is provided in the Appendix below). For the avoidance
44
+ of doubt, the Work includes the model weights, parameters,
45
+ configuration files, inference and training code, and documentation
46
+ made available by Licensor under this License.
47
+
48
+ "Derivative Works" shall mean any work, whether in Source or Object
49
+ form, that is based on (or derived from) the Work and for which the
50
+ editorial revisions, annotations, elaborations, or other modifications
51
+ represent, as a whole, an original work of authorship. For the purposes
52
+ of this License, Derivative Works shall not include works that remain
53
+ separable from, or merely link (or bind by name) to the interfaces of,
54
+ the Work and Derivative Works thereof. For the avoidance of doubt,
55
+ Derivative Works include any fine-tuned, quantized, distilled, merged,
56
+ pruned, or otherwise modified versions of the model weights.
57
+
58
+ "Contribution" shall mean any work of authorship, including
59
+ the original version of the Work and any modifications or additions
60
+ to that Work or Derivative Works thereof, that is intentionally
61
+ submitted to Licensor for inclusion in the Work by the copyright owner
62
+ or by an individual or Legal Entity authorized to submit on behalf of
63
+ the copyright owner. For the purposes of this definition, "submitted"
64
+ means any form of electronic, verbal, or written communication sent
65
+ to the Licensor or its representatives, including but not limited to
66
+ communication on electronic mailing lists, source code control systems,
67
+ and issue tracking systems that are managed by, or on behalf of, the
68
+ Licensor for the purpose of discussing and improving the Work, but
69
+ excluding communication that is conspicuously marked or otherwise
70
+ designated in writing by the copyright owner as "Not a Contribution."
71
+
72
+ "Contributor" shall mean Licensor and any individual or Legal Entity
73
+ on behalf of whom a Contribution has been received by Licensor and
74
+ subsequently incorporated within the Work.
75
+
76
+ 2. Grant of Copyright License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ copyright license to reproduce, prepare Derivative Works of,
80
+ publicly display, publicly perform, sublicense, and distribute the
81
+ Work and such Derivative Works in Source or Object form.
82
+
83
+ 3. Grant of Patent License. Subject to the terms and conditions of
84
+ this License, each Contributor hereby grants to You a perpetual,
85
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
86
+ (except as stated in this section) patent license to make, have made,
87
+ use, offer to sell, sell, import, and otherwise transfer the Work,
88
+ where such license applies only to those patent claims licensable
89
+ by such Contributor that are necessarily infringed by their
90
+ Contribution(s) alone or by combination of their Contribution(s)
91
+ with the Work to which such Contribution(s) was submitted. If You
92
+ institute patent litigation against any entity (including a
93
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
94
+ or a Contribution incorporated within the Work constitutes direct
95
+ or contributory patent infringement, then any patent licenses
96
+ granted to You under this License for that Work shall terminate
97
+ as of the date such litigation is filed.
98
+
99
+ 4. Redistribution. You may reproduce and distribute copies of the
100
+ Work or Derivative Works thereof in any medium, with or without
101
+ modifications, and in Source or Object form, provided that You
102
+ meet the following conditions:
103
+
104
+ (a) You must give any other recipients of the Work or
105
+ Derivative Works a copy of this License; and
106
+
107
+ (b) You must cause any modified files to carry prominent notices
108
+ stating that You changed the files; and
109
+
110
+ (c) You must retain, in the Source form of any Derivative Works
111
+ that You distribute, all copyright, patent, trademark, and
112
+ attribution notices from the Source form of the Work,
113
+ excluding those notices that do not pertain to any part of
114
+ the Derivative Works; and
115
+
116
+ (d) If the Work includes a "NOTICE" text file as part of its
117
+ distribution, then any Derivative Works that You distribute must
118
+ include a readable copy of the attribution notices contained
119
+ within such NOTICE file, excluding those notices that do not
120
+ pertain to any part of the Derivative Works, in at least one
121
+ of the following places: within a NOTICE text file distributed
122
+ as part of the Derivative Works; within the Source form or
123
+ documentation, if provided along with the Derivative Works; or,
124
+ within a display generated by the Derivative Works, if and
125
+ wherever such third-party notices normally appear. The contents
126
+ of the NOTICE file are for informational purposes only and
127
+ do not modify the License. You may add Your own attribution
128
+ notices within Derivative Works that You distribute, alongside
129
+ or as an addendum to the NOTICE text from the Work, provided
130
+ that such additional attribution notices cannot be construed
131
+ as modifying the License.
132
+
133
+ You may add Your own copyright statement to Your modifications and
134
+ may provide additional or different license terms and conditions
135
+ for use, reproduction, or distribution of Your modifications, or
136
+ for any such Derivative Works as a whole, provided Your use,
137
+ reproduction, and distribution of the Work otherwise complies with
138
+ the conditions stated in this License. Notwithstanding the
139
+ foregoing, any license terms You provide for the Work or any
140
+ Derivative Works must not remove, limit, or conflict with Section 10,
141
+ and Section 10 shall continue to apply to every recipient of the
142
+ Work or any Derivative Works.
143
+
144
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
145
+ any Contribution intentionally submitted for inclusion in the Work
146
+ by You to the Licensor shall be under the terms and conditions of
147
+ this License, without any additional terms or conditions.
148
+ Notwithstanding the above, nothing herein shall supersede or modify
149
+ the terms of any separate license agreement you may have executed
150
+ with Licensor regarding such Contributions.
151
+
152
+ 6. Trademarks. This License does not grant permission to use the trade
153
+ names, trademarks, service marks, or product names of the Licensor,
154
+ except as required for reasonable and customary use in describing the
155
+ origin of the Work and reproducing the content of the NOTICE file.
156
+
157
+ 7. Disclaimer of Warranty. Unless required by applicable law or
158
+ agreed to in writing, Licensor provides the Work (and each
159
+ Contributor provides its Contributions) on an "AS IS" BASIS,
160
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
161
+ implied, including, without limitation, any warranties or conditions
162
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
163
+ PARTICULAR PURPOSE. You are solely responsible for determining the
164
+ appropriateness of using or redistributing the Work and assume any
165
+ risks associated with Your exercise of permissions under this License.
166
+
167
+ 8. Limitation of Liability. In no event and under no legal theory,
168
+ whether in tort (including negligence), contract, or otherwise,
169
+ unless required by applicable law (such as deliberate and grossly
170
+ negligent acts) or agreed to in writing, shall any Contributor be
171
+ liable to You for damages, including any direct, indirect, special,
172
+ incidental, or consequential damages of any character arising as a
173
+ result of this License or out of the use or inability to use the
174
+ Work (including but not limited to damages for loss of goodwill,
175
+ work stoppage, computer failure or malfunction, or any and all
176
+ other commercial damages or losses), even if such Contributor
177
+ has been advised of the possibility of such damages.
178
+
179
+ 9. Accepting Warranty or Additional Liability. While redistributing
180
+ the Work or Derivative Works thereof, You may choose to offer,
181
+ and charge a fee for, acceptance of support, warranty, indemnity,
182
+ or other liability obligations and/or rights consistent with this
183
+ License. However, in accepting such obligations, You may act only
184
+ on Your own behalf and on Your sole responsibility, not on behalf
185
+ of any other Contributor, and only if You agree to indemnify,
186
+ defend, and hold each Contributor harmless for any liability
187
+ incurred by, or claims asserted against, such Contributor by reason
188
+ of your accepting any such warranty or additional liability.
189
+
190
+ 10. Additional Commercial Terms.
191
+
192
+ 10.1 MaaS. "MaaS" means giving third parties remote access to model
193
+ inference or fine-tuning (e.g., via API), allowing them to
194
+ submit inputs or specify parameters or training data. This
195
+ excludes (i) end-user products with model capabilities confined
196
+ to specific features or workflows, without general-purpose
197
+ model access, or (ii) merely relaying requests to an
198
+ independently operated third-party model service.
199
+
200
+ 10.2 Separate License Required. Notwithstanding Sections 2 and 3,
201
+ and except as provided in Section 10.3, if You operate a MaaS
202
+ business, You must obtain a separate written license to use the
203
+ Work or any Derivative Works from Licensor (including by email),
204
+ in either of the following cases:
205
+
206
+ (a) if Your aggregate worldwide gross revenue exceeds
207
+ US$50 million (or the equivalent in other currencies) in
208
+ any consecutive 12-month period, whether or not such
209
+ revenue is derived from the Work or any Derivative Works,
210
+ before using (or continuing to use) the Work or any
211
+ Derivative Works; or
212
+
213
+ (b) before using the Work or any Derivative Works in or for any
214
+ product or service provided by You that has more than
215
+ 100 million monthly active users in any calendar month.
216
+
217
+ 10.3 Internal Use. Section 10.2 does not apply to Your use of the
218
+ Work or any Derivative Works solely for internal purposes,
219
+ provided that neither the Work, any Derivative Works, nor their
220
+ outputs are made available to third parties.
221
+
222
+ 10.4 Contact. For licensing requests or questions, please contact
223
+ hy_partners@tencent.com.
224
+
225
+ END OF TERMS AND CONDITIONS
226
+
227
+ APPENDIX: How to apply the Tencent Hy License to your work.
228
+
229
+ To apply this License to a Derivative Work, attach the following
230
+ notice, with the fields enclosed by brackets "[]" replaced with your
231
+ own identifying information. (Don't include the brackets!)
232
+
233
+ Copyright [yyyy] [name of copyright owner]
234
+
235
+ Licensed under the Tencent Hy License, Version 1.0 (the "License"),
236
+ which is based on the Apache License, Version 2.0, with additional
237
+ commercial terms. You may not use this file except in compliance
238
+ with the License. You may obtain a copy of the License in the
239
+ LICENSE file distributed with this work.
240
+
241
+ Unless required by applicable law or agreed to in writing, software
242
+ distributed under the License is distributed on an "AS IS" BASIS,
243
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
244
+ implied. See the License for the specific language governing
245
+ permissions and limitations under the License.
NOTICE ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Hy4 Vision
2
+ This release includes vision weights from Tencent Hy4.
3
+ Source: https://huggingface.co/tencent/Hy4/tree/c10c0de5b6f850703fb0a90e65d1c32b558b9167
4
+ The weights are redistributed under the Tencent Hy License, Version 1.0.
5
+
6
+ Changes: extracted the Tower and Projector from the parent checkpoint,
7
+ removed the vit. prefix from tensor names, and added standalone modeling
8
+ code. The benchmark uses 512-pixel RGB crops and omits image_newline tokens
9
+ from the projected features. The original tensor values are preserved.
README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: tencent-hy-license
4
+ license_link: LICENSE
5
+ base_model: tencent/Hy4
6
+ pipeline_tag: image-feature-extraction
7
+ library_name: transformers
8
+ ---
9
+
10
+ # Hy4 Vision
11
+
12
+ The standalone BF16 Tower and Projector extracted from [Tencent Hy4](https://huggingface.co/tencent/Hy4/tree/c10c0de5b6f850703fb0a90e65d1c32b558b9167) for frozen-feature probing. The release preserves the 649 vision tensors and removes the language model.
13
+
14
+ The benchmark uses 512×512 RGB crops normalized with mean and standard deviation 0.5. The 40-block Tower produces a 32×32 raster grid at width 1536. The Projector produces 16×16 grids at width 6144. The `merged` Stage groups RMS-normalized 2×2 neighborhoods. The `projected` Stage emits the convolution output without row delimiters.
15
+
16
+ Load with `AutoModel.from_pretrained("immanuelpeter/Hy4-Vision", trust_remote_code=True)`. Pass a batch of normalized RGB tensors and the desired one-indexed block depths. The model returns the requested Tower outputs, merged features, and projected features.
17
+
18
+ The [Tencent Hy License 1.0](LICENSE) governs the weights. See [NOTICE](NOTICE) for attribution and changes.
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "transformers_version": "5.17.0",
3
+ "architectures": [
4
+ "Hy4VisionModel"
5
+ ],
6
+ "output_hidden_states": false,
7
+ "return_dict": true,
8
+ "dtype": "bfloat16",
9
+ "chunk_size_feed_forward": 0,
10
+ "is_encoder_decoder": false,
11
+ "id2label": {
12
+ "0": "LABEL_0",
13
+ "1": "LABEL_1"
14
+ },
15
+ "label2id": {
16
+ "LABEL_0": 0,
17
+ "LABEL_1": 1
18
+ },
19
+ "problem_type": null,
20
+ "_name_or_path": "",
21
+ "auto_map": {
22
+ "AutoConfig": "modeling_hy4.Hy4VisionConfig",
23
+ "AutoModel": "modeling_hy4.Hy4VisionModel"
24
+ },
25
+ "hidden_size": 1536,
26
+ "intermediate_size": 6144,
27
+ "num_hidden_layers": 40,
28
+ "num_attention_heads": 16,
29
+ "out_hidden_size": 6144,
30
+ "patch_size": 16,
31
+ "max_image_size": 2048,
32
+ "rms_norm_eps": 1e-05,
33
+ "model_type": "vtb_hy4",
34
+ "output_attentions": false
35
+ }
export_manifest.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "source_repo": "tencent/Hy4",
3
+ "source_revision": "c10c0de5b6f850703fb0a90e65d1c32b558b9167",
4
+ "tensors": 649,
5
+ "bytes": 2470253568
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa4441199ff0fc2eeb94c4148388d7093a52095e3d3ce16e2d2d223cabccc7f8
3
+ size 2470323552
modeling_hy4.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone Tencent Hy4 Tower and Projector with checkpoint-native names."""
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+ from transformers import PretrainedConfig, PreTrainedModel
7
+
8
+
9
+ class Hy4VisionConfig(PretrainedConfig):
10
+ model_type = "vtb_hy4"
11
+
12
+ def __init__(
13
+ self,
14
+ hidden_size=1536,
15
+ intermediate_size=6144,
16
+ num_hidden_layers=40,
17
+ num_attention_heads=16,
18
+ out_hidden_size=6144,
19
+ patch_size=16,
20
+ max_image_size=2048,
21
+ rms_norm_eps=1e-5,
22
+ **kwargs,
23
+ ):
24
+ super().__init__(**kwargs)
25
+ self.hidden_size = hidden_size
26
+ self.intermediate_size = intermediate_size
27
+ self.num_hidden_layers = num_hidden_layers
28
+ self.num_attention_heads = num_attention_heads
29
+ self.out_hidden_size = out_hidden_size
30
+ self.patch_size = patch_size
31
+ self.max_image_size = max_image_size
32
+ self.rms_norm_eps = rms_norm_eps
33
+
34
+
35
+ class PatchEmbedding(nn.Module):
36
+ def __init__(self, config):
37
+ super().__init__()
38
+ patch = config.patch_size
39
+ self.edge = config.max_image_size // patch
40
+ self.patch_embedding = nn.Conv2d(3, config.hidden_size, patch, stride=patch)
41
+ self.position_embedding = nn.Embedding(self.edge**2 + 1, config.hidden_size)
42
+
43
+ def forward(self, pixels):
44
+ height, width = pixels.shape[-2:]
45
+ patch = self.patch_embedding.kernel_size[0]
46
+ rows, cols = height // patch, width // patch
47
+ patches = F.unfold(pixels, patch, stride=patch).transpose(1, 2)
48
+ embedded = self.patch_embedding(patches.reshape(-1, 3, patch, patch))
49
+ tokens = embedded.reshape(pixels.shape[0], rows * cols, -1)
50
+ positions = self.position_embedding.weight[1:].T.reshape(
51
+ 1, -1, self.edge, self.edge
52
+ )
53
+ positions = F.interpolate(
54
+ positions.float(),
55
+ scale_factor=((rows + 0.1) / self.edge, (cols + 0.1) / self.edge),
56
+ mode="bilinear",
57
+ align_corners=False,
58
+ )
59
+ return tokens + positions.flatten(2).transpose(1, 2).to(tokens.dtype)
60
+
61
+
62
+ class Attention(nn.Module):
63
+ def __init__(self, config):
64
+ super().__init__()
65
+ width = config.hidden_size
66
+ self.heads = config.num_attention_heads
67
+ self.q_proj = nn.Linear(width, width)
68
+ self.k_proj = nn.Linear(width, width)
69
+ self.v_proj = nn.Linear(width, width)
70
+ self.o_proj = nn.Linear(width, width)
71
+
72
+ def forward(self, tokens):
73
+ batch, length, width = tokens.shape
74
+ q, k, v = [
75
+ proj(tokens).view(batch, length, self.heads, -1).transpose(1, 2)
76
+ for proj in (self.q_proj, self.k_proj, self.v_proj)
77
+ ]
78
+ attended = F.scaled_dot_product_attention(q, k, v)
79
+ return self.o_proj(attended.transpose(1, 2).reshape(batch, length, width))
80
+
81
+
82
+ class MLP(nn.Module):
83
+ def __init__(self, config):
84
+ super().__init__()
85
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size)
86
+ self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size)
87
+
88
+ def forward(self, tokens):
89
+ return self.dense_4h_to_h(F.gelu(self.dense_h_to_4h(tokens)))
90
+
91
+
92
+ class Block(nn.Module):
93
+ def __init__(self, config):
94
+ super().__init__()
95
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps)
96
+ self.self_attn = Attention(config)
97
+ self.post_attention_layernorm = nn.LayerNorm(
98
+ config.hidden_size, eps=config.rms_norm_eps
99
+ )
100
+ self.mlp = MLP(config)
101
+
102
+ def forward(self, tokens):
103
+ tokens = tokens + self.self_attn(self.input_layernorm(tokens))
104
+ return tokens + self.mlp(self.post_attention_layernorm(tokens))
105
+
106
+
107
+ class RMSNorm(nn.RMSNorm):
108
+ def forward(self, tokens):
109
+ values = tokens.float()
110
+ normalized = values * torch.rsqrt(
111
+ values.square().mean(-1, keepdim=True) + self.eps
112
+ )
113
+ return self.weight * normalized.to(tokens.dtype)
114
+
115
+
116
+ class Projector(nn.Module):
117
+ def __init__(self, config):
118
+ super().__init__()
119
+ width = config.hidden_size
120
+ self.norm = RMSNorm(width, eps=config.rms_norm_eps)
121
+ self.proj = nn.Sequential(
122
+ nn.Conv2d(width, 4 * width, 2, stride=2),
123
+ nn.GELU(),
124
+ nn.Conv2d(4 * width, config.out_hidden_size, 1),
125
+ )
126
+ self.image_newline = nn.Parameter(torch.zeros(config.out_hidden_size))
127
+
128
+ def forward(self, tokens, rows, cols):
129
+ batch, _, width = tokens.shape
130
+ grid = self.norm(tokens).reshape(batch, rows, cols, width)
131
+ merged = (
132
+ grid.reshape(batch, rows // 2, 2, cols // 2, 2, width)
133
+ .permute(0, 1, 3, 2, 4, 5)
134
+ .reshape(batch, rows * cols // 4, 4 * width)
135
+ )
136
+ projected = self.proj(grid.permute(0, 3, 1, 2)).flatten(2).transpose(1, 2)
137
+ return merged, projected
138
+
139
+
140
+ class Hy4VisionModel(PreTrainedModel):
141
+ config_class = Hy4VisionConfig
142
+ main_input_name = "pixel_values"
143
+
144
+ def __init__(self, config):
145
+ super().__init__(config)
146
+ self.embeddings = PatchEmbedding(config)
147
+ self.layers = nn.ModuleList(
148
+ Block(config) for _ in range(config.num_hidden_layers)
149
+ )
150
+ self.perceive = Projector(config)
151
+ self.post_init()
152
+
153
+ def forward(self, pixel_values, depths=()):
154
+ tokens = self.embeddings(pixel_values)
155
+ hidden = {}
156
+ for depth, layer in enumerate(self.layers, 1):
157
+ tokens = layer(tokens)
158
+ if depth in depths:
159
+ hidden[depth] = tokens
160
+ rows, cols = (
161
+ side // self.config.patch_size for side in pixel_values.shape[-2:]
162
+ )
163
+ merged, projected = self.perceive(tokens, rows, cols)
164
+ return hidden, merged, projected