蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。explore-pipeline-design.py
explore-pipeline-design.py165 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/verilog-pipeline-design-lab/explore-pipeline-design.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-pipeline-design.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Verilog RTL 位精确数字算法与周期仿真模型(本机未安装 iverilog/vvp/verilator/vsim/vivado)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Verilog

课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a2580.zip

下载课程关联工程包:Verilog

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2606.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习