
    ^j                        d dl Z d dlmZmZ d dlmZ d dlZd dlZd dl	m
c mZ d dlmZm
Z
 ddlmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1  e)d      e G d de                    Z2 e)d      e G d de                    Z3 e)d      e G d de                    Z4 e)d      e G d d e                    Z5 e)d!      e G d" d#e                    Z6 G d$ d%e
jn                        Z8 e&d&'      d(e9d)e9d*ejt                  d+ejv                  d,ej                  f
d-       Z<	 	 	 dd.ej                  d/e=dz  d0e=dz  d1e=dz  d,ej                  f
d2Z> G d3 d4e
jn                        Z? ed5       G d6 d7e
jn                               Z@d8 ZA	 	 	 dd9e
jn                  d:ej                  d;ej                  d<ej                  d=ej                  dz  d>e=e9z  d?e=dz  d@e=dz  d,eBej                  ej                  f   fdAZCdBej                  dCej                  dDej                  dEej                  d,eBej                  ej                  f   f
dFZDdGej                  dHe9d,ej                  fdIZE G dJ dKe
jn                        ZF G dL dMe
jn                        ZG G dN dOe
jn                        ZH G dP dQe
jn                        ZI G dR dSe
jn                        ZJ G dT dUe      ZK G dV dWe
jn                        ZL G dX dYe
jn                        ZM G dZ d[e
jn                        ZN G d\ d]e
jn                        ZO G d^ d_e
jn                        ZPe) G d` dae"             ZQ G db dceQ      ZRe) G dd deeQ             ZSe) G df dgeeQ             ZT e)dhi       G dj dkeQ             ZUddlZV e)dmdno       G dp dqeQ             ZW e)drdso       G dt dueQ             ZX e)dvdwo       G dx dyeQ             ZY e)dzd{o       G d| d}eQ             ZZg d~Z[y)    N)CallableIterable)	dataclass)Tensornn   )initialization)ACT2FN)BackboneMixinfilter_output_hidden_states)use_kernel_forward_from_hub)GradientCheckpointingLayer)BackboneOutputBaseModelOutputBaseModelOutputWithPoolingModelOutputSemanticSegmenterOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)#compile_compatible_method_lru_cache)TransformersKwargsauto_docstring)can_return_tuplemaybe_autocastmerge_with_config_defaults)capture_outputs   )Sapiens2Configz
    Output type of [`Sapiens2Backbone`], extending [`BackboneOutput`] with optional CLS tokens from
    each selected feature stage (used when `config.return_class_token=True`).
    )custom_introc                   @    e Zd ZU dZdZeej                     dz  ed<   y)Sapiens2BackboneOutputz
    cls_tokens (`tuple(torch.FloatTensor)`, *optional*):
        CLS token from each selected feature stage, each of shape `(batch_size, hidden_size)`.
        Only present when `config.return_class_token=True`.
    N
cls_tokens)	__name__
__module____qualname____doc__r#   tupletorchFloatTensor__annotations__     y/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/sapiens2/modeling_sapiens2.pyr"   r"   1   s#     37Je''(4/6r-   r"   z6
    Class for outputs of pose estimation models.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   y)Sapiens2PoseEstimatorOutputa  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Pose estimation loss.
    heatmaps (`torch.FloatTensor` of shape `(batch_size, num_keypoints, height, width)`):
        Heatmaps as predicted by the model.
    hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
        Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
        one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states
        (also called feature maps) of the model at the output of each stage.
    Nlossheatmaps.hidden_states
attentions)r$   r%   r&   r'   r1   r)   r*   r+   r2   r3   r(   r4   r,   r-   r.   r0   r0   E   sq    	 &*D%

d
"))-He$&-:>M5**C/047>7;Je'',-4;r-   r0   z8
    Class for outputs of normal estimation models.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   y)Sapiens2NormalEstimatorOutputa  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Normal estimation loss.
    normals (`torch.FloatTensor` of shape `(batch_size, num_labels, height, width)`):
        Raw normal map predictions as output by the model (unnormalized).
    hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
        Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage)
        of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of
        each layer plus the initial embedding outputs.
    attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
        Tuple of `torch.FloatTensor` (one per layer) of shape `(batch_size, num_heads, sequence_length,
        sequence_length)`. Attentions weights after the attention softmax.
    Nr1   normals.r3   r4   )r$   r%   r&   r'   r1   r)   r*   r+   r7   r3   r(   r4   r,   r-   r.   r6   r6   ]   sq     &*D%

d
")(,GU%,:>M5**C/047>7;Je'',-4;r-   r6   z:
    Class for outputs of pointmap estimation models.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	ej                  dz  ed<   dZ
eej                  df   dz  ed<   dZeej                  df   dz  ed<   y)	Sapiens2PointmapEstimatorOutputa  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Pointmap estimation loss.
    pointmaps (`torch.FloatTensor` of shape `(batch_size, 3, height, width)`):
        Per-pixel 3D XYZ coordinate predictions in canonical camera space.
    scales (`torch.FloatTensor` of shape `(batch_size, 1)`, *optional*):
        Canonical focal length / actual focal length ratio. `None` when no scale branch is configured.
    hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
        Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage)
        of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of
        each layer plus the initial embedding outputs.
    attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
        Tuple of `torch.FloatTensor` (one per layer) of shape `(batch_size, num_heads, sequence_length,
        sequence_length)`. Attentions weights after the attention softmax.
    Nr1   	pointmapsscales.r3   r4   )r$   r%   r&   r'   r1   r)   r*   r+   r:   r;   r3   r(   r4   r,   r-   r.   r9   r9   x   s      &*D%

d
")*.Iu  4'.'+FE$+:>M5**C/047>7;Je'',-4;r-   r9   z4
    Class for outputs of image matting models.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
ej                     dz  ed<   dZe
ej                     dz  ed<   dZej                  dz  ed<   y)Sapiens2ImageMattingOutputaN  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Loss.
    alphas (`torch.FloatTensor` of shape `(batch_size, 1, height, width)`):
        Estimated alpha values.
    hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
        Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
        one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states
        (also called feature maps) of the model at the output of each stage.
    foregrounds (`torch.FloatTensor` of shape `(batch_size, 3, height, width)`):
        Pre-multiplied RGB foreground predictions in `[0, 1]` (sigmoid-activated).
    Nr1   alphasr3   r4   foregrounds)r$   r%   r&   r'   r1   r)   r*   r+   r>   r3   r(   r4   r?   r,   r-   r.   r=   r=      s|     &*D%

d
")'+FE$+59M5**+d2926Je''(4/6,0K""T)0r-   r=   c                        e Zd ZdZdef fdZd	dej                  dej                  dz  dej                  fdZ xZ	S )
Sapiens2EmbeddingszM
    Construct the CLS token, mask token, position and patch embeddings.
    configc                 B   t         |           || _        t        j                  t        j                  dd|j                              | _        |j                  r4t        j                  t        j                  dd|j                              nd | _        t        j                  t        j                  d|j                  |j                              | _        t        j                  |j                   |j                  |j"                  |j"                        | _        y )Nr   )kernel_sizestride)super__init__rB   r   	Parameterr)   randnhidden_size	cls_tokenuse_mask_tokenzeros
mask_tokenemptynum_register_tokensregister_tokensConv2dnum_channels
patch_sizepatch_embeddingsselfrB   	__class__s     r.   rG   zSapiens2Embeddings.__init__   s    ekk!Q8J8J&KLQWQfQf",,u{{1a9K9K'LMlp!||EKK6;U;UW]WiWi,jk "		!3!3ARAR[a[l[l!
r-   Npixel_valuesbool_masked_posreturnc                 \   || j                   t        d      |j                  d   }| j                  j                  j
                  }| j                  |j                  |            }|j                  d      j                  dd      }|K| j                   j                  |j
                        }t        j                  |j                  d      ||      }| j                  j                  |dd      }| j                  j                  |dd      }t        j                  |||gd      }	|	S )Nz:bool_masked_pos requires use_mask_token=True in the configr   dtype   r   dim)rN   
ValueErrorshaperU   weightr^   toflatten	transposer)   where	unsqueezerK   expandrQ   cat)
rW   rY   rZ   
batch_sizetarget_dtyperU   rN   rK   rQ   
embeddingss
             r.   forwardzSapiens2Embeddings.forward   s   &4??+BYZZ!''*
,,3399  00|1TU+33A6@@AF&++,<,B,BCJ${{?+D+DR+H*Vfg NN))*b"=	..55j"bIYY	?<LMSTU
r-   N)
r$   r%   r&   r'   r   rG   r)   r   rp   __classcell__rX   s   @r.   rA   rA      sC    
~ 
ELL 5<<RVCV bgbnbn r-   rA       )maxsizenum_patches_hnum_patches_wr^   devicer[   c                    t        j                  d| ||      }t        j                  d|||      }|| z  }||z  }t        j                  t        j                  ||d      d      }|j	                  dd      }d	|z  d
z
  }|S )aq  
    Computes the 2D coordinates of the centers of image patches, normalized to the range [-1, +1].
    The center of each patch is exactly halfway between its top-left and bottom-right corners.

    Args:
        num_patches_h (int): Number of patches along the vertical (height) axis.
        num_patches_w (int): Number of patches along the horizontal (width) axis.
        dtype (torch.dtype): The desired data type of the returned tensor.

    Returns:
        torch.Tensor: A tensor of shape (height * width, 2), where each row contains the (y, x)
            coordinates of a patch center, normalized to [-1, +1].
    g      ?r^   rx   ij)indexingr`   ra   r   r   g       @g      ?)r)   arangestackmeshgridrg   )rv   rw   r^   rx   coords_hcoords_wcoordss          r.   get_patches_center_coordinatesr      s    " ||CeFKH||CeFKH-'H-'H[[(TJPRSF^^Aq!F6\CFMr-   r   shiftjitterrescalec                 6   |Dt        j                  d| j                  | j                        }|j	                  | |      }| |z   } |gt        j                  |      }t        j                  d| j                  | j                        }|j	                  | |      j                         }| |z  } |gt        j                  |      }t        j                  d| j                  | j                        }|j	                  | |      j                         }| |z  } | S )N)r   r_   )rx   r^   r   )r)   rO   rx   r^   uniform_nplogexp)	r   r   r   r   shift_hwjitter_range	jitter_hwrescale_range
rescale_hws	            r.   "augment_patches_center_coordinatesr      s     ;;vfmm6<<P$$eVU3(" vvf~KKv}}FLLQ	&&}lCGGI	)# w[[6==M
((-GKKM
*$Mr-   c                        e Zd ZU ej                  ed<   def fdZdej                  deej                  ej                  f   fdZ	 xZ
S )Sapiens2RopePositionEmbeddinginv_freqrB   c                 $   t         	|           || _        |j                  | _        |j
                  |j                  z  | _        d| j                  t        j                  ddd| j                  z  t        j                        z  z  }| j                  d|d       |j                  }t        |t              r|n||f\  }}|j                  }t        |t               r|n|d   }t        |t               r|n|d   }||z  | _        ||z  | _        y )Nr   r      r]   r   F)
persistent)rF   rG   rB   
rope_thetabaserJ   num_attention_headshead_dimr)   r}   float32register_buffer
image_size
isinstancer   rT   intrv   rw   )
rW   rB   r   r   image_himage_wrT   patch_size_hpatch_size_wrX   s
            r.   rG   z&Sapiens2RopePositionEmbedding.__init__  s    %%	**f.H.HHtyyELLAq4==7HPUP]P]$^^^ZeD&&
)3J)I:PZ\fOg&&
%/
C%@zjQRm%/
C%@zjQRm$4$4r-   rY   r[   c                    |j                   \  }}}}|| j                  j                  z  }|| j                  j                  z  }|j                  }t	        |j
                  t              r|j
                  dk7  r|j
                  nd}t        |d      5  t        ||t        j                  |      }	| j                  rKt        |	| j                  j                  | j                  j                  | j                  j                        }	dt         j"                  z  |	d d d d d f   z  | j$                  d d d d f   z  }
|
j'                  dd      }
|
j)                  d      }
t        j*                  |
      }t        j,                  |
      }d d d        |j.                  }j1                  |	      j1                  |	      fS # 1 sw Y   9xY w)
NmpscpuF)device_typeenabledrz   )r   r   r   r_   r   r]   )rd   rB   rT   rx   r   typestrr   r   r)   r   trainingr   pos_embed_shiftpos_embed_jitterpos_embed_rescalemathpir   rg   tilecossinr^   rf   )rW   rY   _heightwidthrv   rw   rx   r   patch_coordsanglesr   r   r^   s                 r.   rp   z%Sapiens2RopePositionEmbedding.forward%  s   *001fe$++"8"88!7!77$$%/S%AfkkUZFZfkk`eUC 	$ :}EMM&L }}A ++55;;77 KK99	  [<1d
#;;dmmDRVXYM>ZZF^^Aq)F[[^F))F#C))F#C+	$. ""vvEv"CFFF$7771	$ 	$s   C7GG)r$   r%   r&   r)   r   r+   r   rG   r(   rp   rr   rs   s   @r.   r   r     sB    ll5~ 5" 8ELL  8U5<<;U5V  8r-   r   RMSNormc                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	Sapiens2RMSNormepsr[   Nc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z>
        Sapiens2RMSNorm is equivalent to T5LayerNorm
        N)rF   rG   r   rH   r)   onesre   variance_epsilon)rW   rJ   r   rX   s      r.   rG   zSapiens2RMSNorm.__init__J  s1     	ll5::k#:; #r-   r3   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr_   r`   T)keepdim)	r^   rf   r)   r   powmeanrsqrtr   re   )rW   r3   input_dtypevariances       r.   rp   zSapiens2RMSNorm.forwardR  sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r-   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r(   re   rd   r   rW   s    r.   
extra_reprzSapiens2RMSNorm.extra_reprY  s*    ))*+6$2G2G1HIIr-   )gư>)
r$   r%   r&   floatrG   r)   r   rp   r   rr   rs   s   @r.   r   r   H  s7    $ $$ $;U\\ ;ell ;Jr-   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr`   r_   ra   )rd   r)   rl   )xx1x2s      r.   rotate_halfr   ]  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r-   modulequerykeyvalueattention_maskdropoutscalingsoftcapc                 |   || j                   dz  }t        || j                        }	t        || j                        }
t        j                  ||	j                  dd            |z  }|||z  }t        j                  |      }||z  }|||z   }t        j                  j                  |dt        j                        j                  |j                        }t        j                  j                  ||| j                        }t        j                  ||
      }|j                  dd      j                         }||fS )N      r_   r   r`   )rb   r^   )pr   r   )r   	repeat_kvnum_key_value_groupsr)   matmulrh   tanhr   
functionalsoftmaxr   rf   r^   r   r   
contiguous)r   r   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightsattn_outputs                r.   eager_attention_forwardr   d  s    //4'3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL#g-zz,/#g-!#n4 ==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r-   qkr   r   c                 d   | j                   d   }|j                   d   }||z
  }| j                  ||fd      \  }}	|j                  ||fd      \  }
}|	|z  t        |	      |z  z   }	||z  t        |      |z  z   }t        j                  ||	fd      } t        j                  |
|fd      }| |fS )a  Applies Rotary Position Embedding to the query and key tensors, but only to the patch tokens,
    ignoring the prefix tokens (cls token and register tokens).

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.

    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    ra   )rd   splitr   r)   rl   )r   r   r   r   r   
num_tokensnum_patchesnum_prefix_tokensq_prefix_tokens	q_patchesk_prefix_tokens	k_patchess               r.   apply_rotary_pos_embr     s      J))B-K"[0!"*;[)Ir!ROY!"*;[)Ir!ROY S[%;c%ABIS[%;c%ABI		?I.B7A		?I.B7Aa4Kr-   r3   n_repc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rd   rk   reshape)r3   r   batchnum_key_value_headsslenr   s         r.   r   r     so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr-   c                        e Zd ZdZdedef fdZ	 	 ddej                  dej                  dz  de	ej                  ej                  f   dz  d	e
e   d
e	ej                  ej                  dz  f   f
dZ xZS )Sapiens2AttentionzI
    Multi-headed attention compatible with ALL_ATTENTION_FUNCTIONS.
    rB   	layer_idxc                    t         |           || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        d| _        | j                  dz  | _	        d| _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                         | _        |j$                  |   | _        | j                  | j&                  z  | _        t        j                  | j                  | j&                  | j                  z  |j*                        | _        t        j                  | j                  | j&                  | j                  z  |j.                        | _        |j2                  r!t5        | j                  |j6                        nt        j8                         | _        |j2                  r't5        | j                  |j6                        | _        y t        j8                         | _        y )NFr   biasr   )rF   rG   rB   rJ   	embed_dimr   	num_headsr   	is_causalr   attention_dropoutr   r   Linear
query_biasq_proj	proj_biaso_projnum_key_value_heads_per_layerr   r   key_biask_proj
value_biasv_projuse_qk_normr   rms_norm_epsIdentityq_normk_normrW   rB   r   rX   s      r.   rG   zSapiens2Attention.__init__  s   ++33$..8}}d*//iiVEVEVWiiVEUEUV#)#G#G	#R $(NNd6N6N$N!ii0H0H4==0X_e_n_noii0H0H4==0X_e_p_pqQWQcQcodmm9L9LMikititivQWQcQcodmm9L9LMikititivr-   Nr3   r   position_embeddingsr   r[   c                 
   |j                   dd }g |d| j                  }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }	| j                  |      }| j                  |      }|\  }
}t        |||
|      \  }}t        j                  | j                  j                  t              } || |||	|f| j                  sdn| j                   | j"                  d|\  }} |j$                  g |d j'                         }| j)                  |      }||fS )z#Input shape: Batch x Time x ChannelNr`   r   r_           )r   r   )rd   r   r	  viewrh   r  r  r  r  r   r   get_interfacerB   _attn_implementationr   r   r   r   r   r   r  )rW   r3   r   r  r   input_shapehidden_shapequery_statesr   r   r   r   attention_interfacer   r   s                  r.   rp   zSapiens2Attention.forward  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST{{<0[[,
&S#7jRUWZ#[ j(?(M(MKK,,.E)
 %8	%
  $}}C$,,LL	%
 	%
!\ *k));;;;FFHkk+.L((r-   NNr$   r%   r&   r'   r   r   rG   r)   r   r(   r   r   rp   rr   rs   s   @r.   r   r     s    w~ w# w2 /3HL	$)||$) t+$) #5<<#=>E	$)
 +,$) 
u||U\\D00	1$)r-   r   c                   X     e Zd Zd fdZdej
                  dej
                  fdZ xZS )Sapiens2LayerScaler[   c                     t         |           t        j                  |j                  t        j                  |j                        z        | _        y rq   )	rF   rG   r   rH   layerscale_valuer)   r   rJ   lambda1rV   s     r.   rG   zSapiens2LayerScale.__init__  s8    ||F$;$;ejjI[I[>\$\]r-   hidden_statec                      || j                   z  S rq   )r'  )rW   r(  s     r.   rp   zSapiens2LayerScale.forward  s    dll**r-   r[   N)r$   r%   r&   rG   r)   r   rp   rr   rs   s   @r.   r$  r$    s$    ^+ELL +U\\ +r-   r$  c                   $     e Zd Z fdZd Z xZS )Sapiens2MLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        |j                     | _        y Nr   )rF   rG   rB   rJ   intermediate_sizer   r  mlp_biasup_proj	down_projr
   
hidden_actact_fnrV   s     r.   rG   zSapiens2MLP.__init__  s    !--!'!9!9yy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r-   c                 `    | j                  | j                  | j                  |                  S rq   )r2  r4  r1  )rW   r   s     r.   rp   zSapiens2MLP.forward  s"    ~~dkk$,,q/:;;r-   r$   r%   r&   rG   rp   rr   rs   s   @r.   r,  r,    s    0<r-   r,  c                   $     e Zd Z fdZd Z xZS )Sapiens2GatedMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        j                  | j                  | j                  |j                        | _
        t        |j                     | _        y r.  )rF   rG   rB   rJ   r/  r   r  r0  	gate_projr1  r2  r
   r3  r4  rV   s     r.   rG   zSapiens2GatedMLP.__init__  s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r-   c                     | j                  | j                  | j                  |            | j                  |      z        }|S rq   )r2  r4  r:  r1  )rW   r   r2  s      r.   rp   zSapiens2GatedMLP.forward  s6    NN4;;t~~a/@#ADLLQRO#ST	r-   r6  rs   s   @r.   r8  r8    s    0r-   r8  c                   r     e Zd ZdZd	deddf fdZdej                  dej                  fdZde	fdZ
 xZS )
Sapiens2DropPathzStochastic depth (DropPath) per sample, for residual blocks.

    Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
    <https://arxiv.org/abs/1603.09382>`_.
    	drop_probr[   Nc                 0    t         |           || _        y rq   )rF   rG   r>  )rW   r>  rX   s     r.   rG   zSapiens2DropPath.__init__#  s    "r-   r3   c                 P   | j                   dk(  s| j                  s|S d| j                   z
  }|j                  d   fd|j                  dz
  z  z   }t	        j
                  ||j                  |j                        }t	        j                  ||z         }|j                  |      |z  S )Nr  r   r   )r   rz   )
r>  r   rd   ndimr)   randr^   rx   floordiv)rW   r3   	keep_probrd   random_tensors        r.   rp   zSapiens2DropPath.forward'  s    >>S   &	$$Q')DM4F4F4J,KK

50C0CML`L`aMI$=>  +m;;r-   c                      d| j                    S )Nzp=)r>  r   s    r.   r   zSapiens2DropPath.extra_repr0  s    DNN#$$r-   )r  )r$   r%   r&   r'   r   rG   r)   r   rp   r   r   rr   rs   s   @r.   r=  r=    sB    #% #$ #<U\\ <ell <%C %r-   r=  c                        e Zd ZdZdedef fdZ	 	 ddej                  dej                  dz  de	ej                  ej                  f   dz  d	e
e   d
ej                  f
dZ xZS )Sapiens2LayerzCThis corresponds to the Block class in the original implementation.rB   r   c                    t         |           t        |j                  |j                        | _        t        ||      | _        t        |      | _	        |j                  dkD  rt        |j                        nt        j                         | _        t        |j                  |j                        | _        |j                   rt#        |      | _        nt'        |      | _        t        j                         | _        y )Nr  r   r  )rF   rG   r   rJ   r  norm1r   	attentionr$  layer_scale1drop_path_rater=  r   r  	drop_pathnorm2use_gated_mlpr8  mlpr,  layer_scale2r  s      r.   rG   zSapiens2Layer.__init__7  s    $V%7%7V=P=PQ
*6YG.v6DJDYDY\_D_)&*?*?@egepeper$V%7%7V=P=PQ
'/DH"6*DHKKMr-   Nr3   r   r  r   r[   c                 :   |}| j                  |      } | j                  |f||d|\  }}| j                  |      }| j                  |      |z   }|}| j	                  |      }| j                  |      }| j                  |      }| j                  |      |z   }|S )N)r   r  )rL  rM  rN  rP  rQ  rS  rT  )rW   r3   r   r  r   residualr   s          r.   rp   zSapiens2Layer.forwardE  s     !

=1)4>>
) 3
 	
q ))-8}5@ !

=1/))-8}5@r-   r!  r"  rs   s   @r.   rI  rI  4  s    M*~ *# *" /3HL	|| t+ #5<<#=>E	
 +, 
r-   rI  c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 ddededeeeef   z  dedeeeef   z  ez  deded	ed
ededef fdZde	j                  de	j                  fdZ xZS )Sapiens2ConvLayerzc
    A basic wrapper for Convolution-BatchNorm-Activation, typically used for head components.
    in_channelsout_channelsrD   rE   paddinggroups
activationr  convolution_transposepixel_shufflescale_factorc           	         t         |           |	rt        j                  ||||      | _        n!t        j
                  |||||||      | _        t        j                  |      | _        t        |   | _	        |	r,t        j                  ||
r||dz  z  n||||||      | _        n+t        j
                  ||
r||dz  z  n||||||      | _        |
rt        j                  |      | _        y t        j                         | _        y )N)rY  rZ  rD   rE   )rY  rZ  rD   rE   r[  r\  r  r_   )rD   rE   r[  r  r\  )rF   rG   r   ConvTranspose2dconvolutionrR   InstanceNorm2dnormr
   r4  PixelShuffler  r_  )rW   rY  rZ  rD   rE   r[  r\  r]  r  r^  r_  r`  rX   s               r.   rG   zSapiens2ConvLayer.__init__g  s    	 !11')'	 D  "yy')' D %%l3	Z( !112?|Q.\' D  "yy2?|Q.\' D ?LR__\:QSQ\Q\Q^r-   r3   r[   c                     | j                  |      }| j                  |      }| j                  |      }| j                  |      }|S rq   )rc  r_  re  r4  rW   r3   s     r.   rp   zSapiens2ConvLayer.forward  sD    ((7**=9		-0M2r-   )	r   r   r   r   siluTFFr_   )r$   r%   r&   r'   r   r(   r   boolrG   r)   r   rp   rr   rs   s   @r.   rX  rX  b  s     .//0 &+#6_6_ 6_ 5c?*	6_
 6_ uS#X&,6_ 6_ 6_ 6_  $6_ 6_ 6_pU\\ ell r-   rX  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )Sapiens2HeadrB   c                    t         |           j                  j                  r#t	        j
                  j
                  dd      nt        j                         | _        j
                  gj                  j                  d d z   }t        j                  fdt        |j                  j                  j                  j                        D              | _        j                  j                  d   gj                  j                  d d z   }t        j                  fdt        |j                  j                  j                  j                        D              | _        j                  j                  rj                  j                  d   n:j                  j                  rj                  j                  d   nj
                  }t        j"                  |j$                  d      | _        y )Nr   r   rD   r[  r`   c              3   V  K   | ]  \  }}}t        |||j                  j                  rd ndj                  j                  r|d z
  dz  nd t        j                  j                        t        j                  j                        j                  j                           yw)r   r_   )rD   rE   r[  r  r_  r^  N)rX  head_configuse_pixel_shufflerj  .0in_chout_chrD   rB   s       r.   	<genexpr>z(Sapiens2Head.__init__.<locals>.<genexpr>  s      -
 +v{ '"..@@qa282D2D2V2VqQ.\]&,,>>?"6#5#5#G#GH*0*<*<*N*N&N	 	-
s   B&B)c              3      K   | ]5  \  }}}t        |||j                  j                  r|d z
  dz  nd       7 yw)r   r_   r   rn  N)rX  rp  rq  rr  s       r.   rv  z(Sapiens2Head.__init__.<locals>.<genexpr>  sQ      
)
 +v{ '282D2D2V2VqQ.\]	 
)
s   ;>)rD   )rF   rG   rp  rq  rX  rJ   r   r  
input_convupsample_out_channels
ModuleListzipupsample_kernel_sizesupsample_layersconv_out_channelsconv_kernel_sizesconv_layersrR   
num_labels	predictor)rW   rB   upsample_in_channelsconv_in_channelspredictor_inrX   s    `   r.   rG   zSapiens2Head.__init__  s    !!33 f00&2D2DRS]^_ 	
 !' 2 23f6H6H6^6^_b`b6cc!}} -
 /2$""88""88/-
  
" #..DDRHIFL^L^LpLpqtrtLuu== 
)
 /2 &"4"4"F"FHZHZHlHl/
)
 

 !!33 004 !!77 ##99"=## 	 <1B1BPQRr-   r3   r[   c                     | j                  |      }| j                  D ]
  } ||      } | j                  D ]
  } ||      } | j                  |      S rq   )rx  r}  r  r  rW   r3   layers      r.   rp   zSapiens2Head.forward  s]    6)) 	1E!-0M	1%% 	1E!-0M	1~~m,,r-   	r$   r%   r&   r   rG   r)   r   rp   rr   rs   s   @r.   rl  rl    s-    ,S~ ,S\-U\\ -ell -r-   rl  c                   T     e Zd Zdededej
                  ddf fdZdedefdZ xZ	S )	Sapiens2PointmapFinalLayerBlockin_dimout_dimr]  r[   Nc                     t         |           t        j                  t        j                  ||      |g      | _        y rq   )rF   rG   r   rz  r  layers)rW   r  r  r]  rX   s       r.   rG   z(Sapiens2PointmapFinalLayerBlock.__init__  s.    mmRYYvw%?$LMr-   inputc                 <    |}| j                   D ]
  } ||      } |S rq   )r  )rW   r  r(  r  s       r.   rp   z'Sapiens2PointmapFinalLayerBlock.forward  s*    [[ 	/E .L	/r-   )
r$   r%   r&   r   r   ModulerG   r   rp   rr   rs   s   @r.   r  r    s@    Ns NS Nbii ND NV  r-   r  c            	       t     e Zd Zd	dedeeef   dedef fdZdej                  dej                  fdZ	 xZ
S )
Sapiens2PointmapFinalLayerr  hidden_sizesr  r]  c                 
   t         |           t        j                         | _        t        ||d   t        |         | _        t        |d   |d   t        |         | _        t        j                  |d   |      | _
        y )Nr   )r  r  r]  r   )rF   rG   r   Flattenrg   r  r
   block1block2r  proj)rW   r  r  r  r]  rX   s        r.   rG   z#Sapiens2PointmapFinalLayer.__init__  sq    zz|5<?vj?Q
 6?LOzHZ
 IIl1ow7	r-   r3   r[   c                     | j                  |      }| j                  |      }| j                  |      }| j                  |      S rq   )rg   r  r  r  rh  s     r.   rp   z"Sapiens2PointmapFinalLayer.forward  s;    ]3M2M2yy''r-   )r   ri  )r$   r%   r&   r   r(   r   rG   r)   r   rp   rr   rs   s   @r.   r  r    sH    	8s 	8%S/ 	8C 	8ad 	8(U\\ (ell (r-   r  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )Sapiens2PointmapScaleHeadrB   c                    t         |           t        j                         | _        |j
                  g|j                  j                  d d z   }t        ||j                  j                  |j                  j                        D ]5  \  }}}| j                  j                  t        |||d|dz
  dz               7 t        |j                  j                  |j                  j                  |j                        | _        y )Nr`   r_   r   )rD   rE   r[  )r]  )rF   rG   r   rz  r  rJ   rp  scale_conv_out_channelsr{  scale_conv_kernel_sizesappendrX  r  scale_final_input_sizescale_final_hidden_sizesr3  r  )rW   rB   scale_in_channelsrt  ru  rD   rX   s         r.   rG   z"Sapiens2PointmapScaleHead.__init__  s    ==?#//063E3E3]3]^a_a3bb*-6666+
 	&E6;
 ##!%[QR]hkl]lqr\rs	 45577((
r-   r3   r[   c                 V    | j                   D ]
  } ||      } | j                  |      S rq   )r  r  r  s      r.   rp   z!Sapiens2PointmapScaleHead.forward  s0    %% 	1E!-0M	1~~m,,r-   r  rs   s   @r.   r  r    s*    
~ 
$-U\\ -ell -r-   r  c                        e Zd ZU eed<   dZdZdZdZdgZ	dZ
dZdZdZeedZdgZd	gZ ej(                         d fd
       Z xZS )Sapiens2PreTrainedModelrB   modelrY   )imageTrI  )r3   r4   periodsrN   c                    t         |   |       t        |t        j                  t        j
                  f      r7t        j                  |j                  d| j                  j                         yt        |t        j                        r#t        j                  |j                  dd       yt        |t              rt        j                  |j                  d| j                  j                         |j                  j                  dkD  r6t        j                  |j                   d| j                  j                         |j                  j"                  r t        j$                  |j&                         yyt        |t(              r5t        j*                  |j,                  | j                  j.                         yt        |t0              red|j2                  t5        j6                  ddd|j8                  z  t4        j:                  	      z  z  }t        j<                  |j>                  |       yt        |t@        tB        f      r|jE                         D ]|  }t        |t        j
                        r#t        j                  |j                  dd       @t        |t        j                        s[t        j                  |j                  d
d       ~ yy)zInitialize the weightsr  )r   stdfan_outrelu)modenonlinearityr   r   r   r]   fan_inlinearN)#rF   _init_weightsr   r   r  rR   inittrunc_normal_re   rB   initializer_rangerb  kaiming_normal_rA   rK   rP   rQ   rL   zeros_rN   r$  	constant_r'  r&  r   r   r)   r}   r   r   copy_r   rl  r  modules)rW   r   r   head_modulerX   s       r.   r  z%Sapiens2PreTrainedModel._init_weights-  s    	f%fryy"))45v}}3DKK<Y<YZ 2 23  YVT 23v//ct{{?\?\]}}0014""6#9#9IfIfg}}++F--. , 23NN6>>4;;+G+GH =>6;;%,,q!Q=PX]XeXe*fffHJJv1/H IJ%~~/ ck2995((););)Z`aRYY7((););(Yab	c Kr-   r*  )r$   r%   r&   r   r+   base_model_prefixmain_input_nameinput_modalitiessupports_gradient_checkpointing_no_split_modules_supports_sdpa_supports_flash_attn_supports_flex_attn_supports_attention_backendrI  r   _can_record_outputs"_keys_to_ignore_on_load_unexpected_keys_to_ignore_on_load_missingr)   no_gradr  rr   rs   s   @r.   r  r    s|    $O!&*#()N"&&' +5&'4o#U]]_c cr-   r  c                        e Zd Zdef fdZe ed      	 ddej                  de	ej                  ej                  f   dz  de
e   d	efd
              Z xZS )Sapiens2EncoderrB   c           	          t         |   |       t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        | j                          y c c}w )NrK  )	rF   rG   r   rz  rangenum_hidden_layersrI  r  	post_initr  s      r.   rG   zSapiens2Encoder.__init__I  sR     ]]INvOgOgIhiI]6Y7i

 	 js   A(F)tie_last_hidden_statesNr3   r  r   r[   c                 R    | j                   D ]  } ||fd|i|} t        |      S )Nr  )last_hidden_state)r  r   )rW   r3   r  r   layer_modules        r.   rp   zSapiens2Encoder.forwardQ  s<     !JJ 	kL(jL_jcijM	k ??r-   rq   )r$   r%   r&   r   rG   r   r   r)   r   r(   r   r   r   rp   rr   rs   s   @r.   r  r  H  s    ~   E2 IM	@||	@ #5<<#=>E	@ +,		@
 
	@ 3  	@r-   r  c                        e Zd Zdef fdZd Zee	 d
dej                  dej                  dz  de
e   defd	              Z xZS )Sapiens2ModelrB   c                     t         |   |       t        |      | _        t	        |      | _        t        |      | _        t        |j                  |j                        | _        d| _        | j                          y )Nr  F)rF   rG   rA   ro   r   rope_embeddingsr  r  r   rJ   r  re  gradient_checkpointingr  rV   s     r.   rG   zSapiens2Model.__init__a  sa     ,V4<VD$V,
#F$6$6F<O<OP	&+#r-   c                 .    | j                   j                  S rq   ro   rU   r   s    r.   get_input_embeddingsz"Sapiens2Model.get_input_embeddingsk      ///r-   NrY   rZ   r   r[   c                 x   |j                  | j                  j                  j                  j                        }| j                  ||      }| j                  |      } | j                  ||fi |}| j                  |j                        }|dddddf   }t        |||j                  |j                        S )a  
        bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
            pre-training.

        Example:

        ```python
        >>> from transformers import AutoImageProcessor, AutoModel
        >>> from transformers.image_utils import load_image
        >>> import torch

        >>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
        >>> model = AutoModel.from_pretrained("facebook/sapiens2-pretrain-0.4b")

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)

        >>> cls_token = outputs.pooler_output
        >>> cls_token.shape
        torch.Size([1, 1024])
        ```
        )rZ   Nr   )r  pooler_outputr3   r4   )rf   ro   rU   re   r^   r  r  re  r  r   r3   r4   )	rW   rY   rZ   r   r3   r  outputsequence_outputpooled_outputs	            r.   rp   zSapiens2Model.forwardn  s    D $t'G'G'N'N'T'TUoV"22<@M+>I&I))F$<$<='1a0)-' ..((	
 	
r-   rq   )r$   r%   r&   r   rG   r  r   r   r)   r   r   r   r   rp   rr   rs   s   @r.   r  r  _  sn    ~ 0  04-
ll-
 ,-
 +,	-

 
$-
  -
r-   r  c            	       v     e Zd Zdef fdZd Zeeede	j                  dee   defd                     Z xZS )Sapiens2BackbonerB   c                 r   t         |   |       t        |      | _        t	        |      | _        t        |      | _        t        |j                  |j                        | _        d| _        t        |j                  dz         D cg c]  }|j                   c}| _        | j!                          y c c}w )Nr  Fr   )rF   rG   rA   ro   r   r  r  r  r   rJ   r  re  r  r  r  num_featuresr  )rW   rB   r   rX   s      r.   rG   zSapiens2Backbone.__init__  s     ,V4<VD$V,
#F$6$6F<O<OP	&+#9>v?W?WZ[?[9\]AV//] ^s   B4c                 .    | j                   j                  S rq   r  r   s    r.   r  z%Sapiens2Backbone.get_input_embeddings  r  r-   rY   r   r[   c                    |j                  | j                  j                  j                  j                        }| j                  |      }| j                  |      }d|d<    | j                  ||fi |}|j                  }|j                  \  }}}	}
| j                  j                  }t        |t              r|n|d   }t        |t              r|n|d   }|	|z  }|
|z  }dt        | j                  dd      z   }t        | j                  dd      }g g }}t        t        | j                   |            D ]  \  }\  }}| j                  j"                  r| j%                  |      }|| j&                  v s?|r|j)                  |dddddf          |dd|dddf   }| j                  j*                  rB|j-                  ||||j                  d	         j/                  dd
dd      j1                         }n|}|j)                  |        t3        t5        |      |rt5        |      nd|j                  |j6                        S )a2  
        Example:

        ```python
        >>> from transformers import AutoBackbone, AutoImageProcessor
        >>> from transformers.image_utils import load_image
        >>> import torch

        >>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pretrain-0.4b")
        >>> model = AutoBackbone.from_pretrained("facebook/sapiens2-pretrain-0.4b")

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     outputs = model(**inputs, return_class_token=True)

        >>> outputs.feature_maps[0].shape
        torch.Size([1, 1024, 64, 48])
        >>> outputs.cls_tokens[0].shape
        torch.Size([1, 1024])
        ```
        Toutput_hidden_statesr   r   rP   return_class_tokenFNr`   r   r_   )feature_mapsr#   r3   r4   )rf   ro   rU   re   r^   r  r  r3   rd   rB   rT   r   r   getattr	enumerater{  stage_namesnormalize_backbone_outputsre  out_featuresr  reshape_hidden_statesr   permuter   r"   r(   r4   )rW   rY   r   r3   r  r  stage_hidden_statesrm   r   image_heightimage_widthrT   r   r   num_patches_heightnum_patches_width
num_prefixr  r  r#   idx
stage_namer(  patch_tokensfeature_maps                            r.   rp   zSapiens2Backbone.forward  s(   < $t'G'G'N'N'T'TU5"22<@)-%&M+>I&I$223?3E3E0
A|[[[++
%/
C%@zjQRm%/
C%@zjQRm)\9'<7.CQGG
$T[[2FN#%rj/8T=M=MOb9c/d 	1+C+*l{{55#yy6T...%%%l1a7&;<+Az{A,=>;;44$,,Z9KM^`l`r`rsu`vw Aq!,#   #/K##K0#	1& &|,,>uZ(D ..((	
 	
r-   )r$   r%   r&   r   rG   r  r   r   r   r)   r   r   r   r"   rp   rr   rs   s   @r.   r  r    sc    
~ 
0  F
llF
 +,F
 
 	F
  ! F
r-   r  zfacebook/sapiens2-seg-0.4b)
checkpointc                        e Zd Zdef fdZee	 d	dej                  dej                  dz  de
e   defd              Z xZS )
Sapiens2ForSemanticSegmentationrB   c                     t         |   |       |j                  | _        t        |      | _        t        |      | _        | j                          y rq   rF   rG   r  r  r  rl  decode_headr  rV   s     r.   rG   z(Sapiens2ForSemanticSegmentation.__init__  @      ++"6*
'/r-   NrY   labelsr   r[   c                    |$| j                   j                  dk(  rt        d       | j                  |fi |}|j                  \  }}}}| j                   j
                  }	t        |	t              r|	n|	d   }
t        |	t              r|	n|	d   }||
z  }||z  }|j                  ddd| j                   j                  z   df   }|j                  dd      j                  |d||      }| j                  |      }d}|(| j                  ||| j                   j                        }t        |||j                   |j"                        S )	a  
        labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
            Ground truth semantic segmentation maps for computing the loss.
            Indices should be in `[0, ..., config.num_labels - 1]`.
            If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).

        Example:

        ```python
        >>> from transformers import AutoImageProcessor, AutoModel
        >>> from transformers.image_utils import load_image
        >>> import torch

        >>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-seg-0.4b")
        >>> model = AutoModel.from_pretrained("facebook/sapiens2-seg-0.4b")

        >>> inputs = image_processor(image, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)

        >>> outputs.logits.shape
        torch.Size([1, 29, 1024, 768])
        ```
        Nr   z/The number of labels should be greater than oner   r_   r`   )ignore_index)r1   logitsr3   r4   )rB   r  rc   r  rd   rT   r   r   r  rP   rh   r   r  loss_functionsemantic_loss_ignore_indexr   r3   r4   )rW   rY   r  r   outputsrm   r   r   r   rT   r   r   patch_heightpatch_widthr  r  r  r1   s                     r.   rp   z'Sapiens2ForSemanticSegmentation.forward  sJ   B $++"8"8A"=NOO$**\4V4'3'9'9$
Avu[[++
%/
C%@zjQRm%/
C%@zjQRm-|+00A8W8W4W4Y1YZ",,Q2:::r<Yde!!+.%%ff4;;CiCi%jD&!//))	
 	
r-   rq   )r$   r%   r&   r   rG   r   r   r)   r*   
LongTensorr   r   r   rp   rr   rs   s   @r.   r  r    sm    ~   +/9
''9
   4'9
 +,	9

 
!9
  9
r-   r  c                    |dvrt        d      | j                  dk7  rt        d      | j                  \  }}}}d}|dk(  r+d}| j                         } | dddddd	f    | dddddd	f<   | j	                  |d
|||      } | j                         }|j                  d
      \  }	}
| dd|
d	f   |dd|	d	f<   | dd|	d	f   |dd|
d	f<   |j	                  ||||f      }|j                  d
      }|S )a  Flip the flipped heatmaps back to the original form.

    Args:
        output_flipped (`torch.tensor` of shape `(batch_size, num_keypoints, height, width)`):
            The output heatmaps obtained from the flipped images.
        flip_pairs (`torch.Tensor` of shape `(num_keypoints, 2)`):
            Pairs of keypoints which are mirrored (for example, left ear -- right ear).
        target_type (`str`, *optional*, defaults to `"gaussian-heatmap"`):
            Target type to use. Can be gaussian-heatmap or combined-target.
            gaussian-heatmap: Classification target with gaussian distribution.
            combined-target: The combination of classification target (response map) and regression target (offset map).
            Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020).

    Returns:
        torch.Tensor: heatmaps that flipped back to the original image
    )gaussian-heatmapcombined-targetz9target_type should be gaussian-heatmap or combined-targetr   zCoutput_flipped should be [batch_size, num_keypoints, height, width]r   r  r   N.r`   )rc   rA  rd   cloner   unbindflip)output_flipped
flip_pairstarget_typerm   num_keypointsr   r   channelsoutput_flipped_backleft_indicesright_indicess              r.   	flip_backr  D  sA   " AATUUa^__/=/C/C,JvuH'''--/(6q!$Q$|(D'Dq!$Q$|$#++JHfeTN(..0 #-"3"3B"7L-0>q-QT?T0U<,-1?<QT@T1U=#-.-55z=RXZ_6`a-2226r-   zfacebook/sapiens2-pose-0.4bz
    The Sapiens2 model with a pose estimation head on top (a set of heatmap predictors on top of the hidden states output).
    )r  r    c                        e Zd Zdef fdZee	 	 	 ddej                  dej                  dz  dej                  dz  dej                  dz  de
e   d	efd
              Z xZS )Sapiens2ForPoseEstimationrB   c                     t         |   |       |j                  | _        t        |      | _        t        |      | _        | j                          y rq   r   rV   s     r.   rG   z"Sapiens2ForPoseEstimation.__init__u  r  r-   NrY   r  r  label_weightsr   r[   c                 B    | j                   |fi |}|j                  \  }}}	}
| j                  j                  }t	        |t
              r|n|d   }t	        |t
              r|n|d   }|	|z  }|
|z  }|j                  ddd| j                  j                  z   df   }|j                  dd      j                  |d||      }| j                  |      }|t        ||      }d}|t        j                  |||      }t        |||j                  |j                         S )a   
        flip_pairs (`torch.Tensor` of shape `(num_pairs, 2)`, *optional*):
            Pairs of keypoints which are mirrored (for example, left ear -- right ear), used for
            test-time flip augmentation. When provided, the model assumes `pixel_values` contains
            horizontally-flipped images and calls `flip_back` on the output heatmaps to restore the
            original orientation.
        labels (`torch.FloatTensor` of shape `(batch_size, num_keypoints, height, width)`, *optional*):
            Heatmap ground truth for computing the loss.
        label_weights (`torch.FloatTensor` of shape `(batch_size, num_labels, 1, 1)` or `(batch_size, num_labels, height, width)`, *optional*):
            Visibility weights for each keypoint. Must be broadcastable to the shape of `labels`.

        Example:

        ```python
        >>> from transformers import AutoImageProcessor, AutoModel
        >>> from transformers.image_utils import load_image
        >>> import torch

        >>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pose-0.4b")
        >>> model = AutoModel.from_pretrained("facebook/sapiens2-pose-0.4b")

        >>> boxes = [[[270.8, 0.6, 294.1, 379.5]]]
        >>> inputs = image_processor(image, boxes=boxes, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)

        >>> outputs.heatmaps.shape
        torch.Size([1, 308, 256, 192])
        ```
        r   r   Nr_   r`   )re   )r1   r2   r3   r4   )r  rd   rB   rT   r   r   r  rP   rh   r   r  r  Fmse_lossr0   r3   r4   )rW   rY   r  r  r  r   r	  rm   r   r   r   rT   r   r   r
  r  r  r  r2   r1   s                       r.   rp   z!Sapiens2ForPoseEstimation.forward|  s*   R $**\4V4'3'9'9$
Avu[[++
%/
C%@zjQRm%/
C%@zjQRm-|+00A8W8W4W4Y1YZ",,Q2:::r<Yde##K0! :6H::h}ED*!//))	
 	
r-   NNN)r$   r%   r&   r   rG   r   r   r)   r*   r   r   r   r0   rp   rr   rs   s   @r.   r  r  n  s    ~   +/+/26@
''@
 LL4'@
 !!D(	@

 ((4/@
 +,@
 
%@
  @
r-   r  zfacebook/sapiens2-normal-0.4bz
    The Sapiens2 model with a normal estimation head on top (a PixelShuffle-based decoder that predicts surface normal maps).
    c                        e Zd Zdef fdZee	 d	dej                  dej                  dz  de	e
   defd              Z xZS )
Sapiens2ForNormalEstimationrB   c                     t         |   |       |j                  | _        t        |      | _        t        |      | _        | j                          y rq   r   rV   s     r.   rG   z$Sapiens2ForNormalEstimation.__init__  r  r-   NrY   r  r   r[   c                     | j                   |fi |}|j                  \  }}}}| j                  j                  }	t	        |	t
              r|	n|	d   }
t	        |	t
              r|	n|	d   }||
z  }||z  }|j                  ddd| j                  j                  z   df   }|j                  dd      j                  |d||      }| j                  |      }d}|t        d      t        |||j                  |j                        S )ae  
        labels (`torch.FloatTensor` of shape `(batch_size, num_labels, height, width)`, *optional*):
            Ground-truth surface normal maps for computing the loss.

        Example:

        ```python
        >>> from transformers import AutoImageProcessor, AutoModel
        >>> from transformers.image_utils import load_image
        >>> import torch

        >>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-normal-0.4b")
        >>> model = AutoModel.from_pretrained("facebook/sapiens2-normal-0.4b")

        >>> inputs = image_processor(image, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)

        >>> outputs.normals.shape
        torch.Size([1, 3, 1024, 768])
        ```
        r   r   Nr_   r`   Training is not yet supported)r1   r7   r3   r4   )r  rd   rB   rT   r   r   r  rP   rh   r   r  NotImplementedErrorr6   r3   r4   )rW   rY   r  r   r	  rm   r   r   r   rT   r   r   r
  r  r  r  r7   r1   s                     r.   rp   z#Sapiens2ForNormalEstimation.forward  s   > $**\4V4'3'9'9$
Avu[[++
%/
C%@zjQRm%/
C%@zjQRm-|+00A8W8W4W4Y1YZ",,Q2:::r<Yde"";/%&EFF,!//))	
 	
r-   rq   )r$   r%   r&   r   rG   r   r   r)   r*   r   r   r6   rp   rr   rs   s   @r.   r%  r%    sm    ~   ,04
''4
 !!D(4
 +,	4

 
'4
  4
r-   r%  zfacebook/sapiens2-pointmap-0.4bz
    The Sapiens2 model with a pointmap head on top (a PixelShuffle-based decoder that predicts per-pixel 3D XYZ
    coordinates, plus an optional scale branch for focal-length normalization).
    c                        e Zd Zdef fdZee	 d	dej                  dej                  dz  de	e
   defd              Z xZS )
Sapiens2ForPointmapEstimationrB   c                    t         |   |       t        |      | _        t	        |      | _        |j                  !|j                  j                  t        |      nt        j                         | _        | j                          y rq   )rF   rG   r  r  rl  r  rp  r  r  r   r  
scale_headr  rV   s     r.   rG   z&Sapiens2ForPointmapEstimation.__init__  sn     "6*
'/ !!-&2D2D2\2\2h &f- 	
 	r-   NrY   r  r   r[   c                 |    | j                   |fi |}|j                  \  }}}}| j                  j                  }	t	        |	t
              r|	n|	d   }
t	        |	t
              r|	n|	d   }||
z  }||z  }|j                  ddd| j                  j                  z   df   }|j                  dd      j                  |d||      }| j                  |      }t	        | j                  t        j                        rdn| j                  |      }d}|t        d      t        ||||j                   |j"                        S )aW  
        labels (`torch.FloatTensor` of shape `(batch_size, 3, height, width)`, *optional*):
            Ground-truth pointmap for computing the loss.

        Example:

        ```python
        >>> from transformers import AutoImageProcessor, AutoModel
        >>> from transformers.image_utils import load_image
        >>> import torch

        >>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-pointmap-0.4b")
        >>> model = AutoModel.from_pretrained("facebook/sapiens2-pointmap-0.4b")

        >>> inputs = image_processor(image, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)

        >>> outputs.pointmaps.shape
        torch.Size([1, 3, 1024, 768])
        ```
        r   r   Nr_   r`   r(  )r1   r:   r;   r3   r4   )r  rd   rB   rT   r   r   r  rP   rh   r   r  r-  r   r  r)  r9   r3   r4   )rW   rY   r  r   r	  rm   r   r   r   rT   r   r   r
  r  r  r  r:   r;   r1   s                      r.   rp   z%Sapiens2ForPointmapEstimation.forward  s6   > $**\4V4'3'9'9$
Avu[[++
%/
C%@zjQRm%/
C%@zjQRm-|+00A8W8W4W4Y1YZ",,Q2:::r<Yde$$[1	#DOOR[[AtWbGc%&EFF.!//))
 	
r-   rq   )r$   r%   r&   r   rG   r   r   r)   r*   r   r   r9   rp   rr   rs   s   @r.   r+  r+    sm    	~ 	  ,06
''6
 !!D(6
 +,	6

 
)6
  6
r-   r+  zfacebook/sapiens2-matting-1bz
    The Sapiens2 model with a matting head on top (a PixelShuffle-based decoder that predicts a
    pre-multiplied RGB foreground and an alpha matte).
    c                        e Zd Zdef fdZee	 d	dej                  dej                  dz  de	e
   defd              Z xZS )
Sapiens2ForImageMattingrB   c                     t         |   |       t        |      | _        t	        |      | _        | j                          y rq   )rF   rG   r  r  rl  r  r  rV   s     r.   rG   z Sapiens2ForImageMatting.__init__^  s3     "6*
'/r-   NrY   r  r   r[   c                 V    | j                   |fi |}|j                  \  }}}}| j                  j                  }	t	        |	t
              r|	n|	d   }
t	        |	t
              r|	n|	d   }||
z  }||z  }|j                  ddd| j                  j                  z   df   }|j                  dd      j                  |d||      }| j                  |      j                         }|ddddf   }|ddddf   }d}|t        d      t        ||||j                  |j                        S )	a  
        labels (`torch.FloatTensor` of shape `(batch_size, 4, height, width)`, *optional*):
            Ground-truth matting targets for computing the loss.

        Example:

        ```python
        >>> from transformers import AutoImageProcessor, AutoModel
        >>> from transformers.image_utils import load_image
        >>> import torch

        >>> image = load_image("http://images.cocodataset.org/val2017/000000004016.jpg")
        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/sapiens2-matting-1b")
        >>> model = AutoModel.from_pretrained("facebook/sapiens2-matting-1b")

        >>> inputs = image_processor(image, return_tensors="pt")
        >>> with torch.inference_mode():
        ...     outputs = model(**inputs)

        >>> outputs.alphas.shape
        torch.Size([1, 1, 1024, 768])
        >>> outputs.foregrounds.shape
        torch.Size([1, 3, 1024, 768])
        ```
        r   r   Nr_   r`   r   r(  )r1   r>   r?   r3   r4   )r  rd   rB   rT   r   r   r  rP   rh   r   r  sigmoidr)  r=   r3   r4   )rW   rY   r  r   r	  rm   r   r   r   rT   r   r   r
  r  r  r  mattingr?   r>   r1   s                       r.   rp   zSapiens2ForImageMatting.forwardd  s>   B $**\4V4'3'9'9$
Avu[[++
%/
C%@zjQRm%/
C%@zjQRm-|+00A8W8W4W4Y1YZ",,Q2:::r<Yde"";/779a!enAB%&EFF)#!//))
 	
r-   rq   )r$   r%   r&   r   rG   r   r   r)   r*   r   r   r=   rp   rr   rs   s   @r.   r0  r0  V  sm    ~   ,09
''9
 !!D(9
 +,	9

 
$9
  9
r-   r0  )r  r  r%  r+  r0  r  r  r  r#  )r  NN)r  )\r   collections.abcr   r   dataclassesr   numpyr   r)   torch.nn.functionalr   r   r!  r    r	   r  activationsr
   backbone_utilsr   r   integrationsr   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_utilsr   r   processing_utilsr   pytorch_utilsr   utilsr   r   utils.genericr   r   r   utils.output_capturingr   configuration_sapiens2r   r"   r0   r6   r9   r=   r  rA   r   r^   rx   r   r   r   r   r   r   r(   r   r   r   r   r$  r,  r8  r=  rI  rX  rl  r  r  r  r  r  r  r  r  r  r  r%  r+  r0  __all__r,   r-   r.   <module>rG     sC  &  . !      & ! H 7 9  G & @ 7 Y Y 5 2  7^ 7 7 
 <+ < <$ 
 <K < <* 
 <k < <0 
 1 1 1," "J %R0'*38;;HM
\\ 1<  	LL4< DL T\	
 \\:48BII 48n Y'Jbii J (J((   %II%<<% 
% <<	%
 LL4'% S[% T\% T\% 5<<%&%D||+0<<>Cll
5<<%&B	UU\\ 	U# 	U%,, 	U?)		 ?)D+ +<")) <ryy  %ryy %0+. +\B		 BJ5-299 5-p	bii 	( (&-		 -2 -co -c -c`@- @. =
+ =
 =
@ Y
}&= Y
 Y
x 78C
&= C
 9C
L'T ,J
 7 J
J
Z .>
"9 >
>
B 0D
$; D
D
N -B
5 B
B
J	r-   