




'''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_ 			=		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 		UpperCamelCase__			(		__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE=0		)						->      Tuple:
      snake_case__					:      Union[str, Any]  			=						(size, size) if isinstance(__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE		) else size
      snake_case__			,       snake_case__					:      int  			=						img.size
      snake_case__					:      Tuple  			=						size[1] - original_height if original_height < size[1] else 0
      snake_case__					:      int  			=						size[0] - original_width if original_width < size[0] else 0
      snake_case__					:      Dict  			=						functional.pad(__SCREAMING_SNAKE_CASE							,			(0, 0, pad_width, pad_height)							,			fill=__SCREAMING_SNAKE_CASE		)
      return img






class 					lowercase_			:





     def __init__(    self    :				List[Any]    ,       __lowerCamelCase    :				List[Any] ):
           snake_case__					:      str  			=						transforms





     def __call__(    self    :				Tuple    ,       __lowerCamelCase    :				Union[str, Any]    ,       __lowerCamelCase    :				Any ):
           for t in self.transforms:
                 snake_case__			,       snake_case__					:      Optional[int]  			=						t(__lowerCamelCase    ,       __lowerCamelCase )
           return image, target






class 					lowercase_			:





     def __init__(    self    :				Tuple ):
           pass





     def __call__(    self    :				Dict    ,       __lowerCamelCase    :				Optional[Any]    ,       __lowerCamelCase    :				int ):
           return image, target






class 					lowercase_			:





     def __init__(    self    :				str    ,       __lowerCamelCase    :				str ):
           snake_case__					:      str  			=						size





     def __call__(    self    :				List[Any]    ,       __lowerCamelCase    :				int    ,       __lowerCamelCase    :				int ):
           snake_case__					:      List[Any]  			=						functional.resize(__lowerCamelCase    ,       self.size )
           snake_case__					:      List[Any]  			=						functional.resize(__lowerCamelCase    ,       self.size    ,       interpolation=transforms.InterpolationMode.NEAREST )
           return image, target






class 					lowercase_			:





     def __init__(    self    :				Dict    ,       __lowerCamelCase    :				List[Any]    ,       __lowerCamelCase    :				str=None ):
           snake_case__					:      Optional[Any]  			=						min_size
           if max_size is None:
                 snake_case__					:      int  			=						min_size
           snake_case__					:      Optional[int]  			=						max_size





     def __call__(    self    :				str    ,       __lowerCamelCase    :				Optional[int]    ,       __lowerCamelCase    :				Union[str, Any] ):
           snake_case__					:      Tuple  			=						random.randint(self.min_size    ,       self.max_size )
           snake_case__					:      List[str]  			=						functional.resize(__lowerCamelCase    ,       __lowerCamelCase )
           snake_case__					:      Optional[int]  			=						functional.resize(__lowerCamelCase    ,       __lowerCamelCase    ,       interpolation=transforms.InterpolationMode.NEAREST )
           return image, target






class 					lowercase_			:





     def __init__(    self    :				List[Any]    ,       __lowerCamelCase    :				Optional[int] ):
           snake_case__					:      Optional[Any]  			=						size if isinstance(__lowerCamelCase    ,       __lowerCamelCase ) else (size, size)





     def __call__(    self    :				Tuple    ,       __lowerCamelCase    :				Optional[Any]    ,       __lowerCamelCase    :				str ):
           snake_case__					:      Tuple  			=						pad_if_smaller(__lowerCamelCase    ,       self.size )
           snake_case__					:      Tuple  			=						pad_if_smaller(__lowerCamelCase    ,       self.size    ,       fill=255 )
           snake_case__					:      Optional[int]  			=						transforms.RandomCrop.get_params(__lowerCamelCase    ,       self.size )
           snake_case__					:      Dict  			=						functional.crop(__lowerCamelCase    ,       *__lowerCamelCase )
           snake_case__					:      Optional[Any]  			=						functional.crop(__lowerCamelCase    ,       *__lowerCamelCase )
           return image, target






class 					lowercase_			:





     def __init__(    self    :				Dict    ,       __lowerCamelCase    :				List[Any] ):
           snake_case__					:      str  			=						flip_prob





     def __call__(    self    :				str    ,       __lowerCamelCase    :				Dict    ,       __lowerCamelCase    :				Dict ):
           if random.random() < self.flip_prob:
                 snake_case__					:      int  			=						functional.hflip(__lowerCamelCase )
                 snake_case__					:      Dict  			=						functional.hflip(__lowerCamelCase )
           return image, target






class 					lowercase_			:





     def __call__(    self    :				Tuple    ,       __lowerCamelCase    :				Union[str, Any]    ,       __lowerCamelCase    :				Union[str, Any] ):
           snake_case__					:      Union[str, Any]  			=						functional.pil_to_tensor(__lowerCamelCase )
           snake_case__					:      List[Any]  			=						torch.as_tensor(np.array(__lowerCamelCase )    ,       dtype=torch.intaa )
           return image, target






class 					lowercase_			:





     def __init__(    self    :				List[Any]    ,       __lowerCamelCase    :				List[Any] ):
           snake_case__					:      Dict  			=						dtype





     def __call__(    self    :				Optional[int]    ,       __lowerCamelCase    :				List[Any]    ,       __lowerCamelCase    :				Union[str, Any] ):
           snake_case__					:      Union[str, Any]  			=						functional.convert_image_dtype(__lowerCamelCase    ,       self.dtype )
           return image, target






class 					lowercase_			:





     def __init__(    self    :				List[Any]    ,       __lowerCamelCase    :				List[str]    ,       __lowerCamelCase    :				Optional[Any] ):
           snake_case__					:      Optional[int]  			=						mean
           snake_case__					:      Optional[int]  			=						std





     def __call__(    self    :				Union[str, Any]    ,       __lowerCamelCase    :				List[Any]    ,       __lowerCamelCase    :				int ):
           snake_case__					:      Union[str, Any]  			=						functional.normalize(__lowerCamelCase    ,       mean=self.mean    ,       std=self.std )
           return image, target






class 					lowercase_			:





     def __call__(    self    :				List[Any]    ,       __lowerCamelCase    :				Any    ,       __lowerCamelCase    :				Tuple ):
           if not isinstance(__lowerCamelCase    ,       np.ndarray ):
                 snake_case__					:      str  			=						np.array(__lowerCamelCase ).astype(np.uinta )
           # avoid using underflow conversion
           snake_case__					:      List[str]  			=						255
           snake_case__					:      Optional[Any]  			=						target - 1
           snake_case__					:      Tuple  			=						255

           snake_case__					:      str  			=						Image.fromarray(__lowerCamelCase )
           return image, target






@dataclass
class 					lowercase_			:
     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.1_5	,					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  _lowerCAmelCase			(    self    :				List[Any] ):
           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 					lowercase_			:
     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 		UpperCamelCase__			(		)						->      Tuple:
      # 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.

      snake_case__					:      Optional[Any]  			=						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.
            snake_case__			,       snake_case__			,       snake_case__					:      Optional[int]  			=						parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]		)		)
      else:
            snake_case__			,       snake_case__			,       snake_case__					:      Tuple  			=						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'							,			__SCREAMING_SNAKE_CASE							,			__SCREAMING_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()

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

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

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

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

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

            return metrics

      snake_case__					:      List[str]  			=						AutoConfig.from_pretrained(
          model_args.config_name or model_args.model_name_or_path							,			labelaid=__SCREAMING_SNAKE_CASE							,			idalabel=__SCREAMING_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							,			)
      snake_case__					:      Dict  			=						AutoModelForSemanticSegmentation.from_pretrained(
          model_args.model_name_or_path							,			from_tf=bool('.ckpt' in model_args.model_name_or_path		)							,			config=__SCREAMING_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							,			)
      snake_case__					:      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.
            snake_case__					:      Any  			=						(image_processor.size['shortest_edge'], image_processor.size['shortest_edge'])
      else:
            snake_case__					:      Dict  			=						(image_processor.size['height'], image_processor.size['width'])
      snake_case__					:      str  			=						Compose(
          [
              ReduceLabels() if data_args.reduce_labels else Identity(),
              RandomCrop(size=__SCREAMING_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)
      snake_case__					:      Union[str, Any]  			=						Compose(
          [
              ReduceLabels() if data_args.reduce_labels else Identity(),
              Resize(size=__SCREAMING_SNAKE_CASE		),
              PILToTensor(),
              ConvertImageDtype(torch.float		),
              Normalize(mean=image_processor.image_mean							,			std=image_processor.image_std		),
          ]		)

      def preprocess_train(__SCREAMING_SNAKE_CASE		):
            snake_case__					:      Any  			=						[]
            snake_case__					:      Optional[int]  			=						[]
            for image, target in zip(example_batch['image']							,			example_batch['label']		):
                  snake_case__			,       snake_case__					:      str  			=						train_transforms(image.convert('RGB'		)							,			__SCREAMING_SNAKE_CASE		)
                  pixel_values.append(__SCREAMING_SNAKE_CASE		)
                  labels.append(__SCREAMING_SNAKE_CASE		)

            snake_case__					:      List[str]  			=						{}
            snake_case__					:      int  			=						torch.stack(__SCREAMING_SNAKE_CASE		)
            snake_case__					:      Union[str, Any]  			=						torch.stack(__SCREAMING_SNAKE_CASE		)

            return encoding

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

            snake_case__					:      Optional[Any]  			=						{}
            snake_case__					:      Optional[Any]  			=						torch.stack(__SCREAMING_SNAKE_CASE		)
            snake_case__					:      Optional[Any]  			=						torch.stack(__SCREAMING_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:
                  snake_case__					:      List[Any]  			=						(
                      dataset['train'].shuffle(seed=training_args.seed		).select(range(data_args.max_train_samples		)		)
                  )
            # Set the training transforms
            dataset["train"].set_transform(__SCREAMING_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:
                  snake_case__					:      str  			=						(
                      dataset['validation'].shuffle(seed=training_args.seed		).select(range(data_args.max_eval_samples		)		)
                  )
            # Set the validation transforms
            dataset["validation"].set_transform(__SCREAMING_SNAKE_CASE		)

      # Initalize our trainer
      snake_case__					:      Optional[Any]  			=						Trainer(
          model=__SCREAMING_SNAKE_CASE							,			args=__SCREAMING_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=__SCREAMING_SNAKE_CASE							,			tokenizer=__SCREAMING_SNAKE_CASE							,			data_collator=__SCREAMING_SNAKE_CASE							,			)

      # Training
      if training_args.do_train:
            snake_case__					:      str  			=						None
            if training_args.resume_from_checkpoint is not None:
                  snake_case__					:      List[str]  			=						training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  snake_case__					:      Optional[Any]  			=						last_checkpoint
            snake_case__					:      Any  			=						trainer.train(resume_from_checkpoint=__SCREAMING_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:
            snake_case__					:      Optional[Any]  			=						trainer.evaluate()
            trainer.log_metrics('eval'							,			__SCREAMING_SNAKE_CASE		)
            trainer.save_metrics('eval'							,			__SCREAMING_SNAKE_CASE		)

      # Write model card and (optionally) push to hub
      snake_case__					:      List[str]  			=						{
          '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(**__SCREAMING_SNAKE_CASE		)
      else:
            trainer.create_model_card(**__SCREAMING_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_ 			=		"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 		UpperCamelCase__			(		__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			__SCREAMING_SNAKE_CASE=None							,			)						->      Union[str, Any]:
      if attention_mask is None:
            snake_case__					:      Union[str, Any]  			=						np.where(input_ids != config.pad_token_id							,			1							,			0		)
      if decoder_attention_mask is None:
            snake_case__					:      int  			=						np.where(decoder_input_ids != config.pad_token_id							,			1							,			0		)
      if head_mask is None:
            snake_case__					:      Optional[int]  			=						np.ones((config.encoder_layers, config.encoder_attention_heads)		)
      if decoder_head_mask is None:
            snake_case__					:      str  			=						np.ones((config.decoder_layers, config.decoder_attention_heads)		)
      if cross_attn_head_mask is None:
            snake_case__					:      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 					lowercase_			:





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





     def  _lowerCAmelCase			(    self    :				Optional[int] ):
           snake_case__					:      List[Any]  			=						np.clip(ids_tensor([self.batch_size, self.seq_length - 1]    ,       self.vocab_size )    ,       3    ,       self.vocab_size )
           snake_case__					:      Tuple  			=						np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)    ,       dtype=np.intaa ))    ,       -1 )

           snake_case__					:      Optional[int]  			=						shift_tokens_right(__lowerCamelCase    ,       1    ,       2 )

           snake_case__					:      Union[str, 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    ,       )
           snake_case__					:      Union[str, Any]  			=						prepare_marian_inputs_dict(__lowerCamelCase    ,       __lowerCamelCase    ,       __lowerCamelCase )
           return config, inputs_dict





     def  _lowerCAmelCase			(    self    :				Optional[int] ):
           snake_case__			,       snake_case__					:      Optional[int]  			=						self.prepare_config_and_inputs()
           return config, inputs_dict





     def  _lowerCAmelCase			(    self    :				Tuple    ,       __lowerCamelCase    :				Union[str, Any]    ,       __lowerCamelCase    :				Dict    ,       __lowerCamelCase    :				Dict ):
           snake_case__					:      Optional[int]  			=						20
           snake_case__					:      str  			=						model_class_name(__lowerCamelCase )

           snake_case__					:      Dict  			=						model.encode(inputs_dict['input_ids'] )

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

           snake_case__					:      Dict  			=						model.init_cache(decoder_input_ids.shape[0]    ,       __lowerCamelCase    ,       __lowerCamelCase )
           snake_case__					:      Optional[int]  			=						jnp.ones((decoder_input_ids.shape[0], max_decoder_length)    ,       dtype='i4' )

           snake_case__					:      List[str]  			=						jnp.broadcast_to(
               jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :]    ,       (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)    ,       )
           snake_case__					:      Dict  			=						model.decode(
               decoder_input_ids[:, :-1]    ,       __lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase    ,       past_key_values=__lowerCamelCase    ,       decoder_position_ids=__lowerCamelCase    ,       )

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

           snake_case__					:      Union[str, Any]  			=						model.decode(__lowerCamelCase    ,       __lowerCamelCase )

           snake_case__					:      Tuple  			=						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  _lowerCAmelCase			(    self    :				Tuple    ,       __lowerCamelCase    :				Any    ,       __lowerCamelCase    :				Dict    ,       __lowerCamelCase    :				Optional[int] ):
           snake_case__					:      int  			=						20
           snake_case__					:      Tuple  			=						model_class_name(__lowerCamelCase )

           snake_case__					:      Optional[int]  			=						model.encode(inputs_dict['input_ids'] )

           snake_case__			,       snake_case__					:      Dict  			=						(
               inputs_dict['decoder_input_ids'],
               inputs_dict['decoder_attention_mask'],
           )

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

           snake_case__					:      Union[str, Any]  			=						model.init_cache(decoder_input_ids.shape[0]    ,       __lowerCamelCase    ,       __lowerCamelCase )
           snake_case__					:      List[str]  			=						jnp.broadcast_to(
               jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :]    ,       (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)    ,       )

           snake_case__					:      List[Any]  			=						model.decode(
               decoder_input_ids[:, :-1]    ,       __lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase    ,       past_key_values=__lowerCamelCase    ,       decoder_position_ids=__lowerCamelCase    ,       )
           snake_case__					:      Tuple  			=						jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]    ,       dtype='i4' )
           snake_case__					:      int  			=						model.decode(
               decoder_input_ids[:, -1:]    ,       __lowerCamelCase    ,       past_key_values=outputs_cache.past_key_values    ,       decoder_attention_mask=__lowerCamelCase    ,       decoder_position_ids=__lowerCamelCase    ,       )

           snake_case__					:      Dict  			=						model.decode(__lowerCamelCase    ,       __lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase )

           snake_case__					:      Optional[int]  			=						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 					lowercase_			(	lowerCAmelCase_	,					unittest.TestCase	,					lowerCAmelCase_       ):
     A_       							= True
     A_       							= (FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
     A_       							= (FlaxMarianMTModel,) if is_flax_available() else ()





     def  _lowerCAmelCase			(    self    :				int ):
           snake_case__					:      Any  			=						FlaxMarianModelTester(self )





     def  _lowerCAmelCase			(    self    :				Optional[Any] ):
           snake_case__			,       snake_case__					:      Optional[Any]  			=						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  _lowerCAmelCase			(    self    :				str ):
           snake_case__			,       snake_case__					:      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  _lowerCAmelCase			(    self    :				List[Any] ):
           snake_case__			,       snake_case__					:      Optional[Any]  			=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 with self.subTest(model_class.__name__ ):
                       snake_case__					:      Union[str, Any]  			=						self._prepare_for_class(__lowerCamelCase    ,       __lowerCamelCase )
                       snake_case__					:      List[str]  			=						model_class(__lowerCamelCase )

                       @jax.jit
                       def encode_jitted(__lowerCamelCase    :				Dict    ,       __lowerCamelCase    :				Optional[Any]=None    ,       **__lowerCamelCase    :				List[str] ):
                             return model.encode(input_ids=__lowerCamelCase    ,       attention_mask=__lowerCamelCase )

                       with self.subTest('JIT Enabled' ):
                             snake_case__					:      List[Any]  			=						encode_jitted(**__lowerCamelCase ).to_tuple()

                       with self.subTest('JIT Disabled' ):
                             with jax.disable_jit():
                                   snake_case__					:      Dict  			=						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  _lowerCAmelCase			(    self    :				int ):
           snake_case__			,       snake_case__					:      Dict  			=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 with self.subTest(model_class.__name__ ):
                       snake_case__					:      List[str]  			=						model_class(__lowerCamelCase )
                       snake_case__					:      Union[str, Any]  			=						model.encode(inputs_dict['input_ids']    ,       inputs_dict['attention_mask'] )

                       snake_case__					:      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    :				Tuple    ,       __lowerCamelCase    :				Any    ,       __lowerCamelCase    :				Optional[Any] ):
                             return model.decode(
                                 decoder_input_ids=__lowerCamelCase    ,       decoder_attention_mask=__lowerCamelCase    ,       encoder_outputs=__lowerCamelCase    ,       )

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

                       with self.subTest('JIT Disabled' ):
                             with jax.disable_jit():
                                   snake_case__					:      str  			=						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  _lowerCAmelCase			(    self    :				List[str] ):
           for model_class_name in self.all_model_classes:
                 snake_case__					:      Any  			=						model_class_name.from_pretrained('Helsinki-NLP/opus-mt-en-de' )
                 # FlaxMarianForSequenceClassification expects eos token in input_ids
                 snake_case__					:      List[Any]  			=						np.ones((1, 1) ) * model.config.eos_token_id
                 snake_case__					:      Union[str, Any]  			=						model(__lowerCamelCase )
                 self.assertIsNotNone(__lowerCamelCase )






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	unittest.TestCase       ):
     A_       							= None
     A_       							= None





     @classmethod
     def  _lowerCAmelCase			(    cls    :				Union[str, Any] ):
           snake_case__					:      List[Any]  			=						F"Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"
           return cls





     @cached_property
     def  _lowerCAmelCase			(    self    :				Optional[int] ):
           return MarianTokenizer.from_pretrained(self.model_name )





     @property
     def  _lowerCAmelCase			(    self    :				int ):
           return self.tokenizer.eos_token_id





     @cached_property
     def  _lowerCAmelCase			(    self    :				Dict ):
           snake_case__					:      FlaxMarianMTModel  			=						FlaxMarianMTModel.from_pretrained(self.model_name )
           self.assertEqual(model.config.decoder_start_token_id    ,       model.config.pad_token_id )
           return model





     def  _lowerCAmelCase			(    self    :				Tuple    ,       **__lowerCamelCase    :				List[Any] ):
           snake_case__					:      Dict  			=						self.translate_src_text(**__lowerCamelCase )
           self.assertListEqual(self.expected_text    ,       __lowerCamelCase )





     def  _lowerCAmelCase			(    self    :				List[str]    ,       **__lowerCamelCase    :				Dict ):
           snake_case__					:      str  			=						self.tokenizer(self.src_text    ,       padding=__lowerCamelCase    ,       return_tensors='np'    ,       **__lowerCamelCase )
           snake_case__					:      Any  			=						self.model.generate(
               model_inputs.input_ids    ,       attention_mask=model_inputs.attention_mask    ,       num_beams=2    ,       max_length=128    ,       ).sequences
           snake_case__					:      List[str]  			=						self.tokenizer.batch_decode(__lowerCamelCase    ,       skip_special_tokens=__lowerCamelCase )
           return generated_words






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





     @slow
     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           self._assert_generated_batch_equal_expected()






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





     @slow
     def  _lowerCAmelCase			(    self    :				List[Any] ):
           self._assert_generated_batch_equal_expected()






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





     @slow
     def  _lowerCAmelCase			(    self    :				Dict ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "en"
     A_       							= "de"
     A_       							= [
         "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.",
     ]
     A_       							= [
         "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  _lowerCAmelCase			(    self    :				Dict ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "en"
     A_       							= "zh"
     A_       							= ["My name is Wolfgang and I live in Berlin"]
     A_       							= ["我叫沃尔夫冈 我住在柏林"]





     @slow
     def  _lowerCAmelCase			(    self    :				Union[str, Any] ):
           self._assert_generated_batch_equal_expected()






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





     @slow
     def  _lowerCAmelCase			(    self    :				Optional[Any] ):
           self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 					lowercase_			(	lowerCAmelCase_       ):
     A_       							= "en"
     A_       							= "ROMANCE"
     A_       							= [
         ">>fr<< Don't spend so much time watching TV.",
         ">>pt<< Your message has been sent.",
         ">>es<< He's two years older than me.",
     ]
     A_       							= [
         "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  _lowerCAmelCase			(    self    :				int ):
           self._assert_generated_batch_equal_expected()
