Ë
    ëÓ^jb  ã                  ó¦   — d Z ddlmZ dgZddlmZmZmZmZm	Z	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 erdd	lmZ  G d
„ d«      ZeZdd„Zdd„Zy)z=ModelContext and model-context builder for RF-DETR inference.é    )ÚannotationsÚModelContext)ÚTYPE_CHECKINGÚAnyÚCallableÚListÚOptionalÚcastN)ÚTrainConfig)ÚPostProcessÚbuild_model)Ú
apply_loraÚload_pretrain_weights)ÚModelConfigc                  ó>   — e Zd ZdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dd„Zdd„Zy)r   as  Lightweight model wrapper returned by RFDETR.get_model().

    Provides the same attribute interface as the legacy ``main.py:Model`` but without importing or depending on
    ``populate_args()`` or the legacy stack.

    Args:
        model: The underlying ``nn.Module`` (LWDETR instance).
        postprocess: PostProcess instance for converting raw outputs to boxes.
        device: Device the model lives on.
        resolution: Input resolution (square side length in pixels).
        args: Namespace produced by :func:`build_namespace`.
        class_names: Optional list of class name strings loaded from checkpoint.
    Nc                óf   — || _         || _        || _        || _        || _        || _        d | _        y ©N)ÚmodelÚpostprocessÚdeviceÚ
resolutionÚargsÚclass_namesÚinference_model)Úselfr   r   r   r   r   r   s          ú[/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/inference.pyÚ__init__zModelContext.__init__'   s8   € ð ˆŒ
Ø&ˆÔØˆŒØ$ˆŒØˆŒ	Ø&ˆÔØ#ˆÕó    c                ó’   — t        t        t        gdf   t        | j                  d«      «      } ||«       || j
                  _        y)z¨Reinitialize the detection head for a different number of classes.

        Args:
            num_classes: New number of output classes (including background).
        NÚreinitialize_detection_head)r
   r   ÚintÚgetattrr   r   Únum_classes)r   r#   Úreinitialize_heads      r   r    z(ModelContext.reinitialize_detection_head8   s<   € ô !¤¬3¨%°¨+Ñ!6¼ÀÇ
Á
ÐLiÓ8jÓkÐÙ˜+Ô&Ø +ˆ�	‰	Õr   r   )r   ztorch.nn.Moduler   r   r   ztorch.devicer   r!   r   r   r   zOptional[List[str]]ÚreturnÚNone)r#   r!   r%   r&   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r    © r   r   r   r      sZ   „ ñð* ,0ð$àð$ð !ð$ð ð	$ð
 ð$ð ð$ð )ð$ð 
ó$ô",r   c                ó¬   — | dk(  r|S | dk(  r|j                  dd¬«      S | dz   dz  }t        j                  |g|z  d¬«      dd…d| …f   }|d| z  z  }|S )	aq  Adapt a 3-channel pretrained conv weight tensor to *num_channels* input channels.

    When ``num_channels == 3``: returns the weight unchanged. When ``num_channels == 1``: averages weights across the
    original 3 channels.
    Otherwise (``num_channels != 1`` and ``num_channels != 3``): tiles the 3-channel
    pattern and scales by ``3 / num_channels`` to preserve activation magnitude.

    Args:
        num_channels: Target number of input channels.
        conv_weight: Original weight tensor of shape ``[out_ch, 3, H, W]``.

    Returns:
        Adapted weight tensor of shape ``[out_ch, num_channels, H, W]``.
    é   é   T)ÚdimÚkeepdimé   )r/   Ng      @)ÚmeanÚtorchÚcat)Únum_channelsÚconv_weightÚrepeatsÚ
weight_outs       r   Ú_adapt_input_convr9   F   sy   € ð �qÒØÐØ�qÒØ×Ñ A¨tÐÓ4Ð4à˜aÑ AÑ%€GÜ—‘˜K˜=¨7Ñ2¸Ô:º1¸m¸|¸mÐ;KÑL€JØ˜s \Ñ1Ñ2€JØÐr   c           	     óN  — ddl m} t        dd¬«      } || |«      }t        |«      }g }| j                  �Œt        || «      }t        |d«      r*t        |d«      | j                  k7  r| j                  |_        t        t        | dg «      xs g «      }t        |d«      r$t        t        |dg «      xs g «      |k7  r||_
        | j                  rt        |«       | j                  dk7  �rRddl}|j                  d   j                   j                   j"                  j$                  j&                  }|j)                  |«      }	| j                  |	_        t-        | j                  |j.                  «      }
t0        j2                  j5                  |
«      |	_        |j.                  j6                  |	j.                  _        |	|j                  d   j                   j                   j"                  j$                  _        | j                  |j                  d   j                   j                   j"                  j$                  _        t1        j8                  |j8                  «      }t;        |j<                  t        |dg «      t        |d	d
«      ¬«      }t?        |||| j@                  ||xs d¬«      S )a  Build a ModelContext from ModelConfig without using legacy main.py:Model.

    Replicates ``Model.__init__`` logic: builds the nn.Module, optionally loads pretrain weights and applies LoRA.  The
    model is intentionally kept on CPU; :func:`_ensure_model_on_device` in ``detr.py`` performs the deferred
    ``.to(device)`` on the first ``predict()`` / ``export()`` / ``optimize_for_inference()`` call.  Keeping construction
    CPU-only prevents CUDA initialisation during ``__init__``, which would block DDP strategies (``ddp_notebook``,
    ``ddp_spawn``) from spawning child processes in notebook environments.

    Args:
        model_config: Architecture configuration.

    Returns:
        ModelContext with the model on CPU, ready for lazy device placement.
    r   )Ú_namespace_from_configsú.)Údataset_dirÚ
output_dirNr#   Únum_keypoints_per_classr-   Úpostprocess_trace_alphagš™™™™™É?)Ú
num_selectr?   Útrace_alpha)r   r   r   r   r   r   )!Úrfdetr._namespacer;   r   r   Úpretrain_weightsr   Úhasattrr"   r#   Úlistr?   Úbackbone_lorar   r5   ÚcopyÚbackboneÚencoderÚ
embeddingsÚpatch_embeddingsÚ
projectionÚdeepcopyÚin_channelsr9   Úweightr3   ÚnnÚ	ParameterÚrequires_gradr   r   rA   r   r   )Úmodel_configr;   Údummy_train_configr   Únn_modelr   Ú_mc_kprH   ÚprojÚnew_projÚ
new_weightr   r   s                r   Ú_build_model_contextr[   `   s7  € õ :ô %°ÀÔEÐÙ" <Ð1CÓD€DÜ˜4Ó €Hà€KØ×$Ñ$Ð0Ü+¨H°lÓCˆô �4˜Ô'¬G°D¸-Ó,HÈL×LdÑLdÒ,dØ+×7Ñ7ˆDÔÜ”g˜lÐ,EÀrÓJÒPÈbÓQˆä�DÐ3Ô4Ü”W˜TÐ#<¸bÓAÒGÀRÓHÈFÒRà+1ˆDÔ(à×!Ò!Ü�8Ôð × Ñ  AÓ%Ûà× Ñ  Ñ#×+Ñ+×3Ñ3×>Ñ>×OÑO×ZÑZˆØ—=‘= Ó&ˆØ+×8Ñ8ˆÔÜ& |×'@Ñ'@À$Ç+Á+ÓNˆ
ÜŸ(™(×,Ñ,¨ZÓ8ˆŒØ(,¯©×(AÑ(Aˆ�‰Ô%ØV^ˆ×Ñ˜!Ñ×$Ñ$×,Ñ,×7Ñ7×HÑHÔSØXd×XqÑXqˆ×Ñ˜!Ñ×$Ñ$×,Ñ,×7Ñ7×HÑHÔUä�\‰\˜$Ÿ+™+Ó&€Fô Ø—?‘?Ü '¨Ð.GÈÓ Lä˜DÐ";¸SÓAô	€Kô ØØØØ×*Ñ*ØØÒ' 4ôð r   )r5   r!   r6   útorch.Tensorr%   r\   )rT   r   r%   r   )r*   Ú
__future__r   Ú__all__Útypingr   r   r   r   r	   r
   r3   Úrfdetr.configr   Úrfdetr.modelsr   r   Úrfdetr.models.weightsr   r   r   r   Ú_ModelContextr9   r[   r+   r   r   ú<module>rd      sK   ðñ Då "àÐ
€ç E× Eã å %ß 2ß CáÝ)÷(,ñ (,ðV €óô4Jr   