






from typing import List, Optional, Union

import torch
from transformers import (
    XLMRobertaTokenizer,
)

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


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

_a      	=  '''
    Examples:
        ```py
        >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline
        >>> import torch

        >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")
        >>> pipe_prior.to("cuda")

        >>> prompt = "red cat, 4k photo"
        >>> out = pipe_prior(prompt)
        >>> image_emb = out.image_embeds
        >>> negative_image_emb = out.negative_image_embeds

        >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")
        >>> pipe.to("cuda")

        >>> image = pipe(
        ...     prompt,
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=negative_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=100,
        ... ).images

        >>> image[0].save("cat.png")
        ```
'''


def __A    (      __lowerCAmelCase ,		__lowerCAmelCase ,		__lowerCAmelCase=8	)->  List[str]:





						"""simple docstring"""



						_UpperCAmelCase									=			h // scale_factor**2
						if h % scale_factor**2 != 0:
												new_h += 1
						_UpperCAmelCase									=			w // scale_factor**2
						if w % scale_factor**2 != 0:
												new_w += 1
						return new_h * scale_factor, new_w * scale_factor





class __lowerCamelCase (      __UpperCamelCase):





	"""simple docstring"""






	def __init__(							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    ):
							"""simple docstring"""







							super().__init__()

							self.register_modules(
							    text_encoder=lowerCAmelCase__       ,    tokenizer=lowerCAmelCase__       ,    unet=lowerCAmelCase__       ,    scheduler=lowerCAmelCase__       ,    movq=lowerCAmelCase__       ,    )
							_UpperCAmelCase									=			2 ** (len(self.movq.config.block_out_channels    ) - 1)

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							if latents is None:
													_UpperCAmelCase									=			randn_tensor(lowerCAmelCase__       ,    generator=lowerCAmelCase__       ,    device=lowerCAmelCase__       ,    dtype=lowerCAmelCase__    )
							else:
													if latents.shape != shape:
																			raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""    )
													_UpperCAmelCase									=			latents.to(lowerCAmelCase__    )

							_UpperCAmelCase									=			latents * scheduler.init_noise_sigma
							return latents

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase=None       ,    ):
							"""simple docstring"""







							_UpperCAmelCase									=			len(lowerCAmelCase__    ) if isinstance(lowerCAmelCase__       ,    lowerCAmelCase__    ) else 1
							# get prompt text embeddings
							_UpperCAmelCase									=			self.tokenizer(
							    lowerCAmelCase__       ,    padding='max_length'       ,    truncation=lowerCAmelCase__       ,    max_length=77       ,    return_attention_mask=lowerCAmelCase__       ,    add_special_tokens=lowerCAmelCase__       ,    return_tensors='pt'       ,    )

							_UpperCAmelCase									=			text_inputs.input_ids
							_UpperCAmelCase									=			self.tokenizer(lowerCAmelCase__       ,    padding='longest'       ,    return_tensors='pt'    ).input_ids

							if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase__       ,    lowerCAmelCase__    ):
													_UpperCAmelCase									=			self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]    )
													logger.warning(
													    'The following part of your input was truncated because CLIP can only handle sequences up to'
													    F""" {self.tokenizer.model_max_length} tokens: {removed_text}"""    )

							_UpperCAmelCase									=			text_input_ids.to(lowerCAmelCase__    )
							_UpperCAmelCase									=			text_inputs.attention_mask.to(lowerCAmelCase__    )

							_UpperCAmelCase									=			self.text_encoder(
							    input_ids=lowerCAmelCase__       ,    attention_mask=lowerCAmelCase__    )

							_UpperCAmelCase									=			prompt_embeds.repeat_interleave(lowerCAmelCase__       ,    dim=0    )
							_UpperCAmelCase									=			text_encoder_hidden_states.repeat_interleave(lowerCAmelCase__       ,    dim=0    )
							_UpperCAmelCase									=			text_mask.repeat_interleave(lowerCAmelCase__       ,    dim=0    )

							if do_classifier_free_guidance:
													_UpperCAmelCase									=			42
													if negative_prompt is None:
																			_UpperCAmelCase									=			[''] * batch_size
													elif type(lowerCAmelCase__    ) is not type(lowerCAmelCase__    ):
																			raise TypeError(
																			    F"""`negative_prompt` should be the same type to `prompt`, but got {type(lowerCAmelCase__    )} !="""
																			    F""" {type(lowerCAmelCase__    )}."""    )
													elif isinstance(lowerCAmelCase__       ,    lowerCAmelCase__    ):
																			_UpperCAmelCase									=			[negative_prompt]
													elif batch_size != len(lowerCAmelCase__    ):
																			raise ValueError(
																			    F"""`negative_prompt`: {negative_prompt} has batch size {len(lowerCAmelCase__    )}, but `prompt`:"""
																			    F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
																			    ' the batch size of `prompt`.'    )
													else:
																			_UpperCAmelCase									=			negative_prompt

													_UpperCAmelCase									=			self.tokenizer(
													    lowerCAmelCase__       ,    padding='max_length'       ,    max_length=77       ,    truncation=lowerCAmelCase__       ,    return_attention_mask=lowerCAmelCase__       ,    add_special_tokens=lowerCAmelCase__       ,    return_tensors='pt'       ,    )
													_UpperCAmelCase									=			uncond_input.input_ids.to(lowerCAmelCase__    )
													_UpperCAmelCase									=			uncond_input.attention_mask.to(lowerCAmelCase__    )

													_UpperCAmelCase									=			self.text_encoder(
													    input_ids=lowerCAmelCase__       ,    attention_mask=lowerCAmelCase__    )

													# duplicate unconditional embeddings for each generation per prompt, using mps friendly method

													_UpperCAmelCase									=			negative_prompt_embeds.shape[1]
													_UpperCAmelCase									=			negative_prompt_embeds.repeat(1       ,    lowerCAmelCase__    )
													_UpperCAmelCase									=			negative_prompt_embeds.view(batch_size * num_images_per_prompt       ,    lowerCAmelCase__    )

													_UpperCAmelCase									=			uncond_text_encoder_hidden_states.shape[1]
													_UpperCAmelCase									=			uncond_text_encoder_hidden_states.repeat(1       ,    lowerCAmelCase__       ,    1    )
													_UpperCAmelCase									=			uncond_text_encoder_hidden_states.view(
													    batch_size * num_images_per_prompt       ,    lowerCAmelCase__       ,    -1    )
													_UpperCAmelCase									=			uncond_text_mask.repeat_interleave(lowerCAmelCase__       ,    dim=0    )

													# done duplicates

													# For classifier free guidance, we need to do two forward passes.
													# Here we concatenate the unconditional and text embeddings into a single batch
													# to avoid doing two forward passes
													_UpperCAmelCase									=			torch.cat([negative_prompt_embeds, prompt_embeds]    )
													_UpperCAmelCase									=			torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]    )

													_UpperCAmelCase									=			torch.cat([uncond_text_mask, text_mask]    )

							return prompt_embeds, text_encoder_hidden_states, text_mask

	def        UpperCamelCase    (							self       ,    UpperCAmelCase=0    ):
							"""simple docstring"""







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

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

							_UpperCAmelCase									=			[
							    self.unet,
							    self.text_encoder,
							    self.movq,
							]
							for cpu_offloaded_model in models:
													if cpu_offloaded_model is not None:
																			cpu_offload(lowerCAmelCase__       ,    lowerCAmelCase__    )

	def        UpperCamelCase    (							self       ,    UpperCAmelCase=0    ):
							"""simple docstring"""







							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									=			torch.device(F"""cuda:{gpu_id}"""    )

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

							_UpperCAmelCase									=			None
							for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
													_UpperCAmelCase									=			cpu_offload_with_hook(lowerCAmelCase__       ,    lowerCAmelCase__       ,    prev_module_hook=lowerCAmelCase__    )

							if self.safety_checker is not None:
													_UpperCAmelCase									=			cpu_offload_with_hook(self.safety_checker       ,    lowerCAmelCase__       ,    prev_module_hook=lowerCAmelCase__    )

							# We'll offload the last model manually.
							_UpperCAmelCase									=			hook

	@property
	# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							if not hasattr(self.unet       ,    '_hf_hook'    ):
													return self.device
							for module in self.unet.modules():
													if (
													    hasattr(lowerCAmelCase__       ,    '_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(lowerCAmelCase__    )
	def __call__(							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase = None       ,    UpperCAmelCase = 512       ,    UpperCAmelCase = 512       ,    UpperCAmelCase = 100       ,    UpperCAmelCase = 4.0       ,    UpperCAmelCase = 1       ,    UpperCAmelCase = None       ,    UpperCAmelCase = None       ,    UpperCAmelCase = "pil"       ,    UpperCAmelCase = True       ,    ):
							"""simple docstring"""







							if isinstance(lowerCAmelCase__       ,    lowerCAmelCase__    ):
													_UpperCAmelCase									=			1
							elif isinstance(lowerCAmelCase__       ,    lowerCAmelCase__    ):
													_UpperCAmelCase									=			len(lowerCAmelCase__    )
							else:
													raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase__    )}"""    )

							_UpperCAmelCase									=			self._execution_device

							_UpperCAmelCase									=			batch_size * num_images_per_prompt
							_UpperCAmelCase									=			guidance_scale > 1.0

							_UpperCAmelCase									=			self._encode_prompt(
							    lowerCAmelCase__       ,    lowerCAmelCase__       ,    lowerCAmelCase__       ,    lowerCAmelCase__       ,    lowerCAmelCase__    )

							if isinstance(lowerCAmelCase__       ,    lowerCAmelCase__    ):
													_UpperCAmelCase									=			torch.cat(lowerCAmelCase__       ,    dim=0    )
							if isinstance(lowerCAmelCase__       ,    lowerCAmelCase__    ):
													_UpperCAmelCase									=			torch.cat(lowerCAmelCase__       ,    dim=0    )

							if do_classifier_free_guidance:
													_UpperCAmelCase									=			image_embeds.repeat_interleave(lowerCAmelCase__       ,    dim=0    )
													_UpperCAmelCase									=			negative_image_embeds.repeat_interleave(lowerCAmelCase__       ,    dim=0    )

							_UpperCAmelCase									=			torch.cat([negative_image_embeds, image_embeds]       ,    dim=0    ).to(
							    dtype=prompt_embeds.dtype       ,    device=lowerCAmelCase__    )

							self.scheduler.set_timesteps(lowerCAmelCase__       ,    device=lowerCAmelCase__    )
							_UpperCAmelCase									=			self.scheduler.timesteps

							_UpperCAmelCase									=			self.unet.config.in_channels

							_UpperCAmelCase									=			get_new_h_w(lowerCAmelCase__       ,    lowerCAmelCase__       ,    self.movq_scale_factor    )

							# create initial latent
							_UpperCAmelCase									=			self.prepare_latents(
							    (batch_size, num_channels_latents, height, width)       ,    text_encoder_hidden_states.dtype       ,    lowerCAmelCase__       ,    lowerCAmelCase__       ,    lowerCAmelCase__       ,    self.scheduler       ,    )

							for i, t in enumerate(self.progress_bar(lowerCAmelCase__    )    ):
													# expand the latents if we are doing classifier free guidance
													_UpperCAmelCase									=			torch.cat([latents] * 2    ) if do_classifier_free_guidance else latents

													_UpperCAmelCase									=			{'text_embeds': prompt_embeds, 'image_embeds': image_embeds}
													_UpperCAmelCase									=			self.unet(
													    sample=lowerCAmelCase__       ,    timestep=lowerCAmelCase__       ,    encoder_hidden_states=lowerCAmelCase__       ,    added_cond_kwargs=lowerCAmelCase__       ,    return_dict=lowerCAmelCase__       ,    )[0]

													if do_classifier_free_guidance:
																			_UpperCAmelCase									=			noise_pred.split(latents.shape[1]       ,    dim=1    )
																			_UpperCAmelCase									=			noise_pred.chunk(2    )
																			_UpperCAmelCase									=			variance_pred.chunk(2    )
																			_UpperCAmelCase									=			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																			_UpperCAmelCase									=			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									=			noise_pred.split(latents.shape[1]       ,    dim=1    )

													# compute the previous noisy sample x_t -> x_t-1
													_UpperCAmelCase									=			self.scheduler.step(
													    lowerCAmelCase__       ,    lowerCAmelCase__       ,    lowerCAmelCase__       ,    generator=lowerCAmelCase__       ,    ).prev_sample
							# post-processing
							_UpperCAmelCase									=			self.movq.decode(lowerCAmelCase__       ,    force_not_quantize=lowerCAmelCase__    )['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									=			image * 0.5 + 0.5
													_UpperCAmelCase									=			image.clamp(0       ,    1    )
													_UpperCAmelCase									=			image.cpu().permute(0       ,    2       ,    3       ,    1    ).float().numpy()

							if output_type == "pil":
													_UpperCAmelCase									=			self.numpy_to_pil(lowerCAmelCase__    )

							if not return_dict:
													return (image,)

							return ImagePipelineOutput(images=lowerCAmelCase__    )




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, 10_88, 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   __a			(    nn.Module      ):
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ = 3				, lowerCAmelCase__ = 1				, lowerCAmelCase__ = 1				, lowerCAmelCase__ = "relu"				, )					->				Optional[Any]:




        '''simple docstring'''
        super().__init__()
        lowercase__:   Any  			=   nn.Convad(
            lowerCAmelCase__				, lowerCAmelCase__				, kernel_size=lowerCAmelCase__				, stride=lowerCAmelCase__				, padding=kernel_size // 2				, groups=lowerCAmelCase__				, bias=lowerCAmelCase__				, )
        lowercase__:   str  			=   nn.BatchNormad(lowerCAmelCase__ )
        lowercase__:   Union[str, Any]  			=   ACTaFN[activation] if activation is not None else nn.Identity()
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				Dict:




        '''simple docstring'''
        lowercase__:   List[str]  			=   self.convolution(lowerCAmelCase__ )
        lowercase__:   Optional[Any]  			=   self.normalization(lowerCAmelCase__ )
        lowercase__:   Union[str, Any]  			=   self.activation(lowerCAmelCase__ )
        return hidden_state





class   __a			(    nn.Module      ):
 def __init__(   self				, lowerCAmelCase__ )					->				Union[str, Any]:




        '''simple docstring'''
        super().__init__()
        lowercase__:   Dict  			=   RegNetConvLayer(
            config.num_channels				, config.embedding_size				, kernel_size=3				, stride=2				, activation=config.hidden_act )
        lowercase__:   Dict  			=   config.num_channels
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   Tuple  			=   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.' )
        lowercase__:   Optional[int]  			=   self.embedder(lowerCAmelCase__ )
        return hidden_state





class   __a			(    nn.Module      ):
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ = 2 )					->				Optional[Any]:




        '''simple docstring'''
        super().__init__()
        lowercase__:   Optional[Any]  			=   nn.Convad(lowerCAmelCase__				, lowerCAmelCase__				, kernel_size=1				, stride=lowerCAmelCase__				, bias=lowerCAmelCase__ )
        lowercase__:   Union[str, Any]  			=   nn.BatchNormad(lowerCAmelCase__ )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				Tensor:




        '''simple docstring'''
        lowercase__:   Any  			=   self.convolution(lowerCAmelCase__ )
        lowercase__:   str  			=   self.normalization(lowerCAmelCase__ )
        return hidden_state





class   __a			(    nn.Module      ):
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__ )					->				List[str]:




        '''simple docstring'''
        super().__init__()

        lowercase__:   Any  			=   nn.AdaptiveAvgPoolad((1, 1) )
        lowercase__:   str  			=   nn.Sequential(
            nn.Convad(lowerCAmelCase__				, lowerCAmelCase__				, kernel_size=1 )				, nn.ReLU()				, nn.Convad(lowerCAmelCase__				, lowerCAmelCase__				, kernel_size=1 )				, nn.Sigmoid()				, )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				Optional[Any]:




        '''simple docstring'''
        # b c h w -> b c 1 1
        lowercase__:   str  			=   self.pooler(lowerCAmelCase__ )
        lowercase__:   List[str]  			=   self.attention(lowerCAmelCase__ )
        lowercase__:   List[Any]  			=   hidden_state * attention
        return hidden_state





class   __a			(    nn.Module      ):
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ = 1 )					->				Dict:




        '''simple docstring'''
        super().__init__()
        lowercase__:   str  			=   in_channels != out_channels or stride != 1
        lowercase__:   Optional[int]  			=   max(1				, out_channels // config.groups_width )
        lowercase__:   Union[str, Any]  			=   (
            RegNetShortCut(lowerCAmelCase__				, lowerCAmelCase__				, stride=lowerCAmelCase__ ) if should_apply_shortcut else nn.Identity()
        )
        lowercase__:   Dict  			=   nn.Sequential(
            RegNetConvLayer(lowerCAmelCase__				, lowerCAmelCase__				, kernel_size=1				, activation=config.hidden_act )				, RegNetConvLayer(lowerCAmelCase__				, lowerCAmelCase__				, stride=lowerCAmelCase__				, groups=lowerCAmelCase__				, activation=config.hidden_act )				, RegNetConvLayer(lowerCAmelCase__				, lowerCAmelCase__				, kernel_size=1				, activation=lowerCAmelCase__ )				, )
        lowercase__:   Tuple  			=   ACTaFN[config.hidden_act]
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   Dict  			=   hidden_state
        lowercase__:   Union[str, Any]  			=   self.layer(lowerCAmelCase__ )
        lowercase__:   int  			=   self.shortcut(lowerCAmelCase__ )
        hidden_state += residual
        lowercase__:   Optional[int]  			=   self.activation(lowerCAmelCase__ )
        return hidden_state





class   __a			(    nn.Module      ):
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ = 1 )					->				Dict:




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




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   hidden_state
        lowercase__:   Optional[int]  			=   self.layer(lowerCAmelCase__ )
        lowercase__:   str  			=   self.shortcut(lowerCAmelCase__ )
        hidden_state += residual
        lowercase__:   Optional[int]  			=   self.activation(lowerCAmelCase__ )
        return hidden_state





class   __a			(    nn.Module      ):
 def __init__(   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ = 2				, lowerCAmelCase__ = 2				, )					->				Tuple:




        '''simple docstring'''
        super().__init__()

        lowercase__:   Optional[int]  			=   RegNetXLayer if config.layer_type == 'x' else RegNetYLayer

        lowercase__:   str  			=   nn.Sequential(
            # downsampling is done in the first layer with stride of 2
            layer(
                lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, stride=lowerCAmelCase__				, )				, *[layer(lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ ) for _ in range(depth - 1 )]				, )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				Optional[Any]:




        '''simple docstring'''
        lowercase__:   str  			=   self.layers(lowerCAmelCase__ )
        return hidden_state





class   __a			(    nn.Module      ):
 def __init__(   self				, lowerCAmelCase__ )					->				Dict:




        '''simple docstring'''
        super().__init__()
        lowercase__:   int  			=   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(
                lowerCAmelCase__				, config.embedding_size				, config.hidden_sizes[0]				, stride=2 if config.downsample_in_first_stage else 1				, depth=config.depths[0]				, ) )
        lowercase__:   int  			=   zip(config.hidden_sizes				, config.hidden_sizes[1:] )
        for (in_channels, out_channels), depth in zip(lowerCAmelCase__				, config.depths[1:] ):
               self.stages.append(RegNetStage(lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__				, depth=lowerCAmelCase__ ) )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__ = False				, lowerCAmelCase__ = True )					->				BaseModelOutputWithNoAttention:




        '''simple docstring'''
        lowercase__:   List[str]  			=   () if output_hidden_states else None

        for stage_module in self.stages:
               if output_hidden_states:
                      lowercase__:   Optional[Any]  			=   hidden_states + (hidden_state,)

               lowercase__:   List[Any]  			=   stage_module(lowerCAmelCase__ )

        if output_hidden_states:
               lowercase__:   Optional[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=lowerCAmelCase__				, hidden_states=lowerCAmelCase__ )





class   __a			(    __UpperCamelCase      ):
 __lowercase :							Dict        = RegNetConfig
 __lowercase :							Dict        = 'regnet'
 __lowercase :							str        = 'pixel_values'
 __lowercase :							List[str]        = True
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ )					->				List[str]:




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




        '''simple docstring'''
        if isinstance(lowerCAmelCase__				, lowerCAmelCase__ ):
               lowercase__:   Any  			=   value





__lowerCAmelCase		       =							r'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

__lowerCAmelCase		       =							r'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
'''





@add_start_docstrings(
    'The bare RegNet model outputting raw features without any specific head on top.'       ,       __UpperCamelCase       ,       )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class   __a			(    __UpperCamelCase      ):
 def __init__(   self				, lowerCAmelCase__ )					->				List[str]:




        '''simple docstring'''
        super().__init__(lowerCAmelCase__ )
        lowercase__:   Tuple  			=   config
        lowercase__:   List[str]  			=   RegNetEmbeddings(lowerCAmelCase__ )
        lowercase__:   Optional[int]  			=   RegNetEncoder(lowerCAmelCase__ )
        lowercase__:   Optional[Any]  			=   nn.AdaptiveAvgPoolad((1, 1) )
        # Initialize weights and apply final processing
        self.post_init()
 @add_start_docstrings_to_model_forward(lowerCAmelCase__ )
 @add_code_sample_docstrings(
     checkpoint=_CHECKPOINT_FOR_DOC				, output_type=lowerCAmelCase__				, config_class=_CONFIG_FOR_DOC				, modality='vision'				, expected_output=_EXPECTED_OUTPUT_SHAPE				, )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__ = None				, lowerCAmelCase__ = None )					->				BaseModelOutputWithPoolingAndNoAttention:




        '''simple docstring'''
        lowercase__:   List[Any]  			=   (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        lowercase__:   Union[str, Any]  			=   return_dict if return_dict is not None else self.config.use_return_dict

        lowercase__:   Any  			=   self.embedder(lowerCAmelCase__ )

        lowercase__:   List[Any]  			=   self.encoder(
            lowerCAmelCase__				, output_hidden_states=lowerCAmelCase__				, return_dict=lowerCAmelCase__ )

        lowercase__:   Optional[Any]  			=   encoder_outputs[0]

        lowercase__:   Optional[int]  			=   self.pooler(lowerCAmelCase__ )

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

        return BaseModelOutputWithPoolingAndNoAttention(
            last_hidden_state=lowerCAmelCase__				, pooler_output=lowerCAmelCase__				, 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    '       ,       __UpperCamelCase       ,       )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class   __a			(    __UpperCamelCase      ):
 def __init__(   self				, lowerCAmelCase__ )					->				str:




        '''simple docstring'''
        super().__init__(lowerCAmelCase__ )
        lowercase__:   Dict  			=   config.num_labels
        lowercase__:   Dict  			=   RegNetModel(lowerCAmelCase__ )
        # classification head
        lowercase__:   str  			=   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(lowerCAmelCase__ )
 @add_code_sample_docstrings(
     checkpoint=_IMAGE_CLASS_CHECKPOINT				, output_type=lowerCAmelCase__				, config_class=_CONFIG_FOR_DOC				, expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT				, )
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__ = None				, lowerCAmelCase__ = None				, lowerCAmelCase__ = None				, lowerCAmelCase__ = None				, )					->				ImageClassifierOutputWithNoAttention:




        '''simple docstring'''
        lowercase__:   str  			=   return_dict if return_dict is not None else self.config.use_return_dict

        lowercase__:   Optional[int]  			=   self.regnet(lowerCAmelCase__				, output_hidden_states=lowerCAmelCase__				, return_dict=lowerCAmelCase__ )

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

        lowercase__:   List[str]  			=   self.classifier(lowerCAmelCase__ )

        lowercase__:   Optional[Any]  			=   None

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

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

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


