Repository navigation
Description
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
stopof-1is treated as "past index 0" instead of "the last entry", e.g. inloc_data_idx(utils.py#L170, #L178). So[k:-1:-1]returnsk..0where NumPy returns nothing. - Bounds beyond the ends (a
startofnor more with a negative step, or astartbelow-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
vala rank keeps is computed byindex_dist_to_replin global index units, which ignores the stride (data.py#L328). The "Handle step size > 1" fix-up below it (data.py#L343) zipsglb_idxagainst aval_idxthat has already dropped the integer-indexed axes, so it pairs the wrong axes. _process_argsturns a negative-step slice intoslice(stop + 1, start + 1, -step)(data.py#L408). That is only correct whenstopis aligned to the stride (e.g.6:0:-4selects 6 and 2, but1:7:4selects 1 and 5). It also buildstransformonly for the negative-step axes (data.py#L410), so the flip ofvallands 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 stayNone, a negative-stepstopthat resolves to "past 0" becomesNone, and empty selections become0:0. - Add
owned_positions(idx, decomposition)indevito/data/utils.py. It returns which positions of a strided global selection the calling rank owns, and__setitem__uses it to cutval. This replaces the step > 1 fix-up. - In
_process_args, derive the increasing slice fromrange(*slice.indices(n))and give everyvalaxis atransformentry.
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