Lecture 2 · High-Level Synthesis: From C++ to Hardware

Hardware Accelerators for Machine Learning · Lecture 02。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: Stanford CS 217 Hardware Accelerators for Machine Learning (Winter 2026), Lecture 2 · Thu 01/08/2026 · High-Level Synthesis. Lab 0 (overview of HLS and AWS FPGA prototyping) is in progress. Reading: the schedule lists none for this session. These notes draw on standard HLS references:

  • G. De Micheli, Synthesis and Optimization of Digital Circuits (1994), chapters on scheduling and binding;
  • J. Cong et al., “High-level synthesis for FPGAs: from prototyping to deployment”, IEEE TCAD 2011;
  • B. R. Rau, “Iterative modulo scheduling”, MICRO 1994;
  • L. Carloni, K. McMillan, A. Sangiovanni-Vincentelli, “Theory of latency-insensitive design”, IEEE TCAD 2001;
  • B. Khailany et al., “A modular digital VLSI flow for high-productivity SoC design”, DAC 2018 (the MatchLib / object-oriented HLS methodology behind MAGNet, a Lecture 3 reading);
  • R. Kastner, J. Matai, S. Neuendorffer, Parallel Programming for FPGAs (2018, open book).

Basis: The slides are not public. The topic list follows the schedule and Lab 0’s theme. The algorithms are the textbook ones, and so are the definitions of ASAP/ALAP, list scheduling, II, ResMII/RecMII and ready/valid. A real HLS tool cannot run in these notes, so the experiments use a toy HLS engine and a channel simulator written for these notes (hls.py, channels.py). Their latencies and some cell areas are stated assumptions. All experimental numbers come from those programs and do not reflect what was said in class. Code: code/lecture02/ (4 scripts + 2 modules; each script runs in about a second) Reading time: 4 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain why high-level synthesis exists — the gap between how fast ML moves and how slowly hand-written RTL is designed and verified — and what remains the designer’s job when a tool writes the RTL.
  2. Describe the four decisions of an HLS tool — allocation, scheduling, binding, control generation — and recognize them in a synthesis report.
  3. Compute ASAP and ALAP schedules and mobility for a dataflow graph, and run list scheduling by hand under unit and memory-port limits.
  4. Explain why a sum written as a chain has a much longer critical path than a tree, and why a tool may not turn one into the other for floating point.
  5. Estimate the cost of sharing a unit (multiplexers, registers, latency), and say when sharing pays.
  6. Define initiation interval (II), pipeline depth and the loop-time formula (N−1)⋅II+D(N-1)\cdot II + D; compute ResMII and RecMII; explain modulo scheduling.
  7. Remove each kind of II limit with the matching design pattern: ports/banks, shift registers and line buffers, interleaved accumulators, look-ahead, strength reduction — and state what each does to area and numerics.
  8. Predict the effect of the directives UNROLL, PIPELINE, ARRAY_PARTITION alone and together, and read an area–latency Pareto front.
  9. Explain latency-insensitive design: ready/valid handshakes, back-pressure, why registered ready needs 2-entry buffers, how to size FIFOs for burstiness and reconvergent paths, and how FIFO sizing can deadlock a design.
  10. Say what an FPGA prototype measures faithfully about a future ASIC (cycles, II, function) and what it does not (frequency, area, energy).

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
C/C++ loops and arrays; what a clock, a register and a multiplexer aredataflow graphs, scheduling, binding, pipelining, IIthe SIMD PE built with these ideas (L3), systolic arrays (L5)
Lecture 1: Horowitz’s energy and area tablearea of units, registers, multiplexers, SRAM banks (45 nm model)memory banking and global buffers (L7)
a little Pythona toy HLS engine and a cycle-level channel simulatorthe NoC and top level of the accelerator (L8)

No HLS tool or FPGA is needed. If “a register holds a value from one clock edge to the next” is new, read §2.1 slowly.

0.3 Map

§1  why HLS: the design gap; what a tool decides and what it does not
§2  from C++ to a dataflow graph; ASAP, ALAP, mobility                       ← code 01 (Part 1)
§3  scheduling under constraints; chains vs trees; floating point             ← code 01 (Parts 2-3)
§4  binding: the cost of sharing (multiplexers, registers)                    ← code 01 (Parts 4-5)
§5  pipelining: II, ResMII, RecMII, modulo scheduling, design patterns         ← code 02
§6  directives and the design space; Pareto fronts; line buffers               ← code 03
§7  latency-insensitive design: ready/valid, FIFOs, slack, deadlock            ← code 04
§8  FPGAs and cloud prototyping (Lab 0)
§9 summary   §10 pitfalls   §11 exercises   §12 further reading   §13 next lecture

Suggested order: §1 → §2 → run 01 → §3–§4 → §5 → run 02 → §6 → run 03 → §7 → run 04 → §8.

0.4 Notation

SymbolMeaning
DFGdataflow graph: nodes = operations, edges = “this value is needed by that operation”
latency of an operationcycles from its start to its result (fp32 add 4, multiply 3 in our library)
ASAP / ALAPearliest / latest start of an operation without / with a deadline
mobilityALAP − ASAP: how far an operation can slide without lengthening the schedule
IIIIinitiation interval: cycles between the starts of consecutive loop iterations
DDpipeline depth: cycles of one iteration from start to end
ResMII, RecMII, MIIlower bounds on II from resources, from recurrences, and their maximum
UU, PP, LLunroll factor, partition factor (banks per array), number of accumulators
ready / valid / firereceiver can accept / sender has data / both, so the data moves this cycle

The library of the toy tool (assumptions, typical of an ASIC library near 1 GHz): fp32 add 4 cycles, fp32 multiply 3 cycles, both pipelined; fp32 divide 12 cycles, not pipelined; int8 multiply and int32 add 1 cycle; SRAM read 1 cycle. Areas: Horowitz’s 45 nm units (fp32 adder 4,184 µm², multiplier 7,700 µm²; int8 multiplier 282 µm², int32 adder 137 µm²). A register bit is 4.5 µm² and a 2:1 multiplexer bit 1.9 µm². SRAM costs 0.7 µm²/bit plus 2,500 µm² of periphery per bank, and a second port adds 50%. These last three are assumptions, and each is stated next to its constant in hls.py.


1. Why high-level synthesis?

1.1 Intuition: describing hardware cycle by cycle is assembly programming

Register-transfer level (RTL) code — Verilog, VHDL — describes hardware cycle by cycle and wire by wire: in this cycle, this register takes the sum of those two registers; this multiplexer selects input 2 when the state machine is in state 7. Every pipeline stage, every handshake and every state of the controller is written by hand. That is the hardware equivalent of writing a program in assembly. It is precise and it gives total control, but it is slow to write and slow to change. Above all, it is slow to verify: every change can break timing assumptions somewhere else.

High-level synthesis (HLS) lets the designer write the algorithm — in C++ or SystemC, with loops, arrays and function calls — and generates the RTL. The designer does not disappear: they still choose the architecture, the memories and the interfaces, and steer the tool with directives. What disappears is writing out the schedule and the controller by hand.

1.2 Background: the design gap

Three pressures make HLS attractive for ML accelerators in particular:

  • The models move faster than chips. A chip takes years from specification to silicon. In that time the important layers of ML change: convolutions gave way to attention, fp32 to bf16 to fp8 to 4-bit formats (Lecture 4). A team that can re-target a block in weeks instead of months keeps up.
  • Design-space exploration needs many variants. Lecture 1 showed that the right number of MACs, the size of the buffers and the precision depend on the workload. Comparing ten variants of a processing element in RTL means writing ten designs. In HLS it often means changing a template parameter or a directive.
  • Verification dominates. C++ models run orders of magnitude faster than RTL simulation, and the same C++ testbench checks both the algorithm and (through co-simulation) the generated RTL.

The CS 217 labs follow this methodology: blocks are written in C++/SystemC, synthesized with an HLS tool, and evaluated on cloud FPGAs. The style is the one NVIDIA Research published as “object-oriented HLS” with the MatchLib library. Khailany et al. (DAC 2018) describe a flow built on reusable, latency-insensitive C++ components and report large productivity gains for SoC blocks. MAGNet (Lecture 3’s reading) is an accelerator generator built the same way.

1.3 What HLS decides — and what it does not

An HLS tool turns a function into a datapath (functional units, registers, multiplexers, memories) plus a controller (a finite-state machine that sequences the datapath). Along the way it makes four decisions (§2–§5):

DecisionQuestionWhere in this lecture
allocationhow many adders, multipliers, memory ports?§3, §6
schedulingin which cycle does each operation start?§2, §3, §5
bindingwhich unit instance runs each operation; which register holds each value?§4
controlwhich states does the FSM have, which signals does it drive?§4

What the tool does not decide is just as important: the algorithm (a chain or a tree, a line buffer or not), the memory organization (how data is laid out and reused), the interfaces between blocks, and the numeric formats. These are the decisions that move performance by 10× or more, and they remain the designer’s. The theme of this lecture is that HLS is not “compiling software into hardware”. The C++ describes a structure, and writing it well requires thinking about that structure.


2. From C++ to a dataflow graph

2.1 The front end

Take the inner loop of every ML accelerator, a dot product:

float dot(float a[8], float b[8]) {
    float acc = 0;
    for (int i = 0; i < 8; i++)
        acc += a[i] * b[i];
    return acc;
}

An HLS front end parses this into a control-dataflow graph. Straight-line code becomes a dataflow graph (DFG): one node per operation, one edge per value passed from one operation to another. Loops become control structure around a loop-body DFG. Arrays become memories (SRAM, or registers if small and partitioned), scalars become wires or registers, and the function’s arguments become ports. If the loop is fully unrolled, the DFG of the whole function is eight loads from a, eight from b, eight multiplies and seven adds:

a[0] b[0]  a[1] b[1]  a[2] b[2] ...          chain (the C++ order):  ((((p0 + p1) + p2) + p3) + ...)
   \ /        \ /        \ /                 tree  (rewritten):      ((p0 + p1) + (p2 + p3)) + ...
   *0         *1         *2 ...

The toy tool of this lecture builds the same graph by tracing. Kernels are ordinary Python, and operator overloading turns every +, *, a[i] and a[i] = v into a node instead of a number (hls.py, class Kernel):

k = hls.Kernel("dot8", dtype="fp32")
a, b = k.array("a", 8), k.array("b", 8)
k.output("y", hls.reduce_sum([a[i] * b[i] for i in range(8)], style="tree"))

2.2 The hardware model behind a schedule

To schedule, a tool needs a library: for every operation, which unit runs it, its latency in cycles at the target clock, whether the unit is pipelined (accepts a new operation every cycle) and its area. The library of these notes is listed in §0.4. Two rules complete the model:

  • No chaining: every operation starts at a clock edge and delivers its result latency cycles later. Real tools can chain several fast operations in one cycle if the clock period allows; the principle is the same.
  • Memories have ports: a single-port SRAM bank serves one access per cycle. Loads and stores compete for ports exactly as multiplies compete for multipliers. This is the most underestimated constraint in HLS designs.

2.3 ASAP, ALAP and mobility

The ASAP (as-soon-as-possible) schedule starts every operation the moment its operands are ready. Its length is the critical path: no amount of hardware can make the kernel faster. The ALAP (as-late-as-possible) schedule starts every operation as late as possible without exceeding a deadline — by default the critical path itself. Mobility = ALAP − ASAP is the slack of an operation: 0 means it is on the critical path.

Script 01, Part 1 computes them for a 4-element dot product, with operands in registers:

op (chain)ASAPALAPmobilityop (tree)ASAPALAPmobility
*0, *1000*0–*3000
*2044+0 (*0+*1)330
*3088+1 (*2+*3)330
+0, +1, +23, 7, 113, 7, 110+2770

The chain’s critical path is 15 cycles (3 + 3 × 4), the tree’s 11 (3 + 2 × 4). In the chain, the late multiplies have slack: *3 can wait 8 cycles. That slack is what a scheduler uses when units are scarce.


3. Scheduling under constraints

3.1 Why we need heuristics

With unlimited units, ASAP is optimal. With limited units — one multiplier, one adder, one memory port — the question “what is the shortest schedule?” is NP-hard in general. HLS tools therefore use heuristics. The classic one is list scheduling:

Walk through the cycles 0, 1, 2, …. In each cycle, collect the ready operations (all operands available), sort them by a priority, and start as many as there are free units. The rest wait.

The usual priority is the ALAP time (least slack first): an operation that will delay the whole kernel if it waits goes first. The dual problem — fix the latency and minimize the units — is solved by force-directed scheduling (Paulin & Knight, 1989), which spreads operations evenly over the allowed cycles so that the peak number of units in use is low. Both appear in commercial tools in some form.

3.2 Experiment: what limits an 8-element dot product?

Script 01, Part 2 list-schedules the tree-shaped 8-element fp32 dot product. It varies the memory organization of a and b (rows) and the unit limits (columns):

arrays a, b1 mul, 1 add2 mul, 1 add4 mul, 2 add8 mul, 4 add
1 bank, 1 port23232323
1 bank, 2 ports23191919
2 banks, 1 port23191919
registers22181615

(latency in cycles; critical path 16 with SRAM, 15 with registers)

Read the first row: with each array in one single-port bank, the 8 loads of a take 8 cycles whatever the arithmetic, so a second multiplier changes nothing. Only when the memories deliver more operands per cycle do more units help. This is Lecture 1’s roofline at the scale of one block: if the “bandwidth” (ports) is the bottleneck, adding “compute” (units) is wasted. The printed schedule shows it directly. The mul column is busy from cycle 1 to 8, one product per cycle, because each product waits for its two loads.

The area table of the same run has a second lesson. With the arrays in one bank and unlimited units, the greedy scheduler grabs a second adder that buys no latency (23,174 vs 19,111 µm²). “Unlimited” is not “optimal”: a real tool’s allocation step decides how many units to build (§5.3).

Two schedules of the 8-element dot product

Figure (script 01): top, arrays in one single-port bank with 1 multiplier and 1 adder (23 cycles). The loads serialize, and the adder idles while it waits. Bottom, arrays in registers with 4 multipliers and 2 adders (16 cycles). A box marks the cycle an operation is issued; the thin bar is the rest of its latency, during which the pipelined unit already accepts new work.

3.3 Chains, trees, and why floating point is special

The chain and the tree contain the same n−1n-1 adders, but their critical paths differ enormously (script 01, Part 3, operands in registers, unlimited units):

nnfp32 chainfp32 treeint8 chainint8 tree
8311584
6425527647
2561023352569

The chain grows like n×n \times (add latency), the tree like log⁡2n×\log_2 n \times (add latency). So why does a tool not rewrite the chain as a tree automatically? Because floating-point addition is not associative: (a+b)+c(a+b)+c and a+(b+c)a+(b+c) round differently. Part 3 evaluates both versions operation by operation in float32 on 500 random length-64 vectors:

value
fp32 results where chain ≠ tree (bitwise)423 of 500 (85%)
mean |chain − exact| (exact = float64)8.4 × 10⁻⁷
mean |tree − exact|4.5 × 10⁻⁷
int8 × int8 → int32: results where chain ≠ tree0 of 500

Neither float result is “wrong” — the tree even happens to be slightly more accurate. But they are different. A tool that changed the order without permission would make the hardware disagree with the C++ reference model, and every test that compares bit-exact outputs would fail. So tools preserve the order of float operations unless told otherwise (a “relaxed” floating-point option, like -ffast-math in software), and the designer writes the tree. Integer addition is associative, so tools rebalance integer sums freely — another quiet advantage of integer and fixed-point datapaths (Lecture 4).


4. Binding: the cost of sharing

4.1 Functional units, registers, multiplexers

Once operations have start times, binding assigns each one to a unit instance and each value to a register:

  • Unit binding. Operations that never overlap in time can share a unit. Fewer units means less area — but every input of a shared unit now has several possible sources, so it needs a multiplexer. A unit shared by kk operations with different operands needs a k:1k{:}1 multiplexer per input, i.e. (k−1)(k-1) 2:1 multiplexers per bit.
  • Register binding. A value produced in cycle pp and last used in cycle ℓ>p\ell > p must be stored during [p,ℓ)[p, \ell). Two values whose lifetimes do not overlap can share a register. The left-edge algorithm (sort lifetimes by start, pack greedily) achieves the minimum: the maximum number of values alive at once.
  • Control. The FSM has one state per cycle of a straight-line schedule. In each state it drives the multiplexer selects and the register enables.

Script 01, Part 5 prints the binding of the 1-multiplier, 1-adder schedule. The multiplier runs all 8 products, so each of its inputs selects among 8 sources: 7×32=2247 \times 32 = 224 multiplexer bits per input. The adder runs 7 additions: 192 bits per input. Total: 832 multiplexer bits (1,581 µm²), plus 64 register bits and an FSM with 23 states.

4.2 Experiment: when does sharing pay?

Script 01, Part 4 schedules one pixel of a 3×3 convolution (9 multiply-accumulates) with 1 to 9 multipliers. It measures logic = units + registers + multiplexers:

units (limit)int8: latencyint8: logic µm²fp32: latencyfp32: logic µm²
1 mul, 1 add121,9092614,860
3 mul, 2 add72,2482133,791
9 mul, 8 add53,6441986,666
  • int8. Sharing one multiplier nine ways saves 2,667 µm² of units but adds 608 µm² of multiplexers and more than doubles the latency. Area × latency hardly moves (23 vs 18 thousand), and it is lowest in between, at 3 multipliers. An 8-bit multiplier (282 µm²) is not much bigger than the multiplexers needed to share it.
  • fp32. A unit is ~30× larger, so sharing saves real area — 14,860 vs 86,666 µm² — for 1.4× the latency. Area × latency is lowest with a single multiplier.

The rule of thumb: cheap units gain little from sharing; expensive units gain a lot. This is one reason ML accelerators replicate thousands of small int8 MACs without sharing, while expensive special-function units (exp, divide, Lecture 6) are shared among many lanes. Note also the column “used” in the script output: when allowed 8 adders, the binder used only 4. A pipelined unit is free again one cycle after it accepts an operation, so a good binder reuses it in later cycles.

4.3 Reading an HLS report

Everything above has a name in a tool’s report:

This lectureFPGA HLS reportASIC HLS report
latency (cycles), FSM stateslatency (cycles), “interval”latency, throughput
multipliers, addersDSP slices (multipliers), LUTs (adders)area of operators
register bitsFF (flip-flops)sequential area
multiplexer bitsLUTscombinational area
SRAM banksBRAM / URAM blocksmemory macros

5. Pipelining

5.1 Intuition: an assembly line

Most of an accelerator’s time is spent in loops. A non-pipelined loop executes one iteration after another: if one iteration takes DD cycles, NN iterations take N⋅DN \cdot D. A pipelined loop starts a new iteration every IIII cycles, before the previous ones finish — like an assembly line where a new car enters every minute although each car spends an hour on the line:

Tloop=(N−1)⋅II+D.T_{\text{loop}} = (N - 1)\cdot II + D .

For large NN, the time per iteration is IIII, not DD. The initiation interval decides the throughput; the depth only adds a one-time fill. That is why designers fight for II=1II = 1 and accept a longer depth.

Script 02, Part 1 pipelines y[i] = alpha * x[i] + y[i] (fp32, N=1024N = 1024, depth 9):

versionIIcycles
not pipelined—9,216
pipelined, y single-port22,056
pipelined, y dual-port11,032

With II = 1 the same units do 8.9× more work per cycle. But II = 1 needed a dual-port y. Each iteration reads and writes y, and a single port serves only one of the two per cycle.

5.2 What limits II

Two kinds of constraints bound the II from below:

  • Resources (ResMII). If each iteration uses a resource class uu times and there are cc instances, then II≥⌈u/c⌉II \ge \lceil u/c \rceil. Three loads from one single-port array per iteration give II≥3II \ge 3. A non-pipelined unit counts its whole latency per use. And because one operation is bound to the same unit in every iteration, it forces II≥II \ge its occupancy no matter how many units exist.
  • Recurrences (RecMII). A loop-carried dependence — iteration i+1i+1 needs a value computed in iteration ii — forms a cycle in the graph. If the cycle has total latency Λ\Lambda and spans δ\delta iterations, then II≥⌈Λ/δ⌉II \ge \lceil \Lambda / \delta \rceil: iteration i+δi+\delta cannot start its part of the cycle before iteration ii has finished it. acc += a[i]*b[i] in fp32 has a cycle through the 4-cycle adder with δ=1\delta = 1, so II≥4II \ge 4.

MII=max⁡(ResMII,RecMII)MII = \max(\text{ResMII}, \text{RecMII}) is a lower bound. The tool then searches for a schedule that achieves it.

5.3 Modulo scheduling

In a pipelined loop, an operation placed at cycle tt of its iteration uses its unit at cycles t,t+II,t+2II,…t, t+II, t+2II, \dots — one use per iteration. So the scheduler only has to make sure that, modulo II, no unit is double-booked. It keeps a modulo reservation table with IIII rows per resource. Rau’s iterative modulo scheduling (1994) tries II=MII,MII+1,…II = MII, MII+1, \dots and, for each, places operations in priority order, evicting and re-placing (“backtracking”) when a placement fails.

The toy engine (modulo_schedule) is a simplified version:

  1. Allocation: give each unit class the fewest instances that could work at this II, ⌈\lceiluses / II⌉\rceil. At II = 4, four multiplies per iteration need one multiplier.
  2. Forward pass: place each operation at the earliest cycle that respects its operands and has a free modulo slot.
  3. Backward pass: slide each operation as late as its consumers allow (if a slot is free). An operation placed too early stretches a recurrence. In y=a y−1+xy = a\,y_{-1} + x, starting the multiply long before the add needs it lengthens the cycle from one add to the next.
  4. Check every loop-carried constraint. If something fails, try II + 1.

It does not backtrack. On the 19 loops of script 02 it reaches MII every time, and §6.3 shows a case where it does not.

Registers in a pipeline. A value that lives TT cycles is overwritten by the next iteration after IIII cycles. So it needs ⌈T/II⌉\lceil T/II\rceil copies — modulo variable expansion, or rotating registers. Script 02, Part 5 found a beautiful special case. With 4 accumulators, a 4-cycle adder and II = 1, the partial sums need zero registers: each sum leaves the adder in the very cycle the next update of the same accumulator needs it, so the adder’s 4 pipeline stages are the 4 accumulators. With 8 accumulators the extra four need 128 register bits.

5.4 Removing resource limits: the 3-tap FIR filter

Script 02, Part 2 runs yi=c0xi+c1xi+1+c2xi+2y_i = c_0 x_i + c_1 x_{i+1} + c_2 x_{i+2} (fp32, 1024 outputs):

versionloads/iterResMIIIIcycleslogic µm²memory µm²
x in 1 single-port bank3333,08312,82550,920
x dual-port3222,06020,40363,661
x in 3 cyclic banks3111,03632,40955,920
shift register1111,03532,04450,920

Each fix makes a different trade:

  • More ports cost memory area (a dual-port cell is larger).
  • Cyclic partitioning puts xi,xi+1,xi+2x_i, x_{i+1}, x_{i+2} in three different banks. But which bank holds xix_i rotates as ii advances, so the hardware needs a crossbar between banks and loads (365 µm² of multiplexers here).
  • A shift register is the algorithmic fix: xi+1x_{i+1} and xi+2x_{i+2} were already loaded in the previous iterations, so keep them in two registers. One load per iteration remains, with no extra port or bank. The slow version is slow because it re-reads data it already had. Removing redundant memory traffic is the same idea as Lecture 1’s tiling and Lecture 5’s systolic arrays.

All four versions produce the same filter (max error vs float64 1.2 × 10⁻⁷, float32 rounding).

5.5 Removing recurrence limits: accumulators and look-ahead

Script 02, Part 3:

loopRecMIIIIcycles (N = 1024)
fp32 dot product, 1 accumulator444,100
2 accumulators222,054
4 accumulators111,031
int8 dot product, 1 accumulator111,026
IIR yi=a yi−1+xiy_i = a\,y_{i-1} + x_i777,169
IIR look-ahead yi=a2yi−2+(a xi−1+xi)y_i = a^2 y_{i-2} + (a\,x_{i-1} + x_i)444,106
  • Interleaved accumulators. Iteration ii adds into partial sum i mod Li \bmod L, which was last written LL iterations earlier. The recurrence now spans LL iterations: RecMII=⌈4/L⌉RecMII = \lceil 4/L \rceil. After the loop, an epilogue adds the LL partial sums. The int8 loop never had the problem: a 1-cycle adder allows II = 1 with one accumulator. This is one more reason integer accumulation is pleasant in hardware.
  • Look-ahead. Substituting the recurrence into itself, yi=a(a yi−2+xi−1)+xiy_i = a(a\,y_{i-2} + x_{i-1}) + x_i, gives a recurrence of distance 2. The same 7-cycle multiply-add cycle now constrains II only to ⌈7/2⌉=4\lceil 7/2\rceil = 4. The price is one more multiply-add per sample.

Both transformations change the rounding, so the designer must accept them. A tool must not. The dot product with 4 accumulators has mean error 1.8 × 10⁻⁶ vs 3.0 × 10⁻⁶ with one (100 random length-256 vectors): different, not worse. Both IIR versions match a float64 recursion to ~10⁻⁶.

Pipelined dot product with 1 vs 4 accumulators

Figure (script 02): iterations of the fp32 dot product. Left: with one accumulator each iteration’s add must wait for the previous one (II = 4). Right: four interleaved accumulators let a new iteration start every cycle (II = 1); the four adds in flight belong to four different partial sums.

5.6 Non-pipelined units and strength reduction

Script 02, Part 4 normalizes a vector, yi=xi/sy_i = x_i / s, with a 12-cycle iterative divider:

versionIIcycles/element
1 divider1212
2 dividers1212
unroll 2, 2 dividers126
unroll 4, 4 dividers123
r=1/sr = 1/s once, then multiply11

A second divider does not help by itself, because one operation is bound to one unit. Unrolling gives each divider its own division. The usual fix is strength reduction: compute the reciprocal once outside the loop and multiply. That is 12× faster with a pipelined multiplier — but in float32, x/sx/s and x⋅(1/s)x \cdot (1/s) differ in 33% of cases (by one unit in the last place, for s=3s = 3). Again a numerical decision that belongs to the designer. Lecture 6 comes back to this when softmax and normalization need division and reciprocal square roots on a vector unit.


6. Directives and the design space

6.1 The knobs

HLS tools accept directives (pragmas or a separate script) that restructure loops and memories without changing the C++ function. The three that matter most for accelerators:

float dot(float a[256], float b[256]) {
#pragma HLS ARRAY_PARTITION variable=a cyclic factor=P   // split a into P banks: a[i] lives in bank i mod P
#pragma HLS ARRAY_PARTITION variable=b cyclic factor=P
    float acc[L] = {0};                                 // L partial sums: a CODE change, not a directive
    for (int i = 0; i < 256; i += U) {
#pragma HLS PIPELINE II=1                               // overlap iterations, aiming at II = 1
        float s = 0;
        for (int u = 0; u < U; u++) {
#pragma HLS UNROLL                                      // replicate the body U times (U products per iteration)
            s += a[i + u] * b[i + u];
        }
        acc[(i / U) % L] += s;
    }
    return acc[0] + acc[1] + acc[2] + acc[3];           // epilogue (for L = 4)
}

(The syntax shown is Vitis-HLS-like; Catapult and other tools spell the same ideas differently, e.g. #pragma hls_unroll yes.) In the DFG:

  • UNROLL copies the loop body: more operations per iteration, fewer iterations.
  • ARRAY_PARTITION splits a memory into banks: more ports.
  • PIPELINE overlaps iterations.

Other common directives: DATAFLOW (run consecutive functions or loops concurrently, connected by FIFOs — §7), INLINE (dissolve a function into its caller) and INTERFACE (how arguments become ports or AXI buses).

6.2 Experiment: 108 designs of a dot product

Script 03 synthesizes every combination of U∈{1,…,32}U \in \{1,\dots,32\}, P∈{1,…,32}P \in \{1,\dots,32\}, pipelining on/off and L∈{1,4}L \in \{1, 4\}. Cycles of the pipelined design with L=4L = 4:

cyclesP = 1P = 2P = 4P = 8P = 16P = 32
U = 1271271271271271271
U = 2276147147147147147
U = 428215287878787
U = 828615892595959
U = 32310170102705243

Three lessons:

  1. Unrolling without partitioning does nothing. With P=1P = 1, U=32U = 32 is no faster than U=1U = 1 (310 vs 271 cycles): 32 products per iteration still need 32 loads through one port.
  2. Partitioning without unrolling does nothing either. At U=1U = 1 one load per array per iteration is all the loop needs; extra banks only cost periphery.
  3. Speed lives on the diagonal P=UP = U, where every copy of the body has its own port: 87 cycles at 4, 43 at 32. Beyond P=UP = U, area grows and speed does not.

The Pareto front — the designs that no other design beats in both cycles and area — consists only of pipelined, 4-accumulator, diagonal designs:

U = Pcyclesarea µm²
127128,353
214745,237
48779,005
859146,541
1647281,613
3243551,757

The front spans 6× in cycles and 19.5× in area. Notice the diminishing returns at the fast end: from U=16U = 16 to U=32U = 32 the area doubles for 9% fewer cycles. The loop has only 8 iterations left, so the fixed depth and epilogue dominate. Which point is “best” depends on the budget, and that is exactly why tools take directives instead of deciding for you. Notice also what is not on the front: no non-pipelined design survives. Pipelining with enough accumulators is the cheapest speedup of all. At U=P=1U = P = 1 it turns 2,048 cycles into 271 with the same single multiplier and adder.

Design space of the dot product

Figure (script 03): every design’s cycles vs area (log-log). The Pareto front (black) runs along the U = P diagonal of pipelined, 4-accumulator designs.

6.3 Restructuring beats directives: the line buffer

A 3×3 convolution reads, for every output pixel, a 3×3 window of the image — nine loads, of which six were already read for the neighbouring pixel. Script 03, Part 4 compares, on a 32×32 int8 image:

variantimage loads / pixelII (9 multipliers)II (3)II (1)
naive, image in single-port memory9999
naive, dual-port9559
naive, 9 cyclic banks9239
line buffers + window registers1139

The line buffer is the classic HLS image-processing structure. Pixels arrive once, in raster order. Two row buffers (each one image row wide, dual-port) hold the two previous rows, and nine registers hold the window. For each new pixel: read the two pixels above it from the line buffers, shift the column up, shift the window left, insert the new column. One image load per pixel remains, and every pixel is fetched from the image exactly once. Once memory is no longer the limit, the multipliers set the pace (3 multipliers → II = 3). All variants match a numpy reference exactly on the valid pixels.

The 9-bank row is an honest failure of the toy scheduler. ResMII is 1 (nine loads, nine banks), but the offsets rW+crW + c are not all distinct modulo 9 (offset 1 and offset 2W=642W = 64 share a bank). The scheduler does not search for the load delays that would separate them, so it stops at II = 2. A cleverer scheduler would find II = 1 (Exercise 7). A real tool might find it, or might report the conflict. Either way, a designer who writes a line buffer never has to wonder.

6.4 How designers use this

In practice an HLS designer:

  1. writes a functional C++ model and a testbench;
  2. restructures the code for the hardware: trees instead of chains, line buffers and shift registers, explicit partial sums, fixed-size arrays, bit-accurate types;
  3. applies directives and reads the reports: II, latency, resources;
  4. explores the design space — often by sweeping template parameters, exactly like script 03;
  5. verifies the RTL against the C++ testbench (co-simulation);
  6. only then looks at timing, area and power from the downstream tools.

Steps 2 and 4 are where accelerator design happens. The tool automates the rest.


7. Latency-insensitive design

7.1 Why blocks talk through handshakes

An accelerator is many blocks: processing elements, vector units, buffers, a network-on-chip, DMA engines. If block A assumed that block B’s result arrives exactly 7 cycles after the request, then re-pipelining B to meet timing (making it 8 cycles) would break A. Every change would ripple through the design. Latency-insensitive design (Carloni et al., 2001) removes such assumptions. Blocks communicate through channels with a handshake, so correctness never depends on how many cycles a block or a wire takes.

The ubiquitous protocol is ready/valid (AXI-Stream, MatchLib Connections, most on-chip interfaces):

  • the sender raises valid when it has data on the bus;
  • the receiver raises ready when it can accept data;
  • the data moves — the handshake fires — in every cycle where both are high;
  • a sender with valid high must hold its data until it fires (no take-backs).

When the receiver is not ready, the sender waits: back-pressure propagates upstream, block by block, without any global controller. FIFOs between blocks decouple their timing.

In MatchLib-style SystemC, a block’s ports are typed channels and its code reads like software:

// sketch in the style of MatchLib Connections (not a complete module)
Connections::In<int16_t>  in;      // a ready/valid input port
Connections::Out<int32_t> out;     // a ready/valid output port

void run() {                       // a SystemC thread: loops forever
    int32_t acc = 0;
    while (true) {
        int16_t x = in.Pop();      // blocks (waits for valid) until data arrives
        acc += x * x;
        out.Push(acc);             // blocks while the receiver is not ready
    }
}

The HLS tool turns Pop and Push into handshake logic and the loop into a pipelined datapath. The channels between blocks can be configured as combinational wires, pipeline registers, bypass buffers or FIFOs of a given depth. That choice is the subject of the rest of this section.

7.2 One handshake, cycle by cycle

Script 04, Part 1 connects a source to a sink through a 2-entry FIFO. The sink is ready 2 cycles out of 3:

cyclesrc validFIFO readyfiredata inoccupancysink readyfiredata out
0111d011.
1111d1111d0
2111d22..
31..d3111d1
4111d3111d2

In cycle 3 the FIFO was full at the start of the cycle, so ready is low and d3 does not move. The source holds d3 and it fires in cycle 4. That is back-pressure. All 8 items arrive in order after 3 stall cycles, and neither side knew anything about the other’s timing.

7.3 Registered ready and the 2-entry skid buffer

How “ready” is computed has a surprisingly large effect. Script 04, Part 2 builds a 4-stage pipeline with FIFOs between the stages:

FIFO depthready signalthroughput (items/cycle)longest ready path
1registered0.501 FIFO
1combinational1.005 FIFOs in series
2registered1.001 FIFO

With a registered ready (computed from the FIFO’s state at the start of the cycle), a full 1-entry buffer says “not ready” for the whole cycle — even if its consumer empties it in that same cycle. Every item causes one bubble, and the pipeline runs at half speed. There are two fixes:

  • Combinational ready: ready = “not full, or my consumer is taking an item right now”. Full speed with 1 entry, but ready now ripples backwards through every stage within one clock cycle. That timing path grows with pipeline length and eventually limits the clock frequency.
  • A 2-entry buffer (a “skid buffer”): the second entry catches the item that arrives while the first is leaving. Registered timing and full throughput, for twice the storage.

The skid buffer is the standard answer. It is also why HLS channel libraries offer several channel types (combinational, bypass, pipeline, buffered) — each a different point on this trade-off.

7.4 Sizing FIFOs: burstiness and slack matching

Burstiness. Script 04, Part 3 feeds a FIFO from a producer that sends 8 items and then idles for 8 cycles (average 0.5 items/cycle) into a consumer that takes one item every other cycle. During a burst, 8 items arrive while 4 leave. The FIFO peaks at 5 items, and with registered ready the producer stops stalling at depth 6. With depth 1 the system runs at 0.25 items/cycle, half of what both sides could do. A random consumer (ready with probability 0.6) needed depth 8 in this run. Buffers absorb variation; they do not create bandwidth: no FIFO helps if the consumer is slower on average.

Reconvergent paths. When a stream forks into two paths of different latency that join again, the short path must buffer the items that wait for their partners on the long path. Script 04, Part 4 measures the short-path FIFO depth needed for full throughput:

long-path latency LL24816
minimum depth571119

The rule is d≥L+3d \ge L + 3. An item stays in the short FIFO from the cycle the fork pushes it until its partner reaches the join: 1 cycle in the long path’s input FIFO, LL in the stage, 1 in its output FIFO. Its slot is seen as free one cycle later. With less buffering, throughput falls in proportion, roughly d/(L+3)d / (L + 3). This is slack matching. It is invisible in a functional simulation — the results are correct, just slow — and it is a common cause of accelerators that run at a fraction of their expected speed.

Channel experiments

Figure (script 04): left, 1-entry buffers with registered ready halve the throughput of a pipeline. Right, a fork/join needs short-path depth ≥ L + 3 (dotted lines) for full speed.

7.5 Relay stations and deadlock

Relay stations. Long wires across a chip cannot be crossed in one clock cycle, so designers insert pipeline registers (“relay stations”) into channels. Script 04, Part 5 inserts 0, 1 or 4 one-cycle stages on every link of a three-block pipeline:

FIFO depthrelays per linksame resultsfirst-item latencythroughput
20yes101.00
24yes261.00
14yes260.50

The results never change, and with 2-entry FIFOs neither does the throughput; only the latency grows. This is what latency insensitivity buys: a block or a wire can be re-pipelined to close timing without touching its neighbours.

Deadlock. Script 04, Part 6 has a producer that writes alternately to FIFOs A and B, and a consumer that reads kk items from A, then kk from B. To deliver the kk-th item of A, the producer must first push k−1k-1 items into B, which nobody reads yet. If B holds fewer, the producer waits for B, the consumer waits for A, and nothing ever moves:

kkFIFO depthstatusitems delivered
42deadlock3 / 16
43done16 / 16
86deadlock7 / 32
87done32 / 32

Each block is correct on its own; the deadlock is a property of the FIFO sizes. This exact bug — a producer and consumer that access shared channels in different orders — is common in HLS dataflow designs. It shows up in co-simulation as a hang. The cures are to size the FIFOs from the access pattern, or to make both sides use the same order.


8. FPGAs and cloud prototyping (Lab 0)

8.1 What an FPGA is

A field-programmable gate array is a chip whose logic is configured after manufacturing. Its resources map neatly onto the vocabulary of this lecture:

FPGA resourceWhat it isWhat HLS maps onto it
LUT (lookup table, typically 6 inputs)any small Boolean functionadders, comparators, multiplexers, control
flip-flopone register bitregisters, pipeline stages
DSP slicea hard multiplier + adder/accumulator (roughly 27×18 bits in recent AMD parts)multipliers, MACs
block RAM (BRAM, plus larger UltraRAM in some parts)small dual-port SRAM blocks (tens of kbits each)arrays, FIFOs, line buffers
programmable routingwires and switches between all of the aboveevery edge of the datapath

Array partitioning on an FPGA literally means “spread this array over more BRAMs” (or into flip-flops if it is small), and every extra port or bank uses a block whether it is full or not — the FPGA version of §6’s bank overhead.

8.2 Prototyping in the cloud

Cloud providers rent FPGAs by the hour. AWS F1 instances carry AMD (Xilinx) Virtex UltraScale+ FPGAs; the newer F2 instances (2024) use Virtex UltraScale+ parts with on-package HBM. The flow of Lab 0 in outline:

  1. write the block in C++/SystemC with a testbench;
  2. run HLS → RTL, and co-simulate the RTL against the C++ testbench;
  3. synthesize, place and route the RTL into an FPGA bitstream — on AWS, packaged as an “FPGA image” loaded onto the instance;
  4. run the block on the instance with real data, measuring cycles and throughput.

8.3 What a prototype tells you about an ASIC

An FPGA prototype runs real workloads millions of times faster than RTL simulation, so it catches bugs and measures cycle-level behavior faithfully: II, stalls, back-pressure, FIFO occupancy and the number of cycles per layer all carry over to an ASIC built from the same RTL. Absolute numbers do not:

  • Frequency. FPGA designs typically close timing at a few hundred MHz; the same RTL in an ASIC runs at 1–2 GHz.
  • Area and energy. Kuon and Rose (“Measuring the gap between FPGAs and ASICs”, 2007) measured FPGAs at very roughly 20–35× the area, 3–4× the delay and an order of magnitude more dynamic power than standard-cell ASICs. Hard DSP and memory blocks narrow the gap.

So use the FPGA for function and cycles, and use the ASIC flow — or, in these notes, the 45 nm models — for area and energy. Cycle counts and relative comparisons of designs transfer; MHz, LUTs and watts do not.


9. Summary

  1. HLS turns C++/SystemC into RTL by deciding allocation, scheduling, binding and control. The designer still owns the algorithm, the memory organization, the interfaces and the numerics — the decisions worth 10× or more.
  2. ASAP gives the critical path, ALAP the latest starts, mobility the slack. List scheduling with ALAP priorities is the standard heuristic under limits.
  3. Memory ports are resources: an 8-element dot product from single-port memories takes 23 cycles with 1 multiplier or 8. Adding units behind a port bottleneck is wasted.
  4. A tree beats a chain (log⁡n\log n vs nn adder latencies), but floating-point sums may only be rebalanced by the designer: the two orders differ bitwise in 85% of random cases.
  5. Sharing costs multiplexers and latency. It pays for big units (fp32: 87k → 15k µm²) and hardly for small ones (int8).
  6. Pipelining: T=(N−1) II+DT = (N-1)\,II + D. II sets throughput. II≥max⁡(ResMII,RecMII)II \ge \max(\text{ResMII}, \text{RecMII}).
  7. Fix resource limits with ports, banks (with a crossbar if they rotate) or — best — reuse: shift registers and line buffers. Fix recurrence limits with interleaved accumulators and look-ahead. Fix non-pipelined units with unrolling or strength reduction. The arithmetic transformations change float rounding, so they are the designer’s call.
  8. UNROLL needs PARTITION and vice versa. The fast designs lie on the diagonal U=PU = P, and every Pareto-optimal design is pipelined.
  9. Latency-insensitive blocks talk through ready/valid channels. Registered ready needs 2-entry buffers for full speed. FIFOs absorb burstiness but not average rate mismatch. Reconvergent paths need ≈L+3\approx L + 3 entries of slack. Undersized FIFOs can deadlock correct blocks.
  10. FPGA prototypes measure cycles and function faithfully; frequency, area and energy come from the ASIC flow.

10. Common pitfalls

  • “More units = faster.” Only if operands can be delivered: count memory ports first (§3.2).
  • “Unroll the loop and it will be parallel.” Without partitioning, the unrolled copies queue at the same port (§6.2).
  • “The tool will reorder my float sum.” It will not, and must not; write the tree or the partial sums yourself (§3.3, §5.5).
  • “Latency is what matters for a loop.” Throughput is 1/II1/II; a deeper pipeline at II = 1 beats a shallow one at II = 2 for any long loop (§5.1).
  • “Two dividers halve the II.” Not without unrolling; one operation is bound to one unit (§5.6).
  • “A 1-entry FIFO is enough between pipeline stages.” With registered ready it halves throughput (§7.3).
  • “FIFO depth only affects performance.” It can also decide whether the design deadlocks (§7.5).
  • “The FPGA ran at 250 MHz, so the ASIC will be 4× faster and 4× more efficient.” Cycle counts transfer; frequency, area and energy must be re-estimated (§8.3).
  • “Sharing always saves area.” For small units the multiplexers cost nearly as much as the units saved (§4.2).

11. Exercises

Library for all exercises unless stated: fp32 add 4 cycles, multiply 3, pipelined; SRAM read 1 cycle; no chaining.

Exercise 1 (ASAP/ALAP). For y=(a⋅b+c⋅d)⋅(e+f)y = (a\cdot b + c\cdot d)\cdot(e + f) with all inputs in registers, compute the ASAP and ALAP start of each operation and its mobility. What is the critical path?

Answer

ASAP: a⋅ba\cdot b and c⋅dc\cdot d at 0 (ready at 3); e+fe+f at 0 (ready at 4); (ab+cd)(ab + cd) at 3 (ready at 7); final multiply at 7 (ready at 10). Critical path = 10 cycles. ALAP with deadline 10: final multiply at 7; (ab+cd)(ab+cd) at 3; the two multiplies at 0; e+fe+f must be ready by 7, so it can start as late as 3. Mobility: 0 for everything except e+fe+f, which has mobility 3.

Exercise 2 (list scheduling by hand). Schedule the 8-element tree dot product with operands in registers, one multiplier and one adder, ALAP priority. Show that the latency is 22 cycles (script 01, Part 2, last row).

Answer

Multiplies issue at cycles 0–7, products ready at 3–10. Level-1 adds: +0 (p0, p1) can start at 4, +1 (p2, p3) at 6, +2 (p4, p5) at 8, +3 (p6, p7) at 10. +4 (+0, +1) is ready at 10 (6 + 4) but the adder is taken by +3, so it starts at 11. +5 (+2, +3) is ready at 14, and +6 (+4, +5) at 18. It finishes at 22. Every cycle in which the adder sits idle is waiting for an operand, so a second adder would not help here; a second multiplier would (18 cycles in the table).

Exercise 3 (RecMII of Horner’s rule). A polynomial is evaluated as acc = acc * x + c[i] for i=0..15i = 0..15. What is RecMII? Suggest two ways to pipeline faster.

Answer

The recurrence passes through one multiply and one add: 3 + 4 = 7 cycles over one iteration, so RecMII = 7. Fixes: (a) evaluate several polynomials (or several x values) interleaved, so that the loop alternates between independent recurrences, like interleaved accumulators. With 7 independent evaluations, II = 1. (b) Use a different evaluation scheme with more parallelism, such as Estrin’s scheme, (c0+c1x)+(c2+c3x)x2+…(c_0 + c_1x) + (c_2 + c_3x)x^2 + \dots, a tree of depth O(log⁡n)O(\log n) — at the price of computing powers of xx and a different rounding. With a fused multiply-add unit of latency 4, Horner’s RecMII would drop to 4.

Exercise 4 (ResMII). A loop body reads a[i], a[i+1], b[i] and writes c[i]. Each array is a separate single-port SRAM. What is ResMII? What changes if a is cyclically partitioned by 2? By 4?

Answer

a is accessed twice per iteration through one port, so ResMII = 2; b and c once each. With a cyclic partition by 2, a[i] and a[i+1] are always in different banks. Which bank holds a[i] alternates with ii, so the design needs a 2×2 crossbar, but ResMII = 1. Partitioning by 4 gives nothing more (two accesses per iteration) and costs two more banks of periphery. A shift register (keep a[i+1] for the next iteration) gives ResMII = 1 with one bank and no crossbar.

Exercise 5 (loop time). A loop of N=1000N = 1000 iterations has depth 20 and II = 2. (a) How many cycles does it take? (b) It is unrolled by 4 with partitioning, giving 250 iterations of depth 26 and II = 2. How many cycles now? (c) What would it take to make it 4× faster than (a)?

Answer

(a) 999⋅2+20=2018999 \cdot 2 + 20 = 2018. (b) 249⋅2+26=524249 \cdot 2 + 26 = 524, which is 3.85× faster: the depth and the shorter loop make it slightly less than 4×. (c) It is already almost there. For exactly 4× at large NN, the unrolled loop needs II = 2 with 4× the work per iteration. Note that if the original II = 2 came from a recurrence, unrolling alone would not keep II at 2: the unrolled body contains the recurrence four times, so a tree or partial sums are needed.

Exercise 6 (accumulators). An adder has latency 6 and you want II = 1 for acc += x[i] * y[i]. How many accumulators do you need? If the loop is also unrolled by 4 (the 4 products summed by a tree inside the iteration), how many?

Answer

L=6L = 6 in both cases. The recurrence is through the accumulator add, once per iteration, with latency 6: ⌈6/L⌉=1\lceil 6/L\rceil = 1 requires L≥6L \ge 6. Unrolling puts more products into each iteration (summed by a tree off the recurrence), but the accumulator is still updated once per iteration. With exactly 6 accumulators at II = 1, the partial sums live in the adder’s pipeline and need no extra registers (script 02, Part 5).

Exercise 7 (beating the toy scheduler). In script 03, the naive convolution with the image in 9 cyclic banks got II = 2 although ResMII = 1. The 9 loads per iteration have offsets rW+crW + c (W=32W = 32, r,c∈{0,1,2}r, c \in \{0,1,2\}). In a modulo schedule with II = 1, a load with offset oo issued at cycle tt of its iteration uses bank (o−t) mod 9(o - t) \bmod 9 (the bank key of hls.py). Find issue cycles that put the nine loads into nine different banks.

Answer

Offsets mod 9 are: row 0: 0, 1, 2; row 1 (32, 33, 34): 5, 6, 7; row 2 (64, 65, 66): 1, 2, 3. Rows 0 and 1 occupy banks {0, 1, 2, 5, 6, 7} when issued at cycle 0. Row 2 must go to {3, 4, 8}. Issue offset 66 at cycle 0 (bank 3), offset 65 at cycle 3 ((65 − 3) mod 9 = 8) and offset 64 at cycle 6 ((64 − 6) mod 9 = 4). All nine keys are distinct, so II = 1 works with 6 more cycles of depth. Delays such as (7, 7, 4) also work. The toy scheduler places every load as early as possible and never tries these delays; Rau’s backtracking scheduler, or a smarter priority, would.

Exercise 8 (FIFO sizing). (a) A fork/join has a long path of latency 12 (with registered-ready FIFOs as in script 04). How deep must the short path’s FIFO be for full throughput? (b) With depth 6, what throughput do you expect? (c) A producer writes A, B, A, B, …; the consumer reads 6 items from A, then 6 from B. What FIFO depth avoids deadlock?

Answer

(a) d≥L+3=15d \ge L + 3 = 15. (b) About 6/15=0.46/15 = 0.4 items per cycle (the measured curves follow d/(L+3)d/(L+3) closely). (c) Depth 5 (k−1k - 1): to deliver the 6th A item, 5 B items must already sit in B.

Exercise 9 (sharing). Using the areas of §0.4, estimate the logic area of a 16-element int8 dot product with (a) 16 multipliers and a tree of 15 adders, (b) one multiplier and one adder shared by all operations. Ignore registers. Which wins on area × latency, assuming latencies of about 5 and 32 cycles?

Answer

(a) 16⋅282+15⋅137=656716 \cdot 282 + 15 \cdot 137 = 6567 µm², no multiplexers. (b) 282+137=419282 + 137 = 419 µm² of units. The multiplier’s two 8-bit inputs each select among 16 sources: 2⋅15⋅8=2402 \cdot 15 \cdot 8 = 240 mux bits. The adder’s two 32-bit inputs select among up to ~15 sources: about 2⋅14⋅32≈9002 \cdot 14 \cdot 32 \approx 900 mux bits. In all about 1,140 bits ≈ 2,170 µm², so roughly 2,600 µm² in total. Area × latency: (a) 6567⋅5≈33,0006567 \cdot 5 \approx 33{,}000; (b) 2600⋅32≈83,0002600 \cdot 32 \approx 83{,}000. Full parallelism wins for int8: the adder multiplexers alone cost more than several adders. Script 01, Part 4 shows the same effect on 9 elements.

Exercise 10 (FPGA vs ASIC). A pipelined block processes 1,024 elements in 1,032 cycles on an FPGA at 250 MHz. Estimate its time on an ASIC at 1 GHz. Which other measurement from the FPGA run would you trust for the ASIC, and which not?

Answer

The cycle count carries over: 1,032 cycles at 1 GHz = 1.03 µs, vs 4.13 µs on the FPGA. Trust the cycle counts, the II, stall and back-pressure behavior, FIFO occupancies and functional results. Do not trust the FPGA’s power, its LUT/DSP/BRAM counts as an area estimate, or its frequency. Those must come from ASIC synthesis, or from a model such as the 45 nm estimates of these notes.

Exercise 11 (programming: a fused multiply-add). Add an "fma" operation to the fp32 library of hls.py (latency 4, pipelined, area ≈ adder + multiplier) and a method so that k.fma(a, b, c) traces a⋅b+ca\cdot b + c as one node. Re-run the IIR filter of script 02 with the FMA. What RecMII do you expect with and without look-ahead?

Answer

The recurrence y=fma(a,y−1,x)y = \text{fma}(a, y_{-1}, x) goes through one 4-cycle FMA with distance 1: RecMII = 4 (vs 7 with a separate multiply and add). With look-ahead, y=fma(a2,y−2,fma(a,x−1,x))y = \text{fma}(a^2, y_{-2}, \text{fma}(a, x_{-1}, x)): the recurrence is one FMA over distance 2, so RecMII = 2. The FMA also rounds once instead of twice, which slightly changes the numbers again. Implementation hint: add an OpSpec to LIBRARY["fp32"], a three-operand node kind, and evaluate it as np.float32(a * b + c) computed in float64 (one rounding).

Exercise 12 (programming: slack matching). Modify forkjoin_throughput in script 04 so that both branches contain a stage, with latencies L1<L2L_1 < L_2. Each branch has a 2-entry input FIFO, the stage, and an output FIFO; vary the depth dd of the short branch’s output FIFO. Predict, then measure, the depth needed for full throughput.

Answer

What matters is the latency difference. Both branches now have the same fixed overheads (an input FIFO and an output FIFO), and the short stage’s own pipeline registers hold up to L1L_1 waiting items. Running it (author’s run) gives full throughput at d=L2−L1+2d = L_2 - L_1 + 2: for (L1,L2)=(1,8),(2,8),(4,8),(4,12),(8,16)(L_1, L_2) = (1, 8), (2, 8), (4, 8), (4, 12), (8, 16) the measured depths are 9, 8, 6, 10, 10. The “+2” is the registered-ready overhead of the join’s input FIFO. In script 04 the short branch had no stage and one FIFO hop fewer than the long branch, hence L+3L + 3 there. Slack must match the difference of the path latencies, measured hop by hop.

12. Further reading

  • R. Kastner, J. Matai, S. Neuendorffer, Parallel Programming for FPGAs (2018, free online) — HLS by example: pipelining, unrolling, partitioning, line buffers.
  • J. Cong et al., “High-level synthesis for FPGAs: from prototyping to deployment”, IEEE TCAD 2011 — the state of HLS when it became practical.
  • G. De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill 1994 — scheduling (ASAP/ALAP, list, force-directed) and binding (left-edge, clique partitioning).
  • P. Paulin, J. Knight, “Force-directed scheduling for the behavioral synthesis of ASICs”, IEEE TCAD 1989.
  • B. R. Rau, “Iterative modulo scheduling: an algorithm for software pipelining loops”, MICRO 1994.
  • L. Carloni, K. McMillan, A. Sangiovanni-Vincentelli, “Theory of latency-insensitive design”, IEEE TCAD 2001.
  • B. Khailany et al., “A modular digital VLSI flow for high-productivity SoC design”, DAC 2018; NVIDIA’s MatchLib (open source on GitHub).
  • I. Kuon, J. Rose, “Measuring the gap between FPGAs and ASICs”, IEEE TCAD 2007.
  • R. Venkatesan et al., “MAGNet: a modular accelerator generator for neural networks”, ICCAD 2019 — the next lecture’s reading, built with this methodology.

13. Next lecture

Lecture 3, Data parallelism and efficiency metrics, builds the first block of the course’s accelerator: a SIMD processing element in the style of MAGNet (Lab 1). With the tools of this lecture we can now ask the right questions about it. How many MAC lanes, and how wide? How are weights and inputs buffered so that every lane gets an operand every cycle? What does utilization look like on real layer shapes? Then, how should such a PE — or a whole accelerator — be measured honestly: TOPS, TOPS/W, TOPS/mm², at which precision, which sparsity, which utilization? Eyeriss’s energy accounting will show that the answer depends far more on where the data comes from than on the arithmetic.

← 返回课程目录