






'''simple docstring'''







from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
			import numpy
			import tensorflow as tf

			from transformers import (
			    TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
			    TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
			    TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
			    BertConfig,
			    DPRConfig,
			    TFDPRContextEncoder,
			    TFDPRQuestionEncoder,
			    TFDPRReader,
			)

class _lowercase	:




							def __init__(							self:				int			,							UpperCamelCase__:				Union[str, Any]			,							UpperCamelCase__:				Optional[Any]=13			,							UpperCamelCase__:				Dict=7			,							UpperCamelCase__:				Tuple=True			,							UpperCamelCase__:				Any=True			,							UpperCamelCase__:				List[str]=True			,							UpperCamelCase__:				Optional[Any]=True			,							UpperCamelCase__:				List[str]=99			,							UpperCamelCase__:				Dict=32			,							UpperCamelCase__:				int=2			,							UpperCamelCase__:				Any=4			,							UpperCamelCase__:				Optional[int]=37			,							UpperCamelCase__:				List[Any]="gelu"			,							UpperCamelCase__:				int=0.1			,							UpperCamelCase__:				List[str]=0.1			,							UpperCamelCase__:				Dict=512			,							UpperCamelCase__:				Union[str, Any]=16			,							UpperCamelCase__:				Optional[int]=2			,							UpperCamelCase__:				int=0.02			,							UpperCamelCase__:				Tuple=3			,							UpperCamelCase__:				Optional[Any]=4			,							UpperCamelCase__:				Optional[int]=None			,							UpperCamelCase__:				List[Any]=0			,							):
														lowerCamelCase__					:	str         =       parent
														lowerCamelCase__					:	Tuple         =       batch_size
														lowerCamelCase__					:	Optional[int]         =       seq_length
														lowerCamelCase__					:	Dict         =       is_training
														lowerCamelCase__					:	Optional[int]         =       use_input_mask
														lowerCamelCase__					:	Optional[Any]         =       use_token_type_ids
														lowerCamelCase__					:	Optional[Any]         =       use_labels
														lowerCamelCase__					:	Tuple         =       vocab_size
														lowerCamelCase__					:	List[str]         =       hidden_size
														lowerCamelCase__					:	List[Any]         =       num_hidden_layers
														lowerCamelCase__					:	Any         =       num_attention_heads
														lowerCamelCase__					:	Optional[int]         =       intermediate_size
														lowerCamelCase__					:	List[str]         =       hidden_act
														lowerCamelCase__					:	Dict         =       hidden_dropout_prob
														lowerCamelCase__					:	Dict         =       attention_probs_dropout_prob
														lowerCamelCase__					:	str         =       max_position_embeddings
														lowerCamelCase__					:	List[str]         =       type_vocab_size
														lowerCamelCase__					:	Optional[Any]         =       type_sequence_label_size
														lowerCamelCase__					:	Optional[Any]         =       initializer_range
														lowerCamelCase__					:	int         =       num_labels
														lowerCamelCase__					:	List[Any]         =       num_choices
														lowerCamelCase__					:	int         =       scope
														lowerCamelCase__					:	Tuple         =       projection_dim




							def 		lowerCamelCase_				(							self:				List[str]     ):
														lowerCamelCase__					:	Union[str, Any]         =       ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size     )

														lowerCamelCase__					:	Dict         =       None
														if self.use_input_mask:
																					# follow test_modeling_tf_ctrl.py
																					lowerCamelCase__					:	Optional[Any]         =       random_attention_mask([self.batch_size, self.seq_length]     )

														lowerCamelCase__					:	Tuple         =       None
														if self.use_token_type_ids:
																					lowerCamelCase__					:	List[Any]         =       ids_tensor([self.batch_size, self.seq_length]			,							self.type_vocab_size     )

														lowerCamelCase__					:	Optional[int]         =       None
														lowerCamelCase__					:	int         =       None
														lowerCamelCase__					:	Tuple         =       None
														if self.use_labels:
																					lowerCamelCase__					:	Optional[int]         =       ids_tensor([self.batch_size]			,							self.type_sequence_label_size     )
																					lowerCamelCase__					:	str         =       ids_tensor([self.batch_size, self.seq_length]			,							self.num_labels     )
																					lowerCamelCase__					:	Optional[Any]         =       ids_tensor([self.batch_size]			,							self.num_choices     )

														lowerCamelCase__					:	Union[str, Any]         =       BertConfig(
														    vocab_size=self.vocab_size			,							hidden_size=self.hidden_size			,							num_hidden_layers=self.num_hidden_layers			,							num_attention_heads=self.num_attention_heads			,							intermediate_size=self.intermediate_size			,							hidden_act=self.hidden_act			,							hidden_dropout_prob=self.hidden_dropout_prob			,							attention_probs_dropout_prob=self.attention_probs_dropout_prob			,							max_position_embeddings=self.max_position_embeddings			,							type_vocab_size=self.type_vocab_size			,							is_decoder=UpperCamelCase__			,							initializer_range=self.initializer_range			,							)
														lowerCamelCase__					:	Tuple         =       DPRConfig(projection_dim=self.projection_dim			,							**config.to_dict()     )

														return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




							def 		lowerCamelCase_				(							self:				int			,							UpperCamelCase__:				Union[str, Any]			,							UpperCamelCase__:				str			,							UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				str			,							UpperCamelCase__:				int			,							UpperCamelCase__:				Any     ):
														lowerCamelCase__					:	Optional[Any]         =       TFDPRContextEncoder(config=UpperCamelCase__     )
														lowerCamelCase__					:	List[Any]         =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__     )
														lowerCamelCase__					:	int         =       model(UpperCamelCase__			,							token_type_ids=UpperCamelCase__     )
														lowerCamelCase__					:	str         =       model(UpperCamelCase__     )
														self.parent.assertEqual(result.pooler_output.shape			,							(self.batch_size, self.projection_dim or self.hidden_size)     )




							def 		lowerCamelCase_				(							self:				int			,							UpperCamelCase__:				Union[str, Any]			,							UpperCamelCase__:				List[str]			,							UpperCamelCase__:				List[str]			,							UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				str			,							UpperCamelCase__:				str			,							UpperCamelCase__:				Any     ):
														lowerCamelCase__					:	int         =       TFDPRQuestionEncoder(config=UpperCamelCase__     )
														lowerCamelCase__					:	Any         =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__			,							token_type_ids=UpperCamelCase__     )
														lowerCamelCase__					:	Optional[int]         =       model(UpperCamelCase__			,							token_type_ids=UpperCamelCase__     )
														lowerCamelCase__					:	Tuple         =       model(UpperCamelCase__     )
														self.parent.assertEqual(result.pooler_output.shape			,							(self.batch_size, self.projection_dim or self.hidden_size)     )




							def 		lowerCamelCase_				(							self:				List[Any]			,							UpperCamelCase__:				Optional[Any]			,							UpperCamelCase__:				str			,							UpperCamelCase__:				List[str]			,							UpperCamelCase__:				Any			,							UpperCamelCase__:				int			,							UpperCamelCase__:				Any			,							UpperCamelCase__:				Tuple     ):
														lowerCamelCase__					:	str         =       TFDPRReader(config=UpperCamelCase__     )
														lowerCamelCase__					:	Optional[Any]         =       model(UpperCamelCase__			,							attention_mask=UpperCamelCase__     )

														self.parent.assertEqual(result.start_logits.shape			,							(self.batch_size, self.seq_length)     )
														self.parent.assertEqual(result.end_logits.shape			,							(self.batch_size, self.seq_length)     )
														self.parent.assertEqual(result.relevance_logits.shape			,							(self.batch_size,)     )




							def 		lowerCamelCase_				(							self:				List[Any]     ):
														lowerCamelCase__					:	Optional[Any]         =       self.prepare_config_and_inputs()
														(
														    (
														    lowerCamelCase__
														)  ,		(
														    lowerCamelCase__
														)  ,		(
														    lowerCamelCase__
														)  ,		(
														    lowerCamelCase__
														)  ,		(
														    lowerCamelCase__
														)  ,		(
														    lowerCamelCase__
														)  ,		(
														    lowerCamelCase__
														)  ,		
														)					:	str         =       config_and_inputs
														lowerCamelCase__					:	Optional[int]         =       {"""input_ids""": input_ids}
														return config, inputs_dict



@require_tf
class _lowercase	(				_lowercase				,      _lowercase				,      unittest.TestCase		):
							a				      =       (
							    (
							        TFDPRContextEncoder,
							        TFDPRQuestionEncoder,
							        TFDPRReader,
							    )
							    if is_tf_available()
							    else ()
							)
							a				      =       {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

							a				      =       False
							a				      =       False
							a				      =       False
							a				      =       False
							a				      =       False




							def 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__					:	str         =       TFDPRModelTester(self     )
														lowerCamelCase__					:	int         =       ConfigTester(self			,							config_class=UpperCamelCase__			,							hidden_size=37     )




							def 		lowerCamelCase_				(							self:				Dict     ):
														self.config_tester.run_common_tests()




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__					:	Optional[Any]         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_dpr_context_encoder(*UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__					:	int         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_dpr_question_encoder(*UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__					:	Tuple         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_dpr_reader(*UpperCamelCase__     )




							@slow
							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__					:	str         =       TFDPRContextEncoder.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )

														for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__					:	Optional[int]         =       TFDPRContextEncoder.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )

														for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__					:	Tuple         =       TFDPRQuestionEncoder.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )

														for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__					:	int         =       TFDPRReader.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )



@require_tf
class _lowercase	(				unittest.TestCase		):




							@slow
							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														lowerCamelCase__					:	List[str]         =       TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""     )

														lowerCamelCase__					:	Optional[Any]         =       tf.constant(
														    [[101, 7_592, 1_010, 2_003, 2_026, 3_899, 10_140, 1_029, 102]]     )  # [CLS] hello, is my dog cute? [SEP]
														lowerCamelCase__					:	Optional[Any]         =       model(UpperCamelCase__     )[0]  # embedding shape = (1, 768)
														# compare the actual values for a slice.
														lowerCamelCase__					:	Union[str, Any]         =       tf.constant(
														    [
														        [
														            0.03_236_253,
														            0.12_753_335,
														            0.16_818_509,
														            0.00_279_786,
														            0.3_896_933,
														            0.24_264_945,
														            0.2_178_971,
														            -0.02_335_227,
														            -0.08_481_959,
														            -0.14_324_117,
														        ]
														    ]     )
														self.assertTrue(numpy.allclose(output[:, :10].numpy()			,							expected_slice.numpy()			,							atol=1e-4     )     )




'''simple docstring'''






import argparse
from pathlib import Path

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

from diffusers import AutoencoderKL


lowerCAmelCase__											=	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"""



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

 # VAE DECODER
 __lowercase							  = AutoencoderKL.from_pretrained(model_path + '''/vae'''      )
 __lowercase							  = vae_decoder.config.latent_channels
 # forward only through the decoder part
 __lowercase							  = 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__":
 lowerCAmelCase__											=	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''')

 lowerCAmelCase__											=	parser.parse_args()
 print(args.output_path)
 convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
 print('''SD: Done: ONNX''')

