
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


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

SCREAMING_SNAKE_CASE							:Union[str, Any]										=    50  # max width of layer names
SCREAMING_SNAKE_CASE							:Optional[Any]										=    70  # max width of quantizer names


def 						UpperCAmelCase      (     a_						)		->     Optional[int]:







				"""simple docstring"""



				__A             =			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 						UpperCAmelCase      (     a_						)		->     Tuple:







				"""simple docstring"""



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

				__A             =			QuantDescriptor(num_bits=args.aprec		,       calib_method=a_						)
				__A             =			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 						UpperCAmelCase      (     a_		,       a_		,       a_=False		,       a_=False						)		->     Optional[Any]:







				"""simple docstring"""



				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 						UpperCAmelCase      (     a_						)		->     Optional[int]:







				"""simple docstring"""



				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 						UpperCAmelCase      (     a_		,       a_						)		->     List[str]:







				"""simple docstring"""



				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 						UpperCAmelCase      (     a_		,       a_						)		->     List[Any]:







				"""simple docstring"""



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

								__A             =			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 						UpperCAmelCase      (     a_		,       a_						)		->     List[str]:







				"""simple docstring"""



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


def 						UpperCAmelCase      (     a_						)		->     Dict:







				"""simple docstring"""



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


def 						UpperCAmelCase      (     a_						)		->     int:







				"""simple docstring"""



				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)
												__A             =			set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis						)
												__A             =			set(range(len(mod.weight.size()						)						)						) - axis_set
												__A             =			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()}'''						)
												__A             =			amax


def 						UpperCAmelCase      (     a_		,       a_=2_5		,       a_=1_8_0		,       a_=None						)		->     List[Any]:







				"""simple docstring"""



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

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

				for name, mod in model.named_modules():
								__A             =			getattr(a_		,       "_input_quantizer"		,       a_						)
								__A             =			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
								__A             =			F'''Act:{input_q.extra_repr()}'''
								__A             =			F'''Wgt:{weight_q.extra_repr()}'''
								__A             =			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 						UpperCAmelCase      (     a_						)		->     Optional[int]:







				"""simple docstring"""



				__A             =			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 						UpperCAmelCase      (     a_		,       a_		,       a_		,       a_		,       a_						)		->     Optional[int]:







				"""simple docstring"""



				__A             =			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 						UpperCAmelCase      (     a_		,       a_		,       a_="both"		,       **a_						)		->     Dict:







				"""simple docstring"""



				__A             =			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 						UpperCAmelCase      (     a_		,       a_		,       **a_						)		->     Optional[Any]:







				"""simple docstring"""



				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_						):
																				__A             =			F'''Warning: changing {name:{name_width}}'''
																				for k, v in kwargs.items():
																								s += F''' {k}={v}'''
																								setattr(a_		,       a_		,       a_						)
																				logger.info(a_						)


from typing import Optional

import numpy as np
import torch
from torch import nn
from transformers import GPTaConfig, GPTaLMHeadModel
from transformers.modeling_utils import ModuleUtilsMixin

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin





class 							UpperCAmelCase				(  __SCREAMING_SNAKE_CASE      ,      __SCREAMING_SNAKE_CASE      ,      __SCREAMING_SNAKE_CASE  ):




	'''simple docstring'''





	snake_case_    =					[R"h\.\d+\.attn\.bias", R"h\.\d+\.attn\.masked_bias"]






	@register_to_config
	def __init__(	self :			Tuple							,A :			int							,A :			int							,A :			Optional[int] = None							,A :			int = 5_02_57							,A :			int = 10_24							,A :			int = 7_68							,A :			int = 12							,A :			int = 12							,A :			Optional[int] = None							,A :			str = "gelu_new"							,A :			float = 0.1							,A :			float = 0.1							,A :			float = 0.1							,A :			float = 1E-5							,A :			float = 0.02							,A :			bool = True							,A :			bool = True							,A :			bool = False							,A :			bool = False							,):
					super().__init__()

					__A             =			prefix_length

					if prefix_inner_dim != n_embd and prefix_hidden_dim is None:
									raise ValueError(
									    f'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and'''
									    f''' `n_embd`: {n_embd} are not equal.'''			)

					__A             =			prefix_inner_dim
					__A             =			prefix_hidden_dim

					__A             =			(
					    nn.Linear(self.prefix_inner_dim							,self.prefix_hidden_dim			)
					    if self.prefix_hidden_dim is not None
					    else nn.Identity()
					)
					__A             =			(
					    nn.Linear(self.prefix_hidden_dim							,A			) if self.prefix_hidden_dim is not None else nn.Identity()
					)

					__A             =			GPTaConfig(
					    vocab_size=A							,n_positions=A							,n_embd=A							,n_layer=A							,n_head=A							,n_inner=A							,activation_function=A							,resid_pdrop=A							,embd_pdrop=A							,attn_pdrop=A							,layer_norm_epsilon=A							,initializer_range=A							,scale_attn_weights=A							,use_cache=A							,scale_attn_by_inverse_layer_idx=A							,reorder_and_upcast_attn=A							,)
					__A             =			GPTaLMHeadModel(A			)






	def     UpperCamelCase_  (	self :			Union[str, Any]							,A :			torch.Tensor							,A :			torch.Tensor							,A :			Optional[torch.Tensor] = None							,A :			Optional[torch.Tensor] = None							,):
					__A             =			self.transformer.transformer.wte(A			)
					__A             =			self.encode_prefix(A			)
					__A             =			self.decode_prefix(A			)
					__A             =			torch.cat((prefix_embeds, embedding_text)							,dim=1			)

					if labels is not None:
									__A             =			self.get_dummy_token(input_ids.shape[0]							,input_ids.device			)
									__A             =			torch.cat((dummy_token, input_ids)							,dim=1			)
					__A             =			self.transformer(inputs_embeds=A							,labels=A							,attention_mask=A			)
					if self.prefix_hidden_dim is not None:
									return out, hidden
					else:
									return out






	def     UpperCamelCase_  (	self :			int							,A :			int							,A :			torch.device			):
					return torch.zeros(A							,self.prefix_length							,dtype=torch.intaa							,device=A			)






	def     UpperCamelCase_  (	self :			Optional[Any]							,A :			List[Any]			):
					return self.encode_prefix(A			)






	@torch.no_grad()
	def     UpperCamelCase_  (	self :			str							,A :			List[str]							,A :			List[Any]							,A :			List[Any]			):
					__A             =			torch.split(A							,1							,dim=0			)
					__A             =			[]
					__A             =			[]
					for feature in features:
									__A             =			self.decode_prefix(feature.to(A			)			)  # back to the clip feature
									# Only support beam search for now
									__A      ,							__A             =			self.generate_beam(
									    input_embeds=A							,device=A							,eos_token_id=A			)
									generated_tokens.append(output_tokens[0]			)
									generated_seq_lengths.append(seq_lengths[0]			)
					__A             =			torch.stack(A			)
					__A             =			torch.stack(A			)
					return generated_tokens, generated_seq_lengths







	@torch.no_grad()
	def     UpperCamelCase_  (	self :			Tuple							,A :			List[str]=None							,A :			Dict=None							,A :			Optional[int]=None							,A :			int = 5							,A :			int = 67							,A :			float = 1.0							,A :			Optional[int] = None							,):
					__A             =			eos_token_id
					__A             =			None
					__A             =			None
					__A             =			torch.ones(A							,device=A							,dtype=torch.int			)
					__A             =			torch.zeros(A							,device=A							,dtype=torch.bool			)

					if input_embeds is not None:
									__A             =			input_embeds
					else:
									__A             =			self.transformer.transformer.wte(A			)

					for i in range(A			):
									__A             =			self.transformer(inputs_embeds=A			)
									__A             =			outputs.logits
									__A             =			logits[:, -1, :] / (temperature if temperature > 0 else 1.0)
									__A             =			logits.softmax(-1			).log()

									if scores is None:
													__A      ,							__A             =			logits.topk(A							,-1			)
													__A             =			generated.expand(A							,*generated.shape[1:]			)
													__A      ,							__A             =			next_tokens.permute(1							,0			), scores.squeeze(0			)
													if tokens is None:
																	__A             =			next_tokens
													else:
																	__A             =			tokens.expand(A							,*tokens.shape[1:]			)
																	__A             =			torch.cat((tokens, next_tokens)							,dim=1			)
									else:
													__A             =			-float(np.inf			)
													__A             =			0
													__A             =			scores[:, None] + logits
													seq_lengths[~is_stopped] += 1
													__A             =			scores_sum / seq_lengths[:, None]
													__A      ,							__A             =			scores_sum_average.view(-1			).topk(A							,-1			)
													__A             =			next_tokens // scores_sum.shape[1]
													__A             =			seq_lengths[next_tokens_source]
													__A             =			next_tokens % scores_sum.shape[1]
													__A             =			next_tokens.unsqueeze(1			)
													__A             =			tokens[next_tokens_source]
													__A             =			torch.cat((tokens, next_tokens)							,dim=1			)
													__A             =			generated[next_tokens_source]
													__A             =			scores_sum_average * seq_lengths
													__A             =			is_stopped[next_tokens_source]

									__A             =			self.transformer.transformer.wte(next_tokens.squeeze()			).view(generated.shape[0]							,1							,-1			)
									__A             =			torch.cat((generated, next_token_embed)							,dim=1			)
									__A             =			is_stopped + next_tokens.eq(A			).squeeze()
									if is_stopped.all():
													break

					__A             =			scores / seq_lengths
					__A             =			scores.argsort(descending=A			)
					# tokens tensors are already padded to max_seq_length
					__A             =			[tokens[i] for i in order]
					__A             =			torch.stack(A							,dim=0			)
					__A             =			torch.tensor([seq_lengths[i] for i in order]							,dtype=seq_lengths.dtype			)
					return output_texts, seq_lengths
