code: 
  '''simple docstring'''
  
  
  
  import collections
  import inspect
  import unittest
  
  from transformers import DonutSwinConfig
  from transformers.testing_utils import require_torch, slow, torch_device
  from transformers.utils import is_torch_available
  
  from ...test_configuration_common import ConfigTester
  from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
  from ...test_pipeline_mixin import PipelineTesterMixin
  
  
  if is_torch_available():
  				import torch
  				from torch import nn
  
  				from transformers import DonutSwinModel
  				from transformers.models.donut.modeling_donut_swin import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST
  
  
  
  
  
  class 			A							:
  
  
  
  			def __init__(					self       ,     lowerCamelCase__       ,     lowerCamelCase__=13       ,     lowerCamelCase__=32       ,     lowerCamelCase__=2       ,     lowerCamelCase__=3       ,     lowerCamelCase__=16       ,     lowerCamelCase__=[1, 2, 1]       ,     lowerCamelCase__=[2, 2, 4]       ,     lowerCamelCase__=2       ,     lowerCamelCase__=2.0       ,     lowerCamelCase__=True       ,     lowerCamelCase__=0.0       ,     lowerCamelCase__=0.0       ,     lowerCamelCase__=0.1       ,     lowerCamelCase__="gelu"       ,     lowerCamelCase__=False       ,     lowerCamelCase__=True       ,     lowerCamelCase__=0.02       ,     lowerCamelCase__=1e-5       ,     lowerCamelCase__=True       ,     lowerCamelCase__=None       ,     lowerCamelCase__=True       ,     lowerCamelCase__=10       ,     lowerCamelCase__=8       ,     )			->		Tuple:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       parent
  									lowercase__							 =       batch_size
  									lowercase__							 =       image_size
  									lowercase__							 =       patch_size
  									lowercase__							 =       num_channels
  									lowercase__							 =       embed_dim
  									lowercase__							 =       depths
  									lowercase__							 =       num_heads
  									lowercase__							 =       window_size
  									lowercase__							 =       mlp_ratio
  									lowercase__							 =       qkv_bias
  									lowercase__							 =       hidden_dropout_prob
  									lowercase__							 =       attention_probs_dropout_prob
  									lowercase__							 =       drop_path_rate
  									lowercase__							 =       hidden_act
  									lowercase__							 =       use_absolute_embeddings
  									lowercase__							 =       patch_norm
  									lowercase__							 =       layer_norm_eps
  									lowercase__							 =       initializer_range
  									lowercase__							 =       is_training
  									lowercase__							 =       scope
  									lowercase__							 =       use_labels
  									lowercase__							 =       type_sequence_label_size
  									lowercase__							 =       encoder_stride
  
  
  
  			def A__ (					self       )			->		int:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )
  
  									lowercase__							 =       None
  									if self.use_labels:
  															lowercase__							 =       ids_tensor([self.batch_size]       ,     self.type_sequence_label_size       )
  
  									lowercase__							 =       self.get_config()
  
  									return config, pixel_values, labels
  
  
  
  			def A__ (					self       )			->		List[str]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									return DonutSwinConfig(
  									    image_size=self.image_size       ,     patch_size=self.patch_size       ,     num_channels=self.num_channels       ,     embed_dim=self.embed_dim       ,     depths=self.depths       ,     num_heads=self.num_heads       ,     window_size=self.window_size       ,     mlp_ratio=self.mlp_ratio       ,     qkv_bias=self.qkv_bias       ,     hidden_dropout_prob=self.hidden_dropout_prob       ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,     drop_path_rate=self.drop_path_rate       ,     hidden_act=self.hidden_act       ,     use_absolute_embeddings=self.use_absolute_embeddings       ,     path_norm=self.patch_norm       ,     layer_norm_eps=self.layer_norm_eps       ,     initializer_range=self.initializer_range       ,     encoder_stride=self.encoder_stride       ,     )
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		str:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       DonutSwinModel(config=lowerCamelCase__       )
  									model.to(lowerCamelCase__       )
  									model.eval()
  									lowercase__							 =       model(lowerCamelCase__       )
  
  									lowercase__							 =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths       ) - 1))
  									lowercase__							 =       int(config.embed_dim * 2 ** (len(config.depths       ) - 1)       )
  
  									self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, expected_seq_len, expected_dim)       )
  
  
  
  			def A__ (					self       )			->		Optional[Any]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.prepare_config_and_inputs()
  									(
  									    lowercase__       
  									)							 =       config_and_inputs
  									lowercase__							 =       {'''pixel_values''': pixel_values}
  									return config, inputs_dict
  
  
  
  
  
  @require_torch
  class 			A							(       __UpperCAmelCase		,						__UpperCAmelCase		,						unittest.TestCase				):
  			lowerCamelCase							:							Optional[int]       		=  (DonutSwinModel,) if is_torch_available() else ()
  			lowerCamelCase							:							List[Any]       		=  {"""feature-extraction""": DonutSwinModel} if is_torch_available() else {}
  			lowerCamelCase							:							int       		=  True
  
  			lowerCamelCase							:							Optional[int]       		=  False
  			lowerCamelCase							:							str       		=  False
  			lowerCamelCase							:							Optional[int]       		=  False
  
  
  
  			def A__ (					self       )			->		Union[str, Any]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       DonutSwinModelTester(self       )
  									lowercase__							 =       ConfigTester(self       ,     config_class=lowerCamelCase__       ,     embed_dim=37       )
  
  
  
  			def A__ (					self       )			->		Any:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									self.create_and_test_config_common_properties()
  									self.config_tester.create_and_test_config_to_json_string()
  									self.config_tester.create_and_test_config_to_json_file()
  									self.config_tester.create_and_test_config_from_and_save_pretrained()
  									self.config_tester.create_and_test_config_with_num_labels()
  									self.config_tester.check_config_can_be_init_without_params()
  									self.config_tester.check_config_arguments_init()
  
  
  
  			def A__ (					self       )			->		str:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									return
  
  
  
  			def A__ (					self       )			->		Any:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.model_tester.prepare_config_and_inputs()
  									self.model_tester.create_and_check_model(*lowerCamelCase__       )
  
  
  
  			def A__ (					self       )			->		Tuple:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									pass
  
  
  
  			def A__ (					self       )			->		Optional[Any]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.model_tester.prepare_config_and_inputs_for_common()
  
  									for model_class in self.all_model_classes:
  															lowercase__							 =       model_class(lowerCamelCase__       )
  															self.assertIsInstance(model.get_input_embeddings()       ,     (nn.Module)       )
  															lowercase__							 =       model.get_output_embeddings()
  															self.assertTrue(x is None or isinstance(lowerCamelCase__       ,     nn.Linear       )       )
  
  
  
  			def A__ (					self       )			->		Union[str, Any]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.model_tester.prepare_config_and_inputs_for_common()
  
  									for model_class in self.all_model_classes:
  															lowercase__							 =       model_class(lowerCamelCase__       )
  															lowercase__							 =       inspect.signature(model.forward       )
  															# signature.parameters is an OrderedDict => so arg_names order is deterministic
  															lowercase__							 =       [*signature.parameters.keys()]
  
  															lowercase__							 =       ['''pixel_values''']
  															self.assertListEqual(arg_names[:1]       ,     lowerCamelCase__       )
  
  
  
  			def A__ (					self       )			->		str:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.model_tester.prepare_config_and_inputs_for_common()
  									lowercase__							 =       True
  
  									for model_class in self.all_model_classes:
  															lowercase__							 =       True
  															lowercase__							 =       False
  															lowercase__							 =       True
  															lowercase__							 =       model_class(lowerCamelCase__       )
  															model.to(lowerCamelCase__       )
  															model.eval()
  															with torch.no_grad():
  																					lowercase__							 =       model(**self._prepare_for_class(lowerCamelCase__       ,     lowerCamelCase__       )       )
  															lowercase__							 =       outputs.attentions
  															lowercase__							 =       len(self.model_tester.depths       )
  															self.assertEqual(len(lowerCamelCase__       )       ,     lowerCamelCase__       )
  
  															# check that output_attentions also work using config
  															del inputs_dict["output_attentions"]
  															lowercase__							 =       True
  															lowercase__							 =       config.window_size**2
  															lowercase__							 =       model_class(lowerCamelCase__       )
  															model.to(lowerCamelCase__       )
  															model.eval()
  															with torch.no_grad():
  																					lowercase__							 =       model(**self._prepare_for_class(lowerCamelCase__       ,     lowerCamelCase__       )       )
  															lowercase__							 =       outputs.attentions
  															self.assertEqual(len(lowerCamelCase__       )       ,     lowerCamelCase__       )
  
  															self.assertListEqual(
  															    list(attentions[0].shape[-3:]       )       ,     [self.model_tester.num_heads[0], window_size_squared, window_size_squared]       ,     )
  															lowercase__							 =       len(lowerCamelCase__       )
  
  															# Check attention is always last and order is fine
  															lowercase__							 =       True
  															lowercase__							 =       True
  															lowercase__							 =       model_class(lowerCamelCase__       )
  															model.to(lowerCamelCase__       )
  															model.eval()
  															with torch.no_grad():
  																					lowercase__							 =       model(**self._prepare_for_class(lowerCamelCase__       ,     lowerCamelCase__       )       )
  
  															if hasattr(self.model_tester       ,     """num_hidden_states_types"""       ):
  																					lowercase__							 =       self.model_tester.num_hidden_states_types
  															else:
  																					# also another +1 for reshaped_hidden_states
  																					lowercase__							 =       2
  															self.assertEqual(out_len + added_hidden_states       ,     len(lowerCamelCase__       )       )
  
  															lowercase__							 =       outputs.attentions
  
  															self.assertEqual(len(lowerCamelCase__       )       ,     lowerCamelCase__       )
  
  															self.assertListEqual(
  															    list(self_attentions[0].shape[-3:]       )       ,     [self.model_tester.num_heads[0], window_size_squared, window_size_squared]       ,     )
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		Dict:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       model_class(lowerCamelCase__       )
  									model.to(lowerCamelCase__       )
  									model.eval()
  
  									with torch.no_grad():
  															lowercase__							 =       model(**self._prepare_for_class(lowerCamelCase__       ,     lowerCamelCase__       )       )
  
  									lowercase__							 =       outputs.hidden_states
  
  									lowercase__							 =       getattr(
  									    self.model_tester       ,     """expected_num_hidden_layers"""       ,     len(self.model_tester.depths       ) + 1       )
  									self.assertEqual(len(lowerCamelCase__       )       ,     lowerCamelCase__       )
  
  									# DonutSwin has a different seq_length
  									lowercase__							 =       (
  									    config.patch_size
  									    if isinstance(config.patch_size       ,     collections.abc.Iterable       )
  									    else (config.patch_size, config.patch_size)
  									)
  
  									lowercase__							 =       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  
  									self.assertListEqual(
  									    list(hidden_states[0].shape[-2:]       )       ,     [num_patches, self.model_tester.embed_dim]       ,     )
  
  									lowercase__							 =       outputs.reshaped_hidden_states
  									self.assertEqual(len(lowerCamelCase__       )       ,     lowerCamelCase__       )
  
  									lowercase__							 =       reshaped_hidden_states[0].shape
  									lowercase__							 =       (
  									    reshaped_hidden_states[0].view(lowerCamelCase__       ,     lowerCamelCase__       ,     height * width       ).permute(0       ,     2       ,     1       )
  									)
  									self.assertListEqual(
  									    list(reshaped_hidden_states.shape[-2:]       )       ,     [num_patches, self.model_tester.embed_dim]       ,     )
  
  
  
  			def A__ (					self       )			->		Optional[int]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.model_tester.prepare_config_and_inputs_for_common()
  
  									lowercase__							 =       (
  									    self.model_tester.image_size
  									    if isinstance(self.model_tester.image_size       ,     collections.abc.Iterable       )
  									    else (self.model_tester.image_size, self.model_tester.image_size)
  									)
  
  									for model_class in self.all_model_classes:
  															lowercase__							 =       True
  															self.check_hidden_states_output(lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )
  
  															# check that output_hidden_states also work using config
  															del inputs_dict["output_hidden_states"]
  															lowercase__							 =       True
  
  															self.check_hidden_states_output(lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )
  
  
  
  			def A__ (					self       )			->		List[Any]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.model_tester.prepare_config_and_inputs_for_common()
  									lowercase__							 =       3
  
  									lowercase__							 =       (
  									    self.model_tester.image_size
  									    if isinstance(self.model_tester.image_size       ,     collections.abc.Iterable       )
  									    else (self.model_tester.image_size, self.model_tester.image_size)
  									)
  									lowercase__							 =       (
  									    config.patch_size
  									    if isinstance(config.patch_size       ,     collections.abc.Iterable       )
  									    else (config.patch_size, config.patch_size)
  									)
  
  									lowercase__							 =       image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
  									lowercase__							 =       image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
  
  									for model_class in self.all_model_classes:
  															lowercase__							 =       True
  															self.check_hidden_states_output(lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     (padded_height, padded_width)       )
  
  															# check that output_hidden_states also work using config
  															del inputs_dict["output_hidden_states"]
  															lowercase__							 =       True
  															self.check_hidden_states_output(lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     (padded_height, padded_width)       )
  
  
  
  			@slow
  			def A__ (					self       )			->		int:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
  															lowercase__							 =       DonutSwinModel.from_pretrained(lowerCamelCase__       )
  															self.assertIsNotNone(lowerCamelCase__       )
  
  
  
  			def A__ (					self       )			->		Any:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.model_tester.prepare_config_and_inputs_for_common()
  
  									lowercase__							 =       _config_zero_init(lowerCamelCase__       )
  									for model_class in self.all_model_classes:
  															lowercase__							 =       model_class(config=lowerCamelCase__       )
  															for name, param in model.named_parameters():
  																					if "embeddings" not in name and 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'''       ,     )
  
  
  
  
  
  
  
style_context: 
  '''simple docstring'''
  
  
  
  import bisect
  import copy
  from collections import defaultdict
  
  import numpy as np
  from torch.utils.data import BatchSampler, Sampler
  
  from utils import logger
  
  
  
  
  
  def  _A		(							lowercase__		,		lowercase__	):
  						lowercase__							 =       copy.deepcopy(lowercase__	)
  						lowercase__							 =       sorted(lowercase__	)
  						lowercase__							 =       [bisect.bisect_right(lowercase__		,		lowercase__	) for y in x]
  						return quantized
  
  
  
  
  
  def  _A		(							lowercase__		,		lowercase__=0	):
  						lowercase__							 =       np.arange(start=3		,		stop=lowercase__		,		step=4	).tolist() if k > 0 else [10]
  						lowercase__							 =       _quantize(lowercase__		,		lowercase__	)
  						# count number of elements per group
  						lowercase__							 =       np.unique(lowercase__		,		return_counts=lowercase__	)[1]
  						lowercase__							 =       [0] + bins + [np.inf]
  						logger.info("""Using {} as bins for aspect lengths quantization""".format(lowercase__	)	)
  						logger.info("""Count of instances per bin: {}""".format(lowercase__	)	)
  						return groups
  
  
  
  
  
  
  
  class 			A							(       __UpperCAmelCase				):
  
  
  
  			def __init__(					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		Optional[int]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									if not isinstance(lowerCamelCase__       ,     lowerCamelCase__       ):
  															raise ValueError(
  															    """sampler should be an instance of torch.utils.data.Sampler, but got sampler={}""".format(lowerCamelCase__       )       )
  									lowercase__							 =       sampler
  									lowercase__							 =       group_ids
  									lowercase__							 =       batch_size
  
  
  
  			def __iter__(					self       )			->		List[str]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       defaultdict(lowerCamelCase__       )
  									lowercase__							 =       defaultdict(lowerCamelCase__       )
  
  									lowercase__							 =       0
  									for idx in self.sampler:
  															lowercase__							 =       self.group_ids[idx]
  															buffer_per_group[group_id].append(lowerCamelCase__       )
  															samples_per_group[group_id].append(lowerCamelCase__       )
  															if len(buffer_per_group[group_id]       ) == self.batch_size:
  																					yield buffer_per_group[group_id]  # TODO
  																					num_batches += 1
  																					del buffer_per_group[group_id]
  															assert len(buffer_per_group[group_id]       ) < self.batch_size
  
  									# now we have run out of elements that satisfy
  									# the group criteria, let's return the remaining
  									# elements so that the size of the sampler is
  									# deterministic
  									lowercase__							 =       len(self       )
  									lowercase__							 =       expected_num_batches - num_batches
  									if num_remaining > 0:
  															# for the remaining batches, group the batches by similar lengths
  															lowercase__							 =       []
  															for group_id, idxs in sorted(buffer_per_group.items()       ,     key=lambda lowerCamelCase__       : x[0]       ):
  																					batch_idx.extend(lowerCamelCase__       )
  																					if len(lowerCamelCase__       ) >= self.batch_size:
  																											yield batch_idx[: self.batch_size]
  																											lowercase__							 =       batch_idx[self.batch_size :]
  																											num_remaining -= 1
  															if len(lowerCamelCase__       ) > 0:
  																					yield batch_idx
  																					num_remaining -= 1
  									assert num_remaining == 0
  
  
  
  			def __len__(					self       )			->		Any:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									return (len(self.sampler       ) + self.batch_size - 1) // self.batch_size
  
  
  
  
  
  
  