a
    d-                     @   s  d Z ddlZddlmZmZ ddlZddlmZ ddlm  m	Z
 ddlmZ ddlmZ deeef eeeef  eejdd	d
ZG dd dejZdeeef eeef dddZG dd dejZdeee dddZeeejejejdddZG dd dejZdS )zf Relative position embedding modules and functions

Hacked together by / Copyright 2022 Ross Wightman
    N)OptionalTuple   )Mlp)trunc_normal_F)q_sizek_sizeclass_tokenreturnc           
   	   C   s  |d u rt t t | d t | d gd}|d d d d d f |d d d d d f  }|ddd}d| d  d d| d  d  d }nt t t | d t | d gd}t t t |d t |d gd}|d d d d d f |d d d d d f  }|ddd}| d |d  d | d | d  d  d }t j|ddddd\}}	|rt	|	g d}	|d |	ddd f< |d |	dd df< |d |	d	< |	
 S )
Nr   r         T)Zreturn_inverseZdim)r   r   r   r   r   r   )torchstackmeshgridarangeflattenpermuteuniqueviewFpad
contiguous)
r   r   r	   ZcoordsZrelative_coordsnum_relative_distanceZq_coordsZk_coords_relative_position_index r   b/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/timm/layers/pos_embed_rel.pygen_relative_position_index   sL    ,&,,r   c                       sP   e Zd ZdZd fdd	Zdd Zejddd	Zde	ej dddZ
  ZS )
RelPosBiasz_ Relative Position Bias
    Adapted from Swin-V1 relative position bias impl, modularized.
    r   c                    s   t    |dksJ || _|d |d  | _| j| fd |f | _d|d  d d|d  d  d|  }tt||| _	| j
dt| j|dkdddd	 |   d S )
Nr   r   r   r   r   )r	   r   F
persistent)super__init__window_sizewindow_area
bias_shapenn	Parameterr   zerosrelative_position_bias_tableregister_bufferr   r   init_weights)selfr%   	num_headsprefix_tokensr   	__class__r   r   r$   I   s    
(zRelPosBias.__init__c                 C   s   t | jdd d S Ng{Gz?)Zstd)r   r+   r.   r   r   r   r-   Z   s    zRelPosBias.init_weightsr
   c                 C   s0   | j | j }|| jddd}|d S )Nr   r   r   )r+   r   r   r'   r   	unsqueezer   r.   Zrelative_position_biasr   r   r   get_bias]   s    zRelPosBias.get_biasNshared_rel_posc                 C   s   ||    S Nr8   r.   Zattnr:   r   r   r   forwardc   s    zRelPosBias.forward)r   )N__name__
__module____qualname____doc__r$   r-   r   Tensorr8   r   r>   __classcell__r   r   r1   r   r    D   s
   r    r   swin)win_sizepretrained_win_sizec                 C   sr  |dv sJ t j| d d  | d t jd}t j| d d  | d t jd}t t ||g}|ddd }|dkrR|d dkr|d d d d df  |d d   < |d d d d df  |d d   < nL|d d d d df  | d d   < |d d d d df  | d d   < |d9 }t |t d|	   t
d }nt |t d|	   }|S )	N)rF   crr   r   )Zdtyper   rF      g      ?)r   r   float32r   r   r   r   signlog2absmathlog)rG   rH   modeZrelative_coords_hZrelative_coords_wZrelative_coords_tabler   r   r   gen_relative_log_coordsg   s*      
&(&&

rR   c                       sH   e Zd ZdZd fdd	Zejd	d
dZdeej dddZ	  Z
S )	RelPosMlpz Log-Coordinate Relative Position MLP
    Based on ideas presented in Swin-V2 paper (https://arxiv.org/abs/2111.09883)

    This impl covers the 'swin' implementation as well as two timm specific modes ('cr', and 'rw')
    rJ      r   rI   r   c                    s   t    || _| jd | jd  | _|| _|| _| jfd |f | _|dkrdt | _	d| _
d}nt | _	d | _
d}td||tj|dd	| _| jd
t|ddd | jdt|||ddd d S )Nr   r   r   rF      )TFT)g      ?g        )Zhidden_featuresZout_featuresZ	act_layerZbiasZdropr   r   Fr!   rel_coords_log)rQ   )r#   r$   r%   r&   r0   r/   r'   r(   ZSigmoidbias_act	bias_gainZIdentityr   ZReLUmlpr,   r   r   rR   )r.   r%   r/   Z
hidden_dimr0   rQ   Zpretrained_window_sizeZmlp_biasr1   r   r   r$      s>    	


	zRelPosMlp.__init__r5   c                 C   s   |  | j}| jd ur6|d| j| j }|| j}|ddd}| |}| jd urb| j| }| j	rt
|| j	d| j	dg}|d S )Nr   r   r   r   )rY   rV   r   r   r/   r'   r   rW   rX   r0   r   r   r6   r   r7   r   r   r   r8      s    



zRelPosMlp.get_biasNr9   c                 C   s   ||    S r;   r<   r=   r   r   r   r>      s    zRelPosMlp.forward)rJ   rT   r   rI   r   )N)r@   rA   rB   rC   r$   r   rD   r8   r   r>   rE   r   r   r1   r   rS      s        ,rS   )lengthmax_relative_positionc                 C   sv   |du r| d }d| d }t | | |}t| D ]>}t| D ]0}|| | }t|| |kr`q>d||||f< q>q2|S )a  Generate a one_hot lookup tensor to reindex embeddings along one dimension.

    Args:
        length: the length to reindex to.
        max_relative_position: the maximum relative position to consider.
            Relative position embeddings for distances above this threshold
            are zeroed out.
    Returns:
        a lookup Tensor of size [length, length, vocab_size] that satisfies
            ret[n,m,v] = 1{m - n + max_relative_position = v}.
    Nr   r   )r   r*   rangerN   )rZ   r[   Z
vocab_sizeretixvr   r   r   generate_lookup_tensor   s    ra   )heightwidthheight_lookupwidth_lookupr
   c                 C   s8   t d| |}t d||}|| }|| jd ||S )a\  Reindex 2d relative position bias with 2 independent einsum lookups.

    Adapted from:
     https://github.com/google-research/maxvit/blob/2e06a7f1f70c76e64cd3dabe5cd1b8c1a23c9fb7/maxvit/models/attention_utils.py

    Args:
        relative_position_tensor: tensor of shape
            [..., vocab_height, vocab_width, ...].
        height: height to reindex to.
        width: width to reindex to.
        height_lookup: one-hot height lookup
        width_lookup: one-hot width lookup
    Returns:
        reindexed_tensor: a Tensor of shape
            [..., height * width, height * width, ...]
    znhw,ixh->nixwznixw,jyw->nijxyr   )r   ZeinsumZreshapeshape)Zrelative_position_tensorrb   rc   rd   re   Zreindexed_tensorarear   r   r   reindex_2d_einsum_lookup   s    rh   c                       sP   e Zd ZdZd fdd	Zdd Zejddd	Zde	ej dddZ
  ZS )RelPosBiasTfz Relative Position Bias Impl (Compatible with Tensorflow MaxViT models)
    Adapted from:
     https://github.com/google-research/maxvit/blob/2e06a7f1f70c76e64cd3dabe5cd1b8c1a23c9fb7/maxvit/models/attention_utils.py
    r   c                    s   t    |dksJ || _|d |d  | _|| _d|d  d }d|d  d }| j||f| _tt	| j| _
| jdt|d dd | jdt|d dd |   d S )Nr   r   r   rd   Fr!   re   )r#   r$   r%   r&   r/   r'   r(   r)   r   r*   r+   r,   ra   r-   )r.   r%   r/   r0   Zvocab_heightZvocab_widthr1   r   r   r$     s    
zRelPosBiasTf.__init__c                 C   s   t jj| jdd d S r3   )r(   initZnormal_r+   r4   r   r   r   r-     s    zRelPosBiasTf.init_weightsr5   c                 C   s"   t | j| jd | jd | j| jS )Nr   r   )rh   r+   r%   rd   re   r4   r   r   r   r8     s    zRelPosBiasTf.get_biasNr9   c                 C   s   ||    S r;   r<   r=   r   r   r   r>   "  s    zRelPosBiasTf.forward)r   )Nr?   r   r   r1   r   ri     s
   
ri   )NF)r   rF   )N)rC   rO   typingr   r   r   Ztorch.nnr(   Ztorch.nn.functionalZ
functionalr   rY   r   Zweight_initr   intboolrD   r   Moduler    rR   rS   ra   rh   ri   r   r   r   r   <module>   sF     
4%  

E 