




'''simple docstring'''







from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
      import tensorflow as tf

      from ..tf_utils import stable_softmax


if is_torch_available():
      import torch


lowercase      :   int      =       logging.get_logger(__name__)







@add_end_docstrings(
    UpperCamelCase__,		r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """,		)
class 					_a (UpperCamelCase__	):





     '''simple docstring'''



     def 			snake_case_      (				self							,__a							)      ->				np.ndarray:
          if self.framework == "tf":
               snake_case			:      List[str]        =			tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()
          elif self.framework == "pt":
               snake_case			:      Any        =			torch.nonzero(input_ids == self.tokenizer.mask_token_id							,as_tuple=lowercase_							)
          else:
               raise ValueError("""Unsupported framework"""							)
          return masked_index







     def 			snake_case_      (				self							,__a							)      ->				np.ndarray:
          snake_case			:      List[Any]        =			self.get_masked_index(lowercase_							)
          snake_case			:      Optional[Any]        =			np.prod(masked_index.shape							)
          if numel < 1:
               raise PipelineException(
                   """fill-mask"""							,self.model.base_model_prefix							,F'''No mask_token ({self.tokenizer.mask_token}) found on the input'''							,)







     def 			snake_case_      (				self							,__a							)      ->				Any:
          if isinstance(lowercase_							,lowercase_							):
               for model_input in model_inputs:
                    self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0]							)
          else:
               for input_ids in model_inputs["input_ids"]:
                    self._ensure_exactly_one_mask_token(lowercase_							)







     def 			snake_case_      (				self							,__a							,__a=None							,**__a							)      ->				Dict[str, GenericTensor]:
          if return_tensors is None:
               snake_case			:      Dict        =			self.framework
          snake_case			:      int        =			self.tokenizer(lowercase_							,return_tensors=lowercase_							)
          self.ensure_exactly_one_mask_token(lowercase_							)
          return model_inputs







     def 			snake_case_      (				self							,__a							)      ->				Any:
          snake_case			:      Tuple        =			self.model(**lowercase_							)
          snake_case			:      List[str]        =			model_inputs["""input_ids"""]
          return model_outputs







     def 			snake_case_      (				self							,__a							,__a=5							,__a=None							)      ->				int:
          # Cap top_k if there are targets
          if target_ids is not None and target_ids.shape[0] < top_k:
               snake_case			:      Optional[Any]        =			target_ids.shape[0]
          snake_case			:      int        =			model_outputs["""input_ids"""][0]
          snake_case			:      Union[str, Any]        =			model_outputs["""logits"""]

          if self.framework == "tf":
               snake_case			:      Optional[Any]        =			tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()[:, 0]

               snake_case			:      Optional[int]        =			outputs.numpy()

               snake_case			:      Union[str, Any]        =			outputs[0, masked_index, :]
               snake_case			:      Any        =			stable_softmax(lowercase_							,axis=-1							)
               if target_ids is not None:
                    snake_case			:      Optional[int]        =			tf.gather_nd(tf.squeeze(lowercase_							,0							)							,target_ids.reshape(-1							,1							)							)
                    snake_case			:      Optional[Any]        =			tf.expand_dims(lowercase_							,0							)

               snake_case			:      str        =			tf.math.top_k(lowercase_							,k=lowercase_							)
               snake_case ,		snake_case			:      List[Any]        =			topk.values.numpy(), topk.indices.numpy()
          else:
               snake_case			:      List[str]        =			torch.nonzero(input_ids == self.tokenizer.mask_token_id							,as_tuple=lowercase_							).squeeze(-1							)
               # Fill mask pipeline supports only one ${mask_token} per sample

               snake_case			:      Any        =			outputs[0, masked_index, :]
               snake_case			:      Tuple        =			logits.softmax(dim=-1							)
               if target_ids is not None:
                    snake_case			:      str        =			probs[..., target_ids]

               snake_case ,		snake_case			:      Union[str, Any]        =			probs.topk(lowercase_							)

          snake_case			:      Optional[Any]        =			[]
          snake_case			:      Tuple        =			values.shape[0] == 1
          for i, (_values, _predictions) in enumerate(zip(values.tolist()							,predictions.tolist()							)							):
               snake_case			:      Union[str, Any]        =			[]
               for v, p in zip(_values							,_predictions							):
                    # Copy is important since we're going to modify this array in place
                    snake_case			:      List[str]        =			input_ids.numpy().copy()
                    if target_ids is not None:
                         snake_case			:      Optional[int]        =			target_ids[p].tolist()

                    snake_case			:      Any        =			p
                    # Filter padding out:
                    snake_case			:      Optional[int]        =			tokens[np.where(tokens != self.tokenizer.pad_token_id							)]
                    # Originally we skip special tokens to give readable output.
                    # For multi masks though, the other [MASK] would be removed otherwise
                    # making the output look odd, so we add them back
                    snake_case			:      str        =			self.tokenizer.decode(lowercase_							,skip_special_tokens=lowercase_							)
                    snake_case			:      Union[str, Any]        =			{"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]							), """sequence""": sequence}
                    row.append(lowercase_							)
               result.append(lowercase_							)
          if single_mask:
               return result[0]
          return result







     def 			snake_case_      (				self							,__a							,__a=None							)      ->				Optional[Any]:
          if isinstance(lowercase_							,lowercase_							):
               snake_case			:      Dict        =			[targets]
          try:
               snake_case			:      int        =			self.tokenizer.get_vocab()
          except Exception:
               snake_case			:      Optional[int]        =			{}
          snake_case			:      Union[str, Any]        =			[]
          for target in targets:
               snake_case			:      str        =			vocab.get(lowercase_							,lowercase_							)
               if id_ is None:
                    snake_case			:      Optional[Any]        =			self.tokenizer(
                        lowercase_							,add_special_tokens=lowercase_							,return_attention_mask=lowercase_							,return_token_type_ids=lowercase_							,max_length=1							,truncation=lowercase_							,)["""input_ids"""]
                    if len(lowercase_							) == 0:
                         logger.warning(
                             F'''The specified target token `{target}` does not exist in the model vocabulary. '''
                             """We cannot replace it with anything meaningful, ignoring it"""							)
                         continue
                    snake_case			:      Union[str, Any]        =			input_ids[0]
                    # XXX: If users encounter this pass
                    # it becomes pretty slow, so let's make sure
                    # The warning enables them to fix the input to
                    # get faster performance.
                    logger.warning(
                        F'''The specified target token `{target}` does not exist in the model vocabulary. '''
                        F'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_							)}`.'''							)
               target_ids.append(id_							)
          snake_case			:      str        =			list(set(lowercase_							)							)
          if len(lowercase_							) == 0:
               raise ValueError("""At least one target must be provided when passed."""							)
          snake_case			:      List[Any]        =			np.array(lowercase_							)
          return target_ids







     def 			snake_case_      (				self							,__a=None							,__a=None							)      ->				List[Any]:
          snake_case			:      List[Any]        =			{}

          if targets is not None:
               snake_case			:      Optional[int]        =			self.get_target_ids(lowercase_							,lowercase_							)
               snake_case			:      Tuple        =			target_ids

          if top_k is not None:
               snake_case			:      Any        =			top_k

          if self.tokenizer.mask_token_id is None:
               raise PipelineException(
                   """fill-mask"""							,self.model.base_model_prefix							,"""The tokenizer does not define a `mask_token`."""							)
          return {}, {}, postprocess_params







     def __call__(				self							,__a							,*__a							,**__a							)      ->				Union[str, Any]:
          snake_case			:      Optional[int]        =			super().__call__(lowercase_							,**lowercase_							)
          if isinstance(lowercase_							,lowercase_							) and len(lowercase_							) == 1:
               return outputs[0]
          return outputs










'''simple docstring'''

import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
import unittest
from unittest import mock

import torch
from accelerate.utils import write_basic_config

from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device
from transformers.utils import is_apex_available


logging.basicConfig(level=logging.DEBUG)

__lowerCAmelCase				:      Dict						      =logging.getLogger()





def 		UpperCamelCase							(				):
    A__							=     argparse.ArgumentParser()
    parser.add_argument("-f"			)
    A__							=     parser.parse_args()
    return args.f





def 		UpperCamelCase							(				_lowerCamelCase   :   List[str]			):
    A__							=     {}
    A__							=     os.path.join(_lowerCamelCase		,			"all_results.json"			)
    if os.path.exists(_lowerCamelCase			):
        with open(_lowerCamelCase		,			"r"			) as f:
            A__							=     json.load(_lowerCamelCase			)
    else:
        raise ValueError(F"can't find {path}"			)
    return results





def 		UpperCamelCase							(				):
    A__							=     torch.cuda.is_available() and torch_device == "cuda"
    return is_using_cuda and is_apex_available()


__lowerCAmelCase				:      Union[str, Any]						      =logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)






class   UpperCAmelCase      (			UpperCamelCase__							):
 @classmethod
 def 	UpperCAmelCase_				(							cls :List[Any]				)->				Union[str, Any]:
     # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU
     A__							=     tempfile.mkdtemp()
     A__							=     os.path.join(cls.tmpdir		,			"default_config.yml"				)
     write_basic_config(save_location=cls.configPath				)
     A__							=     ["accelerate", "launch", "--config_file", cls.configPath]
 @classmethod
 def 	UpperCAmelCase_				(							cls :Tuple				)->				List[Any]:
     shutil.rmtree(cls.tmpdir				)
 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :Union[str, Any]				)->				Any:
     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py\n            --model_name_or_path distilbert-base-uncased\n            --output_dir {tmp_dir}\n            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --learning_rate=1e-4\n            --seed=42\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

     if is_cuda_and_apex_available():
         testargs.append("--fp16"				)

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     self.assertGreaterEqual(result["eval_accuracy"]		,			0.7_5				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"epoch_0"				)				)				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"glue_no_trainer"				)				)				)
 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :List[Any]				)->				Tuple:
     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py\n            --model_name_or_path distilgpt2\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --block_size 128\n            --per_device_train_batch_size 5\n            --per_device_eval_batch_size 5\n            --num_train_epochs 2\n            --output_dir {tmp_dir}\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

     if torch.cuda.device_count() > 1:
         # Skipping because there are not enough batches to train the model + would need a drop_last to work.
         return

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     self.assertLess(result["perplexity"]		,			1_00				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"epoch_0"				)				)				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"clm_no_trainer"				)				)				)
 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :Any				)->				str:
     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py\n            --model_name_or_path distilroberta-base\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --output_dir {tmp_dir}\n            --num_train_epochs=1\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     self.assertLess(result["perplexity"]		,			42				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"epoch_0"				)				)				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"mlm_no_trainer"				)				)				)
 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :Optional[Any]				)->				List[str]:
     # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
     A__							=     7 if get_gpu_count() > 1 else 2

     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/conll/sample.json\n            --validation_file tests/fixtures/tests_samples/conll/sample.json\n            --output_dir {tmp_dir}\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=2\n            --num_train_epochs={epochs}\n            --seed 7\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     self.assertGreaterEqual(result["eval_accuracy"]		,			0.7_5				)
     self.assertLess(result["train_loss"]		,			0.5				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"epoch_0"				)				)				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"ner_no_trainer"				)				)				)
 @unittest.skip(reason="Fix me @muellerzr"				)
 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :Any				)->				Optional[int]:
     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py\n            --model_name_or_path bert-base-uncased\n            --version_2_with_negative\n            --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --output_dir {tmp_dir}\n            --seed=42\n            --max_train_steps=10\n            --num_warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics.
     self.assertGreaterEqual(result["eval_f1"]		,			28				)
     self.assertGreaterEqual(result["eval_exact"]		,			28				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"epoch_0"				)				)				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"qa_no_trainer"				)				)				)
 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :Optional[int]				)->				List[str]:
     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/swag/sample.json\n            --validation_file tests/fixtures/tests_samples/swag/sample.json\n            --output_dir {tmp_dir}\n            --max_train_steps=20\n            --num_warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --with_tracking\n        ".split()

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     self.assertGreaterEqual(result["eval_accuracy"]		,			0.8				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"swag_no_trainer"				)				)				)
 @slow
 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :Tuple				)->				Any:
     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py\n            --model_name_or_path t5-small\n            --train_file tests/fixtures/tests_samples/xsum/sample.json\n            --validation_file tests/fixtures/tests_samples/xsum/sample.json\n            --output_dir {tmp_dir}\n            --max_train_steps=50\n            --num_warmup_steps=8\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     self.assertGreaterEqual(result["eval_rouge1"]		,			10				)
     self.assertGreaterEqual(result["eval_rouge2"]		,			2				)
     self.assertGreaterEqual(result["eval_rougeL"]		,			7				)
     self.assertGreaterEqual(result["eval_rougeLsum"]		,			7				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"epoch_0"				)				)				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"summarization_no_trainer"				)				)				)
 @slow
 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :Union[str, Any]				)->				Optional[int]:
     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py\n            --model_name_or_path sshleifer/student_marian_en_ro_6_1\n            --source_lang en\n            --target_lang ro\n            --train_file tests/fixtures/tests_samples/wmt16/sample.json\n            --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n            --output_dir {tmp_dir}\n            --max_train_steps=50\n            --num_warmup_steps=8\n            --num_beams=6\n            --learning_rate=3e-3\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --source_lang en_XX\n            --target_lang ro_RO\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     self.assertGreaterEqual(result["eval_bleu"]		,			30				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"epoch_0"				)				)				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"translation_no_trainer"				)				)				)
 @slow
 def 	UpperCAmelCase_				(							self :Optional[int]				)->				List[Any]:
     A__							=     logging.StreamHandler(sys.stdout				)
     logger.addHandler(lowercase_				)

     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py\n            --dataset_name huggingface/semantic-segmentation-test-sample\n            --output_dir {tmp_dir}\n            --max_train_steps=10\n            --num_warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --checkpointing_steps epoch\n        ".split()

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     self.assertGreaterEqual(result["eval_overall_accuracy"]		,			0.1_0				)



 @mock.patch.dict(os.environ		,			{"WANDB_MODE": "offline"}				)
 def 	UpperCAmelCase_				(							self :str				)->				Dict:
     A__							=     self.get_auto_remove_tmp_dir()
     A__							=     F"\n            {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py\n            --model_name_or_path google/vit-base-patch16-224-in21k\n            --dataset_name hf-internal-testing/cats_vs_dogs_sample\n            --learning_rate 1e-4\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --max_train_steps 2\n            --train_val_split 0.1\n            --seed 42\n            --output_dir {tmp_dir}\n            --with_tracking\n            --checkpointing_steps 1\n        ".split()

     if is_cuda_and_apex_available():
         testargs.append("--fp16"				)

     run_command(self._launch_args + testargs				)
     A__							=     get_results(lowercase_				)
     # The base model scores a 25%
     self.assertGreaterEqual(result["eval_accuracy"]		,			0.6				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"step_1"				)				)				)
     self.assertTrue(os.path.exists(os.path.join(lowercase_		,			"image_classification_no_trainer"				)				)				)



