


'''simple docstring'''
import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    BertTokenizer,
    ViltConfig,
    ViltForImageAndTextRetrieval,
    ViltForImagesAndTextClassification,
    ViltForMaskedLM,
    ViltForQuestionAnswering,
    ViltImageProcessor,
    ViltProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
UpperCamelCase__    					=      logging.get_logger(__name__)





def 					a__       (					lowerCAmelCase__  ,					lowerCAmelCase__=False  ,					lowerCAmelCase__=False  ,					lowerCAmelCase__=False						)    ->	Optional[Any]:
    UpperCAmelCase__			:		Tuple													=				[]
    for i in range(config.num_hidden_layers						):
        # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
        rename_keys.append((F"""transformer.blocks.{i}.norm1.weight""", F"""vilt.encoder.layer.{i}.layernorm_before.weight""")						)
        rename_keys.append((F"""transformer.blocks.{i}.norm1.bias""", F"""vilt.encoder.layer.{i}.layernorm_before.bias""")						)
        rename_keys.append(
            (F"""transformer.blocks.{i}.attn.proj.weight""", F"""vilt.encoder.layer.{i}.attention.output.dense.weight""")						)
        rename_keys.append(
            (F"""transformer.blocks.{i}.attn.proj.bias""", F"""vilt.encoder.layer.{i}.attention.output.dense.bias""")						)
        rename_keys.append((F"""transformer.blocks.{i}.norm2.weight""", F"""vilt.encoder.layer.{i}.layernorm_after.weight""")						)
        rename_keys.append((F"""transformer.blocks.{i}.norm2.bias""", F"""vilt.encoder.layer.{i}.layernorm_after.bias""")						)
        rename_keys.append(
            (F"""transformer.blocks.{i}.mlp.fc1.weight""", F"""vilt.encoder.layer.{i}.intermediate.dense.weight""")						)
        rename_keys.append((F"""transformer.blocks.{i}.mlp.fc1.bias""", F"""vilt.encoder.layer.{i}.intermediate.dense.bias""")						)
        rename_keys.append((F"""transformer.blocks.{i}.mlp.fc2.weight""", F"""vilt.encoder.layer.{i}.output.dense.weight""")						)
        rename_keys.append((F"""transformer.blocks.{i}.mlp.fc2.bias""", F"""vilt.encoder.layer.{i}.output.dense.bias""")						)

    # embeddings
    rename_keys.extend(
        [
            # text embeddings
            ('''text_embeddings.word_embeddings.weight''', '''vilt.embeddings.text_embeddings.word_embeddings.weight'''),
            (
                '''text_embeddings.position_embeddings.weight''',
                '''vilt.embeddings.text_embeddings.position_embeddings.weight''',
            ),
            ('''text_embeddings.position_ids''', '''vilt.embeddings.text_embeddings.position_ids'''),
            (
                '''text_embeddings.token_type_embeddings.weight''',
                '''vilt.embeddings.text_embeddings.token_type_embeddings.weight''',
            ),
            ('''text_embeddings.LayerNorm.weight''', '''vilt.embeddings.text_embeddings.LayerNorm.weight'''),
            ('''text_embeddings.LayerNorm.bias''', '''vilt.embeddings.text_embeddings.LayerNorm.bias'''),
            # patch embeddings
            ('''transformer.cls_token''', '''vilt.embeddings.cls_token'''),
            ('''transformer.patch_embed.proj.weight''', '''vilt.embeddings.patch_embeddings.projection.weight'''),
            ('''transformer.patch_embed.proj.bias''', '''vilt.embeddings.patch_embeddings.projection.bias'''),
            ('''transformer.pos_embed''', '''vilt.embeddings.position_embeddings'''),
            # token type embeddings
            ('''token_type_embeddings.weight''', '''vilt.embeddings.token_type_embeddings.weight'''),
        ]						)

    # final layernorm + pooler
    rename_keys.extend(
        [
            ('''transformer.norm.weight''', '''vilt.layernorm.weight'''),
            ('''transformer.norm.bias''', '''vilt.layernorm.bias'''),
            ('''pooler.dense.weight''', '''vilt.pooler.dense.weight'''),
            ('''pooler.dense.bias''', '''vilt.pooler.dense.bias'''),
        ]						)

    # classifier head(s)
    if vqa_model:
        # classification head
        rename_keys.extend(
            [
                ('''vqa_classifier.0.weight''', '''classifier.0.weight'''),
                ('''vqa_classifier.0.bias''', '''classifier.0.bias'''),
                ('''vqa_classifier.1.weight''', '''classifier.1.weight'''),
                ('''vqa_classifier.1.bias''', '''classifier.1.bias'''),
                ('''vqa_classifier.3.weight''', '''classifier.3.weight'''),
                ('''vqa_classifier.3.bias''', '''classifier.3.bias'''),
            ]						)
    elif nlvr_model:
        # classification head
        rename_keys.extend(
            [
                ('''nlvr2_classifier.0.weight''', '''classifier.0.weight'''),
                ('''nlvr2_classifier.0.bias''', '''classifier.0.bias'''),
                ('''nlvr2_classifier.1.weight''', '''classifier.1.weight'''),
                ('''nlvr2_classifier.1.bias''', '''classifier.1.bias'''),
                ('''nlvr2_classifier.3.weight''', '''classifier.3.weight'''),
                ('''nlvr2_classifier.3.bias''', '''classifier.3.bias'''),
            ]						)
    else:
        pass

    return rename_keys





def 					a__       (					lowerCAmelCase__  ,					lowerCAmelCase__						)    ->	List[str]:
    for i in range(config.num_hidden_layers						):
        UpperCAmelCase__			:		Tuple													=				'''vilt.'''
        # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
        UpperCAmelCase__			:		Any													=				state_dict.pop(F"""transformer.blocks.{i}.attn.qkv.weight"""						)
        UpperCAmelCase__			:		List[Any]													=				state_dict.pop(F"""transformer.blocks.{i}.attn.qkv.bias"""						)
        # next, add query, keys and values (in that order) to the state dict
        UpperCAmelCase__			:		List[str]													=				in_proj_weight[
            : config.hidden_size, :
        ]
        UpperCAmelCase__			:		Optional[int]													=				in_proj_bias[: config.hidden_size]
        UpperCAmelCase__			:		Any													=				in_proj_weight[
            config.hidden_size : config.hidden_size * 2, :
        ]
        UpperCAmelCase__			:		Any													=				in_proj_bias[
            config.hidden_size : config.hidden_size * 2
        ]
        UpperCAmelCase__			:		Optional[Any]													=				in_proj_weight[
            -config.hidden_size :, :
        ]
        UpperCAmelCase__			:		Optional[Any]													=				in_proj_bias[-config.hidden_size :]





def 					a__       (					lowerCAmelCase__						)    ->	Optional[int]:
    UpperCAmelCase__			:		List[Any]													=				['''head.weight''', '''head.bias''']
    for k in ignore_keys:
        state_dict.pop(__UpperCAmelCase  ,					__UpperCAmelCase						)





def 					a__       (					lowerCAmelCase__  ,					lowerCAmelCase__  ,					lowerCAmelCase__						)    ->	Optional[Any]:
    UpperCAmelCase__			:		Optional[int]													=				dct.pop(__UpperCAmelCase						)
    UpperCAmelCase__			:		int													=				val





@torch.no_grad()
def 					a__       (					lowerCAmelCase__  ,					lowerCAmelCase__						)    ->	Dict:
    UpperCAmelCase__			:		List[Any]													=				ViltConfig(image_size=3_84  ,					patch_size=32  ,					tie_word_embeddings=__UpperCAmelCase						)
    UpperCAmelCase__			:		Any													=				False
    UpperCAmelCase__			:		Optional[Any]													=				False
    UpperCAmelCase__			:		Any													=				False
    UpperCAmelCase__			:		Any													=				False
    if "vqa" in checkpoint_url:
        UpperCAmelCase__			:		str													=				True
        UpperCAmelCase__			:		int													=				31_29
        UpperCAmelCase__			:		Any													=				'''huggingface/label-files'''
        UpperCAmelCase__			:		Optional[Any]													=				'''vqa2-id2label.json'''
        UpperCAmelCase__			:		List[Any]													=				json.load(open(hf_hub_download(__UpperCAmelCase  ,					__UpperCAmelCase  ,					repo_type='''dataset'''						)  ,					'''r'''						)						)
        UpperCAmelCase__			:		Optional[Any]													=				{int(__UpperCAmelCase						): v for k, v in idalabel.items()}
        UpperCAmelCase__			:		str													=				idalabel
        UpperCAmelCase__			:		Optional[Any]													=				{v: k for k, v in idalabel.items()}
        UpperCAmelCase__			:		str													=				ViltForQuestionAnswering(__UpperCAmelCase						)
    elif "nlvr" in checkpoint_url:
        UpperCAmelCase__			:		List[Any]													=				True
        UpperCAmelCase__			:		Union[str, Any]													=				2
        UpperCAmelCase__			:		Tuple													=				{0: '''False''', 1: '''True'''}
        UpperCAmelCase__			:		Optional[int]													=				{v: k for k, v in config.idalabel.items()}
        UpperCAmelCase__			:		Dict													=				3
        UpperCAmelCase__			:		Dict													=				ViltForImagesAndTextClassification(__UpperCAmelCase						)
    elif "irtr" in checkpoint_url:
        UpperCAmelCase__			:		Any													=				True
        UpperCAmelCase__			:		List[str]													=				ViltForImageAndTextRetrieval(__UpperCAmelCase						)
    elif "mlm_itm" in checkpoint_url:
        UpperCAmelCase__			:		Any													=				True
        UpperCAmelCase__			:		List[Any]													=				ViltForMaskedLM(__UpperCAmelCase						)
    else:
        raise ValueError('''Unknown model type'''						)

    # load state_dict of original model, remove and rename some keys
    UpperCAmelCase__			:		Tuple													=				torch.hub.load_state_dict_from_url(__UpperCAmelCase  ,					map_location='''cpu'''						)['''state_dict''']
    UpperCAmelCase__			:		Optional[int]													=				create_rename_keys(__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase						)
    for src, dest in rename_keys:
        rename_key(__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase						)
    read_in_q_k_v(__UpperCAmelCase  ,					__UpperCAmelCase						)
    if mlm_model or irtr_model:
        UpperCAmelCase__			:		Any													=				['''itm_score.fc.weight''', '''itm_score.fc.bias''']
        for k in ignore_keys:
            state_dict.pop(__UpperCAmelCase  ,					__UpperCAmelCase						)

    # load state dict into HuggingFace model
    model.eval()
    if mlm_model:
        UpperCAmelCase__			:		Tuple													=				model.load_state_dict(__UpperCAmelCase  ,					strict=__UpperCAmelCase						)
        assert missing_keys == ["mlm_score.decoder.bias"]
    else:
        model.load_state_dict(__UpperCAmelCase						)

    # Define processor
    UpperCAmelCase__			:		Optional[int]													=				ViltImageProcessor(size=3_84						)
    UpperCAmelCase__			:		Union[str, Any]													=				BertTokenizer.from_pretrained('''bert-base-uncased'''						)
    UpperCAmelCase__			:		Union[str, Any]													=				ViltProcessor(__UpperCAmelCase  ,					__UpperCAmelCase						)

    # Forward pass on example inputs (image + text)
    if nlvr_model:
        UpperCAmelCase__			:		Tuple													=				Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg'''  ,					stream=__UpperCAmelCase						).raw						)
        UpperCAmelCase__			:		Union[str, Any]													=				Image.open(requests.get('''https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg'''  ,					stream=__UpperCAmelCase						).raw						)
        UpperCAmelCase__			:		List[Any]													=				(
            '''The left image contains twice the number of dogs as the right image, and at least two dogs in total are'''
            ''' standing.'''
        )
        UpperCAmelCase__			:		Any													=				processor(__UpperCAmelCase  ,					__UpperCAmelCase  ,					return_tensors='''pt'''						)
        UpperCAmelCase__			:		Union[str, Any]													=				processor(__UpperCAmelCase  ,					__UpperCAmelCase  ,					return_tensors='''pt'''						)
        UpperCAmelCase__			:		List[Any]													=				model(
            input_ids=encoding_a.input_ids  ,					pixel_values=encoding_a.pixel_values  ,					pixel_values_a=encoding_a.pixel_values  ,					)
    else:
        UpperCAmelCase__			:		List[Any]													=				Image.open(requests.get('''http://images.cocodataset.org/val2017/000000039769.jpg'''  ,					stream=__UpperCAmelCase						).raw						)
        if mlm_model:
            UpperCAmelCase__			:		List[Any]													=				'''a bunch of [MASK] laying on a [MASK].'''
        else:
            UpperCAmelCase__			:		Optional[Any]													=				'''How many cats are there?'''
        UpperCAmelCase__			:		int													=				processor(__UpperCAmelCase  ,					__UpperCAmelCase  ,					return_tensors='''pt'''						)
        UpperCAmelCase__			:		Tuple													=				model(**__UpperCAmelCase						)

    # Verify outputs
    if mlm_model:
        UpperCAmelCase__			:		List[Any]													=				torch.Size([1, 11, 3_05_22]						)
        UpperCAmelCase__			:		Any													=				torch.tensor([-12.50_61, -12.51_23, -12.51_74]						)
        assert outputs.logits.shape == expected_shape
        assert torch.allclose(outputs.logits[0, 0, :3]  ,					__UpperCAmelCase  ,					atol=1E-4						)

        # verify masked token prediction equals "cats"
        UpperCAmelCase__			:		Optional[int]													=				outputs.logits[0, 4, :].argmax(-1						).item()
        assert tokenizer.decode([predicted_id]						) == "cats"
    elif vqa_model:
        UpperCAmelCase__			:		Optional[int]													=				torch.Size([1, 31_29]						)
        UpperCAmelCase__			:		int													=				torch.tensor([-15.94_95, -18.14_72, -10.30_41]						)
        assert torch.allclose(outputs.logits[0, :3]  ,					__UpperCAmelCase  ,					atol=1E-4						)
        assert outputs.logits.shape == expected_shape
        assert torch.allclose(outputs.logits[0, 0, :3]  ,					__UpperCAmelCase  ,					atol=1E-4						)

        # verify vqa prediction equals "2"
        UpperCAmelCase__			:		Union[str, Any]													=				outputs.logits.argmax(-1						).item()
        assert model.config.idalabel[predicted_idx] == "2"
    elif nlvr_model:
        UpperCAmelCase__			:		Any													=				torch.Size([1, 2]						)
        UpperCAmelCase__			:		Union[str, Any]													=				torch.tensor([-2.8_7_2_1, 2.1_2_9_1]						)
        assert torch.allclose(outputs.logits[0, :3]  ,					__UpperCAmelCase  ,					atol=1E-4						)
        assert outputs.logits.shape == expected_shape

    Path(__UpperCAmelCase						).mkdir(exist_ok=__UpperCAmelCase						)
    print(F"""Saving model and processor to {pytorch_dump_folder_path}"""						)
    model.save_pretrained(__UpperCAmelCase						)
    processor.save_pretrained(__UpperCAmelCase						)


if __name__ == "__main__":
  UpperCamelCase__    					=      argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '''--checkpoint_url''',
      default='''https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt''',
      type=str,
      help='''URL of the checkpoint you\'d like to convert.''',
  )
  parser.add_argument(
      '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
  )

  UpperCamelCase__    					=      parser.parse_args()
  convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)

"""simple docstring"""






from collections import defaultdict
from typing import Optional

from ..image_utils import load_image
from ..utils import (
    add_end_docstrings,
    is_torch_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_torch_available():
       import torch

       from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING

__A			   = logging.get_logger(__name__)


@add_end_docstrings(_UpperCAmelCase  )
class     UpperCAmelCase						(_UpperCAmelCase  ):



    """simple docstring"""

    def __init__(   self    ,			**_UpperCAmelCase							):
       super().__init__(**_UpperCAmelCase							)
       requires_backends(self    ,			'''vision'''							)
       requires_backends(self    ,			'''torch'''							)

       if self.framework != "pt":
          raise ValueError(F"""The {self.__class__} is only available in PyTorch."""							)

       self.check_model_type(_UpperCAmelCase							)






    def _snake_case			(   self    ,			**_UpperCAmelCase							):
       lowercase__:   List[Any]					=      {}
       lowercase__:   List[Any]					=      {}
       lowercase__:   Dict					=      {}
       # preprocess args
       if "points_per_batch" in kwargs:
          lowercase__:   Dict					=      kwargs['''points_per_batch''']
       if "points_per_crop" in kwargs:
          lowercase__:   Any					=      kwargs['''points_per_crop''']
       if "crops_n_layers" in kwargs:
          lowercase__:   Union[str, Any]					=      kwargs['''crops_n_layers''']
       if "crop_overlap_ratio" in kwargs:
          lowercase__:   Optional[Any]					=      kwargs['''crop_overlap_ratio''']
       if "crop_n_points_downscale_factor" in kwargs:
          lowercase__:   Union[str, Any]					=      kwargs['''crop_n_points_downscale_factor''']
       # postprocess args
       if "pred_iou_thresh" in kwargs:
          lowercase__:   Any					=      kwargs['''pred_iou_thresh''']
       if "stability_score_offset" in kwargs:
          lowercase__:   Tuple					=      kwargs['''stability_score_offset''']
       if "mask_threshold" in kwargs:
          lowercase__:   List[str]					=      kwargs['''mask_threshold''']
       if "stability_score_thresh" in kwargs:
          lowercase__:   str					=      kwargs['''stability_score_thresh''']
       if "crops_nms_thresh" in kwargs:
          lowercase__:   List[str]					=      kwargs['''crops_nms_thresh''']
       if "output_rle_mask" in kwargs:
          lowercase__:   Dict					=      kwargs['''output_rle_mask''']
       if "output_bboxes_mask" in kwargs:
          lowercase__:   int					=      kwargs['''output_bboxes_mask''']
       return preprocess_kwargs, forward_params, postprocess_kwargs






    def __call__(   self    ,			_UpperCAmelCase    ,			*_UpperCAmelCase    ,			_UpperCAmelCase=None    ,			_UpperCAmelCase=None    ,			**_UpperCAmelCase							):
       return super().__call__(_UpperCAmelCase    ,			*_UpperCAmelCase    ,			num_workers=_UpperCAmelCase    ,			batch_size=_UpperCAmelCase    ,			**_UpperCAmelCase							)






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase=64    ,			_UpperCAmelCase = 0    ,			_UpperCAmelCase = 512 / 1500    ,			_UpperCAmelCase = 32    ,			_UpperCAmelCase = 1    ,			):
       lowercase__:   Union[str, Any]					=      load_image(_UpperCAmelCase							)
       lowercase__:   Dict					=      self.image_processor.size['''longest_edge''']
       lowercase__, lowercase__, lowercase__, lowercase__:   Optional[Any]					=      self.image_processor.generate_crop_boxes(
           _UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							)
       lowercase__:   List[Any]					=      self.image_processor(images=_UpperCAmelCase    ,			return_tensors='''pt'''							)

       with self.device_placement():
          if self.framework == "pt":
             lowercase__:   Tuple					=      self.get_inference_context()
             with inference_context():
                lowercase__:   Optional[Any]					=      self._ensure_tensor_on_device(_UpperCAmelCase    ,			device=self.device							)
                lowercase__:   Any					=      self.model.get_image_embeddings(model_inputs.pop('''pixel_values'''							)							)
                lowercase__:   Tuple					=      image_embeddings

       lowercase__:   Optional[Any]					=      grid_points.shape[1]
       lowercase__:   Tuple					=      points_per_batch if points_per_batch is not None else n_points

       if points_per_batch <= 0:
          raise ValueError(
              '''Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. '''
              '''To return all points at once, set points_per_batch to None'''							)

       for i in range(0    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
          lowercase__:   Dict					=      grid_points[:, i : i + points_per_batch, :, :]
          lowercase__:   int					=      input_labels[:, i : i + points_per_batch]
          lowercase__:   Any					=      i == n_points - points_per_batch
          yield {
              "input_points": batched_points,
              "input_labels": labels,
              "input_boxes": crop_boxes,
              "is_last": is_last,
              **model_inputs,
          }






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase=0.88    ,			_UpperCAmelCase=0.95    ,			_UpperCAmelCase=0    ,			_UpperCAmelCase=1    ,			):
       lowercase__:   List[Any]					=      model_inputs.pop('''input_boxes'''							)
       lowercase__:   List[Any]					=      model_inputs.pop('''is_last'''							)
       lowercase__:   Any					=      model_inputs.pop('''original_sizes'''							).tolist()
       lowercase__:   Union[str, Any]					=      model_inputs.pop('''reshaped_input_sizes'''							).tolist()

       lowercase__:   List[Any]					=      self.model(**_UpperCAmelCase							)

       # post processing happens here in order to avoid CPU GPU copies of ALL the masks
       lowercase__:   int					=      model_outputs['''pred_masks''']
       lowercase__:   str					=      self.image_processor.post_process_masks(
           _UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			binarize=_UpperCAmelCase							)
       lowercase__:   str					=      model_outputs['''iou_scores''']
       lowercase__, lowercase__, lowercase__:   Optional[int]					=      self.image_processor.filter_masks(
           masks[0]    ,			iou_scores[0]    ,			original_sizes[0]    ,			input_boxes[0]    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			)
       return {
           "masks": masks,
           "is_last": is_last,
           "boxes": boxes,
           "iou_scores": iou_scores,
       }






    def _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase=False    ,			_UpperCAmelCase=False    ,			_UpperCAmelCase=0.7    ,			):
       lowercase__:   int					=      []
       lowercase__:   str					=      []
       lowercase__:   List[Any]					=      []
       for model_output in model_outputs:
          all_scores.append(model_output.pop('''iou_scores'''							)							)
          all_masks.extend(model_output.pop('''masks'''							)							)
          all_boxes.append(model_output.pop('''boxes'''							)							)

       lowercase__:   Any					=      torch.cat(_UpperCAmelCase							)
       lowercase__:   Dict					=      torch.cat(_UpperCAmelCase							)
       lowercase__, lowercase__, lowercase__, lowercase__:   Any					=      self.image_processor.post_process_for_mask_generation(
           _UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							)

       lowercase__:   Union[str, Any]					=      defaultdict(_UpperCAmelCase							)
       for output in model_outputs:
          for k, v in output.items():
             extra[k].append(_UpperCAmelCase							)

       lowercase__:   Any					=      {}
       if output_rle_mask:
          lowercase__:   Optional[Any]					=      rle_mask

       if output_bboxes_mask:
          lowercase__:   Optional[int]					=      bounding_boxes

       return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
