Prompt48 commited on
Commit
f0e1b30
·
verified ·
1 Parent(s): adadcb0

Upload edit\Qwen3-TTS-test\.venv\Lib\site-packages\transformers\models\hgnet_v2\modeling_hgnet_v2.py with huggingface_hub

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//hgnet_v2//modeling_hgnet_v2.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/hgnet_v2/modular_hgnet_v2.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_hgnet_v2.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+
23
+ from typing import Optional
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from torch import Tensor, nn
28
+
29
+ from ...activations import ACT2FN
30
+ from ...modeling_outputs import BackboneOutput, BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
31
+ from ...modeling_utils import PreTrainedModel
32
+ from ...utils import auto_docstring
33
+ from ...utils.backbone_utils import BackboneMixin
34
+ from .configuration_hgnet_v2 import HGNetV2Config
35
+
36
+
37
+ # General docstring
38
+
39
+
40
+ @auto_docstring
41
+ class HGNetV2PreTrainedModel(PreTrainedModel):
42
+ config: HGNetV2Config
43
+ base_model_prefix = "hgnetv2"
44
+ main_input_name = "pixel_values"
45
+ _no_split_modules = ["HGNetV2BasicLayer"]
46
+
47
+
48
+ class HGNetV2LearnableAffineBlock(nn.Module):
49
+ def __init__(self, scale_value: float = 1.0, bias_value: float = 0.0):
50
+ super().__init__()
51
+ self.scale = nn.Parameter(torch.tensor([scale_value]), requires_grad=True)
52
+ self.bias = nn.Parameter(torch.tensor([bias_value]), requires_grad=True)
53
+
54
+ def forward(self, hidden_state: Tensor) -> Tensor:
55
+ hidden_state = self.scale * hidden_state + self.bias
56
+ return hidden_state
57
+
58
+
59
+ class HGNetV2ConvLayer(nn.Module):
60
+ def __init__(
61
+ self,
62
+ in_channels: int,
63
+ out_channels: int,
64
+ kernel_size: int,
65
+ stride: int = 1,
66
+ groups: int = 1,
67
+ activation: str = "relu",
68
+ use_learnable_affine_block: bool = False,
69
+ ):
70
+ super().__init__()
71
+ self.convolution = nn.Conv2d(
72
+ in_channels,
73
+ out_channels,
74
+ kernel_size=kernel_size,
75
+ stride=stride,
76
+ groups=groups,
77
+ padding=(kernel_size - 1) // 2,
78
+ bias=False,
79
+ )
80
+ self.normalization = nn.BatchNorm2d(out_channels)
81
+ self.activation = ACT2FN[activation] if activation is not None else nn.Identity()
82
+ if activation and use_learnable_affine_block:
83
+ self.lab = HGNetV2LearnableAffineBlock()
84
+ else:
85
+ self.lab = nn.Identity()
86
+
87
+ def forward(self, input: Tensor) -> Tensor:
88
+ hidden_state = self.convolution(input)
89
+ hidden_state = self.normalization(hidden_state)
90
+ hidden_state = self.activation(hidden_state)
91
+ hidden_state = self.lab(hidden_state)
92
+ return hidden_state
93
+
94
+
95
+ class HGNetV2ConvLayerLight(nn.Module):
96
+ def __init__(
97
+ self, in_channels: int, out_channels: int, kernel_size: int, use_learnable_affine_block: bool = False
98
+ ):
99
+ super().__init__()
100
+ self.conv1 = HGNetV2ConvLayer(
101
+ in_channels,
102
+ out_channels,
103
+ kernel_size=1,
104
+ activation=None,
105
+ use_learnable_affine_block=use_learnable_affine_block,
106
+ )
107
+ self.conv2 = HGNetV2ConvLayer(
108
+ out_channels,
109
+ out_channels,
110
+ kernel_size=kernel_size,
111
+ groups=out_channels,
112
+ use_learnable_affine_block=use_learnable_affine_block,
113
+ )
114
+
115
+ def forward(self, hidden_state: Tensor) -> Tensor:
116
+ hidden_state = self.conv1(hidden_state)
117
+ hidden_state = self.conv2(hidden_state)
118
+ return hidden_state
119
+
120
+
121
+ class HGNetV2Embeddings(nn.Module):
122
+ def __init__(self, config: HGNetV2Config):
123
+ super().__init__()
124
+
125
+ self.stem1 = HGNetV2ConvLayer(
126
+ config.stem_channels[0],
127
+ config.stem_channels[1],
128
+ kernel_size=3,
129
+ stride=2,
130
+ activation=config.hidden_act,
131
+ use_learnable_affine_block=config.use_learnable_affine_block,
132
+ )
133
+ self.stem2a = HGNetV2ConvLayer(
134
+ config.stem_channels[1],
135
+ config.stem_channels[1] // 2,
136
+ kernel_size=2,
137
+ stride=1,
138
+ activation=config.hidden_act,
139
+ use_learnable_affine_block=config.use_learnable_affine_block,
140
+ )
141
+ self.stem2b = HGNetV2ConvLayer(
142
+ config.stem_channels[1] // 2,
143
+ config.stem_channels[1],
144
+ kernel_size=2,
145
+ stride=1,
146
+ activation=config.hidden_act,
147
+ use_learnable_affine_block=config.use_learnable_affine_block,
148
+ )
149
+ self.stem3 = HGNetV2ConvLayer(
150
+ config.stem_channels[1] * 2,
151
+ config.stem_channels[1],
152
+ kernel_size=3,
153
+ stride=2,
154
+ activation=config.hidden_act,
155
+ use_learnable_affine_block=config.use_learnable_affine_block,
156
+ )
157
+ self.stem4 = HGNetV2ConvLayer(
158
+ config.stem_channels[1],
159
+ config.stem_channels[2],
160
+ kernel_size=1,
161
+ stride=1,
162
+ activation=config.hidden_act,
163
+ use_learnable_affine_block=config.use_learnable_affine_block,
164
+ )
165
+
166
+ self.pool = nn.MaxPool2d(kernel_size=2, stride=1, ceil_mode=True)
167
+ self.num_channels = config.num_channels
168
+
169
+ def forward(self, pixel_values: Tensor) -> Tensor:
170
+ num_channels = pixel_values.shape[1]
171
+ if num_channels != self.num_channels:
172
+ raise ValueError(
173
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
174
+ )
175
+ embedding = self.stem1(pixel_values)
176
+ embedding = F.pad(embedding, (0, 1, 0, 1))
177
+ emb_stem_2a = self.stem2a(embedding)
178
+ emb_stem_2a = F.pad(emb_stem_2a, (0, 1, 0, 1))
179
+ emb_stem_2a = self.stem2b(emb_stem_2a)
180
+ pooled_emb = self.pool(embedding)
181
+ embedding = torch.cat([pooled_emb, emb_stem_2a], dim=1)
182
+ embedding = self.stem3(embedding)
183
+ embedding = self.stem4(embedding)
184
+ return embedding
185
+
186
+
187
+ class HGNetV2BasicLayer(nn.Module):
188
+ def __init__(
189
+ self,
190
+ in_channels: int,
191
+ middle_channels: int,
192
+ out_channels: int,
193
+ layer_num: int,
194
+ kernel_size: int = 3,
195
+ residual: bool = False,
196
+ light_block: bool = False,
197
+ drop_path: float = 0.0,
198
+ use_learnable_affine_block: bool = False,
199
+ ):
200
+ super().__init__()
201
+ self.residual = residual
202
+
203
+ self.layers = nn.ModuleList()
204
+ for i in range(layer_num):
205
+ temp_in_channels = in_channels if i == 0 else middle_channels
206
+ if light_block:
207
+ block = HGNetV2ConvLayerLight(
208
+ in_channels=temp_in_channels,
209
+ out_channels=middle_channels,
210
+ kernel_size=kernel_size,
211
+ use_learnable_affine_block=use_learnable_affine_block,
212
+ )
213
+ else:
214
+ block = HGNetV2ConvLayer(
215
+ in_channels=temp_in_channels,
216
+ out_channels=middle_channels,
217
+ kernel_size=kernel_size,
218
+ use_learnable_affine_block=use_learnable_affine_block,
219
+ stride=1,
220
+ )
221
+ self.layers.append(block)
222
+
223
+ # feature aggregation
224
+ total_channels = in_channels + layer_num * middle_channels
225
+ aggregation_squeeze_conv = HGNetV2ConvLayer(
226
+ total_channels,
227
+ out_channels // 2,
228
+ kernel_size=1,
229
+ stride=1,
230
+ use_learnable_affine_block=use_learnable_affine_block,
231
+ )
232
+ aggregation_excitation_conv = HGNetV2ConvLayer(
233
+ out_channels // 2,
234
+ out_channels,
235
+ kernel_size=1,
236
+ stride=1,
237
+ use_learnable_affine_block=use_learnable_affine_block,
238
+ )
239
+ self.aggregation = nn.Sequential(
240
+ aggregation_squeeze_conv,
241
+ aggregation_excitation_conv,
242
+ )
243
+ self.drop_path = nn.Dropout(drop_path) if drop_path else nn.Identity()
244
+
245
+ def forward(self, hidden_state: Tensor) -> Tensor:
246
+ identity = hidden_state
247
+ output = [hidden_state]
248
+ for layer in self.layers:
249
+ hidden_state = layer(hidden_state)
250
+ output.append(hidden_state)
251
+ hidden_state = torch.cat(output, dim=1)
252
+ hidden_state = self.aggregation(hidden_state)
253
+ if self.residual:
254
+ hidden_state = self.drop_path(hidden_state) + identity
255
+ return hidden_state
256
+
257
+
258
+ class HGNetV2Stage(nn.Module):
259
+ def __init__(self, config: HGNetV2Config, stage_index: int, drop_path: float = 0.0):
260
+ super().__init__()
261
+ in_channels = config.stage_in_channels[stage_index]
262
+ mid_channels = config.stage_mid_channels[stage_index]
263
+ out_channels = config.stage_out_channels[stage_index]
264
+ num_blocks = config.stage_num_blocks[stage_index]
265
+ num_layers = config.stage_numb_of_layers[stage_index]
266
+ downsample = config.stage_downsample[stage_index]
267
+ light_block = config.stage_light_block[stage_index]
268
+ kernel_size = config.stage_kernel_size[stage_index]
269
+ use_learnable_affine_block = config.use_learnable_affine_block
270
+
271
+ if downsample:
272
+ self.downsample = HGNetV2ConvLayer(
273
+ in_channels, in_channels, kernel_size=3, stride=2, groups=in_channels, activation=None
274
+ )
275
+ else:
276
+ self.downsample = nn.Identity()
277
+
278
+ blocks_list = []
279
+ for i in range(num_blocks):
280
+ blocks_list.append(
281
+ HGNetV2BasicLayer(
282
+ in_channels if i == 0 else out_channels,
283
+ mid_channels,
284
+ out_channels,
285
+ num_layers,
286
+ residual=(i != 0),
287
+ kernel_size=kernel_size,
288
+ light_block=light_block,
289
+ drop_path=drop_path,
290
+ use_learnable_affine_block=use_learnable_affine_block,
291
+ )
292
+ )
293
+ self.blocks = nn.ModuleList(blocks_list)
294
+
295
+ def forward(self, hidden_state: Tensor) -> Tensor:
296
+ hidden_state = self.downsample(hidden_state)
297
+ for block in self.blocks:
298
+ hidden_state = block(hidden_state)
299
+ return hidden_state
300
+
301
+
302
+ class HGNetV2Encoder(nn.Module):
303
+ def __init__(self, config: HGNetV2Config):
304
+ super().__init__()
305
+ self.stages = nn.ModuleList([])
306
+ for stage_index in range(len(config.stage_in_channels)):
307
+ resnet_stage = HGNetV2Stage(config, stage_index)
308
+ self.stages.append(resnet_stage)
309
+
310
+ def forward(
311
+ self, hidden_state: Tensor, output_hidden_states: bool = False, return_dict: bool = True
312
+ ) -> BaseModelOutputWithNoAttention:
313
+ hidden_states = () if output_hidden_states else None
314
+
315
+ for stage in self.stages:
316
+ if output_hidden_states:
317
+ hidden_states = hidden_states + (hidden_state,)
318
+
319
+ hidden_state = stage(hidden_state)
320
+
321
+ if output_hidden_states:
322
+ hidden_states = hidden_states + (hidden_state,)
323
+
324
+ if not return_dict:
325
+ return tuple(v for v in [hidden_state, hidden_states] if v is not None)
326
+
327
+ return BaseModelOutputWithNoAttention(
328
+ last_hidden_state=hidden_state,
329
+ hidden_states=hidden_states,
330
+ )
331
+
332
+
333
+ class HGNetV2Backbone(HGNetV2PreTrainedModel, BackboneMixin):
334
+ has_attentions = False
335
+
336
+ def __init__(self, config: HGNetV2Config):
337
+ super().__init__(config)
338
+ super()._init_backbone(config)
339
+ self.depths = config.depths
340
+ self.num_features = [config.embedding_size] + config.hidden_sizes
341
+ self.embedder = HGNetV2Embeddings(config)
342
+ self.encoder = HGNetV2Encoder(config)
343
+
344
+ # initialize weights and apply final processing
345
+ self.post_init()
346
+
347
+ @auto_docstring
348
+ def forward(
349
+ self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
350
+ ) -> BackboneOutput:
351
+ r"""
352
+ Examples:
353
+
354
+ ```python
355
+ >>> from transformers import HGNetV2Config, HGNetV2Backbone
356
+ >>> import torch
357
+
358
+ >>> config = HGNetV2Config()
359
+ >>> model = HGNetV2Backbone(config)
360
+
361
+ >>> pixel_values = torch.randn(1, 3, 224, 224)
362
+
363
+ >>> with torch.no_grad():
364
+ ... outputs = model(pixel_values)
365
+
366
+ >>> feature_maps = outputs.feature_maps
367
+ >>> list(feature_maps[-1].shape)
368
+ [1, 2048, 7, 7]
369
+ ```"""
370
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
371
+ output_hidden_states = (
372
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
373
+ )
374
+
375
+ embedding_output = self.embedder(pixel_values)
376
+
377
+ outputs = self.encoder(embedding_output, output_hidden_states=True, return_dict=True)
378
+
379
+ hidden_states = outputs.hidden_states
380
+
381
+ feature_maps = ()
382
+ for idx, stage in enumerate(self.stage_names):
383
+ if stage in self.out_features:
384
+ feature_maps += (hidden_states[idx],)
385
+
386
+ if not return_dict:
387
+ output = (feature_maps,)
388
+ if output_hidden_states:
389
+ output += (outputs.hidden_states,)
390
+ return output
391
+
392
+ return BackboneOutput(
393
+ feature_maps=feature_maps,
394
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
395
+ attentions=None,
396
+ )
397
+
398
+
399
+ @auto_docstring(
400
+ custom_intro="""
401
+ HGNetV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
402
+ ImageNet.
403
+ """
404
+ )
405
+ class HGNetV2ForImageClassification(HGNetV2PreTrainedModel):
406
+ def __init__(self, config: HGNetV2Config):
407
+ super().__init__(config)
408
+ self.num_labels = config.num_labels
409
+ self.embedder = HGNetV2Embeddings(config)
410
+ self.encoder = HGNetV2Encoder(config)
411
+ self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
412
+ self.flatten = nn.Flatten()
413
+ self.fc = nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
414
+
415
+ # classification head
416
+ self.classifier = nn.ModuleList([self.avg_pool, self.flatten])
417
+
418
+ # initialize weights and apply final processing
419
+ self.post_init()
420
+
421
+ @auto_docstring
422
+ def forward(
423
+ self,
424
+ pixel_values: Optional[torch.FloatTensor] = None,
425
+ labels: Optional[torch.LongTensor] = None,
426
+ output_hidden_states: Optional[bool] = None,
427
+ return_dict: Optional[bool] = None,
428
+ ) -> ImageClassifierOutputWithNoAttention:
429
+ r"""
430
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
431
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
432
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
433
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
434
+
435
+ Examples:
436
+ ```python
437
+ >>> import torch
438
+ >>> import requests
439
+ >>> from transformers import HGNetV2ForImageClassification, AutoImageProcessor
440
+ >>> from PIL import Image
441
+
442
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
443
+ >>> image = Image.open(requests.get(url, stream=True).raw)
444
+
445
+ >>> model = HGNetV2ForImageClassification.from_pretrained("ustc-community/hgnet-v2")
446
+ >>> processor = AutoImageProcessor.from_pretrained("ustc-community/hgnet-v2")
447
+
448
+ >>> inputs = processor(images=image, return_tensors="pt")
449
+ >>> with torch.no_grad():
450
+ ... outputs = model(**inputs)
451
+ >>> outputs.logits.shape
452
+ torch.Size([1, 2])
453
+ ```"""
454
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
455
+ output_hidden_states = (
456
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
457
+ )
458
+ embedding_output = self.embedder(pixel_values)
459
+ outputs = self.encoder(embedding_output, output_hidden_states=output_hidden_states, return_dict=return_dict)
460
+ last_hidden_state = outputs[0]
461
+ for layer in self.classifier:
462
+ last_hidden_state = layer(last_hidden_state)
463
+ logits = self.fc(last_hidden_state)
464
+ loss = None
465
+
466
+ if labels is not None:
467
+ loss = self.loss_function(labels, logits, self.config)
468
+
469
+ if not return_dict:
470
+ output = (logits,) + outputs[2:]
471
+ return (loss,) + output if loss is not None else output
472
+
473
+ return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
474
+
475
+
476
+ __all__ = ["HGNetV2Backbone", "HGNetV2PreTrainedModel", "HGNetV2ForImageClassification"]