





import unittest

from transformers import (
    MODEL_FOR_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
    TextGenerationPipeline,
    logging,
    pipeline,
)
from transformers.testing_utils import (
    CaptureLogger,
    is_pipeline_test,
    require_accelerate,
    require_tf,
    require_torch,
    require_torch_gpu,
    require_torch_or_tf,
)

from .test_pipelines_common import ANY







@is_pipeline_test
@require_torch_or_tf
class 			__A       (      unittest.TestCase  ):




      """simple docstring"""







      UpperCAmelCase__						=      MODEL_FOR_CAUSAL_LM_MAPPING
      UpperCAmelCase__						=      TF_MODEL_FOR_CAUSAL_LM_MAPPING


      @require_torch
      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Optional[int]	=		pipeline(task='''text-generation'''      ,							model='''sshleifer/tiny-ctrl'''      ,							framework='''pt''')
             # Using `do_sample=False` to force deterministic output
             _lowerCamelCase							:     Tuple	=		text_generator('''This is a test'''      ,							do_sample=a__)
             self.assertEqual(
                 a__      ,							[
                     {
                         '''generated_text''': (
                             '''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.'''
                             ''' oscope. FiliFili@@'''
                         )
                     }
                 ]      ,							)

             _lowerCamelCase							:     Optional[int]	=		text_generator(['''This is a test''', '''This is a second test'''])
             self.assertEqual(
                 a__      ,							[
                     [
                         {
                             '''generated_text''': (
                                 '''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.'''
                                 ''' oscope. FiliFili@@'''
                             )
                         }
                     ],
                     [
                         {
                             '''generated_text''': (
                                 '''This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy'''
                                 ''' oscope. oscope. FiliFili@@'''
                             )
                         }
                     ],
                 ]      ,							)

             _lowerCamelCase							:     Optional[Any]	=		text_generator('''This is a test'''      ,							do_sample=a__      ,							num_return_sequences=2      ,							return_tensors=a__)
             self.assertEqual(
                 a__      ,							[
                     {'''generated_token_ids''': ANY(a__)},
                     {'''generated_token_ids''': ANY(a__)},
                 ]      ,							)
             _lowerCamelCase							:     int	=		text_generator.model.config.eos_token_id
             _lowerCamelCase							:     List[str]	=		'''<pad>'''
             _lowerCamelCase							:     str	=		text_generator(
                 ['''This is a test''', '''This is a second test''']      ,							do_sample=a__      ,							num_return_sequences=2      ,							batch_size=2      ,							return_tensors=a__      ,							)
             self.assertEqual(
                 a__      ,							[
                     [
                         {'''generated_token_ids''': ANY(a__)},
                         {'''generated_token_ids''': ANY(a__)},
                     ],
                     [
                         {'''generated_token_ids''': ANY(a__)},
                         {'''generated_token_ids''': ANY(a__)},
                     ],
                 ]      ,							)


      @require_tf
      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Optional[Any]	=		pipeline(task='''text-generation'''      ,							model='''sshleifer/tiny-ctrl'''      ,							framework='''tf''')

             # Using `do_sample=False` to force deterministic output
             _lowerCamelCase							:     Optional[Any]	=		text_generator('''This is a test'''      ,							do_sample=a__)
             self.assertEqual(
                 a__      ,							[
                     {
                         '''generated_text''': (
                             '''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵'''
                             ''' please,'''
                         )
                     }
                 ]      ,							)

             _lowerCamelCase							:     Optional[Any]	=		text_generator(['''This is a test''', '''This is a second test''']      ,							do_sample=a__)
             self.assertEqual(
                 a__      ,							[
                     [
                         {
                             '''generated_text''': (
                                 '''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵'''
                                 ''' please,'''
                             )
                         }
                     ],
                     [
                         {
                             '''generated_text''': (
                                 '''This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes'''
                                 ''' Cannes 閲閲Cannes Cannes Cannes 攵 please,'''
                             )
                         }
                     ],
                 ]      ,							)


      def 				__snake_case			(		self      ,							a__      ,							a__      ,							a__):



             """simple docstring"""





             _lowerCamelCase							:     List[Any]	=		TextGenerationPipeline(model=a__      ,							tokenizer=a__)
             return text_generator, ["This is a test", "Another test"]


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     List[Any]	=		'''Hello I believe in'''
             _lowerCamelCase							:     Tuple	=		pipeline('''text-generation'''      ,							model='''hf-internal-testing/tiny-random-gpt2''')
             _lowerCamelCase							:     Optional[int]	=		text_generator(a__)
             self.assertEqual(
                 a__      ,							[{'''generated_text''': '''Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'''}]      ,							)

             _lowerCamelCase							:     int	=		text_generator(a__      ,							stop_sequence=''' fe''')
             self.assertEqual(a__      ,							[{'''generated_text''': '''Hello I believe in fe'''}])


      def 				__snake_case			(		self      ,							a__      ,							a__):



             """simple docstring"""





             _lowerCamelCase							:     Optional[Any]	=		text_generator.model
             _lowerCamelCase							:     Optional[int]	=		text_generator.tokenizer

             _lowerCamelCase							:     Tuple	=		text_generator('''This is a test''')
             self.assertEqual(a__      ,							[{'''generated_text''': ANY(a__)}])
             self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test'''))

             _lowerCamelCase							:     List[Any]	=		text_generator('''This is a test'''      ,							return_full_text=a__)
             self.assertEqual(a__      ,							[{'''generated_text''': ANY(a__)}])
             self.assertNotIn('''This is a test'''      ,							outputs[0]['''generated_text'''])

             _lowerCamelCase							:     List[Any]	=		pipeline(task='''text-generation'''      ,							model=a__      ,							tokenizer=a__      ,							return_full_text=a__)
             _lowerCamelCase							:     str	=		text_generator('''This is a test''')
             self.assertEqual(a__      ,							[{'''generated_text''': ANY(a__)}])
             self.assertNotIn('''This is a test'''      ,							outputs[0]['''generated_text'''])

             _lowerCamelCase							:     Optional[int]	=		text_generator('''This is a test'''      ,							return_full_text=a__)
             self.assertEqual(a__      ,							[{'''generated_text''': ANY(a__)}])
             self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test'''))

             _lowerCamelCase							:     List[str]	=		text_generator(['''This is great !''', '''Something else''']      ,							num_return_sequences=2      ,							do_sample=a__)
             self.assertEqual(
                 a__      ,							[
                     [{'''generated_text''': ANY(a__)}, {'''generated_text''': ANY(a__)}],
                     [{'''generated_text''': ANY(a__)}, {'''generated_text''': ANY(a__)}],
                 ]      ,							)

             if text_generator.tokenizer.pad_token is not None:
                    _lowerCamelCase							:     Optional[Any]	=		text_generator(
                        ['''This is great !''', '''Something else''']      ,							num_return_sequences=2      ,							batch_size=2      ,							do_sample=a__)
                    self.assertEqual(
                        a__      ,							[
                            [{'''generated_text''': ANY(a__)}, {'''generated_text''': ANY(a__)}],
                            [{'''generated_text''': ANY(a__)}, {'''generated_text''': ANY(a__)}],
                        ]      ,							)

             with self.assertRaises(a__):
                    _lowerCamelCase							:     int	=		text_generator('''test'''      ,							return_full_text=a__      ,							return_text=a__)
             with self.assertRaises(a__):
                    _lowerCamelCase							:     Optional[int]	=		text_generator('''test'''      ,							return_full_text=a__      ,							return_tensors=a__)
             with self.assertRaises(a__):
                    _lowerCamelCase							:     str	=		text_generator('''test'''      ,							return_text=a__      ,							return_tensors=a__)

             # Empty prompt is slighly special
             # it requires BOS token to exist.
             # Special case for Pegasus which will always append EOS so will
             # work even without BOS.
             if (
                 text_generator.tokenizer.bos_token_id is not None
                 or "Pegasus" in tokenizer.__class__.__name__
                 or "Git" in model.__class__.__name__
             ):
                    _lowerCamelCase							:     str	=		text_generator('''''')
                    self.assertEqual(a__      ,							[{'''generated_text''': ANY(a__)}])
             else:
                    with self.assertRaises((ValueError, AssertionError)):
                           _lowerCamelCase							:     Optional[int]	=		text_generator('''''')

             if text_generator.framework == "tf":
                    # TF generation does not support max_new_tokens, and it's impossible
                    # to control long generation with only max_length without
                    # fancy calculation, dismissing tests for now.
                    return
             # We don't care about infinite range models.
             # They already work.
             # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly.
             _lowerCamelCase							:     str	=		['''RwkvForCausalLM''', '''XGLMForCausalLM''', '''GPTNeoXForCausalLM''']
             if (
                 tokenizer.model_max_length < 1_0000
                 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS
             ):
                    # Handling of large generations
                    with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError)):
                           text_generator('''This is a test''' * 500      ,							max_new_tokens=20)

                    _lowerCamelCase							:     Optional[int]	=		text_generator('''This is a test''' * 500      ,							handle_long_generation='''hole'''      ,							max_new_tokens=20)
                    # Hole strategy cannot work
                    with self.assertRaises(a__):
                           text_generator(
                               '''This is a test''' * 500      ,							handle_long_generation='''hole'''      ,							max_new_tokens=tokenizer.model_max_length + 10      ,							)


      @require_torch
      @require_accelerate
      @require_torch_gpu
      def 				__snake_case			(		self):



             """simple docstring"""





             import torch

             # Classic `model_kwargs`
             _lowerCamelCase							:     List[Any]	=		pipeline(
                 model='''hf-internal-testing/tiny-random-bloom'''      ,							model_kwargs={'''device_map''': '''auto''', '''torch_dtype''': torch.bfloataa}      ,							)
             self.assertEqual(pipe.model.device      ,							torch.device(0))
             self.assertEqual(pipe.model.lm_head.weight.dtype      ,							torch.bfloataa)
             _lowerCamelCase							:     int	=		pipe('''This is a test''')
             self.assertEqual(
                 a__      ,							[
                     {
                         '''generated_text''': (
                             '''This is a test test test test test test test test test test test test test test test test'''
                             ''' test'''
                         )
                     }
                 ]      ,							)

             # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.)
             _lowerCamelCase							:     List[Any]	=		pipeline(model='''hf-internal-testing/tiny-random-bloom'''      ,							device_map='''auto'''      ,							torch_dtype=torch.bfloataa)
             self.assertEqual(pipe.model.device      ,							torch.device(0))
             self.assertEqual(pipe.model.lm_head.weight.dtype      ,							torch.bfloataa)
             _lowerCamelCase							:     Optional[Any]	=		pipe('''This is a test''')
             self.assertEqual(
                 a__      ,							[
                     {
                         '''generated_text''': (
                             '''This is a test test test test test test test test test test test test test test test test'''
                             ''' test'''
                         )
                     }
                 ]      ,							)

             # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602
             _lowerCamelCase							:     List[Any]	=		pipeline(model='''hf-internal-testing/tiny-random-bloom'''      ,							device_map='''auto''')
             self.assertEqual(pipe.model.device      ,							torch.device(0))
             self.assertEqual(pipe.model.lm_head.weight.dtype      ,							torch.floataa)
             _lowerCamelCase							:     List[str]	=		pipe('''This is a test''')
             self.assertEqual(
                 a__      ,							[
                     {
                         '''generated_text''': (
                             '''This is a test test test test test test test test test test test test test test test test'''
                             ''' test'''
                         )
                     }
                 ]      ,							)


      @require_torch
      @require_torch_gpu
      def 				__snake_case			(		self):



             """simple docstring"""





             import torch

             _lowerCamelCase							:     Union[str, Any]	=		pipeline(model='''hf-internal-testing/tiny-random-bloom'''      ,							device=0      ,							torch_dtype=torch.floataa)
             pipe('''This is a test''')


      @require_torch
      @require_accelerate
      @require_torch_gpu
      def 				__snake_case			(		self):



             """simple docstring"""





             import torch

             _lowerCamelCase							:     str	=		pipeline(model='''hf-internal-testing/tiny-random-bloom'''      ,							device_map='''auto'''      ,							torch_dtype=torch.floataa)
             pipe('''This is a test'''      ,							do_sample=a__      ,							top_p=0.5)



      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Optional[int]	=		'''Hello world'''
             _lowerCamelCase							:     Tuple	=		pipeline('''text-generation'''      ,							model='''hf-internal-testing/tiny-random-gpt2''')
             if text_generator.model.framework == "tf":
                    _lowerCamelCase							:     Dict	=		logging.get_logger('''transformers.generation.tf_utils''')
             else:
                    _lowerCamelCase							:     List[Any]	=		logging.get_logger('''transformers.generation.utils''')
             _lowerCamelCase							:     Union[str, Any]	=		'''Both `max_new_tokens`'''  # The beggining of the message to be checked in this test

             # Both are set by the user -> log warning
             with CaptureLogger(a__) as cl:
                    _lowerCamelCase							:     str	=		text_generator(a__      ,							max_length=10      ,							max_new_tokens=1)
             self.assertIn(a__      ,							cl.out)

             # The user only sets one -> no warning
             with CaptureLogger(a__) as cl:
                    _lowerCamelCase							:     Tuple	=		text_generator(a__      ,							max_new_tokens=1)
             self.assertNotIn(a__      ,							cl.out)

             with CaptureLogger(a__) as cl:
                    _lowerCamelCase							:     Dict	=		text_generator(a__      ,							max_length=10)
             self.assertNotIn(a__      ,							cl.out)








import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


_lowerCamelCase			       =      logging.get_logger(__name__)







@dataclass
class 			__A       :




      """simple docstring"""







      UpperCAmelCase__						=      field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()  )}  )
      UpperCAmelCase__						=      field(
          metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}  )
      UpperCAmelCase__						=      field(
          default=128 ,metadata={
              """help""": (
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )
          } ,)
      UpperCAmelCase__						=      field(
          default=lowerCamelCase__ ,metadata={"""help""": """Overwrite the cached training and evaluation sets"""}  )


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Dict	=		self.task_name.lower()







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      UpperCAmelCase__						=      """train"""
      UpperCAmelCase__						=      """dev"""
      UpperCAmelCase__						=      """test"""







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42


      def __init__(		self      ,							a__      ,							a__      ,							a__ = None      ,							a__ = Split.train      ,							a__ = None      ,							):



             """simple docstring"""





             warnings.warn(
                 '''This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '''
                 '''library. You can have a look at this example script for pointers: '''
                 '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'''      ,							a__      ,							)
             _lowerCamelCase							:     Optional[Any]	=		args
             _lowerCamelCase							:     Tuple	=		glue_processors[args.task_name]()
             _lowerCamelCase							:     Any	=		glue_output_modes[args.task_name]
             if isinstance(a__      ,							a__):
                    try:
                           _lowerCamelCase							:     List[Any]	=		Split[mode]
                    except KeyError:
                           raise KeyError('''mode is not a valid split name''')
        # Load data features from cache or dataset file
             _lowerCamelCase							:     Tuple	=		os.path.join(
                 cache_dir if cache_dir is not None else args.data_dir      ,							F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}"""      ,							)
             _lowerCamelCase							:     int	=		self.processor.get_labels()
             if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
                 "RobertaTokenizer",
                 "RobertaTokenizerFast",
                 "XLMRobertaTokenizer",
                 "BartTokenizer",
                 "BartTokenizerFast",
             ):
                    # HACK(label indices are swapped in RoBERTa pretrained model)
                    _lowerCamelCase,  _lowerCamelCase							:     Union[str, Any]	=		label_list[2], label_list[1]
             _lowerCamelCase							:     str	=		label_list

             # Make sure only the first process in distributed training processes the dataset,
             # and the others will use the cache.
             _lowerCamelCase							:     Any	=		cached_features_file + '''.lock'''
             with FileLock(a__):
                    if os.path.exists(a__) and not args.overwrite_cache:
                           _lowerCamelCase							:     Any	=		time.time()
                           _lowerCamelCase							:     Optional[Any]	=		torch.load(a__)
                           logger.info(
                               F"""Loading features from cached file {cached_features_file} [took %.3f s]"""      ,							time.time() - start)
                    else:
                           logger.info(F"""Creating features from dataset file at {args.data_dir}""")

                           if mode == Split.dev:
                                  _lowerCamelCase							:     List[str]	=		self.processor.get_dev_examples(args.data_dir)
                           elif mode == Split.test:
                                  _lowerCamelCase							:     str	=		self.processor.get_test_examples(args.data_dir)
                           else:
                                  _lowerCamelCase							:     List[Any]	=		self.processor.get_train_examples(args.data_dir)
                           if limit_length is not None:
                                  _lowerCamelCase							:     List[Any]	=		examples[:limit_length]
                           _lowerCamelCase							:     List[str]	=		glue_convert_examples_to_features(
                               a__      ,							a__      ,							max_length=args.max_seq_length      ,							label_list=a__      ,							output_mode=self.output_mode      ,							)
                           _lowerCamelCase							:     int	=		time.time()
                           torch.save(self.features      ,							a__)
                           # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                           logger.info(
                               F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""")


      def __len__(		self):



             """simple docstring"""





             return len(self.features)


      def __getitem__(		self      ,							a__):



             """simple docstring"""





             return self.features[i]



      def 				__snake_case			(		self):



             """simple docstring"""





             return self.label_list

