


'''simple docstring'''



import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


__lowercase	:						str       =	logging.get_logger(__name__)

__lowercase	:						List[Any]       =	'▁'

__lowercase	:						List[Any]       =	{'vocab_file': 'sentencepiece.bpe.model'}

__lowercase	:						Any       =	{
    'vocab_file': {
        'facebook/mbart-large-en-ro': (
            'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model'
        ),
        'facebook/mbart-large-cc25': (
            'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model'
        ),
    }
}

__lowercase	:						List[Any]       =	{
    'facebook/mbart-large-en-ro': 10_24,
    'facebook/mbart-large-cc25': 10_24,
}

# fmt: off
__lowercase	:						List[Any]       =	['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN']





class 							__UpperCamelCase				(		lowerCAmelCase_					):
	A_				=    VOCAB_FILES_NAMES
	A_				=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	A_				=    PRETRAINED_VOCAB_FILES_MAP
	A_				=    ["input_ids", "attention_mask"]

	A_				=    []
	A_				=    []




	def __init__(   self						,				__a						,				__a="<s>"						,				__a="</s>"						,				__a="</s>"						,				__a="<s>"						,				__a="<unk>"						,				__a="<pad>"						,				__a="<mask>"						,				__a=None						,				__a=None						,				__a=None						,				__a = None						,				__a=None						,				**__a						,				):

						'''simple docstring'''





						__a			:       Tuple					    =  AddedToken(__a						,				lstrip=__a						,				rstrip=__a							) if isinstance(__a						,				__a							) else mask_token

						__a			:       Any					    =  {} if sp_model_kwargs is None else sp_model_kwargs

						super().__init__(
						    bos_token=__a						,				eos_token=__a						,				unk_token=__a						,				sep_token=__a						,				cls_token=__a						,				pad_token=__a						,				mask_token=__a						,				tokenizer_file=__a						,				src_lang=__a						,				tgt_lang=__a						,				additional_special_tokens=__a						,				sp_model_kwargs=self.sp_model_kwargs						,				**__a						,				)

						__a			:       Optional[Any]					    =  spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.Load(str(__a							)							)
						__a			:       int					    =  vocab_file

						# Original fairseq vocab and spm vocab must be "aligned":
						# Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
						# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
						# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
						# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

						# Mimic fairseq token-to-id alignment for the first 4 token
						__a			:       Tuple					    =  {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}

						# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
						__a			:       str					    =  1

						__a			:       Any					    =  len(self.sp_model							)
						__a			:       Dict					    =  {
						    code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__a							)
						}
						__a			:       Optional[int]					    =  {v: k for k, v in self.lang_code_to_id.items()}
						__a			:       Tuple					    =  len(self.sp_model							) + len(self.lang_code_to_id							) + self.fairseq_offset

						self.fairseq_tokens_to_ids.update(self.lang_code_to_id							)
						__a			:       Tuple					    =  {v: k for k, v in self.fairseq_tokens_to_ids.items()}
						__a			:       List[str]					    =  list(self.lang_code_to_id.keys()							)

						if additional_special_tokens is not None:
											# Only add those special tokens if they are not already there.
											self._additional_special_tokens.extend(
											    [t for t in additional_special_tokens if t not in self._additional_special_tokens]							)

						__a			:       Dict					    =  src_lang if src_lang is not None else 'en_XX'
						__a			:       int					    =  self.lang_code_to_id[self._src_lang]
						__a			:       Optional[Any]					    =  tgt_lang
						self.set_src_lang_special_tokens(self._src_lang							)




	def __getstate__(   self							):

						'''simple docstring'''





						__a			:       int					    =  self.__dict__.copy()
						__a			:       str					    =  None
						__a			:       int					    =  self.sp_model.serialized_model_proto()
						return state




	def __setstate__(   self						,				__a							):

						'''simple docstring'''





						__a			:       Any					    =  d

						# for backward compatibility
						if not hasattr(self						,				'sp_model_kwargs'							):
											__a			:       Tuple					    =  {}

						__a			:       int					    =  spm.SentencePieceProcessor(**self.sp_model_kwargs							)
						self.sp_model.LoadFromSerializedProto(self.sp_model_proto							)




	@property
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return len(self.sp_model							) + len(self.lang_code_to_id							) + self.fairseq_offset + 1  # Plus 1 for the mask token




	@property
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return self._src_lang




	@src_lang.setter
	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       Optional[Any]					    =  new_src_lang
						self.set_src_lang_special_tokens(self._src_lang							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a = None						,				__a = 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							)

						__a			:       int					    =  [1] * len(self.prefix_tokens							)
						__a			:       List[Any]					    =  [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       __UpperCAmelCase							(   self						,				__a						,				__a = 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       __UpperCAmelCase							(   self						,				__a						,				__a = None							):

						'''simple docstring'''





						__a			:       List[str]					    =  [self.sep_token_id]
						__a			:       Any					    =  [self.cls_token_id]

						if token_ids_a is None:
											return len(cls + token_ids_a + sep							) * [0]
						return len(cls + token_ids_a + sep + sep + token_ids_a + sep							) * [0]




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a						,				__a						,				**__a							):

						'''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'							)
						__a			:       Dict					    =  src_lang
						__a			:       List[Any]					    =  self(__a						,				add_special_tokens=__a						,				return_tensors=__a						,				**__a							)
						__a			:       Any					    =  self.convert_tokens_to_ids(__a							)
						__a			:       Any					    =  tgt_lang_id
						return inputs




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





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




	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						return self.sp_model.encode(__a						,				out_type=__a							)




	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						if token in self.fairseq_tokens_to_ids:
											return self.fairseq_tokens_to_ids[token]
						__a			:       Dict					    =  self.sp_model.PieceToId(__a							)

						# Need to return unknown token if the SP model returned 0
						return spm_id + self.fairseq_offset if spm_id else self.unk_token_id




	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						if index in self.fairseq_ids_to_tokens:
											return self.fairseq_ids_to_tokens[index]
						return self.sp_model.IdToPiece(index - self.fairseq_offset							)




	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       List[str]					    =  ''.join(__a							).replace(__a						,				' '							).strip()
						return out_string




	def       __UpperCAmelCase							(   self						,				__a						,				__a = None							):

						'''simple docstring'''





						if not os.path.isdir(__a							):
											logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""							)
											return
						__a			:       Dict					    =  os.path.join(
						    __a						,				(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']							)

						if os.path.abspath(self.vocab_file							) != os.path.abspath(__a							) and os.path.isfile(self.vocab_file							):
											copyfile(self.vocab_file						,				__a							)
						elif not os.path.isfile(self.vocab_file							):
											with open(__a						,				'wb'							) as fi:
																__a			:       int					    =  self.sp_model.serialized_model_proto()
																fi.write(__a							)

						return (out_vocab_file,)




	def       __UpperCAmelCase							(   self						,				__a						,				__a = "en_XX"						,				__a = None						,				__a = "ro_RO"						,				**__a						,				):

						'''simple docstring'''





						__a			:       List[str]					    =  src_lang
						__a			:       str					    =  tgt_lang
						return super().prepare_seqaseq_batch(__a						,				__a						,				**__a							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return self.set_src_lang_special_tokens(self.src_lang							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return self.set_tgt_lang_special_tokens(self.tgt_lang							)




	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       int					    =  self.lang_code_to_id[src_lang]
						__a			:       List[Any]					    =  []
						__a			:       Dict					    =  [self.eos_token_id, self.cur_lang_code]





	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       Optional[Any]					    =  self.lang_code_to_id[lang]
						__a			:       int					    =  []
						__a			:       int					    =  [self.eos_token_id, self.cur_lang_code]







'''simple docstring'''



import inspect
import os
import unittest

import torch

import accelerate
from accelerate import debug_launcher
from accelerate.test_utils import (
    execute_subprocess_async,
    require_cpu,
    require_huggingface_suite,
    require_multi_gpu,
    require_single_gpu,
)
from accelerate.utils import patch_environment





@require_huggingface_suite
class 							__UpperCamelCase				(		unittest.TestCase					):




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       List[Any]					    =  inspect.getfile(accelerate.test_utils							)
						__a			:       List[str]					    =  os.path.sep.join(
						    mod_file.split(os.path.sep							)[:-1] + ['scripts', 'external_deps', 'test_metrics.py']							)

						from accelerate.test_utils.scripts.external_deps import test_metrics  # noqa: F401

						__a			:       Union[str, Any]					    =  test_metrics




	@require_cpu
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						debug_launcher(self.test_metrics.main						,				num_processes=1							)




	@require_cpu
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						debug_launcher(self.test_metrics.main							)




	@require_single_gpu
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						self.test_metrics.main()





	@require_multi_gpu
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						print(f"""Found {torch.cuda.device_count()} devices."""							)
						__a			:       List[Any]					    =  ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
						with patch_environment(omp_num_threads=1							):
											execute_subprocess_async(__a						,				env=os.environ.copy()							)



