G1Medium★ 工业基石 (核心高频)Part G · 核心架构与微调技术

Conv2d 卷积算子纯手写(四层循环实现)

⚡闪卡盲测➔

计算机视觉底层基石,纯手写前向滑动窗口,清晰展示输出尺寸公式、零填充与通道累加。

⏱️ 时间复杂度: O(B * C_out * H_out * W_out * C_in * Kh * Kw)
💾 空间复杂度: O(B * C_in * (H+2P) * (W+2P)) 填充后的中间张量
🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def conv2d_forward(
x: np.ndarray, # (B, C_in, H, W)
w: np.ndarray, # (C_out, C_in, Kh, Kw)
b: np.ndarray = None, # (C_out,)
stride: int = 1,
padding: int = 0
) -> np.ndarray:
B, C_in, H, W = x.shape
C_out, _, Kh, Kw = w.shape
# 1. 计算输出特征图尺寸
H_out =
W_out = (W + 2 * padding - Kw) // stride + 1
# 2. 空间零填充
if padding > 0:
x_pad = np.pad(x, ((0, 0), (0, 0), (padding, padding), (padding, padding)), mode='constant')
else:
x_pad = x
out = np.zeros((B, C_out, H_out, W_out), dtype=x.dtype)
# 3. 滑动窗口四层循环计算
for h in range(H_out):
h_start = h * stride
h_end = h_start + Kh
for w_idx in range(W_out):
w_start = w_idx * stride
w_end = w_start + Kw
# 截取感受野切片: (B, C_in, Kh, Kw)
x_slice = x_pad[:, :, h_start:h_end, w_start:w_end]
# 沿输入通道与核尺寸乘加规约,输出 (B, C_out)
# x_slice: (B, 1, Cin, Kh, Kw), w: (1, Cout, Cin, Kh, Kw)
val =
if b is not None:
val += b[np.newaxis, :]
out[:, :, h, w_idx] = val
return out
Step 3 · 反例与边界断言核对
Step 4 · 面试追问盲答与错题记录
Q1: Depthwise Separable Convolution(深度可分离卷积)如何大幅削减 Conv2d 的计算量?
下一题: LoRA 低秩矩阵微调(前向传播与权重合并) →
💡

实战一句话记忆口诀

输出尺寸算整齐,零填只补宽高围,切片内积通道合

📐 核心数学公式与机理推导

Hout=⌊Hin+2P−KhS⌋+1,Ob,cout,h,w=∑cin∑i∑jXb,cin,h⋅S+i,w⋅S+jWcout,cin,i,jH_{\text{out}} = \left\lfloor\frac{H_{\text{in}} + 2P - K_h}{S}\right\rfloor + 1, \quad O_{b, c_{\text{out}}, h, w} = \sum_{c_{\text{in}}} \sum_{i} \sum_{j} X_{b, c_{\text{in}}, h\cdot S + i, w\cdot S + j} W_{c_{\text{out}}, c_{\text{in}}, i, j}
### 滑动窗口与空间几何投影
二维卷积将输入特征图 X∈RB×Cin×H×WX \in \mathbb{R}^{B \times C_{\text{in}} \times H \times W} 映射为 O∈RB×Cout×Hout×WoutO \in \mathbb{R}^{B \times C_{\text{out}} \times H_{\text{out}} \times W_{\text{out}}}。
- Padding(填充):在输入外围补 PP 圈 0,保护边缘空间分辨率;
- Stride(步长):卷积核在空间移动的步距 SS;
每个输出通道 coutc_{\text{out}} 拥有一套独立的 Cin×Kh×KwC_{\text{in}} \times K_h \times K_w 权重核,在输入对应的三维感受野区域执行内积并累加求和,最后加上偏置 bb。
在硬件底层(cuDNN / TensorRT),通常使用 im2col + GEMM 将滑动窗口展开为二维大矩阵,调用高度优化的矩阵乘法单元计算。

🔄 张量维度与形状流转说明

x: (B, Cin, H, W) -> 零填充 -> (B, Cin, H+2P, W+2P) -> 窗口切片 -> 与核相乘累加 -> out: (B, Cout, H_out, W_out)

🛡️ 数值稳定性自检与边界要点

  • 输出尺寸计算必须使用整数向下取整地板除 //,而非浮点除
  • Padding 必须只作用在后两维 (H, W),绝不能在 Batch 或 Channel 维度上补零
  • 工业实现中使用 im2col 将感受野拉平为 (H_out*W_out, Cin*Kh*Kw) 执行矩阵乘,以额外临时显存换取更高访存连续性与 GEMM 算力吞吐

💻 完整参考代码实现

import numpy as np

def conv2d_forward(
    x: np.ndarray,          # (B, C_in, H, W)
    w: np.ndarray,          # (C_out, C_in, Kh, Kw)
    b: np.ndarray = None,   # (C_out,)
    stride: int = 1,
    padding: int = 0
) -> np.ndarray:
    B, C_in, H, W = x.shape
    C_out, _, Kh, Kw = w.shape
    
    # 1. 计算输出特征图尺寸
    H_out = (H + 2 * padding - Kh) // stride + 1
    W_out = (W + 2 * padding - Kw) // stride + 1
    
    # 2. 空间零填充
    if padding > 0:
        x_pad = np.pad(x, ((0, 0), (0, 0), (padding, padding), (padding, padding)), mode='constant')
    else:
        x_pad = x
        
    out = np.zeros((B, C_out, H_out, W_out), dtype=x.dtype)
    
    # 3. 滑动窗口四层循环计算
    for h in range(H_out):
        h_start = h * stride
        h_end = h_start + Kh
        for w_idx in range(W_out):
            w_start = w_idx * stride
            w_end = w_start + Kw
            
            # 截取感受野切片: (B, C_in, Kh, Kw)
            x_slice = x_pad[:, :, h_start:h_end, w_start:w_end]
            
            # 沿输入通道与核尺寸乘加规约,输出 (B, C_out)
            # x_slice: (B, 1, Cin, Kh, Kw), w: (1, Cout, Cin, Kh, Kw)
            val = np.sum(x_slice[:, np.newaxis, :, :, :] * w[np.newaxis, :, :, :, :], axis=(2, 3, 4))
            
            if b is not None:
                val += b[np.newaxis, :]
                
            out[:, :, h, w_idx] = val
            
    return out

🧪 本地测试与正确性断言

可直接复制到本地 Python / Jupyter 验证:

import numpy as np
x = np.ones((1, 1, 3, 3))
w = np.ones((1, 1, 2, 2)) # 2x2 全 1 核
out = conv2d_forward(x, w, stride=1, padding=0)
assert out.shape == (1, 1, 2, 2)
assert np.allclose(out, 4.0), "2x2 全 1 卷积结果应全为 4.0"
print("✓ Conv2d 卷积纯手写自测通过")

🎯 核心工程追问与标准应答

Q1:Depthwise Separable Convolution(深度可分离卷积)如何大幅削减 Conv2d 的计算量?
将标准卷积拆分为两阶段:1. Depthwise Convolution:每个输入通道独立进行单通道空间卷积(计算量降为 1/Cout1/C_{\text{out}});2. Pointwise Convolution:使用 1×11 \times 1 卷积做跨通道线性混合。整体计算量被压缩为标准卷积的 1Cout+1KhKw\frac{1}{C_{\text{out}}} + \frac{1}{K_h K_w}(通常节省 80%~90% FLOPS)。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔
← 上一题: 多臂老虎机探索策略(epsilon-Greedy 与 UCB1)返回 Part G 与全部 105 题下一题: LoRA 低秩矩阵微调(前向传播与权重合并) →