




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




					'''simple docstring'''






					def __init__(       self,    __UpperCamelCase,    __UpperCamelCase=False,    __UpperCamelCase=13,    __UpperCamelCase=(32, 128),    __UpperCamelCase=4,    __UpperCamelCase=3,    __UpperCamelCase=27,    __UpperCamelCase=38,    __UpperCamelCase=99,    __UpperCamelCase=99,    __UpperCamelCase=32,    __UpperCamelCase=5,    __UpperCamelCase=4,    __UpperCamelCase=4.0,    __UpperCamelCase=257,    __UpperCamelCase=None,    ):
							_snake_case      			=			parent
							_snake_case      			=			is_training
							_snake_case      			=			batch_size
							_snake_case      			=			image_size
							_snake_case      			=			patch_size
							_snake_case      			=			num_channels
							_snake_case      			=			max_token_length
							_snake_case      			=			num_character_labels
							_snake_case      			=			num_bpe_labels
							_snake_case      			=			num_wordpiece_labels
							_snake_case      			=			hidden_size
							_snake_case      			=			num_hidden_layers
							_snake_case      			=			num_attention_heads
							_snake_case      			=			mlp_ratio
							_snake_case      			=			patch_embeds_hidden_size
							_snake_case      			=			output_hidden_states






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]					)
							_snake_case      			=			self.get_config()
							return config, pixel_values






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							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 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase					):
							_snake_case      			=			MgpstrForSceneTextRecognition(__UpperCamelCase					)
							model.to(__UpperCamelCase					)
							model.eval()
							with torch.no_grad():
									_snake_case      			=			model(__UpperCamelCase					)
							self.parent.assertEqual(
							    generated_ids[0][0].shape,    (self.batch_size, self.max_token_length, self.num_character_labels)					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			self.prepare_config_and_inputs()
							_snake_case			,       _snake_case      			=			config_and_inputs
							_snake_case      			=			{"pixel_values": pixel_values}
							return config, inputs_dict





@require_torch
class 	lowerCamelCase_				(			UpperCAmelCase_,			UpperCAmelCase_,			unittest.TestCase				):




					'''simple docstring'''






					lowercase__       =					(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
					lowercase__       =					{"""feature-extraction""": MgpstrForSceneTextRecognition} if is_torch_available() else {}
					lowercase__       =					False

					lowercase__       =					False
					lowercase__       =					False
					lowercase__       =					False
					lowercase__       =					False






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			MgpstrModelTester(self					)
							_snake_case      			=			ConfigTester(self,    config_class=__UpperCamelCase,    has_text_modality=__UpperCamelCase					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							self.config_tester.run_common_tests()






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__UpperCamelCase					)






					@unittest.skip(reason="MgpstrModel does not use inputs_embeds"					)
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							pass






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			self.model_tester.prepare_config_and_inputs_for_common()

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






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			self.model_tester.prepare_config_and_inputs_for_common()

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

									_snake_case      			=			["pixel_values"]
									self.assertListEqual(arg_names[:1],    __UpperCamelCase					)






					@unittest.skip(reason="MgpstrModel does not support feedforward chunking"					)
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							pass






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			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

									_snake_case      			=			True
									_snake_case      			=			model_class(__UpperCamelCase					)
									self.assertTrue(model.is_gradient_checkpointing					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							def check_hidden_states_output(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					):
									_snake_case      			=			model_class(__UpperCamelCase					)
									model.to(__UpperCamelCase					)
									model.eval()

									with torch.no_grad():
											_snake_case      			=			model(**self._prepare_for_class(__UpperCamelCase,    __UpperCamelCase					)					)

									_snake_case      			=			outputs.hidden_states

									_snake_case      			=			getattr(
									    self.model_tester,    "expected_num_hidden_layers",    self.model_tester.num_hidden_layers + 1					)
									self.assertEqual(len(__UpperCamelCase					),    __UpperCamelCase					)

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

							_snake_case			,       _snake_case      			=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									_snake_case      			=			True
									check_hidden_states_output(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					)

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

									check_hidden_states_output(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			self.model_tester.prepare_config_and_inputs_for_common()

							_snake_case      			=			_config_zero_init(__UpperCamelCase					)
							for model_class in self.all_model_classes:
									_snake_case      			=			model_class(config=__UpperCamelCase					)
									for name, param in model.named_parameters():
											if isinstance(__UpperCamelCase,    (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 							__SCREAMING_SNAKE_CASE      (       self					):
							pass






def 						_lowercase						(      ):



		'''simple docstring'''







		_snake_case      			=			"https://i.postimg.cc/ZKwLg2Gw/367-14.png"
		_snake_case      			=			Image.open(requests.get(lowercase_		,				stream=lowercase_    ).raw    ).convert("RGB"    )
		return im





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




					'''simple docstring'''






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			"alibaba-damo/mgp-str-base"
							_snake_case      			=			MgpstrForSceneTextRecognition.from_pretrained(__UpperCamelCase					).to(__UpperCamelCase					)
							_snake_case      			=			MgpstrProcessor.from_pretrained(__UpperCamelCase					)

							_snake_case      			=			prepare_img()
							_snake_case      			=			processor(images=__UpperCamelCase,    return_tensors="pt"					).pixel_values.to(__UpperCamelCase					)

							# forward pass
							with torch.no_grad():
									_snake_case      			=			model(__UpperCamelCase					)

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

							_snake_case      			=			processor.batch_decode(outputs.logits					)
							_snake_case      			=			"ticket"

							self.assertEqual(out_strs["generated_text"][0],    __UpperCamelCase					)

							_snake_case      			=			torch.tensor(
							    [[[-39.53_97, -44.40_24, -36.18_44], [-61.47_09, -63.86_39, -58.34_54], [-74.02_25, -68.54_94, -71.21_64]]],    device=__UpperCamelCase,    )

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











'''simple docstring'''







import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


_lowerCamelCase				:		Optional[Any]				      =    logging.get_logger(__name__)  # pylint: disable=invalid-name





@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
class 	lowerCamelCase_				(			UpperCAmelCase_				):




					'''simple docstring'''






					lowercase__       =					42
					lowercase__       =					None






def 						_lowercase						(      lowercase_		,				lowercase_=0.999		,				lowercase_="cosine"		,				):



		'''simple docstring'''







		if alpha_transform_type == "cosine":

				def alpha_bar_fn(lowercase_    ):
						return math.cos((t + 0.008) / 1.008 * math.pi / 2    ) ** 2

		elif alpha_transform_type == "exp":

				def alpha_bar_fn(lowercase_    ):
						return math.exp(t * -12.0    )

		else:
				raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}'''    )

		_snake_case      			=			[]
		for i in range(lowercase_    ):
				_snake_case      			=			i / num_diffusion_timesteps
				_snake_case      			=			(i + 1) / num_diffusion_timesteps
				betas.append(min(1 - alpha_bar_fn(lowercase_    ) / alpha_bar_fn(lowercase_    )		,				lowercase_    )    )
		return torch.tensor(lowercase_		,				dtype=torch.floataa    )





class 	lowerCamelCase_				(			UpperCAmelCase_,			UpperCAmelCase_				):




					'''simple docstring'''






					lowercase__       =					[e.name for e in KarrasDiffusionSchedulers]
					lowercase__       =					1






					@register_to_config
					def __init__(       self,    __UpperCamelCase = 1_000,    __UpperCamelCase = 0.00_01,    __UpperCamelCase = 0.02,    __UpperCamelCase = "linear",    __UpperCamelCase = None,    __UpperCamelCase = "epsilon",    __UpperCamelCase = "linspace",    __UpperCamelCase = 0,    ):
							if trained_betas is not None:
									_snake_case      			=			torch.tensor(__UpperCamelCase,    dtype=torch.floataa					)
							elif beta_schedule == "linear":
									_snake_case      			=			torch.linspace(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    dtype=torch.floataa					)
							elif beta_schedule == "scaled_linear":
									# this schedule is very specific to the latent diffusion model.
									_snake_case      			=			(
									    torch.linspace(beta_start**0.5,    beta_end**0.5,    __UpperCamelCase,    dtype=torch.floataa					) ** 2
									)
							elif beta_schedule == "squaredcos_cap_v2":
									# Glide cosine schedule
									_snake_case      			=			betas_for_alpha_bar(__UpperCamelCase					)
							else:
									raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}'''					)

							_snake_case      			=			1.0 - self.betas
							_snake_case      			=			torch.cumprod(self.alphas,    dim=0					)

							_snake_case      			=			np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5					)
							_snake_case      			=			np.concatenate([sigmas[::-1], [0.0]]					).astype(np.floataa					)
							_snake_case      			=			torch.from_numpy(__UpperCamelCase					)

							# setable values
							_snake_case      			=			None
							_snake_case      			=			np.linspace(0,    num_train_timesteps - 1,    __UpperCamelCase,    dtype=__UpperCamelCase					)[::-1].copy()
							_snake_case      			=			torch.from_numpy(__UpperCamelCase					)
							_snake_case      			=			False






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							# standard deviation of the initial noise distribution
							if self.config.timestep_spacing in ["linspace", "trailing"]:
									return self.sigmas.max()

							return (self.sigmas.max() ** 2 + 1) ** 0.5






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase					):
							if isinstance(__UpperCamelCase,    torch.Tensor					):
									_snake_case      			=			timestep.to(self.timesteps.device					)
							_snake_case      			=			(self.timesteps == timestep).nonzero().item()
							_snake_case      			=			self.sigmas[step_index]
							_snake_case      			=			sample / ((sigma**2 + 1) ** 0.5)
							_snake_case      			=			True
							return sample






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase = None					):
							_snake_case      			=			num_inference_steps

							# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
							if self.config.timestep_spacing == "linspace":
									_snake_case      			=			np.linspace(0,    self.config.num_train_timesteps - 1,    __UpperCamelCase,    dtype=__UpperCamelCase					)[
									    ::-1
									].copy()
							elif self.config.timestep_spacing == "leading":
									_snake_case      			=			self.config.num_train_timesteps // self.num_inference_steps
									# creates integer timesteps by multiplying by ratio
									# casting to int to avoid issues when num_inference_step is power of 3
									_snake_case      			=			(np.arange(0,    __UpperCamelCase					) * step_ratio).round()[::-1].copy().astype(__UpperCamelCase					)
									timesteps += self.config.steps_offset
							elif self.config.timestep_spacing == "trailing":
									_snake_case      			=			self.config.num_train_timesteps / self.num_inference_steps
									# creates integer timesteps by multiplying by ratio
									# casting to int to avoid issues when num_inference_step is power of 3
									_snake_case      			=			(np.arange(self.config.num_train_timesteps,    0,    -step_ratio					)).round().copy().astype(__UpperCamelCase					)
									timesteps -= 1
							else:
									raise ValueError(
									    f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'''					)

							_snake_case      			=			np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5					)
							_snake_case      			=			np.interp(__UpperCamelCase,    np.arange(0,    len(__UpperCamelCase					)					),    __UpperCamelCase					)
							_snake_case      			=			np.concatenate([sigmas, [0.0]]					).astype(np.floataa					)
							_snake_case      			=			torch.from_numpy(__UpperCamelCase					).to(device=__UpperCamelCase					)
							if str(__UpperCamelCase					).startswith("mps"					):
									# mps does not support float64
									_snake_case      			=			torch.from_numpy(__UpperCamelCase					).to(__UpperCamelCase,    dtype=torch.floataa					)
							else:
									_snake_case      			=			torch.from_numpy(__UpperCamelCase					).to(device=__UpperCamelCase					)






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase = None,    __UpperCamelCase = True,    ):

							if (
							    isinstance(__UpperCamelCase,    __UpperCamelCase					)
							    or isinstance(__UpperCamelCase,    torch.IntTensor					)
							    or isinstance(__UpperCamelCase,    torch.LongTensor					)
							):
									raise ValueError(
									    (
									        "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
									        " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
									        " one of the `scheduler.timesteps` as a timestep."
									    ),    )

							if not self.is_scale_input_called:
									logger.warning(
									    "The `scale_model_input` function should be called before `step` to ensure correct denoising. "
									    "See `StableDiffusionPipeline` for a usage example."					)

							if isinstance(__UpperCamelCase,    torch.Tensor					):
									_snake_case      			=			timestep.to(self.timesteps.device					)

							_snake_case      			=			(self.timesteps == timestep).nonzero().item()
							_snake_case      			=			self.sigmas[step_index]

							# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
							if self.config.prediction_type == "epsilon":
									_snake_case      			=			sample - sigma * model_output
							elif self.config.prediction_type == "v_prediction":
									# * c_out + input * c_skip
									_snake_case      			=			model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
							elif self.config.prediction_type == "sample":
									raise NotImplementedError("prediction_type not implemented yet: sample"					)
							else:
									raise ValueError(
									    f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'''					)

							_snake_case      			=			self.sigmas[step_index]
							_snake_case      			=			self.sigmas[step_index + 1]
							_snake_case      			=			(sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
							_snake_case      			=			(sigma_to**2 - sigma_up**2) ** 0.5

							# 2. Convert to an ODE derivative
							_snake_case      			=			(sample - pred_original_sample) / sigma

							_snake_case      			=			sigma_down - sigma

							_snake_case      			=			sample + derivative * dt

							_snake_case      			=			model_output.device
							_snake_case      			=			randn_tensor(model_output.shape,    dtype=model_output.dtype,    device=__UpperCamelCase,    generator=__UpperCamelCase					)

							_snake_case      			=			prev_sample + noise * sigma_up

							if not return_dict:
									return (prev_sample,)

							return EulerAncestralDiscreteSchedulerOutput(
							    prev_sample=__UpperCamelCase,    pred_original_sample=__UpperCamelCase					)






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    ):
							# Make sure sigmas and timesteps have the same device and dtype as original_samples
							_snake_case      			=			self.sigmas.to(device=original_samples.device,    dtype=original_samples.dtype					)
							if original_samples.device.type == "mps" and torch.is_floating_point(__UpperCamelCase					):
									# mps does not support float64
									_snake_case      			=			self.timesteps.to(original_samples.device,    dtype=torch.floataa					)
									_snake_case      			=			timesteps.to(original_samples.device,    dtype=torch.floataa					)
							else:
									_snake_case      			=			self.timesteps.to(original_samples.device					)
									_snake_case      			=			timesteps.to(original_samples.device					)

							_snake_case      			=			[(schedule_timesteps == t).nonzero().item() for t in timesteps]

							_snake_case      			=			sigmas[step_indices].flatten()
							while len(sigma.shape					) < len(original_samples.shape					):
									_snake_case      			=			sigma.unsqueeze(-1					)

							_snake_case      			=			original_samples + noise * sigma
							return noisy_samples






					def __len__(       self					):
							return self.config.num_train_timesteps





