




'''simple docstring'''




import inspect
import unittest

import requests

from transformers import MgpstrConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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


if is_torch_available():
     import torch
     from torch import nn

     from transformers import MgpstrForSceneTextRecognition


if is_vision_available():
     from PIL import Image

     from transformers import MgpstrProcessor


class 						__UpperCamelCase :






       def __init__(							self,	lowerCAmelCase,	lowerCAmelCase=False,	lowerCAmelCase=13,	lowerCAmelCase=(32, 128),	lowerCAmelCase=4,	lowerCAmelCase=3,	lowerCAmelCase=27,	lowerCAmelCase=38,	lowerCAmelCase=99,	lowerCAmelCase=99,	lowerCAmelCase=32,	lowerCAmelCase=5,	lowerCAmelCase=4,	lowerCAmelCase=4.0,	lowerCAmelCase=257,	lowerCAmelCase=None,	):



              """simple docstring"""







              lowerCamelCase_							=parent
              lowerCamelCase_							=is_training
              lowerCamelCase_							=batch_size
              lowerCamelCase_							=image_size
              lowerCamelCase_							=patch_size
              lowerCamelCase_							=num_channels
              lowerCamelCase_							=max_token_length
              lowerCamelCase_							=num_character_labels
              lowerCamelCase_							=num_bpe_labels
              lowerCamelCase_							=num_wordpiece_labels
              lowerCamelCase_							=hidden_size
              lowerCamelCase_							=num_hidden_layers
              lowerCamelCase_							=num_attention_heads
              lowerCamelCase_							=mlp_ratio
              lowerCamelCase_							=patch_embeds_hidden_size
              lowerCamelCase_							=output_hidden_states






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]						)
              lowerCamelCase_							=self.get_config()
              return config, pixel_values






       def   lowercase__  (							self						):



              """simple docstring"""







              return MgpstrConfig(
                  image_size=self.image_size,	patch_size=self.patch_size,	num_channels=self.num_channels,	max_token_length=self.max_token_length,	num_character_labels=self.num_character_labels,	num_bpe_labels=self.num_bpe_labels,	num_wordpiece_labels=self.num_wordpiece_labels,	hidden_size=self.hidden_size,	num_hidden_layers=self.num_hidden_layers,	num_attention_heads=self.num_attention_heads,	mlp_ratio=self.mlp_ratio,	output_hidden_states=self.output_hidden_states,	)






       def   lowercase__  (							self,	lowerCAmelCase,	lowerCAmelCase						):



              """simple docstring"""







              lowerCamelCase_							=MgpstrForSceneTextRecognition(lowerCAmelCase						)
              model.to(lowerCAmelCase						)
              model.eval()
              with torch.no_grad():
                     lowerCamelCase_							=model(lowerCAmelCase						)
              self.parent.assertEqual(
                  generated_ids[0][0].shape,	(self.batch_size, self.max_token_length, self.num_character_labels)						)






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=self.prepare_config_and_inputs()
              lowerCamelCase_,   lowerCamelCase_							=config_and_inputs
              lowerCamelCase_							={'''pixel_values''': pixel_values}
              return config, inputs_dict





@require_torch
class 						__UpperCamelCase (				lowerCamelCase__    ,      lowerCamelCase__    ,      unittest.TestCase       ):
       lowercase			:					Optional[int]   		=(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
       lowercase			:					Any   		={'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
       lowercase			:					Any   		=False

       lowercase			:					Tuple   		=False
       lowercase			:					Optional[int]   		=False
       lowercase			:					Union[str, Any]   		=False
       lowercase			:					Tuple   		=False






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=MgpstrModelTester(self						)
              lowerCamelCase_							=ConfigTester(self,	config_class=lowerCAmelCase,	has_text_modality=lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              self.config_tester.run_common_tests()






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*lowerCAmelCase						)






       @unittest.skip(reason='''MgpstrModel does not use inputs_embeds'''						)
       def   lowercase__  (							self						):



              """simple docstring"""







              pass






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_,   lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     lowerCamelCase_							=model_class(lowerCAmelCase						)
                     self.assertIsInstance(model.get_input_embeddings(),	(nn.Module)						)
                     lowerCamelCase_							=model.get_output_embeddings()
                     self.assertTrue(x is None or isinstance(lowerCAmelCase,	nn.Linear						)						)






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_,   lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     lowerCamelCase_							=model_class(lowerCAmelCase						)
                     lowerCamelCase_							=inspect.signature(model.forward						)
                     # signature.parameters is an OrderedDict => so arg_names order is deterministic
                     lowerCamelCase_							=[*signature.parameters.keys()]

                     lowerCamelCase_							=['''pixel_values''']
                     self.assertListEqual(arg_names[:1],	lowerCAmelCase						)






       @unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''						)
       def   lowercase__  (							self						):



              """simple docstring"""







              pass






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_,   lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     if not model_class.supports_gradient_checkpointing:
                            continue

                     lowerCamelCase_							=True
                     lowerCamelCase_							=model_class(lowerCAmelCase						)
                     self.assertTrue(model.is_gradient_checkpointing						)






       def   lowercase__  (							self						):



              """simple docstring"""







              def check_hidden_states_output(lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						):
                     lowerCamelCase_							=model_class(lowerCAmelCase						)
                     model.to(lowerCAmelCase						)
                     model.eval()

                     with torch.no_grad():
                            lowerCamelCase_							=model(**self._prepare_for_class(lowerCAmelCase,	lowerCAmelCase						)						)

                     lowerCamelCase_							=outputs.hidden_states

                     lowerCamelCase_							=getattr(
                         self.model_tester,	'''expected_num_hidden_layers''',	self.model_tester.num_hidden_layers + 1						)
                     self.assertEqual(len(lowerCAmelCase						),	lowerCAmelCase						)

                     self.assertListEqual(
                         list(hidden_states[0].shape[-2:]						),	[self.model_tester.patch_embeds_hidden_size, self.model_tester.hidden_size],	)

              lowerCamelCase_,   lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     lowerCamelCase_							=True
                     check_hidden_states_output(lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						)

                     # check that output_hidden_states also work using config
                     del inputs_dict["output_hidden_states"]
                     lowerCamelCase_							=True

                     check_hidden_states_output(lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_,   lowerCamelCase_							=self.model_tester.prepare_config_and_inputs_for_common()

              lowerCamelCase_							=_config_zero_init(lowerCAmelCase						)
              for model_class in self.all_model_classes:
                     lowerCamelCase_							=model_class(config=lowerCAmelCase						)
                     for name, param in model.named_parameters():
                            if isinstance(lowerCAmelCase,	(nn.Linear, nn.Convad, nn.LayerNorm)						):
                                   if param.requires_grad:
                                          self.assertIn(
                                              ((param.data.mean() * 1e9).round() / 1e9).item(),	[0.0, 1.0],	msg=f'''Parameter {name} of model {model_class} seems not properly initialized''',	)






       @unittest.skip(reason='''Retain_grad is tested in individual model tests'''						)
       def   lowercase__  (							self						):



              """simple docstring"""







              pass





def   a_							(   )							->		Optional[Any]:



       """simple docstring"""
       lowerCamelCase_							='''https://i.postimg.cc/ZKwLg2Gw/367-14.png'''
       lowerCamelCase_							=Image.open(requests.get(__snake_case     , stream=__snake_case     ).raw     ).convert('''RGB'''     )
       return im


@require_vision
@require_torch
class 						__UpperCamelCase (				unittest.TestCase       ):






       @slow
       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							='''alibaba-damo/mgp-str-base'''
              lowerCamelCase_							=MgpstrForSceneTextRecognition.from_pretrained(lowerCAmelCase						).to(lowerCAmelCase						)
              lowerCamelCase_							=MgpstrProcessor.from_pretrained(lowerCAmelCase						)

              lowerCamelCase_							=prepare_img()
              lowerCamelCase_							=processor(images=lowerCAmelCase,	return_tensors='''pt'''						).pixel_values.to(lowerCAmelCase						)

              # forward pass
              with torch.no_grad():
                     lowerCamelCase_							=model(lowerCAmelCase						)

              # verify the logits
              self.assertEqual(outputs.logits[0].shape,	torch.Size((1, 27, 38)						)						)

              lowerCamelCase_							=processor.batch_decode(outputs.logits						)
              lowerCamelCase_							='''ticket'''

              self.assertEqual(out_strs['''generated_text'''][0],	lowerCAmelCase						)

              lowerCamelCase_							=torch.tensor(
                  [[[-3_9.5_3_9_7, -4_4.4_0_2_4, -3_6.1_8_4_4], [-6_1.4_7_0_9, -6_3.8_6_3_9, -5_8.3_4_5_4], [-7_4.0_2_2_5, -6_8.5_4_9_4, -7_1.2_1_6_4]]],	device=lowerCAmelCase,	)

              self.assertTrue(torch.allclose(outputs.logits[0][:, 1:4, 1:4],	lowerCAmelCase,	atol=1e-4						)						)










'''simple docstring'''




import torch

from diffusers import HeunDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest


class 						__UpperCamelCase (				lowerCamelCase__       ):
       lowercase			:					Union[str, Any]   		=(HeunDiscreteScheduler,)
       lowercase			:					int   		=10






       def   lowercase__  (							self,	**lowerCAmelCase						):



              """simple docstring"""







              lowerCamelCase_							={
                  '''num_train_timesteps''': 1_100,
                  '''beta_start''': 0.0_0_0_1,
                  '''beta_end''': 0.0_2,
                  '''beta_schedule''': '''linear''',
              }

              config.update(**lowerCAmelCase						)
              return config






       def   lowercase__  (							self						):



              """simple docstring"""







              for timesteps in [10, 50, 100, 1_000]:
                     self.check_over_configs(num_train_timesteps=lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              for beta_start, beta_end in zip([0.0_0_0_0_1, 0.0_0_0_1, 0.0_0_1],	[0.0_0_0_2, 0.0_0_2, 0.0_2]						):
                     self.check_over_configs(beta_start=lowerCAmelCase,	beta_end=lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              for schedule in ["linear", "scaled_linear", "exp"]:
                     self.check_over_configs(beta_schedule=lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              for clip_sample_range in [1.0, 2.0, 3.0]:
                     self.check_over_configs(clip_sample_range=lowerCAmelCase,	clip_sample=lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              for prediction_type in ["epsilon", "v_prediction", "sample"]:
                     self.check_over_configs(prediction_type=lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=self.scheduler_classes[0]
              lowerCamelCase_							=self.get_scheduler_config()
              lowerCamelCase_							=scheduler_class(**lowerCAmelCase						)

              scheduler.set_timesteps(self.num_inference_steps						)

              lowerCamelCase_							=self.dummy_model()
              lowerCamelCase_							=self.dummy_sample_deter * scheduler.init_noise_sigma
              lowerCamelCase_							=sample.to(lowerCAmelCase						)

              for i, t in enumerate(scheduler.timesteps						):
                     lowerCamelCase_							=scheduler.scale_model_input(lowerCAmelCase,	lowerCAmelCase						)

                     lowerCamelCase_							=model(lowerCAmelCase,	lowerCAmelCase						)

                     lowerCamelCase_							=scheduler.step(lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						)
                     lowerCamelCase_							=output.prev_sample

              lowerCamelCase_							=torch.sum(torch.abs(lowerCAmelCase						)						)
              lowerCamelCase_							=torch.mean(torch.abs(lowerCAmelCase						)						)

              if torch_device in ["cpu", "mps"]:
                     assert abs(result_sum.item() - 0.1_2_3_3						) < 1e-2
                     assert abs(result_mean.item() - 0.0_0_0_2						) < 1e-3
              else:
                     # CUDA
                     assert abs(result_sum.item() - 0.1_2_3_3						) < 1e-2
                     assert abs(result_mean.item() - 0.0_0_0_2						) < 1e-3






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=self.scheduler_classes[0]
              lowerCamelCase_							=self.get_scheduler_config(prediction_type='''v_prediction'''						)
              lowerCamelCase_							=scheduler_class(**lowerCAmelCase						)

              scheduler.set_timesteps(self.num_inference_steps						)

              lowerCamelCase_							=self.dummy_model()
              lowerCamelCase_							=self.dummy_sample_deter * scheduler.init_noise_sigma
              lowerCamelCase_							=sample.to(lowerCAmelCase						)

              for i, t in enumerate(scheduler.timesteps						):
                     lowerCamelCase_							=scheduler.scale_model_input(lowerCAmelCase,	lowerCAmelCase						)

                     lowerCamelCase_							=model(lowerCAmelCase,	lowerCAmelCase						)

                     lowerCamelCase_							=scheduler.step(lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						)
                     lowerCamelCase_							=output.prev_sample

              lowerCamelCase_							=torch.sum(torch.abs(lowerCAmelCase						)						)
              lowerCamelCase_							=torch.mean(torch.abs(lowerCAmelCase						)						)

              if torch_device in ["cpu", "mps"]:
                     assert abs(result_sum.item() - 4.6_934e-07						) < 1e-2
                     assert abs(result_mean.item() - 6.1_112e-10						) < 1e-3
              else:
                     # CUDA
                     assert abs(result_sum.item() - 4.693_428_650_170_972e-07						) < 1e-2
                     assert abs(result_mean.item() - 0.0_0_0_2						) < 1e-3






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=self.scheduler_classes[0]
              lowerCamelCase_							=self.get_scheduler_config()
              lowerCamelCase_							=scheduler_class(**lowerCAmelCase						)

              scheduler.set_timesteps(self.num_inference_steps,	device=lowerCAmelCase						)

              lowerCamelCase_							=self.dummy_model()
              lowerCamelCase_							=self.dummy_sample_deter.to(lowerCAmelCase						) * scheduler.init_noise_sigma

              for t in scheduler.timesteps:
                     lowerCamelCase_							=scheduler.scale_model_input(lowerCAmelCase,	lowerCAmelCase						)

                     lowerCamelCase_							=model(lowerCAmelCase,	lowerCAmelCase						)

                     lowerCamelCase_							=scheduler.step(lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						)
                     lowerCamelCase_							=output.prev_sample

              lowerCamelCase_							=torch.sum(torch.abs(lowerCAmelCase						)						)
              lowerCamelCase_							=torch.mean(torch.abs(lowerCAmelCase						)						)

              if str(lowerCAmelCase						).startswith('''cpu'''						):
                     # The following sum varies between 148 and 156 on mps. Why?
                     assert abs(result_sum.item() - 0.1_2_3_3						) < 1e-2
                     assert abs(result_mean.item() - 0.0_0_0_2						) < 1e-3
              elif str(lowerCAmelCase						).startswith('''mps'''						):
                     # Larger tolerance on mps
                     assert abs(result_mean.item() - 0.0_0_0_2						) < 1e-2
              else:
                     # CUDA
                     assert abs(result_sum.item() - 0.1_2_3_3						) < 1e-2
                     assert abs(result_mean.item() - 0.0_0_0_2						) < 1e-3






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=self.scheduler_classes[0]
              lowerCamelCase_							=self.get_scheduler_config()
              lowerCamelCase_							=scheduler_class(**lowerCAmelCase,	use_karras_sigmas=lowerCAmelCase						)

              scheduler.set_timesteps(self.num_inference_steps,	device=lowerCAmelCase						)

              lowerCamelCase_							=self.dummy_model()
              lowerCamelCase_							=self.dummy_sample_deter.to(lowerCAmelCase						) * scheduler.init_noise_sigma
              lowerCamelCase_							=sample.to(lowerCAmelCase						)

              for t in scheduler.timesteps:
                     lowerCamelCase_							=scheduler.scale_model_input(lowerCAmelCase,	lowerCAmelCase						)

                     lowerCamelCase_							=model(lowerCAmelCase,	lowerCAmelCase						)

                     lowerCamelCase_							=scheduler.step(lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						)
                     lowerCamelCase_							=output.prev_sample

              lowerCamelCase_							=torch.sum(torch.abs(lowerCAmelCase						)						)
              lowerCamelCase_							=torch.mean(torch.abs(lowerCAmelCase						)						)

              assert abs(result_sum.item() - 0.0_0_0_1_5						) < 1e-2
              assert abs(result_mean.item() - 1.9_869_554_535_034_695e-07						) < 1e-2




