"""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


lowerCAmelCase__						:						str		  =			logging.getLogger(__name__)



def 						a_		(      lowerCamelCase      ,    lowerCamelCase ):
				# save results
				if os.path.exists(lowerCamelCase ):
								if os.path.exists(os.path.join(lowerCamelCase      ,    'config.json' ) ) and os.path.isfile(
								    os.path.join(lowerCamelCase      ,    'config.json' ) ):
												os.remove(os.path.join(lowerCamelCase      ,    'config.json' ) )
								if os.path.exists(os.path.join(lowerCamelCase      ,    'pytorch_model.bin' ) ) and os.path.isfile(
								    os.path.join(lowerCamelCase      ,    'pytorch_model.bin' ) ):
												os.remove(os.path.join(lowerCamelCase      ,    'pytorch_model.bin' ) )
				else:
								os.makedirs(lowerCamelCase )
				model.save_pretrained(lowerCamelCase )



def 						a_		(      lowerCamelCase      ,    lowerCamelCase=False ):
				UpperCAmelCase__    =							2
				if unlogit:
								UpperCAmelCase__    =							torch.pow(lowerCamelCase      ,    lowerCamelCase )
				UpperCAmelCase__    =							p * torch.log(lowerCamelCase )
				UpperCAmelCase__    =							0
				return -plogp.sum(dim=-1 )



def 						a_		(      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 						a_		(      lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase=True      ,    lowerCamelCase=True      ,    lowerCamelCase=None      ,    lowerCamelCase=False ):
				UpperCAmelCase__   ,			UpperCAmelCase__    =							model.config.num_hidden_layers, model.config.num_attention_heads
				UpperCAmelCase__    =							torch.zeros(lowerCamelCase      ,    lowerCamelCase ).to(args.device )
				UpperCAmelCase__    =							torch.zeros(lowerCamelCase      ,    lowerCamelCase ).to(args.device )

				if head_mask is None:
								UpperCAmelCase__    =							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:
								UpperCAmelCase__    =							None

				UpperCAmelCase__    =							0.0
				UpperCAmelCase__    =							0.0
				for step, inputs in enumerate(tqdm(lowerCamelCase      ,    desc='Iteration'      ,    disable=args.local_rank not in [-1, 0] ) ):
								UpperCAmelCase__    =							tuple(t.to(args.device ) for t in inputs )
								((UpperCAmelCase__			)   ,						)    =							inputs

								# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
								UpperCAmelCase__    =							model(lowerCamelCase      ,    labels=lowerCamelCase      ,    head_mask=lowerCamelCase )
								#  (loss), lm_logits, presents, (all hidden_states), (attentions)
								UpperCAmelCase__   ,			UpperCAmelCase__   ,			UpperCAmelCase__    =							(
								    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(lowerCamelCase ):
																UpperCAmelCase__    =							entropy(attn.detach()      ,    lowerCamelCase )
																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(lowerCamelCase ).float().detach().sum().data

				# Normalize
				attn_entropy /= tot_tokens
				head_importance /= tot_tokens
				# Layerwise importance normalization
				if not args.dont_normalize_importance_by_layer:
								UpperCAmelCase__    =							2
								UpperCAmelCase__    =							torch.pow(torch.pow(lowerCamelCase      ,    lowerCamelCase ).sum(-1 )      ,    1 / exponent )
								head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-2_0

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

				# Print matrices
				if compute_entropy:
								logger.info('Attention entropies' )
								print_ad_tensor(lowerCamelCase )
				if compute_importance:
								logger.info('Head importance scores' )
								print_ad_tensor(lowerCamelCase )
				logger.info('Head ranked by importance scores' )
				UpperCAmelCase__    =							torch.zeros(head_importance.numel()      ,    dtype=torch.long      ,    device=args.device )
				UpperCAmelCase__    =							torch.arange(
				    head_importance.numel()      ,    device=args.device )
				UpperCAmelCase__    =							head_ranks.view_as(lowerCamelCase )
				print_ad_tensor(lowerCamelCase )
				return attn_entropy, head_importance, total_loss



def 						a_		(      lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase ):
				UpperCAmelCase__   ,			UpperCAmelCase__   ,			UpperCAmelCase__    =							compute_heads_importance(lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase      ,    compute_entropy=lowerCamelCase )
				UpperCAmelCase__    =							1 / loss  # instead of downsteam score use the LM loss
				logger.info('Pruning: original score: %f, threshold: %f'      ,    lowerCamelCase      ,    original_score * args.masking_threshold )

				UpperCAmelCase__    =							torch.ones_like(lowerCamelCase )
				UpperCAmelCase__    =							max(1      ,    int(new_head_mask.numel() * args.masking_amount ) )

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

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

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

								# Compute metric and head importance again
								UpperCAmelCase__   ,			UpperCAmelCase__   ,			UpperCAmelCase__    =							compute_heads_importance(
								    lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase      ,    compute_entropy=lowerCamelCase      ,    head_mask=lowerCamelCase )
								UpperCAmelCase__    =							1 / loss
								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_0_0      ,    )

				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 						a_		(      lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase ):
				UpperCAmelCase__    =							datetime.now()
				UpperCAmelCase__   ,			UpperCAmelCase__   ,			UpperCAmelCase__    =							compute_heads_importance(
				    lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase      ,    compute_entropy=lowerCamelCase      ,    compute_importance=lowerCamelCase      ,    head_mask=lowerCamelCase )
				UpperCAmelCase__    =							1 / loss
				UpperCAmelCase__    =							datetime.now() - before_time

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

				for k, v in heads_to_prune.items():
								if isinstance(lowerCamelCase      ,    lowerCamelCase ):
												UpperCAmelCase__    =							[
												    v,
												]

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

				UpperCAmelCase__    =							datetime.now()
				UpperCAmelCase__   ,			UpperCAmelCase__   ,			UpperCAmelCase__    =							compute_heads_importance(
				    lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase      ,    compute_entropy=lowerCamelCase      ,    compute_importance=lowerCamelCase      ,    head_mask=lowerCamelCase      ,    actually_pruned=lowerCamelCase      ,    )

				UpperCAmelCase__    =							1 / loss
				UpperCAmelCase__    =							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_0_0      ,    )
				logger.info('Pruning: score with masking: %f score with pruning: %f'      ,    lowerCamelCase      ,    lowerCamelCase )
				logger.info('Pruning: speed ratio (original timing / new timing): %f percents'      ,    original_time / new_time * 1_0_0 )
				save_model(lowerCamelCase      ,    args.output_dir )



def 						a_		(      ):
				UpperCAmelCase__    =							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(
				    '--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 s3'      ,    )
				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_2_8      ,    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=4_2 )
				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.' )
				UpperCAmelCase__    =							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:
								UpperCAmelCase__    =							torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' )
								UpperCAmelCase__    =							0 if args.no_cuda else torch.cuda.device_count()
				else:
								torch.cuda.set_device(args.local_rank )
								UpperCAmelCase__    =							torch.device('cuda'      ,    args.local_rank )
								UpperCAmelCase__    =							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 ) ) )

				UpperCAmelCase__    =							GPTaLMHeadModel.from_pretrained(args.model_name_or_path )

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

				# 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:
								UpperCAmelCase__    =							mask_heads(lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase )
								prune_heads(lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase      ,    lowerCamelCase )


if __name__ == "__main__":
						main()




"""simple docstring"""






import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
						from PIL import Image

						from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
						import torch

if is_tf_available():
						import tensorflow as tf
@require_vision
@require_torchvision
class        snake_case (				unittest.TestCase       ):




					"""simple docstring"""

					def 	__lowerCAmelCase		(       self     :			Optional[Any]    ):
									UpperCAmelCase__    =							tempfile.mkdtemp()
									UpperCAmelCase__    =							SamImageProcessor()
									UpperCAmelCase__    =							SamProcessor(lowerCamelCase__    )
									processor.save_pretrained(self.tmpdirname    )







					def 	__lowerCAmelCase		(       self     :			str					,**lowerCamelCase__     :			Dict    ):
									return AutoProcessor.from_pretrained(self.tmpdirname					,**lowerCamelCase__    ).image_processor







					def 	__lowerCAmelCase		(       self     :			Optional[int]    ):
									shutil.rmtree(self.tmpdirname    )







					def 	__lowerCAmelCase		(       self     :			Dict    ):
									UpperCAmelCase__    =							[np.random.randint(255					,size=(3, 30, 400)					,dtype=np.uinta    )]

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

									return image_inputs







					def 	__lowerCAmelCase		(       self     :			Optional[Any]    ):
									UpperCAmelCase__    =							SamProcessor(image_processor=self.get_image_processor()    )
									processor.save_pretrained(self.tmpdirname    )

									UpperCAmelCase__    =							self.get_image_processor(do_normalize=lowerCamelCase__					,padding_value=1.0    )

									UpperCAmelCase__    =							SamProcessor.from_pretrained(self.tmpdirname					,do_normalize=lowerCamelCase__					,padding_value=1.0    )

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







					def 	__lowerCAmelCase		(       self     :			Optional[int]    ):
									UpperCAmelCase__    =							self.get_image_processor()

									UpperCAmelCase__    =							SamProcessor(image_processor=lowerCamelCase__    )

									UpperCAmelCase__    =							self.prepare_image_inputs()

									UpperCAmelCase__    =							image_processor(lowerCamelCase__					,return_tensors='np'    )
									UpperCAmelCase__    =							processor(images=lowerCamelCase__					,return_tensors='np'    )

									input_feat_extract.pop('original_sizes'    )  # pop original_sizes as it is popped in the processor
									input_feat_extract.pop('reshaped_input_sizes'    )  # pop original_sizes as it is popped in the processor

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







					@require_torch
					def 	__lowerCAmelCase		(       self     :			Dict    ):
									UpperCAmelCase__    =							self.get_image_processor()

									UpperCAmelCase__    =							SamProcessor(image_processor=lowerCamelCase__    )
									UpperCAmelCase__    =							[torch.ones((1, 3, 5, 5)    )]

									UpperCAmelCase__    =							[[1_764, 2_646]]

									UpperCAmelCase__    =							[[683, 1_024]]
									UpperCAmelCase__    =							processor.post_process_masks(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__    )
									self.assertEqual(masks[0].shape					,(1, 3, 1_764, 2_646)    )

									UpperCAmelCase__    =							processor.post_process_masks(
									    lowerCamelCase__					,torch.tensor(lowerCamelCase__    )					,torch.tensor(lowerCamelCase__    )    )
									self.assertEqual(masks[0].shape					,(1, 3, 1_764, 2_646)    )

									# should also work with np
									UpperCAmelCase__    =							[np.ones((1, 3, 5, 5)    )]
									UpperCAmelCase__    =							processor.post_process_masks(lowerCamelCase__					,np.array(lowerCamelCase__    )					,np.array(lowerCamelCase__    )    )

									self.assertEqual(masks[0].shape					,(1, 3, 1_764, 2_646)    )

									UpperCAmelCase__    =							[[1, 0], [0, 1]]
									with self.assertRaises(lowerCamelCase__    ):
													UpperCAmelCase__    =							processor.post_process_masks(lowerCamelCase__					,np.array(lowerCamelCase__    )					,np.array(lowerCamelCase__    )    )






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




					"""simple docstring"""

					def 	__lowerCAmelCase		(       self     :			List[str]    ):
									UpperCAmelCase__    =							tempfile.mkdtemp()
									UpperCAmelCase__    =							SamImageProcessor()
									UpperCAmelCase__    =							SamProcessor(lowerCamelCase__    )
									processor.save_pretrained(self.tmpdirname    )







					def 	__lowerCAmelCase		(       self     :			str					,**lowerCamelCase__     :			Union[str, Any]    ):
									return AutoProcessor.from_pretrained(self.tmpdirname					,**lowerCamelCase__    ).image_processor







					def 	__lowerCAmelCase		(       self     :			List[Any]    ):
									shutil.rmtree(self.tmpdirname    )







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

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

									return image_inputs







					def 	__lowerCAmelCase		(       self     :			Optional[int]    ):
									UpperCAmelCase__    =							SamProcessor(image_processor=self.get_image_processor()    )
									processor.save_pretrained(self.tmpdirname    )

									UpperCAmelCase__    =							self.get_image_processor(do_normalize=lowerCamelCase__					,padding_value=1.0    )

									UpperCAmelCase__    =							SamProcessor.from_pretrained(self.tmpdirname					,do_normalize=lowerCamelCase__					,padding_value=1.0    )

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







					def 	__lowerCAmelCase		(       self     :			Union[str, Any]    ):
									UpperCAmelCase__    =							self.get_image_processor()

									UpperCAmelCase__    =							SamProcessor(image_processor=lowerCamelCase__    )

									UpperCAmelCase__    =							self.prepare_image_inputs()

									UpperCAmelCase__    =							image_processor(lowerCamelCase__					,return_tensors='np'    )
									UpperCAmelCase__    =							processor(images=lowerCamelCase__					,return_tensors='np'    )

									input_feat_extract.pop('original_sizes'    )  # pop original_sizes as it is popped in the processor
									input_feat_extract.pop('reshaped_input_sizes'    )  # pop reshaped_input_sizes as it is popped in the processor

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







					@require_tf
					def 	__lowerCAmelCase		(       self     :			Tuple    ):
									UpperCAmelCase__    =							self.get_image_processor()

									UpperCAmelCase__    =							SamProcessor(image_processor=lowerCamelCase__    )
									UpperCAmelCase__    =							[tf.ones((1, 3, 5, 5)    )]

									UpperCAmelCase__    =							[[1_764, 2_646]]

									UpperCAmelCase__    =							[[683, 1_024]]
									UpperCAmelCase__    =							processor.post_process_masks(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					,return_tensors='tf'    )
									self.assertEqual(masks[0].shape					,(1, 3, 1_764, 2_646)    )

									UpperCAmelCase__    =							processor.post_process_masks(
									    lowerCamelCase__					,tf.convert_to_tensor(lowerCamelCase__    )					,tf.convert_to_tensor(lowerCamelCase__    )					,return_tensors='tf'					,)
									self.assertEqual(masks[0].shape					,(1, 3, 1_764, 2_646)    )

									# should also work with np
									UpperCAmelCase__    =							[np.ones((1, 3, 5, 5)    )]
									UpperCAmelCase__    =							processor.post_process_masks(
									    lowerCamelCase__					,np.array(lowerCamelCase__    )					,np.array(lowerCamelCase__    )					,return_tensors='tf'    )

									self.assertEqual(masks[0].shape					,(1, 3, 1_764, 2_646)    )

									UpperCAmelCase__    =							[[1, 0], [0, 1]]
									with self.assertRaises(tf.errors.InvalidArgumentError    ):
													UpperCAmelCase__    =							processor.post_process_masks(
													    lowerCamelCase__					,np.array(lowerCamelCase__    )					,np.array(lowerCamelCase__    )					,return_tensors='tf'    )






@require_vision
@require_torchvision
class        snake_case (				unittest.TestCase       ):




					"""simple docstring"""

					def 	__lowerCAmelCase		(       self     :			Any    ):
									UpperCAmelCase__    =							tempfile.mkdtemp()
									UpperCAmelCase__    =							SamImageProcessor()
									UpperCAmelCase__    =							SamProcessor(lowerCamelCase__    )
									processor.save_pretrained(self.tmpdirname    )







					def 	__lowerCAmelCase		(       self     :			Dict					,**lowerCamelCase__     :			Any    ):
									return AutoProcessor.from_pretrained(self.tmpdirname					,**lowerCamelCase__    ).image_processor







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







					def 	__lowerCAmelCase		(       self     :			List[str]    ):
									UpperCAmelCase__    =							[np.random.randint(255					,size=(3, 30, 400)					,dtype=np.uinta    )]

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

									return image_inputs







					@is_pt_tf_cross_test
					def 	__lowerCAmelCase		(       self     :			List[Any]    ):
									UpperCAmelCase__    =							self.get_image_processor()

									UpperCAmelCase__    =							SamProcessor(image_processor=lowerCamelCase__    )
									UpperCAmelCase__    =							np.random.randint(0					,2					,size=(1, 3, 5, 5)    ).astype(np.floataa    )
									UpperCAmelCase__    =							[tf.convert_to_tensor(lowerCamelCase__    )]
									UpperCAmelCase__    =							[torch.tensor(lowerCamelCase__    )]

									UpperCAmelCase__    =							[[1_764, 2_646]]

									UpperCAmelCase__    =							[[683, 1_024]]
									UpperCAmelCase__    =							processor.post_process_masks(
									    lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					,return_tensors='tf'    )
									UpperCAmelCase__    =							processor.post_process_masks(
									    lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					,return_tensors='pt'    )

									self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()    )    )







					@is_pt_tf_cross_test
					def 	__lowerCAmelCase		(       self     :			Optional[Any]    ):
									UpperCAmelCase__    =							self.get_image_processor()

									UpperCAmelCase__    =							SamProcessor(image_processor=lowerCamelCase__    )

									UpperCAmelCase__    =							self.prepare_image_inputs()

									UpperCAmelCase__    =							image_processor(lowerCamelCase__					,return_tensors='pt'    )['pixel_values'].numpy()
									UpperCAmelCase__    =							processor(images=lowerCamelCase__					,return_tensors='pt'    )['pixel_values'].numpy()

									UpperCAmelCase__    =							image_processor(lowerCamelCase__					,return_tensors='tf'    )['pixel_values'].numpy()
									UpperCAmelCase__    =							processor(images=lowerCamelCase__					,return_tensors='tf'    )['pixel_values'].numpy()

									self.assertTrue(np.allclose(lowerCamelCase__					,lowerCamelCase__    )    )
									self.assertTrue(np.allclose(lowerCamelCase__					,lowerCamelCase__    )    )
									self.assertTrue(np.allclose(lowerCamelCase__					,lowerCamelCase__    )    )



