





"""simple docstring"""




from typing import Callable, List, Optional, Union

import torch

from ...models import UNetaDModel
from ...schedulers import CMStochasticIterativeScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


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


lowerCamelCase_	:		Union[str, Any]         =   '\n    Examples:\n        ```py\n        >>> import torch\n\n        >>> from diffusers import ConsistencyModelPipeline\n\n        >>> device = "cuda"\n        >>> # Load the cd_imagenet64_l2 checkpoint.\n        >>> model_id_or_path = "openai/diffusers-cd_imagenet64_l2"\n        >>> pipe = ConsistencyModelPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)\n        >>> pipe.to(device)\n\n        >>> # Onestep Sampling\n        >>> image = pipe(num_inference_steps=1).images[0]\n        >>> image.save("cd_imagenet64_l2_onestep_sample.png")\n\n        >>> # Onestep sampling, class-conditional image generation\n        >>> # ImageNet-64 class label 145 corresponds to king penguins\n        >>> image = pipe(num_inference_steps=1, class_labels=145).images[0]\n        >>> image.save("cd_imagenet64_l2_onestep_sample_penguin.png")\n\n        >>> # Multistep sampling, class-conditional image generation\n        >>> # Timesteps can be explicitly specified; the particular timesteps below are from the original Github repo:\n        >>> # https://github.com/openai/consistency_models/blob/main/scripts/launch.sh#L77\n        >>> image = pipe(num_inference_steps=None, timesteps=[22, 0], class_labels=145).images[0]\n        >>> image.save("cd_imagenet64_l2_multistep_sample_penguin.png")\n        ```\n'

class 					_UpperCAmelCase    (  UpperCAmelCase__						):



      '''simple docstring'''

      def __init__(	self   , snake_case_   , snake_case_    ):

        """simple docstring"""

        super().__init__()

        self.register_modules(
            unet=snake_case_   , scheduler=snake_case_   , )

        A_    :			List[Any]									=    None

      def    lowerCamelCase_     (	self   , snake_case_=0    ):

        """simple docstring"""

        if is_accelerate_available() and is_accelerate_version('>='   , '0.14.0'    ):
          from accelerate import cpu_offload
        else:
          raise ImportError('`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher'    )

        A_    :			Optional[int]									=    torch.device(F"""cuda:{gpu_id}"""    )

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

        for cpu_offloaded_model in [self.unet]:
          cpu_offload(snake_case_   , snake_case_    )

        if self.safety_checker is not None:
          cpu_offload(self.safety_checker   , execution_device=snake_case_   , offload_buffers=snake_case_    )

      def    lowerCamelCase_     (	self   , snake_case_=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.'    )

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

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

        A_    :			Optional[int]									=    None
        for cpu_offloaded_model in [self.unet]:
          A_		,			A_    :			List[Any]									=    cpu_offload_with_hook(snake_case_   , snake_case_   , prev_module_hook=snake_case_    )

        if self.safety_checker is not None:
          A_		,			A_    :			List[str]									=    cpu_offload_with_hook(self.safety_checker   , snake_case_   , prev_module_hook=snake_case_    )

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

      @property
      # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
      def    lowerCamelCase_     (	self    ):

        """simple docstring"""

        if not hasattr(self.unet   , '_hf_hook'    ):
          return self.device
        for module in self.unet.modules():
          if (
              hasattr(snake_case_   , '_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

      def    lowerCamelCase_     (	self   , snake_case_   , snake_case_   , snake_case_   , snake_case_   , snake_case_   , snake_case_   , snake_case_   , snake_case_=None    ):

        """simple docstring"""

        A_    :			Optional[int]									=    (batch_size, num_channels, height, width)
        if isinstance(snake_case_   , snake_case_    ) and len(snake_case_    ) != batch_size:
          raise ValueError(
              F"""You have passed a list of generators of length {len(snake_case_    )}, but requested an effective batch"""
              F""" size of {batch_size}. Make sure the batch size matches the length of the generators."""    )

        if latents is None:
          A_    :			List[Any]									=    randn_tensor(snake_case_   , generator=snake_case_   , device=snake_case_   , dtype=snake_case_    )
        else:
          A_    :			Optional[int]									=    latents.to(device=snake_case_   , dtype=snake_case_    )

        # scale the initial noise by the standard deviation required by the scheduler
        A_    :			Union[str, Any]									=    latents * self.scheduler.init_noise_sigma
        return latents

      def    lowerCamelCase_     (	self   , snake_case_   , snake_case_ = "pil"    ):

        """simple docstring"""

        if output_type not in ["pt", "np", "pil"]:
          raise ValueError(
              F"""output_type={output_type} is not supported. Make sure to choose one of ['pt', 'np', or 'pil']"""    )

        # Equivalent to diffusers.VaeImageProcessor.denormalize
        A_    :			Tuple									=    (sample / 2 + 0.5).clamp(0   , 1    )
        if output_type == "pt":
          return sample

        # Equivalent to diffusers.VaeImageProcessor.pt_to_numpy
        A_    :			Optional[int]									=    sample.cpu().permute(0   , 2   , 3   , 1    ).numpy()
        if output_type == "np":
          return sample

        # Output_type must be 'pil'
        A_    :			str									=    self.numpy_to_pil(snake_case_    )
        return sample

      def    lowerCamelCase_     (	self   , snake_case_   , snake_case_   , snake_case_=None    ):

        """simple docstring"""

        if self.unet.config.num_class_embeds is not None:
          if isinstance(snake_case_   , snake_case_    ):
            A_    :			Optional[int]									=    torch.tensor(snake_case_   , dtype=torch.int    )
          elif isinstance(snake_case_   , snake_case_    ):
            assert batch_size == 1, "Batch size must be 1 if classes is an int"
            A_    :			Optional[Any]									=    torch.tensor([class_labels]   , dtype=torch.int    )
          elif class_labels is None:
            # Randomly generate batch_size class labels
            # TODO: should use generator here? int analogue of randn_tensor is not exposed in ...utils
            A_    :			Tuple									=    torch.randint(0   , self.unet.config.num_class_embeds   , size=(batch_size,)    )
          A_    :			Optional[int]									=    class_labels.to(snake_case_    )
        else:
          A_    :			Optional[Any]									=    None
        return class_labels

      def    lowerCamelCase_     (	self   , snake_case_   , snake_case_   , snake_case_   , snake_case_   , snake_case_   , snake_case_    ):

        """simple docstring"""

        if num_inference_steps is None and timesteps is None:
          raise ValueError('Exactly one of `num_inference_steps` or `timesteps` must be supplied.'    )

        if num_inference_steps is not None and timesteps is not None:
          logger.warning(
              F"""Both `num_inference_steps`: {num_inference_steps} and `timesteps`: {timesteps} are supplied;"""
              ' `timesteps` will be used over `num_inference_steps`.'    )

        if latents is not None:
          A_    :			List[Any]									=    (batch_size, 3, img_size, img_size)
          if latents.shape != expected_shape:
            raise ValueError(F"""The shape of latents is {latents.shape} but is expected to be {expected_shape}."""    )

        if (callback_steps is None) or (
            callback_steps is not None and (not isinstance(snake_case_   , snake_case_    ) or callback_steps <= 0)
        ):
          raise ValueError(
              F"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
              F""" {type(snake_case_    )}."""    )

      @torch.no_grad()
      @replace_example_docstring(snake_case_    )
      def __call__(	self   , snake_case_ = 1   , snake_case_ = None   , snake_case_ = 1   , snake_case_ = None   , snake_case_ = None   , snake_case_ = None   , snake_case_ = "pil"   , snake_case_ = True   , snake_case_ = None   , snake_case_ = 1   , ):

        """simple docstring"""

        A_    :			Union[str, Any]									=    self.unet.config.sample_size
        A_    :			Any									=    self._execution_device

        # 1. Check inputs
        self.check_inputs(snake_case_   , snake_case_   , snake_case_   , snake_case_   , snake_case_   , snake_case_    )

        # 2. Prepare image latents
        # Sample image latents x_0 ~ N(0, sigma_0^2 * I)
        A_    :			Tuple									=    self.prepare_latents(
            batch_size=snake_case_   , num_channels=self.unet.config.in_channels   , height=snake_case_   , width=snake_case_   , dtype=self.unet.dtype   , device=snake_case_   , generator=snake_case_   , latents=snake_case_   , )

        # 3. Handle class_labels for class-conditional models
        A_    :			List[str]									=    self.prepare_class_labels(snake_case_   , snake_case_   , class_labels=snake_case_    )

        # 4. Prepare timesteps
        if timesteps is not None:
          self.scheduler.set_timesteps(timesteps=snake_case_   , device=snake_case_    )
          A_    :			Tuple									=    self.scheduler.timesteps
          A_    :			List[Any]									=    len(snake_case_    )
        else:
          self.scheduler.set_timesteps(snake_case_    )
          A_    :			str									=    self.scheduler.timesteps

        # 5. Denoising loop
        # Multistep sampling: implements Algorithm 1 in the paper
        with self.progress_bar(total=snake_case_    ) as progress_bar:
          for i, t in enumerate(snake_case_    ):
            A_    :			int									=    self.scheduler.scale_model_input(snake_case_   , snake_case_    )
            A_    :			Tuple									=    self.unet(snake_case_   , snake_case_   , class_labels=snake_case_   , return_dict=snake_case_    )[0]

            A_    :			Any									=    self.scheduler.step(snake_case_   , snake_case_   , snake_case_   , generator=snake_case_    )[0]

            # call the callback, if provided
            progress_bar.update()
            if callback is not None and i % callback_steps == 0:
              callback(snake_case_   , snake_case_   , snake_case_    )

        # 6. Post-process image sample
        A_    :			str									=    self.postprocess_image(snake_case_   , output_type=snake_case_    )

        # Offload last model to CPU
        if hasattr(self   , 'final_offload_hook'    ) and self.final_offload_hook is not None:
          self.final_offload_hook.offload()

        if not return_dict:
          return (image,)

        return ImagePipelineOutput(images=snake_case_    )



"""simple docstring"""
from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


__SCREAMING_SNAKE_CASE				:     int		=     logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE				:     str		=     {
    'google/bigbird-pegasus-large-arxiv': (
        'https://huggingface.co/google/bigbird-pegasus-large-arxiv/resolve/main/config.json'
    ),
    'google/bigbird-pegasus-large-pubmed': (
        'https://huggingface.co/google/bigbird-pegasus-large-pubmed/resolve/main/config.json'
    ),
    'google/bigbird-pegasus-large-bigpatent': (
        'https://huggingface.co/google/bigbird-pegasus-large-bigpatent/resolve/main/config.json'
    ),
    # See all BigBirdPegasus models at https://huggingface.co/models?filter=bigbird_pegasus
}





class   __A  (snake_case__):





							'''simple docstring'''

							__lowercase:		str				   =     """bigbird_pegasus"""
							__lowercase:		Any				   =     ["""past_key_values"""]
							__lowercase:		Optional[Any]				   =     {
							    """num_attention_heads""": """encoder_attention_heads""",
							    """hidden_size""": """d_model""",
							    """attention_probs_dropout_prob""": """attention_dropout""",
							}



							def __init__(					self				:   Optional[int]		,							UpperCAmelCase_				:   List[Any]=96_103		,							UpperCAmelCase_				:   List[str]=4_096		,							UpperCAmelCase_				:   Optional[Any]=16		,							UpperCAmelCase_				:   str=4_096		,							UpperCAmelCase_				:   Optional[int]=16		,							UpperCAmelCase_				:   List[Any]=16		,							UpperCAmelCase_				:   Optional[int]=4_096		,							UpperCAmelCase_				:   List[str]=16		,							UpperCAmelCase_				:   Tuple=0.0		,							UpperCAmelCase_				:   Union[str, Any]=0.0		,							UpperCAmelCase_				:   str=True		,							UpperCAmelCase_				:   Dict=True		,							UpperCAmelCase_				:   List[str]="gelu_new"		,							UpperCAmelCase_				:   Tuple=1_024		,							UpperCAmelCase_				:   int=0.1		,							UpperCAmelCase_				:   Union[str, Any]=0.0		,							UpperCAmelCase_				:   str=0.0		,							UpperCAmelCase_				:   str=0.02		,							UpperCAmelCase_				:   Tuple=2		,							UpperCAmelCase_				:   int=0.0		,							UpperCAmelCase_				:   str=True		,							UpperCAmelCase_				:   Any=0		,							UpperCAmelCase_				:   Dict=2		,							UpperCAmelCase_				:   List[str]=1		,							UpperCAmelCase_				:   Optional[int]="block_sparse"		,							UpperCAmelCase_				:   Tuple=64		,							UpperCAmelCase_				:   List[str]=3		,							UpperCAmelCase_				:   Optional[int]=False		,							**UpperCAmelCase_				:   str		,							)       ->List[str]:



														"""simple docstring"""



														snake_case_     							=		vocab_size
														snake_case_     							=		max_position_embeddings
														snake_case_     							=		d_model
														snake_case_     							=		encoder_ffn_dim
														snake_case_     							=		encoder_layers
														snake_case_     							=		encoder_attention_heads
														snake_case_     							=		decoder_ffn_dim
														snake_case_     							=		decoder_layers
														snake_case_     							=		decoder_attention_heads
														snake_case_     							=		dropout
														snake_case_     							=		attention_dropout
														snake_case_     							=		activation_dropout
														snake_case_     							=		activation_function
														snake_case_     							=		init_std
														snake_case_     							=		encoder_layerdrop
														snake_case_     							=		decoder_layerdrop
														snake_case_     							=		classifier_dropout
														snake_case_     							=		use_cache
														snake_case_     							=		encoder_layers
														snake_case_     							=		scale_embedding  # scale factor will be sqrt(d_model) if True

														# extra config
														snake_case_     							=		attention_type
														snake_case_     							=		block_size
														snake_case_     							=		num_random_blocks
														snake_case_     							=		use_bias

														super().__init__(
														    pad_token_id=UpperCAmelCase_		,							bos_token_id=UpperCAmelCase_		,							eos_token_id=UpperCAmelCase_		,							is_encoder_decoder=UpperCAmelCase_		,							decoder_start_token_id=UpperCAmelCase_		,							**UpperCAmelCase_		,							)





class   __A  (snake_case__):





							'''simple docstring'''

							@property
							def 		lowerCAmelCase							(					self				:   List[str]							)       ->Mapping[str, Mapping[int, str]]:



														"""simple docstring"""



														if self.task in ["default", "seq2seq-lm"]:
																					snake_case_     							=		OrderedDict(
																					    [
																					        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
																					    ]							)

																					if self.use_past:
																												snake_case_     							=		{0: """batch"""}
																												snake_case_     							=		{0: """batch""", 1: """past_decoder_sequence + sequence"""}
																					else:
																												snake_case_     							=		{0: """batch""", 1: """decoder_sequence"""}
																												snake_case_     							=		{0: """batch""", 1: """decoder_sequence"""}

																					if self.use_past:
																												self.fill_with_past_key_values_(UpperCAmelCase_		,							direction="""inputs"""							)
														elif self.task == "causal-lm":
																					# TODO: figure this case out.
																					snake_case_     							=		OrderedDict(
																					    [
																					        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
																					    ]							)
																					if self.use_past:
																												snake_case_							,    snake_case_     							=		self.num_layers
																												for i in range(UpperCAmelCase_							):
																																			snake_case_     							=		{0: """batch""", 2: """past_sequence + sequence"""}
																																			snake_case_     							=		{0: """batch""", 2: """past_sequence + sequence"""}
														else:
																					snake_case_     							=		OrderedDict(
																					    [
																					        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
																					        ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}),
																					        ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}),
																					    ]							)

														return common_inputs



							@property
							def 		lowerCAmelCase							(					self				:   Dict							)       ->Mapping[str, Mapping[int, str]]:



														"""simple docstring"""



														if self.task in ["default", "seq2seq-lm"]:
																					snake_case_     							=		super().outputs
														else:
																					snake_case_     							=		super(UpperCAmelCase_		,							self							).outputs
																					if self.use_past:
																												snake_case_							,    snake_case_     							=		self.num_layers
																												for i in range(UpperCAmelCase_							):
																																			snake_case_     							=		{0: """batch""", 2: """past_sequence + sequence"""}
																																			snake_case_     							=		{0: """batch""", 2: """past_sequence + sequence"""}
														return common_outputs



							def 		lowerCAmelCase							(					self				:   int		,							UpperCAmelCase_				:   PreTrainedTokenizer		,							UpperCAmelCase_				:   int = -1		,							UpperCAmelCase_				:   int = -1		,							UpperCAmelCase_				:   bool = False		,							UpperCAmelCase_				:   Optional[TensorType] = None		,							)       ->Mapping[str, Any]:



														"""simple docstring"""



														snake_case_     							=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
														    UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_							)

														# Generate decoder inputs
														snake_case_     							=		seq_length if not self.use_past else 1
														snake_case_     							=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
														    UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_							)
														snake_case_     							=		{F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
														snake_case_     							=		dict(**UpperCAmelCase_		,							**UpperCAmelCase_							)

														if self.use_past:
																					if not is_torch_available():
																												raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
																					else:
																												import torch
																					snake_case_							,    snake_case_     							=		common_inputs["""input_ids"""].shape
																					snake_case_     							=		common_inputs["""decoder_input_ids"""].shape[1]
																					snake_case_							,    snake_case_     							=		self.num_attention_heads
																					snake_case_     							=		(
																					    batch,
																					    num_encoder_attention_heads,
																					    encoder_seq_length,
																					    self._config.hidden_size // num_encoder_attention_heads,
																					)
																					snake_case_     							=		decoder_seq_length + 3
																					snake_case_     							=		(
																					    batch,
																					    num_decoder_attention_heads,
																					    decoder_past_length,
																					    self._config.hidden_size // num_decoder_attention_heads,
																					)

																					snake_case_     							=		torch.cat(
																					    [common_inputs["""decoder_attention_mask"""], torch.ones(UpperCAmelCase_		,							UpperCAmelCase_							)]		,							dim=1							)

																					snake_case_     							=		[]
																					# If the number of encoder and decoder layers are present in the model configuration, both are considered
																					snake_case_							,    snake_case_     							=		self.num_layers
																					snake_case_     							=		min(UpperCAmelCase_		,							UpperCAmelCase_							)
																					snake_case_     							=		max(UpperCAmelCase_		,							UpperCAmelCase_							) - min_num_layers
																					snake_case_     							=		"""encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

																					for _ in range(UpperCAmelCase_							):
																												common_inputs["past_key_values"].append(
																												    (
																												        torch.zeros(UpperCAmelCase_							),
																												        torch.zeros(UpperCAmelCase_							),
																												        torch.zeros(UpperCAmelCase_							),
																												        torch.zeros(UpperCAmelCase_							),
																												    )							)
																					# TODO: test this.
																					snake_case_     							=		encoder_shape if remaining_side_name == """encoder""" else decoder_shape
																					for _ in range(UpperCAmelCase_		,							UpperCAmelCase_							):
																												common_inputs["past_key_values"].append((torch.zeros(UpperCAmelCase_							), torch.zeros(UpperCAmelCase_							))							)
														return common_inputs



							def 		lowerCAmelCase							(					self				:   Union[str, Any]		,							UpperCAmelCase_				:   PreTrainedTokenizer		,							UpperCAmelCase_				:   int = -1		,							UpperCAmelCase_				:   int = -1		,							UpperCAmelCase_				:   bool = False		,							UpperCAmelCase_				:   Optional[TensorType] = None		,							)       ->Mapping[str, Any]:



														"""simple docstring"""



														snake_case_     							=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
														    UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_							)

														if self.use_past:
																					if not is_torch_available():
																												raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
																					else:
																												import torch
																					snake_case_							,    snake_case_     							=		common_inputs["""input_ids"""].shape
																					# Not using the same length for past_key_values
																					snake_case_     							=		seqlen + 2
																					snake_case_							,    snake_case_     							=		self.num_layers
																					snake_case_							,    snake_case_     							=		self.num_attention_heads
																					snake_case_     							=		(
																					    batch,
																					    num_encoder_attention_heads,
																					    past_key_values_length,
																					    self._config.hidden_size // num_encoder_attention_heads,
																					)

																					snake_case_     							=		common_inputs["""attention_mask"""].dtype
																					snake_case_     							=		torch.cat(
																					    [common_inputs["""attention_mask"""], torch.ones(UpperCAmelCase_		,							UpperCAmelCase_		,							dtype=UpperCAmelCase_							)]		,							dim=1							)
																					snake_case_     							=		[
																					    (torch.zeros(UpperCAmelCase_							), torch.zeros(UpperCAmelCase_							)) for _ in range(UpperCAmelCase_							)
																					]
														return common_inputs



							def 		lowerCAmelCase							(					self				:   Dict		,							UpperCAmelCase_				:   PreTrainedTokenizer		,							UpperCAmelCase_				:   int = -1		,							UpperCAmelCase_				:   int = -1		,							UpperCAmelCase_				:   bool = False		,							UpperCAmelCase_				:   Optional[TensorType] = None		,							)       ->Mapping[str, Any]:



														"""simple docstring"""



														snake_case_     							=		compute_effective_axis_dimension(
														    UpperCAmelCase_		,							fixed_dimension=OnnxConfig.default_fixed_batch		,							num_token_to_add=0							)

														# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
														snake_case_     							=		tokenizer.num_special_tokens_to_add(UpperCAmelCase_							)
														snake_case_     							=		compute_effective_axis_dimension(
														    UpperCAmelCase_		,							fixed_dimension=OnnxConfig.default_fixed_sequence		,							num_token_to_add=UpperCAmelCase_							)

														# Generate dummy inputs according to compute batch and sequence
														snake_case_     							=		[""" """.join([tokenizer.unk_token]							) * seq_length] * batch_size
														snake_case_     							=		dict(tokenizer(UpperCAmelCase_		,							return_tensors=UpperCAmelCase_							)							)
														return common_inputs



							def 		lowerCAmelCase							(					self				:   str		,							UpperCAmelCase_				:   PreTrainedTokenizer		,							UpperCAmelCase_				:   int = -1		,							UpperCAmelCase_				:   int = -1		,							UpperCAmelCase_				:   bool = False		,							UpperCAmelCase_				:   Optional[TensorType] = None		,							)       ->Mapping[str, Any]:



														"""simple docstring"""



														if self.task in ["default", "seq2seq-lm"]:
																					snake_case_     							=		self._generate_dummy_inputs_for_default_and_seqaseq_lm(
																					    UpperCAmelCase_		,							batch_size=UpperCAmelCase_		,							seq_length=UpperCAmelCase_		,							is_pair=UpperCAmelCase_		,							framework=UpperCAmelCase_							)

														elif self.task == "causal-lm":
																					snake_case_     							=		self._generate_dummy_inputs_for_causal_lm(
																					    UpperCAmelCase_		,							batch_size=UpperCAmelCase_		,							seq_length=UpperCAmelCase_		,							is_pair=UpperCAmelCase_		,							framework=UpperCAmelCase_							)
														else:
																					snake_case_     							=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
																					    UpperCAmelCase_		,							batch_size=UpperCAmelCase_		,							seq_length=UpperCAmelCase_		,							is_pair=UpperCAmelCase_		,							framework=UpperCAmelCase_							)

														return common_inputs



							def 		lowerCAmelCase							(					self				:   Union[str, Any]		,							UpperCAmelCase_				:   Any		,							UpperCAmelCase_				:   Union[str, Any]		,							UpperCAmelCase_				:   Any		,							UpperCAmelCase_				:   Any							)       ->Tuple:



														"""simple docstring"""



														if self.task in ["default", "seq2seq-lm"]:
																					snake_case_     							=		super()._flatten_past_key_values_(UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_							)
														else:
																					snake_case_     							=		super(UpperCAmelCase_		,							self							)._flatten_past_key_values_(
																					    UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_		,							UpperCAmelCase_							)



