从零构建深度学习推理框架-8 卷积算子实现

其实这一次课还蛮好理解的:

首先将kernel展平:

cpp 复制代码
    for (uint32_t g = 0; g < groups; ++g) {
      std::vector<arma::fmat> kernel_matrix_arr(kernel_count_group);
      arma::fmat kernel_matrix_c(1, row_len * input_c_group);

      for (uint32_t k = 0; k < kernel_count_group; ++k) {
        const std::shared_ptr<Tensor<float>> &kernel =
            weights.at(k + g * kernel_count_group);
        for (uint32_t ic = 0; ic < input_c_group; ++ic) {
          memcpy(kernel_matrix_c.memptr() + row_len * ic,
                 kernel->at(ic).memptr(), row_len * sizeof(float));
        }
        LOG(INFO) << "kernel展开后: " << "\n" << kernel_matrix_c;
        kernel_matrix_arr.at(k) = kernel_matrix_c;
      }

将原来的kernel放到kernel_matrix_c里面,之后如果是多个channel,也就是input_c有多个,那就按照rowlen*ic依次存放到里面。

将输入input展平:

cpp 复制代码
//按照上面的图就是input = 3*9 ,4的这样一个空间
      arma::fmat input_matrix(input_c_group * row_len, col_len);
      for (uint32_t ic = 0; ic < input_c_group; ++ic) {
        const arma::fmat &input_channel = input_->at(ic + g * input_c_group);
        int current_col = 0;
//下面是以窗口滑动的顺序选取
        for (uint32_t w = 0; w < input_w - kernel_w + 1; w += stride_w) {
          for (uint32_t r = 0; r < input_h - kernel_h + 1; r += stride_h) {
            float *input_matrix_c_ptr =
                input_matrix.colptr(current_col) + ic * row_len;//对准窗口位置,比如对第一个就是对准红色, 黄色, 绿色
            current_col += 1;

            for (uint32_t kw = 0; kw < kernel_w; ++kw) {
              const float *region_ptr = input_channel.colptr(w + kw) + r;
              memcpy(input_matrix_c_ptr, region_ptr, kernel_h * sizeof(float));
              input_matrix_c_ptr += kernel_h;
            }
          }
        }
      }
      LOG(INFO)  << "input展开后: " << "\n"  << input_matrix;

对于:

cpp 复制代码
 for (uint32_t kw = 0; kw < kernel_w; ++kw) {
              const float *region_ptr = input_channel.colptr(w + kw) + r;
              memcpy(input_matrix_c_ptr, region_ptr, kernel_h * sizeof(float));
              input_matrix_c_ptr += kernel_h;
            }

w+kw指向的是窗口的列,r指向的是窗口的行

然后对于每个窗口的以kernel的列为标准复制过去。

最后两个矩阵相乘就可以得到结果

相关推荐
Allen_LVyingbo11 分钟前
数智读书笔记系列035《未来医疗:医疗4.0引领第四次医疗产业变革》
人工智能·经验分享·笔记·健康医疗
zzc92116 分钟前
时频图数据集更正程序,去除坐标轴白边及调整对应的标签值
人工智能·深度学习·数据集·标签·时频图·更正·白边
isNotNullX18 分钟前
什么是数据分析?常见方法全解析
大数据·数据库·数据仓库·人工智能·数据分析
riveting27 分钟前
明远智睿H618:开启多场景智慧生活新时代
人工智能·嵌入式硬件·智能硬件·lga封装·3506
夜阑卧听风吹雨,铁马冰河入梦来41 分钟前
Spring AI 阿里巴巴学习
人工智能·学习·spring
c7691 小时前
【文献笔记】Automatic Chain of Thought Prompting in Large Language Models
人工智能·笔记·语言模型·论文笔记
Blossom.1181 小时前
机器学习在智能供应链中的应用:需求预测与物流优化
人工智能·深度学习·神经网络·机器学习·计算机视觉·机器人·语音识别
Gyoku Mint1 小时前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
zzywxc7872 小时前
AI大模型的技术演进、流程重构、行业影响三个维度的系统性分析
人工智能·重构
点控云2 小时前
智能私域运营中枢:从客户视角看 SCRM 的体验革新与价值重构
大数据·人工智能·科技·重构·外呼系统·呼叫中心