a
    yf0                     @   s   d dl mZ d dlZd dlm  mZ dd Zd ddZe	e	dd	d
Z
d!e	e	e	edddZejejdddZd"ejejejedddZdd Zdd Ze	e	ejejdddZejejejejee	e	f ee	e	f ejdddZdS )#    )TupleNc                    s   |dkst  |kr i }n|dks.J di tfdd D dd}|dur` | |< tfdd D dd}|dur | |< |t  }tfd	d D fd
ddd| } fdd|D  fdd  D }|fS )a  
    Selects the closest conditioning frames to a given frame index.

    Args:
        frame_idx (int): Current frame index.
        cond_frame_outputs (Dict[int, Any]): Dictionary of conditioning frame outputs keyed by frame indices.
        max_cond_frame_num (int): Maximum number of conditioning frames to select.

    Returns:
        (Tuple[Dict[int, Any], Dict[int, Any]]): A tuple containing two dictionaries:
            - selected_outputs: Selected items from cond_frame_outputs.
            - unselected_outputs: Items not selected from cond_frame_outputs.

    Examples:
        >>> frame_idx = 5
        >>> cond_frame_outputs = {1: "a", 3: "b", 7: "c", 9: "d"}
        >>> max_cond_frame_num = 2
        >>> selected, unselected = select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num)
        >>> print(selected)
        {3: 'b', 7: 'c'}
        >>> print(unselected)
        {1: 'a', 9: 'd'}
       z,we should allow using 2+ conditioning framesc                 3   s   | ]}| k r|V  qd S N .0t	frame_idxr   `/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/models/sam/modules/utils.py	<genexpr>)       z-select_closest_cond_frames.<locals>.<genexpr>N)defaultc                 3   s   | ]}| kr|V  qd S r   r   r   r
   r   r   r   .   r   c                 3   s   | ]}| vr|V  qd S r   r   r   selected_outputsr   r   r   6   r   c                    s   t |   S r   )abs)xr
   r   r   <lambda>7   r   z,select_closest_cond_frames.<locals>.<lambda>)keyc                 3   s   | ]}| | fV  qd S r   r   r   )cond_frame_outputsr   r   r   9   r   c                    s   i | ]\}}| vr||qS r   r   )r   r	   vr   r   r   
<dictcomp>:   r   z.select_closest_cond_frames.<locals>.<dictcomp>)lenmaxminsortedupdateitems)r   r   Zmax_cond_frame_numZunselected_outputsZ
idx_beforeZ	idx_afterZ
num_remainZinds_remainr   )r   r   r   r   select_closest_cond_frames	   s*    
r   '  c                 C   s\   |d }t j|t j| jd}|d|d  |  }| d| }t j| | gdd}|S )zQGenerates 1D sinusoidal positional embeddings for given positions and dimensions.r   )dtypedevicer   dim)torcharangefloat32r"   Z	unsqueezecatsincos)Zpos_indsr$   ZtemperatureZpe_dimZdim_tZ	pos_embedr   r   r   get_1d_sine_pe?   s    r+   )end_xend_yc                 C   s<   t j| | t jd}||   }t j|| dd }||fS )zLInitializes 1D and 2D coordinate tensors for a grid of specified dimensions.)r!   floor)Zrounding_mode)r%   r&   r'   floatdiv)r,   r-   r	   t_xt_yr   r   r   	init_t_xyJ   s    r3        @)r$   r,   r-   thetac           
      C   s   d|t d| dd| d   |    }d|t d| dd| d   |    }t||\}}t ||}t ||}t t ||}t t ||}	t j||	gddS )z[Computes axial complex exponential positional encodings for 2D spatial positions in a grid.      ?r      Nr   r#   )r%   r&   r/   r3   outerZpolarZ	ones_liker(   )
r$   r,   r-   r5   Zfreqs_xZfreqs_yr1   r2   Zfreqs_cis_xZfreqs_cis_yr   r   r   compute_axial_cisR   s    **r9   )	freqs_cisr   c                    s`   |j  dd  kr k s n J | j|jd |jd fks>J  fddt|jD }| j| S )zaReshapes frequency tensor for broadcasting with input tensor, ensuring dimensional compatibility.r      r   c                    s$   g | ]\}}| d  kr|ndqS )r   r;   r   )r   idndimr   r   
<listcomp>d   r   z)reshape_for_broadcast.<locals>.<listcomp>)r@   shape	enumerateview)r:   r   rB   r   r?   r   reshape_for_broadcast_   s
    rE   F)xqxkr:   repeat_freqs_kc           	      C   s  t |  jg | jdd ddR  }|jd dkrft | jg |jdd ddR  nd}t||}t || d}|du r|| 	| j
|fS |r|jd |jd  }|jg dg|jd  |dR  }t || d}|| 	| j
||	|j
fS )zfApplies rotary positional encoding to query and key tensors using complex-valued frequency components.Nr   r   r<   r      r;   )r%   Zview_as_complexr/   reshaperB   rE   Zview_as_realflattenZtype_astor"   repeatr@   )	rF   rG   r:   rH   Zxq_Zxk_Zxq_outrZxk_outr   r   r   apply_rotary_ench   s    ,>
$rO   c              	   C   s   | j \}}}}|||  | }|||  | }|dks>|dkrVt| ddd|d|f} || ||  }}	| ||| ||	| ||} | dddddd d|||}
|
||	ffS )a  
    Partitions input tensor into non-overlapping windows with padding if needed.

    Args:
        x (torch.Tensor): Input tensor with shape (B, H, W, C).
        window_size (int): Size of each window.

    Returns:
        (Tuple[torch.Tensor, Tuple[int, int]]): A tuple containing:
            - windows (torch.Tensor): Partitioned windows with shape (B * num_windows, window_size, window_size, C).
            - (Hp, Wp) (Tuple[int, int]): Padded height and width before partition.

    Examples:
        >>> x = torch.randn(1, 16, 16, 3)
        >>> windows, (Hp, Wp) = window_partition(x, window_size=4)
        >>> print(windows.shape, Hp, Wp)
        torch.Size([16, 4, 4, 3]) 16 16
    r   r;   rI   r   r7      r   )rB   FpadrD   permute
contiguous)r   window_sizeBHWCZpad_hZpad_wHpWpwindowsr   r   r   window_partition~   s    $r]   c           
      C   s   |\}}|\}}| j d || | |  }| ||| || ||d}	|	dddddd |||d}	||ksz||kr|	ddd|d|ddf  }	|	S )	af  
    Unpartitions windowed sequences into original sequences and removes padding.

    This function reverses the windowing process, reconstructing the original input from windowed segments
    and removing any padding that was added during the windowing process.

    Args:
        windows (torch.Tensor): Input tensor of windowed sequences with shape (B * num_windows, window_size,
            window_size, C), where B is the batch size, num_windows is the number of windows, window_size is
            the size of each window, and C is the number of channels.
        window_size (int): Size of each window.
        pad_hw (Tuple[int, int]): Padded height and width (Hp, Wp) of the input before windowing.
        hw (Tuple[int, int]): Original height and width (H, W) of the input before padding and windowing.

    Returns:
        (torch.Tensor): Unpartitioned sequences with shape (B, H, W, C), where B is the batch size, H and W
            are the original height and width, and C is the number of channels.

    Examples:
        >>> windows = torch.rand(32, 8, 8, 64)  # 32 windows of size 8x8 with 64 channels
        >>> pad_hw = (16, 16)  # Padded height and width
        >>> hw = (15, 14)  # Original height and width
        >>> x = window_unpartition(windows, window_size=8, pad_hw=pad_hw, hw=hw)
        >>> print(x.shape)
        torch.Size([1, 15, 14, 64])
    r   r   r;   rI   r   r7   rP   N)rB   rD   rS   rT   )
r\   rU   Zpad_hwZhwrZ   r[   rW   rX   rV   r   r   r   r   window_unpartition   s    $$r^   )q_sizek_sizerel_posreturnc                 C   s   t dt| | d }|jd |krdtj|d|jd dddd|dd}|d|dd}n|}t| dddf t||  d }t|dddf t| | d }|| |d t| | d  }||	  S )	a  
    Extracts relative positional embeddings based on query and key sizes.

    Args:
        q_size (int): Size of the query.
        k_size (int): Size of the key.
        rel_pos (torch.Tensor): Relative position embeddings with shape (L, C), where L is the maximum relative
            distance and C is the embedding dimension.

    Returns:
        (torch.Tensor): Extracted positional embeddings according to relative positions, with shape (q_size,
            k_size, C).

    Examples:
        >>> q_size, k_size = 8, 16
        >>> rel_pos = torch.randn(31, 64)  # 31 = 2 * max(8, 16) - 1
        >>> extracted_pos = get_rel_pos(q_size, k_size, rel_pos)
        >>> print(extracted_pos.shape)
        torch.Size([8, 16, 64])
    r   r;   r   r   Zlinear)sizemodeNr6   )
intr   rB   rQ   ZinterpolaterJ   rS   r%   r&   long)r_   r`   ra   Zmax_rel_distZrel_pos_resizedZq_coordsZk_coordsZrelative_coordsr   r   r   get_rel_pos   s    $$rg   )attnq	rel_pos_h	rel_pos_wr_   r`   rb   c                 C   s   |\}}|\}}	t |||}
t ||	|}|j\}}}|||||}td||
}td||}| |||||	|dddddddddf  |dddddddddf  ||| ||	 } | S )aP  
    Adds decomposed Relative Positional Embeddings to the attention map.

    This function calculates and applies decomposed Relative Positional Embeddings as described in the MVITv2
    paper. It enhances the attention mechanism by incorporating spatial relationships between query and key
    positions.

    Args:
        attn (torch.Tensor): Attention map with shape (B, q_h * q_w, k_h * k_w).
        q (torch.Tensor): Query tensor in the attention layer with shape (B, q_h * q_w, C).
        rel_pos_h (torch.Tensor): Relative position embeddings for height axis with shape (Lh, C).
        rel_pos_w (torch.Tensor): Relative position embeddings for width axis with shape (Lw, C).
        q_size (Tuple[int, int]): Spatial sequence size of query q as (q_h, q_w).
        k_size (Tuple[int, int]): Spatial sequence size of key k as (k_h, k_w).

    Returns:
        (torch.Tensor): Updated attention map with added relative positional embeddings, shape
            (B, q_h * q_w, k_h * k_w).

    Examples:
        >>> B, C, q_h, q_w, k_h, k_w = 1, 64, 8, 8, 8, 8
        >>> attn = torch.rand(B, q_h * q_w, k_h * k_w)
        >>> q = torch.rand(B, q_h * q_w, C)
        >>> rel_pos_h = torch.rand(2 * max(q_h, k_h) - 1, C)
        >>> rel_pos_w = torch.rand(2 * max(q_w, k_w) - 1, C)
        >>> q_size, k_size = (q_h, q_w), (k_h, k_w)
        >>> updated_attn = add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size)
        >>> print(updated_attn.shape)
        torch.Size([1, 64, 64])

    References:
        https://github.com/facebookresearch/mvit/blob/main/mvit/models/attention.py
    zbhwc,hkc->bhwkzbhwc,wkc->bhwkN)rg   rB   rJ   r%   ZeinsumrD   )rh   ri   rj   rk   r_   r`   Zq_hZq_wZk_hZk_wZRhZRwrV   _r$   Zr_qZrel_hZrel_wr   r   r   add_decomposed_rel_pos   s    )Vrm   )r    )r4   )F)typingr   r%   Ztorch.nn.functionalnnZ
functionalrQ   r   r+   re   r3   r/   r9   ZTensorrE   boolrO   r]   r^   rg   rm   r   r   r   r   <module>   s2   6
  &+

