chainer.functions.as_strided

chainer.functions.as_strided(x, shape, strides, storage_offset=None)[source]

Create a new view of array with the given shape, strides, and offset.

Parameters:
  • x (tuple of Variable or numpy.ndarray or cupy.ndarray) – The array pointing a memory buffer. Its view is totally ignored.
  • shape (tuple of int) – The shape of output.
  • strides (tuple of int) – The strides of output, given in the unit of steps.
  • storage_offset (int) – The offset between the head of allocated memory and the pointer of first element, given in the unit of steps.
Returns:

The strided variable.

Return type:

Variable

Warning

Users should be aware that this function potentially causes unintended side effects. See numpy.lib.stride_tricks.as_strided for the detail.

Note

The backward algorithm is borrowed from torch.Tensor.as_strided. Therefore, the returned gradient of backward is layout-agnostic when x contains memory overlap. See notes in pytorch’s source code (as_strided Backward and layout-aware/agnostic autograd) too.

Note

In this function strides and storage_offset are given in the unit of steps instead of bytes. This specification differs from numpy.lib.stride_tricks.as_strided().

Example

>>> from chainer import functions as F, Variable
>>> x = Variable(np.arange(4, dtype=np.float32))
>>> x
variable([0., 1., 2., 3.])
>>> y = F.as_strided(x, (3, 2), (1, 1), 0)
>>> y
variable([[0., 1.],
          [1., 2.],
          [2., 3.]])
>>> y.grad = np.ones((3, 2), dtype=np.float32)
>>> y.backward()
>>> x.grad
array([1., 2., 2., 1.], dtype=float32)