


'''simple docstring'''




import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import numpy as np
import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForMaskedImageModeling,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
_a   :   Dict												=   logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt")

_a   :   str												=   list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys())
_a   :   int												=   tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class 			_lowercase :
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(
       default="cifar10"						,					metadata={"help": "Name of a dataset from the datasets package"}							)
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(
       default=__lowercase						,					metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}							)
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(
       default=__lowercase						,					metadata={"help": "The column name of the images in the files. If not set, will try to use 'image' or 'img'."}						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(default=__lowercase						,					metadata={"help": "A folder containing the training data."}							)
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(default=__lowercase						,					metadata={"help": "A folder containing the validation data."}							)
   _SCREAMING_SNAKE_CASE  :  Optional[float]          =	field(
       default=0.15						,					metadata={"help": "Percent to split off of train for validation."}							)
   _SCREAMING_SNAKE_CASE  :  int          =	field(default=3_2						,					metadata={"help": "The size of the square patches to use for masking."}							)
   _SCREAMING_SNAKE_CASE  :  float          =	field(
       default=0.6						,					metadata={"help": "Percentage of patches to mask."}						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[int]          =	field(
       default=__lowercase						,					metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of training examples to this "
               "value if set."
           )
       }						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[int]          =	field(
       default=__lowercase						,					metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
               "value if set."
           )
       }						,					)
   def a  (						self       :      List[str]      ) ->							Tuple:
        __snake_case           =						{}
        if self.train_dir is not None:
             __snake_case           =						self.train_dir
        if self.validation_dir is not None:
             __snake_case           =						self.validation_dir
        __snake_case           =						data_files if data_files else None




@dataclass
class 			_lowercase :
   _SCREAMING_SNAKE_CASE  :  str          =	field(
       default=__lowercase						,					metadata={
           "help": (
               "The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a "
               "checkpoint identifier on the hub. "
               "Don't set if you want to train a model from scratch."
           )
       }						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(
       default=__lowercase						,					metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(__lowercase							)}						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(
       default=__lowercase						,					metadata={"help": "Pretrained config name or path if not the same as model_name"}							)
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(
       default=__lowercase						,					metadata={
           "help": (
               "Override some existing default config settings when a model is trained from scratch. Example: "
               "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
           )
       }						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[str]          =	field(
       default=__lowercase						,					metadata={"help": "Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"}						,					)
   _SCREAMING_SNAKE_CASE  :  str          =	field(
       default="main"						,					metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}						,					)
   _SCREAMING_SNAKE_CASE  :  str          =	field(default=__lowercase						,					metadata={"help": "Name or path of preprocessor config."}							)
   _SCREAMING_SNAKE_CASE  :  bool          =	field(
       default=__lowercase						,					metadata={
           "help": (
               "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
               "with private models)."
           )
       }						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[int]          =	field(
       default=__lowercase						,					metadata={
           "help": (
               "The size (resolution) of each image. If not specified, will use `image_size` of the configuration."
           )
       }						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[int]          =	field(
       default=__lowercase						,					metadata={
           "help": (
               "The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration."
           )
       }						,					)
   _SCREAMING_SNAKE_CASE  :  Optional[int]          =	field(
       default=__lowercase						,					metadata={"help": "Stride to use for the encoder."}						,					)




class 			_lowercase :
   def __init__(						self       :      Any       ,   SCREAMING_SNAKE_CASE_       :      Dict=192       ,   SCREAMING_SNAKE_CASE_       :      int=32       ,   SCREAMING_SNAKE_CASE_       :      Union[str, Any]=4       ,   SCREAMING_SNAKE_CASE_       :      Dict=0.6      ) ->							List[str]:
        __snake_case           =						input_size
        __snake_case           =						mask_patch_size
        __snake_case           =						model_patch_size
        __snake_case           =						mask_ratio

        if self.input_size % self.mask_patch_size != 0:
             raise ValueError('Input size must be divisible by mask patch size'      )
        if self.mask_patch_size % self.model_patch_size != 0:
             raise ValueError('Mask patch size must be divisible by model patch size'      )

        __snake_case           =						self.input_size // self.mask_patch_size
        __snake_case           =						self.mask_patch_size // self.model_patch_size

        __snake_case           =						self.rand_size**2
        __snake_case           =						int(np.ceil(self.token_count * self.mask_ratio      )      )





   def __call__(						self       :      List[Any]      ) ->							Tuple:
        __snake_case           =						np.random.permutation(self.token_count      )[: self.mask_count]
        __snake_case           =						np.zeros(self.token_count       ,   dtype=SCREAMING_SNAKE_CASE_      )
        __snake_case           =						1

        __snake_case           =						mask.reshape((self.rand_size, self.rand_size)      )
        __snake_case           =						mask.repeat(self.scale       ,   axis=0      ).repeat(self.scale       ,   axis=1      )

        return torch.tensor(mask.flatten()      )





def   _a		(lowercase__			:   Optional[Any]						)			->			List[Any]:






     """simple docstring"""
     __snake_case           =						torch.stack([example['pixel_values'] for example in examples]						)
     __snake_case           =						torch.stack([example['mask'] for example in examples]						)
     return {"pixel_values": pixel_values, "bool_masked_pos": mask}





def   _a		()			->			Dict:






     """simple docstring"""
     # See all possible arguments in src/transformers/training_args.py
     # or by passing the --help flag to this script.
     # We now keep distinct sets of args, for a cleaner separation of concerns.

     __snake_case           =						HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
     if len(sys.argv						) == 2 and sys.argv[1].endswith('.json'						):
          # If we pass only one argument to the script and it's the path to a json file,
          # let's parse it to get our arguments.
          __snake_case      ,       __snake_case      ,       __snake_case           =						parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
     else:
          __snake_case      ,       __snake_case      ,       __snake_case           =						parser.parse_args_into_dataclasses()

     # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
     # information sent is the one passed as arguments along with your Python/PyTorch versions.
     send_example_telemetry('run_mim'							,   lowercase__							,   lowercase__						)

     # Setup logging
     logging.basicConfig(
         format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'							,   datefmt='%m/%d/%Y %H:%M:%S'							,   handlers=[logging.StreamHandler(sys.stdout						)]							,   )

     if training_args.should_log:
          # The default of training_args.log_level is passive, so we set log level at info here to have that default.
          transformers.utils.logging.set_verbosity_info()

     __snake_case           =						training_args.get_process_log_level()
     logger.setLevel(lowercase__						)
     transformers.utils.logging.set_verbosity(lowercase__						)
     transformers.utils.logging.enable_default_handler()
     transformers.utils.logging.enable_explicit_format()

     # Log on each process the small summary:
     logger.warning(
         f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
         + f'distributed training: {bool(training_args.local_rank != -1						)}, 16-bits training: {training_args.fpaa}'						)
     logger.info(f'Training/evaluation parameters {training_args}'						)

     # Detecting last checkpoint.
     __snake_case           =						None
     if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
          __snake_case           =						get_last_checkpoint(training_args.output_dir						)
          if last_checkpoint is None and len(os.listdir(training_args.output_dir						)						) > 0:
               raise ValueError(
                   f'Output directory ({training_args.output_dir}) already exists and is not empty. '
                   'Use --overwrite_output_dir to overcome.'						)
          elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
               logger.info(
                   f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
                   'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'						)

    # Initialize our dataset.
     __snake_case           =						load_dataset(
         data_args.dataset_name							,   data_args.dataset_config_name							,   data_files=data_args.data_files							,   cache_dir=model_args.cache_dir							,   use_auth_token=True if model_args.use_auth_token else None							,   )

     # If we don't have a validation split, split off a percentage of train as validation.
     __snake_case           =						None if 'validation' in ds.keys() else data_args.train_val_split
     if isinstance(data_args.train_val_split							,   lowercase__						) and data_args.train_val_split > 0.0:
          __snake_case           =						ds['train'].train_test_split(data_args.train_val_split						)
          __snake_case           =						split['train']
          __snake_case           =						split['test']

     # Create config
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.
     __snake_case           =						{
         'cache_dir': model_args.cache_dir,
         'revision': model_args.model_revision,
         'use_auth_token': True if model_args.use_auth_token else None,
     }
     if model_args.config_name_or_path:
          __snake_case           =						AutoConfig.from_pretrained(model_args.config_name_or_path							,   **lowercase__						)
     elif model_args.model_name_or_path:
          __snake_case           =						AutoConfig.from_pretrained(model_args.model_name_or_path							,   **lowercase__						)
     else:
          __snake_case           =						CONFIG_MAPPING[model_args.model_type]()
          logger.warning('You are instantiating a new config instance from scratch.'						)
          if model_args.config_overrides is not None:
               logger.info(f'Overriding config: {model_args.config_overrides}'						)
               config.update_from_string(model_args.config_overrides						)
               logger.info(f'New config: {config}'						)

    # make sure the decoder_type is "simmim" (only relevant for BEiT)
     if hasattr(lowercase__							,   'decoder_type'						):
          __snake_case           =						'simmim'

     # adapt config
     __snake_case           =						model_args.image_size if model_args.image_size is not None else config.image_size
     __snake_case           =						model_args.patch_size if model_args.patch_size is not None else config.patch_size
     __snake_case           =						(
         model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride
     )

     config.update(
         {
             'image_size': model_args.image_size,
             'patch_size': model_args.patch_size,
             'encoder_stride': model_args.encoder_stride,
         }						)

     # create image processor
     if model_args.image_processor_name:
          __snake_case           =						AutoImageProcessor.from_pretrained(model_args.image_processor_name							,   **lowercase__						)
     elif model_args.model_name_or_path:
          __snake_case           =						AutoImageProcessor.from_pretrained(model_args.model_name_or_path							,   **lowercase__						)
     else:
          __snake_case           =						{
              conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items()
          }
          __snake_case           =						IMAGE_PROCESSOR_TYPES[model_args.model_type]()

     # create model
     if model_args.model_name_or_path:
          __snake_case           =						AutoModelForMaskedImageModeling.from_pretrained(
              model_args.model_name_or_path							,   from_tf=bool('.ckpt' in model_args.model_name_or_path						)							,   config=lowercase__							,   cache_dir=model_args.cache_dir							,   revision=model_args.model_revision							,   use_auth_token=True if model_args.use_auth_token else None							,   )
     else:
          logger.info('Training new model from scratch'						)
          __snake_case           =						AutoModelForMaskedImageModeling.from_config(lowercase__						)

     if training_args.do_train:
          __snake_case           =						ds['train'].column_names
     else:
          __snake_case           =						ds['validation'].column_names

     if data_args.image_column_name is not None:
          __snake_case           =						data_args.image_column_name
     elif "image" in column_names:
          __snake_case           =						'image'
     elif "img" in column_names:
          __snake_case           =						'img'
     else:
          __snake_case           =						column_names[0]

     # transformations as done in original SimMIM paper
     # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py
     __snake_case           =						Compose(
         [
             Lambda(lambda lowercase__						: img.convert('RGB'						) if img.mode != "RGB" else img						),
             RandomResizedCrop(model_args.image_size							,   scale=(0.67, 1.0)							,   ratio=(3.0 / 4.0, 4.0 / 3.0)						),
             RandomHorizontalFlip(),
             ToTensor(),
             Normalize(mean=image_processor.image_mean							,   std=image_processor.image_std						),
         ]						)

     # create mask generator
     __snake_case           =						MaskGenerator(
         input_size=model_args.image_size							,   mask_patch_size=data_args.mask_patch_size							,   model_patch_size=model_args.patch_size							,   mask_ratio=data_args.mask_ratio							,   )

     def preprocess_images(lowercase__			:   Union[str, Any]						):
          __snake_case           =						[transforms(lowercase__						) for image in examples[image_column_name]]
          __snake_case           =						[mask_generator() for i in range(len(examples[image_column_name]						)						)]

          return examples

     if training_args.do_train:
          if "train" not in ds:
               raise ValueError('--do_train requires a train dataset'						)
          if data_args.max_train_samples is not None:
               __snake_case           =						ds['train'].shuffle(seed=training_args.seed						).select(range(data_args.max_train_samples						)						)
          # Set the training transforms
          ds["train"].set_transform(lowercase__						)

     if training_args.do_eval:
          if "validation" not in ds:
               raise ValueError('--do_eval requires a validation dataset'						)
          if data_args.max_eval_samples is not None:
               __snake_case           =						(
                   ds['validation'].shuffle(seed=training_args.seed						).select(range(data_args.max_eval_samples						)						)
               )
          # Set the validation transforms
          ds["validation"].set_transform(lowercase__						)

     # Initialize our trainer
     __snake_case           =						Trainer(
         model=lowercase__							,   args=lowercase__							,   train_dataset=ds['train'] if training_args.do_train else None							,   eval_dataset=ds['validation'] if training_args.do_eval else None							,   tokenizer=lowercase__							,   data_collator=lowercase__							,   )

     # Training
     if training_args.do_train:
          __snake_case           =						None
          if training_args.resume_from_checkpoint is not None:
               __snake_case           =						training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
               __snake_case           =						last_checkpoint
          __snake_case           =						trainer.train(resume_from_checkpoint=lowercase__						)
          trainer.save_model()
          trainer.log_metrics('train'							,   train_result.metrics						)
          trainer.save_metrics('train'							,   train_result.metrics						)
          trainer.save_state()

     # Evaluation
     if training_args.do_eval:
          __snake_case           =						trainer.evaluate()
          trainer.log_metrics('eval'							,   lowercase__						)
          trainer.save_metrics('eval'							,   lowercase__						)

     # Write model card and (optionally) push to hub
     __snake_case           =						{
         'finetuned_from': model_args.model_name_or_path,
         'tasks': 'masked-image-modeling',
         'dataset': data_args.dataset_name,
         'tags': ['masked-image-modeling'],
     }
     if training_args.push_to_hub:
          trainer.push_to_hub(**lowercase__						)
     else:
          trainer.create_model_card(**lowercase__						)


if __name__ == "__main__":
       main()










'''simple docstring'''


import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
UpperCAmelCase_					=   {"LayoutLMv2Config", "LayoutLMv3Config"}





@is_pipeline_test
class  __lowercase    (	unittest.TestCase			):
   _a    						=   MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
   _a    						=   TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

   if model_mapping is not None:
      _a    						=   {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
   if tf_model_mapping is not None:
      _a    						=   {
          config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
      }







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Optional[Any]:
     __a								=       ZeroShotClassificationPipeline(
         model=UpperCamelCase   ,				tokenizer=UpperCamelCase   ,				candidate_labels=['polics', 'health']   )
     return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   )					->     Tuple:
     __a								=       classifier('Who are you voting for in 2020?'   ,				candidate_labels='politics'   )
     self.assertEqual(UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   )]}   )

     # No kwarg
     __a								=       classifier('Who are you voting for in 2020?'   ,				['politics']   )
     self.assertEqual(UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   )]}   )

     __a								=       classifier('Who are you voting for in 2020?'   ,				candidate_labels=['politics']   )
     self.assertEqual(UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   )]}   )

     __a								=       classifier('Who are you voting for in 2020?'   ,				candidate_labels='politics, public health'   )
     self.assertEqual(
         UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )]}   )
     self.assertAlmostEqual(sum(nested_simplify(outputs['scores']   )   )   ,				1.0   )

     __a								=       classifier('Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health']   )
     self.assertEqual(
         UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )]}   )
     self.assertAlmostEqual(sum(nested_simplify(outputs['scores']   )   )   ,				1.0   )

     __a								=       classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels='politics'   ,				hypothesis_template='This text is about {}'   )
     self.assertEqual(UpperCamelCase   ,				{'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   )]}   )

     # https://github.com/huggingface/transformers/issues/13846
     __a								=       classifier(['I am happy']   ,				['positive', 'negative']   )
     self.assertEqual(
         UpperCamelCase   ,				[
             {'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )]}
             for i in range(1   )
         ]   ,				)
     __a								=       classifier(['I am happy', 'I am sad']   ,				['positive', 'negative']   )
     self.assertEqual(
         UpperCamelCase   ,				[
             {'sequence': ANY(UpperCamelCase   ), 'labels': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )], 'scores': [ANY(UpperCamelCase   ), ANY(UpperCamelCase   )]}
             for i in range(2   )
         ]   ,				)

     with self.assertRaises(UpperCamelCase   ):
       classifier(''   ,				candidate_labels='politics'   )

     with self.assertRaises(UpperCamelCase   ):
       classifier(UpperCamelCase   ,				candidate_labels='politics'   )

     with self.assertRaises(UpperCamelCase   ):
       classifier('Who are you voting for in 2020?'   ,				candidate_labels=''   )

     with self.assertRaises(UpperCamelCase   ):
       classifier('Who are you voting for in 2020?'   ,				candidate_labels=UpperCamelCase   )

     with self.assertRaises(UpperCamelCase   ):
       classifier(
           'Who are you voting for in 2020?'   ,				candidate_labels='politics'   ,				hypothesis_template='Not formatting template'   ,				)

     with self.assertRaises(UpperCamelCase   ):
       classifier(
           'Who are you voting for in 2020?'   ,				candidate_labels='politics'   ,				hypothesis_template=UpperCamelCase   ,				)

     self.run_entailment_id(UpperCamelCase   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Optional[int]:
     __a								=       zero_shot_classifier.model.config
     __a								=       config.labelaid
     __a								=       zero_shot_classifier.entailment_id

     __a								=       {'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2}
     self.assertEqual(zero_shot_classifier.entailment_id   ,				-1   )

     __a								=       {'entailment': 0, 'neutral': 1, 'contradiction': 2}
     self.assertEqual(zero_shot_classifier.entailment_id   ,				0   )

     __a								=       {'ENTAIL': 0, 'NON-ENTAIL': 1}
     self.assertEqual(zero_shot_classifier.entailment_id   ,				0   )

     __a								=       {'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0}
     self.assertEqual(zero_shot_classifier.entailment_id   ,				2   )

     __a								=       original_labelaid
     self.assertEqual(UpperCamelCase   ,				zero_shot_classifier.entailment_id   )







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     Tuple:
     __a								=       pipeline(
         'zero-shot-classification'   ,				model='sshleifer/tiny-distilbert-base-cased-distilled-squad'   ,				framework='pt'   ,				)
     # There was a regression in 4.10 for this
     # Adding a test so we don't make the mistake again.
     # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
     zero_shot_classifier(
         'Who are you voting for in 2020?' * 100   ,				candidate_labels=['politics', 'public health', 'science']   )







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     List[str]:
     __a								=       pipeline(
         'zero-shot-classification'   ,				model='sshleifer/tiny-distilbert-base-cased-distilled-squad'   ,				framework='pt'   ,				)
     __a								=       zero_shot_classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health', 'science']   )

     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': 'Who are you voting for in 2020?',
             'labels': ['science', 'public health', 'politics'],
             'scores': [0.333, 0.333, 0.333],
         }   ,				)







   @require_tf
   def 		UpperCamelCase__      (						self   )					->     Dict:
     __a								=       pipeline(
         'zero-shot-classification'   ,				model='sshleifer/tiny-distilbert-base-cased-distilled-squad'   ,				framework='tf'   ,				)
     __a								=       zero_shot_classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health', 'science']   )

     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': 'Who are you voting for in 2020?',
             'labels': ['science', 'public health', 'politics'],
             'scores': [0.333, 0.333, 0.333],
         }   ,				)







   @slow
   @require_torch
   def 		UpperCamelCase__      (						self   )					->     List[str]:
     __a								=       pipeline('zero-shot-classification'   ,				model='roberta-large-mnli'   ,				framework='pt'   )
     __a								=       zero_shot_classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health', 'science']   )

     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': 'Who are you voting for in 2020?',
             'labels': ['politics', 'public health', 'science'],
             'scores': [0.976, 0.015, 0.009],
         }   ,				)
     __a								=       zero_shot_classifier(
         'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'
         ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'
         ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'
         ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'
         ' machine translation tasks show these models to be superior in quality while being more parallelizable'
         ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'
         ' English-to-German translation task, improving over the existing best results, including ensembles by'
         ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'
         ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'
         ' fraction of the training costs of the best models from the literature. We show that the Transformer'
         ' generalizes well to other tasks by applying it successfully to English constituency parsing both with'
         ' large and limited training data.'   ,				candidate_labels=['machine learning', 'statistics', 'translation', 'vision']   ,				multi_label=UpperCamelCase   ,				)
     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': (
                 'The dominant sequence transduction models are based on complex recurrent or convolutional neural'
                 ' networks in an encoder-decoder configuration. The best performing models also connect the'
                 ' encoder and decoder through an attention mechanism. We propose a new simple network'
                 ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'
                 ' and convolutions entirely. Experiments on two machine translation tasks show these models to be'
                 ' superior in quality while being more parallelizable and requiring significantly less time to'
                 ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'
                 ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'
                 ' English-to-French translation task, our model establishes a new single-model state-of-the-art'
                 ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'
                 ' costs of the best models from the literature. We show that the Transformer generalizes well to'
                 ' other tasks by applying it successfully to English constituency parsing both with large and'
                 ' limited training data.'
             ),
             'labels': ['translation', 'machine learning', 'vision', 'statistics'],
             'scores': [0.817, 0.713, 0.018, 0.018],
         }   ,				)







   @slow
   @require_tf
   def 		UpperCamelCase__      (						self   )					->     Union[str, Any]:
     __a								=       pipeline('zero-shot-classification'   ,				model='roberta-large-mnli'   ,				framework='tf'   )
     __a								=       zero_shot_classifier(
         'Who are you voting for in 2020?'   ,				candidate_labels=['politics', 'public health', 'science']   )

     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': 'Who are you voting for in 2020?',
             'labels': ['politics', 'public health', 'science'],
             'scores': [0.976, 0.015, 0.009],
         }   ,				)
     __a								=       zero_shot_classifier(
         'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'
         ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'
         ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'
         ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'
         ' machine translation tasks show these models to be superior in quality while being more parallelizable'
         ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'
         ' English-to-German translation task, improving over the existing best results, including ensembles by'
         ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'
         ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'
         ' fraction of the training costs of the best models from the literature. We show that the Transformer'
         ' generalizes well to other tasks by applying it successfully to English constituency parsing both with'
         ' large and limited training data.'   ,				candidate_labels=['machine learning', 'statistics', 'translation', 'vision']   ,				multi_label=UpperCamelCase   ,				)
     self.assertEqual(
         nested_simplify(UpperCamelCase   )   ,				{
             'sequence': (
                 'The dominant sequence transduction models are based on complex recurrent or convolutional neural'
                 ' networks in an encoder-decoder configuration. The best performing models also connect the'
                 ' encoder and decoder through an attention mechanism. We propose a new simple network'
                 ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'
                 ' and convolutions entirely. Experiments on two machine translation tasks show these models to be'
                 ' superior in quality while being more parallelizable and requiring significantly less time to'
                 ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'
                 ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'
                 ' English-to-French translation task, our model establishes a new single-model state-of-the-art'
                 ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'
                 ' costs of the best models from the literature. We show that the Transformer generalizes well to'
                 ' other tasks by applying it successfully to English constituency parsing both with large and'
                 ' limited training data.'
             ),
             'labels': ['translation', 'machine learning', 'vision', 'statistics'],
             'scores': [0.817, 0.713, 0.018, 0.018],
         }   ,				)



