o
    ۷i                     @  s   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 G dd dZG d	d
 d
ZG dd dZeG dd dZG dd dZdS )zBase hook classes for model forward interception.

This module provides the foundational hook mechanism that allows intercepting
and modifying model forward passes without invasive changes to model code.
    )annotations)Callable)	dataclass)AnyNc                   @  s   e Zd ZdZdddZdS )	BaseStatez%Base class for hook state containers.returnNonec                 C  s   d S N selfr
   r
   T/home/ubuntu/vllm_env/lib/python3.10/site-packages/vllm_omni/diffusion/hooks/base.pyreset   s   zBaseState.resetNr   r   )__name__
__module____qualname____doc__r   r
   r
   r
   r   r      s    r   c                   @  s8   e Zd ZdZdddZdd
dZdddZdddZdS )StateManagerz(Manage per-context hook state instances.	state_clsCallable[[], BaseState]c                 C  s   || _ i | _d| _d S Ndefault)
_state_cls_states_context)r   r   r
   r
   r   __init__   s   
zStateManager.__init__namestrr   r   c                 C  s   |pd| _ d S r   )r   r   r   r
   r
   r   set_context!      zStateManager.set_contextr   c                 C  s(   | j | jvr|  | j| j < | j| j  S r	   )r   r   r   r   r
   r
   r   	get_state$   s   zStateManager.get_statec                 C  s   | j   d S r	   )r   clearr   r
   r
   r   r   )   r!   zStateManager.resetN)r   r   r   r   r   r   )r   r   r   )r   r   r   r   r   r    r"   r   r
   r
   r
   r   r      s    


r   c                   @  sB   e Zd ZdZdddZdddZdddZdddZdddZdS )	ModelHooka  Base class for model hooks that can override a module's forward.

    Hooks can intercept the forward pass at two points:
    - pre_forward: Called before the original forward, can modify args/kwargs
    - post_forward: Called after the original forward, can modify output

    Subclasses can override either or both methods. The default implementations
    pass through args/kwargs/output unchanged.

    For more complex behavior, override new_forward to completely replace
    the forward logic.
    module	nn.Moduler   c                 C     |S )zInitialize the hook when it's registered to a module.

        Args:
            module: The module this hook is being attached to.

        Returns:
            The module (possibly modified).
        r
   r   r&   r
   r
   r   initialize_hook;      	zModelHook.initialize_hookargsr   kwargstuple[tuple, dict]c                 O  s   ||fS )a*  Called before the module's forward pass.

        Args:
            module: The module being called.
            *args: Positional arguments to forward.
            **kwargs: Keyword arguments to forward.

        Returns:
            Tuple of (args, kwargs) to pass to the forward method.
        r
   )r   r&   r,   r-   r
   r
   r   pre_forwardF   s   zModelHook.pre_forwardoutputc                 C  s   |S )zCalled after the module's forward pass.

        Args:
            module: The module that was called.
            output: The output from the forward method.

        Returns:
            The (possibly modified) output.
        r
   )r   r&   r0   r
   r
   r   post_forwardS   s   
zModelHook.post_forwardc                 O  s8   | j |g|R i |\}}|j|i |}| ||S )a  Override the module's forward pass completely.

        The default implementation calls pre_forward, then the original forward,
        then post_forward. Override this method for more complex behavior.

        Args:
            module: The module being called.
            *args: Positional arguments to forward.
            **kwargs: Keyword arguments to forward.

        Returns:
            The output of the forward pass.
        )r/   _original_forwardr1   )r   r&   r,   r-   r0   r
   r
   r   new_forward_   s   zModelHook.new_forwardc                 C  r(   )zReset any state associated with this hook.

        Args:
            module: The module this hook is attached to.

        Returns:
            The module.
        r
   r)   r
   r
   r   reset_stateq   r+   zModelHook.reset_stateN)r&   r'   r   r'   )r&   r'   r,   r   r-   r   r   r.   )r&   r'   r0   r   r   r   )r&   r'   r,   r   r-   r   r   r   )	r   r   r   r   r*   r/   r1   r3   r4   r
   r
   r
   r   r%   -   s    



r%   c                   @  s$   e Zd ZU dZded< d
ddZd	S )_WrappedForwardz>Wrapper that intercepts forward calls and dispatches to hooks.r'   r&   r,   r   r-   c                 O  s>   t | jdd }|d u s|js| jj|i |S |j|i |S )N_hook_registry)getattrr&   _hooksr2   dispatch)r   r,   r-   registryr
   r
   r   __call__   s   z_WrappedForward.__call__N)r,   r   r-   r   )r   r   r   r   __annotations__r;   r
   r
   r
   r   r5   }   s   
 r5   c                   @  sZ   e Zd ZdZdddZedddZdddZd ddZd!ddZ	d"ddZ
d ddZdS )#HookRegistryzRegistry of hooks attached to a module.

    Manages multiple hooks that can intercept a module's forward pass.
    Hooks are called in sorted order by name for determinism.
    r&   r'   c                 C  s   || _ i | _d S r	   )r&   r8   r)   r
   r
   r   r      s   
zHookRegistry.__init__r   c                 C  sH   t |dd}|du r"| |}t|d| t|ds"|j|_t||_|S )zGet existing registry or create a new one for the module.

        Args:
            module: The module to get/create a registry for.

        Returns:
            The HookRegistry for this module.
        r6   Nr2   )r7   setattrhasattrforwardr2   r5   )clsr&   r:   r
   r
   r   get_or_create   s   


zHookRegistry.get_or_creater   r   hookr%   r   c                 C  s   | | j || j|< dS )zRegister a hook with the given name.

        Args:
            name: Unique name for this hook.
            hook: The hook instance to register.
        N)r*   r&   r8   r   r   rC   r
   r
   r   register_hook   s   zHookRegistry.register_hookc                 C  s   || j v r| j |= dS dS )z`Remove a hook by name.

        Args:
            name: The name of the hook to remove.
        N)r8   r   r
   r
   r   remove_hook   s   
zHookRegistry.remove_hookModelHook | Nonec                 C  s   | j |S )zGet a hook by name.

        Args:
            name: The name of the hook.

        Returns:
            The hook if found, None otherwise.
        )r8   getr   r
   r
   r   get_hook   s   	zHookRegistry.get_hookr,   r   r-   c                 O  s   | j s| jj|i |S t| j dkr)tt| j  }|j| jg|R i |S t| j 	 dd d}|D ]\}}|j
| jg|R i |\}}q6| jj|i |}t|D ]\}}|| j|}qW|S )a  Dispatch a forward call through registered hooks.

        Currently supports a single active hook. Multiple hooks are called
        in sorted order by name, with each hook's output passed to the next.

        Args:
            *args: Positional arguments to forward.
            **kwargs: Keyword arguments to forward.

        Returns:
            The output of the forward pass.
           c                 S  s   | d S )Nr   r
   )xr
   r
   r   <lambda>   s    z'HookRegistry.dispatch.<locals>.<lambda>)key)r8   r&   r2   lennextitervaluesr3   sorteditemsr/   reversedr1   )r   r,   r-   rC   sorted_hooks_r0   r
   r
   r   r9      s    zHookRegistry.dispatchc                 C  s(   | j |}|dur|| j dS dS )zfReset a hook's state by name.

        Args:
            name: The name of the hook to reset.
        N)r8   rH   r4   r&   rD   r
   r
   r   
reset_hook   s   zHookRegistry.reset_hookN)r&   r'   )r&   r'   r   r=   )r   r   rC   r%   r   r   r$   )r   r   r   rG   )r,   r   r-   r   r   r   )r   r   r   r   r   classmethodrB   rE   rF   rI   r9   rW   r
   r
   r
   r   r=      s    




	
&r=   )r   
__future__r   collections.abcr   dataclassesr   typingr   torch.nnnnr   r   r%   r5   r=   r
   r
   r
   r   <module>   s   P