





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


__A    :   int          =       logging.get_logger(__name__)

__A    :   Dict          =       {
    "facebook/mbart-large-cc25": "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/config.json",
    # See all MBART models at https://huggingface.co/models?filter=mbart
}

class      A_	(a_      ):
	UpperCAmelCase__ =      '''mbart'''
	UpperCAmelCase__ =      ['''past_key_values''']
	UpperCAmelCase__ =      {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}
	def __init__(   self							, _A=5_0_2_6_5							, _A=1_0_2_4							, _A=1_2							, _A=4_0_9_6							, _A=1_6							, _A=1_2							, _A=4_0_9_6							, _A=1_6							, _A=0.0							, _A=0.0							, _A=True							, _A=True							, _A="gelu"							, _A=1_0_2_4							, _A=0.1							, _A=0.0							, _A=0.0							, _A=0.02							, _A=0.0							, _A=False							, _A=1							, _A=0							, _A=2							, _A=2							, **_A							, ):






				'''simple docstring'''







				UpperCAmelCase       		=    vocab_size
				UpperCAmelCase       		=    max_position_embeddings
				UpperCAmelCase       		=    d_model
				UpperCAmelCase       		=    encoder_ffn_dim
				UpperCAmelCase       		=    encoder_layers
				UpperCAmelCase       		=    encoder_attention_heads
				UpperCAmelCase       		=    decoder_ffn_dim
				UpperCAmelCase       		=    decoder_layers
				UpperCAmelCase       		=    decoder_attention_heads
				UpperCAmelCase       		=    dropout
				UpperCAmelCase       		=    attention_dropout
				UpperCAmelCase       		=    activation_dropout
				UpperCAmelCase       		=    activation_function
				UpperCAmelCase       		=    init_std
				UpperCAmelCase       		=    encoder_layerdrop
				UpperCAmelCase       		=    decoder_layerdrop
				UpperCAmelCase       		=    classifier_dropout
				UpperCAmelCase       		=    use_cache
				UpperCAmelCase       		=    encoder_layers
				UpperCAmelCase       		=    scale_embedding  # scale factor will be sqrt(d_model) if True
				super().__init__(
				    pad_token_id=_A							, bos_token_id=_A							, eos_token_id=_A							, is_encoder_decoder=_A							, forced_eos_token_id=_A							, **_A							, )

class      A_	(a_      ):
	@property
	def 					_lowercase    (   self		):






				'''simple docstring'''







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

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

							if self.use_past:
										self.fill_with_past_key_values_(_A							, direction='''inputs'''		)
				elif self.task == "causal-lm":
							# TODO: figure this case out.
							UpperCAmelCase       		=    OrderedDict(
							    [
							        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
							        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
							    ]		)
							if self.use_past:
										UpperCAmelCase		,      UpperCAmelCase       		=    self.num_layers
										for i in range(_A		):
													UpperCAmelCase       		=    {0: '''batch''', 2: '''past_sequence + sequence'''}
													UpperCAmelCase       		=    {0: '''batch''', 2: '''past_sequence + sequence'''}
				else:
							UpperCAmelCase       		=    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 					_lowercase    (   self		):






				'''simple docstring'''







				if self.task in ["default", "seq2seq-lm"]:
							UpperCAmelCase       		=    super().outputs
				else:
							UpperCAmelCase       		=    super(_A							, self		).outputs
							if self.use_past:
										UpperCAmelCase		,      UpperCAmelCase       		=    self.num_layers
										for i in range(_A		):
													UpperCAmelCase       		=    {0: '''batch''', 2: '''past_sequence + sequence'''}
													UpperCAmelCase       		=    {0: '''batch''', 2: '''past_sequence + sequence'''}
				return common_outputs
	def 					_lowercase    (   self							, _A							, _A = -1							, _A = -1							, _A = False							, _A = None							, ):






				'''simple docstring'''







				UpperCAmelCase       		=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
				    _A							, _A							, _A							, _A							, _A		)

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

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

							UpperCAmelCase       		=    torch.cat(
							    [common_inputs['''decoder_attention_mask'''], torch.ones(_A							, _A		)]							, dim=1		)

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

							for _ in range(_A		):
										common_inputs["past_key_values"].append(
										    (
										        torch.zeros(_A		),
										        torch.zeros(_A		),
										        torch.zeros(_A		),
										        torch.zeros(_A		),
										    )		)
							# TODO: test this.
							UpperCAmelCase       		=    encoder_shape if remaining_side_name == '''encoder''' else decoder_shape
							for _ in range(_A							, _A		):
										common_inputs["past_key_values"].append((torch.zeros(_A		), torch.zeros(_A		))		)
				return common_inputs
	def 					_lowercase    (   self							, _A							, _A = -1							, _A = -1							, _A = False							, _A = None							, ):






				'''simple docstring'''







				UpperCAmelCase       		=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
				    _A							, _A							, _A							, _A							, _A		)

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

							UpperCAmelCase       		=    common_inputs['''attention_mask'''].dtype
							UpperCAmelCase       		=    torch.cat(
							    [common_inputs['''attention_mask'''], torch.ones(_A							, _A							, dtype=_A		)]							, dim=1		)
							UpperCAmelCase       		=    [
							    (torch.zeros(_A		), torch.zeros(_A		)) for _ in range(_A		)
							]
				return common_inputs
	def 					_lowercase    (   self							, _A							, _A = -1							, _A = -1							, _A = False							, _A = None							, ):






				'''simple docstring'''







				UpperCAmelCase       		=    compute_effective_axis_dimension(
				    _A							, 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
				UpperCAmelCase       		=    tokenizer.num_special_tokens_to_add(_A		)
				UpperCAmelCase       		=    compute_effective_axis_dimension(
				    _A							, fixed_dimension=OnnxConfig.default_fixed_sequence							, num_token_to_add=_A		)

				# Generate dummy inputs according to compute batch and sequence
				UpperCAmelCase       		=    [''' '''.join([tokenizer.unk_token]		) * seq_length] * batch_size
				UpperCAmelCase       		=    dict(tokenizer(_A							, return_tensors=_A		)		)
				return common_inputs
	def 					_lowercase    (   self							, _A							, _A = -1							, _A = -1							, _A = False							, _A = None							, ):






				'''simple docstring'''







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

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

				return common_inputs







	def 					_lowercase    (   self							, _A							, _A							, _A							, _A		):






				'''simple docstring'''







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










from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve





def 						__SCREAMING_SNAKE_CASE  (    UpperCamelCase__      ,      UpperCamelCase__      ,      UpperCamelCase__			)  ->    np.ndarray:







			'''simple docstring'''

			UpperCAmelCase       		=    np.stack((horizontal_flow, vertical_flow)      ,      2			)

			# Create a grid of all pixel coordinates and subtract the flow to get the
			# target pixels coordinates
			UpperCAmelCase       		=    np.stack(
			    np.meshgrid(np.arange(0      ,      image.shape[1]			)      ,      np.arange(0      ,      image.shape[0]			)			)      ,      2			)
			UpperCAmelCase       		=    np.round(grid - flow			).astype(np.intaa			)

			# Find the locations outside of the original image
			UpperCAmelCase       		=    (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]			))
			UpperCAmelCase       		=    0

			UpperCAmelCase       		=    image[grid[:, :, 1], grid[:, :, 0]]

			# Set pixels at invalid locations to 0
			UpperCAmelCase       		=    0

			return warped





def 						__SCREAMING_SNAKE_CASE  (    UpperCamelCase__      ,      UpperCamelCase__      ,      UpperCamelCase__      ,      UpperCamelCase__ = None      ,      )  ->    tuple[np.ndarray, np.ndarray]:







			'''simple docstring'''

			if alpha is None:
						UpperCAmelCase       		=    0.1

			# Initialize flow
			UpperCAmelCase       		=    np.zeros_like(UpperCamelCase__			)
			UpperCAmelCase       		=    np.zeros_like(UpperCamelCase__			)

			# Prepare kernels for the calculation of the derivatives and the average velocity
			UpperCAmelCase       		=    np.array([[-1, 1], [-1, 1]]			) * 0.25
			UpperCAmelCase       		=    np.array([[-1, -1], [1, 1]]			) * 0.25
			UpperCAmelCase       		=    np.array([[1, 1], [1, 1]]			) * 0.25
			UpperCAmelCase       		=    np.array(
			    [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]]			)

			# Iteratively refine the flow
			for _ in range(UpperCamelCase__			):
						UpperCAmelCase       		=    warp(UpperCamelCase__      ,      UpperCamelCase__      ,      UpperCamelCase__			)
						UpperCAmelCase       		=    convolve(UpperCamelCase__      ,      UpperCamelCase__			) + convolve(UpperCamelCase__      ,      UpperCamelCase__			)
						UpperCAmelCase       		=    convolve(UpperCamelCase__      ,      UpperCamelCase__			) + convolve(UpperCamelCase__      ,      UpperCamelCase__			)
						UpperCAmelCase       		=    convolve(UpperCamelCase__      ,      UpperCamelCase__			) + convolve(UpperCamelCase__      ,      -kernel_t			)

						UpperCAmelCase       		=    convolve(UpperCamelCase__      ,      UpperCamelCase__			)
						UpperCAmelCase       		=    convolve(UpperCamelCase__      ,      UpperCamelCase__			)

						# This updates the flow as proposed in the paper (Step 12)
						UpperCAmelCase       		=    (
						    derivative_x * avg_horizontal_velocity
						    + derivative_y * avg_vertical_velocity
						    + derivative_t
						)
						UpperCAmelCase       		=    update / (alpha**2 + derivative_x**2 + derivative_y**2)

						UpperCAmelCase       		=    avg_horizontal_velocity - derivative_x * update
						UpperCAmelCase       		=    avg_vertical_velocity - derivative_y * update

			return horizontal_flow, vertical_flow


if __name__ == "__main__":
				import doctest

				doctest.testmod()



