






'''simple docstring'''







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


_A	:			Optional[int]         =logging.getLogger(__name__)





def  SCREAMING_SNAKE_CASE_       (UpperCamelCase				,			UpperCamelCase      )      ->       Dict:
							# save results
							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  SCREAMING_SNAKE_CASE_       (UpperCamelCase				,			UpperCamelCase=False      )      ->       Union[str, Any]:
							lowerCamelCase__					:	Any         =       2
							if unlogit:
														lowerCamelCase__					:	List[str]         =       torch.pow(UpperCamelCase				,			UpperCamelCase      )
							lowerCamelCase__					:	List[str]         =       p * torch.log(UpperCamelCase      )
							lowerCamelCase__					:	Any         =       0
							return -plogp.sum(dim=-1      )





def  SCREAMING_SNAKE_CASE_       (UpperCamelCase      )      ->       Any:
							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  SCREAMING_SNAKE_CASE_       (UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase=True				,			UpperCamelCase=True				,			UpperCamelCase=None				,			UpperCamelCase=False      )      ->       Union[str, Any]:
							lowerCamelCase__  ,		lowerCamelCase__					:	Any         =       model.config.num_hidden_layers, model.config.num_attention_heads
							lowerCamelCase__					:	List[Any]         =       torch.zeros(UpperCamelCase				,			UpperCamelCase      ).to(args.device      )
							lowerCamelCase__					:	Optional[Any]         =       torch.zeros(UpperCamelCase				,			UpperCamelCase      ).to(args.device      )

							if head_mask is None:
														lowerCamelCase__					:	List[Any]         =       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:
														lowerCamelCase__					:	int         =       None

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

														# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
														lowerCamelCase__					:	Tuple         =       model(UpperCamelCase				,			labels=UpperCamelCase				,			head_mask=UpperCamelCase      )
														#  (loss), lm_logits, presents, (all hidden_states), (attentions)
														lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	List[str]         =       (
														    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      ):
																												lowerCamelCase__					:	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:
														lowerCamelCase__					:	List[str]         =       2
														lowerCamelCase__					:	Optional[int]         =       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:
														lowerCamelCase__					:	Any         =       (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"""      )
							lowerCamelCase__					:	Dict         =       torch.zeros(head_importance.numel()				,			dtype=torch.long				,			device=args.device      )
							lowerCamelCase__					:	Dict         =       torch.arange(
							    head_importance.numel()				,			device=args.device      )
							lowerCamelCase__					:	Union[str, Any]         =       head_ranks.view_as(UpperCamelCase      )
							print_ad_tensor(UpperCamelCase      )
							return attn_entropy, head_importance, total_loss





def  SCREAMING_SNAKE_CASE_       (UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase      )      ->       List[Any]:
							lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	List[Any]         =       compute_heads_importance(UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase				,			compute_entropy=UpperCamelCase      )
							lowerCamelCase__					:	str         =       1 / loss  # instead of downsteam score use the LM loss
							logger.info("""Pruning: original score: %f, threshold: %f"""				,			UpperCamelCase				,			original_score * args.masking_threshold      )

							lowerCamelCase__					:	Tuple         =       torch.ones_like(UpperCamelCase      )
							lowerCamelCase__					:	Dict         =       max(1				,			int(new_head_mask.numel() * args.masking_amount      )      )

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

														if len(UpperCamelCase      ) <= num_to_mask:
																					print("""BREAK BY num_to_mask"""      )
																					break

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

														# Compute metric and head importance again
														lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	int         =       compute_heads_importance(
														    UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase				,			compute_entropy=UpperCamelCase				,			head_mask=UpperCamelCase      )
														lowerCamelCase__					:	Tuple         =       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  SCREAMING_SNAKE_CASE_       (UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase      )      ->       Any:
							lowerCamelCase__					:	Any         =       datetime.now()
							lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	Optional[int]         =       compute_heads_importance(
							    UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase				,			compute_entropy=UpperCamelCase				,			compute_importance=UpperCamelCase				,			head_mask=UpperCamelCase      )
							lowerCamelCase__					:	List[str]         =       1 / loss
							lowerCamelCase__					:	List[Any]         =       datetime.now() - before_time

							lowerCamelCase__					:	Dict         =       sum(p.numel() for p in model.parameters()      )
							lowerCamelCase__					:	Tuple         =       {
							    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      ):
																					lowerCamelCase__					:	Union[str, Any]         =       [
																					    v,
																					]

							assert sum(len(UpperCamelCase      ) for h in heads_to_prune.values()      ) == (1 - head_mask.long()).sum().item()
							model.prune_heads(UpperCamelCase      )
							lowerCamelCase__					:	Union[str, Any]         =       sum(p.numel() for p in model.parameters()      )

							lowerCamelCase__					:	List[Any]         =       datetime.now()
							lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	Optional[int]         =       compute_heads_importance(
							    UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase				,			compute_entropy=UpperCamelCase				,			compute_importance=UpperCamelCase				,			head_mask=UpperCamelCase				,			actually_pruned=UpperCamelCase				,			)

							lowerCamelCase__					:	List[Any]         =       1 / loss
							lowerCamelCase__					:	List[Any]         =       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  SCREAMING_SNAKE_CASE_       ()      ->       Union[str, Any]:
							lowerCamelCase__					:	str         =       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."""      )
							lowerCamelCase__					:	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:
														lowerCamelCase__					:	int         =       torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""      )
														lowerCamelCase__					:	int         =       0 if args.no_cuda else torch.cuda.device_count()
							else:
														torch.cuda.set_device(args.local_rank      )
														lowerCamelCase__					:	Optional[int]         =       torch.device("""cuda"""				,			args.local_rank      )
														lowerCamelCase__					:	Optional[Any]         =       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      )      )      )

							lowerCamelCase__					:	int         =       GPTaLMHeadModel.from_pretrained(args.model_name_or_path      )

							# Distributed and parallel training
							model.to(args.device      )
							if args.local_rank != -1:
														lowerCamelCase__					:	Any         =       nn.parallel.DistributedDataParallel(
														    UpperCamelCase				,			device_ids=[args.local_rank]				,			output_device=args.local_rank				,			find_unused_parameters=UpperCamelCase      )
							elif args.n_gpu > 1:
														lowerCamelCase__					:	Dict         =       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
							lowerCamelCase__					:	Union[str, Any]         =       np.concatenate(
							    [
							        np.loadtxt(args.data_dir				,			dtype=np.intaa      ),
							    ]      )
							lowerCamelCase__					:	Optional[Any]         =       (torch.from_numpy(UpperCamelCase      ),)
							lowerCamelCase__					:	str         =       TensorDataset(*UpperCamelCase      )
							lowerCamelCase__					:	Tuple         =       RandomSampler(UpperCamelCase      )
							lowerCamelCase__					:	Optional[int]         =       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:
														lowerCamelCase__					:	Optional[Any]         =       mask_heads(UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase      )
														prune_heads(UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase				,			UpperCamelCase      )


if __name__ == "__main__":
			main()









'''simple docstring'''







import json
import os
import shutil
import tempfile
import unittest

import numpy as np

from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
			from PIL import Image

			from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor

@require_tokenizers
@require_vision
class _lowercase	(				unittest.TestCase		):




							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	int         =       tempfile.mkdtemp()

														# fmt: off
														lowerCamelCase__					:	int         =       ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest"""]
														# fmt: on
														lowerCamelCase__					:	Union[str, Any]         =       os.path.join(self.tmpdirname			,							VOCAB_FILES_NAMES["""vocab_file"""]     )
														with open(self.vocab_file			,							"""w"""			,							encoding="""utf-8"""     ) as vocab_writer:
																					vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]     )     )

														lowerCamelCase__					:	Tuple         =       {
														    """do_resize""": True,
														    """size""": {"""height""": 18, """width""": 18},
														    """do_normalize""": True,
														    """image_mean""": [0.5, 0.5, 0.5],
														    """image_std""": [0.5, 0.5, 0.5],
														}
														lowerCamelCase__					:	Tuple         =       os.path.join(self.tmpdirname			,							UpperCamelCase__     )
														with open(self.image_processor_file			,							"""w"""			,							encoding="""utf-8"""     ) as fp:
																					json.dump(UpperCamelCase__			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				str			,							**UpperCamelCase__:				List[str]     ):
														return BertTokenizer.from_pretrained(self.tmpdirname			,							**UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				int			,							**UpperCamelCase__:				Tuple     ):
														return ViTImageProcessor.from_pretrained(self.tmpdirname			,							**UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Optional[Any]     ):
														shutil.rmtree(self.tmpdirname     )




							def 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__					:	List[Any]         =       [np.random.randint(255			,							size=(3, 30, 400)			,							dtype=np.uinta     )]

														lowerCamelCase__					:	Tuple         =       [Image.fromarray(np.moveaxis(UpperCamelCase__			,							0			,							-1     )     ) for x in image_inputs]

														return image_inputs




							def 		lowerCamelCase_				(							self:				int     ):
														lowerCamelCase__					:	Optional[Any]         =       self.get_tokenizer()
														lowerCamelCase__					:	Dict         =       self.get_image_processor()

														lowerCamelCase__					:	Optional[Any]         =       VisionTextDualEncoderProcessor(tokenizer=UpperCamelCase__			,							image_processor=UpperCamelCase__     )

														processor.save_pretrained(self.tmpdirname     )
														lowerCamelCase__					:	int         =       VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname     )

														self.assertEqual(processor.tokenizer.get_vocab()			,							tokenizer.get_vocab()     )
														self.assertIsInstance(processor.tokenizer			,							(BertTokenizer, BertTokenizerFast)     )

														self.assertEqual(processor.image_processor.to_json_string()			,							image_processor.to_json_string()     )
														self.assertIsInstance(processor.image_processor			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Tuple     ):
														lowerCamelCase__					:	Dict         =       VisionTextDualEncoderProcessor(
														    tokenizer=self.get_tokenizer()			,							image_processor=self.get_image_processor()     )
														processor.save_pretrained(self.tmpdirname     )

														lowerCamelCase__					:	int         =       self.get_tokenizer(bos_token="""(BOS)"""			,							eos_token="""(EOS)"""     )
														lowerCamelCase__					:	List[Any]         =       self.get_image_processor(do_normalize=UpperCamelCase__			,							padding_value=1.0     )

														lowerCamelCase__					:	Tuple         =       VisionTextDualEncoderProcessor.from_pretrained(
														    self.tmpdirname			,							bos_token="""(BOS)"""			,							eos_token="""(EOS)"""			,							do_normalize=UpperCamelCase__			,							padding_value=1.0     )

														self.assertEqual(processor.tokenizer.get_vocab()			,							tokenizer_add_kwargs.get_vocab()     )
														self.assertIsInstance(processor.tokenizer			,							(BertTokenizer, BertTokenizerFast)     )

														self.assertEqual(processor.image_processor.to_json_string()			,							image_processor_add_kwargs.to_json_string()     )
														self.assertIsInstance(processor.image_processor			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														lowerCamelCase__					:	Optional[Any]         =       self.get_image_processor()
														lowerCamelCase__					:	Union[str, Any]         =       self.get_tokenizer()

														lowerCamelCase__					:	Any         =       VisionTextDualEncoderProcessor(tokenizer=UpperCamelCase__			,							image_processor=UpperCamelCase__     )

														lowerCamelCase__					:	List[Any]         =       self.prepare_image_inputs()

														lowerCamelCase__					:	List[str]         =       image_processor(UpperCamelCase__			,							return_tensors="""np"""     )
														lowerCamelCase__					:	Optional[Any]         =       processor(images=UpperCamelCase__			,							return_tensors="""np"""     )

														for key in input_feat_extract.keys():
																					self.assertAlmostEqual(input_feat_extract[key].sum()			,							input_processor[key].sum()			,							delta=1e-2     )




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__					:	Any         =       self.get_image_processor()
														lowerCamelCase__					:	List[str]         =       self.get_tokenizer()

														lowerCamelCase__					:	List[Any]         =       VisionTextDualEncoderProcessor(tokenizer=UpperCamelCase__			,							image_processor=UpperCamelCase__     )

														lowerCamelCase__					:	List[Any]         =       """lower newer"""

														lowerCamelCase__					:	Union[str, Any]         =       processor(text=UpperCamelCase__     )

														lowerCamelCase__					:	Any         =       tokenizer(UpperCamelCase__     )

														for key in encoded_tok.keys():
																					self.assertListEqual(encoded_tok[key]			,							encoded_processor[key]     )




							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	Optional[Any]         =       self.get_image_processor()
														lowerCamelCase__					:	List[Any]         =       self.get_tokenizer()

														lowerCamelCase__					:	List[Any]         =       VisionTextDualEncoderProcessor(tokenizer=UpperCamelCase__			,							image_processor=UpperCamelCase__     )

														lowerCamelCase__					:	Any         =       """lower newer"""
														lowerCamelCase__					:	Dict         =       self.prepare_image_inputs()

														lowerCamelCase__					:	Tuple         =       processor(text=UpperCamelCase__			,							images=UpperCamelCase__     )

														self.assertListEqual(list(inputs.keys()     )			,							["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""]     )

														# test if it raises when no input is passed
														with self.assertRaises(UpperCamelCase__     ):
																					processor()




							def 		lowerCamelCase_				(							self:				int     ):
														lowerCamelCase__					:	List[str]         =       self.get_image_processor()
														lowerCamelCase__					:	List[str]         =       self.get_tokenizer()

														lowerCamelCase__					:	int         =       VisionTextDualEncoderProcessor(tokenizer=UpperCamelCase__			,							image_processor=UpperCamelCase__     )

														lowerCamelCase__					:	Dict         =       [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

														lowerCamelCase__					:	Union[str, Any]         =       processor.batch_decode(UpperCamelCase__     )
														lowerCamelCase__					:	Dict         =       tokenizer.batch_decode(UpperCamelCase__     )

														self.assertListEqual(UpperCamelCase__			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				List[str]     ):
														lowerCamelCase__					:	Any         =       self.get_image_processor()
														lowerCamelCase__					:	Union[str, Any]         =       self.get_tokenizer()

														lowerCamelCase__					:	int         =       VisionTextDualEncoderProcessor(tokenizer=UpperCamelCase__			,							image_processor=UpperCamelCase__     )

														lowerCamelCase__					:	Optional[Any]         =       """lower newer"""
														lowerCamelCase__					:	str         =       self.prepare_image_inputs()

														lowerCamelCase__					:	int         =       processor(text=UpperCamelCase__			,							images=UpperCamelCase__     )

														self.assertListEqual(list(inputs.keys()     )			,							processor.model_input_names     )

