§
    ­¸je"  ã                  óÌ   — d Z ddlmZ dgZddlmZ ddl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 dd
l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œdd„ZdS )z=ModelContext and model-context builder for RF-DETR inference.é    )ÚannotationsÚModelContext)ÚCallable)ÚTYPE_CHECKINGÚAnyÚcastN)ÚTrainConfig)ÚPostProcessÚbuild_model)ÚBackbone)ÚLWDETR)Ú
apply_loraÚload_pretrain_weights)ÚModelConfigc                  ó&   — e Zd ZdZ	 ddd„Zdd„ZdS )r   a  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 ``LWDETR`` module. The attribute is cleared to ``None`` by
            :meth:`RFDETR.inference` when called with ``inplace=True``, which frees the
            weights from memory.
        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 of resolved training/model configuration.
        class_names: Optional list of class name strings loaded from checkpoint.
    NÚmodelr   Úpostprocessr
   Údeviceútorch.deviceÚ
resolutionÚintÚargsr   Úclass_namesúlist[str] | NoneÚreturnÚNonec                óh   — || _         || _        || _        || _        || _        || _        d | _        d S ©N)r   r   r   r   r   r   Úinference_model)Úselfr   r   r   r   r   r   s          ú`/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/inference.pyÚ__init__zModelContext.__init__,   s>   € ð %*ˆŒ
Ø&ˆÔØˆŒØ$ˆŒØˆŒ	Ø&ˆÔØ#ˆÔÐÐó    Únum_classesc                ó”   — | j         €t          d¦  «        ‚t          d| j         j        ¦  «        } ||¦  «         || j        _        dS )a$  Reinitialize the detection head for a different number of classes.

        Args:
            num_classes: New number of output classes (including background).

        Raises:
            RuntimeError: If the model weights were already cleared by ``RFDETR.inference(inplace=True)``.
        Nz…Cannot reinitialize the detection head after inplace optimization. The original model has been cleared. Create a new RFDETR instance.zCallable[[int], None])r   ÚRuntimeErrorr   Úreinitialize_detection_headr   r$   )r    r$   Úreinitialize_heads      r!   r'   z(ModelContext.reinitialize_detection_head=   s]   € ð Œ:ÐÝðUñô ð õ !Ð!8¸$¼*Ô:`ÑaÔaÐØÐ˜+Ñ&Ô&Ð&Ø +ˆŒ	ÔÐÐr#   r   )r   r   r   r
   r   r   r   r   r   r   r   r   r   r   )r$   r   r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r"   r'   © r#   r!   r   r      sP   € € € € € ðð ð. )-ð$ð $ð $ð $ð $ð",ð ,ð ,ð ,ð ,ð ,r#   Únum_channelsr   Úconv_weightútorch.Tensorr   c                ó¼   — | dk    r|S | dk    r|                      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é   )r4   Ng      @)ÚmeanÚtorchÚcat)r.   r/   ÚrepeatsÚ
weight_outs       r!   Ú_adapt_input_convr<   S   sŠ   € ð �qÒÐØÐØ�qÒÐØ×Ò A¨tÐÑ4Ô4Ð4à˜aÑ AÑ%€GÝ”˜K˜=¨7Ñ2¸Ð:Ñ:Ô:¸1¸1¸1¸m¸|¸mÐ;KÔL€JØ˜s \Ñ1Ñ2€JØÐr#   F)Útrust_checkpointÚmodel_configr   r=   Úboolc          	     óø  — ddl m} t          dd¬¦  «        } || |¦  «        }d|_        d|_        t          |¦  «        }t          |t          ¦  «        s
J d¦   «         ‚g }| j        �™t          || |¬¦  «        }t          |d¦  «        r|j        | j        k    r| j        |_        t          t          | d	g ¦  «        pg ¦  «        }t          |d	¦  «        r+t          t          |d	g ¦  «        pg ¦  «        |k    r||_        | j        rt!          |¦  «         | j        d
k    rïddl}t'          t(          |j        d         ¦  «        }	|	j        j        j        j        j        }
|                     |
¦  «        }| j        |_        t9          | j        |
j        ¦  «        }t<          j                              |¦  «        |_        |
j        j!        |j        _!        ||	j        j        j        j        _        | j        |	j        j        j        j        _        t=          j"        |j"        ¦  «        }tG          |j$        t          |d	g ¦  «        t          |dd¦  «        ¬¦  «        }tK          |||| j&        ||pd¬¦  «        S )u<  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()`` / ``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.
        trust_checkpoint: Forwarded to :func:`~rfdetr.models.weights.load_pretrain_weights` as its
            ``trust`` argument â€” set ``True`` only when ``model_config.pretrain_weights`` is a
            checkpoint the caller explicitly trusts (mirrors ``RFDETR.from_checkpoint(...,
            trust_checkpoint=True)``).

    Returns:
        ModelContext with the model on CPU, ready for lazy device placement.
    r   )Ú_namespace_from_configsNÚoutput)Údataset_dirÚ
output_dirz_build_model() returned a non-LWDETR result even though encoder_only/backbone_only were not set.)Útrustr$   Únum_keypoints_per_classr2   Úpostprocess_trace_alphagš™™™™™É?)Ú
num_selectrF   Útrace_alpha)r   r   r   r   r   r   )'Úrfdetr._namespacerA   r	   rC   rD   r   Ú
isinstancer   Úpretrain_weightsr   Úhasattrr$   ÚlistÚgetattrrF   Úbackbone_lorar   r.   Úcopyr   r   ÚbackboneÚencoderÚ
embeddingsÚpatch_embeddingsÚ
projectionÚdeepcopyÚin_channelsr<   Úweightr8   ÚnnÚ	ParameterÚrequires_gradr   r
   rH   r   r   )r>   r=   rA   Údummy_train_configr   Únn_modelr   Ú_mc_kprQ   rR   ÚprojÚnew_projÚ
new_weightr   r   s                  r!   Ú_build_model_contextrc   m   s“  € ð& :Ð9Ð9Ð9Ð9Ð9õ %°À(ÐKÑKÔKÐØ"Ð" <Ð1CÑDÔD€Dð €DÔØ€D„OÝ˜4Ñ Ô €HÝ�h¥Ñ'Ô'ð ð Øiñô Ð'ð  €KØÔ$Ð0Ý+¨H°lÐJZÐ[Ñ[Ô[ˆõ �4˜Ñ'Ô'ð 	8¨DÔ,<ÀÔ@XÒ,XÐ,XØ+Ô7ˆDÔÝ•g˜lÐ,EÀrÑJÔJÐPÈbÑQÔQˆå�DÐ3Ñ4Ô4ð	2å•W˜TÐ#<¸bÑAÔAÐGÀRÑHÔHÈFÒRÐRà+1ˆDÔ(àÔ!ð Ý�8ÑÔÐð Ô  AÒ%Ð%Øˆˆˆå� (Ô"3°AÔ"6Ñ7Ô7ˆØÔÔ'Ô2ÔCÔNˆØ—=’= Ñ&Ô&ˆØ+Ô8ˆÔÝ& |Ô'@À$Ä+ÑNÔNˆ
Ýœ(×,Ò,¨ZÑ8Ô8ˆŒØ(,¬Ô(AˆŒÔ%ØJRˆÔÔ Ô+Ô<ÔGØLXÔLeˆÔÔ Ô+Ô<ÔIåŒ\˜$œ+Ñ&Ô&€Fõ Ø”?Ý '¨Ð.GÈÑ LÔ Lå˜DÐ";¸SÑAÔAð	ñ ô €Kõ ØØØØÔ*ØØÐ' 4ðñ ô ð r#   )r.   r   r/   r0   r   r0   )r>   r   r=   r?   r   r   )r,   Ú
__future__r   Ú__all__Úcollections.abcr   Útypingr   r   r   r8   Úrfdetr.configr	   Úrfdetr.modelsr
   r   Úrfdetr.models.backbone.backboner   Úrfdetr.models.lwdetrr   Úrfdetr.models.weightsr   r   r   r   Ú_ModelContextr<   rc   r-   r#   r!   ú<module>rn      s\  ðð DÐ Cà "Ð "Ð "Ð "Ð "Ð "àÐ
€à $Ð $Ð $Ð $Ð $Ð $Ø +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +à €€€à %Ð %Ð %Ð %Ð %Ð %Ø 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ð 2Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ø CÐ CÐ CÐ CÐ CÐ CÐ CÐ Càð *Ø)Ð)Ð)Ð)Ð)Ð)ð2,ð 2,ð 2,ð 2,ð 2,ñ 2,ô 2,ð 2,ðj €ðð ð ð ð4 QVð Wð Wð Wð Wð Wð Wð Wð Wr#   