§
    ­¸jº7  ã                  ól  — d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	m
Z
mZ ddlZddlZddlmZ ddlmZmZ dd	lmZmZmZmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddl m!Z!  e!¦   «         Z"dZ# G d„ de
¦  «        Z$ edd¬¦  «         G d„ d¦  «        ¦   «         Z%	 	 d5d6d"„Z&d7d)„Z'd8d-„Z(dd.d/d/d0œd9d4„Z)dS ):u)  Format-independent preparation of a model for export.

Every export backend needs the same graph-shaping work before it can trace anything: freeze the DINOv2 position
embeddings to the export shape, build an example input, wrap the backbone when only the encoder is wanted, decide the
graph's input/output names and dynamic axes, and run one forward pass so a broken graph fails here rather than inside a
third-party converter. Keeping that in one place is what stops the six format paths from each growing their own copy â€”
the drift that already happened once between :meth:`rfdetr.detr.RFDETR.export` and the export CLI that used to live in
``rfdetr.export.main`` (removed in v1.11).

The result is an :class:`ExportGraph`: everything a converter needs, and nothing about *which* format is being written.
é    )Úannotations)ÚMappingÚSequence)Ú	dataclass)ÚAnyÚProtocolÚcastN)ÚImage)ÚTensorÚnn)ÚComposeÚResizeÚToDtypeÚToImage)Ú	Normalize)Ú_BackboneExport)ÚBackbone)ÚDinoV2)Ú
get_loggerc                  ór   — e Zd ZdZedd„¦   «         Zedd„¦   «         Zedd„¦   «         Zedd	„¦   «         Zd
S )ÚExportModelConfigaç  The subset of a model config the export preparation reads.

    Declared structurally rather than importing :class:`~rfdetr.config.ModelConfig` so the preparation stays independent
    of how a caller assembles its configuration. The members are read-only properties rather than plain attributes: a
    mutable protocol attribute is invariant, which would reject a config that narrows one of them (``ModelConfig`` types
    *projector_scale* as ``list[Literal["P3", "P4", "P5"]]``).
    ÚreturnÚintc                ó   — dS )z,Number of input channels the model consumes.N© ©Úselfs    úe/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/export/prepare.pyÚnum_channelszExportModelConfig.num_channels9   ó   € € € ó    úSequence[Any]c                ó   — dS )uZ   Feature levels the backbone projects â€” one graph output each for a backbone-only export.Nr   r   s    r   Úprojector_scalez!ExportModelConfig.projector_scale=   r    r!   Úboolc                ó   — dS )z!Whether the model predicts masks.Nr   r   s    r   Úsegmentation_headz#ExportModelConfig.segmentation_headA   r    r!   c                ó   — dS )z%Whether the model predicts keypoints.Nr   r   s    r   Úuse_grouppose_keypointsz)ExportModelConfig.use_grouppose_keypointsE   r    r!   N)r   r   )r   r"   )r   r%   )	Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úpropertyr   r$   r'   r)   r   r!   r   r   r   0   s¢   € € € € € ðð ð ð;ð ;ð ;ñ „Xð;ð ðið ið iñ „Xðið ð0ð 0ð 0ñ „Xð0ð ð4ð 4ð 4ñ „Xð4ð 4ð 4r!   r   T)ÚfrozenÚslotsc                  óZ   — e Zd ZU dZded<   ded<   ded<   ded<   d	ed
<   ded<   ded<   dS )ÚExportGraphuê  A model prepared for export, together with the graph metadata every backend needs.

    Attributes:
        model: The module to trace â€” already in eval mode, on CPU, and wrapped for a backbone-only export.
        input_tensors: Example input the backend traces with, matching *shape* and the model's channel count.
        input_names: Names for the graph's inputs.
        output_names: Names for the graph's outputs, in the order the model returns them.
        dynamic_axes: Axis-name mapping for a dynamic batch dimension, or ``None`` for a fully static graph.
        shape: The ``(height, width)`` the graph was prepared for.
        backbone_only: Whether *model* is the backbone-only export wrapper rather than the full detector.
    ú	nn.ModuleÚmodelr   Úinput_tensorsztuple[str, ...]Úinput_namesÚoutput_namesz&Mapping[str, Mapping[int, str]] | NoneÚdynamic_axesútuple[int, int]Úshaper%   Úbackbone_onlyN)r*   r+   r,   r-   Ú__annotations__r   r!   r   r2   r2   J   sr   € € € € € € ð
ð 
ð ÐÐÑØÐÐÑØ Ð Ð Ñ Ø!Ð!Ð!Ñ!Ø8Ð8Ð8Ñ8ØÐÐÑØÐÐÑÐÐr!   r2   Úcudaé   Ú	infer_dirú
str | Noner:   r9   Ú
batch_sizer   Údeviceústr | torch.devicer   r   r   c           	     ó  ‡
— | €€|dk    rSt           j                             dd|d         |d         dft           j        ¬¦  «        }t	          j        |d¬¦  «        }n}t          j        |||d         |d         |¬	¦  «        Š
‰
S |dk    rt          d
¦  «        ‚t	          j	        | ¦  «        5 }| 
                    d¦  «        }ddd¦  «         n# 1 swxY w Y   t          t          ¦   «         t          t          j        d¬¦  «        t          |d         |d         fd¬¦  «        t!          ¦   «         g¦  «        } ||d¦  «        \  Š
}	‰
                     |¦  «        Š
t          j        ˆ
fd„t'          |¦  «        D ¦   «         ¦  «        Š
‰
S )a™  Build the example input tensor an export traces with.

    Args:
        infer_dir: Path to a sample image, or ``None`` to synthesize one.
        shape: Target ``(height, width)``.
        batch_size: Number of copies stacked into the batch dimension.
        device: Device the returned tensor is placed on.
        num_channels: Channel count of the model being exported.

    Returns:
        A ``(batch_size, num_channels, height, width)`` float32 tensor.

    Raises:
        ValueError: If *infer_dir* is given for a model that is not RGB.

    Examples:
        >>> make_infer_image(None, (8, 8), 2, device="cpu").shape
        torch.Size([2, 3, 8, 8])
    Nr>   r   é   é   )ÚdtypeÚRGB)Úmode)rB   z�Providing `infer_dir` is only supported for RGB models (num_channels=3). For non-RGB models, omit `infer_dir` to use a synthetic dummy input.T)ÚscaleF)Ú	antialiasc                ó   •— g | ]}‰‘ŒS r   r   )Ú.0Ú_Úinpss     €r   ú
<listcomp>z$make_infer_image.<locals>.<listcomp>ž   s   ø€ Ð8Ð8Ð8 ˜Ð8Ð8Ð8r!   )ÚnpÚrandomÚrandintÚuint8r
   Ú	fromarrayÚtorchÚrandÚ
ValueErrorÚopenÚconvertr   r   r   Úfloat32r   r   ÚtoÚstackÚrange)r?   r:   rA   rB   r   ÚdummyÚimageÚ_imgÚ
transformsrN   rO   s             @r   Úmake_infer_imagerc   a   sÇ  ø€ ð4 ÐØ˜1ÒÐÝ”I×%Ò% a¨¨u°Q¬x¸¸q¼À1Ð.EÍRÌXÐ%ÑVÔVˆEÝ”O E°Ð6Ñ6Ô6ˆEˆEõ ”:˜j¨,¸¸a¼À%ÈÄ(ÐSYÐZÑZÔZˆDØˆKà˜1ÒÐÝðWñô ð õ ŒZ˜	Ñ"Ô"ð 	( dØ—L’L Ñ'Ô'ˆEð	(ð 	(ð 	(ñ 	(ô 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(øøøð 	(ð 	(ð 	(ð 	(õ
 å‰IŒIÝ•E”M¨Ð.Ñ.Ô.Ý�E˜!”H˜e AœhÐ'°5Ð9Ñ9Ô9Ý‰KŒKð		
ñô €Jð ˆj˜ Ñ%Ô%�G€Dˆ!Ø�7Š7�6‰?Œ?€DÝŒ;Ð8Ð8Ð8Ð8¥e¨JÑ&7Ô&7Ð8Ñ8Ô8Ñ9Ô9€DØ€Ks   Â-CÃCÃCÚmodel_configr;   r%   ÚbackboneúBackbone | Noneú	list[str]c               ó@  — |rƒ|€t          d¦  «        ‚d„ t          t          | j        ¦  «        ¦  «        D ¦   «         }|j        �>|                     d„ t          t          | j        ¦  «        ¦  «        D ¦   «         ¦  «         |S | j        rg d¢S | j        rg d¢S ddgS )	a�  Name the graph's outputs for the model's task.

    A backbone-only export emits one name per projector scale, followed by the cross-attention levels when the
    backbone has a separate cross-attention projector. The full detector emits ``dets``/``labels``, plus the
    task-specific third output.

    Args:
        model_config: Configuration of the model being exported.
        backbone_only: Whether only the backbone is exported.
        backbone: The backbone being exported; required when *backbone_only* is set.

    Returns:
        Output names, in the order the traced model returns them.

    Examples:
        >>> from types import SimpleNamespace
        >>> config = SimpleNamespace(projector_scale=["P4"], segmentation_head=True, use_grouppose_keypoints=False)
        >>> resolve_output_names(config, backbone_only=False, backbone=None)
        ['dets', 'labels', 'masks']
    Nz4backbone must be provided for a backbone-only exportc                ó(   — g | ]}|d k    rdnd|› �‘ŒS )r   ÚfeaturesÚ	features_r   ©rM   Úindexs     r   rP   z(resolve_output_names.<locals>.<listcomp>¼   s:   € ð 
ð 
ð 
ØBG˜% 1š*˜*ˆJˆJÐ*=°eÐ*=Ð*=ð
ð 
ð 
r!   c              3  ó0   K  — | ]}|d k    rdnd|› �V — ŒdS )r   Úcross_attn_featuresÚcross_attn_features_Nr   rl   s     r   ú	<genexpr>z'resolve_output_names.<locals>.<genexpr>À   sN   è è € ð ð àð */°!ª¨Ð%Ð%Ð9WÐPUÐ9WÐ9Wðð ð ð ð ð r!   )ÚdetsÚlabelsÚmasks)rr   rs   Ú	keypointsrr   rs   )rX   r^   Úlenr$   Úcross_attn_projectorÚextendr'   r)   )rd   r;   re   Únamess       r   Úresolve_output_namesrz   ¢   sä   € ð. ð ØÐÝÐSÑTÔTÐTð
ð 
ÝKPÕQTÐUaÔUqÑQrÔQrÑKsÔKsð
ñ 
ô 
ˆð Ô(Ð4Ø�LŠLð ð å"¥3 |Ô'CÑ#DÔ#DÑEÔEðñ ô ñ ô ð ð ˆØÔ%ð +Ø*Ð*Ð*Ð*ØÔ+ð /Ø.Ð.Ð.Ð.Ø�HÐÐr!   ÚoutputsÚobjectÚNonec                óê  — t          | t          ¦  «        rÝ|                      ¦   «         D ]Æ\  }}t          |t          ¦  «        r3t                               d|› dt          |j        ¦  «        › �¦  «         ŒMt          |t          ¦  «        rd|                     ¦   «         D ]O\  }}t          |t          ¦  «        r5t                               d|› d|› dt          |j        ¦  «        › �¦  «         ŒPŒÇdS t          | t          ¦  «        r)t                               dd„ | D ¦   «         › �¦  «         dS t                               dt          t          t          | ¦  «        j        ¦  «        › �¦  «         dS )u|  Log the shapes a sanity forward pass produced, whatever structure the task returns.

    Args:
        outputs: Whatever the prepared model returned â€” a sequence of feature maps for a backbone-only
            export, otherwise the detector's output mapping. Segmentation heads may return ``pred_masks``
            as a dict of mask components rather than a single tensor.
    z!PyTorch inference output shape - z: ú.Nz PyTorch backbone output shapes: c                ó6   — g | ]}t          |j        ¦  «        ‘ŒS r   )Útupler:   )rM   Úfeatures     r   rP   z._log_forward_output_shapes.<locals>.<listcomp>à   s#   € Ð8eÐ8eÐ8eÐRY½¸w¼}Ñ9MÔ9MÐ8eÐ8eÐ8er!   z PyTorch inference output shape: )
Ú
isinstancer   Úitemsr   ÚloggerÚdebugr�   r:   r   r	   )r{   ÚnameÚvalueÚpartÚtensors        r   Ú_log_forward_output_shapesr‹   Ì   ss  € õ �'�7Ñ#Ô#ð 
Ø"Ÿ=š=™?œ?ð 	oð 	o‰KˆD�%Ý˜%¥Ñ(Ô(ð oÝ—’Ð]ÀÐ]Ð]ÍÈuÌ{ÑI[ÔI[Ð]Ð]Ñ^Ô^Ð^Ð^Ý˜E¥7Ñ+Ô+ð oð %*§K¢K¡M¤Mð oð o‘L�D˜&Ý! &­&Ñ1Ô1ð oÝŸšÐ%mÈÐ%mÐ%mÐPTÐ%mÐ%mÕX]Ð^dÔ^jÑXkÔXkÐ%mÐ%mÑnÔnÐnøøØˆÝ�'�8Ñ$Ô$ð Ý�ŠÐgÐ8eÐ8eÐ]dÐ8eÑ8eÔ8eÐgÐgÑhÔhÐhØˆÝ
‡L‚LÐXµE½$½vÀwÑ:OÔ:OÔ:UÑ4VÔ4VÐXÐXÑYÔYÐYÐYÐYr!   rF   F)r?   rA   Údynamic_batchr;   r4   r3   rŒ   c          	     ó.  — |                       ¦   «         D ]2}t          |t          ¦  «        r||_        |                     ¦   «          Œ3t          j        |¦  «        }	|	j        dk    rLt
          j         	                    ¦   «         s.t                               d¦  «         t          j        d¦  «        }	t          ||||	|j        ¬¦  «                             |	¦  «        }
| }d}|rCt          t           | j        d         ¦  «        }|                     ¦   «          t%          |¦  «        }d}t'          t)          |||¬¦  «        ¦  «        }|rd	„ ||z   D ¦   «         nd}|                     ¦   «                              |	¦  «         |
                     |	¦  «        }
t          j        ¦   «         5  t/           ||
¦  «        ¦  «         ddd¦  «         n# 1 swxY w Y   |                      ¦   «          t3          ||
                     ¦   «         |||||¬
¦  «        S )u‡  Prepare *model* for tracing and describe the graph a backend is about to write.

    Runs, in order: freeze every DINOv2 backbone's position embeddings to *shape*; build the example input;
    wrap the backbone when *backbone_only* is set; resolve names and dynamic axes; run one forward pass to
    surface a broken graph here; move everything to CPU, where every backend traces.

    Args:
        model: The module to export. Mutated in place â€” callers pass a copy they own, not a live training model.
        model_config: Configuration of the model being exported.
        shape: Already-validated ``(height, width)`` to export at.
        device: Device the sanity forward pass runs on. Falls back to CPU when CUDA is requested but absent.
        infer_dir: Optional sample image used to build the example input instead of synthesizing one.
        batch_size: Static batch size baked into the graph.
        dynamic_batch: Whether to mark the batch dimension dynamic.
        backbone_only: Export the encoder and feature projectors without the prediction heads.

    Returns:
        The prepared :class:`ExportGraph`.

    Examples:
        Requires a real RF-DETR model, so this is documentation only (not a doctest):

        ```python
        graph = prepare_export_graph(model, model_config, shape=(560, 560), device="cpu")
        graph.output_names
        # -> ('dets', 'labels')
        ```
    r=   zQCUDA requested but not available; falling back to CPU for the export preparation.Úcpu)r   Nr   )Úinput)r;   re   c                ó"   — i | ]}|t           d i“ŒS )Úbatch)Ú
BATCH_AXIS)rM   r‡   s     r   ú
<dictcomp>z(prepare_export_graph.<locals>.<dictcomp>+  s   € ÐLÐLÐL¨ˆ•
˜GÐ$ÐLÐLÐLr!   )r4   r5   r6   r7   r8   r:   r;   )Úmodulesrƒ   r   r:   ÚexportrV   rB   Útyper=   Úis_availabler…   Úwarningrc   r   r\   r	   r   re   r   r�   rz   ÚevalÚno_gradr‹   rŽ   r2   )r4   rd   r:   rB   r?   rA   rŒ   r;   Úbackbone_moduleÚ
run_devicer5   Úexport_modelre   r6   r7   r8   s                   r   Úprepare_export_graphrž   å   sc  € ðV !Ÿ=š=™?œ?ð %ð %ˆÝ�o¥vÑ.Ô.ð 	%Ø$)ˆOÔ!Ø×"Ò"Ñ$Ô$Ð$øõ
 ”˜fÑ%Ô%€JØ„˜&Ò Ð ­¬×)@Ò)@Ñ)BÔ)BÐ Ý�ŠÐjÑkÔkÐkÝ”\ %Ñ(Ô(ˆ
å$Ø�5˜* j¸|Ô?Xðñ ô ç‚bˆ�n„nð ð $€LØ $€HØð 1Ý� %¤.°Ô"3Ñ4Ô4ˆØ�ŠÑÔÐÝ& xÑ0Ô0ˆà€KÝÕ-¨lÈ-ÐbjÐkÑkÔkÑlÔl€LàP]ÐgÐLÐL°¸|Ñ1KÐLÑLÔLÐLÐcgð ð
 ×ÒÑÔ×Ò˜:Ñ&Ô&Ð&Ø!×$Ò$ ZÑ0Ô0€MÝ	Œ‰Œð @ð @Ý" < <°Ñ#>Ô#>Ñ?Ô?Ð?ð@ð @ð @ñ @ô @ð @ð @ð @ð @ð @ð @øøøð @ð @ð @ð @ð 
‡I‚I�K„K€KÝØØ#×'Ò'Ñ)Ô)ØØ!Ø!ØØ#ðñ ô ð s   Æ+GÇGÇG)r=   r>   )r?   r@   r:   r9   rA   r   rB   rC   r   r   r   r   )rd   r   r;   r%   re   rf   r   rg   )r{   r|   r   r}   )r4   r3   rd   r   r:   r9   rB   rC   r?   r@   rA   r   rŒ   r%   r;   r%   r   r2   )*r-   Ú
__future__r   Úcollections.abcr   r   Údataclassesr   Útypingr   r   r	   ÚnumpyrQ   rV   ÚPILr
   r   r   Útorchvision.transforms.v2r   r   r   r   Úrfdetr.datasets.transformsr   Úrfdetr.export._backendr   Úrfdetr.models.backbone.backboner   Úrfdetr.models.backbone.dinov2r   Úrfdetr.utilities.loggerr   r…   r’   r   r2   rc   rz   r‹   rž   r   r!   r   ú<module>r«      s5  ðð
ð 
ð #Ð "Ð "Ð "Ð "Ð "à -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ø !Ð !Ð !Ð !Ð !Ð !Ø &Ð &Ð &Ð &Ð &Ð &Ð &Ð &Ð &Ð &à Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ð Ð Ø GÐ GÐ GÐ GÐ GÐ GÐ GÐ GÐ GÐ GÐ GÐ Gà 0Ð 0Ð 0Ð 0Ð 0Ð 0Ø 2Ð 2Ð 2Ð 2Ð 2Ð 2Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø 0Ð 0Ð 0Ð 0Ð 0Ð 0Ø .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€ð €
ð4ð 4ð 4ð 4ð 4˜ñ 4ô 4ð 4ð4 €�$˜dÐ#Ñ#Ô#ðð ð ð ð ñ ô ñ $Ô#ðð4 "(Øð>ð >ð >ð >ð >ðB'ð 'ð 'ð 'ðTZð Zð Zð Zð> !ØØØðXð Xð Xð Xð Xð Xð Xð Xr!   