

import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, SequentialSampler, Subset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    GlueDataset,
    default_data_collator,
    glue_compute_metrics,
    glue_output_modes,
    glue_processors,
    set_seed,
)
from transformers.trainer_utils import is_main_process


__A    	=			logging.getLogger(__name__)



def    snake_case_(_UpperCamelCase  )							->			Optional[Any]:



  """simple docstring"""






  _snake_case		=							p * torch.log(_UpperCamelCase  )
  _snake_case		=							0
  return -plogp.sum(dim=-1  )



def    snake_case_(_UpperCamelCase  )							->			int:



  """simple docstring"""






  logger.info('''lv, h >\t''' + '''\t'''.join(F"""{x + 1}""" for x in range(len(_UpperCamelCase  )  )  )  )
  for row in range(len(_UpperCamelCase  )  ):
    if tensor.dtype != torch.long:
      logger.info(F"""layer {row + 1}:\t""" + '''\t'''.join(F"""{x:.5f}""" for x in tensor[row].cpu().data  )  )
    else:
      logger.info(F"""layer {row + 1}:\t""" + '''\t'''.join(F"""{x:d}""" for x in tensor[row].cpu().data  )  )



def    snake_case_(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase=True				, _UpperCamelCase=True				, _UpperCamelCase=None				, _UpperCamelCase=False  )							->			Optional[Any]:



  """simple docstring"""






  _snake_case,  _snake_case		=							model.config.num_hidden_layers, model.config.num_attention_heads
  _snake_case		=							torch.zeros(_UpperCamelCase				, _UpperCamelCase  ).to(args.device  )
  _snake_case		=							torch.zeros(_UpperCamelCase				, _UpperCamelCase  ).to(args.device  )

  if head_mask is None:
    _snake_case		=							torch.ones(_UpperCamelCase				, _UpperCamelCase  ).to(args.device  )

  head_mask.requires_grad_(requires_grad=_UpperCamelCase  )
  # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
  if actually_pruned:
    _snake_case		=							None

  _snake_case		=							None
  _snake_case		=							None
  _snake_case		=							0.0

  for step, inputs in enumerate(tqdm(_UpperCamelCase				, desc='''Iteration'''				, disable=args.local_rank not in [-1, 0]  )  ):
    for k, v in inputs.items():
      _snake_case		=							v.to(args.device  )

    # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
    _snake_case		=							model(**_UpperCamelCase				, head_mask=_UpperCamelCase  )
    _snake_case,  _snake_case,  _snake_case		=							(
        outputs[0],
        outputs[1],
        outputs[-1],
    )  # Loss and logits are the first, attention the last
    loss.backward()  # Backpropagate to populate the gradients in the head mask

    if compute_entropy:
      for layer, attn in enumerate(_UpperCamelCase  ):
        _snake_case		=							entropy(attn.detach()  ) * inputs['''attention_mask'''].float().unsqueeze(1  )
        attn_entropy[layer] += masked_entropy.sum(-1  ).sum(0  ).detach()

    if compute_importance:
      head_importance += head_mask.grad.abs().detach()

    # Also store our logits/labels if we want to compute metrics afterwards
    if preds is None:
      _snake_case		=							logits.detach().cpu().numpy()
      _snake_case		=							inputs['''labels'''].detach().cpu().numpy()
    else:
      _snake_case		=							np.append(_UpperCamelCase				, logits.detach().cpu().numpy()				, axis=0  )
      _snake_case		=							np.append(_UpperCamelCase				, inputs['''labels'''].detach().cpu().numpy()				, axis=0  )

    tot_tokens += inputs["attention_mask"].float().detach().sum().data

  # Normalize
  attn_entropy /= tot_tokens
  head_importance /= tot_tokens
  # Layerwise importance normalization
  if not args.dont_normalize_importance_by_layer:
    _snake_case		=							2
    _snake_case		=							torch.pow(torch.pow(_UpperCamelCase				, _UpperCamelCase  ).sum(-1  )				, 1 / exponent  )
    head_importance /= norm_by_layer.unsqueeze(-1  ) + 1E-20

  if not args.dont_normalize_global_importance:
    _snake_case		=							(head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

  # Print/save matrices
  np.save(os.path.join(args.output_dir				, '''attn_entropy.npy'''  )				, attn_entropy.detach().cpu().numpy()  )
  np.save(os.path.join(args.output_dir				, '''head_importance.npy'''  )				, head_importance.detach().cpu().numpy()  )

  logger.info('''Attention entropies'''  )
  print_ad_tensor(_UpperCamelCase  )
  logger.info('''Head importance scores'''  )
  print_ad_tensor(_UpperCamelCase  )
  logger.info('''Head ranked by importance scores'''  )
  _snake_case		=							torch.zeros(head_importance.numel()				, dtype=torch.long				, device=args.device  )
  _snake_case		=							torch.arange(
      head_importance.numel()				, device=args.device  )
  _snake_case		=							head_ranks.view_as(_UpperCamelCase  )
  print_ad_tensor(_UpperCamelCase  )

  return attn_entropy, head_importance, preds, labels



def    snake_case_(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase  )							->			Tuple:



  """simple docstring"""






  _snake_case,  _snake_case,  _snake_case,  _snake_case		=							compute_heads_importance(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase				, compute_entropy=_UpperCamelCase  )
  _snake_case		=							np.argmax(_UpperCamelCase				, axis=1  ) if args.output_mode == '''classification''' else np.squeeze(_UpperCamelCase  )
  _snake_case		=							glue_compute_metrics(args.task_name				, _UpperCamelCase				, _UpperCamelCase  )[args.metric_name]
  logger.info('''Pruning: original score: %f, threshold: %f'''				, _UpperCamelCase				, original_score * args.masking_threshold  )

  _snake_case		=							torch.ones_like(_UpperCamelCase  )
  _snake_case		=							max(1				, int(new_head_mask.numel() * args.masking_amount  )  )

  _snake_case		=							original_score
  while current_score >= original_score * args.masking_threshold:
    _snake_case		=							new_head_mask.clone()  # save current head mask
    # heads from least important to most - keep only not-masked heads
    _snake_case		=							float('''Inf'''  )
    _snake_case		=							head_importance.view(-1  ).sort()[1]

    if len(_UpperCamelCase  ) <= num_to_mask:
      break

    # mask heads
    _snake_case		=							current_heads_to_mask[:num_to_mask]
    logger.info('''Heads to mask: %s'''				, str(current_heads_to_mask.tolist()  )  )
    _snake_case		=							new_head_mask.view(-1  )
    _snake_case		=							0.0
    _snake_case		=							new_head_mask.view_as(_UpperCamelCase  )
    _snake_case		=							new_head_mask.clone().detach()
    print_ad_tensor(_UpperCamelCase  )

    # Compute metric and head importance again
    _snake_case,  _snake_case,  _snake_case,  _snake_case		=							compute_heads_importance(
        _UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase				, compute_entropy=_UpperCamelCase				, head_mask=_UpperCamelCase  )
    _snake_case		=							np.argmax(_UpperCamelCase				, axis=1  ) if args.output_mode == '''classification''' else np.squeeze(_UpperCamelCase  )
    _snake_case		=							glue_compute_metrics(args.task_name				, _UpperCamelCase				, _UpperCamelCase  )[args.metric_name]
    logger.info(
        '''Masking: current score: %f, remaining heads %d (%.1f percents)'''				, _UpperCamelCase				, new_head_mask.sum()				, new_head_mask.sum() / new_head_mask.numel() * 100				, )

  logger.info('''Final head mask'''  )
  print_ad_tensor(_UpperCamelCase  )
  np.save(os.path.join(args.output_dir				, '''head_mask.npy'''  )				, head_mask.detach().cpu().numpy()  )

  return head_mask



def    snake_case_(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase  )							->			Optional[Any]:



  """simple docstring"""






  _snake_case		=							datetime.now()
  _snake_case,  _snake_case,  _snake_case,  _snake_case		=							compute_heads_importance(
      _UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase				, compute_entropy=_UpperCamelCase				, compute_importance=_UpperCamelCase				, head_mask=_UpperCamelCase  )
  _snake_case		=							np.argmax(_UpperCamelCase				, axis=1  ) if args.output_mode == '''classification''' else np.squeeze(_UpperCamelCase  )
  _snake_case		=							glue_compute_metrics(args.task_name				, _UpperCamelCase				, _UpperCamelCase  )[args.metric_name]
  _snake_case		=							datetime.now() - before_time

  _snake_case		=							sum(p.numel() for p in model.parameters()  )
  _snake_case		=							{
      layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_UpperCamelCase  )  )
  }

  assert sum(len(_UpperCamelCase  ) for h in heads_to_prune.values()  ) == (1 - head_mask.long()).sum().item()
  model.prune_heads(_UpperCamelCase  )
  _snake_case		=							sum(p.numel() for p in model.parameters()  )

  _snake_case		=							datetime.now()
  _snake_case,  _snake_case,  _snake_case,  _snake_case		=							compute_heads_importance(
      _UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase				, compute_entropy=_UpperCamelCase				, compute_importance=_UpperCamelCase				, head_mask=_UpperCamelCase				, actually_pruned=_UpperCamelCase				, )
  _snake_case		=							np.argmax(_UpperCamelCase				, axis=1  ) if args.output_mode == '''classification''' else np.squeeze(_UpperCamelCase  )
  _snake_case		=							glue_compute_metrics(args.task_name				, _UpperCamelCase				, _UpperCamelCase  )[args.metric_name]
  _snake_case		=							datetime.now() - before_time

  logger.info(
      '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'''				, _UpperCamelCase				, _UpperCamelCase				, pruned_num_params / original_num_params * 100				, )
  logger.info('''Pruning: score with masking: %f score with pruning: %f'''				, _UpperCamelCase				, _UpperCamelCase  )
  logger.info('''Pruning: speed ratio (new timing / original timing): %f percents'''				, original_time / new_time * 100  )



def    snake_case_()							->			Any:



  """simple docstring"""






  _snake_case		=							argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '''--data_dir'''				, default=_UpperCamelCase				, type=_UpperCamelCase				, required=_UpperCamelCase				, help='''The input data dir. Should contain the .tsv files (or other data files) for the task.'''				, )
  parser.add_argument(
      '''--model_name_or_path'''				, default=_UpperCamelCase				, type=_UpperCamelCase				, required=_UpperCamelCase				, help='''Path to pretrained model or model identifier from huggingface.co/models'''				, )
  parser.add_argument(
      '''--task_name'''				, default=_UpperCamelCase				, type=_UpperCamelCase				, required=_UpperCamelCase				, help='''The name of the task to train selected in the list: ''' + ''', '''.join(glue_processors.keys()  )				, )
  parser.add_argument(
      '''--output_dir'''				, default=_UpperCamelCase				, type=_UpperCamelCase				, required=_UpperCamelCase				, help='''The output directory where the model predictions and checkpoints will be written.'''				, )

  # Other parameters
  parser.add_argument(
      '''--config_name'''				, default=''''''				, type=_UpperCamelCase				, help='''Pretrained config name or path if not the same as model_name_or_path'''				, )
  parser.add_argument(
      '''--tokenizer_name'''				, default=''''''				, type=_UpperCamelCase				, help='''Pretrained tokenizer name or path if not the same as model_name_or_path'''				, )
  parser.add_argument(
      '''--cache_dir'''				, default=_UpperCamelCase				, type=_UpperCamelCase				, help='''Where do you want to store the pre-trained models downloaded from huggingface.co'''				, )
  parser.add_argument(
      '''--data_subset'''				, type=_UpperCamelCase				, default=-1				, help='''If > 0: limit the data to a subset of data_subset instances.'''  )
  parser.add_argument(
      '''--overwrite_output_dir'''				, action='''store_true'''				, help='''Whether to overwrite data in output directory'''  )
  parser.add_argument(
      '''--overwrite_cache'''				, action='''store_true'''				, help='''Overwrite the cached training and evaluation sets'''  )

  parser.add_argument(
      '''--dont_normalize_importance_by_layer'''				, action='''store_true'''				, help='''Don\'t normalize importance score by layers'''  )
  parser.add_argument(
      '''--dont_normalize_global_importance'''				, action='''store_true'''				, help='''Don\'t normalize all importance scores between 0 and 1'''				, )

  parser.add_argument(
      '''--try_masking'''				, action='''store_true'''				, help='''Whether to try to mask head until a threshold of accuracy.'''  )
  parser.add_argument(
      '''--masking_threshold'''				, default=0.9				, type=_UpperCamelCase				, help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).'''				, )
  parser.add_argument(
      '''--masking_amount'''				, default=0.1				, type=_UpperCamelCase				, help='''Amount to heads to masking at each masking step.'''  )
  parser.add_argument('''--metric_name'''				, default='''acc'''				, type=_UpperCamelCase				, help='''Metric to use for head masking.'''  )

  parser.add_argument(
      '''--max_seq_length'''				, default=128				, type=_UpperCamelCase				, help=(
          '''The maximum total input sequence length after WordPiece tokenization. \n'''
          '''Sequences longer than this will be truncated, sequences shorter padded.'''
      )				, )
  parser.add_argument('''--batch_size'''				, default=1				, type=_UpperCamelCase				, help='''Batch size.'''  )

  parser.add_argument('''--seed'''				, type=_UpperCamelCase				, default=42  )
  parser.add_argument('''--local_rank'''				, type=_UpperCamelCase				, default=-1				, help='''local_rank for distributed training on gpus'''  )
  parser.add_argument('''--no_cuda'''				, action='''store_true'''				, help='''Whether not to use CUDA when available'''  )
  parser.add_argument('''--server_ip'''				, type=_UpperCamelCase				, default=''''''				, help='''Can be used for distant debugging.'''  )
  parser.add_argument('''--server_port'''				, type=_UpperCamelCase				, default=''''''				, help='''Can be used for distant debugging.'''  )
  _snake_case		=							parser.parse_args()

  if args.server_ip and args.server_port:
    # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
    import ptvsd

    print('''Waiting for debugger attach'''  )
    ptvsd.enable_attach(address=(args.server_ip, args.server_port)				, redirect_output=_UpperCamelCase  )
    ptvsd.wait_for_attach()

  # Setup devices and distributed training
  if args.local_rank == -1 or args.no_cuda:
    _snake_case		=							torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''  )
    _snake_case		=							0 if args.no_cuda else torch.cuda.device_count()
  else:
    torch.cuda.set_device(args.local_rank  )
    _snake_case		=							torch.device('''cuda'''				, args.local_rank  )
    _snake_case		=							1
    torch.distributed.init_process_group(backend='''nccl'''  )  # Initializes the distributed backend

  # Setup logging
  logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN  )
  logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device				, args.n_gpu				, bool(args.local_rank != -1  )  )  )
  # Set the verbosity to info of the Transformers logger (on main process only):
  if is_main_process(args.local_rank  ):
    transformers.utils.logging.set_verbosity_info()
    transformers.utils.logging.enable_default_handler()
    transformers.utils.logging.enable_explicit_format()

  # Set seeds
  set_seed(args.seed  )

  # Prepare GLUE task
  _snake_case		=							args.task_name.lower()
  if args.task_name not in glue_processors:
    raise ValueError('''Task not found: %s''' % (args.task_name)  )
  _snake_case		=							glue_processors[args.task_name]()
  _snake_case		=							glue_output_modes[args.task_name]
  _snake_case		=							processor.get_labels()
  _snake_case		=							len(_UpperCamelCase  )

  # Load pretrained model and tokenizer
  #
  # Distributed training:
  # The .from_pretrained methods guarantee that only one local process can concurrently
  # download model & vocab.

  _snake_case		=							AutoConfig.from_pretrained(
      args.config_name if args.config_name else args.model_name_or_path				, num_labels=_UpperCamelCase				, finetuning_task=args.task_name				, output_attentions=_UpperCamelCase				, cache_dir=args.cache_dir				, )
  _snake_case		=							AutoTokenizer.from_pretrained(
      args.tokenizer_name if args.tokenizer_name else args.model_name_or_path				, cache_dir=args.cache_dir				, )
  _snake_case		=							AutoModelForSequenceClassification.from_pretrained(
      args.model_name_or_path				, from_tf=bool('''.ckpt''' in args.model_name_or_path  )				, config=_UpperCamelCase				, cache_dir=args.cache_dir				, )

  # Distributed and parallel training
  model.to(args.device  )
  if args.local_rank != -1:
    _snake_case		=							nn.parallel.DistributedDataParallel(
        _UpperCamelCase				, device_ids=[args.local_rank]				, output_device=args.local_rank				, find_unused_parameters=_UpperCamelCase  )
  elif args.n_gpu > 1:
    _snake_case		=							nn.DataParallel(_UpperCamelCase  )

  # Print/save training arguments
  os.makedirs(args.output_dir				, exist_ok=_UpperCamelCase  )
  torch.save(_UpperCamelCase				, os.path.join(args.output_dir				, '''run_args.bin'''  )  )
  logger.info('''Training/evaluation parameters %s'''				, _UpperCamelCase  )

  # Prepare dataset for the GLUE task
  _snake_case		=							GlueDataset(_UpperCamelCase				, tokenizer=_UpperCamelCase				, mode='''dev'''  )
  if args.data_subset > 0:
    _snake_case		=							Subset(_UpperCamelCase				, list(range(min(args.data_subset				, len(_UpperCamelCase  )  )  )  )  )
  _snake_case		=							SequentialSampler(_UpperCamelCase  ) if args.local_rank == -1 else DistributedSampler(_UpperCamelCase  )
  _snake_case		=							DataLoader(
      _UpperCamelCase				, sampler=_UpperCamelCase				, batch_size=args.batch_size				, collate_fn=_UpperCamelCase  )

  # Compute head entropy and importance score
  compute_heads_importance(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase  )

  # Try head masking (set heads to zero until the score goes under a threshole)
  # and head pruning (remove masked heads and see the effect on the network)
  if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
    _snake_case		=							mask_heads(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase  )
    prune_heads(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase  )


if __name__ == "__main__":
 main()




import argparse

import torch
from clip import load

from transformers import CLIPConfig, CLIPModel



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			Optional[Any]:



  """simple docstring"""






  _snake_case,  _snake_case,  _snake_case		=							pt_attn_layer.in_proj_weight.chunk(3				, dim=0  )
  _snake_case,  _snake_case,  _snake_case		=							pt_attn_layer.in_proj_bias.chunk(3				, dim=0  )

  _snake_case		=							pt_attn_layer.out_proj.weight
  _snake_case		=							pt_attn_layer.out_proj.bias

  _snake_case		=							q_proj
  _snake_case		=							q_proj_bias

  _snake_case		=							k_proj
  _snake_case		=							k_proj_bias

  _snake_case		=							v_proj
  _snake_case		=							v_proj_bias

  _snake_case		=							out_proj_weights
  _snake_case		=							out_proj_bias



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			List[str]:



  """simple docstring"""






  copy_linear(hf_mlp.fca				, pt_mlp.c_fc  )
  copy_linear(hf_mlp.fca				, pt_mlp.c_proj  )



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			str:



  """simple docstring"""






  _snake_case		=							pt_linear.weight
  _snake_case		=							pt_linear.bias



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			Tuple:



  """simple docstring"""






  copy_linear(hf_layer.layer_norma				, pt_layer.ln_a  )
  copy_linear(hf_layer.layer_norma				, pt_layer.ln_a  )

  # copy MLP
  copy_mlp(hf_layer.mlp				, pt_layer.mlp  )

  # copy attn
  copy_attn_layer(hf_layer.self_attn				, pt_layer.attn  )



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			List[Any]:



  """simple docstring"""






  for hf_layer, pt_layer in zip(_UpperCamelCase				, _UpperCamelCase  ):
    copy_layer(_UpperCamelCase				, _UpperCamelCase  )



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			List[Any]:



  """simple docstring"""






  _snake_case		=							pt_model.token_embedding.weight
  _snake_case		=							pt_model.positional_embedding

  # copy layer norm
  copy_linear(hf_encoder.final_layer_norm				, pt_model.ln_final  )

  # copy hidden layers
  copy_layers(hf_encoder.encoder.layers				, pt_model.transformer.resblocks  )



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			Tuple:



  """simple docstring"""






  _snake_case		=							pt_model.text_projection.data.T

  # copy text encoder
  copy_encoder(hf_model.text_model				, _UpperCamelCase  )



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			int:



  """simple docstring"""






  _snake_case		=							pt_model.visual.proj.data.T

  # copy layer norms
  copy_linear(hf_model.vision_model.pre_layrnorm				, pt_model.visual.ln_pre  )
  copy_linear(hf_model.vision_model.post_layernorm				, pt_model.visual.ln_post  )

  # copy embeds
  _snake_case		=							pt_model.visual.conva.weight.data
  _snake_case		=							pt_model.visual.class_embedding
  _snake_case		=							pt_model.visual.positional_embedding.data

  # copy encoder
  copy_layers(hf_model.vision_model.encoder.layers				, pt_model.visual.transformer.resblocks  )



@torch.no_grad()
def    snake_case_(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase=None  )							->			Any:



  """simple docstring"""






  if config_path is not None:
    _snake_case		=							CLIPConfig.from_pretrained(_UpperCamelCase  )
  else:
    _snake_case		=							CLIPConfig(projection_dim=512				, text_config={}				, vision_config={}  )

  _snake_case		=							CLIPModel(_UpperCamelCase  ).eval()

  _snake_case,  _snake_case		=							load(_UpperCamelCase				, device='''cpu'''				, jit=_UpperCamelCase  )
  _snake_case		=							pt_model.eval()

  copy_text_model_and_projection(_UpperCamelCase				, _UpperCamelCase  )
  copy_vison_model_and_projection(_UpperCamelCase				, _UpperCamelCase  )
  _snake_case		=							pt_model.logit_scale

  _snake_case		=							torch.arange(0				, 77  ).unsqueeze(0  )
  _snake_case		=							torch.randn(1				, 3				, 224				, 224  )

  _snake_case		=							hf_model(input_ids=_UpperCamelCase				, pixel_values=_UpperCamelCase				, return_dict=_UpperCamelCase  )
  _snake_case		=							hf_outputs.logits_per_image
  _snake_case		=							hf_outputs.logits_per_text
  _snake_case,  _snake_case		=							pt_model(_UpperCamelCase				, _UpperCamelCase  )

  assert torch.allclose(_UpperCamelCase				, _UpperCamelCase				, atol=1E-3  )
  assert torch.allclose(_UpperCamelCase				, _UpperCamelCase				, atol=1E-3  )

  hf_model.save_pretrained(_UpperCamelCase  )


if __name__ == "__main__":
 __A    	=			argparse.ArgumentParser()
 parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
 parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
 parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
 __A    	=			parser.parse_args()

 convert_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)

