
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, RandomSampler, TensorDataset
from tqdm import tqdm

from transformers import GPTaLMHeadModel


UpperCamelCase_						=						logging.getLogger(__name__)





def 				_lowerCamelCase      (       lowerCamelCase_:	List[str]					,						lowerCamelCase_:	Union[str, Any]		):



				'''simple docstring'''







				if os.path.exists(UpperCamelCase_		):
								if os.path.exists(os.path.join(UpperCamelCase_					,						'''config.json'''		)		) and os.path.isfile(
								    os.path.join(UpperCamelCase_					,						'''config.json'''		)		):
												os.remove(os.path.join(UpperCamelCase_					,						'''config.json'''		)		)
								if os.path.exists(os.path.join(UpperCamelCase_					,						'''pytorch_model.bin'''		)		) and os.path.isfile(
								    os.path.join(UpperCamelCase_					,						'''pytorch_model.bin'''		)		):
												os.remove(os.path.join(UpperCamelCase_					,						'''pytorch_model.bin'''		)		)
				else:
								os.makedirs(UpperCamelCase_		)
				model.save_pretrained(UpperCamelCase_		)





def 				_lowerCamelCase      (       lowerCamelCase_:	Any					,						lowerCamelCase_:	Optional[Any]=False		):



				'''simple docstring'''







				A  :	Tuple				=					2
				if unlogit:
								A  :	Dict				=					torch.pow(UpperCamelCase_					,						UpperCamelCase_		)
				A  :	List[Any]				=					p * torch.log(UpperCamelCase_		)
				A  :	int				=					0
				return -plogp.sum(dim=-1		)





def 				_lowerCamelCase      (       lowerCamelCase_:	Optional[Any]		):



				'''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 				_lowerCamelCase      (       lowerCamelCase_:	int					,						lowerCamelCase_:	List[str]					,						lowerCamelCase_:	Dict					,						lowerCamelCase_:	Union[str, Any]=True					,						lowerCamelCase_:	str=True					,						lowerCamelCase_:	Tuple=None					,						lowerCamelCase_:	Optional[int]=False		):



				'''simple docstring'''







				A			,							A  :	List[str]				=					model.config.num_hidden_layers, model.config.num_attention_heads
				A  :	Any				=					torch.zeros(UpperCamelCase_					,						UpperCamelCase_		).to(args.device		)
				A  :	Dict				=					torch.zeros(UpperCamelCase_					,						UpperCamelCase_		).to(args.device		)

				if head_mask is None:
								A  :	Optional[int]				=					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:
								A  :	str				=					None

				A  :	Optional[int]				=					0.0
				A  :	int				=					0.0
				for step, inputs in enumerate(tqdm(UpperCamelCase_					,						desc='''Iteration'''					,						disable=args.local_rank not in [-1, 0]		)		):
								A  :	Tuple				=					tuple(t.to(args.device		) for t in inputs		)
								((A						)			,													)  :	str				=					inputs

								# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
								A  :	List[Any]				=					model(UpperCamelCase_					,						labels=UpperCamelCase_					,						head_mask=UpperCamelCase_		)
								#  (loss), lm_logits, presents, (all hidden_states), (attentions)
								A			,							A			,							A  :	int				=					(
								    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
								total_loss += loss.detach().cpu().numpy()
								if compute_entropy:
												for layer, attn in enumerate(UpperCamelCase_		):
																A  :	List[str]				=					entropy(attn.detach()					,						UpperCamelCase_		)
																attn_entropy[layer] += masked_entropy.sum(-1		).sum(0		).sum(0		).detach()

								if compute_importance:
												head_importance += head_mask.grad.abs().detach()
								tot_tokens += torch.ones_like(UpperCamelCase_		).float().detach().sum().data

				# Normalize
				attn_entropy /= tot_tokens
				head_importance /= tot_tokens
				# Layerwise importance normalization
				if not args.dont_normalize_importance_by_layer:
								A  :	Optional[Any]				=					2
								A  :	List[str]				=					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:
								A  :	str				=					(head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

				# Print matrices
				if compute_entropy:
								logger.info('''Attention entropies'''		)
								print_ad_tensor(UpperCamelCase_		)
				if compute_importance:
								logger.info('''Head importance scores'''		)
								print_ad_tensor(UpperCamelCase_		)
				logger.info('''Head ranked by importance scores'''		)
				A  :	Dict				=					torch.zeros(head_importance.numel()					,						dtype=torch.long					,						device=args.device		)
				A  :	int				=					torch.arange(
				    head_importance.numel()					,						device=args.device		)
				A  :	Union[str, Any]				=					head_ranks.view_as(UpperCamelCase_		)
				print_ad_tensor(UpperCamelCase_		)
				return attn_entropy, head_importance, total_loss





def 				_lowerCamelCase      (       lowerCamelCase_:	Any					,						lowerCamelCase_:	Optional[Any]					,						lowerCamelCase_:	List[Any]		):



				'''simple docstring'''







				A			,							A			,							A  :	str				=					compute_heads_importance(UpperCamelCase_					,						UpperCamelCase_					,						UpperCamelCase_					,						compute_entropy=UpperCamelCase_		)
				A  :	int				=					1 / loss  # instead of downsteam score use the LM loss
				logger.info('''Pruning: original score: %f, threshold: %f'''					,						UpperCamelCase_					,						original_score * args.masking_threshold		)

				A  :	Optional[Any]				=					torch.ones_like(UpperCamelCase_		)
				A  :	List[Any]				=					max(1					,						int(new_head_mask.numel() * args.masking_amount		)		)

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

								if len(UpperCamelCase_		) <= num_to_mask:
												print('''BREAK BY num_to_mask'''		)
												break

								# mask heads
								A  :	str				=					current_heads_to_mask[:num_to_mask]
								logger.info('''Heads to mask: %s'''					,						str(current_heads_to_mask.tolist()		)		)
								A  :	Optional[int]				=					new_head_mask.view(-1		)
								A  :	List[Any]				=					0.0
								A  :	Union[str, Any]				=					new_head_mask.view_as(UpperCamelCase_		)
								A  :	Optional[int]				=					new_head_mask.clone().detach()
								print_ad_tensor(UpperCamelCase_		)

								# Compute metric and head importance again
								A			,							A			,							A  :	str				=					compute_heads_importance(
								    UpperCamelCase_					,						UpperCamelCase_					,						UpperCamelCase_					,						compute_entropy=UpperCamelCase_					,						head_mask=UpperCamelCase_		)
								A  :	Optional[int]				=					1 / loss
								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 				_lowerCamelCase      (       lowerCamelCase_:	str					,						lowerCamelCase_:	List[str]					,						lowerCamelCase_:	Union[str, Any]					,						lowerCamelCase_:	List[str]		):



				'''simple docstring'''







				A  :	str				=					datetime.now()
				A			,							A			,							A  :	Tuple				=					compute_heads_importance(
				    UpperCamelCase_					,						UpperCamelCase_					,						UpperCamelCase_					,						compute_entropy=UpperCamelCase_					,						compute_importance=UpperCamelCase_					,						head_mask=UpperCamelCase_		)
				A  :	str				=					1 / loss
				A  :	Dict				=					datetime.now() - before_time

				A  :	int				=					sum(p.numel() for p in model.parameters()		)
				A  :	List[Any]				=					{
				    layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(UpperCamelCase_		)		)
				}

				for k, v in heads_to_prune.items():
								if isinstance(UpperCamelCase_					,						UpperCamelCase_		):
												A  :	Optional[Any]				=					[
												    v,
												]

				assert sum(len(UpperCamelCase_		) for h in heads_to_prune.values()		) == (1 - head_mask.long()).sum().item()
				model.prune_heads(UpperCamelCase_		)
				A  :	List[Any]				=					sum(p.numel() for p in model.parameters()		)

				A  :	List[str]				=					datetime.now()
				A			,							A			,							A  :	List[str]				=					compute_heads_importance(
				    UpperCamelCase_					,						UpperCamelCase_					,						UpperCamelCase_					,						compute_entropy=UpperCamelCase_					,						compute_importance=UpperCamelCase_					,						head_mask=UpperCamelCase_					,						actually_pruned=UpperCamelCase_					,						)

				A  :	Tuple				=					1 / loss
				A  :	Optional[int]				=					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 (original timing / new timing): %f percents'''					,						original_time / new_time * 100		)
				save_model(UpperCamelCase_					,						args.output_dir		)





def 				_lowerCamelCase      (       ):



				'''simple docstring'''







				A  :	Any				=					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(
				    '''--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 s3'''					,						)
				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.'''		)
				A  :	Dict				=					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:
								A  :	List[str]				=					torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''		)
								A  :	Dict				=					0 if args.no_cuda else torch.cuda.device_count()
				else:
								torch.cuda.set_device(args.local_rank		)
								A  :	str				=					torch.device('''cuda'''					,						args.local_rank		)
								A  :	int				=					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		)		)		)

				A  :	Dict				=					GPTaLMHeadModel.from_pretrained(args.model_name_or_path		)

				# Distributed and parallel training
				model.to(args.device		)
				if args.local_rank != -1:
								A  :	Any				=					nn.parallel.DistributedDataParallel(
								    UpperCamelCase_					,						device_ids=[args.local_rank]					,						output_device=args.local_rank					,						find_unused_parameters=UpperCamelCase_		)
				elif args.n_gpu > 1:
								A  :	List[str]				=					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
				A  :	List[str]				=					np.concatenate(
				    [
				        np.loadtxt(args.data_dir					,						dtype=np.intaa		),
				    ]		)
				A  :	List[Any]				=					(torch.from_numpy(UpperCamelCase_		),)
				A  :	str				=					TensorDataset(*UpperCamelCase_		)
				A  :	Tuple				=					RandomSampler(UpperCamelCase_		)
				A  :	Tuple				=					DataLoader(UpperCamelCase_					,						sampler=UpperCamelCase_					,						batch_size=args.batch_size		)

				# 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:
								A  :	Tuple				=					mask_heads(UpperCamelCase_					,						UpperCamelCase_					,						UpperCamelCase_		)
								prune_heads(UpperCamelCase_					,						UpperCamelCase_					,						UpperCamelCase_					,						UpperCamelCase_		)


if __name__ == "__main__":
					main()




from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
   from transformers import (
       TFBertModel,
       TFCLIPVisionModel,
       TFDeiTModel,
       TFRobertaModel,
       TFVisionTextDualEncoderModel,
       TFViTModel,
       VisionTextDualEncoderConfig,
   )

if is_vision_available():
   from PIL import Image

   from transformers import VisionTextDualEncoderProcessor



def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[Any]						)->	Dict:
    if isinstance(UpperCamelCase_			,							collections.abc.Iterable						):
        return x
    return (x, x)



@require_tf
class      _UpperCAmelCase      :




     def 		snake_case_		(					self			,    a__			,    a__):
         pass




     def 		snake_case_		(					self):
         pass




     def 		snake_case_		(					self):
         pass




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__					=       VisionTextDualEncoderConfig.from_vision_text_configs(a__			,    a__)

         A__					=       TFVisionTextDualEncoderModel(a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], model.config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], model.config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       {'''vision_model''': vision_model, '''text_model''': text_model}
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(**a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)

         self.assertEqual(output['''text_embeds'''].shape			,    (input_ids.shape[0], model.config.projection_dim))
         self.assertEqual(output['''image_embeds'''].shape			,    (pixel_values.shape[0], model.config.projection_dim))




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)
         A__					=       output[0].numpy()

         with tempfile.TemporaryDirectory() as tmpdirname:
             model.save_pretrained(a__)
             A__					=       TFVisionTextDualEncoderModel.from_pretrained(a__)

             A__					=       model(input_ids=a__			,    pixel_values=a__			,    attention_mask=a__)
             A__					=       after_output[0].numpy()
             A__					=       np.amax(np.abs(out_a - out_a))
             self.assertLessEqual(a__			,    1e-5)




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(
             input_ids=a__			,    pixel_values=a__			,    attention_mask=a__			,    output_attentions=a__)

         A__					=       output.vision_model_output.attentions
         self.assertEqual(len(a__)			,    vision_config.num_hidden_layers)

         # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
         A__					=       to_atuple(vision_model.config.image_size)
         A__					=       to_atuple(vision_model.config.patch_size)
         A__					=       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         A__					=       num_patches + 1
         self.assertEqual(vision_attentions[0].shape[-3:]			,    (vision_config.num_attention_heads, seq_len, seq_len))

         A__					=       output.text_model_output.attentions
         self.assertEqual(len(a__)			,    text_config.num_hidden_layers)

         self.assertEqual(
             text_attentions[0].shape[-3:]			,    (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,    )




     def 		snake_case_		(					self			,    a__			,    a__			,    a__):
         A__					=       np.abs((a - b)).max()
         self.assertLessEqual(a__			,    a__			,    F"Difference between torch and flax is {diff} (>= {tol}).")




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_dual_encoder_model(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_model_from_pretrained_configs(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_dual_encoder_from_pretrained(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_save_load(**a__)




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         self.check_vision_text_output_attention(**a__)




     @slow
     def 		snake_case_		(					self):
         A__			,						A__					=       self.get_pretrained_model_and_inputs()

         A__					=       model_a(**a__)
         A__					=       outputs[0].numpy()

         with tempfile.TemporaryDirectory() as tmp_dirname:
             model_a.save_pretrained(a__)
             A__					=       TFVisionTextDualEncoderModel.from_pretrained(a__)

             A__					=       model_a(**a__)
             A__					=       after_outputs[0].numpy()
             A__					=       np.amax(np.abs(out_a - out_a))
             self.assertLessEqual(a__			,    1e-5)







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''hf-internal-testing/tiny-random-vit'''			,    '''hf-internal-testing/tiny-random-bert''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFViTModel(a__			,    name='''vision_model''')
         A__					=       TFBertModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFViTModelTester(self)
         A__					=       TFBertModelTester(self)
         A__					=       vit_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
         # just reinitialize it.
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''Rocketknight1/tiny-random-deit-tf'''			,    '''hf-internal-testing/tiny-random-roberta''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__			,    a__			,    a__			,    a__=None			,    **a__):
         A__			,						A__					=       self.get_vision_text_model(a__			,    a__)
         A__					=       TFVisionTextDualEncoderModel(vision_model=a__			,    text_model=a__)

         A__					=       model(
             input_ids=a__			,    pixel_values=a__			,    attention_mask=a__			,    output_attentions=a__)

         A__					=       output.vision_model_output.attentions
         self.assertEqual(len(a__)			,    vision_config.num_hidden_layers)

         # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
         A__					=       to_atuple(vision_model.config.image_size)
         A__					=       to_atuple(vision_model.config.patch_size)
         A__					=       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         A__					=       num_patches + 2
         self.assertEqual(vision_attentions[0].shape[-3:]			,    (vision_config.num_attention_heads, seq_len, seq_len))

         A__					=       output.text_model_output.attentions
         self.assertEqual(len(a__)			,    text_config.num_hidden_layers)

         self.assertEqual(
             text_attentions[0].shape[-3:]			,    (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,    )




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFDeiTModel(a__			,    name='''vision_model''')
         A__					=       TFRobertaModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFDeiTModelTester(self)
         A__					=       TFRobertaModelTester(self)
         A__					=       vit_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_tf
class      _UpperCAmelCase      (							A__      ,   unittest.TestCase  ):




     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_vision_text_pretrained(
             '''Rocketknight1/tiny-random-clip-tf'''			,    '''hf-internal-testing/tiny-random-bert''')
         A__					=       1_3
         A__					=       floats_tensor(
             [
                 batch_size,
                 model.vision_model.config.num_channels,
                 model.vision_model.config.image_size,
                 model.vision_model.config.image_size,
             ])
         A__					=       ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size)
         A__					=       random_attention_mask([batch_size, 4])
         A__					=       {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

         return model, inputs




     def 		snake_case_		(					self			,    a__			,    a__):
         A__					=       TFCLIPVisionModel(a__			,    name='''vision_model''')
         A__					=       TFBertModel(a__			,    name='''text_model''')
         return vision_model, text_model




     def 		snake_case_		(					self):
         A__					=       TFCLIPVisionModelTester(self)
         A__					=       TFBertModelTester(self)
         A__					=       clip_model_tester.prepare_config_and_inputs()
         A__					=       bert_model_tester.prepare_config_and_inputs()

         A__			,						A__					=       vision_config_and_inputs

         (
             (
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						(
             A__
         )			,						
         )					=       text_config_and_inputs

         return {
             "text_config": text_config,
             "vision_config": vision_config,
             "pixel_values": pixel_values,
             "attention_mask": input_mask,
             "input_ids": input_ids,
             "text_token_type_ids": token_type_ids,
             "text_sequence_labels": sequence_labels,
             "text_token_labels": token_labels,
             "text_choice_labels": choice_labels,
         }







@require_vision
@require_tf
class      _UpperCAmelCase      (							unittest.TestCase  ):




     @slow
     def 		snake_case_		(					self):
         A__					=       TFVisionTextDualEncoderModel.from_pretrained(
             '''clip-italian/clip-italian'''			,    logit_scale_init_value=1.0			,    from_pt=a__)
         A__					=       VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''')

         A__					=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
         A__					=       processor(
             text=['''una foto di un gatto''', '''una foto di un cane''']			,    images=a__			,    padding=a__			,    return_tensors='''np''')

         A__					=       model(**a__)

         # verify the logits
         self.assertEqual(outputs.logits_per_image.shape			,    (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]))
         self.assertEqual(
             outputs.logits_per_text.shape			,    (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])			,    )

         A__					=       np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]])

         self.assertTrue(np.allclose(outputs.logits_per_image.numpy()			,    a__			,    atol=1e-3))
