






"""simple docstring"""



import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput


def      SCREAMING_SNAKE_CASE__    (   snake_case    :      int       , snake_case    :      List[Any]=0.999       , snake_case    :      Optional[Any]="cosine"       , )->						Union[str, Any]:






     '''simple docstring'''



     if alpha_transform_type == "cosine":

          def alpha_bar_fn(snake_case    :      List[str]							):
               return math.cos((t + 0.008) / 1.008 * math.pi / 2							) ** 2

     elif alpha_transform_type == "exp":

          def alpha_bar_fn(snake_case    :      List[Any]							):
               return math.exp(t * -12.0							)

     else:
          raise ValueError(f'Unsupported alpha_tranform_type: {alpha_transform_type}'							)

     UpperCAmelCase__		:  str				=				[]
     for i in range(lowerCAmelCase_							):
          UpperCAmelCase__		:  List[str]				=				i / num_diffusion_timesteps
          UpperCAmelCase__		:  str				=				(i + 1) / num_diffusion_timesteps
          betas.append(min(1 - alpha_bar_fn(lowerCAmelCase_							) / alpha_bar_fn(lowerCAmelCase_							)       , lowerCAmelCase_							)							)
     return torch.tensor(lowerCAmelCase_       , dtype=torch.floataa							)




class        lowerCAmelCase__       (  __a				,		__a					):
   SCREAMING_SNAKE_CASE_					      =[e.name for e in KarrasDiffusionSchedulers]
   SCREAMING_SNAKE_CASE_					      =2
   @register_to_config
   def __init__(						self	:     str				,       snake_case__	:     Optional[int] = 1_0_0_0				,       snake_case__	:     Any = 0.0_0085				,       snake_case__	:     Optional[int] = 0.012				,       snake_case__	:     Any = "linear"				,       snake_case__	:     List[Any] = None				,       snake_case__	:     Optional[int] = "epsilon"				,       snake_case__	:     Optional[int] = "linspace"				,       snake_case__	:     Optional[Any] = 0				,       ):


        '''simple docstring'''
        if trained_betas is not None:
             UpperCAmelCase__		:  Optional[int]				=				torch.tensor(lowerCAmelCase__				,       dtype=torch.floataa				)
        elif beta_schedule == "linear":
             UpperCAmelCase__		:  Optional[int]				=				torch.linspace(lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__				,       dtype=torch.floataa				)
        elif beta_schedule == "scaled_linear":
             # this schedule is very specific to the latent diffusion model.
             UpperCAmelCase__		:  Tuple				=				(
                 torch.linspace(beta_start**0.5				,       beta_end**0.5				,       lowerCAmelCase__				,       dtype=torch.floataa				) ** 2
             )
        elif beta_schedule == "squaredcos_cap_v2":
             # Glide cosine schedule
             UpperCAmelCase__		:  Union[str, Any]				=				betas_for_alpha_bar(lowerCAmelCase__				)
        else:
             raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}'				)

        UpperCAmelCase__		:  Union[str, Any]				=				1.0 - self.betas
        UpperCAmelCase__		:  List[Any]				=				torch.cumprod(self.alphas				,       dim=0				)

        #  set all values
        self.set_timesteps(lowerCAmelCase__				,       lowerCAmelCase__				,       lowerCAmelCase__				)
   def 	__a				(						self	:     List[Any]				,       snake_case__	:     Optional[Any]				,       snake_case__	:     List[Any]=None				):


        '''simple docstring'''
        if schedule_timesteps is None:
             UpperCAmelCase__		:  Optional[Any]				=				self.timesteps

        UpperCAmelCase__		:  Optional[Any]				=				(schedule_timesteps == timestep).nonzero()

        # The sigma index that is taken for the **very** first `step`
        # is always the second index (or the last index if there is only 1)
        # This way we can ensure we don't accidentally skip a sigma in
        # case we start in the middle of the denoising schedule (e.g. for image-to-image)
        if len(self._index_counter				) == 0:
             UpperCAmelCase__		:  Dict				=				1 if len(lowerCAmelCase__				) > 1 else 0
        else:
             UpperCAmelCase__		:  str				=				timestep.cpu().item() if torch.is_tensor(lowerCAmelCase__				) else timestep
             UpperCAmelCase__		:  Any				=				self._index_counter[timestep_int]

        return indices[pos].item()
   @property
   def 	__a				(						self	:     Tuple				):


        '''simple docstring'''
        # standard deviation of the initial noise distribution
        if self.config.timestep_spacing in ["linspace", "trailing"]:
             return self.sigmas.max()

        return (self.sigmas.max() ** 2 + 1) ** 0.5
   def 	__a				(						self	:     List[str]				,       snake_case__	:     List[Any]				,       snake_case__	:     Optional[int]				,       ):


        '''simple docstring'''
        UpperCAmelCase__		:  Dict				=				self.index_for_timestep(lowerCAmelCase__				)

        if self.state_in_first_order:
             UpperCAmelCase__		:  Any				=				self.sigmas[step_index]
        else:
             UpperCAmelCase__		:  Tuple				=				self.sigmas_interpol[step_index - 1]

        UpperCAmelCase__		:  Dict				=				sample / ((sigma**2 + 1) ** 0.5)
        return sample
   def 	__a				(						self	:     Union[str, Any]				,       snake_case__	:     Union[str, Any]				,       snake_case__	:     Any = None				,       snake_case__	:     Any = None				,       ):


        '''simple docstring'''
        UpperCAmelCase__		:  Dict				=				num_inference_steps

        UpperCAmelCase__		:  int				=				num_train_timesteps or self.config.num_train_timesteps

        # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
        if self.config.timestep_spacing == "linspace":
             UpperCAmelCase__		:  Dict				=				np.linspace(0				,       num_train_timesteps - 1				,       lowerCAmelCase__				,       dtype=lowerCAmelCase__				)[::-1].copy()
        elif self.config.timestep_spacing == "leading":
             UpperCAmelCase__		:  List[str]				=				num_train_timesteps // self.num_inference_steps
             # creates integer timesteps by multiplying by ratio
             # casting to int to avoid issues when num_inference_step is power of 3
             UpperCAmelCase__		:  Optional[Any]				=				(np.arange(0				,       lowerCAmelCase__				) * step_ratio).round()[::-1].copy().astype(lowerCAmelCase__				)
             timesteps += self.config.steps_offset
        elif self.config.timestep_spacing == "trailing":
             UpperCAmelCase__		:  Any				=				num_train_timesteps / self.num_inference_steps
             # creates integer timesteps by multiplying by ratio
             # casting to int to avoid issues when num_inference_step is power of 3
             UpperCAmelCase__		:  List[Any]				=				(np.arange(lowerCAmelCase__				,       0				,       -step_ratio				)).round().copy().astype(lowerCAmelCase__				)
             timesteps -= 1
        else:
             raise ValueError(
                 f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'				)

        UpperCAmelCase__		:  List[str]				=				np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5				)
        UpperCAmelCase__		:  Dict				=				torch.from_numpy(np.log(lowerCAmelCase__				)				).to(lowerCAmelCase__				)

        UpperCAmelCase__		:  Optional[Any]				=				np.interp(lowerCAmelCase__				,       np.arange(0				,       len(lowerCAmelCase__				)				)				,       lowerCAmelCase__				)
        UpperCAmelCase__		:  Dict				=				np.concatenate([sigmas, [0.0]]				).astype(np.floataa				)
        UpperCAmelCase__		:  Any				=				torch.from_numpy(lowerCAmelCase__				).to(device=lowerCAmelCase__				)

        # compute up and down sigmas
        UpperCAmelCase__		:  str				=				sigmas.roll(-1				)
        UpperCAmelCase__		:  List[Any]				=				0.0
        UpperCAmelCase__		:  Optional[int]				=				(sigmas_next**2 * (sigmas**2 - sigmas_next**2) / sigmas**2) ** 0.5
        UpperCAmelCase__		:  Any				=				(sigmas_next**2 - sigmas_up**2) ** 0.5
        UpperCAmelCase__		:  Tuple				=				0.0

        # compute interpolated sigmas
        UpperCAmelCase__		:  Union[str, Any]				=				sigmas.log().lerp(sigmas_down.log()				,       0.5				).exp()
        UpperCAmelCase__		:  int				=				0.0

        # set sigmas
        UpperCAmelCase__		:  List[Any]				=				torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2				), sigmas[-1:]]				)
        UpperCAmelCase__		:  str				=				torch.cat(
            [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2				), sigmas_interpol[-1:]]				)
        UpperCAmelCase__		:  Optional[int]				=				torch.cat([sigmas_up[:1], sigmas_up[1:].repeat_interleave(2				), sigmas_up[-1:]]				)
        UpperCAmelCase__		:  List[Any]				=				torch.cat([sigmas_down[:1], sigmas_down[1:].repeat_interleave(2				), sigmas_down[-1:]]				)

        if str(lowerCAmelCase__				).startswith("mps"				):
             # mps does not support float64
             UpperCAmelCase__		:  List[str]				=				torch.from_numpy(lowerCAmelCase__				).to(lowerCAmelCase__				,       dtype=torch.floataa				)
        else:
             UpperCAmelCase__		:  int				=				torch.from_numpy(lowerCAmelCase__				).to(lowerCAmelCase__				)

        UpperCAmelCase__		:  int				=				self.sigma_to_t(lowerCAmelCase__				).to(lowerCAmelCase__				,       dtype=timesteps.dtype				)
        UpperCAmelCase__		:  Optional[int]				=				torch.stack((timesteps_interpol[:-2, None], timesteps[1:, None])				,       dim=-1				).flatten()

        UpperCAmelCase__		:  Any				=				torch.cat([timesteps[:1], interleaved_timesteps]				)

        UpperCAmelCase__		:  Dict				=				None

        # for exp beta schedules, such as the one for `pipeline_shap_e.py`
        # we need an index counter
        UpperCAmelCase__		:  Dict				=				defaultdict(lowerCAmelCase__				)
   def 	__a				(						self	:     str				,       snake_case__	:     List[Any]				):


        '''simple docstring'''
        # get log sigma
        UpperCAmelCase__		:  Union[str, Any]				=				sigma.log()

        # get distribution
        UpperCAmelCase__		:  str				=				log_sigma - self.log_sigmas[:, None]

        # get sigmas range
        UpperCAmelCase__		:  str				=				dists.ge(0				).cumsum(dim=0				).argmax(dim=0				).clamp(max=self.log_sigmas.shape[0] - 2				)
        UpperCAmelCase__		:  List[Any]				=				low_idx + 1

        UpperCAmelCase__		:  Optional[int]				=				self.log_sigmas[low_idx]
        UpperCAmelCase__		:  Dict				=				self.log_sigmas[high_idx]

        # interpolate sigmas
        UpperCAmelCase__		:  Union[str, Any]				=				(low - log_sigma) / (low - high)
        UpperCAmelCase__		:  Union[str, Any]				=				w.clamp(0				,       1				)

        # transform interpolation to time range
        UpperCAmelCase__		:  Union[str, Any]				=				(1 - w) * low_idx + w * high_idx
        UpperCAmelCase__		:  str				=				t.view(sigma.shape				)
        return t
   @property
   def 	__a				(						self	:     Tuple				):


        '''simple docstring'''
        return self.sample is None
   def 	__a				(						self	:     Dict				,       snake_case__	:     int				,       snake_case__	:     Any				,       snake_case__	:     List[str]				,       snake_case__	:     List[Any] = None				,       snake_case__	:     Optional[Any] = True				,       ):


        '''simple docstring'''
        UpperCAmelCase__		:  Union[str, Any]				=				self.index_for_timestep(lowerCAmelCase__				)

        # advance index counter by 1
        UpperCAmelCase__		:  Optional[Any]				=				timestep.cpu().item() if torch.is_tensor(lowerCAmelCase__				) else timestep
        self._index_counter[timestep_int] += 1

        if self.state_in_first_order:
             UpperCAmelCase__		:  Tuple				=				self.sigmas[step_index]
             UpperCAmelCase__		:  List[str]				=				self.sigmas_interpol[step_index]
             UpperCAmelCase__		:  Tuple				=				self.sigmas_up[step_index]
             UpperCAmelCase__		:  Optional[int]				=				self.sigmas_down[step_index - 1]
        else:
             # 2nd order / KPDM2's method
             UpperCAmelCase__		:  List[Any]				=				self.sigmas[step_index - 1]
             UpperCAmelCase__		:  Tuple				=				self.sigmas_interpol[step_index - 1]
             UpperCAmelCase__		:  List[Any]				=				self.sigmas_up[step_index - 1]
             UpperCAmelCase__		:  Tuple				=				self.sigmas_down[step_index - 1]

        # currently only gamma=0 is supported. This usually works best anyways.
        # We can support gamma in the future but then need to scale the timestep before
        # passing it to the model which requires a change in API
        UpperCAmelCase__		:  int				=				0
        UpperCAmelCase__		:  str				=				sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

        UpperCAmelCase__		:  Optional[int]				=				model_output.device
        UpperCAmelCase__		:  Tuple				=				randn_tensor(model_output.shape				,       dtype=model_output.dtype				,       device=lowerCAmelCase__				,       generator=lowerCAmelCase__				)

        # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
        if self.config.prediction_type == "epsilon":
             UpperCAmelCase__		:  int				=				sigma_hat if self.state_in_first_order else sigma_interpol
             UpperCAmelCase__		:  List[Any]				=				sample - sigma_input * model_output
        elif self.config.prediction_type == "v_prediction":
             UpperCAmelCase__		:  Tuple				=				sigma_hat if self.state_in_first_order else sigma_interpol
             UpperCAmelCase__		:  Dict				=				model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
                 sample / (sigma_input**2 + 1)
             )
        elif self.config.prediction_type == "sample":
             raise NotImplementedError("prediction_type not implemented yet: sample"				)
        else:
             raise ValueError(
                 f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'				)

        if self.state_in_first_order:
             # 2. Convert to an ODE derivative for 1st order
             UpperCAmelCase__		:  Any				=				(sample - pred_original_sample) / sigma_hat
             # 3. delta timestep
             UpperCAmelCase__		:  Any				=				sigma_interpol - sigma_hat

             # store for 2nd order step
             UpperCAmelCase__		:  List[str]				=				sample
             UpperCAmelCase__		:  Optional[Any]				=				dt
             UpperCAmelCase__		:  Optional[int]				=				sample + derivative * dt
        else:
             # DPM-Solver-2
             # 2. Convert to an ODE derivative for 2nd order
             UpperCAmelCase__		:  Optional[int]				=				(sample - pred_original_sample) / sigma_interpol
             # 3. delta timestep
             UpperCAmelCase__		:  List[Any]				=				sigma_down - sigma_hat

             UpperCAmelCase__		:  int				=				self.sample
             UpperCAmelCase__		:  Union[str, Any]				=				None

             UpperCAmelCase__		:  str				=				sample + derivative * dt
             UpperCAmelCase__		:  List[str]				=				prev_sample + noise * sigma_up

        if not return_dict:
             return (prev_sample,)

        return SchedulerOutput(prev_sample=lowerCAmelCase__				)
   def 	__a				(						self	:     List[Any]				,       snake_case__	:     Union[str, Any]				,       snake_case__	:     List[Any]				,       snake_case__	:     Any				,       ):


        '''simple docstring'''
        # Make sure sigmas and timesteps have the same device and dtype as original_samples
        UpperCAmelCase__		:  List[Any]				=				self.sigmas.to(device=original_samples.device				,       dtype=original_samples.dtype				)
        if original_samples.device.type == "mps" and torch.is_floating_point(lowerCAmelCase__				):
             # mps does not support float64
             UpperCAmelCase__		:  Any				=				self.timesteps.to(original_samples.device				,       dtype=torch.floataa				)
             UpperCAmelCase__		:  Dict				=				timesteps.to(original_samples.device				,       dtype=torch.floataa				)
        else:
             UpperCAmelCase__		:  Dict				=				self.timesteps.to(original_samples.device				)
             UpperCAmelCase__		:  Tuple				=				timesteps.to(original_samples.device				)

        UpperCAmelCase__		:  Any				=				[self.index_for_timestep(lowerCAmelCase__				,       lowerCAmelCase__				) for t in timesteps]

        UpperCAmelCase__		:  List[Any]				=				sigmas[step_indices].flatten()
        while len(sigma.shape				) < len(original_samples.shape				):
             UpperCAmelCase__		:  Dict				=				sigma.unsqueeze(-1				)

        UpperCAmelCase__		:  str				=				original_samples + noise * sigma
        return noisy_samples




   def __len__(						self	:     Optional[Any]				):


        '''simple docstring'''
        return self.config.num_train_timesteps




'''simple docstring'''

import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class 	__lowerCAmelCase    (  __a       ,					unittest.TestCase				):
     snake_case   :    Dict							      =      PreTrainedTokenizerFast
     snake_case   :    Optional[Any]							      =      False
     snake_case   :    List[str]							      =      True
     snake_case   :    Any							      =      """tokenizer_file"""



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Dict         =    False  # because we don't have pretrained_vocab_files_map
          super().setUp()
          _UpperCAmelCase					:  Optional[Any]         =    True

          _UpperCAmelCase					:  int         =    ["""robot-test/dummy-tokenizer-fast""", """robot-test/dummy-tokenizer-wordlevel"""]
          _UpperCAmelCase					:  Union[str, Any]         =    """SaulLu/dummy-tokenizer-bytelevel-bpe"""

          # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
          _UpperCAmelCase					:  List[str]         =    [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

          _UpperCAmelCase					:  Optional[Any]         =    PreTrainedTokenizerFast.from_pretrained(model_paths[0]	)
          tokenizer.save_pretrained(self.tmpdirname	)



     def     snake_case_ (self	):
          # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
          # model
          pass



     def     snake_case_ (self	):
          # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
          # model
          pass



     def     snake_case_ (self	):
          # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
          # model
          pass



     def     snake_case_ (self	):
          # PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
          pass



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Optional[Any]         =    self.tmpdirname
          # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"	):
                    try:
                         _UpperCAmelCase					:  Optional[int]         =    tempfile.mkdtemp()
                         _UpperCAmelCase					:  Tuple         =    self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__						,	**lowerCAmelCase__	)

                         tokenizer.save_pretrained(self.tmpdirname	)
                         super().test_training_new_tokenizer()
                    finally:
                         # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                         # is restored
                         shutil.rmtree(self.tmpdirname	)
                         _UpperCAmelCase					:  Optional[int]         =    tmpdirname_orig



     def     snake_case_ (self	):
          _UpperCAmelCase					:  int         =    self.tmpdirname
          # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"	):
                    try:
                         _UpperCAmelCase					:  Any         =    tempfile.mkdtemp()
                         _UpperCAmelCase					:  Union[str, Any]         =    self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__						,	**lowerCAmelCase__	)

                         tokenizer.save_pretrained(self.tmpdirname	)
                         super().test_training_new_tokenizer_with_special_tokens_change()
                    finally:
                         # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                         # is restored
                         shutil.rmtree(self.tmpdirname	)
                         _UpperCAmelCase					:  Dict         =    tmpdirname_orig



     def     snake_case_ (self	):
          _UpperCAmelCase					:  List[Any]         =    self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name	)

          _UpperCAmelCase					:  Dict         =    ("""a""" for _ in range(1_0_0_0	))
          _UpperCAmelCase					:  Optional[int]         =    tokenizer.train_new_from_iterator(text_iterator=lowerCAmelCase__						,	length=1_0_0_0						,	vocab_size=5_0	)

          _UpperCAmelCase					:  int         =    new_tokenizer.encode("""a🤗"""	)
          self.assertEqual(lowerCAmelCase__						,	[6_4, 1_7_2, 2_5_3, 9_7, 2_4_5]	)







@require_tokenizers
class 	__lowerCAmelCase    (  unittest.TestCase				):



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Any         =    AutoTokenizer.from_pretrained("""bert-base-cased"""	)
          _UpperCAmelCase					:  Dict         =    json.loads(tokenizer._tokenizer.to_str()	)
          _UpperCAmelCase					:  List[Any]         =    len(lowerCAmelCase__	)

          with tempfile.TemporaryDirectory() as tmp_dir:
               # Hack to save this in the tokenizer_config.json
               _UpperCAmelCase					:  Union[str, Any]         =    ["""tokenizer.4.0.0.json"""]
               tokenizer.save_pretrained(lowerCAmelCase__	)
               json.dump(lowerCAmelCase__						,	open(os.path.join(lowerCAmelCase__						,	"""tokenizer.4.0.0.json"""	)						,	"""w"""	)	)

               # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
               _UpperCAmelCase					:  Optional[int]         =    AutoTokenizer.from_pretrained(lowerCAmelCase__	)
               self.assertEqual(len(lowerCAmelCase__	)						,	len(lowerCAmelCase__	) + 1	)
               _UpperCAmelCase					:  Tuple         =    json.loads(new_tokenizer._tokenizer.to_str()	)
               self.assertIn("""huggingface"""						,	json_tokenizer["""model"""]["""vocab"""]	)

               # Will need to be adjusted if we reach v42 and this test is still here.
               # Should pick the old tokenizer file as the version of Transformers is < 4.0.0
               shutil.move(os.path.join(lowerCAmelCase__						,	"""tokenizer.4.0.0.json"""	)						,	os.path.join(lowerCAmelCase__						,	"""tokenizer.42.0.0.json"""	)	)
               _UpperCAmelCase					:  Tuple         =    ["""tokenizer.42.0.0.json"""]
               tokenizer.save_pretrained(lowerCAmelCase__	)
               _UpperCAmelCase					:  str         =    AutoTokenizer.from_pretrained(lowerCAmelCase__	)
               self.assertEqual(len(lowerCAmelCase__	)						,	len(lowerCAmelCase__	)	)
               _UpperCAmelCase					:  Union[str, Any]         =    json.loads(new_tokenizer._tokenizer.to_str()	)
               self.assertNotIn("""huggingface"""						,	json_tokenizer["""model"""]["""vocab"""]	)



     def     snake_case_ (self	):
          # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
          _UpperCAmelCase					:  List[Any]         =    """hf-internal-testing/test-two-tokenizers"""

          # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
          _UpperCAmelCase					:  Dict         =    AutoTokenizer.from_pretrained(lowerCAmelCase__	)
          self.assertEqual(len(lowerCAmelCase__	)						,	2_8_9_9_7	)
          _UpperCAmelCase					:  List[str]         =    json.loads(tokenizer._tokenizer.to_str()	)
          self.assertIn("""huggingface"""						,	json_tokenizer["""model"""]["""vocab"""]	)

          # Testing an older version by monkey-patching the version in the module it's used.
          import transformers as old_transformers

          _UpperCAmelCase					:  Optional[Any]         =    """3.0.0"""
          _UpperCAmelCase					:  str         =    old_transformers.models.auto.AutoTokenizer.from_pretrained(lowerCAmelCase__	)
          self.assertEqual(len(lowerCAmelCase__	)						,	2_8_9_9_6	)
          _UpperCAmelCase					:  Optional[int]         =    json.loads(old_tokenizer._tokenizer.to_str()	)
          self.assertNotIn("""huggingface"""						,	json_tokenizer["""model"""]["""vocab"""]	)







@require_tokenizers
class 	__lowerCAmelCase    (  unittest.TestCase				):



     def     snake_case_ (self	):
          # See https://github.com/huggingface/transformers/pull/12550
          # and https://github.com/huggingface/tokenizers/issues/537
          _UpperCAmelCase					:  int         =    PreTrainedTokenizerFast.from_pretrained("""robot-test/dummy-tokenizer-wordlevel"""	)
          _UpperCAmelCase					:  str         =    """The Matrix is a 1999 science fiction action film."""

          with concurrent.futures.ThreadPoolExecutor() as executor:
               _UpperCAmelCase					:  List[Any]         =    [executor.submit(self.fetch						,	lowerCAmelCase__						,	lowerCAmelCase__	) for i in range(1_0	)]
               _UpperCAmelCase					:  Any         =    [future.result() for future in futures]
               self.assertEqual(lowerCAmelCase__						,	[[1, 1_0, 0, 8, 0, 1_8, 0, 0, 0, 2] for i in range(1_0	)]	)



     def     snake_case_ (self						,	lowerCAmelCase__						,	lowerCAmelCase__	):
          return tokenizer.encode(lowerCAmelCase__						,	truncation="""longest_first"""						,	padding="""longest"""	)


