






"""simple docstring"""



import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
__A		:	Union[str, Any]      =		logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=2.0.0''', '''To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt''')



def 						lowercase   (    __snake_case    :			Any		, __snake_case    :			Union[str, Any]		, __snake_case    :			List[str]=0     ):
		lowercase_			:			Tuple								=       (size, size) if isinstance(__snake_case		, __snake_case     ) else size
		lowercase_			:			Optional[int]								=       img.size
		lowercase_			:			List[Any]								=       size[1] - original_height if original_height < size[1] else 0
		lowercase_			:			Dict								=       size[0] - original_width if original_width < size[0] else 0
		lowercase_			:			Optional[Any]								=       functional.pad(__snake_case		, (0, 0, pad_width, pad_height)		, fill=__snake_case     )
		return img





class  _UpperCAmelCase	:




					def __init__(    self					:						Any   ,						A					:						Any       )  ->  Dict:
							lowercase_			:			Tuple								=       transforms






					def __call__(    self					:						int   ,						A					:						Tuple   ,						A					:						Tuple       )  ->  Dict:
							for t in self.transforms:
									lowercase_			:			Union[str, Any]								=       t(A   ,						A       )
							return image, target





class  _UpperCAmelCase	:




					def __init__(    self					:						Union[str, Any]       )  ->  Optional[Any]:
							pass






					def __call__(    self					:						Optional[Any]   ,						A					:						Optional[int]   ,						A					:						int       )  ->  Optional[int]:
							return image, target





class  _UpperCAmelCase	:




					def __init__(    self					:						int   ,						A					:						str       )  ->  List[str]:
							lowercase_			:			str								=       size






					def __call__(    self					:						Tuple   ,						A					:						str   ,						A					:						str       )  ->  Union[str, Any]:
							lowercase_			:			List[str]								=       functional.resize(A   ,						self.size       )
							lowercase_			:			Any								=       functional.resize(A   ,						self.size   ,						interpolation=transforms.InterpolationMode.NEAREST       )
							return image, target





class  _UpperCAmelCase	:




					def __init__(    self					:						Optional[Any]   ,						A					:						Any   ,						A					:						Optional[Any]=None       )  ->  Any:
							lowercase_			:			str								=       min_size
							if max_size is None:
									lowercase_			:			List[Any]								=       min_size
							lowercase_			:			Optional[Any]								=       max_size






					def __call__(    self					:						Any   ,						A					:						int   ,						A					:						str       )  ->  str:
							lowercase_			:			Any								=       random.randint(self.min_size   ,						self.max_size       )
							lowercase_			:			Optional[Any]								=       functional.resize(A   ,						A       )
							lowercase_			:			Optional[int]								=       functional.resize(A   ,						A   ,						interpolation=transforms.InterpolationMode.NEAREST       )
							return image, target





class  _UpperCAmelCase	:




					def __init__(    self					:						str   ,						A					:						int       )  ->  Dict:
							lowercase_			:			Optional[Any]								=       size if isinstance(A   ,						A       ) else (size, size)






					def __call__(    self					:						str   ,						A					:						Tuple   ,						A					:						str       )  ->  Optional[int]:
							lowercase_			:			Union[str, Any]								=       pad_if_smaller(A   ,						self.size       )
							lowercase_			:			Dict								=       pad_if_smaller(A   ,						self.size   ,						fill=2_55       )
							lowercase_			:			Union[str, Any]								=       transforms.RandomCrop.get_params(A   ,						self.size       )
							lowercase_			:			Optional[int]								=       functional.crop(A   ,						*A       )
							lowercase_			:			Tuple								=       functional.crop(A   ,						*A       )
							return image, target





class  _UpperCAmelCase	:




					def __init__(    self					:						Any   ,						A					:						List[Any]       )  ->  Any:
							lowercase_			:			List[str]								=       flip_prob






					def __call__(    self					:						Optional[Any]   ,						A					:						Any   ,						A					:						Optional[int]       )  ->  Dict:
							if random.random() < self.flip_prob:
									lowercase_			:			Union[str, Any]								=       functional.hflip(A       )
									lowercase_			:			Optional[int]								=       functional.hflip(A       )
							return image, target





class  _UpperCAmelCase	:




					def __call__(    self					:						Tuple   ,						A					:						Optional[Any]   ,						A					:						Dict       )  ->  Optional[Any]:
							lowercase_			:			Optional[Any]								=       functional.pil_to_tensor(A       )
							lowercase_			:			Any								=       torch.as_tensor(np.array(A       )   ,						dtype=torch.intaa       )
							return image, target





class  _UpperCAmelCase	:




					def __init__(    self					:						List[Any]   ,						A					:						Any       )  ->  Optional[Any]:
							lowercase_			:			Optional[Any]								=       dtype






					def __call__(    self					:						Dict   ,						A					:						Optional[Any]   ,						A					:						int       )  ->  Tuple:
							lowercase_			:			Optional[int]								=       functional.convert_image_dtype(A   ,						self.dtype       )
							return image, target





class  _UpperCAmelCase	:




					def __init__(    self					:						str   ,						A					:						Optional[int]   ,						A					:						Union[str, Any]       )  ->  List[Any]:
							lowercase_			:			Union[str, Any]								=       mean
							lowercase_			:			str								=       std






					def __call__(    self					:						Dict   ,						A					:						Dict   ,						A					:						Optional[int]       )  ->  Union[str, Any]:
							lowercase_			:			Union[str, Any]								=       functional.normalize(A   ,						mean=self.mean   ,						std=self.std       )
							return image, target





class  _UpperCAmelCase	:




					def __call__(    self					:						Union[str, Any]   ,						A					:						str   ,						A					:						Union[str, Any]       )  ->  List[Any]:
							if not isinstance(A   ,						np.ndarray       ):
									lowercase_			:			Dict								=       np.array(A       ).astype(np.uinta       )
							# avoid using underflow conversion
							lowercase_			:			Dict								=       2_55
							lowercase_			:			Union[str, Any]								=       target - 1
							lowercase_			:			List[Any]								=       2_55

							lowercase_			:			int								=       Image.fromarray(A       )
							return image, target





@dataclass
class  _UpperCAmelCase	:
					SCREAMING_SNAKE_CASE_		:    Optional[str]							   =       field(
					    default="segments/sidewalk-semantic"       ,						metadata={
					        "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
					    }       ,						)
					SCREAMING_SNAKE_CASE_		:    Optional[str]							   =       field(
					    default=_A       ,						metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}							)
					SCREAMING_SNAKE_CASE_		:    Optional[float]							   =       field(
					    default=0.15       ,						metadata={"help": "Percent to split off of train for validation."}							)
					SCREAMING_SNAKE_CASE_		:    Optional[int]							   =       field(
					    default=_A       ,						metadata={
					        "help": (
					            "For debugging purposes or quicker training, truncate the number of training examples to this "
					            "value if set."
					        )
					    }       ,						)
					SCREAMING_SNAKE_CASE_		:    Optional[int]							   =       field(
					    default=_A       ,						metadata={
					        "help": (
					            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
					            "value if set."
					        )
					    }       ,						)
					SCREAMING_SNAKE_CASE_		:    Optional[bool]							   =       field(
					    default=_A       ,						metadata={"help": "Whether or not to reduce all labels by 1 and replace background by 255."}       ,						)




					def   A  (    self					:						Any       )  ->  List[str]:
							if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
									raise ValueError(
									    '''You must specify either a dataset name from the hub or a train and/or validation directory.'''       )





@dataclass
class  _UpperCAmelCase	:
					SCREAMING_SNAKE_CASE_		:    str							   =       field(
					    default="nvidia/mit-b0"       ,						metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}       ,						)
					SCREAMING_SNAKE_CASE_		:    Optional[str]							   =       field(
					    default=_A       ,						metadata={"help": "Pretrained config name or path if not the same as model_name"}							)
					SCREAMING_SNAKE_CASE_		:    Optional[str]							   =       field(
					    default=_A       ,						metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}							)
					SCREAMING_SNAKE_CASE_		:    str							   =       field(
					    default="main"       ,						metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}       ,						)
					SCREAMING_SNAKE_CASE_		:    str							   =       field(default=_A       ,						metadata={"help": "Name or path of preprocessor config."}							)
					SCREAMING_SNAKE_CASE_		:    bool							   =       field(
					    default=_A       ,						metadata={
					        "help": (
					            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
					            "with private models)."
					        )
					    }       ,						)



def 						lowercase   (    ):
		# See all possible arguments in src/transformers/training_args.py
		# or by passing the --help flag to this script.
		# We now keep distinct sets of args, for a cleaner separation of concerns.

		lowercase_			:			Dict								=       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
		if len(sys.argv     ) == 2 and sys.argv[1].endswith('''.json'''     ):
				# If we pass only one argument to the script and it's the path to a json file,
				# let's parse it to get our arguments.
				lowercase_			:			int								=       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
		else:
				lowercase_			:			Dict								=       parser.parse_args_into_dataclasses()

		# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
		# information sent is the one passed as arguments along with your Python/PyTorch versions.
		send_example_telemetry('''run_semantic_segmentation'''		, __snake_case		, __snake_case     )

		# Setup logging
		logging.basicConfig(
		    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''		, datefmt='''%m/%d/%Y %H:%M:%S'''		, handlers=[logging.StreamHandler(sys.stdout     )]		, )

		if training_args.should_log:
				# The default of training_args.log_level is passive, so we set log level at info here to have that default.
				transformers.utils.logging.set_verbosity_info()

		lowercase_			:			str								=       training_args.get_process_log_level()
		logger.setLevel(__snake_case     )
		transformers.utils.logging.set_verbosity(__snake_case     )
		transformers.utils.logging.enable_default_handler()
		transformers.utils.logging.enable_explicit_format()

		# Log on each process the small summary:
		logger.warning(
		    F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
		    + F'''distributed training: {bool(training_args.local_rank != -1     )}, 16-bits training: {training_args.fpaa}'''     )
		logger.info(F'''Training/evaluation parameters {training_args}'''     )

		# Detecting last checkpoint.
		lowercase_			:			Optional[Any]								=       None
		if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
				lowercase_			:			Optional[int]								=       get_last_checkpoint(training_args.output_dir     )
				if last_checkpoint is None and len(os.listdir(training_args.output_dir     )     ) > 0:
						raise ValueError(
						    F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
						    '''Use --overwrite_output_dir to overcome.'''     )
				elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
						logger.info(
						    F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
						    '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''     )

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
		lowercase_			:			Any								=       load_dataset(data_args.dataset_name		, cache_dir=model_args.cache_dir     )

		# Rename column names to standardized names (only "image" and "label" need to be present)
		if "pixel_values" in dataset["train"].column_names:
				lowercase_			:			str								=       dataset.rename_columns({'''pixel_values''': '''image'''}     )
		if "annotation" in dataset["train"].column_names:
				lowercase_			:			str								=       dataset.rename_columns({'''annotation''': '''label'''}     )

		# If we don't have a validation split, split off a percentage of train as validation.
		lowercase_			:			Optional[Any]								=       None if '''validation''' in dataset.keys() else data_args.train_val_split
		if isinstance(data_args.train_val_split		, __snake_case     ) and data_args.train_val_split > 0.0:
				lowercase_			:			Union[str, Any]								=       dataset['''train'''].train_test_split(data_args.train_val_split     )
				lowercase_			:			str								=       split['''train''']
				lowercase_			:			Tuple								=       split['''test''']

		# Prepare label mappings.
		# We'll include these in the model's config to get human readable labels in the Inference API.
		if data_args.dataset_name == "scene_parse_150":
				lowercase_			:			Dict								=       '''huggingface/label-files'''
				lowercase_			:			Union[str, Any]								=       '''ade20k-id2label.json'''
		else:
				lowercase_			:			List[Any]								=       data_args.dataset_name
				lowercase_			:			Union[str, Any]								=       '''id2label.json'''
		lowercase_			:			str								=       json.load(open(hf_hub_download(__snake_case		, __snake_case		, repo_type='''dataset'''     )		, '''r'''     )     )
		lowercase_			:			str								=       {int(__snake_case     ): v for k, v in idalabel.items()}
		lowercase_			:			Any								=       {v: str(__snake_case     ) for k, v in idalabel.items()}

		# Load the mean IoU metric from the datasets package
		lowercase_			:			Union[str, Any]								=       evaluate.load('''mean_iou'''     )

		# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
		# predictions and label_ids field) and has to return a dictionary string to float.
		@torch.no_grad()
		def compute_metrics(__snake_case    :			Union[str, Any]     ):
				lowercase_			:			Tuple								=       eval_pred
				lowercase_			:			List[str]								=       torch.from_numpy(__snake_case     )
				# scale the logits to the size of the label
				lowercase_			:			Union[str, Any]								=       nn.functional.interpolate(
				    __snake_case		, size=labels.shape[-2:]		, mode='''bilinear'''		, align_corners=__snake_case		, ).argmax(dim=1     )

				lowercase_			:			Optional[int]								=       logits_tensor.detach().cpu().numpy()
				lowercase_			:			Dict								=       metric.compute(
				    predictions=__snake_case		, references=__snake_case		, num_labels=len(__snake_case     )		, ignore_index=0		, reduce_labels=image_processor.do_reduce_labels		, )
				# add per category metrics as individual key-value pairs
				lowercase_			:			str								=       metrics.pop('''per_category_accuracy'''     ).tolist()
				lowercase_			:			Dict								=       metrics.pop('''per_category_iou'''     ).tolist()

				metrics.update({F'''accuracy_{idalabel[i]}''': v for i, v in enumerate(__snake_case     )}     )
				metrics.update({F'''iou_{idalabel[i]}''': v for i, v in enumerate(__snake_case     )}     )

				return metrics

		lowercase_			:			Dict								=       AutoConfig.from_pretrained(
		    model_args.config_name or model_args.model_name_or_path		, labelaid=__snake_case		, idalabel=__snake_case		, cache_dir=model_args.cache_dir		, revision=model_args.model_revision		, use_auth_token=True if model_args.use_auth_token else None		, )
		lowercase_			:			Dict								=       AutoModelForSemanticSegmentation.from_pretrained(
		    model_args.model_name_or_path		, from_tf=bool('''.ckpt''' in model_args.model_name_or_path     )		, config=__snake_case		, cache_dir=model_args.cache_dir		, revision=model_args.model_revision		, use_auth_token=True if model_args.use_auth_token else None		, )
		lowercase_			:			Dict								=       AutoImageProcessor.from_pretrained(
		    model_args.image_processor_name or model_args.model_name_or_path		, cache_dir=model_args.cache_dir		, revision=model_args.model_revision		, use_auth_token=True if model_args.use_auth_token else None		, )

		# Define torchvision transforms to be applied to each image + target.
		# Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
		# Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
		if "shortest_edge" in image_processor.size:
				# We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
				lowercase_			:			Optional[Any]								=       (image_processor.size['''shortest_edge'''], image_processor.size['''shortest_edge'''])
		else:
				lowercase_			:			Optional[Any]								=       (image_processor.size['''height'''], image_processor.size['''width'''])
		lowercase_			:			Any								=       Compose(
		    [
		        ReduceLabels() if data_args.reduce_labels else Identity(),
		        RandomCrop(size=__snake_case     ),
		        RandomHorizontalFlip(flip_prob=0.5     ),
		        PILToTensor(),
		        ConvertImageDtype(torch.float     ),
		        Normalize(mean=image_processor.image_mean		, std=image_processor.image_std     ),
		    ]     )
		# Define torchvision transform to be applied to each image.
		# jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
		lowercase_			:			int								=       Compose(
		    [
		        ReduceLabels() if data_args.reduce_labels else Identity(),
		        Resize(size=__snake_case     ),
		        PILToTensor(),
		        ConvertImageDtype(torch.float     ),
		        Normalize(mean=image_processor.image_mean		, std=image_processor.image_std     ),
		    ]     )

		def preprocess_train(__snake_case    :			Dict     ):
				lowercase_			:			Dict								=       []
				lowercase_			:			Any								=       []
				for image, target in zip(example_batch['''image''']		, example_batch['''label''']     ):
						lowercase_			:			str								=       train_transforms(image.convert('''RGB'''     )		, __snake_case     )
						pixel_values.append(__snake_case     )
						labels.append(__snake_case     )

				lowercase_			:			Union[str, Any]								=       {}
				lowercase_			:			Any								=       torch.stack(__snake_case     )
				lowercase_			:			Optional[Any]								=       torch.stack(__snake_case     )

				return encoding

		def preprocess_val(__snake_case    :			str     ):
				lowercase_			:			List[Any]								=       []
				lowercase_			:			Optional[Any]								=       []
				for image, target in zip(example_batch['''image''']		, example_batch['''label''']     ):
						lowercase_			:			Dict								=       val_transforms(image.convert('''RGB'''     )		, __snake_case     )
						pixel_values.append(__snake_case     )
						labels.append(__snake_case     )

				lowercase_			:			Dict								=       {}
				lowercase_			:			Optional[int]								=       torch.stack(__snake_case     )
				lowercase_			:			Union[str, Any]								=       torch.stack(__snake_case     )

				return encoding

		if training_args.do_train:
				if "train" not in dataset:
						raise ValueError('''--do_train requires a train dataset'''     )
				if data_args.max_train_samples is not None:
						lowercase_			:			Tuple								=       (
						    dataset['''train'''].shuffle(seed=training_args.seed     ).select(range(data_args.max_train_samples     )     )
						)
				# Set the training transforms
				dataset["train"].set_transform(__snake_case     )

		if training_args.do_eval:
				if "validation" not in dataset:
						raise ValueError('''--do_eval requires a validation dataset'''     )
				if data_args.max_eval_samples is not None:
						lowercase_			:			Union[str, Any]								=       (
						    dataset['''validation'''].shuffle(seed=training_args.seed     ).select(range(data_args.max_eval_samples     )     )
						)
				# Set the validation transforms
				dataset["validation"].set_transform(__snake_case     )

		# Initalize our trainer
		lowercase_			:			List[str]								=       Trainer(
		    model=__snake_case		, args=__snake_case		, train_dataset=dataset['''train'''] if training_args.do_train else None		, eval_dataset=dataset['''validation'''] if training_args.do_eval else None		, compute_metrics=__snake_case		, tokenizer=__snake_case		, data_collator=__snake_case		, )

		# Training
		if training_args.do_train:
				lowercase_			:			Any								=       None
				if training_args.resume_from_checkpoint is not None:
						lowercase_			:			Union[str, Any]								=       training_args.resume_from_checkpoint
				elif last_checkpoint is not None:
						lowercase_			:			Any								=       last_checkpoint
				lowercase_			:			Any								=       trainer.train(resume_from_checkpoint=__snake_case     )
				trainer.save_model()
				trainer.log_metrics('''train'''		, train_result.metrics     )
				trainer.save_metrics('''train'''		, train_result.metrics     )
				trainer.save_state()

		# Evaluation
		if training_args.do_eval:
				lowercase_			:			int								=       trainer.evaluate()
				trainer.log_metrics('''eval'''		, __snake_case     )
				trainer.save_metrics('''eval'''		, __snake_case     )

		# Write model card and (optionally) push to hub
		lowercase_			:			Union[str, Any]								=       {
		    '''finetuned_from''': model_args.model_name_or_path,
		    '''dataset''': data_args.dataset_name,
		    '''tags''': ['''image-segmentation''', '''vision'''],
		}
		if training_args.push_to_hub:
				trainer.push_to_hub(**__snake_case     )
		else:
				trainer.create_model_card(**__snake_case     )


if __name__ == "__main__":
						main()












"""simple docstring"""



import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
						import os

						# The slow tests are often failing with OOM error on GPU
						# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
						# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
						__A		:	Union[str, Any]      =		'''platform'''

						import jax
						import jax.numpy as jnp

						from transformers import MarianTokenizer
						from transformers.models.marian.modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, shift_tokens_right



def 						lowercase   (    __snake_case    :			Union[str, Any]		, __snake_case    :			Optional[int]		, __snake_case    :			List[str]=None		, __snake_case    :			List[str]=None		, __snake_case    :			str=None		, __snake_case    :			List[str]=None		, __snake_case    :			Any=None		, __snake_case    :			List[Any]=None		, ):
		if attention_mask is None:
				lowercase_			:			int								=       np.where(input_ids != config.pad_token_id		, 1		, 0     )
		if decoder_attention_mask is None:
				lowercase_			:			Tuple								=       np.where(decoder_input_ids != config.pad_token_id		, 1		, 0     )
		if head_mask is None:
				lowercase_			:			Any								=       np.ones((config.encoder_layers, config.encoder_attention_heads)     )
		if decoder_head_mask is None:
				lowercase_			:			Optional[Any]								=       np.ones((config.decoder_layers, config.decoder_attention_heads)     )
		if cross_attn_head_mask is None:
				lowercase_			:			int								=       np.ones((config.decoder_layers, config.decoder_attention_heads)     )
		return {
		    "input_ids": input_ids,
		    "decoder_input_ids": decoder_input_ids,
		    "attention_mask": attention_mask,
		    "decoder_attention_mask": attention_mask,
		}





class  _UpperCAmelCase	:




					def __init__(    self					:						Union[str, Any]   ,						A					:						Union[str, Any]   ,						A					:						Union[str, Any]=13   ,						A					:						Tuple=7   ,						A					:						List[Any]=True   ,						A					:						List[Any]=False   ,						A					:						int=99   ,						A					:						Optional[int]=16   ,						A					:						Tuple=2   ,						A					:						Optional[int]=4   ,						A					:						Any=4   ,						A					:						List[str]="gelu"   ,						A					:						List[str]=0.1   ,						A					:						Union[str, Any]=0.1   ,						A					:						Union[str, Any]=32   ,						A					:						int=2   ,						A					:						Optional[Any]=1   ,						A					:						int=0   ,						A					:						Tuple=0.02   ,						)  ->  Union[str, Any]:
							lowercase_			:			Any								=       parent
							lowercase_			:			Optional[int]								=       batch_size
							lowercase_			:			str								=       seq_length
							lowercase_			:			Union[str, Any]								=       is_training
							lowercase_			:			List[str]								=       use_labels
							lowercase_			:			Tuple								=       vocab_size
							lowercase_			:			Tuple								=       hidden_size
							lowercase_			:			Tuple								=       num_hidden_layers
							lowercase_			:			Optional[Any]								=       num_attention_heads
							lowercase_			:			int								=       intermediate_size
							lowercase_			:			List[Any]								=       hidden_act
							lowercase_			:			Union[str, Any]								=       hidden_dropout_prob
							lowercase_			:			Optional[Any]								=       attention_probs_dropout_prob
							lowercase_			:			Optional[int]								=       max_position_embeddings
							lowercase_			:			Any								=       eos_token_id
							lowercase_			:			Optional[int]								=       pad_token_id
							lowercase_			:			int								=       bos_token_id
							lowercase_			:			int								=       initializer_range




					def   A  (    self					:						List[str]       )  ->  Union[str, Any]:
							lowercase_			:			Optional[int]								=       np.clip(ids_tensor([self.batch_size, self.seq_length - 1]   ,						self.vocab_size       )   ,						3   ,						self.vocab_size       )
							lowercase_			:			Dict								=       np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)   ,						dtype=np.intaa       ))   ,						-1       )

							lowercase_			:			Optional[int]								=       shift_tokens_right(A   ,						1   ,						2       )

							lowercase_			:			Tuple								=       MarianConfig(
							    vocab_size=self.vocab_size   ,						d_model=self.hidden_size   ,						encoder_layers=self.num_hidden_layers   ,						decoder_layers=self.num_hidden_layers   ,						encoder_attention_heads=self.num_attention_heads   ,						decoder_attention_heads=self.num_attention_heads   ,						encoder_ffn_dim=self.intermediate_size   ,						decoder_ffn_dim=self.intermediate_size   ,						dropout=self.hidden_dropout_prob   ,						attention_dropout=self.attention_probs_dropout_prob   ,						max_position_embeddings=self.max_position_embeddings   ,						eos_token_id=self.eos_token_id   ,						bos_token_id=self.bos_token_id   ,						pad_token_id=self.pad_token_id   ,						initializer_range=self.initializer_range   ,						use_cache=A   ,						)
							lowercase_			:			Tuple								=       prepare_marian_inputs_dict(A   ,						A   ,						A       )
							return config, inputs_dict




					def   A  (    self					:						Any       )  ->  List[Any]:
							lowercase_	, lowercase_			:			Dict								=       self.prepare_config_and_inputs()
							return config, inputs_dict




					def   A  (    self					:						int   ,						A					:						Any   ,						A					:						List[Any]   ,						A					:						Optional[Any]       )  ->  Union[str, Any]:
							lowercase_			:			Dict								=       20
							lowercase_			:			Optional[Any]								=       model_class_name(A       )

							lowercase_			:			Tuple								=       model.encode(inputs_dict['''input_ids''']       )

							lowercase_	, lowercase_			:			int								=       (
							    inputs_dict['''decoder_input_ids'''],
							    inputs_dict['''decoder_attention_mask'''],
							)

							lowercase_			:			Any								=       model.init_cache(decoder_input_ids.shape[0]   ,						A   ,						A       )
							lowercase_			:			int								=       jnp.ones((decoder_input_ids.shape[0], max_decoder_length)   ,						dtype='''i4'''       )

							lowercase_			:			Any								=       jnp.broadcast_to(
							    jnp.arange(decoder_input_ids.shape[-1] - 1       )[None, :]   ,						(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)   ,						)
							lowercase_			:			str								=       model.decode(
							    decoder_input_ids[:, :-1]   ,						A   ,						decoder_attention_mask=A   ,						past_key_values=A   ,						decoder_position_ids=A   ,						)

							lowercase_			:			List[str]								=       jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]   ,						dtype='''i4'''       )
							lowercase_			:			Tuple								=       model.decode(
							    decoder_input_ids[:, -1:]   ,						A   ,						decoder_attention_mask=A   ,						past_key_values=outputs_cache.past_key_values   ,						decoder_position_ids=A   ,						)

							lowercase_			:			List[Any]								=       model.decode(A   ,						A       )

							lowercase_			:			Union[str, Any]								=       np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])       )       )
							self.parent.assertTrue(diff < 1e-3   ,						msg=F'''Max diff is {diff}'''       )






					def   A  (    self					:						Optional[Any]   ,						A					:						Tuple   ,						A					:						Optional[Any]   ,						A					:						Any       )  ->  Tuple:
							lowercase_			:			List[str]								=       20
							lowercase_			:			List[str]								=       model_class_name(A       )

							lowercase_			:			Union[str, Any]								=       model.encode(inputs_dict['''input_ids''']       )

							lowercase_	, lowercase_			:			str								=       (
							    inputs_dict['''decoder_input_ids'''],
							    inputs_dict['''decoder_attention_mask'''],
							)

							lowercase_			:			Any								=       jnp.concatenate(
							    [
							        decoder_attention_mask,
							        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])       ),
							    ]   ,						axis=-1   ,						)

							lowercase_			:			List[str]								=       model.init_cache(decoder_input_ids.shape[0]   ,						A   ,						A       )
							lowercase_			:			Dict								=       jnp.broadcast_to(
							    jnp.arange(decoder_input_ids.shape[-1] - 1       )[None, :]   ,						(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)   ,						)

							lowercase_			:			Union[str, Any]								=       model.decode(
							    decoder_input_ids[:, :-1]   ,						A   ,						decoder_attention_mask=A   ,						past_key_values=A   ,						decoder_position_ids=A   ,						)
							lowercase_			:			int								=       jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]   ,						dtype='''i4'''       )
							lowercase_			:			int								=       model.decode(
							    decoder_input_ids[:, -1:]   ,						A   ,						past_key_values=outputs_cache.past_key_values   ,						decoder_attention_mask=A   ,						decoder_position_ids=A   ,						)

							lowercase_			:			int								=       model.decode(A   ,						A   ,						decoder_attention_mask=A       )

							lowercase_			:			Any								=       np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])       )       )
							self.parent.assertTrue(diff < 1e-3   ,						msg=F'''Max diff is {diff}'''       )





@require_flax
class  _UpperCAmelCase	(			_A       ,						unittest.TestCase       ,						_A							):
					SCREAMING_SNAKE_CASE_		:    Optional[Any]							   =       True
					SCREAMING_SNAKE_CASE_		:    Optional[Any]							   =       (FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
					SCREAMING_SNAKE_CASE_		:    int							   =       (FlaxMarianMTModel,) if is_flax_available() else ()




					def   A  (    self					:						Dict       )  ->  List[Any]:
							lowercase_			:			str								=       FlaxMarianModelTester(self       )




					def   A  (    self					:						Optional[int]       )  ->  List[Any]:
							lowercase_	, lowercase_			:			Tuple								=       self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
									self.model_tester.check_use_cache_forward(A   ,						A   ,						A       )




					def   A  (    self					:						List[Any]       )  ->  Dict:
							lowercase_	, lowercase_			:			List[str]								=       self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
									self.model_tester.check_use_cache_forward_with_attn_mask(A   ,						A   ,						A       )




					def   A  (    self					:						Tuple       )  ->  int:
							lowercase_	, lowercase_			:			Dict								=       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__       ):
											lowercase_			:			Dict								=       self._prepare_for_class(A   ,						A       )
											lowercase_			:			Tuple								=       model_class(A       )

											@jax.jit
											def encode_jitted(A					:						Tuple   ,						A					:						Optional[int]=None   ,						**A					:						str       ):
													return model.encode(input_ids=A   ,						attention_mask=A       )

											with self.subTest('''JIT Enabled'''       ):
													lowercase_			:			List[str]								=       encode_jitted(**A       ).to_tuple()

											with self.subTest('''JIT Disabled'''       ):
													with jax.disable_jit():
															lowercase_			:			int								=       encode_jitted(**A       ).to_tuple()

											self.assertEqual(len(A       )   ,						len(A       )       )
											for jitted_output, output in zip(A   ,						A       ):
													self.assertEqual(jitted_output.shape   ,						output.shape       )




					def   A  (    self					:						Tuple       )  ->  Union[str, Any]:
							lowercase_	, lowercase_			:			List[str]								=       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__       ):
											lowercase_			:			Dict								=       model_class(A       )
											lowercase_			:			Optional[int]								=       model.encode(inputs_dict['''input_ids''']   ,						inputs_dict['''attention_mask''']       )

											lowercase_			:			List[str]								=       {
											    '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''],
											    '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''],
											    '''encoder_outputs''': encoder_outputs,
											}

											@jax.jit
											def decode_jitted(A					:						Tuple   ,						A					:						Tuple   ,						A					:						int       ):
													return model.decode(
													    decoder_input_ids=A   ,						decoder_attention_mask=A   ,						encoder_outputs=A   ,						)

											with self.subTest('''JIT Enabled'''       ):
													lowercase_			:			List[str]								=       decode_jitted(**A       ).to_tuple()

											with self.subTest('''JIT Disabled'''       ):
													with jax.disable_jit():
															lowercase_			:			str								=       decode_jitted(**A       ).to_tuple()

											self.assertEqual(len(A       )   ,						len(A       )       )
											for jitted_output, output in zip(A   ,						A       ):
													self.assertEqual(jitted_output.shape   ,						output.shape       )






					@slow
					def   A  (    self					:						Optional[int]       )  ->  str:
							for model_class_name in self.all_model_classes:
									lowercase_			:			List[Any]								=       model_class_name.from_pretrained('''Helsinki-NLP/opus-mt-en-de'''       )
									# FlaxMarianForSequenceClassification expects eos token in input_ids
									lowercase_			:			Union[str, Any]								=       np.ones((1, 1)       ) * model.config.eos_token_id
									lowercase_			:			str								=       model(A       )
									self.assertIsNotNone(A       )





@require_flax
@require_sentencepiece
@require_tokenizers
class  _UpperCAmelCase	(			unittest.TestCase							):
					SCREAMING_SNAKE_CASE_		:    int							   =       None
					SCREAMING_SNAKE_CASE_		:    str							   =       None




					@classmethod
					def   A  (    cls					:						List[Any]       )  ->  None:
							lowercase_			:			List[Any]								=       F'''Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'''
							return cls




					@cached_property
					def   A  (    self					:						List[str]       )  ->  Optional[int]:
							return MarianTokenizer.from_pretrained(self.model_name       )




					@property
					def   A  (    self					:						Dict       )  ->  int:
							return self.tokenizer.eos_token_id




					@cached_property
					def   A  (    self					:						Union[str, Any]       )  ->  str:
							lowercase_			:			FlaxMarianMTModel								=       FlaxMarianMTModel.from_pretrained(self.model_name       )
							self.assertEqual(model.config.decoder_start_token_id   ,						model.config.pad_token_id       )
							return model




					def   A  (    self					:						Tuple   ,						**A					:						Optional[Any]       )  ->  Dict:
							lowercase_			:			Dict								=       self.translate_src_text(**A       )
							self.assertListEqual(self.expected_text   ,						A       )






					def   A  (    self					:						List[str]   ,						**A					:						Union[str, Any]       )  ->  List[str]:
							lowercase_			:			Optional[Any]								=       self.tokenizer(self.src_text   ,						padding=A   ,						return_tensors='''np'''   ,						**A       )
							lowercase_			:			Union[str, Any]								=       self.model.generate(
							    model_inputs.input_ids   ,						attention_mask=model_inputs.attention_mask   ,						num_beams=2   ,						max_length=1_28   ,						).sequences
							lowercase_			:			Any								=       self.tokenizer.batch_decode(A   ,						skip_special_tokens=A       )
							return generated_words





@require_flax
@require_sentencepiece
@require_tokenizers
class  _UpperCAmelCase	(			_A							):
					SCREAMING_SNAKE_CASE_		:    Any							   =       "en"
					SCREAMING_SNAKE_CASE_		:    Optional[Any]							   =       "fr"
					SCREAMING_SNAKE_CASE_		:    Tuple							   =       [
					    "I am a small frog.",
					    "Now I can forget the 100 words of german that I know.",
					]
					SCREAMING_SNAKE_CASE_		:    Optional[Any]							   =       [
					    "Je suis une petite grenouille.",
					    "Maintenant, je peux oublier les 100 mots d'allemand que je connais.",
					]




					@slow
					def   A  (    self					:						str       )  ->  List[Any]:
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class  _UpperCAmelCase	(			_A							):
					SCREAMING_SNAKE_CASE_		:    Any							   =       "fr"
					SCREAMING_SNAKE_CASE_		:    str							   =       "en"
					SCREAMING_SNAKE_CASE_		:    List[Any]							   =       [
					    "Donnez moi le micro.",
					    "Tom et Mary étaient assis à une table.",  # Accents
					]
					SCREAMING_SNAKE_CASE_		:    Tuple							   =       [
					    "Give me the microphone.",
					    "Tom and Mary were sitting at a table.",
					]




					@slow
					def   A  (    self					:						List[str]       )  ->  List[Any]:
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class  _UpperCAmelCase	(			_A							):
					SCREAMING_SNAKE_CASE_		:    Tuple							   =       "mt"
					SCREAMING_SNAKE_CASE_		:    List[str]							   =       "en"
					SCREAMING_SNAKE_CASE_		:    Dict							   =       ["Billi messu b'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem."]
					SCREAMING_SNAKE_CASE_		:    Union[str, Any]							   =       ["Touching gently, Jesus healed a man who was affected by the sad disease of leprosy."]




					@slow
					def   A  (    self					:						List[str]       )  ->  List[Any]:
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class  _UpperCAmelCase	(			_A							):
					SCREAMING_SNAKE_CASE_		:    Optional[int]							   =       "en"
					SCREAMING_SNAKE_CASE_		:    Optional[Any]							   =       "de"
					SCREAMING_SNAKE_CASE_		:    int							   =       [
					    "I am a small frog.",
					    "Now I can forget the 100 words of german that I know.",
					    "Tom asked his teacher for advice.",
					    "That's how I would do it.",
					    "Tom really admired Mary's courage.",
					    "Turn around and close your eyes.",
					]
					SCREAMING_SNAKE_CASE_		:    Tuple							   =       [
					    "Ich bin ein kleiner Frosch.",
					    "Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.",
					    "Tom bat seinen Lehrer um Rat.",
					    "So würde ich das machen.",
					    "Tom bewunderte Marias Mut wirklich.",
					    "Drehen Sie sich um und schließen Sie die Augen.",
					]




					@slow
					def   A  (    self					:						List[Any]       )  ->  Union[str, Any]:
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class  _UpperCAmelCase	(			_A							):
					SCREAMING_SNAKE_CASE_		:    Dict							   =       "en"
					SCREAMING_SNAKE_CASE_		:    Dict							   =       "zh"
					SCREAMING_SNAKE_CASE_		:    int							   =       ["My name is Wolfgang and I live in Berlin"]
					SCREAMING_SNAKE_CASE_		:    Any							   =       ["我叫沃尔夫冈 我住在柏林"]




					@slow
					def   A  (    self					:						List[str]       )  ->  Union[str, Any]:
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class  _UpperCAmelCase	(			_A							):
					SCREAMING_SNAKE_CASE_		:    Tuple							   =       "ru"
					SCREAMING_SNAKE_CASE_		:    List[str]							   =       "fr"
					SCREAMING_SNAKE_CASE_		:    Dict							   =       ["Он показал мне рукопись своей новой пьесы."]
					SCREAMING_SNAKE_CASE_		:    int							   =       ["Il m'a montré le manuscrit de sa nouvelle pièce."]




					@slow
					def   A  (    self					:						Optional[Any]       )  ->  Optional[int]:
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class  _UpperCAmelCase	(			_A							):
					SCREAMING_SNAKE_CASE_		:    int							   =       "en"
					SCREAMING_SNAKE_CASE_		:    Tuple							   =       "ROMANCE"
					SCREAMING_SNAKE_CASE_		:    Tuple							   =       [
					    ">>fr<< Don't spend so much time watching TV.",
					    ">>pt<< Your message has been sent.",
					    ">>es<< He's two years older than me.",
					]
					SCREAMING_SNAKE_CASE_		:    List[Any]							   =       [
					    "Ne passez pas autant de temps à regarder la télé.",
					    "A sua mensagem foi enviada.",
					    "Es dos años más viejo que yo.",
					]




					@slow
					def   A  (    self					:						Optional[int]       )  ->  int:
							self._assert_generated_batch_equal_expected()



