 
         // filter out overlapped boxes with lower scores
         int ref_item_idx = offset;
-        int ref_bbox_idx = share_location ? (beforeNMS_index_array[ref_item_idx] % num_preds_per_class + bbox_idx_offset) : beforeNMS_index_array[ref_item_idx];
-
-        while ((ref_bbox_idx != -1) && ref_item_idx < max_idx)
+
+        int32_t ref_bbox_idx = -1;
+        if (ref_item_idx < max_read_idx)
+        {
+            ref_bbox_idx = share_location
+                ? (beforeNMS_index_array[ref_item_idx] % num_preds_per_class + bbox_idx_offset)
+                : beforeNMS_index_array[ref_item_idx];
+        }
+        while ((ref_bbox_idx != -1) && ref_item_idx < max_read_idx)
         {
             Bbox<T_BBOX> ref_bbox;
             ref_bbox.xmin = flipXY ? bbox_data[ref_bbox_idx * 4 + 1] : bbox_data[ref_bbox_idx * 4 + 0];

        {
            const int cur_idx = threadIdx.x + blockDim.x * t;
            const int item_idx = offset + cur_idx;

            if (item_idx < max_idx)
            {
                loc_bboxIndex[t] = beforeNMS_index_array[item_idx];

                if (loc_bboxIndex[t] != -1)
                {

            do
            {
                ref_item_idx++;
            } while (ref_item_idx < max_read_idx && !kept_bboxinfo_flag[ref_item_idx - offset]);

            // Move to next valid point
            if (ref_item_idx < max_read_idx)
            {
                ref_bbox_idx = share_location
                    ? (beforeNMS_index_array[ref_item_idx] % num_preds_per_class + bbox_idx_offset)
                    : beforeNMS_index_array[ref_item_idx];
            }
        }

        // store data
