o
    s::j"                     @  sN   d dl mZ d dlmZmZ d dlZd dlmZ	 d dl
mZ G dd dZdS )    )annotations)AnyIteratorN)builder)	Parameterc                   @  s   e Zd ZdZd<d=ddZed>d	d
Zd?ddZd@ddZdAddZ	dAddZ
dBdCddZ	dDdEd#d$ZdFd&d'ZdGd)d*ZdFd+d,ZdHdId-d.ZdHdJd0d1Z	dBdKd5d6ZdLd8d9ZdMd:d;ZdS )NModulea  Base class for all onnxscript modules, mirroring PyTorch's nn.Module.

    Subclasses define ``forward()`` to build ONNX subgraphs. Child modules
    and parameters are registered automatically via ``__setattr__``.
    Because ``Parameter`` subclasses ``ir.Value``, parameters like
    ``self.weight`` can be passed directly to ONNX ops.

    Example::

        class Linear(onnxscript.nn.Module):
            def __init__(self, in_features, out_features, bias=True, name=None):
                super().__init__(name)
                self.weight = Parameter([out_features, in_features], name="weight")
                if bias:
                    self.bias = Parameter([out_features], name="bias")
                else:
                    self.bias = None

            def forward(self, op, x):
                w_t = op.Transpose(self.weight, perm=[1, 0])
                result = op.MatMul(x, w_t)
                if self.bias is not None:
                    result = op.Add(result, self.bias)
                return result
    Nname
str | NonereturnNonec                 C  s.   t | d| t | di  t | di  d S )N_name_parameters_modulesobject__setattr__selfr    r   \/home/nk/hobo-godmode/plappi-mvp/.venv/lib/python3.10/site-packages/onnxscript/nn/_module.py__init__)   s   zModule.__init__c                 C  s   | j S N)r   r   r   r   r   r   0   s   zModule.namestrc                 C  s   t | d| dS )zLSet the module name. Subclasses may override to propagate names to children.r   Nr   r   r   r   r   	_set_name4   s   zModule._set_namevaluer   c                 C  s   t |tr|jd u r||_|| j|< t| || d S t |tr8|jd u r*|| || j	|< t| || d S t| || d S r   )

isinstancer   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   8   s   






zModule.__setattr__op_builder.OpBuilderargskwargsc           	      O  sr   |j }| jpd}t| j}||| z | j D ]}|| q| j|g|R i |}W |	  |S |	  w )N )
r   r   type__qualname__push_moduler   values_realizeforward
pop_module)	r   r   r   r    r   module_name
class_nameparamresultr   r   r   __call__I   s   


zModule.__call__c                 O  s   t t| j d)zDefine the computation performed by this module.

        Must be overridden by subclasses. Receives an ``OpBuilder`` as the
        first argument so that ONNX ops can be called as ``op.MatMul(x, w)``.
        z must implement forward())NotImplementedErrorr"   __name__)r   r   r   r    r   r   r   r'   X   s   zModule.forwardTrecurseboolIterator[Parameter]c                 c  s@    | j  E dH  |r| j D ]}|jddE dH  qdS dS )z*Return an iterator over module parameters.NT)r0   )r   r%   r   
parameters)r   r0   moduler   r   r   r3   d   s   zModule.parametersr!   prefixIterator[tuple[str, Parameter]]c           	      c  s    | j  D ]\}}|r| d| n|}||fV  q|r<| j D ]\}}|r/| d| n|}|j|ddE dH  q"dS dS )zLReturn an iterator over module parameters, yielding (name, Parameter) pairs..T)r5   r0   N)r   itemsr   named_parameters)	r   r5   r0   r   r+   	full_namemod_namer4   
sub_prefixr   r   r   r9   k   s   zModule.named_parametersIterator[Module]c                 c      | j  E dH  dS )z0Return an iterator over immediate child modules.N)r   r%   r   r   r   r   childrenw      zModule.childrenIterator[tuple[str, Module]]c                 c  r>   )zOReturn an iterator over immediate child modules, yielding (name, Module) pairs.N)r   r8   r   r   r   r   named_children{   r@   zModule.named_childrenc                 c  s*    | V  | j  D ]	}| E dH  q	dS )zAReturn an iterator over all modules in the tree (including self).N)r   r%   modules)r   r4   r   r   r   rC      s
   zModule.modulesc                 c  sL    || fV  | j  D ]\}}|r| d| n|}|j|dE dH  qdS )zCReturn an iterator over all modules, yielding (name, Module) pairs.r7   r5   N)r   r8   named_modules)r   r5   r   r4   r<   r   r   r   rE      s   
zModule.named_modules#dict[str, ir.TensorProtocol | None]c           	      C  sx   i }| j  D ]\}}|r| d| n|}|j||< q| j D ]\}}|r.| d| n|}||j|d q!|S )a!  Return a dictionary mapping parameter names to their tensor data.

        Mirrors ``torch.nn.Module.state_dict()``. Keys use dot-separated
        hierarchical names (e.g. ``"layer1.weight"``). Values are the
        ``const_value`` of each parameter (``None`` if uninitialized).
        r7   rD   )r   r8   const_valuer   update
state_dict)	r   r5   r,   r   r+   r:   r;   r4   r<   r   r   r   rI      s   zModule.state_dictrI   dict[str, ir.TensorProtocol]strictc                 C  s   | j |d|d dS )a  Load parameter data from a state dictionary.

        Mirrors ``torch.nn.Module.load_state_dict()``. Sets ``const_value``
        on each matching parameter.

        Args:
            state_dict: Mapping of parameter names to tensor data.
            strict: If ``True`` (default), raises ``KeyError`` for missing
                keys and ``ValueError`` for unexpected keys.
        r!   r5   rK   N)_load_state_dict_recursive)r   rI   rK   r   r   r   load_state_dict   s   zModule.load_state_dictset[str]c                 C  s   t  }| j D ]'\}}|r| d| n|}||v r&|| |_|| q|r/td|q| j D ]\}}	|rB| d| n|}
||	j||
|dO }q5|rf|dkrft | | }|rft	d| |S )z;Recursively load state and return the set of consumed keys.r7   zMissing key in state_dict: rL   r!   zUnexpected keys in state_dict: )
setr   r8   rG   addKeyErrorr   rM   keys
ValueError)r   rI   r5   rK   consumedr   r+   r:   r;   r4   r<   
unexpectedr   r   r   rM      s&   

z!Module._load_state_dict_recursivec                 C  s   t | j dg}| j D ]\}}t|dd}|d| d|  q| j D ]\}}|d| d| q+|d d|S )N(
z
  z  (z): ))	r"   r/   r   r8   reprreplaceappendr   join)r   linesr   r4   mod_reprr+   r   r   r   __repr__   s   

zModule.__repr__r   )r   r	   r
   r   )r
   r	   )r   r   r
   r   )r   r   r   r   r
   r   )r   r   r   r   r    r   r
   r   )T)r0   r1   r
   r2   )r!   T)r5   r   r0   r1   r
   r6   )r
   r=   )r
   rA   )r!   )r5   r   r
   rA   )r5   r   r
   rF   )rI   rJ   rK   r1   r
   r   )rI   rJ   r5   r   rK   r1   r
   rO   )r
   r   )r/   
__module__r#   __doc__r   propertyr   r   r   r-   r'   r3   r9   r?   rB   rC   rE   rI   rN   rM   r`   r   r   r   r   r      s*    







r   )
__future__r   typingr   r   onnx_irironnxscript._internalr   _builderonnxscript.nn._parameterr   r   r   r   r   r   <module>   s   