# CS152 Lecture 18: Vectors ### Section 1: Vector Architectures — Programming Model, Lanes, Chaining, and Memory Both superscalars and VLIWs struggle to extract **instruction-level parallelism (ILP)** from sequential scalar code—either spending $\sim W^3$ hardware complexity rediscovering independence at runtime, or failing on unpredictable code at compile time. Yet many of the world's most demanding workloads—weather forecasting, oil exploration, car crash simulation, bioinformatics, cryptography, and scientific simulation—perform **huge computations on large, regular datasets**. In the 1970s–1980s, **Supercomputer $\equiv$ Vector Machine** (CDC 6600, CDC 7600, **Cray-1**). Instead of trying to extract parallelism across tiny unrelated scalar instructions, **Vector Architectures** expose **data-level parallelism (DLP)** directly in the ISA! #### Vector Programming Model and Code Comparison Epitomized by the **Cray-1 (1976)**, a vector machine pairs a standard **Scalar Unit** (load/store architecture with scalar registers `x0..x31`) with a **Vector Extension**: - **Vector Registers (`v0..v31`):** Each vector register holds an entire array of `VLMAX` elements (`[0], [1], [2], ..., [VLMAX-1]`). (Cray-1 had 8 vector registers `V0..V7` of 64 elements each, plus a Vector Mask `V. Mask` and Vector Length `V. Length`.) - **Vector Length Register (`vl`):** Controls how many elements (`0` to `vl-1`) a vector instruction operates on. - **Vector Arithmetic Instructions:** E.g., `vadd v3, v1, v2` adds pairs `v1[i] + v2[i] -> v3[i]` across all elements $0 \le i \le \text{vl}-1$. - **Vector Load and Store Instructions:** E.g., unit-stride `vld v1, (x1)` loads `vl` contiguous elements starting at base address `x1`; strided `vls v1, (x1), x2` loads elements spaced by **Stride `x2`** starting at **Base `x1`**. Look at how dramatic the difference is for `for (i = 0; i < 64; i++) C[i] = A[i] + B[i];`: - **Scalar Code:** Initializes `x4 = 64`, then runs a 9-instruction loop (`fld`, `fld`, `fadd.d`, `fsd`, `addi`, `addi`, `addi`, `subi`, `bnez`) 64 times—fetching and decoding **$1 + 64 \times 9 = 577$ instructions**! - **Vector Code:** ``` li x4, 64 vsetvl x4 vld v1, (x1) vld v2, (x2) vadd v3, v1, v2 vst v3, (x3) ``` Only **6 instructions total**! #### Why Vector ISAs Are So Effective A vector ISA brings three decisive hardware advantages: 1. **Compact:** One short instruction encodes $N$ (e.g., 64) independent operations, drastically reducing instruction fetch bandwidth. 2. **Expressive:** A single vector instruction tells hardware simultaneously that these $N$ operations: - are **mutually independent** (zero hazards between elements!), - use the **same functional unit**, - access **disjoint registers** (one element per slot in `v1, v2, v3`), - access registers in the **same pattern** as previous instructions, and - access a **contiguous block** (unit-stride) or **known strided pattern** of memory. 3. **Scalable:** The **exact same binary code** runs unmodified on a cheap machine with 1 pipeline or a supercomputer with 8 or 16 parallel pipelines (**lanes**)! #### Deep Pipelining, Parallel Lanes, and Instruction Overlap Look at how vector arithmetic executes in hardware: - **Deep pipelines with zero hazards:** Because elements within `v3 <- v1 * v2` are completely independent, hardware can use a deeply pipelined functional unit (e.g., a 6-stage multiply pipeline) clocked very fast with **zero hazard-detection or bypass control logic inside the pipe**! - **Scaling with Lanes:** Instead of running one `vadd vc, va, vb` element per cycle on 1 functional unit (`C[0]`, then `C[1]`, `C[2]`...), we can split the vector register file across **multiple parallel lanes** (e.g., 4 lanes, or 8 lanes on the **T0 Vector Microprocessor, 1995**). Lane 0 holds elements `0, 4, 8, ...` alongside its own ALU and memory port; Lane 1 holds `1, 5, 9, ...`; Lane 2 holds `2, 6, 10, ...`; Lane 3 holds `3, 7, 11, ...`. Because element `i` of every vector register lives in the same lane (`i mod #lanes`), **zero cross-lane wiring is needed for vector arithmetic!** Now look at **Vector Instruction Parallelism**: suppose a machine has **32 elements per vector register** and **8 lanes**. Each vector instruction completes in $32 / 8 = 4$ cycles (8 elements/cycle). By overlapping a **Load Unit**, a **Multiply Unit**, and an **Add Unit** (and overlapping consecutive vector streams), the machine completes **$8 \times 3 = 24$ operations per cycle while issuing only 1 short instruction per cycle**! #### Vector Chaining Wait: if `vmul v3, v1, v2` depends on `vld v1` and `vadd v5, v3, v4` depends on `vmul v3`, doesn't `vmul` have to wait until all 64 elements of `v1` finish loading? - Without chaining, yes—each instruction must wait for the *last* element of its predecessor to be written. - **Vector Chaining** (the vector version of register bypassing, introduced on the **Cray-1**) forwards each element from the `Load Unit` output straight into the `Mult.` pipeline (and from `Mult.` straight into `Add`) **as soon as the very first element appears**! Load, Multiply, and Add then execute almost completely overlapped in time. #### Interleaved Vector Memory System (and Why Vector Registers Beat Memory-Memory) The Cray-1 had **no data caches** and **no virtual memory** (realizing that streaming scientific arrays wouldn't fit in small caches anyway). How did it feed 80 MW/s of data from a `50 ns` DRAM memory bank to an `80 MHz` (`12.5 ns` cycle) processor—where each bank had a **4-cycle bank busy time** and a **12-cycle latency**? Through an **Interleaved Vector Memory System**: - Memory is divided into **16 independent banks (`0..F`)**. - An **Address Generator** computes `Base + i * Stride` each cycle and sends requests across different banks. As long as consecutive addresses hit different banks (e.g., unit stride or any odd stride), a bank accessed on cycle 0 has 15 other banks accessed before cycle 16—easily hiding the 4-cycle bank busy time and sustaining **1 word per cycle**! (Only strides that share a large power-of-2 factor with 16 cause bank conflicts.) Notice also why **Cray-1 (1976)** switched from earlier **Vector Memory-Memory Architectures (VMMAs)**—like the TI ASC (1971) and CDC Star-100 (1973), which held all operands in main memory (`vadd (C), (A), (B)`)—to **Vector Register Architectures**: 1. **Main memory bandwidth:** For `C[i] = A[i] + B[i]; D[i] = A[i] - B[i];`, a VMMA reads `A` and `B` from DRAM *twice* (`4` reads + `2` writes = `6` vector memory streams), whereas a vector-register machine loads `V1(A)` and `V2(B)` *once* and reuses them from registers! 2. **Overlapping operations:** VMMAs struggle to overlap operations because they must constantly check memory address dependencies. 3. **Startup latency:** VMMAs paid massive startup latency—on the CDC Star-100, scalar code was actually faster for vectors shorter than **100 elements**, whereas Cray-1's vector/scalar breakeven point was only **2–4 elements**! *(All major vector machines since Cray-1, aside from CDC's direct follow-ons Cyber-205 and ETA-10, have been vector-register architectures.)* *[Editor Note: removed title slide and homebrew Cray-1 photo/URL trivia.]* #### ✎ Check Your Understanding 1. On a 4-lane vector processor with 64-element vector registers, which elements of `v1` are physically stored in Lane 2, and how many cycles does a single vector add take once started? **Answer:** Lane 2 stores elements $2, 6, 10, \dots, 62$ (indices $\equiv 2 \pmod 4$). Processing 4 elements per cycle, the 64-element vector add takes $64 / 4 = \mathbf{16\text{ cycles}}$. 2. What is **Vector Chaining**, and how does it reduce the total execution time of `vld` $\to$ `vmul` $\to$ `vadd`? **Answer:** Vector chaining is the vector equivalent of register bypassing: it forwards individual vector elements from a producer unit directly into a dependent consumer unit as soon as the first element completes, allowing the operations to overlap instead of waiting for all elements of the first instruction to finish. --- ### Section 2: Vectorizing Real Code — Stripmining, Masks, Reductions, Scatter/Gather, and Packed SIMD Real loops rarely look as neat as `for (i = 0; i < 64; i++) C[i] = A[i] + B[i];`. Vectorizing general loops requires **automatic code vectorization**—a massive compile-time reordering that transforms sequential per-iteration execution (`Iter 1: load, load, add, store` then `Iter 2: load, load, add, store`) into across-iteration vector phases (`load all A`, `load all B`, `add all`, `store all`), requiring extensive loop-dependence analysis. Four common loop patterns require special vector ISA support: #### 1. Arbitrary Loop Lengths: Vector Stripmining **Problem:** Vector registers have finite hardware length (e.g., `VLMAX = 64`), but loops run for arbitrary length $N$. **Solution — Stripmining:** Break the loop into $64$-element strips plus a remainder strip (`N mod 64`). Look at how cleanly the remainder is handled *first* in the loop: ``` andi x1, xN, 63 # x1 = N mod 64 (remainder) vsetvl x1 # Set vector length for remainder loop: vld v1, (xA) slli x2, x1, 3 # Multiply element count by 8 bytes add xA, xA, x2 # Bump A pointer vld v2, (xB) add xB, xB, x2 # Bump B pointer vadd v3, v1, v2 vst v3, (xC) add xC, xC, x2 # Bump C pointer sub xN, xN, x1 # Subtract completed elements li x1, 64 vsetvl x1 # Reset vl to full 64-element length bgtz xN, loop # Repeat if elements remain ``` After handling the odd remainder on the first pass (or executing 0 elements if $N \bmod 64 = 0$), every subsequent pass runs at full `vl = 64`! #### 2. Conditional Code: Vector Masks, Density-Time, and Compress/Expand **Problem:** A loop contains an `if` statement: ```c for (i = 0; i < N; i++) if (A[i] > 0) A[i] = B[i]; ``` **Solution:** Add a **vector mask (flag) register** (1 bit per vector element) and **maskable vector instructions**, where any element whose mask bit is 0 becomes a bubble (`NOP`): ``` cvm # Clear/turn on all mask elements (all 1s) vld vA, (xA) # Load entire A vector vgt vA, f0 # Set mask bits where A[i] > 0 vld vA, (xB) # Load B[i] into vA ONLY where mask=1 vst vA, (xA) # Store vA back to memory ONLY where mask=1 ``` How does hardware implement masked execution? - **Simple Implementation:** Execute all $N$ operations down the pipeline, and simply gate off the **Write Enable** signal with `M[i]` so masked-out elements don't overwrite the register file. - **Density-Time Implementation:** Scan the mask vector and **only execute elements with `M[i] == 1`** (skipping `M[i] == 0` cycles entirely). Related to density-time execution are **Compress** and **Expand** instructions: - **Compress** packs all unmasked elements (`M[i] == 1`, e.g., `A[7], A[5], A[4], A[1]`) contiguously at the bottom of a destination register; the **population count** of the mask gives the new packed vector length! - **Expand** performs the exact inverse, scattering packed results back into their original positions (`A[7], B[6], A[5], A[4], B[3], B[2], A[1], B[0]`). #### 3. Loop-Carried Dependences: Vector Reductions **Problem:** A reduction loop (`sum += A[i];`) has a **loop-carried dependence** on `sum`—iteration $i$ depends on iteration $i-1$! **Solution:** If the operation is associative, convert it into `VL` independent partial sums and then reduce them with a **binary tree**: ```c sum[0:VL-1] = 0; // Vector of VL partial sums for (i = 0; i < N; i += VL) // Stripmine VL-sized chunks sum[0:VL-1] += A[i : i+VL-1]; // Independent vector add! do { VL = VL / 2; // Halve vector length sum[0:VL-1] += sum[VL : 2*VL-1]; } while (VL > 1); ``` Instead of $N$ serial additions, the binary tree finishes the final reduction in just $\log_2(\text{VL})$ vector steps! #### 4. Indirect Memory Accesses: Vector Scatter/Gather **Problem:** Irregular indexing such as `A[i] = B[i] + C[D[i]];`. **Solution:** **Indexed Load (`Gather`)** and **Indexed Store (`Scatter`)** instructions: ``` vld vD, (xD) # Load index array D vlx vC, (xC), vD # Gather: vC[i] = Mem[xC + vD[i]] vld vB, (xB) # Load B vector vadd vA, vB, vC # Vector add vst vA, (xA) # Store result ``` #### Packed SIMD Extensions vs. True Vector Architectures Desktop microprocessors (starting as early as the 1957 Lincoln Labs TX-2 splitting a 36-bit datapath into $2\times 18\text{b}$ or $4\times 9\text{b}$, and later PowerPC AltiVec, Intel SSE2/3/4, and Intel AVX) adopted **Packed SIMD Extensions**—splitting a wide register (64b, 128b, 256b, or 512b) into short subwords (e.g., `4x16b adds` across a 64-bit register). Why are classic Packed SIMD extensions inferior to true Vector ISAs? 1. **Limited instruction set:** Originally had **no vector length control (`vl`)** (requiring messy scalar cleanup loops and forcing recompilation whenever register widths doubled from 128b $\to$ 256b $\to$ 512b!), **no strided load/store or scatter/gather**, and strict **64/128-bit alignment rules** on unit-stride loads. 2. **Limited vector register length:** Because each SIMD register holds only a few elements (e.g., 4 doubles in 256-bit AVX), hardware **still requires superscalar dispatch** to keep multiply, add, and load units busy, and **loop unrolling** to hide latencies increases register pressure! Because of these limits, modern microprocessors have steadily evolved back toward true vector support—adding misaligned memory access support, 64-bit floating-point, `gather`/`scatter` in Intel AVX, and true vector-length-agnostic ISAs like **ARM Scalable Vector Extensions (SVE)** (and RISC-V Vector). *[Editor Note: removed acknowledgements slide.]* #### ✎ Check Your Understanding 1. Suppose we execute a `Compress` operation on vector `A[0..7]` using mask `M = 10110010` (with `M[7]=1, M[6]=0, M[5]=1, M[4]=1, M[3]=0, M[2]=0, M[1]=1, M[0]=0`). Which elements appear in the compressed destination register, and what is the new packed vector length? **Answer:** The compressed register holds `A[1], A[4], A[5], A[7]` contiguously in its first four slots, and the new vector length is the population count of the mask, **4**. 2. Give two architectural reasons why true Vector ISAs (such as Cray-1 or ARM SVE) scale more cleanly than traditional fixed-width Packed SIMD extensions (such as Intel SSE). **Answer:** First, true Vector ISAs include a **vector length register (`vl`)**, allowing the same binary code to handle stripmining and wider hardware lanes without recompiling for each new register width. Second, they provide **strided and scatter/gather memory operations** and long vector registers that keep functional units busy without needing heavy superscalar dispatch or loop unrolling.