§
    l¬¸j²<  ã                  óö   — d Z ddlmZ ddl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 ddlmZ d>d„Zd?d„Zd@d„ZdAd„Z	 	 dBdCd#„Z e¦   «         	 dDdEd)„¦   «         Z	 	 	 dFdGd-„Z	 	 dHdId5„Z	 dJddd$d6œdKd=„ZdS )Lu  Scale-only calibration for monocular depth models.

The log-depth head predicts relative scene structure (shape); absolute scale is a separate
two-parameter log-affine ``d' = exp(aÂ·log d + b)`` stored in the head's ``cal_a``/``cal_b``
buffers. This module fits ``(a, b)`` by closed-form least squares against ground-truth depth
over a small set of images â€” no gradient training, decoder weights untouched. It powers both
the trainer's automatic post-training calibration and the ``Model.calibrate()`` API.

Auto-calibration uses a "calibrate only if it helps" policy (:func:`select_calibration_cv`):
candidates are scored on held-out images and applied only when they beat the un-calibrated
output, so the absolute scale is fixed for cross-domain models without harming in-domain ones.
é    )Úannotations)ÚPath)ÚAnyN)ÚLOGGER)Úsmart_inference_modeÚmodelútorch.nn.ModuleÚreturnútorch.nn.Module | Nonec                ó4  — t          | d¦  «        r| j        n| }t          |dd¦  «        }|�0t          |t          j        j        ¦  «        st          |dd¦  «        }t          |t          j        j        ¦  «        r|d         n|}t          |d¦  «        r|ndS )zOReturn the Depth head module that carries ``cal_a``/``cal_b`` buffers, or None.Úmoduler   NéÿÿÿÿÚcal_a)Úhasattrr   ÚgetattrÚ
isinstanceÚtorchÚnnÚ
Sequential)r   ÚmÚseqÚheads       úw/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/depth/calibrate.pyÚ_depth_headr      s�   € å  xÑ0Ô0Ð;ˆŒˆ°e€AÝ
�!�W˜dÑ
#Ô
#€CØ
€�z¨#­u¬xÔ/BÑCÔC€Ý�c˜7 DÑ)Ô)ˆÝ  ¥e¤hÔ&9Ñ:Ô:ÐAˆ3ˆrŒ7ˆ7À€DÝ˜4 Ñ)Ô)Ð3ˆ4ˆ4¨tÐ3ó    ÚNonec                ó^   — t          | dd¦  «        }t          |¦  «        r |¦   «          dS dS )u/  Rewind a stateful loader to the epoch start before a partial pass.

    The trainer's InfiniteDataLoader keeps one persistent iterator across ``for`` loops, so a previous pass that broke
    out early (e.g. a fit stopping at ``max_images``) leaves it mid-epoch and the next loop silently resumes there.
    Every pass here that wants "the first N" must rewind first â€” the plot pass in particular must see the same leading
    batches BaseValidator plotted as ``val_batch{ni}.jpg``. Plain DataLoaders and list fixtures restart on every
    ``__iter__``.
    ÚresetN)r   Úcallable)Ú
dataloaderr   s     r   Ú_rewindr!   &   s<   € õ �J ¨Ñ.Ô.€EÝ��„ð Øˆ‰Œˆˆˆðð r   Úlog_predú
np.ndarrayÚlog_gtÚaÚfloatÚbc                ó"  — |t          j        | t           j        ¬¦  «        z  |z   t          j        |t           j        ¬¦  «        z
  }t          t          j        t          j        |¦  «        t          j        d¦  «        k     ¦  «        ¦  «        S )u®  Î´1 under no per-image alignment after applying ``d' = exp(aÂ·log_pred + b)``.

    Î´1 is the fraction of pixels with ``max(d'/gt, gt/d') < 1.25``; in log space that is ``|aÂ·log_pred + b âˆ’ log_gt| <
    log(1.25)``. This is the deployment metric (raw absolute scale, the ``align="none"`` protocol) the policy optimizes
    â€” the val scoreboard's default ``align="median"`` is scale-invariant and cannot see calibration.
    ©Údtypeg      ô?)ÚnpÚasarrayÚfloat64r&   ÚmeanÚabsÚlog)r"   r$   r%   r'   Úlds        r   Ú_delta1_noner2   4   si   € ð �bŒj˜­¬Ð4Ñ4Ô4Ñ
4°qÑ
8½B¼JÀvÕUWÔU_Ð<`Ñ<`Ô<`Ñ	`€BÝ•”�œ ™œ¥b¤f¨T¡l¤lÒ2Ñ3Ô3Ñ4Ô4Ð4r   Úlp_fitÚlg_fitÚlp_scoreÚlg_scoreúdict[str, Any]c           	     ó`  ‡‡— t          j        | t           j        ¬¦  «        } t          j        |t           j        ¬¦  «        }dddt          t          j        || z
  ¦  «        ¦  «        fg}ˆˆfd„|D ¦   «         }t          |d„ ¬¦  «        }|d         |d	         |d
         d„ |D ¦   «         dœS )u+  Pick the calibration that best improves *held-out* raw-scale Î´1 â€” "calibrate only if it helps".

    Two candidates are fit on the ``*_fit`` log-pixel arrays and scored on the independent ``*_score`` arrays under
    :func:`_delta1_none`:
    - ``identity`` (a=1, b=0): no calibration,
    - ``scale-only`` (a=1, b=mean(log_gt âˆ’ log_pred)): a global scale.
    The winner is the highest held-out Î´1, with ties favoring identity â€” so a calibration that does not generalize is
    rejected and auto-cal does no harm. (An affine log-slope candidate was evaluated and removed: the extra parameter
    overfits within-dataset cross-validation and harms cross-distribution generalization.)

    Returns:
        dict with ``a``, ``b`` (floats of the winner), ``name``, and ``scores`` (per-candidate Î´1).
    r)   )Úidentityç      ð?ç        ú
scale-onlyr:   c                óD   •— g | ]\  }}}|||t          ‰‰||¦  «        f‘ŒS © )r2   )Ú.0Únamer%   r'   r6   r5   s       €€r   ú
<listcomp>z&select_calibration.<locals>.<listcomp>X   s7   ø€ Ð`Ð`Ð`ÁzÀtÈQÐPQˆt�Q˜�<¨°(¸A¸qÑAÔAÐBÐ`Ð`Ð`r   c                ó   — | d         S )Né   r>   )Úss    r   ú<lambda>z$select_calibration.<locals>.<lambda>Y   s
   €  Q q¤T€ r   )Úkeyé   é   r   c                ó,   — i | ]}|d          |d         “ŒS )r   rC   r>   )r?   rD   s     r   ú
<dictcomp>z&select_calibration.<locals>.<dictcomp>Z   s#   € ÐC_ÐC_ÐC_ÐSTÀAÀaÄDÈ!ÈAÌ$ÐC_ÐC_ÐC_r   )r%   r'   r@   Úscores)r+   r,   r-   r&   r.   Úmax)r3   r4   r5   r6   Ú
candidatesÚscoredÚbests     ``   r   Úselect_calibrationrP   ?   s¾   øø€ õ& ŒZ˜¥b¤jÐ1Ñ1Ô1€FÝŒZ˜¥b¤jÐ1Ñ1Ô1€FàØ	�s�E¥"¤'¨&°6©/Ñ":Ô":Ñ;Ô;Ð<ð€Jð aÐ`Ð`Ð`Ð`ÐU_Ð`Ñ`Ô`€FÝˆv˜>˜>Ð*Ñ*Ô*€DØ�a”˜t Aœw°°Q´ÐC_ÐC_ÐX^ÐC_ÑC_ÔC_Ð`Ð`Ð`r   r;   rH   Úpairsú#list[tuple[np.ndarray, np.ndarray]]ÚmarginÚfoldsÚintc           
     ó  ‡ ‡‡‡— ddg}t          dt          |t          ‰ ¦  «        ¦  «        ¦  «        Šd„ |D ¦   «         Št          ‰¦  «        D �]
Šˆˆˆ fd„t          t          ‰ ¦  «        ¦  «        D ¦   «         }ˆˆˆ fd„t          t          ‰ ¦  «        ¦  «        D ¦   «         }|r|sŒ\t	          t          j        d„ |D ¦   «         ¦  «        t          j        d„ |D ¦   «         ¦  «        t          j        d	„ |D ¦   «         ¦  «        t          j        d
„ |D ¦   «         ¦  «        ¦  «        d         }|D ]#}‰|                              ||         ¦  «         Œ$�Œˆfd„|D ¦   «         }d}	|dd…         D ]}||         ||	         |z   k    r|}	Œ|	dk    rd\  }
}nbt          j        d„ ‰ D ¦   «         ¦  «        }t          j        d„ ‰ D ¦   «         ¦  «        }dt          t          j	        ||z
  ¦  «        ¦  «        }}
|
||	|dœS )uÜ  Cross-validated "calibrate only if it helps": choose a candidate by K-fold held-out Î´1.

    ``pairs`` is a list of per-image ``(log_pred, log_gt)`` arrays. Each candidate type is scored on every fold while
    held out (fit on the rest) via :func:`select_calibration`, and the per-type held-out Î´1 is averaged across folds â€”
    so every image contributes to scoring exactly once and a candidate that only wins on one noisy split cannot be
    selected. The winning *type* must beat identity's mean held-out Î´1 by ``margin`` (ties favor the simpler type); the
    final ``(a, b)`` is then refit on all pairs.

    Returns:
        dict with ``a``, ``b`` (floats), ``name``, and ``cv_scores`` (mean held-out Î´1 per type).
    r9   r<   rH   c                ó   — i | ]}|g “ŒS r>   r>   )r?   Úns     r   rJ   z)select_calibration_cv.<locals>.<dictcomp>o   s   € Ð%Ð%Ð%˜!��2Ð%Ð%Ð%r   c                ó2   •— g | ]}|‰z  ‰k    ¯‰|         ‘ŒS r>   r>   ©r?   ÚiÚfÚkrQ   s     €€€r   rA   z)select_calibration_cv.<locals>.<listcomp>q   s&   ø€ ÐAÐAÐA˜A°a¸!±e¸q²j°jˆu�QŒx°j°j°jr   c                ó2   •— g | ]}|‰z  ‰k    ¯‰|         ‘ŒS r>   r>   rZ   s     €€€r   rA   z)select_calibration_cv.<locals>.<listcomp>r   s&   ø€ ÐCÐCÐC˜a¸¸A¹Àº
¸
��q”¸
¸
¸
r   c                ó   — g | ]
}|d          ‘ŒS ©r   r>   ©r?   Úps     r   rA   z)select_calibration_cv.<locals>.<listcomp>v   ó   € Ð.Ð.Ð. Q˜A˜aœDÐ.Ð.Ð.r   c                ó   — g | ]
}|d          ‘ŒS ©rG   r>   ra   s     r   rA   z)select_calibration_cv.<locals>.<listcomp>w   rc   r   c                ó   — g | ]
}|d          ‘ŒS r`   r>   ra   s     r   rA   z)select_calibration_cv.<locals>.<listcomp>x   ó   € Ð0Ð0Ð0 Q˜A˜aœDÐ0Ð0Ð0r   c                ó   — g | ]
}|d          ‘ŒS re   r>   ra   s     r   rA   z)select_calibration_cv.<locals>.<listcomp>y   rg   r   rK   c           	     ó`   •— i | ]*}|t          t          j        ‰|         ¦  «        ¦  «        “Œ+S r>   )r&   r+   r.   )r?   rX   Úper_folds     €r   rJ   z)select_calibration_cv.<locals>.<dictcomp>}   s1   ø€ Ð	8Ð	8Ð	8¨Qˆ!�U•2”7˜8 Aœ;Ñ'Ô'Ñ(Ô(Ð	8Ð	8Ð	8r   rG   N)r:   r;   c                ó   — g | ]
}|d          ‘ŒS r`   r>   ra   s     r   rA   z)select_calibration_cv.<locals>.<listcomp>†   ó   € Ð1Ð1Ð1 a˜Q˜qœTÐ1Ð1Ð1r   c                ó   — g | ]
}|d          ‘ŒS re   r>   ra   s     r   rA   z)select_calibration_cv.<locals>.<listcomp>‡   rl   r   r:   )r%   r'   r@   Ú	cv_scores)
rL   ÚminÚlenÚrangerP   r+   ÚconcatenateÚappendr&   r.   )rQ   rS   rT   ÚnamesÚfitÚscorerD   rX   ÚcvrO   r%   r'   ÚlpÚlgr\   r]   rj   s   `             @@@r   Úselect_calibration_cvrz   ]   sY  øøøø€ ð  ˜Ð&€EÝˆA�s�5�#˜e™*œ*Ñ%Ô%Ñ&Ô&€AØ%Ð%˜uÐ%Ñ%Ô%€HÝ�1‰XŒXð %ñ %ˆØAÐAÐAÐAÐAÐA¥¥s¨5¡z¤zÑ!2Ô!2ÐAÑAÔAˆØCÐCÐCÐCÐCÐC¥5­¨U©¬Ñ#4Ô#4ÐCÑCÔCˆØð 	˜%ð 	ØÝÝŒNÐ.Ð.¨#Ð.Ñ.Ô.Ñ/Ô/ÝŒNÐ.Ð.¨#Ð.Ñ.Ô.Ñ/Ô/ÝŒNÐ0Ð0¨%Ð0Ñ0Ô0Ñ1Ô1ÝŒNÐ0Ð0¨%Ð0Ñ0Ô0Ñ1Ô1ñ	
ô 
ð
 ôˆð ð 	%ð 	%ˆAØ�QŒK×Ò˜q œtÑ$Ô$Ð$Ð$ñ	%à	8Ð	8Ð	8Ð	8°%Ð	8Ñ	8Ô	8€BØ€DØ�1�2�2ŒYð ð ˆØˆaŒ5�2�d”8˜fÑ$Ò$Ð$ØˆDøàˆzÒÐØ‰ˆˆ1ˆ1åŒ^Ð1Ð1¨5Ð1Ñ1Ô1Ñ2Ô2ˆÝŒ^Ð1Ð1¨5Ð1Ñ1Ô1Ñ2Ô2ˆØ•E�"œ' " r¡'Ñ*Ô*Ñ+Ô+ˆ1ˆØ˜ D°rÐ:Ð:Ð:r   ç      Y@Údeviceútorch.device | strÚ
max_imagesÚ	max_depthc                óä  — t          | ¦  «        }t          |j        ¦  «        t          |j        ¦  «        }}|j                             d¦  «         |j                             d¦  «         t          |¦  «         t          j                             d¦  «        }g }	d}
	 |D �]_}|d          	                    |¦  «                             ¦   «         dz  }|d          	                    |¦  «                             ¦   «         }|j
        dk    r|                     d¦  «        } | |¦  «                             ¦   «         }|j
        dk    r|                     d¦  «        }|j        d	d
…         |j        d	d
…         k    r%t          j        ||j        d	d
…         dd¬¦  «        }t          ||¦  «        D �]3\  }}|dk    ||k     z  |dk    z  t!          j        |¦  «        z  }|                     ¦   «         sŒDt!          j        ||         ¦  «                             ¦   «                              ¦   «                              ¦   «         }t!          j        ||         ¦  «                             ¦   «                              ¦   «                              ¦   «         }|j        dk    r-|                     |j        dd¬¦  «        }||         ||         }}|	                     ||f¦  «         �Œ5|
|j        d         z  }
|
|k    r n�Œa|j                             |¦  «         |j                             |¦  «         n9# |j                             |¦  «         |j                             |¦  «         w xY w|	S )u.  Run the model over the loader and return a list of per-image ``(log_pred, log_gt)`` arrays.

    One entry per image (each subsampled to â‰¤20k valid pixels) so callers can split images into independent fit/score
    sets. Only GT inside ``(0.001, max_depth)`` is collected â€” the same population ``DepthMetrics`` evaluates (Eigen
    protocol), so invalid far GT cannot steer the fitted scale or the held-out Î´1 the selection policy trusts.
    Calibration buffers are reset to identity for the duration so the fit sees the raw output, then restored.
    r:   r;   r   Úimgéÿ   ÚdepthrC   rG   éþÿÿÿNÚbilinearT)ÚsizeÚmodeÚalign_cornersçü©ñÒMbP?i N  F)Úreplace)r   r&   r   Úcal_bÚfill_r!   r+   ÚrandomÚdefault_rngÚtoÚndimÚ	unsqueezeÚshapeÚFÚinterpolateÚzipr   ÚisfiniteÚanyr0   ÚdetachÚcpuÚnumpyr†   Úchoicers   )r   r    r|   r~   r   r   Úa0Úb0ÚrngrQ   ÚseenÚbatchr�   ÚgtÚpredÚpiÚgiÚvalidrx   ry   Úidxs                        r   Ú_collect_logpairsr§   Œ   s  € õ �uÑÔ€DÝ�4”:ÑÔ¥ d¤jÑ 1Ô 1ˆ€BØ„J×Ò�SÑÔÐØ„J×Ò�SÑÔÐÝˆJÑÔÐÝ
Œ)×
Ò
 Ñ
"Ô
"€CØ€EØ€DðØð 	ñ 	ˆEØ˜”,—/’/ &Ñ)Ô)×/Ò/Ñ1Ô1°CÑ7ˆCØ�w”×"Ò" 6Ñ*Ô*×0Ò0Ñ2Ô2ˆBØŒw˜!Š|ˆ|Ø—\’\ !‘_”_�Ø�5˜‘:”:×#Ò#Ñ%Ô%ˆDØŒy˜AŠ~ˆ~Ø—~’~ aÑ(Ô(�ØŒz˜"˜#˜#Œ "¤(¨2¨3¨3¤-Ò/Ð/Ý”} T°´¸¸¸´ÀJÐ^bÐcÑcÔc�Ý˜d B™-œ-ð 	'ñ 	'‘��BØ˜dš r¨I¢~Ñ6¸"¸tº)ÑDÅuÄ~ÐVXÑGYÔGYÑY�Ø—y’y‘{”{ð ØÝ”Y˜r %œyÑ)Ô)×0Ò0Ñ2Ô2×6Ò6Ñ8Ô8×>Ò>Ñ@Ô@�Ý”Y˜r %œyÑ)Ô)×0Ò0Ñ2Ô2×6Ò6Ñ8Ô8×>Ò>Ñ@Ô@�Ø”7˜VÒ#Ð#ØŸ*š* R¤W¨f¸e˜*ÑDÔD�CØ œW b¨¤g˜�BØ—’˜b "˜XÑ&Ô&Ð&Ñ&Ø�C”I˜a”LÑ ˆDØ�zÒ!Ð!Ø�ñ "ð 	Œ
×Ò˜ÑÔÐØŒ
×Ò˜ÑÔÐÐøð 	Œ
×Ò˜ÑÔÐØŒ
×Ò˜ÑÔÐÐøøøØ€Ls   ÂI#L7 Ì76M-éÈ   çü©ñÒMb`?údict[str, Any] | Nonec           
     óÖ  — t          | ¦  «        }|€t          j        d¦  «         dS t          |                      |¦  «                             ¦   «                              ¦   «         ||||¦  «        }t          |¦  «        dk     rt          j        d¦  «         dS t          ||¬¦  «        }t          |¦  «        |d<   |j	         
                    |d         ¦  «         |j         
                    |d         ¦  «         d	                     d
„ |d                              ¦   «         D ¦   «         ¦  «        }	t          j        d|d         › d|d         d›d|d         d›d|	› �¦  «         |S )uæ  Select and apply calibration via "calibrate only if it helps" (see :func:`select_calibration_cv`).

    Collects per-image ``(log_pred, log_gt)`` over the loader, splits images into independent fit/score folds (no
    leakage), chooses identity / scale-only by cross-validated raw-scale Î´1, and writes the winner into the head's
    ``cal_a``/``cal_b``.

    Returns:
        (dict | None): The :func:`select_calibration_cv` result dict, or None if no Depth head / too few images.
    Nz:calibrate: no Depth head with cal buffers found; skipping.rH   zNcalibrate: fewer than 2 valid images for fit/score split; calibration skipped.)rS   Úimagesr%   r'   ú c              3  ó,   K  — | ]\  }}|› d |d›�V — ŒdS )ú=ú.4fNr>   )r?   rX   Úvs      r   ú	<genexpr>z,fit_calibration_selective.<locals>.<genexpr>Û   s2   è è € ÐJÐJ©¨¨A˜�n�n˜Q�n�n�nÐJÐJÐJÐJÐJÐJr   rn   zDepth calibration selected 'r@   z' (a=r°   ú b=u   ); CV held-out Î´1 )r   r   Úwarningr§   r�   r&   Úevalrp   rz   r   rŒ   r‹   ÚjoinÚitemsÚinfo)
r   r    r|   r~   rS   r   r   rQ   ÚresrK   s
             r   Úfit_calibration_selectiverº   ¾   sc  € õ" �uÑÔ€DØ€|ÝŒÐSÑTÔTÐTØˆtÝ˜eŸhšh vÑ.Ô.×4Ò4Ñ6Ô6×;Ò;Ñ=Ô=¸zÈ6ÐS]Ð_hÑiÔi€EÝ
ˆ5�z„z�A‚~€~ÝŒÐgÑhÔhÐhØˆtÝ
 ¨fÐ
5Ñ
5Ô
5€CÝ˜‘J”J€Cˆ�MØ„J×Ò�S˜”XÑÔÐØ„J×Ò�S˜”XÑÔÐØ�XŠXÐJÐJ°°[Ô1A×1GÒ1GÑ1IÔ1IÐJÑJÔJÑJÔJ€FÝ
„KØs s¨6¤{ÐsÐs¸¸S¼ÐsÐsÐsÈ#ÈcÌ(ÐsÐsÐsÐkqÐsÐsñô ð ð €Jr   rC   é   r@   ÚstrÚplot_dirú
str | PathÚmax_batchesc	           
     ó   — ddl m}	 t          | ¦  «        }
t          |
j        ¦  «        t          |
j        ¦  «        }}|
j                             d¦  «         |
j                             d¦  «         |                      |¦  «                             ¦   «         } dddd|› d	t          j
        |¦  «        d
›d�g}t          |¦  «        }t          |¦  «         t          j        ¦   «         5  t          t!          |¦  «        |¦  «        D ]ù\  }}|d                              |¦  «                             ¦   «         dz  }|d                              |¦  «                             ¦   «         } | |¦  «                             ¦   «         }|j        dk    r|                     d¦  «        }t          j
        |t          j        |                     d¬¦  «        ¦  «        z  |z   ¦  «        } |	|||g|d|› d�z  |||¬¦  «         Œú	 ddd¦  «         n# 1 swxY w Y   |
j                             |¦  «         |
j                             |¦  «         dS )u�  Write ``val_batch{ni}_calibrated.jpg`` panels (RGB | GT | raw | calibrated) to ``plot_dir``.

    Runs the model with calibration buffers at identity to get the raw prediction; the calibrated column is its
    deterministic affine ``exp(aÂ·log(raw) + b)`` â€” no second forward. The first ``max_batches`` batches are the same
    ones BaseValidator plots as ``val_batch{ni}.jpg`` (val loaders are not shuffled), so the files are directly
    comparable. With the "only if it helps" policy the selected ``name`` may be ``identity``; the panels are still
    written (raw == calibrated), which documents that calibration was a no-op. Buffers are restored afterwards.
    r   )Úplot_depth_panelsr:   r;   ÚRGBÚGTÚrawzcalibrated (z xz.2fú)r�   r‚   rƒ   rC   rG   r‰   )ro   Ú	val_batchz_calibrated.jpg)r¡   Útitlesr~   N)Úultralytics.utils.plottingrÁ   r   r&   r   r‹   rŒ   r�   rµ   r+   Úexpr   r!   r   Úno_gradr•   rq   r�   r‘   r0   Úclamp)r   r    r|   r%   r'   r@   r½   r¿   r~   rÁ   r   rœ   r�   rÇ   Únir    r�   r¡   rÄ   Úcals                       r   Ú_plot_calibrated_batchesrÎ   â   sƒ  € ð& =Ð<Ð<Ð<Ð<Ð<å�uÑÔ€DÝ�4”:ÑÔ¥ d¤jÑ 1Ô 1ˆ€BØ„J×Ò�SÑÔÐØ„J×Ò�SÑÔÐØ�HŠH�VÑÔ×!Ò!Ñ#Ô#€EØ�T˜5Ð"I°Ð"IÐ"I½¼À¹¼Ð"IÐ"IÐ"IÐ"IÐJ€FÝ�H‰~Œ~€HÝˆJÑÔÐÝ	Œ‰Œð ð å�U ;Ñ/Ô/°Ñ<Ô<ð 	ð 	‰IˆB�Ø˜”,—/’/ &Ñ)Ô)×/Ò/Ñ1Ô1°CÑ7ˆCØ�w”×"Ò" 6Ñ*Ô*×0Ò0Ñ2Ô2ˆBØ�%˜‘*”*×"Ò"Ñ$Ô$ˆCØŒx˜1Š}ˆ}Ø—m’m AÑ&Ô&�Ý”)˜A¥¤	¨#¯)ª)¸¨)Ñ*=Ô*=Ñ >Ô >Ñ>ÀÑBÑCÔCˆCØÐØØ�c�
ØÐ: rÐ:Ð:Ð:Ñ:ØØØ%ðñ ô ð ð ð	ðð ð ñ ô ð ð ð ð ð ð øøøð ð ð ð ð" 	„J×Ò�RÑÔÐØ„J×Ò�RÑÔÐÐÐs   Ã*DHÈHÈH)Údataset_hashÚvalidation_splitr   Ú	ckpt_pathústr | Path | NonerÏ   ú
str | NonerÐ   údict | Nonec               ó¼  — ddl m} ddlm}  || d¬¦  «        }	|	                     d¦  «        p|	                     d¦  «        }
|
�t          |
¦  «        €dS  ||
¦  «                             ¦   «         }t          ||||¬	¦  «        }|€dS |d
         |d         }}dD ]v}|	                     |¦  «        }|�]t          |¦  «        �Nt          |¦  «        j         	                    |¦  «         t          |¦  «        j
         	                    |¦  «         Œwt          |	                     d¦  «        p|	                     d¦  «        ¦  «        }t          |j        ¦  «        t          |j
        ¦  «        }}d|d         |d         ||||d|d         dœ	}||	d<   t          j        |	| ¦  «         t          j        dt          | d| ¦  «        › d|d         › d|d›d|d›�¦  «         |�x	 t!          ||||||d         |¦  «         t          j        d|› �¦  «         nD# t"          $ r7}t          j        dt'          |¦  «        j        › d|› d�¦  «         Y d}~nd}~ww xY w|S )uë  Fit calibration for a saved checkpoint in place (used by automatic post-training calibration).

    Loads the checkpoint, selects calibration with the "calibrate only if it helps" policy
    (:func:`fit_calibration_selective`) on ``dataloader`` using a float copy on ``device``, writes the chosen buffers
    into the stored model, and re-saves â€” preserving the rest of the checkpoint.

    Args:
        ckpt_path (str | Path): Path to the ``.pt`` checkpoint file to calibrate in place.
        dataloader (object): Yields batches with ``img`` (uint8, Bx3xHxW) and ``depth`` (BxHxW meters).
        device (str | torch.device): Torch device to run inference on.
        plot_dir (str | Path, optional): If set, also write ``val_batch{ni}_calibrated.jpg`` comparison panels (RGB | GT
            | raw | calibrated) for the first val batches into this directory.
        dataset_hash (str, optional): Immutable dataset manifest identity used for calibration.
        validation_split (str, optional): Dataset-root-relative split used to collect calibration images.
        max_depth (float): Maximum valid GT depth in meters; pixels beyond it are excluded from the fit and the held-out
            Î´1 scoring, matching the val metrics' Eigen protocol.
    r   )Údeepcopy)Ú
torch_loadr™   )Úmap_locationÚemar   N)r   r%   r'   )rÙ   r   Úselectedr@   r¬   ztwo-fold-held-out-delta1rn   )	ÚstatusÚ	candidater¬   r%   r'   rÏ   rÐ   ÚstrategyrK   Údepth_calibrationzAuto-calibration written to z: 'z' a=r°   r³   z&Calibrated val_batch plots written to zCalibrated val plots skipped (z: rÅ   )ÚcopyrÖ   Úultralytics.utils.patchesr×   Úgetr   r&   rº   r   rŒ   r‹   r   Úsaver   r¸   r   rÎ   Ú	Exceptionr´   ÚtypeÚ__name__)rÑ   r    r|   r½   rÏ   rÐ   r   rÖ   r×   ÚckptÚsavedÚworkr¹   r%   r'   rF   r   Ústored_headÚ
provenanceÚes                       r   Úcalibrate_checkpointrì     sÁ  € ð6 ÐÐÐÐÐà4Ð4Ð4Ð4Ð4Ð4àˆ:�i¨eÐ4Ñ4Ô4€DØ�HŠH�U‰OŒOÐ0˜tŸxšx¨Ñ0Ô0€EØ€}� EÑ*Ô*Ð2ØˆØˆ8�E‰?Œ?× Ò Ñ"Ô"€DÝ
# D¨*°fÈ	Ð
RÑ
RÔ
R€CØ
€{ØˆtØˆsŒ8�S˜”X€q€AØð *ð *ˆØ�HŠH�S‰MŒMˆØˆ=�[¨™^œ^Ð7Ý˜‰NŒNÔ ×&Ò& qÑ)Ô)Ð)Ý˜‰NŒNÔ ×&Ò& qÑ)Ô)Ð)øÝ˜dŸhšh u™oœoÐB°·²¸'Ñ1BÔ1BÑCÔC€KÝ�Ô"Ñ#Ô#¥U¨;Ô+<Ñ%=Ô%=€q€AàØ˜”[Ø�h”-ØØØ$Ø,Ø.Ø�kÔ"ð
ð 
€Jð !+€DÐ	ÑÝ	„Jˆt�YÑÔÐÝ
„KØs¥w¨y¸&À)Ñ'LÔ'LÐsÐsÐQTÐU[ÔQ\ÐsÐsÐbcÐsÐsÐsÐlmÐsÐsÐsñô ð ð Ðð	VÝ$ T¨:°v¸qÀ!ÀSÈÄ[ÐRZÑ[Ô[Ð[ÝŒKÐKÀÐKÐKÑLÔLÐLÐLøÝð 	Vð 	Vð 	VÝŒNÐT½DÀ¹G¼GÔ<LÐTÐTÐPQÐTÐTÐTÑUÔUÐUÐUÐUÐUÐUÐUøøøøð	VøøøàÐs   Ç%2H È
IÈ"-IÉI)r   r	   r
   r   )r
   r   )
r"   r#   r$   r#   r%   r&   r'   r&   r
   r&   )
r3   r#   r4   r#   r5   r#   r6   r#   r
   r7   )r;   rH   )rQ   rR   rS   r&   rT   rU   r
   r7   )r{   )
r   r	   r|   r}   r~   rU   r   r&   r
   rR   )r¨   r©   r{   )r   r	   r|   r}   r~   rU   rS   r&   r   r&   r
   rª   )rC   r»   )r   r	   r|   r}   r%   r&   r'   r&   r@   r¼   r½   r¾   r¿   rU   r~   rU   r
   r   )N)rÑ   r¾   r|   r}   r½   rÒ   rÏ   rÓ   rÐ   rÓ   r   r&   r
   rÔ   )Ú__doc__Ú
__future__r   Úpathlibr   Útypingr   rš   r+   r   Útorch.nn.functionalr   Ú
functionalr“   Úultralytics.utilsr   Úultralytics.utils.torch_utilsr   r   r!   r2   rP   rz   r§   rº   rÎ   rì   r>   r   r   ú<module>rõ      sÒ  ððð ð #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð à $Ð $Ð $Ð $Ð $Ð $Ø >Ð >Ð >Ð >Ð >Ð >ð4ð 4ð 4ð 4ðð ð ð ð5ð 5ð 5ð 5ðað að að að@ Øð,;ð ,;ð ,;ð ,;ð ,;ð^ ÐÑÔàhmð.ð .ð .ð .ñ Ôð.ðj ØØð!ð !ð !ð !ð !ðX Øð/ð /ð /ð /ð /ðl #'ð	Eð  $Ø#'ØðEð Eð Eð Eð Eð Eð Eð Er   