
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:
						SCREAMING_SNAKE_CASE   :		Union[str, Any]					 =       False






class 					__lowercase		:


					def __init__(	self       ,       a__       ,       a__=1_4       ,       a__=7       ,       a__=True       ,       a__=False       ,       a__=True       ,       a__=True       ,       a__=True       ,       a__=9_9       ,       a__=3_2       ,       a__=5       ,       a__=3_7       ,       a__="gelu"       ,       a__=0.1       ,       a__=0.1       ,       a__=5_1_2       ,       a__=1_6       ,       a__=2       ,       a__=3       ,       a__=4       ,       a__=None       ,       )		->							List[Any]:





									'''simple docstring'''
									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						)		->							Tuple:





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


					def        lowerCAmelCase_    (	self       ,       a__=False       ,       a__=False       ,       a__=False						)		->							Any:





									'''simple docstring'''
									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=a__       ,       scale_attn_by_inverse_layer_idx=a__       ,       reorder_and_upcast_attn=a__       ,       )

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


					def        lowerCAmelCase_    (	self       ,       a__=False       ,       a__=False       ,       a__=False						)		->							Optional[int]:





									'''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=a__       ,       bos_token_id=self.bos_token_id       ,       eos_token_id=self.eos_token_id       ,       pad_token_id=self.pad_token_id       ,       gradient_checkpointing=a__       ,       scale_attn_by_inverse_layer_idx=a__       ,       reorder_and_upcast_attn=a__       ,       )


					def        lowerCAmelCase_    (	self						)		->							Any:





									'''simple docstring'''
									A_       	=  self.get_config()
									A_       	=  3_0_0
									return config


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





									'''simple docstring'''
									(
									    (
									    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       ,       a__       ,       a__       ,       a__       ,       a__       ,       a__       ,       *a__						)		->							Tuple:





									'''simple docstring'''
									A_       	=  True
									A_       	=  RwkvModel(config=a__						)
									model.to(a__						)
									model.eval()

									A_       	=  model(a__						)

									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       ,       a__       ,       a__       ,       a__       ,       a__       ,       a__       ,       *a__						)		->							int:





									'''simple docstring'''
									A_       	=  RwkvForCausalLM(a__						)
									model.to(a__						)
									model.eval()

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


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__       ,       a__       ,       a__       ,       *a__						)		->							Optional[Any]:





									'''simple docstring'''
									A_       	=  RwkvModel(config=a__						)
									model.to(a__						)
									model.eval()

									A_       	=  model(a__						)
									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						)       ,       a__       ,       atol=1E-5						)						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__       ,       a__       ,       a__       ,       *a__       ,       a__=False						)		->							Tuple:





									'''simple docstring'''
									A_       	=  RwkvForCausalLM(a__						)
									model.to(a__						)
									if gradient_checkpointing:
													model.gradient_checkpointing_enable()

									A_       	=  model(a__       ,       labels=a__						)
									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						)		->							Optional[int]:





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


					def        lowerCAmelCase_    (	self						)		->							str:





									'''simple docstring'''
									A_       	=  RwkvModelTester(self						)
									A_       	=  ConfigTester(
									    self       ,       config_class=a__       ,       n_embd=3_7       ,       common_properties=['''hidden_size''', '''num_hidden_layers''']						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__=None						)		->							Optional[int]:





									'''simple docstring'''
									if isinstance(a__       ,       torch.Tensor						):
													A_	,					A_       	=  member.max().item(), member.min().item()
									elif isinstance(a__       ,       a__						) or isinstance(a__       ,       a__						):
													A_	,					A_       	=  max(a__						), min(a__						)

									if not isinstance(a__       ,       a__						):
													raise TypeError('''container should be a list or tuple'''						)
									elif len(a__						) != 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(a__						), safe_repr(a__						))
													self.fail(self._formatMessage(a__       ,       a__						)						)


					def        lowerCAmelCase_    (	self						)		->							Any:





									'''simple docstring'''
									self.config_tester.run_common_tests()


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





									'''simple docstring'''
									A_       	=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_rwkv_model(*a__						)


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





									'''simple docstring'''
									A_       	=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_causl_lm(*a__						)


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





									'''simple docstring'''
									A_       	=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_state_equivalency(*a__						)


					def        lowerCAmelCase_    (	self						)		->							Any:





									'''simple docstring'''
									A_	,					A_       	=  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													A_       	=  model_class(config=a__						)
													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						)		->							Optional[int]:





									'''simple docstring'''
									A_	,					A_       	=  self.model_tester.prepare_config_and_inputs_for_common()
									A_       	=  True

									A_       	=  getattr(self.model_tester       ,       '''seq_length'''       ,       a__						)

									for model_class in self.all_model_classes:
													A_       	=  True
													A_       	=  False
													A_       	=  True
													A_       	=  model_class(a__						)
													model.to(a__						)
													model.eval()

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

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

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

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

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

													A_       	=  self._prepare_for_class(a__       ,       a__						)
													A_       	=  inputs['''input_ids'''].shape[0]
													with torch.no_grad():
																	A_       	=  model(**a__						)

													A_       	=  1
													self.assertEqual(out_len + added_hidden_states       ,       len(a__						)						)

													A_       	=  outputs.attentions

													self.assertEqual(len(a__						)       ,       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						)		->							int:





									'''simple docstring'''
									for model_name in RWKV_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													A_       	=  RwkvModel.from_pretrained(a__						)
													self.assertIsNotNone(a__						)






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


					def        lowerCAmelCase_    (	self						)		->							int:





									'''simple docstring'''
									A_       	=  '''RWKV/rwkv-4-169m-pile'''
									A_       	=  AutoTokenizer.from_pretrained(self.model_id						)


					def        lowerCAmelCase_    (	self						)		->							Tuple:





									'''simple docstring'''
									A_       	=  '''Hello my name is Jasmine and I am a newbie to the'''
									A_       	=  RwkvForCausalLM.from_pretrained(self.model_id						).to(a__						)

									A_       	=  self.tokenizer('''Hello my name is'''       ,       return_tensors='''pt'''						).input_ids.to(a__						)
									A_       	=  model.generate(a__       ,       max_new_tokens=1_0						)
									A_       	=  self.tokenizer.decode(output[0].tolist()						)

									self.assertEqual(a__       ,       a__						)


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





									'''simple docstring'''
									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(a__						)
									A_       	=  RwkvForCausalLM.from_pretrained(self.model_id       ,       torch_dtype=torch.bfloataa						).to(a__						)

									A_       	=  model.generate(a__       ,       max_new_tokens=1_0						)
									A_       	=  self.tokenizer.decode(output[0].tolist()						)

									self.assertEqual(a__       ,       a__						)

from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
						import PIL


SCREAMING_SNAKE_CASE   :		Optional[int]					 =       logging.get_logger(__name__)






class 					__lowercase		(					A       ):
					__magic_name__						:							int     	=	['''pixel_values''']


					def __init__(	self       ,       a__ = True       ,       a__ = None       ,       a__ = True       ,       a__ = None       ,       a__ = PILImageResampling.BICUBIC       ,       a__ = True       ,       a__ = 1 / 2_5_5       ,       a__ = True       ,       a__ = None       ,       a__ = None       ,       **a__       ,       )		->							None:





									'''simple docstring'''
									super().__init__(**a__						)
									A_       	=  crop_size if crop_size is not None else {'''height''': 2_5_6, '''width''': 2_5_6}
									A_       	=  get_size_dict(a__       ,       param_name='''crop_size'''						)
									A_       	=  size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
									A_       	=  get_size_dict(a__						)

									A_       	=  do_center_crop
									A_       	=  crop_size
									A_       	=  do_resize
									A_       	=  size
									A_       	=  resample
									A_       	=  do_rescale
									A_       	=  rescale_factor
									A_       	=  do_normalize
									A_       	=  image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
									A_       	=  image_std if image_std is not None else IMAGENET_DEFAULT_STD


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__ = None       ,       a__ = None       ,       **a__       ,       )		->							np.ndarray:





									'''simple docstring'''
									A_       	=  self.size if size is None else size
									A_       	=  get_size_dict(a__						)
									A_       	=  get_size_dict(a__       ,       param_name='''crop_size'''						)

									A_	,					A_       	=  get_image_size(a__						)
									A_       	=  min(a__       ,       a__						)
									A_       	=  (size['''height'''] / crop_size['''height''']) * min_dim
									A_       	=  (size['''width'''] / crop_size['''width''']) * min_dim
									return center_crop(a__       ,       size=(cropped_height, cropped_width)       ,       data_format=a__       ,       **a__						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__ = PIL.Image.BICUBIC       ,       a__ = None       ,       **a__       ,       )		->							np.ndarray:





									'''simple docstring'''
									A_       	=  get_size_dict(a__						)
									if "height" not in size or "width" not in size:
													raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}"						)
									return resize(
									    a__       ,       size=(size['''height'''], size['''width'''])       ,       resample=a__       ,       data_format=a__       ,       **a__						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__ = None       ,       **a__       ,       )		->							Union[str, Any]:





									'''simple docstring'''
									return rescale(a__       ,       scale=a__       ,       data_format=a__       ,       **a__						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__       ,       a__ = None       ,       **a__       ,       )		->							np.ndarray:





									'''simple docstring'''
									return normalize(a__       ,       mean=a__       ,       std=a__       ,       data_format=a__       ,       **a__						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = None       ,       a__ = ChannelDimension.FIRST       ,       **a__       ,       )		->							PIL.Image.Image:





									'''simple docstring'''
									A_       	=  do_center_crop if do_center_crop is not None else self.do_center_crop
									A_       	=  crop_size if crop_size is not None else self.crop_size
									A_       	=  get_size_dict(a__       ,       param_name='''crop_size'''						)
									A_       	=  do_resize if do_resize is not None else self.do_resize
									A_       	=  size if size is not None else self.size
									A_       	=  get_size_dict(a__						)
									A_       	=  resample if resample is not None else self.resample
									A_       	=  do_rescale if do_rescale is not None else self.do_rescale
									A_       	=  rescale_factor if rescale_factor is not None else self.rescale_factor
									A_       	=  do_normalize if do_normalize is not None else self.do_normalize
									A_       	=  image_mean if image_mean is not None else self.image_mean
									A_       	=  image_std if image_std is not None else self.image_std

									A_       	=  make_list_of_images(a__						)

									if not valid_images(a__						):
													raise ValueError(
													    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
													    '''torch.Tensor, tf.Tensor or jax.ndarray.'''						)

									if do_center_crop and crop_size is None:
													raise ValueError('''If `do_center_crop` is set to `True`, `crop_size` must be provided.'''						)

									if do_resize and size is None:
													raise ValueError('''Size must be specified if do_resize is True.'''						)

									if do_rescale and rescale_factor is None:
													raise ValueError('''Rescale factor must be specified if do_rescale is True.'''						)

									if do_normalize and (image_mean is None or image_std is None):
													raise ValueError('''Image mean and image standard deviation must be specified if do_normalize is True.'''						)

									# All transformations expect numpy arrays.
									A_       	=  [to_numpy_array(a__						) for image in images]

									if do_center_crop:
													A_       	=  [self.center_crop(a__       ,       a__       ,       size=a__						) for image in images]

									if do_resize:
													A_       	=  [self.resize(image=a__       ,       size=a__       ,       resample=a__						) for image in images]

									if do_rescale:
													A_       	=  [self.rescale(image=a__       ,       scale=a__						) for image in images]

									if do_normalize:
													A_       	=  [self.normalize(image=a__       ,       mean=a__       ,       std=a__						) for image in images]

									A_       	=  [to_channel_dimension_format(a__       ,       a__						) for image in images]

									A_       	=  {'''pixel_values''': images}
									return BatchFeature(data=a__       ,       tensor_type=a__						)