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

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//hgnet_v2//modular_hgnet_v2.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ from typing import Optional
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+ from torch import Tensor, nn
22
+
23
+ from ...configuration_utils import PretrainedConfig
24
+ from ...modeling_outputs import (
25
+ BackboneOutput,
26
+ BaseModelOutputWithNoAttention,
27
+ ImageClassifierOutputWithNoAttention,
28
+ )
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import (
31
+ auto_docstring,
32
+ )
33
+ from ...utils.backbone_utils import BackboneConfigMixin, BackboneMixin, get_aligned_output_features_output_indices
34
+ from ..rt_detr.modeling_rt_detr_resnet import RTDetrResNetConvLayer
35
+
36
+
37
+ # TODO: Modular conversion for resnet must be fixed as
38
+ # it provides incorrect import for configuration like resnet_resnet
39
+ class HGNetV2Config(BackboneConfigMixin, PretrainedConfig):
40
+ """
41
+ This is the configuration class to store the configuration of a [`HGNetV2Backbone`]. It is used to instantiate a HGNet-V2
42
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
43
+ defaults will yield a similar configuration to that of D-FINE-X-COCO B4 "[ustc-community/dfine_x_coco"](https://huggingface.co/ustc-community/dfine_x_coco").
44
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
45
+ documentation from [`PretrainedConfig`] for more information.
46
+
47
+ Args:
48
+ num_channels (`int`, *optional*, defaults to 3):
49
+ The number of input channels.
50
+ embedding_size (`int`, *optional*, defaults to 64):
51
+ Dimensionality (hidden size) for the embedding layer.
52
+ depths (`list[int]`, *optional*, defaults to `[3, 4, 6, 3]`):
53
+ Depth (number of layers) for each stage.
54
+ hidden_sizes (`list[int]`, *optional*, defaults to `[256, 512, 1024, 2048]`):
55
+ Dimensionality (hidden size) at each stage.
56
+ hidden_act (`str`, *optional*, defaults to `"relu"`):
57
+ The non-linear activation function in each block. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"`
58
+ are supported.
59
+ out_features (`list[str]`, *optional*):
60
+ If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
61
+ (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
62
+ corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
63
+ same order as defined in the `stage_names` attribute.
64
+ out_indices (`list[int]`, *optional*):
65
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
66
+ many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
67
+ If unset and `out_features` is unset, will default to the last stage. Must be in the
68
+ same order as defined in the `stage_names` attribute.
69
+ stem_channels (`list[int]`, *optional*, defaults to `[3, 32, 48]`):
70
+ Channel dimensions for the stem layers:
71
+ - First number (3) is input image channels
72
+ - Second number (32) is intermediate stem channels
73
+ - Third number (48) is output stem channels
74
+ stage_in_channels (`list[int]`, *optional*, defaults to `[48, 128, 512, 1024]`):
75
+ Input channel dimensions for each stage of the backbone.
76
+ This defines how many channels the input to each stage will have.
77
+ stage_mid_channels (`list[int]`, *optional*, defaults to `[48, 96, 192, 384]`):
78
+ Mid-channel dimensions for each stage of the backbone.
79
+ This defines the number of channels used in the intermediate layers of each stage.
80
+ stage_out_channels (`list[int]`, *optional*, defaults to `[128, 512, 1024, 2048]`):
81
+ Output channel dimensions for each stage of the backbone.
82
+ This defines how many channels the output of each stage will have.
83
+ stage_num_blocks (`list[int]`, *optional*, defaults to `[1, 1, 3, 1]`):
84
+ Number of blocks to be used in each stage of the backbone.
85
+ This controls the depth of each stage by specifying how many convolutional blocks to stack.
86
+ stage_downsample (`list[bool]`, *optional*, defaults to `[False, True, True, True]`):
87
+ Indicates whether to downsample the feature maps at each stage.
88
+ If `True`, the spatial dimensions of the feature maps will be reduced.
89
+ stage_light_block (`list[bool]`, *optional*, defaults to `[False, False, True, True]`):
90
+ Indicates whether to use light blocks in each stage.
91
+ Light blocks are a variant of convolutional blocks that may have fewer parameters.
92
+ stage_kernel_size (`list[int]`, *optional*, defaults to `[3, 3, 5, 5]`):
93
+ Kernel sizes for the convolutional layers in each stage.
94
+ stage_numb_of_layers (`list[int]`, *optional*, defaults to `[6, 6, 6, 6]`):
95
+ Number of layers to be used in each block of the stage.
96
+ use_learnable_affine_block (`bool`, *optional*, defaults to `False`):
97
+ Whether to use Learnable Affine Blocks (LAB) in the network.
98
+ LAB adds learnable scale and bias parameters after certain operations.
99
+ initializer_range (`float`, *optional*, defaults to 0.02):
100
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
101
+ """
102
+
103
+ model_type = "hgnet_v2"
104
+
105
+ def __init__(
106
+ self,
107
+ num_channels=3,
108
+ embedding_size=64,
109
+ depths=[3, 4, 6, 3],
110
+ hidden_sizes=[256, 512, 1024, 2048],
111
+ hidden_act="relu",
112
+ out_features=None,
113
+ out_indices=None,
114
+ stem_channels=[3, 32, 48],
115
+ stage_in_channels=[48, 128, 512, 1024],
116
+ stage_mid_channels=[48, 96, 192, 384],
117
+ stage_out_channels=[128, 512, 1024, 2048],
118
+ stage_num_blocks=[1, 1, 3, 1],
119
+ stage_downsample=[False, True, True, True],
120
+ stage_light_block=[False, False, True, True],
121
+ stage_kernel_size=[3, 3, 5, 5],
122
+ stage_numb_of_layers=[6, 6, 6, 6],
123
+ use_learnable_affine_block=False,
124
+ initializer_range=0.02,
125
+ **kwargs,
126
+ ):
127
+ super().__init__(**kwargs)
128
+ self.num_channels = num_channels
129
+ self.embedding_size = embedding_size
130
+ self.depths = depths
131
+ self.hidden_sizes = hidden_sizes
132
+ self.hidden_act = hidden_act
133
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
134
+ self._out_features, self._out_indices = get_aligned_output_features_output_indices(
135
+ out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
136
+ )
137
+ self.stem_channels = stem_channels
138
+ self.stage_in_channels = stage_in_channels
139
+ self.stage_mid_channels = stage_mid_channels
140
+ self.stage_out_channels = stage_out_channels
141
+ self.stage_num_blocks = stage_num_blocks
142
+ self.stage_downsample = stage_downsample
143
+ self.stage_light_block = stage_light_block
144
+ self.stage_kernel_size = stage_kernel_size
145
+ self.stage_numb_of_layers = stage_numb_of_layers
146
+ self.use_learnable_affine_block = use_learnable_affine_block
147
+ self.initializer_range = initializer_range
148
+
149
+ if not (
150
+ len(stage_in_channels)
151
+ == len(stage_mid_channels)
152
+ == len(stage_out_channels)
153
+ == len(stage_num_blocks)
154
+ == len(stage_downsample)
155
+ == len(stage_light_block)
156
+ == len(stage_kernel_size)
157
+ == len(stage_numb_of_layers)
158
+ ):
159
+ raise ValueError("All stage configuration lists must have the same length.")
160
+
161
+
162
+ # General docstring
163
+
164
+
165
+ @auto_docstring
166
+ class HGNetV2PreTrainedModel(PreTrainedModel):
167
+ config: HGNetV2Config
168
+ base_model_prefix = "hgnetv2"
169
+ main_input_name = "pixel_values"
170
+ _no_split_modules = ["HGNetV2BasicLayer"]
171
+
172
+
173
+ class HGNetV2LearnableAffineBlock(nn.Module):
174
+ def __init__(self, scale_value: float = 1.0, bias_value: float = 0.0):
175
+ super().__init__()
176
+ self.scale = nn.Parameter(torch.tensor([scale_value]), requires_grad=True)
177
+ self.bias = nn.Parameter(torch.tensor([bias_value]), requires_grad=True)
178
+
179
+ def forward(self, hidden_state: Tensor) -> Tensor:
180
+ hidden_state = self.scale * hidden_state + self.bias
181
+ return hidden_state
182
+
183
+
184
+ class HGNetV2ConvLayer(RTDetrResNetConvLayer):
185
+ def __init__(
186
+ self,
187
+ in_channels: int,
188
+ out_channels: int,
189
+ kernel_size: int,
190
+ stride: int = 1,
191
+ groups: int = 1,
192
+ activation: str = "relu",
193
+ use_learnable_affine_block: bool = False,
194
+ ):
195
+ super().__init__(in_channels, out_channels, kernel_size, stride, activation)
196
+ self.convolution = nn.Conv2d(
197
+ in_channels,
198
+ out_channels,
199
+ kernel_size=kernel_size,
200
+ stride=stride,
201
+ groups=groups,
202
+ padding=(kernel_size - 1) // 2,
203
+ bias=False,
204
+ )
205
+ if activation and use_learnable_affine_block:
206
+ self.lab = HGNetV2LearnableAffineBlock()
207
+ else:
208
+ self.lab = nn.Identity()
209
+
210
+ def forward(self, input: Tensor) -> Tensor:
211
+ hidden_state = self.convolution(input)
212
+ hidden_state = self.normalization(hidden_state)
213
+ hidden_state = self.activation(hidden_state)
214
+ hidden_state = self.lab(hidden_state)
215
+ return hidden_state
216
+
217
+
218
+ class HGNetV2ConvLayerLight(nn.Module):
219
+ def __init__(
220
+ self, in_channels: int, out_channels: int, kernel_size: int, use_learnable_affine_block: bool = False
221
+ ):
222
+ super().__init__()
223
+ self.conv1 = HGNetV2ConvLayer(
224
+ in_channels,
225
+ out_channels,
226
+ kernel_size=1,
227
+ activation=None,
228
+ use_learnable_affine_block=use_learnable_affine_block,
229
+ )
230
+ self.conv2 = HGNetV2ConvLayer(
231
+ out_channels,
232
+ out_channels,
233
+ kernel_size=kernel_size,
234
+ groups=out_channels,
235
+ use_learnable_affine_block=use_learnable_affine_block,
236
+ )
237
+
238
+ def forward(self, hidden_state: Tensor) -> Tensor:
239
+ hidden_state = self.conv1(hidden_state)
240
+ hidden_state = self.conv2(hidden_state)
241
+ return hidden_state
242
+
243
+
244
+ class HGNetV2Embeddings(nn.Module):
245
+ def __init__(self, config: HGNetV2Config):
246
+ super().__init__()
247
+
248
+ self.stem1 = HGNetV2ConvLayer(
249
+ config.stem_channels[0],
250
+ config.stem_channels[1],
251
+ kernel_size=3,
252
+ stride=2,
253
+ activation=config.hidden_act,
254
+ use_learnable_affine_block=config.use_learnable_affine_block,
255
+ )
256
+ self.stem2a = HGNetV2ConvLayer(
257
+ config.stem_channels[1],
258
+ config.stem_channels[1] // 2,
259
+ kernel_size=2,
260
+ stride=1,
261
+ activation=config.hidden_act,
262
+ use_learnable_affine_block=config.use_learnable_affine_block,
263
+ )
264
+ self.stem2b = HGNetV2ConvLayer(
265
+ config.stem_channels[1] // 2,
266
+ config.stem_channels[1],
267
+ kernel_size=2,
268
+ stride=1,
269
+ activation=config.hidden_act,
270
+ use_learnable_affine_block=config.use_learnable_affine_block,
271
+ )
272
+ self.stem3 = HGNetV2ConvLayer(
273
+ config.stem_channels[1] * 2,
274
+ config.stem_channels[1],
275
+ kernel_size=3,
276
+ stride=2,
277
+ activation=config.hidden_act,
278
+ use_learnable_affine_block=config.use_learnable_affine_block,
279
+ )
280
+ self.stem4 = HGNetV2ConvLayer(
281
+ config.stem_channels[1],
282
+ config.stem_channels[2],
283
+ kernel_size=1,
284
+ stride=1,
285
+ activation=config.hidden_act,
286
+ use_learnable_affine_block=config.use_learnable_affine_block,
287
+ )
288
+
289
+ self.pool = nn.MaxPool2d(kernel_size=2, stride=1, ceil_mode=True)
290
+ self.num_channels = config.num_channels
291
+
292
+ def forward(self, pixel_values: Tensor) -> Tensor:
293
+ num_channels = pixel_values.shape[1]
294
+ if num_channels != self.num_channels:
295
+ raise ValueError(
296
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
297
+ )
298
+ embedding = self.stem1(pixel_values)
299
+ embedding = F.pad(embedding, (0, 1, 0, 1))
300
+ emb_stem_2a = self.stem2a(embedding)
301
+ emb_stem_2a = F.pad(emb_stem_2a, (0, 1, 0, 1))
302
+ emb_stem_2a = self.stem2b(emb_stem_2a)
303
+ pooled_emb = self.pool(embedding)
304
+ embedding = torch.cat([pooled_emb, emb_stem_2a], dim=1)
305
+ embedding = self.stem3(embedding)
306
+ embedding = self.stem4(embedding)
307
+ return embedding
308
+
309
+
310
+ class HGNetV2BasicLayer(nn.Module):
311
+ def __init__(
312
+ self,
313
+ in_channels: int,
314
+ middle_channels: int,
315
+ out_channels: int,
316
+ layer_num: int,
317
+ kernel_size: int = 3,
318
+ residual: bool = False,
319
+ light_block: bool = False,
320
+ drop_path: float = 0.0,
321
+ use_learnable_affine_block: bool = False,
322
+ ):
323
+ super().__init__()
324
+ self.residual = residual
325
+
326
+ self.layers = nn.ModuleList()
327
+ for i in range(layer_num):
328
+ temp_in_channels = in_channels if i == 0 else middle_channels
329
+ if light_block:
330
+ block = HGNetV2ConvLayerLight(
331
+ in_channels=temp_in_channels,
332
+ out_channels=middle_channels,
333
+ kernel_size=kernel_size,
334
+ use_learnable_affine_block=use_learnable_affine_block,
335
+ )
336
+ else:
337
+ block = HGNetV2ConvLayer(
338
+ in_channels=temp_in_channels,
339
+ out_channels=middle_channels,
340
+ kernel_size=kernel_size,
341
+ use_learnable_affine_block=use_learnable_affine_block,
342
+ stride=1,
343
+ )
344
+ self.layers.append(block)
345
+
346
+ # feature aggregation
347
+ total_channels = in_channels + layer_num * middle_channels
348
+ aggregation_squeeze_conv = HGNetV2ConvLayer(
349
+ total_channels,
350
+ out_channels // 2,
351
+ kernel_size=1,
352
+ stride=1,
353
+ use_learnable_affine_block=use_learnable_affine_block,
354
+ )
355
+ aggregation_excitation_conv = HGNetV2ConvLayer(
356
+ out_channels // 2,
357
+ out_channels,
358
+ kernel_size=1,
359
+ stride=1,
360
+ use_learnable_affine_block=use_learnable_affine_block,
361
+ )
362
+ self.aggregation = nn.Sequential(
363
+ aggregation_squeeze_conv,
364
+ aggregation_excitation_conv,
365
+ )
366
+ self.drop_path = nn.Dropout(drop_path) if drop_path else nn.Identity()
367
+
368
+ def forward(self, hidden_state: Tensor) -> Tensor:
369
+ identity = hidden_state
370
+ output = [hidden_state]
371
+ for layer in self.layers:
372
+ hidden_state = layer(hidden_state)
373
+ output.append(hidden_state)
374
+ hidden_state = torch.cat(output, dim=1)
375
+ hidden_state = self.aggregation(hidden_state)
376
+ if self.residual:
377
+ hidden_state = self.drop_path(hidden_state) + identity
378
+ return hidden_state
379
+
380
+
381
+ class HGNetV2Stage(nn.Module):
382
+ def __init__(self, config: HGNetV2Config, stage_index: int, drop_path: float = 0.0):
383
+ super().__init__()
384
+ in_channels = config.stage_in_channels[stage_index]
385
+ mid_channels = config.stage_mid_channels[stage_index]
386
+ out_channels = config.stage_out_channels[stage_index]
387
+ num_blocks = config.stage_num_blocks[stage_index]
388
+ num_layers = config.stage_numb_of_layers[stage_index]
389
+ downsample = config.stage_downsample[stage_index]
390
+ light_block = config.stage_light_block[stage_index]
391
+ kernel_size = config.stage_kernel_size[stage_index]
392
+ use_learnable_affine_block = config.use_learnable_affine_block
393
+
394
+ if downsample:
395
+ self.downsample = HGNetV2ConvLayer(
396
+ in_channels, in_channels, kernel_size=3, stride=2, groups=in_channels, activation=None
397
+ )
398
+ else:
399
+ self.downsample = nn.Identity()
400
+
401
+ blocks_list = []
402
+ for i in range(num_blocks):
403
+ blocks_list.append(
404
+ HGNetV2BasicLayer(
405
+ in_channels if i == 0 else out_channels,
406
+ mid_channels,
407
+ out_channels,
408
+ num_layers,
409
+ residual=(i != 0),
410
+ kernel_size=kernel_size,
411
+ light_block=light_block,
412
+ drop_path=drop_path,
413
+ use_learnable_affine_block=use_learnable_affine_block,
414
+ )
415
+ )
416
+ self.blocks = nn.ModuleList(blocks_list)
417
+
418
+ def forward(self, hidden_state: Tensor) -> Tensor:
419
+ hidden_state = self.downsample(hidden_state)
420
+ for block in self.blocks:
421
+ hidden_state = block(hidden_state)
422
+ return hidden_state
423
+
424
+
425
+ class HGNetV2Encoder(nn.Module):
426
+ def __init__(self, config: HGNetV2Config):
427
+ super().__init__()
428
+ self.stages = nn.ModuleList([])
429
+ for stage_index in range(len(config.stage_in_channels)):
430
+ resnet_stage = HGNetV2Stage(config, stage_index)
431
+ self.stages.append(resnet_stage)
432
+
433
+ def forward(
434
+ self, hidden_state: Tensor, output_hidden_states: bool = False, return_dict: bool = True
435
+ ) -> BaseModelOutputWithNoAttention:
436
+ hidden_states = () if output_hidden_states else None
437
+
438
+ for stage in self.stages:
439
+ if output_hidden_states:
440
+ hidden_states = hidden_states + (hidden_state,)
441
+
442
+ hidden_state = stage(hidden_state)
443
+
444
+ if output_hidden_states:
445
+ hidden_states = hidden_states + (hidden_state,)
446
+
447
+ if not return_dict:
448
+ return tuple(v for v in [hidden_state, hidden_states] if v is not None)
449
+
450
+ return BaseModelOutputWithNoAttention(
451
+ last_hidden_state=hidden_state,
452
+ hidden_states=hidden_states,
453
+ )
454
+
455
+
456
+ class HGNetV2Backbone(HGNetV2PreTrainedModel, BackboneMixin):
457
+ has_attentions = False
458
+
459
+ def __init__(self, config: HGNetV2Config):
460
+ super().__init__(config)
461
+ super()._init_backbone(config)
462
+ self.depths = config.depths
463
+ self.num_features = [config.embedding_size] + config.hidden_sizes
464
+ self.embedder = HGNetV2Embeddings(config)
465
+ self.encoder = HGNetV2Encoder(config)
466
+
467
+ # initialize weights and apply final processing
468
+ self.post_init()
469
+
470
+ @auto_docstring
471
+ def forward(
472
+ self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
473
+ ) -> BackboneOutput:
474
+ r"""
475
+ Examples:
476
+
477
+ ```python
478
+ >>> from transformers import HGNetV2Config, HGNetV2Backbone
479
+ >>> import torch
480
+
481
+ >>> config = HGNetV2Config()
482
+ >>> model = HGNetV2Backbone(config)
483
+
484
+ >>> pixel_values = torch.randn(1, 3, 224, 224)
485
+
486
+ >>> with torch.no_grad():
487
+ ... outputs = model(pixel_values)
488
+
489
+ >>> feature_maps = outputs.feature_maps
490
+ >>> list(feature_maps[-1].shape)
491
+ [1, 2048, 7, 7]
492
+ ```"""
493
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
494
+ output_hidden_states = (
495
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
496
+ )
497
+
498
+ embedding_output = self.embedder(pixel_values)
499
+
500
+ outputs = self.encoder(embedding_output, output_hidden_states=True, return_dict=True)
501
+
502
+ hidden_states = outputs.hidden_states
503
+
504
+ feature_maps = ()
505
+ for idx, stage in enumerate(self.stage_names):
506
+ if stage in self.out_features:
507
+ feature_maps += (hidden_states[idx],)
508
+
509
+ if not return_dict:
510
+ output = (feature_maps,)
511
+ if output_hidden_states:
512
+ output += (outputs.hidden_states,)
513
+ return output
514
+
515
+ return BackboneOutput(
516
+ feature_maps=feature_maps,
517
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
518
+ attentions=None,
519
+ )
520
+
521
+
522
+ @auto_docstring(
523
+ custom_intro="""
524
+ HGNetV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
525
+ ImageNet.
526
+ """
527
+ )
528
+ class HGNetV2ForImageClassification(HGNetV2PreTrainedModel):
529
+ def __init__(self, config: HGNetV2Config):
530
+ super().__init__(config)
531
+ self.num_labels = config.num_labels
532
+ self.embedder = HGNetV2Embeddings(config)
533
+ self.encoder = HGNetV2Encoder(config)
534
+ self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
535
+ self.flatten = nn.Flatten()
536
+ self.fc = nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
537
+
538
+ # classification head
539
+ self.classifier = nn.ModuleList([self.avg_pool, self.flatten])
540
+
541
+ # initialize weights and apply final processing
542
+ self.post_init()
543
+
544
+ @auto_docstring
545
+ def forward(
546
+ self,
547
+ pixel_values: Optional[torch.FloatTensor] = None,
548
+ labels: Optional[torch.LongTensor] = None,
549
+ output_hidden_states: Optional[bool] = None,
550
+ return_dict: Optional[bool] = None,
551
+ ) -> ImageClassifierOutputWithNoAttention:
552
+ r"""
553
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
554
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
555
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
556
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
557
+
558
+ Examples:
559
+ ```python
560
+ >>> import torch
561
+ >>> import requests
562
+ >>> from transformers import HGNetV2ForImageClassification, AutoImageProcessor
563
+ >>> from PIL import Image
564
+
565
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
566
+ >>> image = Image.open(requests.get(url, stream=True).raw)
567
+
568
+ >>> model = HGNetV2ForImageClassification.from_pretrained("ustc-community/hgnet-v2")
569
+ >>> processor = AutoImageProcessor.from_pretrained("ustc-community/hgnet-v2")
570
+
571
+ >>> inputs = processor(images=image, return_tensors="pt")
572
+ >>> with torch.no_grad():
573
+ ... outputs = model(**inputs)
574
+ >>> outputs.logits.shape
575
+ torch.Size([1, 2])
576
+ ```"""
577
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
578
+ output_hidden_states = (
579
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
580
+ )
581
+ embedding_output = self.embedder(pixel_values)
582
+ outputs = self.encoder(embedding_output, output_hidden_states=output_hidden_states, return_dict=return_dict)
583
+ last_hidden_state = outputs[0]
584
+ for layer in self.classifier:
585
+ last_hidden_state = layer(last_hidden_state)
586
+ logits = self.fc(last_hidden_state)
587
+ loss = None
588
+
589
+ if labels is not None:
590
+ loss = self.loss_function(labels, logits, self.config)
591
+
592
+ if not return_dict:
593
+ output = (logits,) + outputs[2:]
594
+ return (loss,) + output if loss is not None else output
595
+
596
+ return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
597
+
598
+
599
+ __all__ = ["HGNetV2Config", "HGNetV2Backbone", "HGNetV2PreTrainedModel", "HGNetV2ForImageClassification"]