
シストリックアレイを作ってみよう④【アレイ全体の設計】
これまでの設計
Pythonでのモデル設計
モデルでの動作確認
PEの設計
では、全体で動作確認してみよう。
シストリックアレイ4x4の設計
コード
`timescale 1ns / 1ps
module SystolicArray4x4 (
input wire Clock,
input wire rst_n,
// Control signals (shared across all PEs)
input wire data_clear,
input wire en_shift_right,
input wire en_shift_bottom,
// B register input (1D array from external sources)
input wire [15:0] b_reg_array_flat [0:15], // Flattened 1D array (4x4 = 16 elements)
input wire b_we_array_flat [0:15], // Flattened 1D array (4x4 = 16 elements)
// External connections for A and partial_sum (1D arrays)
input wire [15:0] a_left_in_flat [0:3], // Input A from the left (4 elements)
input wire [15:0] ps_top_in_flat [0:3], // Input partial_sum from the top (4 elements)
// Outputs for the final results (1D array)
output wire [15:0] ps_bottom_out_flat [0:3] // Bottom partial_sum outputs (4 elements)
);
//========================================================
// Internal 2D arrays (B, WE, A, partial_sum)
//========================================================
wire [15:0] b_reg_array [0:3][0:3];
wire b_we_array [0:3][0:3];
wire [15:0] a_left_in [0:3];
wire [15:0] ps_top_in [0:3];
wire [15:0] ps_bottom_out [0:3];
//========================================================
// Systolic internal wiring (A shifts right, partial_sum shifts down)
//========================================================
wire [15:0] a_wire [0:3][0:4]; // Horizontal wiring (4 rows x 5 columns)
wire [15:0] ps_wire [0:4][0:3]; // Vertical wiring (5 rows x 4 columns)
//========================================================
// Intermediate wiring: a_in and ps_in to pass to each PE (4x4 dimensions)
//========================================================
wire [15:0] a_in_val [0:3][0:3];
wire [15:0] ps_in_val[0:3][0:3];
//========================================================
// Mapping 1D arrays to 2D arrays (B, A, partial_sum inputs)
//========================================================
genvar i, j;
// Mapping B registers and WE signals
generate
for (i = 0; i < 4; i = i + 1) begin : MAP_B_REG
for (j = 0; j < 4; j = j + 1) begin : MAP_B_REG_COL
assign b_reg_array[i][j] = b_reg_array_flat[i * 4 + j];
assign b_we_array[i][j] = b_we_array_flat[i * 4 + j];
end
end
endgenerate
// Mapping A inputs from the left
generate
for (i = 0; i < 4; i = i + 1) begin : MAP_A_LEFT
assign a_left_in[i] = a_left_in_flat[i];
end
endgenerate
// Mapping partial_sum inputs from the top
generate
for (j = 0; j < 4; j = j + 1) begin : MAP_PS_TOP
assign ps_top_in[j] = ps_top_in_flat[j];
end
endgenerate
// Mapping bottom partial_sum outputs
generate
for (j = 0; j < 4; j = j + 1) begin : MAP_PS_BOTTOM
assign ps_bottom_out_flat[j] = ps_bottom_out[j];
end
endgenerate
//========================================================
// Conditional wiring for a_in_val and ps_in_val
// Passing connections to each PE without negative indices
//========================================================
generate
for (i = 0; i < 4; i = i + 1) begin : AIN_GEN
for (j = 0; j < 4; j = j + 1) begin : AIN_GEN_COL
// a_in_val[i][j]
if (j == 0) begin
// First column → a_left_in[i]
assign a_in_val[i][j] = a_left_in[i];
end else begin
// Others → a_wire[i][j-1]
assign a_in_val[i][j] = a_wire[i][j-1];
end
end
end
endgenerate
generate
for (i = 0; i < 4; i = i + 1) begin : PSIN_GEN
for (j = 0; j < 4; j = j + 1) begin : PSIN_GEN_COL
// ps_in_val[i][j]
if (i == 0) begin
// First row → ps_top_in[j]
assign ps_in_val[i][j] = ps_top_in[j];
end else begin
// Others → ps_wire[i-1][j]
assign ps_in_val[i][j] = ps_wire[i-1][j];
end
end
end
endgenerate
//========================================================
// PE array instances (4x4)
//========================================================
genvar r, c;
generate
for (r = 0; r < 4; r = r + 1) begin: ROW_BLOCK
for (c = 0; c < 4; c = c + 1) begin: COL_BLOCK
PE u_pe (
// Clock & Reset
.Clock (Clock),
.rst_n (rst_n),
// Control signals
.data_clear (data_clear),
.en_shift_right (en_shift_right),
.en_shift_bottom(en_shift_bottom),
// B inputs
.b_reg (b_reg_array[r][c]),
.b_we (b_we_array[r][c]),
// A / partial_sum inputs
.a_in (a_in_val[r][c]), // No ternary operator!
.ps_in (ps_in_val[r][c]), // No ternary operator!
// Outputs
.a_shift_to_right (a_wire[r][c]),
.partial_sum_to_bottom (ps_wire[r][c])
);
end
end
endgenerate
//========================================================
// Bottom row partial_sum → ps_bottom_out
//========================================================
generate
for (c = 0; c < 4; c = c + 1) begin : FINAL_PS
assign ps_bottom_out[c] = ps_wire[3][c];
end
endgenerate
endmodule
Cocotbでテスト
cocotbコード
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import RisingEdge, Timer
import numpy as np
# Python model (simple matrix multiplication)
def python_systolic_model(A, B):
"""
A, B: NumPy arrays with shape=(4,4)
Returns: C = A×B (4x4 matrix multiplication)
"""
return A @ B # NumPy matrix multiplication
def resolve_x(signal_handle):
"""
Return the integer value of a signal, treating any 'x' or 'z' bits as 0.
"""
try:
return int(signal_handle.value)
except ValueError:
# Replace 'x' or 'z' bits with 0
val_str = signal_handle.value.binstr.replace('x','0').replace('z','0')
return int(val_str, 2)
def data_trace_screen(dut):
"""
Display the a_reg and b_reg values for all PEs as separate matrices.
Assumes a hierarchical structure like ROW_BLOCK[r].COL_BLOCK[c].u_pe.
"""
NUM_ROWS = 4
NUM_COLS = 4
# Create 4x4 arrays for a_reg and b_reg
a_matrix = []
b_matrix = []
for r in range(NUM_ROWS):
a_row = []
b_row = []
for c in range(NUM_COLS):
pe = getattr(getattr(dut.u_systolic.ROW_BLOCK[r], f"COL_BLOCK[{c}]"), "u_pe")
a_val = resolve_x(pe.a_reg)
b_val = resolve_x(pe.b_reg)
a_row.append(a_val)
b_row.append(b_val)
a_matrix.append(a_row)
b_matrix.append(b_row)
print("\n=== Current PE State (Matrix Format) ===")
# Display a_reg matrix
print(">>> a_reg:")
print("[")
for r in range(NUM_ROWS):
# Display elements of row r separated by spaces
row_str = " ".join(str(val) for val in a_matrix[r])
print(f" [{row_str}]")
print("]")
print("")
# Display b_reg matrix
print(">>> b_reg:")
print("[")
for r in range(NUM_ROWS):
row_str = " ".join(str(val) for val in b_matrix[r])
print(f" [{row_str}]")
print("]")
print("")
@cocotb.test()
async def test_systolic_array(dut):
"""
Simulation test using cocotb.
Compares the Python model's output with the Verilog (hardware) output.
"""
# 1. Clock generation
clock = Clock(dut.Clock, 10, units="ns") # 10ns period = 100MHz
cocotb.start_soon(clock.start())
# 2. Reset sequence
dut.rst_n.value = 0
dut.data_clear.value = 1
dut.en_shift_right.value = 0
dut.en_shift_bottom.value = 0
# Initialize B values
for r in range(4):
for c in range(4):
flat_index = r * 4 + c
getattr(dut, f"b_we_array_flat[{flat_index}]").value = 0
getattr(dut, f"b_reg_array_flat[{flat_index}]").value = int(0)
# Initialize A values
for r in range(4):
getattr(dut, f"a_left_in_flat[{r}]").value = int(0)
# Initialize ps_top_in_flat
for c in range(4):
getattr(dut, f"ps_top_in_flat[{c}]").value = int(0)
# Wait for a few cycles
for _ in range(25):
await RisingEdge(dut.Clock)
dut.rst_n.value = 1
dut.data_clear.value = 0
for _ in range(5):
await RisingEdge(dut.Clock)
# 3. Generate test data for A and B (4x4 matrices)
A_np = np.random.randint(0, 10, (4, 4)) # Small values for clarity
B_np = np.random.randint(0, 10, (4, 4))
C_expected = python_systolic_model(A_np, B_np)
# Initialize a 4x4 zero matrix
C_dut = np.zeros((4, 4), dtype=int)
cocotb.log.info(f"A=\n{A_np}\nB=\n{B_np}\nExpected=\n{C_expected}")
# 4. Write B values into each PE
# Cast NumPy type to standard Python int
for r in range(4):
for c in range(4):
flat_index = r * 4 + c
getattr(dut, f"b_we_array_flat[{flat_index}]").value = 1
getattr(dut, f"b_reg_array_flat[{flat_index}]").value = int(B_np[r][c])
await RisingEdge(dut.Clock)
for c in range(4):
flat_index = r * 4 + c
getattr(dut, f"b_we_array_flat[{flat_index}]").value = 0
# Debug
print("==============INPUT B=====================")
data_trace_screen(dut)
# 5. Shift A values into the leftmost PEs and perform partial_sum shifts
for row_i in range(4 + (4 - 1)):
for r in range(4):
if row_i < 4:
getattr(dut, f"a_left_in_flat[{r}]").value = int(A_np[row_i][r])
else:
getattr(dut, f"a_left_in_flat[{r}]").value = int(0)
print("row_i=", row_i)
await RisingEdge(dut.Clock)
# Debug
print("==============Before SHIFT=====================")
data_trace_screen(dut)
# Perform right shift
dut.en_shift_right.value = 1
await RisingEdge(dut.Clock)
dut.en_shift_right.value = 0
# Wait
for _ in range(3):
await RisingEdge(dut.Clock)
# Debug
print("==============After SHIFT=====================")
data_trace_screen(dut)
# Wait
for _ in range(5):
await RisingEdge(dut.Clock)
# Shift partial_sum downward
for _ in range(4):
dut.en_shift_bottom.value = 1
await RisingEdge(dut.Clock)
dut.en_shift_bottom.value = 0
# Wait
for _ in range(2):
await RisingEdge(dut.Clock)
C_tmp = np.zeros(4, dtype=int)
for col in range(4):
C_tmp[col] = resolve_x(getattr(dut, f"ps_bottom_out_flat[{col}]"))
cocotb.log.info(f"C_tmp = \n{C_tmp}")
# Map C_tmp into C_dut from top left to bottom right
for col in range(len(C_tmp)):
row = row_i - col
if 0 <= row < C_dut.shape[0]:
C_dut[row, col] = C_tmp[col]
cocotb.log.info(f"Updated HW result during step row_i={row_i} = \n{C_dut}")
print("===============calc loop end =======================")
# Wait for stabilization
for _ in range(20):
await RisingEdge(dut.Clock)
print("=============== Output data =======================")
cocotb.log.info(f"Updated HW result during step row_i={row_i} = \n{C_dut}")
# 7. Compare Python model output with hardware output
if not np.array_equal(C_dut, C_expected):
raise cocotb.result.TestFailure(
f"Mismatch:\nHW=\n{C_dut}\nExpected=\n{C_expected}"
)
else:
cocotb.log.info("Test Passed! HW result matches Python model.")
テスト結果
1450.00ns INFO cocotb C_tmp =
[ 0 0 0 114]
1450.00ns INFO cocotb Updated HW result during step row_i=6 =
[[181 78 97 90]
[ 84 103 72 33]
[114 36 80 79]
[212 110 136 114]]
===============calc roop end =======================
=============== Output data =======================
1650.00ns INFO cocotb Updated HW result during step row_i=6 =
[[181 78 97 90]
[ 84 103 72 33]
[114 36 80 79]
[212 110 136 114]]
1650.00ns INFO cocotb Test Passed! HW result matches Python model.
1650.00ns INFO cocotb.regression test_systolic_array passed
1650.00ns INFO cocotb.regression ****************************************************************************************
** TEST STATUS SIM TIME (ns) REAL TIME (s) RATIO (ns/s) **
****************************************************************************************
** test_bench.test_systolic_array PASS 1650.00 0.08 20658.28 **
****************************************************************************************
** TESTS=1 PASS=1 FAIL=0 SKIP=0 1650.00 0.15 11017.83 **
****************************************************************************************
OK!
のようです。
考察
特になし。
所感
朝の作業は終わり。