



import argparse
import os.path as osp
import re

import torch
from safetensors.torch import load_file, save_file


# =================#
# UNet Conversion #
# =================#

_lowerCAmelCase	:   Any    =   [
    # (stable-diffusion, HF Diffusers)
    ("time_embed.0.weight", "time_embedding.linear_1.weight"),
    ("time_embed.0.bias", "time_embedding.linear_1.bias"),
    ("time_embed.2.weight", "time_embedding.linear_2.weight"),
    ("time_embed.2.bias", "time_embedding.linear_2.bias"),
    ("input_blocks.0.0.weight", "conv_in.weight"),
    ("input_blocks.0.0.bias", "conv_in.bias"),
    ("out.0.weight", "conv_norm_out.weight"),
    ("out.0.bias", "conv_norm_out.bias"),
    ("out.2.weight", "conv_out.weight"),
    ("out.2.bias", "conv_out.bias"),
]

_lowerCAmelCase	:   List[Any]    =   [
    # (stable-diffusion, HF Diffusers)
    ("in_layers.0", "norm1"),
    ("in_layers.2", "conv1"),
    ("out_layers.0", "norm2"),
    ("out_layers.3", "conv2"),
    ("emb_layers.1", "time_emb_proj"),
    ("skip_connection", "conv_shortcut"),
]

_lowerCAmelCase	:   Dict    =   []
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
	# loop over downblocks/upblocks

	for j in range(2):
		# loop over resnets/attentions for downblocks
		_lowerCAmelCase	:   Any    =   f"""down_blocks.{i}.resnets.{j}."""
		_lowerCAmelCase	:   Dict    =   f"""input_blocks.{3*i + j + 1}.0."""
		unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))

		if i < 3:
			# no attention layers in down_blocks.3
			_lowerCAmelCase	:   int    =   f"""down_blocks.{i}.attentions.{j}."""
			_lowerCAmelCase	:   Any    =   f"""input_blocks.{3*i + j + 1}.1."""
			unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))

	for j in range(3):
		# loop over resnets/attentions for upblocks
		_lowerCAmelCase	:   Tuple    =   f"""up_blocks.{i}.resnets.{j}."""
		_lowerCAmelCase	:   Optional[Any]    =   f"""output_blocks.{3*i + j}.0."""
		unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))

		if i > 0:
			# no attention layers in up_blocks.0
			_lowerCAmelCase	:   Any    =   f"""up_blocks.{i}.attentions.{j}."""
			_lowerCAmelCase	:   List[Any]    =   f"""output_blocks.{3*i + j}.1."""
			unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))

	if i < 3:
		# no downsample in down_blocks.3
		_lowerCAmelCase	:   Dict    =   f"""down_blocks.{i}.downsamplers.0.conv."""
		_lowerCAmelCase	:   int    =   f"""input_blocks.{3*(i+1)}.0.op."""
		unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))

		# no upsample in up_blocks.3
		_lowerCAmelCase	:   Optional[Any]    =   f"""up_blocks.{i}.upsamplers.0."""
		_lowerCAmelCase	:   Union[str, Any]    =   f"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}."""
		unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))

_lowerCAmelCase	:   Optional[Any]    =   "mid_block.attentions.0."
_lowerCAmelCase	:   List[Any]    =   "middle_block.1."
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))

for j in range(2):
	_lowerCAmelCase	:   str    =   f"""mid_block.resnets.{j}."""
	_lowerCAmelCase	:   Dict    =   f"""middle_block.{2*j}."""
	unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))







def     UpperCAmelCase_		(					snake_case__					)	->     Optional[int]:



				"""simple docstring"""





				lowerCAmelCase__		  =  {k: k for k in unet_state_dict.keys()}
				for sd_name, hf_name in unet_conversion_map:
								lowerCAmelCase__		  =  sd_name
				for k, v in mapping.items():
								if "resnets" in k:
												for sd_part, hf_part in unet_conversion_map_resnet:
																lowerCAmelCase__		  =  v.replace(snake_case__    ,			snake_case__					)
												lowerCAmelCase__		  =  v
				for k, v in mapping.items():
								for sd_part, hf_part in unet_conversion_map_layer:
												lowerCAmelCase__		  =  v.replace(snake_case__    ,			snake_case__					)
								lowerCAmelCase__		  =  v
				lowerCAmelCase__		  =  {v: unet_state_dict[k] for k, v in mapping.items()}
				return new_state_dict


# ================#
# VAE Conversion #
# ================#

_lowerCAmelCase	:   Optional[Any]    =   [
    # (stable-diffusion, HF Diffusers)
    ("nin_shortcut", "conv_shortcut"),
    ("norm_out", "conv_norm_out"),
    ("mid.attn_1.", "mid_block.attentions.0."),
]

for i in range(4):
	# down_blocks have two resnets
	for j in range(2):
		_lowerCAmelCase	:   Union[str, Any]    =   f"""encoder.down_blocks.{i}.resnets.{j}."""
		_lowerCAmelCase	:   List[Any]    =   f"""encoder.down.{i}.block.{j}."""
		vae_conversion_map.append((sd_down_prefix, hf_down_prefix))

	if i < 3:
		_lowerCAmelCase	:   Union[str, Any]    =   f"""down_blocks.{i}.downsamplers.0."""
		_lowerCAmelCase	:   Optional[Any]    =   f"""down.{i}.downsample."""
		vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))

		_lowerCAmelCase	:   List[str]    =   f"""up_blocks.{i}.upsamplers.0."""
		_lowerCAmelCase	:   Optional[int]    =   f"""up.{3-i}.upsample."""
		vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))

	# up_blocks have three resnets
	# also, up blocks in hf are numbered in reverse from sd
	for j in range(3):
		_lowerCAmelCase	:   Optional[Any]    =   f"""decoder.up_blocks.{i}.resnets.{j}."""
		_lowerCAmelCase	:   str    =   f"""decoder.up.{3-i}.block.{j}."""
		vae_conversion_map.append((sd_up_prefix, hf_up_prefix))

# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
	_lowerCAmelCase	:   Union[str, Any]    =   f"""mid_block.resnets.{i}."""
	_lowerCAmelCase	:   int    =   f"""mid.block_{i+1}."""
	vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))


_lowerCAmelCase	:   Optional[Any]    =   [
    # (stable-diffusion, HF Diffusers)
    ("norm.", "group_norm."),
    ("q.", "query."),
    ("k.", "key."),
    ("v.", "value."),
    ("proj_out.", "proj_attn."),
]







def     UpperCAmelCase_		(					snake_case__					)	->     Optional[int]:



				"""simple docstring"""





				return w.reshape(*w.shape    ,			1    ,			1					)







def     UpperCAmelCase_		(					snake_case__					)	->     Optional[int]:



				"""simple docstring"""





				lowerCAmelCase__		  =  {k: k for k in vae_state_dict.keys()}
				for k, v in mapping.items():
								for sd_part, hf_part in vae_conversion_map:
												lowerCAmelCase__		  =  v.replace(snake_case__    ,			snake_case__					)
								lowerCAmelCase__		  =  v
				for k, v in mapping.items():
								if "attentions" in k:
												for sd_part, hf_part in vae_conversion_map_attn:
																lowerCAmelCase__		  =  v.replace(snake_case__    ,			snake_case__					)
												lowerCAmelCase__		  =  v
				lowerCAmelCase__		  =  {v: vae_state_dict[k] for k, v in mapping.items()}
				lowerCAmelCase__		  =  ['q', 'k', 'v', 'proj_out']
				for k, v in new_state_dict.items():
								for weight_name in weights_to_convert:
												if f'mid.attn_1.{weight_name}.weight' in k:
																print(f'Reshaping {k} for SD format'					)
																lowerCAmelCase__		  =  reshape_weight_for_sd(snake_case__					)
				return new_state_dict


# =========================#
# Text Encoder Conversion #
# =========================#


_lowerCAmelCase	:   Dict    =   [
    # (stable-diffusion, HF Diffusers)
    ("resblocks.", "text_model.encoder.layers."),
    ("ln_1", "layer_norm1"),
    ("ln_2", "layer_norm2"),
    (".c_fc.", ".fc1."),
    (".c_proj.", ".fc2."),
    (".attn", ".self_attn"),
    ("ln_final.", "transformer.text_model.final_layer_norm."),
    ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
    ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
]
_lowerCAmelCase	:   str    =   {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
_lowerCAmelCase	:   Dict    =   re.compile("|".join(protected.keys()))

# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
_lowerCAmelCase	:   Dict    =   {"q": 0, "k": 1, "v": 2}







def     UpperCAmelCase_		(					snake_case__					)	->     Dict:



				"""simple docstring"""





				lowerCAmelCase__		  =  {}
				lowerCAmelCase__		  =  {}
				lowerCAmelCase__		  =  {}
				for k, v in text_enc_dict.items():
								if (
								    k.endswith('.self_attn.q_proj.weight'					)
								    or k.endswith('.self_attn.k_proj.weight'					)
								    or k.endswith('.self_attn.v_proj.weight'					)
								):
												lowerCAmelCase__		  =  k[: -len('.q_proj.weight'					)]
												lowerCAmelCase__		  =  k[-len('q_proj.weight'					)]
												if k_pre not in capture_qkv_weight:
																lowerCAmelCase__		  =  [None, None, None]
												lowerCAmelCase__		  =  v
												continue

								if (
								    k.endswith('.self_attn.q_proj.bias'					)
								    or k.endswith('.self_attn.k_proj.bias'					)
								    or k.endswith('.self_attn.v_proj.bias'					)
								):
												lowerCAmelCase__		  =  k[: -len('.q_proj.bias'					)]
												lowerCAmelCase__		  =  k[-len('q_proj.bias'					)]
												if k_pre not in capture_qkv_bias:
																lowerCAmelCase__		  =  [None, None, None]
												lowerCAmelCase__		  =  v
												continue

								lowerCAmelCase__		  =  textenc_pattern.sub(lambda snake_case__					: protected[re.escape(m.group(0					)					)]    ,			snake_case__					)
								lowerCAmelCase__		  =  v

				for k_pre, tensors in capture_qkv_weight.items():
								if None in tensors:
												raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing'					)
								lowerCAmelCase__		  =  textenc_pattern.sub(lambda snake_case__					: protected[re.escape(m.group(0					)					)]    ,			snake_case__					)
								lowerCAmelCase__		  =  torch.cat(snake_case__					)

				for k_pre, tensors in capture_qkv_bias.items():
								if None in tensors:
												raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing'					)
								lowerCAmelCase__		  =  textenc_pattern.sub(lambda snake_case__					: protected[re.escape(m.group(0					)					)]    ,			snake_case__					)
								lowerCAmelCase__		  =  torch.cat(snake_case__					)

				return new_state_dict







def     UpperCAmelCase_		(					snake_case__					)	->     Optional[Any]:



				"""simple docstring"""





				return text_enc_dict


if __name__ == "__main__":
	_lowerCAmelCase	:   List[str]    =   argparse.ArgumentParser()

	parser.add_argument("--model_path", default=None, type=str, required=True, help="Path to the model to convert.")
	parser.add_argument("--checkpoint_path", default=None, type=str, required=True, help="Path to the output model.")
	parser.add_argument("--half", action="store_true", help="Save weights in half precision.")
	parser.add_argument(
	    "--use_safetensors", action="store_true", help="Save weights use safetensors, default is ckpt."
	)

	_lowerCAmelCase	:   Any    =   parser.parse_args()

	assert args.model_path is not None, "Must provide a model path!"

	assert args.checkpoint_path is not None, "Must provide a checkpoint path!"

	# Path for safetensors
	_lowerCAmelCase	:   Tuple    =   osp.join(args.model_path, "unet", "diffusion_pytorch_model.safetensors")
	_lowerCAmelCase	:   int    =   osp.join(args.model_path, "vae", "diffusion_pytorch_model.safetensors")
	_lowerCAmelCase	:   Tuple    =   osp.join(args.model_path, "text_encoder", "model.safetensors")

	# Load models from safetensors if it exists, if it doesn't pytorch
	if osp.exists(unet_path):
		_lowerCAmelCase	:   Optional[Any]    =   load_file(unet_path, device="cpu")
	else:
		_lowerCAmelCase	:   List[str]    =   osp.join(args.model_path, "unet", "diffusion_pytorch_model.bin")
		_lowerCAmelCase	:   List[str]    =   torch.load(unet_path, map_location="cpu")

	if osp.exists(vae_path):
		_lowerCAmelCase	:   List[Any]    =   load_file(vae_path, device="cpu")
	else:
		_lowerCAmelCase	:   Union[str, Any]    =   osp.join(args.model_path, "vae", "diffusion_pytorch_model.bin")
		_lowerCAmelCase	:   List[str]    =   torch.load(vae_path, map_location="cpu")

	if osp.exists(text_enc_path):
		_lowerCAmelCase	:   Union[str, Any]    =   load_file(text_enc_path, device="cpu")
	else:
		_lowerCAmelCase	:   List[str]    =   osp.join(args.model_path, "text_encoder", "pytorch_model.bin")
		_lowerCAmelCase	:   Optional[int]    =   torch.load(text_enc_path, map_location="cpu")

	# Convert the UNet model
	_lowerCAmelCase	:   int    =   convert_unet_state_dict(unet_state_dict)
	_lowerCAmelCase	:   Tuple    =   {"model.diffusion_model." + k: v for k, v in unet_state_dict.items()}

	# Convert the VAE model
	_lowerCAmelCase	:   str    =   convert_vae_state_dict(vae_state_dict)
	_lowerCAmelCase	:   int    =   {"first_stage_model." + k: v for k, v in vae_state_dict.items()}

	# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
	_lowerCAmelCase	:   Any    =   "text_model.encoder.layers.22.layer_norm2.bias" in text_enc_dict

	if is_vaa_model:
		# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
		_lowerCAmelCase	:   Dict    =   {"transformer." + k: v for k, v in text_enc_dict.items()}
		_lowerCAmelCase	:   Union[str, Any]    =   convert_text_enc_state_dict_vaa(text_enc_dict)
		_lowerCAmelCase	:   Any    =   {"cond_stage_model.model." + k: v for k, v in text_enc_dict.items()}
	else:
		_lowerCAmelCase	:   Dict    =   convert_text_enc_state_dict(text_enc_dict)
		_lowerCAmelCase	:   Tuple    =   {"cond_stage_model.transformer." + k: v for k, v in text_enc_dict.items()}

	# Put together new checkpoint
	_lowerCAmelCase	:   Optional[int]    =   {**unet_state_dict, **vae_state_dict, **text_enc_dict}
	if args.half:
		_lowerCAmelCase	:   List[Any]    =   {k: v.half() for k, v in state_dict.items()}

	if args.use_safetensors:
		save_file(state_dict, args.checkpoint_path)
	else:
		_lowerCAmelCase	:   Union[str, Any]    =   {"state_dict": state_dict}
		torch.save(state_dict, args.checkpoint_path)





from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


_lowerCAmelCase	:   str    =   logging.get_logger(__name__)


# General docstring
_lowerCAmelCase	:   Optional[int]    =   "MobileNetV1Config"

# Base docstring
_lowerCAmelCase	:   Tuple    =   "google/mobilenet_v1_1.0_224"
_lowerCAmelCase	:   Optional[int]    =   [1, 1_0_2_4, 7, 7]

# Image classification docstring
_lowerCAmelCase	:   Tuple    =   "google/mobilenet_v1_1.0_224"
_lowerCAmelCase	:   List[Any]    =   "tabby, tabby cat"


_lowerCAmelCase	:   Tuple    =   [
    "google/mobilenet_v1_1.0_224",
    "google/mobilenet_v1_0.75_192",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]







def     UpperCAmelCase_		(					snake_case__    ,			snake_case__    ,			snake_case__=None					)	->     Union[str, Any]:



				"""simple docstring"""





				lowerCAmelCase__		  =  {}

				if isinstance(snake_case__    ,			snake_case__					):
								lowerCAmelCase__		  =  model.mobilenet_va
				else:
								lowerCAmelCase__		  =  model

				lowerCAmelCase__		  =  'MobilenetV1/Conv2d_0/'
				lowerCAmelCase__		  =  backbone.conv_stem.convolution.weight
				lowerCAmelCase__		  =  backbone.conv_stem.normalization.bias
				lowerCAmelCase__		  =  backbone.conv_stem.normalization.weight
				lowerCAmelCase__		  =  backbone.conv_stem.normalization.running_mean
				lowerCAmelCase__		  =  backbone.conv_stem.normalization.running_var

				for i in range(13					):
								lowerCAmelCase__		  =  i + 1
								lowerCAmelCase__		  =  i * 2

								lowerCAmelCase__		  =  backbone.layer[pt_index]
								lowerCAmelCase__		  =  f'MobilenetV1/Conv2d_{tf_index}_depthwise/'
								lowerCAmelCase__		  =  pointer.convolution.weight
								lowerCAmelCase__		  =  pointer.normalization.bias
								lowerCAmelCase__		  =  pointer.normalization.weight
								lowerCAmelCase__		  =  pointer.normalization.running_mean
								lowerCAmelCase__		  =  pointer.normalization.running_var

								lowerCAmelCase__		  =  backbone.layer[pt_index + 1]
								lowerCAmelCase__		  =  f'MobilenetV1/Conv2d_{tf_index}_pointwise/'
								lowerCAmelCase__		  =  pointer.convolution.weight
								lowerCAmelCase__		  =  pointer.normalization.bias
								lowerCAmelCase__		  =  pointer.normalization.weight
								lowerCAmelCase__		  =  pointer.normalization.running_mean
								lowerCAmelCase__		  =  pointer.normalization.running_var

				if isinstance(snake_case__    ,			snake_case__					):
								lowerCAmelCase__		  =  'MobilenetV1/Logits/Conv2d_1c_1x1/'
								lowerCAmelCase__		  =  model.classifier.weight
								lowerCAmelCase__		  =  model.classifier.bias

				return tf_to_pt_map







def     UpperCAmelCase_		(					snake_case__    ,			snake_case__    ,			snake_case__					)	->     List[str]:



				"""simple docstring"""





				try:
								import numpy as np
								import tensorflow as tf
				except ImportError:
								logger.error(
								    'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '
								    'https://www.tensorflow.org/install/ for installation instructions.'					)
								raise

				# Load weights from TF model
				lowerCAmelCase__		  =  tf.train.list_variables(snake_case__					)
				lowerCAmelCase__		  =  {}
				for name, shape in init_vars:
								logger.info(f'Loading TF weight {name} with shape {shape}'					)
								lowerCAmelCase__		  =  tf.train.load_variable(snake_case__    ,			snake_case__					)
								lowerCAmelCase__		  =  array

				# Build TF to PyTorch weights loading map
				lowerCAmelCase__		  =  _build_tf_to_pytorch_map(snake_case__    ,			snake_case__    ,			snake_case__					)

				for name, pointer in tf_to_pt_map.items():
								logger.info(f'Importing {name}'					)
								if name not in tf_weights:
												logger.info(f'{name} not in tf pre-trained weights, skipping'					)
												continue

								lowerCAmelCase__		  =  tf_weights[name]

								if "depthwise_weights" in name:
												logger.info('Transposing depthwise'					)
												lowerCAmelCase__		  =  np.transpose(snake_case__    ,			(2, 3, 0, 1)					)
								elif "weights" in name:
												logger.info('Transposing'					)
												if len(pointer.shape					) == 2:  # copying into linear layer
																lowerCAmelCase__		  =  array.squeeze().transpose()
												else:
																lowerCAmelCase__		  =  np.transpose(snake_case__    ,			(3, 2, 0, 1)					)

								if pointer.shape != array.shape:
												raise ValueError(f'Pointer shape {pointer.shape} and array shape {array.shape} mismatched'					)

								logger.info(f'Initialize PyTorch weight {name} {array.shape}'					)
								lowerCAmelCase__		  =  torch.from_numpy(snake_case__					)

								tf_weights.pop(snake_case__    ,			snake_case__					)
								tf_weights.pop(name + '/RMSProp'    ,			snake_case__					)
								tf_weights.pop(name + '/RMSProp_1'    ,			snake_case__					)
								tf_weights.pop(name + '/ExponentialMovingAverage'    ,			snake_case__					)

				logger.info(f'Weights not copied to PyTorch model: {", ".join(tf_weights.keys()					)}'					)
				return model







def     UpperCAmelCase_		(					snake_case__    ,			snake_case__					)	->     torch.Tensor:



				"""simple docstring"""





				lowerCAmelCase__  ,   lowerCAmelCase__		  =  features.shape[-2:]
				lowerCAmelCase__  ,   lowerCAmelCase__		  =  conv_layer.stride
				lowerCAmelCase__  ,   lowerCAmelCase__		  =  conv_layer.kernel_size

				if in_height % stride_height == 0:
								lowerCAmelCase__		  =  max(kernel_height - stride_height    ,			0					)
				else:
								lowerCAmelCase__		  =  max(kernel_height - (in_height % stride_height)    ,			0					)

				if in_width % stride_width == 0:
								lowerCAmelCase__		  =  max(kernel_width - stride_width    ,			0					)
				else:
								lowerCAmelCase__		  =  max(kernel_width - (in_width % stride_width)    ,			0					)

				lowerCAmelCase__		  =  pad_along_width // 2
				lowerCAmelCase__		  =  pad_along_width - pad_left
				lowerCAmelCase__		  =  pad_along_height // 2
				lowerCAmelCase__		  =  pad_along_height - pad_top

				lowerCAmelCase__		  =  (pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(snake_case__    ,			snake_case__    ,			'constant'    ,			0.0					)


class 	__snake_case   ( nn.Module ):
		def __init__(							self    ,a_    ,a_    ,a_    ,a_    ,a_ = 1    ,a_ = 1    ,a_ = False    ,a_ = True    ,a_ = True    ,):







						"""simple docstring"""
						super().__init__()
						lowerCAmelCase__		  =  config

						if in_channels % groups != 0:
										raise ValueError(f'Input channels ({in_channels}) are not divisible by {groups} groups.'						)
						if out_channels % groups != 0:
										raise ValueError(f'Output channels ({out_channels}) are not divisible by {groups} groups.'						)

						lowerCAmelCase__		  =  0 if config.tf_padding else int((kernel_size - 1) / 2						)

						lowerCAmelCase__		  =  nn.Convad(
						    in_channels=a_    ,out_channels=a_    ,kernel_size=a_    ,stride=a_    ,padding=a_    ,groups=a_    ,bias=a_    ,padding_mode='zeros'    ,)

						if use_normalization:
										lowerCAmelCase__		  =  nn.BatchNormad(
										    num_features=a_    ,eps=config.layer_norm_eps    ,momentum=0.9997    ,affine=a_    ,track_running_stats=a_    ,)
						else:
										lowerCAmelCase__		  =  None

						if use_activation:
										if isinstance(a_    ,a_						):
														lowerCAmelCase__		  =  ACTaFN[use_activation]
										elif isinstance(config.hidden_act    ,a_						):
														lowerCAmelCase__		  =  ACTaFN[config.hidden_act]
										else:
														lowerCAmelCase__		  =  config.hidden_act
						else:
										lowerCAmelCase__		  =  None



		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						if self.config.tf_padding:
										lowerCAmelCase__		  =  apply_tf_padding(a_    ,self.convolution						)
						lowerCAmelCase__		  =  self.convolution(a_						)
						if self.normalization is not None:
										lowerCAmelCase__		  =  self.normalization(a_						)
						if self.activation is not None:
										lowerCAmelCase__		  =  self.activation(a_						)
						return features



class 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		SCREAMING_SNAKE_CASE__								=	MobileNetVaConfig
		SCREAMING_SNAKE_CASE__								=	load_tf_weights_in_mobilenet_va
		SCREAMING_SNAKE_CASE__								=	'mobilenet_v1'
		SCREAMING_SNAKE_CASE__								=	'pixel_values'
		SCREAMING_SNAKE_CASE__								=	False
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						if isinstance(a_    ,(nn.Linear, nn.Convad)						):
										module.weight.data.normal_(mean=0.0    ,std=self.config.initializer_range						)
										if module.bias is not None:
														module.bias.data.zero_()
						elif isinstance(a_    ,nn.BatchNormad						):
										module.bias.data.zero_()
										module.weight.data.fill_(1.0						)



_lowerCAmelCase	:   Tuple    =   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 ([`MobileNetV1Config`]): 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	:   Dict    =   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            [`MobileNetV1ImageProcessor.__call__`] for details.\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 MobileNetV1 model outputting raw hidden-states without any specific head on top.'							, SCREAMING_SNAKE_CASE							, )
class 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		def __init__(							self    ,a_    ,a_ = True						):







						"""simple docstring"""
						super().__init__(a_						)
						lowerCAmelCase__		  =  config

						lowerCAmelCase__		  =  32
						lowerCAmelCase__		  =  max(int(depth * config.depth_multiplier						)    ,config.min_depth						)

						lowerCAmelCase__		  =  MobileNetVaConvLayer(
						    a_    ,in_channels=config.num_channels    ,out_channels=a_    ,kernel_size=3    ,stride=2    ,)

						lowerCAmelCase__		  =  [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

						lowerCAmelCase__		  =  nn.ModuleList()
						for i in range(13						):
										lowerCAmelCase__		  =  out_channels

										if strides[i] == 2 or i == 0:
														depth *= 2
														lowerCAmelCase__		  =  max(int(depth * config.depth_multiplier						)    ,config.min_depth						)

										self.layer.append(
										    MobileNetVaConvLayer(
										        a_    ,in_channels=a_    ,out_channels=a_    ,kernel_size=3    ,stride=strides[i]    ,groups=a_    ,)						)

										self.layer.append(
										    MobileNetVaConvLayer(
										        a_    ,in_channels=a_    ,out_channels=a_    ,kernel_size=1    ,)						)

						lowerCAmelCase__		  =  nn.AdaptiveAvgPoolad((1, 1)						) if add_pooling_layer else None

						# Initialize weights and apply final processing
						self.post_init()
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_						):







						"""simple docstring"""
						raise NotImplementedError



		@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 						SCREAMING_SNAKE_CASE_					(							self    ,a_ = None    ,a_ = None    ,a_ = None    ,):







						"""simple docstring"""
						lowerCAmelCase__		  =  (
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						lowerCAmelCase__		  =  return_dict if return_dict is not None else self.config.use_return_dict

						if pixel_values is None:
										raise ValueError('You have to specify pixel_values'						)

						lowerCAmelCase__		  =  self.conv_stem(a_						)

						lowerCAmelCase__		  =  () if output_hidden_states else None

						for i, layer_module in enumerate(self.layer						):
										lowerCAmelCase__		  =  layer_module(a_						)

										if output_hidden_states:
														lowerCAmelCase__		  =  all_hidden_states + (hidden_states,)

						lowerCAmelCase__		  =  hidden_states

						if self.pooler is not None:
										lowerCAmelCase__		  =  torch.flatten(self.pooler(a_						)    ,start_dim=1						)
						else:
										lowerCAmelCase__		  =  None

						if not return_dict:
										return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None						)

						return BaseModelOutputWithPoolingAndNoAttention(
						    last_hidden_state=a_    ,pooler_output=a_    ,hidden_states=a_    ,)



@add_start_docstrings(
    '\n    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '							, SCREAMING_SNAKE_CASE							, )
class 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		def __init__(							self    ,a_						):







						"""simple docstring"""
						super().__init__(a_						)

						lowerCAmelCase__		  =  config.num_labels
						lowerCAmelCase__		  =  MobileNetVaModel(a_						)

						lowerCAmelCase__		  =  self.mobilenet_va.layer[-1].convolution.out_channels

						# Classifier head
						lowerCAmelCase__		  =  nn.Dropout(config.classifier_dropout_prob    ,inplace=a_						)
						lowerCAmelCase__		  =  nn.Linear(a_    ,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 						SCREAMING_SNAKE_CASE_					(							self    ,a_ = None    ,a_ = None    ,a_ = None    ,a_ = None    ,):







						"""simple docstring"""
						lowerCAmelCase__		  =  return_dict if return_dict is not None else self.config.use_return_dict

						lowerCAmelCase__		  =  self.mobilenet_va(a_    ,output_hidden_states=a_    ,return_dict=a_						)

						lowerCAmelCase__		  =  outputs.pooler_output if return_dict else outputs[1]

						lowerCAmelCase__		  =  self.classifier(self.dropout(a_						)						)

						lowerCAmelCase__		  =  None
						if labels is not None:
										if self.config.problem_type is None:
														if self.num_labels == 1:
																		lowerCAmelCase__		  =  'regression'
														elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																		lowerCAmelCase__		  =  'single_label_classification'
														else:
																		lowerCAmelCase__		  =  'multi_label_classification'

										if self.config.problem_type == "regression":
														lowerCAmelCase__		  =  MSELoss()
														if self.num_labels == 1:
																		lowerCAmelCase__		  =  loss_fct(logits.squeeze()    ,labels.squeeze()						)
														else:
																		lowerCAmelCase__		  =  loss_fct(a_    ,a_						)
										elif self.config.problem_type == "single_label_classification":
														lowerCAmelCase__		  =  CrossEntropyLoss()
														lowerCAmelCase__		  =  loss_fct(logits.view(-1    ,self.num_labels						)    ,labels.view(-1						)						)
										elif self.config.problem_type == "multi_label_classification":
														lowerCAmelCase__		  =  BCEWithLogitsLoss()
														lowerCAmelCase__		  =  loss_fct(a_    ,a_						)

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

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