from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCAmelCase       =		logging.get_logger(__name__)

_lowerCAmelCase       =		{
    "microsoft/trocr-base-handwritten": (
        "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json"
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}
class     lowerCAmelCase_     (       __lowercase ):
							UpperCAmelCase				   =     "trocr"
							UpperCAmelCase				   =     ["past_key_values"]
							UpperCAmelCase				   =     {
							    "num_attention_heads": "decoder_attention_heads",
							    "hidden_size": "d_model",
							    "num_hidden_layers": "decoder_layers",
							}







							def __init__(   self      :     List[str] ,			_A      :     Optional[Any]=5_0265 ,			_A      :     Optional[Any]=1024 ,			_A      :     Optional[Any]=12 ,			_A      :     Any=16 ,			_A      :     Any=4096 ,			_A      :     Optional[Any]="gelu" ,			_A      :     Union[str, Any]=512 ,			_A      :     Dict=0.1 ,			_A      :     List[str]=0.0 ,			_A      :     Optional[Any]=0.0 ,			_A      :     Union[str, Any]=2 ,			_A      :     Any=0.02 ,			_A      :     List[str]=0.0 ,			_A      :     List[str]=True ,			_A      :     str=False ,			_A      :     List[str]=True ,			_A      :     Optional[Any]=True ,			_A      :     Optional[int]=1 ,			_A      :     int=0 ,			_A      :     Any=2 ,			**_A      :     Optional[int] ,			):
												_UpperCamelCase			     =     vocab_size
												_UpperCamelCase			     =     d_model
												_UpperCamelCase			     =     decoder_layers
												_UpperCamelCase			     =     decoder_attention_heads
												_UpperCamelCase			     =     decoder_ffn_dim
												_UpperCamelCase			     =     activation_function
												_UpperCamelCase			     =     max_position_embeddings
												_UpperCamelCase			     =     dropout
												_UpperCamelCase			     =     attention_dropout
												_UpperCamelCase			     =     activation_dropout
												_UpperCamelCase			     =     init_std
												_UpperCamelCase			     =     decoder_layerdrop
												_UpperCamelCase			     =     use_cache
												_UpperCamelCase			     =     scale_embedding
												_UpperCamelCase			     =     use_learned_position_embeddings
												_UpperCamelCase			     =     layernorm_embedding

												super().__init__(
												    pad_token_id=_A ,			bos_token_id=_A ,			eos_token_id=_A ,			decoder_start_token_id=_A ,			**_A ,			)

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     lowerCAmelCase_     (       unittest.TestCase ):
							UpperCAmelCase				   =     MODEL_FOR_CAUSAL_LM_MAPPING
							UpperCAmelCase				   =     TF_MODEL_FOR_CAUSAL_LM_MAPPING







							@require_torch
							def  UpperCamelCase_						(   self      :     str		):
												_UpperCamelCase			     =     pipeline(task='''text-generation''' ,			model='''sshleifer/tiny-ctrl''' ,			framework='''pt'''		)
												# Using `do_sample=False` to force deterministic output
												_UpperCamelCase			     =     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@@'''
												            )
												        }
												    ] ,			)

												_UpperCamelCase			     =     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@@'''
												                )
												            }
												        ],
												    ] ,			)

												_UpperCamelCase			     =     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		)},
												    ] ,			)
												_UpperCamelCase			     =     text_generator.model.config.eos_token_id
												_UpperCamelCase			     =     '''<pad>'''
												_UpperCamelCase			     =     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  UpperCamelCase_						(   self      :     Dict		):
												_UpperCamelCase			     =     pipeline(task='''text-generation''' ,			model='''sshleifer/tiny-ctrl''' ,			framework='''tf'''		)

												# Using `do_sample=False` to force deterministic output
												_UpperCamelCase			     =     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,'''
												            )
												        }
												    ] ,			)

												_UpperCamelCase			     =     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  UpperCamelCase_						(   self      :     int ,			_A      :     str ,			_A      :     Union[str, Any] ,			_A      :     Any		):
												_UpperCamelCase			     =     TextGenerationPipeline(model=_A ,			tokenizer=_A		)
												return text_generator, ["This is a test", "Another test"]







							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												_UpperCamelCase			     =     '''Hello I believe in'''
												_UpperCamelCase			     =     pipeline('''text-generation''' ,			model='''hf-internal-testing/tiny-random-gpt2'''		)
												_UpperCamelCase			     =     text_generator(_A		)
												self.assertEqual(
												    _A ,			[{'''generated_text''': '''Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'''}] ,			)

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







							def  UpperCamelCase_						(   self      :     Any ,			_A      :     List[Any] ,			_A      :     Union[str, Any]		):
												_UpperCamelCase			     =     text_generator.model
												_UpperCamelCase			     =     text_generator.tokenizer

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

												_UpperCamelCase			     =     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''']		)

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

												_UpperCamelCase			     =     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'''		)		)

												_UpperCamelCase			     =     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:
																	_UpperCamelCase			     =     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		):
																	_UpperCamelCase			     =     text_generator('''test''' ,			return_full_text=_A ,			return_text=_A		)
												with self.assertRaises(_A		):
																	_UpperCamelCase			     =     text_generator('''test''' ,			return_full_text=_A ,			return_tensors=_A		)
												with self.assertRaises(_A		):
																	_UpperCamelCase			     =     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__
												):
																	_UpperCamelCase			     =     text_generator(''''''		)
																	self.assertEqual(_A ,			[{'''generated_text''': ANY(_A		)}]		)
												else:
																	with self.assertRaises((ValueError, AssertionError)		):
																						_UpperCamelCase			     =     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.
												_UpperCamelCase			     =     ['''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		)

																	_UpperCamelCase			     =     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  UpperCamelCase_						(   self      :     Optional[int]		):
												import torch

												# Classic `model_kwargs`
												_UpperCamelCase			     =     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		)
												_UpperCamelCase			     =     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.)
												_UpperCamelCase			     =     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		)
												_UpperCamelCase			     =     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
												_UpperCamelCase			     =     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		)
												_UpperCamelCase			     =     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  UpperCamelCase_						(   self      :     Union[str, Any]		):
												import torch

												_UpperCamelCase			     =     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  UpperCamelCase_						(   self      :     Optional[int]		):
												import torch

												_UpperCamelCase			     =     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  UpperCamelCase_						(   self      :     Tuple		):
												_UpperCamelCase			     =     '''Hello world'''
												_UpperCamelCase			     =     pipeline('''text-generation''' ,			model='''hf-internal-testing/tiny-random-gpt2'''		)
												if text_generator.model.framework == "tf":
																	_UpperCamelCase			     =     logging.get_logger('''transformers.generation.tf_utils'''		)
												else:
																	_UpperCamelCase			     =     logging.get_logger('''transformers.generation.utils'''		)
												_UpperCamelCase			     =     '''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:
																	_UpperCamelCase			     =     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:
																	_UpperCamelCase			     =     text_generator(_A ,			max_new_tokens=1		)
												self.assertNotIn(_A ,			cl.out		)

												with CaptureLogger(_A		) as cl:
																	_UpperCamelCase			     =     text_generator(_A ,			max_length=10		)
												self.assertNotIn(_A ,			cl.out		)
