






"""simple docstring"""



import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 							__SCREAMING_SNAKE_CASE  (			UpperCamelCase    ,						UpperCamelCase    ,						unittest.TestCase						):
							snake_case_       =							CycleDiffusionPipeline
							snake_case_       =							TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
							    'negative_prompt',
							    'height',
							    'width',
							    'negative_prompt_embeds',
							}
							snake_case_       =							PipelineTesterMixin.required_optional_params - {'latents'}
							snake_case_       =							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'source_prompt'}						)
							snake_case_       =							IMAGE_TO_IMAGE_IMAGE_PARAMS
							snake_case_       =							IMAGE_TO_IMAGE_IMAGE_PARAMS


							def   _UpperCamelCase    (     self :  Tuple							):
													'''simple docstring'''





													torch.manual_seed(0							)
													A__  :					int											=					UNetaDConditionModel(
													    block_out_channels=(32, 64)     ,      layers_per_block=2     ,      sample_size=32     ,      in_channels=4     ,      out_channels=4     ,      down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")     ,      up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")     ,      cross_attention_dim=32     ,      )
													A__  :					Any											=					DDIMScheduler(
													    beta_start=0.00085     ,      beta_end=0.012     ,      beta_schedule="""scaled_linear"""     ,      num_train_timesteps=1000     ,      clip_sample=snake_case     ,      set_alpha_to_one=snake_case     ,      )
													torch.manual_seed(0							)
													A__  :					List[str]											=					AutoencoderKL(
													    block_out_channels=[32, 64]     ,      in_channels=3     ,      out_channels=3     ,      down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]     ,      up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]     ,      latent_channels=4     ,      )
													torch.manual_seed(0							)
													A__  :					Dict											=					CLIPTextConfig(
													    bos_token_id=0     ,      eos_token_id=2     ,      hidden_size=32     ,      intermediate_size=37     ,      layer_norm_eps=1e-05     ,      num_attention_heads=4     ,      num_hidden_layers=5     ,      pad_token_id=1     ,      vocab_size=1000     ,      )
													A__  :					Any											=					CLIPTextModel(snake_case							)
													A__  :					Union[str, Any]											=					CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""							)

													A__  :					int											=					{
													    """unet""": unet,
													    """scheduler""": scheduler,
													    """vae""": vae,
													    """text_encoder""": text_encoder,
													    """tokenizer""": tokenizer,
													    """safety_checker""": None,
													    """feature_extractor""": None,
													}
													return components


							def   _UpperCamelCase    (     self :  Union[str, Any]     ,      snake_case :  Optional[Any]     ,      snake_case :  str=0							):
													'''simple docstring'''





													A__  :					Any											=					floats_tensor((1, 3, 32, 32)     ,      rng=random.Random(snake_case							)							).to(snake_case							)
													A__  :					Tuple											=					image / 2 + 0.5
													if str(snake_case							).startswith("""mps"""							):
																			A__  :					List[Any]											=					torch.manual_seed(snake_case							)
													else:
																			A__  :					Union[str, Any]											=					torch.Generator(device=snake_case							).manual_seed(snake_case							)
													A__  :					Dict											=					{
													    """prompt""": """An astronaut riding an elephant""",
													    """source_prompt""": """An astronaut riding a horse""",
													    """image""": image,
													    """generator""": generator,
													    """num_inference_steps""": 2,
													    """eta""": 0.1,
													    """strength""": 0.8,
													    """guidance_scale""": 3,
													    """source_guidance_scale""": 1,
													    """output_type""": """numpy""",
													}
													return inputs


							def   _UpperCamelCase    (     self :  Optional[Any]							):
													'''simple docstring'''





													A__  :					str											=					"""cpu"""  # ensure determinism for the device-dependent torch.Generator

													A__  :					Union[str, Any]											=					self.get_dummy_components()
													A__  :					List[Any]											=					CycleDiffusionPipeline(**snake_case							)
													A__  :					Dict											=					pipe.to(snake_case							)
													pipe.set_progress_bar_config(disable=snake_case							)

													A__  :					Optional[int]											=					self.get_dummy_inputs(snake_case							)
													A__  :					List[Any]											=					pipe(**snake_case							)
													A__  :					Optional[Any]											=					output.images

													A__  :					str											=					images[0, -3:, -3:, -1]

													assert images.shape == (1, 32, 32, 3)
													A__  :					List[Any]											=					np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179]							)

													assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2


							@unittest.skipIf(torch_device != """cuda"""     ,      """This test requires a GPU"""							)
							def   _UpperCamelCase    (     self :  Tuple							):
													'''simple docstring'''





													A__  :					Optional[Any]											=					self.get_dummy_components()
													for name, module in components.items():
																			if hasattr(snake_case     ,      """half"""							):
																									A__  :					str											=					module.half()
													A__  :					Dict											=					CycleDiffusionPipeline(**snake_case							)
													A__  :					Optional[Any]											=					pipe.to(snake_case							)
													pipe.set_progress_bar_config(disable=snake_case							)

													A__  :					Optional[Any]											=					self.get_dummy_inputs(snake_case							)
													A__  :					Tuple											=					pipe(**snake_case							)
													A__  :					Union[str, Any]											=					output.images

													A__  :					Tuple											=					images[0, -3:, -3:, -1]

													assert images.shape == (1, 32, 32, 3)
													A__  :					Any											=					np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116]							)

													assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2


							@skip_mps
							def   _UpperCamelCase    (     self :  List[str]							):
													'''simple docstring'''





													return super().test_save_load_local()


							@unittest.skip("""non-deterministic pipeline"""							)
							def   _UpperCamelCase    (     self :  str							):
													'''simple docstring'''





													return super().test_inference_batch_single_identical()


							@skip_mps
							def   _UpperCamelCase    (     self :  Any							):
													'''simple docstring'''





													return super().test_dict_tuple_outputs_equivalent()


							@skip_mps
							def   _UpperCamelCase    (     self :  Union[str, Any]							):
													'''simple docstring'''





													return super().test_save_load_optional_components()


							@skip_mps
							def   _UpperCamelCase    (     self :  Any							):
													'''simple docstring'''





													return super().test_attention_slicing_forward_pass()






@slow
@require_torch_gpu
class 							__SCREAMING_SNAKE_CASE  (			unittest.TestCase						):


							def   _UpperCamelCase    (     self :  Optional[int]							):
													'''simple docstring'''





													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()


							def   _UpperCamelCase    (     self :  str							):
													'''simple docstring'''





													A__  :					Dict											=					load_image(
													    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
													    """/cycle-diffusion/black_colored_car.png"""							)
													A__  :					List[str]											=					load_numpy(
													    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy"""							)
													A__  :					List[Any]											=					init_image.resize((512, 512)							)

													A__  :					List[str]											=					"""CompVis/stable-diffusion-v1-4"""
													A__  :					str											=					DDIMScheduler.from_pretrained(snake_case     ,      subfolder="""scheduler"""							)
													A__  :					Dict											=					CycleDiffusionPipeline.from_pretrained(
													    snake_case     ,      scheduler=snake_case     ,      safety_checker=snake_case     ,      torch_dtype=torch.floataa     ,      revision="""fp16"""							)

													pipe.to(snake_case							)
													pipe.set_progress_bar_config(disable=snake_case							)
													pipe.enable_attention_slicing()

													A__  :					Dict											=					"""A black colored car"""
													A__  :					Optional[Any]											=					"""A blue colored car"""

													A__  :					List[Any]											=					torch.manual_seed(0							)
													A__  :					Tuple											=					pipe(
													    prompt=snake_case     ,      source_prompt=snake_case     ,      image=snake_case     ,      num_inference_steps=100     ,      eta=0.1     ,      strength=0.85     ,      guidance_scale=3     ,      source_guidance_scale=1     ,      generator=snake_case     ,      output_type="""np"""     ,      )
													A__  :					List[str]											=					output.images

													# the values aren't exactly equal, but the images look the same visually
													assert np.abs(image - expected_image							).max() < 5e-1


							def   _UpperCamelCase    (     self :  str							):
													'''simple docstring'''





													A__  :					Optional[int]											=					load_image(
													    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
													    """/cycle-diffusion/black_colored_car.png"""							)
													A__  :					int											=					load_numpy(
													    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy"""							)
													A__  :					str											=					init_image.resize((512, 512)							)

													A__  :					Tuple											=					"""CompVis/stable-diffusion-v1-4"""
													A__  :					Optional[int]											=					DDIMScheduler.from_pretrained(snake_case     ,      subfolder="""scheduler"""							)
													A__  :					Any											=					CycleDiffusionPipeline.from_pretrained(snake_case     ,      scheduler=snake_case     ,      safety_checker=snake_case							)

													pipe.to(snake_case							)
													pipe.set_progress_bar_config(disable=snake_case							)
													pipe.enable_attention_slicing()

													A__  :					Dict											=					"""A black colored car"""
													A__  :					Any											=					"""A blue colored car"""

													A__  :					Any											=					torch.manual_seed(0							)
													A__  :					Union[str, Any]											=					pipe(
													    prompt=snake_case     ,      source_prompt=snake_case     ,      image=snake_case     ,      num_inference_steps=100     ,      eta=0.1     ,      strength=0.85     ,      guidance_scale=3     ,      source_guidance_scale=1     ,      generator=snake_case     ,      output_type="""np"""     ,      )
													A__  :					Any											=					output.images

													assert np.abs(image - expected_image							).max() < 2e-2














"""simple docstring"""



import unittest

from parameterized import parameterized

from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
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 (
						    GPTNeoXForCausalLM,
						    GPTNeoXForQuestionAnswering,
						    GPTNeoXForSequenceClassification,
						    GPTNeoXForTokenClassification,
						    GPTNeoXModel,
						)






class 							__SCREAMING_SNAKE_CASE  :


							def __init__(     self :  Optional[int]     ,      snake_case :  Optional[Any]     ,      snake_case :  Tuple=13     ,      snake_case :  Dict=7     ,      snake_case :  Optional[int]=True     ,      snake_case :  Union[str, Any]=True     ,      snake_case :  Dict=True     ,      snake_case :  Any=True     ,      snake_case :  List[str]=99     ,      snake_case :  str=64     ,      snake_case :  Optional[int]=5     ,      snake_case :  str=4     ,      snake_case :  List[Any]=37     ,      snake_case :  Optional[Any]="gelu"     ,      snake_case :  List[str]=0.1     ,      snake_case :  str=0.1     ,      snake_case :  Optional[int]=512     ,      snake_case :  Dict=16     ,      snake_case :  List[Any]=2     ,      snake_case :  Optional[int]=0.02     ,      snake_case :  Any=3     ,      snake_case :  Union[str, Any]=4     ,      snake_case :  Dict=None     ,      ):
													'''simple docstring'''





													A__  :					Tuple											=					parent
													A__  :					Union[str, Any]											=					batch_size
													A__  :					List[str]											=					seq_length
													A__  :					Optional[int]											=					is_training
													A__  :					Dict											=					use_input_mask
													A__  :					Any											=					use_token_type_ids
													A__  :					Optional[Any]											=					use_labels
													A__  :					List[str]											=					vocab_size
													A__  :					Optional[int]											=					hidden_size
													A__  :					Optional[Any]											=					num_hidden_layers
													A__  :					Any											=					num_attention_heads
													A__  :					List[Any]											=					intermediate_size
													A__  :					Optional[Any]											=					hidden_act
													A__  :					Optional[int]											=					hidden_dropout_prob
													A__  :					Tuple											=					attention_probs_dropout_prob
													A__  :					str											=					max_position_embeddings
													A__  :					List[str]											=					type_vocab_size
													A__  :					Union[str, Any]											=					type_sequence_label_size
													A__  :					List[Any]											=					initializer_range
													A__  :					Optional[int]											=					num_labels
													A__  :					Dict											=					num_choices
													A__  :					Dict											=					scope
													A__  :					List[Any]											=					vocab_size - 1


							def   _UpperCamelCase    (     self :  List[Any]							):
													'''simple docstring'''





													A__  :					Any											=					ids_tensor([self.batch_size, self.seq_length]     ,      self.vocab_size							)

													A__  :					List[Any]											=					None
													if self.use_input_mask:
																			A__  :					List[Any]											=					random_attention_mask([self.batch_size, self.seq_length]							)

													A__  :					Union[str, Any]											=					None
													if self.use_labels:
																			A__  :					Optional[int]											=					ids_tensor([self.batch_size, self.seq_length]     ,      self.num_labels							)

													A__  :					Tuple											=					self.get_config()

													return config, input_ids, input_mask, token_labels


							def   _UpperCamelCase    (     self :  Union[str, Any]							):
													'''simple docstring'''





													return GPTNeoXConfig(
													    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     ,      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     ,      pad_token_id=self.pad_token_id     ,      )


							def   _UpperCamelCase    (     self :  List[str]							):
													'''simple docstring'''





													A__					,					A__					,					A__					,					A__  :					str											=					self.prepare_config_and_inputs()

													A__  :					Union[str, Any]											=					True

													return config, input_ids, input_mask, token_labels


							def   _UpperCamelCase    (     self :  Union[str, Any]     ,      snake_case :  Optional[int]     ,      snake_case :  List[str]     ,      snake_case :  int							):
													'''simple docstring'''





													A__  :					Any											=					GPTNeoXModel(config=snake_case							)
													model.to(snake_case							)
													model.eval()
													A__  :					int											=					model(snake_case     ,      attention_mask=snake_case							)
													A__  :					Optional[int]											=					model(snake_case							)
													self.parent.assertEqual(result.last_hidden_state.shape     ,      (self.batch_size, self.seq_length, self.hidden_size)							)


							def   _UpperCamelCase    (     self :  Union[str, Any]     ,      snake_case :  str     ,      snake_case :  Any     ,      snake_case :  Union[str, Any]							):
													'''simple docstring'''





													A__  :					int											=					True
													A__  :					str											=					GPTNeoXModel(snake_case							)
													model.to(snake_case							)
													model.eval()
													A__  :					Tuple											=					model(snake_case     ,      attention_mask=snake_case							)
													self.parent.assertEqual(result.last_hidden_state.shape     ,      (self.batch_size, self.seq_length, self.hidden_size)							)


							def   _UpperCamelCase    (     self :  Dict     ,      snake_case :  List[Any]     ,      snake_case :  str     ,      snake_case :  Optional[Any]     ,      snake_case :  Any							):
													'''simple docstring'''





													A__  :					Any											=					GPTNeoXForCausalLM(config=snake_case							)
													model.to(snake_case							)
													model.eval()
													A__  :					Tuple											=					model(snake_case     ,      attention_mask=snake_case     ,      labels=snake_case							)
													self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.seq_length, self.vocab_size)							)


							def   _UpperCamelCase    (     self :  List[str]     ,      snake_case :  Optional[Any]     ,      snake_case :  Optional[Any]     ,      snake_case :  Union[str, Any]     ,      snake_case :  Tuple							):
													'''simple docstring'''





													A__  :					int											=					self.num_labels
													A__  :					int											=					GPTNeoXForQuestionAnswering(snake_case							)
													model.to(snake_case							)
													model.eval()
													A__  :					Optional[Any]											=					model(snake_case     ,      attention_mask=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   _UpperCamelCase    (     self :  str     ,      snake_case :  Tuple     ,      snake_case :  int     ,      snake_case :  int     ,      snake_case :  Dict							):
													'''simple docstring'''





													A__  :					List[Any]											=					self.num_labels
													A__  :					Tuple											=					GPTNeoXForSequenceClassification(snake_case							)
													model.to(snake_case							)
													model.eval()
													A__  :					Any											=					ids_tensor([self.batch_size]     ,      self.type_sequence_label_size							)
													A__  :					List[str]											=					model(snake_case     ,      attention_mask=snake_case     ,      labels=snake_case							)
													self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.num_labels)							)


							def   _UpperCamelCase    (     self :  Any     ,      snake_case :  Union[str, Any]     ,      snake_case :  int     ,      snake_case :  Tuple     ,      snake_case :  Any							):
													'''simple docstring'''





													A__  :					Tuple											=					self.num_labels
													A__  :					Any											=					GPTNeoXForTokenClassification(snake_case							)
													model.to(snake_case							)
													model.eval()
													A__  :					Dict											=					model(snake_case     ,      attention_mask=snake_case     ,      labels=snake_case							)
													self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.seq_length, self.num_labels)							)


							def   _UpperCamelCase    (     self :  List[str]     ,      snake_case :  List[str]     ,      snake_case :  Tuple     ,      snake_case :  Any							):
													'''simple docstring'''





													A__  :					Optional[int]											=					True
													A__  :					Any											=					GPTNeoXForCausalLM(config=snake_case							)
													model.to(snake_case							)
													model.eval()

													# first forward pass
													A__  :					Tuple											=					model(snake_case     ,      attention_mask=snake_case     ,      use_cache=snake_case							)
													A__  :					str											=					outputs.past_key_values

													# create hypothetical multiple next token and extent to next_input_ids
													A__  :					Any											=					ids_tensor((self.batch_size, 3)     ,      config.vocab_size							)
													A__  :					Tuple											=					ids_tensor((self.batch_size, 3)     ,      vocab_size=2							)

													# append to next input_ids and
													A__  :					Any											=					torch.cat([input_ids, next_tokens]     ,      dim=-1							)
													A__  :					Any											=					torch.cat([input_mask, next_mask]     ,      dim=-1							)

													A__  :					Tuple											=					model(snake_case     ,      attention_mask=snake_case     ,      output_hidden_states=snake_case							)
													A__  :					List[Any]											=					output_from_no_past["""hidden_states"""][0]
													A__  :					List[str]											=					model(
													    snake_case     ,      attention_mask=snake_case     ,      past_key_values=snake_case     ,      output_hidden_states=snake_case     ,      )["""hidden_states"""][0]

													# select random slice
													A__  :					Tuple											=					ids_tensor((1,)     ,      output_from_past.shape[-1]							).item()
													A__  :					List[Any]											=					output_from_no_past[:, -3:, random_slice_idx].detach()
													A__  :					Any											=					output_from_past[:, :, random_slice_idx].detach()

													self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]							)

													# test that outputs are equal for slice
													self.parent.assertTrue(torch.allclose(snake_case     ,      snake_case     ,      atol=1e-3							)							)


							def   _UpperCamelCase    (     self :  str							):
													'''simple docstring'''





													A__  :					str											=					self.prepare_config_and_inputs()
													A__					,					A__					,					A__					,					A__  :					Dict											=					config_and_inputs
													A__  :					Optional[Any]											=					{"""input_ids""": input_ids, """attention_mask""": input_mask}
													return config, inputs_dict






@require_torch
class 							__SCREAMING_SNAKE_CASE  (			UpperCamelCase    ,						UpperCamelCase    ,						UpperCamelCase    ,						unittest.TestCase						):
							snake_case_       =							(
							    (
							        GPTNeoXModel,
							        GPTNeoXForCausalLM,
							        GPTNeoXForQuestionAnswering,
							        GPTNeoXForSequenceClassification,
							        GPTNeoXForTokenClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							snake_case_       =							(GPTNeoXForCausalLM,) if is_torch_available() else ()
							snake_case_       =							(
							    {
							        'feature-extraction': GPTNeoXModel,
							        'question-answering': GPTNeoXForQuestionAnswering,
							        'text-classification': GPTNeoXForSequenceClassification,
							        'text-generation': GPTNeoXForCausalLM,
							        'token-classification': GPTNeoXForTokenClassification,
							        'zero-shot': GPTNeoXForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							snake_case_       =							False
							snake_case_       =							False
							snake_case_       =							False
							snake_case_       =							False


							def   _UpperCamelCase    (     self :  Union[str, Any]							):
													'''simple docstring'''





													A__  :					Any											=					GPTNeoXModelTester(self							)
													A__  :					Any											=					ConfigTester(self     ,      config_class=snake_case     ,      hidden_size=64     ,      num_attention_heads=8							)


							def   _UpperCamelCase    (     self :  Union[str, Any]							):
													'''simple docstring'''





													self.config_tester.run_common_tests()


							def   _UpperCamelCase    (     self :  Any							):
													'''simple docstring'''





													A__					,					A__					,					A__					,					A__  :					Any											=					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(snake_case     ,      snake_case     ,      snake_case							)


							def   _UpperCamelCase    (     self :  Dict							):
													'''simple docstring'''





													A__					,					A__					,					A__					,					A__  :					Dict											=					self.model_tester.prepare_config_and_inputs_for_decoder()
													self.model_tester.create_and_check_model_as_decoder(snake_case     ,      snake_case     ,      snake_case							)


							def   _UpperCamelCase    (     self :  Dict							):
													'''simple docstring'''





													A__					,					A__					,					A__					,					A__  :					List[str]											=					self.model_tester.prepare_config_and_inputs_for_decoder()

													A__  :					Optional[Any]											=					None

													self.model_tester.create_and_check_model_as_decoder(snake_case     ,      snake_case     ,      snake_case							)


							def   _UpperCamelCase    (     self :  str							):
													'''simple docstring'''





													A__					,					A__					,					A__					,					A__  :					Union[str, Any]											=					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_decoder_model_past_large_inputs(snake_case     ,      snake_case     ,      snake_case							)


							def   _UpperCamelCase    (     self :  Optional[Any]							):
													'''simple docstring'''





													A__  :					Optional[Any]											=					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_causal_lm(*snake_case							)


							def   _UpperCamelCase    (     self :  List[str]							):
													'''simple docstring'''





													A__  :					Any											=					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_question_answering(*snake_case							)


							def   _UpperCamelCase    (     self :  str							):
													'''simple docstring'''





													A__  :					Optional[Any]											=					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_sequence_classification(*snake_case							)


							def   _UpperCamelCase    (     self :  str							):
													'''simple docstring'''





													A__  :					List[str]											=					self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_token_classification(*snake_case							)


							@unittest.skip(reason="""Feed forward chunking is not implemented"""							)
							def   _UpperCamelCase    (     self :  List[Any]							):
													'''simple docstring'''





													pass


							@parameterized.expand([("""linear""",), ("""dynamic""",)]							)
							def   _UpperCamelCase    (     self :  Optional[Any]     ,      snake_case :  Optional[Any]							):
													'''simple docstring'''





													A__					,					A__  :					int											=					self.model_tester.prepare_config_and_inputs_for_common()
													A__  :					List[Any]											=					ids_tensor([1, 10]     ,      config.vocab_size							)
													A__  :					str											=					ids_tensor([1, int(config.max_position_embeddings * 1.5							)]     ,      config.vocab_size							)

													set_seed(42							)  # Fixed seed at init time so the two models get the same random weights
													A__  :					Union[str, Any]											=					GPTNeoXModel(snake_case							)
													original_model.to(snake_case							)
													original_model.eval()
													A__  :					Optional[int]											=					original_model(snake_case							).last_hidden_state
													A__  :					List[str]											=					original_model(snake_case							).last_hidden_state

													set_seed(42							)  # Fixed seed at init time so the two models get the same random weights
													A__  :					Optional[int]											=					{"""type""": scaling_type, """factor""": 10.0}
													A__  :					Optional[int]											=					GPTNeoXModel(snake_case							)
													scaled_model.to(snake_case							)
													scaled_model.eval()
													A__  :					List[str]											=					scaled_model(snake_case							).last_hidden_state
													A__  :					Tuple											=					scaled_model(snake_case							).last_hidden_state

													# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
													# maximum sequence length, so the outputs for the short input should match.
													if scaling_type == "dynamic":
																			self.assertTrue(torch.allclose(snake_case     ,      snake_case     ,      atol=1e-5							)							)
													else:
																			self.assertFalse(torch.allclose(snake_case     ,      snake_case     ,      atol=1e-5							)							)

													# The output should be different for long inputs
													self.assertFalse(torch.allclose(snake_case     ,      snake_case     ,      atol=1e-5							)							)






@require_torch
class 							__SCREAMING_SNAKE_CASE  (			unittest.TestCase						):


							@slow
							def   _UpperCamelCase    (     self :  Tuple							):
													'''simple docstring'''





													A__  :					Any											=					AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped"""							)
													for checkpointing in [True, False]:
																			A__  :					Optional[Any]											=					GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped"""							)

																			if checkpointing:
																									model.gradient_checkpointing_enable()
																			else:
																									model.gradient_checkpointing_disable()
																			model.to(snake_case							)

																			A__  :					Optional[Any]											=					tokenizer("""My favorite food is"""     ,      return_tensors="""pt"""							).to(snake_case							)
																			# The hub repo. is updated on 2023-04-04, resulting in poor outputs.
																			# See: https://github.com/huggingface/transformers/pull/24193
																			A__  :					Union[str, Any]											=					"""My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure"""

																			A__  :					Tuple											=					model.generate(**snake_case     ,      do_sample=snake_case     ,      max_new_tokens=20							)
																			A__  :					Tuple											=					tokenizer.batch_decode(snake_case							)[0]

																			self.assertEqual(snake_case     ,      snake_case							)






