Ë
    ëÓ^jJ¼ ã                  óÐ  — U 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Zd dl	Z	d dl
mZ d dlmZ d dlmZmZ d dlmZ d dlmZ d dlmZmZmZmZmZ d dlZd dlZd dlZd dlmc m Z! d dl"Z"d d	l#m$Z$ d d
l%m&Z&m'Z' d dl(m)Z)m*Z* d dl+m,Z,m-Z- d dl.m/Z/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5m6Z6 d dl7m8Z8m9Z9 d dl:m;Z; d dl<m=Z=m>Z> d dl?m@Z@ erd dlAmBZBmCZC 	  ejˆ                  d«        e@«       ZF ed«      ZG ed«      ZHdZIddgeI¢ZJ eKddh«      ZL eMd„ eID «       «      ZNdeOd<   d ZPdeOd!<   d"ZQd#eOd$<   d%ZRd#eOd&<   	 	 	 	 	 	 	 	 	 	 d.d'„ZSd/d(„ZTd0d)„ZUd1d*„ZV G d+„ d«      ZWd2d,„ZXd3d-„ZYy# eE$ r Y Œ†w xY w)4é    )ÚannotationsN)Údefaultdict)ÚCallable)ÚcopyÚdeepcopy©Úwraps)ÚPath)ÚTYPE_CHECKINGÚAnyÚConcatenateÚ	ParamSpecÚTypeVar)ÚImage)ÚCOCO_CLASS_NAMESÚCOCO_CLASSES)Údownload_pretrain_weightsÚget_model_cache_dir)ÚModelConfigÚTrainConfig)Úactive_keypoint_countsÚinfer_coco_keypoint_schemaÚinfer_yolo_keypoint_schema)Úis_valid_coco_dataset)ÚREQUIRED_YOLO_YAML_FILESÚis_valid_yolo_dataset)ÚModelContextÚ_build_model_context)Úis_main_process)Ú_is_bg_first_schemaÚ&precision_cholesky_to_pixel_covariance)Ú
get_logger©Ú
DetectionsÚ	KeyPointsÚhighÚ_PÚ_R)Ú
RFDETRBaseÚRFDETRKeypointPreviewÚRFDETRLargeÚRFDETRLargeDeprecatedÚRFDETRMediumÚ
RFDETRNanoÚ	RFDETRSegÚRFDETRSeg2XLargeÚRFDETRSegLargeÚRFDETRSegMediumÚRFDETRSegNanoÚRFDETRSegPreviewÚRFDETRSegSmallÚRFDETRSegXLargeÚRFDETRSmallÚRFDETRr   r,   r/   c              #  ó2   K  — | ]  }|t         vsŒ|–— Œ y ­w)N)Ú'_CHECKPOINT_MODEL_NAME_EXCLUDED_SYMBOLS)Ú.0Úclass_symbols     úV/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/detr.pyú	<genexpr>r>   N   s   è ø€ ò >Ø!¸ÔMtÒ9t„Lñ>ùs   ‚�ztuple[str, ...]Ú$_CHECKPOINT_MODEL_NAME_CLASS_SYMBOLS)ÚRFDETRXLargeÚRFDETR2XLargeÚ)_CHECKPOINT_PLUS_MODEL_NAME_CLASS_SYMBOLS))úkeypoint-previewr*   )zseg-2xlarger0   )zseg-xxlarger0   )z
seg-xlarger6   )z	seg-larger1   )z
seg-mediumr2   )z	seg-smallr5   )zseg-nanor3   )zseg-previewr4   )Úlarger+   )Úmediumr-   )Úsmallr7   )Únanor.   )Úbaser)   ztuple[tuple[str, str], ...]Ú_CHECKPOINT_MODEL_MAP_ENTRIES))Ú2xlargerA   )ÚxxlargerA   )Úxlarger@   Ú"_CHECKPOINT_PLUS_MODEL_MAP_ENTRIESc                óP  — 	 | \  }}d|fd|ffD ]g  \  }}t        |t        «      r(t        d|› dt	        |«      j
                  › d| ›d	�«      ‚	 t        j                  |«       |d
k  sŒZt        d| ›d�«      ‚ t        j                  |«      t        j                  |«      }}||z  d
k7  s||z  d
k7  rt        d|› d|› d|› d| ›d�	«      ‚||fS # t         t        f$ r t        d| ›d�«      d‚w xY w# t         $ r* t        d|› dt	        |«      j
                  › d| ›d	�«      d‚w xY w)uÕ  Validate a user-supplied ``(height, width)`` shape tuple and return normalised plain-int dims.

    Args:
        shape: The raw value supplied by the caller (e.g. from ``export(shape=...)`` or
            ``predict(shape=...)``).  Must be a two-element sequence of positive integers (or integer-compatible types
            accepted by :func:`operator.index`).
        block_size: Required divisor for both dimensions.  Equals ``patch_size * num_windows``.
        patch_size: Backbone patch size â€” used only in error messages.
        num_windows: Number of attention windows â€” used only in error messages.

    Returns:
        A ``(height, width)`` tuple of plain Python :class:`int` values.

    Raises:
        ValueError: If ``shape`` cannot be unpacked as a two-element sequence, if either
            dimension is a bool, float, or other non-integer type, if either dimension is not positive, or if either
            dimension is not divisible by ``block_size``.
    zGshape must be a sequence of two positive integers (height, width), got ú.NÚheightÚwidthzshape z must be an integer, got z (shape=z).r   z?shape must contain positive integers for height and width, got z-shape must have both dimensions divisible by ú (patch_size=ú * num_windows=z), got )Ú	TypeErrorÚ
ValueErrorÚ
isinstanceÚboolÚtypeÚ__name__ÚoperatorÚindex)ÚshapeÚ
block_sizeÚ
patch_sizeÚnum_windowsrP   rQ   Údim_nameÚdims           r=   Ú_validate_shape_dimsrb   i   s“  € ð0yØ‰ˆ�ð $ VÐ,¨w¸Ð.>Ð?ò 
k‰ˆ�#Ü�cœ4Ô Ü˜v h ZÐ/HÌÈcË×I[ÑI[ÐH\Ð\dÐejÐdmÐmoÐpÓqÐqð	Ü�N‰N˜3Ôð
 �!‹8ÜÐ^Ð_dÐ^gÐghÐiÓjÐjð
kô —N‘N 6Ó*¬H¯N©N¸5Ó,AˆE€FØ�
Ñ˜aÒ 5¨:Ñ#5¸Ò#:ÜØ;¸J¸<ð HØ%˜, o°k°]À'È%ÈÐRSðUó
ð 	
ð �5ˆ=Ðøô) ”zÐ"ò yÜÐbÐchÐbkÐklÐmÓnÐtxÐxðyûô ò 	ÜØ˜˜
Ð";¼DÀ»I×<NÑ<NÐ;OÈxÐX]ÐW`Ð`bÐcóàðð	ús   ‚C ÁC2Ã C/Ã23D%c                óB  — | €t        |dd«      } n[t        | t        «      st        | t        «      r| dk  rt	        d| ›�«      ‚t        |dd«      }|�| |k7  rt	        |› d| › d|› d�«      ‚t        | t        «      st        | t        «      r| dk  rt	        d| ›�«      ‚| S )	u2  Resolve and validate the ``patch_size`` argument for :meth:`RFDETR.export` and :meth:`RFDETR.predict`.

    Args:
        patch_size: Value supplied by the caller, or ``None`` to read from ``model_config``.
        model_config: The model's configuration object.  Must expose ``patch_size`` as a
            positive integer attribute when ``patch_size`` is ``None`` or when a mismatch check is needed.
        caller: Name of the calling method (``"export"`` or ``"predict"``) â€” used in
            error messages to help the caller locate the problem.

    Returns:
        A validated, positive :class:`int` patch size.

    Raises:
        ValueError: If the resolved or provided ``patch_size`` is not a positive integer,
            or if a caller-provided value disagrees with ``model_config.patch_size``.
    Nr^   é   r   z+patch_size must be a positive integer, got z(patch_size=z5) does not match the instantiated model's patch_size=z`. Patch size is an architectural parameter; omit patch_size to use the model's configured value.)ÚgetattrrV   rW   ÚintrU   )r^   Úmodel_configÚcallerÚmodel_patch_sizes       r=   Ú_resolve_patch_sizerj   š   sÆ   € ð" ÐÜ˜\¨<¸Ó<‰
ä�j¤$Ô'¬z¸*ÄcÔ/JÈjÐ\]ÊoÜÐJÈ:È.ÐYÓZÐZÜ" <°¸tÓDÐØÐ'¨JÐ:JÒ,JÜØ�(˜, z lð 3Ø.Ð/ð 0GðHóð ô
 �*œdÔ#¬:°jÄ#Ô+FÈ*ÐXYÊ/ÜÐFÀzÀnÐUÓVÐVØÐó    c                ó*  — t        | dd«      }t        | dd«      }|�|�t        |d«      syt        |t        «      rt	        j
                  |«      }t        |j                  «       d«      }|�'|j
                  |k7  r|j                  |«      | _	        yyy)aò  Move model weights to the target device recorded in *model_ctx*.

    ``_build_model_context`` intentionally keeps the ``nn.Module`` on CPU so that ``RFDETR.__init__`` does not
    initialise CUDA (which would prevent DDP strategies from forking in notebook environments).  This helper performs
    the deferred ``.to(device)`` on first use.

    It is safe to call on duck-typed stand-ins (e.g. ``SimpleNamespace``); the function silently returns when the
    expected attributes are missing.
    ÚdeviceNÚmodelÚ
parameters)
re   ÚhasattrrV   ÚstrÚtorchrm   Únextro   Útorn   )Ú	model_ctxÚtargetÚinnerÚfirst_params       r=   Ú_move_model_context_to_devicery   ¼   sŽ   € ô �Y ¨$Ó/€FÜ�I˜w¨Ó-€EØ€~˜˜¬g°e¸\Ô.JØÜ�&œ#ÔÜ—‘˜fÓ%ˆÜ�u×'Ñ'Ó)¨4Ó0€KØÐ ;×#5Ñ#5¸Ò#?ØŸ(™( 6Ó*ˆ	�ð $@Ðrk   c                ó0   ‡ — t        ‰ «      dˆ fd„«       }|S )aÕ  Decorate RF-DETR instance methods that require lazy model device placement.

    The wrapped method receives the same arguments and return value as the original method. Before calling it, the
    decorator moves ``self.model.model`` to ``self.model.device`` if the model context is available and the weights are
    still on a different device. This keeps public inference methods clean while preserving deferred CUDA initialization
    during ``RFDETR.__init__``.
    c                óH   •— t        t        | dd «      «        ‰| g|¢­i |¤ŽS )Nrn   )ry   re   )ÚselfÚargsÚkwargsÚmethods      €r=   Úwrapperz(_ensure_model_on_device.<locals>.wrapperÚ   s)   ø€ ä%¤g¨d°G¸TÓ&BÔCÙ�dÐ,˜TÒ, VÑ,Ð,rk   )r|   r   r}   z_P.argsr~   z	_P.kwargsÚreturnr(   r   )r   r€   s   ` r=   Ú_ensure_model_on_devicer‚   Ñ   s"   ø€ ô ˆ6ƒ]ô-ó ð-ð €Nrk   c                  óz  — e Zd ZU dZg d¢Zg d¢ZdZeZde	d<   e
Zde	d<   d	„ Zd
„ Zd(d„Zed)d„«       Zed*d„«       Zd„ Zeddej,                  fddœ	 	 	 	 	 	 	 	 	 d+d„«       Zd,d„Zed-d„«       Z	 	 	 	 	 	 	 	 	 	 	 	 	 d.ddœ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d/d„Zed0d„«       Zeddœd1d„«       Zd2d„Zed3d„«       Zed3d„«       Z ed3d„«       Z!ed4d„«       Z"d5d „Z#d6d!„Z$d7d"„Z%ed8d#„«       Z&d,d$„Z' ejP                  «       e	 	 	 	 d9	 	 	 	 	 	 	 	 	 	 	 	 	 d:d%„«       «       Z)	 	 d;	 	 	 	 	 	 	 	 	 	 	 d<d&„Z*d=d'„Z+y)>r8   z´The base RF-DETR class implements the core methods for training RF-DETR models, running inference on the models,
    optimising models, and uploading trained models for deployment.)g
×£p=
ß?gÉv¾Ÿ/Ý?g–C‹lçûÙ?)gZd;ßOÍ?gyé&1¬Ì?gÍÌÌÌÌÌÌ?Nztype[ModelConfig]Ú_model_config_classztype[TrainConfig]Ú_train_config_classc                óØ  —  | j                   di |¤Ž| _        | j                  «        | j                  | j                  «      | _        t        t        «      | _        | j                  j                  dk7  r¨ddl	m
} t        t        | j                  j                  «       || j                  «      «      D ��cg c]  \  }}|‘Œ	 c}}| _        t        t        | j                  j                  «       || j                  «      «      D ��cg c]  \  }}|‘Œ	 c}}| _        d | j                  _        d| _        d| _        d| _        d | _        d | _        d | _        d| _        y c c}}w c c}}w )Né   r   )ÚcycleF© )Úget_model_configrg   Úmaybe_download_pretrain_weightsÚ	get_modelrn   r   ÚlistÚ	callbacksÚnum_channelsÚ	itertoolsrˆ   ÚzipÚrangeÚmeansÚstdsÚinference_modelÚ_is_optimized_for_inferenceÚ3_has_warned_about_not_being_optimized_for_inferenceÚ_optimized_has_been_compiledÚ_optimized_batch_sizeÚ_optimized_resolutionÚ_optimized_dtypeÚ_optimized_inplace)r|   r~   rˆ   Ú_Úvals        r=   Ú__init__zRFDETR.__init__ì   s$  € Ø1˜D×1Ñ1Ñ;°FÑ;ˆÔØ×,Ñ,Ô.Ø—^‘^ D×$5Ñ$5Ó6ˆŒ
Ü$¤TÓ*ˆŒð ×Ñ×)Ñ)¨QÒ.Ý'ä,/´°d×6GÑ6G×6TÑ6TÓ0UÑW\Ð]a×]gÑ]gÓWhÓ,i×j¡& ! Sš#ÓjˆDŒJÜ+.¬u°T×5FÑ5F×5SÑ5SÓ/TÑV[Ð\`×\eÑ\eÓVfÓ+g×h¡  CšÓhˆDŒIà%)ˆ�
‰
Ô"Ø+0ˆÔ(ØCHˆÔ@Ø,1ˆÔ)Ø%)ˆÔ"Ø%)ˆÔ"Ø $ˆÔØ"'ˆÕùó kùÛhs   Â7E ÄE&c                óÀ  — | j                   j                  }|€yt        j                  j	                  |«      sBt        «       }t        j                  |d¬«       t        j                  j                  ||«      }n4t        j                  t        j                  j	                  |«      d¬«       || j                   _        t        | j                   j                  «       y)uw  Download pre-trained weights if they are not already downloaded.

        Bare filenames (no directory component, e.g. ``rf-detr-base.pth``) are resolved to the model cache directory â€”
        set the ``RF_HOME`` environment variable to override the location (default: ``~/.roboflow/models``). Resolution
        happens in ``ModelConfig.expand_path`` for explicitly-provided values, and here as a fallback for field defaults
        (which Pydantic does not validate by default).

        Paths that already contain a directory component are used as-is; the parent directory is created if it does not
        yet exist.
        NT©Úexist_ok)	rg   Úpretrain_weightsÚosÚpathÚdirnamer   ÚmakedirsÚjoinr   )r|   r£   Ú	cache_dirs      r=   r‹   z&RFDETR.maybe_download_pretrain_weights  sš   € ð  ×,Ñ,×=Ñ=ÐØÐ#ØÜ�w‰w�‰Ð/Ô0ä+Ó-ˆIÜ�K‰K˜	¨DÕ1Ü!Ÿw™wŸ|™|¨IÐ7GÓHÑä�K‰KœŸ™Ÿ™Ð(8Ó9ÀDÕIØ-=ˆ×ÑÔ*Ü! $×"3Ñ"3×"DÑ"DÕErk   c                ó&   —  | j                   di |¤ŽS )z8Retrieve the configuration parameters used by the model.r‰   )r„   ©r|   r~   s     r=   rŠ   zRFDETR.get_model_config  ó   € à'ˆt×'Ñ'Ñ1¨&Ñ1Ð1rk   c                óÂ  — ddl m} d}i }g }ddlm} |rE	 ddlmc m} t        D ]  }	t        ||	«      }
|
||	<   Œ t        D ��	cg c]  \  }}	|||	   f‘Œ }}}	d}t        j                  |dd¬«      }|d	   }t        |«      D ��ci c]-  }|j                  d
«      rt        ||«      }t        |d|«      |“Œ/ }}}t         D �	ci c]  }	|	||	   “Œ
 }}	t"        D ��	cg c]  \  }}	|j                  d«      r|||	   f‘Œ }}}	t"        D ��	cg c]  \  }}	d|v r|||	   f‘Œ }}}	t"        D ��	cg c]!  \  }}	|j                  d«      sd|vr|||	   f‘Œ# }}}	||z   |z   |z   }t%        |«      }|r|j'                  |«       |j)                  d«      }d}t+        |t,        «      r$|j/                  «       }|r|j)                  |«      }nd}t+        |t$        «      r8t-        |j)                  dd«      «      j/                  «       j1                  «       }n2t-        t        |dd«      «      j/                  «       j1                  «       }d}|dv rBt2        j4                  j7                  t3        j8                  |«      «      j1                  «       }d}|€‹|t        v }d|v xr
 d|vxr d|v}|s/|s|r+ddlm} t=        d|›d|›d�|j?                  d¬«      z   «      ‚|D ]  \  }} ||v sŒ| } n |r.|�,t@        jC                  d|t        |dtE        |«      «      |«       |€tG        d|›d|›d|›d�«      ‚t+        |t$        «      r|j)                  d«      }!nt        |dd«      }!i }"tI        «       }#t        |dd«      }$i }%t        |$d d«      }&t+        |&t$        «      r|&}%nt        |$d!d«      }'t+        |'t$        «      r|'}%|j)                  d"«      }(t+        |(t$        «      r;|(jK                  «       D ](  \  })}*|)dk(  rŒ|%r|)|%v sŒ|*|"|)<   |#jM                  |)«       Œ* |!�d|vr|!|"d<   |#jM                  d«       |j)                  d#«      xs i }+|+sgd$|v rcd%},i }+|d$   jK                  «       D ]I  \  }-}.|-j                  |,«      sŒ|-tO        |,«      d })|)j                  d&«      r|)tO        d&«      d })|.|+|)<   ŒK |+�rPd'|vr¹|%rd'|%v r³|+j)                  d(«      }/t+        |/t        jP                  «      rˆ|/jR                  d)k(  ry|/jU                  d*¬+«      jW                  «       D �0cg c]  }0tY        |0«      ‘Œ }1}0|"j)                  d'«      }2|1|2k7  rt@        j[                  d,|2|1«       |1|"d'<   |#jM                  d'«       d|vr�|+j)                  d-«      }3t+        |3t        jP                  «      rd|3jR                  d)k(  rU|3j\                  d   d*z
  }4|"j)                  d«      }5|4|5k7  rt@        j[                  d.|5|4«       |4|"d<   |#jM                  d«       |"j'                  |«       t-        |«      |"d<   |#tI        |«      z
  }6 |d2i |"¤Ž}7|6r^t        |7d"d«      }8t        |8d/d«      }9|9€t        |8d0d«      }9|9�|9j_                  |6«       d|6v rdt        |8d/tI        «       «      vsJ d1«       ‚|7S c c}	}w # t        $ r}|j                  dvr‚ Y d}~�Œ]d}~ww xY wc c}}w c c}	w c c}	}w c c}	}w c c}	}w c c}0w )3u^  Load an RF-DETR model from a training checkpoint, automatically inferring the model class.

        The correct subclass is resolved in order of preference:

        1. ``model_name`` key in the checkpoint (written by the PTL training
           stack since v1.7.0).
        2. ``pretrain_weights`` field in the checkpoint's ``args`` entry
           (legacy fallback for older checkpoints).
        3. The **filename** of *path* itself, used as a last resort when
           ``pretrain_weights`` is absent or an unset-like sentinel value
           (empty string, ``"none"``, or ``"null"``).  Starter weights
           published by Roboflow store ``pretrain_weights="none"`` in their
           ``args``; passing the canonical filename (e.g.
           ``rf-detr-small.pth``) lets ``from_checkpoint`` infer the class
           automatically.

        Both legacy ``argparse.Namespace`` checkpoints (produced by ``engine.py``) and dict-style checkpoints (produced
        by the PTL training stack) are supported.

        Args:
            path: Path to a checkpoint file (e.g. ``checkpoint_best_total.pth``).
            **kwargs: Additional keyword arguments forwarded to the model
                constructor (e.g. ``accept_platform_model_license=True`` for XLarge / 2XLarge models).

                ``num_classes`` is resolved in this priority order:

                1. Explicit caller kwarg â€” always wins.
                2. Weight inference from ``class_embed.weight`` shape in the checkpoint
                   (``shape[0] - 1``, since the head includes a background class). This
                   overrides a stale ``model_config`` value written before fine-tuning
                   changed the class count.
                3. ``saved_model_config["num_classes"]`` from the checkpoint's
                   ``model_config`` entry â€” may be stale for older checkpoints.
                4. Legacy ``args["num_classes"]`` dict entry.
                5. Constructor default.

                In cases 2â€“5 the field is not recorded as a user-set override, so
                :meth:`train` can still adapt the detection head to the training
                dataset's class count.  Pass an explicit ``num_classes=N`` to pin
                the head and prevent adaptation.

        Returns:
            An instance of the appropriate :class:`RFDETR` subclass loaded from the checkpoint.

        Warning:
            This method calls ``torch.load`` with ``weights_only=False``, which
            unpickles arbitrary Python objects. Only load checkpoints from trusted sources.

        Raises:
            FileNotFoundError: If *path* does not exist.
            OSError: If *path* exists but cannot be read.
            KeyError: If the checkpoint does not contain an ``"args"`` key.
            ValueError: If the model class cannot be inferred from ``model_name``,
                ``pretrain_weights``, or the checkpoint filename.

        Examples:
            >>> model = RFDETR.from_checkpoint("checkpoint_best_total.pth")  # doctest: +SKIP
            >>> model = RFDETRSmall.from_checkpoint("checkpoint_best_total.pth")  # doctest: +SKIP
        r   NF)Ú_IS_RFDETR_PLUS_AVAILABLET>   úrfdetr_plus.modelsÚrfdetr_plusÚcpu)Úmap_locationÚweights_onlyr}   r8   rY   zseg-ÚkeypointÚ
model_nameÚ r£   >   r¶   ÚnoneÚnullrL   rC   )Ú_INSTALL_MSGzCheckpoint model_name=z, pretrain_weights=z# requires the rfdetr_plus package. zplatform model downloads)ÚnamezQpretrain_weights unset in checkpoint %r; inferred model class %s from filename %rz/Could not infer model class from checkpoint at z (model_name=z/). Please instantiate the model class directly.Únum_classesr„   Úmodel_fieldsÚ
__fields__rg   rn   Ú
state_dictzmodel.z
_orig_mod.Únum_keypoints_per_classÚ_kp_active_maské   é   )ra   u   from_checkpoint: overriding num_keypoints_per_class %s â†’ %s (inferred from _kp_active_mask; saved model_config may be stale).zclass_embed.weightuv   from_checkpoint: overriding num_classes %s â†’ %s (inferred from class_embed.weight; saved model_config may be stale).Úmodel_fields_setÚ__pydantic_fields_set__uÊ   num_classes still in model_fields_set after checkpoint load; Pydantic may return a snapshot rather than the live backing set â€” switch to model_construct(_fields_set=...) for Pydantic v3 compatibility.r‰   )0Úrfdetr.variantsÚvariantsÚrfdetr.platformr®   Úrfdetr.platform.modelsÚplatformÚmodelsrB   re   rM   ÚModuleNotFoundErrorrº   rr   ÚloadÚdirÚ
startswithr?   rI   ÚdictÚupdateÚgetrV   rq   ÚstripÚlowerr¤   r¥   ÚbasenameÚfspathr¹   ÚImportErrorÚformatÚloggerÚinfoÚreprrU   ÚsetÚitemsÚaddÚlenÚTensorÚndimÚsumÚtolistrf   Údebugr\   Údifference_update):Úclsr¥   r~   Úrfdetr_variantsÚ_plus_availableÚ_plus_symbolsÚ_plus_entriesr®   Úplatform_modelsr<   Úplus_objrº   ÚexÚckptr}   ÚsymbolÚvariant_objÚ_variant_name_to_classÚ_variant_symbolsÚ_seg_mapÚ_keypoint_mapÚ	_base_mapÚ
_model_mapÚ	_name_mapÚsaved_model_nameÚ	model_clsÚnormalized_nameÚweights_nameÚ_filename_fallbackÚplus_by_model_nameÚplus_by_weights_namer¹   Úklassr»   Úconstructor_kwargsÚcheckpoint_config_keysr„   Ú
_mc_fieldsÚ_mc_model_fieldsÚ
_mc_legacyÚsaved_model_configÚkeyÚvalueÚ_ckpt_weightsÚ_pfxÚkÚvÚ_kp_maskÚnÚ_inferred_kpÚ_current_kpÚ
_ce_weightÚ_inferred_ncÚ_current_ncÚcheckpoint_derived_keysrn   Úloaded_configÚ
fields_sets:                                                             r=   Úfrom_checkpointzRFDETR.from_checkpoint  sþ  € õ| 	2àˆØ13ˆØ8:ˆÝ=á$ðß@Ð@ä$Mò ;�LÜ& ¸ÓE�HØ2:�M ,Ò/ð;ô Su÷!Ù<N¸DÀ,�T˜=¨Ñ6Ò7ð!�ñ !ð #'�ô  %Ÿz™z¨$¸UÐQVÔWˆØ�F‰|ˆô ˜oÓ.÷;
àØ× Ñ  Ô*Ü '¨¸Ó @�ô �K ¨VÓ4°kÐAÐ4ð;
Ðñ ;
ô Txö5
ØCOˆLÐ0°Ñ>Ñ>ð5
Ðð 5
ô 'D÷4
á"��lØ�‰˜vÔ&ð Ð# LÑ1Ò2ð4
ˆñ 4
ô 'D÷9
á"��lØ˜TÑ!ð Ð# LÑ1Ò2ð9
ˆñ 9
ô 'D÷5
á"��lØ—?‘? 6Ô*¨zÀÑ/Eð Ð# LÑ1Ò2ð5
ˆ	ñ 5
ð
 6>ÀÑ5MÐP]Ñ5]Ð`iÑ5iˆ
ô .2Ð2BÓ-Cˆ	áØ×Ñ˜]Ô+ØŸ8™8 LÓ1ÐØ)-ˆ	ÜÐ&¬Ô,Ø.×4Ñ4Ó6ˆOÙØ%ŸM™M¨/Ó:‘	à ˆOô �dœDÔ!Ü˜tŸx™xÐ(:¸BÓ?Ó@×FÑFÓH×NÑNÓP‰Läœw tÐ-?ÀÓDÓE×KÑKÓM×SÑSÓUˆLð #ÐØÐ/Ñ/ÜŸ7™7×+Ñ+¬B¯I©I°d«OÓ<×BÑBÓDˆLØ!%ÐàÐð "1Ô4]Ð!]Ðà˜LÐ(Òr¨V¸<Ð-GÒrÐL^ÐfrÐLrð !ñ #Ñ(:Ñ>RÝ8ä!Ø,Ð-=Ð,@Ð@SÐT`ÐScð d,ð -Ø/;×/BÑ/BÐHbÐ/BÓ/cñdóð ð
  *ò ‘��eØ˜<Ò'Ø %�IÙðñ
 " iÐ&;Ü—‘ØgØÜ˜I z´4¸	³?ÓCØ ô	ð ÐÜØAÀ$Àð JØ/Ð2Ð2EÀlÐEUð V?ð@óð ô �dœDÔ!Ø&*§h¡h¨}Ó&=‰Kä! $¨°tÓ<ˆKà-/ÐÜ+.«5Ðô & iÐ1FÈÓMÐØ%'ˆ
Ü"Ð#6¸ÈÓMÐÜÐ&¬Ô-Ø)‰Jä Ð!4°lÀDÓIˆJÜ˜*¤dÔ+Ø'�
à!ŸX™X nÓ5ÐÜÐ(¬$Ô/Ø0×6Ñ6Ó8ò 4‘
��UØÐ,Ò,ØÙ! S¨JÒ%6Ø.3Ð& sÑ+Ø*×.Ñ.¨sÕ3ð4ð Ð" }¸FÑ'BØ0;Ð˜}Ñ-Ø"×&Ñ& }Ô5ð )-¯©°Ó(9Ò(?¸RˆÙ °Ñ!5ØˆDØˆMØ˜\Ñ*×0Ñ0Ó2ò +‘��1Ø—<‘< Õ%ØœC ›I˜K˜.�Cà—~‘~ lÔ3Ø!¤# lÓ"3Ð"5Ð6˜Ø)*�M #Ò&ð+ò ð )°Ñ6Á
ÐNgÐkuÑNuØ(×,Ñ,Ð->Ó?�Ü˜h¬¯©Ô5¸(¿-¹-È1Ò:LØ4<·L±LÀQ°LÓ4G×4NÑ4NÓ4PÖ#Q¨q¤C¨¥FÐ#Q�LÐ#QØ"4×"8Ñ"8Ð9RÓ"S�KØ# {Ò2ÜŸ™ð`à'Ø(ô	ð EQÐ&Ð'@ÑAØ*×.Ñ.Ð/HÔIð  FÑ*Ø*×.Ñ.Ð/CÓD�
Ü˜j¬%¯,©,Ô7¸J¿O¹OÈqÒ<PØ#-×#3Ñ#3°AÑ#6¸Ñ#:�LØ"4×"8Ñ"8¸Ó"G�KØ# {Ò2ÜŸ™ðcà'Ø(ô	ð 9EÐ& }Ñ5Ø*×.Ñ.¨}Ô=à×!Ñ! &Ô)ô 25°T³ÐÐ-Ñ.ð #9¼3¸v»;Ñ"FÐáÑ/Ð.Ñ/ˆá"Ü# E¨>¸4Ó@ˆMô ! Ð0BÀDÓIˆJØÐ!Ü$ ]Ð4MÈtÓT�
ØÐ%Ø×,Ñ,Ð-DÔEð Ð 7Ñ7Ø$¬G°MÐCUÔWZÓW\Ó,]Ñ]ð ð`óÐ]ð ˆùóI!øô 'ò Ø—7‘7Ð"GÑGØõ Hûðüó;
ùò5
ùó
4
ùó
9
ùó
5
ùòF $RsM   –.Z ÁZÁZ Â2Z?Ã[Ã"[
Ä[Ä)&[Ô[ÚZ Ú	Z<Ú"Z7Ú7Z<c                ó¶  — | €y	 t        j                  | «      }|j
                  dk(  ry|j
                  dk(  rd|j                  �|j                  gfS dfS |j
                  d	k(  rd	|j                  �|j                  gfS dfS t        j                  d
|j
                  ›d�t        d¬«       y# t        t        t        f$ r}t        d| ›d�«      |‚d}~ww xY w)a±  Map a torch-style device specifier to PTL ``accelerator``/``devices`` kwargs.

        Args:
            device: A device specifier accepted by ``torch.device``.

        Returns:
            ``(accelerator, devices)`` where ``devices`` is ``None`` unless an explicit device index is provided (for
            example ``cuda:1``).

        Raises:
            ValueError: If ``device`` is not a valid torch device specifier.
        N©NNz&Invalid device specifier for train(): zE. Expected values like 'cpu', 'cuda', 'cuda:0', or torch.device(...).r±   )r±   NÚcudaÚgpuÚmpszDevice type zˆ is not explicitly mapped to a PyTorch Lightning accelerator; falling back to PTL auto-detection. Training may use an unexpected device.rÁ   ©Ú
stacklevel)
rr   rm   rT   rU   ÚRuntimeErrorrX   r[   ÚwarningsÚwarnÚUserWarning)rm   Úresolved_deviceÚexcs      r=   Ú_resolve_trainer_device_kwargsz%RFDETR._resolve_trainer_device_kwargsP  s  € ð ˆ>Øð	Ü#Ÿl™l¨6Ó2ˆOð ×Ñ 5Ò(ØØ×Ñ 6Ò)Ø°_×5JÑ5JÐ5V˜?×0Ñ0Ð1Ð`Ð`Ð\`Ð`Ð`Ø×Ñ 5Ò(Ø°_×5JÑ5JÐ5V˜?×0Ñ0Ð1Ð`Ð`Ð\`Ð`Ð`ä�‰Ø˜?×/Ñ/Ð2ð 3fð fäØõ		
ð øô' œ:¤|Ð4ò 	ÜØ8¸¸
ð CVð Vóð ðûð	ús   …B/ Â/CÃCÃCc                óZ  — 	 ddl m}m}m} ddlm} |j                  dd«      }|r5t        |j                  «       «      rt        j                  dt        d	¬
«       |j                  dd«      }t         j#                  |«      \  }	}
d|v r-t        j                  dt        d	¬
«       |j                  d«       t%        |j                  dd«      «      }|rt        j                  dt        d	¬
«       |j                  dd«      }|��½t'        |t$        «      rt)        d«      ‚	 t+        j,                  |«      }|dk  rt)        d«      ‚| j0                  j2                  | j0                  j4                  z  }||z  dk7  rCt)        d|› d| j0                  j2                  › d| j0                  j4                  › d|› d|› d�«      ‚| j0                  j6                  }| j0                  j8                  | j0                  j2                  z  }||k(  r+|| j0                  j2                  z  }|| j0                  _        n|}|| j0                  _        t;        | d«      rr| j<                  �ft;        | j<                  d«      r|| j<                  _        t?        | j<                  dd«      }|�&t;        |d«      r||_        t;        |d«      r||_         | j@                  d5i |¤Ž}|jB                  dk(  rŒtE        | j<                  «        || j<                  | j0                  |¬«      }|jF                  |_!        |jH                  |_%        tL        jO                  d|jB                  |jJ                  |jP                  «       tS        | «      jT                  | j0                  _+        t?        |dd«      }|r"| jY                  |«       | j[                  |«        || j0                  |«      } || j0                  |«      }|j\                  r¡t^        j`                  jc                  d d!«      d!k(  r~	 dd"l2m3} |ji                  d#«       tk        |jl                  «      d$z  } ||jo                  «       |d%¬&«      jq                  «         ||js                  «       |d'¬&«      jq                  «        d+|	i}|
�|
|d,<    ||| j0                  fi |¤Ž}|jy                  |||jz                  xs d¬-«       |j<                  | j<                  _        | j}                  «        t?        |d.d«      }|�|| j<                  _?        n t?        |d.d«      }|�|| j<                  _?        t�        «       �r|jƒ                  «       | j0                  jƒ                  «       | j0                  j„                  jT                  | j<                  j~                  | j<                  j~                  rt‡        | j<                  j~                  «      ndd/œ}	 t_        jˆ                  |jl                  d)¬0«       t‹        t^        jŒ                  j�                  |jl                  d1«      d2«      5 }t‘        j’                  ||d	t”        ¬3«       ddd«       yy# t        $ r9}|j                  r|j                  j                  d«      r‚ t        d«      |‚d}~ww xY w# t.        $ r}t)        d«      |‚d}~ww xY w# tt        $ r tL        jw                  d(d)¬*«       Y �ŒPw xY w# 1 sw Y   yxY w# t–        $ r+}tL        jw                  d4|jl                  |«       Y d}~yd}~ww xY w)6uÁ
  Train an RF-DETR model via the PyTorch Lightning stack.

        All keyword arguments are forwarded to :meth:`get_train_config` to build a :class:`~rfdetr.config.TrainConfig`.
        Several kwargs are absorbed and handled specially so that existing call-sites do not break:

        * ``resolution`` â€” updates the model's input resolution by mutating
          :attr:`model_config.resolution` in place before the train config is built. This change persists on
          :attr:`model_config` after :meth:`train` returns. The value must be a positive integer divisible by
          ``patch_size * num_windows`` for the model variant; a :class:`ValueError` is raised otherwise.
          :attr:`model_config.positional_encoding_size` is also updated when the config derives it formulaically (``PE
          == resolution // patch_size``); configs with a pretrained-specific PE value (e.g. ``RFDETRBase`` uses DINOv2's
          PE=37 at 560 px) are left unchanged to preserve checkpoint compatibility.
        * ``device`` â€” normalized via :class:`torch.device` and mapped to PyTorch
          Lightning trainer arguments. ``"cpu"`` becomes ``accelerator="cpu"``; ``"cuda"`` and ``"cuda:N"`` become
          ``accelerator="gpu"`` and optionally ``devices=[N]``; ``"mps"`` becomes ``accelerator="mps"``. Other valid
          torch device types fall back to PTL auto-detection and emit a :class:`UserWarning`.
        * ``callbacks`` â€” if the dict contains any non-empty lists a
          :class:`DeprecationWarning` is emitted; the dict is then discarded. Use PTL
          :class:`~pytorch_lightning.Callback` objects passed via :func:`~rfdetr.training.build_trainer` instead.
        * ``start_epoch`` â€” emits :class:`DeprecationWarning` and is dropped.
        * ``do_benchmark`` â€” emits :class:`DeprecationWarning` and is dropped.
        * ``notes`` â€” optional user-defined metadata (string, dict, list, or
          any JSON-serialisable value) stored under the ``"notes"`` key in every ``.pth`` checkpoint produced during
          training.  The value is also available inside ``args["notes"]`` for full provenance.  Pass the same value to
          :meth:`export` to embed it in the ONNX file as well.

        After training completes the underlying ``nn.Module`` is synced back onto ``self.model.model`` so that
        :meth:`predict` and :meth:`export` continue to work without reloading the checkpoint.

        Raises:
            ImportError: If training dependencies are not installed. Install with
                ``pip install "rfdetr[train,loggers]"``.
            ValueError: If ``resolution`` is not a positive integer or is not
                divisible by ``patch_size * num_windows`` for the model variant.
        r   )ÚRFDETRDataModuleÚRFDETRModelModuleÚbuild_trainer)Úresolve_auto_batch_configzrfdetr.zqRF-DETR training dependencies are missing. Install them with `pip install "rfdetr[train,loggers]"` and try again.NrŽ   z„Custom callbacks dict is not forwarded to PTL. Deprecated since v1.7.0, will be removed in v1.9.0. Use PTL Callback objects instead.rÁ   r  rm   Ústart_epochzo`start_epoch` is deprecated since v1.7.0 and will be removed in v1.9.0; PTL resumes automatically via `resume`.Údo_benchmarkFzn`do_benchmark` in `.train()` is deprecated since v1.7.0 and will be removed in v1.9.0; use `rfdetr benchmark`.Ú
resolutionz%resolution must be a positive integerzresolution=z! is not divisible by patch_size (z) * num_windows (z) = z,. Choose a resolution that is a multiple of rO   rn   r}   Úpositional_encoding_sizeÚauto)Úmodel_contextrg   Útrain_configz][auto-batch] resolved train config: batch_size=%s grad_accum_steps=%s effective_batch_size=%sÚdataset_dirÚ
LOCAL_RANKÚ0)ÚDatasetGridSaverÚfitÚdataset_gridsÚtrain)Údataset_typerž   zBFailed to save dataset grids; training will continue without them.T)Úexc_infoÚacceleratorÚdevices)Ú	ckpt_pathÚclass_names)r/  rg   Úmodel_config_typer<  r»   r¡   ztraining_config.jsonÚw)ÚindentÚdefaultz-Could not save training_config.json to %s: %sr‰   )LÚrfdetr.trainingr%  r&  r'  Úrfdetr.training.auto_batchr(  rË   rº   rÎ   rÖ   ÚpopÚanyÚvaluesr  r  ÚDeprecationWarningr8   r#  rW   rV   rU   rZ   r[   rT   rg   r^   r_   r,  r+  rp   rn   re   Úget_train_configÚ
batch_sizery   Úsafe_micro_batchÚrecommended_grad_accum_stepsÚgrad_accum_stepsrØ   rÙ   Úeffective_batch_sizerX   rY   rµ   Ú#_align_keypoint_schema_from_datasetÚ_align_num_classes_from_datasetÚsave_dataset_gridsr¤   ÚenvironrÑ   Úrfdetr.datasets.save_gridsr3  Úsetupr
   Ú
output_dirÚtrain_dataloaderÚ	save_gridÚval_dataloaderÚ	ExceptionÚwarningr4  ÚresumeÚremove_optimized_modelr<  r   Ú
model_dumpÚ	__class__rÞ   r§   Úopenr¥   r¨   ÚjsonÚdumprq   ÚOSError) r|   r~   r%  r&  r'  r(  r"  Úcallbacks_dictÚ_deviceÚ_acceleratorÚ_devicesÚrun_benchmarkÚ_resolutionÚerrorr]   Ú_current_peÚ_derived_peÚnew_peÚ
model_argsÚconfigÚ
auto_batchr0  ÚmoduleÚ
datamoduler3  Úgrids_output_dirÚtrainer_kwargsÚtrainerÚconfig_class_namesÚdataset_class_namesÚcomplete_configÚfs                                    r=   r6  zRFDETR.trainw  s€  € ðP	ßZÑZÝLð  Ÿ™ K°Ó6ˆÙœc .×"7Ñ"7Ó"9Ô:Ü�M‰Mð4ô #Øõð —*‘*˜X tÓ,ˆÜ!'×!FÑ!FÀwÓ!OÑˆ�hð ˜FÑ"Ü�M‰Mð:ä"Øõ	ð �J‰J�}Ô%ô ˜VŸZ™Z¨¸Ó>Ó?ˆÙÜ�M‰Mð*ä"Øõ	ð —j‘j ¨tÓ4ˆØÑ"Ü˜+¤tÔ,Ü Ð!HÓIÐIðUÜ&Ÿn™n¨[Ó9�ð ˜aÒÜ Ð!HÓIÐIØ×*Ñ*×5Ñ5¸×8IÑ8I×8UÑ8UÑUˆJØ˜ZÑ'¨1Ò,Ü Ø! + ð /#Ø#'×#4Ñ#4×#?Ñ#?Ð"@ð AØ×)Ñ)×5Ñ5Ð6°d¸:¸,ð GAØAKÀÈAðOóð ð ×+Ñ+×DÑDˆKØ×+Ñ+×6Ñ6¸$×:KÑ:K×:VÑ:VÑVˆKØ˜kÒ)à$¨×(9Ñ(9×(DÑ(DÑD�Ø=C�×!Ñ!Õ:ð %�Ø+6ˆD×ÑÔ(ô �t˜WÔ%¨$¯*©*Ð*@Ü˜4Ÿ:™: |Ô4Ø,7�D—J‘JÔ)Ü$ T§Z¡Z°¸Ó>�
ØÐ)Ü˜z¨<Ô8Ø0;˜
Ô-Ü˜zÐ+EÔFØ>D˜
Ô;Ø&�×&Ñ&Ñ0¨Ñ0ˆØ×Ñ Ò&ô *¨$¯*©*Ô5Ù2Ø"Ÿj™jØ!×.Ñ.Ø#ôˆJð
 !+× ;Ñ ;ˆFÔØ&0×&MÑ&MˆFÔ#Ü�K‰KØoØ×!Ñ!Ø×'Ñ'Ø×/Ñ/ô	ô (,¨D£z×':Ñ':ˆ×ÑÔ$ô
 ˜f m°TÓ:ˆÙØ×4Ñ4°VÔ<Ø×0Ñ0°Ô=á" 4×#4Ñ#4°fÓ=ˆÙ% d×&7Ñ&7¸Ó@ˆ
ð ×$Ò$¬¯©¯©¸ÀcÓ)JÈcÒ)QðÝGà× Ñ  Ô'Ü#'¨×(9Ñ(9Ó#:¸_Ñ#LÐ Ù  ×!<Ñ!<Ó!>Ð@PÐ_fÔg×qÑqÔsÙ  ×!:Ñ!:Ó!<Ð>NÐ]bÔc×mÑmÔoð (¨Ð6ˆØÐØ(0ˆN˜9Ñ%Ù ¨×(9Ñ(9ÑL¸^ÑLˆØ�‰�F˜J°&·-±-Ò2GÀ4ˆÔHð "Ÿ<™<ˆ�
‰
Ôð 	×#Ñ#Ô%ä$ V¨]¸DÓAÐØÐ)Ø%7ˆD�J‰JÕ"ä")¨*°mÀTÓ"JÐØ"Ð.Ø)<�—
‘
Ô&ô Õà &× 1Ñ 1Ó 3Ø $× 1Ñ 1× <Ñ <Ó >Ø%)×%6Ñ%6×%@Ñ%@×%IÑ%IØ#Ÿz™z×5Ñ5Ø>B¿j¹j×>TÒ>Tœs 4§:¡:×#9Ñ#9Ô:ÐZ[ñˆOðhÜ—‘˜F×-Ñ-¸Õ=Üœ"Ÿ'™'Ÿ,™, v×'8Ñ'8Ð:PÓQÐSVÓWð IÐ[\Ü—I‘I˜o¨q¸ÄCÕH÷Ið Ið øôM #ò 	ð �xŠx˜CŸH™H×/Ñ/°	Ô:ØÜðYóð ðûð	ûôn ò UÜ Ð!HÓIÈuÐTûðUûôf ò Ü—‘ØXØ!ð ÷ ðú÷LIð Iûäò hÜ—‘ÐNÐPV×PaÑPaÐcf×gÑgûðhúsy   ‚Y! Ä Z& ÐA=[ ×$A[6 Ø9[*Ù[6 Ù!	Z#Ù*4ZÚZ#Ú&	[ Ú/Z;Ú;[ Û ['Û&['Û*[3Û/[6 Û3[6 Û6	\*Û?!\%Ü%\*TrÂ   F)Úinplacec               ó¸  — t        |t        «      r	 t        t        |«      }t        |t        j                  «      st        dt        |«      ›�«      ‚|j                  st        d|› �«      ‚|r|rt        d«      ‚| j                  «        | j                  j                  €t        d«      ‚| j                  j                  }|j                  dk(  rt        j                  j                  |«      nt        j                   «       }	 |5  |r| j                  j                  nt#        | j                  j                  «      }|j%                  «        |j'                  «        |j)                  |¬«      }|r—t        j*                  j-                  |t        j.                  || j0                  j2                  | j                  j4                  | j                  j4                  | j                  j                  |¬«      «      }d	| _        || _        || j                  _        || _        |rd| j                  _        | j                  j4                  | _        d	| _         || _!        ddd«       y# t        $ r t        d|›�«      d‚w xY w# 1 sw Y   yxY w# tD        $ r@ t        jF                  tD        «      5  | j                  «        ddd«       ‚ # 1 sw Y   ‚ xY ww xY w)
u-  Optimize the model for inference with optional JIT compilation and dtype casting.

        Operations are wrapped in the correct CUDA device context to prevent context leaks on multi-GPU setups. When
        ``compile=True`` the model is traced with ``torch.jit.trace`` using a dummy input of ``batch_size`` images at
        the model's current resolution. By default, optimization deep-copies the loaded model before exporting it so the
        original module remains available. Set ``inplace=True`` for memory-constrained inference-only deployments; this
        exports the loaded module itself, may cast it to ``dtype``, and clears ``model.model`` after optimization
        succeeds. In-place optimization is destructive: :meth:`remove_optimized_model` becomes a no-op (issues
        :class:`UserWarning`), and :meth:`export` raises :class:`RuntimeError`. Create or reload a new ``RFDETR``
        instance to recover the original model.

        If ``inplace=True`` and the underlying ``export()`` call mutates the module before raising (e.g. setting
        internal flags and swapping ``forward``), the exception handler resets RFDETR wrapper flags to the unoptimized
        state but cannot undo changes made inside ``export()``. Create a new RFDETR instance for reliable inference
        after such a failure.

        Args:
            compile: If ``True``, trace the model with ``torch.jit.trace`` to obtain
                a JIT-compiled ``ScriptModule``. Set to ``False`` for broader compatibility (e.g. models with dynamic
                control flow).
            batch_size: Number of images the traced model will be optimized for. Ignored when ``compile=False``.
            dtype: Target floating-point dtype for the inference model. Accepts a
                ``torch.dtype`` directly (e.g. ``torch.float16``) or its string name (e.g. ``"float16"``). Defaults to
                ``torch.float32``. When ``dtype`` differs from the model's current dtype, ``to()`` transiently
                allocates both old and new parameter tensors simultaneously; peak memory during optimization is
                approximately 1.5Ã— the model weight size rather than 1Ã—.
            inplace: If ``True``, optimize ``model.model`` directly instead of deep-copying it. This is a destructive,
                inference-only path because ``export()`` mutates the module and dtype casting mutates its parameters.
                Requires ``compile=False``. With the default ``dtype=torch.float32``, the dtype cast is a no-op, so
                memory savings come only from clearing the base model reference rather than from dtype reduction.

        Raises:
            TypeError: If ``dtype`` is not a ``torch.dtype``, or if ``dtype`` is a
                string that does not correspond to a valid ``torch.dtype`` attribute.
            ValueError: If ``dtype`` is not a floating-point dtype, or if ``inplace=True`` is used with
                ``compile=True``.
            RuntimeError: If the base model has already been cleared by a previous inplace optimization.

        Examples:
            >>> from types import SimpleNamespace
            >>> import torch
            >>> class _TinyModel(torch.nn.Module):
            ...     def __init__(self):
            ...         super().__init__()
            ...         self.linear = torch.nn.Linear(1, 1)
            ...     def forward(self, x):
            ...         return {"pred_boxes": self.linear(x[:, :1, :1, :1].squeeze(-1).squeeze(-1))}
            ...     def export(self):
            ...         return None
            >>> class _TinyContext:
            ...     def __init__(self):
            ...         self.device = torch.device("cpu")
            ...         self.resolution = 28
            ...         self.model = _TinyModel()
            ...         self.inference_model = None
            >>> model = object.__new__(RFDETR)
            >>> model.model_config = SimpleNamespace(num_channels=3)
            >>> model.model = _TinyContext()
            >>> model._is_optimized_for_inference = False
            >>> model._has_warned_about_not_being_optimized_for_inference = False
            >>> model._optimized_has_been_compiled = False
            >>> model._optimized_batch_size = None
            >>> model._optimized_resolution = None
            >>> model._optimized_dtype = None
            >>> model._optimized_inplace = False
            >>> # Standard (non-inplace) optimization â€” reversible:
            >>> model.optimize_for_inference(compile=False)
            >>> model._is_optimized_for_inference
            True
            >>> model._optimized_inplace
            False
            >>> model.remove_optimized_model()
            >>> model._is_optimized_for_inference
            False
            >>> # Inplace optimization â€” destructive, cannot be reversed:
            >>> model.optimize_for_inference(compile=False, dtype="float16", inplace=True)
            >>> model._is_optimized_for_inference
            True
            >>> model._optimized_dtype
            torch.float16
            >>> model._optimized_inplace
            True
        z=dtype must be a torch.dtype or a string name of a dtype, got NzFdtype must be a floating-point torch.dtype or string name of one, got a  optimize_for_inference(inplace=True) requires compile=False. torch.jit.trace retains references to the original parameter storage in the returned ScriptModule, so setting model.model=None would not free the weight tensors and inplace=True would not reduce memory usage.z|Cannot optimize: the base model has been cleared by a previous inplace optimization. Create or reload a new RFDETR instance.r  ©Údtype)rm   rz  T)$rV   rq   re   rr   ÚAttributeErrorrT   rz  rX   Úis_floating_pointrU   rZ  rn   r  rm   r  Ú
contextlibÚnullcontextr   ÚevalÚexportrt   ÚjitÚtraceÚrandnrg   r�   r+  r˜   r™   r•   rœ   rš   r–   r›   rW  Úsuppress)r|   ÚcompilerH  rz  rw  rm   Úcuda_ctxr•   s           r=   Úoptimize_for_inferencezRFDETR.optimize_for_inferenceW  sƒ  € ôx �eœSÔ!ðuÜ¤ uÓ-�ô ˜%¤§¡Ô-ÜÐ[Ô\`ÐafÓ\gÐ[jÐkÓlÐlØ×&Ò&ÜÐeÐfkÐelÐmÓnÐnÙ‘wÜð>óð ð 	×#Ñ#Ô%à�:‰:×ÑÐ#Üð:óð ð
 —‘×"Ñ"ˆØ06·±¸vÒ0E”5—:‘:×$Ñ$ VÔ,Ì:×KaÑKaÓKcˆð'	Øñ !.Ù6= $§*¡*×"2Ò"2Ä8ÈDÏJÉJ×L\ÑL\ÓC]�Ø×$Ñ$Ô&Ø×&Ñ&Ô(à"1×"4Ñ"4¸5Ð"4Ó"A�áÜ&+§i¡i§o¡oØ'ÜŸ™Ø&Ø ×-Ñ-×:Ñ:Ø ŸJ™J×1Ñ1Ø ŸJ™J×1Ñ1Ø#'§:¡:×#4Ñ#4Ø"'ôó
'�Oð 9=�DÔ5Ø1;�DÔ.ð .=�—
‘
Ô*ð
 +2�Ô'ÙØ'+�D—J‘JÔ$Ø-1¯Z©Z×-BÑ-B�Ô*Ø37�Ô0Ø(-�Ô%÷C!.ð !.øô7 "ò uÜÐ"_Ð`eÐ_hÐ iÓjÐptÐtðuú÷6!.ð !.ûôD ò 	ä×$Ñ$¤YÓ/ñ .Ø×+Ñ+Ô-÷.à÷.àúð		úsN   ’I( ÄJ ÄEJÉJ É(JÊJÊ	J ÊJ Ê"KÊ2KË	KËK	ËKc                óÎ   — t        | dd«      rt        j                  dt        d¬«       yd| j                  _        d| _        d| _        d| _        d| _	        d| _
        d| _        y)u  Remove the optimized inference model and reset all optimization flags.

        Clears ``model.inference_model`` and resets all internal state set by :meth:`optimize_for_inference`. Safe to
        call even if the model has not been optimized. When the model was optimized with ``inplace=True``, this method
        issues a :class:`UserWarning` and returns without modifying state â€” the original module cannot be restored
        because ``export()`` and dtype casting mutate it; create or reload a new ``RFDETR`` instance instead.

        Examples:
            >>> from types import SimpleNamespace
            >>> import torch
            >>> class _TinyModel(torch.nn.Module):
            ...     def __init__(self):
            ...         super().__init__()
            ...         self.linear = torch.nn.Linear(1, 1)
            ...     def forward(self, x):
            ...         return {"pred_boxes": self.linear(x[:, :1, :1, :1].squeeze(-1).squeeze(-1))}
            ...     def export(self):
            ...         return None
            >>> class _TinyContext:
            ...     def __init__(self):
            ...         self.device = torch.device("cpu")
            ...         self.resolution = 28
            ...         self.model = _TinyModel()
            ...         self.inference_model = None
            >>> model = object.__new__(RFDETR)
            >>> model.model_config = SimpleNamespace(num_channels=3)
            >>> model.model = _TinyContext()
            >>> model._is_optimized_for_inference = False
            >>> model._has_warned_about_not_being_optimized_for_inference = False
            >>> model._optimized_has_been_compiled = False
            >>> model._optimized_batch_size = None
            >>> model._optimized_resolution = None
            >>> model._optimized_dtype = None
            >>> model._optimized_inplace = False
            >>> model.optimize_for_inference(compile=False)
            >>> model.remove_optimized_model()
            >>> model._is_optimized_for_inference
            False
        rœ   FuÉ   remove_optimized_model() has no effect after inplace optimization â€” the original model cannot be restored because export() and dtype casting mutate it. Create or reload a new RFDETR instance instead.rÁ   r  N)re   r  r  r   rn   r•   r–   r˜   r™   rš   r›   rœ   ©r|   s    r=   rZ  zRFDETR.remove_optimized_modelù  sm   € ôP �4Ð-¨uÔ5Ü�M‰MðBô Øõð Ø%)ˆ�
‰
Ô"Ø+0ˆÔ(Ø,1ˆÔ)Ø%)ˆÔ"Ø%)ˆÔ"Ø $ˆÔØ"'ˆÕrk   c                ó   — t        | dd«      S )a  Whether the model was optimized with ``inplace=True``.

        Returns ``True`` after a successful :meth:`optimize_for_inference` call with ``inplace=True``,
        meaning the base model has been cleared and :meth:`remove_optimized_model` is a no-op.

        Examples:
            >>> from types import SimpleNamespace
            >>> import torch
            >>> class _TinyModel(torch.nn.Module):
            ...     def __init__(self):
            ...         super().__init__()
            ...         self.linear = torch.nn.Linear(1, 1)
            ...     def forward(self, x):
            ...         return {"pred_boxes": self.linear(x[:, :1, :1, :1].squeeze(-1).squeeze(-1))}
            ...     def export(self):
            ...         return None
            >>> class _TinyContext:
            ...     def __init__(self):
            ...         self.device = torch.device("cpu")
            ...         self.resolution = 28
            ...         self.model = _TinyModel()
            ...         self.inference_model = None
            >>> model = object.__new__(RFDETR)
            >>> model.model_config = SimpleNamespace(num_channels=3)
            >>> model.model = _TinyContext()
            >>> model._is_optimized_for_inference = False
            >>> model._has_warned_about_not_being_optimized_for_inference = False
            >>> model._optimized_has_been_compiled = False
            >>> model._optimized_batch_size = None
            >>> model._optimized_resolution = None
            >>> model._optimized_dtype = None
            >>> model._optimized_inplace = False
            >>> model.is_optimized_inplace
            False
            >>> model.optimize_for_inference(compile=False, inplace=True)
            >>> model.is_optimized_inplace
            True
        rœ   F)re   r‰  s    r=   Úis_optimized_inplacezRFDETR.is_optimized_inplace2  s   € ôP �tÐ1°5Ó9Ð9rk   )Únotesc               óô  — t         j                  d«       d}|
|vrt        d|
›d|› �«      ‚	 ddlm}m} | j                  j                  }t        | dd	«      s| j                  j                  €t        d«      ‚| j                  j                  j                  d«      | j                  _        t        | j                  j                  «      }|j                  |«       	 t        j                  |d¬«       t!        |«      }t#        |	| j$                  d«      }	t        | j$                  dd«      }t'        |t(        «      st'        |t*        «      r|dk  rt        d|›�«      ‚|	|z  }|€f| j                  j,                  | j                  j,                  f}|d   |z  dk7  r=t        d| j                  j,                  › d|› d|	› d|› d|› d�«      ‚t/        |||	|«      } |||||| j$                  j0                  ¬«      j                  |«      }dg}|rdg}n:| j$                  j2                  rg d¢}n| j$                  j4                  rg d¢}nddg}|r||z   D �ci c]  }|dd i“Œ	 }}nd
}|j7                  «        t9        j:                  «       5  |r, ||«      }t         j=                  d!|j>                  › �«       �n_| j$                  j2                  rž ||«      }|d"   }|d#   }|d$   } t'        | t8        j@                  «      r=t         j=                  d%|j>                  › d&|j>                  › d'| j>                  › �«       nÛt         j=                  d%|j>                  › d&|j>                  › �«       n«| j$                  j4                  rT ||«      }|d"   }|d#   }|d(   }!t         j=                  d%|j>                  › d&|j>                  › d)|!j>                  › �«       nA ||«      }|d"   }|d#   }t         j=                  d%|j>                  › d&|j>                  › �«       d
d
d
«       |jC                  «        |jC                  «       } |tE        |«      ||||||||t        | d*d
«      |¬+«      }"t         j                  d,|"› �«       |
d-k(  r�tG        jH                  d.tJ        d/¬0«       	 dd1l&m'}#  |#|"tE        |«      |||rd3nd4||¬5«      }$t         j                  d6|$› �«       |$| j                  j                  j                  |«      | j                  _        S t         j                  d7«       t!        |"«      | j                  j                  j                  |«      | j                  _        S # t        $ r t         j                  d«       ‚ w xY wc c}w # 1 sw Y   �ŒwxY w# t        $ r t         j                  d2«       ‚ w xY w# | j                  j                  j                  |«      | j                  _        w xY w)8u  Export the trained model to ONNX or TFLite format.

        See the `export documentation <https://rfdetr.roboflow.com/learn/export/>`_ for more information.

        Args:
            output_dir: Directory to write the exported model to.
            infer_dir: Optional directory of sample images for dynamic-axes inference.
            backbone_only: Export only the backbone (feature extractor).
            opset_version: ONNX opset version to target.
            verbose: Print export progress information.
            shape: ``(height, width)`` tuple; defaults to square at model resolution.
                Both dimensions must be divisible by ``patch_size * num_windows``.
            batch_size: Static batch size to bake into the ONNX graph.
            dynamic_batch: If True, export with a dynamic batch dimension
                so the ONNX model accepts variable batch sizes at runtime.
            patch_size: Backbone patch size. Defaults to the value stored in
                ``model_config.patch_size`` (typically 14 or 16). When provided explicitly it must match the
                instantiated model's patch size. Shape divisibility is validated against ``patch_size * num_windows``.
            format: Export format â€” ``"onnx"`` (default) or ``"tflite"``.
                When ``"tflite"`` is selected the model is first exported to ONNX then converted to TFLite via
                ``onnx2tf``.  Requires ``pip install rfdetr[onnx,tflite]``.

                .. warning::
                    TFLite export is experimental and subject to change; upstream dependency instabilities (``onnx2tf``,
                    ``ai_edge_litert``) may affect results.
            quantization: TFLite quantization mode (ignored when
                ``format="onnx"``).  One of ``None``, ``"fp32"``, ``"fp16"``, ``"int8"``.  ``None`` / ``"fp32"`` /
                ``"fp16"`` produce FP32 + FP16 ``.tflite`` files; ``"int8"`` additionally produces an INT8-quantized
                model.
            calibration_data: Representative images for INT8 calibration and ``onnx2tf`` output validation.  Accepts:

                * ``None`` â€” auto-generate random data (sufficient for fp32/fp16; warns for int8).
                * A **directory path** (``str``) containing JPEG/PNG
                  images â€” the converter automatically loads, resizes, and prepares them.  This is the simplest
                  approach.
                * A path (``str``) to a ``.npy`` file of shape ``(N, H, W, 3)``, dtype float32, values in ``[0, 1]``.
                * A :class:`numpy.ndarray` with the same format.

                For INT8 quantization, provide 20â€“100 representative images from your training/validation set for best
                accuracy.
            max_images: Maximum number of images to load from a calibration directory.  Defaults to ``100``.  Only used
                when *calibration_data* is a directory path.
            notes: Optional user-defined metadata (string, dict, list, or
                any JSON-serialisable value) to embed in the exported ONNX model under the ``"rfdetr_notes"`` metadata
                property.  When ``None`` no metadata entry is written.  String values are stored verbatim; all other
                types are JSON-encoded so consumers must call ``json.loads()`` to recover a dict or list.  The same
                value can be passed to :meth:`train` so the checkpoint and the ONNX file share the same provenance
                information.

        Returns:
            Path to the exported model file (``.onnx`` or ``.tflite``).
        zExporting model to ONNX format)ÚonnxÚtflitezUnsupported export format z. Choose from: r   )Úexport_onnxÚmake_infer_imagezlIt seems some dependencies for ONNX export are missing. Please run `pip install rfdetr[onnx]` and try again.rœ   FNzRFDETR.export() is not available after inplace optimization. The original model has been cleared. Create a new RFDETR instance.r±   Tr¡   r€  r_   rÂ   z,num_windows must be a positive integer, got úModel's default resolution (ú!) is not divisible by block_size=rR   rS   ú*). Provide an explicit shape divisible by rO   )r�   ÚinputÚfeatures)ÚdetsÚlabelsÚmasks)r—  r˜  Ú	keypointsr—  r˜  Úbatchz PyTorch inference output shape: Ú
pred_boxesÚpred_logitsÚ
pred_masksz)PyTorch inference output shapes - Boxes: z
, Labels: z	, Masks: Úpred_keypointsz, Keypoints: Úsize)rS  rn   Úinput_namesÚinput_tensorsÚoutput_namesÚdynamic_axesÚbackbone_onlyÚverboseÚopset_versionÚvariant_namerŒ  z%Successfully exported ONNX model to: r�  zƒTFLite export is experimental and work-in-progress. Upstream dependency instabilities (onnx2tf, ai_edge_litert) may affect results.rÁ   r  )Úexport_tflitezuIt seems some dependencies for TFLite export are missing. Please run `pip install rfdetr[onnx,tflite]` and try again.rÙ   rg  )Ú	onnx_pathrS  ÚquantizationÚcalibration_dataÚ	verbosityÚ
max_imagesr¦  z'Successfully exported TFLite model to: zExport completed successfully)(rØ   rÙ   rU   Úrfdetr.export.mainr�  r‘  rÖ   rg  rn   rm   re   r  rt   r   r¤   r§   r
   rj   rg   rV   rW   rf   r+  rb   r�   Úsegmentation_headÚuse_grouppose_keypointsr  rr   Úno_gradrã   r\   rß   r±   rq   r  r  r   Úrfdetr.export._tflite.converterr©  )%r|   rS  Ú	infer_dirr¥  r§  r¦  r\   rH  Údynamic_batchr^   r×   r«  r¬  r®  rŒ  Ú_valid_formatsr�  r‘  rm   rn   Úoutput_dir_pathr_   r]   r¢  r¡  r£  rº   r¤  r–  Úoutputsr—  r˜  r™  rš  Úoutput_filer©  Útflite_paths%                                        r=   r€  zRFDETR.export\  sÑ  € ôL 	�‰Ð4Ô5Ø+ˆØ˜Ñ'ÜÐ9¸&¸À?ÐSaÐRbÐcÓdÐdð	ßHð —‘×"Ñ"ˆä�4Ð-¨uÔ5¸¿¹×9IÑ9IÐ9QÜðUóð ð  Ÿ:™:×+Ñ+×.Ñ.¨uÓ5ˆ�
‰
ÔÜ˜Ÿ™×)Ñ)Ó*ˆØ�‰�Ôðv	;Ü�K‰K˜
¨TÕ2Ü" :Ó.ˆOÜ,¨Z¸×9JÑ9JÈHÓUˆJÜ! $×"3Ñ"3°]ÀAÓFˆKÜ˜+¤tÔ,´J¸{ÌCÔ4PÐT_ÐcdÒTdÜ Ð#OÐP[ÈÐ!_Ó`Ð`Ø# kÑ1ˆJØˆ}ØŸ™×.Ñ.°·
±
×0EÑ0EÐF�Ø˜‘8˜jÑ(¨AÒ-Ü$Ø6°t·z±z×7LÑ7LÐ6Mð N&Ø&0 \°¸z¸lÈ/ÐZeÐYfð gBØBLÀÈQðPóð ô -¨U°JÀ
ÈKÓX�á,Ø˜5 *¨fÀ4×CTÑCT×CaÑCaôç‰b�‹jð ð #˜)ˆKÙØ *˜|‘Ø×"Ñ"×4Ò4Ú:‘Ø×"Ñ"×:Ò:Ú>‘à &¨Ð1�áØ?JÈ\Ñ?YÖZ°t  q¨' lÑ 2ÐZ�ÑZà#�Ø�J‰JŒLÜ—‘“ñ sÙ Ù$ ]Ó3�HÜ—L‘LÐ#CÀHÇNÁNÐCSÐ!TÖUØ×&Ñ&×8Ò8Ù# MÓ2�GØ" <Ñ0�DØ$ ]Ñ3�FØ# LÑ1�EÜ! %¬¯©Ô6ÜŸ™ØGÈÏ
É
À|ÐS]Ð^d×^jÑ^jÐ]kð l&Ø&+§k¡k ]ð4õô
 Ÿ™Ð'PÐQU×Q[ÑQ[ÐP\Ð\fÐgm×gsÑgsÐftÐ%uÕvØ×&Ñ&×>Ò>Ù# MÓ2�GØ" <Ñ0�DØ$ ]Ñ3�FØ 'Ð(8Ñ 9�IÜ—L‘LØCÀDÇJÁJÀ<ÈzÐZ`×ZfÑZfÐYgð h&Ø&/§o¡oÐ%6ð8õñ
 $ MÓ2�GØ" <Ñ0�DØ$ ]Ñ3�FÜ—L‘LÐ#LÈTÏZÉZÈLÐXbÐci×coÑcoÐbpÐ!qÔr÷;sð> �I‰IŒKØ)×-Ñ-Ó/ˆMá%Ü˜Ó/ØØ'Ø+Ø)Ø)Ø+ØØ+Ü$ T¨6°4Ó8ØôˆKô �K‰KÐ?À¸}ÐMÔNà˜Ò!Ü—‘ðfäØ õ	ðÝMñ ,Ø)Ü" ?Ó3Ø!-Ø%5Ù(/™f°WØ)Ø#ô�ô —‘ÐEÀkÀ]ÐSÔTØ"ð
  $Ÿz™z×/Ñ/×2Ñ2°6Ó:ˆD�J‰JÕô �K‰KÐ7Ô8Ü˜Ó$à#Ÿz™z×/Ñ/×2Ñ2°6Ó:ˆD�J‰JÕøôW ò 	Ü�L‰LðHôð ð	üòl  [÷sñ sûôv #ò Ü—L‘LðWôð ðûð,  $Ÿz™z×/Ñ/×2Ñ2°6Ó:ˆD�J‰JÕúsb   ®U) ÃE:W ÉVÉ%)W ÊFVÐBW Ò%V Ò+5W ÔW Õ) V	ÖW ÖVÖW Ö V>Ö>W ×6W7c                ó6  ‡— t        | «      �rt        j                  j                  | dd«      }t	        |d¬«      5 }t        j                  |«      }ddd«       t        d   d„ ¬«      }h d	£Št        ˆfd
„|D «       «      }|s|D �cg c]  }|d   ‘Œ	 c}S |D �ch c](  }|j                  dd«      ‰vsŒ|j                  d«      ’Œ* }}|D �ch c]  }|d   |v sŒ|d   ’Œ }}|D �cg c]  }|d   |vsŒ|d   ‘Œ }	}|	xs |D �cg c]  }|d   ‘Œ	 c}S t        | «      �r.t        j                  t        j                  j                  | d«      «      t        j                  t        j                  j                  | d«      «      z   }
|
D �cg c]3  }t        j                  j                  |«      j                  d«      sŒ2|‘Œ5 }}|d   }t	        |«      5 }t        j                  |«      }ddd«       dv rHt!        |d   t"        «      r0t        |d   j%                  «       «      D �cg c]
  }|d   |   ‘Œ c}S |d   S t'        d|› d�«      ‚t)        d| › d�«      ‚# 1 sw Y   �ŒxY wc c}w c c}w c c}w c c}w c c}w c c}w # 1 sw Y   ŒžxY wc c}w )z7Load class names from a COCO or YOLO dataset directory.r6  ú_annotations.coco.jsonúutf-8©ÚencodingNÚ
categoriesc                ó8   — | j                  dt        d«      «      S )NÚidÚinf)rÑ   Úfloat)Úcategorys    r=   ú<lambda>z&RFDETR._load_classes.<locals>.<lambda><  s   € ÈÏÉÐVZÔ\aÐbgÓ\hÓIi€ rk   )r  >   Nr¶   r·   r¸   c              3  óF   •K  — | ]  }|j                  d d«      ‰v–— Œ y­w)Úsupercategoryr·   N)rÑ   )r;   ÚcÚplaceholderss     €r=   r>   z'RFDETR._load_classes.<locals>.<genexpr>B  s"   øè ø€ ÒdÐTU˜QŸU™U ?°FÓ;À<ÔOÑdùs   ƒ!rº   rÈ  r·   z*.yamlz*.ymlÚdatar   ÚnameszFound z' but it does not contain 'names' field.zCould not find class names in zX. Checked for COCO (train/_annotations.coco.json) and YOLO (data.yaml, data.yml) styles.)r   r¤   r¥   r¨   r]  r^  rÌ   ÚsortedrD  rÑ   r   ÚglobrÔ   rÎ   ÚyamlÚ	safe_loadrV   rÏ   ÚkeysrU   ÚFileNotFoundError)r0  Ú	coco_pathrv  ÚannsrÀ  Ú
has_any_scrÉ  ÚparentsÚhas_childrenr<  Ú
yaml_pathsÚypÚyaml_data_filesÚ	yaml_pathrË  ÚirÊ  s                   @r=   Ú_load_classeszRFDETR._load_classes5  sw  ø€ ô ! Õ-ÜŸ™Ÿ™ [°'Ð;SÓTˆIÜ�i¨'Ô2ð $°aÜ—y‘y “|�÷$ä  \Ñ 2Ñ8iÔjˆJò 6ˆLô ÓdÐYcÔdÓdˆJÙØ+5Ö6 a˜˜&›	Ò6Ð6ð
 8BÖx°!ÀQÇUÁUÈ?Ð\bÓEcÐkwÒEw�q—u‘u˜_Õ-ÐxˆGÐxØ/9ÖR¨!¸Q¸v¹YÈ'Ò=Q˜A˜f›IÐRˆLÐRà.8ÖZ¨¸A¸f¹IÈ\Ò<Y˜1˜V›9ÐZˆKÐZàÒA°jÖ"A° 1 V£9Ò"AÐAô ! Õ-ÜŸ™¤2§7¡7§<¡<°¸XÓ#FÓGÌ$Ï)É)ÔTV×T[ÑT[×T`ÑT`ÐalÐnuÓTvÓJwÑwˆJà,6Öb b¼"¿'¹'×:JÑ:JÈ2Ó:N×:YÑ:YÐZ`Õ:ašrÐbˆOÐbØ'¨Ñ*ˆIÜ�i“ð ) AÜ—~‘~ aÓ(�÷)à˜$‰Ü˜d 7™m¬TÔ2Ü6<¸TÀ'¹]×=OÑ=OÓ=QÓ6RÖS°˜D ™M¨!Ó,ÒSÐSØ˜G‘}Ð$Ü˜v i [Ð0WÐXÓYÐYÜØ,¨[¨Mð :fð fó
ð 	
÷G$ñ $üò 7ùò
 yùÚRùâZùâ"Aùò c÷)ð )üò TsY   ¼IÂ	I,ÂI1Â6I1ÃI6ÃI6Ã)I;Ã6I;ÄJ Æ3JÇJÇJ
È*JÉI)Ê
J©r±  c               ó”  — t        | «      r�t        j                  j                  | dd«      }|rt	        t        |«      j                  «      S t        |d¬«      5 }t        j                  |«      }ddd«       d   }|D �ci c]  }|d   |“Œ
 }}t	        |«      S t	        t        j                  | «      «      S # 1 sw Y   ŒJxY wc c}w )ae  Detect the class count using the same category basis as training labels.

        For COCO-style datasets this counts all categories by ``id`` from ``train/_annotations.coco.json`` (matching the
        remapping based on ``coco.cats`` used by the training datamodule). In keypoint mode it instead counts the
        inferred RF-DETR keypoint label slots. In legacy background-first schemas (e.g. ``[0, 17]``) slot ``0`` is
        reserved for classes without keypoints; active-first schemas (e.g. ``[17]``) use normal 0-based indices. For
        YOLO-style datasets it falls back to ``_load_classes``.
        r6  r¼  r½  r¾  NrÀ  rÂ  )r   r¤   r¥   r¨   rÞ   r   r<  r]  r^  rÌ   r8   rÝ  )r0  r±  rÓ  rv  rÔ  rÀ  rÅ  Ú	cat_by_ids           r=   Ú _detect_num_classes_for_trainingz'RFDETR._detect_num_classes_for_trainingb  s¶   € ô ! Ô-ÜŸ™Ÿ™ [°'Ð;SÓTˆIÙ&ÜÔ5°iÓ@×LÑLÓMÐMÜ�i¨'Ô2ð $°aÜ—y‘y “|�÷$à˜lÑ+ˆJØBLÖM°h˜ $™¨Ñ1ÐMˆIÐMÜ�y“>Ð!ä”6×'Ñ'¨Ó4Ó5Ð5÷$ð $üò Ns   ÁB9ÂCÂ9Cc                óú  — 	 t         j                  || j                  j                  ¬«      }g }| j                  j                  r;t        t        | j                  dg «      xs g «      }|rt        |t        |«      «      }| j                  j                  }||k(  rydt        | j                  dt        «       «      v }|s�t        j                  d||||«       || j                  _        t        | j                   dd«      }|�||_        |r@t        |«      |k  r1|d	g|t        |«      z
  z  z   }|| j                  _        |�||_        yyyyt        j%                  d
|||||«       |rWt        |«      |k  rH|d	g|t        |«      z
  z  z   }|| j                  _        t        | j                   dd«      }|�||_        yyyy# t        t
        t        t        f$ r!}t        j                  d||«       Y d}~yd}~ww xY w)u[  Auto-detect the dataset class count and align ``model_config.num_classes`` in-place.

        Must be called before ``RFDETRModelModule`` is constructed so that weight loading inside the module uses the
        correct (dataset-derived) class count.

        When the user did **not** explicitly set ``num_classes`` (it is left unset, e.g. inferred from a
        checkpoint), ``model_config.num_classes`` and ``self.model.args.num_classes`` are updated to match the dataset.
        When the user *did* set ``num_classes`` explicitly â€” to any value, including the class default â€” and it differs
        from the dataset, the configured value is preserved and a warning is emitted.

        Failures from ``_detect_num_classes_for_training`` are caught and logged at DEBUG level so that training is
        never blocked by detection errors.

        When ``model_config.use_grouppose_keypoints`` is True and
        ``model_config.num_keypoints_per_class`` is shorter than the adjusted
        ``num_classes``, the schema is zero-padded in-place so that
        ``len(num_keypoints_per_class) == num_classes``.  Both ``model_config``
        and ``model.args`` (if present) are updated.  Appended classes receive
        zero keypoints and contribute no class-logit boost.

        Args:
            dataset_dir: Path to the training dataset root directory.
        rÞ  z7Could not auto-detect num_classes from dataset '%s': %sNr¿   r»   rÃ   zTDetected %d classes in dataset '%s'; auto-adjusting model num_classes from %d to %d.r}   r   z¹Dataset '%s' has %d classes but model was initialized with num_classes=%d. Using the model's configured value (%d). If this is unintentional, reinitialize the model with num_classes=%d.)r8   rá  rg   r±  rÒ  rU   ÚKeyErrorr`  rØ   rã   r�   re   ÚmaxrÞ   r»   rÛ   rn   r¿   rX  )	r|   r0  Údataset_num_classesr"  Úkeypoint_schemaÚmodel_num_classesÚuser_overroderk  Úpadded_schemas	            r=   rN  z&RFDETR._align_num_classes_from_datasetx  s"  € ð0	Ü"(×"IÑ"IØØ(,×(9Ñ(9×(QÑ(Qð #Jó #Ðð &(ˆØ×Ñ×4Ò4ä"¤7¨4×+<Ñ+<Ð>WÐY[Ó#\Ò#bÐ`bÓcˆOÙÜ&)Ð*=¼sÀ?Ó?SÓ&TÐ#à ×-Ñ-×9Ñ9ÐàÐ"3Ò3Øð &¬°×1BÑ1BÐDVÔX[ÓX]Ó)^Ð^ˆáÜ�L‰LØfØ#ØØ!Ø#ôð -@ˆD×ÑÔ)ä  §¡¨V°TÓ:ˆJØÐ%Ø)<�
Ô&ñ
 ¤3 Ó#7Ð:MÒ#MØ /°1°#Ð9LÌsÐSbÓOcÑ9cÑ2dÑ d�Ø<I�×!Ñ!Ô9ØÐ)Ø9F�JÕ6ð *ð $Nˆô �N‰Nð>ð Ø#Ø!Ø!Ø#ô	ñ ¤3 Ó#7Ð:KÒ#KØ /°1°#Ð9JÌSÐQ`ÓMaÑ9aÑ2bÑ b�Ø<I�×!Ñ!Ô9Ü$ T§Z¡Z°¸Ó>�
ØÐ)Ø9F�JÕ6ð *ð	 $Lˆøô{ "¤:¬x¼ÐAò 	ä�L‰LÐRÐT_ÐadÔeÜûð	ús   ‚+G  Ç G:ÇG5Ç5G:c                ód   — t        | «      syt        | «      dz  dz  }|j                  «       r|S dS )a°  Return the Roboflow COCO train annotation path when it exists.

        Args:
            dataset_dir: Path to the Roboflow dataset root.

        Returns:
            Train split annotation path, or ``None`` when the dataset is not Roboflow COCO style.

        Raises:
            This helper does not raise.

        Example:
            >>> RFDETR._roboflow_keypoint_annotation_path("/missing") is None
            True
        Nr6  r¼  )r   r
   Úexists©r0  Úannotation_paths     r=   Ú"_roboflow_keypoint_annotation_pathz)RFDETR._roboflow_keypoint_annotation_pathÙ  s:   € ô" % [Ô1ØÜ˜{Ó+¨gÑ5Ð8PÑPˆØ"1×"8Ñ"8Ô":ˆÐDÀÐDrk   c                óL   — t        | «      dz  dz  }|j                  «       r|S dS )a±  Return the native COCO train keypoint annotation path when it exists.

        Args:
            dataset_dir: Path to the COCO dataset root.

        Returns:
            Path to ``annotations/person_keypoints_train2017.json``, or ``None`` when it is absent.

        Raises:
            This helper does not raise.

        Example:
            >>> RFDETR._coco_keypoint_annotation_path("/missing") is None
            True
        r   zperson_keypoints_train2017.jsonN)r
   rë  rì  s     r=   Ú_coco_keypoint_annotation_pathz%RFDETR._coco_keypoint_annotation_pathï  s/   € ô" ˜{Ó+¨mÑ;Ð>_Ñ_ˆØ"1×"8Ñ"8Ô":ˆÐDÀÐDrk   c                ób   — t        | «      }t        D ]  }||z  }|j                  «       sŒ|c S  y)a�  Return the YOLO data file path when a dataset root has one.

        Args:
            dataset_dir: Path to the YOLO dataset root.

        Returns:
            Path to ``data.yaml`` or ``data.yml``, or ``None`` when neither exists.

        Raises:
            This helper does not raise.

        Example:
            >>> RFDETR._yolo_data_file_path("/missing") is None
            True
        N)r
   r   rë  )r0  ÚrootÚfilenameÚ	data_files       r=   Ú_yolo_data_file_pathzRFDETR._yolo_data_file_path  s=   € ô" �KÓ ˆÜ0ò 	!ˆHØ˜x™ˆIØ×ÑÕ!Ø Ò ð	!ð rk   c                óþ   — g }t        «       }t        | «      D ]b  \  }}||v s	||v s||k(  r|j                  |«       Œ%|t        | «      k  sŒ4| |   |k(  sŒ=|j	                  ||g«       |j                  ||h«       Œd |S )zIConvert Ultralytics ``flip_idx`` permutation metadata to flat swap pairs.)rÛ   Ú	enumeraterÝ   rÞ   ÚextendrÐ   )Úflip_idxÚpairsÚseenÚidxÚ
mirror_idxs        r=   Ú_flip_idx_to_pairszRFDETR._flip_idx_to_pairs  sŒ   € ð ˆÜ›ˆÜ(¨Ó2ò 	/‰OˆC�Ø�d‰{˜j¨DÑ0°C¸:Ò4EØ—‘˜”ØØœC ›MÓ)¨h°zÑ.BÀcÓ.IØ—‘˜c :Ð.Ô/Ø—‘˜S *Ð-Õ.ð	/ð ˆrk   c           	     óN  — | j                   j                  syt        |dd«      }|dvryt        |dd«      }|syt        | d«      si | _        ||f}|| j                  v r| j                  |   \  }}}n»	 |dk(  r(t
        j                  |«      }|€y|}d}t        |«      }n{|dk(  rOt
        j                  |«      }|�|}d	}t        |«      }nOt
        j                  |«      }	|	€y|	}d
}t        |	«      }n't
        j                  |«      }	|	€y|	}d
}t        |	«      }|||f| j                  |<   |j"                  }t        |dg «      st%        |j&                  «      |_        t%        t        | j                   dg «      xs g «      }dt        | j                   dt)        «       «      v }|rt+        |«      t+        |«      k(  ry||k7  r¤|rt        j-                  d|||«       nVt/        |«      r3|r1t/        |«      s&t1        j2                  d|›d|›d|›d�t4        d¬«       t        j!                  d|||«       || j                   _        t        | j6                  dd«      }|�||_        yyy# t        t        t        t        f$ r!}
t        j!                  d||
«       Y d}
~
yd}
~
ww xY w)a~  Infer or validate keypoint schema from COCO, Roboflow COCO, or YOLO pose metadata.

        Args:
            config: Training configuration containing dataset location and format.

        Returns:
            ``None``. The model config is updated in-place when dataset metadata is available.

        Raises:
            This method does not raise for missing or malformed metadata; later dataset construction still validates
            keypoint-mode requirements.

        Example:
            >>> from rfdetr.config import RFDETRKeypointPreviewConfig, TrainConfig
            >>> model = object.__new__(RFDETR)
            >>> model.model_config = RFDETRKeypointPreviewConfig(pretrain_weights=None)
            >>> model.model = type("Context", (), {"args": None})()
            >>> model._align_keypoint_schema_from_dataset(TrainConfig(dataset_dir="/missing", tensorboard=False))
        NÚdataset_file)ÚcocoÚroboflowÚyolor0  Ú_keypoint_schema_cacher  ÚCOCOr  zRoboflow COCOz	YOLO posez5Could not infer keypoint schema from dataset '%s': %sÚkeypoint_flip_pairsr¿   rÃ   z‹Configured num_keypoints_per_class=%s does not match dataset keypoint metadata %s from '%s'. Using dataset metadata as the source of truth.zYLoaded checkpoint uses a legacy background-first keypoint schema num_keypoints_per_class=z&, but the dataset infers active-first z}. Training will shift person from slot 1 to slot 0; checkpoint head weights are now misaligned. Pass num_keypoints_per_class=z& to train() to keep the legacy schema.rÁ   r  zFInferred num_keypoints_per_class=%s from %s keypoint metadata at '%s'.r}   )rg   r±  re   rp   r  r8   rð  r   rî  rõ  r   rÒ  rU   rã  r`  rØ   rÙ   r¿   r�   r  rÛ   r   rX  r    r  r  r   rn   )r|   rl  r   r0  Ú	cache_keyÚinferredÚsource_pathÚsource_kindrí  Úyolo_data_filer"  Úinferred_schemaÚcurrent_schemaÚuser_set_schemark  s                  r=   rM  z*RFDETR._align_keypoint_schema_from_dataset)  sì  € ð* × Ñ ×8Ò8ØÜ˜v ~°tÓ<ˆØÐ;Ñ;ØÜ˜f m°TÓ:ˆÙØä�tÐ5Ô6Ø02ˆDÔ'à! ;Ð/ˆ	Ø˜×3Ñ3Ñ3Ø15×1LÑ1LÈYÑ1WÑ.ˆH�k¡;ðØ 6Ò)Ü&,×&KÑ&KÈKÓ&X�OØ&Ð.ØØ"1�KØ"(�KÜ9¸/ÓJ‘HØ! ZÒ/Ü&,×&OÑ&OÐP[Ó&\�OØ&Ð2Ø&5˜Ø&5˜Ü#=¸oÓ#N™ä)/×)DÑ)DÀ[Ó)Q˜Ø)Ð1Ø"Ø&4˜Ø&1˜Ü#=¸nÓ#M™ä%+×%@Ñ%@ÀÓ%M�NØ%Ð-ØØ"0�KØ"-�KÜ9¸.ÓI�Hð 7?ÀÈ[Ð5YˆD×'Ñ'¨	Ñ2à"×:Ñ:ˆÜ�vÐ4°bÔ9Ü)-¨h×.JÑ.JÓ)KˆFÔ&äœg d×&7Ñ&7Ð9RÐTVÓWÒ]Ð[]Ó^ˆØ3´w¸t×?PÑ?PÐRdÔfiÓfkÓ7lÐlˆáÔ5°nÓEÔI_Ð`oÓIpÒpØà˜_Ò,ÙÜ—‘ðEà"Ø#Øõô ' ~Ô6¹?ÔSfÐgvÔSwÜ—M‘Mð3Ø3AÐ2Dð E(Ø(7Ð':ð ;8à8FÐ7Ið J)ð	*ô $Ø#$õ	ô —‘Ø\Ø#ØØô	ð 9HˆD×ÑÔ5Ü  §¡¨V°TÓ:ˆJØÐ%Ø5D�
Õ2ð &ð; -øô &¤z´8¼WÐEò Ü—‘ÐSÐU`ÐbeÔfÜûðús+   Á4I* ÂAI* Ã%'I* ÄI* É*J$ÊJÊJ$c                ó&   —  | j                   di |¤ŽS )zERetrieve the configuration parameters that will be used for training.r‰   )r…   r«   s     r=   rG  zRFDETR.get_train_config™  r¬   rk   c                ó   — t        |«      S )a  Retrieve a model context from the provided architecture configuration.

        Args:
            config: Architecture configuration.

        Returns:
            ModelContext with model, postprocess, device, resolution, args, and class_names attributes.
        )r   )r|   rl  s     r=   rŒ   zRFDETR.get_model�  s   € ô $ FÓ+Ð+rk   c                ó¶   — t        | j                  d«      r5| j                  j                  �t        | j                  j                  «      S t        t        «      S )zùRetrieve the class names supported by the loaded model.

        Returns:
            A list of class name strings, 0-indexed.  When no custom class names are embedded in the checkpoint, returns
            the standard 80 COCO class names.
        r<  )rp   rn   r<  r�   r   r‰  s    r=   r<  zRFDETR.class_names¨  sB   € ô �4—:‘:˜}Ô-°$·*±*×2HÑ2HÐ2TÜ˜Ÿ
™
×.Ñ.Ó/Ð/äÔ$Ó%Ð%rk   c                ó¶   — | j                   ry| j                  st        j                  d«       d| _        | j                  j                  j                  «        y)uî  Put the underlying module in eval mode before unoptimized inference.

        Inference must never run with dropout / batch-norm in training mode. The warning that the model is not optimized
        is emitted at most once, but eval mode is (re)asserted on every call: ``train()`` reassigns ``self.model.model``
        to a module that PyTorch Lightning leaves in training mode (see ``train()``), so gating ``eval()`` behind the
        once-only warning would let a later ``predict()`` silently run with dropout active.

        When ``_is_optimized_for_inference`` is ``True``, the method returns immediately â€” the compiled
        ``inference_model`` snapshot is already in eval mode and ``self.model.model`` is not used for inference.
        NzÂModel is not optimized for inference. Latency may be higher than expected. For full GPU throughput (e.g. ~8x on T4 via FP16 Tensor Cores), call model.optimize_for_inference(dtype=torch.float16).T)r–   r—   rØ   rX  rn   r  r‰  s    r=   Ú+_ensure_eval_mode_for_unoptimized_inferencez2RFDETR._ensure_eval_mode_for_unoptimized_inferenceµ  sM   € ð ×+Ò+ØØ×GÒGÜ�N‰NðKôð
 HLˆDÔDØ�
‰
×Ñ×ÑÕrk   c                ó
  — ddl m}m} t        || j                  d«      }t        | j                  dd«      }	t        |	t        «      st        |	t        «      r|	dk  rt        d|	›�«      ‚||	z  }
|€9| j                  j                  }||
z  dk7  r)t        d|› d	|
› d
|› d|	› d|
› d�«      ‚t        ||
||	«      }| j                  «        t        |t        «      s|g}g }g }|rg nd}|D �]W  }t        |t        «      rG|j!                  d«      r!t#        j$                  |d¬«      j&                  }t)        j*                  |«      }t        |t,        j.                  «      s�|rut1        j2                  |«      }|j4                  t0        j6                  k7  r2|dz  j9                  dd«      j;                  t0        j6                  «      }|j=                  |«       t?        j@                  |«      }n`|r^|j=                  |jC                  ddd«      jE                  «       jG                  «       dz  j;                  t0        j6                  «      «       |dkD  jI                  «       rt        d«      ‚|dk  jI                  «       rt        d«      ‚|jJ                  d   | j                  jL                  k7  r9t        d| j                  jL                  › dtO        |jJ                  «      › d�«      ‚|}|jJ                  dd \  }}|j=                  ||f«       |j=                  |jQ                  | j                  jR                  «      «       �ŒZ |�t        |«      n+| j                  j                  | j                  j                  g}t-        jT                  |D �cg c]  }t?        jV                  ||«      ‘Œ c}«      }t?        jX                  || jZ                  | j\                  «      }| j^                  r÷| j`                  |jJ                  d   k7  s| j`                  |jJ                  d   k7  rZt        | dd«      rdnd}t        d| j`                  › d| j`                  › d|jJ                  d   › d|jJ                  d   › d�	|z   «      ‚| jb                  rY| jd                  |jJ                  d   k7  r=t        | dd«      rdnd }t        d!| jd                  › d|jJ                  d   › d�|z   «      ‚| j^                  r6| j                  jg                  |jQ                  | jh                  ¬"«      «      }n| j                  j                  |«      }t        |tN        «      rN|d   |d   d#œ}tk        |«      dk(  r3t        t        | j                  d$d«      d%d«      r	|d   |d&<   n|d   |d'<   |}t-        jl                  || j                  jR                  ¬(«      }| j                  jo                  ||¬)«      }| jp                  }tk        |«      }t        | j                  d*d«      }|€'|t        tr        «      k(  rtt        jw                  d+«       t        |d,|«      }||kD  xr |t        tr        «      k(  } t        |d-g «      xs g }!ty        |!«      }"| r,t{        t|        «      D �#�$ci c]  \  }#}$|#|k  sŒ|$||#   “Œ }%}#}$na|"rKt{        |!«      D �&�'cg c]  \  }&}'|'dkD  sŒ|&‘Œ }(}&}'t{        |(«      D �#�)ci c]  \  }#})|#|k  sŒ|)||#   “Œ }%}#})nt        t{        |«      «      }%g }*t{        |«      D �])  \  }#}+|+d.   },|+d/   }-|+d0   }.|,|kD  }/|,|/   },|-|/   }-|.|/   }.d}0d1|+v r4|+d1   |/   }1|1j�                  «       jE                  «       jG                  «       }0|0du}2d2|+v r²|+d2   }3|3|/   }3 ||.j�                  «       jE                  «       jG                  «       |,j�                  «       jE                  «       jG                  «       |-jE                  «       jG                  «       |3jƒ                  d«      jE                  «       jG                  «       ¬3«      }4n{ ||.j�                  «       jE                  «       jG                  «       |,j�                  «       jE                  «       jG                  «       |-jE                  «       jG                  «       ¬4«      }4d5|+v rA|+d5   |/   }5|5j�                  «       jE                  «       jG                  «       |4j„                  d5<   |r||#   |4j†                  d6<   t1        jˆ                  t1        j2                  ||#   t0        jŠ                  ¬"«      tk        |4«      df«      |4j„                  d7<   |4jŒ                  �|4jŒ                  nt1        j2                  g t        ¬"«      }6|"rdn|}7|6D �8cg c]  }8|8|%vsŒ|8|7k7  sŒ|8‘Œ }9}8|9rtt        jw                  d8|9dd9 «       | r |6D �8cg c]  }8|%j%                  |8d:«      ‘Œ }:}8n&|6D �8cg c]  }8|8|7k(  rd;n|%j%                  |8d:«      ‘Œ }:}8t1        j2                  |:tŽ        ¬"«      |4j„                  d<<   |2�rò|0��ït        |4j„                  «      };|4j�                  j;                  t0        j’                  «      |;d=<   |r(t•        tk        |4«      «      D �<cg c]  }<||#   ‘Œ	 c}<|;d6<   |;j%                  d5«      }=|;j%                  d7«      }>|=�£|>�¡tk        |4«      dkD  r“t1        j–                  |=t0        j’                  ¬"«      }?t1        j–                  |>t0        j’                  ¬"«      }@|?jJ                  dd |0jJ                  dd k(  r*@jJ                  tk        |4«      dfk(  rt™        |?@¬>«      |;d?<   |0j;                  t0        j’                  d¬@«      }0|0dd…dd…df   }A ||0dd…dd…dd…f   |A|4jš                  �)|4jš                  j;                  t0        j’                  «      nd|4jŒ                  �|4jŒ                  j;                  t        «      ndAdkD  |;¬A«      }B|*j=                  |B«       �Œ|*j=                  |4«       �Œ, tk        |*«      dkD  r|*S |*d   S c c}w c c}$}#w c c}'}&w c c})}#w c c}8w c c}8w c c}8w c c}<w )Bu"  Performs model inference on the input images.

        This method accepts a single image or a list of images in various formats (file path, image url, PIL Image,
        NumPy array, or torch.Tensor). The images should be in RGB channel order. If a torch.Tensor is provided, it must
        already be normalized to values in the [0, 1] range and have the shape (C, H, W).

        Args:
            images:
                A single image or a list of images to process. Images can be provided
                as file paths, PIL Images, NumPy arrays, or torch.Tensors.
            threshold:
                The minimum confidence score needed to consider a detected bounding box valid.
            shape:
                Optional ``(height, width)`` tuple to resize images to before inference. When provided, overrides the
                model's default inference resolution. The tuple should match the resolution used when exporting the
                model (typically a square shape). Both dimensions must be positive integers divisible by ``patch_size *
                num_windows``. Defaults to ``(model.resolution, model.resolution)`` when not set.
            patch_size:
                Backbone patch size used for shape divisibility validation. Defaults to ``model_config.patch_size``
                (typically 14 for large models, 16 for smaller ones). Divisibility is checked against ``patch_size *
                num_windows``.
            include_source_image:
                Whether to attach the original image to the returned prediction. Detection and segmentation outputs use
                ``detections.metadata["source_image"]``. Keypoint outputs use per-object
                ``key_points.data["source_image"]`` because Supervision ``KeyPoints`` currently has no collection-level
                metadata field. Defaults to ``True``. Set to ``False`` to reduce memory use when source images are not
                needed.
            **kwargs:
                Additional keyword arguments.

        Returns:
            A single or multiple Supervision prediction objects. Detection and segmentation models return
            :class:`~supervision.Detections`. Keypoint models return :class:`~supervision.KeyPoints`, with keypoint
            coordinates in ``xy``. Keypoint predictions preserve the detection-level fields produced by RF-DETR:
            ``key_points.detection_confidence`` is the per-object score used by ``threshold``. For keypoint models this
            is the postprocessed detection score and, by default, includes keypoint uncertainty fusion controlled by
            ``model_config.postprocess_trace_alpha``. ``key_points.keypoint_confidence`` is separate: it is a
            ``(num_detections, num_keypoints)`` array of per-keypoint findability scores decoded from the keypoint head,
            not a repeated copy of the detection score. When RF-DETR emits keypoint precision parameters,
            ``key_points.data["covariance"]`` stores per-keypoint pixel-space covariance matrices with shape
            ``(num_detections, num_keypoints, 2, 2)``. ``key_points.data["xyxy"]`` stores the corresponding detection
            boxes as a ``(num_detections, 4)`` array in the same row order as ``key_points.xy`` because Supervision
            ``KeyPoints`` does not have a native bounding-box field. The ``data`` dict also contains ``class_name`` and
            ``source_shape`` as per-object arrays. When ``include_source_image=True`` for keypoint models,
            ``source_image`` is stored as per-object data until Supervision exposes collection-level metadata for
            ``KeyPoints``.

        Note:
            For ``Detections`` outputs, ``source_image`` moved from ``detections.data`` to ``detections.metadata``.
            Update detection callers reading ``detections.data["source_image"]`` to use
            ``detections.metadata["source_image"]``.

        Note:
            ``class_name`` mapping uses one of three modes depending on the checkpoint. For pretrained COCO checkpoints
            (detected when ``model.args.num_classes > len(class_names)`` and ``class_names`` matches
            ``COCO_CLASS_NAMES``), raw COCO category IDs (1â€“90, sparse) are looked up by category ID rather than by
            position â€” so ``class_id=18`` yields ``"dog"``, not ``class_names[18]``. For fine-tuned detection and
            segmentation models and active-first keypoint models, ``class_id`` is a 0-based index into ``class_names``.
            Legacy keypoint checkpoints with ``args.num_keypoints_per_class[0] == 0`` use a background-first layout:
            slot 0 maps to ``"__background__"`` and foreground slots map to ``class_names`` in order.

        Raises:
            ValueError: If ``shape`` cannot be unpacked as a two-element sequence,
                if either dimension does not support the ``__index__`` protocol (e.g. ``float``) or is a ``bool``, if
                either dimension is zero or negative, if either dimension is not divisible by ``patch_size *
                num_windows``, or if ``patch_size`` is not a positive integer.
        r   r#   Úpredictr_   rÂ   z9model_config.num_windows must be a positive integer, got Nr’  r“  rR   rS   r”  rO   ÚhttpT)Ústreaméÿ   rÁ   zYImage has pixel values above 1. Please ensure the image is normalized (scaled to [0, 1]).zYImage has pixel values below 0. Please ensure the image is normalized (scaled to [0, 1]).z~Invalid tensor image shape. Tensor inputs to `predict()` must be in (C, H, W) format with C matching the model configuration (z' channels). Received tensor with shape r‡   rœ   Fz< Create a new RFDETR instance to use a different resolution.zY You can explicitly remove the optimized model by calling model.remove_optimized_model().z8Resolution mismatch. Model was optimized for resolution Úxz
, but got zF Create a new RFDETR instance to recompile for a different batch size.zï You can explicitly remove the optimized model by calling model.remove_optimized_model(). Alternatively, you can recompile the optimized model for a different batch size by calling model.optimize_for_inference(batch_size=<new_batch_size>).zABatch size mismatch. Optimized model was compiled for batch size ry  )r�  rœ  rg   r±  rŸ  rž  )rm   )Útarget_sizesr}   u¦   predict(): model has no 'args' attribute â€” COCO sparse-ID mapping cannot activate; class_ids are treated as 0-indexed (may be wrong for pretrained COCO checkpoints)r»   r¿   Úscoresr˜  Úboxesrš  r™  )ÚxyxyÚ
confidenceÚclass_idÚmask)r  r  r  Úkeypoint_precision_choleskyÚsource_imageÚsource_shapeuJ   predict() encountered unmapped class_id(s): %s â€” mapping to empty stringé   r¶   Ú__background__Ú
class_namer  )Úprecision_choleskyr#  Ú
covariance)r   )ÚxyÚkeypoint_confidenceÚdetection_confidencer  ÚvisiblerË  )NÚsupervisionr$   r%   rj   rg   re   rV   rW   rf   rU   rn   r+  rb   r  r�   rq   rÎ   ÚrequestsrÑ   Úrawr   r]  rr   rß   ÚnpÚarrayrz  Úuint8ÚclipÚastypeÚappendÚFÚ	to_tensorÚpermuter±   ÚnumpyrD  r\   r�   Útuplert   rm   ÚstackÚresizeÚ	normalizer“   r”   r–   rš   r˜   r™   r•   r›   rÞ   ÚtensorÚpostprocessr<  r   rØ   Úwarning_oncer    r÷  r   rÏ   rÄ  ÚsqueezerË  ÚmetadataÚtileÚint64r  Úobjectr  Úfloat32r’   Úasarrayr!   r  )Cr|   ÚimagesÚ	thresholdr\   r^   Úinclude_source_imager~   r$   r%   r_   r]   Údefault_resÚ
orig_sizesÚprocessed_imagesÚsource_imagesÚimgÚsrcÚ
img_tensorÚhr>  Ú	resize_toÚtÚbatch_tensorÚ_restore_hintÚpredictionsÚreturn_predictionsr  ÚresultsÚmodel_class_namesr  Ú_model_argsÚnum_logit_slotsÚ_is_coco_pretrainedÚ_num_keypoints_per_classÚ_is_legacy_bgfirst_keypointrÜ  Úcoco_idÚ_class_id_to_namerü  r	  Ú_kp_foreground_slotsÚslotÚpredictions_listÚresultr  r˜  r  ÚkeepÚkeypoints_arrayrš  Úhas_keypointsr™  Ú
detectionsÚkeypoint_precisionÚ	class_idsÚ_bg_sentinelÚcidÚ	truly_oobr<  Úkeypoint_datar�   Úraw_precisionÚraw_source_shapeÚ	precisionr#  r*  Ú
key_pointssC                                                                      r=   r  zRFDETR.predictË  s  € ÷\ 	6ä(¨°T×5FÑ5FÈ	ÓRˆ
Ü˜d×/Ñ/°ÀÓBˆÜ�k¤4Ô(´
¸;ÌÔ0LÐP[Ð_`ÒP`ÜÐXÐYdÐXgÐhÓiÐiØ +Ñ-ˆ
àˆ=ØŸ*™*×/Ñ/ˆKØ˜ZÑ'¨1Ò,Ü Ø2°;°-ð @"Ø", ¨]¸:¸,ÀoÐVaÐUbð c>Ø>H¸\ÈðLóð ô )¨°
¸JÈÓTˆEà×8Ñ8Ô:ä˜&¤$Ô'Ø�XˆFàˆ
ØÐÙ2™¸ˆàó #	FˆCÜ˜#œsÔ#Ø—>‘> &Ô)Ü"Ÿ,™, s°4Ô8×<Ñ<�CÜ—j‘j “o�ä˜c¤5§<¡<Ô0Ù'ÜŸ(™( 3›-�CØ—y‘y¤B§H¡HÒ,Ø" S™y×.Ñ.¨q°#Ó6×=Ñ=¼b¿h¹hÓG˜Ø!×(Ñ(¨Ô-Ü—k‘k #Ó&‘Ù%Ø×$Ñ$ c§k¡k°!°Q¸Ó&:×&>Ñ&>Ó&@×&FÑ&FÓ&HÈ3Ñ&N×%VÑ%VÔWY×W_ÑW_Ó%`Ôaà�a‘�}‰}ŒÜ Øoóð ð �a‘�}‰}ŒÜ Øoóð ð �y‰y˜‰|˜t×0Ñ0×=Ñ=Ò=Ü ð@Ø@D×@QÑ@Q×@^Ñ@^Ð?_ð `2Ü27¸¿	¹	Ó2BÐ1CÀ1ðFóð ð
 ˆJà×#Ñ# A BÐ'‰DˆAˆqØ×Ñ˜q !˜fÔ%à×#Ñ# J§M¡M°$·*±*×2CÑ2CÓ$DÖEðG#	FðJ $)Ð#4”D˜”K¸4¿:¹:×;PÑ;PÐRV×R\ÑR\×RgÑRgÐ:hˆ	Ü—{‘{ÐDTÖ#U¸q¤A§H¡H¨Q°	Õ$:Ò#UÓVˆÜ—{‘{ <°·±¸T¿Y¹YÓGˆà×+Ò+à×*Ñ*¨l×.@Ñ.@ÀÑ.CÒCØ×-Ñ-°×1CÑ1CÀAÑ1FÒFô ˜tÐ%9¸5ÔAñ Sàtð ô
 !ð:Ø:>×:TÑ:TÐ9UÐUVÐW[×WqÑWqÐVrð sØ+×1Ñ1°!Ñ4Ð5°Q°|×7IÑ7IÈ!Ñ7LÐ6MÈQðPàR_ñ`óð ð
 ×0Ò0Ø×-Ñ-°×1CÑ1CÀAÑ1FÒFô # 4Ð)=¸uÔEñ aðeð	 "ô %ðGØGK×GaÑGaÐFbð c#Ø#/×#5Ñ#5°aÑ#8Ð"9¸ð<à>KñLóð ð ×+Ò+ØŸ*™*×4Ñ4°\·_±_È4×K`ÑK`°_Ó5aÓb‰KàŸ*™*×*Ñ*¨<Ó8ˆKÜ�k¤5Ô)à*¨1™~Ø)¨!™nñ"Ðô �;Ó 1Ò$äœ7 4§:¡:¨~¸tÓDÐF_ÐafÔgØ;FÀq¹>Ð&Ð'7Ò8à7BÀ1±~Ð& |Ñ4Ø,ˆKÜ—|‘| J°t·z±z×7HÑ7HÔIˆØ—*‘*×(Ñ(¨À<Ð(ÓPˆà ×,Ñ,ÐÜÐ!Ó"ˆô ˜dŸj™j¨&°$Ó7ˆØÐÐ#4¼Ô=MÓ8NÒ#NÜ×Ñðdôô  ' {°MÀ1ÓEˆØ-°Ñ1ÒaÐ6GÌ4ÔP`ÓKaÑ6aÐô /6°kÐC\Ð^`Ó.aÒ.gÐegÐ Ü&9Ð:RÓ&SÐ#Ùä@IÌ,Ó@W÷1Ù2<°!°WÐ[\Ð_`Ó[`�Ð*¨1Ñ-Ñ-ð1Ðò 1ñ )ô 7@Ð@XÓ6Y×#c©F¨C°Ð]^ÐabÓ]b¢CÐ#cÐ Ñ#cÜKTÐUiÓKj× tÁÀÀ4ÐnoÐrsÓns Ð'8¸Ñ';Ñ!;Ð tÐÒ tä $¤YÐ/@Ó%AÓ BÐØ9;ÐÜ" 7Ó+ó ^	4‰IˆAˆvØ˜HÑ%ˆFØ˜HÑ%ˆFØ˜7‘OˆEà˜IÑ%ˆDØ˜D‘\ˆFØ˜D‘\ˆFØ˜$‘KˆEØ"ˆOØ˜fÑ$Ø" ;Ñ/°Ñ5�	Ø"+§/¡/Ó"3×"7Ñ"7Ó"9×"?Ñ"?Ó"A�Ø+°4Ð7ˆMà˜&Ñ Ø˜w™�Ø˜d™�á'ØŸ™›×*Ñ*Ó,×2Ñ2Ó4Ø%Ÿ|™|›~×1Ñ1Ó3×9Ñ9Ó;Ø#ŸZ™Z›\×/Ñ/Ó1ØŸ™ qÓ)×-Ñ-Ó/×5Ñ5Ó7ô	‘
ñ (ØŸ™›×*Ñ*Ó,×2Ñ2Ó4Ø%Ÿ|™|›~×1Ñ1Ó3×9Ñ9Ó;Ø#ŸZ™Z›\×/Ñ/Ó1ô�
ð
 -°Ñ6Ø%+Ð,IÑ%JÈ4Ñ%PÐ"ØAS×AYÑAYÓA[×A_ÑA_ÓAa×AgÑAgÓAi�
—‘Ð =Ñ>á#Ø6CÀAÑ6F�
×#Ñ# NÑ3Ü.0¯g©g´b·h±h¸zÈ!¹}ÔTV×T\ÑT\Ô6]Ô`cÐdnÓ`oÐqrÐ_sÓ.tˆJ�O‰O˜NÑ+ð 0:×/BÑ/BÐ/N˜
×+Ò+ÔTV×T\ÑT\Ð]_ÔgjÔTkˆIñ !<™1ÀˆLØ(1Öj °SÐ@QÒ5QÐVYÐ]iÓVišÐjˆIÐjÙÜ×#Ñ#Ø`Ø˜b˜q�Môñ #ØIRÖSÀ#Ð0×4Ñ4°S¸"Õ=ÐS�ÑSð luöØdg¨¨|Ò(;Ñ$ÐAR×AVÑAVÐWZÐ\^ÓA_Ñ_ð�ð ô -/¯H©H°[ÌÔ,OˆJ�O‰O˜LÑ)â Ñ!<Ü $ Z§_¡_Ó 5�Ø(2¯©×(>Ñ(>¼r¿z¹zÓ(J�˜fÑ%Ù'ÜOTÔUXÐYcÓUdÓOeÖ4fÈ!°]À1Ó5EÒ4f�M .Ñ1Ø -× 1Ñ 1Ð2OÓ P�Ø#0×#4Ñ#4°^Ó#DÐ Ø Ð,Ð1AÐ1MÔRUÐV`ÓRaÐdeÒReÜ "§
¡
¨=ÄÇ
Á
Ô K�IÜ#%§:¡:Ð.>ÄbÇjÁjÔ#Q�LØ —‘ r¨Ð*¨o×.CÑ.CÀBÀQÐ.GÒGÈL×L^ÑL^ÔcfÐgqÓcrÐtuÐbvÒLvÜ6\Ø/8À|ô7˜ lÑ3ð #2×"8Ñ"8¼¿¹È%Ð"8Ó"P�Ø&5²aº¸A°gÑ&>Ð#Ù&Ø&¢qª!¨R¨a¨R xÑ0Ø(;à!×,Ñ,Ð8ð *4×)>Ñ)>×)EÑ)EÄbÇjÁjÔ)QàØ@J×@SÑ@SÐ@_˜Z×0Ñ0×7Ñ7¼Ô<ÐeiØ/°!Ñ3Ø&ô	�
ð !×'Ñ'¨
Ö3à ×'Ñ'¨
Ö3ð}^	4ô@ $'Ð'7Ó#8¸1Ò#<ÐÐUÐBRÐSTÑBUÐUùòy $VùóZ1ùó $dùÛ tùòp kùò Tùòùò 5gsN   ÎqÚqÚqÚ:q%Ûq%Ûq+Û+q+æ	q1æ%q1æ+q1çq6ç2 q;êr c                óÂ  — ddl m} |€"t        j                  d«      }|€t	        d«      ‚ ||¬«      }|j                  |«      }| j                  €|€t	        d«      ‚| j                  xs |}t        j                  d¬	«      5 }| j                  |«       |j                  |«      }	|	j                  |«      }
|
j                  ||d
¬«       ddd«       y# 1 sw Y   yxY w)aú  Deploy the trained RF-DETR model to Roboflow.

        Deploying with Roboflow will create a Serverless API to which you can make requests.

        You can also download weights into a Roboflow Inference deployment for use in Roboflow Workflows and on-device
        deployment.

        Args:
            workspace: The name of the Roboflow workspace to deploy to.
            project_id: The project ID to which the model will be deployed.
            version: The project version to which the model will be deployed.
            api_key: Your Roboflow API key. If not provided,
                it will be read from the environment variable `ROBOFLOW_API_KEY`.
            size: The size of the model to deploy. If not provided,
                it will default to the size of the model being trained (e.g., "rfdetr-base", "rfdetr-large", etc.).

        Raises:
            ValueError: If the `api_key` is not provided and not found in the
                environment variable `ROBOFLOW_API_KEY`, or if the `size` is not set for custom architectures.

        Note:
            Bundle creation is delegated to :meth:`export_for_roboflow`, which can be called independently
            to write ``weights.pt`` and ``class_names.txt`` without a network round-trip.
        r   )ÚRoboflowNÚROBOFLOW_API_KEYzHSet api_key=<KEY> in deploy_to_roboflow or export ROBOFLOW_API_KEY=<KEY>)Úapi_keyz&Must set size for custom architecturesÚroboflow_upload_)Úprefixú
weights.pt)Ú
model_typeÚ
model_pathró  )r  ru  r¤   ÚgetenvrU   Ú	workspacer   ÚtempfileÚTemporaryDirectoryÚexport_for_roboflowÚprojectÚversionÚdeploy)r|   r~  Ú
project_idrƒ  rw  r   ru  ÚrfÚtmp_out_dirr‚  Úproject_versions              r=   Údeploy_to_roboflowzRFDETR.deploy_to_roboflow  sÙ   € õ@ 	&àˆ?Ü—i‘iÐ 2Ó3ˆGØˆÜ Ð!kÓlÐlá˜gÔ&ˆØ—L‘L Ó+ˆ	à�9‰9Ð  ÜÐEÓFÐFà�y‰yÒ ˜DˆÜ×(Ñ(Ð0BÔCð 	cÀ{Ø×$Ñ$ [Ô1Ø×'Ñ'¨
Ó3ˆGØ%Ÿo™o¨gÓ6ˆOØ×"Ñ"¨d¸{ÐUaÐ"Ôb÷		c÷ 	cñ 	cús   ÂACÃCc                óT  — t        j                  |d¬«       t         j                  j                  |d«      }t	        |ddd¬«      5 }|j                  dj                  | j                  «      «       ddd«       t        | j                  j                  «      }t        |d	«      r|j                  €| j                  |_        t         j                  j                  |d
«      }t        j                  | j                  j                  j                  «       |dœ|«       y# 1 sw Y   Œ­xY w)aÕ  Write a Roboflow upload bundle (``weights.pt`` + ``class_names.txt``) into *output_dir*.

        This is the network-free core of :meth:`deploy_to_roboflow`: it serialises the model state and
        training args into ``weights.pt``, always embedding ``class_names`` into a copy of the args so
        the bundle is self-contained, and writes the class labels to ``class_names.txt``.  The Roboflow
        SDK uses this format to adapt raw PyTorch-Lightning checkpoints into a deploy-ready bundle.

        Args:
            output_dir: Directory into which ``weights.pt`` and ``class_names.txt`` are written.  Created
                if it does not exist.  Existing files are silently overwritten.

        Raises:
            PermissionError: If the process lacks write access to *output_dir* or its parent directory.
            OSError: On disk-full, invalid path, or other filesystem failure during directory creation,
                file write, or ``torch.save``.
        Tr¡   zclass_names.txtr>  r½  ú
)r¿  ÚnewlineNr<  rz  )rn   r}   )r¤   r§   r¥   r¨   r]  Úwriter<  r   rn   r}   rp   rr   Úsaver¾   )r|   rS  Úclass_names_pathrv  r}   Úoutpaths         r=   r�  zRFDETR.export_for_roboflowM  sÜ   € ô" 	�‰�J¨Õ.ô Ÿ7™7Ÿ<™<¨
Ð4EÓFÐÜÐ" C°'À4ÔHð 	1ÈAØ�G‰G�D—I‘I˜d×.Ñ.Ó/Ô0÷	1ô �D—J‘J—O‘OÓ$ˆÜ�t˜]Ô+¨t×/?Ñ/?Ð/GØ#×/Ñ/ˆDÔä—'‘'—,‘,˜z¨<Ó8ˆÜ�
‰
˜TŸZ™Z×-Ñ-×8Ñ8Ó:ÀDÑIÈ7ÕS÷	1ð 	1ús   Á+DÄD')r�   r   )r¥   ústr | os.PathLike[str]r~   r   r�   r8   )rm   r   r�   z#tuple[str | None, list[int] | None])
r…  rW   rH  rf   rz  ztorch.dtype | strrw  rW   r�   ÚNone)r�   r’  )r�   rW   )ÚoutputNFé   TNrÂ   FNrŽ  NNéd   )rS  rq   r´  ú
str | Noner¥  rW   r§  rf   r¦  rW   r\   útuple[int, int] | NonerH  rf   rµ  rW   r^   ú
int | Noner×   rq   r«  r–  r¬  zstr | np.ndarray | Noner®  rf   rŒ  rE  r�   r
   )r0  rq   r�   ú	list[str])r0  rq   r±  rW   r�   rf   )r0  rq   r�   r’  )r0  rq   r�   zPath | None)rù  ú	list[int]r�   rš  )rl  r   r�   r’  )r�   r   )rl  r   r�   r   ©r�   r™  )g      à?NNT)rH  zcstr | Image.Image | np.ndarray | torch.Tensor | list[str | np.ndarray | Image.Image | torch.Tensor]rI  rÄ  r\   r—  r^   r˜  rJ  rW   r~   r   r�   z5Detections | KeyPoints | list[Detections | KeyPoints]r  )r~  rq   r…  rq   rƒ  z	int | strrw  r–  r   r–  r�   r’  )rS  r‘  r�   r’  ),rY   Ú
__module__Ú__qualname__Ú__doc__r“   r”   r   r   r„   Ú__annotations__r   r…   rŸ   r‹   rŠ   Úclassmethodr  Ústaticmethodr#  r6  r‚   rr   rF  r‡  rZ  Úpropertyr‹  r€  rÝ  rá  rN  rî  rð  rõ  rþ  rM  rG  rŒ   r<  r  Úinference_moder  r‰  r�  r‰   rk   r=   r8   r8   â   sh  … ñGò "€EÚ €DØ€DØ-8ÐÐ*Ó8Ø-8ÐÐ*Ó8ò(ò,Fó02ð òoó ðoðb	 ò$ó ð$òL^hð@ ð ØØ#(§=¡=ð	_ð ñ_àð_ð ð_ð !ð	_ð ð_ð 
ò_ó ð_óB7(ðr ò':ó ð':ðV #Ø $Ø#ØØØ(,ØØ#Ø!%ØØ#'Ø48ØðW;ð  ñ!W;àðW;ð ðW;ð ð	W;ð
 ðW;ð ðW;ð &ðW;ð ðW;ð ðW;ð ðW;ð ðW;ð !ðW;ð 2ðW;ð ðW;ð  ð!W;ð" 
ó#W;ðr ò*
ó ð*
ðX Ø^cô 6ó ð6ó*_GðB òEó ðEð* òEó ðEð& òó ðð. òó ðónEó`2ó	,ð ò
&ó ð
&ó ð, €U×ÑÓØð Ø(,Ø!%Ø%)ðJVàsðJVð ðJVð &ð	JVð
 ðJVð #ðJVð ðJVð 
?òJVó ó ðJVðb
 #Øð2càð2cð ð2cð ð	2cð
 ð2cð ð2cð 
ó2côh!Trk   c                óœ   — | t         v r0t        j                  d«      }t        || «      }|t	        «       | <   |S t        dt        ›d| ›�«      ‚)zFLazily resolve legacy re-exports without creating import-order cycles.zrfdetr.variantszmodule z has no attribute )Ú_VARIANT_EXPORTSÚ	importlibÚimport_modulere   Úglobalsr{  rY   )rº   rn  r  s      r=   Ú__getattr__r©  q  sQ   € àÔÑÜ×(Ñ(Ð):Ó;ˆÜ˜ Ó%ˆØŒ‹	�$‰Øˆä
˜7¤8 ,Ð.@ÀÀÐIÓ
JÐJrk   c                 óZ   — t        t        t        «       «      t        t        «      z  «      S )z1Include lazy re-exports in interactive discovery.)rÍ  rÛ   r¨  r¥  r‰   rk   r=   Ú__dir__r«  |  s   € ä”#”g“i“.¤3Ô'7Ó#8Ñ8Ó9Ð9rk   )
r\   rE  r]   rf   r^   rf   r_   rf   r�   ztuple[int, int])r^   r˜  rg   rE  rh   rq   r�   rf   )ru   r   r�   r’  )r   ú"Callable[Concatenate[Any, _P], _R]r�   r¬  )rº   rq   r›  )ZÚ
__future__r   r}  rÎ  r¦  r^  rZ   r¤   r  r  Úcollectionsr   Úcollections.abcr   r   r   Ú	functoolsr	   Úpathlibr
   Útypingr   r   r   r   r   r9  r0  r.  rr   Ú!torchvision.transforms.functionalÚ
transformsÚ
functionalr6  rÏ  ÚPILr   Úrfdetr.assets.coco_classesr   r   Úrfdetr.assets.model_weightsr   r   Úrfdetr.configr   r   Ú rfdetr.datasets._keypoint_schemar   r   r   Úrfdetr.datasets.cocor   Úrfdetr.datasets.yolor   r   Úrfdetr.inferencer   r   Úrfdetr.utilities.distributedr   Úrfdetr.utilities.keypointsr    r!   Úrfdetr.utilities.loggerr"   r-  r$   r%   Úset_float32_matmul_precisionrW  rØ   r'   r(   r¥  Ú__all__Ú	frozensetr:   r:  r?   rŸ  rB   rI   rM   rb   rj   ry   r‚   r8   r©  r«  r‰   rk   r=   ú<module>rÄ     s–  ðö #ã Û Û Û Û Û 	Û Û Ý #Ý $ß Ý Ý ß FÕ Fã Û Û ß -Ð -Û Ý ç Eß Vß 2÷ñ õ
 7ß Pß ?Ý 8ß bÝ .áß1ð	Ø&€E×&Ñ& vÔ.ñ 
‹€Ùˆtƒ_€ÙˆTƒ]€ðÐ ð" �^Ð
7Ð&6Ð
7€á*3Ð5LÈkÐ4ZÓ*[Ð 'Ù8=ñ >Ø%5ô>ó 9Ð $ oó ð >_Ð )¨?Ó ^ð>Ð Ð:ó ð CÐ "Ð$?ó ð.Øð.àð.ð ð.ð ð	.ð
 ó.óbóD+ó*÷"LTñ LTó^<Kô:øðUB ò 	Ùð	ús   ÃE ÅE%Å$E%