"""simple docstring"""




import unittest
from unittest.util import safe_repr

from transformers import AutoTokenizer, RwkvConfig, is_torch_available
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, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    RWKV_PRETRAINED_MODEL_ARCHIVE_LIST,
					    RwkvForCausalLM,
					    RwkvModel,
					)
					from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_0
else:
					UpperCAmelCase       :    List[Any]									=			False

class        __SCREAMING_SNAKE_CASE     :







				def __init__(    self    :Any      ,__UpperCAmelCase    :Optional[int]      ,__UpperCAmelCase    :Optional[Any]=14      ,__UpperCAmelCase    :int=7      ,__UpperCAmelCase    :Optional[Any]=True      ,__UpperCAmelCase    :List[str]=False      ,__UpperCAmelCase    :List[Any]=True      ,__UpperCAmelCase    :Optional[Any]=True      ,__UpperCAmelCase    :Optional[int]=True      ,__UpperCAmelCase    :Any=99      ,__UpperCAmelCase    :Any=32      ,__UpperCAmelCase    :List[Any]=5      ,__UpperCAmelCase    :Any=37      ,__UpperCAmelCase    :Tuple="gelu"      ,__UpperCAmelCase    :str=0.1      ,__UpperCAmelCase    :str=0.1      ,__UpperCAmelCase    :Dict=5_12      ,__UpperCAmelCase    :Dict=16      ,__UpperCAmelCase    :Optional[int]=2      ,__UpperCAmelCase    :Optional[Any]=3      ,__UpperCAmelCase    :List[str]=4      ,__UpperCAmelCase    :Optional[int]=None      ,)      ->					int:




									"""simple docstring"""



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







				def   lowercase_		(    self    :str  )      ->					int:




									"""simple docstring"""



									return RwkvConfig.from_pretrained('''sgugger/rwkv-4-pile-7b'''  )







				def   lowercase_		(    self    :Union[str, Any]      ,__UpperCAmelCase    :Dict=False      ,__UpperCAmelCase    :Dict=False      ,__UpperCAmelCase    :int=False  )      ->					Optional[int]:




									"""simple docstring"""



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

									lowerCamelCase__		:   int  				=					None
									if self.use_input_mask:
														lowerCamelCase__		:   Optional[int]  				=					random_attention_mask([self.batch_size, self.seq_length]  )

									lowerCamelCase__		:   Any  				=					None
									if self.use_token_type_ids:
														lowerCamelCase__		:   str  				=					ids_tensor([self.batch_size, self.seq_length]      ,self.type_vocab_size  )

									lowerCamelCase__		:   List[Any]  				=					None
									if self.use_mc_token_ids:
														lowerCamelCase__		:   Union[str, Any]  				=					ids_tensor([self.batch_size, self.num_choices]      ,self.seq_length  )

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

									lowerCamelCase__		:   str  				=					self.get_config(
									    gradient_checkpointing=__UpperCAmelCase      ,scale_attn_by_inverse_layer_idx=__UpperCAmelCase      ,reorder_and_upcast_attn=__UpperCAmelCase      ,)

									return (
									    config,
									    input_ids,
									    input_mask,
									    None,
									    token_type_ids,
									    mc_token_ids,
									    sequence_labels,
									    token_labels,
									    choice_labels,
									)







				def   lowercase_		(    self    :int      ,__UpperCAmelCase    :Optional[int]=False      ,__UpperCAmelCase    :List[Any]=False      ,__UpperCAmelCase    :Optional[Any]=False  )      ->					Union[str, Any]:




									"""simple docstring"""



									return RwkvConfig(
									    vocab_size=self.vocab_size      ,hidden_size=self.hidden_size      ,num_hidden_layers=self.num_hidden_layers      ,intermediate_size=self.intermediate_size      ,activation_function=self.hidden_act      ,resid_pdrop=self.hidden_dropout_prob      ,attn_pdrop=self.attention_probs_dropout_prob      ,n_positions=self.max_position_embeddings      ,type_vocab_size=self.type_vocab_size      ,use_cache=__UpperCAmelCase      ,bos_token_id=self.bos_token_id      ,eos_token_id=self.eos_token_id      ,pad_token_id=self.pad_token_id      ,gradient_checkpointing=__UpperCAmelCase      ,scale_attn_by_inverse_layer_idx=__UpperCAmelCase      ,reorder_and_upcast_attn=__UpperCAmelCase      ,)







				def   lowercase_		(    self    :List[Any]  )      ->					int:




									"""simple docstring"""



									lowerCamelCase__		:   int  				=					self.get_config()
									lowerCamelCase__		:   Union[str, Any]  				=					3_00
									return config







				def   lowercase_		(    self    :Union[str, Any]  )      ->					List[str]:




									"""simple docstring"""



									(
									    (
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						
									)		:   Dict  				=					self.prepare_config_and_inputs()

									lowerCamelCase__		:   Dict  				=					floats_tensor([self.batch_size, self.seq_length, self.hidden_size]  )
									lowerCamelCase__		:   Optional[Any]  				=					ids_tensor([self.batch_size, self.seq_length]      ,vocab_size=2  )

									return (
									    config,
									    input_ids,
									    input_mask,
									    head_mask,
									    token_type_ids,
									    sequence_labels,
									    token_labels,
									    choice_labels,
									    encoder_hidden_states,
									    encoder_attention_mask,
									)







				def   lowercase_		(    self    :str      ,__UpperCAmelCase    :List[str]      ,__UpperCAmelCase    :List[Any]      ,__UpperCAmelCase    :List[str]      ,__UpperCAmelCase    :str      ,__UpperCAmelCase    :Union[str, Any]      ,*__UpperCAmelCase    :List[Any]  )      ->					Any:




									"""simple docstring"""



									lowerCamelCase__		:   Dict  				=					True
									lowerCamelCase__		:   Optional[int]  				=					RwkvModel(config=__UpperCAmelCase  )
									model.to(__UpperCAmelCase  )
									model.eval()

									lowerCamelCase__		:   Tuple  				=					model(__UpperCAmelCase  )

									self.parent.assertEqual(result.last_hidden_state.shape      ,(self.batch_size, self.seq_length, self.hidden_size)  )
									self.parent.assertEqual(len(result.hidden_states  )      ,config.num_hidden_layers + 1  )







				def   lowercase_		(    self    :Dict      ,__UpperCAmelCase    :List[str]      ,__UpperCAmelCase    :List[Any]      ,__UpperCAmelCase    :List[Any]      ,__UpperCAmelCase    :Optional[int]      ,__UpperCAmelCase    :List[str]      ,*__UpperCAmelCase    :List[str]  )      ->					Dict:




									"""simple docstring"""



									lowerCamelCase__		:   Dict  				=					RwkvForCausalLM(__UpperCAmelCase  )
									model.to(__UpperCAmelCase  )
									model.eval()

									lowerCamelCase__		:   Optional[int]  				=					model(__UpperCAmelCase      ,labels=__UpperCAmelCase  )
									self.parent.assertEqual(result.loss.shape      ,()  )
									self.parent.assertEqual(result.logits.shape      ,(self.batch_size, self.seq_length, self.vocab_size)  )







				def   lowercase_		(    self    :int      ,__UpperCAmelCase    :int      ,__UpperCAmelCase    :Union[str, Any]      ,__UpperCAmelCase    :Optional[Any]      ,__UpperCAmelCase    :str      ,__UpperCAmelCase    :Union[str, Any]      ,*__UpperCAmelCase    :Optional[Any]  )      ->					Optional[Any]:




									"""simple docstring"""



									lowerCamelCase__		:   int  				=					RwkvModel(config=__UpperCAmelCase  )
									model.to(__UpperCAmelCase  )
									model.eval()

									lowerCamelCase__		:   str  				=					model(__UpperCAmelCase  )
									lowerCamelCase__		:   Optional[Any]  				=					outputs.last_hidden_state

									lowerCamelCase__		:   Optional[int]  				=					model(input_ids[:, :2]  )
									lowerCamelCase__		:   Tuple  				=					outputs.last_hidden_state

									# Using the state computed on the first inputs, we will get the same output
									lowerCamelCase__		:   int  				=					model(input_ids[:, 2:]      ,state=outputs.state  )
									lowerCamelCase__		:   Union[str, Any]  				=					outputs.last_hidden_state

									self.parent.assertTrue(torch.allclose(torch.cat([output_one, output_two]      ,dim=1  )      ,__UpperCAmelCase      ,atol=1E-5  )  )







				def   lowercase_		(    self    :List[str]      ,__UpperCAmelCase    :List[Any]      ,__UpperCAmelCase    :str      ,__UpperCAmelCase    :List[str]      ,__UpperCAmelCase    :Any      ,__UpperCAmelCase    :str      ,*__UpperCAmelCase    :List[Any]      ,__UpperCAmelCase    :Union[str, Any]=False  )      ->					Tuple:




									"""simple docstring"""



									lowerCamelCase__		:   int  				=					RwkvForCausalLM(__UpperCAmelCase  )
									model.to(__UpperCAmelCase  )
									if gradient_checkpointing:
														model.gradient_checkpointing_enable()

									lowerCamelCase__		:   Optional[int]  				=					model(__UpperCAmelCase      ,labels=__UpperCAmelCase  )
									self.parent.assertEqual(result.loss.shape      ,()  )
									self.parent.assertEqual(result.logits.shape      ,(self.batch_size, self.seq_length, self.vocab_size)  )
									result.loss.backward()







				def   lowercase_		(    self    :Optional[int]  )      ->					Optional[Any]:




									"""simple docstring"""



									lowerCamelCase__		:   Any  				=					self.prepare_config_and_inputs()

									(
									    (
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						(
									    lowerCamelCase__
									)				,						
									)		:   List[str]  				=					config_and_inputs

									lowerCamelCase__		:   List[Any]  				=					{'''input_ids''': input_ids}

									return config, inputs_dict





@unittest.skipIf(
    not is_torch_greater_or_equal_than_2_0						,       reason='''See https://github.com/huggingface/transformers/pull/24204'''							)
@require_torch
class        __SCREAMING_SNAKE_CASE     (   _lowerCAmelCase						,       _lowerCAmelCase						,       _lowerCAmelCase						,       unittest.TestCase							):
				UpperCAmelCase	=      (RwkvModel, RwkvForCausalLM) if is_torch_available() else ()
				UpperCAmelCase	=      (
				    {'''feature-extraction''': RwkvModel, '''text-generation''': RwkvForCausalLM} if is_torch_available() else {}
				)
				# all_generative_model_classes = (RwkvForCausalLM,) if is_torch_available() else ()
				UpperCAmelCase	=      False
				UpperCAmelCase	=      False
				UpperCAmelCase	=      False
				UpperCAmelCase	=      False
				UpperCAmelCase	=      False  # Rwkv does not support head masking







				def   lowercase_		(    self    :Tuple  )      ->					Tuple:




									"""simple docstring"""



									lowerCamelCase__		:   Union[str, Any]  				=					RwkvModelTester(self  )
									lowerCamelCase__		:   int  				=					ConfigTester(
									    self      ,config_class=__UpperCAmelCase      ,n_embd=37      ,common_properties=['''hidden_size''', '''num_hidden_layers''']  )







				def   lowercase_		(    self    :Union[str, Any]      ,__UpperCAmelCase    :int      ,__UpperCAmelCase    :str      ,__UpperCAmelCase    :Dict=None  )      ->					List[str]:




									"""simple docstring"""



									if isinstance(__UpperCAmelCase      ,torch.Tensor  ):
														lowerCamelCase__				,						lowerCamelCase__		:   int  				=					member.max().item(), member.min().item()
									elif isinstance(__UpperCAmelCase      ,__UpperCAmelCase  ) or isinstance(__UpperCAmelCase      ,__UpperCAmelCase  ):
														lowerCamelCase__				,						lowerCamelCase__		:   List[Any]  				=					max(__UpperCAmelCase  ), min(__UpperCAmelCase  )

									if not isinstance(__UpperCAmelCase      ,__UpperCAmelCase  ):
														raise TypeError('''container should be a list or tuple'''  )
									elif len(__UpperCAmelCase  ) != 2:
														raise ValueError('''container should have 2 elements'''  )

									lowerCamelCase__				,						lowerCamelCase__		:   Tuple  				=					container

									lowerCamelCase__		:   List[Any]  				=					(min_value >= expected_min) and (max_value <= expected_max)

									if not is_inside_interval:
														lowerCamelCase__		:   Dict  				=					'''%s not found in %s''' % (safe_repr(__UpperCAmelCase  ), safe_repr(__UpperCAmelCase  ))
														self.fail(self._formatMessage(__UpperCAmelCase      ,__UpperCAmelCase  )  )







				def   lowercase_		(    self    :List[str]  )      ->					str:




									"""simple docstring"""



									self.config_tester.run_common_tests()







				def   lowercase_		(    self    :Optional[Any]  )      ->					Optional[Any]:




									"""simple docstring"""



									lowerCamelCase__		:   Any  				=					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_rwkv_model(*__UpperCAmelCase  )







				def   lowercase_		(    self    :Dict  )      ->					Tuple:




									"""simple docstring"""



									lowerCamelCase__		:   List[Any]  				=					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_causl_lm(*__UpperCAmelCase  )







				def   lowercase_		(    self    :Dict  )      ->					Union[str, Any]:




									"""simple docstring"""



									lowerCamelCase__		:   List[Any]  				=					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_state_equivalency(*__UpperCAmelCase  )







				def   lowercase_		(    self    :Any  )      ->					List[Any]:




									"""simple docstring"""



									lowerCamelCase__				,						lowerCamelCase__		:   Tuple  				=					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
														lowerCamelCase__		:   List[str]  				=					model_class(config=__UpperCAmelCase  )
														for name, param in model.named_parameters():
																			if "time_decay" in name:
																								if param.requires_grad:
																													self.assertTrue(param.data.max().item() == 3.0  )
																													self.assertTrue(param.data.min().item() == -5.0  )
																			elif "time_first" in name:
																								if param.requires_grad:
																													# check if it's a ones like
																													self.assertTrue(torch.allclose(param.data      ,torch.ones_like(param.data  )      ,atol=1E-5      ,rtol=1E-5  )  )
																			elif any(x in name for x in ['''time_mix_key''', '''time_mix_receptance''']  ):
																								if param.requires_grad:
																													self.assertInterval(
																													    param.data      ,[0.0, 1.0]      ,msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""      ,)
																			elif "time_mix_value" in name:
																								if param.requires_grad:
																													self.assertInterval(
																													    param.data      ,[0.0, 1.3]      ,msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""      ,)







				def   lowercase_		(    self    :List[Any]  )      ->					Dict:




									"""simple docstring"""



									lowerCamelCase__				,						lowerCamelCase__		:   int  				=					self.model_tester.prepare_config_and_inputs_for_common()
									lowerCamelCase__		:   Tuple  				=					True

									lowerCamelCase__		:   int  				=					getattr(self.model_tester      ,'''seq_length'''      ,__UpperCAmelCase  )

									for model_class in self.all_model_classes:
														lowerCamelCase__		:   Tuple  				=					True
														lowerCamelCase__		:   Optional[Any]  				=					False
														lowerCamelCase__		:   Dict  				=					True
														lowerCamelCase__		:   List[str]  				=					model_class(__UpperCAmelCase  )
														model.to(__UpperCAmelCase  )
														model.eval()

														lowerCamelCase__		:   str  				=					self._prepare_for_class(__UpperCAmelCase      ,__UpperCAmelCase  )
														lowerCamelCase__		:   Tuple  				=					inputs['''input_ids'''].shape[0]
														with torch.no_grad():
																			lowerCamelCase__		:   int  				=					model(**__UpperCAmelCase  )
														lowerCamelCase__		:   Optional[Any]  				=					outputs.attentions
														self.assertEqual(len(__UpperCAmelCase  )      ,self.model_tester.num_hidden_layers  )

														# check that output_attentions also work using config
														del inputs_dict["output_attentions"]
														lowerCamelCase__		:   Optional[int]  				=					True
														lowerCamelCase__		:   Dict  				=					model_class(__UpperCAmelCase  )
														model.to(__UpperCAmelCase  )
														model.eval()

														lowerCamelCase__		:   List[str]  				=					self._prepare_for_class(__UpperCAmelCase      ,__UpperCAmelCase  )
														lowerCamelCase__		:   Optional[Any]  				=					inputs['''input_ids'''].shape[0]
														with torch.no_grad():
																			lowerCamelCase__		:   Tuple  				=					model(**__UpperCAmelCase  )
														lowerCamelCase__		:   List[str]  				=					outputs.attentions
														self.assertEqual(len(__UpperCAmelCase  )      ,self.model_tester.num_hidden_layers  )

														self.assertListEqual(
														    list(attentions[0].shape[-3:]  )      ,[batch_size, seq_len, config.hidden_size]      ,)
														lowerCamelCase__		:   Tuple  				=					len(__UpperCAmelCase  )

														# Check attention is always last and order is fine
														lowerCamelCase__		:   List[str]  				=					True
														lowerCamelCase__		:   int  				=					True
														lowerCamelCase__		:   str  				=					model_class(__UpperCAmelCase  )
														model.to(__UpperCAmelCase  )
														model.eval()

														lowerCamelCase__		:   int  				=					self._prepare_for_class(__UpperCAmelCase      ,__UpperCAmelCase  )
														lowerCamelCase__		:   Union[str, Any]  				=					inputs['''input_ids'''].shape[0]
														with torch.no_grad():
																			lowerCamelCase__		:   Dict  				=					model(**__UpperCAmelCase  )

														lowerCamelCase__		:   str  				=					1
														self.assertEqual(out_len + added_hidden_states      ,len(__UpperCAmelCase  )  )

														lowerCamelCase__		:   List[str]  				=					outputs.attentions

														self.assertEqual(len(__UpperCAmelCase  )      ,self.model_tester.num_hidden_layers  )
														self.assertListEqual(
														    list(self_attentions[0].shape[-3:]  )      ,[batch_size, seq_len, config.hidden_size]      ,)







				@slow
				def   lowercase_		(    self    :Optional[int]  )      ->					Any:




									"""simple docstring"""



									for model_name in RWKV_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowerCamelCase__		:   Dict  				=					RwkvModel.from_pretrained(__UpperCAmelCase  )
														self.assertIsNotNone(__UpperCAmelCase  )





@unittest.skipIf(
    not is_torch_greater_or_equal_than_2_0						,       reason='''See https://github.com/huggingface/transformers/pull/24204'''							)
@slow
class        __SCREAMING_SNAKE_CASE     (   unittest.TestCase							):







				def   lowercase_		(    self    :Optional[int]  )      ->					Union[str, Any]:




									"""simple docstring"""



									lowerCamelCase__		:   int  				=					'''RWKV/rwkv-4-169m-pile'''
									lowerCamelCase__		:   Dict  				=					AutoTokenizer.from_pretrained(self.model_id  )







				def   lowercase_		(    self    :List[Any]  )      ->					List[Any]:




									"""simple docstring"""



									lowerCamelCase__		:   Optional[Any]  				=					'''Hello my name is Jasmine and I am a newbie to the'''
									lowerCamelCase__		:   Any  				=					RwkvForCausalLM.from_pretrained(self.model_id  ).to(__UpperCAmelCase  )

									lowerCamelCase__		:   Tuple  				=					self.tokenizer('''Hello my name is'''      ,return_tensors='''pt'''  ).input_ids.to(__UpperCAmelCase  )
									lowerCamelCase__		:   Optional[int]  				=					model.generate(__UpperCAmelCase      ,max_new_tokens=10  )
									lowerCamelCase__		:   Union[str, Any]  				=					self.tokenizer.decode(output[0].tolist()  )

									self.assertEqual(__UpperCAmelCase      ,__UpperCAmelCase  )







				def   lowercase_		(    self    :str  )      ->					Optional[Any]:




									"""simple docstring"""



									lowerCamelCase__		:   Tuple  				=					'''Hello my name is Jasmine and I am a newbie to the'''

									lowerCamelCase__		:   Optional[Any]  				=					self.tokenizer('''Hello my name is'''      ,return_tensors='''pt'''  ).input_ids.to(__UpperCAmelCase  )
									lowerCamelCase__		:   List[Any]  				=					RwkvForCausalLM.from_pretrained(self.model_id      ,torch_dtype=torch.bfloataa  ).to(__UpperCAmelCase  )

									lowerCamelCase__		:   Tuple  				=					model.generate(__UpperCAmelCase      ,max_new_tokens=10  )
									lowerCamelCase__		:   Union[str, Any]  				=					self.tokenizer.decode(output[0].tolist()  )

									self.assertEqual(__UpperCAmelCase      ,__UpperCAmelCase  )







"""simple docstring"""




import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


UpperCAmelCase       :    str									=			logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCAmelCase       :    List[str]									=			"\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = \"a shark\"\n\n        >>> images = pipe(\n        ...     prompt,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")\n        ```\n"

@dataclass
class        __SCREAMING_SNAKE_CASE     (   _lowerCAmelCase							):
				UpperCAmelCase	=      42





class        __SCREAMING_SNAKE_CASE     (   _lowerCAmelCase							):







				def __init__(    self    :Optional[Any]      ,__UpperCAmelCase    :PriorTransformer      ,__UpperCAmelCase    :CLIPTextModelWithProjection      ,__UpperCAmelCase    :CLIPTokenizer      ,__UpperCAmelCase    :HeunDiscreteScheduler      ,__UpperCAmelCase    :ShapERenderer      ,)      ->					List[Any]:




									"""simple docstring"""



									super().__init__()

									self.register_modules(
									    prior=__UpperCAmelCase      ,text_encoder=__UpperCAmelCase      ,tokenizer=__UpperCAmelCase      ,scheduler=__UpperCAmelCase      ,renderer=__UpperCAmelCase      ,)







				def   lowercase_		(    self    :Any      ,__UpperCAmelCase    :Tuple      ,__UpperCAmelCase    :Dict      ,__UpperCAmelCase    :Optional[int]      ,__UpperCAmelCase    :Dict      ,__UpperCAmelCase    :Any      ,__UpperCAmelCase    :Dict  )      ->					Optional[Any]:




									"""simple docstring"""



									if latents is None:
														lowerCamelCase__		:   Optional[Any]  				=					randn_tensor(__UpperCAmelCase      ,generator=__UpperCAmelCase      ,device=__UpperCAmelCase      ,dtype=__UpperCAmelCase  )
									else:
														if latents.shape != shape:
																			raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""  )
														lowerCamelCase__		:   Optional[Any]  				=					latents.to(__UpperCAmelCase  )

									lowerCamelCase__		:   Dict  				=					latents * scheduler.init_noise_sigma
									return latents







				def   lowercase_		(    self    :Dict      ,__UpperCAmelCase    :List[Any]=0  )      ->					str:




									"""simple docstring"""



									if is_accelerate_available():
														from accelerate import cpu_offload
									else:
														raise ImportError('''Please install accelerate via `pip install accelerate`'''  )

									lowerCamelCase__		:   List[str]  				=					torch.device(F"""cuda:{gpu_id}"""  )

									lowerCamelCase__		:   Optional[int]  				=					[self.text_encoder, self.prior]
									for cpu_offloaded_model in models:
														if cpu_offloaded_model is not None:
																			cpu_offload(__UpperCAmelCase      ,__UpperCAmelCase  )







				def   lowercase_		(    self    :int      ,__UpperCAmelCase    :Dict=0  )      ->					Dict:




									"""simple docstring"""



									if is_accelerate_available() and is_accelerate_version('''>='''      ,'''0.17.0.dev0'''  ):
														from accelerate import cpu_offload_with_hook
									else:
														raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'''  )

									lowerCamelCase__		:   List[Any]  				=					torch.device(F"""cuda:{gpu_id}"""  )

									if self.device.type != "cpu":
														self.to('''cpu'''      ,silence_dtype_warnings=__UpperCAmelCase  )
														torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

									lowerCamelCase__		:   List[Any]  				=					None
									for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
														lowerCamelCase__				,						lowerCamelCase__		:   Tuple  				=					cpu_offload_with_hook(__UpperCAmelCase      ,__UpperCAmelCase      ,prev_module_hook=__UpperCAmelCase  )

									if self.safety_checker is not None:
														lowerCamelCase__				,						lowerCamelCase__		:   Any  				=					cpu_offload_with_hook(self.safety_checker      ,__UpperCAmelCase      ,prev_module_hook=__UpperCAmelCase  )

									# We'll offload the last model manually.
									lowerCamelCase__		:   Dict  				=					hook







				@property
				def   lowercase_		(    self    :Dict  )      ->					Optional[Any]:




									"""simple docstring"""



									if self.device != torch.device('''meta'''  ) or not hasattr(self.text_encoder      ,'''_hf_hook'''  ):
														return self.device
									for module in self.text_encoder.modules():
														if (
														    hasattr(__UpperCAmelCase      ,'''_hf_hook'''  )
														    and hasattr(module._hf_hook      ,'''execution_device'''  )
														    and module._hf_hook.execution_device is not None
														):
																			return torch.device(module._hf_hook.execution_device  )
									return self.device







				def   lowercase_		(    self    :Tuple      ,__UpperCAmelCase    :Optional[int]      ,__UpperCAmelCase    :Optional[Any]      ,__UpperCAmelCase    :Any      ,__UpperCAmelCase    :Optional[Any]      ,)      ->					str:




									"""simple docstring"""



									len(__UpperCAmelCase  ) if isinstance(__UpperCAmelCase      ,__UpperCAmelCase  ) else 1

									# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
									lowerCamelCase__		:   Optional[int]  				=					0
									# get prompt text embeddings
									lowerCamelCase__		:   Union[str, Any]  				=					self.tokenizer(
									    __UpperCAmelCase      ,padding='''max_length'''      ,max_length=self.tokenizer.model_max_length      ,truncation=__UpperCAmelCase      ,return_tensors='''pt'''      ,)
									lowerCamelCase__		:   Union[str, Any]  				=					text_inputs.input_ids
									lowerCamelCase__		:   Any  				=					self.tokenizer(__UpperCAmelCase      ,padding='''longest'''      ,return_tensors='''pt'''  ).input_ids

									if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__UpperCAmelCase      ,__UpperCAmelCase  ):
														lowerCamelCase__		:   List[str]  				=					self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]  )
														logger.warning(
														    '''The following part of your input was truncated because CLIP can only handle sequences up to'''
														    F""" {self.tokenizer.model_max_length} tokens: {removed_text}"""  )

									lowerCamelCase__		:   Optional[int]  				=					self.text_encoder(text_input_ids.to(__UpperCAmelCase  )  )
									lowerCamelCase__		:   List[Any]  				=					text_encoder_output.text_embeds

									lowerCamelCase__		:   Optional[Any]  				=					prompt_embeds.repeat_interleave(__UpperCAmelCase      ,dim=0  )
									# in Shap-E it normalize the prompt_embeds and then later rescale it
									lowerCamelCase__		:   Union[str, Any]  				=					prompt_embeds / torch.linalg.norm(__UpperCAmelCase      ,dim=-1      ,keepdim=__UpperCAmelCase  )

									if do_classifier_free_guidance:
														lowerCamelCase__		:   Any  				=					torch.zeros_like(__UpperCAmelCase  )

														# For classifier free guidance, we need to do two forward passes.
														# Here we concatenate the unconditional and text embeddings into a single batch
														# to avoid doing two forward passes
														lowerCamelCase__		:   Optional[int]  				=					torch.cat([negative_prompt_embeds, prompt_embeds]  )

									# Rescale the features to have unit variance
									lowerCamelCase__		:   Optional[int]  				=					math.sqrt(prompt_embeds.shape[1]  ) * prompt_embeds

									return prompt_embeds







				@torch.no_grad()
				@replace_example_docstring(__UpperCAmelCase  )
				def __call__(    self    :Any      ,__UpperCAmelCase    :str      ,__UpperCAmelCase    :int = 1      ,__UpperCAmelCase    :int = 25      ,__UpperCAmelCase    :Optional[Union[torch.Generator, List[torch.Generator]]] = None      ,__UpperCAmelCase    :Optional[torch.FloatTensor] = None      ,__UpperCAmelCase    :float = 4.0      ,__UpperCAmelCase    :int = 64      ,__UpperCAmelCase    :Optional[str] = "pil"      ,__UpperCAmelCase    :bool = True      ,)      ->					Tuple:




									"""simple docstring"""



									if isinstance(__UpperCAmelCase      ,__UpperCAmelCase  ):
														lowerCamelCase__		:   Union[str, Any]  				=					1
									elif isinstance(__UpperCAmelCase      ,__UpperCAmelCase  ):
														lowerCamelCase__		:   Any  				=					len(__UpperCAmelCase  )
									else:
														raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(__UpperCAmelCase  )}"""  )

									lowerCamelCase__		:   Optional[Any]  				=					self._execution_device

									lowerCamelCase__		:   List[Any]  				=					batch_size * num_images_per_prompt

									lowerCamelCase__		:   Optional[int]  				=					guidance_scale > 1.0
									lowerCamelCase__		:   Tuple  				=					self._encode_prompt(__UpperCAmelCase      ,__UpperCAmelCase      ,__UpperCAmelCase      ,__UpperCAmelCase  )

									# prior

									self.scheduler.set_timesteps(__UpperCAmelCase      ,device=__UpperCAmelCase  )
									lowerCamelCase__		:   str  				=					self.scheduler.timesteps

									lowerCamelCase__		:   Dict  				=					self.prior.config.num_embeddings
									lowerCamelCase__		:   Optional[Any]  				=					self.prior.config.embedding_dim

									lowerCamelCase__		:   int  				=					self.prepare_latents(
									    (batch_size, num_embeddings * embedding_dim)      ,prompt_embeds.dtype      ,__UpperCAmelCase      ,__UpperCAmelCase      ,__UpperCAmelCase      ,self.scheduler      ,)

									# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
									lowerCamelCase__		:   Tuple  				=					latents.reshape(latents.shape[0]      ,__UpperCAmelCase      ,__UpperCAmelCase  )

									for i, t in enumerate(self.progress_bar(__UpperCAmelCase  )  ):
														# expand the latents if we are doing classifier free guidance
														lowerCamelCase__		:   Optional[Any]  				=					torch.cat([latents] * 2  ) if do_classifier_free_guidance else latents
														lowerCamelCase__		:   List[Any]  				=					self.scheduler.scale_model_input(__UpperCAmelCase      ,__UpperCAmelCase  )

														lowerCamelCase__		:   Dict  				=					self.prior(
														    __UpperCAmelCase      ,timestep=__UpperCAmelCase      ,proj_embedding=__UpperCAmelCase      ,).predicted_image_embedding

														# remove the variance
														lowerCamelCase__				,						lowerCamelCase__		:   Optional[Any]  				=					noise_pred.split(
														    scaled_model_input.shape[2]      ,dim=2  )  # batch_size, num_embeddings, embedding_dim

														if do_classifier_free_guidance is not None:
																			lowerCamelCase__				,						lowerCamelCase__		:   Dict  				=					noise_pred.chunk(2  )
																			lowerCamelCase__		:   List[str]  				=					noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

														lowerCamelCase__		:   Union[str, Any]  				=					self.scheduler.step(
														    __UpperCAmelCase      ,timestep=__UpperCAmelCase      ,sample=__UpperCAmelCase      ,).prev_sample

									if output_type == "latent":
														return ShapEPipelineOutput(images=__UpperCAmelCase  )

									lowerCamelCase__		:   List[Any]  				=					[]
									for i, latent in enumerate(__UpperCAmelCase  ):
														lowerCamelCase__		:   Tuple  				=					self.renderer.decode(
														    latent[None, :]      ,__UpperCAmelCase      ,size=__UpperCAmelCase      ,ray_batch_size=40_96      ,n_coarse_samples=64      ,n_fine_samples=1_28      ,)
														images.append(__UpperCAmelCase  )

									lowerCamelCase__		:   Union[str, Any]  				=					torch.stack(__UpperCAmelCase  )

									if output_type not in ["np", "pil"]:
														raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}"""  )

									lowerCamelCase__		:   Optional[int]  				=					images.cpu().numpy()

									if output_type == "pil":
														lowerCamelCase__		:   Optional[Any]  				=					[self.numpy_to_pil(__UpperCAmelCase  ) for image in images]

									# Offload last model to CPU
									if hasattr(self      ,'''final_offload_hook'''  ) and self.final_offload_hook is not None:
														self.final_offload_hook.offload()

									if not return_dict:
														return (images,)

									return ShapEPipelineOutput(images=__UpperCAmelCase  )






