Ë
    ëÓ^jÞ{  ã                  óN  — U d Z ddlmZ ddlZddlZddlmZmZ ddlZddl	m
c mZ ddlmZmZ ddlmZmZ ddlmZ ddlmZ dd	lmZmZmZ  e«       Zg d
¢ZdZdZded<   	 	 	 	 	 	 	 	 	 	 	 	 dd„Z dd„Z!dd„Z"	 	 	 	 	 	 dd„Z# edddiddd¬«      	 d	 	 	 	 	 	 	 d d„«       Z$d!d„Z%y)"a8  Shared weight-loading and LoRA application utilities.

Provides the canonical implementations of pretrained checkpoint loading and LoRA adapter injection, used by both the L1
inference facade (``rfdetr.detr``) and the L2 LightningModule (``rfdetr.training.module_model``).

The weight-loading logic is taken from ``RFDETRModelModule._load_pretrain_weights`` in ``module_model.py`` (more
complete: Pydantic-aware user-override detection, auto-alignment for fine-tuned checkpoints) and augmented with class-
name extraction from ``detr.py:_load_pretrain_weights_into``.
é    )ÚannotationsN)ÚAnyÚList)Údownload_pretrain_weightsÚvalidate_pretrain_weights)ÚModelConfigÚTrainConfig)Ú
deprecated)Ú
get_logger)Ú_ckpt_args_getÚremap_projector_to_cross_attnÚ!validate_checkpoint_compatibility)Úload_pretrain_weightsÚ
apply_loraÚinterpolate_position_embeddingszembeddings.position_embeddings)zrefpoint_embed.weightzquery_feat.weightztuple[str, ...]Ú_QUERY_PARAM_SUFFIXESc                ó¬  — |dk  s|dk  s
|dk  s|dk  rt        d|› d|› d|› d|› d�	«      ‚||z  }| j                  d   |k7  r.t        j                  d|||| j                  d   «       | d||z   S ||k(  r||k(  r| S t	        ||«      }t	        ||«      }t        |«      D �cg c]  }| ||z  ||z  |z    ‘Œ }	}t        j                  |	d¬	«      S c c}w )
u˜	  Slice a ``refpoint_embed`` / ``query_feat`` weight preserving per-group structure.

    ``LWDETR`` packs query embeddings as ``nn.Embedding(num_queries * group_detr, ...)`` where group ``g`` occupies the
    contiguous slot range ``[g * num_queries, (g + 1) * num_queries)`` (see ``LWDETR.__init__`` and ``LWDETR.forward``
    in ``models/lwdetr.py``).  When ``num_queries`` decreases and ``group_detr > 1``, a flat ``tensor[:
    target_num_queries * target_group_detr]`` slice silently scrambles groups: the tail of group 0 winds up in what
    should be group 1's slots, and so on.  At inference only group 0 is read so the bug is invisible, but for
    training-resume it corrupts groups 1+.

    This helper does the right thing per group:

    * ``num_queries`` decrease (``target_num_queries < ckpt_num_queries``) â†’
      keep the first ``target_num_queries`` slots of each retained group.
    * ``group_detr`` decrease (``target_group_detr < ckpt_group_detr``) â†’
      drop tail groups; retained groups stay pretrained.
    * Either dimension expands, or one shrinks while the other expands â†’
      return whatever per-group sub-tensor can be built (``min(target, ckpt)`` along each axis). The result has fewer
      rows than the model expects, so ``load_state_dict`` will raise a shape mismatch immediately.

    When the tensor's flat length disagrees with ``ckpt_num_queries * ckpt_group_detr`` (corrupt or unexpected
    checkpoint shape), fall back to the legacy flat slice so loading continues with the same behavior the codebase had
    before this fix.

    Args:
        tensor: The checkpoint tensor for ``refpoint_embed.weight`` or
            ``query_feat.weight``.
        ckpt_num_queries: ``num_queries`` recorded in the checkpoint's training args.
        ckpt_group_detr: ``group_detr`` recorded in the checkpoint's training args.
        target_num_queries: ``num_queries`` configured for the model.
        target_group_detr: ``group_detr`` configured for the model.

    Returns:
        A tensor whose layout matches the model's configured packing for the decrease-or-equal cases, or a per-group
        sub-tensor built from ``min(target, ckpt)`` along each axis for the expansion case (which ``load_state_dict``
        will then reject on shape mismatch).

    Raises:
        ValueError: If any of ``ckpt_num_queries``, ``ckpt_group_detr``,
            ``target_num_queries``, or ``target_group_detr`` is â‰¤ 0.
    r   zX_slice_query_param_per_group: all dimension args must be positive; got ckpt_num_queries=z, ckpt_group_detr=z, target_num_queries=z, target_group_detr=ú.u²   _slice_query_param_per_group: checkpoint args claim %d Ã— %d = %d rows but tensor has %d rows; falling back to flat slice. Per-group structure may be scrambled if group_detr > 1.N©Údim)Ú
ValueErrorÚshapeÚloggerÚwarningÚminÚrangeÚtorchÚcat)
ÚtensorÚckpt_num_queriesÚckpt_group_detrÚtarget_num_queriesÚtarget_group_detrÚexpected_totalÚkeep_groupsÚkeep_per_groupÚgÚpiecess
             ú`/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/models/weights.pyÚ_slice_query_param_per_groupr*   *   s7  € ð^ ˜1Ò °1Ò 4Ð8JÈaÒ8OÐSdÐhiÒSiÜð$Ø$4Ð#5Ð5GÈÐGXð Y"Ø"4Ð!5Ð5IÐJ[ÐI\Ð\]ð_ó
ð 	
ð &¨Ñ7€NØ‡|�|�A�˜.Ò(ä�‰ð2ð ØØØ�L‰L˜‰Oô	
ð Ð>Ð*Ð->Ñ>Ð?Ð?àÐ-Ò-Ð2CÀÒ2VØˆäÐ'¨Ó9€KÜÐ+Ð-=Ó>€NÜ\aÐbmÓ\nÖoÐWXˆf�QÐ)Ñ)¨AÐ0@Ñ,@À>Ñ,QÒRÐo€FÐoÜ�9‰9�V Ô#Ð#ùò ps   Â#Cc                ój   ‡— ddgt         ¢d‘d‘­Šdˆfd„}| D �cg c]  } ||«      rŒ|‘Œ c}S c c}w )u;  Return *keys* with intentional-reinit/trim entries removed.

    Matching is boundary-aware: a pattern matches a key when the pattern appears at the start of the key or immediately
    after a module separator (``.``).  This prevents substring collisions where a pattern like ``"class_embed."`` would
    inadvertently match a key belonging to an unrelated module (e.g. ``"class_embed_projection.weight"`` is safe because
    ``class_embed_projection.`` â‰  ``class_embed.``, but using a plain ``in`` check against longer ambiguous strings is
    fragile by design).
    zclass_embed.zbbox_embed.zenc_out_class_embed.zenc_out_bbox_embed.c                ó.   •‡ — t        ˆ fd„‰D «       «      S )Nc              3  óR   •K  — | ]  }‰j                  |«      xs d |› �‰v –— Œ  y­w)r   N)Ú
startswith)Ú.0ÚpatÚkeys     €r)   ú	<genexpr>zD_filter_intentional_keys.<locals>._is_intentional.<locals>.<genexpr>Ž   s-   øè ø€ Ò[¸s�3—>‘> #Ó&Ò:¨A¨c¨U¨)°sÐ*:Ó:Ñ[ùs   ƒ$')Úany)r1   Úintentional_patternss   `€r)   Ú_is_intentionalz1_filter_intentional_keys.<locals>._is_intentional�   s   ù€ ÜÓ[ÐFZÔ[Ó[Ð[ó    )r1   ÚstrÚreturnÚbool)r   )Úkeysr5   Úkr4   s      @r)   Ú_filter_intentional_keysr<   w   sT   ø€ ð 	Øð-ô 
ð-ð 	ð	-ð
 	ñ-Ðõ\ð Ö6�!¡?°1Õ#5ŠAÒ6Ð6ùÒ6s   ›0©0c                óŠ  — t        | dd«      }t        | dd«      }	 |r|D �cg c]  }t        |«      ‘Œ c}ng }|r|D �cg c]  }t        |«      ‘Œ c}ng }t        |«      }t        |«      }|s|syg }	|rGdj	                  |dd «      }
t        |«      dkD  r|
dz  }
|	j                  t        |«      › d|
› d�«       |rGdj	                  |dd «      }
t        |«      dkD  r|
dz  }
|	j                  t        |«      › d	|
› d�«       t        j                  d
|dj	                  |	«      «       yc c}w c c}w # t        $ r Y yw xY w)uP  Emit a ``logger.warning`` when ``load_state_dict`` left non-trivial gaps.

    ``load_state_dict(strict=False)`` silently ignores keys that the model has but the checkpoint does not
    (``missing_keys``) and keys present in the checkpoint but absent from the model (``unexpected_keys``).  When this
    happens for parameters outside the head / query embeddings â€” which the loader intentionally reinitialises or trims â€”
    the corresponding model weights were left at their random initial values and the user is silently getting a much
    weaker model. This helper surfaces that condition with a single, actionable warning. Same-key shape mismatches do
    not reach this function â€” they raise :class:`RuntimeError` directly from ``load_state_dict`` and are therefore
    impossible to miss.

    Args:
        incompatible: The ``_IncompatibleKeys`` namedtuple returned by
            :meth:`torch.nn.Module.load_state_dict`.
        pretrain_weights_path: Path to the checkpoint that was loaded; included
            in the warning so the user can identify which load partially succeeded.
    Úmissing_keysNÚunexpected_keysz, é   z, ...z> model parameter(s) not in checkpoint (left at random init): [ú]z+ checkpoint key(s) not consumed by model: [uü   Pretrained weights at %r loaded only partially â€” this typically produces lower accuracy. %s. Check that the model configuration (encoder, hidden_dim, out_feature_indexes, projector_scale, ...) matches the architecture the checkpoint was trained with.ú )	Úgetattrr7   Ú	TypeErrorr<   ÚjoinÚlenÚappendr   r   )ÚincompatibleÚpretrain_weights_pathÚmissing_keys_rawÚunexpected_keys_rawr;   r>   r?   ÚmissingÚ
unexpectedÚpartsÚsamples              r)   Ú_warn_on_partial_loadrP   “   sW  € ô" ˜|¨^¸TÓBÐÜ! ,Ð0AÀ4ÓHÐðÙ=MÐ(8Ö9 1œ˜A�Ó9ÐSUˆÙCVÐ+>Ö? aœ3˜q�6Ó?Ð\^ˆô ' |Ó4€GÜ)¨/Ó:€JÙ™:Øà€EÙØ—‘˜7 2 A˜;Ó'ˆÜˆw‹<˜!ÒØ�gÑˆFØ�‰œ˜G›�~Ð%cÐdjÐckÐklÐmÔnÙØ—‘˜: b q˜>Ó*ˆÜˆz‹?˜QÒØ�gÑˆFØ�‰œ˜J›Ð(Ð(SÐTZÐS[Ð[\Ð]Ô^ä
‡N�Nð	'ð 	Ø�‰�‹õùò- :ùÚ?øÜò áðús,   œD6 ¢D,´D6 ¿D1ÁD6 Ä,
D6 Ä6	EÅEc           
     óÔ  — ||z  }| D �cg c]  }|j                  t        «      sŒ|‘Œ }}|D �]³  }| |   }|j                  d   dz
  }||k(  rŒ!t        t	        j
                  |«      «      }t        t	        j
                  |«      «      }	||z  |k7  s|	|	z  |k7  r t        j                  d|› d|› d|› d�«       Œ�|j                  d   }
|dd…dd…f   }|dd…dd…f   }|j                  d|||
«      j                  dd	dd
«      }t        j                  |j                  «       |	|	fdd|j                  j                  dk7  ¬«      j                  |j                   «      }|j                  dd
d	d«      j                  d||
«      }t#        j$                  ||gd¬«      | |<   t        j'                  d|t)        |j                  «      t)        | |   j                  «      «       �Œ¶ yc c}w )ut  Interpolate DINOv2 positional embeddings in *checkpoint_state* to match *pe_size*.

    When the model is configured with a custom ``resolution`` that differs from the checkpoint's training resolution,
    the DINOv2 backbone's ``position_embeddings`` parameter has an incompatible shape.
    ``load_state_dict(strict=False)`` does **not** skip shape mismatches on matching keys â€” it raises ``RuntimeError``.

    This function bicubic-interpolates every PE tensor in the checkpoint whose shape differs from the target grid,
    modifying *checkpoint_state* in-place before ``load_state_dict`` is called.

    Args:
        checkpoint_state: The ``"model"`` sub-dict from a loaded checkpoint.
        pe_size: Target grid side length in patches (number of patches per spatial
            dimension, assuming a square grid).  Typically ``model_config.positional_encoding_size``.
    é   zSkipping PE interpolation for z,: grid size is not a perfect square (source z	, target z).éÿÿÿÿNr   é   é   ÚbicubicFÚmps)ÚsizeÚmodeÚalign_cornersÚ	antialiasr   u1   Interpolated positional embeddings %s: %s â†’ %s.)ÚendswithÚ_PE_KEY_SUFFIXr   ÚintÚmathÚisqrtr   r   ÚreshapeÚpermuteÚFÚinterpolateÚfloatÚdeviceÚtypeÚtoÚdtyper   r   ÚdebugÚtuple)Úcheckpoint_stateÚpe_sizeÚn_targetr;   Úpe_keysr1   Úckpt_peÚn_sourceÚh_srcÚh_tgtr   Úclass_tokenÚpatch_pes                r)   r   r   Ç   sì  € ð$ ˜Ñ €Hà*ÖI�Q¨a¯j©j¼Õ.HŠqÐI€GÐIØó #
ˆØ" 3Ñ'ˆØ—=‘= Ñ# aÑ'ˆØ�xÒØä”D—J‘J˜xÓ(Ó)ˆÜ”D—J‘J˜xÓ(Ó)ˆØ�5‰=˜HÒ$¨°©¸Ò(AÜ�N‰NØ0°°ð 6>Ø>F¸ZÀyÐQYÐPZÐZ\ð^ôð à�m‰m˜BÑˆØša  ! ˜e‘nˆØš1˜a™b˜5‘>ˆà×#Ñ# A u¨e°SÓ9×AÑAÀ!ÀQÈÈ1ÓMˆÜ—=‘=Ø�N‰NÓØ˜�ØØØ—o‘o×*Ñ*¨eÑ3ô
÷ ‰"ˆW�]‰]Ó
ð 	ð ×#Ñ# A q¨!¨QÓ/×7Ñ7¸¸8ÀSÓIˆä %§	¡	¨;¸Ð*AÀqÔ IÐ˜ÑÜ�‰Ø?ØÜ�'—-‘-Ó ÜÐ" 3Ñ'×-Ñ-Ó.ö		
ñ=#
ùò Js
   ŠG%¥G%TÚtrain_configz1.7.0z1.9.0rS   )ÚtargetÚargs_mappingÚdeprecated_inÚ	remove_inÚ	num_warnsc           	     óÌ  ‡— |}|j                   }|€g S g }t        |«       t        j                  j	                  |«      s#t
        j                  d«       t        |dd¬«       t        |d¬«       	 t        j                  |dd¬«      }d
|vr¤d|v r t
        j                  d«       d}d}i }	|d   j                  «       D ]I  \  }
}|
j                  |«      sŒ|
t        |«      d }|j                  |«      r|t        |«      d }||	|<   ŒK |	st!        d|›d�«      ‚|	|d
<   d|vrd|v r|d   |d<   d|v rQt#        |d   d«      }|r@t%        |t&        «      r|g}n,	 t)        |«      }|D �cg c]  }t%        |t&        «      sŒ|‘Œ }}t-        ||«       dt/        |dt1        «       «      v }|j2                  }|d
   d   j4                  d   }|dz   }||k7  r&||k  r|s|dz
  }|}||_        | j7                  |«       |j9                  d«      }|�t#        |d«      nd}|�t#        |d«      nd}	 |�t;        |«      nd}|�t;        |«      nd}|du |du k7  r‹t=        d„ |d
   D «       d«      }|�s|d
   |   j4                  d   }d}|�|dkD  r||z  dk(  r||z  }d|d|f\  }}}}n|�|dkD  r||z  dk(  r||z  }d|d|f\  }}}}|�t
        j                  d|||«       |j>                  dkD  r$|�|€ t
        j                  d|j>                  «       tA        |d
   jC                  «       «      D ]t  ŠtE        ˆfd„tF        D «       «      sŒ|d
   ‰   }|�-|�+tI        ||||jJ                  |j>                  ¬ «      |d
   ‰<   ŒS|d|jJ                  |j>                  z   |d
   ‰<   Œv tM        |d
   | «      |d
<   d!t/        |dt1        «       «      v } | �s8t/        |d"d«      �r*tO        |d!«      �r|d
   j9                  d#«      }!t%        |!t        jP                  «      r¬|!jR                  d$k(  r�|!jU                  d¬%«      jW                  «       D �"cg c]  }"t;        |"«      ‘Œ }#}"tA        t/        |d!g «      xs g «      }$tE        d&„ |#D «       «      st
        j                  d'|#«       ng|#|$k7  rbt
        j                  d(|$|#«       |#|_,        nCt%        |!t        jP                  «      r)t
        j                  d)t[        |!j4                  «      «       tA        t/        |d!g «      xs g «      }%d}&d}'t/        |d"d«      r�tO        | d*«      ru| j]                  |d
   «      }&|&r_t/        | d+d«      }(t_        |(«      r |(«       n|%})|&|)k7  r9tO        | d,«      r-t
        j                  d-|)|&«       | ja                  |&«       |&|%k7  }'|d
   j9                  d#«      }*tO        | d«      r| jc                  «       ni }+t%        |+td        «      r|+j9                  d#«      nd},t%        |*t        jP                  «      r‡t%        |,t        jP                  «      rm|*j4                  |,j4                  k7  rT|'sRt
        j                  d.t[        |*j4                  «      t[        |,j4                  «      «       |d
   jg                  d#d«       ti        |d
   |jj                  «       | jm                  |d
   d¬«      }-to        |-|«       |'r3tO        | d,«      r't
        j                  d/|%«       | ja                  |%«       ||k  r|r| j7                  |«       |dz   |k  r| j7                  |dz   «       |S # t        $ r? t
        j                  d	«       t        |dd¬«       t        j                  |dd¬«      }Y �Œw xY wc c}w # t*        $ r g }Y �Œ(w xY w# t*        t         f$ r t
        j                  d«       d}d}Y �Œ“w xY wc c}"w )0uó  Load pretrained checkpoint weights into *nn_model* in-place.

    Canonical implementation shared by the L1 facade (``_build_model_context`` in ``rfdetr.detr``) and the L2
    LightningModule (``RFDETRModelModule.__init__`` in ``rfdetr.training.module_model``).

    Uses the Pydantic-aware logic from ``module_model.py``:

    - When the user did **not** explicitly set ``num_classes`` (it is left unset),
      the checkpoint class count is treated as authoritative and the model head is auto-aligned to it.
    - When the user **did** explicitly set ``num_classes`` (to any value, including the
      class default) larger than the checkpoint provides, the head is temporarily aligned to the checkpoint for
      loading, then expanded back to the configured size.
    - When the checkpoint has more classes than configured (backbone-pretrain
      scenario), both reinitializations are applied: expand to checkpoint size for loading, then trim to configured
      size.

    Class names stored in the checkpoint ``args`` are extracted and returned.

    Args:
        nn_model: The model whose weights will be updated in-place.
        model_config: Pydantic ``ModelConfig`` instance. Must have
            ``pretrain_weights``, ``num_classes``, ``num_queries``, and ``group_detr`` attributes.
        train_config: Deprecated since v1.7.0 â€” no longer used internally.
            Passing a non-``None`` value emits a ``DeprecationWarning``.
            Omit the argument; it will be removed in v1.9.0.

    Returns:
        List of class name strings from the checkpoint, or an empty list if none are present or if
        ``model_config.pretrain_weights`` is ``None``.

    Raises:
        Exception: If the checkpoint file cannot be loaded even after a re-download.
    NzSPretrain weights not found after initial download; retrying without MD5 validation.TF)Ú
redownloadÚvalidate_md5)ÚstrictÚcpu)Úmap_locationÚweights_onlyz/Failed to load pretrain weights, re-downloadingÚmodelÚ
state_dictz=Normalizing PTL .ckpt checkpoint format (state_dict -> model)zmodel.z
_orig_mod.zThe checkpoint at zÚ appears to be in PyTorch Lightning format ('state_dict' key present, 'model' key absent), but 'state_dict' contains no keys with the expected 'model.' prefix. The checkpoint may be corrupt or in an unsupported format.ÚargsÚhyper_parametersÚclass_namesÚnum_classesÚmodel_fields_setzclass_embed.biasr   rR   Únum_queriesÚ
group_detrz}load_pretrain_weights: checkpoint args.num_queries / args.group_detr not coercible to int; falling back to legacy flat slice.c              3  óT   ‡K  — | ]  Št        ˆfd „t        D «       «      sŒ‰–— Œ! y­w)c              3  ó@   •K  — | ]  }‰j                  |«      –— Œ y ­w©N©r\   )r/   Úsr;   s     €r)   r2   z2load_pretrain_weights.<locals>.<genexpr>.<genexpr>£  s   øè ø€ Ò2`ÀQ°1·:±:¸a·=Ñ2`ùó   ƒN)r3   r   )r/   r;   s    @r)   r2   z(load_pretrain_weights.<locals>.<genexpr>£  s   øè ø€ Òa�1¬sÓ2`ÔJ_Ô2`Õ/`ŒQÑaùs   ƒ(¡(u]   load_pretrain_weights: args.%s absent; inferred ckpt_%s=%d from tensor rows %d Ã· ckpt_%s=%d.zÙload_pretrain_weights: checkpoint lacks args.num_queries / args.group_detr; falling back to flat slice. With group_detr=%d this may scramble per-group query structure if the checkpoint was trained with group_detr > 1.c              3  ó@   •K  — | ]  }‰j                  |«      –— Œ y ­wrŽ   r�   )r/   ÚxÚnames     €r)   r2   z(load_pretrain_weights.<locals>.<genexpr>Ã  s   øè ø€ Ò? Aˆt�}‰}˜Q×Ñ?ùr‘   )r    r!   r"   r#   Únum_keypoints_per_classÚuse_grouppose_keypointsÚ_kp_active_maskrU   r   c              3  ó&   K  — | ]	  }|d kD  –— Œ y­w)r   N© )r/   Úns     r)   r2   z(load_pretrain_weights.<locals>.<genexpr>ç  s   è ø€ Ò6 �q˜1•uÑ6ùs   ‚u›   load_pretrain_weights: _kp_active_mask in checkpoint has no active slots (schema=%s) â€” skipping auto-align to avoid overwriting config with empty schema.u�   load_pretrain_weights: auto-aligning num_keypoints_per_class %s â†’ %s (inferred from checkpoint _kp_active_mask; user did not set explicitly).u›   load_pretrain_weights: _kp_active_mask has unexpected shape %s (expected 2-D) â€” skipping auto-align; schema mismatch may cause APâ‰ˆ0 on keypoint models.Ú+get_num_keypoints_per_class_from_checkpointÚget_num_keypoints_per_classÚreinitialize_keypoint_headz\load_pretrain_weights: temporarily resizing keypoint schema from %s to checkpoint schema %s.z‘load_pretrain_weights: dropping checkpoint _kp_active_mask with shape %s because current model expects %s (derived from current keypoint schema).zUload_pretrain_weights: restoring configured keypoint schema %s after checkpoint load.)8Úpretrain_weightsr   ÚosÚpathÚisfiler   r   r   r   ÚloadÚ	ExceptionÚinforj   Úitemsr.   rF   r   r   Ú
isinstancer7   ÚiterrD   r   rC   Úsetrˆ   r   Úreinitialize_detection_headÚgetr^   Únextr‹   Úlistr:   r3   r   r*   rŠ   r   ÚhasattrÚTensorÚndimÚsumÚtolistr•   rk   r›   Úcallabler�   r„   ÚdictÚpopr   Úpositional_encoding_sizeÚload_state_dictrP   ).Únn_modelÚmodel_configrv   Úmcrž   r‡   Ú
checkpointÚprefixÚcompile_prefixÚmodel_stater;   ÚvÚstrippedÚraw_class_namesÚiteratorr”   Úuser_overroderˆ   Úcheckpoint_num_classesÚconfigured_num_classes_plus_bgÚ	ckpt_argsÚckpt_num_queries_rawÚckpt_group_detr_rawr    r!   Ú_first_query_keyÚ_nÚ_absentÚ	_inferredÚ_knownÚ
_known_valr   Ú_user_overrode_kp_schemaÚ_early_kp_maskrš   Ú_ckpt_kp_schemaÚ_cfg_kp_schemaÚconfigured_keypoint_schemaÚcheckpoint_keypoint_schemaÚ%should_restore_config_keypoint_schemaÚget_model_schemaÚmodel_keypoint_schemaÚckpt_kp_active_maskÚmodel_state_dictÚmodel_kp_active_maskrH   s.                  `                              r)   r   r     s¿  ø€ ðN 
€BØ×*Ñ*ÐØÐØˆ	Ø€Kô Ð.Ô/ô �7‰7�>‰>Ð*Ô+Ü�‰ÐlÔmÜ!Ð"2¸tÐRWÕXÜÐ.°uÕ=ðZÜ—Z‘ZÐ 0¸uÐSXÔYˆ
ð �jÑ  \°ZÑ%?Ü�‰ÐTÔUØˆð &ˆØˆØ˜|Ñ,×2Ñ2Ó4ò 	*‰DˆAˆqØ�|‰|˜FÕ#ØœS ›[˜]Ð+�Ø×&Ñ& ~Ô6Ø'¬¨NÓ(;Ð(=Ð>�HØ()�˜HÒ%ð	*ñ ÜØ$Ð%5Ð$8ð 9Mð Móð ð *ˆ
�7Ñð ˜Ñ#Ð(:¸jÑ(HØ!+Ð,>Ñ!?ˆJ�vÑð �ÑÜ(¨°FÑ);¸]ÓKˆÙô ˜/¬3Ô/Ø.Ð/‘ðWÜ# OÓ4�Hð
 5=Ö"V¨DÄ
È4ÔQTÕ@U¢4Ð"V�KÐ"Vä% j°"Ô5ð "¤W¨RÐ1CÄSÃUÓ%KÐK€MØ—.‘.€Kà'¨Ñ0Ð1CÑD×JÑJÈ1ÑMÐØ%0°1¡_Ð"ØÐ!?Ò?à!Ð$BÒBá ð 5°qÑ8�Ø1GÐ.Ø!,�”ð 	×,Ñ,Ð-CÔDð
 —‘˜vÓ&€IØGPÐG\œ>¨)°]ÔCÐbfÐØENÐEZœ.¨°LÔAÐ`dÐð	Ø8LÐ8Xœ3Ð3Ô4Ð^bÐØ6IÐ6Uœ#Ð1Ô2Ð[_ˆð 	˜DÐ  o¸Ð&=Ò>ÜÙa˜
 7Ñ+ÔaØó
Ðð Ð'Ø˜GÑ$Ð%5Ñ6×<Ñ<¸QÑ?ˆBØ"&ˆGØÐ+Ð0@À1Ò0DÈÐN^ÑI^ÐbcÒIcØ"$Ð(8Ñ"8�Ø9EÀÐXeÐgwÐ9wÑ6�˜ F©JØ Ð,°À1Ò1DÈÈoÑI]ÐabÒIbØ#%¨Ñ#8Ð Ø9FÐHXÐZfÐhwÐ9wÑ6�˜ F¨JØÐ"Ü—‘ØsØØØØØØôð 
‡}�}�qÒÐ.Ð6¸/Ð:QÜ�‰ð>ð �M‰Mô	
ô �Z Ñ(×-Ñ-Ó/Ó0ò UˆÜÓ?Ô)>Ô?Õ?Ø Ñ(¨Ñ.ˆFØÐ+°Ð0KÜ,HØØ%5Ø$3Ø')§~¡~Ø&(§m¡mô-�
˜7Ñ# DÒ)ð -3Ð3S°R·^±^ÀbÇmÁmÑ5SÐ,T�
˜7Ñ# DÒ)ð#Uô& 8¸
À7Ñ8KÈXÓV€JˆwÑð  9¼GÀBÐHZÔ\_Ó\aÓ<bÐbÐâ$Ü�BÐ1°5Õ9Ü�BÐ1Õ2à# GÑ,×0Ñ0Ð1BÓCˆÜ�n¤e§l¡lÔ3¸×8KÑ8KÈqÒ8PØ/=×/AÑ/AÀaÐ/AÓ/H×/OÑ/OÓ/QÖR¨!œs 1�vÐRˆOÐRÜ!¤'¨"Ð.GÈÓ"LÒ"RÐPRÓSˆNÜÑ6 oÔ6Ô6Ü—‘ðià#õð
 ! NÒ2Ü—‘ð_à"Ø#ô	ð .=�Õ*Ü˜¬¯©Ô5Ü�N‰Nð`ä�n×*Ñ*Ó+ôô "&¤g¨bÐ2KÈRÓ&PÒ&VÐTVÓ!WÐØ!%ÐØ,1Ð)ÜˆrÐ,¨eÔ4¼ØÐ?ô:ð &.×%YÑ%YÐZdÐelÑZmÓ%nÐ"Ù%Ü& xÐ1NÐPTÓUÐÜ:BÐCSÔ:TÑ$4Ô$6ÐZtÐ!Ø)Ð-BÒBÄwÈxÐYuÔGvÜ—‘ØrØ)Ø.ôð
 ×3Ñ3Ð4NÔOØ8RÐVpÑ8pÐ5ð % WÑ-×1Ñ1Ð2CÓDÐÜ07¸À,Ô0O�x×*Ñ*Ô,ÐUWÐÜFPÐQaÔcgÔFhÐ+×/Ñ/Ð0AÔBÐnrÐäÐ&¬¯©Ô5ÜÐ+¬U¯\©\Ô:Ø×%Ñ%Ð)=×)CÑ)CÒCÙ5ä�‰ðWäÐ%×+Ñ+Ó,ÜÐ&×,Ñ,Ó-ô		
ð 	�7Ñ×ÑÐ 1°4Ô8Ü# J¨wÑ$7¸×9TÑ9TÔUØ×+Ñ+¨J°wÑ,?ÈÐ+ÓN€LÜ˜,Ð(8Ô9á,´¸ÐC_Ô1`Ü�‰ØcØ&ô	
ð 	×+Ñ+Ð,FÔGð Ð >Ò>Á=Ø×,Ñ,Ð-KÔLð �Q�Ð/Ò/Ø×,Ñ,¨[¸1©_Ô=àÐøô ò ZÜ�‰ÐEÔFÜ!Ð"2¸tÐRWÕXÜ—Z‘ZÐ 0¸uÐSXÔY‹
ðZüòh #Wøô	 !ò %à"$“Kð%ûôV ”zÐ"ò Ü�‰ð9ô	
ð  ÐØ‹ðüò^ SsI   Á1] Å^  Å*^Æ ^È,^2 Ñ
_!ÝA^Þ^Þ ^/Þ.^/Þ2(_ß_c                óÐ   — 	 ddl m}m}  |dddg d¢¬«      } || j                  d   j
                  |«      | j                  d   _        y# t        $ r}t        d«      |‚d}~ww xY w)	aý  Apply LoRA adapters to the backbone encoder of *nn_model*.

    Replaces ``nn_model.backbone[0].encoder`` in-place with a PEFT-wrapped encoder using DoRA with rank 16 and alpha 16.

    Args:
        nn_model: LWDETR model whose backbone encoder will receive LoRA adapters.

    Raises:
        ImportError: If ``peft`` is not installed.
            Install via the RF-DETR extras, for example::

                pip install "rfdetr[lora]"
                # or
                pip install "rfdetr[train]"
    r   )Ú
LoraConfigÚget_peft_modelz„LoRA requires the 'peft' dependency. Install it via RF-DETR extras, e.g.: pip install "rfdetr[lora]" or pip install "rfdetr[train]".Né   T)	Úq_projÚv_projÚk_projÚqkvÚqueryr1   ÚvalueÚ	cls_tokenÚregister_tokens)ÚrÚ
lora_alphaÚuse_doraÚtarget_modules)ÚpeftrÛ   rÜ   ÚImportErrorÚbackboneÚencoder)r·   rÛ   rÜ   ÚexcÚlora_configs        r)   r   r   =  s|   € ð ß3ñ Ø
ØØò

ô	€Kñ  $2°(×2CÑ2CÀAÑ2F×2NÑ2NÐP[Ó#\€H×Ñ�aÑÕ øô/ ò ÜðIó
ð ð		ûðús   ‚A Á	A%ÁA Á A%)r   útorch.Tensorr    r^   r!   r^   r"   r^   r#   r^   r8   rð   )r:   ú	list[str]r8   rñ   )rH   r   rI   r7   r8   ÚNone)rl   r³   rm   r^   r8   rò   rŽ   )r·   útorch.nn.Moduler¸   r   rv   zTrainConfig | Noner8   z	List[str])r·   ró   r8   rò   )&Ú__doc__Ú
__future__r   r_   rŸ   Útypingr   r   r   Útorch.nn.functionalÚnnÚ
functionalrc   Úrfdetr.assets.model_weightsr   r   Úrfdetr.configr   r	   Úrfdetr.utilities.decoratorsr
   Úrfdetr.utilities.loggerr   Úrfdetr.utilities.state_dictr   r   r   r   Ú__all__r]   r   Ú__annotations__r*   r<   rP   r   r   r   r™   r6   r)   ú<module>r     s!  ðòõ #ã Û 	ß ã ß Ð ç \ß 2Ý 2Ý .ß xÑ xá	‹€â
T€à1€ð *XÐ �Ó WðJ$ØðJ$àðJ$ð ðJ$ð ð	J$ð
 ðJ$ð óJ$óZ7ó81ðh8
Øð8
àð8
ð 
ó8
ñv �4 ~°tÐ&<ÈGÐ_fÐrtÔuð (,ðwØðwàðwð %ðwð ò	wó vðwôt	)]r6   