

import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          FalconForCausalLM,
          FalconForQuestionAnswering,
          FalconForSequenceClassification,
          FalconForTokenClassification,
          FalconModel,
      )






class 						__magic_name__    :


 def __init__(						self		: Optional[Any]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Dict=3			,						lowerCAmelCase__		: str=7			,						lowerCAmelCase__		: Dict=True			,						lowerCAmelCase__		: Tuple=True			,						lowerCAmelCase__		: int=False			,						lowerCAmelCase__		: Optional[Any]=True			,						lowerCAmelCase__		: List[Any]=9_9			,						lowerCAmelCase__		: Union[str, Any]=3_2			,						lowerCAmelCase__		: Optional[Any]=5			,						lowerCAmelCase__		: Any=4			,						lowerCAmelCase__		: Tuple=3_7			,						lowerCAmelCase__		: Optional[int]="gelu"			,						lowerCAmelCase__		: int=0.1			,						lowerCAmelCase__		: Tuple=0.1			,						lowerCAmelCase__		: List[str]=5_1_2			,						lowerCAmelCase__		: Any=1_6			,						lowerCAmelCase__		: Any=2			,						lowerCAmelCase__		: int=0.02			,						lowerCAmelCase__		: Dict=3			,						lowerCAmelCase__		: List[Any]=4			,						lowerCAmelCase__		: Optional[int]=None			,						)    ->      Dict:
   UpperCAmelCase					      =  parent
   UpperCAmelCase					      =  batch_size
   UpperCAmelCase					      =  seq_length
   UpperCAmelCase					      =  is_training
   UpperCAmelCase					      =  use_input_mask
   UpperCAmelCase					      =  use_token_type_ids
   UpperCAmelCase					      =  use_labels
   UpperCAmelCase					      =  vocab_size
   UpperCAmelCase					      =  hidden_size
   UpperCAmelCase					      =  num_hidden_layers
   UpperCAmelCase					      =  num_attention_heads
   UpperCAmelCase					      =  intermediate_size
   UpperCAmelCase					      =  hidden_act
   UpperCAmelCase					      =  hidden_dropout_prob
   UpperCAmelCase					      =  attention_probs_dropout_prob
   UpperCAmelCase					      =  max_position_embeddings
   UpperCAmelCase					      =  type_vocab_size
   UpperCAmelCase					      =  type_sequence_label_size
   UpperCAmelCase					      =  initializer_range
   UpperCAmelCase					      =  num_labels
   UpperCAmelCase					      =  num_choices
   UpperCAmelCase					      =  scope


 def _UpperCamelCase	(						self		: int    )    ->      Tuple:
   UpperCAmelCase					      =  ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size    )

   UpperCAmelCase					      =  None
   if self.use_input_mask:
     UpperCAmelCase					      =  random_attention_mask([self.batch_size, self.seq_length]    )

   UpperCAmelCase					      =  None

   UpperCAmelCase					      =  None
   UpperCAmelCase					      =  None
   UpperCAmelCase					      =  None
   if self.use_labels:
     UpperCAmelCase					      =  ids_tensor([self.batch_size]			,						self.type_sequence_label_size    )
     UpperCAmelCase					      =  ids_tensor([self.batch_size, self.seq_length]			,						self.num_labels    )
     UpperCAmelCase					      =  ids_tensor([self.batch_size]			,						self.num_choices    )

   UpperCAmelCase					      =  self.get_config()

   return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels


 def _UpperCamelCase	(						self		: List[Any]    )    ->      Tuple:
   return FalconConfig(
       vocab_size=self.vocab_size			,						hidden_size=self.hidden_size			,						num_hidden_layers=self.num_hidden_layers			,						num_attention_heads=self.num_attention_heads			,						intermediate_size=self.intermediate_size			,						hidden_act=self.hidden_act			,						hidden_dropout_prob=self.hidden_dropout_prob			,						attention_probs_dropout_prob=self.attention_probs_dropout_prob			,						max_position_embeddings=self.max_position_embeddings			,						type_vocab_size=self.type_vocab_size			,						is_decoder=lowerCAmelCase__			,						initializer_range=self.initializer_range			,						pad_token_id=1			,						new_decoder_architecture=lowerCAmelCase__			,						)


 def _UpperCamelCase	(						self		: Dict			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Union[str, Any]    )    ->      Dict:
   UpperCAmelCase					      =  FalconModel(config=lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__    )
   UpperCAmelCase					      =  model(lowerCAmelCase__    )
   self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Union[str, Any]			,						)    ->      Tuple:
   UpperCAmelCase					      =  True
   UpperCAmelCase					      =  FalconModel(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						)
   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						)
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__    )
   self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)    )


 def _UpperCamelCase	(						self		: Optional[Any]			,						lowerCAmelCase__		: List[str]			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: List[str]			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Any			,						lowerCAmelCase__		: Dict			,						)    ->      str:
   UpperCAmelCase					      =  FalconForCausalLM(config=lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.seq_length, self.vocab_size)    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: int			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Optional[Any]			,						lowerCAmelCase__		: List[Any]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: Dict			,						)    ->      Optional[Any]:
   UpperCAmelCase					      =  True
   UpperCAmelCase					      =  True
   UpperCAmelCase					      =  FalconForCausalLM(config=lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()

   # first forward pass
   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						use_cache=lowerCAmelCase__			,						)
   UpperCAmelCase					      =  outputs.past_key_values

   # create hypothetical multiple next token and extent to next_input_ids
   UpperCAmelCase					      =  ids_tensor((self.batch_size, 3)			,						config.vocab_size    )
   UpperCAmelCase					      =  ids_tensor((self.batch_size, 3)			,						vocab_size=2    )

   # append to next input_ids and
   UpperCAmelCase					      =  torch.cat([input_ids, next_tokens]			,						dim=-1    )
   UpperCAmelCase					      =  torch.cat([input_mask, next_mask]			,						dim=-1    )

   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						output_hidden_states=lowerCAmelCase__			,						)["hidden_states"][0]
   UpperCAmelCase					      =  model(
       lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						encoder_hidden_states=lowerCAmelCase__			,						encoder_attention_mask=lowerCAmelCase__			,						past_key_values=lowerCAmelCase__			,						output_hidden_states=lowerCAmelCase__			,						)["hidden_states"][0]

   # select random slice
   UpperCAmelCase					      =  ids_tensor((1,)			,						output_from_past.shape[-1]    ).item()
   UpperCAmelCase					      =  output_from_no_past[:, -3:, random_slice_idx].detach()
   UpperCAmelCase					      =  output_from_past[:, :, random_slice_idx].detach()

   self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]    )

   # test that outputs are equal for slice
   self.parent.assertTrue(torch.allclose(lowerCAmelCase__			,						lowerCAmelCase__			,						atol=1e-3    )    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      str:
   UpperCAmelCase					      =  self.prepare_config_and_inputs()
   (
       (
       UpperCAmelCase
   )      ,	(
       UpperCAmelCase
   )      ,	(
       UpperCAmelCase
   )      ,	(
       UpperCAmelCase
   )      ,	(
       UpperCAmelCase
   )      ,	(
       UpperCAmelCase
   )      ,	(
       UpperCAmelCase
   )      ,	
   )					      =  config_and_inputs
   UpperCAmelCase					      =  {"input_ids": input_ids, "attention_mask": input_mask}
   return config, inputs_dict






@require_torch
class 						__magic_name__    (       _snake_case	,						_snake_case	,						_snake_case	,						unittest.TestCase    ):
 UpperCAmelCase							    =						(
     (
         FalconModel,
         FalconForCausalLM,
         FalconForSequenceClassification,
         FalconForTokenClassification,
         FalconForQuestionAnswering,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase							    =						(FalconForCausalLM,) if is_torch_available() else ()
 UpperCAmelCase							    =						(
     {
         """feature-extraction""": FalconModel,
         """text-classification""": FalconForSequenceClassification,
         """text-generation""": FalconForCausalLM,
         """question-answering""": FalconForQuestionAnswering,
         """token-classification""": FalconForTokenClassification,
         """zero-shot""": FalconForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False


 def _UpperCamelCase	(						self		: Any    )    ->      Dict:
   UpperCAmelCase					      =  FalconModelTester(self    )
   UpperCAmelCase					      =  ConfigTester(self			,						config_class=lowerCAmelCase__			,						hidden_size=3_7    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      Any:
   self.config_tester.run_common_tests()


 def _UpperCamelCase	(						self		: List[str]    )    ->      int:
   UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Any    )    ->      Union[str, Any]:
   UpperCAmelCase      ,	*UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   for alibi in [True, False]:
     UpperCAmelCase					      =  alibi
     self.model_tester.create_and_check_model(lowerCAmelCase__			,						*lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Dict    )    ->      Dict:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  3
   UpperCAmelCase					      =  input_dict["input_ids"]
   UpperCAmelCase					      =  input_ids.ne(1    ).to(lowerCAmelCase__    )
   UpperCAmelCase					      =  ids_tensor([self.model_tester.batch_size]			,						self.model_tester.type_sequence_label_size    )
   UpperCAmelCase					      =  FalconForSequenceClassification(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.assertEqual(result.logits.shape			,						(self.model_tester.batch_size, self.model_tester.num_labels)    )


 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Any:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  3
   UpperCAmelCase					      =  "single_label_classification"
   UpperCAmelCase					      =  input_dict["input_ids"]
   UpperCAmelCase					      =  input_ids.ne(1    ).to(lowerCAmelCase__    )
   UpperCAmelCase					      =  ids_tensor([self.model_tester.batch_size]			,						self.model_tester.type_sequence_label_size    )
   UpperCAmelCase					      =  FalconForSequenceClassification(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.assertEqual(result.logits.shape			,						(self.model_tester.batch_size, self.model_tester.num_labels)    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      Any:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  input_dict["input_ids"]
   UpperCAmelCase					      =  FalconForCausalLM(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						use_cache=lowerCAmelCase__    )
   UpperCAmelCase					      =  input_ids.shape[0]
   UpperCAmelCase					      =  model._convert_to_rw_cache(result.past_key_values    )
   UpperCAmelCase					      =  model._convert_cache_to_standard_format(lowerCAmelCase__			,						lowerCAmelCase__    )
   for layer in range(len(lowerCAmelCase__    )    ):
     for tensor_idx in range(2    ):
       self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3    )
       self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4    )
       self.assertTrue(
           torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]    )    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      Dict:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  3
   UpperCAmelCase					      =  "multi_label_classification"
   UpperCAmelCase					      =  input_dict["input_ids"]
   UpperCAmelCase					      =  input_ids.ne(1    ).to(lowerCAmelCase__    )
   UpperCAmelCase					      =  ids_tensor(
       [self.model_tester.batch_size, config.num_labels]			,						self.model_tester.type_sequence_label_size    ).to(torch.float    )
   UpperCAmelCase					      =  FalconForSequenceClassification(lowerCAmelCase__    )
   model.to(lowerCAmelCase__    )
   model.eval()
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						attention_mask=lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.assertEqual(result.logits.shape			,						(self.model_tester.batch_size, self.model_tester.num_labels)    )


 def _UpperCamelCase	(						self		: Union[str, Any]    )    ->      Tuple:
   # Falcon can have different numbers of KV-heads than the number of query heads, so we need
   # to override this test to use the right head counts.
   for model_class in self.all_generative_model_classes:
     UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

     # If it doesn't support cache, pass the test
     if not hasattr(lowerCAmelCase__			,						"use_cache"    ):
       return

     UpperCAmelCase					      =  model_class(lowerCAmelCase__    ).to(lowerCAmelCase__    )
     if "use_cache" not in inputs:
       UpperCAmelCase					      =  True
     UpperCAmelCase					      =  model(**lowerCAmelCase__    )

     # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
     if "past_key_values" not in outputs:
       return

     UpperCAmelCase					      =  (
         getattr(lowerCAmelCase__			,						"decoder_layers"			,						lowerCAmelCase__    )
         or getattr(lowerCAmelCase__			,						"num_decoder_layers"			,						lowerCAmelCase__    )
         or config.num_hidden_layers
     )
     UpperCAmelCase					      =  getattr(lowerCAmelCase__			,						"num_kv_heads"			,						config.num_attention_heads    )
     UpperCAmelCase					      =  getattr(lowerCAmelCase__			,						"d_model"			,						config.hidden_size    )
     UpperCAmelCase					      =  embed_dim // num_attention_heads

     UpperCAmelCase					      =  outputs["past_key_values"]
     self.assertEqual(len(lowerCAmelCase__    )			,						lowerCAmelCase__    )

     UpperCAmelCase      ,	UpperCAmelCase					      =  inputs["input_ids"].shape
     for i in range(lowerCAmelCase__    ):
       if config.new_decoder_architecture:
         UpperCAmelCase					      =  config.num_attention_heads
       elif config.multi_query:
         UpperCAmelCase					      =  1
       self.assertEqual(len(past_kv[0]    )			,						2    )  # K V for the decoder = 2
       self.assertEqual(
           past_kv[i][0].shape			,						(batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )
       self.assertEqual(
           past_kv[i][1].shape			,						(batch_size, num_attention_heads, seq_length, per_head_embed_dim)    )






@require_torch
class 						__magic_name__    (       unittest.TestCase    ):


 @slow
 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Optional[Any]:
   UpperCAmelCase					      =  AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b"    )
   UpperCAmelCase					      =  FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b"    )
   model.eval()
   model.to(lowerCAmelCase__    )
   UpperCAmelCase					      =  tokenizer("My favorite food is"			,						return_tensors="pt"    ).to(lowerCAmelCase__    )

   UpperCAmelCase					      =  (
       "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
   )

   UpperCAmelCase					      =  model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=1_9    )
   UpperCAmelCase					      =  tokenizer.batch_decode(lowerCAmelCase__    )[0]

   self.assertEqual(lowerCAmelCase__			,						lowerCAmelCase__    )


 @slow
 def _UpperCamelCase	(						self		: Optional[int]    )    ->      Optional[int]:
   # The big models are way too big for the CI, so we use tiny random models that resemble their
   # architectures but with much smaller and fewer layers
   for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
     UpperCAmelCase					      =  AutoTokenizer.from_pretrained(lowerCAmelCase__    )
     UpperCAmelCase					      =  FalconForCausalLM.from_pretrained(lowerCAmelCase__    )
     model.eval()
     model.to(lowerCAmelCase__    )
     UpperCAmelCase					      =  tokenizer("My favorite food is"			,						return_tensors="pt"    ).to(lowerCAmelCase__    )

     # We just test that these run without errors - the models are randomly initialized
     # and so the actual text outputs will be garbage
     model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=4    )
     model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=4    )
     model.generate(**lowerCAmelCase__			,						num_beams=2			,						max_new_tokens=4    )


 @slow
 def _UpperCamelCase	(						self		: List[str]    )    ->      Tuple:
   # The big models are way too big for the CI, so we use tiny random models that resemble their
   # architectures but with much smaller and fewer layers
   with torch.no_grad():
     for repo in [
         "Rocketknight1/falcon-rw-1b",
         "Rocketknight1/tiny-random-falcon-7b",
         "Rocketknight1/tiny-random-falcon-40b",
     ]:
       UpperCAmelCase					      =  AutoTokenizer.from_pretrained(lowerCAmelCase__    )
       UpperCAmelCase					      =  FalconForCausalLM.from_pretrained(lowerCAmelCase__    )
       model.eval()
       model.to(device=lowerCAmelCase__    )
       UpperCAmelCase					      =  tokenizer("My favorite food is"			,						return_tensors="pt"    ).to(lowerCAmelCase__    )

       # Test results are the same with and without cache
       UpperCAmelCase					      =  model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=2_0			,						use_cache=lowerCAmelCase__    )
       UpperCAmelCase					      =  model.generate(**lowerCAmelCase__			,						do_sample=lowerCAmelCase__			,						max_new_tokens=2_0			,						use_cache=lowerCAmelCase__    )
       self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0    )






import logging
import re

import pytorch_quantization
import pytorch_quantization.nn as quant_nn
import torch
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor


lowerCAmelCase__       = logging.getLogger(__name__)

lowerCAmelCase__       = 50  # max width of layer names
lowerCAmelCase__       = 70  # max width of quantizer names
def      _lowerCAmelCase(	__A			):
  UpperCAmelCase					      =  parser.add_argument_group("quant_trainer arguments"			)
  group.add_argument("--wprec"   ,       type=__A   ,       default=8   ,       help="weight precision"			)
  group.add_argument("--aprec"   ,       type=__A   ,       default=8   ,       help="activation precision"			)
  group.add_argument("--quant-per-tensor"   ,       action="store_true"   ,       help="per tensor weight scaling"			)
  group.add_argument("--quant-disable"   ,       action="store_true"   ,       help="disable all quantizers"			)
  group.add_argument("--quant-disable-embeddings"   ,       action="store_true"   ,       help="disable all embeddings quantizers"			)
  group.add_argument("--quant-disable-keyword"   ,       type=__A   ,       nargs="+"   ,       help="disable quantizers by keyword"			)
  group.add_argument("--quant-disable-layer-module"   ,       type=__A   ,       help="disable quantizers by keyword under layer."			)
  group.add_argument("--quant-enable-layer-module"   ,       type=__A   ,       help="enable quantizers by keyword under layer"			)
  group.add_argument("--calibrator"   ,       default="max"   ,       help="which quantization range calibrator to use"			)
  group.add_argument("--percentile"   ,       default=__A   ,       type=__A   ,       help="percentile for PercentileCalibrator"			)
  group.add_argument("--fuse-qkv"   ,       action="store_true"   ,       help="use the same scale factor for qkv"			)
  group.add_argument("--clip-gelu"   ,       metavar="N"   ,       type=__A   ,       help="clip gelu output maximum value to N"			)
  group.add_argument(
      "--recalibrate-weights"   ,       action="store_true"   ,       help=(
          "recalibrate weight amaxes by taking the max of the weights."
          " amaxes will be computed with the current quantization granularity (axis)."
      )   ,       )
def      _lowerCAmelCase(	__A			):

  if args.calibrator == "max":
    UpperCAmelCase					      =  "max"
  elif args.calibrator == "percentile":
    if args.percentile is None:
      raise ValueError("Specify --percentile when using percentile calibrator"			)
    UpperCAmelCase					      =  "histogram"
  elif args.calibrator == "mse":
    UpperCAmelCase					      =  "histogram"
  else:
    raise ValueError(F"Invalid calibrator {args.calibrator}"			)

  UpperCAmelCase					      =  QuantDescriptor(num_bits=args.aprec   ,       calib_method=__A			)
  UpperCAmelCase					      =  QuantDescriptor(num_bits=args.wprec   ,       axis=(None if args.quant_per_tensor else (0,))			)
  quant_nn.QuantLinear.set_default_quant_desc_input(__A			)
  quant_nn.QuantLinear.set_default_quant_desc_weight(__A			)
def      _lowerCAmelCase(	__A   ,       __A   ,       __A=False   ,       __A=False			):
  logger.info("Configuring Model for Quantization"			)
  logger.info(F"using quantization package {pytorch_quantization.__file__}"			)

  if not calib:
    if args.quant_disable_embeddings:
      set_quantizer_by_name(__A   ,       ["embeddings"]   ,       which="weight"   ,       _disabled=__A			)

    if args.quant_disable:
      set_quantizer_by_name(__A   ,       [""]   ,       _disabled=__A			)

    if args.quant_disable_keyword:
      set_quantizer_by_name(__A   ,       args.quant_disable_keyword   ,       _disabled=__A			)

    if args.quant_disable_layer_module:
      set_quantizer_by_name(__A   ,       [r"layer.\d+." + args.quant_disable_layer_module]   ,       _disabled=__A			)

    if args.quant_enable_layer_module:
      set_quantizer_by_name(__A   ,       [r"layer.\d+." + args.quant_enable_layer_module]   ,       _disabled=__A			)

    if args.recalibrate_weights:
      recalibrate_weights(__A			)

    if args.fuse_qkv:
      fuse_qkv(__A   ,       __A			)

  if args.clip_gelu:
    clip_gelu(__A   ,       args.clip_gelu			)

  # if args.local_rank in [-1, 0] and not calib:
  print_quant_summary(__A			)
def      _lowerCAmelCase(	__A			):
  logger.info("Enabling Calibration"			)
  for name, module in model.named_modules():
    if name.endswith("_quantizer"			):
      if module._calibrator is not None:
        module.disable_quant()
        module.enable_calib()
      else:
        module.disable()
      logger.info(F"{name:80}: {module}"			)
def      _lowerCAmelCase(	__A   ,       __A			):
  logger.info("Loading calibrated amax"			)
  for name, module in model.named_modules():
    if name.endswith("_quantizer"			):
      if module._calibrator is not None:
        if isinstance(module._calibrator   ,       calib.MaxCalibrator			):
          module.load_calib_amax()
        else:
          module.load_calib_amax("percentile"   ,       percentile=args.percentile			)
        module.enable_quant()
        module.disable_calib()
      else:
        module.enable()
  model.cuda()
  print_quant_summary(__A			)
def      _lowerCAmelCase(	__A   ,       __A			):

  def fusea(__A   ,       __A   ,       __A			):
    for mod in [qq, qk, qv]:
      if not hasattr(__A   ,       "_amax"			):
        print("          WARNING: NO AMAX BUFFER"			)
        return
    UpperCAmelCase					      =  qq._amax.detach().item()
    UpperCAmelCase					      =  qk._amax.detach().item()
    UpperCAmelCase					      =  qv._amax.detach().item()

    UpperCAmelCase					      =  max(__A   ,       __A   ,       __A			)
    qq._amax.fill_(__A			)
    qk._amax.fill_(__A			)
    qv._amax.fill_(__A			)
    logger.info(F"          q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}"			)

  for name, mod in model.named_modules():
    if name.endswith(".attention.self"			):
      logger.info(F"FUSE_QKV: {name:{name_width}}"			)
      fusea(mod.matmul_q_input_quantizer   ,       mod.matmul_k_input_quantizer   ,       mod.matmul_v_input_quantizer			)
      if args.quant_per_tensor:
        fusea(mod.query._weight_quantizer   ,       mod.key._weight_quantizer   ,       mod.value._weight_quantizer			)
def      _lowerCAmelCase(	__A   ,       __A			):

  for name, mod in model.named_modules():
    if name.endswith(".output.dense"			) and not name.endswith("attention.output.dense"			):
      UpperCAmelCase					      =  mod._input_quantizer._amax.data.detach().item()
      mod._input_quantizer._amax.data.detach().clamp_(max=__A			)
      UpperCAmelCase					      =  mod._input_quantizer._amax.data.detach().item()
      logger.info(F"CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}"			)
def      _lowerCAmelCase(	__A			):

  for name, mod in model.named_modules():
    if hasattr(__A   ,       "_weight_quantizer"			) and mod._weight_quantizer.axis is not None:
      UpperCAmelCase					      =  mod.weight.shape[0]
      UpperCAmelCase					      =  mod._weight_quantizer._amax.detach()
      UpperCAmelCase					      =  torch.ones(__A   ,       dtype=amax.dtype   ,       device=amax.device			) * amax
      print(F"expanding {name} {amax} -> {mod._weight_quantizer._amax}"			)
def      _lowerCAmelCase(	__A			):

  for name, mod in model.named_modules():
    if hasattr(__A   ,       "_weight_quantizer"			):
      if not hasattr(mod.weight_quantizer   ,       "_amax"			):
        print("RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER"			)
        continue

      # determine which axes to reduce across
      # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3)
      UpperCAmelCase					      =  set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis			)
      UpperCAmelCase					      =  set(range(len(mod.weight.size()			)			)			) - axis_set
      UpperCAmelCase					      =  pytorch_quantization.utils.reduce_amax(mod.weight   ,       axis=__A   ,       keepdims=__A			).detach()
      logger.info(F"RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}"			)
      UpperCAmelCase					      =  amax
def      _lowerCAmelCase(	__A   ,       __A=25   ,       __A=180   ,       __A=None			):

  if ignore is None:
    UpperCAmelCase					      =  []
  elif not isinstance(__A   ,       __A			):
    UpperCAmelCase					      =  [ignore]

  UpperCAmelCase					      =  0
  for name, mod in model.named_modules():
    if not hasattr(__A   ,       "weight"			):
      continue
    UpperCAmelCase					      =  max(__A   ,       len(__A			)			)

  for name, mod in model.named_modules():
    UpperCAmelCase					      =  getattr(__A   ,       "_input_quantizer"   ,       __A			)
    UpperCAmelCase					      =  getattr(__A   ,       "_weight_quantizer"   ,       __A			)
    if not hasattr(__A   ,       "weight"			):
      continue
    if type(__A			) in ignore:
      continue
    if [True for s in ignore if type(__A			) is str and s in name]:
      continue
    UpperCAmelCase					      =  F"Act:{input_q.extra_repr()}"
    UpperCAmelCase					      =  F"Wgt:{weight_q.extra_repr()}"
    UpperCAmelCase					      =  F"{name:{name_width}} {act_str} {wgt_str}"
    if len(__A			) <= line_width:
      logger.info(__A			)
    else:
      logger.info(F"{name:{name_width}} {act_str}"			)
      logger.info(F"{'  ':{name_width}} {wgt_str}"			)
def      _lowerCAmelCase(	__A			):
  UpperCAmelCase					      =  0
  for name, mod in model.named_modules():
    if isinstance(__A   ,       pytorch_quantization.nn.TensorQuantizer			):
      print(F"{name:80} {mod}"			)
      count += 1
  print(F"{count} TensorQuantizers found in model"			)
def      _lowerCAmelCase(	__A   ,       __A   ,       __A   ,       __A   ,       __A			):
  UpperCAmelCase					      =  getattr(__A   ,       __A   ,       __A			)
  if quantizer_mod is not None:
    assert hasattr(__A   ,       __A			)
    setattr(__A   ,       __A   ,       __A			)
  else:
    logger.warning(F"{name} has no {quantizer}"			)
def      _lowerCAmelCase(	__A   ,       __A   ,       __A="both"   ,       **__A			):
  UpperCAmelCase					      =  F"Warning: changing {which} quantizers of {name:{qname_width}}"
  for k, v in kwargs.items():
    s += F" {k}={v}"
    if which in ["input", "both"]:
      set_quantizer(__A   ,       __A   ,       "_input_quantizer"   ,       __A   ,       __A			)
    if which in ["weight", "both"]:
      set_quantizer(__A   ,       __A   ,       "_weight_quantizer"   ,       __A   ,       __A			)
  logger.info(__A			)





def      _lowerCAmelCase(	__A   ,       __A   ,       **__A			):

  for name, mod in model.named_modules():
    if hasattr(__A   ,       "_input_quantizer"			) or hasattr(__A   ,       "_weight_quantizer"			):
      for n in names:
        if re.search(__A   ,       __A			):
          set_quantizers(__A   ,       __A   ,       **__A			)
    elif name.endswith("_quantizer"			):
      for n in names:
        if re.search(__A   ,       __A			):
          UpperCAmelCase					      =  F"Warning: changing {name:{name_width}}"
          for k, v in kwargs.items():
            s += F" {k}={v}"
            setattr(__A   ,       __A   ,       __A			)
          logger.info(__A			)



