diff --git a/paddle/fluid/pybind/slice_utils.h b/paddle/fluid/pybind/slice_utils.h index 73af402de7b31e..326e480553f392 100644 --- a/paddle/fluid/pybind/slice_utils.h +++ b/paddle/fluid/pybind/slice_utils.h @@ -1037,6 +1037,28 @@ static void DealWithIndex(const int pos_of_new_dim, if (indice.defined() && indice.dtype() == paddle::DataType::INT32) { indice = indice.cast(paddle::DataType::INT64); // int32 -> int64 } + + // Handle negative indices for advanced indexing + if (indice.defined() && (indice.dtype() == paddle::DataType::INT64 || + indice.dtype() == paddle::DataType::INT32)) { + // Convert negative indices to positive indices + // For each dimension, if the index is negative, add the dimension size + auto dims = transed_sub_tensor->dims(); + if (dims.size() > 0) { + int64_t dim_size = dims[0]; // First dimension size + // Create a tensor with the dimension size for broadcasting + auto dim_size_tensor = full_ad_func( + {1}, dim_size, paddle::DataType::INT64, indice.place()); + + // Handle negative indices: if index < 0, add dim_size + auto negative_mask = + less_than_ad_func(indice, zeros_like_ad_func(indice)); + auto positive_indices = where_ad_func( + negative_mask, add_ad_func(indice, dim_size_tensor), indice); + indice = positive_indices; + } + } + transed_index_int64->push_back(indice); } } diff --git a/python/unittest_py/issue75574.py b/python/unittest_py/issue75574.py new file mode 100644 index 00000000000000..fd9c868fe6ec66 --- /dev/null +++ b/python/unittest_py/issue75574.py @@ -0,0 +1,11 @@ +import sys +import paddle + +print(paddle.__version__) +sys.stdout.flush() + +edge_index = paddle.arange(17758, dtype='int64') +strided_edge_index = edge_index[::32] +print(strided_edge_index) +print(strided_edge_index[[-1]]) +assert strided_edge_index[[-1]] == 17728 \ No newline at end of file