rai_toolbox.perturbations.uniform_like_l1_n_ball_#

rai_toolbox.perturbations.uniform_like_l1_n_ball_(x, epsilon=1.0, param_ndim=-1, generator=<torch._C.Generator object>)[source]#

Uniform sampling of an \(\epsilon\)-sized n-ball for \(L^1\)-norm, where n is controlled by x.shape and param_ndim. The result overwrites x in-place.

Parameters:
x: Tensor, shape-(N, D, …)

The tensor from which to generate a new random tensor, i.e., returns a tensor of similar shape and on the same device.

By default, each of the N shape-(D, ...) subtensors are initialized independently. See param_ndim to control this behavior.

epsilonfloat, optional (default=1)

Determines the radius of the ball.

param_ndimint | None, optional (default=-1)

Determines the dimensionality of the subtensors that are sampled by this function.

  • A positive number determines the dimensionality of each subtensor to be drawn and packed into the shape-(N, D, ...) resulting tensor.

  • A negative number determines from the dimensionality of the subtensor in terms of the offset of x.ndim. E.g. -1 indicates that x is arranged in a batch-style, and that N independent shape-(D, ...) tensors will be sampled.

  • None means that a single tensor of shape-(N, D, ...) is sampled.

Returns:
xTensor, shape-(N, D, …)

The input tensor, which has been modified in-place.

References

[1]

Rauber et al., 2020, Foolbox Native: Fast adversarial attacks to benchmark the robustness of machine learning models in PyTorch, TensorFlow, and JAX https://doi.org/10.21105/joss.02607

Examples

>>> import torch as tr
>>> from rai_toolbox.perturbations.init import uniform_like_l1_n_ball_

Drawing two shape-(3,) tensors from an \(\epsilon=2\) sized \(L^1\) 3D-ball.

>>> x = tr.zeros(2, 3)
>>> uniform_like_l1_n_ball_(x, epsilon=2.0) # default: param_ndim=-1
>>> x
tensor([[0.3301, 0.8459, 0.7071],
        [0.3470, 0.5077, 0.0977]])
>>> tr.linalg.norm(x, dim=1, ord=1) < 2.0
tensor([True, True])

Drawing one tensor shape-(6,) tensor from a \(\epsilon=2\) sized \(L^1\) 6D-ball, and storing it in x as a shape-(2, 3) tensor. We specify param_ndim=2 (or param_ndim=None) to achieve this.

>>> x = tr.zeros(2, 3)
>>> uniform_like_l1_n_ball_(x, epsilon=2.0, param_ndim=2)
>>> x
tensor([[0.1413, 0.5270, 0.1570],
        [0.4817, 0.2760, 0.4076]])
>>> tr.linalg.norm(x, ord=1) < 2.0
tensor(True)