从零构建深度学习推理框架-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的列为标准复制过去。

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

相关推荐
MediaTea几秒前
AI 术语通俗词典:C4.5 算法
人工智能·算法
海兰26 分钟前
【第27篇】Micrometer + Zipkin
人工智能·spring boot·alibaba·spring ai
DeepReinforce1 小时前
四、AI量化投资:使用akshare获取A股主板20260430筛选后的涨停股票
人工智能
qcx231 小时前
【AI Agent通识九课】02 · Agent 的“思考回路“长啥样?
人工智能·ai·llm·agent
FL16238631291 小时前
电力设备红外图像与可见光图像配准数据集227对共454张无标注
深度学习
翔云1234561 小时前
端侧推理:全面解析与深度洞察
人工智能·ai·大模型
AI精钢1 小时前
AI Agent 从上线到删库跑路始末
网络·人工智能·云原生·aigc
码农小旋风1 小时前
2026 终端 AI 编程工具深度横评:Claude Code、Codex CLI、Gemini CLI、Aider 怎么选
人工智能·gpt·claude
Chef_Chen2 小时前
论文解读:多模态智能体长期记忆突破:M3-Agent让AI像人一样“看、听、记、想“
人工智能·机器学习·agent·memory
zhuiyisuifeng2 小时前
2026AI办公革命:Gemini3.1Pro重塑职场效率
人工智能