pytorch torchvision.ops.roi_align

news2024/10/7 6:42:55

pytorch的torchvision.ops.roi_align这个算子真的是坑我好多天啊!害我连续加班半个月!二阶段目标检测后面用roi_align来提取特征。
接口官方说明:https://pytorch.org/vision/stable/generated/torchvision.ops.roi_align.html?highlight=roi_align#torchvision.ops.roi_align

boxes (Tensor[K, 5] or List[Tensor[L, 4]]) – the box coordinates in (x1, y1, x2, y2) format where the regions will be taken from. The coordinate must satisfy 0 <= x1 < x2 and 0 <= y1 < y2. If a single Tensor is passed, then the first column should contain the index of the corresponding element in the batch, i.e. a number in [0, N - 1]. If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i in the batch.

我做的是caffe转pytorch,caffe网络用到了roi_align这个算子。caffe的网络prototxt是这么的:

layer {
  name: "persion_roi_pooling"
  type: "ROIAlignment"
  bottom: "p3_conv"  #[b 128 24 72]
  bottom: "persion_detection_out" #[1 1 18 7]
  top: "persion_roi_pooling" #[18 128 7 7]
  propagate_down: true
  propagate_down: false
  roi_alignment_param {
    pooled_height: 7
    pooled_width: 7
  }
}

这里解释一下,p3_conv是卷积网络的featuremap,其shape是[b 128 24 72]
persion_detection_out是第一阶段输出检测出18个目标,7是[b,label,score,xmin,ymin,xmax,ymax]. 其实roialign里面只需要5个就可以了[b,xmin,ymin,xmax,ymax],label和score用不到。
然后roialign的输出persion_roi_pooling是[18 128 7 7]。
这里就是把之前的batch丢了,现在是18, 18是目标个数。然后后续还是需要卷积做一些回归任务,比如回归深度,然后接入卷积最后的输出的是[18 1 1 1], 然后和gt那边一堆逻辑操作下来也是的shape是[18, 1]. 所以这个就可以接入smoothl1做回归任务了。
这是caffe的,我们只需要搞懂输入输出就可以了。这里注意一下,输入的bottom: "persion_detection_out" #[1 1 18 7],这里xmin,ymin是0.2,0.1之类的相对值。

然后到pytorch这边,网上的示例确实也是这样的:https://blog.csdn.net/Bit_Coders/article/details/121203584
box = torch.tensor([[0.0,0.375,0.875,0.625]])
然后自然而然的我在我的实现中也这样。

最后整个pytorch弄完毕,不收敛啊,loss巨大!不知道哪里出问题,然后一层层排查,固定caffe输出和pytorch验证。
验证下来就是经过roialign这个算子之后两边不一样!
当初觉得是两个框架实现这么复杂逻辑哪里不一样正常,我就直接用pytorch的训练就可以了。但是loss依旧大不收敛!!!

自闭了,这个任务搞了好久,任务延期再延,加班再加!

这里略过很多。。
最后发现pytorch的roialign不是和网上说的一样啊,他输入的bbox框坐标是需要相对于input的坐标的啊!比如inpu的featuremap的width是24,那么就要求框坐标是[0-23]之间的数!
在pytorch源码里面/pytorch-master/caffe2/operators/roi_align_op.cu

#include "caffe2/operators/roi_align_op.h"

#include <stdio.h>
#include <cfloat>
#include "caffe2/core/context_gpu.h"
#include "caffe2/utils/math.h"

namespace caffe2 {

namespace {

template <typename T>
__device__ T bilinear_interpolate(
    const T* bottom_data,
    const int height,
    const int width,
    T y,
    T x) {
  // deal with cases that inverse elements are out of feature map boundary
  if (y < -1.0 || y > height || x < -1.0 || x > width) {
    // empty
    return 0;
  }

  if (y <= 0) {
    y = 0;
  }
  if (x <= 0) {
    x = 0;
  }

  int y_low = (int)y;
  int x_low = (int)x;
  int y_high;
  int x_high;

  if (y_low >= height - 1) {
    y_high = y_low = height - 1;
    y = (T)y_low;
  } else {
    y_high = y_low + 1;
  }

  if (x_low >= width - 1) {
    x_high = x_low = width - 1;
    x = (T)x_low;
  } else {
    x_high = x_low + 1;
  }

  T ly = y - y_low;
  T lx = x - x_low;
  T hy = 1. - ly, hx = 1. - lx;
  // do bilinear interpolation
  T v1 = bottom_data[y_low * width + x_low];
  T v2 = bottom_data[y_low * width + x_high];
  T v3 = bottom_data[y_high * width + x_low];
  T v4 = bottom_data[y_high * width + x_high];
  T w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx;

  T val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);

  return val;
}

template <typename T>
__global__ void RoIAlignForward(
    const int nthreads,
    const T* bottom_data,
    const T spatial_scale,
    const int channels,
    const int height,
    const int width,
    const int pooled_height,
    const int pooled_width,
    const int sampling_ratio,
    const T* bottom_rois,
    int roi_cols,
    T* top_data,
    bool continuous_coordinate) {
  CUDA_1D_KERNEL_LOOP(index, nthreads) {
    // (n, c, ph, pw) is an element in the pooled output
    int pw = index % pooled_width;
    int ph = (index / pooled_width) % pooled_height;
    int c = (index / pooled_width / pooled_height) % channels;
    int n = index / pooled_width / pooled_height / channels;

    // RoI could have 4 or 5 columns
    const T* offset_bottom_rois = bottom_rois + n * roi_cols;
    int roi_batch_ind = 0;
    if (roi_cols == 5) {
      roi_batch_ind = offset_bottom_rois[0];
      offset_bottom_rois++;
    }

    // Do not using rounding; this implementation detail is critical
    T roi_offset = continuous_coordinate ? T(0.5) : 0;
    T roi_start_w = offset_bottom_rois[0] * spatial_scale - roi_offset;
    T roi_start_h = offset_bottom_rois[1] * spatial_scale - roi_offset;
    T roi_end_w = offset_bottom_rois[2] * spatial_scale - roi_offset;
    T roi_end_h = offset_bottom_rois[3] * spatial_scale - roi_offset;

    T roi_width = roi_end_w - roi_start_w;
    T roi_height = roi_end_h - roi_start_h;
    if (!continuous_coordinate) { // backward compatibility
      // Force malformed ROIs to be 1x1
      roi_width = c10::cuda::compat::max(roi_width, (T)1.);
      roi_height = c10::cuda::compat::max(roi_height, (T)1.);
    }
    T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height);
    T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width);

    const T* offset_bottom_data =
        bottom_data + (roi_batch_ind * channels + c) * height * width;

    // We use roi_bin_grid to sample the grid and mimic integral
    int roi_bin_grid_h = (sampling_ratio > 0)
        ? sampling_ratio
        : ceil(roi_height / pooled_height); // e.g., = 2
    int roi_bin_grid_w =
        (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width);

    // We do average (integral) pooling inside a bin
    const T count = roi_bin_grid_h * roi_bin_grid_w; // e.g. = 4

    T output_val = 0.;
    for (int iy = 0; iy < roi_bin_grid_h; iy++) // e.g., iy = 0, 1
    {
      const T y = roi_start_h + ph * bin_size_h +
          static_cast<T>(iy + .5f) * bin_size_h /
              static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5
      for (int ix = 0; ix < roi_bin_grid_w; ix++) {
        const T x = roi_start_w + pw * bin_size_w +
            static_cast<T>(ix + .5f) * bin_size_w /
                static_cast<T>(roi_bin_grid_w);

        T val = bilinear_interpolate(
            offset_bottom_data, height, width, y, x);
        output_val += val;
      }
    }
    output_val /= count;

    top_data[index] = output_val;
  }
}

} // namespace

template <>
C10_EXPORT bool RoIAlignOp<float, CUDAContext>::RunOnDevice() {
  auto& X = Input(0); // Input data to pool
  auto& R = Input(1); // RoIs
                      // RoI pooled data

  if (R.numel() == 0) {
    // Handle empty rois
    Output(0, {0, X.dim32(1), pooled_h_, pooled_w_}, at::dtype<float>());
    return true;
  }

  assert(sampling_ratio_ >= 0);

  auto* Y = Output(
      0, {R.dim32(0), X.dim32(1), pooled_h_, pooled_w_}, at::dtype<float>());
  int output_size = Y->numel();
  RoIAlignForward<float>
      <<<CAFFE_GET_BLOCKS(output_size),
         CAFFE_CUDA_NUM_THREADS,
         0,
         context_.cuda_stream()>>>(
          output_size,
          X.data<float>(),
          spatial_scale_,
          X.dim32(1),
          X.dim32(2),
          X.dim32(3),
          pooled_h_,
          pooled_w_,
          sampling_ratio_,
          R.data<float>(),
          R.dim32(1),
          Y->mutable_data<float>(),
          aligned_);
  C10_CUDA_KERNEL_LAUNCH_CHECK();

  return true;
}

REGISTER_CUDA_OPERATOR(RoIAlign, RoIAlignOp<float, CUDAContext>);
} // namespace caffe2

using RoIAlignOpFloatCUDA = caffe2::RoIAlignOp<float, caffe2::CUDAContext>;

C10_EXPORT_CAFFE2_OP_TO_C10_CUDA(RoIAlign, RoIAlignOpFloatCUDA);

通过这段代码:

// Do not using rounding; this implementation detail is critical
    T roi_offset = continuous_coordinate ? T(0.5) : 0;
    T roi_start_w = offset_bottom_rois[0] * spatial_scale - roi_offset;
    T roi_start_h = offset_bottom_rois[1] * spatial_scale - roi_offset;
    T roi_end_w = offset_bottom_rois[2] * spatial_scale - roi_offset;
    T roi_end_h = offset_bottom_rois[3] * spatial_scale - roi_offset;

    T roi_width = roi_end_w - roi_start_w;
    T roi_height = roi_end_h - roi_start_h;
    if (!continuous_coordinate) { // backward compatibility
      // Force malformed ROIs to be 1x1
      roi_width = c10::cuda::compat::max(roi_width, (T)1.);
      roi_height = c10::cuda::compat::max(roi_height, (T)1.);
    }
    T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height);
    T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width);

特别是通过这里,roi_width = c10::cuda::compat::max(roi_width, (T)1.);, 这里还要求roi_width最小值为1.

所以我明白了,这里是认为输入框坐标是原图上面的,然后通过spatial_scale来映射到input大小。比如一般是下采样8倍做roialign,所以框坐标是原图上面坐标,然后spatial_scale放1/8就可以了。

所以网上那些介绍roialign示例的时候输入框还是0.1之类的小数这些都是错误的!当然也有对的,比如下面链接里面提到:

假设候选框坐标为左上角(0,105),右下角:(230,250),原图和featureMap的spaceRatio为32,那么映射到featureMap上的候选框为:左上角:(0,105/32),即为(0,3.28125);右下角:(230/32,250/32),即为(7.1875,7.8125),那么候选框在特征图上的区域即为下图中红色区域。注意,这里并没有对坐标进行取整,因此是精确的坐标,这就解决了问题二

https://zhuanlan.zhihu.com/p/565986126?utm_id=0

ps:当然我改完pytorch这边,和caffe对比,经过roialign输出还是不一样。但是loss正常了。
(⊙o⊙)…
暂时就不深究了吧!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/154412.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

React Devtools 使用技巧

首先在扩展迷中搜索下载该扩展&#xff0c;引入到 Chrome 的扩展程序中。 当我们添加扩展到Chrome中&#xff0c;就会在浏览器中看到 React Devtools 的 Icon&#xff0c;同时通过该扩展我们就可以知道当前打开的网站是开发环境的网站还是生产环境&#xff0c;React Devtools …

Mysql 安装 ubutu20.04

Mysql 安装 1&#xff1a;sudo apt-get autoremove --purge mysql* 2&#xff1a;sudo apt-get install mysql-server 3&#xff1a;sudo apt --fix-broken install -y 4&#xff1a;sudo apt-get install mysql-server 5&#xff1a; service mysql status 5&#xff1a;sudo…

C++STL-stackqueuepriority_queue介绍

文章目录1. 容器适配器1.1 什么是适配器1.2 STL标准库中stack和queue的底层结构2. stack的介绍和使用2.1 stack的介绍2.2 stack的使用3. queue的介绍和使用3.1 queue的介绍3.2 queue的使用4. priority_queue的介绍和使用4.1 priority_queue的介绍4.2 priority_queue的使用1. 容…

年度征文 | 回顾2022,展望2023

目录 一、前言 二、回顾2022 三、展望2023 个人主页: ζ小菜鸡大家好我是ζ小菜鸡&#xff0c;感谢大家一直的支持。岁末年初&#xff0c;让我们一起回顾2022展望2023。一、前言 时光荏苒&#xff0c;岁月如梭&#xff0c;2022 已和我们再见&#xff0c;2023 正向我们走来。…

云原生周刊 | 在 Grafana 中显示 K8s Service 之间的依赖关系

开源项目推荐 Caretta 这个项目可以在 Grafana 监控面板中显示 K8s Service 之间的依赖关系。底层使用的是 eBPF&#xff0c;对应用无侵入。 busuanzi 这是一个基于 Golang Redis 的简易访问量统计系统&#xff0c;可以用来替代不蒜子。 vim-online-editor 这是一个在线版…

一文读懂 Kubernetes 存储设计

在 Docker 的设计中&#xff0c;容器内的文件是临时存放的&#xff0c;并且随着容器的删除&#xff0c;容器内部的数据也会一同被清空。不过&#xff0c;我们可以通过在 docker run 启动容器时&#xff0c;使用 --volume/-v 参数来指定挂载卷&#xff0c;这样就能够将容器内部的…

企业级数据中台构建方法和指导

目录1. 数据中台的概念2. 数据中台适合企业2.1 企业构建数据中台面临的问题2.2 企业构建数据中台解决问题的方法2.3 什么样的企业适合构建数据中台3. 如何建设数据中台3.1 方法论3.1.1 OneData3.1.2 OneService3.2 技术3.3 组织4. 数据中台实现&#xff1a;指标管理5. 数据中台…

高速缓存伪共享(false sharing)

0. CPU缓存 根据摩尔定律&#xff1a;芯片中的晶体管数量每隔18个月就会翻一番。导致CPU的性能和处理速度变得越来越快&#xff0c;而提升CPU的运行速度比提升内存的运行速度要容易和便宜的多&#xff0c;所以就导致了CPU与内存之间的速度差距越来越大。 为了弥补CPU与内存之间…

错失搭档张云雷,杨九郎和郭冬临一起演小品

熟悉相声的人都知道&#xff0c;这个传统的曲艺行业&#xff0c;一般是由捧哏和逗哏组成&#xff0c;两个人相辅相成缺一不可。就拿德云社的相声演员来说&#xff0c;也产生了很多对优秀演员&#xff0c;比如说郭德纲和于谦&#xff0c;比如说岳云鹏和孙越等等。 除了这两对相声…

微信开放平台之小程序获取用户信息

说实话&#xff0c;微信开放平台的文档真的是狗屎一般的存在&#xff0c;维护不及时&#xff0c;混乱&#xff0c;每隔一段时间更新一次授权接口&#xff01;着实让开发者想口吐芬芳了&#xff01;文档内跳来跳去&#xff0c;找不到一个完整的链路&#xff01;维护好几套接口文…

_Linux多线程-线程控制篇

文章目录1. POSIX线程库2. 创建线程3. 线程ID及进程地址空间布局4. 线程等待5. 线程终止pthread_ exitpthread_ cancel6. 分离线程7. 总结1. POSIX线程库 与线程有关的函数构成了一个完整的系列&#xff0c;绝大多数函数的名字都是以“pthread_”打头的要使用这些函数库&#…

三角函数在编程中的实际运用—永劫无间脚本

三角函数在编程中的实际运用—永劫无间脚本前言需求思路代码■ 转义码■ 源码具体讲解三角函数计算相对移动求余跳过不需要的位置成品最后前言 义务教育下&#xff0c;年轻人从初中就开始学三角函数却半辈子也没用上&#xff0c;除了特殊行业&#xff0c;做开发的可能也就大学…

Nginx web服务器入门及其在Linux中的搭建

目录 ​编辑 一、Nginx基本概述 1.介绍 2.优点 3.应用场景 &#xff08;1&#xff09;负载均衡 &#xff08;2&#xff09;代理缓存 &#xff08;3&#xff09;静态资源 &#xff08;4&#xff09;安全应用场景 4.Nginx的组成 &#xff08;1&#xff09;Nginx二进制…

Canal同步数据

canal同步数据 canal可以用来监控数据库数据的变化&#xff0c;从而获得新增数据&#xff0c;或者修改的数据。 canal是应阿里巴巴存在杭州和美国的双机房部署&#xff0c;存在跨机房同步的业务需求而提出的。 阿里系公司开始逐步的尝试基于数据库的日志解析&#xff0c;获取…

(9)Qt中信号与槽重载的解决方案

信号与槽重载的解决方案 一、通过函数指针解决 //信号 void (Me::*funchungury)() &Me::hungury; void (Me::*funchungury_QString)(QString) &Me::hungury; //槽 void (Me::*funceat)() &Me::eat; void (Me::*funceat_QString)(QString) &Me::eat;//有参…

Oracle与MySQL语法转换

前言 Oracle与MySQL语法转换 场景&#xff1a;系统改造&#xff0c;需要由Oracle切换为MySQL&#xff0c;因而要对代码中的Oracle语法的sql调整为MySQL语法 博客地址&#xff1a;芒果橙的个人博客 【http://mangocheng.com】 sysdate–当前日期 Oracle 使用sysdate select s…

hdl_graph_slam代码解析

hdl SLAM和定位的关系&#xff1a;HDL和cartographer一样&#xff0c;是离线建图的 整个SLAM系统的架构 包含四个节点&#xff1a; 预处理、 帧匹配、hdl_slam、地面检测 输入点云首先经过预处理进行降采样&#xff0c;然后传给下一个节点。帧匹配通过迭代获取两帧之间运动变化…

【SpringCloud01】微服务架构入门

1.微服务架构理论入门 SpringCloud微服务 2.Boot和Cloud版本选型 上篇&#xff1a;SpringBoot2.X版和SpringCloud H版 下篇&#xff1a;SpringCloud Alibaba 官网强烈推荐SpringBoot2.0以上的版本 Cloud与Boot之间的版本关系 技术选型相关的网站使用在线解析json字符串 由于…

第2章 马尔可夫决策过程

2.1 马尔可夫决策过程&#xff08;上&#xff09; Markov Decision Process&#xff08;MDP&#xff09; Markov Decision Process can model a lot of real-world problem. It formally describes the framework of reinforcement learningUnder MDP, the environment is ful…

Promise 实现 (从简易版到符合Promise A+规范)

前言 手写 Promise 是面试的时候大家都逃避的送命题&#xff0c;在学些了解后发现通过实现源码更能将新一代的异步方案理解的通透&#xff0c;知其然知其所以然的运用。 如果直接将源码贴到此处势必不能有更大的收获&#xff0c;下面就按实现版本来看做简要分析。 回顾 Prom…