

import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402


lowerCAmelCase							:  Optional[int]           =						get_tests_dir("""fixtures/dummy-config.json""")



class   __lowercase    (			unittest.TestCase     ):




			"""simple docstring"""







			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any):
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	0



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									self.assertIsNotNone(transformers.models.auto.__spec__)
									self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"))



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									SCREAMING_SNAKE_CASE_:			Dict  		=	AutoConfig.from_pretrained("bert-base-uncased")
									self.assertIsInstance(__A       ,						__A)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoConfig.from_pretrained(__A)
									self.assertIsInstance(__A       ,						__A)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]):
									SCREAMING_SNAKE_CASE_:			Dict  		=	AutoConfig.from_pretrained(__A)
									self.assertIsInstance(__A       ,						__A)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									SCREAMING_SNAKE_CASE_:			Any  		=	AutoConfig.for_model("roberta")
									self.assertIsInstance(__A       ,						__A)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									with tempfile.TemporaryDirectory() as tmp_dir:
															# This model name contains bert and roberta, but roberta ends up being picked.
															SCREAMING_SNAKE_CASE_:			List[str]  		=	os.path.join(__A       ,						"fake-roberta")
															os.makedirs(__A       ,						exist_ok=__A)
															with open(os.path.join(__A       ,						"config.json")       ,						"w") as f:
																					f.write(json.dumps({}))
															SCREAMING_SNAKE_CASE_:			Tuple  		=	AutoConfig.from_pretrained(__A)
															self.assertEqual(type(__A)       ,						__A)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]):
									try:
															AutoConfig.register("custom"       ,						__A)
															# Wrong model type will raise an error
															with self.assertRaises(__A):
																					AutoConfig.register("model"       ,						__A)
															# Trying to register something existing in the Transformers library will raise an error
															with self.assertRaises(__A):
																					AutoConfig.register("bert"       ,						__A)

															# Now that the config is registered, it can be used as any other config with the auto-API
															SCREAMING_SNAKE_CASE_:			Any  		=	CustomConfig()
															with tempfile.TemporaryDirectory() as tmp_dir:
																					config.save_pretrained(__A)
																					SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	AutoConfig.from_pretrained(__A)
																					self.assertIsInstance(__A       ,						__A)

									finally:
															if "custom" in CONFIG_MAPPING._extra_content:
																					del CONFIG_MAPPING._extra_content["custom"]



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									with self.assertRaisesRegex(
									    __A       ,						"bert-base is not a local folder and is not a valid model identifier"):
															SCREAMING_SNAKE_CASE_:			Any  		=	AutoConfig.from_pretrained("bert-base")



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									with self.assertRaisesRegex(
									    __A       ,						R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"):
															SCREAMING_SNAKE_CASE_:			Any  		=	AutoConfig.from_pretrained(__A       ,						revision="aaaaaa")



			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									with self.assertRaisesRegex(
									    __A       ,						"hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."       ,						):
															SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo")



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									# If remote code is not set, we will time out when asking whether to load the model.
									with self.assertRaises(__A):
															SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model")
									# If remote code is disabled, we can't load this config.
									with self.assertRaises(__A):
															SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"       ,						trust_remote_code=__A)

									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"       ,						trust_remote_code=__A)
									self.assertEqual(config.__class__.__name__       ,						"NewModelConfig")

									# Test config can be reloaded.
									with tempfile.TemporaryDirectory() as tmp_dir:
															config.save_pretrained(__A)
															SCREAMING_SNAKE_CASE_:			Any  		=	AutoConfig.from_pretrained(__A       ,						trust_remote_code=__A)
									self.assertEqual(reloaded_config.__class__.__name__       ,						"NewModelConfig")




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):



									class   __lowercase    (			lowerCamelCase__     ):




												"""simple docstring"""







												_UpperCAmelCase       :							Any      							=					'''new-model'''

									try:
															AutoConfig.register("new-model"       ,						__A)
															# If remote code is not set, the default is to use local
															SCREAMING_SNAKE_CASE_:			Dict  		=	AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model")
															self.assertEqual(config.__class__.__name__       ,						"NewModelConfigLocal")

															# If remote code is disabled, we load the local one.
															SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"       ,						trust_remote_code=__A)
															self.assertEqual(config.__class__.__name__       ,						"NewModelConfigLocal")

															# If remote is enabled, we load from the Hub
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"       ,						trust_remote_code=__A)
															self.assertEqual(config.__class__.__name__       ,						"NewModelConfig")

									finally:
															if "new-model" in CONFIG_MAPPING._extra_content:
																					del CONFIG_MAPPING._extra_content["new-model"]









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   __lowercase    (			unittest.TestCase     ):




			"""simple docstring"""







			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									SCREAMING_SNAKE_CASE_:			str  		=	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_:			str  		=	AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			str  		=	-1

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	ids_tensor((1, 5)       ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Any  		=	model.generate(lowerCAmelCase__       ,						max_new_tokens=10       ,						do_sample=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[str]  		=	tokenizer.decode(greedy_ids[0])

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

									self.assertEqual(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_:			int  		=	AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	-1

									SCREAMING_SNAKE_CASE_:			int  		=	ids_tensor((1, 5)       ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			int  		=	model.generate(lowerCAmelCase__       ,						max_new_tokens=10       ,						do_sample=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Tuple  		=	tokenizer.decode(greedy_ids[0])

									SCREAMING_SNAKE_CASE_:			int  		=	TextIteratorStreamer(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	{"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
									SCREAMING_SNAKE_CASE_:			Tuple  		=	Thread(target=model.generate       ,						kwargs=lowerCAmelCase__)
									thread.start()
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	""
									for new_text in streamer:
															streamer_text += new_text

									self.assertEqual(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[int]):
									SCREAMING_SNAKE_CASE_:			int  		=	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_:			int  		=	AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	-1

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

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

									self.assertEqual(lowerCAmelCase__       ,						lowerCAmelCase__)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									# 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
									SCREAMING_SNAKE_CASE_:			Tuple  		=	AutoTokenizer.from_pretrained("distilgpt2")
									SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoModelForCausalLM.from_pretrained("distilgpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	-1

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

									# 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
									SCREAMING_SNAKE_CASE_:			str  		=	cs.out[:-1]  # Remove the final "\n"
									SCREAMING_SNAKE_CASE_:			Tuple  		=	tokenizer(lowerCAmelCase__       ,						return_tensors="pt")
									self.assertEqual(streamer_text_tokenized.input_ids.shape       ,						(1, 1))




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_:			List[str]  		=	AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Dict  		=	-1

									SCREAMING_SNAKE_CASE_:			List[str]  		=	ids_tensor((1, 5)       ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Any  		=	TextIteratorStreamer(lowerCAmelCase__       ,						timeout=0.001)
									SCREAMING_SNAKE_CASE_:			Any  		=	{"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
									SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	Thread(target=model.generate       ,						kwargs=lowerCAmelCase__)
									thread.start()

									# The streamer will timeout after 0.001 seconds, so an exception will be raised
									with self.assertRaises(lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_:			Tuple  		=	""
															for new_text in streamer:
																					streamer_text += new_text






