


'''simple docstring'''
import unittest

from transformers import TrOCRConfig
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.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM

@require_torch
class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase=99      ,      __lowercase=13      ,      __lowercase=16      ,      __lowercase=7      ,      __lowercase=True      ,      __lowercase=True      ,      __lowercase=True      ,      __lowercase=False      ,      __lowercase=True      ,      __lowercase=2      ,      __lowercase=32      ,      __lowercase=4      ,      __lowercase=4      ,      __lowercase=30      ,      __lowercase=0      ,      __lowercase=1      ,      __lowercase=2      ,      __lowercase=None      ,      ):

  """simple docstring"""







  __A  :		Optional[Any]       =			parent
  __A  :		List[str]       =			batch_size
  __A  :		str       =			decoder_seq_length
  # For common tests
  __A  :		Any       =			self.decoder_seq_length
  __A  :		Optional[Any]       =			is_training
  __A  :		List[str]       =			use_attention_mask
  __A  :		int       =			use_labels

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

  __A  :		Optional[Any]       =			None
  __A  :		Optional[int]       =			decoder_seq_length
  __A  :		Optional[int]       =			2
  __A  :		Union[str, Any]       =			1


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[int]       =			ids_tensor([self.batch_size, self.decoder_seq_length]      ,      self.vocab_size						)

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

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

  __A  :		List[Any]       =			TrOCRConfig(
      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  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      __lowercase      ,      ):

  """simple docstring"""







  __A  :		Optional[int]       =			True
  __A  :		Dict       =			TrOCRDecoder(config=__lowercase						).to(__lowercase						).eval()
  __A  :		int       =			input_ids[:2]

  input_ids[input_ids == 0] += 1
  # first forward pass
  __A  :		Tuple       =			model(__lowercase      ,      use_cache=__lowercase						)
  __A  :		Tuple       =			model(__lowercase						)
  __A  :		Any       =			model(__lowercase      ,      use_cache=__lowercase						)

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

  __A  :		Any       =			outputs['past_key_values']

  # create hypothetical next token and extent to next_input_ids
  __A  :		List[Any]       =			ids_tensor((2, 1)      ,      config.vocab_size - 1						) + 1

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

  __A  :		Dict       =			model(__lowercase						)['last_hidden_state']
  __A  :		Dict       =			model(__lowercase      ,      past_key_values=__lowercase						)['last_hidden_state']

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

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







 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		int       =			self.prepare_config_and_inputs()
  __A     ,__A     ,__A     ,__A  :		int       =			config_and_inputs

  __A  :		List[str]       =			{'input_ids': input_ids, 'attention_mask': attention_mask}
  return config, inputs_dict


@require_torch
class 						_lowerCamelCase					(    snake_case_    ,		snake_case_    ,		snake_case_    ,		unittest.TestCase				):




 '''simple docstring'''
 __lowercase				:		Any    							=						(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
 __lowercase				:		Dict    							=						(TrOCRForCausalLM,) if is_torch_available() else ()
 __lowercase				:		Any    							=						{'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {}
 __lowercase				:		str    							=						True
 __lowercase				:		Tuple    							=						False


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Union[str, Any]       =			TrOCRStandaloneDecoderModelTester(self      ,      is_training=__lowercase						)
  __A  :		int       =			ConfigTester(self      ,      config_class=__lowercase						)


 def  snake_case__   (      self						):

  """simple docstring"""







  pass


 def  snake_case__   (      self						):

  """simple docstring"""







  pass


 def  snake_case__   (      self						):

  """simple docstring"""







  pass


 def  snake_case__   (      self						):

  """simple docstring"""







  self.config_tester.run_common_tests()


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		int       =			self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_decoder_model_past(*__lowercase						)


 def  snake_case__   (      self						):

  """simple docstring"""







  return







 @unittest.skip('The model doesn\'t support left padding'						)  # and it's not used enough to be worth fixing :)
 def  snake_case__   (      self						):

  """simple docstring"""







  pass










'''simple docstring'''
from __future__ import annotations

import math
import random
from collections.abc import Collection
from typing import overload

class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase = None						):

  """simple docstring"""







  if components is None:
   __A  :		Optional[int]       =			[]
  __A  :		Dict       =			list(__lowercase						)


 def __len__(      self						):

  """simple docstring"""







  return len(self.__components						)


 def __str__(      self						):

  """simple docstring"""







  return "(" + ",".join(map(__lowercase      ,      self.__components						)						) + ")"


 def __add__(      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		Union[str, Any]       =			len(self						)
  if size == len(__lowercase						):
   __A  :		Dict       =			[self.__components[i] + other.component(__lowercase						) for i in range(__lowercase						)]
   return Vector(__lowercase						)
  else:
   raise Exception('must have the same size'						)


 def __sub__(      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		int       =			len(self						)
  if size == len(__lowercase						):
   __A  :		str       =			[self.__components[i] - other.component(__lowercase						) for i in range(__lowercase						)]
   return Vector(__lowercase						)
  else:  # error case
   raise Exception('must have the same size'						)


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      (float, int)						):
   __A  :		Dict       =			[c * other for c in self.__components]
   return Vector(__lowercase						)
  elif isinstance(__lowercase      ,      __lowercase						) and len(self						) == len(__lowercase						):
   __A  :		Optional[Any]       =			len(self						)
   __A  :		Optional[int]       =			[self.__components[i] * other.component(__lowercase						) for i in range(__lowercase						)]
   return sum(__lowercase						)
  else:  # error case
   raise Exception('invalid operand!'						)


 def  snake_case__   (      self						):

  """simple docstring"""







  return Vector(self.__components						)


 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      __lowercase						) and -len(self.__components						) <= i < len(self.__components						):
   return self.__components[i]
  else:
   raise Exception('index out of range'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  assert -len(self.__components						) <= pos < len(self.__components						)
  __A  :		str       =			value


 def  snake_case__   (      self						):

  """simple docstring"""







  if len(self.__components						) == 0:
   raise Exception('Vector is empty'						)
  __A  :		List[Any]       =			[c**2 for c in self.__components]
  return math.sqrt(sum(__lowercase						)						)







 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase = False						):

  """simple docstring"""







  __A  :		List[Any]       =			self * other
  __A  :		Any       =			self.euclidean_length() * other.euclidean_length()
  if deg:
   return math.degrees(math.acos(num / den						)						)
  else:
   return math.acos(num / den						)


def 			_lowercase       (				UpperCamelCase__       :					int			):
 assert isinstance(UpperCamelCase__,				UpperCamelCase__			)
 return Vector([0] * dimension			)


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 assert isinstance(UpperCamelCase__,				UpperCamelCase__			) and (isinstance(UpperCamelCase__,				UpperCamelCase__			))
 __A  :		List[str]       =			[0] * dimension
 __A  :		Tuple       =			1
 return Vector(UpperCamelCase__			)


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					Vector,				UpperCamelCase__       :					Vector			):
 assert (
     isinstance(UpperCamelCase__,				UpperCamelCase__			)
     and isinstance(UpperCamelCase__,				UpperCamelCase__			)
     and (isinstance(UpperCamelCase__,				(int, float)			))
 )
 return x * scalar + y


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 random.seed(UpperCamelCase__			)
 __A  :		Any       =			[random.randint(UpperCamelCase__,				UpperCamelCase__			) for _ in range(UpperCamelCase__			)]
 return Vector(UpperCamelCase__			)

class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  __A  :		str       =			matrix
  __A  :		str       =			w
  __A  :		Dict       =			h


 def __str__(      self						):

  """simple docstring"""







  __A  :		Tuple       =			''
  for i in range(self.__height						):
   ans += "|"
   for j in range(self.__width						):
    if j < self.__width - 1:
     ans += str(self.__matrix[i][j]						) + ","
    else:
     ans += str(self.__matrix[i][j]						) + "|\n"
  return ans


 def __add__(      self      ,      __lowercase						):

  """simple docstring"""







  if self.__width == other.width() and self.__height == other.height():
   __A  :		Union[str, Any]       =			[]
   for i in range(self.__height						):
    __A  :		List[Any]       =			[
        self.__matrix[i][j] + other.component(__lowercase      ,      __lowercase						)
        for j in range(self.__width						)
    ]
    matrix.append(__lowercase						)
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  else:
   raise Exception('matrix must have the same dimension!'						)


 def __sub__(      self      ,      __lowercase						):

  """simple docstring"""







  if self.__width == other.width() and self.__height == other.height():
   __A  :		Dict       =			[]
   for i in range(self.__height						):
    __A  :		str       =			[
        self.__matrix[i][j] - other.component(__lowercase      ,      __lowercase						)
        for j in range(self.__width						)
    ]
    matrix.append(__lowercase						)
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  else:
   raise Exception('matrices must have the same dimension!'						)


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      __lowercase						):  # matrix-vector
   if len(__lowercase						) == self.__width:
    __A  :		Tuple       =			zero_vector(self.__height						)
    for i in range(self.__height						):
     __A  :		Any       =			[
         self.__matrix[i][j] * other.component(__lowercase						)
         for j in range(self.__width						)
     ]
     ans.change_component(__lowercase      ,      sum(__lowercase						)						)
    return ans
   else:
    raise Exception(
        'vector must have the same size as the '
        'number of columns of the matrix!'						)
  elif isinstance(__lowercase      ,      (int, float)						):  # matrix-scalar
   __A  :		Optional[Any]       =			[
       [self.__matrix[i][j] * other for j in range(self.__width						)]
       for i in range(self.__height						)
   ]
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  return None


 def  snake_case__   (      self						):

  """simple docstring"""







  return self.__height


 def  snake_case__   (      self						):

  """simple docstring"""







  return self.__width


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if 0 <= x < self.__height and 0 <= y < self.__width:
   return self.__matrix[x][y]
  else:
   raise Exception('change_component: indices out of bounds'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if 0 <= x < self.__height and 0 <= y < self.__width:
   __A  :		Dict       =			value
  else:
   raise Exception('change_component: indices out of bounds'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  __A  :		Union[str, Any]       =			self.__matrix[:x] + self.__matrix[x + 1 :]
  for i in range(len(__lowercase						)						):
   __A  :		Dict       =			minor[i][:y] + minor[i][y + 1 :]
  return Matrix(__lowercase      ,      self.__width - 1      ,      self.__height - 1						).determinant()


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  if 0 <= x < self.__height and 0 <= y < self.__width:
   return (-1) ** (x + y) * self.minor(__lowercase      ,      __lowercase						)
  else:
   raise Exception('Indices out of bounds'						)







 def  snake_case__   (      self						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  if self.__height < 1:
   raise Exception('Matrix has no element'						)
  elif self.__height == 1:
   return self.__matrix[0][0]
  elif self.__height == 2:
   return (
       self.__matrix[0][0] * self.__matrix[1][1]
       - self.__matrix[0][1] * self.__matrix[1][0]
   )
  else:
   __A  :		List[str]       =			[
       self.__matrix[0][y] * self.cofactor(0      ,      __lowercase						) for y in range(self.__width						)
   ]
   return sum(__lowercase						)


def 			_lowercase       (				UpperCamelCase__       :					int			):
 __A  :		list[list[float]]       =			[[0] * n for _ in range(UpperCamelCase__			)]
 return Matrix(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 random.seed(UpperCamelCase__			)
 __A  :		list[list[float]]       =			[
     [random.randint(UpperCamelCase__,				UpperCamelCase__			) for _ in range(UpperCamelCase__			)] for _ in range(UpperCamelCase__			)
 ]
 return Matrix(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)






