





"""simple docstring"""
from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


lowerCamelCase_        =						logging.get_logger(__name__)

# General docstring
lowerCamelCase_        =						"RegNetConfig"

# Base docstring
lowerCamelCase_        =						"facebook/regnet-y-040"
lowerCamelCase_        =						[1, 1_0_8_8, 7, 7]

# Image classification docstring
lowerCamelCase_        =						"facebook/regnet-y-040"
lowerCamelCase_        =						"tabby, tabby cat"

lowerCamelCase_        =						[
    "facebook/regnet-y-040",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]






class    _SCREAMING_SNAKE_CASE(  nn.Module    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__ = 3						,SCREAMING_SNAKE_CASE__ = 1						,SCREAMING_SNAKE_CASE__ = 1						,SCREAMING_SNAKE_CASE__ = "relu"						,)     -> List[Any]:





             """simple docstring"""






             super().__init__()
             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    nn.Convad(
                 A_						,A_						,kernel_size=A_						,stride=A_						,padding=kernel_size // 2						,groups=A_						,bias=A_						,)
             __SCREAMING_SNAKE_CASE  :Any													=    nn.BatchNormad(A_				)
             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    ACTaFN[activation] if activation is not None else nn.Identity()




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__				)     -> str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Tuple													=    self.convolution(A_				)
             __SCREAMING_SNAKE_CASE  :Tuple													=    self.normalization(A_				)
             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    self.activation(A_				)
             return hidden_state






class    _SCREAMING_SNAKE_CASE(  nn.Module    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__				)     -> int:





             """simple docstring"""






             super().__init__()
             __SCREAMING_SNAKE_CASE  :List[Any]													=    RegNetConvLayer(
                 config.num_channels						,config.embedding_size						,kernel_size=3						,stride=2						,activation=config.hidden_act				)
             __SCREAMING_SNAKE_CASE  :List[Any]													=    config.num_channels




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__				)     -> Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Dict													=    pixel_values.shape[1]
             if num_channels != self.num_channels:
                   raise ValueError(
                       '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.'''				)
             __SCREAMING_SNAKE_CASE  :Tuple													=    self.embedder(A_				)
             return hidden_state






class    _SCREAMING_SNAKE_CASE(  nn.Module    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__ = 2				)     -> Optional[int]:





             """simple docstring"""






             super().__init__()
             __SCREAMING_SNAKE_CASE  :List[str]													=    nn.Convad(A_						,A_						,kernel_size=1						,stride=A_						,bias=A_				)
             __SCREAMING_SNAKE_CASE  :str													=    nn.BatchNormad(A_				)




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__				)     -> str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Dict													=    self.convolution(A_				)
             __SCREAMING_SNAKE_CASE  :List[Any]													=    self.normalization(A_				)
             return hidden_state






class    _SCREAMING_SNAKE_CASE(  nn.Module    ):




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





             """simple docstring"""






             super().__init__()

             __SCREAMING_SNAKE_CASE  :str													=    nn.AdaptiveAvgPoolad((1, 1)				)
             __SCREAMING_SNAKE_CASE  :List[Any]													=    nn.Sequential(
                 nn.Convad(A_						,A_						,kernel_size=1				)						,nn.ReLU()						,nn.Convad(A_						,A_						,kernel_size=1				)						,nn.Sigmoid()						,)




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__				)     -> Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :List[str]													=    self.pooler(A_				)
             __SCREAMING_SNAKE_CASE  :Dict													=    self.attention(A_				)
             __SCREAMING_SNAKE_CASE  :List[str]													=    hidden_state * attention
             return hidden_state






class    _SCREAMING_SNAKE_CASE(  nn.Module    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__ = 1				)     -> int:





             """simple docstring"""






             super().__init__()
             __SCREAMING_SNAKE_CASE  :str													=    in_channels != out_channels or stride != 1
             __SCREAMING_SNAKE_CASE  :str													=    max(1						,out_channels // config.groups_width				)
             __SCREAMING_SNAKE_CASE  :List[Any]													=    (
                 RegNetShortCut(A_						,A_						,stride=A_				) if should_apply_shortcut else nn.Identity()
             )
             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    nn.Sequential(
                 RegNetConvLayer(A_						,A_						,kernel_size=1						,activation=config.hidden_act				)						,RegNetConvLayer(A_						,A_						,stride=A_						,groups=A_						,activation=config.hidden_act				)						,RegNetConvLayer(A_						,A_						,kernel_size=1						,activation=A_				)						,)
             __SCREAMING_SNAKE_CASE  :str													=    ACTaFN[config.hidden_act]




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__				)     -> Optional[int]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Dict													=    hidden_state
             __SCREAMING_SNAKE_CASE  :Dict													=    self.layer(A_				)
             __SCREAMING_SNAKE_CASE  :Any													=    self.shortcut(A_				)
             hidden_state += residual
             __SCREAMING_SNAKE_CASE  :int													=    self.activation(A_				)
             return hidden_state






class    _SCREAMING_SNAKE_CASE(  nn.Module    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__ = 1				)     -> Dict:





             """simple docstring"""






             super().__init__()
             __SCREAMING_SNAKE_CASE  :Dict													=    in_channels != out_channels or stride != 1
             __SCREAMING_SNAKE_CASE  :List[Any]													=    max(1						,out_channels // config.groups_width				)
             __SCREAMING_SNAKE_CASE  :List[Any]													=    (
                 RegNetShortCut(A_						,A_						,stride=A_				) if should_apply_shortcut else nn.Identity()
             )
             __SCREAMING_SNAKE_CASE  :Tuple													=    nn.Sequential(
                 RegNetConvLayer(A_						,A_						,kernel_size=1						,activation=config.hidden_act				)						,RegNetConvLayer(A_						,A_						,stride=A_						,groups=A_						,activation=config.hidden_act				)						,RegNetSELayer(A_						,reduced_channels=int(round(in_channels / 4				)				)				)						,RegNetConvLayer(A_						,A_						,kernel_size=1						,activation=A_				)						,)
             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    ACTaFN[config.hidden_act]




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__				)     -> str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Any													=    hidden_state
             __SCREAMING_SNAKE_CASE  :List[str]													=    self.layer(A_				)
             __SCREAMING_SNAKE_CASE  :int													=    self.shortcut(A_				)
             hidden_state += residual
             __SCREAMING_SNAKE_CASE  :Any													=    self.activation(A_				)
             return hidden_state






class    _SCREAMING_SNAKE_CASE(  nn.Module    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__ = 2						,SCREAMING_SNAKE_CASE__ = 2						,)     -> Optional[Any]:





             """simple docstring"""






             super().__init__()

             __SCREAMING_SNAKE_CASE  :List[str]													=    RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer

             __SCREAMING_SNAKE_CASE  :Any													=    nn.Sequential(
                 # downsampling is done in the first layer with stride of 2
                 layer(
                     A_						,A_						,A_						,stride=A_						,)						,*[layer(A_						,A_						,A_				) for _ in range(depth - 1				)]						,)




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__				)     -> str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :int													=    self.layers(A_				)
             return hidden_state






class    _SCREAMING_SNAKE_CASE(  nn.Module    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__				)     -> Tuple:





             """simple docstring"""






             super().__init__()
             __SCREAMING_SNAKE_CASE  :str													=    nn.ModuleList([]				)
             # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
             self.stages.append(
                 RegNetStage(
                     A_						,config.embedding_size						,config.hidden_sizes[0]						,stride=2 if config.downsample_in_first_stage else 1						,depth=config.depths[0]						,)				)
             __SCREAMING_SNAKE_CASE  :str													=    zip(config.hidden_sizes						,config.hidden_sizes[1:]				)
             for (in_channels, out_channels), depth in zip(A_						,config.depths[1:]				):
                   self.stages.append(RegNetStage(A_						,A_						,A_						,depth=A_				)				)




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__ = False						,SCREAMING_SNAKE_CASE__ = True				)     -> Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :List[Any]													=    () if output_hidden_states else None

             for stage_module in self.stages:
                   if output_hidden_states:
                         __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    hidden_states + (hidden_state,)

                   __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    stage_module(A_				)

             if output_hidden_states:
                   __SCREAMING_SNAKE_CASE  :Optional[int]													=    hidden_states + (hidden_state,)

             if not return_dict:
                   return tuple(v for v in [hidden_state, hidden_states] if v is not None				)

             return BaseModelOutputWithNoAttention(last_hidden_state=A_						,hidden_states=A_				)






class    _SCREAMING_SNAKE_CASE(  _a    ):
       SCREAMING_SNAKE_CASE_  : List[str]      		=    RegNetConfig
       SCREAMING_SNAKE_CASE_  : int      		=    """regnet"""
       SCREAMING_SNAKE_CASE_  : Tuple      		=    """pixel_values"""
       SCREAMING_SNAKE_CASE_  : Dict      		=    True




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__				)     -> List[Any]:





             """simple docstring"""






             if isinstance(A_						,nn.Convad				):
                   nn.init.kaiming_normal_(module.weight						,mode='''fan_out'''						,nonlinearity='''relu'''				)
             elif isinstance(A_						,(nn.BatchNormad, nn.GroupNorm)				):
                   nn.init.constant_(module.weight						,1				)
                   nn.init.constant_(module.bias						,0				)




       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__=False				)     -> str:





             """simple docstring"""






             if isinstance(A_						,A_				):
                   __SCREAMING_SNAKE_CASE  :Dict													=    value




lowerCamelCase_        =						r"\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

lowerCamelCase_        =						r"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n"






@add_start_docstrings(
    '''The bare RegNet model outputting raw features without any specific head on top.'''       ,      _a       ,      )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class    _SCREAMING_SNAKE_CASE(  _a    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__				)     -> Optional[int]:





             """simple docstring"""






             super().__init__(A_				)
             __SCREAMING_SNAKE_CASE  :Optional[int]													=    config
             __SCREAMING_SNAKE_CASE  :List[Any]													=    RegNetEmbeddings(A_				)
             __SCREAMING_SNAKE_CASE  :List[Any]													=    RegNetEncoder(A_				)
             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    nn.AdaptiveAvgPoolad((1, 1)				)
             # Initialize weights and apply final processing
             self.post_init()




       @add_start_docstrings_to_model_forward(A_				)
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC						,output_type=A_						,config_class=_CONFIG_FOR_DOC						,modality='''vision'''						,expected_output=_EXPECTED_OUTPUT_SHAPE						,)
       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__						,SCREAMING_SNAKE_CASE__ = None						,SCREAMING_SNAKE_CASE__ = None				)     -> str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Optional[int]													=    (
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             __SCREAMING_SNAKE_CASE  :Dict													=    return_dict if return_dict is not None else self.config.use_return_dict

             __SCREAMING_SNAKE_CASE  :List[str]													=    self.embedder(A_				)

             __SCREAMING_SNAKE_CASE  :Optional[int]													=    self.encoder(
                 A_						,output_hidden_states=A_						,return_dict=A_				)

             __SCREAMING_SNAKE_CASE  :List[Any]													=    encoder_outputs[0]

             __SCREAMING_SNAKE_CASE  :Optional[Any]													=    self.pooler(A_				)

             if not return_dict:
                   return (last_hidden_state, pooled_output) + encoder_outputs[1:]

             return BaseModelOutputWithPoolingAndNoAttention(
                 last_hidden_state=A_						,pooler_output=A_						,hidden_states=encoder_outputs.hidden_states						,)






@add_start_docstrings(
    '''
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''       ,      _a       ,      )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class    _SCREAMING_SNAKE_CASE(  _a    ):




       def __init__(		self						,SCREAMING_SNAKE_CASE__				)     -> Any:





             """simple docstring"""






             super().__init__(A_				)
             __SCREAMING_SNAKE_CASE  :List[str]													=    config.num_labels
             __SCREAMING_SNAKE_CASE  :int													=    RegNetModel(A_				)
             # classification head
             __SCREAMING_SNAKE_CASE  :List[Any]													=    nn.Sequential(
                 nn.Flatten()						,nn.Linear(config.hidden_sizes[-1]						,config.num_labels				) if config.num_labels > 0 else nn.Identity()						,)
             # initialize weights and apply final processing
             self.post_init()




       @add_start_docstrings_to_model_forward(A_				)
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT						,output_type=A_						,config_class=_CONFIG_FOR_DOC						,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT						,)
       def        _UpperCamelCase	(		self						,SCREAMING_SNAKE_CASE__ = None						,SCREAMING_SNAKE_CASE__ = None						,SCREAMING_SNAKE_CASE__ = None						,SCREAMING_SNAKE_CASE__ = None						,)     -> List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE  :Optional[int]													=    return_dict if return_dict is not None else self.config.use_return_dict

             __SCREAMING_SNAKE_CASE  :int													=    self.regnet(A_						,output_hidden_states=A_						,return_dict=A_				)

             __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    outputs.pooler_output if return_dict else outputs[1]

             __SCREAMING_SNAKE_CASE  :List[str]													=    self.classifier(A_				)

             __SCREAMING_SNAKE_CASE  :List[Any]													=    None

             if labels is not None:
                   if self.config.problem_type is None:
                         if self.num_labels == 1:
                               __SCREAMING_SNAKE_CASE  :str													=    '''regression'''
                         elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                               __SCREAMING_SNAKE_CASE  :int													=    '''single_label_classification'''
                         else:
                               __SCREAMING_SNAKE_CASE  :List[str]													=    '''multi_label_classification'''
                   if self.config.problem_type == "regression":
                         __SCREAMING_SNAKE_CASE  :Any													=    MSELoss()
                         if self.num_labels == 1:
                               __SCREAMING_SNAKE_CASE  :Dict													=    loss_fct(logits.squeeze()						,labels.squeeze()				)
                         else:
                               __SCREAMING_SNAKE_CASE  :int													=    loss_fct(A_						,A_				)
                   elif self.config.problem_type == "single_label_classification":
                         __SCREAMING_SNAKE_CASE  :List[Any]													=    CrossEntropyLoss()
                         __SCREAMING_SNAKE_CASE  :Tuple													=    loss_fct(logits.view(-1						,self.num_labels				)						,labels.view(-1				)				)
                   elif self.config.problem_type == "multi_label_classification":
                         __SCREAMING_SNAKE_CASE  :Any													=    BCEWithLogitsLoss()
                         __SCREAMING_SNAKE_CASE  :Union[str, Any]													=    loss_fct(A_						,A_				)

             if not return_dict:
                   __SCREAMING_SNAKE_CASE  :List[Any]													=    (logits,) + outputs[2:]
                   return (loss,) + output if loss is not None else output

             return ImageClassifierOutputWithNoAttention(loss=A_						,logits=A_						,hidden_states=outputs.hidden_states				)



"""simple docstring"""

import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase__					=logging.get_logger(__name__)

UpperCAmelCase__					="▁"

UpperCAmelCase__					={
    "vocab_file": "vocab.json",
    "spm_file": "sentencepiece.bpe.model",
    "tokenizer_config_file": "tokenizer_config.json",
}

UpperCAmelCase__					={
    "vocab_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json",
    },
    "spm_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model",
    },
    "tokenizer_config_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json",
    },
}

UpperCAmelCase__					={
    "facebook/m2m100_418M": 1024,
}

# fmt: off
UpperCAmelCase__					={
    "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"],
    "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"]
}





class  lowerCamelCase__    (		_a     ):
      a			:  str           =		VOCAB_FILES_NAMES
      a			:  Dict           =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      a			:  int           =		PRETRAINED_VOCAB_FILES_MAP
      a			:  Union[str, Any]           =		["""input_ids""", """attention_mask"""]

      a			:  List[int]           =		[]
      a			:  List[int]           =		[]
      def __init__(		self						:						Optional[Any]   ,							A_						:						str   ,							A_						:						Dict   ,							A_						:						str=None   ,							A_						:						Dict=None   ,							A_						:						str="<s>"   ,							A_						:						Any="</s>"   ,							A_						:						List[Any]="</s>"   ,							A_						:						List[str]="<pad>"   ,							A_						:						Optional[int]="<unk>"   ,							A_						:						str="m2m100"   ,							A_						:						Optional[Dict[str, Any]] = None   ,							A_						:						Tuple=8   ,							**A_						:						Dict   ,							):






       '''simple docstring'''


       __lowercase						=						{} if sp_model_kwargs is None else sp_model_kwargs

       __lowercase						=						language_codes
       __lowercase						=						FAIRSEQ_LANGUAGE_CODES[language_codes]
       __lowercase						=						{lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code}

       __lowercase						=						kwargs.get("""additional_special_tokens"""   ,							[]				)
       kwargs["additional_special_tokens"] += [
           self.get_lang_token(A_				)
           for lang_code in fairseq_language_code
           if self.get_lang_token(A_				) not in kwargs["additional_special_tokens"]
       ]

       super().__init__(
           src_lang=A_   ,							tgt_lang=A_   ,							bos_token=A_   ,							eos_token=A_   ,							sep_token=A_   ,							unk_token=A_   ,							pad_token=A_   ,							language_codes=A_   ,							sp_model_kwargs=self.sp_model_kwargs   ,							num_madeup_words=A_   ,							**A_   ,							)

       __lowercase						=						vocab_file
       __lowercase						=						load_json(A_				)
       __lowercase						=						{v: k for k, v in self.encoder.items()}
       __lowercase						=						spm_file
       __lowercase						=						load_spm(A_   ,							self.sp_model_kwargs				)

       __lowercase						=						len(self.encoder				)

       __lowercase						=						{
           self.get_lang_token(A_				): self.encoder_size + i for i, lang_code in enumerate(A_				)
       }
       __lowercase						=						{lang_code: self.encoder_size + i for i, lang_code in enumerate(A_				)}
       __lowercase						=						{v: k for k, v in self.lang_token_to_id.items()}

       __lowercase						=						src_lang if src_lang is not None else """en"""
       __lowercase						=						tgt_lang
       __lowercase						=						self.get_lang_id(self._src_lang				)
       self.set_src_lang_special_tokens(self._src_lang				)

       __lowercase						=						num_madeup_words
      @property
      def SCREAMING_SNAKE_CASE_						(		self						:						Union[str, Any]				):






       '''simple docstring'''


       return len(self.encoder				) + len(self.lang_token_to_id				)
      @property
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict				):






       '''simple docstring'''


       return self._src_lang
      @src_lang.setter
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						new_src_lang
       self.set_src_lang_special_tokens(self._src_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       return self.sp_model.encode(A_   ,							out_type=A_				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[Any]   ,							A_						:						str				):






       '''simple docstring'''


       if token in self.lang_token_to_id:
        return self.lang_token_to_id[token]
       return self.encoder.get(A_   ,							self.encoder[self.unk_token]				)
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]   ,							A_						:						int				):






       '''simple docstring'''


       if index in self.id_to_lang_token:
        return self.id_to_lang_token[index]
       return self.decoder.get(A_   ,							self.unk_token				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Tuple   ,							A_						:						Union[str, Any]				):






       '''simple docstring'''


       __lowercase						=						[]
       __lowercase						=						""""""
       for token in tokens:
        # make sure that special tokens are not decoded using sentencepiece model
        if token in self.all_special_tokens:
         out_string += self.sp_model.decode(A_				) + token
         __lowercase						=						[]
        else:
         current_sub_tokens.append(A_				)
       out_string += self.sp_model.decode(A_				)
       return out_string.strip()
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]   ,							A_						:						List[int]   ,							A_						:						Optional[List[int]] = None   ,							A_						:						bool = False				):






       '''simple docstring'''


       if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_a=A_   ,							token_ids_a=A_   ,							already_has_special_tokens=A_				)

       __lowercase						=						[1] * len(self.prefix_tokens				)
       __lowercase						=						[1] * len(self.suffix_tokens				)
       if token_ids_a is None:
        return prefix_ones + ([0] * len(A_				)) + suffix_ones
       return prefix_ones + ([0] * len(A_				)) + ([0] * len(A_				)) + suffix_ones
      def SCREAMING_SNAKE_CASE_						(		self						:						Any   ,							A_						:						List[int]   ,							A_						:						Optional[List[int]] = None				):






       '''simple docstring'''


       if token_ids_a is None:
        return self.prefix_tokens + token_ids_a + self.suffix_tokens
       # We don't expect to process pairs, but leave the pair logic for API consistency
       return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]				):






       '''simple docstring'''


       __lowercase						=						{self.convert_ids_to_tokens(A_				): i for i in range(self.vocab_size				)}
       vocab.update(self.added_tokens_encoder				)
       return vocab
      def __getstate__(		self						:						List[str]				):






       '''simple docstring'''


       __lowercase						=						self.__dict__.copy()
       __lowercase						=						None
       return state
      def __setstate__(		self						:						Optional[Any]   ,							A_						:						Dict				):






       '''simple docstring'''


       __lowercase						=						d

       # for backward compatibility
       if not hasattr(self   ,							"""sp_model_kwargs"""				):
        __lowercase						=						{}

       __lowercase						=						load_spm(self.spm_file   ,							self.sp_model_kwargs				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Tuple   ,							A_						:						str   ,							A_						:						Optional[str] = None				):






       '''simple docstring'''


       __lowercase						=						Path(A_				)
       if not save_dir.is_dir():
        raise OSError(F'''{save_directory} should be a directory'''				)
       __lowercase						=						save_dir / (
           (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""]
       )
       __lowercase						=						save_dir / (
           (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""]
       )

       save_json(self.encoder   ,							A_				)

       if os.path.abspath(self.spm_file				) != os.path.abspath(A_				) and os.path.isfile(self.spm_file				):
        copyfile(self.spm_file   ,							A_				)
       elif not os.path.isfile(self.spm_file				):
        with open(A_   ,							"""wb"""				) as fi:
         __lowercase						=						self.sp_model.serialized_model_proto()
         fi.write(A_				)

       return (str(A_				), str(A_				))
      def SCREAMING_SNAKE_CASE_						(		self						:						List[Any]   ,							A_						:						List[str]   ,							A_						:						str = "en"   ,							A_						:						Optional[List[str]] = None   ,							A_						:						str = "ro"   ,							**A_						:						List[Any]   ,							):






       '''simple docstring'''


       __lowercase						=						src_lang
       __lowercase						=						tgt_lang
       self.set_src_lang_special_tokens(self.src_lang				)
       return super().prepare_seqaseq_batch(A_   ,							A_   ,							**A_				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]   ,							A_						:						List[Any]   ,							A_						:						Optional[str]   ,							A_						:						Optional[str]   ,							**A_						:						Optional[Any]				):






       '''simple docstring'''


       if src_lang is None or tgt_lang is None:
        raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""				)
       __lowercase						=						src_lang
       __lowercase						=						self(A_   ,							add_special_tokens=A_   ,							**A_				)
       __lowercase						=						self.get_lang_id(A_				)
       __lowercase						=						tgt_lang_id
       return inputs
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]				):






       '''simple docstring'''


       self.set_src_lang_special_tokens(self.src_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]				):






       '''simple docstring'''


       self.set_tgt_lang_special_tokens(self.tgt_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[Any]   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       __lowercase						=						self.lang_token_to_id[lang_token]
       __lowercase						=						[self.cur_lang_id]
       __lowercase						=						[self.eos_token_id]
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       __lowercase						=						self.lang_token_to_id[lang_token]
       __lowercase						=						[self.cur_lang_id]
       __lowercase						=						[self.eos_token_id]
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       return self.lang_code_to_token[lang]






      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       return self.lang_token_to_id[lang_token]






def lowerCAmelCase_   (					UpperCamelCase__						:			str					, UpperCamelCase__						:			Dict[str, Any]			):






 """simple docstring"""







 __lowercase						=						sentencepiece.SentencePieceProcessor(**UpperCamelCase__			)
 spm.Load(str(UpperCamelCase__			)			)
 return spm


def lowerCAmelCase_   (					UpperCamelCase__						:			str			):






 """simple docstring"""







 with open(UpperCamelCase__					, """r"""			) as f:
  return json.load(UpperCamelCase__			)


def lowerCAmelCase_   (					UpperCamelCase__						:			List[str]					, UpperCamelCase__						:			str			):






 """simple docstring"""







 with open(UpperCamelCase__					, """w"""			) as f:
  json.dump(UpperCamelCase__					, UpperCamelCase__					, indent=2			)
