
    ڧg*              	       &   d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZmZ d dlmZ ddlmZ ddlmZ  G d	 d
ej                  Zd#dedede	e         defdZ ed          Zdedef         dedef         fdZ ede          Z edej                  Z ed          Zde
eee	e         eeeef         ge	e         f         f         f         fdZdeeef         dededdfdZ dede	e         dedefd Z! G d! d"e"          Z#dS )$    N)OrderedDict)AnyCallableDictOptionalTupleTypeVarUnion)nn   )sequence_to_str   )WeightsEnumc                   l     e Zd ZdZdZdeeef         iZdej	        deeef         ddf fdZ
d Z xZS )	IntermediateLayerGetterax  
    Module wrapper that returns intermediate layers from a model

    It has a strong assumption that the modules have been registered
    into the model in the same order as they are used.
    This means that one should **not** reuse the same nn.Module
    twice in the forward if you want this to work.

    Additionally, it is only able to query submodules that are directly
    assigned to the model. So if `model` is passed, `model.feature1` can
    be returned, but not `model.feature1.layer2`.

    Args:
        model (nn.Module): model on which we will extract the features
        return_layers (Dict[name, new_name]): a dict containing the names
            of the modules for which the activations will be returned as
            the key of the dict, and the value of the dict is the name
            of the returned activation (which the user can specify).

    Examples::

        >>> m = torchvision.models.resnet18(weights=ResNet18_Weights.DEFAULT)
        >>> # extract layer1 and layer3, giving as names `feat1` and feat2`
        >>> new_m = torchvision.models._utils.IntermediateLayerGetter(m,
        >>>     {'layer1': 'feat1', 'layer3': 'feat2'})
        >>> out = new_m(torch.rand(1, 3, 224, 224))
        >>> print([(k, v.shape) for k, v in out.items()])
        >>>     [('feat1', torch.Size([1, 64, 56, 56])),
        >>>      ('feat2', torch.Size([1, 256, 14, 14]))]
    r   return_layersmodelreturnNc                    t          |                              d |                                D                       st          d          |}d |                                D             }t                      }|                                D ]\  }}|||<   ||v r||= |s nt                                          |           || _        d S )Nc                     g | ]\  }}|S  r   ).0name_s      U/var/www/html/ai-engine/env/lib/python3.11/site-packages/torchvision/models/_utils.py
<listcomp>z4IntermediateLayerGetter.__init__.<locals>.<listcomp>3   s    +W+W+WWT1D+W+W+W    z&return_layers are not present in modelc                 N    i | ]"\  }}t          |          t          |          #S r   )str)r   kvs      r   
<dictcomp>z4IntermediateLayerGetter.__init__.<locals>.<dictcomp>6   s*    JJJDAqQQJJJr   )	setissubsetnamed_children
ValueErroritemsr   super__init__r   )selfr   r   orig_return_layerslayersr   module	__class__s          r   r)   z IntermediateLayerGetter.__init__2   s    =!!**+W+W@T@T@V@V+W+W+WXX 	GEFFF*JJM4G4G4I4IJJJ!0022 	 	LD&!F4L}$$!$'   	   /r   c                     t                      }|                                 D ]+\  }} ||          }|| j        v r| j        |         }|||<   ,|S N)r   r'   r   )r*   xoutr   r-   out_names         r   forwardzIntermediateLayerGetter.forwardB   s]    mm JJLL 	" 	"LD&q		At)))-d3 !H
r   )__name__
__module____qualname____doc___versionr   r   __annotations__r   Moduler)   r4   __classcell__r.   s   @r   r   r      s         > Hc3hO0bi 0S#X 04 0 0 0 0 0 0       r   r   r!   divisor	min_valuer   c                 |    ||}t          |t          | |dz  z             |z  |z            }|d| z  k     r||z  }|S )z
    This function is taken from the original tf repo.
    It ensures that all layers have a channel number that is divisible by 8
    It can be seen here:
    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
    Nr   g?)maxint)r!   r>   r?   new_vs       r   _make_divisiblerD   L   sT     		3q7Q;//7:WDEEEsQwLr   Dfn.c                     t          j                   j        }	 t          d t	          |                                          D                       n'# t          $ r t          d j         d          dw xY wt          t          j                   j                  d         t          j                   dt          dt          dt          f fd            }|S )	a  Decorates a function that uses keyword only parameters to also allow them being passed as positionals.

    For example, consider the use case of changing the signature of ``old_fn`` into the one from ``new_fn``:

    .. code::

        def old_fn(foo, bar, baz=None):
            ...

        def new_fn(foo, *, bar, baz=None):
            ...

    Calling ``old_fn("foo", "bar, "baz")`` was valid, but the same call is no longer valid with ``new_fn``. To keep BC
    and at the same time warn the user of the deprecation, this decorator can be used:

    .. code::

        @kwonly_to_pos_or_kw
        def new_fn(foo, *, bar, baz=None):
            ...

        new_fn("foo", "bar, "baz")
    c              3   @   K   | ]\  }}|j         |j        k    |V  d S r0   )kindKEYWORD_ONLY)r   idxparams      r   	<genexpr>z&kwonly_to_pos_or_kw.<locals>.<genexpr>z   s>       &
 &
C
eN`@`@`C@`@`@`@`&
 &
r   z-Found no keyword-only parameter on function ''Nargskwargsr   c            	      0   | d          | d          }} |rxt          t          |                    }t          j        dt	          t          |                                          d           d           |                    |            | i |S )NzUsing zand )separate_lastz as positional parameter(s) is deprecated since 0.13 and may be removed in the future. Please use keyword parameter(s) instead.)dictzipwarningswarnr   tuplekeysupdate)rO   rP   keyword_only_argskeyword_only_kwargsrF   keyword_only_paramskeyword_only_start_idxs       r   wrapperz$kwonly_to_pos_or_kw.<locals>.wrapper   s    "&'>(>'>"?F\F]F]A^ 	/"&s+>@Q'R'R"S"SM/B/G/G/I/I)J)JZ`aaa     
 MM-...r4"6"""r   )inspect	signature
parametersnext	enumeratevaluesStopIteration	TypeErrorr5   rW   	functoolswrapsr   rE   )rF   paramsr^   r\   r]   s   `  @@r   kwonly_to_pos_or_kwrj   _   s"   0 r""-Fb!% &
 &
"+FMMOO"<"<&
 &
 &
 "
 "
  b b bVVVVWW]aab   1" 5 5 @AABXBYBYZ_R#s #c #a # # # # # # # # Ns   8A $A;W)boundMVweightsc                  d     dt           dt          f         dt           dt          f         f fd}|S )a0  Decorates a model builder with the new interface to make it compatible with the old.

    In particular this handles two things:

    1. Allows positional parameters again, but emits a deprecation warning in case they are used. See
        :func:`torchvision.prototype.utils._internal.kwonly_to_pos_or_kw` for details.
    2. Handles the default value change from ``pretrained=False`` to ``weights=None`` and ``pretrained=True`` to
        ``weights=Weights`` and emits a deprecation warning with instructions for the new interface.

    Args:
        **weights (Tuple[str, Union[Optional[W], Callable[[Dict[str, Any]], Optional[W]]]]): Deprecated parameter
            name and default value for the legacy ``pretrained=True``. The default value can be a callable in which
            case it will be called with a dictionary of the keyword arguments. The only key that is guaranteed to be in
            the dictionary is the deprecated parameter name passed as first element in the tuple. All other parameters
            should be accessed with :meth:`~dict.get`.
    builder.r   c                      t           t          j                   dt          dt          dt          f fd                        }|S )NrO   rP   r   c                                                      D ]B\  }\  }}t                      }|                    ||          }||vr||vs2t          |t                    st          |t
                    r|dk    s|h||u}|r|                    |          x||<   }n||         }|rIt          |          r ||          n|}	t          |	t                    st          dj	                   nd }	|st          j        d| d| d           d| d| d|	 d	}
|r|
 d
| dt          |	          j	         d}
t          j        |
           ||= |	||<   D | i |S )NlegacyzNo weights available for model The parameter 'zI' is deprecated since 0.13 and may be removed in the future, please use 'z
' instead.z2Arguments other than a weight enum or `None` for 'zm' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `=z`.z You can also use `z-.DEFAULT` to get the most up-to-date weights.)r'   objectget
isinstancer   r   popcallabler&   r5   rU   rV   type)rO   rP   weights_parampretrained_paramdefaultsentinelweights_argpretrained_positionalpretrained_argdefault_weights_argmsgrq   ro   s              r   inner_wrapperzEhandle_legacy_interface.<locals>.outer_wrapper.<locals>.inner_wrapper   sA    ?Fmmoo 4< 4<:: 0' "88$jjAA"&005EV5S5S!+{;; 6T";44 6T9D9P9P"* )48(C%( > AG

=@Y@YYF+,~~%+,<%=N! /=Eg=N=N*[''&///T['%&9;GG _()]7K[)])]^^^_ +/', MA*: A A'4A A A  n n nFSn nVin n n 
 "  ? ?= ? ?4H[C\C\Ce ? ? ?  c"""+,(;}%%7D+F+++r   )rj   rg   rh   r   rm   )rq   r   ro   s   ` r   outer_wrapperz.handle_legacy_interface.<locals>.outer_wrapper   se    			!	!7	, 7	, 7	, 7	, 7	, 7	, 7	, 7	, 7	, 
"	! 
	7	,r r   )r   rm   )ro   r   s   ` r   handle_legacy_interfacer      sJ    $<xQ/ <HS!V4D < < < < < <| r   rP   rL   	new_valuec           	      r    || v r-| |         |k    rt          d| d| d| |          d          d S || |<   d S Nru   z' expected value z	 but got z	 instead.r&   )rP   rL   r   s      r   _ovewrite_named_paramr      sb    %=I%%sussyss[abg[hsssttt &% "ur   actualexpectedc           	      H    |||k    rt          d|  d| d| d          |S r   r   )rL   r   r   s      r   _ovewrite_value_paramr      sC    XkukkxkkZ`kkklllOr   c                        e Zd Z fdZ xZS )
_ModelURLsc                 n    t          j        d           t                                          |          S )NzAccessing the model URLs via the internal dictionary of the module is deprecated since 0.13 and may be removed in the future. Please access them via the appropriate Weights Enum instead.)rU   rV   r(   __getitem__)r*   itemr.   s     r   r   z_ModelURLs.__getitem__   s7    e	
 	
 	
 ww""4(((r   )r5   r6   r7   r   r<   r=   s   @r   r   r      s8        ) ) ) ) ) ) ) ) )r   r   r0   )$rg   r_   rU   collectionsr   typingr   r   r   r   r   r	   r
   torchr   _utilsr   _apir   
ModuleDictr   floatrB   rD   rE   rj   rk   r;   rm   rn   r   r   r   r   rS   r   r   r   r   <module>r      s}         # # # # # # G G G G G G G G G G G G G G G G G G       $ $ $ $ $ $      < < < < <bm < < <~ u s x} PS      GCLL1HS!V, 1#q&1A 1 1 1 1h GC{###GCry!!!GCLLPuS%XtTWY\T\~N^`hij`kNkEl8l2m-m'n P P P Pf"$sCx. " " "t " " " " hqk Q 1    ) ) ) ) ) ) ) ) ) )r   