§
    ­¸jëé  ã                  ó   — U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
mZ ddlmZmZmZ ddlZddlZddlZddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlm Z   e ¦   «         Z! e"h d£¦  «        Z#dZ$ddddœZ%de&d<   ddddœZ'de&d<   dZ(ej)        j*        ej)        j+        fZ,dZ-de&d<   d@d„Z.dAdBd$„Z/dCd%„Z0ej1        dDd'„¦   «         Z2 G d(„ d)e¦  «        Z3 G d*„ d+e3¦  «        Z4 G d,„ d-e4¦  «        Z5dCd.„Z6 ej7        d¬/¦  «        dEd1„¦   «         Z8 G d2„ d3¦  «        Z9 e9¦   «         Z: G d4„ d5e4¦  «        Z; G d6„ d7e3¦  «        Z<dCd8„Z= G d9„ d:e3¦  «        Z>e<e5e;e>d;œZ?d<e&d=<    G d>„ d?e¦  «        Z@dS )FaÐ  Internal one-pass COCO mean-average-precision adapter.

Purpose:
    Isolate RF-DETR's deliberately narrow dependency on TorchMetrics COCO internals and avoid its per-class evaluator
    reruns. The adapter derives compact per-class AP and AR vectors from the aggregate evaluator arrays produced by one
    global evaluation for each requested IoU type.
Scope:
    Own CPU-backed metric updates, validation of the private TorchMetrics state/backend contract, explicit fixed-order
    distributed state merging, update-state inspection, prediction-score hoisting during COCO-format construction, and
    compact one-pass computation. Lightning lifecycle, EMA voting, logging, checkpoint metrics, F1, keypoint
    evaluation, and terminal rendering remain callback concerns.
Usage:
    Import :class:`OnePassCocoMeanAveragePrecision` only from RF-DETR training code. Construct it with one of the
    backends registered in ``_BACKENDS`` (``hotcoco`` by default, ``faster_coco_eval``, ``ufcoco`` or ``vernier``) and
    ``sync_on_compute=False``; call ``update`` for each batch, explicitly call ``merge_distributed_state`` at
    rank-symmetric callback sites, then call ``compute``.
Outputs:
    Return the same aggregate, per-class, and class-ID tensor keys consumed from TorchMetrics by RF-DETR. Evaluator
    precision, recall, score, and IoU arrays are reduced immediately and are never returned or retained. One
    deliberate divergence: when an IoU type has no images this pass, :meth:`compute` still emits
    ``*_per_class`` sentinel keys (see :meth:`OnePassCocoMeanAveragePrecision._per_class_sentinels`), whereas
    stock TorchMetrics omits them for that branch; this direction is safe for RF-DETR's callback (it always
    expects the per-class keys to exist) but is not covered by parity tests against upstream for that path.
Failure:
    Reject extended summaries, alternative backends, micro averaging, implicit distributed synchronization, and any
    installed TorchMetrics private layout that differs from the verified contract. These failures are intentional and
    actionable; there is no silent slow fallback.
Used by:
    ``rfdetr.training.callbacks.coco_eval.COCOEvalCallback`` for train, validation/test, and EMA COCO accumulators.
é    )ÚannotationsN)ÚCallableÚIterator)ÚAnyÚLiteralÚcast)ÚTensor)ÚMeanAveragePrecision)ÚCocoBackend)ÚCocoEvalBackend)Ú
all_gatherÚget_world_sizeÚis_dist_avail_and_initialized)Ú
get_logger>   ÚareaÚboxesÚmasksÚlabelsÚscoresÚiscrowd)	Údetection_boxÚdetection_scoresÚdetection_labelsÚdetection_maskÚgroundtruth_boxÚgroundtruth_labelsÚgroundtruth_maskÚgroundtruth_crowdsÚgroundtruth_area)r   r   r   r   r   r   r   r   r   Úiou_typeÚaverage)ÚstatsÚprefixÚmax_detection_thresholds)	r   Ú
all_labelsr   r   r   Úcrowdsr   r    r!   )Ú_get_coco_datasetsÚ_coco_stats_to_tensor_dictÚ_get_coco_formatzdict[str, tuple[str, ...]]Ú_BACKEND_METHOD_PARAMS©r!   ©r#   r$   Ú_BACKEND_KEYWORD_PARAMS)ÚevaluateÚ
accumulateÚ	summarizeÚ	correctedzLiteral['strict', 'corrected']Ú_VERNIER_PARITY_MODEÚreturnÚintc            	     óÀ   — t          dt          t          j                             dd¦  «        ¦  «        ¦  «        } t          dt          j        ¦   «         | z  ¦  «        S )a[  Return the CPU thread budget one DDP-local vernier evaluation should use.

    ``torch.get_num_threads()`` reports the process-wide intra-op thread pool, sized for one process per node.
    Under DDP with multiple ranks sharing a node, handing vernier that same budget on every rank oversubscribes
    the node's CPUs by a factor of ``LOCAL_WORLD_SIZE``; dividing it by the local rank count keeps each rank's
    evaluation within its fair share of the node.

    Returns:
        At least one thread, even when ``LOCAL_WORLD_SIZE`` is unset, zero, or larger than the reported thread
        count.
    é   ÚLOCAL_WORLD_SIZEÚ1)Úmaxr4   ÚosÚenvironÚgetÚtorchÚget_num_threads)Úlocal_world_sizes    úh/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/training/coco_map.pyÚ_vernier_thread_budgetrA   m   sL   € õ ˜1�c¥"¤*§.¢.Ð1CÀSÑ"IÔ"IÑJÔJÑKÔKÐÝˆq•%Ô'Ñ)Ô)Ð-=Ñ=Ñ>Ô>Ð>ó    Úmodule_nameÚstrÚbackend_valueÚpip_nameú
str | Noner   c                ó�   — 	 t          | ¦  «        S # t          $ r*}|j        | k    r‚ t          d|›d|p| › d�¦  «        |‚d}~ww xY w)a€  Import one of the optional COCO evaluation backend packages.

    ``hotcoco``, ``ultrafast_pycocotools`` and ``vernier`` are required members of the ``train`` extra (see
    pyproject.toml), so a missing import here always means the extra itself was never installed, not that one specific
    backend was left out. Shared by :func:`_hotcoco`, :func:`_ufcoco` and :func:`_vernier` so the backends report a
    missing extra identically.
    Uses the ``__import__`` builtin rather than :func:`importlib.import_module`: the latter bypasses a
    ``patch("builtins.__import__", ...)`` mock, which the missing-dependency regression tests rely on.

    Args:
        module_name: The package's import name (e.g. ``"hotcoco"``).
        backend_value: The ``TrainConfig.eval_backend`` value that selects this package, used in the install hint.
        pip_name: The package's PyPI distribution name, if it differs from ``module_name`` (e.g. a hyphen where the
            import name has an underscore). Defaults to ``module_name``.

    Returns:
        The imported module.

    Raises:
        ImportError: If the optional dependency is not installed.
    úbackend=z requires the z6 package; install it with: pip install 'rfdetr[train]'N)Ú
__import__ÚModuleNotFoundErrorÚnameÚImportError)rC   rE   rF   Úerrors       r@   Ú_import_optional_backendrO   }   s‚   € ð,Ý˜+Ñ&Ô&Ð&øÝð ð ð ØŒ:˜Ò$Ð$ØÝð;�}ð ;ð ;°hÐ6MÀ+ð ;ð ;ð ;ñ
ô 
ð ð	øøøøðøøøs   ‚ ‘
A›%A Á Ac                 ó"   — t          dd¦  «        S )z»Import the optional ``hotcoco`` backend package.

    Returns:
        The imported ``hotcoco`` module.

    Raises:
        ImportError: If the optional dependency is not installed.
    Úhotcoco©rO   © rB   r@   Ú_hotcocorT   ž   ó   € õ $ I¨yÑ9Ô9Ð9rB   úIterator[None]c               #  ó  K  — t          j        ¦   «         5  t          j        t	          j        ¦   «         ¦  «        5  t          j        dt          ¦  «         dV — ddd¦  «         n# 1 swxY w Y   ddd¦  «         dS # 1 swxY w Y   dS )u9  Silence the configuration diagnostics hotcoco reports while an evaluation runs.

    hotcoco reports every evaluator parameter that differs from the COCO defaults, plus a summary table. RF-DETR
    overrides ``maxDets`` on every evaluation and hands over thresholds torchmetrics stores in float32, which
    hotcoco reads as off-reference by ~2.4e-8, so those messages describe intended configuration and would
    otherwise repeat each validation epoch and each IoU type.

    Each message fires once, as a :class:`UserWarning`, and ``summarize()``'s table goes through
    :data:`sys.stdout`, so ordinary Python-level redirection catches both. Every ``UserWarning`` raised inside
    the window is dropped rather than an enumerated set of messages: hotcoco has four of them today, one firing
    only on empty state, and matching on text would silently stop working when a release rewords one. Nothing
    but the three backend calls runs inside the window, so no other source can be caught by it, and genuine
    failures still surface as exceptions.

    TODO: narrow or drop this once hotcoco stops reporting RF-DETR's configuration as off-reference. Two of the
    four messages are false â€” the IoU and recall grids differ from the defaults only by torchmetrics' float32
    round-trip â€” and a third fires on empty state after ``evaluate()`` did run. Once an upstream release stops
    reporting them, only the genuine ``max_dets`` message remains and this can shrink to that one filter.

    Yields:
        Nothing; standard output and the warning filter are restored on exit.
    ÚignoreN)ÚwarningsÚcatch_warningsÚ
contextlibÚredirect_stdoutÚioÚStringIOÚsimplefilterÚUserWarningrS   rB   r@   Ú_silenced_backend_diagnosticsra   ª   s  è è € õ0 
Ô	 Ñ	"Ô	"ð ð ¥JÔ$>½r¼{¹}¼}Ñ$MÔ$Mð ð ÝÔ˜h­Ñ4Ô4Ð4Øˆˆˆðð ð ñ ô ð ð ð ð ð ð øøøð ð ð ð ð ð ð ñ ô ð ð ð ð ð ð ð øøøð ð ð ð ð ð s4   –&A?¼A'ÁA?Á'A+	Á+A?Á.A+	Á/A?Á?BÂBc                  ó>   — e Zd ZU dZdZded<   dZded<   dZded	<   d
S )Ú_RfdetrCocoBackendaj  Typed capability-flag defaults every RF-DETR COCO backend shares.

    :meth:`OnePassCocoMeanAveragePrecision._validate_private_contract` and its constructor read three capability
    flags off the active backend -- :attr:`requires_bbox`, :attr:`unused_backend_methods`,
    :attr:`uses_coco_evaluator` -- and previously did so through ``getattr(backend, name, default)`` at each call
    site, repeating the same default three times with no typed declaration anywhere a backend could see. Declaring
    them here as typed class attributes gives every backend the same shared default and one place to override it.
    FÚboolÚrequires_bboxrS   ztuple[str, ...]Úunused_backend_methodsTÚuses_coco_evaluatorN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__re   Ú__annotations__rf   rg   rS   rB   r@   rc   rc   Ç   sS   € € € € € € ðð ð  €MÐÐÐÑØ.0ÐÐ0Ð0Ð0Ñ0Ø $ÐÐ$Ð$Ð$Ñ$Ð$Ð$rB   rc   c                  ót   ‡ — e Zd ZdZdˆ fd„Zdd„Zedd„¦   «         Zedd	„¦   «         Zedd
„¦   «         Z	ˆ xZ
S )Ú_PackageCocoBackendaÿ  TorchMetrics COCO backend whose surfaces come from an optional package outside TorchMetrics' backend enum.

    TorchMetrics resolves its COCO, evaluator and mask modules from a closed backend-name enum, so the parent is
    constructed with the supported ``faster_coco_eval`` name and each of the three resolved surfaces is overridden here
    to read from :meth:`_package` instead. Only the surfaces are swapped: every private helper the adapter calls on the
    backend (COCO-format construction, statistics conversion) is TorchMetrics' own and stays shared with the default
    backend. The package is resolved on every access rather than stored on the instance, so the backend pickles with the
    metric under Lightning's DDP spawn and checkpoint plumbing.
    r3   ÚNonec                ór   •— t          ¦   «                              d¦  «         |                      ¦   «          d S ©NÚfaster_coco_eval)ÚsuperÚ__init__Ú_package©ÚselfÚ	__class__s    €r@   rt   z_PackageCocoBackend.__init__á   s/   ø€ Ý‰Œ×ÒÐ+Ñ,Ô,Ð,ð 	�Š‰ŒˆˆˆrB   r   c                ó   — t           ‚)z°Import and return the package that supplies ``COCO``, ``COCOeval`` and ``mask``.

        Raises:
            ImportError: If the optional dependency is not installed.
        )ÚNotImplementedError©rw   s    r@   ru   z_PackageCocoBackend._packageè   s
   € õ "Ð!rB   Úobjectc                ó4   — |                       ¦   «         j        S )z'Return the package's COCO dataset type.)ru   ÚCOCOr{   s    r@   Úcocoz_PackageCocoBackend.cocoð   ó   € ð �}Š}‰ŒÔ#Ð#rB   c                ó4   — |                       ¦   «         j        S )z)Return the package's COCO evaluator type.)ru   ÚCOCOevalr{   s    r@   Úcocoevalz_PackageCocoBackend.cocoevalõ   s   € ð �}Š}‰ŒÔ'Ð'rB   c                ó4   — |                       ¦   «         j        S )z(Return the package's RLE mask utilities.)ru   Úmaskr{   s    r@   Ú
mask_utilsz_PackageCocoBackend.mask_utilsú   r€   rB   ©r3   ro   ©r3   r   ©r3   r|   )rh   ri   rj   rk   rt   ru   Úpropertyr   rƒ   r†   Ú__classcell__©rx   s   @r@   rn   rn   Ö   s»   ø€ € € € € ðð ðð ð ð ð ð ð"ð "ð "ð "ð ð$ð $ð $ñ „Xð$ð ð(ð (ð (ñ „Xð(ð ð$ð $ð $ñ „Xð$ð $ð $ð $ð $rB   rn   c                  ó   — e Zd ZdZdZdd„ZdS )Ú_HotCocoBackendzWTorchMetrics COCO backend that resolves to ``hotcoco`` instead of ``faster-coco-eval``.)r'   r3   r   c                ó   — t          ¦   «         S )zImport and return ``hotcoco``.)rT   r{   s    r@   ru   z_HotCocoBackend._package  s   € å‰zŒzÐrB   Nrˆ   )rh   ri   rj   rk   rf   ru   rS   rB   r@   rŽ   rŽ      s6   € € € € € ØaÐað
 5Ððð ð ð ð ð rB   rŽ   c                 ó&   — t          ddd¬¦  «        S )z×Import the optional ``ultrafast_pycocotools`` backend package.

    Returns:
        The imported ``ultrafast_pycocotools`` module.

    Raises:
        ImportError: If the optional dependency is not installed.
    Úultrafast_pycocotoolsÚufcocozultrafast-pycocotools)rF   rR   rS   rB   r@   Ú_ufcocor“     s   € õ $Ð$;¸XÐPgÐhÑhÔhÐhrB   )ÚmaxsizeÚtypec                 ón   — t          t          t          ¦   «         j        ¦  «        }  G d„ d| ¦  «        }|S )aX  Return ufcoco's COCO evaluator, with aggregate AP summarized at the largest configured detection limit.

    ufcoco reproduces pycocotools exactly, its summary included: pycocotools reads ``stats[0]`` -- the ``map``
    TorchMetrics reports -- at ``maxDets=100`` whatever the configured thresholds are, and reports ``-1`` when 100 is
    not among them. RF-DETR evaluates at ``eval_max_dets`` (500 by default), and faster-coco-eval and hotcoco both
    read ``stats[0]`` at the largest configured threshold, so this subclass does the same. The other eleven entries
    already use the configured thresholds in pycocotools and are left alone.

    Returns:
        The evaluator class to construct for each IoU type. Built on first use and cached, so the optional import
        stays off the module import path and the adapter sees one class identity.
    c                  ó    ‡ — e Zd Zdˆ fd„Zˆ xZS )ú/_ufcoco_evaluator_type.<locals>._UfcocoCocoEvalr3   ro   c                óÚ   •— t          ¦   «                              ¦   «          | j        j        d         }| j        j        dv r'|dk    r#|                      d|¬¦  «        | j        d<   dS dS dS )zLSummarize results and report aggregate AP at the configured detection limit.éÿÿÿÿ)ÚbboxÚsegméd   r6   )ÚmaxDetsr   N)rs   r0   Úparamsrž   ÚiouTypeÚ
_summarizer"   )rw   Úmax_detectionsrx   s     €r@   r0   z9_ufcoco_evaluator_type.<locals>._UfcocoCocoEval.summarize*  sp   ø€ å‰GŒG×ÒÑÔÐØ!œ[Ô0°Ô4ˆNØŒ{Ô"Ð&6Ð6Ð6¸>ÈSÒ;PÐ;PØ $§¢°¸> Ñ JÔ J�”
˜1‘��ð 7Ð6Ð;PÐ;PrB   r‡   )rh   ri   rj   r0   r‹   rŒ   s   @r@   Ú_UfcocoCocoEvalr˜   )  sG   ø€ € € € € ð	Kð 	Kð 	Kð 	Kð 	Kð 	Kð 	Kð 	Kð 	Kð 	KrB   r£   )r   r•   r“   r‚   )Úevaluator_typer£   s     r@   Ú_ufcoco_evaluator_typer¥     sT   € õ �$¥¡	¤	Ô 2Ñ3Ô3€NðKð Kð Kð Kð K˜.ñ Kô Kð Kð ÐrB   c                  ó"   — e Zd ZdZdd„Zdd	„Zd
S )Ú_UfcocoMaskToolsat  Ufcoco's RLE utilities, accepting the boolean masks TorchMetrics hands over.

    TorchMetrics encodes each stored mask as ``np.asfortranarray(mask)`` of the boolean array it keeps, which faster-
    coco-eval and hotcoco accept. ufcoco's ``encode`` holds pycocotools' ``uint8`` contract and rejects a boolean
    array, so it is converted here, one mask at a time; the Fortran-ordered ``uint8`` copy is the array the encoder
    would have been given by pycocotools' own callers. Every other utility -- ``area``, which TorchMetrics calls to size
    annotations -- is the module's own, reached through :meth:`__getattr__`.
    r…   únp.ndarray[Any, Any]r3   r   c                ó¸   — |j         t          j        k    r t          j        |t          j        ¬¦  «        }t          ¦   «         j                             |¦  «        S )zMEncode one binary mask as RLE, converting a boolean array to ``uint8`` first.©Údtype)r«   ÚnpÚbool_ÚasfortranarrayÚuint8r“   r…   Úencode)rw   r…   s     r@   r°   z_UfcocoMaskTools.encode>  sB   € àŒ:�œÒ!Ð!ÝÔ$ Tµ´Ð:Ñ:Ô:ˆDÝ‰yŒyŒ~×$Ò$ TÑ*Ô*Ð*rB   rL   rD   c                óD   — t          t          ¦   «         j        |¦  «        S )z]Forward every other RLE utility, such as ``area``, to ultrafast-pycocotools' ``mask`` module.)Úgetattrr“   r…   )rw   rL   s     r@   Ú__getattr__z_UfcocoMaskTools.__getattr__D  s   € å•w‘y”y”~ tÑ,Ô,Ð,rB   N)r…   r¨   r3   r   )rL   rD   r3   r   )rh   ri   rj   rk   r°   r³   rS   rB   r@   r§   r§   4  sF   € € € € € ðð ð+ð +ð +ð +ð-ð -ð -ð -ð -ð -rB   r§   c                  óJ   — e Zd ZdZd	d„Zed
d„¦   «         Zed
d„¦   «         ZdS )Ú_UfcocoBackenda(  TorchMetrics COCO backend that resolves to ``ultrafast-pycocotools`` instead of ``faster-coco-eval``.

    Unlike hotcoco, ufcoco keeps pycocotools' Python-side ``COCO`` object -- ``dataset`` assignment followed by
    ``createIndex()``, annotations read back as the same dictionaries -- so the adapter routes it through the paths it
    takes for faster-coco-eval; the only adaptations are the two places where ufcoco follows pycocotools more literally
    than the other backends do, :func:`_ufcoco_evaluator_type` and :class:`_UfcocoMaskTools`.
    r3   r   c                ó   — t          ¦   «         S )z,Import and return ``ultrafast_pycocotools``.)r“   r{   s    r@   ru   z_UfcocoBackend._packageU  s   € å‰yŒyÐrB   r|   c                ó   — t          ¦   «         S )zSReturn ufcoco's COCO evaluator type, summarizing at the configured detection limit.)r¥   r{   s    r@   rƒ   z_UfcocoBackend.cocoevalY  s   € õ &Ñ'Ô'Ð'rB   c                ó   — t           S )z<Return ufcoco's RLE mask utilities, accepting boolean masks.)Ú_UFCOCO_MASK_TOOLSr{   s    r@   r†   z_UfcocoBackend.mask_utils^  s
   € õ "Ð!rB   Nrˆ   r‰   )rh   ri   rj   rk   ru   rŠ   rƒ   r†   rS   rB   r@   rµ   rµ   L  sr   € € € € € ðð ðð ð ð ð ð(ð (ð (ñ „Xð(ð ð"ð "ð "ñ „Xð"ð "ð "rB   rµ   c                  ó$   ‡ — e Zd ZdZdˆ fd„Zˆ xZS )Ú_FasterCocoEvalBackenda(  TorchMetrics' own ``faster_coco_eval`` backend, the one :class:`MeanAveragePrecision` builds itself.

    Nothing is overridden beyond the shared capability-flag defaults: the class exists so the registry holds one
    backend class per name and the metric builds every backend the same way.
    r3   ro   c                óJ   •— t          ¦   «                              d¦  «         d S rq   )rs   rt   rv   s    €r@   rt   z_FasterCocoEvalBackend.__init__k  s"   ø€ Ý‰Œ×ÒÐ+Ñ,Ô,Ð,Ð,Ð,rB   r‡   )rh   ri   rj   rk   rt   r‹   rŒ   s   @r@   r»   r»   d  sG   ø€ € € € € ðð ð-ð -ð -ð -ð -ð -ð -ð -ð -ð -rB   r»   c                 ó"   — t          dd¦  «        S )z»Import the optional ``vernier`` backend package.

    Returns:
        The imported ``vernier`` module.

    Raises:
        ImportError: If the optional dependency is not installed.
    ÚvernierrR   rS   rB   r@   Ú_vernierr¿   o  rU   rB   c                  ó0   ‡ — e Zd ZdZdZdZdZdˆ fd„Zˆ xZS )	Ú_VernierBackenda”  TorchMetrics COCO backend built with the ``faster_coco_eval`` name, evaluating on ``vernier``'s native API.

    vernier takes both ground truth and detections as arrays, so
    :meth:`OnePassCocoMeanAveragePrecision._vernier_results` bypasses the COCO dataset and evaluator surfaces
    entirely; only the parent's statistics helper and RLE mask utilities are used. It inherits
    :class:`_RfdetrCocoBackend` directly rather than :class:`_FasterCocoEvalBackend`: the two share only that
    constructor argument, and subclassing the sibling backend it happens to resemble instead of the common base
    both descend from is not a real is-a relationship.
    )r'   r)   FTr3   ro   c                óf   •— t          ¦   «                              d¦  «         t          ¦   «          d S rq   )rs   rt   r¿   rv   s    €r@   rt   z_VernierBackend.__init__�  s-   ø€ õ
 	‰Œ×ÒÐ+Ñ,Ô,Ð,õ 	‰
Œ
ˆ
ˆ
ˆ
rB   r‡   )	rh   ri   rj   rk   rf   rg   re   rt   r‹   rŒ   s   @r@   rÁ   rÁ   {  s[   ø€ € € € € ðð ð HÐØÐà€Mðð ð ð ð ð ð ð ð ð rB   rÁ   )rr   rQ   r’   r¾   z7dict[CocoEvalBackend, Callable[[], _RfdetrCocoBackend]]Ú	_BACKENDSc                  ó  ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 dKdLˆ fd„ZedMd„¦   «         ZdNˆ fd!„ZdOd"„ZdPd$„Z	dQd'„Z
dRd)„ZdSd+„ZdTd.„ZdUd0„ZdOd1„ZdVd4„ZdWd9„ZdXd;„ZdYd>„ZedZdA„¦   «         Zed[dC„¦   «         ZdOdD„Zd\dE„Zd]dG„Zd]dH„Zd^dJ„Zˆ xZS )_ÚOnePassCocoMeanAveragePrecisionaè  Compute compact COCO AP/AR with CPU state and one global evaluation.

    The subclass is RF-DETR's internal compatibility boundary around private TorchMetrics 1.x COCO state and backend
    helpers. It deliberately supports only the configuration used by the training callback. Per-class AP and AR are
    reduced from the aggregate evaluator's precision and recall arrays, avoiding TorchMetrics' additional evaluator
    construction and one evaluation per observed class.

    Args:
        box_format: Input bounding-box representation.
        iou_type: COCO IoU types to evaluate.
        iou_thresholds: Optional IoU thresholds forwarded to TorchMetrics.
        rec_thresholds: Optional recall thresholds forwarded to TorchMetrics.
        max_detection_thresholds: Three COCO maximum-detection thresholds.
        class_metrics: Whether to return per-class AP and AR.
        extended_summary: Must remain ``False`` so large evaluator arrays do not escape computation.
        average: Must remain ``"macro"`` because RF-DETR logs class-level metrics.
        backend: COCO evaluation backend. ``"vernier"`` is the default; ``"faster_coco_eval"`` selects the previous
            evaluator, ``"ufcoco"`` selects ultrafast-pycocotools and ``"hotcoco"`` selects hotcoco. All four ship
            with ``rfdetr[train]`` and return identical metrics.
        kwargs: TorchMetrics configuration. ``sync_on_compute`` defaults to and must remain ``False`` because the
            callback invokes :meth:`merge_distributed_state` explicitly at rank-symmetric sites.

    Raises:
        ValueError: If a configuration falls outside the RF-DETR adapter contract.
        RuntimeError: If the installed TorchMetrics private state/backend contract is incompatible.
    Úxyxyr›   NFÚmacrorQ   Ú
box_formatú!Literal['xyxy', 'xywh', 'cxcywh']r    ú=Literal['bbox', 'segm'] | tuple[Literal['bbox', 'segm'], ...]Úiou_thresholdsúlist[float] | NoneÚrec_thresholdsr$   úlist[int] | NoneÚclass_metricsrd   Úextended_summaryr!   úLiteral['macro', 'micro']Úbackendr   Úkwargsr   r3   ro   c
                óò  •— |rt          d¦  «        ‚|	t          vr$t          dt          t          ¦  «        › �¦  «        ‚|dk    rt          d¦  «        ‚|
                     dd¦  «        }|durt          d¦  «        ‚ t	          ¦   «         j        d||||||d|ddd	œ
|
¤Ž t          |	         ¦   «         | _        | j        j        rd
| j        vrt          d|	›d�¦  «        ‚|  	                    ¦   «          d S )NzFOnePassCocoMeanAveragePrecision does not support extended_summary=Truez4OnePassCocoMeanAveragePrecision requires backend in rÇ   z8OnePassCocoMeanAveragePrecision requires average='macro'Úsync_on_computeFz>OnePassCocoMeanAveragePrecision requires sync_on_compute=Falserr   )
rÈ   r    rË   rÍ   r$   rÏ   rÐ   r!   rÒ   rÕ   r›   rI   zC requires 'bbox' among the IoU types; it needs a box per annotationrS   )
Ú
ValueErrorrÃ   ÚtupleÚpoprs   rt   Ú_coco_backendre   r    Ú_validate_private_contract)rw   rÈ   r    rË   rÍ   r$   rÏ   rÐ   r!   rÒ   rÓ   rÕ   rx   s               €r@   rt   z(OnePassCocoMeanAveragePrecision.__init__À  sD  ø€ ð ð 	gÝÐeÑfÔfÐfØ�)Ð#Ð#ÝÐfÕTYÕZcÑTdÔTdÐfÐfÑgÔgÐgØ�gÒÐÝÐWÑXÔXÐXØ Ÿ*š*Ð%6¸Ñ>Ô>ˆØ %Ð'Ð'ÝÐ]Ñ^Ô^Ð^Ø�‰ŒÔð 	
Ø!ØØ)Ø)Ø%=Ø'Ø"Øð 'Ø!ð	
ð 	
ð ð	
ð 	
ð 	
õ  ' wÔ/Ñ1Ô1ˆÔð ÔÔ+ð 	x°¸d¼mÐ0KÐ0KÝÐv¨ÐvÐvÐvÑwÔwÐwØ×'Ò'Ñ)Ô)Ð)Ð)Ð)rB   c                ó  — t          | dd¦  «        }t          |t          ¦  «        r|dk    S t          j        |¦  «        rIt          |                     ¦   «                              ¦   «                              ¦   «         dk    ¦  «        S dS )z:Return whether at least one batch has updated this metric.Ú_update_countNr   T)	r²   Ú
isinstancer4   r=   Ú	is_tensorrd   ÚdetachÚcpuÚitem)rw   Úupdate_counts     r@   Úhas_updatesz+OnePassCocoMeanAveragePrecision.has_updatesí  s�   € õ ˜t _°dÑ;Ô;ˆÝ�l¥CÑ(Ô(ð 	$Ø !Ò#Ð#ÝŒ?˜<Ñ(Ô(ð 	@Ý˜×+Ò+Ñ-Ô-×1Ò1Ñ3Ô3×8Ò8Ñ:Ô:¸QÒ>Ñ?Ô?Ð?ØˆtrB   Úpredsúlist[dict[str, Tensor]]Útargetc                ó|   •— d„ |D ¦   «         }d„ |D ¦   «         }t          ¦   «                              ||¦  «         dS )a  Validate inputs and store detached CPU copies of fields consumed by TorchMetrics.

        Args:
            preds: Per-image predictions in TorchMetrics detection format.
            target: Per-image ground-truth annotations in TorchMetrics detection format.
        c                óJ   — g | ] }d „ |                      ¦   «         D ¦   «         ‘Œ!S )c                ót   — i | ]5\  }}|t           v ¯||                     ¦   «                              ¦   «         “Œ6S rS   ©Ú_METRIC_INPUT_FIELDSrß   rà   ©Ú.0rL   Úvalues      r@   ú
<dictcomp>zEOnePassCocoMeanAveragePrecision.update.<locals>.<listcomp>.<dictcomp>ÿ  ó=   € ÐhÐhÐh©K¨D°%È4ÕSgÐKgÐKgˆT�5—<’<‘>”>×%Ò%Ñ'Ô'ÐKgÐKgÐKgrB   ©Úitems©rí   rá   s     r@   ú
<listcomp>z:OnePassCocoMeanAveragePrecision.update.<locals>.<listcomp>þ  s?   € ð 
ð 
ð 
àð iÐh¸4¿:º:¹<¼<ÐhÑhÔhð
ð 
ð 
rB   c                óJ   — g | ] }d „ |                      ¦   «         D ¦   «         ‘Œ!S )c                ót   — i | ]5\  }}|t           v ¯||                     ¦   «                              ¦   «         “Œ6S rS   rê   rì   s      r@   rï   zEOnePassCocoMeanAveragePrecision.update.<locals>.<listcomp>.<dictcomp>  rð   rB   rñ   ró   s     r@   rô   z:OnePassCocoMeanAveragePrecision.update.<locals>.<listcomp>  s?   € ð 
ð 
ð 
àð iÐh¸4¿:º:¹<¼<ÐhÑhÔhð
ð 
ð 
rB   N)rs   Úupdate)rw   rä   ræ   Ú	cpu_predsÚ
cpu_targetrx   s        €r@   r÷   z&OnePassCocoMeanAveragePrecision.update÷  s_   ø€ ð
ð 
àð
ñ 
ô 
ˆ	ð
ð 
àð
ñ 
ô 
ˆ
õ 	‰Œ�Š�y *Ñ-Ô-Ð-Ð-Ð-rB   c                ó2  — t          ¦   «         rt          ¦   «         dk    rdS t          D ]H}t          | |¦  «        }d„ |D ¦   «         }t	          |¦  «        }t          | |d„ |D ¦   «         ¦  «         ŒIt          t          | dd¦  «        d¦  «        | _        dS )a£  Merge all TorchMetrics list states across ranks using a fixed collective order.

        The explicit call site is intentional: every callback rank must enter the same collectives in the same order.
        TorchMetrics' tensor gather can issue a shape-dependent number of collectives for segmentation state, whereas
        RF-DETR's object gather performs exactly one collective for each declared list state.
        r6   Nc                ó†   — g | ]>}t          j        |¦  «        r&|                     ¦   «                              ¦   «         n|‘Œ?S rS   )r=   rÞ   rß   rà   )rí   rî   s     r@   rô   zKOnePassCocoMeanAveragePrecision.merge_distributed_state.<locals>.<listcomp>  sA   € ÐfÐfÐfÐW\µ´ÀÑ1GÔ1GÐR˜Ÿš™œ×+Ò+Ñ-Ô-Ð-ÈUÐfÐfÐfrB   c                ó   — g | ]	}|D ]}|‘ŒŒ
S rS   rS   )rí   Ú
rank_itemsrá   s      r@   rô   zKOnePassCocoMeanAveragePrecision.merge_distributed_state.<locals>.<listcomp>  s%   € Ð XÐ XÐ X¨*ÈZÐ XÐ XÀT Ð XÐ XÐ XÐ XrB   rÜ   r   )r   r   Ú_MAP_STATE_ATTRSr²   r   Úsetattrr9   rÜ   )rw   ÚattrÚlocalÚ	local_cpuÚgathereds        r@   Úmerge_distributed_statez7OnePassCocoMeanAveragePrecision.merge_distributed_state  s°   € õ -Ñ.Ô.ð 	µ.Ñ2BÔ2BÀaÒ2GÐ2GØˆFÝ$ð 	Zð 	ZˆDÝ˜D $Ñ'Ô'ˆEØfÐfÐ`eÐfÑfÔfˆIÝ! )Ñ,Ô,ˆHÝ�D˜$Ð XÐ X¸Ð XÑ XÔ XÑYÔYÐYÐYÝ ¥¨¨ÀÑ!BÔ!BÀAÑFÔFˆÔÐÐrB   údict[str, Tensor]c           
     ó(  — |                       ¦   «         }t                               dt          |¦  «        | j        ¦  «         t          | j        t          ¦  «        r9i |                      |¦  «        ¥dt          j
        |t          j        ¬¦  «        i¥S |                      |¦  «        \  }}}i }| j        D �]5}t          | j        ¦  «        dk    rdn|› d�}t          | j        ¦  «        dk    r|                      |||¦  «        }t          |j        ¦  «        dk    st          |j        ¦  «        dk    r*|                     |                      ||¦  «        ¦  «         Œ«t#          t$          dt&          f         | j        j        ¦  «        } ||||¬	¦  «        }	|	j        }
t-          j        | j        t,          j        ¬¦  «        |
_        t-          j        | j        t,          j        ¬¦  «        |
_        | j        |
_        ||
_        |
|	_        |                       ¦   «         5  |	 !                    ¦   «          |	 "                    ¦   «          |	 #                    ¦   «          d
d
d
¦  «         n# 1 swxY w Y   |                     | j         $                    |	j%        || j        ¬¦  «        ¦  «         |                     |  &                    tO          |	dd
¦  «        ||¦  «        ¦  «         �Œ7t          j
        |t          j        ¬¦  «        |d<   |S )as  Return aggregate and compact per-class COCO metrics from one evaluator per IoU type.

        Returns:
            TorchMetrics-compatible aggregate metrics, per-class AP/AR vectors, and observed class IDs.

        Raises:
            RuntimeError: If the installed backend no longer exposes the evaluator arrays required for one-pass
                reduction.
        z@Computing one-pass COCO metrics for %d classes and IoU types %s.Úclassesrª   r6   Ú Ú_r   .)r    Nr,   Úeval)(Ú_observed_classesÚloggerÚdebugÚlenr    rÝ   rÙ   rÁ   Ú_vernier_resultsr=   ÚtensorÚint32Ú_coco_datasetsÚ _prediction_dataset_for_iou_typeÚimgsr÷   Ú_empty_iou_type_resultsr   r   r   rƒ   rŸ   r¬   ÚasarrayrË   Úfloat64ÚiouThrsrÍ   ÚrecThrsr$   rž   ÚcatIdsÚ_quiet_evaluationr.   r/   r0   r(   r"   Ú_reduce_per_classr²   )rw   r  Ú
coco_predsÚcoco_targetÚprediction_datasetÚresultr    r#   Úevaluator_factoryÚ	coco_evalrŸ   s              r@   Úcomputez'OnePassCocoMeanAveragePrecision.compute  s  € ð ×(Ò(Ñ*Ô*ˆÝ�ŠÐWÕY\Ð]dÑYeÔYeÐgkÔgtÑuÔuÐuÝ�dÔ(­/Ñ:Ô:ð 	kØj�d×+Ò+¨GÑ4Ô4Ðj°iÅÄÈgÕ]bÔ]hÐAiÑAiÔAiÐjÐjÐjØ6:×6IÒ6IÈ'Ñ6RÔ6RÑ3ˆ
�KÐ!3à$&ˆØœð #	eñ #	eˆHÝ˜tœ}Ñ-Ô-°Ò2Ð2�R�R¸8¸¸¸ˆFÝ�4”=Ñ!Ô! AÒ%Ð%Ø!×BÒBÀ:ÐOaÐckÑlÔl�
Ý�:”?Ñ#Ô# qÒ(Ð(­C°Ô0@Ñ,AÔ,AÀQÒ,FÐ,FØ—’˜d×:Ò:¸6À7ÑKÔKÑLÔLÐLØå $¥X¨cµ3¨hÔ%7¸Ô9KÔ9TÑ UÔ UÐð *Ð)¨+°zÈ8ÐTÑTÔTˆIð Ô%ˆFÝœZ¨Ô(;Å2Ä:ÐNÑNÔNˆFŒNÝœZ¨Ô(;Å2Ä:ÐNÑNÔNˆFŒNØ!Ô:ˆFŒNØ#ˆFŒMØ%ˆIÔð ×'Ò'Ñ)Ô)ð &ð &Ø×"Ò"Ñ$Ô$Ð$Ø×$Ò$Ñ&Ô&Ð&Ø×#Ò#Ñ%Ô%Ð%ð&ð &ð &ñ &ô &ð &ð &ð &ð &ð &ð &øøøð &ð &ð &ð &ð �MŠMØÔ"×=Ò=Ø”O¨FÈTÔMjð >ñ ô ñô ð ð
 �MŠM˜$×0Ò0µ¸ÀFÈDÑ1QÔ1QÐSYÐ[bÑcÔcÑdÔdÐdÑdå!œL¨½¼ÐDÑDÔDˆˆyÑØˆs   È&=I/É/I3	É6I3	r  ú	list[int]c                ól  — t          ¦   «         }d}| j        r6|                      ¦   «         \  }}|j                             ||d|d¬¦  «        }i }| j        D �][}t          | j        ¦  «        dk    rdn|› d�}|€*|                     |                      ||¦  «        ¦  «         ŒN|\  }	}
|dk    r|j	        j
        n|j	        j        } ||	|
t          | j        d	         d
| j        | j        t!          ¦   «         |dk    rdnd¬¦	  «	        }|                     | j        ¦  «        }|                     | j                             |                     ¦   «         j        || j        ¬¦  «        ¦  «         d}| j        r|j        |j        dœ}|                     |                      |||¦  «        ¦  «         �Œ]|S )a›  Evaluate on vernier's native grid, one per IoU type, keyed for TorchMetrics.

        ``vernier.adapters.coco_inputs_from_columns`` builds the inputs from
        :meth:`_vernier_columns`, once for the whole call, reusing the already concatenated stored state.

        ``iou_thresholds`` / ``rec_thresholds`` are forwarded because TorchMetrics builds them with
        ``torch.linspace`` in ``float32``, unlike vernier.

        Args:
            classes: Sorted class IDs observed in predictions or targets, used as COCO category IDs.

        Returns:
            TorchMetrics-compatible aggregate metrics and per-class AP/AR vectors, without ``classes``.
        NÚxywhÚauto)rÈ   Ú
categoriesr   r6   r  r	  r›   rš   Tr…   )Úparity_modeÚmax_dets_per_imageÚuse_catsrË   Úrecall_thresholdsÚnum_threadsÚdt_arear,   )Ú	precisionÚrecall)r¿   r   Ú_vernier_columnsÚadaptersÚcoco_inputs_from_columnsr    r  r÷   r  ÚinstanceÚevaluate_bbox_gridÚevaluate_segm_gridr2   r$   rË   rÍ   rA   r/   rÙ   r(   r0   r"   rÏ   r/  r0  r  )rw   r  r¾   ÚinputsÚdetection_columnsÚtarget_columnsr   r    r#   Úground_truthÚ
detectionsÚevaluate_gridÚgridÚaccumulatedÚ
evaluations                  r@   r  z0OnePassCocoMeanAveragePrecision._vernier_resultsQ  s   € õ ‘*”*ˆð ˆØÔ"ð 
	Ø04×0EÒ0EÑ0GÔ0GÑ-Ð˜~ð Ô%×>Ò>Ø!ØØ!Ø"Øð ?ñ ô ˆFð %'ˆØœð 	Oñ 	OˆHÝ˜tœ}Ñ-Ô-°Ò2Ð2�R�R¸8¸¸¸ˆFØˆ~Ø—’˜d×:Ò:¸6À7ÑKÔKÑLÔLÐLØØ'-Ñ$ˆL˜*à7?À6Ò7IÐ7I�Ô Ô3Ð3ÈwÔO_ÔOrð ð !�=ØØÝ0Ø#'Ô#@ÀÔ#DØØ#Ô2Ø"&Ô"5Ý2Ñ4Ô4Ø"*¨fÒ"4Ð"4˜˜¸&ð
ñ 
ô 
ˆDð Ÿ/š/¨$Ô*GÑHÔHˆKØ�MŠMØÔ"×=Ò=Ø×)Ò)Ñ+Ô+Ô1¸&Ð[_Ô[xð >ñ ô ñô ð ð ˆJØÔ!ð `Ø+6Ô+@ÈKÔL^Ð_Ð_�
Ø�MŠM˜$×0Ò0°¸VÀWÑMÔMÑNÔNÐNÑNØˆrB   ú%tuple[dict[str, Any], dict[str, Any]]c                óx  — t          j        d„ | j        D ¦   «         ¦  «        t          j        | j        ¦  «        t          j        | j        ¦  «        t          j        d„ | j        D ¦   «         ¦  «        dœ}t          j        d„ | j        D ¦   «         ¦  «        t          j        | j        ¦  «        t          j        | j        ¦  «        t          j        | j	        ¦  «        t          j        d„ | j        D ¦   «         ¦  «        dœ}d| j
        v r(d„ | j        D ¦   «         |d	<   d
„ | j        D ¦   «         |d	<   ||fS )a©  Return the stored state as the whole columns ``coco_inputs_from_columns`` reads.

        ``rles`` is written only if ``segm`` is in ``self.iou_type``.

        Columns are handed over at their stored dtype; vernier widens them at its own ingest boundary,
        including the ``bfloat16`` an autocast run holds (needs ``vernier>=0.5.3``).

        Returns:
            The detection columns and the target columns.
        c                ó:   — g | ]}|                      d d¦  «        ‘ŒS ©rš   é   ©Úreshape©rí   Úimages     r@   rô   zDOnePassCocoMeanAveragePrecision._vernier_columns.<locals>.<listcomp>¢  s&   € ÐUÐUÐU¸ §¢¨b°!Ñ 4Ô 4ÐUÐUÐUrB   c                ó,   — g | ]}t          |¦  «        ‘ŒS rS   ©r  rG  s     r@   rô   zDOnePassCocoMeanAveragePrecision._vernier_columns.<locals>.<listcomp>¥  s   € Ð#RÐ#RÐ#R°5¥C¨¡J¤JÐ#RÐ#RÐ#RrB   )r   r   r   Úcountsc                ó:   — g | ]}|                      d d¦  «        ‘ŒS rC  rE  rG  s     r@   rô   zDOnePassCocoMeanAveragePrecision._vernier_columns.<locals>.<listcomp>¨  s&   € ÐWÐWÐW¸ §¢¨b°!Ñ 4Ô 4ÐWÐWÐWrB   c                ó,   — g | ]}t          |¦  «        ‘ŒS rS   rJ  rG  s     r@   rô   zDOnePassCocoMeanAveragePrecision._vernier_columns.<locals>.<listcomp>¬  s   € Ð#TÐ#TÐ#T°5¥C¨¡J¤JÐ#TÐ#TÐ#TrB   )r   r   r   r   rK  rœ   c                ó(   — g | ]}|D ]
\  }}||d œ‘ŒŒS ©)ÚsizerK  rS   ©rí   rH  rP  rK  s       r@   rô   zDOnePassCocoMeanAveragePrecision._vernier_columns.<locals>.<listcomp>¯  sH   € ð )ð )ð )Ø5:Ðfkð)ð )ÙVbÐVZÐ\b˜¨Ð0Ð0ð)ð )ð )ð )rB   Úrlesc                ó(   — g | ]}|D ]
\  }}||d œ‘ŒŒS rO  rS   rQ  s       r@   rô   zDOnePassCocoMeanAveragePrecision._vernier_columns.<locals>.<listcomp>²  sH   € ð &ð &ð &Ø5:Ðhmð&ð &ÙXdÐX\Ð^d˜¨Ð0Ð0ð&ð &ð &ð &rB   )r=   Úcatr   r   r   r  r   r   r   r   r    r   r   )rw   r8  r9  s      r@   r1  z0OnePassCocoMeanAveragePrecision._vernier_columns“  sT  € õ ”YÐUÐUÀ$ÔBTÐUÑUÔUÑVÔVÝ”i Ô 5Ñ6Ô6Ý”i Ô 5Ñ6Ô6Ý”lÐ#RÐ#R¸DÔ<QÐ#RÑ#RÔ#RÑSÔSð-
ð -
Ðõ ”YÐWÐWÀ$ÔBVÐWÑWÔWÑXÔXÝ”i Ô 7Ñ8Ô8Ý”y Ô!8Ñ9Ô9Ý”I˜dÔ3Ñ4Ô4Ý”lÐ#TÐ#T¸DÔ<SÐ#TÑ#TÔ#TÑUÔUð*
ð *
ˆð �T”]Ð"Ð"ð)ð )Ø>BÔ>Qð)ñ )ô )Ð˜fÑ%ð&ð &Ø>BÔ>Sð&ñ &ô &ˆN˜6Ñ"ð ! .Ð0Ð0rB   ú&tuple[Any, Any, dict[str, Any] | None]c                ó"  — | j         }t          | j        ¦  «        dk    r| j        nd}|€Ãt          |t          ¦  «        s®t          t          t          t          f         |                     | j	        | j
        | j        | j        | j        | j        | j        | j        | j        | j        | j        ¬¦  «        ¦  «        \  }}||t          t&          t(          t          f         |j        ¦  «        fS t          t,          t.                   |¦  «        }|                     | j	        t          | j
        ¦  «        dk    r| j
        ndt          | j        ¦  «        dk    r| j        nd| j        | j        | j        || j        ¬¦  «        }|                      |¦  «        }|                      |¦  «        r*|                     |                      ¦   «         ¦  «        |dfS |                     | j        |t          | j        ¦  «        dk    r| j        nd|�dn| j        | j        || j        ¬¦  «        }|�|                      |d         ¦  «         t          | j        ¦  «        dk    ot          |t          ¦  «        }	|	rdn|                      |¦  «        }|||fS )a‚  Return the COCO prediction and target datasets, hoisting prediction scores out of the annotation loop.

        TorchMetrics' ``_get_coco_format`` hoists boxes and labels to Python lists once per image but reads scores
        one annotation at a time (``scores[image_id][k].cpu().tolist()``, ``helpers.py:563``), which is CPU tensor
        indexing and scalar conversion for every detection because ``update()`` stores detached CPU state. At
        RF-DETR's validation scale that is hundreds of thousands of conversions per ``compute()``. Asking upstream
        for the same annotations with
        ``scores=None`` and assigning per-image score lists afterwards produces byte-identical datasets while
        converting each image's scores once.

        The rewrite needs prediction annotations to appear in state order with no image dropped. Upstream skips an
        image only when it has no masks *and* no boxes (``helpers.py:508-511``), so the hoist is used only when
        boxes are present; a mask-only prediction state falls back to upstream unchanged.

        Args:
            classes: Sorted class IDs observed in predictions or targets, used as COCO category IDs.

        Returns:
            The prediction and target datasets in the order ``_get_coco_datasets`` returns them, followed by the
            COCO-format dictionary the prediction dataset was built from, or ``None`` when it was loaded from a
            detection array instead. That dictionary is returned rather than read back from the dataset because
            hotcoco's ``dataset`` getter is a copy, so the ``area_bbox``/``area_segm`` switch a multi-IoU-type
            evaluation performs would be discarded (hotcoco 0.5 also dropped those non-COCO keys outright; 1.0.0
            preserves them, but a copy is still a copy); ``None`` is safe because the array path is taken only for
            single-IoU-type evaluation, where no area switching happens.

        Raises:
            ValueError: If stored detection scores are not one-dimensional floating-point tensors.
            RuntimeError: If upstream stops emitting one annotation for each stored detection score.
        r   Nr+   )r   r   r   r&   r   r    r%   r!   )r   r   r   r   r    r%   r!   r   r6   )rÙ   r  r   rÝ   rŽ   r   r×   r   r'   r   r   r   r   r   r   r   r   r    r!   ÚdictrD   ÚdatasetÚlistr	   r)   Ú_build_cocoÚ_loads_detections_from_arrayÚloadResÚ_detection_results_arrayÚ_assign_detection_scores)
rw   r  rÒ   Údetection_boxesr  r  r%   Útarget_datasetr  Úrebuilt_per_iou_types
             r@   r  z.OnePassCocoMeanAveragePrecision._coco_datasets·  s–  € ð> Ô$ˆÝ03°DÔ4FÑ0GÔ0GÈ!Ò0KÐ0K˜$Ô,Ð,ÐQUˆð Ð"­:°g½Ñ+OÔ+OÐ"Ý&*Ý•c�3�h”Ø×*Ò*ØÔ+ØÔ(ØÔ)ØÔ+ØÔ)ØÔ)ØÔ&ØÔ'ØÔ)Ø”MØ œLð +ñ ô ñ'ô 'Ñ#ˆJ˜ð  ˜{­Dµµc½3°h´ÀÔASÑ,TÔ,TÐTÐTõ �$�vœ,¨Ñ0Ô0ˆ
Ø ×1Ò1ØÔ*Ý*-¨dÔ.BÑ*CÔ*CÀaÒ*GÐ*G�$Ô&Ð&ÈTÝ+.¨tÔ/DÑ+EÔ+EÈÒ+IÐ+I�$Ô'Ð'ÈtØÔ*ØÔ&Ø”]Ø!Ø”Lð 2ñ 	
ô 	
ˆð ×&Ò& ~Ñ6Ô6ˆØ×,Ò,¨_Ñ=Ô=ð 	[Ø×&Ò& t×'DÒ'DÑ'FÔ'FÑGÔGÈÐVZÐZÐZà$×5Ò5ØÔ(Ø!Ý),¨TÔ-@Ñ)AÔ)AÀAÒ)EÐ)E�$Ô%Ð%È4Ø*Ð6�4�4¸DÔ<QØ”]Ø!Ø”Lð 6ñ 
ô 
Ðð Ð&Ø×)Ò)Ð*<¸]Ô*KÑLÔLÐLõ  # 4¤=Ñ1Ô1°AÒ5Ð^½*ÀWÍoÑ:^Ô:^ÐØ1Ð[�T�T°t×7GÒ7GÐHZÑ7[Ô7[ˆ
Ø˜;Ð(:Ð:Ð:rB   r_  úlist[Tensor] | Nonec                ón   — t          | j        t          ¦  «        o|duot          | j        ¦  «        dk    S )aL  Return whether predictions can be loaded from a detection array instead of built as annotation dicts.

        Building the prediction dataset is the dominant cost of ``compute()`` once the evaluator is fast: at COCO
        validation scale TorchMetrics materializes one Python dict per detection, over a million of them, which
        takes longer than hotcoco needs to evaluate them. ``loadRes`` accepts the same detections as one array and
        parses it in Rust. faster-coco-eval is excluded because its own ``loadRes`` is slower than the dict path it
        would replace, and mask evaluation is excluded because an array carries no segmentation.

        Args:
            detection_boxes: Stored detection boxes, or ``None`` when the state holds none.

        Returns:
            Whether the detection-array path applies.
        N)r›   )rÝ   rÙ   rŽ   r×   r    )rw   r_  s     r@   r[  z<OnePassCocoMeanAveragePrecision._loads_detections_from_array  s=   € õ  �tÔ)­?Ñ;Ô;ð 2Ø tÐ+ð2å�d”mÑ$Ô$¨	Ò1ð	
rB   r¨   c                óÒ  — |                       ¦   «          d„ | j        D ¦   «         }t          j        |¦  «                             ¦   «         }t          j        d„ |D ¦   «         ¦  «        }t          j        t          j        t          |¦  «        ¦  «        |¦  «        }|                     ¦   «          	                    d¦  «        |t          j        | j
        ¦  «                             ¦   «          	                    d¦  «        t          j        | j        ¦  «                             ¦   «          	                    d¦  «        f}t          j        |d¬¦  «                             ¦   «         S )a”  Return stored detections as the array COCO's ``loadRes`` accepts, which is also vernier's ``(N, 7)``.

        Columns are ``[image_id, x, y, width, height, score, category_id]``, in stored-state order so that
        equal-scoring detections keep the tie order the annotation-dict path produced. Boxes need no conversion:
        TorchMetrics already converted them to COCO's ``xywh`` when ``update()`` stored them.

        ``torch.cat(..., dim=1)`` writes the seven columns into one C-contiguous float64 buffer, which vernier's
        matrix route requires of the caller rather than copying silently. The ID columns ride as float64; vernier
        checks them back to exact integers, safe from ``int64`` state below 2^53.

        Returns:
            One row for each stored detection.

        Raises:
            ValueError: If stored detection scores are not one-dimensional floating-point tensors.
        c                ó:   — g | ]}|                      d d¦  «        ‘ŒS rC  rE  ©rí   Úimage_boxess     r@   rô   zLOnePassCocoMeanAveragePrecision._detection_results_array.<locals>.<listcomp>=  s(   € Ð[Ð[Ð[¸˜+×-Ò-¨b°!Ñ4Ô4Ð[Ð[Ð[rB   c                ó,   — g | ]}t          |¦  «        ‘ŒS rS   rJ  rf  s     r@   rô   zLOnePassCocoMeanAveragePrecision._detection_results_array.<locals>.<listcomp>?  s    € Ð,`Ð,`Ð,`À+­S°Ñ-=Ô-=Ð,`Ð,`Ð,`rB   r6   )Údim)Ú_validate_detection_scoresr   r=   rT  Údoubler  Úrepeat_interleaveÚaranger  Ú	unsqueezer   r   Únumpy)rw   Úreshaped_boxesr   Údetections_per_imageÚ	image_idsÚcolumnss         r@   r]  z8OnePassCocoMeanAveragePrecision._detection_results_array&  s.  € ð" 	×'Ò'Ñ)Ô)Ð)ð \Ð[ÈÔHZÐ[Ñ[Ô[ˆÝ”	˜.Ñ)Ô)×0Ò0Ñ2Ô2ˆÝ$œ|Ð,`Ð,`ÐQ_Ð,`Ñ,`Ô,`ÑaÔaÐÝÔ+­E¬L½Ð=QÑ9RÔ9RÑ,SÔ,SÐUiÑjÔjˆ	à×ÒÑÔ×(Ò(¨Ñ+Ô+ØÝŒI�dÔ+Ñ,Ô,×3Ò3Ñ5Ô5×?Ò?ÀÑBÔBÝŒI�dÔ+Ñ,Ô,×3Ò3Ñ5Ô5×?Ò?ÀÑBÔBð	
ˆõ Œy˜ aÐ(Ñ(Ô(×.Ò.Ñ0Ô0Ð0rB   c                óä   — t          | j        ¦  «        D ]Z\  }}|j        dk    rt          d|› d|j        › d�¦  «        ‚t	          j        |¦  «        st          d|› d|j        › d�¦  «        ‚Œ[dS )aþ  Restate the per-annotation score checks TorchMetrics performs during conversion.

        Upstream validates that scores are a tensor but not that each is a one-dimensional floating-point one; that
        check only happens while converting one annotation at a time. Both of RF-DETR's paths convert whole images
        or the whole state at once, so the check has to be made here instead.

        Raises:
            ValueError: If an image's scores are not a one-dimensional floating-point tensor.
        r6   zInvalid input score of sample z' (expected one-dimensional tensor, got z dimensions)z (expected floating point, got ú)N)Ú	enumerater   ÚndimrÖ   r=   Úis_floating_pointr«   )rw   Úimage_idÚimage_scoress      r@   rj  z:OnePassCocoMeanAveragePrecision._validate_detection_scoresI  s¿   € õ '0°Ô0EÑ&FÔ&Fð 		ð 		Ñ"ˆH�lØÔ  AÒ%Ð%Ý ð]°Xð ]ð ]Ø=IÔ=Nð]ð ]ð ]ñô ð õ Ô*¨<Ñ8Ô8ð Ý Øs°XÐsÐsÐ^jÔ^pÐsÐsÐsñô ð ðð		ð 		rB   rX  údict[str, Any]c                ól  — t          t          dt          f         | j        j        ¦  «        }t          | j        t          ¦  «        sd |¦   «         }||_        t          j	        t          j        ¦   «         ¦  «        5  |                     ¦   «          ddd¦  «         n# 1 swxY w Y   |S  ||¦  «        S )a4  Return an indexed backend COCO dataset for a TorchMetrics COCO-format dictionary.

        Args:
            dataset: A COCO-format dictionary as produced by TorchMetrics' ``_get_coco_format``.

        Returns:
            The backend's COCO dataset object, with its annotation index already built.
        .N)r   r   r   rÙ   r   rÝ   rŽ   rX  r[   r\   r]   r^   ÚcreateIndex)rw   rX  Úcoco_factoryr   s       r@   rZ  z+OnePassCocoMeanAveragePrecision._build_coco^  sÜ   € õ �H S­# XÔ.°Ô0BÔ0GÑHÔHˆÝ˜$Ô,­oÑ>Ô>ð 	Ø�<‘>”>ˆDØ"ˆDŒLÝÔ+­B¬K©M¬MÑ:Ô:ð #ð #Ø× Ò Ñ"Ô"Ð"ð#ð #ð #ñ #ô #ð #ð #ð #ð #ð #ð #øøøð #ð #ð #ð #àˆKàˆ|˜GÑ$Ô$Ð$s   Á=BÂB"Â%B"r  r  údict[str, Any] | NonerD   c                ó¸   — |€t          d¦  «        ‚|d         D ]}|d|› �         |d<   Œt          | j        t          ¦  «        s|S |                      |¦  «        S )aæ  Point prediction annotation areas at one IoU type of a multi-type evaluation.

        Args:
            coco_preds: The prediction COCO dataset built by :meth:`_coco_datasets`.
            prediction_dataset: The COCO-format dictionary ``coco_preds`` was built from. Never ``None`` here: the
                array path that returns ``None`` is restricted to single-IoU-type evaluation, which never reaches
                this method.
            iou_type: The IoU type whose per-annotation area should become the active ``area``.

        Returns:
            The prediction dataset to evaluate for this IoU type.

        Raises:
            RuntimeError: If a multi-IoU-type evaluation reached the array-built prediction dataset.
        Nz±OnePassCocoMeanAveragePrecision cannot switch annotation areas on an array-built prediction dataset; the detection-array path must stay restricted to single-IoU-type evaluation.r   Úarea_r   )ÚRuntimeErrorrÝ   rÙ   rŽ   rZ  )rw   r  r  r    Ú
annotations        r@   r  z@OnePassCocoMeanAveragePrecision._prediction_dataset_for_iou_typeq  s‡   € ð$ Ð%Ýðhñô ð ð -¨]Ô;ð 	@ð 	@ˆJØ!+Ð,>°HÐ,>Ð,>Ô!?ˆJ�vÑÐÝ˜$Ô,­oÑ>Ô>ð 	àÐð ×ÒÐ 2Ñ3Ô3Ð3rB   ú&contextlib.AbstractContextManager[Any]c                óœ   — t          | j        t          ¦  «        rt          ¦   «         S t	          j        t          j        ¦   «         ¦  «        S )z»Return the standard-output suppression the active backend needs while evaluating.

        Returns:
            A context manager that silences the backend's COCO summary output.
        )rÝ   rÙ   rŽ   ra   r[   r\   r]   r^   r{   s    r@   r  z1OnePassCocoMeanAveragePrecision._quiet_evaluation”  s<   € õ �dÔ(­/Ñ:Ô:ð 	3Ý0Ñ2Ô2Ð2ÝÔ)­"¬+©-¬-Ñ8Ô8Ð8rB   r   úlist[dict[str, Any]]c                óx  — |                       ¦   «          d„ | j        D ¦   «         }t          |¦  «        t          |¦  «        k    rYdt          |¦  «        › dt          |¦  «        › dt          j        › d�}t
                               |¦  «         t          |¦  «        ‚t          ||¦  «        D ]
\  }}||d<   ŒdS )aè  Attach stored detection scores to prediction annotations, converting one image of scores at a time.

        Args:
            annotations: Prediction annotations built by TorchMetrics with ``scores=None``, in state order.

        Raises:
            ValueError: If an image's scores are not one-dimensional floating-point tensors, which upstream rejects
                per annotation.
            RuntimeError: If the annotation count no longer matches the stored score count.
        c                ód   — g | ]-}|                      ¦   «                              ¦   «         D ]}|‘ŒŒ.S rS   )rà   Útolist)rí   rz  Úscores      r@   rô   zLOnePassCocoMeanAveragePrecision._assign_detection_scores.<locals>.<listcomp>ª  s>   € ÐpÐpÐp ÐT`×TdÒTdÑTfÔTf×TmÒTmÑToÔToÐpÐpÈ5�uÐpÐpÐpÐprB   z&OnePassCocoMeanAveragePrecision built z prediction annotations for z$ detection scores with torchmetrics ú4. Re-verify rfdetr.training.coco_map before upgrade.rŠ  N)	rj  r   r  ÚtorchmetricsÚ__version__r  rN   r‚  Úzip)rw   r   Úflat_scoresÚmessagerƒ  rŠ  s         r@   r^  z8OnePassCocoMeanAveragePrecision._assign_detection_scoresž  sî   € ð 	×'Ò'Ñ)Ô)Ð)ØpÐp°Ô1FÐpÑpÔpˆÝˆ{ÑÔ�s ;Ñ/Ô/Ò/Ð/ðE½¸[Ñ9IÔ9Ið Eð EÝ�{Ñ#Ô#ðEð EÝIUÔIaðEð Eð Eð õ
 �LŠL˜Ñ!Ô!Ð!Ý˜wÑ'Ô'Ð'Ý!$ [°+Ñ!>Ô!>ð 	(ð 	(ÑˆJ˜Ø"'ˆJ�wÑÐð	(ð 	(rB   Úpresent_methodsú	list[str]c                ó0  ‡— g }|D ]�}t          j        t          | |¦  «        ¦  «        j        Št	          t
          |         ¦  «        t	          ‰¦  «        k    r&t          ˆfd„t          |         D ¦   «         ¦  «        r|                     |¦  «         Œ�|S )zTReturn backend methods whose required parameters cannot accept this adapter's calls.c              3  óT   •K  — | ]"}‰|         j         t          j        j        u V — Œ#d S ©N)ÚkindÚinspectÚ	ParameterÚPOSITIONAL_ONLY)rí   Ú	parameterÚ
parameterss     €r@   ú	<genexpr>zQOnePassCocoMeanAveragePrecision._mismatched_backend_signatures.<locals>.<genexpr>¾  sR   øè è € ð Oð Oàð ˜9Ô%Ô*­gÔ.?Ô.OÐOðOð Oð Oð Oð Oð OrB   )	r—  Ú	signaturer²   r›  Úsetr*   Úanyr-   Úappend)rÒ   r‘  Ú
mismatchedrL   r›  s       @r@   Ú_mismatched_backend_signaturesz>OnePassCocoMeanAveragePrecision._mismatched_backend_signatures¸  sµ   ø€ ð ˆ
Ø#ð 	(ð 	(ˆDÝ Ô*­7°7¸DÑ+AÔ+AÑBÔBÔMˆJÝÕ-¨dÔ3Ñ4Ô4½¸J¹¼ÒGÐGÍ3ð Oð Oð Oð Oå!8¸Ô!>ðOñ Oô Oñ Lô LÐGð ×!Ò! $Ñ'Ô'Ð'øØÐrB   r¤   c           	     ó  — g }|D ]~}t          t          j        t          | |¦  «        ¦  «        j                             ¦   «         ¦  «        dd…         }t          d„ |D ¦   «         ¦  «        r|                     |¦  «         Œ|S )zUReturn evaluator method names that now require an argument this adapter never passes.r6   Nc              3  ób   K  — | ]*}|j         t          j        j        u o|j        t
          vV — Œ+d S r•  )Údefaultr—  r˜  Úemptyr–  Ú_VAR_PARAM_KINDS)rí   Úps     r@   rœ  zXOnePassCocoMeanAveragePrecision._evaluator_methods_now_requiring_args.<locals>.<genexpr>Í  s=   è è € ÐkÐkÐ_`�1”9¥Ô 1Ô 7Ð7ÐZ¸A¼FÕJZÐ<ZÐkÐkÐkÐkÐkÐkrB   )rY  r—  r�  r²   r›  ÚvaluesrŸ  r   )r¤   r‘  r¡  rL   rŸ   s        r@   Ú%_evaluator_methods_now_requiring_argszEOnePassCocoMeanAveragePrecision._evaluator_methods_now_requiring_argsÅ  s’   € ð ˆ
Ø#ð 	(ð 	(ˆDõ �'Ô+­G°NÀDÑ,IÔ,IÑJÔJÔU×\Ò\Ñ^Ô^Ñ_Ô_Ð`aÐ`bÐ`bÔcˆFÝÐkÐkÐdjÐkÑkÔkÑkÔkð (Ø×!Ò! $Ñ'Ô'Ð'øØÐrB   c                óž  ‡‡‡‡‡— d„ | j                              ¦   «         D ¦   «         }t          t          ¦  «        }t	          ||z
  ¦  «        }t	          ||z
  ¦  «        }t          | dd¦  «        Š‰�‰j        ndŠt          ˆfd„t          D ¦   «         ¦  «        }‰�‰j	        rt          nd}‰€dgnˆfd„|D ¦   «         Šˆfd„|D ¦   «         }|r|                      ‰|¦  «        ng }dŠg Šg }	‰�„|r‚	 ‰j        ‰j        cŠ}
n!# t          t          t           f$ r dxŠ}
Y nw xY wt#          |
¦  «        sg ‰¢d‘Š‰€d	gnˆfd
„|D ¦   «         Šˆfd„|D ¦   «         }|r|                      ‰|¦  «        ng }	|s|s
‰s‰s|s|	sdS dt&          j        › d|› d|› d‰› d‰› d|› d|	› d�}t*                               |¦  «         t/          |¦  «        ‚)zZFail fast when installed TorchMetrics internals differ from the verified adapter boundary.c                óB   — h | ]\  }}t          |t          ¦  «        ¯|’ŒS rS   )rÝ   rY  )rí   rL   r¥  s      r@   ú	<setcomp>zMOnePassCocoMeanAveragePrecision._validate_private_contract.<locals>.<setcomp>Ó  s.   € ÐjÐjÐj¡] T¨7ÕPZÐ[bÕdhÑPiÔPiÐj˜DÐjÐjÐjrB   rÙ   NrS   c              3  ó$   •K  — | ]
}|‰v¯|V — Œd S r•  rS   )rí   rL   Úunuseds     €r@   rœ  zMOnePassCocoMeanAveragePrecision._validate_private_contract.<locals>.<genexpr>Ý  s.   øè è € Ð^Ð^¨È4ÐW]ÐK]ÐK] ÐK]ÐK]ÐK]ÐK]Ð^Ð^rB   c           	     óP   •— g | ]"}t          t          ‰|d ¦  «        ¦  «        ° |‘Œ#S r•  ©Úcallabler²   )rí   rL   rÒ   s     €r@   rô   zNOnePassCocoMeanAveragePrecision._validate_private_contract.<locals>.<listcomp>â  s4   ø€ ÐaÐaÐa˜4½(Å7È7ÐTXÐZ^ÑC_ÔC_Ñ:`Ô:`Ða�$ÐaÐaÐarB   c                ó   •— g | ]}|‰v¯|‘Œ	S rS   rS   )rí   rL   Úmissing_methodss     €r@   rô   zNOnePassCocoMeanAveragePrecision._validate_private_contract.<locals>.<listcomp>ä  s$   ø€ Ð"cÐ"cÐ"c¨DÀtÐSbÐGbÐGb 4ÐGbÐGbÐGbrB   r   rƒ   c           	     óP   •— g | ]"}t          t          ‰|d ¦  «        ¦  «        ° |‘Œ#S r•  r±  )rí   rL   r¤   s     €r@   rô   zNOnePassCocoMeanAveragePrecision._validate_private_contract.<locals>.<listcomp>ú  s5   ø€ ÐnÐnÐn˜tÅÍÐQ_ÐaeÐgkÑIlÔIlÑ@mÔ@mÐn�dÐnÐnÐnrB   c                ó   •— g | ]}|‰v¯|‘Œ	S rS   rS   )rí   rL   Úmissing_evaluator_methodss     €r@   rô   zNOnePassCocoMeanAveragePrecision._validate_private_contract.<locals>.<listcomp>ü  s$   ø€ Ð(uÐ(uÐ(u°$ÈtÐ[tÐOtÐOt¨ÐOtÐOtÐOtrB   zLOnePassCocoMeanAveragePrecision is incompatible with installed torchmetrics z. Missing list states: z; unexpected list states: z; missing backend methods: z; missing evaluator methods: z2; backend methods with an incompatible signature: z/; evaluator methods now requiring an argument: r‹  )Ú	_defaultsrò   rž  rþ   Úsortedr²   rf   r×   r*   rg   Ú_EVALUATOR_ZERO_ARG_METHODSr¢  rƒ   r   ÚAttributeErrorÚ	TypeErrorrM   r²  rª  rŒ  r�  r  rN   r‚  )rw   Úinstalled_statesÚexpected_statesÚmissing_statesÚstale_statesÚbackend_methodsÚevaluator_methodsÚpresent_backend_methodsÚmismatched_signaturesÚmismatched_evaluator_signaturesr~  Úpresent_evaluator_methodsr�  rÒ   r¤   r·  r´  r¯  s                @@@@@r@   rÚ   z:OnePassCocoMeanAveragePrecision._validate_private_contractÑ  s  øøøøø€ àjÐj°d´n×6JÒ6JÑ6LÔ6LÐjÑjÔjÐÝÕ.Ñ/Ô/ˆÝ Ð2BÑ BÑCÔCˆÝÐ.°Ñ@ÑAÔAˆÝ-4°T¸?ÈDÑ-QÔ-Qˆð
 4;Ð3F�Ô/Ð/ÈBˆÝÐ^Ð^Ð^Ð^Õ1GÐ^Ñ^Ô^Ñ^Ô^ˆØ;B¸?ÈgÔNi¸?Õ7Ð7ÐoqÐð ˆð ÐÐàaÐaÐaÐa ?ÐaÑaÔað 	ð
 #dÐ"cÐ"cÐ"c°OÐ"cÑ"cÔ"cÐàUlÐtˆD×/Ò/°Ð9PÑQÔQÐQÐrtð 	ð ˆØ/1Ð!Ø57Ð'ØÐÐ#4Ðð5ð 07Ô/?ÀÄÐ,�  øÝ"¥I­{Ð;ð 5ð 5ð 5ð 15Ð4�   ð	5øøøõ
 ˜LÑ)Ô)ð =Ø"< OÐ"<°VÐ"<�ð "Ð)ð ��ànÐnÐnÐnÐ'8ÐnÑnÔnð &ð
 )vÐ(uÐ(uÐ(uÐ:KÐ(uÑ(uÔ(uÐ%ð -ð�×:Ò:¸>ÐKdÑeÔeÐeàð ,ð ð	àð	ð ð	ð )ð		ð
 %ð	ð /ð	ð ˆFðAÝ(Ô4ðAð AØM[ðAð Aà'3ðAð AàP_ðAð Að +DðAð Að @Uð	Að Að
 =\ðAð Að Að 	õ 	�Š�WÑÔÐÝ˜7Ñ#Ô#Ð#s   Ã5D ÄD#Ä"D#c                óø   — | j         | j        z   }|sg S t          t          t                   t          j        t          j        |¦  «        ¦  «                             ¦   «          	                    ¦   «         ¦  «        S )z;Return sorted class IDs observed in predictions or targets.)
r   r   r   rY  r4   r=   ÚuniquerT  rà   r‰  )rw   r   s     r@   r  z1OnePassCocoMeanAveragePrecision._observed_classes  s_   € àÔ&¨Ô)@Ñ@ˆØð 	ØˆIÝ•D�”I�uœ|­E¬I°fÑ,=Ô,=Ñ>Ô>×BÒBÑDÔD×KÒKÑMÔMÑNÔNÐNrB   r#   c                óÎ   — | j         rt          |¦  «        nd}t          j        |fdt          j        ¬¦  «        }|› d�||› d| j        d         › d�|                     ¦   «         iS )zOReturn compact negative per-class sentinels when COCO evaluation has no images.r6   ç      ð¿rª   Úmap_per_classÚmar_rš   Ú
_per_class)rÏ   r  r=   ÚfullÚfloat32r$   Úclone)rw   r#   r  Úcountr©  s        r@   Ú_per_class_sentinelsz4OnePassCocoMeanAveragePrecision._per_class_sentinels  sq   € à $Ô 2Ð9•�G‘”�¸ˆÝ”˜U˜H dµ%´-Ð@Ñ@Ô@ˆàÐ$Ð$Ð$ fØÐHÐH˜4Ô8¸Ô<ÐHÐHÐHÈ&Ï,Ê,É.Ì.ð
ð 	
rB   c                ó~   — i | j                              ddgz  || j        ¬¦  «        ¥|                      ||¦  «        ¥S )aî  Return every metric key for an IoU type with no images to evaluate, all at COCO's ``-1``.

        Args:
            prefix: Key prefix for this IoU type, empty when only one is evaluated.
            classes: Sorted class IDs observed in predictions or targets.

        Returns:
            The aggregate sentinels upstream emits, plus the per-class ones it omits -- a divergence from stock
            TorchMetrics (module docstring's Outputs section), which the callback relies on.
        é   rÊ  r,   )rÙ   r(   r$   rÒ  )rw   r#   r  s      r@   r  z7OnePassCocoMeanAveragePrecision._empty_iou_type_results'  sV   € ð
ØÔ ×;Ò;Ø�d�V‘ FÀTÔEbð <ñ ô ð
ð ×'Ò'¨°Ñ8Ô8ð	
ð 	
rB   r?  c                óà  — | j         s|                      ||¦  «        S t          |t          ¦  «        rd|vsd|vr9dt          j        › d�}t                               |¦  «         t          |¦  «        ‚t          j
        |d         ¦  «        }t          j
        |d         ¦  «        }|j        dk    sG|j        dk    s<|j        d         t          |¦  «        k    s|j        d         t          |¦  «        k    rLd	|j        › d
|j        › dt          |¦  «        › d�}t                               |¦  «         t          |¦  «        ‚g }g }t          t          |¦  «        ¦  «        D ]³}	|dd…dd…|	ddf         }
|
|
dk             }|                     |j        r!t#          |                     ¦   «         ¦  «        nd¦  «         |dd…|	ddf         }||dk             }|                     |j        r!t#          |                     ¦   «         ¦  «        nd¦  «         Œ´|› d�t'          j        |t&          j        ¬¦  «        |› d| j        d         › d�t'          j        |t&          j        ¬¦  «        iS )zPReduce precision and recall arrays to TorchMetrics-compatible per-class vectors.r/  r0  zvOnePassCocoMeanAveragePrecision requires COCO evaluator eval['precision'] and eval['recall'] arrays with torchmetrics ú.é   rD  é   r6   zWOnePassCocoMeanAveragePrecision received incompatible COCO evaluator shapes: precision=z	, recall=z
, classes=Nr   rš   rÊ  rË  rª   rÌ  rÍ  )rÏ   rÒ  rÝ   rW  rŒ  r�  r  rN   r‚  r¬   r  rw  Úshaper  Úranger   rP  ÚfloatÚmeanr=   r  rÏ  r$   )rw   r?  r#   r  r�  r/  r0  rË  Úmar_per_classÚclass_indexÚclass_precisionÚvalid_precisionÚclass_recallÚvalid_recalls                 r@   r  z1OnePassCocoMeanAveragePrecision._reduce_per_class9  s¸  € àÔ!ð 	>Ø×,Ò,¨V°WÑ=Ô=Ð=Ý˜*¥dÑ+Ô+ð 	(¨{À*Ð/LÐ/LÐPXÐ`jÐPjÐPjðAÝ%1Ô%=ðAð Að Að õ �LŠL˜Ñ!Ô!Ð!Ý˜wÑ'Ô'Ð'Ý”J˜z¨+Ô6Ñ7Ô7ˆ	Ý”˜J xÔ0Ñ1Ô1ˆàŒN˜aÒÐØŒ{˜aÒÐØŒ˜qÔ!¥S¨¡\¤\Ò1Ð1ØŒ|˜AŒ¥# g¡,¤,Ò.Ð.ð_Ø&œ_ð_ð _Ø7=´|ð_ð _ÝORÐSZÉ|Ì|ð_ð _ð _ð õ �LŠL˜Ñ!Ô!Ð!Ý˜wÑ'Ô'Ð'à%'ˆØ%'ˆÝ ¥ W¡¤Ñ.Ô.ð 	\ð 	\ˆKØ'¨¨¨¨1¨1¨1¨k¸1¸bÐ(@ÔAˆOØ-¨oÀÒ.BÔCˆOØ× Ò À/ÔBVÐ!`¥ ×';Ò';Ñ'=Ô'=Ñ!>Ô!>Ð!>Ð\`ÑaÔaÐaØ! ! ! ! [°!°RÐ"7Ô8ˆLØ'¨°rÒ(9Ô:ˆLØ× Ò ¸|Ô?PÐ!Z¥ |×'8Ò'8Ñ':Ô':Ñ!;Ô!;Ð!;ÐVZÑ[Ô[Ð[Ð[àÐ$Ð$Ð$¥e¤l°=ÍÌÐ&VÑ&VÔ&VØÐHÐH˜4Ô8¸Ô<ÐHÐHÐHÍ%Ì,Ø¥U¤]ðKñ Kô Kð
ð 	
rB   )	rÆ   r›   NNNFFrÇ   rQ   )rÈ   rÉ   r    rÊ   rË   rÌ   rÍ   rÌ   r$   rÎ   rÏ   rd   rÐ   rd   r!   rÑ   rÒ   r   rÓ   r   r3   ro   )r3   rd   )rä   rå   ræ   rå   r3   ro   r‡   )r3   r  )r  r$  r3   r  )r3   r@  )r  r$  r3   rU  )r_  rb  r3   rd   )r3   r¨   )rX  r{  r3   r   )r  r   r  r  r    rD   r3   r   )r3   r„  )r   r†  r3   ro   )rÒ   r   r‘  r’  r3   r’  )r¤   r   r‘  r’  r3   r’  )r3   r$  )r#   rD   r  r$  r3   r  )r?  r   r#   rD   r  r$  r3   r  )rh   ri   rj   rk   rt   rŠ   rã   r÷   r  r#  r  r1  r  r[  r]  rj  rZ  r  r  r^  Ústaticmethodr¢  rª  rÚ   r  rÒ  r  r  r‹   rŒ   s   @r@   rÅ   rÅ   ¤  sW  ø€ € € € € ðð ð: 9?ØRXØ-1Ø-1Ø59Ø#Ø!&Ø-4Ø#,ð+*ð +*ð +*ð +*ð +*ð +*ð +*ðZ ðð ð ñ „Xðð.ð .ð .ð .ð .ð .ð"Gð Gð Gð Gð 7ð 7ð 7ð 7ðr@ð @ð @ð @ðD"1ð "1ð "1ð "1ðHX;ð X;ð X;ð X;ðt
ð 
ð 
ð 
ð*!1ð !1ð !1ð !1ðFð ð ð ð*%ð %ð %ð %ð&!4ð !4ð !4ð !4ðF9ð 9ð 9ð 9ð(ð (ð (ð (ð4 ð
ð 
ð 
ñ „\ð
ð ð	ð 	ð 	ñ „\ð	ðD$ð D$ð D$ð D$ðLOð Oð Oð Oð
ð 
ð 
ð 
ð
ð 
ð 
ð 
ð$(
ð (
ð (
ð (
ð (
ð (
ð (
ð (
rB   rÅ   )r3   r4   r•  )rC   rD   rE   rD   rF   rG   r3   r   rˆ   )r3   rV   )r3   r•   )Ark   Ú
__future__r   r[   Ú	functoolsr—  r]   r:   rY   Úcollections.abcr   r   Útypingr   r   r   ro  r¬   r=   rŒ  r	   Útorchmetrics.detectionr
   Útorchmetrics.detection.helpersr   Úrfdetr.configr   Úrfdetr.utilities.distributedr   r   r   Úrfdetr.utilities.loggerr   r  Ú	frozensetrë   rþ   r*   rl   r-   rº  r˜  ÚVAR_POSITIONALÚVAR_KEYWORDr§  r2   rA   rO   rT   Úcontextmanagerra   rc   rn   rŽ   r“   Ú	lru_cacher¥   r§   r¹   rµ   r»   r¿   rÁ   rÃ   rÅ   rS   rB   r@   ú<module>rò     s[  ððð ð ð> #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ø Ð Ð Ð Ø €€€Ø 	€	€	€	Ø 	€	€	€	Ø €€€Ø .Ð .Ð .Ð .Ð .Ð .Ð .Ð .Ø %Ð %Ð %Ð %Ð %Ð %Ð %Ð %Ð %Ð %à Ð Ð Ð Ø €€€Ø Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø 7Ð 7Ð 7Ð 7Ð 7Ð 7Ø 6Ð 6Ð 6Ð 6Ð 6Ð 6à )Ð )Ð )Ð )Ð )Ð )Ø bÐ bÐ bÐ bÐ bÐ bÐ bÐ bÐ bÐ bØ .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€à �yÐ!ZÐ!ZÐ!ZÑ[Ô[Ð ð
Ð ðð #RØuð6ð 6Ð ð ð ð ñ ð( 'Ø"HØuð7ð 7Ð ð ð ð ñ ð FÐ ØÔ%Ô4°gÔ6GÔ6SÐTÐ ð 8CÐ Ð BÐ BÐ BÑ Bð?ð ?ð ?ð ?ð ð ð ð ð ðB	:ð 	:ð 	:ð 	:ð Ôðð ð ñ Ôðð8%ð %ð %ð %ð %˜ñ %ô %ð %ð'$ð '$ð '$ð '$ð '$Ð,ñ '$ô '$ð '$ðT
ð 
ð 
ð 
ð 
Ð)ñ 
ô 
ð 
ð	ið 	ið 	ið 	ið €Ô˜TÐ"Ñ"Ô"ðð ð ñ #Ô"ðð4-ð -ð -ð -ð -ñ -ô -ð -ð* &Ð%Ñ'Ô'Ð ð"ð "ð "ð "ð "Ð(ñ "ô "ð "ð0-ð -ð -ð -ð -Ð/ñ -ô -ð -ð	:ð 	:ð 	:ð 	:ðð ð ð ð Ð(ñ ô ð ðD /ØØØð	Fð F€	ð ð ð ñ ð}

ð }

ð }

ð }

ð }

Ð&:ñ }

ô }

ð }

ð }

ð }

rB   