from ...configuration_utils import PretrainedConfig
from ...utils import logging


a_    					=       logging.get_logger(__name__)

a_    					=       {
    'microsoft/trocr-base-handwritten': (
        'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json'
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}





class 		_lowercase						(					snake_case_       ):
 lowercase				     =   'trocr'
 lowercase				     =   ['past_key_values']
 lowercase				     =   {
     'num_attention_heads': 'decoder_attention_heads',
     'hidden_size': 'd_model',
     'num_hidden_layers': 'decoder_layers',
 }

 def __init__( self	:							Optional[Any]   ,      snake_case	:							str=5_0_2_6_5   ,      snake_case	:							Optional[int]=1_0_2_4   ,      snake_case	:							int=1_2   ,      snake_case	:							str=1_6   ,      snake_case	:							List[Any]=4_0_9_6   ,      snake_case	:							List[Any]="gelu"   ,      snake_case	:							Optional[int]=5_1_2   ,      snake_case	:							Tuple=0.1   ,      snake_case	:							int=0.0   ,      snake_case	:							Optional[int]=0.0   ,      snake_case	:							Tuple=2   ,      snake_case	:							Tuple=0.02   ,      snake_case	:							Any=0.0   ,      snake_case	:							List[Any]=True   ,      snake_case	:							int=False   ,      snake_case	:							List[str]=True   ,      snake_case	:							str=True   ,      snake_case	:							Union[str, Any]=1   ,      snake_case	:							Optional[Any]=0   ,      snake_case	:							Any=2   ,      **snake_case	:							List[str]   ,      )   ->						Tuple:

  """simple docstring"""





  UpperCamelCase_					:						str =					vocab_size
  UpperCamelCase_					:						str =					d_model
  UpperCamelCase_					:						List[Any] =					decoder_layers
  UpperCamelCase_					:						Any =					decoder_attention_heads
  UpperCamelCase_					:						Tuple =					decoder_ffn_dim
  UpperCamelCase_					:						Optional[Any] =					activation_function
  UpperCamelCase_					:						List[str] =					max_position_embeddings
  UpperCamelCase_					:						Optional[int] =					dropout
  UpperCamelCase_					:						Optional[Any] =					attention_dropout
  UpperCamelCase_					:						Dict =					activation_dropout
  UpperCamelCase_					:						str =					init_std
  UpperCamelCase_					:						Dict =					decoder_layerdrop
  UpperCamelCase_					:						List[str] =					use_cache
  UpperCamelCase_					:						str =					scale_embedding
  UpperCamelCase_					:						List[str] =					use_learned_position_embeddings
  UpperCamelCase_					:						Optional[Any] =					layernorm_embedding

  super().__init__(
      pad_token_id=snake_case   ,      bos_token_id=snake_case   ,      eos_token_id=snake_case   ,      decoder_start_token_id=snake_case   ,      **snake_case   ,      )




import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)





def    __lowercase     (						lowerCamelCase					:     Dict  ,  lowerCamelCase					:     int=False	):
 try:
  UpperCamelCase_					:						Union[str, Any] =					os.environ[key]
 except KeyError:
  # KEY isn't set, default to `default`.
  UpperCamelCase_					:						List[str] =					default
 else:
  # KEY is set, convert it to True or False.
  try:
   UpperCamelCase_					:						Union[str, Any] =					strtobool(lowerCamelCase	)
  except ValueError:
   # More values are supported, but let's keep the message simple.
   raise ValueError(F"If set, {key} must be yes or no."	)
 return _value


a_    					=       parse_flag_from_env('RUN_SLOW', default=False)





def    __lowercase     (						lowerCamelCase					:     List[Any]	):
 return unittest.skip('Test was skipped'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     int	):
 return unittest.skipUnless(_run_slow_tests  ,  'test is slow'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     str	):
 return unittest.skipUnless(not torch.cuda.is_available()  ,  'test requires only a CPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Optional[Any]	):
 return unittest.skipUnless(torch.cuda.is_available()  ,  'test requires a GPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Any	):
 return unittest.skipUnless(is_xpu_available()  ,  'test requires a XPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Any	):
 return unittest.skipUnless(is_mps_available()  ,  'test requires a `mps` backend support in `torch`'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     str	):
 return unittest.skipUnless(
     is_transformers_available() and is_datasets_available()  ,  'test requires the Hugging Face suite'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     List[str]	):
 return unittest.skipUnless(is_bnb_available()  ,  'test requires the bitsandbytes library'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     str	):
 return unittest.skipUnless(is_tpu_available()  ,  'test requires TPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Tuple	):
 return unittest.skipUnless(torch.cuda.device_count() == 1  ,  'test requires a GPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Tuple	):
 return unittest.skipUnless(torch.xpu.device_count() == 1  ,  'test requires a XPU'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Optional[Any]	):
 return unittest.skipUnless(torch.cuda.device_count() > 1  ,  'test requires multiple GPUs'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     List[Any]	):
 return unittest.skipUnless(torch.xpu.device_count() > 1  ,  'test requires multiple XPUs'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     int	):
 return unittest.skipUnless(is_safetensors_available()  ,  'test requires safetensors'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Any	):
 return unittest.skipUnless(is_deepspeed_available()  ,  'test requires DeepSpeed'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Tuple	):
 return unittest.skipUnless(is_torch_version('>='  ,  '1.12.0'	)  ,  'test requires torch version >= 1.12.0'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     List[Any]=None  ,  lowerCamelCase					:     Optional[int]=None	):
 if test_case is None:
  return partial(lowerCamelCase  ,  version=lowerCamelCase	)
 return unittest.skipUnless(is_torch_version('>='  ,  lowerCamelCase	)  ,  F"test requires torch version >= {version}"	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     int	):
 return unittest.skipUnless(is_tensorboard_available()  ,  'test requires Tensorboard'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     int	):
 return unittest.skipUnless(is_wandb_available()  ,  'test requires wandb'	)(lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     Dict	):
 return unittest.skipUnless(is_comet_ml_available()  ,  'test requires comet_ml'	)(lowerCamelCase	)


a_    					=       (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)





def    __lowercase     (						lowerCamelCase					:     Dict	):
 return unittest.skipUnless(
     _atleast_one_tracker_available  ,  'test requires at least one tracker to be available and for `comet_ml` to not be installed'  ,  )(lowerCamelCase	)





class 		_lowercase						(					unittest.TestCase       ):
 lowercase				     =   True

 @classmethod
 def 						SCREAMING_SNAKE_CASE__   ( cls	:							Union[str, Any]			)   ->						Union[str, Any]:

  """simple docstring"""





  UpperCamelCase_					:						str =					tempfile.mkdtemp()

 @classmethod
 def 						SCREAMING_SNAKE_CASE__   ( cls	:							Any			)   ->						Union[str, Any]:

  """simple docstring"""





  if os.path.exists(cls.tmpdir			):
   shutil.rmtree(cls.tmpdir			)


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

  """simple docstring"""





  if self.clear_on_setup:
   for path in Path(self.tmpdir			).glob('**/*'			):
    if path.is_file():
     path.unlink()
    elif path.is_dir():
     shutil.rmtree(snake_case			)





class 		_lowercase						(					unittest.TestCase       ):

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]			)   ->						Any:

  """simple docstring"""





  super().tearDown()
  # Reset the state of the AcceleratorState singleton.
  AcceleratorState._reset_state()
  PartialState._reset_state()





class 		_lowercase						(					unittest.TestCase       ):

 def 						SCREAMING_SNAKE_CASE__   ( self	:							str   ,      snake_case	:							Union[mock.Mock, List[mock.Mock]]			)   ->						Optional[int]:

  """simple docstring"""





  UpperCamelCase_					:						str =					mocks if isinstance(snake_case   ,      (tuple, list)			) else [mocks]
  for m in self.mocks:
   m.start()
   self.addCleanup(m.stop			)





def    __lowercase     (						lowerCamelCase					:     Optional[Any]	):
 UpperCamelCase_					:						str =					AcceleratorState()
 UpperCamelCase_					:						str =					tensor[None].clone().to(state.device	)
 UpperCamelCase_					:						List[Any] =					gather(lowerCamelCase	).cpu()
 UpperCamelCase_					:						Tuple =					tensor[0].cpu()
 for i in range(tensors.shape[0]	):
  if not torch.equal(tensors[i]  ,  lowerCamelCase	):
   return False
 return True





class 		_lowercase						:

 def __init__( self	:							Optional[int]   ,      snake_case	:							Any   ,      snake_case	:							List[Any]   ,      snake_case	:							int			)   ->						Optional[int]:

  """simple docstring"""





  UpperCamelCase_					:						int =					returncode
  UpperCamelCase_					:						Optional[int] =					stdout
  UpperCamelCase_					:						Optional[int] =					stderr





async def    __lowercase     (						lowerCamelCase					:     Optional[Any]  ,  lowerCamelCase					:     Tuple	):
 while True:
  UpperCamelCase_					:						Tuple =					await stream.readline()
  if line:
   callback(lowerCamelCase	)
  else:
   break





async def    __lowercase     (						lowerCamelCase					:     Dict  ,  lowerCamelCase					:     Dict=None  ,  lowerCamelCase					:     Optional[Any]=None  ,  lowerCamelCase					:     List[str]=None  ,  lowerCamelCase					:     Dict=False  ,  lowerCamelCase					:     Tuple=False	):
 if echo:
  print('\nRunning: '  ,  ' '.join(lowerCamelCase	)	)

 UpperCamelCase_					:						Optional[int] =					await asyncio.create_subprocess_exec(
     cmd[0]  ,  *cmd[1:]  ,  stdin=lowerCamelCase  ,  stdout=asyncio.subprocess.PIPE  ,  stderr=asyncio.subprocess.PIPE  ,  env=lowerCamelCase  ,  )

 # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
 # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
 #
 # If it starts hanging, will need to switch to the following code. The problem is that no data
 # will be seen until it's done and if it hangs for example there will be no debug info.
 # out, err = await p.communicate()
 # return _RunOutput(p.returncode, out, err)

 UpperCamelCase_					:						str =					[]
 UpperCamelCase_					:						Union[str, Any] =					[]

 def tee(lowerCamelCase					:     Tuple  ,  lowerCamelCase					:     Optional[Any]  ,  lowerCamelCase					:     Any  ,  lowerCamelCase					:     List[str]=""	):
  UpperCamelCase_					:						int =					line.decode('utf-8'	).rstrip()
  sink.append(lowerCamelCase	)
  if not quiet:
   print(lowerCamelCase  ,  lowerCamelCase  ,  file=lowerCamelCase	)

    # XXX: the timeout doesn't seem to make any difference here
 await asyncio.wait(
     [
         asyncio.create_task(_read_stream(p.stdout  ,  lambda lowerCamelCase	: tee(lowerCamelCase  ,  lowerCamelCase  ,  sys.stdout  ,  label='stdout:'	)	)	),
         asyncio.create_task(_read_stream(p.stderr  ,  lambda lowerCamelCase	: tee(lowerCamelCase  ,  lowerCamelCase  ,  sys.stderr  ,  label='stderr:'	)	)	),
     ]  ,  timeout=lowerCamelCase  ,  )
 return _RunOutput(await p.wait()  ,  lowerCamelCase  ,  lowerCamelCase	)





def    __lowercase     (						lowerCamelCase					:     List[Any]  ,  lowerCamelCase					:     Optional[Any]=None  ,  lowerCamelCase					:     int=None  ,  lowerCamelCase					:     Any=180  ,  lowerCamelCase					:     Dict=False  ,  lowerCamelCase					:     Optional[int]=True	):
 UpperCamelCase_					:						str =					asyncio.get_event_loop()
 UpperCamelCase_					:						Union[str, Any] =					loop.run_until_complete(
     _stream_subprocess(lowerCamelCase  ,  env=lowerCamelCase  ,  stdin=lowerCamelCase  ,  timeout=lowerCamelCase  ,  quiet=lowerCamelCase  ,  echo=lowerCamelCase	)	)

 UpperCamelCase_					:						int =					' '.join(lowerCamelCase	)
 if result.returncode > 0:
  UpperCamelCase_					:						Dict =					'\n'.join(result.stderr	)
  raise RuntimeError(
      F"'{cmd_str}' failed with returncode {result.returncode}\n\n"
      F"The combined stderr from workers follows:\n{stderr}"	)

 return result





class 		_lowercase						(					snake_case_       ):
 pass





def    __lowercase     (						lowerCamelCase					:     List[str]  ,  lowerCamelCase					:     Optional[int]=False	):
 try:
  UpperCamelCase_					:						Any =					subprocess.check_output(lowerCamelCase  ,  stderr=subprocess.STDOUT	)
  if return_stdout:
   if hasattr(lowerCamelCase  ,  'decode'	):
    UpperCamelCase_					:						Any =					output.decode('utf-8'	)
   return output
 except subprocess.CalledProcessError as e:
  raise SubprocessCallException(
      F"Command `{' '.join(lowerCamelCase	)}` failed with the following error:\n\n{e.output.decode()}"	) from e



