import math
import os
import unittest

from transformers import MegatronBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import (
			    MODEL_FOR_PRETRAINING_MAPPING,
			    MegatronBertForCausalLM,
			    MegatronBertForMaskedLM,
			    MegatronBertForMultipleChoice,
			    MegatronBertForNextSentencePrediction,
			    MegatronBertForPreTraining,
			    MegatronBertForQuestionAnswering,
			    MegatronBertForSequenceClassification,
			    MegatronBertForTokenClassification,
			    MegatronBertModel,
			)
class   _lowerCAmelCase		:







							def __init__(				self     :    str	,					__snake_case     :    str	,					__snake_case     :    Dict=13	,					__snake_case     :    Dict=7	,					__snake_case     :    Any=True	,					__snake_case     :    Any=True	,					__snake_case     :    Optional[int]=True	,					__snake_case     :    Any=True	,					__snake_case     :    Dict=99	,					__snake_case     :    int=64	,					__snake_case     :    Dict=32	,					__snake_case     :    int=5	,					__snake_case     :    Union[str, Any]=4	,					__snake_case     :    Optional[int]=37	,					__snake_case     :    List[Any]="gelu"	,					__snake_case     :    Any=0.1	,					__snake_case     :    Dict=0.1	,					__snake_case     :    Union[str, Any]=512	,					__snake_case     :    List[str]=16	,					__snake_case     :    str=2	,					__snake_case     :    Optional[int]=0.0_2	,					__snake_case     :    Optional[int]=3	,					__snake_case     :    Optional[int]=4	,					__snake_case     :    Dict=None	,					):
										lowerCamelCase						:Optional[Any]						  =     parent
										lowerCamelCase						:Optional[Any]						  =     batch_size
										lowerCamelCase						:str						  =     seq_length
										lowerCamelCase						:Union[str, Any]						  =     is_training
										lowerCamelCase						:Tuple						  =     use_input_mask
										lowerCamelCase						:int						  =     use_token_type_ids
										lowerCamelCase						:List[Any]						  =     use_labels
										lowerCamelCase						:List[Any]						  =     vocab_size
										lowerCamelCase						:Any						  =     hidden_size
										lowerCamelCase						:Tuple						  =     embedding_size
										lowerCamelCase						:List[Any]						  =     num_hidden_layers
										lowerCamelCase						:Optional[Any]						  =     num_attention_heads
										lowerCamelCase						:List[str]						  =     intermediate_size
										lowerCamelCase						:List[str]						  =     hidden_act
										lowerCamelCase						:Dict						  =     hidden_dropout_prob
										lowerCamelCase						:List[Any]						  =     attention_probs_dropout_prob
										lowerCamelCase						:Tuple						  =     max_position_embeddings
										lowerCamelCase						:Optional[int]						  =     type_vocab_size
										lowerCamelCase						:List[str]						  =     type_sequence_label_size
										lowerCamelCase						:Optional[int]						  =     initializer_range
										lowerCamelCase						:Any						  =     num_labels
										lowerCamelCase						:Any						  =     num_choices
										lowerCamelCase						:Optional[int]						  =     scope







							def 				snake_case  (				self     :    Any		):
										lowerCamelCase						:List[str]						  =     ids_tensor([self.batch_size, self.seq_length]	,					self.vocab_size		)

										lowerCamelCase						:Union[str, Any]						  =     None
										if self.use_input_mask:
													lowerCamelCase						:Optional[Any]						  =     random_attention_mask([self.batch_size, self.seq_length]		)

										lowerCamelCase						:Dict						  =     None
										if self.use_token_type_ids:
													lowerCamelCase						:Optional[int]						  =     ids_tensor([self.batch_size, self.seq_length]	,					self.type_vocab_size		)

										lowerCamelCase						:Dict						  =     None
										lowerCamelCase						:Tuple						  =     None
										lowerCamelCase						:Optional[Any]						  =     None
										if self.use_labels:
													lowerCamelCase						:str						  =     ids_tensor([self.batch_size]	,					self.type_sequence_label_size		)
													lowerCamelCase						:str						  =     ids_tensor([self.batch_size, self.seq_length]	,					self.num_labels		)
													lowerCamelCase						:int						  =     ids_tensor([self.batch_size]	,					self.num_choices		)

										lowerCamelCase						:Optional[Any]						  =     self.get_config()

										return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







							def 				snake_case  (				self     :    str		):
										return MegatronBertConfig(
										    vocab_size=self.vocab_size	,					hidden_size=self.hidden_size	,					num_hidden_layers=self.num_hidden_layers	,					num_attention_heads=self.num_attention_heads	,					intermediate_size=self.intermediate_size	,					embedding_size=self.embedding_size	,					hidden_act=self.hidden_act	,					hidden_dropout_prob=self.hidden_dropout_prob	,					attention_probs_dropout_prob=self.attention_probs_dropout_prob	,					max_position_embeddings=self.max_position_embeddings	,					type_vocab_size=self.type_vocab_size	,					is_decoder=__snake_case	,					initializer_range=self.initializer_range	,					)







							def 				snake_case  (				self     :    int	,					__snake_case     :    List[str]	,					__snake_case     :    int	,					__snake_case     :    Tuple	,					__snake_case     :    int	,					__snake_case     :    Optional[int]	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Optional[int]		):
										lowerCamelCase						:Dict						  =     MegatronBertModel(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:Tuple						  =     model(__snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case		)
										lowerCamelCase						:str						  =     model(__snake_case	,					token_type_ids=__snake_case		)
										lowerCamelCase						:Optional[int]						  =     model(__snake_case		)

										self.parent.assertEqual(result.last_hidden_state.shape	,					(self.batch_size, self.seq_length, self.hidden_size)		)
										self.parent.assertEqual(result.pooler_output.shape	,					(self.batch_size, self.hidden_size)		)







							def 				snake_case  (				self     :    int	,					__snake_case     :    Optional[int]	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    str	,					__snake_case     :    Any	,					__snake_case     :    int	,					__snake_case     :    Dict	,					__snake_case     :    Union[str, Any]		):
										lowerCamelCase						:Dict						  =     MegatronBertForMaskedLM(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:List[Any]						  =     model(__snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case		)
										self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.seq_length, self.vocab_size)		)







							def 				snake_case  (				self     :    Tuple	,					__snake_case     :    int	,					__snake_case     :    str	,					__snake_case     :    Any	,					__snake_case     :    List[str]	,					__snake_case     :    str	,					__snake_case     :    Any	,					__snake_case     :    List[Any]		):
										lowerCamelCase						:Any						  =     MegatronBertForCausalLM(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:str						  =     model(__snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case		)
										self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.seq_length, self.vocab_size)		)







							def 				snake_case  (				self     :    str	,					__snake_case     :    Optional[int]	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Optional[int]	,					__snake_case     :    str	,					__snake_case     :    Optional[int]	,					__snake_case     :    List[str]	,					__snake_case     :    str		):
										lowerCamelCase						:Dict						  =     MegatronBertForNextSentencePrediction(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:int						  =     model(
										    __snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case	,					)
										self.parent.assertEqual(result.logits.shape	,					(self.batch_size, 2)		)







							def 				snake_case  (				self     :    List[str]	,					__snake_case     :    str	,					__snake_case     :    int	,					__snake_case     :    Tuple	,					__snake_case     :    Dict	,					__snake_case     :    List[str]	,					__snake_case     :    Optional[int]	,					__snake_case     :    Optional[int]		):
										lowerCamelCase						:Dict						  =     MegatronBertForPreTraining(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:Optional[Any]						  =     model(
										    __snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case	,					next_sentence_label=__snake_case	,					)
										self.parent.assertEqual(result.prediction_logits.shape	,					(self.batch_size, self.seq_length, self.vocab_size)		)
										self.parent.assertEqual(result.seq_relationship_logits.shape	,					(self.batch_size, 2)		)







							def 				snake_case  (				self     :    Optional[int]	,					__snake_case     :    List[str]	,					__snake_case     :    List[str]	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Tuple	,					__snake_case     :    List[Any]	,					__snake_case     :    Optional[int]		):
										lowerCamelCase						:Dict						  =     MegatronBertForQuestionAnswering(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:Tuple						  =     model(
										    __snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case	,					start_positions=__snake_case	,					end_positions=__snake_case	,					)
										self.parent.assertEqual(result.start_logits.shape	,					(self.batch_size, self.seq_length)		)
										self.parent.assertEqual(result.end_logits.shape	,					(self.batch_size, self.seq_length)		)







							def 				snake_case  (				self     :    Dict	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    str	,					__snake_case     :    Any	,					__snake_case     :    int	,					__snake_case     :    int	,					__snake_case     :    Tuple	,					__snake_case     :    Tuple		):
										lowerCamelCase						:int						  =     self.num_labels
										lowerCamelCase						:List[str]						  =     MegatronBertForSequenceClassification(__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:List[str]						  =     model(__snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case		)
										self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_labels)		)







							def 				snake_case  (				self     :    List[str]	,					__snake_case     :    Optional[int]	,					__snake_case     :    str	,					__snake_case     :    int	,					__snake_case     :    Dict	,					__snake_case     :    Tuple	,					__snake_case     :    List[Any]	,					__snake_case     :    Dict		):
										lowerCamelCase						:Optional[Any]						  =     self.num_labels
										lowerCamelCase						:int						  =     MegatronBertForTokenClassification(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:Any						  =     model(__snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case		)
										self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.seq_length, self.num_labels)		)







							def 				snake_case  (				self     :    Optional[Any]	,					__snake_case     :    Optional[Any]	,					__snake_case     :    List[str]	,					__snake_case     :    Dict	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Optional[Any]	,					__snake_case     :    Tuple	,					__snake_case     :    Union[str, Any]		):
										lowerCamelCase						:Optional[Any]						  =     self.num_choices
										lowerCamelCase						:Tuple						  =     MegatronBertForMultipleChoice(config=__snake_case		)
										model.to(__snake_case		)
										model.eval()
										lowerCamelCase						:List[Any]						  =     input_ids.unsqueeze(1		).expand(-1	,					self.num_choices	,					-1		).contiguous()
										lowerCamelCase						:List[Any]						  =     token_type_ids.unsqueeze(1		).expand(-1	,					self.num_choices	,					-1		).contiguous()
										lowerCamelCase						:List[str]						  =     input_mask.unsqueeze(1		).expand(-1	,					self.num_choices	,					-1		).contiguous()
										lowerCamelCase						:Dict						  =     model(
										    __snake_case	,					attention_mask=__snake_case	,					token_type_ids=__snake_case	,					labels=__snake_case	,					)
										self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_choices)		)







							def 				snake_case  (				self     :    Dict		):
										lowerCamelCase						:List[str]						  =     self.prepare_config_and_inputs()
										(
										    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    (
										    lowerCamelCase
										)  ,    
										)						:Optional[Any]						  =     config_and_inputs
										lowerCamelCase						:List[Any]						  =     {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
										return config, inputs_dict


@require_torch
class   _lowerCAmelCase		(     __SCREAMING_SNAKE_CASE      ,   __SCREAMING_SNAKE_CASE      ,   unittest.TestCase				):
							_UpperCAmelCase						    =     (
							    (
							        MegatronBertModel,
							        MegatronBertForMaskedLM,
							        MegatronBertForCausalLM,
							        MegatronBertForMultipleChoice,
							        MegatronBertForNextSentencePrediction,
							        MegatronBertForPreTraining,
							        MegatronBertForQuestionAnswering,
							        MegatronBertForSequenceClassification,
							        MegatronBertForTokenClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							_UpperCAmelCase						    =     (
							    {
							        'feature-extraction': MegatronBertModel,
							        'fill-mask': MegatronBertForMaskedLM,
							        'question-answering': MegatronBertForQuestionAnswering,
							        'text-classification': MegatronBertForSequenceClassification,
							        'text-generation': MegatronBertForCausalLM,
							        'token-classification': MegatronBertForTokenClassification,
							        'zero-shot': MegatronBertForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							_UpperCAmelCase						    =     True
							# test_resize_embeddings = False
							_UpperCAmelCase						    =     False







							def 				snake_case  (				self     :    Any	,					__snake_case     :    Optional[Any]	,					__snake_case     :    str	,					__snake_case     :    List[Any]=False		):
										lowerCamelCase						:Union[str, Any]						  =     super()._prepare_for_class(__snake_case	,					__snake_case	,					return_labels=__snake_case		)

										if return_labels:
													if model_class in get_values(__snake_case		):
																lowerCamelCase						:int						  =     torch.zeros(
																    (self.model_tester.batch_size, self.model_tester.seq_length)	,					dtype=torch.long	,					device=__snake_case		)
																lowerCamelCase						:str						  =     torch.zeros(
																    self.model_tester.batch_size	,					dtype=torch.long	,					device=__snake_case		)
										return inputs_dict







							def 				snake_case  (				self     :    Optional[Any]		):
										lowerCamelCase						:List[Any]						  =     MegatronBertModelTester(self		)
										lowerCamelCase						:Union[str, Any]						  =     ConfigTester(self	,					config_class=__snake_case	,					hidden_size=37		)







							def 				snake_case  (				self     :    Dict		):
										self.config_tester.run_common_tests()







							def 				snake_case  (				self     :    Any		):
										lowerCamelCase						:int						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_megatron_bert_model(*__snake_case		)







							def 				snake_case  (				self     :    List[str]		):
										lowerCamelCase						:Optional[Any]						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__snake_case		)







							def 				snake_case  (				self     :    Any		):
										lowerCamelCase						:Dict						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__snake_case		)







							def 				snake_case  (				self     :    int		):
										lowerCamelCase						:List[Any]						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__snake_case		)







							def 				snake_case  (				self     :    List[Any]		):
										lowerCamelCase						:Tuple						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_megatron_bert_for_pretraining(*__snake_case		)







							def 				snake_case  (				self     :    Union[str, Any]		):
										lowerCamelCase						:Dict						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_megatron_bert_for_question_answering(*__snake_case		)







							def 				snake_case  (				self     :    int		):
										lowerCamelCase						:Dict						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__snake_case		)







							def 				snake_case  (				self     :    Optional[int]		):
										lowerCamelCase						:List[Any]						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_megatron_bert_for_token_classification(*__snake_case		)





def  _lowerCamelCase					(   a_				: Optional[Any]):
			return torch.tensor(
			    a_						,			dtype=torch.long						,			device=a_						,			)


A__           =							1E-4


@require_torch
@require_sentencepiece
@require_tokenizers
class   _lowerCAmelCase		(     unittest.TestCase				):







							@slow
							@unittest.skip('''Model is not available.'''		)
							def 				snake_case  (				self     :    Union[str, Any]		):
										lowerCamelCase						:Union[str, Any]						  =     '''nvidia/megatron-bert-uncased-345m'''
										if "MYDIR" in os.environ:
													lowerCamelCase						:Any						  =     os.path.join(os.environ['''MYDIR''']	,					__snake_case		)
										lowerCamelCase						:Union[str, Any]						  =     MegatronBertModel.from_pretrained(__snake_case		)
										model.to(__snake_case		)
										model.half()
										lowerCamelCase						:List[str]						  =     _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]]		)
										with torch.no_grad():
													lowerCamelCase						:Any						  =     model(__snake_case		)[0]
										lowerCamelCase						:Tuple						  =     torch.Size((1, 9, 1024)		)
										self.assertEqual(output.shape	,					__snake_case		)

										lowerCamelCase						:str						  =     [-0.6_0_4_0, -0.2_5_1_7, -0.1_0_2_5, 0.3_4_2_0, -0.6_7_5_8, -0.0_0_1_7, -0.1_0_8_9, -0.1_9_9_0, 0.5_7_2_8]
										for ii in range(3		):
													for jj in range(3		):
																lowerCamelCase						:int						  =     output[0, ii, jj]
																lowerCamelCase						:str						  =     expected[3 * ii + jj]
																lowerCamelCase						:Union[str, Any]						  =     '''ii={} jj={} a={} b={}'''.format(__snake_case	,					__snake_case	,					__snake_case	,					__snake_case		)
																self.assertTrue(math.isclose(__snake_case	,					__snake_case	,					rel_tol=__snake_case	,					abs_tol=__snake_case		)	,					msg=__snake_case		)




import unittest
from queue import Empty
from threading import Thread

from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
			import torch

			from transformers import AutoModelForCausalLM
@require_torch
class   _lowerCAmelCase		(     unittest.TestCase				):







							def 				snake_case  (				self     :    str		):
										lowerCamelCase						:int						  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		)
										lowerCamelCase						:List[Any]						  =     AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		).to(__snake_case		)
										lowerCamelCase						:Optional[Any]						  =     -1

										lowerCamelCase						:List[str]						  =     ids_tensor((1, 5)	,					vocab_size=model.config.vocab_size		).to(__snake_case		)
										lowerCamelCase						:Tuple						  =     model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case		)
										lowerCamelCase						:str						  =     tokenizer.decode(greedy_ids[0]		)

										with CaptureStdout() as cs:
													lowerCamelCase						:str						  =     TextStreamer(__snake_case		)
													model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case	,					streamer=__snake_case		)
										# The greedy text should be printed to stdout, except for the final "\n" in the streamer
										lowerCamelCase						:Optional[int]						  =     cs.out[:-1]

										self.assertEqual(__snake_case	,					__snake_case		)







							def 				snake_case  (				self     :    Dict		):
										lowerCamelCase						:Tuple						  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		)
										lowerCamelCase						:int						  =     AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		).to(__snake_case		)
										lowerCamelCase						:List[Any]						  =     -1

										lowerCamelCase						:Dict						  =     ids_tensor((1, 5)	,					vocab_size=model.config.vocab_size		).to(__snake_case		)
										lowerCamelCase						:Tuple						  =     model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case		)
										lowerCamelCase						:List[Any]						  =     tokenizer.decode(greedy_ids[0]		)

										lowerCamelCase						:List[str]						  =     TextIteratorStreamer(__snake_case		)
										lowerCamelCase						:List[str]						  =     {'''input_ids''': input_ids, '''max_new_tokens''': 10, '''do_sample''': False, '''streamer''': streamer}
										lowerCamelCase						:Tuple						  =     Thread(target=model.generate	,					kwargs=__snake_case		)
										thread.start()
										lowerCamelCase						:Any						  =     ''''''
										for new_text in streamer:
													streamer_text += new_text

										self.assertEqual(__snake_case	,					__snake_case		)







							def 				snake_case  (				self     :    str		):
										lowerCamelCase						:int						  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		)
										lowerCamelCase						:Dict						  =     AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		).to(__snake_case		)
										lowerCamelCase						:List[str]						  =     -1

										lowerCamelCase						:Optional[Any]						  =     ids_tensor((1, 5)	,					vocab_size=model.config.vocab_size		).to(__snake_case		)
										lowerCamelCase						:Optional[Any]						  =     model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case		)
										lowerCamelCase						:List[str]						  =     greedy_ids[:, input_ids.shape[1] :]
										lowerCamelCase						:Union[str, Any]						  =     tokenizer.decode(new_greedy_ids[0]		)

										with CaptureStdout() as cs:
													lowerCamelCase						:List[str]						  =     TextStreamer(__snake_case	,					skip_prompt=__snake_case		)
													model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case	,					streamer=__snake_case		)
										# The greedy text should be printed to stdout, except for the final "\n" in the streamer
										lowerCamelCase						:int						  =     cs.out[:-1]

										self.assertEqual(__snake_case	,					__snake_case		)







							def 				snake_case  (				self     :    Optional[int]		):
										# Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested
										# with actual models -- the dummy models' tokenizers are not aligned with their models, and
										# `skip_special_tokens=True` has no effect on them
										lowerCamelCase						:List[Any]						  =     AutoTokenizer.from_pretrained('''distilgpt2'''		)
										lowerCamelCase						:Union[str, Any]						  =     AutoModelForCausalLM.from_pretrained('''distilgpt2'''		).to(__snake_case		)
										lowerCamelCase						:Optional[int]						  =     -1

										lowerCamelCase						:Union[str, Any]						  =     torch.ones((1, 5)	,					device=__snake_case		).long() * model.config.bos_token_id
										with CaptureStdout() as cs:
													lowerCamelCase						:Dict						  =     TextStreamer(__snake_case	,					skip_special_tokens=__snake_case		)
													model.generate(__snake_case	,					max_new_tokens=1	,					do_sample=__snake_case	,					streamer=__snake_case		)

										# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
										# re-tokenized, must only contain one token
										lowerCamelCase						:Tuple						  =     cs.out[:-1]  # Remove the final "\n"
										lowerCamelCase						:int						  =     tokenizer(__snake_case	,					return_tensors='''pt'''		)
										self.assertEqual(streamer_text_tokenized.input_ids.shape	,					(1, 1)		)







							def 				snake_case  (				self     :    List[Any]		):
										lowerCamelCase						:List[str]						  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		)
										lowerCamelCase						:Optional[int]						  =     AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		).to(__snake_case		)
										lowerCamelCase						:Optional[int]						  =     -1

										lowerCamelCase						:Tuple						  =     ids_tensor((1, 5)	,					vocab_size=model.config.vocab_size		).to(__snake_case		)
										lowerCamelCase						:List[Any]						  =     TextIteratorStreamer(__snake_case	,					timeout=0.0_0_1		)
										lowerCamelCase						:Dict						  =     {'''input_ids''': input_ids, '''max_new_tokens''': 10, '''do_sample''': False, '''streamer''': streamer}
										lowerCamelCase						:Tuple						  =     Thread(target=model.generate	,					kwargs=__snake_case		)
										thread.start()

										# The streamer will timeout after 0.001 seconds, so an exception will be raised
										with self.assertRaises(__snake_case		):
													lowerCamelCase						:Dict						  =     ''''''
													for new_text in streamer:
																streamer_text += new_text



