Ë
    S^(hdP  ã            
       óž  — d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZmZ ddlmZmZmZmZ  e«       r
ddlZddlmZ  ej*                  e«      Zg d	¢g d
¢g d¢ddœg d	¢g d¢g d¢dddœg d	¢g d
¢g d¢ddœg d	¢g d
¢g d¢ddœdœZdddœdddœdddœdddœdddœdddœdddœdddœdœZd„ Z	 	 	 	 d$defd„Zd„ Zd„ Zd„ Zd „ Z d!„ Z!d"„ Z"d#„ Z#y)%z;AWQ (Activation aware Weight Quantization) integration fileé    N)Úversioné   )ÚACT2FN)ÚPreTrainedModel)Úis_auto_awq_availableÚis_ipex_availableÚis_torch_availableÚlogging)ÚAwqBackendPackingMethodÚ	AwqConfigÚAWQLinearVersionÚExllamaVersion)Úq_projÚk_projÚv_projÚo_proj)Ú	gate_projÚup_projÚ	down_proj)Úinput_layernormÚpost_attention_layernormÚnormF)Ú	attentionÚmlpÚ	layernormÚ	use_alibi)Úw1Úw3Úw2g    €„.A)r   r   r   r   Ú
rope_theta)ÚmistralÚmixtralÚllamaÚllavaÚactÚc_fc)r%   Úlayer_before_actÚdense_h_to_4hr   Úfc_inÚ	gelu_impl)Ú
starcoder2ÚRefinedWebModelÚfalconÚmptÚgptjÚgpt_neoxÚgpt_bigcodeÚbloomc                 óZ  — ddl m} |t        vr| S | j                  «       D ]‡  \  }}t        |   d   }t        |   d   }||k(  rYt	        | |«      rMt        | t        |   d   «      }|j                  }t        j                  |«      }	 |||	«      | j                  |<   t        ||«      }
Œ‰ | S )Nr   )ÚScaledActivationr%   r'   )Úawq.modules.actr4   ÚAWQ_SCALES_MAPPINGSÚnamed_childrenÚhasattrÚgetattrÚout_featuresÚtorchÚonesÚ_modulesÚreplace_quantization_scales)ÚmodelÚ
model_typer4   ÚnameÚmoduleÚact_nameÚlayer_before_act_namer'   ÚsizeÚ
scale_likeÚ_s              ú[/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/integrations/awq.pyr>   r>   M   s»   € Ý0àÔ,Ñ,ØˆØ×,Ñ,Ó.ò <‰ˆˆfÜ& zÑ2°5Ñ9ˆÜ 3°JÑ ?Ð@RÑ SÐØ�8Ò¤¨Ð/DÔ EÜ& uÔ.AÀ*Ñ.MÐN`Ñ.aÓbÐØ#×0Ñ0ˆDÜŸ™ DÓ)ˆJÙ#3°F¸JÓ#GˆE�N‰N˜4Ñ Ü'¨°
Ó;‰ð<ð €Ló    Úreturnc           	      ó  ‡— |€g }|j                   }t        «       st        d«      ‚|t        j                  k(  �r|j
                  t        j                  k(  r	ddlm	} |}nö|j
                  t        j                  k(  r	ddlm} |}nÐ|j
                  t        j                  k(  rm|j                  d   t        j                   k(  r	ddlm}	 |	}nŠ|j                  d   t        j&                  k(  r	ddlm}
 |
}nat        d	|j                  d   › �«      ‚|j
                  t        j,                  k(  r	dd
lm} |}n t        d|j
                  › �«      ‚ddlm} |}| j7                  «       D �]  \  }}‰€g Š‰j9                  |«       t;        |t<        j>                  «      rŸ||vr›tA        ˆfd„|D «       «      s‡|jB                  }|jD                  } ||jF                  |jH                  |||jJ                  du|jL                  jN                  ¬«      | jP                  |<   d}| jP                  |   jS                  d«       tU        tW        |jY                  «       «      «      dkD  rt[        ||‰||¬«      \  }}‰j]                  d«       �Œ  | |fS )a¥  
    Public method that recursively replaces the Linear layers of the given model with AWQ quantized layers.
    `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
    conversion has been successfull or not.

    During the module replacement, we also infer the backend to use through the `quantization_config` object.

    Args:
        model (`torch.nn.Module`):
            The model to convert, can be any `torch.nn.Module` instance.
        quantization_config (`AwqConfig`):
            The quantization config object that contains the quantization parameters.
        modules_to_not_convert (`list`, *optional*):
            A list of modules to not convert. If a module name is in the list (e.g. `lm_head`), it will not be
            converted.
        current_key_name (`list`, *optional*):
            A list that contains the current key name. This is used for recursion and should not be passed by the user.
        has_been_replaced (`bool`, *optional*):
            A boolean that indicates if the conversion has been successful or not. This is used for recursion and
            should not be passed by the user.
    Nz¯AWQ (either `autoawq` or `llmawq`) is not available. Please install it with `pip install autoawq` or check out the installation guide in https://github.com/mit-han-lab/llm-awqr   )ÚWQLinear_GEMM)ÚWQLinear_GEMVr   )ÚWQLinear_Exllama)ÚWQLinear_ExllamaV2úUnrecognized Exllama version: ©ÚWQLinear_IPEXzUnrecognized AWQ version: )ÚWQLinearc              3   óD   •K  — | ]  }|d j                  ‰«      v –— Œ y­w)ú.N)Újoin)Ú.0ÚkeyÚcurrent_key_names     €rH   ú	<genexpr>z*replace_with_awq_linear.<locals>.<genexpr>ª   s    øè ø€ Ò[¸S�s˜cŸh™hÐ'7Ó8Ô8Ñ[ùs   ƒ )Úw_bitÚ
group_sizeÚin_featuresr:   ÚbiasÚdevTF)Úmodules_to_not_convertrY   Úquantization_configÚhas_been_replacedéÿÿÿÿ)/Úbackendr   Ú
ValueErrorr   ÚAUTOAWQr   r   ÚGEMMÚawq.modules.linear.gemmrL   ÚGEMVÚawq.modules.linear.gemvrM   ÚEXLLAMAÚexllama_configr   ÚONEÚawq.modules.linear.exllamarN   ÚTWOÚawq.modules.linear.exllamav2rO   ÚIPEXÚawq.modules.linear.gemm_ipexrR   Úawq.quantize.qmodulerS   r7   ÚappendÚ
isinstanceÚnnÚLinearÚanyr]   r:   Úbitsr\   r^   ÚweightÚdevicer=   Úrequires_grad_ÚlenÚlistÚchildrenÚreplace_with_awq_linearÚpop)r?   r`   ra   rY   rb   rd   rL   Ú
target_clsrM   rN   rO   rR   rS   rA   rB   r]   r:   rG   s      `              rH   r€   r€   ^   sf  ø€ ð8 Ð%Ø!#Ðà!×)Ñ)€Gä Ô"Üð ~ó
ð 	
ð Ô)×1Ñ1Ó1Ø×&Ñ&Ô*:×*?Ñ*?Ò?Ý=à&‰JØ ×(Ñ(Ô,<×,AÑ,AÒAÝ=à&‰JØ ×(Ñ(Ô,<×,DÑ,DÒDØ"×1Ñ1°)Ñ<Ä×@RÑ@RÒRÝGà-‘
Ø$×3Ñ3°IÑ>Ä.×BTÑBTÒTÝKà/‘
ä Ð#AÐBU×BdÑBdÐenÑBoÐApÐ!qÓrÐrØ ×(Ñ(Ô,<×,AÑ,AÒAÝBà&‰JäÐ9Ð:M×:UÑ:UÐ9VÐWÓXÐXå1àˆ
à×,Ñ,Ó.ó  !‰ˆˆfØÐ#Ø!ÐØ×Ñ Ô%ä�fœbŸi™iÔ(¨TÐ9OÑ-OäÓ[ÐDZÔ[Ô[Ø$×0Ñ0�Ø%×2Ñ2�á'1Ø-×2Ñ2Ø2×=Ñ=Ø +Ø!-ØŸ™¨DÐ0ØŸ™×,Ñ,ô(�—‘˜tÑ$ð %)Ð!ð —‘˜tÑ$×3Ñ3°EÔ:ÜŒt�F—O‘OÓ%Ó&Ó'¨!Ò+Ü#:ØØ'=Ø!1Ø$7Ø"3ô$Ñ ˆAÐ ð 	×Ñ˜RÖ ðA !ðB Ð#Ð#Ð#rI   c                 ó  — t        | t        «      s"t        d| j                  j                  › �«      ‚|j
                  �|j
                  }|j                  |d<   |S | j                  j                  t        v r~t        | j                  j                     }| j                  j                  d¬«      }|j                  }|j                  }t        |d|«      }||d<   ||d<   ||d<   |j                  |d<   |S t        d«      ‚)	af  
    Returns the fusing mapping given the quantization config and the model

    Args:
        model (`~PreTrainedModel`):
            The model to fuse - note this model should have been converted into AWQ format beforehand.
        quantization_config (`~transformers.quantization_config.AWQConfig`):
            The quantization configuration to use.
    z:The model should be an instance of `PreTrainedModel`, got Úmax_seq_lenT©ÚdecoderÚnum_key_value_headsÚhidden_sizeÚnum_attention_headsa  Fusing mapping not found either on the quantization config or the supported `AWQ_FUSED_MAPPINGS`. Please pass a `fused_mapping` argument in the `quantization_config` or raise an issue on transformers https://github.com/huggingface/transformers to add its support.)ru   r   Ú	TypeErrorÚ	__class__Ú__name__Úmodules_to_fuseÚfuse_max_seq_lenÚconfigr@   ÚAWQ_FUSED_MAPPINGSÚget_text_configrˆ   r‰   r9   re   )r?   ra   Úcurrent_fused_mappingr�   rˆ   r‰   r‡   s          rH   Úget_modules_to_fuser“   Ç   s"  € ô �eœ_Ô-ÜÐTÐUZ×UdÑUd×UmÑUmÐTnÐoÓpÐpð ×*Ñ*Ð6Ø 3× CÑ CÐØ/B×/SÑ/SÐ˜mÑ,ð, !Ð ð+ 
�‰×	 Ñ	 Ô$6Ñ	6Ü 2°5·<±<×3JÑ3JÑ KÐð —‘×-Ñ-°dÐ-Ó;ˆð ×(Ñ(ˆØ$×8Ñ8ÐÜ% fÐ.CÐEXÓYÐð 0;Ð˜mÑ,Ø7JÐÐ3Ñ4Ø7JÐÐ3Ñ4Ø/B×/SÑ/SÐ˜mÑ,ð !Ð ô	 ðNó
ð 	
rI   c                 ó>  ‡
‡‡— t        |t        «      rt        j                  |«      }|j                  }t        | |«      }t        |dd«      }|t        j                  k(  rddl	m
} ddlm} ddlm} nt        d«      ‚g Š
| j!                  «       D ]˜  \  Š}|�t#        ˆfd„|D «       «      rŒt%        |d	   ||«       |j&                  d
k7  rt)        | ‰|d   ||«       nt*        j-                  d«       t/        | ||‰|«      }	|	sŒv‰
j1                  ‰j3                  d«      d   «       Œš t5        ‰
«      dkD  rc| j!                  «       D ]P  \  Š}t#        ˆ
ˆfd„‰
D «       «      sŒt7        |d«      sŒ)t7        |j8                  d«      sŒ@d|j8                  _        ŒR | S )aJ  
    Optionally fuse some modules in the model to speedup inference.

    Args:
        model (`~PreTrainedModel`):
            The model to fuse - note this model should have been converted into AWQ format beforehand.
        quantization_config (`Union[AwqConfig, dict]`):
            The quantization configuration to use.
    r`   Nr   )ÚQuantAttentionFused)ÚQuantFusedMLP)ÚFasterTransformerRMSNormz0Fusing is only supported for the AutoAWQ backendc              3   ó&   •K  — | ]  }|‰v –— Œ
 y ­w©N© )rW   Úmodule_name_to_not_convertrA   s     €rH   rZ   z#fuse_awq_modules.<locals>.<genexpr>  s   øè ø€ ÒoÐ:TÐ-°Ô5Ñoùó   ƒr   Úipexr   z7The IPEX version AWQ does not support fuse mlp for now.rU   c              3   ó&   •K  — | ]  }‰‰v –— Œ
 y ­wr™   rš   )rW   Úfused_attention_parent_moduleÚfused_attention_modulesÚmodule_names     €€rH   rZ   z#fuse_awq_modules.<locals>.<genexpr>(  s   øè ø€ ò Ø;X�Ð6Ô6ñùrœ   r�   Ú_attn_implementationÚcustom)ru   Údictr   Ú	from_dictrd   r“   r9   r   rf   Úawq.modules.fused.attnr•   Úawq.modules.fused.mlpr–   Úawq.modules.fused.normr—   re   Únamed_modulesrx   Ú_fuse_awq_layernormr   Ú_fuse_awq_mlpÚloggerÚinfoÚ_fuse_awq_attention_layersrt   Úsplitr}   r8   r�   r¢   )r?   ra   rd   r�   r`   r•   r–   r—   rB   Úattention_has_been_fusedr    r¡   rA   s             @@@rH   Úfuse_awq_modulesr±   ð   sš  ú€ ô Ð%¤tÔ,Ü'×1Ñ1Ð2EÓFÐØ!×)Ñ)€Gä)¨%Ð1DÓE€OÜ$Ð%8Ð:RÐTXÓYÐàÔ)×1Ñ1Ò1Ý>Ý7ÞCäÐKÓLÐLà Ðà×+Ñ+Ó-ò ?‰ˆˆfØ!Ð-ÜÓoÐXnÔoÔoØô 	˜O¨KÑ8¸&ÐBZÔ[ð ×&Ñ&¨&Ò0Ü˜%  °uÑ'=¸vÀ}ÕUä�K‰KÐQÔRô $>Ø�6˜?¨DÐ2Eó$
Ð ò $Ø#×*Ñ*¨4¯:©:°c«?¸1Ñ+=Õ>ð)?ô2 Ð"Ó# aÒ'Ø#(×#6Ñ#6Ó#8ò 	BÑˆK˜Üô Ø\sôõ ô ˜6 8Õ,´¸¿¹ÐH^Õ1_Ø9A�F—M‘MÕ6ð	Bð €LrI   c                 óà   — | D ]i  }t        ||«      sŒt        ||«      } ||j                  |j                  «      j	                  |j                  j
                  «      |j                  |<   ~Œk y)a¬  
    Fuse the LayerNorm layers into a target class using autoawq

    Args:
        fuse_module_names (`List[str]`):
            The list of module names to fuse
        module (`nn.Module`):
            The pytorch parent module that has layernorm modules to fuse
        target_cls (`~autoawq.FasterTransformerRMSNorm`):
            The `FasterTransformerRMSNorm` class as it only supports that class
            for now.
    N)r8   r9   rz   Úvariance_epsilonÚtor{   r=   )Úfuse_module_namesrB   r‚   r¡   Ú
old_modules        rH   rª   rª   0  sn   € ð )ò ˆÜ�6˜;Õ'Ü  ¨Ó5ˆJÙ+5Ø×!Ñ!Ø×+Ñ+ó,÷ ‰b�×"Ñ"×)Ñ)Ó*ð �O‰O˜KÑ(ñ ñrI   c                 óÊ  — t        |«      dk(  ryt        ||d   «      rÅt        ||d   «      }t        ||d   «      }t        ||d   «      }|j                  j                  }| j
                  j                  d¬«      }	|	j                  }
t        |
   } |||||«      }|j                  dd«      \  }}| j                  |«      }t        |||j                  |«      «       ~~~yy)aÏ  
    Fuse the MLP layers into a target class using autoawq

    Args:
        model (`~PreTrainedModel`):
            The input pretrained model
        current_module_name (`str`):
            The current submodule name
        fuse_module_names (`List[str]`):
            The list of module names to fuse. For the MLP layers it has to be an array
            of length 3 that consists of the 3 MLP layers in the order (gate (dense layer post-attention) / up / down layers)
        module (`nn.Module`):
            The pytorch parent module that has layernorm modules to fuse
        target_cls (`~autoawq.QuantFusedMLP`):
            The `QuantFusedMLP` class as it only supports that class
            for now.
    r   Né   r   Tr…   rU   )r}   r8   r9   Úqweightr{   r�   r‘   Ú
hidden_actr   ÚrsplitÚget_submoduleÚsetattrr´   )r?   Úcurrent_module_namerµ   rB   r‚   r   r   r   Úprevious_devicer�   rº   Úactivation_fnÚ
new_moduleÚparent_nameÚ
child_nameÚparents                   rH   r«   r«   G  sò   € ô$ ÐÓ Ò"ØäˆvÐ(¨Ñ+Ô,Ü˜FÐ$5°aÑ$8Ó9ˆ	Ü˜&Ð"3°AÑ"6Ó7ˆÜ˜FÐ$5°aÑ$8Ó9ˆ	à#×+Ñ+×2Ñ2ˆð —‘×-Ñ-°dÐ-Ó;ˆØ×&Ñ&ˆ
Ü˜zÑ*ˆÙ 	¨9°g¸}ÓMˆ
à"5×"<Ñ"<¸SÀ!Ó"DÑˆ�ZØ×$Ñ$ [Ó1ˆÜ�˜
 J§M¡M°/Ó$BÔCà�w¡	ð# -rI   c                 ó´  — ddl m}m} d}t        |d   «      dk(  r|S t	        ||d   d   «      �r't        ||d   d   «      }t        ||«      r|}	d}
n…t        ||«      r|}	d}
ntt        «       r_t        j                  t        j                  j                  d«      «      t        j                  d«      kD  rddl m} t        ||«      r|}	d}
nt        d	«      ‚|j                  j                  }t        ||d   d   «      }t        ||d   d
   «      }t        ||d   d   «      }|j                   �8t#        j$                  |j                   |j                   |j                   gd¬«      nd} 	|j&                  |j(                  |j*                  |j,                  |j,                  z   |j,                  z   |j                   dut/        t1        |j3                  «       j5                  «       «      «      j                  «      }t#        j$                  |j                  |j                  |j                  g
¬«      |_        t#        j$                  |j6                  |j6                  |j6                  g|
¬«      |_        t#        j$                  |j8                  |j8                  |j8                  g|
¬«      |_        t        ||«      r|j:                  |_        ||_         ||d   |d   |d   ||||d   |d   |j=                  dd«      ¬«	      }d|_        |jA                  dd«      \  }}| jC                  |«      }tE        |||jG                  |«      «       ~~~~d}|S )a²  
    Fuse the Attention layers into a target class using autoawq

    Args:
        model (`~PreTrainedModel`):
            The input pretrained model
        module (`nn.Module`):
            The pytorch parent module that has layernorm modules to fuse
        modules_to_fuse (`List[str]`):
            The module fusing mapping. The dictionary has to contain a field `attention` with attention module names
            in the correct order: q, k, v, o layer
        current_module_name (`str`):
            The current submodule name
        target_cls (`~autoawq.QuantAttentionFused`):
            The `QuantAttentionFused` class as it only supports that class
            for now.
    r   )rL   rM   Fr   r¸   Úautoawqz0.2.6rQ   z'Unsupported q_proj type: {type(q_proj)}r   é   N)Údimrˆ   r‰   r‡   r„   r   r    g     ˆÃ@)r   r    TrU   )$Úawq.modules.linearrL   rM   r}   r8   r9   ru   r   r   ÚparseÚ	importlibÚmetadatarR   re   r¹   r{   r^   r;   Úcatr[   r\   r]   r:   ÚnextÚiterÚ
state_dictÚvaluesÚqzerosÚscalesÚsplit_k_itersÚgetÚis_hf_transformersr»   r¼   r½   r´   )r?   rB   r�   r¾   r‚   rL   rM   Úmodule_has_been_fusedr   Úlinear_target_clsÚcat_dimrR   r¿   r   r   r   r^   Ú	qkv_layerÚfused_attention_layerrÂ   rÃ   rÄ   s                         rH   r®   r®   p  s  € ÷$ @à!Ðä
ˆ?˜;Ñ'Ó(¨AÒ-Ø$Ð$äˆv� {Ñ3°AÑ6Õ7ä˜ °Ñ!=¸aÑ!@ÓAˆä�f˜mÔ,Ø -ÐØ‰GÜ˜ Ô.Ø -ÐØ‰GÜÔ ¤W§]¡]´9×3EÑ3E×3MÑ3MÈiÓ3XÓ%YÔ\c×\iÑ\iÐjqÓ\rÒ%rÝ8ä˜& -Ô0Ø$1Ð!Ø‘äÐFÓGÐGà Ÿ.™.×/Ñ/ˆä˜ °Ñ!=¸aÑ!@ÓAˆÜ˜ °Ñ!=¸aÑ!@ÓAˆÜ˜ °Ñ!=¸aÑ!@ÓAˆàLRÏKÉKÐLcŒu�y‰y˜&Ÿ+™+ v§{¡{°F·K±KÐ@ÀaÕHÐimˆá%Ø�L‰LØ×ÑØ×ÑØ×Ñ &×"5Ñ"5Ñ5¸×8KÑ8KÑKØ�K‰K˜tÐ#Ü”�f×'Ñ'Ó)×0Ñ0Ó2Ó3Ó4×;Ñ;ó
ˆ	ô "ŸI™I v§~¡~°v·~±~ÀvÇ~Á~Ð&VÐ\cÔdˆ	ÔÜ Ÿ9™9 f§m¡m°V·]±]ÀFÇMÁMÐ%RÐX_Ô`ˆ	ÔÜ Ÿ9™9 f§m¡m°V·]±]ÀFÇMÁMÐ%RÐX_Ô`ˆ	Ôä�i Ô/Ø&,×&:Ñ&:ˆIÔ#àˆ	Œá *Ø˜MÑ*ØÐ1Ñ2ØÐ1Ñ2ØØØØ˜MÑ*Ø% kÑ2à&×*Ñ*¨<¸ÓAô!
Ðð 48ÐÔ0à"5×"<Ñ"<¸SÀ!Ó"DÑˆ�ZØ×$Ñ$ [Ó1ˆÜ�˜
Ð$9×$<Ñ$<¸_Ó$MÔNà�F˜F FØ $Ðà Ð rI   c                 óÎ   — |d   t         j                  k(  rddlm}  || «      } | S |d   t         j                  k(  rddlm}  || |d   |d   ¬«      } | S t        d|d   › �«      ‚)	zœ
    Runs post init for Exllama layers which performs:
        - Weights unpacking, reordering and repacking
        - Devices scratch space allocation
    r   r   )Úexllama_post_init)Úexllamav2_post_initÚmax_input_lenÚmax_batch_size)rß   rà   rP   )r   rm   rn   rÝ   ro   rp   rÞ   re   )r?   rl   rÝ   rÞ   s       rH   Úpost_init_awq_exllama_modulesrá   Ï  sƒ   € ð �iÑ ¤N×$6Ñ$6Ò6Ý@á! %Ó(ˆð €Lð 
˜	Ñ	"¤n×&8Ñ&8Ò	8ÝDá#ØØ(¨Ñ9Ø)Ð*:Ñ;ô
ˆð €Lô Ð9¸.ÈÑ:SÐ9TÐUÓVÐVrI   c                 ó"   — ddl m}  || «      } | S )zl
    Runs post init for IPEX layers which performs:
        - Weights packing, reordering and repacking
    r   )Úipex_post_init)rr   rã   )r?   rã   s     rH   Úpost_init_awq_ipex_modulesrä   è  s   € õ <á˜5Ó!€Eà€LrI   )NNNF)$Ú__doc__rË   Ú	packagingr   Úactivationsr   Úmodeling_utilsr   Úutilsr   r   r	   r
   Úutils.quantization_configr   r   r   r   r;   Útorch.nnrv   Ú
get_loggerrŒ   r¬   r�   r6   r>   Úboolr€   r“   r±   rª   r«   r®   rá   rä   rš   rI   rH   ú<module>rî      s4  ðñ >ã å å  Ý ,ß YÓ Y÷ó ñ ÔÛÝà	ˆ×	Ñ	˜HÓ	%€ò >Ú4ÚLØñ	ò >Ú!ÚLØØñò >Ú4ÚLØñ	ò >Ú4ÚLØñ	ñ)Ð ð:  °VÑ<Ø$¸/ÑJØ°ÑAØ¨iÑ8Ø¨wÑ7Ø°?ÑCØ °fÑ=Ø °oÑFñ	Ð òð&  ØØØñf$ð 
óf$òR&!òR=ò@ò.&*òR\!ò~ó2
rI   