蓝色天空网mbsky.com · 知识 · 实践 · 创造Verilog · 本地阅读预览
教程 / 编程语言 / Verilog

6.7 Verilog 流水线

阐述数字电路流水线以面积换吞吐量的核心思想,对比常数移位乘法、非流水线移位累加乘法器(mult_low)与 M 级流水线乘法器(mult_cell/mult_man)的延迟、吞吐率与寄存器资源权衡。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

流水线基本思想与吞吐率收益

硬件描述语言天然具备并行执行能力,但面对连续串行输入且单次计算需要多拍才能完成的任务时,若每笔数据都要等前一笔彻底算完才能进入,硬件吞吐率将严重受限。流水线(Pipeline)把重复运算拆分为若干专用子阶段并在时间上错开重叠执行:以 4 阶段(取衣、洗衣、烘干、装柜,各 0.5 小时)洗衣流程为例,单套串行处理 4 批需 8 小时,而配备 4 套分阶段流水线后仅需 3.5 小时即可完成 4 批;批量扩大至 N 批时,总耗时精确为 `(3 + N)` 个半小时(约为 `4 + N` 级别,首批建立延迟 2 小时,此后每半小时吐出 1 批),吞吐率随批量增大趋近 4 倍,代价则是设备与空间成本上升。

映射到数字电路中,流水线即把长组合运算路径切分为若干短组合段并在段间插入寄存器暂存中间结果,从而缩短关键路径、提高最高工作频率与数据吞吐率;其代价是增加了流水级寄存器面积与并行翻转功耗。以下以乘法器为例直观对比非流水与流水实现。

一般乘法器原理与非流水移位累加实现

在 RTL 中直接书写乘号 `*` 会由综合器映射为未知内部结构的默认乘法器,在位宽较大或高频约束下易埋下时序隐患;FPGA 虽可调用专用乘法器/DSP IP 核,但仍受位宽与跨平台限制。常数乘法常用移位相加或移位相减实现(如 `A*2` 为 `A<<1`、`A*3` 为 `(A<<1)+A`、`A*15` 可写作 `(A<<3)+(A<<2)+(A<<1)+A` 或更省加法器的 `(A<<4)-A`)。数字设计中单周期内串联 4 个及以上操作数相加常构成危险关键路径,最稳妥的是每拍只做二输入加法,因此参数可配、时序可控的流水乘法器具有重要价值。

二进制乘法与十进制竖式(如 `13 × 5 = 65`)同理:逐位检测乘数最低位,为 1 则累加移位后的被乘数,每拍执行一次累加共需 `M`(乘数位宽)个时钟周期,故习惯将较窄操作数作为乘数以缩短延迟。非流水线模块 `mult_low` 仅用一组移位累加寄存器与计数器 `cnt`,每完成 1 笔 `N×M` 乘法耗时 `M` 拍加握手间隔,在 `N=8, M=4` 的测试中处理 4~5 笔乘法需约 20~25 个时钟周期。

M 级流水线乘法器设计与面积-效率权衡

为实现不间断流水吞吐,可将单步移位累加与状态暂存封装为独立流水单元 `mult_cell`(每拍将 `mult1 << 1`、`mult2 >> 1`、累加结果 `mult1_acco` 及有效标志 `rdy` 写入级间寄存器),再在顶层 `mult_man` 中单独例化第 0 级 `u_mult_step0` 并用 `generate for` 级联其余 `M-1` 级 `mult_cell`,把前一级输出直接连至下一级输入。

在配套自校验 Testbench 中,对输入操作数施加与流水深度匹配的 `M` 拍移位延迟 `mult1_ref`/`mult2_ref`,再与输出 `res` 实时比对生成 `error_flag`。仿真验证表明:经过 4 个时钟周期的初始建立延迟后,流水线乘法器在每个时钟周期都能无停顿输出正确乘积(224 组连续数据 `error_flag` 恒为 `0`)。与 `mult_low` 相比,吞吐率提升约 4 倍,而寄存器开销也增至约 4 倍,工程中需按性能指标与芯片资源预算综合权衡。来源工程压缩包已登记未联网抓取。

离线仿真四阶段流水加速、常数移位乘法与 4 级流水线乘法器自校验

python · 阅读源码
"""Offline Verilog RTL verification lab for Chapter 28 (pipeline-design)."""
import json

VERSION = "CPython 3.12.14 offline Verilog RTL bit-accurate simulator (iverilog absent)"


def sim_mult_low(pairs, n=8, m=4):
    """Non-pipelined shift-and-add multiplier: M cycles per multiplication plus handshake gap."""
    total_cycles = 0
    results = []
    for a, b in pairs:
        acc = 0
        a_shift = a
        b_shift = b
        for _ in range(m):
            if b_shift & 1:
                acc += a_shift
            a_shift <<= 1
            b_shift >>= 1
            total_cycles += 1
        total_cycles += 1  # output ready / next handshake cycle
        results.append(acc)
    return results, total_cycles


def sim_mult_pipeline(pairs, n=8, m=4):
    """M-stage pipelined multiplier (mult_cell x M in mult_man): latency M, throughput 1/cycle."""
    stages = [{"rdy": 0, "m1": 0, "m2": 0, "acc": 0} for _ in range(m)]
    results = []
    cycles = 0
    stream = list(pairs) + [None] * m
    for item in stream:
        cycles += 1
        next_stages = []
        for idx in range(m):
            if idx == 0:
                if item is not None:
                    en, m1, m2, acci = 1, item[0], item[1], 0
                else:
                    en, m1, m2, acci = 0, 0, 0, 0
            else:
                prev = stages[idx - 1]
                en, m1, m2, acci = prev["rdy"], prev["m1"], prev["m2"], prev["acc"]
            if en:
                acco = acci + m1 if (m2 & 1) else acci
                next_stages.append({"rdy": 1, "m1": m1 << 1, "m2": m2 >> 1, "acc": acco})
            else:
                next_stages.append({"rdy": 0, "m1": 0, "m2": 0, "acc": 0})
        stages = next_stages
        if stages[m - 1]["rdy"]:
            results.append(stages[m - 1]["acc"])
    return results, cycles


def case_laundry_pipeline_speedup():
    """Verify 4-stage pipeline timing: serial 4*4=16 half-hours vs pipelined (3+4)=7 half-hours."""
    stages = 4
    batches = 4
    serial_half_hours = stages * batches       # 16 half-hours = 8.0 h
    pipe_half_hours = (stages - 1) + batches   # 7 half-hours = 3.5 h
    pipe_100_batches = (stages - 1) + 100
    expected = {
        "serial_4_batches_hours": 8.0,
        "pipelined_4_batches_hours": 3.5,
        "speedup_4_batches": 2.2857,
        "pipelined_100_batches_half_hours": 103,
    }
    actual = {
        "serial_4_batches_hours": serial_half_hours * 0.5,
        "pipelined_4_batches_hours": pipe_half_hours * 0.5,
        "speedup_4_batches": round(serial_half_hours / pipe_half_hours, 4),
        "pipelined_100_batches_half_hours": pipe_100_batches,
    }
    return {
        "name": "laundry_pipeline_speedup",
        "summary": "验证四阶段流水线模型下 4 批任务耗时由 8 小时缩短至 3.5 小时及大批量加速比",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_constant_shift_add_multiply():
    """Verify constant multiplication by shift-and-add (x2, x3, x15) and shift-subtract ((A<<4)-A)."""
    a = 13
    expected = {"mul2": 26, "mul3": 39, "mul15_add": 195, "mul15_sub": 195, "13x5": 65}
    actual = {
        "mul2": a << 1,
        "mul3": (a << 1) + a,
        "mul15_add": (a << 3) + (a << 2) + (a << 1) + a,
        "mul15_sub": (a << 4) - a,
        "13x5": (13 << 2) + 13,
    }
    return {
        "name": "constant_shift_add_multiply",
        "summary": "验证常数移位相加(×2/×3/×15)与移位相减优化及 13×5 二进制移位累加原理",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_non_pipelined_vs_pipelined_multiplier():
    """Compare mult_low vs 4-stage pipelined mult_man on the chapter's 5 test vectors."""
    pairs = [(25, 5), (16, 10), (10, 4), (15, 7), (215, 9)]
    ref = [a * b for a, b in pairs]
    res_low, cyc_low = sim_mult_low(pairs, n=8, m=4)
    res_pipe, cyc_pipe = sim_mult_pipeline(pairs, n=8, m=4)
    expected = {
        "products": [125, 160, 40, 105, 1935],
        "low_matches_ref": True,
        "pipe_matches_ref": True,
        "low_cycles": 25,
        "pipe_cycles": 9,
    }
    actual = {
        "products": res_pipe,
        "low_matches_ref": res_low == ref,
        "pipe_matches_ref": res_pipe == ref,
        "low_cycles": cyc_low,
        "pipe_cycles": cyc_pipe,
    }
    return {
        "name": "non_pipelined_vs_pipelined_multiplier",
        "summary": "对比非流水乘法器 mult_low(25 周期)与 4 级流水乘法器 mult_man(9 周期)的输出与吞吐",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_pipeline_continuous_stream_self_check():
    """Verify 224 continuous streaming multiplications pass error_flag == 0 with 4-cycle latency."""
    pairs = []
    cur_m1 = 15
    for m2 in (7, 1, 15, 3, 11, 4, 9):
        for _ in range(32):
            cur_m1 = (cur_m1 + 1) & 0xFF
            pairs.append((cur_m1, m2))
    res_pipe, total_cycles = sim_mult_pipeline(pairs, n=8, m=4)
    errors = sum(1 for (a, b), p in zip(pairs, res_pipe) if a * b != p)
    expected = {"stream_len": 224, "total_cycles": 228, "error_flag_count": 0}
    actual = {"stream_len": len(res_pipe), "total_cycles": total_cycles, "error_flag_count": errors}
    return {
        "name": "pipeline_continuous_stream_self_check",
        "summary": "验证 224 组不间断串行输入通过 4 级流水乘法器自校验零错误(吞吐 1 结果/拍)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_laundry_pipeline_speedup(),
        case_constant_shift_add_multiply(),
        case_non_pipelined_vs_pipelined_multiplier(),
        case_pipeline_continuous_stream_self_check(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在 CPython 3.12.14 离线脚本中验证洗衣店流水线加速比、移位相加/相减乘法、非流水与流水乘法器周期对比及 224 组连续流零误差全部通过。
离线仿真四阶段流水加速、常数移位乘法与 4 级流水线乘法器自校验

所需环境:Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。

当前源码 SHA256:ca6876892c1230c0c30c7d7c3894d5d37e5bd3a3c298ae5c6e0b8c0f4091f029

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载6.7 Verilog 流水线实验

所需环境:Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。

ZIP SHA256:191b846105df31d32a51f6db9cd3f5a89d828f94634db9ed22f5ea314dfc41f4

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

对于 `N=8`、`M=4` 的无符号流水线乘法器,为什么建议把位宽更窄的数放到乘数端口 `M`?流水线设计提升的是单笔运算延迟还是吞吐率?

展开参考解答

流水级数等于乘数位宽 `M`,将较窄操作数作为乘数既能减少流水级建立延迟(4 拍而非 8 拍),也能将级联寄存器与加法器资源减半;流水线并未缩短单笔运算从输入到输出的端到端延迟(仍为 `M` 拍),而是通过多笔运算重叠执行大幅提升了稳态吞吐率(达到 1 结果/拍)。

规范与官方依据