



import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPanoramaPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




@skip_mps
class 					snake_case__						(       lowerCAmelCase_				,     lowerCAmelCase_				,     unittest.TestCase     ):






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	StableDiffusionPanoramaPipeline
     _SCREAMING_SNAKE_CASE						=	TEXT_TO_IMAGE_PARAMS
     _SCREAMING_SNAKE_CASE						=	TEXT_TO_IMAGE_BATCH_PARAMS
     _SCREAMING_SNAKE_CASE						=	TEXT_TO_IMAGE_IMAGE_PARAMS
     _SCREAMING_SNAKE_CASE						=	TEXT_TO_IMAGE_IMAGE_PARAMS






     def    lowercase_   (       self  :  Union[str, Any]					)   ->Any:
            torch.manual_seed(0					)
            snake_case__							:	Optional[int]   	=	UNetaDConditionModel(
                block_out_channels=(3_2, 6_4), layers_per_block=1, sample_size=3_2, in_channels=4, out_channels=4, down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D'), up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D'), cross_attention_dim=3_2, )
            snake_case__							:	Any   	=	DDIMScheduler()
            torch.manual_seed(0					)
            snake_case__							:	str   	=	AutoencoderKL(
                block_out_channels=[3_2, 6_4], in_channels=3, out_channels=3, down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'], up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'], latent_channels=4, )
            torch.manual_seed(0					)
            snake_case__							:	Optional[int]   	=	CLIPTextConfig(
                bos_token_id=0, eos_token_id=2, hidden_size=3_2, intermediate_size=3_7, layer_norm_eps=1e-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1_0_0_0, )
            snake_case__							:	int   	=	CLIPTextModel(_snake_case					)
            snake_case__							:	Tuple   	=	CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'					)

            snake_case__							:	str   	=	{
                'unet': unet,
                'scheduler': scheduler,
                'vae': vae,
                'text_encoder': text_encoder,
                'tokenizer': tokenizer,
                'safety_checker': None,
                'feature_extractor': None,
            }
            return components






     def    lowercase_   (       self  :  Optional[Any], _snake_case  :  List[Any], _snake_case  :  Tuple=0					)   ->Union[str, Any]:
            snake_case__							:	str   	=	torch.manual_seed(_snake_case					)
            snake_case__							:	Optional[Any]   	=	{
                'prompt': 'a photo of the dolomites',
                'generator': generator,
                # Setting height and width to None to prevent OOMs on CPU.
                'height': None,
                'width': None,
                'num_inference_steps': 1,
                'guidance_scale': 6.0,
                'output_type': 'numpy',
            }
            return inputs






     def    lowercase_   (       self  :  Optional[Any]					)   ->str:
            snake_case__							:	Union[str, Any]   	=	'cpu'  # ensure determinism for the device-dependent torch.Generator
            snake_case__							:	List[Any]   	=	self.get_dummy_components()
            snake_case__							:	str   	=	StableDiffusionPanoramaPipeline(**_snake_case					)
            snake_case__							:	Optional[int]   	=	sd_pipe.to(_snake_case					)
            sd_pipe.set_progress_bar_config(disable=_snake_case					)

            snake_case__							:	Union[str, Any]   	=	self.get_dummy_inputs(_snake_case					)
            snake_case__							:	List[Any]   	=	sd_pipe(**_snake_case					).images
            snake_case__							:	int   	=	image[0, -3:, -3:, -1]
            assert image.shape == (1, 6_4, 6_4, 3)

            snake_case__							:	Union[str, Any]   	=	np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7]					)

            assert np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2






     def    lowercase_   (       self  :  Tuple					)   ->Any:
            super().test_inference_batch_consistent(batch_sizes=[1, 2]					)






     def    lowercase_   (       self  :  Optional[Any]					)   ->Any:
            super().test_inference_batch_single_identical(batch_size=2, expected_max_diff=3.25e-3					)






     def    lowercase_   (       self  :  str					)   ->List[str]:
            snake_case__							:	str   	=	'cpu'  # ensure determinism for the device-dependent torch.Generator
            snake_case__							:	Optional[int]   	=	self.get_dummy_components()
            snake_case__							:	Optional[int]   	=	StableDiffusionPanoramaPipeline(**_snake_case					)
            snake_case__							:	List[Any]   	=	sd_pipe.to(_snake_case					)
            sd_pipe.set_progress_bar_config(disable=_snake_case					)

            snake_case__							:	Optional[int]   	=	self.get_dummy_inputs(_snake_case					)
            snake_case__							:	str   	=	'french fries'
            snake_case__							:	int   	=	sd_pipe(**_snake_case, negative_prompt=_snake_case					)
            snake_case__							:	str   	=	output.images
            snake_case__							:	Union[str, Any]   	=	image[0, -3:, -3:, -1]

            assert image.shape == (1, 6_4, 6_4, 3)

            snake_case__							:	str   	=	np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7]					)

            assert np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2






     def    lowercase_   (       self  :  Optional[Any]					)   ->Optional[Any]:
            snake_case__							:	int   	=	'cpu'  # ensure determinism for the device-dependent torch.Generator
            snake_case__							:	Optional[int]   	=	self.get_dummy_components()
            snake_case__							:	int   	=	StableDiffusionPanoramaPipeline(**_snake_case					)
            snake_case__							:	int   	=	sd_pipe.to(_snake_case					)
            sd_pipe.set_progress_bar_config(disable=_snake_case					)

            snake_case__							:	List[Any]   	=	self.get_dummy_inputs(_snake_case					)
            snake_case__							:	str   	=	sd_pipe(**_snake_case, view_batch_size=2					)
            snake_case__							:	int   	=	output.images
            snake_case__							:	Optional[Any]   	=	image[0, -3:, -3:, -1]

            assert image.shape == (1, 6_4, 6_4, 3)

            snake_case__							:	int   	=	np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7]					)

            assert np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2






     def    lowercase_   (       self  :  Dict					)   ->Any:
            snake_case__							:	List[str]   	=	'cpu'  # ensure determinism for the device-dependent torch.Generator
            snake_case__							:	Any   	=	self.get_dummy_components()
            snake_case__							:	str   	=	EulerAncestralDiscreteScheduler(
                beta_start=0.0_0_0_8_5, beta_end=0.0_1_2, beta_schedule='scaled_linear'					)
            snake_case__							:	List[str]   	=	StableDiffusionPanoramaPipeline(**_snake_case					)
            snake_case__							:	int   	=	sd_pipe.to(_snake_case					)
            sd_pipe.set_progress_bar_config(disable=_snake_case					)

            snake_case__							:	Dict   	=	self.get_dummy_inputs(_snake_case					)
            snake_case__							:	List[Any]   	=	sd_pipe(**_snake_case					).images
            snake_case__							:	int   	=	image[0, -3:, -3:, -1]

            assert image.shape == (1, 6_4, 6_4, 3)

            snake_case__							:	str   	=	np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2]					)

            assert np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2






     def    lowercase_   (       self  :  Union[str, Any]					)   ->Any:
            snake_case__							:	Optional[int]   	=	'cpu'  # ensure determinism for the device-dependent torch.Generator
            snake_case__							:	Union[str, Any]   	=	self.get_dummy_components()
            snake_case__							:	int   	=	PNDMScheduler(
                beta_start=0.0_0_0_8_5, beta_end=0.0_1_2, beta_schedule='scaled_linear', skip_prk_steps=_snake_case					)
            snake_case__							:	Tuple   	=	StableDiffusionPanoramaPipeline(**_snake_case					)
            snake_case__							:	Any   	=	sd_pipe.to(_snake_case					)
            sd_pipe.set_progress_bar_config(disable=_snake_case					)

            snake_case__							:	str   	=	self.get_dummy_inputs(_snake_case					)
            snake_case__							:	Dict   	=	sd_pipe(**_snake_case					).images
            snake_case__							:	Dict   	=	image[0, -3:, -3:, -1]

            assert image.shape == (1, 6_4, 6_4, 3)

            snake_case__							:	List[str]   	=	np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9]					)

            assert np.abs(image_slice.flatten() - expected_slice					).max() < 1e-2




@slow
@require_torch_gpu
class 					snake_case__						(       unittest.TestCase     ):






     """simple docstring"""


     def    lowercase_   (       self  :  Dict					)   ->List[Any]:
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()






     def    lowercase_   (       self  :  Optional[Any], _snake_case  :  Any=0					)   ->Any:
            snake_case__							:	List[Any]   	=	torch.manual_seed(_snake_case					)
            snake_case__							:	Tuple   	=	{
                'prompt': 'a photo of the dolomites',
                'generator': generator,
                'num_inference_steps': 3,
                'guidance_scale': 7.5,
                'output_type': 'numpy',
            }
            return inputs






     def    lowercase_   (       self  :  Any					)   ->Optional[Any]:
            snake_case__							:	Any   	=	'stabilityai/stable-diffusion-2-base'
            snake_case__							:	int   	=	DDIMScheduler.from_pretrained(_snake_case, subfolder='scheduler'					)
            snake_case__							:	Optional[int]   	=	StableDiffusionPanoramaPipeline.from_pretrained(_snake_case, scheduler=_snake_case, safety_checker=_snake_case					)
            pipe.to(_snake_case					)
            pipe.set_progress_bar_config(disable=_snake_case					)
            pipe.enable_attention_slicing()

            snake_case__							:	Optional[Any]   	=	self.get_inputs()
            snake_case__							:	List[Any]   	=	pipe(**_snake_case					).images
            snake_case__							:	str   	=	image[0, -3:, -3:, -1].flatten()

            assert image.shape == (1, 5_1_2, 2_0_4_8, 3)

            snake_case__							:	Tuple   	=	np.array(
                [
                    0.3_6_9_6_8_3_9_2,
                    0.2_7_0_2_5_3_7_2,
                    0.3_2_4_4_6_7_6_6,
                    0.2_8_3_7_9_3_8_7,
                    0.3_6_3_6_3_2_7_4,
                    0.3_0_7_3_3_3_4_7,
                    0.2_7_1_0_0_0_2_7,
                    0.2_7_0_5_4_1_2_5,
                    0.2_5_5_3_6_0_9_6,
                ]					)

            assert np.abs(expected_slice - image_slice					).max() < 1e-2






     def    lowercase_   (       self  :  Optional[Any]					)   ->str:
            snake_case__							:	Tuple   	=	StableDiffusionPanoramaPipeline.from_pretrained(
                'stabilityai/stable-diffusion-2-base', safety_checker=_snake_case					)
            snake_case__							:	Dict   	=	LMSDiscreteScheduler.from_config(pipe.scheduler.config					)
            pipe.to(_snake_case					)
            pipe.set_progress_bar_config(disable=_snake_case					)
            pipe.enable_attention_slicing()

            snake_case__							:	Any   	=	self.get_inputs()
            snake_case__							:	str   	=	pipe(**_snake_case					).images
            snake_case__							:	str   	=	image[0, -3:, -3:, -1].flatten()

            assert image.shape == (1, 5_1_2, 2_0_4_8, 3)

            snake_case__							:	Optional[int]   	=	np.array(
                [
                    [
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                    ]
                ]					)

            assert np.abs(expected_slice - image_slice					).max() < 1e-3






     def    lowercase_   (       self  :  int					)   ->Any:
            snake_case__							:	str   	=	0

            def callback_fn(_snake_case  :  int, _snake_case  :  int, _snake_case  :  torch.FloatTensor					) -> None:
                   snake_case__							:	List[Any]   	=	True
                   nonlocal number_of_steps
                   number_of_steps += 1
                   if step == 1:
                          snake_case__							:	Optional[Any]   	=	latents.detach().cpu().numpy()
                          assert latents.shape == (1, 4, 6_4, 2_5_6)
                          snake_case__							:	Tuple   	=	latents[0, -3:, -3:, -1]

                          snake_case__							:	int   	=	np.array(
                              [
                                  0.1_8_6_8_1_8_6_9,
                                  0.3_3_9_0_7_8_1_6,
                                  0.5_3_6_1_2_7_6,
                                  0.1_4_4_3_2_8_6_5,
                                  -0.0_2_8_5_6_6_1_1,
                                  -0.7_3_9_4_1_1_2_3,
                                  0.2_3_3_9_7_9_8_7,
                                  0.4_7_3_2_2_6_8_2,
                                  -0.3_7_8_2_3_1_6_4,
                              ]					)
                          assert np.abs(latents_slice.flatten() - expected_slice					).max() < 5e-2
                   elif step == 2:
                          snake_case__							:	str   	=	latents.detach().cpu().numpy()
                          assert latents.shape == (1, 4, 6_4, 2_5_6)
                          snake_case__							:	Optional[Any]   	=	latents[0, -3:, -3:, -1]

                          snake_case__							:	Any   	=	np.array(
                              [
                                  0.1_8_5_3_9_6_4_5,
                                  0.3_3_9_8_7_2_4_8,
                                  0.5_3_7_8_5_5_9,
                                  0.1_4_4_3_7_1_4_2,
                                  -0.0_2_4_5_5_2_6_1,
                                  -0.7_3_3_8_3_1_7,
                                  0.2_3_9_9_0_7_5_5,
                                  0.4_7_3_5_6_2_7_2,
                                  -0.3_7_8_6_5_0_5,
                              ]					)

                          assert np.abs(latents_slice.flatten() - expected_slice					).max() < 5e-2

            snake_case__							:	List[str]   	=	False

            snake_case__							:	Optional[Any]   	=	'stabilityai/stable-diffusion-2-base'
            snake_case__							:	Optional[Any]   	=	DDIMScheduler.from_pretrained(_snake_case, subfolder='scheduler'					)
            snake_case__							:	str   	=	StableDiffusionPanoramaPipeline.from_pretrained(_snake_case, scheduler=_snake_case, safety_checker=_snake_case					)
            snake_case__							:	Optional[Any]   	=	pipe.to(_snake_case					)
            pipe.set_progress_bar_config(disable=_snake_case					)
            pipe.enable_attention_slicing()

            snake_case__							:	List[str]   	=	self.get_inputs()
            pipe(**_snake_case, callback=_snake_case, callback_steps=1					)
            assert callback_fn.has_been_called
            assert number_of_steps == 3






     def    lowercase_   (       self  :  Optional[Any]					)   ->Optional[int]:
            torch.cuda.empty_cache()
            torch.cuda.reset_max_memory_allocated()
            torch.cuda.reset_peak_memory_stats()

            snake_case__							:	Any   	=	'stabilityai/stable-diffusion-2-base'
            snake_case__							:	Any   	=	DDIMScheduler.from_pretrained(_snake_case, subfolder='scheduler'					)
            snake_case__							:	Optional[int]   	=	StableDiffusionPanoramaPipeline.from_pretrained(_snake_case, scheduler=_snake_case, safety_checker=_snake_case					)
            snake_case__							:	Optional[Any]   	=	pipe.to(_snake_case					)
            pipe.set_progress_bar_config(disable=_snake_case					)
            pipe.enable_attention_slicing(1					)
            pipe.enable_sequential_cpu_offload()

            snake_case__							:	List[Any]   	=	self.get_inputs()
            snake_case__							:	Union[str, Any]   	=	pipe(**_snake_case					)

            snake_case__							:	Optional[int]   	=	torch.cuda.max_memory_allocated()
            # make sure that less than 5.2 GB is allocated
            assert mem_bytes < 5.5 * 1_0**9











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[Any]        =      logging.getLogger(__name__)
def        lowercase_							(A : List[Any]		,					A : List[Any]      ):
       # save results
       if os.path.exists(A      ):
              if os.path.exists(os.path.join(A		,					'config.json'      )      ) and os.path.isfile(
                  os.path.join(A		,					'config.json'      )      ):
                     os.remove(os.path.join(A		,					'config.json'      )      )
              if os.path.exists(os.path.join(A		,					'pytorch_model.bin'      )      ) and os.path.isfile(
                  os.path.join(A		,					'pytorch_model.bin'      )      ):
                     os.remove(os.path.join(A		,					'pytorch_model.bin'      )      )
       else:
              os.makedirs(A      )
       model.save_pretrained(A      )
def        lowercase_							(A : Any		,					A : Optional[Any]=False      ):
       snake_case__							:	str   	=	2
       if unlogit:
              snake_case__							:	Dict   	=	torch.pow(A		,					A      )
       snake_case__							:	Any   	=	p * torch.log(A      )
       snake_case__							:	Tuple   	=	0
       return -plogp.sum(dim=-1      )
def        lowercase_							(A : List[str]      ):
       logger.info('lv, h >\t' + '\t'.join(F'''{x + 1}''' for x in range(len(A      )      )      )      )
       for row in range(len(A      )      ):
              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        lowercase_							(A : Tuple		,					A : Optional[Any]		,					A : str		,					A : int=True		,					A : Optional[int]=True		,					A : Any=None		,					A : int=False      ):
       snake_case__	,				snake_case__							:	Optional[Any]   	=	model.config.num_hidden_layers, model.config.num_attention_heads
       snake_case__							:	int   	=	torch.zeros(A		,					A      ).to(args.device      )
       snake_case__							:	Any   	=	torch.zeros(A		,					A      ).to(args.device      )

       if head_mask is None:
              snake_case__							:	Dict   	=	torch.ones(A		,					A      ).to(args.device      )

       head_mask.requires_grad_(requires_grad=A      )
       # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
       if actually_pruned:
              snake_case__							:	Optional[int]   	=	None

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

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

       # Normalize
       attn_entropy /= tot_tokens
       head_importance /= tot_tokens
       # Layerwise importance normalization
       if not args.dont_normalize_importance_by_layer:
              snake_case__							:	Union[str, Any]   	=	2
              snake_case__							:	List[Any]   	=	torch.pow(torch.pow(A		,					A      ).sum(-1      )		,					1 / exponent      )
              head_importance /= norm_by_layer.unsqueeze(-1      ) + 1e-20

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

       # Print matrices
       if compute_entropy:
              logger.info('Attention entropies'      )
              print_ad_tensor(A      )
       if compute_importance:
              logger.info('Head importance scores'      )
              print_ad_tensor(A      )
       logger.info('Head ranked by importance scores'      )
       snake_case__							:	Tuple   	=	torch.zeros(head_importance.numel()		,					dtype=torch.long		,					device=args.device      )
       snake_case__							:	Union[str, Any]   	=	torch.arange(
           head_importance.numel()		,					device=args.device      )
       snake_case__							:	str   	=	head_ranks.view_as(A      )
       print_ad_tensor(A      )
       return attn_entropy, head_importance, total_loss
def        lowercase_							(A : Optional[int]		,					A : Dict		,					A : Optional[int]      ):
       snake_case__	,				snake_case__	,				snake_case__							:	Any   	=	compute_heads_importance(A		,					A		,					A		,					compute_entropy=A      )
       snake_case__							:	Tuple   	=	1 / loss  # instead of downsteam score use the LM loss
       logger.info('Pruning: original score: %f, threshold: %f'		,					A		,					original_score * args.masking_threshold      )

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

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

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

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

              # Compute metric and head importance again
              snake_case__	,				snake_case__	,				snake_case__							:	Any   	=	compute_heads_importance(
                  A		,					A		,					A		,					compute_entropy=A		,					head_mask=A      )
              snake_case__							:	Dict   	=	1 / loss
              logger.info(
                  'Masking: current score: %f, remaining heads %d (%.1f percents)'		,					A		,					new_head_mask.sum()		,					new_head_mask.sum() / new_head_mask.numel() * 1_0_0		,					)

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

       return head_mask
def        lowercase_							(A : List[str]		,					A : Tuple		,					A : Optional[Any]		,					A : int      ):
       snake_case__							:	Any   	=	datetime.now()
       snake_case__	,				snake_case__	,				snake_case__							:	str   	=	compute_heads_importance(
           A		,					A		,					A		,					compute_entropy=A		,					compute_importance=A		,					head_mask=A      )
       snake_case__							:	Tuple   	=	1 / loss
       snake_case__							:	Dict   	=	datetime.now() - before_time

       snake_case__							:	Union[str, Any]   	=	sum(p.numel() for p in model.parameters()      )
       snake_case__							:	Optional[Any]   	=	{
           layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(A      )      )
       }

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

       assert sum(len(A      ) for h in heads_to_prune.values()      ) == (1 - head_mask.long()).sum().item()
       model.prune_heads(A      )
       snake_case__							:	Dict   	=	sum(p.numel() for p in model.parameters()      )

       snake_case__							:	Tuple   	=	datetime.now()
       snake_case__	,				snake_case__	,				snake_case__							:	Dict   	=	compute_heads_importance(
           A		,					A		,					A		,					compute_entropy=A		,					compute_importance=A		,					head_mask=A		,					actually_pruned=A		,					)

       snake_case__							:	Any   	=	1 / loss
       snake_case__							:	int   	=	datetime.now() - before_time

       logger.info(
           'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'		,					A		,					A		,					pruned_num_params / original_num_params * 1_0_0		,					)
       logger.info('Pruning: score with masking: %f score with pruning: %f'		,					A		,					A      )
       logger.info('Pruning: speed ratio (original timing / new timing): %f percents'		,					original_time / new_time * 1_0_0      )
       save_model(A		,					args.output_dir      )
def        lowercase_							():
       snake_case__							:	str   	=	argparse.ArgumentParser()
       # Required parameters
       parser.add_argument(
           '--data_dir'		,					default=A		,					type=A		,					required=A		,					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=A		,					type=A		,					required=A		,					help='Path to pretrained model or model identifier from huggingface.co/models'		,					)
       parser.add_argument(
           '--output_dir'		,					default=A		,					type=A		,					required=A		,					help='The output directory where the model predictions and checkpoints will be written.'		,					)

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

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

       parser.add_argument('--seed'		,					type=A		,					default=4_2      )
       parser.add_argument('--local_rank'		,					type=A		,					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=A		,					default=''		,					help='Can be used for distant debugging.'      )
       parser.add_argument('--server_port'		,					type=A		,					default=''		,					help='Can be used for distant debugging.'      )
       snake_case__							:	Optional[int]   	=	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=A      )
              ptvsd.wait_for_attach()

       # Setup devices and distributed training
       if args.local_rank == -1 or args.no_cuda:
              snake_case__							:	List[Any]   	=	torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu'      )
              snake_case__							:	Optional[Any]   	=	0 if args.no_cuda else torch.cuda.device_count()
       else:
              torch.cuda.set_device(args.local_rank      )
              snake_case__							:	int   	=	torch.device('cuda'		,					args.local_rank      )
              snake_case__							:	List[str]   	=	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      )      )      )

       snake_case__							:	Any   	=	GPTaLMHeadModel.from_pretrained(args.model_name_or_path      )

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

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

       # Prepare dataset
       snake_case__							:	Optional[Any]   	=	np.concatenate(
           [
               np.loadtxt(args.data_dir		,					dtype=np.intaa      ),
           ]      )
       snake_case__							:	List[str]   	=	(torch.from_numpy(A      ),)
       snake_case__							:	int   	=	TensorDataset(*A      )
       snake_case__							:	Union[str, Any]   	=	RandomSampler(A      )
       snake_case__							:	Any   	=	DataLoader(A		,					sampler=A		,					batch_size=args.batch_size      )

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

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


if __name__ == "__main__":
 main()






