
    ^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)zReinitialize 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

Li8j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At44aA%GK=72:1m|m;KLJs\12J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DD4 HK$$0+HlC 4'GD-,HLLdLd,d+77Dgl,ErJPbQD34WT#<bAGRHFR+1D(!!8   A%  #++33>>OOZZ==&+88&|'@'@$++N
((,,Z8(,(A(A%V^!$$,,77HHSXdXqXq!$$,,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   