dnn: keep the TopK axis attribute unchanged in finalize

TopKLayerImpl::finalize previously normalized the axis attribute by
overwriting this->axis with normalize_axis(axis, input_shape.size()).
When the layer was created with a negative axis (such as the default -1),
this replaced the relative index with a positive index fixed to the rank
of the first input.

Subsequent runs on an input of different rank then either:
- evaluated TopK along the wrong axis (e.g. axis 1 instead of axis 2
  when moving from a 2D tensor to a 3D tensor), or
- triggered an out-of-range assertion in getMemoryShapes (e.g. axis 2
  on a 2D tensor when moving from a 3D tensor to a 2D tensor).

Fix this by keeping this->axis unmodified and storing the normalized axis
separately for execution. Add unit tests for both increasing and decreasing
rank inputs on the same TopK layer instance.
This commit is contained in:
Ishita Singh
2026-11-30 16:14:05 +05:30
parent 4408b9d959
commit e55e631516
2 changed files with 85 additions and 4 deletions

View File

@@ -70,6 +70,7 @@ public:
setParamsFrom(params);
axis = params.get<int>("axis", -1);
normalized_axis = -1;
largest = params.get<int>("largest", 1) == 1;
sorted = params.get<int>("sorted", 1) == 1;
CV_CheckTrue(sorted, "TopK: sorted == false is not supported"); // TODO: support sorted
@@ -116,15 +117,16 @@ public:
// Normalize axis
auto input_shape = shape(inputs.front());
axis = normalize_axis(axis, input_shape.size());
normalized_axis = normalize_axis(axis, input_shape.size());
}
template<class Comparator>
void FindTopK(const Mat &input, Mat &output_value, Mat &output_index) {
const auto input_shape = shape(input);
size_t loops = std::accumulate(input_shape.begin(), input_shape.begin() + axis, 1, std::multiplies<int>());
size_t step = std::accumulate(input_shape.begin() + axis + 1, input_shape.end(), 1, std::multiplies<int>());
int dim_axis = input_shape[axis];
int norm_axis = normalize_axis(axis, input_shape.size());
size_t loops = std::accumulate(input_shape.begin(), input_shape.begin() + norm_axis, 1, std::multiplies<int>());
size_t step = std::accumulate(input_shape.begin() + norm_axis + 1, input_shape.end(), 1, std::multiplies<int>());
int dim_axis = input_shape[norm_axis];
if (loops == 1) {
auto worker = [&](const Range &r) {
const auto *input_ptr = input.ptr<const float>(); // TODO: support other input type
@@ -214,6 +216,7 @@ public:
private:
int axis;
int normalized_axis;
bool largest;
bool sorted;

View File

@@ -3377,4 +3377,82 @@ TEST(Layer_Test_Einsum, UppercaseSubscripts)
normAssert(outputs[0], expected);
}
TEST(Layer_Test_TopK_Axis, keepsNegativeAxisAcrossRanks)
{
LayerParams lp;
lp.type = "TopK";
lp.name = "test_topk";
lp.set("axis", -1);
lp.set("k", 1);
Ptr<Layer> layer = LayerFactory::createLayerInstance(lp.type, lp);
ASSERT_TRUE(layer);
// 2D input: [2, 3]
// row 0: {0, 5, 1} -> largest value is 5 at index 1
// row 1: {9, 0, 0} -> largest value is 9 at index 0
float data[] = {0, 5, 1,
9, 0, 0};
float expected_val[] = {5,
9};
float expected_idx[] = {1,
0};
// First run: 2D input [2, 3], so axis -1 is axis 1
std::vector<Mat> inputs{Mat(2, 3, CV_32F, data).clone()}, outputs;
runLayer(layer, inputs, outputs);
ASSERT_EQ(outputs.size(), (size_t)2);
EXPECT_EQ(shape(outputs[0]), shape(2, 1));
EXPECT_EQ(shape(outputs[1]), shape(2, 1));
normAssert(outputs[0], Mat(2, 1, CV_32F, expected_val));
normAssert(outputs[1], Mat(2, 1, CV_32F, expected_idx));
// Second run on the same layer: 3D input [1, 2, 3], so axis -1 must now be axis 2
const int sz[] = {1, 2, 3};
inputs = {Mat(3, sz, CV_32F, data).clone()};
runLayer(layer, inputs, outputs);
ASSERT_EQ(outputs.size(), (size_t)2);
const int exp_sz[] = {1, 2, 1};
EXPECT_EQ(shape(outputs[0]), shape(1, 2, 1));
EXPECT_EQ(shape(outputs[1]), shape(1, 2, 1));
normAssert(outputs[0], Mat(3, exp_sz, CV_32F, expected_val));
normAssert(outputs[1], Mat(3, exp_sz, CV_32F, expected_idx));
}
TEST(Layer_Test_TopK_Axis, keepsNegativeAxisDecreasingRank)
{
LayerParams lp;
lp.type = "TopK";
lp.name = "test_topk_decreasing";
lp.set("axis", -1);
lp.set("k", 1);
Ptr<Layer> layer = LayerFactory::createLayerInstance(lp.type, lp);
ASSERT_TRUE(layer);
float data[] = {0, 5, 1,
9, 0, 0};
float expected_val[] = {5,
9};
float expected_idx[] = {1,
0};
// First run: 3D input [1, 2, 3], so axis -1 is axis 2
const int sz[] = {1, 2, 3};
std::vector<Mat> inputs{Mat(3, sz, CV_32F, data).clone()}, outputs;
runLayer(layer, inputs, outputs);
ASSERT_EQ(outputs.size(), (size_t)2);
EXPECT_EQ(shape(outputs[0]), shape(1, 2, 1));
EXPECT_EQ(shape(outputs[1]), shape(1, 2, 1));
// Second run on the same layer: 2D input [2, 3], so axis -1 must now be axis 1
inputs = {Mat(2, 3, CV_32F, data).clone()};
runLayer(layer, inputs, outputs);
ASSERT_EQ(outputs.size(), (size_t)2);
EXPECT_EQ(shape(outputs[0]), shape(2, 1));
EXPECT_EQ(shape(outputs[1]), shape(2, 1));
normAssert(outputs[0], Mat(2, 1, CV_32F, expected_val));
normAssert(outputs[1], Mat(2, 1, CV_32F, expected_idx));
}
}} // namespace