3
Á3W^¬	  ã               @   s6   d dl mZ d dlZd dlmZ G dd„ dejƒZdS )é    )ÚOrderedDictN)Únnc                   s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )ÚIntermediateLayerGetteral  
    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`.

    Arguments:
        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(pretrained=True)
        >>> # 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]))]
    c                sŒ   t |ƒjdd„ |jƒ D ƒƒs$tdƒ‚|}dd„ |jƒ D ƒ}tƒ }x0|jƒ D ]$\}}|||< ||krh||= |sJP qJW tt| ƒj|ƒ || _	d S )Nc             S   s   g | ]\}}|‘qS © r   )Ú.0ÚnameÚ_r   r   ú@/tmp/pip-build-7wfi2gtz/torchvision/torchvision/models/_utils.pyú
<listcomp>'   s    z4IntermediateLayerGetter.__init__.<locals>.<listcomp>z&return_layers are not present in modelc             S   s   i | ]\}}||“qS r   r   )r   ÚkÚvr   r   r	   ú
<dictcomp>+   s    z4IntermediateLayerGetter.__init__.<locals>.<dictcomp>)
ÚsetÚissubsetÚnamed_childrenÚ
ValueErrorÚitemsr   Úsuperr   Ú__init__Úreturn_layers)ÚselfÚmodelr   Zorig_return_layersZlayersr   Úmodule)Ú	__class__r   r	   r   &   s    z IntermediateLayerGetter.__init__c             C   sD   t ƒ }x8| jƒ D ],\}}||ƒ}|| jkr| j| }|||< qW |S )N)r   r   r   )r   ÚxÚoutr   r   Zout_namer   r   r	   Úforward7   s    

zIntermediateLayerGetter.forward)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   Ú__classcell__r   r   )r   r	   r      s   r   )Úcollectionsr   Ztorchr   Z
ModuleDictr   r   r   r   r	   Ú<module>   s   