






import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers.models.speech_to_text_a.modeling_speech_to_text_a import (
       SpeechaTextaDecoder,
       SpeechaTextaForCausalLM,
   )


@require_torch
class        SCREAMING_SNAKE_CASE	:
     '''simple docstring'''


     def __init__( self				:		List[str]    ,       UpperCAmelCase_				:		Any    ,       UpperCAmelCase_				:		List[Any]=99    ,       UpperCAmelCase_				:		Tuple=13    ,       UpperCAmelCase_				:		Dict=16    ,       UpperCAmelCase_				:		int=7    ,       UpperCAmelCase_				:		Optional[Any]=True    ,       UpperCAmelCase_				:		List[Any]=True    ,       UpperCAmelCase_				:		Any=True    ,       UpperCAmelCase_				:		List[str]=False    ,       UpperCAmelCase_				:		Tuple=True    ,       UpperCAmelCase_				:		Tuple=2    ,       UpperCAmelCase_				:		List[str]=32    ,       UpperCAmelCase_				:		Union[str, Any]=4    ,       UpperCAmelCase_				:		Any=4    ,       UpperCAmelCase_				:		Optional[int]=30    ,       UpperCAmelCase_				:		Union[str, Any]=0    ,       UpperCAmelCase_				:		Union[str, Any]=1    ,       UpperCAmelCase_				:		Any=2    ,       UpperCAmelCase_				:		Dict=None    ,       ):
       SCREAMING_SNAKE_CASE				:					Any		  =			parent
       SCREAMING_SNAKE_CASE				:					Tuple		  =			batch_size
       SCREAMING_SNAKE_CASE				:					str		  =			decoder_seq_length
       # For common tests
       SCREAMING_SNAKE_CASE				:					Tuple		  =			self.decoder_seq_length
       SCREAMING_SNAKE_CASE				:					str		  =			is_training
       SCREAMING_SNAKE_CASE				:					Dict		  =			use_attention_mask
       SCREAMING_SNAKE_CASE				:					int		  =			use_labels

       SCREAMING_SNAKE_CASE				:					Tuple		  =			vocab_size
       SCREAMING_SNAKE_CASE				:					int		  =			d_model
       SCREAMING_SNAKE_CASE				:					List[str]		  =			d_model
       SCREAMING_SNAKE_CASE				:					int		  =			decoder_layers
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			decoder_layers
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			decoder_ffn_dim
       SCREAMING_SNAKE_CASE				:					Tuple		  =			decoder_attention_heads
       SCREAMING_SNAKE_CASE				:					Dict		  =			decoder_attention_heads
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			eos_token_id
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			bos_token_id
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			pad_token_id
       SCREAMING_SNAKE_CASE				:					List[str]		  =			decoder_start_token_id
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			use_cache
       SCREAMING_SNAKE_CASE				:					Tuple		  =			max_position_embeddings

       SCREAMING_SNAKE_CASE				:					Any		  =			None
       SCREAMING_SNAKE_CASE				:					Tuple		  =			decoder_seq_length
       SCREAMING_SNAKE_CASE				:					int		  =			2
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			1


     def  _A				( self				:		Optional[int]					):
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			ids_tensor([self.batch_size, self.decoder_seq_length]    ,       self.vocab_size					)

       SCREAMING_SNAKE_CASE				:					str		  =			None
       if self.use_attention_mask:
         SCREAMING_SNAKE_CASE				:					Tuple		  =			ids_tensor([self.batch_size, self.decoder_seq_length]    ,       vocab_size=2					)

       SCREAMING_SNAKE_CASE				:					str		  =			None
       if self.use_labels:
         SCREAMING_SNAKE_CASE				:					List[str]		  =			ids_tensor([self.batch_size, self.decoder_seq_length]    ,       self.vocab_size					)

       SCREAMING_SNAKE_CASE				:					str		  =			SpeechaTextaConfig(
           vocab_size=self.vocab_size    ,       d_model=self.d_model    ,       decoder_layers=self.decoder_layers    ,       decoder_ffn_dim=self.decoder_ffn_dim    ,       decoder_attention_heads=self.decoder_attention_heads    ,       eos_token_id=self.eos_token_id    ,       bos_token_id=self.bos_token_id    ,       use_cache=self.use_cache    ,       pad_token_id=self.pad_token_id    ,       decoder_start_token_id=self.decoder_start_token_id    ,       max_position_embeddings=self.max_position_embeddings    ,       )

       return (
           config,
           input_ids,
           attention_mask,
           lm_labels,
       )


     def  _A				( self				:		Optional[Any]    ,       UpperCAmelCase_				:		int    ,       UpperCAmelCase_				:		Dict    ,       UpperCAmelCase_				:		int    ,       UpperCAmelCase_				:		Any    ,       ):
       SCREAMING_SNAKE_CASE				:					str		  =			True
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			SpeechaTextaDecoder(config=UpperCAmelCase_					).to(UpperCAmelCase_					).eval()
       SCREAMING_SNAKE_CASE				:					Tuple		  =			input_ids[:2]

       input_ids[input_ids == 0] += 1
       # first forward pass
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			model(UpperCAmelCase_    ,       use_cache=UpperCAmelCase_					)
       SCREAMING_SNAKE_CASE				:					List[str]		  =			model(UpperCAmelCase_					)
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			model(UpperCAmelCase_    ,       use_cache=UpperCAmelCase_					)

       self.parent.assertTrue(len(UpperCAmelCase_					) == len(UpperCAmelCase_					)					)
       self.parent.assertTrue(len(UpperCAmelCase_					) == len(UpperCAmelCase_					) + 1					)

       SCREAMING_SNAKE_CASE				:					List[Any]		  =			outputs["past_key_values"]

       # create hypothetical next token and extent to next_input_ids
       SCREAMING_SNAKE_CASE				:					str		  =			ids_tensor((2, 1)    ,       config.vocab_size - 1					) + 1

       # append to next input_ids and
       SCREAMING_SNAKE_CASE				:					str		  =			torch.cat([input_ids, next_tokens]    ,       dim=-1					)

       print(UpperCAmelCase_					)

       SCREAMING_SNAKE_CASE				:					List[str]		  =			model(UpperCAmelCase_					)["last_hidden_state"]
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			model(UpperCAmelCase_    ,       past_key_values=UpperCAmelCase_					)["last_hidden_state"]

       # select random slice
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			ids_tensor((1,)    ,       output_from_past.shape[-1]					).item()
       SCREAMING_SNAKE_CASE				:					str		  =			output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
       SCREAMING_SNAKE_CASE				:					int		  =			output_from_past[:, 0, random_slice_idx].detach()

       # test that outputs are equal for slice
       assert torch.allclose(UpperCAmelCase_    ,       UpperCAmelCase_    ,       atol=1E-3					)






     def  _A				( self				:		str					):
       SCREAMING_SNAKE_CASE				:					int		  =			self.prepare_config_and_inputs()
       (
           (
           SCREAMING_SNAKE_CASE
       )  ,     (
           SCREAMING_SNAKE_CASE
       )  ,     (
           SCREAMING_SNAKE_CASE
       )  ,     (
           SCREAMING_SNAKE_CASE
       )  ,     
       )				:					Optional[Any]		  =			config_and_inputs

       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			{
           "input_ids": input_ids,
           "attention_mask": attention_mask,
       }
       return config, inputs_dict





@require_torch
class        SCREAMING_SNAKE_CASE	(	lowerCAmelCase					,						lowerCAmelCase					,						lowerCAmelCase					,						unittest.TestCase    ):
     '''simple docstring'''


     UpperCamelCase_							:						int								=		(SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
     UpperCamelCase_							:						Tuple								=		(SpeechaTextaForCausalLM,) if is_torch_available() else ()
     UpperCamelCase_							:						int								=		{'''text-generation''': SpeechaTextaForCausalLM} if is_torch_available() else {}
     UpperCamelCase_							:						Tuple								=		True
     UpperCamelCase_							:						Union[str, Any]								=		False


     def  _A				( self				:		Tuple    ,       ):
       SCREAMING_SNAKE_CASE				:					Any		  =			SpeechaTextaStandaloneDecoderModelTester(self    ,       is_training=UpperCAmelCase_					)
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			ConfigTester(self    ,       config_class=UpperCAmelCase_					)


     def  _A				( self				:		Optional[Any]					):
       pass


     def  _A				( self				:		str					):
       pass


     def  _A				( self				:		Dict					):
       pass


     def  _A				( self				:		Optional[Any]					):
       self.config_tester.run_common_tests()


     def  _A				( self				:		Optional[int]					):
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_decoder_model_past(*UpperCAmelCase_					)






     def  _A				( self				:		Optional[int]					):
       return














import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import ConvNextImageProcessor


class        SCREAMING_SNAKE_CASE	(	unittest.TestCase    ):
     '''simple docstring'''


     def __init__( self				:		Optional[Any]    ,       UpperCAmelCase_				:		Optional[int]    ,       UpperCAmelCase_				:		Any=7    ,       UpperCAmelCase_				:		Union[str, Any]=3    ,       UpperCAmelCase_				:		List[str]=18    ,       UpperCAmelCase_				:		Optional[int]=30    ,       UpperCAmelCase_				:		int=400    ,       UpperCAmelCase_				:		int=True    ,       UpperCAmelCase_				:		List[Any]=None    ,       UpperCAmelCase_				:		Tuple=0.875    ,       UpperCAmelCase_				:		str=True    ,       UpperCAmelCase_				:		Optional[Any]=[0.5, 0.5, 0.5]    ,       UpperCAmelCase_				:		List[Any]=[0.5, 0.5, 0.5]    ,       ):
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			size if size is not None else {"shortest_edge": 20}
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			parent
       SCREAMING_SNAKE_CASE				:					int		  =			batch_size
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			num_channels
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			image_size
       SCREAMING_SNAKE_CASE				:					Any		  =			min_resolution
       SCREAMING_SNAKE_CASE				:					List[str]		  =			max_resolution
       SCREAMING_SNAKE_CASE				:					int		  =			do_resize
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			size
       SCREAMING_SNAKE_CASE				:					Any		  =			crop_pct
       SCREAMING_SNAKE_CASE				:					Dict		  =			do_normalize
       SCREAMING_SNAKE_CASE				:					List[str]		  =			image_mean
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			image_std






     def  _A				( self				:		str					):
       return {
           "image_mean": self.image_mean,
           "image_std": self.image_std,
           "do_normalize": self.do_normalize,
           "do_resize": self.do_resize,
           "size": self.size,
           "crop_pct": self.crop_pct,
       }





@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE	(	lowerCAmelCase					,						unittest.TestCase    ):
     '''simple docstring'''


     UpperCamelCase_							:						str								=		ConvNextImageProcessor if is_vision_available() else None


     def  _A				( self				:		Optional[int]					):
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			ConvNextImageProcessingTester(self					)


     @property
     def  _A				( self				:		str					):
       return self.image_processor_tester.prepare_image_processor_dict()


     def  _A				( self				:		str					):
       SCREAMING_SNAKE_CASE				:					str		  =			self.image_processing_class(**self.image_processor_dict					)
       self.assertTrue(hasattr(UpperCAmelCase_    ,       "do_resize"					)					)
       self.assertTrue(hasattr(UpperCAmelCase_    ,       "size"					)					)
       self.assertTrue(hasattr(UpperCAmelCase_    ,       "crop_pct"					)					)
       self.assertTrue(hasattr(UpperCAmelCase_    ,       "do_normalize"					)					)
       self.assertTrue(hasattr(UpperCAmelCase_    ,       "image_mean"					)					)
       self.assertTrue(hasattr(UpperCAmelCase_    ,       "image_std"					)					)


     def  _A				( self				:		Union[str, Any]					):
       SCREAMING_SNAKE_CASE				:					Optional[int]		  =			self.image_processing_class.from_dict(self.image_processor_dict					)
       self.assertEqual(image_processor.size    ,       {"shortest_edge": 20}					)

       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			self.image_processing_class.from_dict(self.image_processor_dict    ,       size=42					)
       self.assertEqual(image_processor.size    ,       {"shortest_edge": 42}					)


     def  _A				( self				:		List[str]					):
       pass


     def  _A				( self				:		Optional[Any]					):
       # Initialize image_processing
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			self.image_processing_class(**self.image_processor_dict					)
       # create random PIL images
       SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=UpperCAmelCase_					)
       for image in image_inputs:
         self.assertIsInstance(UpperCAmelCase_    ,       Image.Image					)

       # Test not batched input
       SCREAMING_SNAKE_CASE				:					Dict		  =			image_processing(image_inputs[0]    ,       return_tensors="pt"					).pixel_values
       self.assertEqual(
           encoded_images.shape    ,       (
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size["shortest_edge"],
               self.image_processor_tester.size["shortest_edge"],
           )    ,       )

       # Test batched
       SCREAMING_SNAKE_CASE				:					str		  =			image_processing(UpperCAmelCase_    ,       return_tensors="pt"					).pixel_values
       self.assertEqual(
           encoded_images.shape    ,       (
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size["shortest_edge"],
               self.image_processor_tester.size["shortest_edge"],
           )    ,       )


     def  _A				( self				:		Optional[Any]					):
       # Initialize image_processing
       SCREAMING_SNAKE_CASE				:					List[str]		  =			self.image_processing_class(**self.image_processor_dict					)
       # create random numpy tensors
       SCREAMING_SNAKE_CASE				:					List[Any]		  =			prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=UpperCAmelCase_    ,       numpify=UpperCAmelCase_					)
       for image in image_inputs:
         self.assertIsInstance(UpperCAmelCase_    ,       np.ndarray					)

       # Test not batched input
       SCREAMING_SNAKE_CASE				:					str		  =			image_processing(image_inputs[0]    ,       return_tensors="pt"					).pixel_values
       self.assertEqual(
           encoded_images.shape    ,       (
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size["shortest_edge"],
               self.image_processor_tester.size["shortest_edge"],
           )    ,       )

       # Test batched
       SCREAMING_SNAKE_CASE				:					Dict		  =			image_processing(UpperCAmelCase_    ,       return_tensors="pt"					).pixel_values
       self.assertEqual(
           encoded_images.shape    ,       (
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size["shortest_edge"],
               self.image_processor_tester.size["shortest_edge"],
           )    ,       )






     def  _A				( self				:		Tuple					):
       # Initialize image_processing
       SCREAMING_SNAKE_CASE				:					str		  =			self.image_processing_class(**self.image_processor_dict					)
       # create random PyTorch tensors
       SCREAMING_SNAKE_CASE				:					Tuple		  =			prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=UpperCAmelCase_    ,       torchify=UpperCAmelCase_					)
       for image in image_inputs:
         self.assertIsInstance(UpperCAmelCase_    ,       torch.Tensor					)

       # Test not batched input
       SCREAMING_SNAKE_CASE				:					int		  =			image_processing(image_inputs[0]    ,       return_tensors="pt"					).pixel_values
       self.assertEqual(
           encoded_images.shape    ,       (
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size["shortest_edge"],
               self.image_processor_tester.size["shortest_edge"],
           )    ,       )

       # Test batched
       SCREAMING_SNAKE_CASE				:					Any		  =			image_processing(UpperCAmelCase_    ,       return_tensors="pt"					).pixel_values
       self.assertEqual(
           encoded_images.shape    ,       (
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.size["shortest_edge"],
               self.image_processor_tester.size["shortest_edge"],
           )    ,       )






