






import inspect
import unittest

from transformers import DataaVecVisionConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_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 (
      MODEL_MAPPING,
      DataaVecVisionForImageClassification,
      DataaVecVisionForSemanticSegmentation,
      DataaVecVisionModel,
  )
  from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import BeitImageProcessor


class 					__lowercase					:







     '''simple docstring'''




     def __init__( self				:	List[Any]       ,		UpperCamelCase_				:	List[str]       ,		UpperCamelCase_				:	Any=100       ,		UpperCamelCase_				:	Optional[int]=13       ,		UpperCamelCase_				:	Union[str, Any]=30       ,		UpperCamelCase_				:	Any=2       ,		UpperCamelCase_				:	int=3       ,		UpperCamelCase_				:	Tuple=True       ,		UpperCamelCase_				:	Optional[Any]=True       ,		UpperCamelCase_				:	str=32       ,		UpperCamelCase_				:	Union[str, Any]=4       ,		UpperCamelCase_				:	Dict=4       ,		UpperCamelCase_				:	int=37       ,		UpperCamelCase_				:	Optional[Any]="gelu"       ,		UpperCamelCase_				:	Optional[int]=0.1       ,		UpperCamelCase_				:	Any=0.1       ,		UpperCamelCase_				:	str=10       ,		UpperCamelCase_				:	int=0.02       ,		UpperCamelCase_				:	List[str]=3       ,		UpperCamelCase_				:	Tuple=None       ,		UpperCamelCase_				:	str=[0, 1, 2, 3]       ,		):


         """simple docstring"""



         __A   			=		parent
         __A   			=		100
         __A   			=		batch_size
         __A   			=		image_size
         __A   			=		patch_size
         __A   			=		num_channels
         __A   			=		is_training
         __A   			=		use_labels
         __A   			=		hidden_size
         __A   			=		num_hidden_layers
         __A   			=		num_attention_heads
         __A   			=		intermediate_size
         __A   			=		hidden_act
         __A   			=		hidden_dropout_prob
         __A   			=		attention_probs_dropout_prob
         __A   			=		type_sequence_label_size
         __A   			=		initializer_range
         __A   			=		scope
         __A   			=		out_indices
         __A   			=		num_labels

         # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         __A   			=		(image_size // patch_size) ** 2
         __A   			=		num_patches + 1




     def 						lowerCAmelCase_   ( self				:	Optional[int] ):


         """simple docstring"""



         __A   			=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

         __A   			=		None
         __A   			=		None
         if self.use_labels:
             __A   			=		ids_tensor([self.batch_size]       ,		self.type_sequence_label_size )
             __A   			=		ids_tensor([self.batch_size, self.image_size, self.image_size]       ,		self.num_labels )

         __A   			=		self.get_config()

         return config, pixel_values, labels, pixel_labels




     def 						lowerCAmelCase_   ( self				:	Any ):


         """simple docstring"""



         return DataaVecVisionConfig(
             vocab_size=self.vocab_size       ,		image_size=self.image_size       ,		patch_size=self.patch_size       ,		num_channels=self.num_channels       ,		hidden_size=self.hidden_size       ,		num_hidden_layers=self.num_hidden_layers       ,		num_attention_heads=self.num_attention_heads       ,		intermediate_size=self.intermediate_size       ,		hidden_act=self.hidden_act       ,		hidden_dropout_prob=self.hidden_dropout_prob       ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,		is_decoder=lowercase__       ,		initializer_range=self.initializer_range       ,		out_indices=self.out_indices       ,		)




     def 						lowerCAmelCase_   ( self				:	Any       ,		UpperCamelCase_				:	List[str]       ,		UpperCamelCase_				:	List[Any]       ,		UpperCamelCase_				:	int       ,		UpperCamelCase_				:	Optional[int] ):


         """simple docstring"""



         __A   			=		DataaVecVisionModel(config=lowercase__ )
         model.to(lowercase__ )
         model.eval()
         __A   			=		model(lowercase__ )
         # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
         __A   			=		(self.image_size // self.patch_size) ** 2
         self.parent.assertEqual(result.last_hidden_state.shape       ,		(self.batch_size, num_patches + 1, self.hidden_size) )




     def 						lowerCAmelCase_   ( self				:	Optional[int]       ,		UpperCamelCase_				:	Any       ,		UpperCamelCase_				:	Optional[Any]       ,		UpperCamelCase_				:	Dict       ,		UpperCamelCase_				:	List[Any] ):


         """simple docstring"""



         __A   			=		self.type_sequence_label_size
         __A   			=		DataaVecVisionForImageClassification(lowercase__ )
         model.to(lowercase__ )
         model.eval()
         __A   			=		model(lowercase__       ,		labels=lowercase__ )
         self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.type_sequence_label_size) )




     def 						lowerCAmelCase_   ( self				:	int       ,		UpperCamelCase_				:	Dict       ,		UpperCamelCase_				:	Optional[int]       ,		UpperCamelCase_				:	int       ,		UpperCamelCase_				:	List[str] ):


         """simple docstring"""



         __A   			=		self.num_labels
         __A   			=		DataaVecVisionForSemanticSegmentation(lowercase__ )
         model.to(lowercase__ )
         model.eval()
         __A   			=		model(lowercase__ )
         self.parent.assertEqual(
             result.logits.shape       ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) )
         __A   			=		model(lowercase__       ,		labels=lowercase__ )
         self.parent.assertEqual(
             result.logits.shape       ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) )





     def 						lowerCAmelCase_   ( self				:	List[Any] ):


         """simple docstring"""



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


@require_torch
class 					__lowercase					(		_UpperCAmelCase	,					_UpperCAmelCase	,					unittest.TestCase     ):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE        = (
         (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     SCREAMING_SNAKE_CASE        = (
         {
             "feature-extraction": DataaVecVisionModel,
             "image-classification": DataaVecVisionForImageClassification,
             "image-segmentation": DataaVecVisionForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE        = False
     SCREAMING_SNAKE_CASE        = False
     SCREAMING_SNAKE_CASE        = False




     def 						lowerCAmelCase_   ( self				:	List[str] ):


         """simple docstring"""



         __A   			=		DataaVecVisionModelTester(self )
         __A   			=		ConfigTester(
             self       ,		config_class=lowercase__       ,		has_text_modality=lowercase__       ,		hidden_size=37 )




     def 						lowerCAmelCase_   ( self				:	int ):


         """simple docstring"""



         self.config_tester.run_common_tests()




     def 						lowerCAmelCase_   ( self				:	List[str] ):


         """simple docstring"""



         pass




     @require_torch_multi_gpu
     @unittest.skip(
         reason="""Data2VecVision has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" )
     def 						lowerCAmelCase_   ( self				:	List[str] ):


         """simple docstring"""



         pass




     def 						lowerCAmelCase_   ( self				:	Optional[int] ):


         """simple docstring"""



         __A   			=		self.model_tester.prepare_config_and_inputs_for_common()

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




     def 						lowerCAmelCase_   ( self				:	int ):


         """simple docstring"""



         __A   			=		self.model_tester.prepare_config_and_inputs_for_common()

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

             __A   			=		["pixel_values"]
             self.assertListEqual(arg_names[:1]       ,		lowercase__ )




     def 						lowerCAmelCase_   ( self				:	Optional[int] ):


         """simple docstring"""



         __A   			=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowercase__ )




     def 						lowerCAmelCase_   ( self				:	Union[str, Any] ):


         """simple docstring"""



         __A   			=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_segmentation(*lowercase__ )




     def 						lowerCAmelCase_   ( self				:	List[str] ):


         """simple docstring"""



         if not self.model_tester.is_training:
             return

         __A   			=		self.model_tester.prepare_config_and_inputs_for_common()
         __A   			=		True

         for model_class in self.all_model_classes:
             if model_class in [*get_values(lowercase__ )]:
                 continue

             __A   			=		model_class(lowercase__ )
             model.to(lowercase__ )
             model.train()
             __A   			=		self._prepare_for_class(lowercase__       ,		lowercase__       ,		return_labels=lowercase__ )
             __A   			=		model(**lowercase__ ).loss
             loss.backward()




     def 						lowerCAmelCase_   ( self				:	int ):


         """simple docstring"""



         __A   			=		self.model_tester.prepare_config_and_inputs_for_common()
         if not self.model_tester.is_training:
             return

         __A   			=		False
         __A   			=		True

         for model_class in self.all_model_classes:
             if model_class in [*get_values(lowercase__ )] or not model_class.supports_gradient_checkpointing:
                 continue
             # TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
             # this can then be incorporated into _prepare_for_class in test_modeling_common.py
             elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
                 __A   			=		inputs_dict["pixel_values"].shape
                 __A   			=		torch.zeros(
                     [self.model_tester.batch_size, height, width]       ,		device=lowercase__ ).long()
             __A   			=		model_class(lowercase__ )
             model.gradient_checkpointing_enable()
             model.to(lowercase__ )
             model.train()
             __A   			=		self._prepare_for_class(lowercase__       ,		lowercase__       ,		return_labels=lowercase__ )
             __A   			=		model(**lowercase__ ).loss
             loss.backward()




     def 						lowerCAmelCase_   ( self				:	int ):


         """simple docstring"""



         __A   			=		self.model_tester.prepare_config_and_inputs_for_common()

         __A   			=		_config_zero_init(lowercase__ )
         for model_class in self.all_model_classes:
             __A   			=		model_class(config=lowercase__ )
             for name, param in model.named_parameters():
                 # we skip lambda parameters as these require special initial values
                 # determined by config.layer_scale_init_value
                 if "lambda" in name:
                     continue
                 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"       ,		)




     def 						lowerCAmelCase_   ( self				:	Optional[int]       ,		UpperCamelCase_				:	List[Any]       ,		UpperCamelCase_				:	Union[str, Any]       ,		UpperCamelCase_				:	Dict       ,		UpperCamelCase_				:	str=2e-4       ,		UpperCamelCase_				:	List[str]="outputs"       ,		UpperCamelCase_				:	List[str]=None ):


         """simple docstring"""



         super().check_pt_tf_outputs(lowercase__       ,		lowercase__       ,		lowercase__       ,		lowercase__       ,		lowercase__       ,		lowercase__ )




     def 						lowerCAmelCase_   ( self				:	Union[str, Any] ):


         """simple docstring"""



         __A   			=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*lowercase__ )





     @slow
     def 						lowerCAmelCase_   ( self				:	Tuple ):


         """simple docstring"""



         for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __A   			=		DataaVecVisionModel.from_pretrained(lowercase__ )
             self.assertIsNotNone(lowercase__ )



def 	_SCREAMING_SNAKE_CASE  (       )  ->					List[str]:





    """simple docstring"""

    __A   			=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
    return image






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







     '''simple docstring'''




     @cached_property
     def 						lowerCAmelCase_   ( self				:	Optional[Any] ):


         """simple docstring"""



         return (
             BeitImageProcessor.from_pretrained("""facebook/data2vec-vision-base-ft1k""" ) if is_vision_available() else None
         )





     @slow
     def 						lowerCAmelCase_   ( self				:	List[Any] ):


         """simple docstring"""



         __A   			=		DataaVecVisionForImageClassification.from_pretrained("""facebook/data2vec-vision-base-ft1k""" ).to(
             lowercase__ )

         __A   			=		self.default_image_processor
         __A   			=		prepare_img()
         __A   			=		image_processor(images=lowercase__       ,		return_tensors="""pt""" ).to(lowercase__ )

         # forward pass
         with torch.no_grad():
             __A   			=		model(**lowercase__ )
         __A   			=		outputs.logits

         # verify the logits
         __A   			=		torch.Size((1, 1_000) )
         self.assertEqual(logits.shape       ,		lowercase__ )

         __A   			=		torch.tensor([0.3277, -0.1395, 0.0911] ).to(lowercase__ )

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

         __A   			=		[model.config.labelaid[i] for i in ["remote control, remote", "tabby, tabby cat"]]
         self.assertEqual(logits[0].topk(2 ).indices.cpu().tolist()       ,		lowercase__ )







'''simple docstring'''






from __future__ import annotations

from PIL import Image

# Define the first generation of cells
# fmt: off
snake_case_       =       [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]


def 					__lowerCamelCase			(      SCREAMING_SNAKE_CASE_     :	int    )							->   list[int]:
      """simple docstring"""

      return [int(SCREAMING_SNAKE_CASE_    ) for c in F"{ruleset:08}"[:8]]


def 					__lowerCamelCase			(      SCREAMING_SNAKE_CASE_     :	list[list[int]]  ,  SCREAMING_SNAKE_CASE_     :	list[int]  ,  SCREAMING_SNAKE_CASE_     :	int    )							->   list[int]:
      """simple docstring"""

      SCREAMING_SNAKE_CASE_      :			List[str]     =       len(cells[0]    )  # 31
      SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       []
      for i in range(SCREAMING_SNAKE_CASE_    ):
            # Get the neighbors of each cell
            # Handle neighbours outside bounds by using 0 as their value
            SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       0 if i == 0 else cells[time][i - 1]
            SCREAMING_SNAKE_CASE_      :			Tuple     =       0 if i == population - 1 else cells[time][i + 1]
            # Define a new cell and add it to the new generation
            SCREAMING_SNAKE_CASE_      :			Dict     =       7 - int(F"{left_neighbor}{cells[time][i]}{right_neighbor}"  ,  2    )
            next_generation.append(rule[situation]    )
      return next_generation


def 					__lowerCamelCase			(      SCREAMING_SNAKE_CASE_     :	list[list[int]]    )							->   Image.Image:
      """simple docstring"""

      SCREAMING_SNAKE_CASE_      :			List[Any]     =       Image.new("RGB"  ,  (len(cells[0]    ), len(SCREAMING_SNAKE_CASE_    ))    )
      SCREAMING_SNAKE_CASE_      :			Optional[int]     =       img.load()
      # Generates image
      for w in range(img.width    ):
            for h in range(img.height    ):
                  SCREAMING_SNAKE_CASE_      :			List[str]     =       2_5_5 - int(2_5_5 * cells[h][w]    )
                  SCREAMING_SNAKE_CASE_      :			str     =       (color, color, color)
      return img


if __name__ == "__main__":
      snake_case_       =       bin(int(input('Rule:\n').strip()))[2:]
      snake_case_       =       format_ruleset(int(rule_num))
      for time in range(1_6):
            CELLS.append(new_generation(CELLS, rule, time))
      snake_case_       =       generate_image(CELLS)
      # Uncomment to save the image
      # img.save(f"rule_{rule_num}.png")
      img.show()

