
    Pi^k                         d dl Z d dlmZmZmZ d dlZd dlmc mZ	 d dlmZ d dl
mZmZ  G d dej                  Z G d dej                  Z G d	 d
ej                  ZdS )    N)AnyDictTuple)nn)distribute_tensorDTensorc                   h     e Zd ZdZdedededdf fdZdej        d	ee	         dej        fd
Z
 xZS )TokenPositionalEmbeddinga  
    Token positional embedding for images, different for every token in an image.

    Notice that tile is different from patch (token). For details, please check the documentation of
    :class:`torchtune.modules.vision_transformer.VisionTransformer`.

    Args:
        embed_dim (int): The dimensionality of each token embedding.
        tile_size (int): The size of your image tiles, if the image was tile-cropped in advance. Otherwise,
            the size of the input image. In this case, the function will consider your image as a single tile.
        patch_size (int): The size of each patch. Used to divide the tiles into patches.
            E.g. for ``patch_size=40``, a tile of shape (400, 400) will have 10x10 grid of patches
            with shape (40, 40) each.
    	embed_dim	tile_size
patch_sizereturnNc                     t                                                       ||z  }|dz  dz   }|dz  }t          j        |t	          j        ||f          z            | _        d S N            )super__init__r   	Parametertorchrandnpositional_embedding)selfr   r   r   patch_grid_sizen_tokens_per_tilescale	__class__s          ~/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/torchtune/models/clip/_position_embeddings.pyr   z!TokenPositionalEmbedding.__init__    sn    #z1+Q.24$&LEK!2I >???%
 %
!!!    xargsc                     || j         z   S )z
        Args:
            x (torch.Tensor): torch.Tensor with shape (..., n_tokens_per_tile, embed_dim)
            *args (Tuple[Any]): Optional args.

        Returns:
            torch.Tensor: The input tensor with added positional embeddings.
        )r   )r   r!   r"   s      r   forwardz TokenPositionalEmbedding.forward)   s     4,,,r    )__name__
__module____qualname____doc__intr   r   Tensorr   r   r$   __classcell__r   s   @r   r
   r
      s         
# 
# 
3 
4 
 
 
 
 
 
	- 	-eCj 	-U\ 	- 	- 	- 	- 	- 	- 	- 	-r    r
   c                   P    e Zd ZdZdededededdf
 fdZ ej                    d	ee	e
f         d
e	dee
         dee	e
f         ddf
d            Zedej        dedej        fd            Zedej        dededej        fd            Zdej        dej        dej        fdZ xZS )TiledTokenPositionalEmbeddinga  

    Token positional embedding for tiled images, different for every tile, different for every token.

    There are two positional embeddings in this module:

    * local_token_positional_embedding: same for every tile, different for every token. Equivalent         to :class:`torchtune.models.clip._position_embeddings.TokenPositionalEmbedding`, but gated.
    * global_token_positional_embedding: different for every tile, different for every token.

    Notice that tile is different from patch (token). For details, please check the documentation of
    :class:`torchtune.modules.vision_transformer.VisionTransformer`.

    Args:
        max_num_tiles (int): The maximum number of tiles an image can be divided into.
        embed_dim (int): The dimensionality of each token embedding.
        tile_size (int): The size of your image tiles, if the image was tile-cropped in advance. Otherwise,
            the size of the input image. In this case, the function will consider your image as a single tile.
        patch_size (int): The size of each patch. Used to divide the tiles into patches.
            E.g. for ``patch_size=40``, a tile of shape (400, 400) will have 10x10 grid of patches
            with shape (40, 40) each.
    max_num_tilesr   r   r   r   Nc           	         t                                                       ||z  }|dz  dz   | _        |dz  }t          j        |t          j        | j        |f          z            | _        t          j        |t          j        ||| j        |          z            | _        t          j        t          j	        d                    | _
        |                     | j                   d S r   )r   r   r   r   r   r   r    local_token_positional_embedding!global_token_positional_embeddingzerosgate"_register_load_state_dict_pre_hook_load_state_dict_hook)r   r/   r   r   r   r   r   r   s          r   r   z&TiledTokenPositionalEmbedding.__init__M   s     	#z1!0!!3a!74 13EK!7 CDDD1
 1
-
 24k&	 2
 2
. LQ00	//0JKKKKKr    
state_dictprefixr"   kwargsc           
         |                     |dz             }|t          |t                    r%d}|j        }|j        }|                                }nd}|j        \  }	}
t          j        |	dz
            dz  dk    rt          d|	d          | j
        j        \  }}|                     |t          t          j        |dz
                      	          }|rt          |||
          }|||dz   <   |j        | j
        j        k    r%t          d|j         d| j
        j         d          |                     |dz             }|t          |t                    r%d}|j        }|j        }|                                }nd}|j        \  }}}	}t          j        |	dz
            dz  dk    rt          d|	d          | j        j        \  }}}}|                     ||t          t          j        |dz
                                }|rt          |||
          }|||dz   <   |j        | j        j        k    r't          d|j         d| j        j         d          dS dS )a_  
        Interpolates positional embeddings to accomodate different number of tiles
        and tokens per tile, in case the model was instantiated with different
        settings than the one you are loading the state dict from.

        For more info, please check self._resize_local_position_embedding and
        self._resize_global_position_embedding functions.

        Args:
            state_dict (Dict[str, Any]): The state dict to load.
            prefix (str): The prefix of the state dict.
            *args (Tuple[Any]): Additional positional arguments.
            **kwargs (Dict[str, Any]): Additional keyword arguments.

        Raises:
            ValueError:
                If loaded local or global embedding n_tokens_per_tile is not derived
                    from a squared grid, **or**
                if after interpolation, the shape of the loaded local embedding
                    is not compatible with the current embedding, **or**
                if after interpolation, the shape of the loaded global embedding
                    is not compatible with the current embedding.
        r1   NTFr   r   zCLoaded local positional embedding has shape inpt_n_tokens_per_tile=zS, which indicates a grid_size that is not squared. This is currently not supported.)local_pos_embedtgt_patch_grid_sizedevice_mesh
placementsz,Loaded local positional embedding has shape z&, after interpolation. Expected shape .r2   )global_pos_embedtgt_max_num_tilesr<   z-Loaded global positional embedding has shape )get
isinstancer   r>   r?   full_tensorshapemathsqrt
ValueErrorr1    _resize_local_position_embeddingr)   r   r2   !_resize_global_position_embedding)r   r7   r8   r"   r9   inpt_local_pos_embedlocal_embed_is_shardedlocal_embed_device_meshlocal_embed_placementsinpt_n_tokens_per_tileinpt_embed_dimtgt_n_tokens_per_tiletgt_embed_diminpt_global_pos_embedglobal_embed_is_shardedglobal_embed_device_meshglobal_embed_placements_tgt_max_num_tiles_xtgt_max_num_tiles_ys                       r   r6   z3TiledTokenPositionalEmbedding._load_state_dict_hookj   s   B  *~~77 
  
  +
 .88 /)-&*>*J')=)H&';'G'G'I'I$$).& 6J5O2"Ny/!344q8A== iCY i i i   5;% $(#H#H 4$'	2G!2K(L(L$M$M $I $ $ 
 & '8( 75( ( ($ % ;; %*8>? ? !jCWC] j j;?;`;fj j j   !+88!
 !
 !,
 /99 0*.'+@+L(*?*J'(=(I(I(K(K%%*/'.C.I+Aq(! y/!344q8A== iCY i i i   6<##% %)$J$J!6"5$'	2G!2K(L(L$M$M %K % %! ' (9) 86) ) )% & << &+9?@ @ !kDYD_ k k;?;a;gk k k  i -,b@ @r    r;   r<   c                    | j         \  }}t          t          j        |dz
                      }| dg         | dd         } }|                     d||d                              dddd          } t          j        | ||gdd	          } |                     dddd                              dd|          } |                     d          } t          j
        || gd
          } |                                 S )a  
        Interpolates the local position embedding for a vision encoder to accommodate
        a different number of tokens per tile. This is the only dimension that
        changes during interpolation.

        Args:
            local_pos_embed (torch.Tensor): The position embeddings tensor to be resized. It
                has shape [n_tokens_per_tile, emb_dim], where the first token is the CLS token
                and n_tokens_per_tile = patch_grid_size**2 + 1.
            tgt_patch_grid_size (int): The target size of each patch grid, i.e.,
                the square root of the number of tokens per tile, excluding the class token.

        Returns:
            torch.Tensor: The resized position embeddings tensor of shape
                [tgt_n_tokens_per_tile, dim], where tgt_n_tokens_per_tile = tgt_patch_grid_size**2 + 1.

        Example:
            >>> import torch
            >>> import math
            >>> local_pos_embed = torch.randn((10*10+1, 64))  # Example input tensor
            >>> tgt_patch_grid_size = 20  # Target number of tokens per tile
            >>> resized_pos_embed = _resize_local_position_embedding(local_pos_embed, tgt_patch_grid_size)
            >>> print(resized_pos_embed.shape)
            torch.Size([20*20+1, 64])
        r   r   N   r   bilinearTsizemodealign_cornersdim)rF   r)   rG   rH   reshapepermuteFinterpolatesqueezer   cat
contiguous)r;   r<   rP   rQ   inpt_patch_grid_size	cls_tokens         r   rJ   z>TiledTokenPositionalEmbedding._resize_local_position_embedding  s&   < 2A1F."49-Ca-G#H#HII
 QC ABB #	 *11#%92
 

'!Q1

 	 -%':;	
 
 
 *11!Q1==EEr>
 

 *11!44  )Y$@aHHH))+++r    rA   rB   c                 X   | ddddddddf         }| dddddgddf         }|j         \  }}}}t          t          j        |                    }	|                    |||	|	|          }|                    ddddd                                          }|                    ||	z  ||	z  |          }|                    d          }t          ||z            t          ||z            f}
|                    dddd          }t          j	        ||
dd	          }|                    dddd          
                    d          }|                    |||||          }|                    ddddd                                          }|                    ||t          |dz            |          }|                    dddd          }t          j	        |||fdd	          }|                    dddd          }t          j        ||gd
          } |                                 S )af  
        Interpolates the global position embedding for a vision encoder to accommodate new grid dimensions.
        The embedding dimension is not changed during interpolation, only max_num_tiles and num_tokens_per_tile.

        Args:
            global_pos_embed (torch.Tensor): The input global position embeddings tensor of shape
                [max_num_tiles_x, max_num_tiles_y, num_tokens_per_tile, embed_dim],
                where num_tokens_per_tile = inpt_patch_grid_size * inpt_patch_grid_size + 1 (CLS token), and
                max_num_tiles_x == max_num_tiles_y.
            tgt_max_num_tiles (int): The target maximum number of tiles along one dimension (assumed square grid).
            tgt_patch_grid_size (int): The target size of each patch grid, i.e., the square root of the number of tokens
                per tile, excluding the class token.


        Returns:
            torch.Tensor: The resized global position embeddings tensor of shape
                [tgt_max_num_tiles, tgt_max_num_tiles, tgt_patch_grid_size * tgt_patch_grid_size + 1, embed_dim].

        Example:
            >>> import torch
            >>> global_pos_embed = torch.arange(3*3*(2*2+1)*4).reshape((3, 3, 2*2+1, 4))  # Example input tensor
            >>> tgt_max_num_tiles = 2  # Target maximum number of tiles
            >>> tgt_patch_grid_size = 3  # Target patch grid size
            >>> resized_global_pos_embed = (
            >>> _resize_global_position_embedding(global_pos_embed, tgt_max_num_tiles, tgt_patch_grid_size))
            >>> print(resized_global_pos_embed.shape)
            torch.Size([2, 2, 3*3+1, 4])
        Nr   r   r   r]      r^   Tr_   rc   )rF   r)   rG   rH   re   rf   rk   	unsqueezerg   rh   ri   viewr   rj   )rA   rB   r<   	pos_embed	cls_embedmax_num_tiles_xmax_num_tiles_yr   r   rl   tgt_sizecls_embed_resizeds               r   rK   z?TiledTokenPositionalEmbedding._resize_global_position_embeddingF  s   H %QQQ122qqq[1	$QQQA3\2	 O	

  #49->#?#?@@%%  
 
	 %%aAq!44??AA	%%2222
 
	 ''**	 !$7788!$7788
 %%aAq11	M	
 
 
	 %%aAq1199!<<	 NN
 
	 %%aAq!44??AA	NN#Q&''	
 
	 %%aAq11	M#%67	
 
 
 &--aAq99	 !9i%;CCC**,,,r    r!   aspect_ratioc                    |j         \  }}}}|| j        d| j                                        z
  z  z   }|                    ||||          }t          |          D ]\  }\  }}	t          ||	z            }
| j        d|d|	ddddf         }|                    |
| j	        |          }|| j                                        z  }||d|
ddddfxx         |z  cc<   |S )a  
        Args:
            x (torch.Tensor): torch.Tensor with shape
                (bsz * n_imgs, n_tiles, n_tokens_per_tile, embed_dim).
            aspect_ratio (torch.Tensor): torch.Tensor with shape (bsz * n_imgs, 2),
                where aspect_ratio[k] represents the aspect ratio of the k^th image
                of the batch before tile-cropping,  e.g. aspect_ratio[k] = (2,1).
        Returns:
            torch.Tensor: The input tensor with added positional embeddings.
        r   N)
rF   r1   r4   tanhrq   	enumerater)   r2   re   r   )r   r!   rx   bsz_and_n_imgsn_tilesr   r   	batch_idx	n_tiles_h	n_tiles_wn_non_padded_tilesrr   s               r   r$   z%TiledTokenPositionalEmbedding.forward  s.    AB=!2I 6!dinn>N>N:NOP FF>7,=yII1:<1H1H 	A 	A-I-	9 "%Y%:!;!; >
JYJ111,I
 "))"D$:I I "DINN$4$44Ii,,,aaa2333y@3333r    )r%   r&   r'   r(   r)   r   r   no_gradr   strr   r   r6   staticmethodr*   rJ   rK   r$   r+   r,   s   @r   r.   r.   5   s        .L L-0L=@LNQL	L L L L L L: U]__UcNU U Sz	U
 sCx.U 
U U U _Un @,@,<?@,	@, @, @, \@,F q-,q-q- !q- 
	q- q- q- \q-f% %U\ %el % % % % % % % %r    r.   c                       e Zd ZdZdedef fdZ ej                    dee	e
f         de	dee
         dee	e
f         fd	            Zed
ej        dedej        fd            Zdej        dej        dej        fdZ xZS )TilePositionalEmbeddinga  
    Positional embedding for tiles, different for every tile, same for every token within a tile.

    Notice that tile is different from patch (token). For details, please check the documentation of
    :class:`torchtune.modules.vision_transformer.VisionTransformer`.

    Args:
        max_num_tiles (int): The maximum number of tiles an image can be divided into.
        embed_dim (int): The dimensionality of each tile embedding.
    r/   r   c           	      L   t                                                       || _        |dz  }t          j        |t          j        ||d|          z            | _        t          j        t          j        d                    | _	        | 
                    | j                   d S )Nr   r   )r   r   r   r   r   r   r   	embeddingr3   r4   r5   r6   )r   r/   r   r   r   s       r   r   z TilePositionalEmbedding.__init__  s    
 	"4EK}aKKK
 
 LQ00	 	//0JKKKKKr    r7   r8   r"   r9   c                    |                     |dz             }|)t          |t                    r%d}|j        }|j        }|                                }nd}| j        j        \  }	}
}}||dz            j        \  }}}}||k    s||k    r-t          d| j        j         d||dz            j                   ||k    rt          d| j        j                   | 	                    ||	          }|rt          |||	          }|||dz   <   |j        | j        j        k    r&t          d
| j        j         d|j                   dS dS )a  
        Interpolates positional embeddings to accomodate different number of tiles,
        in case the model was instantiated with different
        settings than the one you are loading the state dict from.

        For more info, check self._dynamic_resize function.

        Args:
            state_dict (Dict[str, Any]): The state dict to load.
            prefix (str): The prefix of the state dict.
            *args (Tuple[Any]): Additional positional arguments.
            **kwargs (Dict[str, Any]): Additional keyword arguments.

        Raises:
            ValueError:
                If the shape of the loaded embedding is not compatible with the current embedding, **or**
                if ``max_num_tiles_x``, ``max_num_tiles_y`` are not equal, **or**
                if after interpolation, the shape of the loaded embedding is not compatible with the current embedding.
        r   NTFzTExpected embedding shape to be (..., num_tokens, tgt_emb) to match but found shapes z and z}Expected max_num_tiles_x, max_num_tiles_y to be equal but found, but found(max_num_tiles_x, max_num_tiles_y, 1, embed_dim) = )rB   r=   zKExpected embedding shape and embedding_new.shape to match but found shapes )rC   rD   r   r>   r?   rE   r   rF   rI   _resize_position_embeddingr   )r   r7   r8   r"   r9   r   embedding_is_shardedr>   r?   rY   rZ   tgt_num_tokenstgt_embinpt_max_num_tiles_xinpt_max_num_tiles_yinpt_num_tokensinpt_embembedding_news                     r   r6   z-TilePositionalEmbedding._load_state_dict_hook   s   8 NN6K#788	 
 )W-- -'+$'3&1
%1133		',$ $## 6K/06$$ .00H4G4G m)-)=m mDNvXcOcDdDjm m  
 $';;; aJN.J^a a   !;;-@ <  M $  1! +)! ! ! 0=Jv+,"dn&::: Z)-)=Z ZDQDWZ Z  s ! p ;:r    r   rB   r   c                     |                      dddd          } t          j        | ||fdd          } |                      dddd          } |                                 S )a  
        Interpolates positional embeddings to accomodate a different max_num_tiles. These
        are the only dimensions that changes during interpolation.

        Args:
            embedding (torch.Tensor): torch.Tensor with shape (max_num_tiles, max_num_tiles, 1, embed_dim
            tgt_max_num_tiles (int): The number of tiles to resize to.

        Returns:
            torch.Tensor: The resized embedding.

        Example:
            >>> import torch
            >>> # create dummy embedding
            >>> embedding = torch.arange(2*2*2*2).reshape(2, 2, 2, 2).float()
            >>> resized_embed = _dynamic_resize(embedding, tgt_max_num_tiles=1)
            >>> print(resized_embed.shape)
            >>> torch.Size([1, 1, 2, 2])
        r   r]   r   r   r^   Tr_   )rf   rg   rh   rk   )r   rB   s     r   r   z2TilePositionalEmbedding._resize_position_embedding\  sr    0 %%aAq11	M#%67	
 
 
	 %%aAq11	##%%%r    r!   rx   c                 ,   t          |          D ]\  }\  }}t          ||z            }| j        d|d|ddddf         }|                    |d| j                  }||d|ddddfxx         || j                                        z  z  cc<   |S )a  
        args:
            x (torch.Tensor): torch.Tensor with shape (bsz * n_imgs, n_tiles, n_tokens_per_tile, embed_dim).
            aspect_ratio (torch.Tensor): torch.Tensor with shape (bsz * n_imgs, 2),
                representing the aspect ratio of the image before tile-cropping, e.g. (2,1).
        returns:
            torch.Tensor: The input tensor with added positional embeddings.
        Nr   )r{   r)   r   re   r   r4   rz   )r   r!   rx   r~   r   r   r   rr   s           r   r$   zTilePositionalEmbedding.forward  s     2;<1H1H 	T 	T-I-	9 "%Y%:!;!; z	z:I:qqq!!!'CDI "))*<aPPIi,,,aaa2333y49>>CSCS7SS3333r    )r%   r&   r'   r(   r)   r   r   r   r   r   r   r   r6   r   r*   r   r$   r+   r,   s   @r   r   r     s8       	 	LL L L L L L L$ U]__YcNY Y Sz	Y
 sCx.Y Y Y _Yv !&<!&47!&	!& !& !& \!&F U\ el        r    r   )rG   typingr   r   r   r   torch.nn.functionalr   
functionalrg   torch.distributed._tensorr   r   Moduler
   r.   r    r    r   <module>r      s    # # # # # # # # # #                 @ @ @ @ @ @ @ @"- "- "- "- "-ry "- "- "-Jj j j j jBI j j jZv v v v vbi v v v v vr    