Skip to content

Enhance performance with memory reuse, SIMD, and safety fixes - #4

Merged
EthanPeng-2048 merged 7 commits into
mainfrom
feature/smart-policy
Jul 12, 2026
Merged

EthanPeng-2048 merged 7 commits into
mainfrom
feature/smart-policy

Conversation

@EthanPeng-2048

Copy link
Copy Markdown
Collaborator

Smart Policy 性能优化与线程池实现

📋 概述

本 PR 实现了全局线程池和 SmartPolicy 执行策略的优化,显著改进神经网络训练的性能。主要包括:

  1. 全局线程池 - 替代 std::execution::par_unseq,避免频繁创建/销毁线程的开销
  2. 预分配缓冲区 - 在 Linear 层中复用计算缓冲区,减少内存分配
  3. 热路径优化 - 使用原始指针和 data_ptr() 接口,便于编译器向量化
  4. 矩阵操作融合 - 统一转置和乘法到预分配缓冲区,零额外分配

🎯 关键改进

1. 线程池实现 (thread_pool.hpp)

  • ThreadPool 类 - 线程安全的任务队列,支持 parallel_for_each、parallel_transform、parallel_transform_reduce
  • 全局单例 - global_thread_pool() 懒初始化,训练期间常驻,程序结束自动析构
  • 自适应回退 - 工作线程数 ≤ 1 或数据量 < 线程数时自动退回串行

2. Linear 层优化 (layer.hpp)

// 添加预分配缓冲区
Matrix product_buf_;      // W * input 的中间结果
Matrix grad_WT_buf_;      // backward: W^T

// forward() 融合计算
W_.multiply_to(product_buf_, input);  // 写入缓冲区
// result = product_buf + bias(NRVO 优化)

// backward() 避免临时矩阵
W_.transpose_to(grad_WT_buf_);        // 就地转置
grad_WT_buf_.multiply_to(grad_input, grad_output);

- matrix.hpp: 添加 resize/data_ptr/multiply_to/transpose_to 方法
  支持预分配缓冲区,避免热路径反复分配内存
  使用原始指针帮助编译器自动向量化
- layer.hpp Linear: 预分配 product_buf_/result_buf_/grad_input_buf_
  融合矩阵乘法+bias加法,减少一次临时矩阵分配
  backward 使用 transpose_to+multiply_to 预分配缓冲区
- layer.hpp ReLU: 预分配 result_buf_/grad_input_buf_
  使用原始指针循环替代 std::transform,帮助自动向量化
- train.cpp: 预分配 batch 矩阵,使用行优先 memcpy 提取数据
  比逐列复制更缓存友好
- matrix.hpp: 移除 resize/multiply_to/transpose_to 的错误 noexcept
  vector::resize 可能抛 bad_alloc,不应标记 noexcept
- layer.hpp: 移除预分配缓冲区返回值,改用 NRVO 返回新矩阵
  修复 Model 链式调用中移动赋值导致缓冲区失效的问题
  Linear 仅保留 product_buf_/grad_WT_buf_ 作为内部计算缓冲
  ReLU 移除不需要的成员缓冲区
- nn_config.hpp: 修正 BLOCK_SIZE 注释 32×32→64×64
  统一 transform_reduce 使用自定义线程池(一元/二元一致)
- thread_pool.hpp: 添加缺失的 #include <iterator>
- loss.hpp: MSELoss::forward 使用 resize 复用 grad_input_ 内存
- train.cpp: 空文件检测,避免整数除零 UB
  添加 --epochs/--batch-size 负数校验
- matrix.hpp: multiply_to/transpose_to 添加 assert 防护自引用
  防止 A.multiply_to(A, B) 导致数据被清零
- nn_config.hpp: 添加 BLOCK_SIZE 栈安全 static_assert
  确保 b_block 栈分配不超过 64KB
- loss.hpp: CrossEntropyLoss 支持 >128 类
  超过 128 类自动降级为 vector,避免栈溢出
- model_io.hpp: load_model 添加读取完整性校验
  防止截断文件导致静默数据损坏
@EthanPeng-2048
EthanPeng-2048 merged commit eec910d into main Jul 12, 2026
3 checks passed
@EthanPeng-2048
EthanPeng-2048 deleted the feature/smart-policy branch July 12, 2026 07:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant