
    Nj                     "   d Z ddlZddlZddlZddlmZ  ej                  e      ZddhZ	d Z
dej                  fdZd Zd	ej                  d
ee   dej                  fdZd	ej                  d
ee   ddfdZd	ej                  d
ee   ddfdZy)as  
Dynamic int8 quantization for pocket-tts.

Uses torchao if available (torch 2.10+ with C++ extensions), otherwise
falls back to torch.ao.quantization (deprecated but functional on torch 2.5-2.9).

Quantizes attention (Q/K/V/output projections) and FFN (linear1/linear2) layers
in the FlowLM transformer. The flow matching network and Mimi VAE decoder
remain in float32.
    N	attentionffnc                      	 ddl } | j                  j                  d      yddl}t	        |d      st        |dd      sy	 y# t        $ r Y yw xY w)zDetect the best available quantization backend.

    Returns "torchao" if torchao is installed with working C++ extensions,
    otherwise returns "torch.ao".
    r   Ntorchaoztorch.ao_C_SKIPPED_CPP_EXTENSIONSF)importlib.utilutil	find_specr   hasattrgetattrImportError)	importlibr   s     h/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/pocket_tts/quantization.py_get_backendr      sa    >>##I.67D!:SUZ)[ *\   s   A A 	AAmodulec                 0    ddl m}m}  ||  |              y)z.Apply int8 dynamic quantization using torchao.r   )%Int8DynamicActivationInt8WeightConfig	quantize_N)torchao.quantizationr   r   )r   r   r   s      r   _quantize_module_torchaor   -   s    Uf;=>    c                      t        j                         dv r dt        j                  j                  _        yt        j                  j                  j
                  dk(  r dt        j                  j                  _        yy)zKSet the quantization engine for torch.ao (QNNPACK for ARM, FBGEMM for x86).)arm64aarch64qnnpacknonefbgemmN)platformmachinetorchbackends	quantizedengine r   r   _ensure_quantization_enginer&   4   sU    11*3  '		!	!	(	(F	2*2  ' 
3r   flow_lmquantize_groupsreturnc                     |st         j                  d       | S t               }t         j                  d|       |dk(  rt        | |       | S t	        | |       | S )a  
    Apply dynamic int8 quantization to the specified layer groups of a FlowLM model.

    Automatically selects the best available backend:
    - torchao (torch 2.10+): optimized C++ kernels, faster on both ARM and x86
    - torch.ao (torch 2.5-2.9): deprecated but functional fallback

    Args:
        flow_lm: The FlowLM model (model.flow_lm)
        quantize_groups: Set of group keys to quantize.
            Valid keys: "attention", "ffn", "flow_net"

    Returns:
        The quantized model (modified in-place).
    z<No quantization groups specified, returning model unchanged.zUsing quantization backend: %sr   )loggerinfor   _apply_torchao_apply_torch_ao)r'   r(   backends      r   apply_dynamic_int8r0   <   sY      RSnG
KK0':)w0 N 	1Nr   c                 x   d|v rt        | j                         | j                  j                  D ]  }d|v rt        |j                         d|v s!t        j                  |j                        }t        j                  |j                        }t        |       t        |       |d   |_        |d   |_         y)z)Apply quantization using torchao backend.flow_netr   r   r   N)	r   r2   transformerlayers	self_attnnn
Sequentiallinear1linear2)r'   r(   layerwrapper1wrapper2s        r   r-   r-   [   s    _$ !1!12$$++/)$U__5O#}}U]]3H}}U]]3H$X.$X.$QKEM$QKEM ,r   c                 t   ddl m} t                d|v r3 || j                  t        j
                  ht        j                  d       | j                  j                  D ]  }d|v r3 ||j                  t        j
                  ht        j                  d       d|v s? |t	        j                  |j                        t        j
                  ht        j                        d   |_         |t	        j                  |j                        t        j
                  ht        j                        d   |_         y	)
z@Apply quantization using deprecated torch.ao backend (fallback).r   )quantize_dynamicr2   T)dtypeinplacer   r   )r?   N)torch.ao.quantizationr>   r&   r2   r6   Linearr!   qint8r3   r4   r5   r7   r8   r9   )r'   r(   r>   r:   s       r   r.   r.   m   s    6!_$))BII;ekkSWX$$++/)U__ryykVZ[O#,emm,ryykEM -emm,ryykEM ,r   )__doc__loggingr   r!   torch.nnr6   	getLogger__name__r+   RECOMMENDED_CONFIGr   Moduler   r&   setstrr0   r-   r.   r%   r   r   <module>rM      s   	    			8	$ "5) *?RYY ?3		 CH  >(BII (C (T ($RYY S d r   