



'''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 							a__:







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

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

      a		:      Tuple       =  None
      a		:      int       =  decoder_seq_length
      a		:      Optional[int]       =  2
      a		:      Optional[int]       =  1







    def     lowercase_ (   self				:						Optional[Any]			):
      a		:      List[str]       =  ids_tensor([self.batch_size, self.decoder_seq_length]		,    self.vocab_size			)

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

      a		:      str       =  None
      if self.use_labels:
        a		:      Optional[Any]       =  ids_tensor([self.batch_size, self.decoder_seq_length]		,    self.vocab_size			)

      a		:      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     lowercase_ (   self				:						Tuple		,    __snake_case				:						Any		,    __snake_case				:						List[Any]		,    __snake_case				:						Any		,    __snake_case				:						str		,    ):
      a		:      Optional[Any]       =  True
      a		:      str       =  TrOCRDecoder(config=__snake_case			).to(__snake_case			).eval()
      a		:      List[str]       =  input_ids[:2]

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

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

      a		:      str       =  outputs['past_key_values']

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

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

      a		:      Any       =  model(__snake_case			)['last_hidden_state']
      a		:      Optional[int]       =  model(__snake_case		,    past_key_values=__snake_case			)['last_hidden_state']

      # select random slice
      a		:      Tuple       =  ids_tensor((1,)		,    output_from_past.shape[-1]			).item()
      a		:      Any       =  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(__snake_case		,    __snake_case		,    atol=1e-3			)







    def     lowercase_ (   self				:						List[Any]			):
      a		:      Union[str, Any]       =  self.prepare_config_and_inputs()
      a     ,			a     ,			a     ,			a		:      Union[str, Any]       =  config_and_inputs

      a		:      Dict       =  {'input_ids': input_ids, 'attention_mask': attention_mask}
      return config, inputs_dict

@require_torch
class 							a__(      lowerCamelCase__	,				lowerCamelCase__	,				lowerCamelCase__	,				unittest.TestCase			):
    lowercase__				=					(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
    lowercase__				=					(TrOCRForCausalLM,) if is_torch_available() else ()
    lowercase__				=					{"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {}
    lowercase__				=					True
    lowercase__				=					False







    def     lowercase_ (   self				:						Union[str, Any]			):
      a		:      Any       =  TrOCRStandaloneDecoderModelTester(self		,    is_training=__snake_case			)
      a		:      str       =  ConfigTester(self		,    config_class=__snake_case			)







    def     lowercase_ (   self				:						Dict			):
      pass







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







    def     lowercase_ (   self				:						List[Any]			):
      pass







    def     lowercase_ (   self				:						List[str]			):
      self.config_tester.run_common_tests()







    def     lowercase_ (   self				:						Optional[int]			):
      a		:      Any       =  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_decoder_model_past(*__snake_case			)







    def     lowercase_ (   self				:						List[str]			):
      return







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




'''simple docstring'''






import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand
def    lowerCamelCase__ (		_A       ):
  return EnvironmentCommand()

class 							a__(      lowerCamelCase__			):







    @staticmethod
    def     lowercase_ (   __snake_case				:						ArgumentParser			):
      a		:      Tuple       =  parser.add_parser('env'			)
      download_parser.set_defaults(func=__snake_case			)







    def     lowercase_ (   self				:						List[str]			):
      a		:      str       =  huggingface_hub.__version__

      a		:      List[str]       =  'not installed'
      a		:      List[str]       =  'NA'
      if is_torch_available():
        import torch

        a		:      Optional[Any]       =  torch.__version__
        a		:      int       =  torch.cuda.is_available()

      a		:      Optional[int]       =  'not installed'
      if is_transformers_available():
        import transformers

        a		:      Tuple       =  transformers.__version__

      a		:      Dict       =  'not installed'
      if is_accelerate_available():
        import accelerate

        a		:      int       =  accelerate.__version__

      a		:      Any       =  'not installed'
      if is_xformers_available():
        import xformers

        a		:      Optional[int]       =  xformers.__version__

      a		:      List[str]       =  {
          '`diffusers` version': version,
          'Platform': platform.platform(),
          'Python version': platform.python_version(),
          'PyTorch version (GPU?)': F"""{pt_version} ({pt_cuda_available})""",
          'Huggingface_hub version': hub_version,
          'Transformers version': transformers_version,
          'Accelerate version': accelerate_version,
          'xFormers version': xformers_version,
          'Using GPU in script?': '<fill in>',
          'Using distributed or parallel set-up in script?': '<fill in>',
      }

      print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'			)
      print(self.format_dict(__snake_case			)			)

      return info







    @staticmethod
    def     lowercase_ (   __snake_case				:						Union[str, Any]			):
      return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()]			) + "\n"