





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
__lowerCAmelCase 	=      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      a    (   _lowercase :  Any			,    _lowercase :  Optional[int]			,    _lowercase :  Any=0							)  ->str:
		UpperCamelCase__								=						(size, size) if isinstance(__A			,    __A							) else size
		UpperCamelCase__								=						img.size
		UpperCamelCase__								=						size[1] - original_height if original_height < size[1] else 0
		UpperCamelCase__								=						size[0] - original_width if original_width < size[0] else 0
		UpperCamelCase__								=						functional.pad(__A			,    (0, 0, pad_width, pad_height)			,    fill=__A							)
		return img




class 	_UpperCAmelCase						:




					def __init__(    self     ,   __lowerCAmelCase							)    ->	Union[str, Any]:
							UpperCamelCase__								=						transforms




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	str:
							for t in self.transforms:
									UpperCamelCase__								=						t(lowerCamelCase_     ,   lowerCamelCase_							)
							return image, target




class 	_UpperCAmelCase						:




					def __init__(    self							)    ->	Tuple:
							pass




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	int:
							return image, target




class 	_UpperCAmelCase						:




					def __init__(    self     ,   __lowerCAmelCase							)    ->	Union[str, Any]:
							UpperCamelCase__								=						size




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Optional[Any]:
							UpperCamelCase__								=						functional.resize(lowerCamelCase_     ,   self.size							)
							UpperCamelCase__								=						functional.resize(lowerCamelCase_     ,   self.size     ,   interpolation=transforms.InterpolationMode.NEAREST							)
							return image, target




class 	_UpperCAmelCase						:




					def __init__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase=None							)    ->	Any:
							UpperCamelCase__								=						min_size
							if max_size is None:
									UpperCamelCase__								=						min_size
							UpperCamelCase__								=						max_size




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Union[str, Any]:
							UpperCamelCase__								=						random.randint(self.min_size     ,   self.max_size							)
							UpperCamelCase__								=						functional.resize(lowerCamelCase_     ,   lowerCamelCase_							)
							UpperCamelCase__								=						functional.resize(lowerCamelCase_     ,   lowerCamelCase_     ,   interpolation=transforms.InterpolationMode.NEAREST							)
							return image, target




class 	_UpperCAmelCase						:




					def __init__(    self     ,   __lowerCAmelCase							)    ->	int:
							UpperCamelCase__								=						size if isinstance(lowerCamelCase_     ,   lowerCamelCase_							) else (size, size)




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Optional[Any]:
							UpperCamelCase__								=						pad_if_smaller(lowerCamelCase_     ,   self.size							)
							UpperCamelCase__								=						pad_if_smaller(lowerCamelCase_     ,   self.size     ,   fill=255							)
							UpperCamelCase__								=						transforms.RandomCrop.get_params(lowerCamelCase_     ,   self.size							)
							UpperCamelCase__								=						functional.crop(lowerCamelCase_     ,   *lowerCamelCase_							)
							UpperCamelCase__								=						functional.crop(lowerCamelCase_     ,   *lowerCamelCase_							)
							return image, target




class 	_UpperCAmelCase						:




					def __init__(    self     ,   __lowerCAmelCase							)    ->	Tuple:
							UpperCamelCase__								=						flip_prob




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Any:
							if random.random() < self.flip_prob:
									UpperCamelCase__								=						functional.hflip(lowerCamelCase_							)
									UpperCamelCase__								=						functional.hflip(lowerCamelCase_							)
							return image, target




class 	_UpperCAmelCase						:




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	List[str]:
							UpperCamelCase__								=						functional.pil_to_tensor(lowerCamelCase_							)
							UpperCamelCase__								=						torch.as_tensor(np.array(lowerCamelCase_							)     ,   dtype=torch.intaa							)
							return image, target




class 	_UpperCAmelCase						:




					def __init__(    self     ,   __lowerCAmelCase							)    ->	Dict:
							UpperCamelCase__								=						dtype




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	str:
							UpperCamelCase__								=						functional.convert_image_dtype(lowerCamelCase_     ,   self.dtype							)
							return image, target




class 	_UpperCAmelCase						:




					def __init__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Any:
							UpperCamelCase__								=						mean
							UpperCamelCase__								=						std




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Any:
							UpperCamelCase__								=						functional.normalize(lowerCamelCase_     ,   mean=self.mean     ,   std=self.std							)
							return image, target




class 	_UpperCAmelCase						:




					def __call__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Dict:
							if not isinstance(lowerCamelCase_     ,   np.ndarray							):
									UpperCamelCase__								=						np.array(lowerCamelCase_							).astype(np.uinta							)
							# avoid using underflow conversion
							UpperCamelCase__								=						255
							UpperCamelCase__								=						target - 1
							UpperCamelCase__								=						255

							UpperCamelCase__								=						Image.fromarray(lowerCamelCase_							)
							return image, target




@dataclass
class 	_UpperCAmelCase						:
					__A        = 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)."
					    }			,							)
					__A        = field(
					    default=_lowerCamelCase			,							metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}       )
					__A        = field(
					    default=0.15			,							metadata={"help": "Percent to split off of train for validation."}       )
					__A        = field(
					    default=_lowerCamelCase			,							metadata={
					        "help": (
					            "For debugging purposes or quicker training, truncate the number of training examples to this "
					            "value if set."
					        )
					    }			,							)
					__A        = field(
					    default=_lowerCamelCase			,							metadata={
					        "help": (
					            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
					            "value if set."
					        )
					    }			,							)
					__A        = field(
					    default=_lowerCamelCase			,							metadata={"help": "Whether or not to reduce all labels by 1 and replace background by 255."}			,							)




					def 						snake_case_		(    self							)    ->	Dict:
							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						:
					__A        = field(
					    default="nvidia/mit-b0"			,							metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}			,							)
					__A        = field(
					    default=_lowerCamelCase			,							metadata={"help": "Pretrained config name or path if not the same as model_name"}       )
					__A        = field(
					    default=_lowerCamelCase			,							metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}       )
					__A        = field(
					    default="main"			,							metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}			,							)
					__A        = field(default=_lowerCamelCase			,							metadata={"help": "Name or path of preprocessor config."}       )
					__A        = field(
					    default=_lowerCamelCase			,							metadata={
					        "help": (
					            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
					            "with private models)."
					        )
					    }			,							)



def      a    (   )  ->List[str]:
		UpperCamelCase__								=						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.
				UpperCamelCase__								=						parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]							)							)
		else:
				UpperCamelCase__								=						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"""			,    __A			,    __A							)

		# 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()

		UpperCamelCase__								=						training_args.get_process_log_level()
		logger.setLevel(__A							)
		transformers.utils.logging.set_verbosity(__A							)
		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.
		UpperCamelCase__								=						None
		if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
				UpperCamelCase__								=						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
		UpperCamelCase__								=						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:
				UpperCamelCase__								=						dataset.rename_columns({"""pixel_values""": """image"""}							)
		if "annotation" in dataset["train"].column_names:
				UpperCamelCase__								=						dataset.rename_columns({"""annotation""": """label"""}							)

		# If we don't have a validation split, split off a percentage of train as validation.
		UpperCamelCase__								=						None if '''validation''' in dataset.keys() else data_args.train_val_split
		if isinstance(data_args.train_val_split			,    __A							) and data_args.train_val_split > 0.0:
				UpperCamelCase__								=						dataset['''train'''].train_test_split(data_args.train_val_split							)
				UpperCamelCase__								=						split['''train''']
				UpperCamelCase__								=						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":
				UpperCamelCase__								=						'''huggingface/label-files'''
				UpperCamelCase__								=						'''ade20k-id2label.json'''
		else:
				UpperCamelCase__								=						data_args.dataset_name
				UpperCamelCase__								=						'''id2label.json'''
		UpperCamelCase__								=						json.load(open(hf_hub_download(__A			,    __A			,    repo_type="""dataset"""							)			,    """r"""							)							)
		UpperCamelCase__								=						{int(__A							): v for k, v in idalabel.items()}
		UpperCamelCase__								=						{v: str(__A							) for k, v in idalabel.items()}

		# Load the mean IoU metric from the datasets package
		UpperCamelCase__								=						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(_lowercase :  Tuple							):
				UpperCamelCase__								=						eval_pred
				UpperCamelCase__								=						torch.from_numpy(__A							)
				# scale the logits to the size of the label
				UpperCamelCase__								=						nn.functional.interpolate(
				    __A			,    size=labels.shape[-2:]			,    mode="""bilinear"""			,    align_corners=__A			,    ).argmax(dim=1							)

				UpperCamelCase__								=						logits_tensor.detach().cpu().numpy()
				UpperCamelCase__								=						metric.compute(
				    predictions=__A			,    references=__A			,    num_labels=len(__A							)			,    ignore_index=0			,    reduce_labels=image_processor.do_reduce_labels			,    )
				# add per category metrics as individual key-value pairs
				UpperCamelCase__								=						metrics.pop("""per_category_accuracy"""							).tolist()
				UpperCamelCase__								=						metrics.pop("""per_category_iou"""							).tolist()

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

				return metrics

		UpperCamelCase__								=						AutoConfig.from_pretrained(
		    model_args.config_name or model_args.model_name_or_path			,    labelaid=__A			,    idalabel=__A			,    cache_dir=model_args.cache_dir			,    revision=model_args.model_revision			,    use_auth_token=True if model_args.use_auth_token else None			,    )
		UpperCamelCase__								=						AutoModelForSemanticSegmentation.from_pretrained(
		    model_args.model_name_or_path			,    from_tf=bool(""".ckpt""" in model_args.model_name_or_path							)			,    config=__A			,    cache_dir=model_args.cache_dir			,    revision=model_args.model_revision			,    use_auth_token=True if model_args.use_auth_token else None			,    )
		UpperCamelCase__								=						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.
				UpperCamelCase__								=						(image_processor.size['''shortest_edge'''], image_processor.size['''shortest_edge'''])
		else:
				UpperCamelCase__								=						(image_processor.size['''height'''], image_processor.size['''width'''])
		UpperCamelCase__								=						Compose(
		    [
		        ReduceLabels() if data_args.reduce_labels else Identity(),
		        RandomCrop(size=__A							),
		        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)
		UpperCamelCase__								=						Compose(
		    [
		        ReduceLabels() if data_args.reduce_labels else Identity(),
		        Resize(size=__A							),
		        PILToTensor(),
		        ConvertImageDtype(torch.float							),
		        Normalize(mean=image_processor.image_mean			,    std=image_processor.image_std							),
		    ]							)

		def preprocess_train(_lowercase :  Dict							):
				UpperCamelCase__								=						[]
				UpperCamelCase__								=						[]
				for image, target in zip(example_batch["""image"""]			,    example_batch["""label"""]							):
						UpperCamelCase__								=						train_transforms(image.convert("""RGB"""							)			,    __A							)
						pixel_values.append(__A							)
						labels.append(__A							)

				UpperCamelCase__								=						{}
				UpperCamelCase__								=						torch.stack(__A							)
				UpperCamelCase__								=						torch.stack(__A							)

				return encoding

		def preprocess_val(_lowercase :  Any							):
				UpperCamelCase__								=						[]
				UpperCamelCase__								=						[]
				for image, target in zip(example_batch["""image"""]			,    example_batch["""label"""]							):
						UpperCamelCase__								=						val_transforms(image.convert("""RGB"""							)			,    __A							)
						pixel_values.append(__A							)
						labels.append(__A							)

				UpperCamelCase__								=						{}
				UpperCamelCase__								=						torch.stack(__A							)
				UpperCamelCase__								=						torch.stack(__A							)

				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:
						UpperCamelCase__								=						(
						    dataset['''train'''].shuffle(seed=training_args.seed							).select(range(data_args.max_train_samples							)							)
						)
				# Set the training transforms
				dataset["train"].set_transform(__A							)

		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:
						UpperCamelCase__								=						(
						    dataset['''validation'''].shuffle(seed=training_args.seed							).select(range(data_args.max_eval_samples							)							)
						)
				# Set the validation transforms
				dataset["validation"].set_transform(__A							)

		# Initalize our trainer
		UpperCamelCase__								=						Trainer(
		    model=__A			,    args=__A			,    train_dataset=dataset["""train"""] if training_args.do_train else None			,    eval_dataset=dataset["""validation"""] if training_args.do_eval else None			,    compute_metrics=__A			,    tokenizer=__A			,    data_collator=__A			,    )

		# Training
		if training_args.do_train:
				UpperCamelCase__								=						None
				if training_args.resume_from_checkpoint is not None:
						UpperCamelCase__								=						training_args.resume_from_checkpoint
				elif last_checkpoint is not None:
						UpperCamelCase__								=						last_checkpoint
				UpperCamelCase__								=						trainer.train(resume_from_checkpoint=__A							)
				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:
				UpperCamelCase__								=						trainer.evaluate()
				trainer.log_metrics("""eval"""			,    __A							)
				trainer.save_metrics("""eval"""			,    __A							)

		# Write model card and (optionally) push to hub
		UpperCamelCase__								=						{
		    '''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(**__A							)
		else:
				trainer.create_model_card(**__A							)


if __name__ == "__main__":
				main()











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
	__lowerCamelCase :    str      						=      '''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__ (		__A:						Optional[int]				,__A:						int				,__A:						Optional[int]=None				,__A:						str=None				,__A:						Optional[Any]=None				,__A:						Dict=None				,__A:						Union[str, Any]=None				,__A:						Dict=None				,):





					'''simple docstring'''






					if attention_mask is None:
										__magic_name__				:						Tuple     				=				np.where(input_ids != config.pad_token_id				,1				,0					)
					if decoder_attention_mask is None:
										__magic_name__				:						str     				=				np.where(decoder_input_ids != config.pad_token_id				,1				,0					)
					if head_mask is None:
										__magic_name__				:						List[str]     				=				np.ones((config.encoder_layers, config.encoder_attention_heads)					)
					if decoder_head_mask is None:
										__magic_name__				:						Any     				=				np.ones((config.decoder_layers, config.decoder_attention_heads)					)
					if cross_attn_head_mask is None:
										__magic_name__				:						str     				=				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  lowerCamelCase     :






			'''simple docstring'''





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

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

								__magic_name__				:						Union[str, Any]     				=				shift_tokens_right(lowerCamelCase_							,    1							,    2	)

								__magic_name__				:						Any     				=				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=lowerCamelCase_							,    )
								__magic_name__				:						int     				=				prepare_marian_inputs_dict(lowerCamelCase_							,    lowerCamelCase_							,    lowerCamelCase_	)
								return config, inputs_dict

			def 				UpperCAmelCase__							(			self      : List[str]	)    -> Any:
								__magic_name__				,     __magic_name__				:						int     				=				self.prepare_config_and_inputs()
								return config, inputs_dict

			def 				UpperCAmelCase__							(			self      : Any							,    lowerCamelCase_      : List[Any]							,    lowerCamelCase_      : str							,    lowerCamelCase_      : Union[str, Any]	)    -> Any:
								__magic_name__				:						int     				=				20
								__magic_name__				:						Union[str, Any]     				=				model_class_name(lowerCamelCase_	)

								__magic_name__				:						List[Any]     				=				model.encode(inputs_dict['''input_ids''']	)

								__magic_name__				,     __magic_name__				:						Any     				=				(
								    inputs_dict['''decoder_input_ids'''],
								    inputs_dict['''decoder_attention_mask'''],
								)

								__magic_name__				:						Union[str, Any]     				=				model.init_cache(decoder_input_ids.shape[0]							,    lowerCamelCase_							,    lowerCamelCase_	)
								__magic_name__				:						Dict     				=				jnp.ones((decoder_input_ids.shape[0], max_decoder_length)							,    dtype='''i4'''	)

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

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

								__magic_name__				:						Optional[int]     				=				model.decode(lowerCamelCase_							,    lowerCamelCase_	)

								__magic_name__				:						Optional[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 				UpperCAmelCase__							(			self      : Tuple							,    lowerCamelCase_      : List[str]							,    lowerCamelCase_      : Optional[Any]							,    lowerCamelCase_      : Any	)    -> Optional[int]:
								__magic_name__				:						List[str]     				=				20
								__magic_name__				:						Union[str, Any]     				=				model_class_name(lowerCamelCase_	)

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

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

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

								__magic_name__				:						List[Any]     				=				model.init_cache(decoder_input_ids.shape[0]							,    lowerCamelCase_							,    lowerCamelCase_	)
								__magic_name__				:						Optional[Any]     				=				jnp.broadcast_to(
								    jnp.arange(decoder_input_ids.shape[-1] - 1	)[None, :]							,    (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)							,    )

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

								__magic_name__				:						Union[str, Any]     				=				model.decode(lowerCamelCase_							,    lowerCamelCase_							,    decoder_attention_mask=lowerCamelCase_	)

								__magic_name__				:						str     				=				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  lowerCamelCase     (		_lowerCamelCase					,unittest.TestCase					,_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										=True
			UpperCamelCase__										=(FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
			UpperCamelCase__										=(FlaxMarianMTModel,) if is_flax_available() else ()

			def 				UpperCAmelCase__							(			self      : Dict	)    -> Optional[int]:
								__magic_name__				:						List[str]     				=				FlaxMarianModelTester(self	)

			def 				UpperCAmelCase__							(			self      : str	)    -> Dict:
								__magic_name__				,     __magic_name__				:						Dict     				=				self.model_tester.prepare_config_and_inputs()
								for model_class in self.all_model_classes:
													self.model_tester.check_use_cache_forward(lowerCamelCase_							,    lowerCamelCase_							,    lowerCamelCase_	)

			def 				UpperCAmelCase__							(			self      : str	)    -> List[str]:
								__magic_name__				,     __magic_name__				:						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(lowerCamelCase_							,    lowerCamelCase_							,    lowerCamelCase_	)

			def 				UpperCAmelCase__							(			self      : Optional[int]	)    -> Any:
								__magic_name__				,     __magic_name__				:						Dict     				=				self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													with self.subTest(model_class.__name__	):
																		__magic_name__				:						Dict     				=				self._prepare_for_class(lowerCamelCase_							,    lowerCamelCase_	)
																		__magic_name__				:						Union[str, Any]     				=				model_class(lowerCamelCase_	)

																		@jax.jit
																		def encode_jitted(lowerCamelCase_      : str							,    lowerCamelCase_      : str=None							,    **lowerCamelCase_      : str	):
																							return model.encode(input_ids=lowerCamelCase_							,    attention_mask=lowerCamelCase_	)

																		with self.subTest('''JIT Enabled'''	):
																							__magic_name__				:						Any     				=				encode_jitted(**lowerCamelCase_	).to_tuple()

																		with self.subTest('''JIT Disabled'''	):
																							with jax.disable_jit():
																												__magic_name__				:						str     				=				encode_jitted(**lowerCamelCase_	).to_tuple()

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

			def 				UpperCAmelCase__							(			self      : List[str]	)    -> Union[str, Any]:
								__magic_name__				,     __magic_name__				:						Optional[int]     				=				self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													with self.subTest(model_class.__name__	):
																		__magic_name__				:						Dict     				=				model_class(lowerCamelCase_	)
																		__magic_name__				:						Dict     				=				model.encode(inputs_dict['''input_ids''']							,    inputs_dict['''attention_mask''']	)

																		__magic_name__				:						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(lowerCamelCase_      : Optional[int]							,    lowerCamelCase_      : List[str]							,    lowerCamelCase_      : Tuple	):
																							return model.decode(
																							    decoder_input_ids=lowerCamelCase_							,    decoder_attention_mask=lowerCamelCase_							,    encoder_outputs=lowerCamelCase_							,    )

																		with self.subTest('''JIT Enabled'''	):
																							__magic_name__				:						List[Any]     				=				decode_jitted(**lowerCamelCase_	).to_tuple()

																		with self.subTest('''JIT Disabled'''	):
																							with jax.disable_jit():
																												__magic_name__				:						int     				=				decode_jitted(**lowerCamelCase_	).to_tuple()

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


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






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		unittest.TestCase    ):






			'''simple docstring'''





			UpperCamelCase__										=None
			UpperCamelCase__										=None

			@classmethod
			def 				UpperCAmelCase__							(			cls      : Dict	)    -> None:
								__magic_name__				:						Tuple     				=				F'''Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'''
								return cls

			@cached_property
			def 				UpperCAmelCase__							(			self      : str	)    -> Any:
								return MarianTokenizer.from_pretrained(self.model_name	)

			@property
			def 				UpperCAmelCase__							(			self      : List[str]	)    -> int:
								return self.tokenizer.eos_token_id

			@cached_property
			def 				UpperCAmelCase__							(			self      : List[Any]	)    -> Optional[Any]:
								__magic_name__				:						FlaxMarianMTModel     				=				FlaxMarianMTModel.from_pretrained(self.model_name	)
								self.assertEqual(model.config.decoder_start_token_id							,    model.config.pad_token_id	)
								return model

			def 				UpperCAmelCase__							(			self      : List[Any]							,    **lowerCamelCase_      : Dict	)    -> Optional[int]:
								__magic_name__				:						List[str]     				=				self.translate_src_text(**lowerCamelCase_	)
								self.assertListEqual(self.expected_text							,    lowerCamelCase_	)


			def 				UpperCAmelCase__							(			self      : int							,    **lowerCamelCase_      : Optional[int]	)    -> Optional[Any]:
								__magic_name__				:						List[str]     				=				self.tokenizer(self.src_text							,    padding=lowerCamelCase_							,    return_tensors='''np'''							,    **lowerCamelCase_	)
								__magic_name__				:						Union[str, Any]     				=				self.model.generate(
								    model_inputs.input_ids							,    attention_mask=model_inputs.attention_mask							,    num_beams=2							,    max_length=128							,    ).sequences
								__magic_name__				:						Dict     				=				self.tokenizer.batch_decode(lowerCamelCase_							,    skip_special_tokens=lowerCamelCase_	)
								return generated_words






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''en'''
			UpperCamelCase__										='''fr'''
			UpperCamelCase__										=[
			    '''I am a small frog.''',
			    '''Now I can forget the 100 words of german that I know.''',
			]
			UpperCamelCase__										=[
			    '''Je suis une petite grenouille.''',
			    '''Maintenant, je peux oublier les 100 mots d\'allemand que je connais.''',
			]

			@slow
			def 				UpperCAmelCase__							(			self      : str	)    -> Tuple:
								self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''fr'''
			UpperCamelCase__										='''en'''
			UpperCamelCase__										=[
			    '''Donnez moi le micro.''',
			    '''Tom et Mary étaient assis à une table.''',  # Accents
			]
			UpperCamelCase__										=[
			    '''Give me the microphone.''',
			    '''Tom and Mary were sitting at a table.''',
			]

			@slow
			def 				UpperCAmelCase__							(			self      : Optional[Any]	)    -> Tuple:
								self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''mt'''
			UpperCamelCase__										='''en'''
			UpperCamelCase__										=['''Billi messu b\'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem.''']
			UpperCamelCase__										=['''Touching gently, Jesus healed a man who was affected by the sad disease of leprosy.''']

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






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''en'''
			UpperCamelCase__										='''de'''
			UpperCamelCase__										=[
			    '''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.''',
			]
			UpperCamelCase__										=[
			    '''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 				UpperCAmelCase__							(			self      : List[str]	)    -> Optional[Any]:
								self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''en'''
			UpperCamelCase__										='''zh'''
			UpperCamelCase__										=['''My name is Wolfgang and I live in Berlin''']
			UpperCamelCase__										=['''我叫沃尔夫冈 我住在柏林''']

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






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''ru'''
			UpperCamelCase__										='''fr'''
			UpperCamelCase__										=['''Он показал мне рукопись своей новой пьесы.''']
			UpperCamelCase__										=['''Il m\'a montré le manuscrit de sa nouvelle pièce.''']

			@slow
			def 				UpperCAmelCase__							(			self      : Tuple	)    -> Optional[Any]:
								self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''en'''
			UpperCamelCase__										='''ROMANCE'''
			UpperCamelCase__										=[
			    '''>>fr<< Don\'t spend so much time watching TV.''',
			    '''>>pt<< Your message has been sent.''',
			    '''>>es<< He\'s two years older than me.''',
			]
			UpperCamelCase__										=[
			    '''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 				UpperCAmelCase__							(			self      : Tuple	)    -> Optional[int]:
								self._assert_generated_batch_equal_expected()



