

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  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: Tuple  		=       AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: int  		=       -1

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

									with CaptureStdout() as cs:
															SCREAMING_SNAKE_CASE_: List[Any]  		=       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_: int  		=       cs.out[:-1]

									self.assertEqual(lowerCAmelCase__   ,						lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									SCREAMING_SNAKE_CASE_: 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_: int  		=       -1

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

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

									self.assertEqual(lowerCAmelCase__   ,						lowerCAmelCase__)



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

									SCREAMING_SNAKE_CASE_: Dict  		=       ids_tensor((1, 5)   ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       model.generate(lowerCAmelCase__   ,						max_new_tokens=10   ,						do_sample=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Dict  		=       greedy_ids[:, input_ids.shape[1] :]
									SCREAMING_SNAKE_CASE_: str  		=       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_: Union[str, Any]  		=       cs.out[:-1]

									self.assertEqual(lowerCAmelCase__   ,						lowerCAmelCase__)



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

									SCREAMING_SNAKE_CASE_: Tuple  		=       torch.ones((1, 5)   ,						device=lowerCAmelCase__).long() * model.config.bos_token_id
									with CaptureStdout() as cs:
															SCREAMING_SNAKE_CASE_: Optional[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_: List[str]  		=       cs.out[:-1]  # Remove the final "\n"
									SCREAMING_SNAKE_CASE_: Any  		=       tokenizer(lowerCAmelCase__   ,						return_tensors="pt")
									self.assertEqual(streamer_text_tokenized.input_ids.shape   ,						(1, 1))




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

									SCREAMING_SNAKE_CASE_: List[Any]  		=       ids_tensor((1, 5)   ,						vocab_size=model.config.vocab_size).to(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: int  		=       TextIteratorStreamer(lowerCAmelCase__   ,						timeout=0.001)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
									SCREAMING_SNAKE_CASE_: List[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_: List[Any]  		=       ""
															for new_text in streamer:
																					streamer_text += new_text









import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
						import torch

						from transformers.generation import DisjunctiveConstraint



@require_torch
class   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									# For consistency across different places the DisjunctiveConstraint is called,
									# dc.token_ids is a list of integers. It is also initialized only by integers.

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       [[1, 2, 4], [1, 2, 3, 4]]
									SCREAMING_SNAKE_CASE_: Any  		=       DisjunctiveConstraint(lowerCAmelCase__)
									self.assertTrue(isinstance(dc.token_ids   ,						lowerCAmelCase__))

									with self.assertRaises(lowerCAmelCase__):
															DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]]))

									with self.assertRaises(lowerCAmelCase__):
															DisjunctiveConstraint([torch.LongTensor([1, 2, 4]), torch.LongTensor([1, 2, 3, 4, 5])])



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									# We can't have constraints that are complete subsets of another. This leads to a preverse
									# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
									# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
									# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
									# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       [[1, 2], [1, 2, 3, 4]]

									with self.assertRaises(lowerCAmelCase__):
															DisjunctiveConstraint(lowerCAmelCase__)  # fails here



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: List[str]  		=       [[1, 2, 3], [1, 2, 4]]

									SCREAMING_SNAKE_CASE_: Tuple  		=       DisjunctiveConstraint(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: int  		=       dc.update(1)
									SCREAMING_SNAKE_CASE_: Dict  		=       stepped is True and completed is False and reset is False
									self.assertTrue(lowerCAmelCase__)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: str  		=       dc.update(2)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       stepped is True and completed is False and reset is False
									self.assertTrue(lowerCAmelCase__)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1, 2])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Tuple  		=       dc.update(3)
									SCREAMING_SNAKE_CASE_: Tuple  		=       stepped is True and completed is True and reset is False
									self.assertTrue(lowerCAmelCase__)
									self.assertTrue(dc.completed)  # Completed!
									self.assertTrue(dc.current_seq == [1, 2, 3])




			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]

									SCREAMING_SNAKE_CASE_: List[Any]  		=       DisjunctiveConstraint(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Optional[Any]  		=       dc.update(1)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Dict  		=       dc.update(2)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1, 2])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Tuple  		=       dc.update(4)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.current_seq == [1, 2, 4])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Optional[Any]  		=       dc.update(5)
									self.assertTrue(dc.completed)  # Completed!
									self.assertTrue(dc.current_seq == [1, 2, 4, 5])

									dc.reset()

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[Any]  		=       dc.update(1)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.remaining() == 3)
									self.assertTrue(dc.current_seq == [1])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Tuple  		=       dc.update(2)
									self.assertTrue(not dc.completed)
									self.assertTrue(dc.remaining() == 2)
									self.assertTrue(dc.current_seq == [1, 2])

									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       dc.update(5)
									self.assertTrue(dc.completed)  # Completed!
									self.assertTrue(dc.remaining() == 0)
									self.assertTrue(dc.current_seq == [1, 2, 5])






