

# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import warnings
from typing import List
from unittest.mock import Mock

import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset

from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType

class 			a					(		UpperCAmelCase			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      data





						def __iter__(    self		):







										'''simple docstring'''


										for element in self.data:
														yield element







def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]=True	)				->    List[str]:
				_UpperCAmelCase    :						List[str]							=      Accelerator(even_batches=lowerCAmelCase	)
				assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
				return accelerator

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Accelerator					, lowerCAmelCase:					int					, lowerCAmelCase:					int					, lowerCAmelCase:					bool = False	)				->    List[Any]:
				if iterable:
								_UpperCAmelCase    :						Tuple							=      DummyIterableDataset(torch.as_tensor(range(lowerCAmelCase	)	)	)
				else:
								_UpperCAmelCase    :						Any							=      TensorDataset(torch.as_tensor(range(lowerCAmelCase	)	)	)

				_UpperCAmelCase    :						int							=      DataLoader(lowerCAmelCase					, batch_size=lowerCAmelCase	)
				_UpperCAmelCase    :						Dict							=      accelerator.prepare(lowerCAmelCase	)

				return dl

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Accelerator					, lowerCAmelCase:					int					, lowerCAmelCase:					int					, lowerCAmelCase:					List[int]					, lowerCAmelCase:					List[int]					, )				->    str:
				_UpperCAmelCase    :						Dict							=      create_dataloader(accelerator=lowerCAmelCase					, dataset_size=lowerCAmelCase					, batch_size=lowerCAmelCase	)

				_UpperCAmelCase    :						List[str]							=      [len(batch[0]	) for batch in dl]

				if accelerator.process_index == 0:
								assert batch_sizes == process_0_expected_batch_sizes
				elif accelerator.process_index == 1:
								assert batch_sizes == process_1_expected_batch_sizes

def 							__SCREAMING_SNAKE_CASE							(			)				->    Optional[Any]:
				_UpperCAmelCase    :						List[str]							=      create_accelerator()

				# without padding, we would expect a different number of batches
				verify_dataloader_batch_sizes(
				    lowerCAmelCase					, dataset_size=3					, batch_size=1					, process_0_expected_batch_sizes=[1, 1]					, process_1_expected_batch_sizes=[1, 1]					, )

				# without padding, we would expect the same number of batches, but different sizes
				verify_dataloader_batch_sizes(
				    lowerCAmelCase					, dataset_size=7					, batch_size=2					, process_0_expected_batch_sizes=[2, 2]					, process_1_expected_batch_sizes=[2, 2]					, )

def 							__SCREAMING_SNAKE_CASE							(			)				->    str:
				_UpperCAmelCase    :						Optional[int]							=      create_accelerator(even_batches=lowerCAmelCase	)

				verify_dataloader_batch_sizes(
				    lowerCAmelCase					, dataset_size=3					, batch_size=1					, process_0_expected_batch_sizes=[1, 1]					, process_1_expected_batch_sizes=[1]					, )

				verify_dataloader_batch_sizes(
				    lowerCAmelCase					, dataset_size=7					, batch_size=2					, process_0_expected_batch_sizes=[2, 2]					, process_1_expected_batch_sizes=[2, 1]					, )

def 							__SCREAMING_SNAKE_CASE							(			)				->    Dict:
				_UpperCAmelCase    :						Tuple							=      create_accelerator(even_batches=lowerCAmelCase	)

				_UpperCAmelCase    :						Dict							=      torch.nn.Linear(1					, 1	)
				_UpperCAmelCase    :						List[Any]							=      accelerator.prepare(lowerCAmelCase	)

				_UpperCAmelCase    :						Dict							=      create_dataloader(lowerCAmelCase					, dataset_size=3					, batch_size=1	)

				_UpperCAmelCase    :						Optional[int]							=      []
				with accelerator.join_uneven_inputs([ddp_model]	):
								for batch_idx, batch in enumerate(lowerCAmelCase	):
												_UpperCAmelCase    :						Dict							=      ddp_model(batch[0].float()	)
												_UpperCAmelCase    :						Any							=      output.sum()
												loss.backward()
												batch_idxs.append(lowerCAmelCase	)

				accelerator.wait_for_everyone()

				if accelerator.process_index == 0:
								assert batch_idxs == [0, 1]
				elif accelerator.process_index == 1:
								assert batch_idxs == [0]

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]	)				->    Dict:
				with warnings.catch_warnings(record=lowerCAmelCase	) as w:
								with accelerator.join_uneven_inputs([Mock()]	):
												pass

								assert issubclass(w[-1].category					, lowerCAmelCase	)
								assert "only supported for multi-GPU" in str(w[-1].message	)

def 							__SCREAMING_SNAKE_CASE							(			)				->    Optional[Any]:
				_UpperCAmelCase    :						Union[str, Any]							=      True
				_UpperCAmelCase    :						List[Any]							=      False
				_UpperCAmelCase    :						Union[str, Any]							=      create_accelerator(even_batches=lowerCAmelCase	)
				_UpperCAmelCase    :						Dict							=      torch.nn.Linear(1					, 1	)
				_UpperCAmelCase    :						Dict							=      accelerator.prepare(lowerCAmelCase	)
				_UpperCAmelCase    :						str							=      create_dataloader(lowerCAmelCase					, dataset_size=3					, batch_size=1	)
				_UpperCAmelCase    :						List[str]							=      create_dataloader(lowerCAmelCase					, dataset_size=3					, batch_size=1	)

				with accelerator.join_uneven_inputs([ddp_model]					, even_batches=lowerCAmelCase	):
								_UpperCAmelCase    :						List[Any]							=      train_dl.batch_sampler.even_batches
								_UpperCAmelCase    :						Optional[int]							=      valid_dl.batch_sampler.even_batches

				assert train_dl_overridden_value == overridden_even_batches
				assert valid_dl_overridden_value == overridden_even_batches
				assert train_dl.batch_sampler.even_batches == default_even_batches
				assert valid_dl.batch_sampler.even_batches == default_even_batches

def 							__SCREAMING_SNAKE_CASE							(			)				->    Dict:
				_UpperCAmelCase    :						Union[str, Any]							=      True
				_UpperCAmelCase    :						Any							=      False
				_UpperCAmelCase    :						Tuple							=      create_accelerator(even_batches=lowerCAmelCase	)
				_UpperCAmelCase    :						Tuple							=      torch.nn.Linear(1					, 1	)
				_UpperCAmelCase    :						Any							=      accelerator.prepare(lowerCAmelCase	)
				create_dataloader(lowerCAmelCase					, dataset_size=3					, batch_size=1					, iterable=lowerCAmelCase	)
				_UpperCAmelCase    :						Optional[Any]							=      create_dataloader(lowerCAmelCase					, dataset_size=3					, batch_size=1	)

				with warnings.catch_warnings():
								warnings.filterwarnings("ignore"	)
								try:
												with accelerator.join_uneven_inputs([ddp_model]					, even_batches=lowerCAmelCase	):
																_UpperCAmelCase    :						Tuple							=      batch_dl.batch_sampler.even_batches
								except AttributeError:
												# ensure attribute error is not raised when processing iterable dl
												raise AssertionError

				assert batch_dl_overridden_value == overridden_even_batches
				assert batch_dl.batch_sampler.even_batches == default_even_batches

def 							__SCREAMING_SNAKE_CASE							(			)				->    Optional[Any]:
				_UpperCAmelCase    :						Optional[int]							=      create_accelerator()
				_UpperCAmelCase    :						Any							=      torch.nn.Linear(1					, 1	)
				_UpperCAmelCase    :						List[Any]							=      accelerator.prepare(lowerCAmelCase	)
				create_dataloader(lowerCAmelCase					, dataset_size=3					, batch_size=1					, iterable=lowerCAmelCase	)

				with warnings.catch_warnings(record=lowerCAmelCase	) as w:
								with accelerator.join_uneven_inputs([ddp_model]					, even_batches=lowerCAmelCase	):
												pass

								assert issubclass(w[-1].category					, lowerCAmelCase	)
								assert "only supported for map-style datasets" in str(w[-1].message	)

def 							__SCREAMING_SNAKE_CASE							(			)				->    Dict:
				_UpperCAmelCase    :						Optional[Any]							=      create_accelerator()

				accelerator.print("Test that even_batches variable ensures uniform batches across processes"	)
				test_default_ensures_even_batch_sizes()

				accelerator.print("Run tests with even_batches disabled"	)
				test_can_disable_even_batches()

				accelerator.print("Test joining uneven inputs"	)
				test_can_join_uneven_inputs()

				accelerator.print("Test overriding even_batches when joining uneven inputs"	)
				test_join_can_override_even_batches()

				accelerator.print("Test overriding even_batches for mixed dataloader types"	)
				test_join_can_override_for_mixed_type_dataloaders()

				accelerator.print("Test overriding even_batches raises a warning for iterable dataloaders"	)
				test_join_raises_warning_for_iterable_when_overriding_even_batches()

				accelerator.print("Test join with non DDP distributed raises warning"	)
				_UpperCAmelCase    :						List[str]							=      accelerator.state.distributed_type
				_UpperCAmelCase    :						Tuple							=      DistributedType.FSDP
				test_join_raises_warning_for_non_ddp_distributed(lowerCAmelCase	)
				_UpperCAmelCase    :						List[Any]							=      original_state


if __name__ == "__main__":
					main()





from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


SCREAMING_SNAKE_CASE_            = logging.get_logger(__name__)

# General docstring
SCREAMING_SNAKE_CASE_            = 'ResNetConfig'

# Base docstring
SCREAMING_SNAKE_CASE_            = 'microsoft/resnet-50'
SCREAMING_SNAKE_CASE_            = [1, 2048, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE_            = 'microsoft/resnet-50'
SCREAMING_SNAKE_CASE_            = 'tiger cat'

SCREAMING_SNAKE_CASE_            = [
    'microsoft/resnet-50',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]

class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 3  ,   A_ = 1  ,   A_ = "relu"		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Union[str, Any]							=      nn.Convad(
										    A_  ,   A_  ,   kernel_size=A_  ,   stride=A_  ,   padding=kernel_size // 2  ,   bias=A_		)
										_UpperCAmelCase    :						List[Any]							=      nn.BatchNormad(A_		)
										_UpperCAmelCase    :						Union[str, Any]							=      ACTaFN[activation] if activation is not None else nn.Identity()





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      self.convolution(A_		)
										_UpperCAmelCase    :						Optional[int]							=      self.normalization(A_		)
										_UpperCAmelCase    :						Optional[Any]							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Any							=      ResNetConvLayer(
										    config.num_channels  ,   config.embedding_size  ,   kernel_size=7  ,   stride=2  ,   activation=config.hidden_act		)
										_UpperCAmelCase    :						List[str]							=      nn.MaxPoolad(kernel_size=3  ,   stride=2  ,   padding=1		)
										_UpperCAmelCase    :						List[Any]							=      config.num_channels





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						int							=      pixel_values.shape[1]
										if num_channels != self.num_channels:
														raise ValueError(
														    "Make sure that the channel dimension of the pixel values match with the one set in the configuration."		)
										_UpperCAmelCase    :						int							=      self.embedder(A_		)
										_UpperCAmelCase    :						int							=      self.pooler(A_		)
										return embedding







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 2		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Union[str, Any]							=      nn.Convad(A_  ,   A_  ,   kernel_size=1  ,   stride=A_  ,   bias=A_		)
										_UpperCAmelCase    :						Optional[int]							=      nn.BatchNormad(A_		)





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						str							=      self.convolution(A_		)
										_UpperCAmelCase    :						List[str]							=      self.normalization(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 1  ,   A_ = "relu"		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Optional[int]							=      in_channels != out_channels or stride != 1
										_UpperCAmelCase    :						Dict							=      (
										    ResNetShortCut(A_  ,   A_  ,   stride=A_		) if should_apply_shortcut else nn.Identity()
										)
										_UpperCAmelCase    :						int							=      nn.Sequential(
										    ResNetConvLayer(A_  ,   A_  ,   stride=A_		)  ,   ResNetConvLayer(A_  ,   A_  ,   activation=A_		)  ,   )
										_UpperCAmelCase    :						Dict							=      ACTaFN[activation]





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[Any]							=      hidden_state
										_UpperCAmelCase    :						Any							=      self.layer(A_		)
										_UpperCAmelCase    :						Optional[int]							=      self.shortcut(A_		)
										hidden_state += residual
										_UpperCAmelCase    :						Optional[int]							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 1  ,   A_ = "relu"  ,   A_ = 4		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Optional[Any]							=      in_channels != out_channels or stride != 1
										_UpperCAmelCase    :						Optional[int]							=      out_channels // reduction
										_UpperCAmelCase    :						List[str]							=      (
										    ResNetShortCut(A_  ,   A_  ,   stride=A_		) if should_apply_shortcut else nn.Identity()
										)
										_UpperCAmelCase    :						Dict							=      nn.Sequential(
										    ResNetConvLayer(A_  ,   A_  ,   kernel_size=1		)  ,   ResNetConvLayer(A_  ,   A_  ,   stride=A_		)  ,   ResNetConvLayer(A_  ,   A_  ,   kernel_size=1  ,   activation=A_		)  ,   )
										_UpperCAmelCase    :						List[str]							=      ACTaFN[activation]





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      hidden_state
										_UpperCAmelCase    :						List[str]							=      self.layer(A_		)
										_UpperCAmelCase    :						List[str]							=      self.shortcut(A_		)
										hidden_state += residual
										_UpperCAmelCase    :						Dict							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_  ,   A_ = 2  ,   A_ = 2  ,   ):







										'''simple docstring'''


										super().__init__()

										_UpperCAmelCase    :						Any							=      ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer

										_UpperCAmelCase    :						Optional[Any]							=      nn.Sequential(
										    # downsampling is done in the first layer with stride of 2
										    layer(A_  ,   A_  ,   stride=A_  ,   activation=config.hidden_act		)  ,   *[layer(A_  ,   A_  ,   activation=config.hidden_act		) for _ in range(depth - 1		)]  ,   )





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      input
										for layer in self.layers:
														_UpperCAmelCase    :						Optional[Any]							=      layer(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Any							=      nn.ModuleList([]		)
										# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
										self.stages.append(
										    ResNetStage(
										        A_  ,   config.embedding_size  ,   config.hidden_sizes[0]  ,   stride=2 if config.downsample_in_first_stage else 1  ,   depth=config.depths[0]  ,   )		)
										_UpperCAmelCase    :						Union[str, Any]							=      zip(config.hidden_sizes  ,   config.hidden_sizes[1:]		)
										for (in_channels, out_channels), depth in zip(A_  ,   config.depths[1:]		):
														self.stages.append(ResNetStage(A_  ,   A_  ,   A_  ,   depth=A_		)		)





						def     _UpperCAmelCase			(    self  ,   A_  ,   A_ = False  ,   A_ = True		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      () if output_hidden_states else None

										for stage_module in self.stages:
														if output_hidden_states:
																		_UpperCAmelCase    :						Dict							=      hidden_states + (hidden_state,)

														_UpperCAmelCase    :						str							=      stage_module(A_		)

										if output_hidden_states:
														_UpperCAmelCase    :						int							=      hidden_states + (hidden_state,)

										if not return_dict:
														return tuple(v for v in [hidden_state, hidden_states] if v is not None		)

										return BaseModelOutputWithNoAttention(
										    last_hidden_state=A_  ,   hidden_states=A_  ,   )







class 			a					(		UpperCAmelCase			):
						_lowercase        =     ResNetConfig
						_lowercase        =     "resnet"
						_lowercase        =     "pixel_values"
						_lowercase        =     True


						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										if isinstance(A_  ,   nn.Convad		):
														nn.init.kaiming_normal_(module.weight  ,   mode="fan_out"  ,   nonlinearity="relu"		)
										elif isinstance(A_  ,   (nn.BatchNormad, nn.GroupNorm)		):
														nn.init.constant_(module.weight  ,   1		)
														nn.init.constant_(module.bias  ,   0		)





						def     _UpperCAmelCase			(    self  ,   A_  ,   A_=False		):







										'''simple docstring'''


										if isinstance(A_  ,   A_		):
														_UpperCAmelCase    :						Optional[Any]							=      value







SCREAMING_SNAKE_CASE_            = R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

SCREAMING_SNAKE_CASE_            = R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'

@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."							,	UpperCAmelCase							,	)
class 			a					(		UpperCAmelCase			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										_UpperCAmelCase    :						List[str]							=      config
										_UpperCAmelCase    :						Any							=      ResNetEmbeddings(A_		)
										_UpperCAmelCase    :						str							=      ResNetEncoder(A_		)
										_UpperCAmelCase    :						Any							=      nn.AdaptiveAvgPoolad((1, 1)		)
										# Initialize weights and apply final processing
										self.post_init()





						@add_start_docstrings_to_model_forward(A_		)
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC  ,   output_type=A_  ,   config_class=_CONFIG_FOR_DOC  ,   modality="vision"  ,   expected_output=_EXPECTED_OUTPUT_SHAPE  ,   )
						def     _UpperCAmelCase			(    self  ,   A_  ,   A_ = None  ,   A_ = None		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      (
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)
										_UpperCAmelCase    :						List[str]							=      return_dict if return_dict is not None else self.config.use_return_dict

										_UpperCAmelCase    :						List[Any]							=      self.embedder(A_		)

										_UpperCAmelCase    :						str							=      self.encoder(
										    A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						List[Any]							=      encoder_outputs[0]

										_UpperCAmelCase    :						int							=      self.pooler(A_		)

										if not return_dict:
														return (last_hidden_state, pooled_output) + encoder_outputs[1:]

										return BaseModelOutputWithPoolingAndNoAttention(
										    last_hidden_state=A_  ,   pooler_output=A_  ,   hidden_states=encoder_outputs.hidden_states  ,   )







@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "							,	UpperCAmelCase							,	)
class 			a					(		UpperCAmelCase			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										_UpperCAmelCase    :						Optional[int]							=      config.num_labels
										_UpperCAmelCase    :						str							=      ResNetModel(A_		)
										# classification head
										_UpperCAmelCase    :						int							=      nn.Sequential(
										    nn.Flatten()  ,   nn.Linear(config.hidden_sizes[-1]  ,   config.num_labels		) if config.num_labels > 0 else nn.Identity()  ,   )
										# initialize weights and apply final processing
										self.post_init()





						@add_start_docstrings_to_model_forward(A_		)
						@add_code_sample_docstrings(
						    checkpoint=_IMAGE_CLASS_CHECKPOINT  ,   output_type=A_  ,   config_class=_CONFIG_FOR_DOC  ,   expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT  ,   )
						def     _UpperCAmelCase			(    self  ,   A_ = None  ,   A_ = None  ,   A_ = None  ,   A_ = None  ,   ):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      return_dict if return_dict is not None else self.config.use_return_dict

										_UpperCAmelCase    :						Tuple							=      self.resnet(A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						Optional[int]							=      outputs.pooler_output if return_dict else outputs[1]

										_UpperCAmelCase    :						int							=      self.classifier(A_		)

										_UpperCAmelCase    :						Dict							=      None

										if labels is not None:
														if self.config.problem_type is None:
																		if self.num_labels == 1:
																						_UpperCAmelCase    :						Optional[Any]							=      "regression"
																		elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																						_UpperCAmelCase    :						Optional[Any]							=      "single_label_classification"
																		else:
																						_UpperCAmelCase    :						Any							=      "multi_label_classification"
														if self.config.problem_type == "regression":
																		_UpperCAmelCase    :						str							=      MSELoss()
																		if self.num_labels == 1:
																						_UpperCAmelCase    :						Any							=      loss_fct(logits.squeeze()  ,   labels.squeeze()		)
																		else:
																						_UpperCAmelCase    :						Optional[int]							=      loss_fct(A_  ,   A_		)
														elif self.config.problem_type == "single_label_classification":
																		_UpperCAmelCase    :						Any							=      CrossEntropyLoss()
																		_UpperCAmelCase    :						Any							=      loss_fct(logits.view(-1  ,   self.num_labels		)  ,   labels.view(-1		)		)
														elif self.config.problem_type == "multi_label_classification":
																		_UpperCAmelCase    :						Any							=      BCEWithLogitsLoss()
																		_UpperCAmelCase    :						Tuple							=      loss_fct(A_  ,   A_		)

										if not return_dict:
														_UpperCAmelCase    :						Any							=      (logits,) + outputs[2:]
														return (loss,) + output if loss is not None else output

										return ImageClassifierOutputWithNoAttention(loss=A_  ,   logits=A_  ,   hidden_states=outputs.hidden_states		)







@add_start_docstrings(
    "\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    "							,	UpperCAmelCase							,	)
class 			a					(		UpperCAmelCase							,	UpperCAmelCase			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										super()._init_backbone(A_		)

										_UpperCAmelCase    :						Optional[int]							=      [config.embedding_size] + config.hidden_sizes
										_UpperCAmelCase    :						str							=      ResNetEmbeddings(A_		)
										_UpperCAmelCase    :						List[Any]							=      ResNetEncoder(A_		)

										# initialize weights and apply final processing
										self.post_init()





						@add_start_docstrings_to_model_forward(A_		)
						@replace_return_docstrings(output_type=A_  ,   config_class=_CONFIG_FOR_DOC		)
						def     _UpperCAmelCase			(    self  ,   A_  ,   A_ = None  ,   A_ = None		):







										'''simple docstring'''


										_UpperCAmelCase    :						Tuple							=      return_dict if return_dict is not None else self.config.use_return_dict
										_UpperCAmelCase    :						Tuple							=      (
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)

										_UpperCAmelCase    :						Tuple							=      self.embedder(A_		)

										_UpperCAmelCase    :						Optional[int]							=      self.encoder(A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						Optional[int]							=      outputs.hidden_states

										_UpperCAmelCase    :						Any							=      ()
										for idx, stage in enumerate(self.stage_names		):
														if stage in self.out_features:
																		feature_maps += (hidden_states[idx],)

										if not return_dict:
														_UpperCAmelCase    :						Union[str, Any]							=      (feature_maps,)
														if output_hidden_states:
																		output += (outputs.hidden_states,)
														return output

										return BackboneOutput(
										    feature_maps=A_  ,   hidden_states=outputs.hidden_states if output_hidden_states else None  ,   attentions=A_  ,   )


