






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   UpperCamelCase			:







		"""simple docstring"""



		def __init__(	self		:							List[Any]    ,_SCREAMING_SNAKE_CASE		:							Optional[Any]    ,_SCREAMING_SNAKE_CASE		:							int=9_9    ,_SCREAMING_SNAKE_CASE		:							Any=1_3    ,_SCREAMING_SNAKE_CASE		:							str=1_6    ,_SCREAMING_SNAKE_CASE		:							Optional[int]=7    ,_SCREAMING_SNAKE_CASE		:							Dict=True    ,_SCREAMING_SNAKE_CASE		:							Tuple=True    ,_SCREAMING_SNAKE_CASE		:							Union[str, Any]=True    ,_SCREAMING_SNAKE_CASE		:							Tuple=False    ,_SCREAMING_SNAKE_CASE		:							int=True    ,_SCREAMING_SNAKE_CASE		:							int=2    ,_SCREAMING_SNAKE_CASE		:							str=3_2    ,_SCREAMING_SNAKE_CASE		:							List[str]=4    ,_SCREAMING_SNAKE_CASE		:							List[str]=4    ,_SCREAMING_SNAKE_CASE		:							Dict=3_0    ,_SCREAMING_SNAKE_CASE		:							Tuple=0    ,_SCREAMING_SNAKE_CASE		:							List[str]=1    ,_SCREAMING_SNAKE_CASE		:							Optional[Any]=2    ,_SCREAMING_SNAKE_CASE		:							Tuple=None    ,)     -> Any:


						'''simple docstring'''
						A									=   parent
						A									=   batch_size
						A									=   decoder_seq_length
						# For common tests
						A									=   self.decoder_seq_length
						A									=   is_training
						A									=   use_attention_mask
						A									=   use_labels

						A									=   vocab_size
						A									=   d_model
						A									=   d_model
						A									=   decoder_layers
						A									=   decoder_layers
						A									=   decoder_ffn_dim
						A									=   decoder_attention_heads
						A									=   decoder_attention_heads
						A									=   eos_token_id
						A									=   bos_token_id
						A									=   pad_token_id
						A									=   decoder_start_token_id
						A									=   use_cache
						A									=   max_position_embeddings

						A									=   None
						A									=   decoder_seq_length
						A									=   2
						A									=   1
		def    A(	self		:							Optional[Any]		)     -> Any:


						'''simple docstring'''
						A									=   ids_tensor([self.batch_size, self.decoder_seq_length]    ,self.vocab_size		)

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

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

						A									=   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		:							Union[str, Any]    ,_SCREAMING_SNAKE_CASE		:							Union[str, Any]    ,_SCREAMING_SNAKE_CASE		:							List[str]    ,_SCREAMING_SNAKE_CASE		:							Union[str, Any]    ,_SCREAMING_SNAKE_CASE		:							Union[str, Any]    ,)     -> List[Any]:


						'''simple docstring'''
						A									=   True
						A									=   SpeechaTextaDecoder(config=_SCREAMING_SNAKE_CASE		).to(_SCREAMING_SNAKE_CASE		).eval()
						A									=   input_ids[:2]

						input_ids[input_ids == 0] += 1
						# first forward pass
						A									=   model(_SCREAMING_SNAKE_CASE    ,use_cache=_SCREAMING_SNAKE_CASE		)
						A									=   model(_SCREAMING_SNAKE_CASE		)
						A									=   model(_SCREAMING_SNAKE_CASE    ,use_cache=_SCREAMING_SNAKE_CASE		)

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

						A									=   outputs['past_key_values']

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

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

						print(_SCREAMING_SNAKE_CASE		)

						A									=   model(_SCREAMING_SNAKE_CASE		)['last_hidden_state']
						A									=   model(_SCREAMING_SNAKE_CASE    ,past_key_values=_SCREAMING_SNAKE_CASE		)['last_hidden_state']

						# select random slice
						A									=   ids_tensor((1,)    ,output_from_past.shape[-1]		).item()
						A									=   output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
						A									=   output_from_past[:, 0, random_slice_idx].detach()

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







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


						'''simple docstring'''
						A									=   self.prepare_config_and_inputs()
						(
						    (
						    A
						)			,		(
						    A
						)			,		(
						    A
						)			,		(
						    A
						)			,		
						)									=   config_and_inputs

						A									=   {
						    'input_ids': input_ids,
						    'attention_mask': attention_mask,
						}
						return config, inputs_dict


@require_torch
class   UpperCamelCase			(					snake_case__      ,							snake_case__      ,							snake_case__      ,							unittest.TestCase			):







		"""simple docstring"""



		snake_case			 = (SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
		snake_case			 = (SpeechaTextaForCausalLM,) if is_torch_available() else ()
		snake_case			 = {"text-generation": SpeechaTextaForCausalLM} if is_torch_available() else {}
		snake_case			 = True
		snake_case			 = False
		def    A(	self		:							Dict    ,)     -> Dict:


						'''simple docstring'''
						A									=   SpeechaTextaStandaloneDecoderModelTester(self    ,is_training=_SCREAMING_SNAKE_CASE		)
						A									=   ConfigTester(self    ,config_class=_SCREAMING_SNAKE_CASE		)
		def    A(	self		:							Optional[Any]		)     -> Dict:


						'''simple docstring'''
						pass
		def    A(	self		:							List[Any]		)     -> int:


						'''simple docstring'''
						pass
		def    A(	self		:							Tuple		)     -> Dict:


						'''simple docstring'''
						pass
		def    A(	self		:							List[str]		)     -> List[Any]:


						'''simple docstring'''
						self.config_tester.run_common_tests()
		def    A(	self		:							Dict		)     -> Any:


						'''simple docstring'''
						A									=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_decoder_model_past(*_SCREAMING_SNAKE_CASE		)







		def    A(	self		:							Any		)     -> Any:


						'''simple docstring'''
						return













import hashlib
import importlib.util
import json
import os
import pathlib
from types import ModuleType

import pytest
import requests

lowerCAmelCase_     =			pathlib.Path.cwd().joinpath('project_euler')
lowerCAmelCase_     =			pathlib.Path.cwd().joinpath(
    'scripts', 'project_euler_answers.json'
)

with open(PROJECT_EULER_ANSWERS_PATH) as file_handle:
					lowerCAmelCase_     =			json.load(file_handle)







def   snake_case		(				UpperCAmelCase						:							pathlib.Path ):
				A									=   importlib.util.spec_from_file_location(file_path.name,    str(UpperCAmelCase ) )
				A									=   importlib.util.module_from_spec(UpperCAmelCase )  # type: ignore
				spec.loader.exec_module(UpperCAmelCase )  # type: ignore
				return module







def   snake_case		(				):
				A									=   []
				for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir():
								if problem_dir_path.is_file() or problem_dir_path.name.startswith('_' ):
												continue
								for file_path in problem_dir_path.iterdir():
												if file_path.suffix != ".py" or file_path.name.startswith(('_', 'test') ):
																continue
												solution_file_paths.append(UpperCAmelCase )
				return solution_file_paths







def   snake_case		(				):
				with open(os.environ['GITHUB_EVENT_PATH'] ) as file:
								A									=   json.load(UpperCAmelCase )
				return event["pull_request"]["url"] + "/files"







def   snake_case		(				):
				A									=   []
				A									=   {
				    'Accept': 'application/vnd.github.v3+json',
				    'Authorization': 'token ' + os.environ['GITHUB_TOKEN'],
				}
				A									=   requests.get(get_files_url(),    headers=UpperCAmelCase ).json()
				for file in files:
								A									=   pathlib.Path.cwd().joinpath(file['filename'] )
								if (
								    filepath.suffix != ".py"
								    or filepath.name.startswith(('_', 'test') )
								    or not filepath.name.startswith('sol' )
								):
												continue
								solution_file_paths.append(UpperCAmelCase )
				return solution_file_paths







def   snake_case		(				):
				if os.environ.get('CI' ) and os.environ.get('GITHUB_EVENT_NAME' ) == "pull_request":
								# Return only if there are any, otherwise default to all solutions
								if filepaths := added_solution_file_path():
												return filepaths
				return all_solution_file_paths()







@pytest.mark.parametrize(
    'solution_path',    collect_solution_file_paths(),    ids=lambda UpperCAmelCase : f'{path.parent.name}/{path.name}',    )
def   snake_case		(				UpperCAmelCase						:							pathlib.Path ):
				A									=   solution_path.parent.name[8:].zfill(3 )
				A									=   PROBLEM_ANSWERS[problem_number]
				A									=   convert_path_to_module(UpperCAmelCase )
				A									=   str(solution_module.solution() )  # type: ignore
				A									=   hashlib.shaaaa(answer.encode() ).hexdigest()
				assert (
				    answer == expected
				), f'Expected solution to {problem_number} to have hash {expected}, got {answer}'





