
"""simple docstring"""





import argparse
from pathlib import Path

import torch
from packaging import version
from torch.onnx import export

from diffusers import AutoencoderKL


UpperCamelCase_					:						Any				= version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''')
def 							A_     (__a				,   __a				,   __a				,   __a				,   __a				,   __a				,   __a				,   __a=False				,   ):

					'''simple docstring'''





					output_path.parent.mkdir(parents=__a				,   exist_ok=__a				)
					# PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11,
					# so we check the torch version for backwards compatibility
					if is_torch_less_than_1_11:
										export(
										    __a				,   __a				,   f=output_path.as_posix()				,   input_names=__a				,   output_names=__a				,   dynamic_axes=__a				,   do_constant_folding=__a				,   use_external_data_format=__a				,   enable_onnx_checker=__a				,   opset_version=__a				,   )
					else:
										export(
										    __a				,   __a				,   f=output_path.as_posix()				,   input_names=__a				,   output_names=__a				,   dynamic_axes=__a				,   do_constant_folding=__a				,   opset_version=__a				,   )
@torch.no_grad()
def 							A_     (__a				,   __a				,   __a				,   __a = False				):

					'''simple docstring'''





					A_				 =						torch.floataa if fpaa else torch.floataa
					if fpaa and torch.cuda.is_available():
										A_				 =						"cuda"
					elif fpaa and not torch.cuda.is_available():
										raise ValueError("`float16` model export is only supported on GPUs with CUDA"				)
					else:
										A_				 =						"cpu"
					A_				 =						Path(__a				)

					# VAE DECODER
					A_				 =						AutoencoderKL.from_pretrained(model_path + "/vae"				)
					A_				 =						vae_decoder.config.latent_channels
					# forward only through the decoder part
					A_				 =						vae_decoder.decode
					onnx_export(
					    __a				,   model_args=(
					        torch.randn(1				,   __a				,   25				,   25				).to(device=__a				,   dtype=__a				),
					        False,
					    )				,   output_path=output_path / "vae_decoder" / "model.onnx"				,   ordered_input_names=["latent_sample", "return_dict"]				,   output_names=["sample"]				,   dynamic_axes={
					        "latent_sample": {0: "batch", 1: "channels", 2: "height", 3: "width"},
					    }				,   opset=__a				,   )
					del vae_decoder


if __name__ == "__main__":
		UpperCamelCase_					:						Union[str, Any]				= argparse.ArgumentParser()

		parser.add_argument(
		    '''--model_path''',
		    type=str,
		    required=True,
		    help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''',
		)

		parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''')
		parser.add_argument(
		    '''--opset''',
		    default=14,
		    type=int,
		    help='''The version of the ONNX operator set to use.''',
		)
		parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''')

		UpperCamelCase_					:						Optional[Any]				= parser.parse_args()
		print(args.output_path)
		convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
		print('''SD: Done: ONNX''')






"""simple docstring"""





from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


UpperCamelCase_					:						Optional[int]				= logging.get_logger(__name__)

UpperCamelCase_					:						Dict				= {
    '''microsoft/focalnet-tiny''': '''https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json''',
}



class __lowerCAmelCase				(					_lowercase     ,				_lowercase      ):




			"""simple docstring"""







			snake_case	      =				"focalnet"




			def __init__(				self						:					Any       ,   _snake_case						:					Optional[int]=224       ,   _snake_case						:					List[str]=4       ,   _snake_case						:					Any=3       ,   _snake_case						:					List[Any]=96       ,   _snake_case						:					Union[str, Any]=False       ,   _snake_case						:					Optional[Any]=[192, 384, 768, 768]       ,   _snake_case						:					List[str]=[2, 2, 6, 2]       ,   _snake_case						:					Any=[2, 2, 2, 2]       ,   _snake_case						:					List[Any]=[3, 3, 3, 3]       ,   _snake_case						:					Optional[Any]="gelu"       ,   _snake_case						:					Dict=4.0       ,   _snake_case						:					List[Any]=0.0       ,   _snake_case						:					List[str]=0.1       ,   _snake_case						:					Optional[Any]=False       ,   _snake_case						:					Any=1e-4       ,   _snake_case						:					str=False       ,   _snake_case						:					Optional[int]=False       ,   _snake_case						:					Tuple=False       ,   _snake_case						:					Any=0.0_2       ,   _snake_case						:					List[Any]=1e-5       ,   _snake_case						:					Union[str, Any]=32       ,   _snake_case						:					Tuple=None       ,   _snake_case						:					Any=None       ,   **_snake_case						:					Tuple       ,   )      -> str:







								"""simple docstring"""
								super().__init__(**_snake_case	)

								A_				 =						image_size
								A_				 =						patch_size
								A_				 =						num_channels
								A_				 =						embed_dim
								A_				 =						use_conv_embed
								A_				 =						hidden_sizes
								A_				 =						depths
								A_				 =						focal_levels
								A_				 =						focal_windows
								A_				 =						hidden_act
								A_				 =						mlp_ratio
								A_				 =						hidden_dropout_prob
								A_				 =						drop_path_rate
								A_				 =						use_layerscale
								A_				 =						layerscale_value
								A_				 =						use_post_layernorm
								A_				 =						use_post_layernorm_in_modulation
								A_				 =						normalize_modulator
								A_				 =						initializer_range
								A_				 =						layer_norm_eps
								A_				 =						encoder_stride
								A_				 =						["stem"] + [F'stage{idx}' for idx in range(1       ,   len(self.depths	) + 1	)]
								A_ ,    A_				 =						get_aligned_output_features_output_indices(
								    out_features=_snake_case       ,   out_indices=_snake_case       ,   stage_names=self.stage_names	)




