

'''simple docstring'''


from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


lowerCAmelCase__										= logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCAmelCase__										= "\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n        >>> from diffusers.utils import load_image\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior.to(\"cuda\")\n\n        >>> prompt = \"A red cartoon frog, 4k\"\n        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n        ... )\n        >>> pipe.to(\"cuda\")\n\n        >>> init_image = load_image(\n        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n        ...     \"/kandinsky/frog.png\"\n        ... )\n\n        >>> image = pipe(\n        ...     image=init_image,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ...     strength=0.2,\n        ... ).images\n\n        >>> image[0].save(\"red_frog.png\")\n        ```\n"







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase=8  )    ->    Dict:

	'''simple docstring'''





	UpperCAmelCase_		:      Optional[Any]       	=					height // scale_factor**2
	if height % scale_factor**2 != 0:
		new_height += 1
	UpperCAmelCase_		:      str       	=					width // scale_factor**2
	if width % scale_factor**2 != 0:
		new_width += 1
	return new_height * scale_factor, new_width * scale_factor







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase=5_1_2   ,UpperCamelCase=5_1_2  )    ->    Optional[Any]:

	'''simple docstring'''





	UpperCAmelCase_		:      Tuple       	=					pil_image.resize((w, h)   ,resample=Image.BICUBIC   ,reducing_gap=1  )
	UpperCAmelCase_		:      int       	=					np.array(pil_image.convert('RGB'  )  )
	UpperCAmelCase_		:      int       	=					arr.astype(np.floataa  ) / 127.5 - 1
	UpperCAmelCase_		:      int       	=					np.transpose(lowercase__   ,[2, 0, 1]  )
	UpperCAmelCase_		:      Tuple       	=					torch.from_numpy(lowercase__  ).unsqueeze(0  )
	return image







class 					lowercase						(  __snake_case ):


							def __init__(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			)							->				Dict:
								super().__init__()

								self.register_modules(
								    unet=__UpperCamelCase    ,			scheduler=__UpperCamelCase    ,			movq=__UpperCamelCase    ,			)
								UpperCAmelCase_		:      Optional[Any]       	=					2 ** (len(self.movq.config.block_out_channels) - 1)


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case)							->				int:
								UpperCAmelCase_		:      List[Any]       	=					min(int(num_inference_steps * strength)    ,			__UpperCamelCase)

								UpperCAmelCase_		:      Any       	=					max(num_inference_steps - init_timestep    ,			0)
								UpperCAmelCase_		:      Any       	=					self.scheduler.timesteps[t_start:]

								return timesteps, num_inference_steps - t_start


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case=None)							->				str:


								if not isinstance(__UpperCamelCase    ,			(torch.Tensor, PIL.Image.Image, list)):
									raise ValueError(
									    F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__UpperCamelCase)}""")

								UpperCAmelCase_		:      str       	=					image.to(device=__UpperCamelCase    ,			dtype=__UpperCamelCase)

								UpperCAmelCase_		:      Any       	=					batch_size * num_images_per_prompt

								if image.shape[1] == 4:
									UpperCAmelCase_		:      Optional[int]       	=					image

								else:
									if isinstance(__UpperCamelCase    ,			__UpperCamelCase) and len(__UpperCamelCase) != batch_size:
										raise ValueError(
										    F"""You have passed a list of generators of length {len(__UpperCamelCase)}, but requested an effective batch"""
										    F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""")

									elif isinstance(__UpperCamelCase    ,			__UpperCamelCase):
										UpperCAmelCase_		:      Tuple       	=					[
										    self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(__UpperCamelCase)
										]
										UpperCAmelCase_		:      Any       	=					torch.cat(__UpperCamelCase    ,			dim=0)
									else:
										UpperCAmelCase_		:      Dict       	=					self.movq.encode(__UpperCamelCase).latent_dist.sample(__UpperCamelCase)

									UpperCAmelCase_		:      Tuple       	=					self.movq.config.scaling_factor * init_latents

								UpperCAmelCase_		:      Any       	=					torch.cat([init_latents]    ,			dim=0)

								UpperCAmelCase_		:      int       	=					init_latents.shape
								UpperCAmelCase_		:      Optional[Any]       	=					randn_tensor(__UpperCamelCase    ,			generator=__UpperCamelCase    ,			device=__UpperCamelCase    ,			dtype=__UpperCamelCase)

								# get latents
								UpperCAmelCase_		:      Tuple       	=					self.scheduler.add_noise(__UpperCamelCase    ,			__UpperCamelCase    ,			__UpperCamelCase)

								UpperCAmelCase_		:      List[str]       	=					init_latents

								return latents


							def 						_snake_case							(			self    ,			_snake_case=0)							->				List[str]:


								if is_accelerate_available():
									from accelerate import cpu_offload
								else:
									raise ImportError('Please install accelerate via `pip install accelerate`')

								UpperCAmelCase_		:      int       	=					torch.device(F"""cuda:{gpu_id}""")

								UpperCAmelCase_		:      Tuple       	=					[
								    self.unet,
								    self.movq,
								]
								for cpu_offloaded_model in models:
									if cpu_offloaded_model is not None:
										cpu_offload(__UpperCamelCase    ,			__UpperCamelCase)


							def 						_snake_case							(			self    ,			_snake_case=0)							->				Tuple:


								if is_accelerate_available() and is_accelerate_version('>='    ,			'0.17.0.dev0'):
									from accelerate import cpu_offload_with_hook
								else:
									raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.')

								UpperCAmelCase_		:      str       	=					torch.device(F"""cuda:{gpu_id}""")

								if self.device.type != "cpu":
									self.to('cpu'    ,			silence_dtype_warnings=__UpperCamelCase)
									torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

								UpperCAmelCase_		:      Tuple       	=					None
								for cpu_offloaded_model in [self.unet, self.movq]:
									UpperCAmelCase_	,    UpperCAmelCase_		:      int       	=					cpu_offload_with_hook(__UpperCamelCase    ,			__UpperCamelCase    ,			prev_module_hook=__UpperCamelCase)

								# We'll offload the last model manually.
								UpperCAmelCase_		:      Any       	=					hook


							@property
							# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
							def 						_snake_case							(			self)							->				int:


								if not hasattr(self.unet    ,			'_hf_hook'):
									return self.device
								for module in self.unet.modules():
									if (
									    hasattr(__UpperCamelCase    ,			'_hf_hook')
									    and hasattr(module._hf_hook    ,			'execution_device')
									    and module._hf_hook.execution_device is not None
									):
										return torch.device(module._hf_hook.execution_device)
								return self.device





							@torch.no_grad()
							@replace_example_docstring(__UpperCamelCase)
							def __call__(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case = 512    ,			_snake_case = 512    ,			_snake_case = 100    ,			_snake_case = 4.0    ,			_snake_case = 0.3    ,			_snake_case = 1    ,			_snake_case = None    ,			_snake_case = "pil"    ,			_snake_case = True    ,			)							->				Dict:
								UpperCAmelCase_		:      Dict       	=					self._execution_device

								UpperCAmelCase_		:      str       	=					guidance_scale > 1.0

								if isinstance(__UpperCamelCase    ,			__UpperCamelCase):
									UpperCAmelCase_		:      Optional[int]       	=					torch.cat(__UpperCamelCase    ,			dim=0)
								UpperCAmelCase_		:      int       	=					image_embeds.shape[0]
								if isinstance(__UpperCamelCase    ,			__UpperCamelCase):
									UpperCAmelCase_		:      List[str]       	=					torch.cat(__UpperCamelCase    ,			dim=0)

								if do_classifier_free_guidance:
									UpperCAmelCase_		:      str       	=					image_embeds.repeat_interleave(__UpperCamelCase    ,			dim=0)
									UpperCAmelCase_		:      int       	=					negative_image_embeds.repeat_interleave(__UpperCamelCase    ,			dim=0)

								UpperCAmelCase_		:      List[Any]       	=					torch.cat([negative_image_embeds, image_embeds]    ,			dim=0).to(dtype=self.unet.dtype    ,			device=__UpperCamelCase)

								if not isinstance(__UpperCamelCase    ,			__UpperCamelCase):
									UpperCAmelCase_		:      Tuple       	=					[image]
								if not all(isinstance(__UpperCamelCase    ,			(PIL.Image.Image, torch.Tensor)) for i in image):
									raise ValueError(
									    F"""Input is in incorrect format: {[type(__UpperCamelCase) for i in image]}. Currently, we only support  PIL image and pytorch tensor""")

								UpperCAmelCase_		:      List[str]       	=					torch.cat([prepare_image(__UpperCamelCase    ,			__UpperCamelCase    ,			__UpperCamelCase) for i in image]    ,			dim=0)
								UpperCAmelCase_		:      List[str]       	=					image.to(dtype=image_embeds.dtype    ,			device=__UpperCamelCase)

								UpperCAmelCase_		:      str       	=					self.movq.encode(__UpperCamelCase)['latents']
								UpperCAmelCase_		:      Optional[int]       	=					latents.repeat_interleave(__UpperCamelCase    ,			dim=0)
								self.scheduler.set_timesteps(__UpperCamelCase    ,			device=__UpperCamelCase)
								UpperCAmelCase_	,    UpperCAmelCase_		:      Any       	=					self.get_timesteps(__UpperCamelCase    ,			__UpperCamelCase    ,			__UpperCamelCase)
								UpperCAmelCase_		:      Any       	=					timesteps[:1].repeat(batch_size * num_images_per_prompt)
								UpperCAmelCase_	,    UpperCAmelCase_		:      Tuple       	=					downscale_height_and_width(__UpperCamelCase    ,			__UpperCamelCase    ,			self.movq_scale_factor)
								UpperCAmelCase_		:      Tuple       	=					self.prepare_latents(
								    __UpperCamelCase    ,			__UpperCamelCase    ,			__UpperCamelCase    ,			__UpperCamelCase    ,			image_embeds.dtype    ,			__UpperCamelCase    ,			__UpperCamelCase)
								for i, t in enumerate(self.progress_bar(__UpperCamelCase)):
									# expand the latents if we are doing classifier free guidance
									UpperCAmelCase_		:      Tuple       	=					torch.cat([latents] * 2) if do_classifier_free_guidance else latents

									UpperCAmelCase_		:      int       	=					{'image_embeds': image_embeds}
									UpperCAmelCase_		:      Any       	=					self.unet(
									    sample=__UpperCamelCase    ,			timestep=__UpperCamelCase    ,			encoder_hidden_states=__UpperCamelCase    ,			added_cond_kwargs=__UpperCamelCase    ,			return_dict=__UpperCamelCase    ,			)[0]

									if do_classifier_free_guidance:
										UpperCAmelCase_	,    UpperCAmelCase_		:      Optional[int]       	=					noise_pred.split(latents.shape[1]    ,			dim=1)
										UpperCAmelCase_	,    UpperCAmelCase_		:      Any       	=					noise_pred.chunk(2)
										UpperCAmelCase_	,    UpperCAmelCase_		:      Any       	=					variance_pred.chunk(2)
										UpperCAmelCase_		:      List[str]       	=					noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
										UpperCAmelCase_		:      int       	=					torch.cat([noise_pred, variance_pred_text]    ,			dim=1)

									if not (
									    hasattr(self.scheduler.config    ,			'variance_type')
									    and self.scheduler.config.variance_type in ["learned", "learned_range"]
									):
										UpperCAmelCase_	,    UpperCAmelCase_		:      Dict       	=					noise_pred.split(latents.shape[1]    ,			dim=1)

									# compute the previous noisy sample x_t -> x_t-1
									UpperCAmelCase_		:      Tuple       	=					self.scheduler.step(
									    __UpperCamelCase    ,			__UpperCamelCase    ,			__UpperCamelCase    ,			generator=__UpperCamelCase    ,			)[0]

								# post-processing
								UpperCAmelCase_		:      Tuple       	=					self.movq.decode(__UpperCamelCase    ,			force_not_quantize=__UpperCamelCase)['sample']

								if output_type not in ["pt", "np", "pil"]:
									raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""")

								if output_type in ["np", "pil"]:
									UpperCAmelCase_		:      Optional[Any]       	=					image * 0.5 + 0.5
									UpperCAmelCase_		:      Optional[int]       	=					image.clamp(0    ,			1)
									UpperCAmelCase_		:      Tuple       	=					image.cpu().permute(0    ,			2    ,			3    ,			1).float().numpy()

								if output_type == "pil":
									UpperCAmelCase_		:      List[str]       	=					self.numpy_to_pil(__UpperCamelCase)

								if not return_dict:
									return (image,)

								return ImagePipelineOutput(images=__UpperCamelCase)









'''simple docstring'''


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 ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


lowerCAmelCase__										= logging.get_logger(__name__)

# General docstring
lowerCAmelCase__										= "RegNetConfig"

# Base docstring
lowerCAmelCase__										= "facebook/regnet-y-040"
lowerCAmelCase__										= [1, 1088, 7, 7]

# Image classification docstring
lowerCAmelCase__										= "facebook/regnet-y-040"
lowerCAmelCase__										= "tabby, tabby cat"

lowerCAmelCase__										= [
    "facebook/regnet-y-040",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]



class 					lowercase						(  nn.Module ):


							def __init__(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case = 3    ,			_snake_case = 1    ,			_snake_case = 1    ,			_snake_case = "relu"    ,			)							->				int:
								super().__init__()
								UpperCAmelCase_		:      str       	=					nn.Convad(
								    _snake_case    ,			_snake_case    ,			kernel_size=_snake_case    ,			stride=_snake_case    ,			padding=kernel_size // 2    ,			groups=_snake_case    ,			bias=_snake_case    ,			)
								UpperCAmelCase_		:      List[Any]       	=					nn.BatchNormad(_snake_case)
								UpperCAmelCase_		:      Tuple       	=					ACTaFN[activation] if activation is not None else nn.Identity()





							def 						_snake_case							(			self    ,			_snake_case)							->				Tuple:
								UpperCAmelCase_		:      Optional[int]       	=					self.convolution(_snake_case)
								UpperCAmelCase_		:      int       	=					self.normalization(_snake_case)
								UpperCAmelCase_		:      Optional[int]       	=					self.activation(_snake_case)
								return hidden_state



class 					lowercase						(  nn.Module ):


							def __init__(			self    ,			_snake_case)							->				List[Any]:
								super().__init__()
								UpperCAmelCase_		:      Tuple       	=					RegNetConvLayer(
								    config.num_channels    ,			config.embedding_size    ,			kernel_size=3    ,			stride=2    ,			activation=config.hidden_act)
								UpperCAmelCase_		:      Optional[Any]       	=					config.num_channels





							def 						_snake_case							(			self    ,			_snake_case)							->				Dict:
								UpperCAmelCase_		:      List[Any]       	=					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_		:      Any       	=					self.embedder(_snake_case)
								return hidden_state



class 					lowercase						(  nn.Module ):


							def __init__(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case = 2)							->				Optional[Any]:
								super().__init__()
								UpperCAmelCase_		:      Any       	=					nn.Convad(_snake_case    ,			_snake_case    ,			kernel_size=1    ,			stride=_snake_case    ,			bias=_snake_case)
								UpperCAmelCase_		:      Optional[Any]       	=					nn.BatchNormad(_snake_case)





							def 						_snake_case							(			self    ,			_snake_case)							->				Tensor:
								UpperCAmelCase_		:      Optional[Any]       	=					self.convolution(_snake_case)
								UpperCAmelCase_		:      Dict       	=					self.normalization(_snake_case)
								return hidden_state



class 					lowercase						(  nn.Module ):


							def __init__(			self    ,			_snake_case    ,			_snake_case)							->				Any:
								super().__init__()

								UpperCAmelCase_		:      Tuple       	=					nn.AdaptiveAvgPoolad((1, 1))
								UpperCAmelCase_		:      int       	=					nn.Sequential(
								    nn.Convad(_snake_case    ,			_snake_case    ,			kernel_size=1)    ,			nn.ReLU()    ,			nn.Convad(_snake_case    ,			_snake_case    ,			kernel_size=1)    ,			nn.Sigmoid()    ,			)





							def 						_snake_case							(			self    ,			_snake_case)							->				Any:
								# b c h w -> b c 1 1
								UpperCAmelCase_		:      Union[str, Any]       	=					self.pooler(_snake_case)
								UpperCAmelCase_		:      Any       	=					self.attention(_snake_case)
								UpperCAmelCase_		:      Optional[Any]       	=					hidden_state * attention
								return hidden_state



class 					lowercase						(  nn.Module ):


							def __init__(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case = 1)							->				str:
								super().__init__()
								UpperCAmelCase_		:      Optional[Any]       	=					in_channels != out_channels or stride != 1
								UpperCAmelCase_		:      Any       	=					max(1    ,			out_channels // config.groups_width)
								UpperCAmelCase_		:      str       	=					(
								    RegNetShortCut(_snake_case    ,			_snake_case    ,			stride=_snake_case) if should_apply_shortcut else nn.Identity()
								)
								UpperCAmelCase_		:      Optional[int]       	=					nn.Sequential(
								    RegNetConvLayer(_snake_case    ,			_snake_case    ,			kernel_size=1    ,			activation=config.hidden_act)    ,			RegNetConvLayer(_snake_case    ,			_snake_case    ,			stride=_snake_case    ,			groups=_snake_case    ,			activation=config.hidden_act)    ,			RegNetConvLayer(_snake_case    ,			_snake_case    ,			kernel_size=1    ,			activation=_snake_case)    ,			)
								UpperCAmelCase_		:      int       	=					ACTaFN[config.hidden_act]





							def 						_snake_case							(			self    ,			_snake_case)							->				Union[str, Any]:
								UpperCAmelCase_		:      str       	=					hidden_state
								UpperCAmelCase_		:      List[Any]       	=					self.layer(_snake_case)
								UpperCAmelCase_		:      Dict       	=					self.shortcut(_snake_case)
								hidden_state += residual
								UpperCAmelCase_		:      Any       	=					self.activation(_snake_case)
								return hidden_state



class 					lowercase						(  nn.Module ):


							def __init__(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case = 1)							->				int:
								super().__init__()
								UpperCAmelCase_		:      List[Any]       	=					in_channels != out_channels or stride != 1
								UpperCAmelCase_		:      Optional[Any]       	=					max(1    ,			out_channels // config.groups_width)
								UpperCAmelCase_		:      Optional[int]       	=					(
								    RegNetShortCut(_snake_case    ,			_snake_case    ,			stride=_snake_case) if should_apply_shortcut else nn.Identity()
								)
								UpperCAmelCase_		:      Optional[Any]       	=					nn.Sequential(
								    RegNetConvLayer(_snake_case    ,			_snake_case    ,			kernel_size=1    ,			activation=config.hidden_act)    ,			RegNetConvLayer(_snake_case    ,			_snake_case    ,			stride=_snake_case    ,			groups=_snake_case    ,			activation=config.hidden_act)    ,			RegNetSELayer(_snake_case    ,			reduced_channels=int(round(in_channels / 4)))    ,			RegNetConvLayer(_snake_case    ,			_snake_case    ,			kernel_size=1    ,			activation=_snake_case)    ,			)
								UpperCAmelCase_		:      Any       	=					ACTaFN[config.hidden_act]





							def 						_snake_case							(			self    ,			_snake_case)							->				Union[str, Any]:
								UpperCAmelCase_		:      List[str]       	=					hidden_state
								UpperCAmelCase_		:      int       	=					self.layer(_snake_case)
								UpperCAmelCase_		:      Any       	=					self.shortcut(_snake_case)
								hidden_state += residual
								UpperCAmelCase_		:      Any       	=					self.activation(_snake_case)
								return hidden_state



class 					lowercase						(  nn.Module ):


							def __init__(			self    ,			_snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case = 2    ,			_snake_case = 2    ,			)							->				Optional[int]:
								super().__init__()

								UpperCAmelCase_		:      str       	=					RegNetXLayer if config.layer_type == 'x' else RegNetYLayer

								UpperCAmelCase_		:      Dict       	=					nn.Sequential(
								    # downsampling is done in the first layer with stride of 2
								    layer(
								        _snake_case    ,			_snake_case    ,			_snake_case    ,			stride=_snake_case    ,			)    ,			*[layer(_snake_case    ,			_snake_case    ,			_snake_case) for _ in range(depth - 1)]    ,			)





							def 						_snake_case							(			self    ,			_snake_case)							->				Dict:
								UpperCAmelCase_		:      Optional[Any]       	=					self.layers(_snake_case)
								return hidden_state



class 					lowercase						(  nn.Module ):


							def __init__(			self    ,			_snake_case)							->				List[Any]:
								super().__init__()
								UpperCAmelCase_		:      List[str]       	=					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(
								    RegNetStage(
								        _snake_case    ,			config.embedding_size    ,			config.hidden_sizes[0]    ,			stride=2 if config.downsample_in_first_stage else 1    ,			depth=config.depths[0]    ,			))
								UpperCAmelCase_		:      Dict       	=					zip(config.hidden_sizes    ,			config.hidden_sizes[1:])
								for (in_channels, out_channels), depth in zip(_snake_case    ,			config.depths[1:]):
									self.stages.append(RegNetStage(_snake_case    ,			_snake_case    ,			_snake_case    ,			depth=_snake_case))





							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case = False    ,			_snake_case = True)							->				BaseModelOutputWithNoAttention:
								UpperCAmelCase_		:      List[Any]       	=					() if output_hidden_states else None

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

									UpperCAmelCase_		:      Tuple       	=					stage_module(_snake_case)

								if output_hidden_states:
									UpperCAmelCase_		:      Union[str, Any]       	=					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=_snake_case    ,			hidden_states=_snake_case)



class 					lowercase						(  a_ ):
							_lowerCamelCase		:      str=   RegNetConfig
							_lowerCamelCase		:      Optional[int]=   "regnet"
							_lowerCamelCase		:      Union[str, Any]=   "pixel_values"
							_lowerCamelCase		:      List[str]=   True


							def 						_snake_case							(			self    ,			_snake_case)							->				List[Any]:
								if isinstance(_snake_case    ,			nn.Convad):
									nn.init.kaiming_normal_(module.weight    ,			mode='fan_out'    ,			nonlinearity='relu')
								elif isinstance(_snake_case    ,			(nn.BatchNormad, nn.GroupNorm)):
									nn.init.constant_(module.weight    ,			1)
									nn.init.constant_(module.bias    ,			0)





							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=False)							->				List[Any]:
								if isinstance(_snake_case    ,			_snake_case):
									UpperCAmelCase_		:      str       	=					value


lowerCAmelCase__										= 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 ([`RegNetConfig`]): 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"

lowerCAmelCase__										= 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 [`~file_utils.ModelOutput`] instead of a plain tuple.\n"



@add_start_docstrings(
    "The bare RegNet model outputting raw features without any specific head on top.",					a_,					)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class 					lowercase						(  a_ ):


							def __init__(			self    ,			_snake_case)							->				List[str]:
								super().__init__(_snake_case)
								UpperCAmelCase_		:      str       	=					config
								UpperCAmelCase_		:      Optional[int]       	=					RegNetEmbeddings(_snake_case)
								UpperCAmelCase_		:      int       	=					RegNetEncoder(_snake_case)
								UpperCAmelCase_		:      Any       	=					nn.AdaptiveAvgPoolad((1, 1))
								# Initialize weights and apply final processing
								self.post_init()





							@add_start_docstrings_to_model_forward(_snake_case)
							@add_code_sample_docstrings(
							    checkpoint=_CHECKPOINT_FOR_DOC    ,			output_type=_snake_case    ,			config_class=_CONFIG_FOR_DOC    ,			modality='vision'    ,			expected_output=_EXPECTED_OUTPUT_SHAPE    ,			)
							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case = None    ,			_snake_case = None)							->				BaseModelOutputWithPoolingAndNoAttention:
								UpperCAmelCase_		:      List[Any]       	=					(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								UpperCAmelCase_		:      Optional[Any]       	=					return_dict if return_dict is not None else self.config.use_return_dict

								UpperCAmelCase_		:      int       	=					self.embedder(_snake_case)

								UpperCAmelCase_		:      str       	=					self.encoder(
								    _snake_case    ,			output_hidden_states=_snake_case    ,			return_dict=_snake_case)

								UpperCAmelCase_		:      List[Any]       	=					encoder_outputs[0]

								UpperCAmelCase_		:      str       	=					self.pooler(_snake_case)

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

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



@add_start_docstrings(
    "\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    ",					a_,					)
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class 					lowercase						(  a_ ):


							def __init__(			self    ,			_snake_case)							->				Union[str, Any]:
								super().__init__(_snake_case)
								UpperCAmelCase_		:      List[str]       	=					config.num_labels
								UpperCAmelCase_		:      Optional[int]       	=					RegNetModel(_snake_case)
								# classification head
								UpperCAmelCase_		:      Optional[Any]       	=					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(_snake_case)
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT    ,			output_type=_snake_case    ,			config_class=_CONFIG_FOR_DOC    ,			expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT    ,			)
							def 						_snake_case							(			self    ,			_snake_case = None    ,			_snake_case = None    ,			_snake_case = None    ,			_snake_case = None    ,			)							->				ImageClassifierOutputWithNoAttention:
								UpperCAmelCase_		:      str       	=					return_dict if return_dict is not None else self.config.use_return_dict

								UpperCAmelCase_		:      Optional[Any]       	=					self.regnet(_snake_case    ,			output_hidden_states=_snake_case    ,			return_dict=_snake_case)

								UpperCAmelCase_		:      Dict       	=					outputs.pooler_output if return_dict else outputs[1]

								UpperCAmelCase_		:      int       	=					self.classifier(_snake_case)

								UpperCAmelCase_		:      List[Any]       	=					None

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

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

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






