


"""simple docstring"""







from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers.models.distilbert.modeling_tf_distilbert import (
     TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
     TFDistilBertForMaskedLM,
     TFDistilBertForMultipleChoice,
     TFDistilBertForQuestionAnswering,
     TFDistilBertForSequenceClassification,
     TFDistilBertForTokenClassification,
     TFDistilBertModel,
 )






class 						_A  :







    """simple docstring"""




    def __init__(					self				:    int				, __UpperCAmelCase				:    Union[str, Any]				, ):
      a						:		Optional[Any]      							=			parent
      a						:		str      							=			13
      a						:		Optional[int]      							=			7
      a						:		Tuple      							=			True
      a						:		str      							=			True
      a						:		Tuple      							=			False
      a						:		List[str]      							=			True
      a						:		Dict      							=			99
      a						:		int      							=			32
      a						:		Any      							=			2
      a						:		int      							=			4
      a						:		Optional[Any]      							=			37
      a						:		int      							=			"gelu"
      a						:		int      							=			0.1
      a						:		int      							=			0.1
      a						:		Optional[int]      							=			512
      a						:		int      							=			16
      a						:		Tuple      							=			2
      a						:		str      							=			0.02
      a						:		List[str]      							=			3
      a						:		Optional[Any]      							=			4
      a						:		List[Any]      							=			None






    def 	__snake_case							(					self				:    Optional[int]):
      a						:		Any      							=			ids_tensor([self.batch_size, self.seq_length]				, self.vocab_size)

      a						:		Any      							=			None
      if self.use_input_mask:
        a						:		List[str]      							=			random_attention_mask([self.batch_size, self.seq_length])

      a						:		List[Any]      							=			None
      a						:		int      							=			None
      a						:		Any      							=			None
      if self.use_labels:
        a						:		List[Any]      							=			ids_tensor([self.batch_size]				, self.type_sequence_label_size)
        a						:		Any      							=			ids_tensor([self.batch_size, self.seq_length]				, self.num_labels)
        a						:		Optional[Any]      							=			ids_tensor([self.batch_size]				, self.num_choices)

      a						:		Optional[int]      							=			DistilBertConfig(
          vocab_size=self.vocab_size				, dim=self.hidden_size				, n_layers=self.num_hidden_layers				, n_heads=self.num_attention_heads				, hidden_dim=self.intermediate_size				, hidden_act=self.hidden_act				, dropout=self.hidden_dropout_prob				, attention_dropout=self.attention_probs_dropout_prob				, max_position_embeddings=self.max_position_embeddings				, initializer_range=self.initializer_range				, )

      return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






    def 	__snake_case							(					self				:    int				, __UpperCAmelCase				:    List[str]				, __UpperCAmelCase				:    List[Any]				, __UpperCAmelCase				:    int				, __UpperCAmelCase				:    Optional[Any]				, __UpperCAmelCase				:    Dict				, __UpperCAmelCase				:    List[str]):
      a						:		Optional[Any]      							=			TFDistilBertModel(config=__UpperCAmelCase)
      a						:		Dict      							=			{"input_ids": input_ids, "attention_mask": input_mask}

      a						:		List[Any]      							=			model(__UpperCAmelCase)

      a						:		List[Any]      							=			[input_ids, input_mask]

      a						:		Any      							=			model(__UpperCAmelCase)

      self.parent.assertEqual(result.last_hidden_state.shape				, (self.batch_size, self.seq_length, self.hidden_size))






    def 	__snake_case							(					self				:    str				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    Optional[Any]				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    int				, __UpperCAmelCase				:    Tuple				, __UpperCAmelCase				:    int):
      a						:		Optional[int]      							=			TFDistilBertForMaskedLM(config=__UpperCAmelCase)
      a						:		int      							=			{"input_ids": input_ids, "attention_mask": input_mask}
      a						:		int      							=			model(__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.seq_length, self.vocab_size))






    def 	__snake_case							(					self				:    Union[str, Any]				, __UpperCAmelCase				:    Any				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    List[Any]				, __UpperCAmelCase				:    Optional[Any]				, __UpperCAmelCase				:    Optional[Any]				, __UpperCAmelCase				:    str):
      a						:		Optional[int]      							=			TFDistilBertForQuestionAnswering(config=__UpperCAmelCase)
      a						:		Union[str, Any]      							=			{
          "input_ids": input_ids,
          "attention_mask": input_mask,
      }
      a						:		List[str]      							=			model(__UpperCAmelCase)
      self.parent.assertEqual(result.start_logits.shape				, (self.batch_size, self.seq_length))
      self.parent.assertEqual(result.end_logits.shape				, (self.batch_size, self.seq_length))






    def 	__snake_case							(					self				:    Tuple				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    Optional[int]				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    Dict				, __UpperCAmelCase				:    Optional[int]				, __UpperCAmelCase				:    Optional[Any]):
      a						:		int      							=			self.num_labels
      a						:		Optional[int]      							=			TFDistilBertForSequenceClassification(__UpperCAmelCase)
      a						:		Union[str, Any]      							=			{"input_ids": input_ids, "attention_mask": input_mask}
      a						:		Dict      							=			model(__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.num_labels))






    def 	__snake_case							(					self				:    Dict				, __UpperCAmelCase				:    Optional[int]				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    str				, __UpperCAmelCase				:    Any				, __UpperCAmelCase				:    List[str]				, __UpperCAmelCase				:    List[str]):
      a						:		str      							=			self.num_choices
      a						:		Optional[Any]      							=			TFDistilBertForMultipleChoice(__UpperCAmelCase)
      a						:		Any      							=			tf.tile(tf.expand_dims(__UpperCAmelCase				, 1)				, (1, self.num_choices, 1))
      a						:		Union[str, Any]      							=			tf.tile(tf.expand_dims(__UpperCAmelCase				, 1)				, (1, self.num_choices, 1))
      a						:		str      							=			{
          "input_ids": multiple_choice_inputs_ids,
          "attention_mask": multiple_choice_input_mask,
      }
      a						:		Tuple      							=			model(__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.num_choices))






    def 	__snake_case							(					self				:    List[Any]				, __UpperCAmelCase				:    Optional[Any]				, __UpperCAmelCase				:    Tuple				, __UpperCAmelCase				:    Union[str, Any]				, __UpperCAmelCase				:    Optional[int]				, __UpperCAmelCase				:    Any				, __UpperCAmelCase				:    List[Any]):
      a						:		Tuple      							=			self.num_labels
      a						:		Dict      							=			TFDistilBertForTokenClassification(__UpperCAmelCase)
      a						:		int      							=			{"input_ids": input_ids, "attention_mask": input_mask}
      a						:		Tuple      							=			model(__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape				, (self.batch_size, self.seq_length, self.num_labels))






    def 	__snake_case							(					self				:    Any):
      a						:		List[str]      							=			self.prepare_config_and_inputs()
      ((a)							,		(a)							,		(a)							,		(a)							,		(a)							,		(a))						:		Optional[Any]      							=			config_and_inputs
      a						:		List[Any]      							=			{"input_ids": input_ids, "attention_mask": input_mask}
      return config, inputs_dict






@require_tf
class 						_A  (  _a    ,_a    ,unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase       :							List[str]	=       (
        (
            TFDistilBertModel,
            TFDistilBertForMaskedLM,
            TFDistilBertForQuestionAnswering,
            TFDistilBertForSequenceClassification,
            TFDistilBertForTokenClassification,
            TFDistilBertForMultipleChoice,
        )
        if is_tf_available()
        else None
    )
    UpperCAmelCase       :							Optional[int]	=       (
        {
            """feature-extraction""": TFDistilBertModel,
            """fill-mask""": TFDistilBertForMaskedLM,
            """question-answering""": TFDistilBertForQuestionAnswering,
            """text-classification""": TFDistilBertForSequenceClassification,
            """token-classification""": TFDistilBertForTokenClassification,
            """zero-shot""": TFDistilBertForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )
    UpperCAmelCase       :							Optional[Any]	=       False
    UpperCAmelCase       :							Tuple	=       False






    def 	__snake_case							(					self				:    str):
      a						:		int      							=			TFDistilBertModelTester(self)
      a						:		Any      							=			ConfigTester(self				, config_class=__UpperCAmelCase				, dim=37)






    def 	__snake_case							(					self				:    Optional[Any]):
      self.config_tester.run_common_tests()






    def 	__snake_case							(					self				:    Tuple):
      a						:		Any      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_distilbert_model(*__UpperCAmelCase)






    def 	__snake_case							(					self				:    Optional[int]):
      a						:		Dict      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_distilbert_for_masked_lm(*__UpperCAmelCase)






    def 	__snake_case							(					self				:    Tuple):
      a						:		Any      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_distilbert_for_question_answering(*__UpperCAmelCase)






    def 	__snake_case							(					self				:    Union[str, Any]):
      a						:		Dict      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_distilbert_for_sequence_classification(*__UpperCAmelCase)






    def 	__snake_case							(					self				:    Tuple):
      a						:		List[Any]      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_distilbert_for_multiple_choice(*__UpperCAmelCase)






    def 	__snake_case							(					self				:    Optional[int]):
      a						:		List[str]      							=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_distilbert_for_token_classification(*__UpperCAmelCase)






    @slow
    def 	__snake_case							(					self				:    Optional[Any]):
      for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]):
        a						:		Tuple      							=			TFDistilBertModel.from_pretrained(__UpperCAmelCase)
        self.assertIsNotNone(__UpperCAmelCase)






@require_tf
class 						_A  (  unittest.TestCase  ):







    """simple docstring"""




    @slow
    def 	__snake_case							(					self				:    Tuple):
      a						:		List[str]      							=			TFDistilBertModel.from_pretrained("distilbert-base-uncased")
      a						:		Tuple      							=			tf.constant([[0, 1, 2, 3, 4, 5]])
      a						:		List[Any]      							=			model(__UpperCAmelCase)[0]

      a						:		Union[str, Any]      							=			[1, 6, 768]
      self.assertEqual(output.shape				, __UpperCAmelCase)

      a						:		Optional[int]      							=			tf.constant(
          [
              [
                  [0.19_261_885, -0.13_732_955, 0.4_119_799],
                  [0.22_150_156, -0.07_422_661, 0.39_037_204],
                  [0.22_756_018, -0.0_896_414, 0.3_701_467],
              ]
          ])
      tf.debugging.assert_near(output[:, :3, :3]				, __UpperCAmelCase				, atol=1e-4)










"""simple docstring"""







from __future__ import annotations

from PIL import Image

# Define glider example
__lowercase    					=      [
    [0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0, 0],
    [1, 1, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
]

# Define blinker example
__lowercase    					=      [[0, 1, 0], [0, 1, 0], [0, 1, 0]]


def      lowercase			(				A_       )->      list[list[int]]:
  '''simple docstring'''







  a						:		str      							=			[]
  for i in range(len(A_       )       ):
    a						:		str      							=			[]
    for j in range(len(cells[i]       )       ):
      # Get the number of live neighbours
      a						:		Union[str, Any]      							=			0
      if i > 0 and j > 0:
        neighbour_count += cells[i - 1][j - 1]
      if i > 0:
        neighbour_count += cells[i - 1][j]
      if i > 0 and j < len(cells[i]       ) - 1:
        neighbour_count += cells[i - 1][j + 1]
      if j > 0:
        neighbour_count += cells[i][j - 1]
      if j < len(cells[i]       ) - 1:
        neighbour_count += cells[i][j + 1]
      if i < len(A_       ) - 1 and j > 0:
        neighbour_count += cells[i + 1][j - 1]
      if i < len(A_       ) - 1:
        neighbour_count += cells[i + 1][j]
      if i < len(A_       ) - 1 and j < len(cells[i]       ) - 1:
        neighbour_count += cells[i + 1][j + 1]

      # Rules of the game of life (excerpt from Wikipedia):
      # 1. Any live cell with two or three live neighbours survives.
      # 2. Any dead cell with three live neighbours becomes a live cell.
      # 3. All other live cells die in the next generation.
      #    Similarly, all other dead cells stay dead.
      a						:		Tuple      							=			cells[i][j] == 1
      if (
          (alive and 2 <= neighbour_count <= 3)
          or not alive
          and neighbour_count == 3
      ):
        next_generation_row.append(1       )
      else:
        next_generation_row.append(0       )

    next_generation.append(A_       )
  return next_generation


def      lowercase			(				A_  ,   A_       )->      list[Image.Image]:
  '''simple docstring'''







  a						:		List[str]      							=			[]
  for _ in range(A_       ):
    # Create output image
    a						:		str      							=			Image.new("RGB"  ,   (len(cells[0]       ), len(A_       ))       )
    a						:		Union[str, Any]      							=			img.load()

    # Save cells to image
    for x in range(len(A_       )       ):
      for y in range(len(cells[0]       )       ):
        a						:		Optional[Any]      							=			255 - cells[y][x] * 255
        a						:		str      							=			(colour, colour, colour)

        # Save image
    images.append(A_       )
    a						:		Tuple      							=			new_generation(A_       )
  return images


if __name__ == "__main__":
 __lowercase    					=      generate_images(GLIDER, 16)
 images[0].save("""out.gif""", save_all=True, append_images=images[1:])






