§
    l¬¸jÕa  ã                  ó‚   — d dl mZ d dl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	dS )	é    )ÚannotationsN)Únn)ÚMLPÚLayerNorm2dc                  óH   ‡ — e Zd ZdZdej        ddfdˆ fd„Zdd„Zdd„Zˆ xZ	S )ÚMaskDecoderaà  Decoder module for generating masks and their associated quality scores using a transformer architecture.

    This class predicts masks given image and prompt embeddings, utilizing a transformer to process the inputs and
    generate mask predictions along with their quality scores.

    Attributes:
        transformer_dim (int): Channel dimension for the transformer module.
        transformer (nn.Module): Transformer module used for mask prediction.
        num_multimask_outputs (int): Number of masks to predict for disambiguating masks.
        iou_token (nn.Embedding): Embedding for the IoU token.
        num_mask_tokens (int): Number of mask tokens.
        mask_tokens (nn.Embedding): Embedding for the mask tokens.
        output_upscaling (nn.Sequential): Neural network sequence for upscaling the output.
        output_hypernetworks_mlps (nn.ModuleList): Hypernetwork MLPs for generating masks.
        iou_prediction_head (nn.Module): MLP for predicting mask quality.

    Methods:
        forward: Predict masks given image and prompt embeddings.
        predict_masks: Internal method for mask prediction.

    Examples:
        >>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module)
        >>> masks, iou_pred = decoder(
        ...     image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, multimask_output=True
        ... )
        >>> print(f"Predicted masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}")
    é   é   Útransformer_dimÚintÚtransformerú	nn.ModuleÚnum_multimask_outputsÚ
activationútype[nn.Module]Úiou_head_depthÚiou_head_hidden_dimÚreturnÚNonec                ó„  •‡— t          ¦   «                              ¦   «          ‰| _        || _        || _        t          j        d‰¦  «        | _        |dz   | _        t          j        | j        ‰¦  «        | _	        t          j
        t          j        ‰‰dz  dd¬¦  «        t          ‰dz  ¦  «         |¦   «         t          j        ‰dz  ‰dz  dd¬¦  «         |¦   «         ¦  «        | _        t          j        ˆfd„t          | j        ¦  «        D ¦   «         ¦  «        | _        t#          ‰|| j        |¦  «        | _        dS )a€  Initialize the MaskDecoder module for generating masks and their associated quality scores.

        Args:
            transformer_dim (int): Channel dimension for the transformer module.
            transformer (nn.Module): Transformer module used for mask prediction.
            num_multimask_outputs (int): Number of masks to predict for disambiguating masks.
            activation (type[nn.Module]): Type of activation to use when upscaling masks.
            iou_head_depth (int): Depth of the MLP used to predict mask quality.
            iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
        é   é   é   ©Úkernel_sizeÚstrideé   c                ó:   •— g | ]}t          ‰‰‰d z  d¦  «        ‘ŒS ©r   r	   ©r   ©Ú.0Ú_r   s     €úw/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/models/sam/modules/decoders.pyú
<listcomp>z(MaskDecoder.__init__.<locals>.<listcomp>M   ó-   ø€ ÐqÐqÐqÐPQ�S� /°?ÀaÑ3GÈÑKÔKÐqÐqÐqó    N)ÚsuperÚ__init__r   r   r   r   Ú	EmbeddingÚ	iou_tokenÚnum_mask_tokensÚmask_tokensÚ
SequentialÚConvTranspose2dr   Úoutput_upscalingÚ
ModuleListÚrangeÚoutput_hypernetworks_mlpsr   Úiou_prediction_head)Úselfr   r   r   r   r   r   Ú	__class__s    `     €r$   r)   zMaskDecoder.__init__(   s?  øø€ õ& 	‰Œ×ÒÑÔÐØ.ˆÔØ&ˆÔà%:ˆÔ"åœ a¨Ñ9Ô9ˆŒØ4°qÑ8ˆÔÝœ<¨Ô(<¸oÑNÔNˆÔå "¤ÝÔ˜°À1Ñ0DÐRSÐ\]Ð^Ñ^Ô^Ý˜¨1Ñ,Ñ-Ô-ØˆJ‰LŒLÝÔ˜°!Ñ3°_ÈÑ5IÐWXÐabÐcÑcÔcØˆJ‰LŒLñ!
ô !
ˆÔõ *,¬ØqÐqÐqÐqÕUZÐ[_Ô[oÑUpÔUpÐqÑqÔqñ*
ô *
ˆÔ&õ $' Ð8KÈTÔMaÐcqÑ#rÔ#rˆÔ Ð Ð r'   Úimage_embeddingsútorch.TensorÚimage_peÚsparse_prompt_embeddingsÚdense_prompt_embeddingsÚmultimask_outputÚboolú!tuple[torch.Tensor, torch.Tensor]c                óÂ   — |                       ||||¬¦  «        \  }}|rt          dd¦  «        nt          dd¦  «        }|dd…|dd…dd…f         }|dd…|f         }||fS )a   Predict masks given image and prompt embeddings.

        Args:
            image_embeddings (torch.Tensor): Embeddings from the image encoder.
            image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings.
            sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes.
            dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs.
            multimask_output (bool): Whether to return multiple masks or a single mask.

        Returns:
            masks (torch.Tensor): Batched predicted masks.
            iou_pred (torch.Tensor): Batched predictions of mask quality.

        Examples:
            >>> decoder = MaskDecoder(transformer_dim=256, transformer=transformer_module)
            >>> image_emb = torch.rand(1, 256, 64, 64)
            >>> image_pe = torch.rand(1, 256, 64, 64)
            >>> sparse_emb = torch.rand(1, 2, 256)
            >>> dense_emb = torch.rand(1, 256, 64, 64)
            >>> masks, iou_pred = decoder(image_emb, image_pe, sparse_emb, dense_emb, multimask_output=True)
            >>> print(f"Masks shape: {masks.shape}, IoU predictions shape: {iou_pred.shape}")
        )r7   r9   r:   r;   r   Nr   )Úpredict_masksÚslice)	r5   r7   r9   r:   r;   r<   ÚmasksÚiou_predÚ
mask_slices	            r$   ÚforwardzMaskDecoder.forwardR   s‰   € ð< ×,Ò,Ø-ØØ%=Ø$;ð	 -ñ 
ô 
‰ˆˆxð (8ÐH•U˜1˜d‘^”^�^½UÀ1Àa¹[¼[ˆ
Ø�a�a�a˜ Q Q Q¨¨¨Ð)Ô*ˆØ˜A˜A˜A˜z˜MÔ*ˆà�hˆÐr'   c                óÆ  ‡ ‡— t          j        ‰ j        j        ‰ j        j        gd¬¦  «        }|                     d¦  «                             |j        d         dd¦  «        }t          j        ||fd¬¦  «        }t          j        ||j        d         d¬¦  «        }||z   }t          j        ||j        d         d¬¦  «        }|j        \  }	}
}}‰  	                    |||¦  «        \  }}|dd…ddd…f         }|dd…dd‰ j
        z   …dd…f         Š|                     dd¦  «                             |	|
||¦  «        }‰                      |¦  «        }ˆˆ fd„t          ‰ j
        ¦  «        D ¦   «         }t          j        |d¬¦  «        }|j        \  }	}
}}||                     |	|
||z  ¦  «        z                       |	d||¦  «        }‰                      |¦  «        }||fS )z`Predict masks and quality scores using image and prompt embeddings via transformer architecture.r   ©Údiméÿÿÿÿr   Nr   c           	     óV   •— g | ]%} ‰j         |         ‰d d …|d d …f         ¦  «        ‘Œ&S ©N©r3   ©r"   ÚiÚmask_tokens_outr5   s     €€r$   r%   z-MaskDecoder.predict_masks.<locals>.<listcomp>™   óL   ø€ ð -
ð -
ð -
ØLMÐ-ˆDÔ*¨1Ô-¨o¸a¸a¸aÀÀAÀAÀA¸gÔ.FÑGÔGð-
ð -
ð -
r'   )ÚtorchÚcatr+   Úweightr-   Ú	unsqueezeÚexpandÚshapeÚrepeat_interleaver   r,   Ú	transposeÚviewr0   r2   Ústackr4   )r5   r7   r9   r:   r;   Úoutput_tokensÚtokensÚsrcÚpos_srcÚbÚcÚhÚwÚhsÚiou_token_outÚupscaled_embeddingÚhyper_in_listÚhyper_inrB   rC   rO   s   `                   @r$   r@   zMaskDecoder.predict_masks~   s  øø€ õ œ	 4¤>Ô#8¸$Ô:JÔ:QÐ"RÐXYÐZÑZÔZˆØ%×/Ò/°Ñ2Ô2×9Ò9Ð:RÔ:XÐYZÔ:[Ð]_ÐacÑdÔdˆÝ”˜MÐ+CÐDÈ!ÐLÑLÔLˆõ Ô%Ð&6¸¼ÀQ¼ÈQÐOÑOÔOˆØÐ+Ñ+ˆÝÔ)¨(°F´LÀ´OÈÐKÑKÔKˆØ”Y‰
ˆˆ1ˆa�ð ×"Ò" 3¨°Ñ8Ô8‰ˆˆCØ˜1˜1˜1˜a   ˜7œˆØ˜Q˜Q˜Q  Q¨Ô)=Ñ%=Ð >ÀÀÀÐAÔBˆð �mŠm˜A˜qÑ!Ô!×&Ò& q¨!¨Q°Ñ2Ô2ˆØ!×2Ò2°3Ñ7Ô7Ðð-
ð -
ð -
ð -
ð -
ÝQVÐW[ÔWkÑQlÔQlð-
ñ -
ô -
ˆõ ”;˜}°!Ð4Ñ4Ô4ˆØ'Ô-‰
ˆˆ1ˆa�ØÐ.×3Ò3°A°q¸!¸a¹%Ñ@Ô@Ñ@×FÒFÀqÈ"ÈaÐQRÑSÔSˆð ×+Ò+¨MÑ:Ô:ˆà�hˆÐr'   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r7   r8   r9   r8   r:   r8   r;   r8   r<   r=   r   r>   )
r7   r8   r9   r8   r:   r8   r;   r8   r   r>   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚGELUr)   rE   r@   Ú__classcell__©r6   s   @r$   r   r      sŽ   ø€ € € € € ðð ð@ &'Ø&(¤gØØ#&ð(sð (sð (sð (sð (sð (sð (sðT*ð *ð *ð *ðX%ð %ð %ð %ð %ð %ð %ð %r'   r   c                  ól   ‡ — e Zd ZdZdej        ddddddddddfd'ˆ fd„Z	 d(d)d#„Z	 d(d*d$„Zd%„ Z	d&„ Z
ˆ xZS )+ÚSAM2MaskDecodera~
  Transformer-based decoder for predicting instance segmentation masks from image and prompt embeddings.

    This class extends the functionality of the MaskDecoder, incorporating additional features such as high-resolution
    feature processing, dynamic multimask output, and object score prediction.

    Attributes:
        transformer_dim (int): Channel dimension of the transformer.
        transformer (nn.Module): Transformer used to predict masks.
        num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
        iou_token (nn.Embedding): Embedding for IOU token.
        num_mask_tokens (int): Total number of mask tokens.
        mask_tokens (nn.Embedding): Embedding for mask tokens.
        pred_obj_scores (bool): Whether to predict object scores.
        obj_score_token (nn.Embedding): Embedding for object score token.
        use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
        output_upscaling (nn.Sequential): Upscaling layers for output.
        use_high_res_features (bool): Whether to use high-resolution features.
        conv_s0 (nn.Conv2d): Convolutional layer for high-resolution features (s0).
        conv_s1 (nn.Conv2d): Convolutional layer for high-resolution features (s1).
        output_hypernetworks_mlps (nn.ModuleList): List of MLPs for output hypernetworks.
        iou_prediction_head (MLP): MLP for IOU prediction.
        pred_obj_score_head (nn.Linear | MLP): Linear layer or MLP for object score prediction.
        dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
        dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
        dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.

    Methods:
        forward: Predict masks given image and prompt embeddings.
        predict_masks: Predict instance segmentation masks from image and prompt embeddings.
        _get_stability_scores: Compute mask stability scores based on IoU between thresholds.
        _dynamic_multimask_via_stability: Dynamically select the most stable mask output.

    Examples:
        >>> image_embeddings = torch.rand(1, 256, 64, 64)
        >>> image_pe = torch.rand(1, 256, 64, 64)
        >>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
        >>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
        >>> decoder = SAM2MaskDecoder(256, transformer)
        >>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward(
        ...     image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False
        ... )
    r	   r
   Fgš™™™™™©?g\�Âõ(\ï?r   r   r   r   r   r   r   r   r   Úuse_high_res_featuresr=   Úpred_obj_scoresÚpred_obj_scores_mlpÚuse_multimask_token_for_obj_ptrr   r   c                ó  •‡— t          ¦   «                              ¦   «          ‰| _        || _        || _        t          j        d‰¦  «        | _        |dz   | _        t          j        | j        ‰¦  «        | _	        || _
        | j
        rt          j        d‰¦  «        | _        || _        t          j        t          j        ‰‰dz  dd¬¦  «        t          ‰dz  ¦  «         |¦   «         t          j        ‰dz  ‰dz  dd¬¦  «         |¦   «         ¦  «        | _        || _        |r@t          j        ‰‰dz  dd¬¦  «        | _        t          j        ‰‰dz  dd¬¦  «        | _        t          j        ˆfd„t-          | j        ¦  «        D ¦   «         ¦  «        | _        t1          ‰|| j        ||¬¦  «        | _        | j
        r3t          j        ‰d¦  «        | _        |rt1          ‰‰dd¦  «        | _        |	| _        |
| _        || _        d	S )
a  Initialize the SAM2MaskDecoder module for predicting instance segmentation masks.

        This decoder extends the functionality of MaskDecoder, incorporating additional features such as high-resolution
        feature processing, dynamic multimask output, and object score prediction.

        Args:
            transformer_dim (int): Channel dimension of the transformer.
            transformer (nn.Module): Transformer used to predict masks.
            num_multimask_outputs (int): Number of masks to predict when disambiguating masks.
            activation (type[nn.Module]): Type of activation to use when upscaling masks.
            iou_head_depth (int): Depth of the MLP used to predict mask quality.
            iou_head_hidden_dim (int): Hidden dimension of the MLP used to predict mask quality.
            use_high_res_features (bool): Whether to use high-resolution features.
            iou_prediction_use_sigmoid (bool): Whether to use sigmoid for IOU prediction.
            dynamic_multimask_via_stability (bool): Whether to use dynamic multimask via stability.
            dynamic_multimask_stability_delta (float): Delta value for dynamic multimask stability.
            dynamic_multimask_stability_thresh (float): Threshold for dynamic multimask stability.
            pred_obj_scores (bool): Whether to predict object scores.
            pred_obj_scores_mlp (bool): Whether to use MLP for object score prediction.
            use_multimask_token_for_obj_ptr (bool): Whether to use multimask token for object pointer.
        r   r   r   r   r   c                ó:   •— g | ]}t          ‰‰‰d z  d¦  «        ‘ŒS r   r    r!   s     €r$   r%   z,SAM2MaskDecoder.__init__.<locals>.<listcomp>  r&   r'   )Úsigmoidr	   N)r(   r)   r   r   r   r   r*   r+   r,   r-   rr   Úobj_score_tokenrt   r.   r/   r   r0   rq   ÚConv2dÚconv_s0Úconv_s1r1   r2   r3   r   r4   ÚLinearÚpred_obj_score_headÚdynamic_multimask_via_stabilityÚ!dynamic_multimask_stability_deltaÚ"dynamic_multimask_stability_thresh)r5   r   r   r   r   r   r   rq   Úiou_prediction_use_sigmoidr~   r   r€   rr   rs   rt   r6   s    `             €r$   r)   zSAM2MaskDecoder.__init__Ò   s/  øø€ õL 	‰Œ×ÒÑÔÐØ.ˆÔØ&ˆÔà%:ˆÔ"åœ a¨Ñ9Ô9ˆŒØ4°qÑ8ˆÔÝœ<¨Ô(<¸oÑNÔNˆÔà.ˆÔØÔð 	DÝ#%¤<°°?Ñ#CÔ#CˆDÔ Ø/NˆÔ,å "¤ÝÔ˜°À1Ñ0DÐRSÐ\]Ð^Ñ^Ô^Ý˜¨1Ñ,Ñ-Ô-ØˆJ‰LŒLÝÔ˜°!Ñ3°_ÈÑ5IÐWXÐabÐcÑcÔcØˆJ‰LŒLñ!
ô !
ˆÔð &;ˆÔ"Ø ð 	eÝœ9 _°oÈÑ6JÐXYÐbcÐdÑdÔdˆDŒLÝœ9 _°oÈÑ6JÐXYÐbcÐdÑdÔdˆDŒLå)+¬ØqÐqÐqÐqÕUZÐ[_Ô[oÑUpÔUpÐqÑqÔqñ*
ô *
ˆÔ&õ $'ØØØÔ ØØ.ð$
ñ $
ô $
ˆÔ ð Ôð 	WÝ')¤y°À!Ñ'DÔ'DˆDÔ$Ø"ð WÝ+.¨ÀÐQRÐTUÑ+VÔ+V�Ô(ð 0OˆÔ,Ø1RˆÔ.Ø2TˆÔ/Ð/Ð/r'   Nr7   r8   r9   r:   r;   r<   Úrepeat_imageÚhigh_res_featuresúlist[torch.Tensor] | Noneú=tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]c                óx  — |                       ||||||¬¦  «        \  }}	}
}|r#|dd…dd…dd…dd…f         }|	dd…dd…f         }	nJ| j        r!| j        s|                      ||	¦  «        \  }}	n"|dd…dd…dd…dd…f         }|	dd…dd…f         }	|r| j        r|
dd…dd…f         }n|
dd…dd…f         }||	||fS )a›  Predict masks given image and prompt embeddings.

        Args:
            image_embeddings (torch.Tensor): Embeddings from the image encoder with shape (B, C, H, W).
            image_pe (torch.Tensor): Positional encoding with the shape of image_embeddings (B, C, H, W).
            sparse_prompt_embeddings (torch.Tensor): Embeddings of the points and boxes with shape (B, N, C).
            dense_prompt_embeddings (torch.Tensor): Embeddings of the mask inputs with shape (B, C, H, W).
            multimask_output (bool): Whether to return multiple masks or a single mask.
            repeat_image (bool): Flag to repeat the image embeddings.
            high_res_features (list[torch.Tensor] | None, optional): Optional high-resolution features.

        Returns:
            masks (torch.Tensor): Batched predicted masks with shape (B, N, H, W).
            iou_pred (torch.Tensor): Batched predictions of mask quality with shape (B, N).
            sam_tokens_out (torch.Tensor): Batched SAM token for mask output with shape (B, N, C).
            object_score_logits (torch.Tensor): Batched object score logits with shape (B, 1).

        Examples:
            >>> image_embeddings = torch.rand(1, 256, 64, 64)
            >>> image_pe = torch.rand(1, 256, 64, 64)
            >>> sparse_prompt_embeddings = torch.rand(1, 2, 256)
            >>> dense_prompt_embeddings = torch.rand(1, 256, 64, 64)
            >>> decoder = SAM2MaskDecoder(256, transformer)
            >>> masks, iou_pred, sam_tokens_out, obj_score_logits = decoder.forward(
            ...     image_embeddings, image_pe, sparse_prompt_embeddings, dense_prompt_embeddings, True, False
            ... )
        )r7   r9   r:   r;   r‚   rƒ   Nr   r   )r@   r~   ÚtrainingÚ _dynamic_multimask_via_stabilityrt   )r5   r7   r9   r:   r;   r<   r‚   rƒ   rB   rC   rO   Úobject_score_logitsÚsam_tokens_outs                r$   rE   zSAM2MaskDecoder.forward)  s=  € ðJ AE×@RÒ@RØ-ØØ%=Ø$;Ø%Ø/ð ASñ A
ô A
Ñ=ˆˆx˜Ð*=ð ð 	(Ø˜!˜!˜!˜Q˜R˜R    A A A˜+Ô&ˆEØ    1 2 2 ”ˆHˆHØÔ1ð 	(¸$¼-ð 	(Ø"×CÒCÀEÈ8ÑTÔT‰OˆE�8�8à˜!˜!˜!˜Q˜q˜S ! ! ! Q Q Q˜,Ô'ˆEØ    1 Q 3 Ô'ˆHàð 	5 Ô Dð 	5Ø,¨Q¨Q¨Q°°°¨UÔ3ˆNˆNð -¨Q¨Q¨Q°°!°¨VÔ4ˆNà�h Ð0CÐCÐCr'   c                ó*  ‡ ‡— d}‰ j         r:t          j        ‰ j        j        ‰ j        j        ‰ j        j        gd¬¦  «        }d}n,t          j        ‰ j        j        ‰ j        j        gd¬¦  «        }|                     d¦  «                             |j	        d         dd¦  «        }t          j        ||fd¬¦  «        }	|r#t          j
        ||	j	        d         d¬¦  «        }
n |j	        d         |	j	        d         k    sJ ‚|}
|
|z   }
|j	        d         dk    s
J d¦   «         ‚t          j
        ||	j	        d         d¬¦  «        }|
j	        \  }}}}‰                      |
||	¦  «        \  }}
|dd…|dd…f         }|dd…|dz   |dz   ‰ j        z   …dd…f         Š|
                     dd¦  «                             ||||¦  «        }
‰ j        r|€‰                      |
¦  «        }nI‰ j        \  }}}}}|\  }} | | ||
¦  «        |z   ¦  «        ¦  «        } | ||¦  «        |z   ¦  «        }ˆˆ fd„t#          ‰ j        ¦  «        D ¦   «         }t          j        |d¬¦  «        }|j	        \  }}}}||                     ||||z  ¦  «        z                       |d||¦  «        }‰                      |¦  «        }‰ j         r+|dk    sJ ‚‰                      |dd…ddd…f         ¦  «        }n$d	|                     |j	        d         d¦  «        z  }||‰|fS )
zYPredict instance segmentation masks from image and prompt embeddings using a transformer.r   rG   r   rI   z@image_pe should have size 1 in batch dim (from `get_dense_pe()`)Nr   c           	     óV   •— g | ]%} ‰j         |         ‰d d …|d d …f         ¦  «        ‘Œ&S rK   rL   rM   s     €€r$   r%   z1SAM2MaskDecoder.predict_masks.<locals>.<listcomp>¢  rP   r'   g      $@)rr   rQ   rR   rx   rS   r+   r-   rT   rU   rV   rW   r   r,   rX   rY   rq   r0   r2   rZ   r4   r}   Únew_ones) r5   r7   r9   r:   r;   r‚   rƒ   Úsr[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   Údc1Úln1Úact1Údc2Úact2Úfeat_s0Úfeat_s1rf   rg   rB   rC   r‰   rO   s    `                              @r$   r@   zSAM2MaskDecoder.predict_masksm  s©  øø€ ð ˆØÔð 	_Ý!œIàÔ(Ô/Ø”NÔ)ØÔ$Ô+ðð
 ðñ ô ˆMð ˆAˆAå!œI t¤~Ô'<¸dÔ>NÔ>UÐ&VÐ\]Ð^Ñ^Ô^ˆMØ%×/Ò/°Ñ2Ô2×9Ò9Ð:RÔ:XÐYZÔ:[Ð]_ÐacÑdÔdˆÝ”˜MÐ+CÐDÈ!ÐLÑLÔLˆð ð 	#ÝÔ)Ð*:¸F¼LÈ¼OÐQRÐSÑSÔSˆCˆCà#Ô)¨!Ô,°´¸Q´Ò?Ð?Ð?Ð?Ø"ˆCØÐ+Ñ+ˆØŒ~˜aÔ  AÒ%Ð%Ð%Ð'iÑ%Ô%Ð%ÝÔ)¨(°F´LÀ´OÈÐKÑKÔKˆØ”Y‰
ˆˆ1ˆa�ð ×"Ò" 3¨°Ñ8Ô8‰ˆˆCØ˜1˜1˜1˜a   ˜7œˆØ˜Q˜Q˜Q  A¡¨¨Q©°Ô1EÑ)EÐ FÈÈÈÐIÔJˆð �mŠm˜A˜qÑ!Ô!×&Ò& q¨!¨Q°Ñ2Ô2ˆØÔ)ð 	IÐ->Ð-FØ!%×!6Ò!6°sÑ!;Ô!;ÐÐà(,Ô(=Ñ%ˆC��d˜C Ø0ÑˆG�WØ!%  c c¨#¨#¨c©(¬(°WÑ*<Ñ&=Ô&=Ñ!>Ô!>ÐØ!%  c cÐ*<Ñ&=Ô&=ÀÑ&GÑ!HÔ!HÐð-
ð -
ð -
ð -
ð -
ÝQVÐW[ÔWkÑQlÔQlð-
ñ -
ô -
ˆõ ”;˜}°!Ð4Ñ4Ô4ˆØ'Ô-‰
ˆˆ1ˆa�ØÐ.×3Ò3°A°q¸!¸a¹%Ñ@Ô@Ñ@×FÒFÀqÈ"ÈaÐQRÑSÔSˆð ×+Ò+¨MÑ:Ô:ˆØÔð 	QØ˜’6�6�6�6Ø"&×":Ò":¸2¸a¸a¸aÀÀAÀAÀA¸g¼;Ñ"GÔ"GÐÐð #'¨×):Ò):¸8¼>È!Ô;LÈaÑ)PÔ)PÑ"PÐà�h Ð1DÐDÐDr'   c                ó,  — |                      d¦  «        }t          j        || j        k    d¬¦  «                             ¦   «         }t          j        || j         k    d¬¦  «                             ¦   «         }t          j        |dk    ||z  d¦  «        S )zNCompute mask stability scores based on IoU between upper and lower thresholds.éþÿÿÿrI   rG   r   g      ð?)ÚflattenrQ   Úsumr   ÚfloatÚwhere)r5   Úmask_logitsÚarea_iÚarea_us       r$   Ú_get_stability_scoresz%SAM2MaskDecoder._get_stability_scores´  s†   € à!×)Ò)¨"Ñ-Ô-ˆÝ”˜;¨Ô)OÒOÐUWÐXÑXÔX×^Ò^Ñ`Ô`ˆÝ”˜;¨$Ô*PÐ)PÒPÐVXÐYÑYÔY×_Ò_ÑaÔaˆÝŒ{˜6 Aš: v°¡¸Ñ<Ô<Ð<r'   c                óv  — |dd…dd…dd…dd…f         }|dd…dd…f         }t          j        |d¬¦  «        }t          j        |j        d         |j        ¬¦  «        }|||f         }|                     d¦  «        }|||f         }|                     d¦  «        }|dd…dd…dd…dd…f         }	|dd…dd…f         }
|                      |	¦  «        }|| j        k    }t          j        |d          	                    |	¦  «        |	|¦  «        }t          j        | 	                    |
¦  «        |
|¦  «        }||fS )aƒ  Dynamically select the most stable mask output based on stability scores and IoU predictions.

        This method is used when outputting a single mask. If the stability score from the current single-mask output
        (based on output token 0) falls below a threshold, it instead selects from multi-mask outputs (based on output
        tokens 1-3) the mask with the highest predicted IoU score. This ensures a valid mask for both clicking and
        tracking scenarios.

        Args:
            all_mask_logits (torch.Tensor): Logits for all predicted masks, shape (B, N, H, W) where B is batch size, N
                is number of masks (typically 4), and H, W are mask dimensions.
            all_iou_scores (torch.Tensor): Predicted IoU scores for all masks, shape (B, N).

        Returns:
            mask_logits_out (torch.Tensor): Selected mask logits, shape (B, 1, H, W).
            iou_scores_out (torch.Tensor): Selected IoU scores, shape (B, 1).

        Examples:
            >>> decoder = SAM2MaskDecoder(...)
            >>> all_mask_logits = torch.rand(2, 4, 256, 256)  # 2 images, 4 masks each
            >>> all_iou_scores = torch.rand(2, 4)
            >>> mask_logits, iou_scores = decoder._dynamic_multimask_via_stability(all_mask_logits, all_iou_scores)
            >>> print(mask_logits.shape, iou_scores.shape)
            torch.Size([2, 1, 256, 256]) torch.Size([2, 1])
        Nr   rI   rG   r   )Údevice).NN)
rQ   ÚargmaxÚarangerV   r¡   rT   rŸ   r€   r›   Ú	expand_as)r5   Úall_mask_logitsÚall_iou_scoresÚmultimask_logitsÚmultimask_iou_scoresÚbest_scores_indsÚ
batch_indsÚbest_multimask_logitsÚbest_multimask_iou_scoresÚsinglemask_logitsÚsinglemask_iou_scoresÚstability_scoresÚ	is_stableÚmask_logits_outÚiou_scores_outs                  r$   rˆ   z0SAM2MaskDecoder._dynamic_multimask_via_stability»  s„  € ð4 +¨1¨1¨1¨a¨b¨b°!°!°!°Q°Q°Q¨;Ô7ÐØ-¨a¨a¨a°°°¨eÔ4ÐÝ œ<Ð(<À"ÐEÑEÔEÐÝ”\Ð"6Ô"<¸QÔ"?ÈÔH]Ð^Ñ^Ô^ˆ
Ø 0°Ð=MÐ1MÔ NÐØ 5× ?Ò ?ÀÑ BÔ BÐØ$8¸ÐEUÐ9UÔ$VÐ!Ø$=×$GÒ$GÈÑ$JÔ$JÐ!ð ,¨A¨A¨A¨q°¨s°A°A°A°q°q°q¨LÔ9ÐØ .¨q¨q¨q°!°A°#¨vÔ 6ÐØ×5Ò5Ð6GÑHÔHÐØ$¨Ô(OÒOˆ	õ  œ+Ø�oÔ&×0Ò0Ð1BÑCÔCØØ!ñ
ô 
ˆõ
 œØ×ÒÐ 5Ñ6Ô6Ø!Ø%ñ
ô 
ˆð
  Ð.Ð.r'   )r   r   r   r   r   r   r   r   r   r   r   r   rq   r=   rr   r=   rs   r=   rt   r=   r   r   rK   )r7   r8   r9   r8   r:   r8   r;   r8   r<   r=   r‚   r=   rƒ   r„   r   r…   )r7   r8   r9   r8   r:   r8   r;   r8   r‚   r=   rƒ   r„   r   r…   )rh   ri   rj   rk   r   rl   r)   rE   r@   rŸ   rˆ   rm   rn   s   @r$   rp   rp   ¦   sô   ø€ € € € € ð)ð )ð^ &'Ø&(¤gØØ#&Ø&+Ø#(Ø(-Ø*.Ø+/Ø %Ø$)Ø05ðUUð UUð UUð UUð UUð UUð UUð~ 8<ðBDð BDð BDð BDð BDðV 8<ðEEð EEð EEð EEð EEðN=ð =ð =ð4/ð 4/ð 4/ð 4/ð 4/ð 4/ð 4/r'   rp   )
Ú
__future__r   rQ   r   Úultralytics.nn.modulesr   r   ÚModuler   rp   © r'   r$   ú<module>r·      sÁ   ðð #Ð "Ð "Ð "Ð "Ð "à €€€Ø Ð Ð Ð Ð Ð à 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3ðXð Xð Xð Xð X�"”)ñ Xô Xð XðvI/ð I/ð I/ð I/ð I/�b”iñ I/ô I/ð I/ð I/ð I/r'   