+
    &j9                         ^ RI t ^ RIHtHtHt ^ RIHt ^ RIH	t	 ^ RI
Ht R tRRRRR	R
R/R R lllt ! R R]	4      t ! R R]	4      t ! R R]	4      tR# )    N)CallableOptionalUnion)Module)tree_map_with_pathc                 Z    R RRRRRRR/pW0,          w  rET;'       g    TT;'       g    T3# )affinemxfp4nvfp4mxfp8)@      )    r   )   r   )r       )mode
group_sizebitsmode_defaultsdefault_group_sizedefault_bitss   &&&   o/Users/jameslopez/projects/CWCArchive/cwc-podcast/.venv/lib/python3.14/site-packages/mlx/nn/layers/quantized.py_defaults_for_moder      sG    '	M (5':$+++T-A-A\AA    r   r	   quantize_inputFclass_predicatec                    V ^8  d   QhR\         R\        R\        R\        R\        R\        \
        \        \         .\        \        \        3,          3,          ,          /# )   modelr   r   r   r   r   )r   intstrboolr   r   r   dict)formats   "r   __annotate__r&      sh     I! I!I!I! I!
 I! I! hV}eD$J6G'GHII!r   c                  aaaaa S;'       g    R oVVVVV3R lpV P                  4       p\        Wg\        P                  R7      pV P	                  V4       R# )a[  Quantize the sub-modules of a module according to a predicate.

By default all layers that define a ``to_quantized()`` method will be
quantized. Both :obj:`Linear` and :obj:`Embedding` layers will be
quantized. The module is updated in-place.

Note:
    ``quantize_input=True`` is only supported for ``"nvfp4"`` and ``"mxfp8"``
    modes and :obj:`Linear` layers.

Args:
    model (mlx.nn.Module): The model whose leaf modules may be quantized.
    group_size (Optional[int]): The quantization group size (see
       :func:`mlx.core.quantize`). Default: ``None``.
    bits (Optional[int]): The number of bits per parameter (see
       :func:`mlx.core.quantize`). Default: ``None``.
    mode (str): The quantization method to use (see
       :func:`mlx.core.quantize`). Default: ``"affine"``.
    quantize_input (bool): Whether to quantize activations. Default: ``False``.
    class_predicate (Optional[Callable]): A callable which receives the
       :obj:`Module` path and :obj:`Module` itself and returns ``True`` or a
       dict of params for ``to_quantized`` if it should be quantized and
       ``False`` otherwise. If ``None``, then all layers that define a
       ``to_quantized()`` method are quantized. Default: ``None``.

Example:
    Weight only quantization for all layers that define a ``to_quantized()`` method:

    >>> import mlx.nn as nn
    >>> nn.quantize(model, group_size=64, bits=4, mode="affine")

    Weight and input quantization for all linear layers:

    >>> predicate = lambda p, m: isinstance(m, nn.Linear)
    >>> nn.quantize(model, mode="nvfp4", quantize_input=True, class_predicate=predicate)
c                     \        VR 4      # )to_quantized)hasattr)_ms   &&r   <lambda>quantize.<locals>.<lambda>C   s    wq.7Qr   c                   < S! W4      ;p'       d   \        VR 4      '       d   \        V\        4      '       d(   RSRSRS/pS'       d   SVR&   VP                  ! R/ VB # \        V\        4      '       d:   RV9   d!   VR,          '       g   VP                  R4       VP                  ! R/ VB # \        R4      h\        R\        V4       24      hV# )r)   r   r   r   r   zZ``class_predicate`` must return a bool or a dict of parameters to pass to ``to_quantized``z!Unable to quantize model of type r   )r*   
isinstancer#   r)   r$   pop
ValueErrortype)	pathr,   bool_or_paramskwargsr   r   r   r   r   s	   &&  r   _maybe_quantize!quantize.<locals>._maybe_quantizeE   s    ,T55>5q.))nd33*JfdSF%3A/0>>3F3355(N:N(E E '**+;<>>;N;;$O 
 !#DT!WI!NOOHr   )is_leafN)leaf_modulesr   r   	is_moduleupdate_modules)r    r   r   r   r   r   r7   leavess   &ffddd  r   quantizer>      sN    Z &RR*QO 0 !FAQAQRF	 r   c                   x   a a ] tR t^bt oRtR
V3R lV 3R llltR tR tR t]	R
V3R lR ll4       t
R	tVtV ;t# )QuantizedEmbeddinga   The same as :obj:`Embedding` but with a  quantized weight matrix.

:obj:`QuantizedEmbedding` also provides a :meth:`from_embedding`
classmethod to convert embedding layers to :obj:`QuantizedEmbedding`
layers.

Args:
    num_embeddings (int): How many possible discrete tokens can we embed.
       Usually called the vocabulary size.
    dims (int): The dimensionality of the embeddings.
    group_size (Optional[int]): The group size to use for the quantized
        weight. See :func:`~mlx.core.quantize`. Default: ``None``.
    bits (Optional[int]): The bit width to use for the quantized weight.
        See :func:`~mlx.core.quantize`. Default: ``None``.
    mode (str): The quantization method to use (see
       :func:`mlx.core.quantize`). Default: ``"affine"``.
c          
      8   < V ^8  d   QhRS[ RS[ RS[ RS[ RS[/# )r   num_embeddingsdimsr   r   r   r!   r"   )r%   __classdict__s   "r   r&   QuantizedEmbedding.__annotate__u   s=        	
  r   c                  < \         S	V `  4        \        WSV4      w  V n        V n        WPn        \        P                  ! ^V,          4      p\        P                  P                  W3VR7      p\        P                  ! WsWER7      vV n        V n        pV'       d
   V^ ,          MRV n        Wn        W n        V P#                  4        R# )   )shapescaler   N)super__init__r   r   r   r   mathsqrtmxrandomnormalr>   weightscalesbiasesrB   rC   freeze)
selfrB   rC   r   r   r   rJ   rS   rU   	__class__s
   &&&&&&   r   rM   QuantizedEmbedding.__init__u   s     	 &8$%O"	 		!d(#!!(>e!L,.KK-
)T[6 $*fQit,	 	r   c           	         V P                  R 4      p\        P                  ! V R,          V,          V R,          V,          Ve	   W!,          MRV P                  V P                  V P
                  R7      # )rU   rS   rT   N)rT   rU   r   r   r   )getrP   
dequantizer   r   r   )rW   xrU   s   && r   __call__QuantizedEmbedding.__call__   sZ    (#}}N1>!$ & 269
 	
r   c                    \         P                  ! VV R,          V R,          V P                  R4      RV P                  V P                  V P
                  R7      # )z
Call the quantized embedding layer as a quantized linear layer.

Use this for example when input embedding and output projection
weights are tied.
rS   rT   rU   TrT   rU   	transposer   r   r   rP   quantized_matmulr[   r   r   r   rW   r]   s   &&r   	as_linearQuantizedEmbedding.as_linear   sL     ""N>88H%	
 		
r   c           	         V P                    R V P                   RV P                   RV P                   RV P                   2	# )z, , group_size=, bits=, mode=)rB   rC   r   r   r   rW   s   &r   _extra_reprQuantizedEmbedding._extra_repr   sF    ""#2dii[ 1//*'$))GDII;P	
r   c                2   < V ^8  d   QhRS[ RS[RS[RS[/# )r   embedding_layerr   r   r   r   r!   r"   )r%   rE   s   "r   r&   rF      s3        	
 r   c                    VP                   P                  w  rVV ! WVW#VR7      p\        P                  ! VP                   VVVR7      vVn         Vn        pV'       d   V^ ,          Vn        V# RVn        V# )zHCreate a :obj:`QuantizedEmbedding` layer from an :obj:`Embedding` layer.rK   N)rS   rI   rP   r>   rT   rU   )	clsrp   r   r   r   embedding_dimsrC   qlrU   s	   &&&&&    r   from_embedding!QuantizedEmbedding.from_embedding   ss      /55;;zdC(*""	)
%	29v "(F1I		 .2		r   )rU   r   rC   r   r   rB   rT   rS   NNr	   )__name__
__module____qualname____firstlineno____doc__rM   r^   rf   rm   classmethodrv   __static_attributes____classdictcell____classcell__rX   rE   s   @@r   r@   r@   b   sA     $ 6	

$
    r   r@   c                   r   a a ] tR t^t oRtR	V3R lV 3R llltR tR t]R
V3R lR ll4       t	Rt
VtV ;t# )QuantizedLineara  Applies an affine transformation to the input using a quantized weight matrix.

It is the quantized equivalent of :class:`mlx.nn.Linear`. For now its
parameters are frozen and will not be included in any gradient computation
but this will probably change in the future.

:obj:`QuantizedLinear` also provides a classmethod :meth:`from_linear` to
convert linear layers to :obj:`QuantizedLinear` layers.

Args:
    input_dims (int): The dimensionality of the input features.
    output_dims (int): The dimensionality of the output features.
    bias (bool, optional): If set to ``False`` then the layer will not use
        a bias. Default: ``True``.
    group_size (Optional[int]): The group size to use for the quantized
        weight. See :func:`~mlx.core.quantize`. Default: ``None``.
    bits (Optional[int]): The bit width to use for the quantized weight.
        See :func:`~mlx.core.quantize`. Default: ``None``.
    mode (str): The quantization method to use (see
       :func:`mlx.core.quantize`). Default: ``"affine"``.
c                >   < V ^8  d   QhRS[ RS[ RS[RS[ RS[ RS[/# )r   
input_dimsoutput_dimsbiasr   r   r   )r!   r#   r"   )r%   rE   s   "r   r&   QuantizedLinear.__annotate__   sG            	 
      r   c                  < \         S
V `  4        \        WdV4      w  V n        V n        W`n        \        P                  ! ^V,          4      p\        P                  P                  V) VW!3R7      p\        P                  ! WWVR7      vV n        V n        p	V	'       d
   V	^ ,          MRV n        V'       d   \        P                  ! V34      V n        V P#                  4        R# )rH   lowhighrI   rK   N)rL   rM   r   r   r   r   rN   rO   rP   rQ   uniformr>   rS   rT   rU   zerosr   rV   )rW   r   r   r   r   r   r   rJ   rS   rU   rX   s   &&&&&&&   r   rM   QuantizedLinear.__init__   s     	 &8$%O"	 		!j.)""+ # 

 -/KK-
)T[6 $*fQit +0DI 	r   c                    V P                   P                  w  rV^ ,          V P                  ,          pRV RV RRV 9    RV P                   RV P                   RV P                   2# )r   input_dims=, output_dims=z, bias=r   ri   rj   rk   )rS   rI   r   r   r   rW   out_dimsin_dimss   &  r   rm   QuantizedLinear._extra_repr  sm     KK--R<DII-'.
'&D.AQ R//*'$))GDII;P	
r   c                    \         P                  ! VV R ,          V R,          V P                  R4      RV P                  V P                  V P
                  R7      pRV 9   d   WR,          ,           pV# )rS   rT   rU   Tra   r   rc   re   s   &&r   r^   QuantizedLinear.__call__	  sa    N>88H%	
 T>L Ar   c                2   < V ^8  d   QhRS[ RS[RS[RS[/# r   linear_layerr   r   r   rq   )r%   rE   s   "r   r&   r     s3        	
 r   c           	        VP                   P                  w  rVV ! WeRW#VR7      p\        P                  ! VP                   VVVR7      vVn         Vn        pV'       d
   V^ ,          MRVn        RV9   d   VP                  Vn        V# )zACreate a :obj:`QuantizedLinear` layer from a :obj:`Linear` layer.FrK   Nr   )rS   rI   rP   r>   rT   rU   r   )	rs   r   r   r   r   r   r   ru   rU   s	   &&&&&    r   from_linearQuantizedLinear.from_linear  s~     #/"5"5";";%M(*	)
%	29v "(F1IT	\!"''BG	r   )r   rU   r   r   r   rT   rS   )TNNr	   rx   )ry   rz   r{   r|   r}   rM   rm   r^   r~   r   r   r   r   r   s   @@r   r   r      s=     ,   D
    r   r   c                      a a ] tR tRt oRtRV3R lV 3R llltR tR tR tV3R lV 3R	 llt	R
 t
]RV3R lR ll4       tRtVtV ;t# )QQLineari1  a  Quantizes the input and applies an affine transformation using quantized weights.

Two use cases are supported:

1) **Eval**:  The weights are frozen and stored in quantized form together with
   their scales (``self.weight`` is quantized and ``self.scales`` is provided).
2) **Train**: The weights are stored in higher precision and are quantized on
     the fly during computation so that gradients with respect to the weights
     can be computed.

To switch between the two cases, use ``layer.eval()`` and ``layer.train()`` respectively.

Compared to the :class:`mlx.nn.QuantizedLinear` layer, this layer
quantizes the input as well and includes weights in gradient computations.

:obj:`QQLinear` also provides the class method :meth:`from_linear` to
convert :class:`mlx.nn.Linear` layers to :obj:`QQLinear` layers.

Note: This layer does not support a bias term yet.

Args:
    input_dims (int): The dimensionality of the input features.
    output_dims (int): The dimensionality of the output features.
    group_size (Optional[int]): The group size to use for the quantized weight.
        See :func:`~mlx.core.quantize`. Default: ``None``.
    bits (Optional[int]): The bit width to use for the quantized weight.
        See :func:`~mlx.core.quantize`. Default: ``None``.
    mode (Optional[str]): The quantization method to use (see
        :func:`mlx.core.quantize`). Currently, only ``"nvfp4"`` and ``"mxfp8"``
        are supported. Default: ``"nvfp4"``.
c          
      8   < V ^8  d   QhRS[ RS[ RS[ RS[ RS[/# )r   r   r   r   r   r   rD   )r%   rE   s   "r   r&   QQLinear.__annotate__R  s=            	 
    r   c                   < \         SV `  4        \        WSV4      w  V n        V n        WPn        \        P                  ! ^V,          4      p\        P                  P                  V) VW!3R7      V n        RV n        R# )rH   r   FN)rL   rM   r   r   r   r   rN   rO   rP   rQ   r   rS   
_quantized)rW   r   r   r   r   r   rJ   rX   s   &&&&&& r   rM   QQLinear.__init__R  sp     	 &8$%O"			!j.)ii''+ ( 

  r   c           
        V P                   P                  w  rV P                   P                  \        P                  8X  d   V^ ,          V P
                  ,          pRV RV RV P                   RV P
                   RV P                   2
# )r   r   r   ri   rj   rk   )rS   rI   dtyperP   uint32r   r   r   r   s   &  r   rm   QQLinear._extra_reprh  sw     KK--;;		)|		1G'.
 ;//*'$))GDII;P	
r   c                    V P                   '       gY   \        P                  ! V P                  V P                  V P
                  V P                  R 7      w  V n        V n        RV n         R# R# )rK   TN)r   rP   r>   rS   r   r   r   rT   rl   s   &r   r>   QQLinear.quantizeq  sL    '){{		YY	($DK #DO r   c                   V P                   '       dm   \        P                  ! V P                  V P                  V P
                  V P                  V P                  R 7      V n        V P                  R4       RV n         R# R# )rT   r   r   r   rT   FN)	r   rP   r\   rS   rT   r   r   r   __delattr__rl   s   &r   r\   QQLinear.dequantize{  sZ    ???--{{??YYYYDK X&#DO r   c                    < V ^8  d   QhRS[ /# )r   r   )r#   )r%   rE   s   "r   r&   r     s      t r   c                   < \         SV `  V4       V P                  '       d   V P                  4        R # V P	                  4        R # )N)rL   _set_training_mode	_trainingr\   r>   )rW   r   rX   s   &&r   r   QQLinear._set_training_mode  s,    "4(>>>OOMMOr   c           	         \         P                  ! VV R ,          V P                  R4      V P                  V P                  V P
                  R7      pV# )rS   rT   r   )rP   qqmmr[   r   r   r   re   s   &&r   r^   QQLinear.__call__  sB    GGN88H%
 r   c                2   < V ^8  d   QhRS[ RS[RS[RS[/# r   rq   )r%   rE   s   "r   r&   r     s3        	
 r   c                    VP                   P                  w  rVVP                  R4      e   \        R4      hV ! WeW#VR7      pVP                   Vn         VP	                  VP
                  4       V# )z:Create a :obj:`QQLinear` layer from a :obj:`Linear` layer.r   z#QQLinear does not support bias yet.rK   )rS   rI   r[   NotImplementedErrortraintraining)rs   r   r   r   r   r   r   ru   s   &&&&&   r   r   QQLinear.from_linear  sg     #/"5"5";";F#/%&KLL*F ''	
&&'	r   )r   r   r   r   rT   rS   )NNr   )ry   rz   r{   r|   r}   rM   rm   r>   r\   r   r^   r~   r   r   r   r   r   s   @@r   r   r   1  sQ     @   ,
#
$ 	    r   r   )NN)rN   typingr   r   r   mlx.corecorerP   mlx.nn.layers.baser   	mlx.utilsr   r   r>   r@   r   r   r   r   r   <module>r      s{     , ,  % (BI!
 I! !I! MQI! I!Xc cLff fRyv yr   