Felix Marty
commited on
Commit
·
309fcfc
1
Parent(s):
77501cd
remove unused
Browse files
modeling/__pycache__/modeling_resnet.cpython-39.pyc
DELETED
Binary file (16.1 kB)
|
|
modeling/modeling_resnet.py
DELETED
@@ -1,518 +0,0 @@
|
|
1 |
-
# coding=utf-8
|
2 |
-
# Copyright 2022 Microsoft Research, Inc. and The HuggingFace Inc. team. All rights reserved.
|
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 |
-
""" PyTorch ResNet model."""
|
16 |
-
|
17 |
-
from typing import Optional
|
18 |
-
|
19 |
-
import torch
|
20 |
-
import torch.utils.checkpoint
|
21 |
-
from torch import Tensor, nn
|
22 |
-
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
23 |
-
|
24 |
-
from transformers.activations import ACT2FN
|
25 |
-
from transformers.modeling_outputs import (
|
26 |
-
BackboneOutput,
|
27 |
-
BaseModelOutputWithNoAttention,
|
28 |
-
BaseModelOutputWithPoolingAndNoAttention,
|
29 |
-
ImageClassifierOutputWithNoAttention,
|
30 |
-
)
|
31 |
-
from transformers.modeling_utils import BackboneMixin, PreTrainedModel
|
32 |
-
from transformers.utils import (
|
33 |
-
add_code_sample_docstrings,
|
34 |
-
add_start_docstrings,
|
35 |
-
add_start_docstrings_to_model_forward,
|
36 |
-
logging,
|
37 |
-
replace_return_docstrings,
|
38 |
-
)
|
39 |
-
from transformers import ResNetConfig
|
40 |
-
|
41 |
-
|
42 |
-
logger = logging.get_logger(__name__)
|
43 |
-
|
44 |
-
# General docstring
|
45 |
-
_CONFIG_FOR_DOC = "ResNetConfig"
|
46 |
-
_FEAT_EXTRACTOR_FOR_DOC = "AutoImageProcessor"
|
47 |
-
|
48 |
-
# Base docstring
|
49 |
-
_CHECKPOINT_FOR_DOC = "microsoft/resnet-50"
|
50 |
-
_EXPECTED_OUTPUT_SHAPE = [1, 2048, 7, 7]
|
51 |
-
|
52 |
-
# Image classification docstring
|
53 |
-
_IMAGE_CLASS_CHECKPOINT = "microsoft/resnet-50"
|
54 |
-
_IMAGE_CLASS_EXPECTED_OUTPUT = "tiger cat"
|
55 |
-
|
56 |
-
RESNET_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
57 |
-
"microsoft/resnet-50",
|
58 |
-
# See all resnet models at https://huggingface.co/models?filter=resnet
|
59 |
-
]
|
60 |
-
|
61 |
-
|
62 |
-
class ResNetConvLayer(nn.Module):
|
63 |
-
def __init__(
|
64 |
-
self, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1, activation: str = "relu"
|
65 |
-
):
|
66 |
-
super().__init__()
|
67 |
-
self.convolution = nn.Conv2d(
|
68 |
-
in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, bias=False
|
69 |
-
)
|
70 |
-
self.normalization = nn.BatchNorm2d(out_channels)
|
71 |
-
self.activation = ACT2FN[activation] if activation is not None else nn.Identity()
|
72 |
-
|
73 |
-
def forward(self, input: Tensor) -> Tensor:
|
74 |
-
hidden_state = self.convolution(input)
|
75 |
-
hidden_state = self.normalization(hidden_state)
|
76 |
-
hidden_state = self.activation(hidden_state)
|
77 |
-
return hidden_state
|
78 |
-
|
79 |
-
|
80 |
-
class ResNetEmbeddings(nn.Module):
|
81 |
-
"""
|
82 |
-
ResNet Embeddings (stem) composed of a single aggressive convolution.
|
83 |
-
"""
|
84 |
-
|
85 |
-
def __init__(self, config: ResNetConfig):
|
86 |
-
super().__init__()
|
87 |
-
self.embedder = ResNetConvLayer(
|
88 |
-
config.num_channels, config.embedding_size, kernel_size=7, stride=2, activation=config.hidden_act
|
89 |
-
)
|
90 |
-
self.pooler = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
91 |
-
self.num_channels = config.num_channels
|
92 |
-
|
93 |
-
def forward(self, pixel_values: Tensor) -> Tensor:
|
94 |
-
num_channels = pixel_values.shape[1]
|
95 |
-
if num_channels != self.num_channels:
|
96 |
-
raise ValueError(
|
97 |
-
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
98 |
-
)
|
99 |
-
embedding = self.embedder(pixel_values)
|
100 |
-
embedding = self.pooler(embedding)
|
101 |
-
return embedding
|
102 |
-
|
103 |
-
|
104 |
-
class ResNetShortCut(nn.Module):
|
105 |
-
"""
|
106 |
-
ResNet shortcut, used to project the residual features to the correct size. If needed, it is also used to
|
107 |
-
downsample the input using `stride=2`.
|
108 |
-
"""
|
109 |
-
|
110 |
-
def __init__(self, in_channels: int, out_channels: int, stride: int = 2):
|
111 |
-
super().__init__()
|
112 |
-
self.convolution = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)
|
113 |
-
self.normalization = nn.BatchNorm2d(out_channels)
|
114 |
-
|
115 |
-
def forward(self, input: Tensor) -> Tensor:
|
116 |
-
hidden_state = self.convolution(input)
|
117 |
-
hidden_state = self.normalization(hidden_state)
|
118 |
-
return hidden_state
|
119 |
-
|
120 |
-
|
121 |
-
class ResNetBasicLayer(nn.Module):
|
122 |
-
"""
|
123 |
-
A classic ResNet's residual layer composed by two `3x3` convolutions.
|
124 |
-
"""
|
125 |
-
|
126 |
-
def __init__(self, in_channels: int, out_channels: int, stride: int = 1, activation: str = "relu"):
|
127 |
-
super().__init__()
|
128 |
-
should_apply_shortcut = in_channels != out_channels or stride != 1
|
129 |
-
self.shortcut = (
|
130 |
-
ResNetShortCut(in_channels, out_channels, stride=stride) if should_apply_shortcut else nn.Identity()
|
131 |
-
)
|
132 |
-
self.layer = nn.Sequential(
|
133 |
-
ResNetConvLayer(in_channels, out_channels, stride=stride),
|
134 |
-
ResNetConvLayer(out_channels, out_channels, activation=None),
|
135 |
-
)
|
136 |
-
self.activation = ACT2FN[activation]
|
137 |
-
|
138 |
-
def forward(self, hidden_state):
|
139 |
-
residual = hidden_state
|
140 |
-
hidden_state = self.layer(hidden_state)
|
141 |
-
residual = self.shortcut(residual)
|
142 |
-
hidden_state += residual
|
143 |
-
hidden_state = self.activation(hidden_state)
|
144 |
-
return hidden_state
|
145 |
-
|
146 |
-
|
147 |
-
class ResNetBottleNeckLayer(nn.Module):
|
148 |
-
"""
|
149 |
-
A classic ResNet's bottleneck layer composed by three `3x3` convolutions.
|
150 |
-
|
151 |
-
The first `1x1` convolution reduces the input by a factor of `reduction` in order to make the second `3x3`
|
152 |
-
convolution faster. The last `1x1` convolution remaps the reduced features to `out_channels`.
|
153 |
-
"""
|
154 |
-
|
155 |
-
def __init__(
|
156 |
-
self, in_channels: int, out_channels: int, stride: int = 1, activation: str = "relu", reduction: int = 4
|
157 |
-
):
|
158 |
-
super().__init__()
|
159 |
-
should_apply_shortcut = in_channels != out_channels or stride != 1
|
160 |
-
reduces_channels = out_channels // reduction
|
161 |
-
self.shortcut = (
|
162 |
-
ResNetShortCut(in_channels, out_channels, stride=stride) if should_apply_shortcut else nn.Identity()
|
163 |
-
)
|
164 |
-
self.layer = nn.Sequential(
|
165 |
-
ResNetConvLayer(in_channels, reduces_channels, kernel_size=1),
|
166 |
-
ResNetConvLayer(reduces_channels, reduces_channels, stride=stride),
|
167 |
-
ResNetConvLayer(reduces_channels, out_channels, kernel_size=1, activation=None),
|
168 |
-
)
|
169 |
-
self.activation = ACT2FN[activation]
|
170 |
-
|
171 |
-
def forward(self, hidden_state):
|
172 |
-
residual = hidden_state
|
173 |
-
hidden_state = self.layer(hidden_state)
|
174 |
-
residual = self.shortcut(residual)
|
175 |
-
hidden_state += residual
|
176 |
-
hidden_state = self.activation(hidden_state)
|
177 |
-
return hidden_state
|
178 |
-
|
179 |
-
|
180 |
-
class ResNetStage(nn.Module):
|
181 |
-
"""
|
182 |
-
A ResNet stage composed by stacked layers.
|
183 |
-
"""
|
184 |
-
|
185 |
-
def __init__(
|
186 |
-
self,
|
187 |
-
config: ResNetConfig,
|
188 |
-
in_channels: int,
|
189 |
-
out_channels: int,
|
190 |
-
stride: int = 2,
|
191 |
-
depth: int = 2,
|
192 |
-
):
|
193 |
-
super().__init__()
|
194 |
-
|
195 |
-
layer = ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer
|
196 |
-
|
197 |
-
self.layers = nn.Sequential(
|
198 |
-
# downsampling is done in the first layer with stride of 2
|
199 |
-
layer(in_channels, out_channels, stride=stride, activation=config.hidden_act),
|
200 |
-
*[layer(out_channels, out_channels, activation=config.hidden_act) for _ in range(depth - 1)],
|
201 |
-
)
|
202 |
-
|
203 |
-
def forward(self, input: Tensor) -> Tensor:
|
204 |
-
hidden_state = input
|
205 |
-
for layer in self.layers:
|
206 |
-
hidden_state = layer(hidden_state)
|
207 |
-
hidden_state = hidden_state + 1
|
208 |
-
print("having fun in my custom code")
|
209 |
-
return hidden_state
|
210 |
-
|
211 |
-
|
212 |
-
class ResNetEncoder(nn.Module):
|
213 |
-
def __init__(self, config: ResNetConfig):
|
214 |
-
super().__init__()
|
215 |
-
self.stages = nn.ModuleList([])
|
216 |
-
# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
|
217 |
-
self.stages.append(
|
218 |
-
ResNetStage(
|
219 |
-
config,
|
220 |
-
config.embedding_size,
|
221 |
-
config.hidden_sizes[0],
|
222 |
-
stride=2 if config.downsample_in_first_stage else 1,
|
223 |
-
depth=config.depths[0],
|
224 |
-
)
|
225 |
-
)
|
226 |
-
in_out_channels = zip(config.hidden_sizes, config.hidden_sizes[1:])
|
227 |
-
for (in_channels, out_channels), depth in zip(in_out_channels, config.depths[1:]):
|
228 |
-
self.stages.append(ResNetStage(config, in_channels, out_channels, depth=depth))
|
229 |
-
|
230 |
-
def forward(
|
231 |
-
self, hidden_state: Tensor, output_hidden_states: bool = False, return_dict: bool = True
|
232 |
-
) -> BaseModelOutputWithNoAttention:
|
233 |
-
hidden_states = () if output_hidden_states else None
|
234 |
-
|
235 |
-
for stage_module in self.stages:
|
236 |
-
if output_hidden_states:
|
237 |
-
hidden_states = hidden_states + (hidden_state,)
|
238 |
-
|
239 |
-
hidden_state = stage_module(hidden_state)
|
240 |
-
|
241 |
-
if output_hidden_states:
|
242 |
-
hidden_states = hidden_states + (hidden_state,)
|
243 |
-
|
244 |
-
if not return_dict:
|
245 |
-
return tuple(v for v in [hidden_state, hidden_states] if v is not None)
|
246 |
-
|
247 |
-
return BaseModelOutputWithNoAttention(
|
248 |
-
last_hidden_state=hidden_state,
|
249 |
-
hidden_states=hidden_states,
|
250 |
-
)
|
251 |
-
|
252 |
-
|
253 |
-
class ResNetPreTrainedModel(PreTrainedModel):
|
254 |
-
"""
|
255 |
-
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
256 |
-
models.
|
257 |
-
"""
|
258 |
-
|
259 |
-
config_class = ResNetConfig
|
260 |
-
base_model_prefix = "resnet"
|
261 |
-
main_input_name = "pixel_values"
|
262 |
-
supports_gradient_checkpointing = True
|
263 |
-
|
264 |
-
def _init_weights(self, module):
|
265 |
-
if isinstance(module, nn.Conv2d):
|
266 |
-
nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
|
267 |
-
elif isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)):
|
268 |
-
nn.init.constant_(module.weight, 1)
|
269 |
-
nn.init.constant_(module.bias, 0)
|
270 |
-
|
271 |
-
def _set_gradient_checkpointing(self, module, value=False):
|
272 |
-
if isinstance(module, ResNetEncoder):
|
273 |
-
module.gradient_checkpointing = value
|
274 |
-
|
275 |
-
|
276 |
-
RESNET_START_DOCSTRING = r"""
|
277 |
-
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
278 |
-
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
279 |
-
behavior.
|
280 |
-
|
281 |
-
Parameters:
|
282 |
-
config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
|
283 |
-
Initializing with a config file does not load the weights associated with the model, only the
|
284 |
-
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
285 |
-
"""
|
286 |
-
|
287 |
-
RESNET_INPUTS_DOCSTRING = r"""
|
288 |
-
Args:
|
289 |
-
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
290 |
-
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
291 |
-
[`AutoImageProcessor.__call__`] for details.
|
292 |
-
|
293 |
-
output_hidden_states (`bool`, *optional*):
|
294 |
-
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
295 |
-
more detail.
|
296 |
-
return_dict (`bool`, *optional*):
|
297 |
-
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
298 |
-
"""
|
299 |
-
|
300 |
-
|
301 |
-
@add_start_docstrings(
|
302 |
-
"The bare ResNet model outputting raw features without any specific head on top.",
|
303 |
-
RESNET_START_DOCSTRING,
|
304 |
-
)
|
305 |
-
class ResNetModel(ResNetPreTrainedModel):
|
306 |
-
def __init__(self, config):
|
307 |
-
super().__init__(config)
|
308 |
-
self.config = config
|
309 |
-
self.embedder = ResNetEmbeddings(config)
|
310 |
-
self.encoder = ResNetEncoder(config)
|
311 |
-
self.pooler = nn.AdaptiveAvgPool2d((1, 1))
|
312 |
-
# Initialize weights and apply final processing
|
313 |
-
self.post_init()
|
314 |
-
|
315 |
-
@add_start_docstrings_to_model_forward(RESNET_INPUTS_DOCSTRING)
|
316 |
-
@add_code_sample_docstrings(
|
317 |
-
processor_class=_FEAT_EXTRACTOR_FOR_DOC,
|
318 |
-
checkpoint=_CHECKPOINT_FOR_DOC,
|
319 |
-
output_type=BaseModelOutputWithPoolingAndNoAttention,
|
320 |
-
config_class=_CONFIG_FOR_DOC,
|
321 |
-
modality="vision",
|
322 |
-
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
323 |
-
)
|
324 |
-
def forward(
|
325 |
-
self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
|
326 |
-
) -> BaseModelOutputWithPoolingAndNoAttention:
|
327 |
-
output_hidden_states = (
|
328 |
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
329 |
-
)
|
330 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
331 |
-
|
332 |
-
embedding_output = self.embedder(pixel_values)
|
333 |
-
|
334 |
-
encoder_outputs = self.encoder(
|
335 |
-
embedding_output, output_hidden_states=output_hidden_states, return_dict=return_dict
|
336 |
-
)
|
337 |
-
|
338 |
-
last_hidden_state = encoder_outputs[0]
|
339 |
-
|
340 |
-
pooled_output = self.pooler(last_hidden_state)
|
341 |
-
|
342 |
-
if not return_dict:
|
343 |
-
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
344 |
-
|
345 |
-
return BaseModelOutputWithPoolingAndNoAttention(
|
346 |
-
last_hidden_state=last_hidden_state,
|
347 |
-
pooler_output=pooled_output,
|
348 |
-
hidden_states=encoder_outputs.hidden_states,
|
349 |
-
)
|
350 |
-
|
351 |
-
|
352 |
-
@add_start_docstrings(
|
353 |
-
"""
|
354 |
-
ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
355 |
-
ImageNet.
|
356 |
-
""",
|
357 |
-
RESNET_START_DOCSTRING,
|
358 |
-
)
|
359 |
-
class ResNetCustomForImageClassification(ResNetPreTrainedModel):
|
360 |
-
def __init__(self, config):
|
361 |
-
super().__init__(config)
|
362 |
-
self.num_labels = config.num_labels
|
363 |
-
self.resnet = ResNetModel(config)
|
364 |
-
# classification head
|
365 |
-
self.classifier = nn.Sequential(
|
366 |
-
nn.Flatten(),
|
367 |
-
nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity(),
|
368 |
-
)
|
369 |
-
# initialize weights and apply final processing
|
370 |
-
self.post_init()
|
371 |
-
|
372 |
-
@add_start_docstrings_to_model_forward(RESNET_INPUTS_DOCSTRING)
|
373 |
-
@add_code_sample_docstrings(
|
374 |
-
processor_class=_FEAT_EXTRACTOR_FOR_DOC,
|
375 |
-
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
376 |
-
output_type=ImageClassifierOutputWithNoAttention,
|
377 |
-
config_class=_CONFIG_FOR_DOC,
|
378 |
-
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
379 |
-
)
|
380 |
-
def forward(
|
381 |
-
self,
|
382 |
-
pixel_values: Optional[torch.FloatTensor] = None,
|
383 |
-
labels: Optional[torch.LongTensor] = None,
|
384 |
-
output_hidden_states: Optional[bool] = None,
|
385 |
-
return_dict: Optional[bool] = None,
|
386 |
-
) -> ImageClassifierOutputWithNoAttention:
|
387 |
-
r"""
|
388 |
-
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
389 |
-
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
390 |
-
config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
391 |
-
"""
|
392 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
393 |
-
|
394 |
-
outputs = self.resnet(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
395 |
-
|
396 |
-
pooled_output = outputs.pooler_output if return_dict else outputs[1]
|
397 |
-
|
398 |
-
logits = self.classifier(pooled_output)
|
399 |
-
|
400 |
-
loss = None
|
401 |
-
|
402 |
-
if labels is not None:
|
403 |
-
if self.config.problem_type is None:
|
404 |
-
if self.num_labels == 1:
|
405 |
-
self.config.problem_type = "regression"
|
406 |
-
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
407 |
-
self.config.problem_type = "single_label_classification"
|
408 |
-
else:
|
409 |
-
self.config.problem_type = "multi_label_classification"
|
410 |
-
if self.config.problem_type == "regression":
|
411 |
-
loss_fct = MSELoss()
|
412 |
-
if self.num_labels == 1:
|
413 |
-
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
414 |
-
else:
|
415 |
-
loss = loss_fct(logits, labels)
|
416 |
-
elif self.config.problem_type == "single_label_classification":
|
417 |
-
loss_fct = CrossEntropyLoss()
|
418 |
-
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
419 |
-
elif self.config.problem_type == "multi_label_classification":
|
420 |
-
loss_fct = BCEWithLogitsLoss()
|
421 |
-
loss = loss_fct(logits, labels)
|
422 |
-
|
423 |
-
if not return_dict:
|
424 |
-
output = (logits,) + outputs[2:]
|
425 |
-
return (loss,) + output if loss is not None else output
|
426 |
-
|
427 |
-
return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
428 |
-
|
429 |
-
|
430 |
-
@add_start_docstrings(
|
431 |
-
"""
|
432 |
-
ResNet backbone, to be used with frameworks like DETR and MaskFormer.
|
433 |
-
""",
|
434 |
-
RESNET_START_DOCSTRING,
|
435 |
-
)
|
436 |
-
class ResNetBackbone(ResNetPreTrainedModel, BackboneMixin):
|
437 |
-
def __init__(self, config):
|
438 |
-
super().__init__(config)
|
439 |
-
|
440 |
-
self.stage_names = config.stage_names
|
441 |
-
self.embedder = ResNetEmbeddings(config)
|
442 |
-
self.encoder = ResNetEncoder(config)
|
443 |
-
|
444 |
-
self.out_features = config.out_features if config.out_features is not None else [self.stage_names[-1]]
|
445 |
-
|
446 |
-
out_feature_channels = {}
|
447 |
-
out_feature_channels["stem"] = config.embedding_size
|
448 |
-
for idx, stage in enumerate(self.stage_names[1:]):
|
449 |
-
out_feature_channels[stage] = config.hidden_sizes[idx]
|
450 |
-
|
451 |
-
self.out_feature_channels = out_feature_channels
|
452 |
-
|
453 |
-
# initialize weights and apply final processing
|
454 |
-
self.post_init()
|
455 |
-
|
456 |
-
@property
|
457 |
-
def channels(self):
|
458 |
-
return [self.out_feature_channels[name] for name in self.out_features]
|
459 |
-
|
460 |
-
@add_start_docstrings_to_model_forward(RESNET_INPUTS_DOCSTRING)
|
461 |
-
@replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
|
462 |
-
def forward(
|
463 |
-
self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
|
464 |
-
) -> BackboneOutput:
|
465 |
-
"""
|
466 |
-
Returns:
|
467 |
-
|
468 |
-
Examples:
|
469 |
-
|
470 |
-
```python
|
471 |
-
>>> from transformers import AutoImageProcessor, AutoBackbone
|
472 |
-
>>> import torch
|
473 |
-
>>> from PIL import Image
|
474 |
-
>>> import requests
|
475 |
-
|
476 |
-
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
477 |
-
>>> image = Image.open(requests.get(url, stream=True).raw)
|
478 |
-
|
479 |
-
>>> processor = AutoImageProcessor.from_pretrained("microsoft/resnet-50")
|
480 |
-
>>> model = AutoBackbone.from_pretrained(
|
481 |
-
... "microsoft/resnet-50", out_features=["stage1", "stage2", "stage3", "stage4"]
|
482 |
-
... )
|
483 |
-
|
484 |
-
>>> inputs = processor(image, return_tensors="pt")
|
485 |
-
|
486 |
-
>>> outputs = model(**inputs)
|
487 |
-
>>> feature_maps = outputs.feature_maps
|
488 |
-
>>> list(feature_maps[-1].shape)
|
489 |
-
[1, 2048, 7, 7]
|
490 |
-
```"""
|
491 |
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
492 |
-
output_hidden_states = (
|
493 |
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
494 |
-
)
|
495 |
-
|
496 |
-
embedding_output = self.embedder(pixel_values)
|
497 |
-
|
498 |
-
outputs = self.encoder(embedding_output, output_hidden_states=True, return_dict=True)
|
499 |
-
|
500 |
-
hidden_states = outputs.hidden_states
|
501 |
-
|
502 |
-
feature_maps = ()
|
503 |
-
for idx, stage in enumerate(self.stage_names):
|
504 |
-
if stage in self.out_features:
|
505 |
-
feature_maps += (hidden_states[idx],)
|
506 |
-
|
507 |
-
if not return_dict:
|
508 |
-
output = (feature_maps,)
|
509 |
-
if output_hidden_states:
|
510 |
-
output += (outputs.hidden_states,)
|
511 |
-
return output
|
512 |
-
|
513 |
-
return BackboneOutput(
|
514 |
-
feature_maps=feature_maps,
|
515 |
-
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
516 |
-
attentions=None,
|
517 |
-
)
|
518 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|