Uniprocessor Optimizations. Idealized Uniprocessor Model

Similar documents
Optimizing Cache Performance in Matrix Multiplication. UCSB CS240A, 2017 Modified from Demmel/Yelick s slides

COMPUTATIONAL LINEAR ALGEBRA

Pipelining, Instruction Level Parallelism and Memory in Processors. Advanced Topics ICOM 4215 Computer Architecture and Organization Fall 2010

CS Software Engineering for Scientific Computing Lecture 10:Dense Linear Algebra

Caches and Memory Hierarchy: Review. UCSB CS240A, Winter 2016

Caches and Memory Hierarchy: Review. UCSB CS240A, Fall 2017

Modern Computer Architecture

Computer Systems Architecture Spring 2016

Lecture 4. Instruction Level Parallelism Vectorization, SSE Optimizing for the memory hierarchy

COSC 6385 Computer Architecture - Pipelining

Linear Algebra for Modern Computers. Jack Dongarra

Computer Architecture Spring 2016

Lecture 3. Pipelining. Dr. Soner Onder CS 4431 Michigan Technological University 9/23/2009 1

Lecture 2: Single processor architecture and memory

CS267 Lecture 2 Single Processor Machines: Memory Hierarchies and Processor Features Case Study: Tuning Matrix Multiply

CISC 662 Graduate Computer Architecture Lecture 6 - Hazards

Computer Architecture

Modern Computer Architecture

Pipeline Overview. Dr. Jiang Li. Adapted from the slides provided by the authors. Jiang Li, Ph.D. Department of Computer Science

1 Motivation for Improving Matrix Multiplication

Outline Marquette University

Chapter 2. Parallel Hardware and Parallel Software. An Introduction to Parallel Programming. The Von Neuman Architecture

Copyright 2012, Elsevier Inc. All rights reserved.

EI338: Computer Systems and Engineering (Computer Architecture & Operating Systems)

Pipelining. Maurizio Palesi

EITF20: Computer Architecture Part2.2.1: Pipeline-1

Computer and Information Sciences College / Computer Science Department Enhancing Performance with Pipelining

HY425 Lecture 05: Branch Prediction

ECE331: Hardware Organization and Design

EITF20: Computer Architecture Part2.2.1: Pipeline-1

CS 426 Parallel Computing. Parallel Computing Platforms

CSC Memory System. A. A Hierarchy and Driving Forces

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. 5 th. Edition. Chapter 4. The Processor

ECE331: Hardware Organization and Design

Perfect Student CS 343 Final Exam May 19, 2011 Student ID: 9999 Exam ID: 9636 Instructions Use pencil, if you have one. For multiple choice

Computer Architecture. Lecture 6.1: Fundamentals of

CS6303 Computer Architecture Regulation 2013 BE-Computer Science and Engineering III semester 2 MARKS

COSC 6385 Computer Architecture. - Memory Hierarchies (I)

Chapter 4 The Processor 1. Chapter 4A. The Processor

Agenda. Cache-Memory Consistency? (1/2) 7/14/2011. New-School Machine Structures (It s a bit more complicated!)

Memory Hierarchy Technology. The Big Picture: Where are We Now? The Five Classic Components of a Computer

COMP Parallel Computing. SMM (1) Memory Hierarchies and Shared Memory

Pipelining! Advanced Topics on Heterogeneous System Architectures. Politecnico di Milano! Seminar DEIB! 30 November, 2017!

ECE 2300 Digital Logic & Computer Organization. Caches

Memory Hierarchy. Maurizio Palesi. Maurizio Palesi 1

Data Hazards Compiler Scheduling Pipeline scheduling or instruction scheduling: Compiler generates code to eliminate hazard

Some material adapted from Mohamed Younis, UMBC CMSC 611 Spr 2003 course slides Some material adapted from Hennessy & Patterson / 2003 Elsevier

CPU Pipelining Issues

The Memory Hierarchy & Cache

Memory Hierarchy, Fully Associative Caches. Instructor: Nick Riasanovsky

Pipeline: Introduction

Chapter 4. The Processor

Caches. Hiding Memory Access Times

Memory Hierarchy. Maurizio Palesi. Maurizio Palesi 1

CPS104 Computer Organization and Programming Lecture 19: Pipelining. Robert Wagner

Lecture 16 Optimizing for the memory hierarchy

Lecture 29 Review" CPU time: the best metric" Be sure you understand CC, clock period" Common (and good) performance metrics"

Advanced Computer Architecture

EE 4683/5683: COMPUTER ARCHITECTURE

Processor Architecture. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

CS/ECE 250 Computer Architecture

CS 110 Computer Architecture. Pipelining. Guest Lecture: Shu Yin. School of Information Science and Technology SIST

EN2910A: Advanced Computer Architecture Topic 02: Review of classical concepts

EITF20: Computer Architecture Part2.2.1: Pipeline-1

CS 352H Computer Systems Architecture Exam #1 - Prof. Keckler October 11, 2007

Overview. Appendix A. Pipelining: Its Natural! Sequential Laundry 6 PM Midnight. Pipelined Laundry: Start work ASAP

Lecture 9. Pipeline Hazards. Christos Kozyrakis Stanford University

ECE468 Computer Organization and Architecture. Memory Hierarchy

Appendix A. Overview

Instruction Pipelining

CMSC 411 Computer Systems Architecture Lecture 13 Instruction Level Parallelism 6 (Limits to ILP & Threading)

COSC4201 Pipelining. Prof. Mokhtar Aboelaze York University

Lecture 18. Optimizing for the memory hierarchy

Full Datapath. Chapter 4 The Processor 2

Advanced issues in pipelining

Matrix Multiplication

LECTURE 10: Improving Memory Access: Direct and Spatial caches

ENGN1640: Design of Computing Systems Topic 06: Advanced Processor Design

Processor Architecture

EN164: Design of Computing Systems Topic 08: Parallel Processor Design (introduction)

SE-292 High Performance Computing. Memory Hierarchy. R. Govindarajan Memory Hierarchy

Locality. Cache. Direct Mapped Cache. Direct Mapped Cache

HPC VT Machine-dependent Optimization

Lecture 6 MIPS R4000 and Instruction Level Parallelism. Computer Architectures S

Algorithm Performance Factors. Memory Performance of Algorithms. Processor-Memory Performance Gap. Moore s Law. Program Model of Memory II

Outline EEL 5764 Graduate Computer Architecture. Chapter 3 Limits to ILP and Simultaneous Multithreading. Overcoming Limits - What do we need??

LECTURE 3: THE PROCESSOR

CPE Computer Architecture. Appendix A: Pipelining: Basic and Intermediate Concepts

Modern Computer Architecture (Processor Design) Prof. Dan Connors

IF1/IF2. Dout2[31:0] Data Memory. Addr[31:0] Din[31:0] Zero. Res ALU << 2. CPU Registers. extension. sign. W_add[4:0] Din[31:0] Dout[31:0] PC+4

Lecture 17 Introduction to Memory Hierarchies" Why it s important " Fundamental lesson(s)" Suggested reading:" (HP Chapter

Beyond Pipelining. CP-226: Computer Architecture. Lecture 23 (19 April 2013) CADSL

Algorithm Performance Factors. Memory Performance of Algorithms. Processor-Memory Performance Gap. Moore s Law. Program Model of Memory I

COMPUTER ORGANIZATION AND DESIGN

CS 2461: Computer Architecture 1

Instruction Pipelining Review

Some material adapted from Mohamed Younis, UMBC CMSC 611 Spr 2003 course slides Some material adapted from Hennessy & Patterson / 2003 Elsevier

Pipelining Analogy. Pipelined laundry: overlapping execution. Parallelism improves performance. Four loads: Non-stop: Speedup = 8/3.5 = 2.3.

TDT Coarse-Grained Multithreading. Review on ILP. Multi-threaded execution. Contents. Fine-Grained Multithreading

3/12/2014. Single Cycle (Review) CSE 2021: Computer Organization. Single Cycle with Jump. Multi-Cycle Implementation. Why Multi-Cycle?

Transcription:

Uniprocessor Optimizations Arvind Krishnamurthy Fall 2004 Idealized Uniprocessor Model Processor names bytes, words, etc. in its address space These represent integers, floats, pointers, arrays, etc. Exist in the program stack, static region, or heap Operations include Read and write (given an address/pointer) Arithmetic and other logical operations Order specified by program Read returns the most recently written data Compiler and architecture translate high level expressions into obvious lower level instructions Hardware executes instructions in order specified by compiler Cost Each operation has the same cost (read, write, add, multiply, etc.) 1

Uniprocessors in the real world Real processors have registers and caches small amounts of fast memory store values of recently used or nearby data different memory ops can have very different costs parallelism multiple functional units that can run in parallel different orders, different instruction mixes have different costs pipelining a form of parallelism, like an assembly line in a factory Why is this your problem? In theory, compilers understand all of this and can optimize your program; in practice they don t. Pipelining Review T a s k O r d e r A B C D 4 people doing laundry: wash (30 min) + dry (40 min) + fold (20 min) 6 PM 7 8 9 Time 30 40 40 40 40 20 In this example: Sequential execution takes 4 * 90min = 6 hours Pipelined execution takes 30+4*40+20 = 3.3 hours Pipelining helps throughput, but not latency Pipeline rate limited by slowest pipeline stage Potential speedup = Number pipe stages Time to fill pipeline and time to drain reduces speedup (overhead) 2

Example: 5 Steps of MIPS Datapath Figure 3.4, Page 134, CA:AQA 2e by Patterson and Hennessy Instruction Fetch Instr. Decode Reg. Fetch Execute Addr. Calc Memory Access Write Back Next PC 4 Adder Next SEQ PC RS1 Next SEQ PC Zero? MUX Address Memory IF/ID RS2 Reg File ID/EX MUX MUX ALU EX/MEM Data Memory MEM/WB MUX Imm Sign Extend RD RD RD WB Data Pipelining is also used within arithmetic units a fp multiply may have latency 10 cycles, but throughput of 1/cycle Limits to Instruction Level Parallelism (ILP) Limits to pipelining: Hazards prevent next instruction from executing during its designated clock cycle Structural hazards: HW cannot support this combination of instructions (single dryer) Data hazards: Instruction depends on result of prior instruction still in the pipeline (missing sock) Control hazards: Caused by delay between the fetching of instructions and decisions about changes in control flow (branches and jumps). The hardware and compiler will try to reduce hazards Reordering instructions, multiple issue, dynamic branch prediction, speculative execution You can also enable parallelism by careful coding 3

Dependences Limit Parallelism A dependence or data hazard is one of the following: true or flow dependence: X writes a location that Y later reads (read-after write or RAW hazard) anti-dependence X reads a location that Y later writes (write-after-read or WAR hazard) output dependence X writes a location that Y later writes (write-after-write or WAW hazard) = a true a = 3.4*b/12.2 = a a = 1 anti a = a = output Memory Hierarchy Most programs have a high degree of locality in their accesses spatial locality: accessing things nearby previous accesses temporal locality: reusing an item that was previously accessed Memory hierarchy tries to exploit locality processor datapath registers control on-chip cache Second level cache (SRAM) Main memory (DRAM) Secondary storage (Disk) Tertiary storage (Disk/Tape) Speed (ns): 1 10 100 10 ms 10 sec Size (bytes): 100s Ks Ms Gs Ts 4

Performance 1000 100 10 1 Processor-DRAM Gap (latency) Memory hierarchies are getting deeper Processors get faster more quickly than memory 1980 1981 1982 1983 1984 1985 Moore s Law 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 Time CPU DRAM 1999 2000 µproc 60%/yr. Processor-Memory Performance Gap: (grows 50% / year) DRAM 7%/yr. Cache Basics Cache contains tag (upper bits of address) and values Cache hit: if tag matches cheap Cache miss: non-cached memory access expensive Consider cache with 4 entries and 4 words per entry Tag Values Address: 10100110 1010 X Cache line length: # of bytes loaded together in one entry Provides spatial locality Associativity direct-mapped: only one address (line) in a given range in cache n-way: 2 or more lines with different addresses exist 5

Experimental Study of Memory Microbenchmark for memory system performance time the following program for each size(a) and stride s (repeat to obtain confidence and mitigate timer resolution) for array A of size from 4KB to 8MB by 2x for stride s from 8 Bytes (1 word) to size(a)/2 by 2x for i from 0 to size by s load A[i] from memory (4 Bytes) Memory Hierarchy of a Sun Ultra-IIi(333MHz) Array size See lambda.cs.yale.edu/~arvind/papers/t3d-isca95.ps for details 6

Some Architecture Lessons Actual performance of a simple program can be a complicated function of the architecture Slight changes in the architecture or program change the performance significantly To write fast programs, need to (sometimes) consider architecture We would like simple models to help us design efficient algorithms Is this possible? We will illustrate with a common technique for improving cache performance Idea: use divide-and-conquer to define a problem that fits in register/l1-cache/l2-cache Matrix Storage A matrix is a 2-D array of elements, but memory addresses are 1- D Conventions for matrix layout by column, or column major (Fortran default) by row, or row major (C default) Column major Row major 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 0 4 8 12 16 1 5 9 13 17 2 6 10 14 18 3 7 11 15 19 7

Simple Model of Memory Assume just 2 levels in the hierarchy, fast and slow All data initially in slow memory m = number of memory elements (words) moved between fast and slow memory t m = time per slow memory operation f = number of arithmetic operations t f = time per arithmetic operation << t m q = f / m average number of flops per slow element access Minimum possible time = f* t f when all data in fast memory Actual time f * t f + m * t m = f * t f * (1 + t m /t f * 1/q) Larger q means Time closer to minimum f * t f Key to machine efficiency Key to algorithm efficiency Warm up: Matrix-vector multiplication {implements y = y + A*x} for i = 1:n for j = 1:n y(i) = y(i) + A(i,j)*x(j) A(i,:) = + * y(i) y(i) x(:) 8

Warm up: Matrix-vector multiplication {read x(1:n) into fast memory} {read y(1:n) into fast memory} for i = 1:n {read row i of A into fast memory} for j = 1:n y(i) = y(i) + A(i,j)*x(j) {write y(1:n) back to slow memory} m = number of slow memory refs = 3n + n 2 f = number of arithmetic operations = 2n 2 q = f / m ~= 2 Matrix-vector multiplication limited by slow memory speed Naïve Matrix Multiply {implements C = C + A*B} for i = 1 to n for j = 1 to n for k = 1 to n C(i,j) = C(i,j) + A(i,k) * B(k,j) C(i,j) C(i,j) A(i,:) = + * B(:,j) 9

Naïve Matrix Multiply {implements C = C + A*B} for i = 1 to n {read row i of A into fast memory} for j = 1 to n {read C(i,j) into fast memory} {read column j of B into fast memory} for k = 1 to n C(i,j) = C(i,j) + A(i,k) * B(k,j) {write C(i,j) back to slow memory} C(i,j) C(i,j) A(i,:) = + * B(:,j) Naïve Matrix Multiply Analysis Number of slow memory references on unblocked matrix multiply m = n 3 read (each column of B n times) + n 2 read (each row of A once) + 2n 2 read and write (each element of C once) = n 3 + 3n 2 So q = f / m = 2n 3 / (n 3 + 3n 2 ) ~= 2 for large n, no improvement over matrix-vector multiply C(i,j) C(i,j) A(i,:) = + * B(:,j) 10

Blocked (tiled) matrix multiply Consider A,B,C to be N by N matrices of b by b subblocks where b=n/n is called the block size for i = 1 to N for j = 1 to N {read block C(i,j) into fast memory} for k = 1 to N {read block A(i,k) into fast memory} {read block B(k,j) into fast memory} C(i,j) = C(i,j) + A(i,k) * B(k,j) {do a matrix multiply on blocks} {write block C(i,j) back to slow memory} C(i,j) C(i,j) A(i,k) = + * B(k,j) Tiled Matrix Multiply Consider A, B, C to be N*N matrices of n/n by n/n tiles Bring in a tile from A and a tile from B, and multiply them to update a C tile = * b = n/n for i = 0 to N-1 for j = 0 to N-1 for k = 0 to N-1 for x = 0 to n/n for y = 0 to n/n C[i*b + x][j*b + y] += A[i*b+x][k*b+z]*B[k*b+z][j*b+y] 11

Blocked Matrix Multiple (analysis) Recall: m is amount memory traffic between slow and fast memory matrix has nxn elements, and NxN blocks each of size bxb f is number of floating point operations, 2n 3 for this problem q = f / m is our measure of algorithm efficiency in the memory system So: m = N*n 2 read each block of B N 3 times (N 3 * n/n * n/n) + N*n 2 read each block of A N 3 times + 2n 2 read and write each block of C once = (2N + 2) * n 2 So q = f / m = 2n 3 / ((2N + 2) * n 2 ) ~= n / N = b for large n So we can improve performance by increasing the blocksize b Can be much faster than matrix-vector multiply (q=2) Limits to optimizing matrix multiply The blocked algorithm has ratio q ~= b The large the block size, the more efficient our algorithm will be Limit: All three blocks from A,B,C must fit in fast memory (cache), so we cannot make these blocks arbitrarily large: 3b 2 <= M, so q ~= b <= sqrt(m/3) There is a lower bound result that says we cannot do any better than this (using only algebraic associativity) Theorem (Hong & Kung, 1981): Any reorganization of this algorithm (that uses only algebraic associativity) is limited to q = O(sqrt(M)) 12

Basic Linear Algebra Routines Industry standard interface (evolving) Vendors, others supply optimized implementations History BLAS1 (1970s): vector operations: dot product, saxpy (y=α*x+y), etc m=3*n, f=2*n, q ~2/3 or less BLAS2 (mid 1980s) matrix-vector operations: matrix vector multiply, etc m=n^2, f=2*n^2, q~2, less overhead somewhat faster than BLAS1 BLAS3 (late 1980s) matrix-matrix operations: matrix matrix multiply, etc m >= 4n^2, f=o(n^3), so q can possibly be as large as n, so BLAS3 is potentially much faster than BLAS2 Good algorithms used BLAS3 when possible (LAPACK) See www.netlib.org/blas, www.netlib.org/lapack BLAS Speeds on IBM RS6000 Peak speed = 266 Mflops Peak BLAS 3 BLAS 2 BLAS 1 BLAS 3 (n-by-n matrix matrix multiply) vs BLAS 2 (n-by-n matrix vector multiply) vs BLAS 1 (saxpy of n vectors) 13

Optimizing in Practice Tiling for multiple levels of cache Tiling for registers loop unrolling, use of named register variables Exploiting fine-grained parallelism in processor superscalar; pipelining Complicated compiler interactions Hard to do by hand Automatic optimization an active research area BeBOP: www.cs.berkeley.edu/~richie/bebop PHiPAC: www.icsi.berkeley.edu/~bilmes/phipac in particular tr-98-035.ps.gz ATLAS: www.netlib.org/atlas Strassen s Matrix Multiply The traditional algorithm (with or without tiling) has O(n^3) flops Strassen discovered an algorithm with asymptotically lower flops O(n^2.81) Consider a 2x2 matrix multiply normally 8 multiplies, Strassen does it with 7 multiplies (but many more adds) Let M = [m11 m12] = [a11 a12] * [b11 b12] [m21 m22] = [a21 a22] [b21 b22] Let p1 = (a12 - a22) * (b21 + b22) p5 = a11 * (b12 - b22) p2 = (a11 + a22) * (b11 + b22) p6 = a22 * (b21 - b11) p3 = (a11 - a21) * (b11 + b12) p7 = (a21 + a22) * b11 p4 = (a11 + a12) * b22 Then m11 = p1 + p2 - p4 + p6 m12 = p4 + p5 m21 = p6 + p7 m22 = p2 - p3 + p5 - p7 Extends to nxn by divide&conquer 14

T(n) Strassen s multiplication (contd.) = Cost of multiplying nxn matrices = 7*T(n/2) + 18*(n/2)2 = O(n log 2 7) = O(n 2.81) Asymptotically faster Several times faster for large n in practice Cross-over depends on machine Available in several libraries Caveats Needs more memory than standard algorithm Can be less accurate because of roundoff error Current world s record is O(n 2.376.. ) Outline Optimizations roadmap Optimizing for cache hierarchy Strassen s matrix multiply algorithm (better algorithms) Bag of tricks for optimizing serial code 15

Removing False Dependencies Using local variables, reorder operations to remove unnecessary/false dependencies a = b*c + d*e d = b + 1 <use d> a = b*c + d*e d1 = b + 1 <use d1> Removing False Dependencies Consider the following code: a[i] = b[i] + c; a[i+1] = b[i+1] * d; Will this generate good code? 16

Removing False Dependencies a[i] = b[i] + c; a[i+1] = b[i+1] * d; float f1 = b[i]; float f2 = b[i+1]; a[i] = f1 + c; a[i+1] = f2 * d; With some compilers, you can declare a and b unaliased. Done via restrict pointers, compiler flag, or pragma Exploit Multiple Registers Reduce demands on memory bandwidth by pre-loading into local variables while( ) { *res++ = filter[0]*signal[0] + filter[1]*signal[1] + filter[2]*signal[2]; signal++; } float f0 = filter[0]; float f1 = filter[1]; float f2 = filter[2]; also: register float f0 = ; while( ) { *res++ = f0*signal[0] + f1*signal[1] + f2*signal[2]; signal++; } 17

Minimize Pointer Updates Replace pointer updates for strided memory addressing with constant array offsets f0 = *r8; r8 += 4; f1 = *r8; r8 += 4; f2 = *r8; r8 += 4; f0 = r8[0]; f1 = r8[4]; f2 = r8[8]; r8 += 12; Pointer vs. array expression costs may differ. Some compilers do a better job at analyzing one than the other Expose instruction-level parallelism float f0 = filter[0], f1 = filter[1], f2 = filter[2]; float s0 = signal[0], s1 = signal[1], s2 = signal[2]; *res++ = f0*s0 + f1*s1 + f2*s2; do { signal += 3; s0 = signal[0]; res[0] = f0*s1 + f1*s2 + f2*s0; s1 = signal[1]; res[1] = f0*s2 + f1*s0 + f2*s1; s2 = signal[2]; res[2] = f0*s0 + f1*s1 + f2*s2; res += 3; } while( ); Loop Unrolling 18

Expose Independent Operations Hide instruction latency Use local variables to expose independent operations that can executed in parallel or in a pipelined fashion Balance the instruction mix (what functional units are available?) f1 = f5 * f9; f2 = f6 + f10; f3 = f7 * f11; f4 = f8 + f12; Summary The performance of any algorithm is limited by q In matrix multiply, we increase q by changing computation order increased temporal locality For other algorithms and data structures, even handtransformations are still an open problem sparse matrices (reordering, blocking) trees (B-Trees are for the disk level of the hierarchy) linked lists (some work done here) Performance programming on uniprocessors requires understanding of fine-grained parallelism in processor produce good instruction mix understanding of memory system Blocking (tiling) is a basic approach Techniques apply generally, but the details (e.g., block size) are architecture dependent 19