`timescale 1ns / 1ps // Requantise an INT32 accumulator to INT8: // q = clamp( round( (acc + bias) * m0 / 2^(31 + shift) ) + zp, lo, 127 ) // m0 is the fixed-point multiplier M0 in Q0.31 (2^30 <= m0 < 2^31 for a normalised M0), // shift is the extra right shift n (0..31), so the real multiplier is M = m0 * 2^-(31+n). // Rounding is round half up: add 2^(30+n) before the arithmetic shift. // lo = zp when relu = 1 (real value 0), otherwise -128. // m0, shift and zp are inputs, so one instance serves every output channel // (per-channel scales). Three pipeline stages, one result per clock. module requant ( input logic clk, input logic rst, // synchronous, active high: clears the valid pipeline input logic in_valid, input logic signed [31:0] acc, input logic signed [31:0] bias, input logic signed [31:0] m0, input logic [4:0] shift, input logic signed [7:0] zp, input logic relu, output logic out_valid, output logic signed [7:0] q ); // Stage 1: add the bias. 33 bits, so acc + bias cannot overflow. logic signed [32:0] sum1; logic signed [31:0] m0_1; logic [4:0] sh1; logic signed [7:0] zp1; logic relu1; // Stage 2: full-precision product, 33 x 32 bits -> 65 bits. logic signed [64:0] prod2; logic [4:0] sh2; logic signed [7:0] zp2; logic relu2; logic [1:0] v; always_ff @(posedge clk) begin sum1 <= 33'(acc) + 33'(bias); m0_1 <= m0; sh1 <= shift; zp1 <= zp; relu1 <= relu; prod2 <= 65'(sum1) * 65'(m0_1); sh2 <= sh1; zp2 <= zp1; relu2 <= relu1; end // Stage 3: rounding shift, zero point, clamp. logic signed [64:0] half; logic signed [64:0] shifted; logic signed [64:0] y; logic signed [64:0] lo; always_comb begin half = 65'sd1 <<< (30 + int'(sh2)); shifted = (prod2 + half) >>> (31 + int'(sh2)); y = shifted + 65'(zp2); lo = relu2 ? 65'(zp2) : -65'sd128; end always_ff @(posedge clk) begin if (y > 65'sd127) q <= 8'sd127; else if (y < lo) q <= lo[7:0]; else q <= y[7:0]; end always_ff @(posedge clk) begin if (rst) begin v <= '0; out_valid <= 1'b0; end else begin v <= {v[0], in_valid}; out_valid <= v[1]; end end endmodule