§
    ­¸j½¼  ã                  ó^  — d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	 erddlm
Z
 ddlmZ ddlZddlmZmZ dd	lmZmZ dd
lmZ 	 ddlmZ n# e$ r dZY nw xY wddlmZ ddlmZ ddlmZ ddlmZm Z   e¦   «         Z! ed¦  «        pdZ"dd„Z# G d„ de¦  «        Z$ G d„ de¦  «        Z%dS )zUBest-model checkpointing and early stopping callbacks for RF-DETR Lightning training.é    )ÚannotationsN)ÚPath)ÚTYPE_CHECKINGÚcast)ÚAny)ÚRFDETRModelModule)ÚLightningModuleÚTrainer)ÚEarlyStoppingÚModelCheckpoint)ÚTensor)Ú_MultiProcessingLauncher)ÚRFDETREMACallback)Ú
get_logger)Úget_version)Ú_make_fit_loop_stateÚstrip_checkpointzpytorch-lightningÚunknownÚtrainerr
   ÚreturnÚboolc                óf   — t           €dS t          t          | j        dd¦  «        t           ¦  «        S )a)  Return whether *trainer* runs inside a process started by a spawn/fork launcher.

    ``strategy="ddp_spawn"`` / ``"ddp_notebook"`` run ``fit`` in workers created by
    ``_MultiProcessingLauncher``; a nested ``trainer.test()`` there launches again instead of joining the existing
    process group. The subprocess launcher behind ``strategy="ddp"`` and single-device strategies run the loop
    in-process.

    Args:
        trainer: The Lightning Trainer instance.

    Returns:
        ``True`` only for a multiprocessing (spawn/fork) launcher.
    NFÚlauncher)r   Ú
isinstanceÚgetattrÚstrategy)r   s    út/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/training/callbacks/best_model.pyÚ_is_spawned_workerr   +   s/   € õ  Ð'ØˆuÝ•g˜gÔ.°
¸DÑAÔAÕC[Ñ\Ô\Ð\ó    c                  ó.  ‡ — e Zd ZdZdZ	 	 	 	 	 	 d>d?ˆ fd„Ze	 	 	 d@dAd#„¦   «         ZedBd'„¦   «         ZedCd(„¦   «         Z	edDd)„¦   «         Z
dEd-„Ze	 dFdGd1„¦   «         ZedHd2„¦   «         ZdIˆ fd4„ZdJˆ fd5„ZdKd7„ZdLˆ fd8„ZdLd9„ZdMd;„ZedNd=„¦   «         Zˆ xZS )OÚBestModelCallbackuÍ  Track the best validation metric and save best checkpoints during training.

    Extends :class:`pytorch_lightning.callbacks.ModelCheckpoint` to save stripped ``{model, args, epoch}`` ``.pth``
    files (instead of full ``.ckpt`` files) and to track a separate EMA checkpoint in parallel.

    At the end of training the overall winner (regular vs EMA, strict ``>`` for EMA) is copied to
    ``checkpoint_best_total.pth`` and optimizer/scheduler state is stripped via
    :func:`rfdetr.utilities.state_dict.strip_checkpoint`.  The stripped payload records ``best_total_source``
    (``"ema"`` or ``"regular"``) so the winning source is recoverable after reload.

    When EMA tracking is enabled (``monitor_ema`` set), EMA-named checkpoints are always left on disk for clarity:
    ``checkpoint_best_ema.pth`` (backfilled with the final EMA weights if the EMA metric never improved) and
    ``last_ema.pth`` (final EMA weights, mirroring ``last.pth`` for the live model).

    Each track only updates when its own monitor key is actually logged that epoch, and the two tracks are
    checked independently.  On non-eval epochs (``eval_interval > 1`` skips COCO eval entirely) both keys are
    absent and the callback is a full no-op.  When validation evaluates only the EMA model (the default, see
    ``TrainConfig.eval_base_model``), ``monitor_regular`` *is* populated â€” ``COCOEvalCallback`` mirrors the EMA
    score onto it so external monitors keep working â€” but it reports the EMA weights, so ``evaluates_base_model``
    disables the regular track and the EMA track becomes the only one that updates.

    ``state_dict()`` and ``load_state_dict()`` are overridden to persist ``_best_ema`` in the Lightning callback state,
    ensuring that ``trainer.fit(ckpt_path=...)`` resumes EMA high-water-mark tracking from the correct value.

    Args:
        output_dir: Directory where checkpoint files are written.
        monitor_regular: Metric key for the regular model (mAP or mAR, per ``TrainConfig.best_model_metric``).
        monitor_ema: Metric key for the EMA model (mAP or mAR).  ``None`` disables EMA tracking.
        run_test: If ``True``, run ``trainer.test()`` on the best model at the end of training.
        skip_best_epochs: Ignore the first N epochs (0..N-1) when tracking
            best regular and EMA checkpoints.  Useful when fine-tuning from ``pretrain_weights``: the pretrained model's
            epoch-0 mAP can artificially dominate best-checkpoint selection before training adapts to the new dataset.
        smooth_alpha: Exponential-moving-average smoothing factor in ``[0.0, 1.0)`` applied to the regular monitor
            metric before checkpoint comparison.  ``0.0`` (default) disables smoothing and keeps legacy behaviour:
            ``trainer.callback_metrics[monitor_regular]`` is consumed as-is by the parent
            :class:`~pytorch_lightning.callbacks.ModelCheckpoint`.  ``smooth_alpha > 0`` maintains an internal EMA
            state ``self._smoothed_regular = alpha * self._smoothed_regular + (1 - alpha) * raw`` and temporarily
            substitutes the smoothed value into ``trainer.callback_metrics`` for the duration of the parent's
            improvement check; the original raw value is always restored before returning so what gets logged to
            ``metrics.csv`` is unaffected.  Useful for noisy metrics (e.g. keypoint mAP under NLL-Cholesky losses) where
            raw per-epoch swings can lock the best checkpoint to an early local peak.  The EMA accumulator is updated
            on every validation epoch including epochs within the ``skip_best_epochs`` window so the smoothed value
            is pre-warmed by the first eligible comparison.
        evaluates_base_model: Whether validation actually evaluates the base model this run (see
            ``TrainConfig.eval_base_model``). ``False`` disables the regular checkpoint track because
            ``monitor_regular`` then carries the EMA score mirrored by ``COCOEvalCallback`` while this track saves
            base weights. The EMA track still runs, and ``on_fit_end`` promotes its checkpoint to
            ``checkpoint_best_total.pth``.

    Examples:
        Skip the first 3 epochs so pretrained weights do not dominate:

        >>> import tempfile
        >>> from rfdetr.training.callbacks.best_model import BestModelCallback
        >>> with tempfile.TemporaryDirectory() as tmp:
        ...     cb = BestModelCallback(output_dir=tmp, skip_best_epochs=3)
        ...     cb._skip_best_epochs
        3
    z.pthúval/mAP_50_95NTr   ç        Ú
output_dirÚstrÚmonitor_regularÚmonitor_emaú
str | NoneÚrun_testr   Úskip_best_epochsÚintÚsmooth_alphaÚfloatÚevaluates_base_modelr   ÚNonec                ó°  •— t          ¦   «                              |d|dddddd¬¦	  «	         || _        t          |¦  «        | _        || _        d| _        t          |¦  «        | _        t          |t          ¦  «        st          |t          ¦  «        st          d¦  «        ‚|dk     rt          d	¦  «        ‚|| _        t          |t          ¦  «        st          |t          t          f¦  «        st          d
¦  «        ‚t          j        |¦  «        r|dk     s|dk    rt          d¦  «        ‚t          |¦  «        | _        d| _        d| _        d | _        d S )NÚcheckpoint_best_regularÚmaxé   F)	ÚdirpathÚfilenameÚmonitorÚmodeÚ
save_top_kÚsave_on_train_epoch_endÚverboseÚauto_insert_metric_nameÚenable_version_counterr#   ú/skip_best_epochs must be a non-negative integerr   ú3skip_best_epochs must be greater than or equal to 0z*smooth_alpha must be a float in [0.0, 1.0)ç      ð?z"smooth_alpha must be in [0.0, 1.0))ÚsuperÚ__init__Ú_monitor_emar   Ú_evaluates_base_modelÚ	_run_testÚ	_best_emar   Ú_output_dirr   r+   Ú	TypeErrorÚ
ValueErrorÚ_skip_best_epochsr-   ÚmathÚisfiniteÚ_smooth_alphaÚ_smoothed_regularÚ_best_raw_regularÚ_current_pl_module)	Úselfr$   r&   r'   r)   r*   r,   r.   Ú	__class__s	           €r   rA   zBestModelCallback.__init__}   su  ø€ õ 	‰Œ×ÒØØ.Ø#ØØØ$)ØØ$)Ø#(ð 	ñ 
	
ô 
	
ð 
	
ð (ˆÔÝ%)Ð*>Ñ%?Ô%?ˆÔ"Ø!ˆŒØ #ˆŒÝ 
Ñ+Ô+ˆÔÝÐ&­Ñ-Ô-ð 	OµZÐ@PÕRUÑ5VÔ5Vð 	OÝÐMÑNÔNÐNØ˜aÒÐÝÐRÑSÔSÐSØ!1ˆÔÝ�l¥DÑ)Ô)ð 	Jµ¸LÍ3ÕPUÈ,Ñ1WÔ1Wð 	JÝÐHÑIÔIÐIÝŒ}˜\Ñ*Ô*ð 	C¨l¸SÒ.@Ð.@ÀLÐTWÒDWÐDWÝÐAÑBÔBÐBÝ$)¨,Ñ$7Ô$7ˆÔð ),ˆÔð ),ˆÔà:>ˆÔÐÐr   FÚmodel_state_dictúdict[str, Tensor]Ú	args_dictÚobjectr   r
   Ú
model_nameÚmodel_config_dictúobject | NoneÚshare_ema_model_stateúdict[str, object]c                óx  — i }|j         D ]"}|                     ¦   «         }|r
|||j        <   Œ#|r–|                     ¦   «         D ]�}t	          |t
          ¦  «        sŒ|                     d¦  «        }	t	          |	t
          ¦  «        sŒC|	D ];}
|
                     d¦  «        r$|
                     d¦  «        }|| v r| |         |	|
<   Œ<Œ‚| ||j	        d„ |  
                    ¦   «         D ¦   «         |j        t          t          |j	        ¦  «        di idi idœ|g g dœ
}|�||d<   |�||d	<   t          ¦   «         }|�||d
<   |S )aï  Build a PTL-compatible RF-DETR checkpoint payload.

        Args:
            model_state_dict: Model weights with raw (non-prefixed) keys.
            args_dict: Serialized training args/config payload.
            trainer: Active Lightning trainer providing epoch/step counters.
            model_name: Name of the model class (e.g. ``"RFDETRLarge"``).
            model_config_dict: Serialized architecture config needed to reconstruct schema-dependent models.
            share_ema_model_state: Whether EMA callback tensors should share storage with top-level EMA weights.

        Returns:
            Checkpoint dictionary that supports ``Trainer.fit(ckpt_path=...)`` while intentionally omitting
            optimizer/scheduler states.
        Úaverage_model_state_dictzmodule.model.c                ó    — i | ]\  }}d |› �|“ŒS )zmodel.© )Ú.0ÚkÚvs      r   ú
<dictcomp>z?BestModelCallback._build_checkpoint_payload.<locals>.<dictcomp>ã   s$   € ÐPÐPÐP©t¨q°!˜< A˜<˜<¨ÐPÐPÐPr   Ú
state_dict)Úfit_loopÚvalidate_loopÚ	test_loop)
ÚmodelÚargsÚepochrc   Úglobal_stepzpytorch-lightning_versionÚloopsÚ	callbacksÚoptimizer_statesÚlr_schedulersNrV   Úmodel_configÚrfdetr_version)rl   rc   Ú	state_keyÚvaluesr   ÚdictÚgetÚ
startswithÚremoveprefixÚcurrent_epochÚitemsrj   Úptl_versionr   r   )rR   rT   r   rV   rW   rY   Úcallback_statesÚcallbackÚstateÚaverage_stateÚkeyÚ	model_keyÚpayloadÚversions                 r   Ú_build_checkpoint_payloadz+BestModelCallback._build_checkpoint_payload¬   s¼  € ð> .0ˆØÔ)ð 	<ð 	<ˆHØ×'Ò'Ñ)Ô)ˆEØð <Ø6;� Ô 2Ñ3øØ ð 	Mð )×/Ò/Ñ1Ô1ð 
Mð 
M�Ý! %­Ñ.Ô.ð ØØ %§	¢	Ð*DÑ EÔ E�Ý! -µÑ6Ô6ð ØØ(ð Mð M�CØ—~’~ oÑ6Ô6ð MØ$'×$4Ò$4°_Ñ$EÔ$E˜	Ø$Ð(8Ð8Ð8Ø1AÀ)Ô1L˜M¨#Ñ.øð	Mð &ØØÔ*àPÐPÐ7G×7MÒ7MÑ7OÔ7OÐPÑPÔPØ"Ô.Ý)4å0°Ô1FÑGÔGð #/°Ð!3Ø*¨BÐ/ðð ð )ð !#Øð1&
ð &
ˆð8 Ð!Ø$.ˆG�LÑ!ØÐ(Ø&7ˆG�NÑ#õ ‘-”-ˆØÐØ(/ˆGÐ$Ñ%Øˆr   Ú	pl_moduler	   útorch.nn.Modulec                ó”   — t          d| ¦  «        j        }t          |dd¦  «        }t          |t          j        j        ¦  «        r|n|S )zbReturn the live ``nn.Module``, unwrapped from ``torch.compile``'s ``OptimizedModule`` when needed.r   Ú	_orig_modN)r   rg   r   r   ÚtorchÚnnÚModule)rƒ   rg   Úorigs      r   Ú_unwrap_modelzBestModelCallback._unwrap_model  sE   € õ Ð(¨)Ñ4Ô4Ô:ˆÝ�u˜k¨4Ñ0Ô0ˆÝ! $­¬¬Ñ8Ô8ÐCˆtˆt¸eÐCr   c                ó^   — t                                | ¦  «        }|                     ¦   «         S )a	  Resolve live model weights from the active Lightning module.

        Args:
            pl_module: The ``RFDETRModelModule`` being trained.

        Returns:
            State dict from the live, non-EMA model, unwrapped from ``torch.compile`` when needed.
        )r!   r‹   rc   )rƒ   Úraws     r   Ú_get_live_model_state_dictz,BestModelCallback._get_live_model_state_dict  s'   € õ  ×-Ò-¨iÑ8Ô8ˆØ�~Š~ÑÔÐr   c                ó&  — | j         D ]B}t          |dd¦  «        }t          |¦  «        r  |¦   «         }|�t          d|¦  «        c S  nŒCt                               d¦  «         t                               |¦  «        }|                     ¦   «         S )a,  Resolve EMA model weights from the active EMA callback.

        Args:
            trainer: The Lightning Trainer instance.
            pl_module: The ``RFDETRModelModule`` being trained.

        Returns:
            EMA model state dict when available, otherwise the live model state dict.
        Úget_ema_model_state_dictNrS   zPEMA callback weights were unavailable; saving current model weights as fallback.)	rl   r   Úcallabler   ÚloggerÚwarningr!   r‹   rc   )r   rƒ   r{   Úgetterrc   r�   s         r   Ú_get_ema_model_state_dictz+BestModelCallback._get_ema_model_state_dict  s¢   € ð  Ô)ð 	ð 	ˆHÝ˜XÐ'AÀ4ÑHÔHˆFÝ˜ÑÔð Ø#˜V™XœX�
ØÐ)ÝÐ 3°ZÑ@Ô@Ð@Ð@Ð@Ø�ð	õ
 	�ŠÐiÑjÔjÐjÝ×-Ò-¨iÑ8Ô8ˆØ�~Š~ÑÔÐr   Úema_state_dictÚdestr   c                óÈ  — t          d|¦  «        j        }t          |j        dd¦  «        }|�9t	          |d¦  «        r)t          |dd¦  «        €|                     d|i¬¦  «        }t	          |d¦  «        r|                     ¦   «         n|}t          j        |  	                    ||||  
                    |¦  «        |                      ||¦  «        d¬¦  «        |¦  «         dS )	aÄ  Build and save an EMA checkpoint payload to ``dest``.

        Enriches the training config with dataset class names so reloaded checkpoints return the correct labels
        rather than COCO defaults (#509), then writes an unstripped PTL-compatible payload.

        Args:
            trainer: Active Lightning trainer providing epoch/step counters.
            pl_module: The ``RFDETRModelModule`` being trained.
            ema_state_dict: EMA model weights to persist.
            dest: Destination checkpoint path.

        Note:
            Internal helper called by ``on_validation_end`` (best EMA) and ``on_fit_end``
            (guaranteed ``checkpoint_best_ema.pth`` and ``last_ema.pth``).
        r   Úclass_namesNÚ
model_copy©ÚupdateÚ
model_dumpT)rV   rW   rY   )r   Útrain_configr   Ú
datamoduleÚhasattrrš   r�   r‡   Úsaver‚   Ú_resolve_model_nameÚ_serialize_model_config)rP   r   rƒ   r–   r—   Úema_train_configÚdataset_class_namesÚema_args_dicts           r   Ú_write_ema_checkpointz'BestModelCallback._write_ema_checkpoint3  s
  € õ,  Ð 3°YÑ?Ô?ÔLÐÝ% gÔ&8¸-ÈÑNÔNÐàÐ+ÝÐ(¨,Ñ7Ô7ð ,åÐ(¨-¸Ñ>Ô>ÐFà/×:Ò:À=ÐReÐBfÐ:ÑgÔgÐÝ9@ÐAQÐS_Ñ9`Ô9`ÐvÐ(×3Ò3Ñ5Ô5Ð5ÐfvˆÝŒ
Ø×*Ò*ØØØØ×3Ò3°IÑ>Ô>Ø"&×">Ò">¸yÈ.Ñ"YÔ"YØ&*ð +ñ ô ð ñ
	
ô 
	
ð 
	
ð 
	
ð 
	
r   rc   údict[str, Any] | Noneúdict[str, object] | Nonec                ó¸  — t          | dd¦  «        }|€dS t          |t          ¦  «        r|S t          |dd¦  «        }t          |¦  «        sdS  |¦   «         }t          |t          ¦  «        sdS |€.t                               | ¦  «        }|                     ¦   «         }|                     d¦  «        }t          |t          ¦  «        rD|j	        dk    r9d|v r5d„ | 
                    d¬	¦  «                             ¦   «         D ¦   «         |d<   |                     d
¦  «        }t          |t          ¦  «        r"|j	        dk    rd|v r|j        d         dz
  |d<   |S )a“  Serialize the model architecture config when the module exposes one.

        Schema-critical fields (``num_keypoints_per_class``, ``num_classes``) are synced from live model weights so the
        saved config reflects what the model actually learned, not a stale constructor default (e.g. COCO ``[0, 17]``
        when the model was fine-tuned on ``[0, 33]``).

        Args:
            pl_module: The Lightning module whose model config will be serialized.
            state_dict: Pre-computed model state dict. If ``None``, computed from the live model.
                Pass the already-retrieved checkpoint state dict to avoid a redundant copy.
        ro   Nr�   Ú_kp_active_maské   Únum_keypoints_per_classc                ó,   — g | ]}t          |¦  «        ‘ŒS r^   )r+   )r_   Úns     r   ú
<listcomp>z=BestModelCallback._serialize_model_config.<locals>.<listcomp>€  s   € Ð0^Ð0^Ð0^¸Aµ°Q±´Ð0^Ð0^Ð0^r   r3   )Údimzclass_embed.weightÚnum_classesr   )r   r   rs   r‘   r!   r‹   rc   rt   r   ÚndimÚsumÚtolistÚshape)rƒ   rc   ro   r�   Údumpedr�   Ú_kp_maskÚ
_ce_weights           r   r£   z)BestModelCallback._serialize_model_config^  sr  € õ ˜y¨.¸$Ñ?Ô?ˆØÐØ�4Ý�l¥DÑ)Ô)ð 	 ØÐÝ˜\¨<¸Ñ>Ô>ˆ
Ý˜
Ñ#Ô#ð 	Ø�4Ø�‘”ˆÝ˜&¥$Ñ'Ô'ð 	Ø�4ð ÐÝ#×1Ò1°)Ñ<Ô<ˆCØŸšÑ)Ô)ˆJà—>’>Ð"3Ñ4Ô4ˆÝ�h¥Ñ'Ô'ð 	_¨H¬M¸QÒ,>Ð,>ÐC\Ð`fÐCfÐCfØ0^Ð0^ÀÇÂÐRSÀÑATÔAT×A[ÒA[ÑA]ÔA]Ð0^Ñ0^Ô0^ˆFÐ,Ñ-à—^’^Ð$8Ñ9Ô9ˆ
Ý�j¥&Ñ)Ô)ð 	<¨j¬oÀÒ.BÐ.BÀ}ÐX^ÐG^ÐG^Ø$.Ô$4°QÔ$7¸!Ñ$;ˆF�=Ñ!àˆr   c                óª  — t          | dd¦  «        }|�t          |dd¦  «        nd}t          |t          ¦  «        r|                     ¦   «         }|r|S |�t	          |¦  «        j        nd}|                     d¦  «        rt          d|› d�¦  «        ‚|                     d¦  «        r*|                     d	¦  «        r| 	                    d	¦  «        S dS )
a‹  Resolve checkpoint model_name from model_config or config type.

        The CLI/PTL path does not call ``RFDETR.train()``, so ``model_config.model_name`` may be unset. In that case,
        infer the model class from concrete config names like ``RFDETRSmallConfig``.

        Note:
            The ``DeprecatedConfig`` ``RuntimeError`` guard is only reachable from the CLI/PTL path. ``RFDETR.train()``
            pre-populates ``model_config.model_name`` before saving any checkpoint, so the config type-name branch (and
            therefore the ``DeprecatedConfig`` guard) is never reached when training is started via ``RFDETR.train()``.
        ro   NrV   Ú ÚDeprecatedConfigzDeprecated model config 'zL' is no longer supported. Re-train your model using a current model variant.ÚRFDETRÚConfig)
r   r   r%   ÚstripÚtypeÚ__name__ÚendswithÚRuntimeErrorru   Úremovesuffix)rƒ   ro   Úconfigured_nameÚnormalized_nameÚconfig_type_names        r   r¢   z%BestModelCallback._resolve_model_nameˆ  s	  € õ ˜y¨.¸$Ñ?Ô?ˆØGSÐG_�' ,°¸dÑCÔCÐCÐeiˆÝ�o¥sÑ+Ô+ð 	'Ø-×3Ò3Ñ5Ô5ˆOØð 'Ø&Ð&à:FÐ:R�4 Ñ-Ô-Ô6Ð6ÐXZÐà×$Ò$Ð%7Ñ8Ô8ð 	ÝðEÐ,<ð Eð Eð Eñô ð ð ×&Ò& xÑ0Ô0ð 	;Ð5E×5NÒ5NÈxÑ5XÔ5Xð 	;Ø#×0Ò0°Ñ:Ô:Ð:Øˆtr   údict[str, Any]c                ó„   •— t          ¦   «                              ¦   «         }| j        |d<   | j        |d<   | j        |d<   |S )aW  Return callback state including ``_best_ema``, ``_smoothed_regular``, and ``_best_raw_regular``.

        Extends the parent :class:`~pytorch_lightning.callbacks.ModelCheckpoint` state dict with three extra keys so
        that ``trainer.fit(ckpt_path=...)`` resumes the EMA high-water mark, the smoothed-metric accumulator, and the
        raw metric at the smoothed-best epoch from their correct values rather than resetting to ``0.0``.

        Returns:
            State dict with all parent fields plus ``"_best_ema"``, ``"_smoothed_regular"``,
            and ``"_best_raw_regular"``.
        rE   rM   rN   )r@   rc   rE   rM   rN   )rP   r|   rQ   s     €r   rc   zBestModelCallback.state_dict¦  sG   ø€ õ ‘”×"Ò"Ñ$Ô$ˆØ!œ^ˆˆkÑØ%)Ô%;ˆÐ!Ñ"Ø%)Ô%;ˆÐ!Ñ"Øˆr   c                ó  •— t          |¦  «        }t          |                     dd¦  «        ¦  «        | _        t	          j        | j        ¦  «        sd| _        t          |                     dd¦  «        ¦  «        | _        t	          j        | j        ¦  «        sd| _        t          |                     dd¦  «        ¦  «        | _        t	          j        | j        ¦  «        sd| _        t          ¦   «          	                    |¦  «         dS )a  Restore callback state from a Lightning checkpoint.

        Pops ``"_best_ema"``, ``"_smoothed_regular"``, and ``"_best_raw_regular"`` from a shallow copy of *state_dict*
        before delegating to the parent so the parent does not receive unexpected keys.  Each key defaults to ``0.0``
        when absent (e.g. checkpoints saved before these fields were persisted) and is reset to ``0.0`` when the stored
        value is non-finite.

        Args:
            state_dict: Callback state dict as produced by :meth:`state_dict`.
        rE   r#   rM   rN   N)
rs   r-   ÚpoprE   rJ   rK   rM   rN   r@   Úload_state_dict)rP   rc   r|   rQ   s      €r   rÌ   z!BestModelCallback.load_state_dict·  sà   ø€ õ �ZÑ Ô ˆÝ˜uŸyšy¨°cÑ:Ô:Ñ;Ô;ˆŒÝŒ}˜Tœ^Ñ,Ô,ð 	!Ø ˆDŒNÝ!& u§y¢yÐ1DÀcÑ'JÔ'JÑ!KÔ!KˆÔÝŒ}˜TÔ3Ñ4Ô4ð 	)Ø%(ˆDÔ"Ý!& u§y¢yÐ1DÀcÑ'JÔ'JÑ!KÔ!KˆÔÝŒ}˜TÔ3Ñ4Ô4ð 	)Ø%(ˆDÔ"Ý‰Œ×Ò Ñ&Ô&Ð&Ð&Ð&r   Úfilepathc           	     óÞ  — |j         sdS | j        }|€t          d|›d|j        › d�¦  «        ‚t	          |¦  «        }|j                             dd¬¦  «         |                      |¦  «        }t          d|¦  «        j	        }t          |j        dd¦  «        }|�9t          |d	¦  «        r)t          |dd¦  «        €|                     d|i¬
¦  «        }t          |d¦  «        r|                     ¦   «         n|}|                      |¦  «        }	|                      ||¦  «        }
t#          j        |                      ||||	|
¬¦  «        |¦  «         |j        | _        | j        €J ‚|j                             | j        ¦  «        }t#          j        |¦  «        r|                     ¦   «         d›}n|�t7          |¦  «        }nd}t8                               d||j        | j        |¦  «         dS )um  Save stripped ``.pth`` format instead of a full ``.ckpt``.

        Skips on non-main processes.  Intentionally does NOT call ``trainer.save_checkpoint()`` â€” we only want ``{model,
        args, epoch}``.

        Args:
            trainer: The Lightning Trainer instance.
            filepath: Destination path (ends in ``.pth`` via ``FILE_EXTENSION``).
        Nz8BestModelCallback._save_checkpoint called with filepath=z
 at epoch=z but pl_module was not set.T©ÚparentsÚexist_okr   r™   rš   r›   r�   )rV   rW   z.6gr   zDBest regular checkpoint saved to %s (epoch %d, monitor=%s, value=%s))Úis_global_zerorO   rÃ   rw   r   ÚparentÚmkdirrŽ   r   rž   r   rŸ   r    rš   r�   r¢   r£   r‡   r¡   r‚   rj   Ú_last_global_step_savedr6   Úcallback_metricsrt   Ú	is_tensorÚitemr%   r’   Úinfo)rP   r   rÍ   rƒ   Úpth_pathrR   rž   r¥   rT   rV   rW   Úmonitor_valueÚmonitor_displays                r   Ú_save_checkpointz"BestModelCallback._save_checkpointÏ  sJ  € ð Ô%ð 	ØˆFØÔ+ˆ	ØÐÝðOÈ8ð Oð OØ#Ô1ðOð Oð Oñô ð õ ˜‘>”>ˆØŒ×Ò d°TÐÑ:Ô:Ð:ð  ×:Ò:¸9ÑEÔEÐõ Ð/°Ñ;Ô;ÔHˆÝ% gÔ&8¸-ÈÑNÔNÐàÐ+Ý˜ lÑ3Ô3ð ,å˜ m°TÑ:Ô:ÐBà'×2Ò2¸=ÐJ]Ð:^Ð2Ñ_Ô_ˆLÝ18¸À|Ñ1TÔ1TÐf�L×+Ò+Ñ-Ô-Ð-ÐZfˆ	Ø×-Ò-¨iÑ8Ô8ˆ
Ø ×8Ò8¸ÐDTÑUÔUÐÝŒ
Ø×*Ò*Ø ØØØ%Ø"3ð +ñ ô ð ñ		
ô 		
ð 		
ð (/Ô':ˆÔ$ØŒ|Ð'Ð'Ð'ØÔ0×4Ò4°T´\ÑBÔBˆÝŒ?˜=Ñ)Ô)ð 	(Ø!.×!3Ò!3Ñ!5Ô!5Ð;Ð;ˆOˆOØÐ&Ý! -Ñ0Ô0ˆOˆOà'ˆOÝ�ŠØRØØÔ!ØŒLØñ	
ô 	
ð 	
ð 	
ð 	
r   c                ó   •— |j         rdS || _        d}| j        dk    r[| j        rT| j        |j        v rF|j        | j                                      ¦   «         }| j        | j        z  d| j        z
  |z  z   | _        |j        | j	        k     rdS | j        �r_| j        |j        v �rP| j        dk    �r"|�|n#|j        | j                                      ¦   «         }| j
        �| j
                             ¦   «         nt          d¦  «         }|j        | j                 }t          j        | j        |j        |j        ¬¦  «        |j        | j        <   	 t!          ¦   «                              ||¦  «         ||j        | j        <   n# ||j        | j        <   w xY w| j
        �| j
                             ¦   «         nt          d¦  «         }||k    r|| _        n"t!          ¦   «                              ||¦  «         | j        �|j        sdS |j                             | j        t          j        d¦  «        ¦  «                             ¦   «         }|| j        k    r||| _        | j                             dd¬¦  «         |                      ||¦  «        }	|                      |||	| j        dz  ¦  «         t6                               d	||j        ¦  «         dS dS )
a“  Save best regular/EMA checkpoints when the selected validation metric improves.

        Delegates regular-model checkpoint management to the :class:`~pytorch_lightning.callbacks.ModelCheckpoint`
        parent (handles improvement detection, fast_dev_run/sanity guards, ``best_model_path`` and ``best_model_score``
        bookkeeping).  EMA is tracked independently, so the pre-training sanity-check guard below applies to both:
        neither should treat the sanity-check validation pass as a real epoch's result.

        Args:
            trainer: The Lightning Trainer instance.
            pl_module: The ``RFDETRModelModule`` being trained.
        Nr#   r?   Úinf)ÚdtypeÚdeviceTrÏ   úcheckpoint_best_ema.pthz+Best EMA metric improved to %.4f (epoch %d))Úsanity_checkingrO   rL   rC   r6   rÖ   rØ   rM   rw   rI   Úbest_model_scorer-   r‡   Útensorrà   rá   r@   Úon_validation_endrN   rB   rÒ   rt   rE   rF   rÔ   r•   r§   r’   rÙ   )rP   r   rƒ   r�   Úcurrent_rawÚprev_best_scoreÚoriginalÚnew_best_scoreÚema_valr–   rQ   s             €r   ræ   z#BestModelCallback.on_validation_end  sõ  ø€ ð$ Ô"ð 	ØˆFð #,ˆÔð !ˆØÔ Ò#Ð#¨Ô(BÐ#ÀtÄ|ÐW^ÔWoÐGoÐGoØÔ*¨4¬<Ô8×=Ò=Ñ?Ô?ˆCØ%)Ô%7¸$Ô:PÑ%PÐTWÐZ^ÔZlÑTlÐpsÑSsÑ%sˆDÔ"ØÔ  4Ô#9Ò9Ð9ØˆFð Ô%ñ 	>¨$¬,¸'Ô:RÐ*RÑ*Rð Ô! CÒ'Ñ'ð -0¨O S SÀÔAYÐZ^ÔZfÔAg×AlÒAlÑAnÔAn�ØBFÔBWÐBc $Ô"7×"<Ò"<Ñ">Ô">Ð">ÕjoÐpuÑjvÔjvÐiv�Ø"Ô3°D´LÔA�Ý9>¼ØÔ*°(´.ÈÌð:ñ :ô :�Ô(¨¬Ñ6ðFÝ‘G”G×-Ò-¨g°yÑAÔAÐAà=E�GÔ,¨T¬\Ñ:Ð:ø¸X�GÔ,¨T¬\Ñ:ÐEÐEÐEÐEð BFÔAVÐAb Ô!6×!;Ò!;Ñ!=Ô!=Ð!=ÕinÐotÑiuÔiuÐhu�Ø! OÒ3Ð3Ø-8�DÔ*øå‘”×)Ò)¨'°9Ñ=Ô=Ð=ð ÔÐ$¨GÔ,BÐ$ØˆFØÔ*×.Ò.¨tÔ/@Å%Ä,ÈsÑBSÔBSÑTÔT×YÒYÑ[Ô[ˆØ�T”^Ò#Ð#Ø$ˆDŒNØÔ×"Ò"¨4¸$Ð"Ñ?Ô?Ð?Ø!×;Ò;¸GÀYÑOÔOˆNØ×&Ò& w°	¸>È4ÔK[Ð^wÑKwÑxÔxÐxÝ�KŠKØ=ØØÔ%ñô ð ð ð ð $Ð#s   Å"E? Å?Fc                ó²  — | j         dz  }|j        r|                      |||¦  «        nd}| j        sdS t	          t          |¦  «        dd¦  «        }|duo|t          j        u}|sdS t          |¦  «        r'|j        rt           
                    d|› d�¦  «         dS |j                             ¦   «          |j                             |j        r|                     ¦   «         |fndd¬	¦  «        \  }}|s#|j        rt           
                    d
¦  «         dS |                      |||¦  «         |j        rt                               d|¦  «         d„ |j        D ¦   «         }d„ |D ¦   «         }	|D ]	}
d|
_        Œ
	 |                     ||j        d¬¦  «         t+          ||	¦  «        D ]\  }
}||
_        ŒdS # t+          ||	¦  «        D ]\  }
}||
_        Œw xY w)aØ  Select the overall best model and optionally run test evaluation.

        On the main process, copies the winner (regular vs EMA, strict ``>`` for EMA) to
        ``checkpoint_best_total.pth`` and strips optimizer/scheduler state. With ``run_test=True`` every rank then
        loads those weights and enters ``trainer.test()``: the call is collective under DDP, so the decision to test
        and the winning source are broadcast from the main process rather than decided per rank. EMA reload tolerates
        only missing module extra state; all weight/key mismatches remain errors.

        Args:
            trainer: The Lightning Trainer instance.
            pl_module: The ``RFDETRModelModule`` being trained.
        zcheckpoint_best_total.pthFNÚ	test_stepzÑSkipping trainer.test() at fit end: run_test=True is not supported with spawn-based DDP (strategy='ddp_spawn' / 'ddp_notebook'). To score the best checkpoint afterwards, load it first: RFDETR.from_checkpoint('zq').evaluate(split='test', dataset_dir=...) (evaluate() scores the weights held in memory, not a checkpoint file).)FFr   )ÚsrczèSkipping trainer.test() because no best checkpoint was produced. Ensure the monitored metric is logged on evaluation epochs, that evaluation runs often enough, and that skip_best_epochs is smaller than the number of training epochs.z0Loaded best weights from %s for test evaluation.c                ó<   — g | ]}t          |t          ¦  «        ¯|‘ŒS r^   )r   r   ©r_   Úcbs     r   r°   z0BestModelCallback.on_fit_end.<locals>.<listcomp>˜  s9   € ð 
ð 
ð 
àÝ˜"Õ/Ñ0Ô0ð
Øð
ð 
ð 
r   c                ó   — g | ]	}|j         ‘Œ
S r^   )Úsuppress_test_swaprð   s     r   r°   z0BestModelCallback.on_fit_end.<locals>.<listcomp>�  s   € ÐEÐEÐE°�rÔ,ÐEÐEÐEr   T)rŸ   r:   )rF   rÒ   Ú_promote_best_totalrD   r   rÀ   r	   rí   r   r’   r“   r   ÚbarrierÚ	broadcastÚexistsÚ_load_best_total_weightsrÙ   rl   ró   ÚtestrŸ   Úzip)rP   r   rƒ   Ú
total_pathÚ	chose_emaÚcls_test_stepÚhas_test_stepÚshould_testÚema_callbacksÚprior_flagsÚema_callbackÚpriors               r   Ú
on_fit_endzBestModelCallback.on_fit_end`  sx  € ð Ô%Ð(CÑCˆ
ØPWÔPfÐq�D×,Ò,¨W°iÀÑLÔLÐLÐlqˆ	àŒ~ð 	ØˆFå¥ Y¡¤°¸dÑCÔCˆØ%¨TÐ1Ðd°mÍ?ÔKdÐ6dˆØð 	ØˆFÝ˜gÑ&Ô&ð 	ð Ô%ð Ý—’ð]à6@ð]ð ]ð ]ñô ð ð ˆFð 	Ô× Ò Ñ"Ô"Ð"Ø!(Ô!1×!;Ò!;Ø07Ô0FÐZˆZ×ÒÑ Ô  )Ð,Ð,ÈNÐ`að "<ñ "
ô "
Ñˆ�Yð ð 	ØÔ%ð Ý—’ð'ñô ð ð ˆFØ×%Ò% i°¸YÑGÔGÐGØÔ!ð 	XÝ�KŠKÐJÈJÑWÔWÐWð
ð 
àÔ'ð
ñ 
ô 
ˆð
 FÐE°}ÐEÑEÔEˆØ)ð 	3ð 	3ˆLØ.2ˆLÔ+Ð+ð	8Ø�LŠL˜¨wÔ/AÈ5ˆLÑQÔQÐQå'*¨=¸+Ñ'FÔ'Fð 8ð 8Ñ#�˜eØ27�Ô/Ð/ð8ð 8ø¥s¨=¸+Ñ'FÔ'Fð 8ð 8Ñ#�˜eØ27�Ô/Ð/ð8øøøs   Å;F7 Æ7Grû   c                ó^  — | j         dk    r| j        }n"| j        �| j                             ¦   «         nd}| j        dz  }d}| j        �~| j                             dd¬¦  «         |                      ||¦  «        }|                     ¦   «         s8|  	                    ||||¦  «         t                               d|j        ¦  «         | j        rt          | j        ¦  «        nd}| j        duo| j         p
| j        |k    }|o|                     ¦   «         }	|	r|n|}
|
rf|
                     ¦   «         rRt#          j        |
|¦  «         t'          |d|	rdnd	i¬
¦  «         t                               d|	rdnd	|| j        ¦  «         | j        �"|� |  	                    |||| j        dz  ¦  «         |	S )a“  Copy the winning best checkpoint to ``total_path`` and refresh ``last_ema.pth``; main process only.

        Args:
            trainer: The Lightning Trainer instance.
            pl_module: The ``RFDETRModelModule`` being trained.
            total_path: Destination of the stripped ``checkpoint_best_total.pth``.

        Returns:
            Whether the copied source was the EMA checkpoint.
        r#   Nrâ   TrÏ   z8EMA metric never improved; saved final EMA weights as %sÚbest_total_sourceÚemaÚregular)Úextra_metadataz<Best total checkpoint saved from %s (regular=%.4f, ema=%.4f)ÚEMAzlast_ema.pth)rL   rN   rä   rØ   rF   rB   rÔ   r•   r÷   r§   r’   rÙ   ÚnameÚbest_model_pathr   rC   rE   ÚshutilÚcopy2r   )rP   r   rƒ   rû   Úbest_regularÚema_pathr–   Úregular_pathÚbest_is_emarü   Ú	best_paths              r   rô   z%BestModelCallback._promote_best_total¦  sù  € ð& Ô Ò#Ð#ØÔ1ˆLˆLà;?Ô;PÐ;\˜4Ô0×5Ò5Ñ7Ô7Ð7ÐbeˆLØÔ#Ð&?Ñ?ˆð 48ˆØÔÐ(ØÔ×"Ò"¨4¸$Ð"Ñ?Ô?Ð?Ø!×;Ò;¸GÀYÑOÔOˆNØ—?’?Ñ$Ô$ð gØ×*Ò*¨7°I¸~ÈxÑXÔXÐXÝ—’ÐVÐX`ÔXeÑfÔfÐfà59Ô5IÐS•t˜DÔ0Ñ1Ô1Ð1Ètˆð Ô'¨tÐ3ð 
ØÔ*Ð*ÐK¨d¬n¸|Ò.Kð 	ð
  Ð5 H§O¢OÑ$5Ô$5ˆ	Ø )Ð;�H�H¨|ˆ	àð 
	˜×)Ò)Ñ+Ô+ð 
	ÝŒL˜ JÑ/Ô/Ð/õ ˜ZÐ9LÐW`ÐNoÈeÈeÐfoÐ8pÐqÑqÔqÐqÝ�KŠKØNØ"Ð1��¨	ØØ”ñ	ô ð ð ÔÐ(¨^Ð-GØ×&Ò& w°	¸>È4ÔK[Ð^lÑKlÑmÔmÐmØÐr   rü   c                óè  — ddl m}  ||d¬¦  «        }t                               | ¦  «        }|rS|                     |d         d¬¦  «        }d„ |j        D ¦   «         }|s|j        rt          d	|› d
|j        › �¦  «        ‚dS d„ |d                              ¦   «         D ¦   «         }|                     |d¬¦  «        }d„ |j        D ¦   «         }|s|j        rt          d|› d
|j        › �¦  «        ‚dS )aè  Load ``checkpoint_best_total.pth`` into the unwrapped module before test evaluation.

        Mirrors legacy ``main.py:602-609``. ``trust=True``: the checkpoint is produced locally, so the pickle fallback
        is allowed if needed. Checkpoints always store plain keys, so loading into the unwrapped module works for
        compiled (``OptimizedModule``) and non-compiled models alike.

        Args:
            pl_module: The ``RFDETRModelModule`` to load into.
            total_path: Path of ``checkpoint_best_total.pth``.
            chose_ema: Whether the checkpoint holds EMA weights, which omit FP8 history.

        Raises:
            RuntimeError: If any weight key is missing or unexpected (module extra state excepted).
        r   )Ú_safe_torch_loadT)Útrustrg   F)Ústrictc                óR   — g | ]$}|                      d d¦  «        d         dk    ¯"|‘Œ%S ©ú.r3   éÿÿÿÿÚ_extra_state©Úrsplit©r_   r~   s     r   r°   z>BestModelCallback._load_best_total_weights.<locals>.<listcomp>ü  s8   € ÐlÐlÐl˜sÀ3Ç:Â:ÈcÐSTÑCUÔCUÐVXÔCYÐ]kÒCkÐCk�sÐCkÐCkÐCkr   z.Error loading best EMA weights: Missing keys: z; Unexpected keys: Nc                óB   — i | ]\  }}t          j        |¦  «        °||“ŒS r^   )r   Ú_is_extra_state_key)r_   r~   Úvalues      r   rb   z>BestModelCallback._load_best_total_weights.<locals>.<dictcomp>	  s@   € ð 
ð 
ð 
Ù%˜3 ÕFWÔFkÐloÑFpÔFpð
Ø�ð
ð 
ð 
r   c                óR   — g | ]$}|                      d d¦  «        d         dk    ¯"|‘Œ%S r  r  r  s     r   r°   z>BestModelCallback._load_best_total_weights.<locals>.<listcomp>  s7   € ÐhÐhÐh˜3¸s¿zºzÈ#ÈqÑ?QÔ?QÐRTÔ?UÐYgÒ?gÐ?g�3Ð?gÐ?gÐ?gr   z2Error loading best regular weights: Missing keys: )	Úrfdetr.utilities.ior  r!   r‹   rÌ   Úmissing_keysÚunexpected_keysrÃ   rx   )	rƒ   rû   rü   r  Úckptr�   ÚincompatibleÚmissingÚfiltered_models	            r   rø   z*BestModelCallback._load_best_total_weightså  s{  € ð  	9Ð8Ð8Ð8Ð8Ð8àÐ 
°$Ð7Ñ7Ô7ˆÝ×-Ò-¨iÑ8Ô8ˆØð 		à×.Ò.¨t°G¬}ÀUÐ.ÑKÔKˆLØlÐl lÔ&?ÐlÑlÔlˆGØð ˜,Ô6ð Ý"ðGÀWð Gð GØ(4Ô(DðGð Gñô ð ð ˆFð
ð 
Ø)-¨g¬×)<Ò)<Ñ)>Ô)>ð
ñ 
ô 
ˆð ×*Ò*¨>À%Ð*ÑHÔHˆØhÐh ,Ô";ÐhÑhÔhˆØð 	�lÔ2ð 	ÝðCÀWð Cð CØ$0Ô$@ðCð Cñô ð ð	ð 	r   )r"   NTr   r#   T)r$   r%   r&   r%   r'   r(   r)   r   r*   r+   r,   r-   r.   r   r   r/   )NNF)rR   rS   rT   rU   r   r
   rV   r(   rW   rX   rY   r   r   rZ   )rƒ   r	   r   r„   )rƒ   r	   r   rS   )r   r
   rƒ   r	   r   rS   )
r   r
   rƒ   r	   r–   rS   r—   r   r   r/   )N)rƒ   r	   rc   r¨   r   r©   )rƒ   r	   r   r(   )r   rÈ   )rc   rÈ   r   r/   )r   r
   rÍ   r%   r   r/   ©r   r
   rƒ   r	   r   r/   )r   r
   rƒ   r	   rû   r   r   r   )rƒ   r	   rû   r   rü   r   r   r/   )rÁ   Ú
__module__Ú__qualname__Ú__doc__ÚFILE_EXTENSIONrA   Ústaticmethodr‚   r‹   rŽ   r•   r§   r£   r¢   rc   rÌ   rÝ   ræ   r  rô   rø   Ú__classcell__©rQ   s   @r   r!   r!   >   s%  ø€ € € € € ð:ð :ðx €Nð
  /Ø"&ØØ !Ø!Ø%)ð-?ð -?ð -?ð -?ð -?ð -?ð -?ð^ ð
 "&Ø+/Ø&+ðWð Wð Wð Wñ „\ðWðr ðDð Dð Dñ „\ðDð ð
 ð 
 ð 
 ñ „\ð
 ð ð ð  ð  ñ „\ð ð0)
ð )
ð )
ð )
ðV àHLð'ð 'ð 'ð 'ñ „\ð'ðR ðð ð ñ „\ðð:ð ð ð ð ð ð"'ð 'ð 'ð 'ð 'ð 'ð0>
ð >
ð >
ð >
ð@Oð Oð Oð Oð Oð OðbD8ð D8ð D8ð D8ðL=ð =ð =ð =ð~ ð,ð ,ð ,ñ „\ð,ð ,ð ,ð ,ð ,r   r!   c                  óP   ‡ — e Zd ZU dZdZded<   	 	 	 	 	 	 	 ddˆ fd„Zd ˆ fd„Zˆ xZS )!ÚRFDETREarlyStoppingu)  Early stopping callback monitoring a validation metric for RF-DETR.

    Extends :class:`pytorch_lightning.callbacks.EarlyStopping` with dual-metric
    monitoring: by default it monitors ``max(regular, ema)`` (legacy
    behaviour); set ``use_ema=True`` to monitor the EMA metric exclusively. The
    metric itself (mAP or mAR) is chosen by the caller via ``monitor_regular``/
    ``monitor_ema``, see ``TrainConfig.best_model_metric``.

    The effective metric is injected into ``trainer.callback_metrics`` under a synthetic key before delegating to the
    parent's stopping logic, so all parent features are available for free: ``state_dict``/``load_state_dict`` for
    checkpoint resumption, NaN/inf guard via ``check_finite``, and ``stopping_threshold``/``divergence_threshold``.

    Early stopping evaluates only on validation epochs where the monitored metrics are logged; non-eval epochs
    (``eval_interval > 1``) are skipped automatically.

    Args:
        patience: Number of epochs with no improvement before stopping.
        min_delta: Minimum improvement (in the monitored metric) to reset the patience counter.
        use_ema: When ``True`` and both regular and EMA metrics are available,
            monitor only the EMA metric.  When ``False``, monitor ``max(regular, ema)``.
        monitor_regular: Metric key for the regular model (mAP or mAR, per ``TrainConfig.best_model_metric``).
        monitor_ema: Metric key for the EMA model (mAP or mAR).
        verbose: If ``True``, log early stopping status each epoch.
        skip_best_epochs: Ignore the first N epochs (0..N-1) when evaluating
            patience and best-score baselines.  Set this when fine-tuning from ``pretrain_weights`` to avoid premature
            stopping before the model adapts to the new dataset.

    Examples:
        Fine-tuning from pretrained weights â€” skip first 3 epochs:

        >>> from rfdetr.training.callbacks.best_model import RFDETREarlyStopping
        >>> cb = RFDETREarlyStopping(patience=10, skip_best_epochs=3)
        >>> cb._skip_best_epochs
        3
    Ú__rfdetr_effective_map__r%   Ú_SYNTHETIC_MONITORé
   çü©ñÒMbP?Fr"   úval/ema_mAP_50_95Tr   Úpatiencer+   Ú	min_deltar-   Úuse_emar   r&   r'   r:   r*   r   r/   c                ó:  •— t          ¦   «                              | j        d||d|ddd¬¦	  «	         t          |t          ¦  «        st          |t
          ¦  «        st          d¦  «        ‚|dk     rt          d¦  «        ‚|| _        || _	        || _
        || _        d S )Nr2   FT)	r6   r7   r:  r;  Úcheck_on_train_epoch_endr:   Úcheck_finiter  Úlog_rank_zero_onlyr=   r   r>   )r@   rA   r6  r   r   r+   rG   rH   Ú_monitor_regularrB   Ú_use_emarI   )	rP   r:  r;  r<  r&   r'   r:   r*   rQ   s	           €r   rA   zRFDETREarlyStopping.__init__<  s¼   ø€ õ 	‰Œ×ÒØÔ+ØØØØ%*ØØØØ#ð 	ñ 
	
ô 
	
ð 
	
õ Ð&­Ñ-Ô-ð 	OµZÐ@PÕRUÑ5VÔ5Vð 	OÝÐMÑNÔNÐNØ˜aÒÐÝÐRÑSÔSÐSà /ˆÔØ'ˆÔØˆŒØ!1ˆÔÐÐr   r   r
   rƒ   r	   c                óä  •— |j         | j        k     rdS |j        }|                     | j        ¦  «        }|                     | j        ¦  «        }|�|                     ¦   «         nd}|�|                     ¦   «         nd}|€|€dS | j        r|�|}n|�|�t          ||¦  «        }n|�|}n|}t          j
        |¦  «        |j        | j        <   t          ¦   «                              ||¦  «         dS )a  Compute the effective validation metric and delegate to parent stopping logic.

        Computes the EMA metric or ``max(regular metric, EMA metric)`` depending on ``use_ema``,
        injects the result under the synthetic monitor key, then calls
        :meth:`EarlyStopping.on_validation_end`, which handles patience,
        ``trainer.should_stop``, logging, and ``state_dict`` persistence.

        Args:
            trainer: The Lightning Trainer instance.
            pl_module: The ``RFDETRModelModule`` being trained.
        N)rw   rI   rÖ   rt   rA  rB   rØ   rB  r2   r‡   rå   r6  r@   ræ   )
rP   r   rƒ   ÚmetricsÚregular_tensorÚ
ema_tensorÚregular_valrë   Ú	effectiverQ   s
            €r   ræ   z%RFDETREarlyStopping.on_validation_end[  s  ø€ ð Ô  4Ô#9Ò9Ð9ØˆFàÔ*ˆØ Ÿš TÔ%:Ñ;Ô;ˆØ—[’[ Ô!2Ñ3Ô3ˆ
à=KÐ=W N×$7Ò$7Ñ$9Ô$9Ð$9Ð]aˆØ5?Ð5K 
§¢Ñ 1Ô 1Ð 1ÐQUˆàÐ 7 ?ØˆFàŒ=ð 	$˜WÐ0ØˆIˆIØÐ$¨Ð)<Ý˜K¨Ñ1Ô1ˆIˆIØÐ ØˆIˆIà#ˆIå<A¼LÈÑ<SÔ<SˆÔ  Ô!8Ñ9Ý‰Œ×!Ò! '¨9Ñ5Ô5Ð5Ð5Ð5r   )r7  r8  Fr"   r9  Tr   )r:  r+   r;  r-   r<  r   r&   r%   r'   r%   r:   r   r*   r+   r   r/   r+  )	rÁ   r,  r-  r.  r6  Ú__annotations__rA   ræ   r1  r2  s   @r   r4  r4    s˜   ø€ € € € € € ð"ð "ðH 9ÐÐ8Ð8Ð8Ñ8ð Ø ØØ.Ø.ØØ !ð2ð 2ð 2ð 2ð 2ð 2ð 2ð>#6ð #6ð #6ð #6ð #6ð #6ð #6ð #6ð #6ð #6r   r4  )r   r
   r   r   )&r.  Ú
__future__r   rJ   r  Úpathlibr   Útypingr   r   r   Úrfdetr.training.module_modelr   r‡   Úpytorch_lightningr	   r
   Úpytorch_lightning.callbacksr   r   r   Ú6pytorch_lightning.strategies.launchers.multiprocessingr   ÚImportErrorÚrfdetr.training.callbacks.emar   Úrfdetr.utilities.loggerr   Úrfdetr.utilities.packager   Úrfdetr.utilities.state_dictr   r   r’   ry   r   r!   r4  r^   r   r   ú<module>rV     s  ðð \Ð [à "Ð "Ð "Ð "Ð "Ð "à €€€Ø €€€Ø Ð Ð Ð Ð Ð Ø &Ð &Ð &Ð &Ð &Ð &Ð &Ð &àð ?ØÐÐÐÐÐà>Ð>Ð>Ð>Ð>Ð>à €€€Ø 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6Ø FÐ FÐ FÐ FÐ FÐ FÐ FÐ FØ Ð Ð Ð Ð Ð ð
$Ø_Ð_Ð_Ð_Ð_Ð_Ð_øØð $ð $ð $Ø#ÐÐÐð$øøøð <Ð ;Ð ;Ð ;Ð ;Ð ;Ø .Ð .Ð .Ð .Ð .Ð .Ø 0Ð 0Ð 0Ð 0Ð 0Ð 0Ø NÐ NÐ NÐ NÐ NÐ NÐ NÐ Nà	ˆ‰Œ€àˆkÐ-Ñ.Ô.Ð;°)€ð]ð ]ð ]ð ]ð&Tð Tð Tð Tð T˜ñ Tô Tð Tðni6ð i6ð i6ð i6ð i6˜-ñ i6ô i6ð i6ð i6ð i6s   ÁA ÁAÁA