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..94d8e4303036c9 --- /dev/null +++ b/python/unittest_py/issue75574.py @@ -0,0 +1,26 @@ +# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +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