Skip to content

Commit 3ce439e

Browse files
author
Nikhil Thorat
authored
Throw a better error message when using negative begin indexing. (tensorflow#1965)
BUG See magenta/magenta-js#342 TensorFlow nor TensorFlow.js support this (though numpy does, and will call tf.strided_slice which does support that type of indexing).
1 parent 54bf277 commit 3ce439e

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

tfjs-core/src/ops/slice.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,10 @@ function slice_<R extends Rank, T extends Tensor<R>>(
131131
} else {
132132
begin_ = begin.slice();
133133
}
134+
begin_.forEach(d => {
135+
util.assert(
136+
d !== -1, () => 'slice() does not support negative begin indexing.');
137+
});
134138
let size_: number[];
135139
if (size == null) {
136140
size_ = new Array($x.rank).fill(-1);
@@ -145,7 +149,10 @@ function slice_<R extends Rank, T extends Tensor<R>>(
145149
if (d >= 0) {
146150
return d;
147151
} else {
148-
util.assert(d === -1, () => 'Bad value in size');
152+
util.assert(
153+
d === -1,
154+
() => `Negative size values should be exactly -1 but got ` +
155+
`${d} for the slice() size at index ${i}.`);
149156
return $x.shape[i] - begin_[i];
150157
}
151158
});

tfjs-core/src/ops/slice_test.ts

+7
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,13 @@ describeWithFlags('slice ergonomics', ALL_ENVS, () => {
513513

514514
expect(tf.slice(b, 0).dtype).toEqual('float32');
515515
});
516+
517+
it('throws when begin is negative', async () => {
518+
const a = [[1, 2], [3, 4]]; // 2x2
519+
expect(() => tf.slice(a, [-1, 1], [
520+
1, 1
521+
])).toThrowError(/slice\(\) does not support negative begin indexing./);
522+
});
516523
});
517524

518525
describeWithFlags('shallow slicing', ALL_ENVS, () => {

0 commit comments

Comments
 (0)