






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:
					snake_case_   :	Dict							      =False





class        a__      :






		def __init__(      self							, lowercase__							, lowercase__=14							, lowercase__=7							, lowercase__=True							, lowercase__=False							, lowercase__=True							, lowercase__=True							, lowercase__=True							, lowercase__=99							, lowercase__=32							, lowercase__=5							, lowercase__=37							, lowercase__="gelu"							, lowercase__=0.1							, lowercase__=0.1							, lowercase__=512							, lowercase__=16							, lowercase__=2							, lowercase__=3							, lowercase__=4							, lowercase__=None							, )				->				Dict:
				__A    =							parent
				__A    =							batch_size
				__A    =							seq_length
				__A    =							is_training
				__A    =							use_token_type_ids
				__A    =							use_input_mask
				__A    =							use_labels
				__A    =							use_mc_token_ids
				__A    =							vocab_size
				__A    =							hidden_size
				__A    =							num_hidden_layers
				__A    =							intermediate_size
				__A    =							hidden_act
				__A    =							hidden_dropout_prob
				__A    =							attention_probs_dropout_prob
				__A    =							max_position_embeddings
				__A    =							type_vocab_size
				__A    =							type_sequence_label_size
				__A    =							num_labels
				__A    =							num_choices
				__A    =							scope
				__A    =							vocab_size - 1
				__A    =							vocab_size - 1
				__A    =							vocab_size - 1






		def 					_lowerCamelCase					(      self						)				->				str:
				return RwkvConfig.from_pretrained("sgugger/rwkv-4-pile-7b"						)






		def 					_lowerCamelCase					(      self							, lowercase__=False							, lowercase__=False							, lowercase__=False						)				->				List[Any]:
				__A    =							ids_tensor([self.batch_size, self.seq_length]							, self.vocab_size						)

				__A    =							None
				if self.use_input_mask:
						__A    =							random_attention_mask([self.batch_size, self.seq_length]						)

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

				__A    =							None
				if self.use_mc_token_ids:
						__A    =							ids_tensor([self.batch_size, self.num_choices]							, self.seq_length						)

				__A    =							None
				__A    =							None
				__A    =							None
				if self.use_labels:
						__A    =							ids_tensor([self.batch_size]							, self.type_sequence_label_size						)
						__A    =							ids_tensor([self.batch_size, self.seq_length]							, self.num_labels						)
						__A    =							ids_tensor([self.batch_size]							, self.num_choices						)

				__A    =							self.get_config(
				    gradient_checkpointing=lowercase__							, scale_attn_by_inverse_layer_idx=lowercase__							, reorder_and_upcast_attn=lowercase__							, )

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






		def 					_lowerCamelCase					(      self							, lowercase__=False							, lowercase__=False							, lowercase__=False						)				->				Optional[Any]:
				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=lowercase__							, bos_token_id=self.bos_token_id							, eos_token_id=self.eos_token_id							, pad_token_id=self.pad_token_id							, gradient_checkpointing=lowercase__							, scale_attn_by_inverse_layer_idx=lowercase__							, reorder_and_upcast_attn=lowercase__							, )






		def 					_lowerCamelCase					(      self						)				->				Optional[int]:
				__A    =							self.get_config()
				__A    =							300
				return config






		def 					_lowerCamelCase					(      self						)				->				Union[str, Any]:
				(
				    (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   
				)    =							self.prepare_config_and_inputs()

				__A    =							floats_tensor([self.batch_size, self.seq_length, self.hidden_size]						)
				__A    =							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 					_lowerCamelCase					(      self							, lowercase__							, lowercase__							, lowercase__							, lowercase__							, lowercase__							, *lowercase__						)				->				Union[str, Any]:
				__A    =							True
				__A    =							RwkvModel(config=lowercase__						)
				model.to(lowercase__						)
				model.eval()

				__A    =							model(lowercase__						)

				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 					_lowerCamelCase					(      self							, lowercase__							, lowercase__							, lowercase__							, lowercase__							, lowercase__							, *lowercase__						)				->				List[str]:
				__A    =							RwkvForCausalLM(lowercase__						)
				model.to(lowercase__						)
				model.eval()

				__A    =							model(lowercase__							, labels=lowercase__						)
				self.parent.assertEqual(result.loss.shape							, ()						)
				self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.seq_length, self.vocab_size)						)






		def 					_lowerCamelCase					(      self							, lowercase__							, lowercase__							, lowercase__							, lowercase__							, lowercase__							, *lowercase__						)				->				List[str]:
				__A    =							RwkvModel(config=lowercase__						)
				model.to(lowercase__						)
				model.eval()

				__A    =							model(lowercase__						)
				__A    =							outputs.last_hidden_state

				__A    =							model(input_ids[:, :2]						)
				__A    =							outputs.last_hidden_state

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

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






		def 					_lowerCamelCase					(      self							, lowercase__							, lowercase__							, lowercase__							, lowercase__							, lowercase__							, *lowercase__							, lowercase__=False						)				->				Tuple:
				__A    =							RwkvForCausalLM(lowercase__						)
				model.to(lowercase__						)
				if gradient_checkpointing:
						model.gradient_checkpointing_enable()

				__A    =							model(lowercase__							, labels=lowercase__						)
				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 					_lowerCamelCase					(      self						)				->				List[str]:
				__A    =							self.prepare_config_and_inputs()

				(
				    (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   (
				    __A
				) ,   
				)    =							config_and_inputs

				__A    =							{"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        a__      (	lowerCAmelCase__	,       lowerCAmelCase__	,       lowerCAmelCase__	,       unittest.TestCase		):
		UpperCAmelCase_							:       Optional[int] 					= (RwkvModel, RwkvForCausalLM) if is_torch_available() else ()
		UpperCAmelCase_							:       Any 					= (
		    {'feature-extraction': RwkvModel, 'text-generation': RwkvForCausalLM} if is_torch_available() else {}
		)
		# all_generative_model_classes = (RwkvForCausalLM,) if is_torch_available() else ()
		UpperCAmelCase_							:       Any 					= False
		UpperCAmelCase_							:       Dict 					= False
		UpperCAmelCase_							:       str 					= False
		UpperCAmelCase_							:       List[str] 					= False
		UpperCAmelCase_							:       Any 					= False  # Rwkv does not support head masking






		def 					_lowerCamelCase					(      self						)				->				str:
				__A    =							RwkvModelTester(self						)
				__A    =							ConfigTester(
				    self							, config_class=lowercase__							, n_embd=37							, common_properties=["hidden_size", "num_hidden_layers"]						)






		def 					_lowerCamelCase					(      self							, lowercase__							, lowercase__							, lowercase__=None						)				->				List[str]:
				if isinstance(lowercase__							, torch.Tensor						):
						__A ,   __A    =							member.max().item(), member.min().item()
				elif isinstance(lowercase__							, lowercase__						) or isinstance(lowercase__							, lowercase__						):
						__A ,   __A    =							max(lowercase__						), min(lowercase__						)

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

				__A ,   __A    =							container

				__A    =							(min_value >= expected_min) and (max_value <= expected_max)

				if not is_inside_interval:
						__A    =							"%s not found in %s" % (safe_repr(lowercase__						), safe_repr(lowercase__						))
						self.fail(self._formatMessage(lowercase__							, lowercase__						)						)






		def 					_lowerCamelCase					(      self						)				->				Optional[Any]:
				self.config_tester.run_common_tests()






		def 					_lowerCamelCase					(      self						)				->				Union[str, Any]:
				__A    =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_rwkv_model(*lowercase__						)






		def 					_lowerCamelCase					(      self						)				->				Dict:
				__A    =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_causl_lm(*lowercase__						)






		def 					_lowerCamelCase					(      self						)				->				str:
				__A    =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_state_equivalency(*lowercase__						)






		def 					_lowerCamelCase					(      self						)				->				str:
				__A ,   __A    =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						__A    =							model_class(config=lowercase__						)
						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 					_lowerCamelCase					(      self						)				->				Tuple:
				__A ,   __A    =							self.model_tester.prepare_config_and_inputs_for_common()
				__A    =							True

				__A    =							getattr(self.model_tester							, "seq_length"							, lowercase__						)

				for model_class in self.all_model_classes:
						__A    =							True
						__A    =							False
						__A    =							True
						__A    =							model_class(lowercase__						)
						model.to(lowercase__						)
						model.eval()

						__A    =							self._prepare_for_class(lowercase__							, lowercase__						)
						__A    =							inputs["input_ids"].shape[0]
						with torch.no_grad():
								__A    =							model(**lowercase__						)
						__A    =							outputs.attentions
						self.assertEqual(len(lowercase__						)							, self.model_tester.num_hidden_layers						)

						# check that output_attentions also work using config
						del inputs_dict["output_attentions"]
						__A    =							True
						__A    =							model_class(lowercase__						)
						model.to(lowercase__						)
						model.eval()

						__A    =							self._prepare_for_class(lowercase__							, lowercase__						)
						__A    =							inputs["input_ids"].shape[0]
						with torch.no_grad():
								__A    =							model(**lowercase__						)
						__A    =							outputs.attentions
						self.assertEqual(len(lowercase__						)							, self.model_tester.num_hidden_layers						)

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

						# Check attention is always last and order is fine
						__A    =							True
						__A    =							True
						__A    =							model_class(lowercase__						)
						model.to(lowercase__						)
						model.eval()

						__A    =							self._prepare_for_class(lowercase__							, lowercase__						)
						__A    =							inputs["input_ids"].shape[0]
						with torch.no_grad():
								__A    =							model(**lowercase__						)

						__A    =							1
						self.assertEqual(out_len + added_hidden_states							, len(lowercase__						)						)

						__A    =							outputs.attentions

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






		@slow
		def 					_lowerCamelCase					(      self						)				->				List[str]:
				for model_name in RWKV_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						__A    =							RwkvModel.from_pretrained(lowercase__						)
						self.assertIsNotNone(lowercase__						)





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






		def 					_lowerCamelCase					(      self						)				->				Dict:
				__A    =							"RWKV/rwkv-4-169m-pile"
				__A    =							AutoTokenizer.from_pretrained(self.model_id						)






		def 					_lowerCamelCase					(      self						)				->				Union[str, Any]:
				__A    =							"Hello my name is Jasmine and I am a newbie to the"
				__A    =							RwkvForCausalLM.from_pretrained(self.model_id						).to(lowercase__						)

				__A    =							self.tokenizer("Hello my name is"							, return_tensors="pt"						).input_ids.to(lowercase__						)
				__A    =							model.generate(lowercase__							, max_new_tokens=10						)
				__A    =							self.tokenizer.decode(output[0].tolist()						)

				self.assertEqual(lowercase__							, lowercase__						)






		def 					_lowerCamelCase					(      self						)				->				Optional[Any]:
				__A    =							"Hello my name is Jasmine and I am a newbie to the"

				__A    =							self.tokenizer("Hello my name is"							, return_tensors="pt"						).input_ids.to(lowercase__						)
				__A    =							RwkvForCausalLM.from_pretrained(self.model_id							, torch_dtype=torch.bfloataa						).to(lowercase__						)

				__A    =							model.generate(lowercase__							, max_new_tokens=10						)
				__A    =							self.tokenizer.decode(output[0].tolist()						)

				self.assertEqual(lowercase__							, lowercase__						)





import enum
import inspect
import warnings
from functools import wraps
from typing import Callable, Optional

from .logging import get_logger


_A							     =       set()
_A							     =       get_logger(__name__)

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Optional[str] = None	)     ->	Optional[int]:



	"""simple docstring"""






	def decorator(UpperCamelCase		:      Callable	):
		global _emitted_deprecation_warnings

		if inspect.isclass(UpperCamelCase	):
			a_     			=   deprecated_class_or_function.__init__
			a_     			=   deprecated_class_or_function.__name__
		else:
			a_     			=   deprecated_class_or_function
			a_     			=   deprecated_function.__name__
			# Support deprecating __init__ class method: class name instead
			a_     			=   name if name != """__init__""" else deprecated_function.__qualname__.split("""."""	)[-2]

		a_     			=   (
		    F"""{name} is deprecated and will be removed in the next major version of datasets.""" + F""" {help_message}"""
		    if help_message
		    else """"""
		)

		@wraps(UpperCamelCase	)
		def wrapper(*UpperCamelCase		:      List[str]     ,					**UpperCamelCase		:      Union[str, Any]	):
			a_     			=   hash(UpperCamelCase	)
			if func_hash not in _emitted_deprecation_warnings:
				warnings.warn(UpperCamelCase     ,					category=UpperCamelCase     ,					stacklevel=2	)
				_emitted_deprecation_warnings.add(UpperCamelCase	)
			return deprecated_function(*UpperCamelCase     ,					**UpperCamelCase	)

		a_     			=   """deprecated"""

		if inspect.isclass(UpperCamelCase	):
			a_     			=   wrapper
			return deprecated_class_or_function
		else:
			return wrapper

	return decorator

class 			lowerCamelCase_					(    enum.EnumMeta    ):





							def __getattribute__(							cls			,       _SCREAMING_SNAKE_CASE    ):
								a_     			=   super().__getattribute__(_SCREAMING_SNAKE_CASE    )
								if isinstance(_SCREAMING_SNAKE_CASE			,       enum.Enum    ) and obj._on_access:
									obj._on_access()
								return obj





							def __getitem__(							cls			,       _SCREAMING_SNAKE_CASE    ):
								a_     			=   super().__getitem__(_SCREAMING_SNAKE_CASE    )
								if member._on_access:
									member._on_access()
								return member





							def __call__(							cls			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE=None			,       *, _SCREAMING_SNAKE_CASE=None			,       _SCREAMING_SNAKE_CASE=None			,       _SCREAMING_SNAKE_CASE=None			,       _SCREAMING_SNAKE_CASE=1    ):
								a_     			=   super().__call__(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       module=_SCREAMING_SNAKE_CASE			,       qualname=_SCREAMING_SNAKE_CASE			,       type=_SCREAMING_SNAKE_CASE			,       start=_SCREAMING_SNAKE_CASE    )
								if isinstance(_SCREAMING_SNAKE_CASE			,       enum.Enum    ) and obj._on_access:
									obj._on_access()
								return obj







class 			lowerCamelCase_					(    enum.Enum   ,		metaclass=_SCREAMING_SNAKE_CASE    ):





							def __new__(							cls			,       _SCREAMING_SNAKE_CASE    ):
								a_     			=   object.__new__(cls    )
								a_     			=   value
								a_     			=   member.deprecate
								return member





							@property
							def   __magic_name__      (							self    ):
								return ""





							def   __magic_name__      (							self    ):
								a_     			=   f""" {self.help_message}""" if self.help_message else """"""
								warnings.warn(
								    f"""'{self.__objclass__.__name__}' is deprecated and will be removed in the next major version of datasets."""
								    + help_message			,       _SCREAMING_SNAKE_CASE			,       stacklevel=3			,       )