Skip to content

Data slicing with negative steps, out-of-range bounds or (under MPI) strides selects or writes the wrong entries #3140

Backlog

Description

@chaitanya0305

Indexing Function.data with some ordinary slices silently selects different entries than the same slice on a NumPy array. Without MPI this affects reads and writes with a negative step or an out-of-range bound. With MPI, assignments through strided slices (step > 1), negative-step slices or negative bounds also write the wrong values, or raise a broadcast error, depending on how the grid is split across ranks.

Everything below is at 9bc70e2.

Serial: wrong entries for negative steps and out-of-range bounds

import numpy as np
from devito import Grid, Function

grid = Grid(shape=(7,))
f = Function(name='f', grid=grid)
full = np.arange(7, dtype=np.float32)
f.data[:] = full

for sl in [slice(None, -1, -1), slice(5, -1, -1), slice(7, None, -2), slice(-10, 5, 3)]:
    print(sl, np.asarray(f.data[sl]), full[sl])
slice(None, -1, -1, None)  [6. 5. 4. 3. 2. 1. 0.]  []
slice(5, -1, -1, None)     [5. 4. 3. 2. 1. 0.]     []
slice(7, None, -2, None)   [5. 3. 1.]              [6. 4. 2. 0.]
slice(-10, 5, 3, None)     [2.]                    [0. 3.]

Writes through the same slices either write the wrong entries or fail with could not broadcast input array from shape ....

I enumerated every slice(a, b, c) with a, b in None, -9..9 and c in -1, -2, -3 on a 7-point axis: 114 of 1200 slices disagree with NumPy, and 45 of those have both bounds inside the array.

Two root causes:

  • With a negative step, a stop of -1 is treated as "past index 0" instead of "the last entry", e.g. in loc_data_idx (utils.py#L170, #L178). So [k:-1:-1] returns k..0 where NumPy returns nothing.
  • Bounds beyond the ends (a start of n or more with a negative step, or a start below -n) are never clipped as NumPy does, so the stride is anchored at the wrong index.

MPI: strided and negative-step assignments write wrong values

# mpirun -n 2 python repro_mpi.py   (DEVITO_MPI=1)
import numpy as np
from devito import Grid, Function

grid = Grid(shape=(9, 7))
for idx in [(1, slice(2, 7, 3)), (slice(0, 9, 2), 1), (slice(0, -3), slice(None, 1, -1))]:
    f = Function(name='f', grid=grid)
    expected = np.zeros((9, 7), np.float32)
    val = np.arange(expected[idx].size, dtype=np.float32).reshape(expected[idx].shape) + 1
    expected[idx] = val
    f.data[idx] = val
    got = f.data_gather()
    if grid.distributor.myrank == 0:
        print(idx, np.array_equal(got, expected))

On 2 ranks, f.data[1, 2:7:3] = [1, 2] stores [1, 1]: row 1 ends up as [0, 0, 1, 0, 0, 1, 0] instead of [0, 0, 1, 0, 0, 2, 0]. f.data[0:9:2, 1] = val raises ValueError: could not broadcast input array from shape (5,) into shape (3,). With random slices on a 9x7 grid, 76 of 300 assignments are wrong or raise on 2 ranks.

Root causes, all in the replicated-value branch of Data.__setitem__:

  • The part of val a rank keeps is computed by index_dist_to_repl in global index units, which ignores the stride (data.py#L328). The "Handle step size > 1" fix-up below it (data.py#L343) zips glb_idx against a val_idx that has already dropped the integer-indexed axes, so it pairs the wrong axes.
  • _process_args turns a negative-step slice into slice(stop + 1, start + 1, -step) (data.py#L408). That is only correct when stop is aligned to the stride (e.g. 6:0:-4 selects 6 and 2, but 1:7:4 selects 1 and 5). It also builds transform only for the negative-step axes (data.py#L410), so the flip of val lands on the wrong axis when an earlier axis has a positive step.

Impact

Anyone who sets or reads model parameters, initial conditions or wavefields through .data with such slices gets silently wrong values. Reversed or strided sub-blocks are typical, e.g. f.data[k:-1:-1], f.data[n::-2], or f.data[i, a:b:s] = ... under MPI. In serial, the most likely trigger is stop=-1 with a negative step. Under MPI, any step > 1 assignment can be affected, and the result depends on the number of ranks.

Fix

  • In Data._normalize_index, resolve slice bounds against the global axis size as NumPy does (slice.indices). Open bounds stay None, a negative-step stop that resolves to "past 0" becomes None, and empty selections become 0:0.
  • Add owned_positions(idx, decomposition) in devito/data/utils.py. It returns which positions of a strided global selection the calling rank owns, and __setitem__ uses it to cut val. This replaces the step > 1 fix-up.
  • In _process_args, derive the increasing slice from range(*slice.indices(n)) and give every val axis a transform entry.

With the fix, all 1200 single-axis slices match NumPy, as do 600 random 2-D read/write slices in serial and 400 random 2-D assignments on 2 and 4 ranks (gathered and compared with NumPy). All of tests/test_data.py passes, including the parallel tests.

I have a fix with a regression test at https://github.com/chaitanya0305/devito/tree/fix/data-negative-step-slices and will open a PR.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions