


"""simple docstring"""





import argparse
from collections import OrderedDict
from pathlib import Path

import torch

from transformers import (
    VisualBertConfig,
    VisualBertForMultipleChoice,
    VisualBertForPreTraining,
    VisualBertForQuestionAnswering,
    VisualBertForVisualReasoning,
)
from transformers.utils import logging


logging.set_verbosity_info()
snake_case__		:     Union[str, Any]    				=				logging.get_logger(__name__)

snake_case__		:     int    				=				[
    ('''bert.bert''', '''visual_bert'''),
    ('''bert.cls''', '''cls'''),
    ('''bert.classifier''', '''cls'''),
    ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''),
    ('''position_embeddings_visual''', '''visual_position_embeddings'''),
    ('''projection''', '''visual_projection'''),
]

snake_case__		:     Any    				=				[
    '''nlvr2_coco_pre_trained.th''',
    '''nlvr2_fine_tuned.th''',
    '''nlvr2_pre_trained.th''',
    '''vcr_coco_pre_train.th''',
    '''vcr_fine_tune.th''',
    '''vcr_pre_train.th''',
    '''vqa_coco_pre_trained.th''',
    '''vqa_fine_tuned.th''',
    '''vqa_pre_trained.th''',
]


def      _snake_case						(						_snake_case				:			List[str]			):
      lowerCAmelCase					:	Optional[int]       =   torch.load(_snake_case ,   map_location='''cpu'''			)
      return sd


def      _snake_case						(						_snake_case				:			Optional[int] ,   _snake_case				:			Union[str, Any] ,   _snake_case				:			int=rename_keys_prefix			):
      lowerCAmelCase					:	Any       =   OrderedDict()
      lowerCAmelCase					:	Dict       =   torch.arange(config.max_position_embeddings			).expand((1, -1)			)
      # detector_d = OrderedDict()
      for key in d:
            if "detector" in key:
                  # detector_d[key.replace('detector.','')] = d[key]
                  continue
            lowerCAmelCase					:	Any       =   key
            for name_pair in rename_keys_prefix:
                  lowerCAmelCase					:	List[str]       =   new_key.replace(name_pair[0] ,   name_pair[1]			)
            lowerCAmelCase					:	str       =   d[key]
            if key == "bert.cls.predictions.decoder.weight":
                  # Old bert code didn't have `decoder.bias`, but was added separately
                  lowerCAmelCase					:	Any       =   new_d['''cls.predictions.bias''']
      return new_d


@torch.no_grad()
def      _snake_case						(						_snake_case				:			Optional[int] ,   _snake_case				:			int			):
      assert (
          checkpoint_path.split('''/'''			)[-1] in ACCEPTABLE_CHECKPOINTS
      ), f'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.'''

      # Get Config
      if "pre" in checkpoint_path:
            lowerCAmelCase					:	List[Any]       =   '''pretraining'''
            if "vcr" in checkpoint_path:
                  lowerCAmelCase					:	Optional[int]       =   {'''visual_embedding_dim''': 512}
            elif "vqa_advanced" in checkpoint_path:
                  lowerCAmelCase					:	Any       =   {'''visual_embedding_dim''': 2048}
            elif "vqa" in checkpoint_path:
                  lowerCAmelCase					:	Optional[int]       =   {'''visual_embedding_dim''': 2048}
            elif "nlvr" in checkpoint_path:
                  lowerCAmelCase					:	Optional[int]       =   {'''visual_embedding_dim''': 1024}
            else:
                  raise NotImplementedError(f'''No implementation found for `{checkpoint_path}`.'''			)
      else:
            if "vcr" in checkpoint_path:
                  lowerCAmelCase					:	Any       =   {'''visual_embedding_dim''': 512}
                  lowerCAmelCase					:	Union[str, Any]       =   '''multichoice'''
            elif "vqa_advanced" in checkpoint_path:
                  lowerCAmelCase					:	Union[str, Any]       =   {'''visual_embedding_dim''': 2048}
                  lowerCAmelCase					:	str       =   '''vqa_advanced'''
            elif "vqa" in checkpoint_path:
                  lowerCAmelCase					:	Tuple       =   {'''visual_embedding_dim''': 2048, '''num_labels''': 3129}
                  lowerCAmelCase					:	Dict       =   '''vqa'''
            elif "nlvr" in checkpoint_path:
                  lowerCAmelCase					:	Optional[Any]       =   {
                      '''visual_embedding_dim''': 1024,
                      '''num_labels''': 2,
                  }
                  lowerCAmelCase					:	int       =   '''nlvr'''

      lowerCAmelCase					:	Union[str, Any]       =   VisualBertConfig(**_snake_case			)

      # Load State Dict
      lowerCAmelCase					:	Optional[int]       =   load_state_dict(_snake_case			)

      lowerCAmelCase					:	str       =   get_new_dict(_snake_case ,   _snake_case			)

      if model_type == "pretraining":
            lowerCAmelCase					:	Union[str, Any]       =   VisualBertForPreTraining(_snake_case			)
      elif model_type == "vqa":
            lowerCAmelCase					:	List[str]       =   VisualBertForQuestionAnswering(_snake_case			)
      elif model_type == "nlvr":
            lowerCAmelCase					:	List[Any]       =   VisualBertForVisualReasoning(_snake_case			)
      elif model_type == "multichoice":
            lowerCAmelCase					:	List[str]       =   VisualBertForMultipleChoice(_snake_case			)

      model.load_state_dict(_snake_case			)
      # Save Checkpoints
      Path(_snake_case			).mkdir(exist_ok=_snake_case			)
      model.save_pretrained(_snake_case			)


if __name__ == "__main__":
 snake_case__		:     Optional[int]    				=				argparse.ArgumentParser()
 # Required parameters
 parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''')
 parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''')
 snake_case__		:     Tuple    				=				parser.parse_args()
 convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)






"""simple docstring"""





from __future__ import annotations

from PIL import Image

# Define glider example
snake_case__		:     int    				=				[
    [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
snake_case__		:     Any    				=				[[0, 1, 0], [0, 1, 0], [0, 1, 0]]


def      _snake_case						(						_snake_case				:			list[list[int]]			):
      lowerCAmelCase					:	Union[str, Any]       =   []
      for i in range(len(_snake_case			)			):
            lowerCAmelCase					:	Any       =   []
            for j in range(len(cells[i]			)			):
                  # Get the number of live neighbours
                  lowerCAmelCase					:	Optional[int]       =   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(_snake_case			) - 1 and j > 0:
                        neighbour_count += cells[i + 1][j - 1]
                  if i < len(_snake_case			) - 1:
                        neighbour_count += cells[i + 1][j]
                  if i < len(_snake_case			) - 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.
                  lowerCAmelCase					:	str       =   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(_snake_case			)
      return next_generation


def      _snake_case						(						_snake_case				:			list[list[int]] ,   _snake_case				:			int			):
      lowerCAmelCase					:	int       =   []
      for _ in range(_snake_case			):
            # Create output image
            lowerCAmelCase					:	Union[str, Any]       =   Image.new('''RGB''' ,   (len(cells[0]			), len(_snake_case			))			)
            lowerCAmelCase					:	Union[str, Any]       =   img.load()

            # Save cells to image
            for x in range(len(_snake_case			)			):
                  for y in range(len(cells[0]			)			):
                        lowerCAmelCase					:	Optional[int]       =   255 - cells[y][x] * 255
                        lowerCAmelCase					:	List[Any]       =   (colour, colour, colour)

        # Save image
            images.append(_snake_case			)
            lowerCAmelCase					:	Union[str, Any]       =   new_generation(_snake_case			)
      return images


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


