示例#1
0
    def __init__(
        self,
        forward_func: Callable,
        layer: Module,
        device_ids: Optional[List[int]] = None,
    ) -> None:
        r"""
        Args:
            forward_func (callable):  The forward function of the model or any
                          modification of it
            layer (torch.nn.Module): Layer for which attributions are computed.
                          Output size of attribute matches this layer's input or
                          output dimensions, depending on whether we attribute to
                          the inputs or outputs of the layer, corresponding to
                          the attribution of each neuron in the input or output
                          of this layer.
            device_ids (list(int)): Device ID list, necessary only if forward_func
                          applies a DataParallel model. This allows reconstruction of
                          intermediate outputs from batched results across devices.
                          If forward_func is given as the DataParallel model itself,
                          then it is not necessary to provide this argument.

        """
        LayerAttribution.__init__(self, forward_func, layer, device_ids=device_ids)
        GradientAttribution.__init__(self, forward_func)
        self.ig = IntegratedGradients(forward_func)
示例#2
0
    def __init__(self, model: Module, layer: ModuleOrModuleList) -> None:
        """
        Args:

            model (module): The forward function of the model or
                        any modification of it. Custom rules for a given layer need to
                        be defined as attribute
                        `module.rule` and need to be of type PropagationRule.
                        Model cannot contain any in-place nonlinear submodules;
                        these are not supported by the register_full_backward_hook
                        PyTorch API starting from PyTorch v1.9.


            layer (torch.nn.Module or list(torch.nn.Module)): Layer or layers
                          for which attributions are computed.
                          The size and dimensionality of the attributions
                          corresponds to the size and dimensionality of the layer's
                          input or output depending on whether we attribute to the
                          inputs or outputs of the layer. If value is None, the
                          relevance for all layers is returned in attribution.
        """
        LayerAttribution.__init__(self, model, layer)
        LRP.__init__(self, model)
        if hasattr(self.model, "device_ids"):
            self.device_ids = cast(List[int], self.model.device_ids)
示例#3
0
    def __init__(
        self,
        forward_func: Callable,
        layer: ModuleOrModuleList,
        device_ids: Union[None, List[int]] = None,
    ) -> None:
        r"""
        Args:

            forward_func (callable):  The forward function of the model or any
                          modification of it
            layer (torch.nn.Module or list(torch.nn.Module)): Layer or layers
                          for which attributions are computed.
                          Output size of attribute matches this layer's input or
                          output dimensions, depending on whether we attribute to
                          the inputs or outputs of the layer, corresponding to
                          attribution of each neuron in the input or output of
                          this layer. If multiple layers are provided, attributions
                          are returned as a list, each element corresponding to the
                          activations of the corresponding layer.
            device_ids (list(int)): Device ID list, necessary only if forward_func
                          applies a DataParallel model. This allows reconstruction of
                          intermediate outputs from batched results across devices.
                          If forward_func is given as the DataParallel model itself,
                          then it is not necessary to provide this argument.
        """
        LayerAttribution.__init__(self, forward_func, layer, device_ids)
示例#4
0
    def __init__(self, model: Module, layer: Module):
        r"""
        Args:

            model (torch.nn.Module):  The reference to PyTorch model instance.
            layer (torch.nn.Module): Layer for which attributions are computed.
                          The size and dimensionality of the attributions
                          corresponds to the size and dimensionality of the layer's
                          input or output depending on whether we attribute to the
                          inputs or outputs of the layer.
        """
        LayerAttribution.__init__(self, model, layer)
        DeepLift.__init__(self, model)
        self.model = model
示例#5
0
    def __init__(self, model: Module, layer: ModuleOrModuleList) -> None:
        """
        Args:

            model (module): The forward function of the model or
                        any modification of it. Custom rules for a given layer need to
                        be defined as attribute
                        `module.rule` and need to be of type PropagationRule.
            layer (torch.nn.Module or list(torch.nn.Module)): Layer or layers
                          for which attributions are computed.
                          The size and dimensionality of the attributions
                          corresponds to the size and dimensionality of the layer's
                          input or output depending on whether we attribute to the
                          inputs or outputs of the layer. If value is None, the
                          relevance for all layers is returned in attribution.
        """
        LayerAttribution.__init__(self, model, layer)
        LRP.__init__(self, model)
    def __init__(
        self,
        forward_func: Callable,
        layer: ModuleOrModuleList,
        device_ids: Union[None, List[int]] = None,
        multiply_by_inputs: bool = True,
    ) -> None:
        r"""
        Args:

            forward_func (callable):  The forward function of the model or any
                        modification of it
            layer (torch.nn.Module or list(torch.nn.Module)): Layer or layers
                          for which attributions are computed.
                          Output size of attribute matches this layer's input or
                          output dimensions, depending on whether we attribute to
                          the inputs or outputs of the layer, corresponding to
                          attribution of each neuron in the input or output of
                          this layer. If multiple layers are provided, attributions
                          are returned as a list, each element corresponding to the
                          attributions of the corresponding layer.
            device_ids (list(int)): Device ID list, necessary only if forward_func
                        applies a DataParallel model. This allows reconstruction of
                        intermediate outputs from batched results across devices.
                        If forward_func is given as the DataParallel model itself,
                        then it is not necessary to provide this argument.
            multiply_by_inputs (bool, optional): Indicates whether to factor
                        model inputs' multiplier in the final attribution scores.
                        In the literature this is also known as local vs global
                        attribution. If inputs' multiplier isn't factored in,
                        then this type of attribution method is also called local
                        attribution. If it is, then that type of attribution
                        method is called global.
                        More detailed can be found here:
                        https://arxiv.org/abs/1711.06104

                        In case of layer gradient x activation, if `multiply_by_inputs`
                        is set to True, final sensitivity scores are being multiplied by
                        layer activations for inputs.

        """
        LayerAttribution.__init__(self, forward_func, layer, device_ids)
        GradientAttribution.__init__(self, forward_func)
        self._multiply_by_inputs = multiply_by_inputs
示例#7
0
    def __init__(
        self,
        model: Module,
        layer: Module,
        multiply_by_inputs: bool = True,
    ) -> None:
        r"""
        Args:

            model (nn.Module):  The reference to PyTorch model instance. Model cannot
                        contain any in-place nonlinear submodules; these are not
                        supported by the register_full_backward_hook PyTorch API
                        starting from PyTorch v1.9.
            layer (torch.nn.Module): Layer for which attributions are computed.
                        The size and dimensionality of the attributions
                        corresponds to the size and dimensionality of the layer's
                        input or output depending on whether we attribute to the
                        inputs or outputs of the layer.
            multiply_by_inputs (bool, optional): Indicates whether to factor
                        model inputs' multiplier in the final attribution scores.
                        In the literature this is also known as local vs global
                        attribution. If inputs' multiplier isn't factored in
                        then that type of attribution method is also called local
                        attribution. If it is, then that type of attribution
                        method is called global.
                        More detailed can be found here:
                        https://arxiv.org/abs/1711.06104

                        In case of Layer DeepLift, if `multiply_by_inputs`
                        is set to True, final sensitivity scores
                        are being multiplied by
                        layer activations for inputs - layer activations for baselines.
                        This flag applies only if `custom_attribution_func` is
                        set to None.
        """
        LayerAttribution.__init__(self, model, layer)
        DeepLift.__init__(self, model)
        self.model = model
        self._multiply_by_inputs = multiply_by_inputs
示例#8
0
    def __init__(
        self,
        forward_func: Callable,
        layer: Module,
        device_ids: Union[None, List[int]] = None,
    ) -> None:
        r"""
        Args:

            forward_func (callable):  The forward function of the model or any
                          modification of it
            layer (torch.nn.Module): Layer for which attributions are computed.
                          Output size of attribute matches this layer's output
                          dimensions, except for dimension 2, which will be 1,
                          since GradCAM sums over channels.
            device_ids (list(int)): Device ID list, necessary only if forward_func
                          applies a DataParallel model. This allows reconstruction of
                          intermediate outputs from batched results across devices.
                          If forward_func is given as the DataParallel model itself,
                          then it is not necessary to provide this argument.
        """
        LayerAttribution.__init__(self, forward_func, layer, device_ids)
        GradientAttribution.__init__(self, forward_func)
示例#9
0
    def __init__(
        self,
        forward_func: Callable,
        layer: ModuleOrModuleList,
        device_ids: Union[None, List[int]] = None,
        multiply_by_inputs: bool = True,
    ) -> None:
        r"""
        Args:
            forward_func (callable):  The forward function of the model or any
                        modification of it
            layer (ModuleOrModuleList):
                        Layer or list of layers for which attributions are computed.
                        For each layer the output size of the attribute matches
                        this layer's input or output dimensions, depending on
                        whether we attribute to the inputs or outputs of the
                        layer, corresponding to the attribution of each neuron
                        in the input or output of this layer.

                        Please note that layers to attribute on cannot be
                        dependent on each other. That is, a subset of layers in
                        `layer` cannot produce the inputs for another layer.

                        For example, if your model is of a simple linked-list
                        based graph structure (think nn.Sequence), e.g. x -> l1
                        -> l2 -> l3 -> output. If you pass in any one of those
                        layers, you cannot pass in another due to the
                        dependence, e.g.  if you pass in l2 you cannot pass in
                        l1 or l3.

            device_ids (list(int)): Device ID list, necessary only if forward_func
                        applies a DataParallel model. This allows reconstruction of
                        intermediate outputs from batched results across devices.
                        If forward_func is given as the DataParallel model itself,
                        then it is not necessary to provide this argument.
            multiply_by_inputs (bool, optional): Indicates whether to factor
                        model inputs' multiplier in the final attribution scores.
                        In the literature this is also known as local vs global
                        attribution. If inputs' multiplier isn't factored in,
                        then this type of attribution method is also called local
                        attribution. If it is, then that type of attribution
                        method is called global.
                        More detailed can be found here:
                        https://arxiv.org/abs/1711.06104

                        In case of layer integrated gradients, if `multiply_by_inputs`
                        is set to True, final sensitivity scores are being multiplied by
                        layer activations for inputs - layer activations for baselines.

        """
        LayerAttribution.__init__(self,
                                  forward_func,
                                  layer,
                                  device_ids=device_ids)
        GradientAttribution.__init__(self, forward_func)
        self.ig = IntegratedGradients(forward_func, multiply_by_inputs)

        if isinstance(layer, list) and len(layer) > 1:
            warnings.warn(
                "Multiple layers provided. Please ensure that each layer is"
                "**not** solely solely dependent on the outputs of"
                "another layer. Please refer to the documentation for more"
                "detail.")
示例#10
0
    def attribute(
        self,
        inputs: TensorOrTupleOfTensorsGeneric,
        target: TargetType = None,
        additional_forward_args: Any = None,
        interpolate_mode: str = "nearest",
        attribute_to_layer_input: bool = False,
    ) -> TensorOrTupleOfTensorsGeneric:
        r"""
        Args:

            inputs (tensor or tuple of tensors):  Input for which attributions
                        are computed. If forward_func takes a single
                        tensor as input, a single input tensor should be provided.
                        If forward_func takes multiple tensors as input, a tuple
                        of the input tensors should be provided. It is assumed
                        that for all given input tensors, dimension 0 corresponds
                        to the number of examples, and if multiple input tensors
                        are provided, the examples must be aligned appropriately.
            target (int, tuple, tensor or list, optional):  Output indices for
                        which gradients are computed (for classification cases,
                        this is usually the target class).
                        If the network returns a scalar value per example,
                        no target index is necessary.
                        For general 2D outputs, targets can be either:

                        - a single integer or a tensor containing a single
                          integer, which is applied to all input examples

                        - a list of integers or a 1D tensor, with length matching
                          the number of examples in inputs (dim 0). Each integer
                          is applied as the target for the corresponding example.

                        For outputs with > 2 dimensions, targets can be either:

                        - A single tuple, which contains #output_dims - 1
                          elements. This target index is applied to all examples.

                        - A list of tuples with length equal to the number of
                          examples in inputs (dim 0), and each tuple containing
                          #output_dims - 1 elements. Each tuple is applied as the
                          target for the corresponding example.

                        Default: None
            additional_forward_args (any, optional): If the forward function
                        requires additional arguments other than the inputs for
                        which attributions should not be computed, this argument
                        can be provided. It must be either a single additional
                        argument of a Tensor or arbitrary (non-tuple) type or a
                        tuple containing multiple additional arguments including
                        tensors or any arbitrary python types. These arguments
                        are provided to forward_func in order following the
                        arguments in inputs.
                        Note that attributions are not computed with respect
                        to these arguments.
                        Default: None
            interpolate_mode (str, optional): Method for interpolation, which
                        must be a valid input interpolation mode for
                        torch.nn.functional. These methods are
                        "nearest", "area", "linear" (3D-only), "bilinear"
                        (4D-only), "bicubic" (4D-only), "trilinear" (5D-only)
                        based on the number of dimensions of the chosen layer
                        output (which must also match the number of
                        dimensions for the input tensor). Note that
                        the original GradCAM paper uses "bilinear"
                        interpolation, but we default to "nearest" for
                        applicability to any of 3D, 4D or 5D tensors.
                        Default: "nearest"
            attribute_to_layer_input (bool, optional): Indicates whether to
                        compute the attribution with respect to the layer input
                        or output in `LayerGradCam`.
                        If `attribute_to_layer_input` is set to True
                        then the attributions will be computed with respect to
                        layer inputs, otherwise it will be computed with respect
                        to layer outputs.
                        Note that currently it is assumed that either the input
                        or the output of internal layer, depending on whether we
                        attribute to the input or output, is a single tensor.
                        Support for multiple tensors will be added later.
                        Default: False

        Returns:
            *tensor* of **attributions**:
            - **attributions** (*tensor*):
                    Element-wise product of (upsampled) GradCAM
                    and Guided Backprop attributions.
                    If a single tensor is provided as inputs, a single tensor is
                    returned. If a tuple is provided for inputs, a tuple of
                    corresponding sized tensors is returned.
                    Attributions will be the same size as the provided inputs,
                    with each value providing the attribution of the
                    corresponding input index.
                    If the GradCAM attributions cannot be upsampled to the shape
                    of a given input tensor, None is returned in the corresponding
                    index position.


        Examples::

            >>> # ImageClassifier takes a single input tensor of images Nx3x32x32,
            >>> # and returns an Nx10 tensor of class probabilities.
            >>> # It contains an attribute conv4, which is an instance of nn.conv2d,
            >>> # and the output of this layer has dimensions Nx50x8x8.
            >>> # It is the last convolution layer, which is the recommended
            >>> # use case for GuidedGradCAM.
            >>> net = ImageClassifier()
            >>> guided_gc = GuidedGradCam(net, net.conv4)
            >>> input = torch.randn(2, 3, 32, 32, requires_grad=True)
            >>> # Computes guided GradCAM attributions for class 3.
            >>> # attribution size matches input size, Nx3x32x32
            >>> attribution = guided_gc.attribute(input, 3)
        """
        is_inputs_tuple = _is_tuple(inputs)
        inputs = _format_input(inputs)
        grad_cam_attr = self.grad_cam.attribute.__wrapped__(
            self.grad_cam,  # self
            inputs=inputs,
            target=target,
            additional_forward_args=additional_forward_args,
            attribute_to_layer_input=attribute_to_layer_input,
            relu_attributions=True,
        )
        if isinstance(grad_cam_attr, tuple):
            assert len(grad_cam_attr) == 1, (
                "GuidedGradCAM attributions for layer with multiple inputs / "
                "outputs is not supported.")
            grad_cam_attr = grad_cam_attr[0]
        guided_backprop_attr = self.guided_backprop.attribute.__wrapped__(
            self.guided_backprop,  # self
            inputs=inputs,
            target=target,
            additional_forward_args=additional_forward_args,
        )
        output_attr: List[Tensor] = []
        for i in range(len(inputs)):
            try:
                output_attr.append(guided_backprop_attr[i] *
                                   LayerAttribution.interpolate(
                                       grad_cam_attr,
                                       inputs[i].shape[2:],
                                       interpolate_mode=interpolate_mode,
                                   ))
            except Exception:
                warnings.warn(
                    "Couldn't appropriately interpolate GradCAM attributions for some "
                    "input tensors, returning empty tensor for corresponding "
                    "attributions.")
                output_attr.append(torch.empty(0))

        return _format_output(is_inputs_tuple, tuple(output_attr))