
import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
      from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
      lowercase__         =True
      from torch.cuda.amp import autocast

lowercase__         =logging.getLogger(__name__)




def   __UpperCamelCase	(							lowerCAmelCase__				:							Optional[Any]=None    ,  lowerCAmelCase__				:							Any=None    ):
 return field(default_factory=lambda: default    ,  metadata=_UpperCAmelCase    )



@dataclass
class 						UpperCamelCase__    :
   _SCREAMING_SNAKE_CASE :				Dict      			= field(
       metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}       )
   _SCREAMING_SNAKE_CASE :				Optional[int]      			= field(
       default=SCREAMING_SNAKE_CASE_       ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}       ,)
   _SCREAMING_SNAKE_CASE :				Optional[int]      			= field(
       default=SCREAMING_SNAKE_CASE_       ,metadata={"help": "Whether to freeze the feature extractor layers of the model."}       )
   _SCREAMING_SNAKE_CASE :				Optional[Any]      			= field(
       default=0.1       ,metadata={"help": "The dropout ratio for the attention probabilities."}       )
   _SCREAMING_SNAKE_CASE :				List[str]      			= field(
       default=0.1       ,metadata={"help": "The dropout ratio for activations inside the fully connected layer."}       )
   _SCREAMING_SNAKE_CASE :				List[str]      			= field(
       default=0.1       ,metadata={
           "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."
       }       ,)
   _SCREAMING_SNAKE_CASE :				Union[str, Any]      			= field(
       default=0.1       ,metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."}       ,)
   _SCREAMING_SNAKE_CASE :				Any      			= field(
       default=0.05       ,metadata={
           "help": (
               "Propability of each feature vector along the time axis to be chosen as the start of the vector"
               "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
               "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``."
           )
       }       ,)
   _SCREAMING_SNAKE_CASE :				Dict      			= field(default=0.0       ,metadata={"help": "The LayerDrop probability."}       )





@dataclass
class 						UpperCamelCase__    :
   _SCREAMING_SNAKE_CASE :				List[Any]      			= field(
       default=SCREAMING_SNAKE_CASE_       ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}       )
   _SCREAMING_SNAKE_CASE :				Any      			= field(
       default="train+validation"       ,metadata={
           "help": "The name of the training data set split to use (via the datasets library). Defaults to \'train\'"
       }       ,)
   _SCREAMING_SNAKE_CASE :				List[str]      			= field(
       default=SCREAMING_SNAKE_CASE_       ,metadata={"help": "Overwrite the cached preprocessed datasets or not."}       )
   _SCREAMING_SNAKE_CASE :				int      			= field(
       default=SCREAMING_SNAKE_CASE_       ,metadata={"help": "The number of processes to use for the preprocessing."}       ,)
   _SCREAMING_SNAKE_CASE :				Tuple      			= field(
       default=SCREAMING_SNAKE_CASE_       ,metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of training examples to this "
               "value if set."
           )
       }       ,)
   _SCREAMING_SNAKE_CASE :				int      			= field(
       default=SCREAMING_SNAKE_CASE_       ,metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of validation examples to this "
               "value if set."
           )
       }       ,)
   _SCREAMING_SNAKE_CASE :				Tuple      			= list_field(
       default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "\'", "\"", "�"]       ,metadata={"help": "A list of characters to remove from the transcripts."}       ,)





@dataclass
class 						UpperCamelCase__    :
   _SCREAMING_SNAKE_CASE :				int      			= 42
   _SCREAMING_SNAKE_CASE :				Tuple      			= True
   _SCREAMING_SNAKE_CASE :				List[str]      			= None
   _SCREAMING_SNAKE_CASE :				Optional[Any]      			= None
   _SCREAMING_SNAKE_CASE :				Any      			= None
   _SCREAMING_SNAKE_CASE :				List[Any]      			= None
   def __call__(self					:   Any   ,							snake_case_					:   List[Dict[str, Union[List[int], torch.Tensor]]]  ):
    __a					:    Any													=    [{'input_values': feature['input_values']} for feature in features]
    __a					:    List[str]													=    [{'input_ids': feature['labels']} for feature in features]

    __a					:    List[str]													=    self.processor.pad(
        __a   ,							padding=self.padding   ,							max_length=self.max_length   ,							pad_to_multiple_of=self.pad_to_multiple_of   ,							return_tensors='''pt'''   ,							)
    __a					:    List[Any]													=    self.processor.pad(
        labels=__a   ,							padding=self.padding   ,							max_length=self.max_length_labels   ,							pad_to_multiple_of=self.pad_to_multiple_of_labels   ,							return_tensors='''pt'''   ,							)

    # replace padding with -100 to ignore loss correctly
    __a					:    Union[str, Any]													=    labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1  )   ,							-1_0_0  )

    __a					:    List[Any]													=    labels

    return batch





class 						UpperCamelCase__    (			SCREAMING_SNAKE_CASE_       ):
   def  lowerCAmelCase     (self					:   Any   ,							snake_case_					:   nn.Module   ,							snake_case_					:   Dict[str, Union[torch.Tensor, Any]]  ):
    model.train()
    __a					:    Union[str, Any]													=    self._prepare_inputs(__a  )

    if self.use_amp:
     with autocast():
      __a					:    Tuple													=    self.compute_loss(__a   ,							__a  )
    else:
     __a					:    str													=    self.compute_loss(__a   ,							__a  )

    if self.args.n_gpu > 1:
     if model.module.config.ctc_loss_reduction == "mean":
      __a					:    Optional[int]													=    loss.mean()
     elif model.module.config.ctc_loss_reduction == "sum":
      __a					:    Any													=    loss.sum() / (inputs['labels'] >= 0).sum()
     else:
      raise ValueError(f"{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']"  )

    if self.args.gradient_accumulation_steps > 1:
     __a					:    Tuple													=    loss / self.args.gradient_accumulation_steps

    if self.use_amp:
     self.scaler.scale(__a  ).backward()
    elif self.use_apex:
     with amp.scale_loss(__a   ,							self.optimizer  ) as scaled_loss:
      scaled_loss.backward()
    elif self.deepspeed:
     self.deepspeed.backward(__a  )
    else:
     loss.backward()

    return loss.detach()





def   __UpperCamelCase	(							):
 # 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.

 __a					:    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.
  __a					:    Optional[Any]													=    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]    )    )
 else:
  __a					:    Optional[int]													=    parser.parse_args_into_dataclasses()

 # Detecting last checkpoint.
 __a					:    Optional[Any]													=    None
 if os.path.isdir(training_args.output_dir    ) and training_args.do_train and not training_args.overwrite_output_dir:
  __a					:    List[str]													=    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:
   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.'''    )

    # 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    )]    ,  )
 logger.setLevel(logging.INFO if is_main_process(training_args.local_rank    ) else logging.WARN    )

 # 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}"    )
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank    ):
  transformers.utils.logging.set_verbosity_info()
 logger.info('''Training/evaluation parameters %s'''    ,  _UpperCAmelCase    )

 # Set seed before initializing model.
 set_seed(training_args.seed    )

 # Get the datasets:
 __a					:    Union[str, Any]													=    datasets.load_dataset(
     '''common_voice'''    ,  data_args.dataset_config_name    ,  split=data_args.train_split_name    )
 __a					:    Dict													=    datasets.load_dataset('''common_voice'''    ,  data_args.dataset_config_name    ,  split='''test'''    )

 # Create and save tokenizer
 __a					:    List[str]													=    f"[{''.join(data_args.chars_to_ignore    )}]"

 def remove_special_characters(lowerCAmelCase__				:							Union[str, Any]    ):
  __a					:    str													=    re.sub(_UpperCAmelCase    ,  ''''''    ,  batch['''sentence''']    ).lower() + ' '
  return batch

 __a					:    str													=    train_dataset.map(_UpperCAmelCase    ,  remove_columns=['''sentence''']    )
 __a					:    Tuple													=    eval_dataset.map(_UpperCAmelCase    ,  remove_columns=['''sentence''']    )

 def extract_all_chars(lowerCAmelCase__				:							Optional[Any]    ):
  __a					:    List[Any]													=    ' '.join(batch['''text''']    )
  __a					:    Union[str, Any]													=    list(set(_UpperCAmelCase    )    )
  return {"vocab": [vocab], "all_text": [all_text]}

 __a					:    int													=    train_dataset.map(
     _UpperCAmelCase    ,  batched=_UpperCAmelCase    ,  batch_size=-1    ,  keep_in_memory=_UpperCAmelCase    ,  remove_columns=train_dataset.column_names    ,  )
 __a					:    str													=    train_dataset.map(
     _UpperCAmelCase    ,  batched=_UpperCAmelCase    ,  batch_size=-1    ,  keep_in_memory=_UpperCAmelCase    ,  remove_columns=eval_dataset.column_names    ,  )

 __a					:    int													=    list(set(vocab_train['''vocab'''][0]    ) | set(vocab_test['''vocab'''][0]    )    )
 __a					:    Any													=    {v: k for k, v in enumerate(_UpperCAmelCase    )}
 __a					:    Optional[int]													=    vocab_dict[' ']
 del vocab_dict[" "]
 __a					:    Optional[Any]													=    len(_UpperCAmelCase    )
 __a					:    Union[str, Any]													=    len(_UpperCAmelCase    )

 with open('''vocab.json'''    ,  '''w'''    ) as vocab_file:
  json.dump(_UpperCAmelCase    ,  _UpperCAmelCase    )

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 __a					:    List[Any]													=    WavaVecaCTCTokenizer(
     '''vocab.json'''    ,  unk_token='''[UNK]'''    ,  pad_token='''[PAD]'''    ,  word_delimiter_token='''|'''    ,  )
 __a					:    Dict													=    WavaVecaFeatureExtractor(
     feature_size=1    ,  sampling_rate=1_6_0_0_0    ,  padding_value=0.0    ,  do_normalize=_UpperCAmelCase    ,  return_attention_mask=_UpperCAmelCase    )
 __a					:    Union[str, Any]													=    WavaVecaProcessor(feature_extractor=_UpperCAmelCase    ,  tokenizer=_UpperCAmelCase    )
 __a					:    Union[str, Any]													=    WavaVecaForCTC.from_pretrained(
     model_args.model_name_or_path    ,  cache_dir=model_args.cache_dir    ,  activation_dropout=model_args.activation_dropout    ,  attention_dropout=model_args.attention_dropout    ,  hidden_dropout=model_args.hidden_dropout    ,  feat_proj_dropout=model_args.feat_proj_dropout    ,  mask_time_prob=model_args.mask_time_prob    ,  gradient_checkpointing=training_args.gradient_checkpointing    ,  layerdrop=model_args.layerdrop    ,  ctc_loss_reduction='''mean'''    ,  pad_token_id=processor.tokenizer.pad_token_id    ,  vocab_size=len(processor.tokenizer    )    ,  )

 if data_args.max_train_samples is not None:
  __a					:    Union[str, Any]													=    min(len(_UpperCAmelCase    )    ,  data_args.max_train_samples    )
  __a					:    Dict													=    train_dataset.select(range(_UpperCAmelCase    )    )

 if data_args.max_val_samples is not None:
  __a					:    str													=    eval_dataset.select(range(data_args.max_val_samples    )    )

 __a					:    Optional[int]													=    torchaudio.transforms.Resample(4_8_0_0_0    ,  1_6_0_0_0    )

 # Preprocessing the datasets.
 # We need to read the aduio files as arrays and tokenize the targets.
 def speech_file_to_array_fn(lowerCAmelCase__				:							List[str]    ):
  __a					:    Dict													=    torchaudio.load(batch['''path''']    )
  __a					:    List[Any]													=    resampler(_UpperCAmelCase    ).squeeze().numpy()
  __a					:    int													=    1_6_0_0_0
  __a					:    Union[str, Any]													=    batch['text']
  return batch

 __a					:    Dict													=    train_dataset.map(
     _UpperCAmelCase    ,  remove_columns=train_dataset.column_names    ,  num_proc=data_args.preprocessing_num_workers    ,  )
 __a					:    Optional[int]													=    eval_dataset.map(
     _UpperCAmelCase    ,  remove_columns=eval_dataset.column_names    ,  num_proc=data_args.preprocessing_num_workers    ,  )

 def prepare_dataset(lowerCAmelCase__				:							Optional[int]    ):
  # check that all files have the correct sampling rate
  assert (
      len(set(batch['''sampling_rate''']    )    ) == 1
  ), f"Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."

  __a					:    Union[str, Any]													=    processor(
      audio=batch['''speech''']    ,  text=batch['''target_text''']    ,  sampling_rate=batch['''sampling_rate'''][0]    )
  batch.update(_UpperCAmelCase    )
  return batch

 __a					:    str													=    train_dataset.map(
     _UpperCAmelCase    ,  remove_columns=train_dataset.column_names    ,  batch_size=training_args.per_device_train_batch_size    ,  batched=_UpperCAmelCase    ,  num_proc=data_args.preprocessing_num_workers    ,  )
 __a					:    int													=    eval_dataset.map(
     _UpperCAmelCase    ,  remove_columns=eval_dataset.column_names    ,  batch_size=training_args.per_device_train_batch_size    ,  batched=_UpperCAmelCase    ,  num_proc=data_args.preprocessing_num_workers    ,  )

 # Metric
 __a					:    Optional[int]													=    datasets.load_metric('''wer'''    )

 def compute_metrics(lowerCAmelCase__				:							Tuple    ):
  __a					:    Union[str, Any]													=    pred.predictions
  __a					:    Dict													=    np.argmax(_UpperCAmelCase    ,  axis=-1    )

  __a					:    Dict													=    processor.tokenizer.pad_token_id

  __a					:    List[Any]													=    processor.batch_decode(_UpperCAmelCase    )
  # we do not want to group tokens when computing the metrics
  __a					:    Optional[Any]													=    processor.batch_decode(pred.label_ids    ,  group_tokens=_UpperCAmelCase    )

  __a					:    Tuple													=    wer_metric.compute(predictions=_UpperCAmelCase    ,  references=_UpperCAmelCase    )

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 # Data collator
 __a					:    List[Any]													=    DataCollatorCTCWithPadding(processor=_UpperCAmelCase    ,  padding=_UpperCAmelCase    )

 # Initialize our Trainer
 __a					:    Optional[int]													=    CTCTrainer(
     model=_UpperCAmelCase    ,  data_collator=_UpperCAmelCase    ,  args=_UpperCAmelCase    ,  compute_metrics=_UpperCAmelCase    ,  train_dataset=train_dataset if training_args.do_train else None    ,  eval_dataset=eval_dataset if training_args.do_eval else None    ,  tokenizer=processor.feature_extractor    ,  )

 # Training
 if training_args.do_train:
  if last_checkpoint is not None:
   __a					:    Optional[int]													=    last_checkpoint
  elif os.path.isdir(model_args.model_name_or_path    ):
   __a					:    Optional[int]													=    model_args.model_name_or_path
  else:
   __a					:    int													=    None

  # Save the feature_extractor and the tokenizer
  if is_main_process(training_args.local_rank    ):
   processor.save_pretrained(training_args.output_dir    )

  __a					:    List[str]													=    trainer.train(resume_from_checkpoint=_UpperCAmelCase    )
  trainer.save_model()

  __a					:    Union[str, Any]													=    train_result.metrics
  __a					:    List[str]													=    (
      data_args.max_train_samples if data_args.max_train_samples is not None else len(_UpperCAmelCase    )
  )
  __a					:    int													=    min(_UpperCAmelCase    ,  len(_UpperCAmelCase    )    )

  trainer.log_metrics('''train'''    ,  _UpperCAmelCase    )
  trainer.save_metrics('''train'''    ,  _UpperCAmelCase    )
  trainer.save_state()

 # Evaluation
 __a					:    Any													=    {}
 if training_args.do_eval:
  logger.info('''*** Evaluate ***'''    )
  __a					:    List[str]													=    trainer.evaluate()
  __a					:    List[str]													=    data_args.max_val_samples if data_args.max_val_samples is not None else len(_UpperCAmelCase    )
  __a					:    List[str]													=    min(_UpperCAmelCase    ,  len(_UpperCAmelCase    )    )

  trainer.log_metrics('''eval'''    ,  _UpperCAmelCase    )
  trainer.save_metrics('''eval'''    ,  _UpperCAmelCase    )

 return results


if __name__ == "__main__":
      main()





'''simple docstring'''





import json
import os
import unittest

from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow

from ...test_tokenization_common import TokenizerTesterMixin



class  snake_case__						(    SCREAMING_SNAKE_CASE_  ,     unittest.TestCase				):
 A__				= DebertaTokenizer
 A__				= True
 A__				= DebertaTokenizerFast
 def A_   (   self						:							Optional[int]  )      ->   str:







       '''simple docstring'''
       super().setUp()

       # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
       __snake_case :   Union[str, Any]													=    [
           'l',
           'o',
           'w',
           'e',
           'r',
           's',
           't',
           'i',
           'd',
           'n',
           '\u0120',
           '\u0120l',
           '\u0120n',
           '\u0120lo',
           '\u0120low',
           'er',
           '\u0120lowest',
           '\u0120newer',
           '\u0120wider',
           '[UNK]',
       ]
       __snake_case :   List[str]													=    dict(zip(__a      ,     range(len(__a  )  )  )  )
       __snake_case :   int													=    ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
       __snake_case :   Any													=    {'unk_token': '[UNK]'}

       __snake_case :   Union[str, Any]													=    os.path.join(self.tmpdirname      ,     VOCAB_FILES_NAMES['vocab_file']  )
       __snake_case :   Dict													=    os.path.join(self.tmpdirname      ,     VOCAB_FILES_NAMES['merges_file']  )
       with open(self.vocab_file      ,     'w'      ,     encoding='utf-8'  ) as fp:
             fp.write(json.dumps(__a  ) + '\n'  )
       with open(self.merges_file      ,     'w'      ,     encoding='utf-8'  ) as fp:
             fp.write('\n'.join(__a  )  )
 def A_   (   self						:							Optional[int]      ,     **__a						:							List[Any]  )      ->   Optional[Any]:







       '''simple docstring'''
       kwargs.update(self.special_tokens_map  )
       return self.tokenizer_class.from_pretrained(self.tmpdirname      ,     **__a  )
 def A_   (   self						:							Optional[int]      ,     __a						:							Dict  )      ->   List[str]:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    'lower newer'
       __snake_case :   List[Any]													=    'lower newer'
       return input_text, output_text
 def A_   (   self						:							Dict  )      ->   Union[str, Any]:







       '''simple docstring'''
       __snake_case :   str													=    self.get_tokenizer()
       __snake_case :   List[str]													=    'lower newer'
       __snake_case :   Tuple													=    ['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er']
       __snake_case :   Optional[int]													=    tokenizer.tokenize(__a  )
       self.assertListEqual(__a      ,     __a  )

       __snake_case :   str													=    tokens + [tokenizer.unk_token]
       __snake_case :   Tuple													=    [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
       self.assertListEqual(tokenizer.convert_tokens_to_ids(__a  )      ,     __a  )
 def A_   (   self						:							List[Any]  )      ->   Dict:







       '''simple docstring'''
       __snake_case :   List[str]													=    self.get_tokenizer()
       __snake_case :   List[str]													=    tokenizer('Hello'      ,     'World'  )
       __snake_case :   int													=    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
       self.assertListEqual(tokd['token_type_ids']      ,     __a  )
 @slow
 def A_   (   self						:							Dict  )      ->   str:







       '''simple docstring'''
       __snake_case :   str													=    self.tokenizer_class.from_pretrained('microsoft/deberta-base'  )

       __snake_case :   str													=    tokenizer.encode('sequence builders'      ,     add_special_tokens=__a  )
       __snake_case :   Any													=    tokenizer.encode('multi-sequence build'      ,     add_special_tokens=__a  )

       __snake_case :   List[Any]													=    tokenizer.encode(
           'sequence builders'      ,     add_special_tokens=__a      ,     add_prefix_space=__a  )
       __snake_case :   Union[str, Any]													=    tokenizer.encode(
           'sequence builders'      ,     'multi-sequence build'      ,     add_special_tokens=__a      ,     add_prefix_space=__a  )

       __snake_case :   int													=    tokenizer.build_inputs_with_special_tokens(__a  )
       __snake_case :   Tuple													=    tokenizer.build_inputs_with_special_tokens(__a      ,     __a  )

       assert encoded_sentence == encoded_text_from_decode
       assert encoded_pair == encoded_pair_from_decode





 @slow
 def A_   (   self						:							Optional[Any]  )      ->   Optional[int]:







       '''simple docstring'''
       __snake_case :   int													=    [self.tokenizer_class]
       if self.test_rust_tokenizer:
             tokenizer_classes.append(self.rust_tokenizer_class  )

       for tokenizer_class in tokenizer_classes:
             __snake_case :   List[Any]													=    tokenizer_class.from_pretrained('microsoft/deberta-base'  )

             __snake_case :   int													=    [
                 'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations',
                 'ALBERT incorporates two parameter reduction techniques',
                 'The first one is a factorized embedding parameterization. By decomposing the large vocabulary'
                 ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'
                 ' vocabulary embedding.',
             ]

             __snake_case :   Union[str, Any]													=    tokenizer(__a      ,     padding=__a  )
             __snake_case :   List[str]													=    [tokenizer.decode(__a      ,     skip_special_tokens=__a  ) for seq in encoding['input_ids']]

             # fmt: off
             __snake_case :   Optional[Any]													=    {
                 'input_ids': [
                     [1, 2118, 11126, 565, 35, 83, 25191, 163, 18854, 13, 12156, 12, 16101, 25376, 13807, 9, 22205, 27893, 1635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [1, 2118, 11126, 565, 24536, 80, 43797, 4878, 7373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [1, 133, 78, 65, 16, 10, 3724, 1538, 33183, 11303, 43797, 1938, 4, 870, 24165, 29105, 5, 739, 32644, 33183, 11303, 36173, 88, 80, 650, 7821, 45940, 6, 52, 2559, 5, 1836, 9, 5, 7397, 13171, 31, 5, 1836, 9, 32644, 33183, 11303, 4, 2]
                 ],
                 'token_type_ids': [
                     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                 ],
                 'attention_mask': [
                     [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
                 ]
             }
             # fmt: on

             __snake_case :   int													=    [
                 'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations',
                 'ALBERT incorporates two parameter reduction techniques',
                 'The first one is a factorized embedding parameterization. By decomposing the large vocabulary'
                 ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'
                 ' vocabulary embedding.',
             ]

             self.assertDictEqual(encoding.data      ,     __a  )

             for expected, decoded in zip(__a      ,     __a  ):
                   self.assertEqual(__a      ,     __a  )



