'''simple docstring'''




import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import MODEL_MAPPING, GLPNConfig, GLPNForDepthEstimation, GLPNModel
  from transformers.models.glpn.modeling_glpn import GLPN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import GLPNImageProcessor

class      lowerCamelCase_     (snake_case__   ):
      '''simple docstring'''

      def 					_A     (	self						:    Optional[int]	):
             _UpperCAmelCase					:  List[str]											=   self.config_class(**self.inputs_dict	)
             self.parent.assertTrue(hasattr(A						, "hidden_sizes"	)	)
             self.parent.assertTrue(hasattr(A						, "num_attention_heads"	)	)
             self.parent.assertTrue(hasattr(A						, "num_encoder_blocks"	)	)

class      lowerCamelCase_     :
      '''simple docstring'''

      def __init__(	self						:    str						, A						:    Optional[int]						, A						:    List[Any]=13						, A						:    Union[str, Any]=64						, A						:    List[str]=3						, A						:    str=4						, A						:    List[str]=[2, 2, 2, 2]						, A						:    Dict=[8, 4, 2, 1]						, A						:    int=[16, 32, 64, 128]						, A						:    Any=[1, 4, 8, 16]						, A						:    List[Any]=[1, 2, 4, 8]						, A						:    Tuple=True						, A						:    int=True						, A						:    Optional[int]="gelu"						, A						:    int=0.1						, A						:    List[str]=0.1						, A						:    Tuple=0.02						, A						:    List[Any]=16						, A						:    int=3						, A						:    Dict=None						, ):
             _UpperCAmelCase					:  str											=   parent
             _UpperCAmelCase					:  Dict											=   batch_size
             _UpperCAmelCase					:  List[str]											=   image_size
             _UpperCAmelCase					:  List[str]											=   num_channels
             _UpperCAmelCase					:  List[str]											=   num_encoder_blocks
             _UpperCAmelCase					:  str											=   sr_ratios
             _UpperCAmelCase					:  Tuple											=   depths
             _UpperCAmelCase					:  Union[str, Any]											=   hidden_sizes
             _UpperCAmelCase					:  Optional[Any]											=   downsampling_rates
             _UpperCAmelCase					:  Union[str, Any]											=   num_attention_heads
             _UpperCAmelCase					:  Any											=   is_training
             _UpperCAmelCase					:  int											=   use_labels
             _UpperCAmelCase					:  Tuple											=   hidden_act
             _UpperCAmelCase					:  Optional[int]											=   hidden_dropout_prob
             _UpperCAmelCase					:  List[Any]											=   attention_probs_dropout_prob
             _UpperCAmelCase					:  Union[str, Any]											=   initializer_range
             _UpperCAmelCase					:  Optional[int]											=   decoder_hidden_size
             _UpperCAmelCase					:  Union[str, Any]											=   num_labels
             _UpperCAmelCase					:  Any											=   scope




      def 					_A     (	self						:    List[Any]	):
             _UpperCAmelCase					:  Dict											=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

             _UpperCAmelCase					:  Union[str, Any]											=   None
             if self.use_labels:
                    _UpperCAmelCase					:  List[str]											=   ids_tensor([self.batch_size, self.image_size, self.image_size]						, self.num_labels	)

             _UpperCAmelCase					:  Optional[Any]											=   self.get_config()
             return config, pixel_values, labels




      def 					_A     (	self						:    Any	):
             return GLPNConfig(
                 image_size=self.image_size						, num_channels=self.num_channels						, num_encoder_blocks=self.num_encoder_blocks						, depths=self.depths						, hidden_sizes=self.hidden_sizes						, num_attention_heads=self.num_attention_heads						, hidden_act=self.hidden_act						, hidden_dropout_prob=self.hidden_dropout_prob						, attention_probs_dropout_prob=self.attention_probs_dropout_prob						, initializer_range=self.initializer_range						, decoder_hidden_size=self.decoder_hidden_size						, )




      def 					_A     (	self						:    Tuple						, A						:    str						, A						:    List[Any]						, A						:    int	):
             _UpperCAmelCase					:  Union[str, Any]											=   GLPNModel(config=A	)
             model.to(A	)
             model.eval()
             _UpperCAmelCase					:  Union[str, Any]											=   model(A	)
             _UpperCAmelCase					:  List[str]											=   self.image_size // (self.downsampling_rates[-1] * 2)
             self.parent.assertEqual(
                 result.last_hidden_state.shape						, (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)	)




      def 					_A     (	self						:    int						, A						:    Any						, A						:    Union[str, Any]						, A						:    Optional[int]	):
             _UpperCAmelCase					:  Any											=   self.num_labels
             _UpperCAmelCase					:  Any											=   GLPNForDepthEstimation(A	)
             model.to(A	)
             model.eval()
             _UpperCAmelCase					:  Tuple											=   model(A	)
             self.parent.assertEqual(result.predicted_depth.shape						, (self.batch_size, self.image_size, self.image_size)	)
             _UpperCAmelCase					:  str											=   model(A						, labels=A	)
             self.parent.assertEqual(result.predicted_depth.shape						, (self.batch_size, self.image_size, self.image_size)	)





      def 					_A     (	self						:    Optional[Any]	):
             _UpperCAmelCase					:  Optional[Any]											=   self.prepare_config_and_inputs()
             _UpperCAmelCase				,  _UpperCAmelCase				,  _UpperCAmelCase					:  Tuple											=   config_and_inputs
             _UpperCAmelCase					:  List[str]											=   {"pixel_values": pixel_values}
             return config, inputs_dict

@require_torch
class      lowerCamelCase_     (snake_case__							,			snake_case__							,			unittest.TestCase   ):
      '''simple docstring'''

      __UpperCamelCase:  List[Any]      =						(GLPNModel, GLPNForDepthEstimation) if is_torch_available() else ()
      __UpperCamelCase:  str      =						(
          {"depth-estimation": GLPNForDepthEstimation, "feature-extraction": GLPNModel} if is_torch_available() else {}
      )

      __UpperCamelCase:  Any      =						False
      __UpperCamelCase:  Union[str, Any]      =						False
      __UpperCamelCase:  Union[str, Any]      =						False




      def 					_A     (	self						:    Optional[Any]	):
             _UpperCAmelCase					:  str											=   GLPNModelTester(self	)
             _UpperCAmelCase					:  str											=   GLPNConfigTester(self						, config_class=A	)




      def 					_A     (	self						:    Tuple	):
             self.config_tester.run_common_tests()




      def 					_A     (	self						:    Any	):
             _UpperCAmelCase					:  Any											=   self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*A	)




      def 					_A     (	self						:    Optional[Any]	):
             _UpperCAmelCase					:  List[str]											=   self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_depth_estimation(*A	)




      @unittest.skip("GLPN does not use inputs_embeds"	)
      def 					_A     (	self						:    Optional[int]	):
             pass




      @unittest.skip("GLPN does not have get_input_embeddings method and get_output_embeddings methods"	)
      def 					_A     (	self						:    Optional[int]	):
             pass




      def 					_A     (	self						:    int	):
             _UpperCAmelCase				,  _UpperCAmelCase					:  Optional[int]											=   self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _UpperCAmelCase					:  List[Any]											=   model_class(A	)
                    _UpperCAmelCase					:  str											=   inspect.signature(model.forward	)
                    # signature.parameters is an OrderedDict => so arg_names order is deterministic
                    _UpperCAmelCase					:  Union[str, Any]											=   [*signature.parameters.keys()]

                    _UpperCAmelCase					:  Dict											=   ["pixel_values"]
                    self.assertListEqual(arg_names[:1]						, A	)




      def 					_A     (	self						:    Any	):
             _UpperCAmelCase				,  _UpperCAmelCase					:  Tuple											=   self.model_tester.prepare_config_and_inputs_for_common()
             _UpperCAmelCase					:  Dict											=   True

             for model_class in self.all_model_classes:
                    _UpperCAmelCase					:  Union[str, Any]											=   True
                    _UpperCAmelCase					:  Any											=   False
                    _UpperCAmelCase					:  Tuple											=   True
                    _UpperCAmelCase					:  Any											=   model_class(A	)
                    model.to(A	)
                    model.eval()
                    with torch.no_grad():
                           _UpperCAmelCase					:  Optional[Any]											=   model(**self._prepare_for_class(A						, A	)	)
                    _UpperCAmelCase					:  Dict											=   outputs.attentions

                    _UpperCAmelCase					:  Any											=   sum(self.model_tester.depths	)
                    self.assertEqual(len(A	)						, A	)

                    # check that output_attentions also work using config
                    del inputs_dict["output_attentions"]
                    _UpperCAmelCase					:  Union[str, Any]											=   True
                    _UpperCAmelCase					:  List[Any]											=   model_class(A	)
                    model.to(A	)
                    model.eval()
                    with torch.no_grad():
                           _UpperCAmelCase					:  str											=   model(**self._prepare_for_class(A						, A	)	)
                    _UpperCAmelCase					:  Any											=   outputs.attentions

                    self.assertEqual(len(A	)						, A	)

                    # verify the first attentions (first block, first layer)
                    _UpperCAmelCase					:  int											=   (self.model_tester.image_size // 4) ** 2
                    _UpperCAmelCase					:  Optional[Any]											=   (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
                    self.assertListEqual(
                        list(attentions[0].shape[-3:]	)						, [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]						, )

                    # verify the last attentions (last block, last layer)
                    _UpperCAmelCase					:  Any											=   (self.model_tester.image_size // 32) ** 2
                    _UpperCAmelCase					:  Optional[int]											=   (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
                    self.assertListEqual(
                        list(attentions[-1].shape[-3:]	)						, [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]						, )
                    _UpperCAmelCase					:  List[str]											=   len(A	)

                    # Check attention is always last and order is fine
                    _UpperCAmelCase					:  str											=   True
                    _UpperCAmelCase					:  List[str]											=   True
                    _UpperCAmelCase					:  Dict											=   model_class(A	)
                    model.to(A	)
                    model.eval()
                    with torch.no_grad():
                           _UpperCAmelCase					:  List[Any]											=   model(**self._prepare_for_class(A						, A	)	)

                    self.assertEqual(out_len + 1						, len(A	)	)

                    _UpperCAmelCase					:  Any											=   outputs.attentions

                    self.assertEqual(len(A	)						, A	)
                    # verify the first attentions (first block, first layer)
                    _UpperCAmelCase					:  str											=   (self.model_tester.image_size // 4) ** 2
                    _UpperCAmelCase					:  int											=   (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
                    self.assertListEqual(
                        list(self_attentions[0].shape[-3:]	)						, [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]						, )




      def 					_A     (	self						:    Dict	):
             def check_hidden_states_output(A						:    Dict						, A						:    Dict						, A						:    Dict	):
                    _UpperCAmelCase					:  Optional[int]											=   model_class(A	)
                    model.to(A	)
                    model.eval()

                    with torch.no_grad():
                           _UpperCAmelCase					:  List[str]											=   model(**self._prepare_for_class(A						, A	)	)

                    _UpperCAmelCase					:  Tuple											=   outputs.hidden_states

                    _UpperCAmelCase					:  Union[str, Any]											=   self.model_tester.num_encoder_blocks
                    self.assertEqual(len(A	)						, A	)

                    # verify the first hidden states (first block)
                    self.assertListEqual(
                        list(hidden_states[0].shape[-3:]	)						, [
                            self.model_tester.hidden_sizes[0],
                            self.model_tester.image_size // 4,
                            self.model_tester.image_size // 4,
                        ]						, )

             _UpperCAmelCase				,  _UpperCAmelCase					:  Union[str, Any]											=   self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _UpperCAmelCase					:  int											=   True
                    check_hidden_states_output(A						, A						, A	)

                    # check that output_hidden_states also work using config
                    del inputs_dict["output_hidden_states"]
                    _UpperCAmelCase					:  Tuple											=   True

                    check_hidden_states_output(A						, A						, A	)




      def 					_A     (	self						:    int	):
             if not self.model_tester.is_training:
                    return

             _UpperCAmelCase				,  _UpperCAmelCase					:  Optional[Any]											=   self.model_tester.prepare_config_and_inputs_for_common()
             _UpperCAmelCase					:  List[str]											=   True

             for model_class in self.all_model_classes:
                    if model_class in get_values(A	):
                           continue
                    # TODO: remove the following 3 lines once we have a MODEL_FOR_DEPTH_ESTIMATION_MAPPING
                    # this can then be incorporated into _prepare_for_class in test_modeling_common.py
                    if model_class.__name__ == "GLPNForDepthEstimation":
                           _UpperCAmelCase				,  _UpperCAmelCase				,  _UpperCAmelCase				,  _UpperCAmelCase					:  str											=   inputs_dict["pixel_values"].shape
                           _UpperCAmelCase					:  List[Any]											=   torch.zeros(
                               [self.model_tester.batch_size, height, width]						, device=A	).long()
                    _UpperCAmelCase					:  Optional[Any]											=   model_class(A	)
                    model.to(A	)
                    model.train()
                    _UpperCAmelCase					:  Dict											=   self._prepare_for_class(A						, A						, return_labels=A	)
                    _UpperCAmelCase					:  List[str]											=   model(**A	).loss
                    loss.backward()





      @slow
      def 					_A     (	self						:    Any	):
             for model_name in GLPN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _UpperCAmelCase					:  Union[str, Any]											=   GLPNModel.from_pretrained(A	)
                    self.assertIsNotNone(A	)

def      UpperCamelCase_							( )   ->   str:


       """simple docstring"""







       _UpperCAmelCase					:  Optional[Any]											=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
       return image


@require_torch
@require_vision
@slow
class      lowerCamelCase_     (unittest.TestCase   ):
      '''simple docstring'''

      @slow
      def 					_A     (	self						:    Optional[Any]	):
             _UpperCAmelCase					:  Union[str, Any]											=   GLPNImageProcessor.from_pretrained(GLPN_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
             _UpperCAmelCase					:  List[Any]											=   GLPNForDepthEstimation.from_pretrained(GLPN_PRETRAINED_MODEL_ARCHIVE_LIST[0]	).to(A	)

             _UpperCAmelCase					:  str											=   prepare_img()
             _UpperCAmelCase					:  Optional[int]											=   image_processor(images=A						, return_tensors="pt"	).to(A	)

             # forward pass
             with torch.no_grad():
                    _UpperCAmelCase					:  Optional[int]											=   model(**A	)

             # verify the predicted depth
             _UpperCAmelCase					:  int											=   torch.Size([1, 480, 640]	)
             self.assertEqual(outputs.predicted_depth.shape						, A	)

             _UpperCAmelCase					:  Optional[Any]											=   torch.tensor(
                 [[3.4_291, 2.7_865, 2.5_151], [3.2_841, 2.7_021, 2.3_502], [3.1_147, 2.4_625, 2.2_481]]	).to(A	)

             self.assertTrue(torch.allclose(outputs.predicted_depth[0, :3, :3]						, A						, atol=1E-4	)	)


'''simple docstring'''




def      UpperCamelCase_							( _UpperCAmelCase  :				Optional[int]      ,     _UpperCAmelCase  :				List[Any]   )   ->   List[str]:


       """simple docstring"""







       if len(str(_UpperCAmelCase   )   ) == 1 or len(str(_UpperCAmelCase   )   ) == 1:
              return a * b

       _UpperCAmelCase					:  Any											=   max(len(str(_UpperCAmelCase   )   )      ,     len(str(_UpperCAmelCase   )   )   )
       _UpperCAmelCase					:  Any											=   ma // 2

       _UpperCAmelCase				,  _UpperCAmelCase					:  Union[str, Any]											=   divmod(_UpperCAmelCase      ,     10**ma   )
       _UpperCAmelCase				,  _UpperCAmelCase					:  int											=   divmod(_UpperCAmelCase      ,     10**ma   )

       _UpperCAmelCase					:  List[str]											=   karatsuba(_UpperCAmelCase      ,     _UpperCAmelCase   )
       _UpperCAmelCase					:  int											=   karatsuba((aa + aa)      ,     (ba + ba)   )
       _UpperCAmelCase					:  Any											=   karatsuba(_UpperCAmelCase      ,     _UpperCAmelCase   )

       return (z * 10 ** (2 * ma)) + ((y - z - x) * 10 ** (ma)) + (x)

def      UpperCamelCase_							( )   ->   List[str]:


       """simple docstring"""







       print(karatsuba(15_463      ,     23_489   )   )


if __name__ == "__main__":
  main()

