§
    ­¸jò,  ã                  ó,  — U d Z ddlmZ ddlZddlZddl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  e¦   «         Z G d	„ d
e¦  «        Zd d„Z G d„ dej        ¦  «        Z ee¦  «        Zded<    edh¦  «        Zded<   d!d„Zd"d„Zd#d„ZdS )$u+  Backend/format resolution and export-format dispatch helpers for :meth:`rfdetr.detr.RFDETR.export`.

These are utility functions shared by :meth:`rfdetr.detr.RFDETR.export` and the exporter classes â€” kept in their own
module so neither the public entry point nor any one format package owns them.
é    )ÚannotationsN)ÚProtocolÚcast)ÚTensorÚnn)ÚREGISTRY)ÚBackbone)Ú
get_loggerc                  ó   — e Zd ZdZdd„ZdS )Ú_ExportableModulea’  Structural type for a module exposing a zero-arg export-mode switch.

    Narrows the static type before calling ``.export()`` directly on an ``nn.Module`` -- ``nn.Module.__getattr__``'s
    stub resolves that attribute access to ``Tensor | Module``, which mypy refuses to call (mirrors the ``cast(Backbone,
    ...)`` precedent used for backbone-only export in :meth:`rfdetr.detr.RFDETR.export`).
    ÚreturnÚNonec                ó   — d S ©N© )Úselfs    úf/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/export/_backend.pyÚexportz_ExportableModule.export$   s   € € € ó    N©r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r      s(   € € € € € ðð ð "Ð!Ð!Ð!Ð!Ð!r   r   Úmodelú	nn.Moduler   r   c                ó¾   — t          | dd¦  «        rdS t          | dd¦  «        }t          |¦  «        r)t          t          | ¦  «                             ¦   «          dS dS )at  Switch *model* into its export-friendly forward, if it exposes one.

    Shared by the ONNX exporter (``export_onnx``) and the ExecuTorch, CoreML, and OpenVINO dispatch
    functions below, so every export path switches through one guarded choke point. A model without a
    callable ``export`` attribute (e.g. a plain ``nn.Module`` in a unit test) is left untouched rather
    than raising.

    Switching a module that is already in export mode is a no-op here, because it is *not* a no-op in
    the models: :meth:`rfdetr.models.lwdetr.LWDETR.export`,
    :meth:`rfdetr.models.backbone.backbone.Backbone.export` and
    :meth:`rfdetr.models.position_encoding.PositionEmbeddingSine.export` each stash
    ``self._forward_origin = self.forward`` before swapping in ``forward_export``, so a second call
    overwrites the saved original with the export forward and loses the real one for good.
    (``DinoV2.export`` already guards itself; these three do not.) The guard lives here rather than in
    the models so every export path shares one choke point.

    Args:
        model: The module to switch into export mode, if supported.
    Ú_exportFNr   )ÚgetattrÚcallabler   r   r   )r   Úexport_methods     r   Ú_switch_to_export_moder"   '   sk   € õ( ˆu�i Ñ'Ô'ð ØˆÝ˜E 8¨TÑ2Ô2€MÝ�ÑÔð 0ÝÕ Ñ&Ô&×-Ò-Ñ/Ô/Ð/Ð/Ð/ð0ð 0r   c                  ó,   ‡ — e Zd ZdZdˆ fd„Zdd
„Zˆ xZS )Ú_BackboneExportzJExpose all feature projectors from a backbone already prepared for export.Úbackboner	   r   r   c                óV   •— t          ¦   «                              ¦   «          || _        d S r   )ÚsuperÚ__init__r%   )r   r%   Ú	__class__s     €r   r(   z_BackboneExport.__init__E   s$   ø€ Ý‰Œ×ÒÑÔÐØ ˆŒˆˆr   Úimagesr   úlist[Tensor]c                óP   — | j                              |¦  «        \  }}}|€|n||z   S )zOReturn primary feature levels followed by cross-attention levels, when present.)r%   Úforward_export)r   r*   ÚfeaturesÚ_Úcross_attn_featuress        r   Úforwardz_BackboneExport.forwardI   s4   € à+/¬=×+GÒ+GÈÑ+OÔ+OÑ(ˆ�!Ð(Ø.Ð6ˆxˆx¸HÐGZÑ<ZÐZr   )r%   r	   r   r   )r*   r   r   r+   )r   r   r   r   r(   r1   Ú__classcell__)r)   s   @r   r$   r$   B   s_   ø€ € € € € ØTÐTð!ð !ð !ð !ð !ð !ð[ð [ð [ð [ð [ð [ð [ð [r   r$   zfrozenset[str]Ú_EXPORT_FORMATSÚ
executorchÚ_BACKEND_FORMATSÚformatÚstrÚbackendú
str | NoneÚsocútuple[str | None, str | None]c           
     óà  — | t           vr(t          d| ›dt          t           ¦  «        › d�¦  «        ‚| t          vr8d|fd|ffD ]-\  }}|�&t	          j        d|› d|›d	| ›d
�t          d¬¦  «         Œ.dS ddlm}m	} d|i}d|i}| 
                    | t          ¦   «         ¦  «        }	| 
                    | t          ¦   «         ¦  «        }
|€#t          d| ›dt          |	¦  «        › d�¦  «        ‚|                     ¦   «         }||	vr&t          d|›d| ›dt          |	¦  «        › d�¦  «        ‚||
vr)|�#t	          j        d|›d|›d�t          d¬¦  «         |dfS |€t          d|›d�¦  «        ‚||fS )u<  Validate a ``format`` / ``backend`` / ``soc`` combination and return the effective ``(backend, soc)``.

    Driven by the :data:`_EXPORT_FORMATS` / :data:`_BACKEND_FORMATS` registries (and the converter's backend/SoC sets)
    rather than per-format branches, so adding a format or backend is a data change:

    * A format not in :data:`_BACKEND_FORMATS` is backend-agnostic â€” it takes neither ``backend`` nor ``soc``;
      supplying one warns and it is ignored (returned ``None``).
    * A format in :data:`_BACKEND_FORMATS` requires ``backend`` to be one of the backends its converter accepts
      (looked up by format).
    * A backend that compiles for a specific chip (looked up by format+backend against the converter's SoC set)
      requires ``soc``; any other backend warns if a ``soc`` is supplied and ignores it.

    Args:
        format: Export format; one of :data:`_EXPORT_FORMATS`.
        backend: Requested hardware backend, or ``None``.
        soc: Requested target SoC, or ``None``.

    Returns:
        ``(backend, soc)`` with each value set to ``None`` when the format/backend does not use it.

    Raises:
        ValueError: On an unknown format, a missing or unknown required backend, or a missing required SoC.

    Examples:
        >>> _resolve_export_backend("onnx", None, None)
        (None, None)
    zUnsupported export format z. Choose from: ú.r8   r:   Nú`ú=z` is ignored for format=zA; this format does not require a hardware backend specialization.é   )Ú
stacklevel)NNr   )ÚSOC_BACKENDSÚVALID_BACKENDSr4   zformat z" requires a valid backend (one of z), but none was provided.zUnsupported backend z for format z`soc=z` is ignored for backend=z.; this backend does not target a specific SoC.zbackend z- requires a valid soc, but none was provided.)r3   Ú
ValueErrorÚsortedr5   ÚwarningsÚwarnÚUserWarningÚ"rfdetr.export._executorch.exporterrB   rC   ÚgetÚ	frozensetÚlower)r6   r8   r:   ÚnameÚvaluerB   rC   Úaccepted_backendsÚsoc_backendsÚvalidÚsoc_requireds              r   Ú_resolve_export_backendrS   Z   s  € ð8 •_Ð$Ð$ÝÐi°fÐiÐiÍvÕVeÑOfÔOfÐiÐiÐiÑjÔjÐjàÕ%Ð%Ð%à&¨Ð0°5¸#°,Ð?ð 	ð 	‰KˆD�%ØÐ Ý”ð/˜ð /ð /˜uð /ð /Àð /ð /ð /åØ ð	ñ ô ð øð ˆzð PÐOÐOÐOÐOÐOÐOÐOà4@À.Ð3QÐØ/;¸\Ð.J€LØ×!Ò! &­)©+¬+Ñ6Ô6€EØ×#Ò# F­I©K¬KÑ8Ô8€Là€ÝÐw 6ÐwÐwÍvÐV[É}Ì}ÐwÐwÐwÑxÔxÐxà�mŠm‰oŒo€GØ�eÐÐÝÐp°ÐpÐpÀvÐpÐpÕ`fÐglÑ`mÔ`mÐpÐpÐpÑqÔqÐqà�lÐ"Ð"Øˆ?ÝŒMØq˜ÐqÐq¸ÐqÐqÐqÝØðñ ô ð ð
 ˜ˆ}Ðà
€{ÝÐ\ GÐ\Ð\Ð\Ñ]Ô]Ð]Ø�Cˆ<Ðr   Úboolc                 ó¶   — t          t          j        ¦  «        D ]>} | dk    s|                      d¦  «        r dS | dk    s|                      d¦  «        r dS Œ?dS )uD  Report whether ``onnx`` entered ``sys.modules`` ahead of ``tensorflow``.

    ``sys.modules`` is an ordinary dict, so iterating it yields keys in insertion order â€” which for a top-level package
    is the order the two libraries were first imported in. That is a heuristic, not a loader guarantee: deleting and
    re-importing a module moves it to the end. It only ever decides whether to emit a warning, never what gets
    imported, so a wrong answer costs a log line.

    ``onnx2tf`` is deliberately not treated as ``onnx``: it is a pure-Python package whose import does not load ONNX's
    compiled extension.

    Returns:
        ``True`` when an ``onnx`` module precedes every ``tensorflow`` module, or when ``onnx`` is imported and
        ``tensorflow`` is not. ``False`` otherwise, including when neither is imported.
    Úonnxzonnx.TÚ
tensorflowztensorflow.F)ÚtupleÚsysÚmodulesÚ
startswith)rM   s    r   Ú _onnx_imported_before_tensorflowr\   ¦   sj   € õ •c”kÑ"Ô"ð ð ˆØ�6Š>ˆ>˜TŸ_š_¨WÑ5Ô5ˆ>Ø�4�4Ø�<ÒÐ 4§?¢?°=Ñ#AÔ#AÐØ�5�5ð  àˆ5r   c                 óî   — t          ¦   «         } dt          j        vr:	 t          j        d¦  «         n$# t
          $ r}|j        dk    r‚ Y d}~dS d}~ww xY w| rt                               d¦  «         dS dS )u:  Import TensorFlow before ONNX's C extension so TFLite conversion cannot deadlock.

    ``onnx``'s compiled extension and TensorFlow both statically link Abseil and export its symbols as *weak external*
    definitions.  The dynamic loader coalesces weak definitions onto the first image that provides them, so whichever
    library is imported first supplies Abseil's synchronization primitives â€” including the per-thread semaphore that
    ``absl::Mutex`` and ``absl::Notification`` block on â€” to *both* libraries.

    When ONNX wins that race, TensorFlow's executor blocks in ``absl::Notification::WaitForNotification()`` while
    restoring the SavedModel bundle and is never woken, hanging the export at 0% CPU with no traceback and no
    ``.tflite``.  ``format="tflite"`` reaches ``onnx2tf`` only after a full ONNX export, so ONNX always wins unless
    TensorFlow is preloaded here.  See https://github.com/roboflow/rf-detr/issues/1322 for the measured comparison.

    Importing ``onnx`` *after* TensorFlow is safe, so the warning below is keyed on the relative order of the two
    imports (:func:`_onnx_imported_before_tensorflow`) rather than on ``onnx`` merely being imported.

    Note:
        Does not re-import TensorFlow when it is already loaded, and stays silent when TensorFlow is not installed â€”
        the actionable missing-dependency error is raised later, by
        :func:`~rfdetr.export._tflite.exporter._check_onnx2tf_available`.

    Examples:
        >>> preload_tensorflow_before_onnx()  # returns when the top-level tensorflow package is unavailable
    rW   Na[  onnx was imported before TensorFlow. Both statically link Abseil and export its symbols weakly, so TensorFlow can block forever while restoring the SavedModel bundle during TFLite conversion. That order cannot be repaired once both are loaded. If the export hangs with no output, import tensorflow before onnx or run the export in a fresh process.)	r\   rY   rZ   Ú	importlibÚimport_moduleÚModuleNotFoundErrorrM   ÚloggerÚwarning)Úonnx_won_the_raceÚerrors     r   Úpreload_tensorflow_before_onnxre   ½   s«   € õ0 9Ñ:Ô:Ðà�3œ;Ð&Ð&ð	ÝÔ# LÑ1Ô1Ð1Ð1øÝ"ð 	ð 	ð 	ØŒz˜\Ò)Ð)ØØˆFˆFˆFˆFˆFøøøøð	øøøð
 ð 
Ý�Šð9ñ	
ô 	
ð 	
ð 	
ð 	
ð
ð 
s   ž3 ³
A½AÁA)r   r   r   r   )r6   r7   r8   r9   r:   r9   r   r;   )r   rT   r   )r   Ú
__future__r   r^   rY   rF   Útypingr   r   Útorchr   r   Úrfdetr.export.registryr   Úrfdetr.models.backbone.backboner	   Úrfdetr.utilities.loggerr
   ra   r   r"   ÚModuler$   rK   r3   Ú__annotations__r5   rS   r\   re   r   r   r   ú<module>rn      s±  ððð ð ð #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ø 
€
€
€
Ø €€€Ø !Ð !Ð !Ð !Ð !Ð !Ð !Ð !à Ð Ð Ð Ð Ð Ð Ð à +Ð +Ð +Ð +Ð +Ð +Ø 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€ð"ð "ð "ð "ð "˜ñ "ô "ð "ð0ð 0ð 0ð 0ð6
[ð 
[ð 
[ð 
[ð 
[�b”iñ 
[ô 
[ð 
[ð #, )¨HÑ"5Ô"5€Ð 5Ð 5Ð 5Ñ 5ð $- 9¨l¨^Ñ#<Ô#<Ð Ð <Ð <Ð <Ñ <ðIð Ið Ið IðXð ð ð ð.(
ð (
ð (
ð (
ð (
ð (
r   