
    ^j                        U d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	m
Z
mZmZmZ d dlZd dlmZmZmZmZmZ d dlmZ e	d   Zeed<   eez  Zeed<    G d	 d
e      ZdefdZ e       Zeed<    G d de      Z G d de      Z  G d de       Z! G d de!      Z" G d de!      Z# G d de!      Z$ G d de!      Z% G d de       Z& G d de!      Z' G d  d!e!      Z( G d" d#e!      Z) G d$ d%e!      Z* G d& d'e!      Z+ G d( d)e!      Z, G d* d+e!      Z- G d, d-e!      Z. G d. d/e      Z/ G d0 d1e/      Z0 G d2 d3e/      Z1y)4    N)Path)	AnyClassVarDictListLiteralMappingOptional	TypeAliasUnion)	BaseModel
ConfigDictFieldfield_validatormodel_validator)PydanticUndefined)dinov2_windowed_smalldinov2_windowed_basedinov2_registers_windowed_smallEncoderNamePathLikeStrc                       e Zd ZdZy)#PretrainWeightsCompatibilityWarningu   Warning emitted when ``ModelConfig`` overrides are likely to prevent the variant's published pretrained weights
    from loading into the model — leaving large portions of the model randomly initialized and typically producing much
    lower accuracy.N)__name__
__module____qualname____doc__     X/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/config.pyr   r      s    r   r   returnc                  x   t        t        dd      } t        | dd      }|	 	  |d      }|t	        |      S yt        j                  j                         ryt        j                  j                  j                         ryy# t        $ r  |       }|| j                         sd}Y }w xY w# t
        $ r Y yw xY w)	u   Detect the best available device **without** initialising the CUDA runtime.

    ``torch.cuda.is_available()`` creates a CUDA driver context that makes ``_is_in_bad_fork()`` return ``True`` in
    child processes.  This breaks fork-based DDP strategies (e.g. ``ddp_notebook``) in notebook environments.

    We defer to :func:`torch.accelerator.current_accelerator` (PyTorch ≥ 2.4) when available — it queries the driver
    through NVML without creating a primary context.  On older builds we fall back to ``torch.cuda.is_available()``.

    ``check_available=True`` is required: without it ``current_accelerator()`` only reports the *compile-time*
    accelerator, so the default CUDA wheel on a machine without an NVIDIA driver yields ``"cuda"`` and every model build
    crashes with "Found no NVIDIA driver".  The runtime check is NVML-backed and still avoids creating a CUDA context.
    Builds whose ``current_accelerator`` predates the ``check_available`` kwarg get the same runtime verification via
    ``torch.accelerator.is_available``.
    acceleratorNcurrent_acceleratorT)check_availablecpucudamps)	getattrtorch	TypeErroris_availablestrRuntimeErrorr'   backendsr(   )r#   r$   accels      r    _detect_devicer1      s     %5K!+/DdK&	!+DA
  5z! zz ~~&&(  !+-$[-E-E-G E!  		s.   	B B- $B*'B- )B**B- -	B98B9DEVICEc                        e Zd ZU dZ edd      Zee   ed<    ed      e	de
d	e
fd
              Zdede
d	df fdZ xZS )
BaseConfigzBase configuration class that validates input parameters against the defined model schema.

    If any unknown fields are provided, a ValueError is raised listing the unknown and available parameters.
    forbidTextravalidate_assignmentmodel_configbeforemodevaluesr!   c                 n   t        |t              s|S | j                  j                  d      dk7  r|S t	        | j
                  j                               }t	        |      }||z
  }|rMdj                  d t        |      D              }dj                  t        |            }t        d| d| d      |S )Nr7   r5   z, c              3   (   K   | ]
  }d | d   yw)'Nr   ).0params     r    	<genexpr>z/BaseConfig.catch_typo_kwargs.<locals>.<genexpr>W   s     +]UawaL+]s   zUnknown parameter(s): z. Available parameter(s): .)

isinstancer	   r9   getsetmodel_fieldskeysjoinsorted
ValueError)clsr=   allowed_paramsprovided_paramsunknown_paramsunknown_params_listallowed_params_lists          r    catch_typo_kwargszBaseConfig.catch_typo_kwargsL   s     &'*M(H4MS--2245f+(>9"&))+]f^F\+]"]"&))F>,B"C()<(==WXkWllmn  r   namevalueNc                     |j                  d      s|t        |       j                  v rt        |   ||       y t        d| d      )N_zUnknown attribute: 'z'.)
startswithtyperH   super__setattr__rL   )selfrT   rU   	__class__s      r    r[   zBaseConfig.__setattr__^   sG    ??344:+B+B#BGe,/vR899r   )r   r   r   r   r   r9   r   __annotations__r   classmethodr   rS   r-   r[   __classcell__)r]   s   @r    r4   r4   D   sm    
 *4(X\)]L(:&](#s s   $ : :C :D : :r   r4   c                   |   e Zd ZU eed<   ee   ed<   eed<   dZeed<   ee	d      ed<   eed<   eed	<   eed
<   eed<   eed<   eed<   dZ
eed<   dZeed<    edd      Zeed<   dZeed<   dZeed<   dZeed<   dZeed<    edd      Zeed<   dZeed<   dZee   ed<   eZeed <   eed!<   d"Zeed#<   d$Zeed%<   d$Zeed&<   dZeed'<   eed(<   dZeed)<   d*Z eed+<   d$Z!eed,<   d$Z"eed-<   dZ#eed.<   d$Z$eed/<   dZ%eed0<   d$Z&eed1<   d$Z'eed2<    ee(3      Z)ee   ed4<   d5Z*eed6<   d7Z+eed8<   d$Z,eed9<   d$Z-eed:<   d;Z.eed<<    edd=>      Z/ee   ed?<    e0d@A      dJdC       Z1 e0d@A      dJdD       Z2 e0d@A      dJdE       Z3 e4ddFA      e5dGedz  dBedz  fdH              Z6 e4d dFA      e5dGe7dBefdI              Z8y)KModelConfigencoderout_feature_indexes
dec_layersT	two_stageP3P4P5projector_scale
hidden_dim
patch_sizenum_windows	sa_nheads	ca_nheadsdec_n_points,  num_queries
num_selectg?        defaultgepostprocess_trace_alphabbox_reparamlite_refpoint_refine
layer_normamp      num_channelsZ   num_classesNpretrain_weightsdevice
resolution   
group_detrFgradient_checkpointingcompilefused_optimizerpositional_encoding_sizeia_bce_loss      ?cls_loss_coefsegmentation_headuse_grouppose_keypointskeypoint_cross_attninter_instance_kp_attn grouppose_keypoint_dim_downscaledual_projectordual_projector_kp_onlydefault_factorynum_keypoints_per_classr   num_decoder_registers   mask_downsample_ratiobackbone_lorafreeze_encoderz
Apache-2.0licensezName of the model class stored in training checkpoints (e.g. ``"RFDETRLarge"``). Set automatically by ``RFDETR.train()`` before saving. Used by ``RFDETR.from_checkpoint()`` to resolve the correct subclass directly without inspecting ``pretrain_weights``.rw   description
model_nameafterr;   r!   c                 Z    d| j                   v rt        j                  dt        d       | S )a  Emit DeprecationWarning when cls_loss_coef is explicitly set on ModelConfig.

        ``cls_loss_coef`` ownership is moving to ``TrainConfig`` (Item #3, v1.7). Setting it on ``ModelConfig`` is
        deprecated.  Use ``TrainConfig(cls_loss_coef=...)`` instead.
        r   z}ModelConfig.cls_loss_coef is deprecated since v1.7.0 and will be removed in v1.9.0. Set cls_loss_coef on TrainConfig instead.   
stacklevelmodel_fields_setwarningswarnDeprecationWarning)r\   s    r    $_warn_deprecated_model_config_fieldsz0ModelConfig._warn_deprecated_model_config_fields   s2     d333
 MM<"	 r   c                    d| j                   vsd| j                   v r| S t        |       }|j                  d   j                  }|j                  d   j                  }|j                  d   j                  }t	        |t
              r t	        |t
              rt	        |t
              s| S |||z  k(  r| j                  | j                  z  | _        | S )a?  Auto-update positional_encoding_size when resolution is explicitly provided.

        When a user provides a custom ``resolution`` at construction time (e.g., ``RFDETRLarge(resolution=640)``),
        ``positional_encoding_size`` is updated proportionally, provided the class-default PE is formula-derived
        (``default_pe == default_resolution // patch_size``).

        Configs with a pretrained-specific PE (e.g., ``RFDETRBaseConfig`` with ``positional_encoding_size=37`` for
        DINOv2's native 518 px grid, while ``resolution=560``) are left unchanged.
        r   r   rm   )	r   rY   rH   rw   rE   intr   rm   r   )r\   rM   default_resolution
default_pedefault_patch_sizes        r    _sync_pe_with_resolutionz$ModelConfig._sync_pe_with_resolution   s     t4448RVZVkVk8kK4j --l;CC%%&@AII
 --l;CC -s3j#.0#6K +/AAA,0OOt,ND)r   c                    t        |       }| j                  }d|v }|r]| j                  Q|j                  d   j                  }|t
        ur.|,t        j                  |j                   d|dt        d       | S |rS| j                  G|j                  d   j                  }|*|t
        ur"|j                  |      }| j                  |k7  r| S | S |j                  d   j                  }||t
        u r| S g }d}	d}
|	D ]p  }||vr|j                  j                  |      }||j                         r6|j                  }|t
        u rKt        | |      }||k7  s]|j                  |||f       r |
D ]  }||vr|j                  j                  |      }||j                         r6|j                  }|t
        u st        |t               s[t        | |      }t        |t               sx||kD  s~|j                  |||f        d|v rr| j"                  rf|j                  j                  d      }|I|j                         s9|j                  }|t
        ur%t        | d      }||k7  r|j                  d||f       |r`|j                  d   j                  }d	j%                  d
 |D              }t        j                  |j                   d|d| dt        d       | S )uf  Warn when overrides are likely to prevent published pretrained weights from loading.

        Three cases:

        1. ``pretrain_weights`` was explicitly set to ``None`` and the variant
           has a non-``None`` default → warn that the model is being initialised from scratch.
        2. ``pretrain_weights`` was explicitly set to a non-``None`` custom path
           → suppress the architecture-override check (we cannot know the architecture stored in a user-supplied
           checkpoint at config time). The load-time partial-load detector in
           :func:`rfdetr.models.weights.load_pretrain_weights` covers this case by inspecting the checkpoint contents
           directly.
        3. ``pretrain_weights`` is the variant's published default → check
           architecture-affecting fields against the variant defaults and emit a single consolidated warning listing
           every load-breaking override.

        The warning class is :class:`PretrainWeightsCompatibilityWarning` (a :class:`UserWarning` subclass), silenceable
        via the standard ``warnings.filterwarnings`` machinery.
        r   z was instantiated with pretrain_weights=None. The model will be initialised from scratch, which typically produces lower accuracy than fine-tuning from the published checkpoint (z).r   r   )rc   rl   re   rn   ro   rp   rq   rd   rk   rz   r{   r|   rf   rm   r   r   )rs   r   r   
c              3   <   K   | ]  \  }}}d | d|d|d  yw)z  z: z (variant default: )Nr   )rA   rT   currentrw   s       r    rC   z;ModelConfig._warn_pretrain_compatibility.<locals>.<genexpr>`  s3      LbDRY[b"TF"WK':7+QGs   z~ was instantiated with overrides that differ from the variant defaults in ways that prevent the published pretrained weights (z) from loading correctly:
aF  
Loading the checkpoint with this configuration will leave significant portions of the model randomly initialised, which typically produces lower accuracy. To suppress this warning: revert the override(s), pick a variant whose defaults match, or pass pretrain_weights=None to acknowledge that you intend to train from scratch.)rY   r   r   rH   rw   r   r   r   r   r   expand_pathrF   is_requiredr)   appendrE   r   r   rJ   )r\   rM   
fields_setpretrain_user_setdefault_pretrain_default_pretrain_expanded_default_class_default_pretrain	overridesbreaking_fieldsbreaking_on_increaserT   
field_inforw   r   	_mdr_info_mdr_default_mdr_currentliness                      r    _warn_pretrain_compatibilityz(ModelConfig._warn_pretrain_compatibility   sE   ( 4j**
.*<!6!6!>"//0BCKK'88=M=Y||n %# $4"6b: 8  K!6!6!B !$ 0 01C D L L ,1BJ[1[$'OO4E$F!((,==K  #&"2"23E"F"N"N"*.EIZ.ZK02	,
(1

 $ 	;D:%))--d3J!Z%;%;%= ((G++dD)G'!  $!9:	; ) 	;D:%))--d3J!Z%;%;%= ((G++:gs3KdD)G'3'Gg,=  $!9:	; #j0T5K5K((,,-DEI$Y-B-B-D(00'88#*41H#IL#|3!((*A<Q])^_"//0BCKKII fo E MM<<. !$''B'    4 r   r:   vc                 @   ||S t         j                  j                  t        j                  |            }t         j                  j	                  |      s+ddlm} t         j                  j                   |       |      S t         j                  j                  |      S )a  Expand and resolve the pretrain_weights path.

        Bare filenames (no directory component, e.g. ``rf-detr-base.pth``) are resolved to the model cache directory so
        weights land in a stable, user-configurable location (``~/.roboflow/models`` by default, or the path set via the
        ``RF_HOME`` environment variable) instead of CWD.

        Paths that already contain a directory separator (e.g. ``~/models/x.pth``, ``/abs/path/x.pth``,
        ``models/x.pth``) are normalised with ``os.path.realpath`` as before.
        r   )get_model_cache_dir)	ospath
expanduserfspathdirnamerfdetr.assets.model_weightsr   rJ   realpath)rM   r   expandedr   s       r    r   zModelConfig.expand_paths  sk     9H77%%biil3wwx(G77<< 3 5x@@ww))r   c                    t        |t        j                        rt        |      S t        |t              r	 t        t        j                  |            S t        d      # t        t
        t        f$ r}t        d|d      |d}~ww xY w)a  Normalize supported device inputs to a canonical torch-style string.

        Args:
            v: Device specifier provided by callers. Supported values are
                ``str`` (for example ``"cpu"``, ``"cuda"``, ``"cuda:1"``) and ``torch.device``.

        Returns:
            Canonical string form of the parsed device (for example ``"cuda:1"``).

        Raises:
            ValueError: If a string value cannot be parsed as a valid torch device.
            ValueError: If ``v`` is not a string or ``torch.device``.
        zInvalid device specifier: rD   Nz(device must be a string or torch.device.)rE   r*   r   r-   r+   rL   r.   )rM   r   excs      r    _normalize_devicezModelConfig._normalize_device  s~      a&q6MaO5<<?++ CDD z<8 O #=aU!!DE3NOs   A   B	4BB	)r!   rb   )9r   r   r   r   r^   r   r   rf   boolr   rs   rt   r   ry   floatrz   r{   r|   r}   r   r   r   r
   r   r2   r   r-   r   r   r   r   r   r   r   r   r   r   r   r   r   listr   r   r   r   r   r   r   r   r   r   r   r   r_   r   r   r   r   r   r    rb   rb   e   s   c"OIt'"2344OONNK J%*33%?U?L$!%$%JCaA.L#.K.2h{+2FCOJ#(D(GT OT !!KM5#t#$)T) $$#(D(,-$c- ND #(D().t)DT#YD!"3"!"3"M4 ND GS %7!J  '" #& '"! #!F '"Y #Yv 'h7*K$. *3: *  8*( XH-E# E# E  .Er   rb   c                      e Zd ZU dZdZeed<   dZeed<   dZ	eed<   dZ
eed	<   d
Zeed<   dZeed<   dZeed<   dZeed<   dZeed<   dZeed<   dgZeed      ed<   g dZee   ed<   dZee   ed<   dZeed<   dZeed<   y )!RFDETRBaseConfigz,The configuration for an RF-DETR Base model.r   rc      rl      rm   r   rn   r~   re      ro      rp   r   rq   rr   rs   rt   ri   rg   rk   )r      r      rd   zrf-detr-base.pthr   i0  r   %   r   N)r   r   r   r   rc   r   r^   rl   r   rm   rn   re   ro   rp   rq   rs   rt   rk   r   r   rd   r   r
   r   r   r   r   r   r    r   r     s    62G[2JJKJIsIsL#KJ8<vOT'"234=%2c2.@h{+@J$&c&r   r   c                       e Zd ZU dZdZeed<   dZeed<   dZ	eed<   dZ
eed	<   d
Zeed<   ddgZeed      ed<   dZee   ed<   y)RFDETRLargeDeprecatedConfigz-The configuration for an RF-DETR Large model.r   rc     rl      ro      rp   r   rq   rh   rj   rg   rk   zrf-detr-large.pthr   N)r   r   r   r   rc   r   r^   rl   r   ro   rp   rq   rk   r   r   r   r
   r   r   r   r    r   r     s`    71G[1JIsIsL#8<d|OT'"234C.Ah{+Ar   r   c                       e Zd ZU dZg dZee   ed<   dZeed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZee   ed<   y)RFDETRNanoConfigz,The configuration for an RF-DETR Nano model.r~      	   r   rd   r   rn   re   r   rm   r   r   r   r   zrf-detr-nano.pthr   Nr   r   r   r   rd   r   r   r^   rn   re   rm   r   r   r   r
   r   r   r   r    r   r     sW    6%2c2KJJJ$&c&.@h{+@r   r   c                       e Zd ZU dZg dZee   ed<   dZeed<   dZ	eed<   dZ
eed	<   d
Zeed<   dZeed<   dZee   ed<   y)RFDETRSmallConfigz-The configuration for an RF-DETR Small model.r   rd   r   rn   r~   re   r   rm   i   r       r   zrf-detr-small.pthr   Nr   r   r   r    r   r     sW    7%2c2KJJJ$&c&.Ah{+Ar   r   c                       e Zd ZU dZg dZee   ed<   dZeed<   dZ	eed<   dZ
eed	<   d
Zeed<   dZeed<   dZee   ed<   y)RFDETRMediumConfigz.The configuration for an RF-DETR Medium model.r   rd   r   rn   r   re   r   rm   @  r   $   r   zrf-detr-medium.pthr   Nr   r   r   r    r   r     sW    8%2c2KJJJ$&c&.Bh{+Br   r   c                      e Zd ZU dZed   ed<   dZeed<   dZeed<   dZ	eed<   d	Z
eed
<   dZeed<   dZeed<   d	Zeed<   dgZeed      ed<   g dZee   ed<   dZeed<   dZeed<   dZee   ed<   dZeed<   dZeed<   dZeed<   y) RFDETRLargeConfigr   rc   r   rl   r   re   r   ro   r   rp   r   rq   rn   rm   ri   )ri   rk   r   rd   r   r   ,   r   zrf-detr-large-2026.pthr   i  r   rr   rs   rt   N)r   r   r   rc   r   r^   rl   r   re   ro   rp   rq   rn   rm   rk   r   rd   r   r   r   r
   r   r   rs   rt   r   r   r    r   r     s    0GGW,-GJJIsIsL#KJ-1FOT'%.)2%2c2K$-c-.Fh{+FJ
 KJr   r   c                       e Zd ZU dZeed<   g dZee   ed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZeed<   dZeed<   dZee   ed<   dZeed<   y)RFDETRSegPreviewConfigTr   r   rd   r   rn   r   re   r   rm     r   r   r      rs   rt   zrf-detr-seg-preview.ptr   r   r   Nr   r   r   r   r   r^   rd   r   r   rn   re   rm   r   r   rs   rt   r   r
   r   r   r   r   r    r   r     s}    "t"%2c2KJJJ$&c&KJ.Fh{+FKr   r   c                       e Zd ZU dZeed<   g dZee   ed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZeed<   dZeed<   dZee   ed<   dZeed<   y)RFDETRSegNanoConfigTr   r   rd   r   rn   r   re   r   rm   i8  r      r   d   rs   rt   zrf-detr-seg-nano.ptr   r   r   Nr   r   r   r    r   r     s}    "t"%2c2KJJJ$-c-KJ.Ch{+CKr   r   c                       e Zd ZU dZeed<   g dZee   ed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZeed<   dZeed<   dZee   ed<   dZeed<   y)RFDETRSegSmallConfigTr   r   rd   r   rn   r   re   r   rm   r   r   r   r   r  rs   rt   zrf-detr-seg-small.ptr   r   r   Nr   r   r   r    r  r    }    "t"%2c2KJJJ$-c-KJ.Dh{+DKr   r  c                       e Zd ZU dZeed<   g dZee   ed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZeed<   dZeed<   dZee   ed<   dZeed<   y)RFDETRSegMediumConfigTr   r   rd   r   rn   r   re   r   rm   r   r   r   r   r   rs   rt   zrf-detr-seg-medium.ptr   r   r   Nr   r   r   r    r  r  )  }    "t"%2c2KJJJ$-c-KJ.Eh{+EKr   r  c                       e Zd ZU dZeed<   g dZee   ed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZeed<   dZeed<   dZee   ed<   dZeed<   y)RFDETRSegLargeConfigTr   r   rd   r   rn   r   re   r   rm   i  r   *   r   r   rs   rt   zrf-detr-seg-large.ptr   r   r   Nr   r   r   r    r	  r	  7  r  r   r	  c                       e Zd ZU dZeed<   g dZee   ed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZeed<   dZeed<   dZee   ed<   dZeed<   y)RFDETRSegXLargeConfigTr   r   rd   r   rn   r   re   r   rm   ip  r   4   r   rr   rs   rt   zrf-detr-seg-xlarge.ptr   r   r   Nr   r   r   r    r  r  E  r  r   r  c                       e Zd ZU dZeed<   g dZee   ed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZeed<   dZeed<   dZee   ed<   dZeed<   y)RFDETRSeg2XLargeConfigTr   r   rd   r   rn   r   re   r   rm   i   r   @   r   rr   rs   rt   zrf-detr-seg-xxlarge.ptr   r   r   Nr   r   r   r    r  r  S  s}    "t"%2c2KJJJ$-c-KJ.Fh{+FKr   r  c                      e Zd ZU dZdZeed<   dZeed<   dZeed<   dgZ	e
e   ed<   dZeed<   d	Zeed
<   dZeed<   g dZe
e   ed<   dZeed<   dZeed<   dZeed<   dZeed<   dZeed<   dZeed<   dZeed<   dZee   ed<   dZeed<   y )!RFDETRKeypointPreviewConfigz-Configuration for the preview keypoint model.Tr   r   r      r   r   Fr   r   r   r   rd   r   rn   r   re   r   rm   r   r   0   r   r  rs   rt   z#rf-detr-keypoint-preview-xlarge.pthr   r   r   N)r   r   r   r   r   r   r^   r   r   r   r   r   r   r   r   rd   rn   re   rm   r   r   rs   rt   r   r
   r   r   r   r   r    r  r  a  s    7$(T(ND#'D'*,T#Y- $$#(D(,-$c-%2c2KJJJ$-c-KJ.Sh{+SKr   r  c                      e Zd ZU dZ edd      Zee   ed<   dZe	ed<   dZ
e	ed	<   d
Zeed   z  ed<   d
Zeed<   dZeed<   dZeed<   dZe	ed<   dZeed<   dZee   ed<   dZe	ed<   dZeed<   dZeed<    edd      Zeed<    edd      Zeed <   d!Ze	ed"<   d!Ze	ed#<   d$Ze	ed%<   dZe	ed&<   d!Z e	ed'<   d(Z!eed)<   dZ"e#ed*<   d+Z$e	ed,<   d-Z%eed.<    ee&/      Z'e(e   ed0<   dZ)e	ed1<   dZ*e	ed2<   dZ+e	ed3<   dZ,e	ed4<   dZ-e(e	   dz  ed5<   d6Z.ed7   ed8<   dZ/e#ed9<   ee   ed:<   d;Z0eed<<   dZ1e#ed=<   dZ2e#ed><   d?Z3e#ed@<   dZ4e#edA<   dZ5eedB<   dCZ6eedD<   dZ7e	edE<    eddFG      Z8edH   edI<   d?Z9e#edJ<   dZ:eedK<   dLZ;e	edM<   d?Z<e#edN<   dZ=eedO      edP<   dZ>e#edQ<   d?Z?e#edR<   d?Z@e#edS<   d?ZAe#edT<   dZBeeC   edU<   dZDeeC   edV<   dZEee(eC      edW<   d?ZFe#edX<   d?ZGe#edY<   dZZHeed[<   dZIeed\<   dZJe#ed]<   dZKeeLeCeMf      ed^<   d_ZNed`   eda<   d?ZOe#edb<    eddcG      ZPeeM   edd<    eQdef      ddh       ZR eSdPdif      eTdjeMdgeMfdk              ZU eSdIdif      eTdjeMdgeMfdl              ZVdZWeCedm<   dnZXe	edo<   dZYee   edp<   d?ZZe#edq<   dZ[eCedr<   dZ\e]eeCf   eds<   dZ^eedt<   d?Z_e#edu<   dvZ`edw   edx<   d!Zae	edy<   d?Zbe#edz<   d?Zce#ed{<   d?Zde#ed|<   d?Zee#ed}<   dZfe#ed~<   dZge#ed<   dZhee#   ed<   dZiee#   ed<   dZjee   ed<    eSddef      eTdeed   z  dgeed   z  fd              Zk eSddddef      eTdedgefd              Zl eSddef      eTde	dge	fd              Zm eSd"def      eTde	dge	fd              Zn eSdBd\def      eTdedgefd              Zo eSddef      eTdee   dgee   fd              Zp eSd:d<dif      eTdedz  dgeCdz  fd              Zq eSddif      eTdedz  dgeCdz  fd              Zry)TrainConfigaW  Training hyperparameters and auto-batching configuration.

    Notes:
        * ``auto_batch_target_effective`` is interpreted as the **per-device**
          effective batch size target, i.e. the number of images seen by a single process in one optimizer step after
          accounting for ``grad_accum_steps``. In multi-GPU / multi-node runs the global effective batch size is
          therefore:

            ``global_effective_batch = auto_batch_target_effective * devices * num_nodes``

          This avoids silently changing behavior when scaling from single-GPU to multi-GPU training.
    ignoreTr6   r9   g-C6?lrga2U0*#?
lr_encoderr   auto
batch_sizegrad_accum_stepsr   auto_batch_target_effectiver   auto_batch_max_targets_per_imagegffffff?auto_batch_ema_headroomepochsNresumeg-?	ema_decayema_taulr_drop
   r   rv   checkpoint_intervalr   skip_best_epochsru   smooth_alphawarmup_epochsg?lr_vit_layer_decaylr_component_decay	drop_pathr   r   r   r   r   rr   rt   r   keypoint_flip_pairskeypoint_l1_loss_coefkeypoint_findable_loss_coefkeypoint_visible_loss_coefkeypoint_nll_loss_coefkeypoint_oks_sigmasroboflow)cocoo365r3  yolodataset_filesquare_resize_div_64dataset_diroutput
output_dirmulti_scaleexpanded_scalesFdo_random_resize_via_paddinguse_emaema_update_intervalr   num_workersweight_decayzMixed-precision autocast dtype. 'auto' selects bf16-mixed on Ampere+ CUDA, fp16 otherwise. 'bf16' forces bfloat16 (falls back to fp16 with a warning if unsupported). 'fp16' forces fp16. Has no effect when model_config.amp=False or when training on CPU.r   r  bf16fp16	amp_dtypeearly_stoppingearly_stopping_patiencegMbP?early_stopping_min_deltaearly_stopping_use_ema)tqdmrichprogress_bartensorboardwandbmlflowclearmlprojectrunclass_namesrun_testr   i  eval_max_detseval_intervallog_per_class_metrics
aug_configr&   )r&   r  gpuaugmentation_backendsave_dataset_gridsaB  User-defined provenance metadata embedded in best-model .pth checkpoints under checkpoint['args']['notes'] and in exported ONNX files under the 'rfdetr_notes' metadata property. Accepts any JSON-serialisable value (string, dict, list, int, float, bool). String values are stored verbatim; all other types are JSON-encoded.notesr   r;   r!   c                 |    d}|D ]4  }|| j                   v st        j                  d| d| dt        d       6 | S )u  Emit DeprecationWarning for fields whose ownership is moving to ModelConfig.

        The following fields are duplicated between ``ModelConfig`` and ``TrainConfig`` but ``ModelConfig`` is the
        authoritative source (Item #3, v1.7.0).  Setting them on ``TrainConfig`` is deprecated.  The fields will be
        removed in v1.9.0.

        - ``group_detr``: query group count is an architecture decision → ``ModelConfig``
        - ``ia_bce_loss``: loss type is tied to architecture family → ``ModelConfig``
        - ``segmentation_head``: architecture flag → ``ModelConfig``
        - ``num_select``: postprocessor count is an architecture decision → ``ModelConfig``
        )r   r   r   rt   zTrainConfig.z? is deprecated since v1.7.0 and will be removed in v1.9.0. Set z on ModelConfig instead.r   r   r   )r\   _deprecatedfields      r    $_warn_deprecated_train_config_fieldsz0TrainConfig._warn_deprecated_train_config_fields  s[     W  		E--- "5' * '!9;& 				 r   r:   rU   c                 2    t        |t              r|rdS dS |S )zNormalize legacy boolean progress_bar values to the new string/None representation.

        This preserves compatibility with older configs where ``progress_bar`` was a bool.
        rK  N)rE   r   rM   rU   s     r    _coerce_legacy_progress_barz'TrainConfig._coerce_legacy_progress_bar  s      eT""6,,r   c                 P    |dvr!t        j                  d|dt        d       y|S )a  Fall back to ``'auto'`` (with a warning) for an unrecognised or wrong-typed ``amp_dtype``.

        Mixed precision is a best-effort speed/memory optimisation, so an invalid request degrades to the auto-selected
        dtype rather than failing the whole training run.
        rC  zUnknown amp_dtype=zA; expected one of 'auto', 'bf16', 'fp16'. Falling back to 'auto'.r   r   r  )r   r   UserWarningrc  s     r    _coerce_amp_dtypezTrainConfig._coerce_amp_dtype  s6     00MM$UI-no
 r   r#   g?clip_max_normseedsync_bnstrategydevices	num_nodes	fp16_evalstep)ro  cosinelr_schedulerlr_min_factordont_save_weightstrain_log_sync_disttrain_log_on_stepcompute_train_metricscompute_val_losscompute_test_loss
pin_memorypersistent_workersprefetch_factorr   c                 4    |dk(  r|S |dk  rt        d      |S )z@Validate batch_size is a positive integer or the literal 'auto'.r  r   z#batch_size must be >= 1, or 'auto'.rL   rM   r   s     r    validate_batch_sizezTrainConfig.validate_batch_size+  s(     ;Hq5BCCr   c                 &    |dk  rt        d      |S )zHValidate accumulation, target-effective batch, and max targets are >= 1.r   zagrad_accum_steps, auto_batch_target_effective, and auto_batch_max_targets_per_image must be >= 1.r}  r~  s     r    validate_positive_train_stepsz)TrainConfig.validate_positive_train_steps5  s"     q5s  r   c                 J    d|cxk  rdk  st        d       t        d      |S )z.Validate auto_batch_ema_headroom is in (0, 1].r   r   z*auto_batch_ema_headroom must be in (0, 1].r}  r~  s     r    validate_ema_headroomz!TrainConfig.validate_ema_headroomA  s1     AIJJ IJJr   c                 J    d|cxk  rdk  st        d       t        d      |S )z'Validate smooth_alpha is in [0.0, 1.0).ru   r   z#smooth_alpha must be in [0.0, 1.0).r}  r~  s     r    validate_smooth_alphaz!TrainConfig.validate_smooth_alphaI  s1     q3BCC BCCr   c                 &    |dk  rt        d      |S )z"Validate interval fields are >= 1.r   zInterval fields must be >= 1.r}  r~  s     r    validate_positive_intervalsz'TrainConfig.validate_positive_intervalsQ  s     q5<==r   c                 *    ||dk  rt        d      |S )z)Validate prefetch_factor is None or >= 1.r   z+prefetch_factor must be >= 1 when provided.r}  r~  s     r    validate_prefetch_factorz$TrainConfig.validate_prefetch_factorY  s      =QUJKKr   c                     ||S t         j                  j                  t         j                  j                  t        j                  |                  S )uj   Expand and normalize dataset/output directory paths via ``os.fspath`` → ``expanduser`` → ``realpath``.)r   r   r   r   r   r~  s     r    expand_pathszTrainConfig.expand_pathsa  s:     9Hww 2 2299Q< @AAr   c                 4    ||S t        j                  |      S )a  Normalise the resume checkpoint value to ``str`` without resolving it.

        Unlike ``dataset_dir``/``output_dir``, ``resume`` is forwarded verbatim to PyTorch Lightning's
        ``trainer.fit(ckpt_path=...)``, which also accepts sentinel values such as ``"last"``. Running
        ``os.path.realpath`` would rewrite those sentinels into spurious absolute paths, so this validator only coerces
        the type (``Path`` -> ``str``) and leaves the value untouched.
        )r   r   r~  s     r    _coerce_resume_pathzTrainConfig._coerce_resume_pathi  s     9Hyy|r   )r!   r  )sr   r   r   r   r   r9   r   r^   r  r   r  r  r   r   r  r  r  r  r   r!  r
   r   r"  r#  r$  r   r&  r'  r(  r)  r*  r+  r,  r   r   r   r   rt   r   r-  r   r.  r/  r0  r1  r2  r7  r8  r;  r<  r=  r>  r?  r@  rA  rB  rF  rG  rH  rI  rJ  rM  rN  rO  rP  rQ  rR  r-   rS  rT  rU  r   rV  rW  rX  rY  r   r   r[  r\  r]  r   ra  r   r_   rd  rg  r#   rh  ri  rj  rk  rl  r   rm  rn  rq  rr  rs  rt  ru  rv  rw  rx  ry  rz  r{  r  r  r  r  r  r  r  r  r   r   r    r  r  w  sa    *4(X\)]L(:&]BJ()Jgfo%)c')),/$c/%(U(FC$(FH[!(IuGSGS$RA66!!2c2L%M5 ## ##IuJKM5J%*4%@c@#$5$)**())$%E%.2et+2@JL'<=J!%$%+&&&J&K OT ). $.GT  KL%16Q	2Iw-. 	 !ND #%S%&+e+#(D(6:L(7>23:KE4FDGT!GXc]!C#'+K$s)$+Hd#t#M3M3"&4&+/Jc3h(/:?'"67?$$ 0	E8C= 	 '" #2 ^(3    4 [x0c c   1$ KM5D(3-GT Hc GU38_  IsIt.4L'*+4M5#t# %%#t#"'4'!d!"t"!%J%)--%)OXc])\0C'&/$9 cGFO>S   1 9;]dk c c   .W=e    > ^'2e    3 *O'JC C   K &W5# 8C=   6 ]Lx@B[4/ BC$J B  AB XH-
K$$6 
3: 
  .
r   r  c                   l    e Zd ZU dZdZee   ed<   dZeed<   dZ	e
ed<   dZe
ed<   d	Ze
ed
<   dZeed<   y)SegmentationTrainConfiga  Training configuration for instance segmentation models.

    Extends :class:`TrainConfig` with segmentation-specific loss coefficients.

    Attributes:
        num_select: Maximum number of predictions to keep per image. ``None`` uses
            the model default.
        mask_point_sample_ratio: Number of points sampled per mask for point-based
            mask loss computation.
        mask_ce_loss_coef: Cross-entropy loss weight for mask prediction.
        mask_dice_loss_coef: Dice loss weight for mask prediction.
        cls_loss_coef: Classification loss weight. Defaults to ``1.0`` to match the
            effective pre-v1.7 value (the v1.7 TrainConfig ownership migration
            silently activated a dormant ``5.0``; this field restores the correct
            weight). To reproduce pre-fix segmentation behaviour pass
            ``cls_loss_coef=5.0`` explicitly.
        segmentation_head: Whether to attach the segmentation head.
    Nrt   r   mask_point_sample_ratiog      @mask_ce_loss_coefmask_dice_loss_coefr   r   Tr   )r   r   r   r   rt   r
   r   r^   r  r  r   r  r   r   r   r   r   r    r  r  x  sM    & !%J$#%S%"u"!$$M5"t"r   r  c                       e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	eed<   dZ
eed	<   d
Zeed<    edd      Zeed<   y)KeypointTrainConfigaE  Training configuration for keypoint detection models.

    Extends :class:`TrainConfig` with keypoint-specific loss coefficients and
    metric-smoothing defaults tuned for the NLL-Cholesky keypoint head, which
    produces noisy per-epoch OKS metrics during early fine-tuning.

    Attributes:
        cls_loss_coef: Classification loss weight.
        keypoint_l1_loss_coef: L1 regression loss weight for keypoint coordinates.
        keypoint_findable_loss_coef: Loss weight for the keypoint visibility head.
        keypoint_visible_loss_coef: Loss weight for the keypoint visibility score.
        keypoint_nll_loss_coef: NLL-Cholesky loss weight. Restored to ``1.0`` to
            align with the other keypoint loss terms (``keypoint_l1_loss_coef``,
            ``keypoint_findable_loss_coef``, ``keypoint_visible_loss_coef``).
            Previously set to ``0.5`` to dampen OKS@75 oscillation; reverted as
            the under-weighting was not beneficial in practice.
        smooth_alpha: EMA smoothing factor for :class:`BestModelCallback` metric
            comparison. Overrides the :class:`TrainConfig` default of ``0.0``
            (disabled) to ``0.5``, which balances responsiveness and noise
            suppression for noisy keypoint mAP curves.
        skip_best_epochs: Number of epochs to skip before checkpoint selection begins.
            Overrides the :class:`TrainConfig` default of ``0`` to ``10`` because
            ``val/keypoint_map_50_95`` under the NLL-Cholesky loss is noisy in early
            fine-tuning and can lock checkpoint selection to a transient peak.
    g       @r   r   r.  r/  r0  r   r1  g      ?r(  r%  r   rv   r'  N)r   r   r   r   r   r   r^   r.  r/  r0  r1  r(  r   r'  r   r   r   r    r  r    s[    4 M5#$5$)**())$'E'L%!"3c3r   r  )2r   r   pathlibr   typingr   r   r   r   r   r	   r
   r   r   r*   pydanticr   r   r   r   r   pydantic_corer   r   r^   r-   r   rf  r   r1   r2   r4   rb   r   r   r   r   r   r   r   r   r  r  r	  r  r  r  r  r  r  r   r   r    <module>r     sl   
   Z Z Z  S S + !stY ttY #+ # #L  : :B{E* {E|	'{ '(	B"2 	B	A' 	A	B( 	B	C) 	C .- * + , + , - "2 ,~* ~B#k #8!4+ !4r   