





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


_lowercase		:     Tuple 					=logging.getLogger(__name__)


def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__	):
		lowerCamelCase_  :    Union[str, Any]   	=			p * torch.log(lowerCAmelCase__	)
		lowerCamelCase_  :    List[str]   	=			0
		return -plogp.sum(dim=-1	)


def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__	):
		logger.info('lv, h >\t' + '\t'.join(F"{x + 1}" for x in range(len(lowerCAmelCase__	)	)	)	)
		for row in range(len(lowerCAmelCase__	)	):
				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    (   lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__=True       ,lowerCAmelCase__=True       ,lowerCAmelCase__=None       ,lowerCAmelCase__=False	):
		lowerCamelCase_  :    List[Any]   	=			model.config.num_hidden_layers, model.config.num_attention_heads
		lowerCamelCase_  :    str   	=			torch.zeros(lowerCAmelCase__       ,lowerCAmelCase__	).to(args.device	)
		lowerCamelCase_  :    List[Any]   	=			torch.zeros(lowerCAmelCase__       ,lowerCAmelCase__	).to(args.device	)

		if head_mask is None:
				lowerCamelCase_  :    Tuple   	=			torch.ones(lowerCAmelCase__       ,lowerCAmelCase__	).to(args.device	)

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

		lowerCamelCase_  :    str   	=			None
		lowerCamelCase_  :    Tuple   	=			None
		lowerCamelCase_  :    List[str]   	=			0.0

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

				# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
				lowerCamelCase_  :    Optional[int]   	=			model(**lowerCAmelCase__       ,head_mask=lowerCAmelCase__	)
				lowerCamelCase_  :    Optional[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

				if compute_entropy:
						for layer, attn in enumerate(lowerCAmelCase__	):
								lowerCamelCase_  :    Union[str, Any]   	=			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:
						lowerCamelCase_  :    int   	=			logits.detach().cpu().numpy()
						lowerCamelCase_  :    int   	=			inputs['labels'].detach().cpu().numpy()
				else:
						lowerCamelCase_  :    Tuple   	=			np.append(lowerCAmelCase__       ,logits.detach().cpu().numpy()       ,axis=0	)
						lowerCamelCase_  :    int   	=			np.append(lowerCAmelCase__       ,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:
				lowerCamelCase_  :    Tuple   	=			2
				lowerCamelCase_  :    Any   	=			torch.pow(torch.pow(lowerCAmelCase__       ,lowerCAmelCase__	).sum(-1	)       ,1 / exponent	)
				head_importance /= norm_by_layer.unsqueeze(-1	) + 1e-20

		if not args.dont_normalize_global_importance:
				lowerCamelCase_  :    List[Any]   	=			(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(lowerCAmelCase__	)
		logger.info('Head importance scores'	)
		print_ad_tensor(lowerCAmelCase__	)
		logger.info('Head ranked by importance scores'	)
		lowerCamelCase_  :    List[Any]   	=			torch.zeros(head_importance.numel()       ,dtype=torch.long       ,device=args.device	)
		lowerCamelCase_  :    List[Any]   	=			torch.arange(
		    head_importance.numel()       ,device=args.device	)
		lowerCamelCase_  :    Union[str, Any]   	=			head_ranks.view_as(lowerCAmelCase__	)
		print_ad_tensor(lowerCAmelCase__	)

		return attn_entropy, head_importance, preds, labels


def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__	):
		lowerCamelCase_  :    Optional[Any]   	=			compute_heads_importance(lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__       ,compute_entropy=lowerCAmelCase__	)
		lowerCamelCase_  :    Optional[int]   	=			np.argmax(lowerCAmelCase__       ,axis=1	) if args.output_mode == 'classification' else np.squeeze(lowerCAmelCase__	)
		lowerCamelCase_  :    Optional[Any]   	=			glue_compute_metrics(args.task_name       ,lowerCAmelCase__       ,lowerCAmelCase__	)[args.metric_name]
		logger.info('Pruning: original score: %f, threshold: %f'       ,lowerCAmelCase__       ,original_score * args.masking_threshold	)

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

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

				if len(lowerCAmelCase__	) <= num_to_mask:
						break

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

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

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

		return head_mask


def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__	):
		lowerCamelCase_  :    List[Any]   	=			datetime.now()
		lowerCamelCase_  :    str   	=			compute_heads_importance(
		    lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__       ,compute_entropy=lowerCAmelCase__       ,compute_importance=lowerCAmelCase__       ,head_mask=lowerCAmelCase__	)
		lowerCamelCase_  :    str   	=			np.argmax(lowerCAmelCase__       ,axis=1	) if args.output_mode == 'classification' else np.squeeze(lowerCAmelCase__	)
		lowerCamelCase_  :    Union[str, Any]   	=			glue_compute_metrics(args.task_name       ,lowerCAmelCase__       ,lowerCAmelCase__	)[args.metric_name]
		lowerCamelCase_  :    Optional[Any]   	=			datetime.now() - before_time

		lowerCamelCase_  :    Tuple   	=			sum(p.numel() for p in model.parameters()	)
		lowerCamelCase_  :    Optional[int]   	=			{
		    layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCAmelCase__	)	)
		}

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

		lowerCamelCase_  :    Optional[int]   	=			datetime.now()
		lowerCamelCase_  :    List[Any]   	=			compute_heads_importance(
		    lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__       ,compute_entropy=lowerCAmelCase__       ,compute_importance=lowerCAmelCase__       ,head_mask=lowerCAmelCase__       ,actually_pruned=lowerCAmelCase__       ,)
		lowerCamelCase_  :    str   	=			np.argmax(lowerCAmelCase__       ,axis=1	) if args.output_mode == 'classification' else np.squeeze(lowerCAmelCase__	)
		lowerCamelCase_  :    Optional[Any]   	=			glue_compute_metrics(args.task_name       ,lowerCAmelCase__       ,lowerCAmelCase__	)[args.metric_name]
		lowerCamelCase_  :    int   	=			datetime.now() - before_time

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


def 		_SCREAMING_SNAKE_CASE    (   ):
		lowerCamelCase_  :    Union[str, Any]   	=			argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '--data_dir'       ,default=lowerCAmelCase__       ,type=lowerCAmelCase__       ,required=lowerCAmelCase__       ,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=lowerCAmelCase__       ,type=lowerCAmelCase__       ,required=lowerCAmelCase__       ,help='Path to pretrained model or model identifier from huggingface.co/models'       ,)
		parser.add_argument(
		    '--task_name'       ,default=lowerCAmelCase__       ,type=lowerCAmelCase__       ,required=lowerCAmelCase__       ,help='The name of the task to train selected in the list: ' + ', '.join(glue_processors.keys()	)       ,)
		parser.add_argument(
		    '--output_dir'       ,default=lowerCAmelCase__       ,type=lowerCAmelCase__       ,required=lowerCAmelCase__       ,help='The output directory where the model predictions and checkpoints will be written.'       ,)

		# Other parameters
		parser.add_argument(
		    '--config_name'       ,default=''       ,type=lowerCAmelCase__       ,help='Pretrained config name or path if not the same as model_name_or_path'       ,)
		parser.add_argument(
		    '--tokenizer_name'       ,default=''       ,type=lowerCAmelCase__       ,help='Pretrained tokenizer name or path if not the same as model_name_or_path'       ,)
		parser.add_argument(
		    '--cache_dir'       ,default=lowerCAmelCase__       ,type=lowerCAmelCase__       ,help='Where do you want to store the pre-trained models downloaded from huggingface.co'       ,)
		parser.add_argument(
		    '--data_subset'       ,type=lowerCAmelCase__       ,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=lowerCAmelCase__       ,help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).'       ,)
		parser.add_argument(
		    '--masking_amount'       ,default=0.1       ,type=lowerCAmelCase__       ,help='Amount to heads to masking at each masking step.'	)
		parser.add_argument('--metric_name'       ,default='acc'       ,type=lowerCAmelCase__       ,help='Metric to use for head masking.'	)

		parser.add_argument(
		    '--max_seq_length'       ,default=1_28       ,type=lowerCAmelCase__       ,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=lowerCAmelCase__       ,help='Batch size.'	)

		parser.add_argument('--seed'       ,type=lowerCAmelCase__       ,default=42	)
		parser.add_argument('--local_rank'       ,type=lowerCAmelCase__       ,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=lowerCAmelCase__       ,default=''       ,help='Can be used for distant debugging.'	)
		parser.add_argument('--server_port'       ,type=lowerCAmelCase__       ,default=''       ,help='Can be used for distant debugging.'	)
		lowerCamelCase_  :    Union[str, Any]   	=			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=lowerCAmelCase__	)
				ptvsd.wait_for_attach()

		# Setup devices and distributed training
		if args.local_rank == -1 or args.no_cuda:
				lowerCamelCase_  :    List[Any]   	=			torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu'	)
				lowerCamelCase_  :    str   	=			0 if args.no_cuda else torch.cuda.device_count()
		else:
				torch.cuda.set_device(args.local_rank	)
				lowerCamelCase_  :    int   	=			torch.device('cuda'       ,args.local_rank	)
				lowerCamelCase_  :    List[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	)	)	)
		# 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
		lowerCamelCase_  :    Union[str, Any]   	=			args.task_name.lower()
		if args.task_name not in glue_processors:
				raise ValueError('Task not found: %s' % (args.task_name)	)
		lowerCamelCase_  :    List[Any]   	=			glue_processors[args.task_name]()
		lowerCamelCase_  :    Tuple   	=			glue_output_modes[args.task_name]
		lowerCamelCase_  :    List[Any]   	=			processor.get_labels()
		lowerCamelCase_  :    List[str]   	=			len(lowerCAmelCase__	)

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

		lowerCamelCase_  :    Dict   	=			AutoConfig.from_pretrained(
		    args.config_name if args.config_name else args.model_name_or_path       ,num_labels=lowerCAmelCase__       ,finetuning_task=args.task_name       ,output_attentions=lowerCAmelCase__       ,cache_dir=args.cache_dir       ,)
		lowerCamelCase_  :    Any   	=			AutoTokenizer.from_pretrained(
		    args.tokenizer_name if args.tokenizer_name else args.model_name_or_path       ,cache_dir=args.cache_dir       ,)
		lowerCamelCase_  :    Any   	=			AutoModelForSequenceClassification.from_pretrained(
		    args.model_name_or_path       ,from_tf=bool('.ckpt' in args.model_name_or_path	)       ,config=lowerCAmelCase__       ,cache_dir=args.cache_dir       ,)

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

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

		# Prepare dataset for the GLUE task
		lowerCamelCase_  :    Tuple   	=			GlueDataset(lowerCAmelCase__       ,tokenizer=lowerCAmelCase__       ,mode='dev'	)
		if args.data_subset > 0:
				lowerCamelCase_  :    str   	=			Subset(lowerCAmelCase__       ,list(range(min(args.data_subset       ,len(lowerCAmelCase__	)	)	)	)	)
		lowerCamelCase_  :    Any   	=			SequentialSampler(lowerCAmelCase__	) if args.local_rank == -1 else DistributedSampler(lowerCAmelCase__	)
		lowerCamelCase_  :    Optional[Any]   	=			DataLoader(
		    lowerCAmelCase__       ,sampler=lowerCAmelCase__       ,batch_size=args.batch_size       ,collate_fn=lowerCAmelCase__	)

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

		# 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_  :    Dict   	=			mask_heads(lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__	)
				prune_heads(lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__       ,lowerCAmelCase__	)


if __name__ == "__main__":
		main()







import unittest

import requests

from transformers import MODEL_FOR_VISION_2_SEQ_MAPPING, TF_MODEL_FOR_VISION_2_SEQ_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
		from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
		_lowercase		:     Dict 					=False


if is_vision_available():
		from PIL import Image
else:






		class 	UpperCamelCase_     :



							@staticmethod
							def      __a    (		*lowerCamelCase    :    Any					,			**lowerCamelCase    :    List[Any]	):
									pass






@is_pipeline_test
@require_vision
class 	UpperCamelCase_     (     unittest.TestCase       ):
					_a			:	int							=				MODEL_FOR_VISION_2_SEQ_MAPPING
					_a			:	int							=				TF_MODEL_FOR_VISION_2_SEQ_MAPPING



					def      __a    (		self    :    int					,			lowerCamelCase    :    Union[str, Any]					,			lowerCamelCase    :    Optional[int]					,			lowerCamelCase    :    Union[str, Any]	):
							lowerCamelCase_  :    List[str]   	=			pipeline('image-to-text'					,			model=lowerCamelCase					,			tokenizer=lowerCamelCase					,			image_processor=lowerCamelCase	)
							lowerCamelCase_  :    str   	=			[
							    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	),
							    './tests/fixtures/tests_samples/COCO/000000039769.png',
							]
							return pipe, examples



					def      __a    (		self    :    List[Any]					,			lowerCamelCase    :    Any					,			lowerCamelCase    :    List[str]	):
							lowerCamelCase_  :    str   	=			pipe(lowerCamelCase	)
							self.assertEqual(
							    lowerCamelCase					,			[
							        [{'generated_text': ANY(lowerCamelCase	)}],
							        [{'generated_text': ANY(lowerCamelCase	)}],
							    ]					,			)



					@require_tf
					def      __a    (		self    :    Union[str, Any]	):
							lowerCamelCase_  :    Tuple   	=			pipeline('image-to-text'					,			model='hf-internal-testing/tiny-random-vit-gpt2'					,			framework='tf'	)
							lowerCamelCase_  :    Optional[int]   	=			'./tests/fixtures/tests_samples/COCO/000000039769.png'

							lowerCamelCase_  :    Optional[int]   	=			pipe(lowerCamelCase	)
							self.assertEqual(
							    lowerCamelCase					,			[
							        {
							            'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
							        },
							    ]					,			)

							lowerCamelCase_  :    List[Any]   	=			pipe([image, image]	)
							self.assertEqual(
							    lowerCamelCase					,			[
							        [
							            {
							                'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
							            }
							        ],
							        [
							            {
							                'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
							            }
							        ],
							    ]					,			)

							lowerCamelCase_  :    str   	=			pipe(lowerCamelCase					,			max_new_tokens=1	)
							self.assertEqual(
							    lowerCamelCase					,			[{'generated_text': 'growth'}]					,			)



					@require_torch
					def      __a    (		self    :    Tuple	):
							lowerCamelCase_  :    Union[str, Any]   	=			pipeline('image-to-text'					,			model='hf-internal-testing/tiny-random-vit-gpt2'	)
							lowerCamelCase_  :    Any   	=			'./tests/fixtures/tests_samples/COCO/000000039769.png'

							lowerCamelCase_  :    int   	=			pipe(lowerCamelCase	)
							self.assertEqual(
							    lowerCamelCase					,			[
							        {
							            'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
							        },
							    ]					,			)

							lowerCamelCase_  :    Tuple   	=			pipe([image, image]	)
							self.assertEqual(
							    lowerCamelCase					,			[
							        [
							            {
							                'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
							            }
							        ],
							        [
							            {
							                'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
							            }
							        ],
							    ]					,			)



					@require_torch
					def      __a    (		self    :    Dict	):
							lowerCamelCase_  :    Any   	=			pipeline('image-to-text'					,			model='hf-internal-testing/tiny-random-BlipForConditionalGeneration'	)
							lowerCamelCase_  :    List[Any]   	=			'./tests/fixtures/tests_samples/COCO/000000039769.png'
							lowerCamelCase_  :    List[Any]   	=			'a photo of'

							lowerCamelCase_  :    Dict   	=			pipe(lowerCamelCase					,			prompt=lowerCamelCase	)
							self.assertTrue(outputs[0]['generated_text'].startswith(lowerCamelCase	)	)



					@slow
					@require_torch
					def      __a    (		self    :    Union[str, Any]	):
							lowerCamelCase_  :    List[str]   	=			pipeline('image-to-text'					,			model='ydshieh/vit-gpt2-coco-en'	)
							lowerCamelCase_  :    Any   	=			'./tests/fixtures/tests_samples/COCO/000000039769.png'

							lowerCamelCase_  :    str   	=			pipe(lowerCamelCase	)
							self.assertEqual(lowerCamelCase					,			[{'generated_text': 'a cat laying on a blanket next to a cat laying on a bed '}]	)

							lowerCamelCase_  :    Union[str, Any]   	=			pipe([image, image]	)
							self.assertEqual(
							    lowerCamelCase					,			[
							        [{'generated_text': 'a cat laying on a blanket next to a cat laying on a bed '}],
							        [{'generated_text': 'a cat laying on a blanket next to a cat laying on a bed '}],
							    ]					,			)



					@slow
					@require_torch
					def      __a    (		self    :    List[Any]	):
							lowerCamelCase_  :    int   	=			pipeline('image-to-text'					,			model='Salesforce/blip-image-captioning-base'	)
							lowerCamelCase_  :    Tuple   	=			'https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png'
							lowerCamelCase_  :    List[Any]   	=			Image.open(requests.get(lowerCamelCase					,			stream=lowerCamelCase	).raw	)

							lowerCamelCase_  :    Optional[Any]   	=			pipe(lowerCamelCase	)
							self.assertEqual(lowerCamelCase					,			[{'generated_text': 'a pink pokemon pokemon with a blue shirt and a blue shirt'}]	)



					@slow
					@require_torch
					def      __a    (		self    :    List[str]	):
							lowerCamelCase_  :    Optional[Any]   	=			pipeline('image-to-text'					,			model='microsoft/git-base-coco'	)
							lowerCamelCase_  :    str   	=			'https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png'
							lowerCamelCase_  :    Dict   	=			Image.open(requests.get(lowerCamelCase					,			stream=lowerCamelCase	).raw	)

							lowerCamelCase_  :    Optional[int]   	=			pipe(lowerCamelCase	)
							self.assertEqual(lowerCamelCase					,			[{'generated_text': 'a cartoon of a purple character.'}]	)



					@slow
					@require_torch
					def      __a    (		self    :    List[str]	):
							lowerCamelCase_  :    List[Any]   	=			pipeline('image-to-text'					,			model='Salesforce/blip-image-captioning-base'	)
							lowerCamelCase_  :    int   	=			'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'
							lowerCamelCase_  :    List[str]   	=			Image.open(requests.get(lowerCamelCase					,			stream=lowerCamelCase	).raw	)

							lowerCamelCase_  :    int   	=			'a photography of'

							lowerCamelCase_  :    Tuple   	=			pipe(lowerCamelCase					,			prompt=lowerCamelCase	)
							self.assertEqual(lowerCamelCase					,			[{'generated_text': 'a photography of a volcano'}]	)

							with self.assertRaises(lowerCamelCase	):
									lowerCamelCase_  :    Union[str, Any]   	=			pipe([image, image]					,			prompt=[prompt, prompt]	)



					@slow
					@require_torch
					def      __a    (		self    :    int	):
							lowerCamelCase_  :    Optional[int]   	=			pipeline('image-to-text'					,			model='microsoft/git-base-coco'	)
							lowerCamelCase_  :    int   	=			'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'
							lowerCamelCase_  :    Optional[Any]   	=			Image.open(requests.get(lowerCamelCase					,			stream=lowerCamelCase	).raw	)

							lowerCamelCase_  :    Optional[int]   	=			'a photo of a'

							lowerCamelCase_  :    Optional[int]   	=			pipe(lowerCamelCase					,			prompt=lowerCamelCase	)
							self.assertEqual(lowerCamelCase					,			[{'generated_text': 'a photo of a tent with a tent and a tent in the background.'}]	)

							with self.assertRaises(lowerCamelCase	):
									lowerCamelCase_  :    List[Any]   	=			pipe([image, image]					,			prompt=[prompt, prompt]	)



					@unittest.skipIf(
					    not is_torch_greater_or_equal_than_1_11					,			reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'	)
					@slow
					@require_torch
					def      __a    (		self    :    Any	):
							lowerCamelCase_  :    Union[str, Any]   	=			pipeline('image-to-text'					,			model='google/pix2struct-ai2d-base'	)
							lowerCamelCase_  :    List[str]   	=			'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'
							lowerCamelCase_  :    Tuple   	=			Image.open(requests.get(lowerCamelCase					,			stream=lowerCamelCase	).raw	)

							lowerCamelCase_  :    str   	=			'What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud'

							lowerCamelCase_  :    Union[str, Any]   	=			pipe(lowerCamelCase					,			prompt=lowerCamelCase	)
							self.assertEqual(lowerCamelCase					,			[{'generated_text': 'ash cloud'}]	)

							with self.assertRaises(lowerCamelCase	):
									lowerCamelCase_  :    Optional[Any]   	=			pipe([image, image]					,			prompt=[prompt, prompt]	)





					@slow
					@require_tf
					def      __a    (		self    :    Dict	):
							lowerCamelCase_  :    List[str]   	=			pipeline('image-to-text'					,			model='ydshieh/vit-gpt2-coco-en'					,			framework='tf'	)
							lowerCamelCase_  :    Dict   	=			'./tests/fixtures/tests_samples/COCO/000000039769.png'

							lowerCamelCase_  :    Optional[Any]   	=			pipe(lowerCamelCase	)
							self.assertEqual(lowerCamelCase					,			[{'generated_text': 'a cat laying on a blanket next to a cat laying on a bed '}]	)

							lowerCamelCase_  :    List[Any]   	=			pipe([image, image]	)
							self.assertEqual(
							    lowerCamelCase					,			[
							        [{'generated_text': 'a cat laying on a blanket next to a cat laying on a bed '}],
							        [{'generated_text': 'a cat laying on a blanket next to a cat laying on a bed '}],
							    ]					,			)
