Solutions
A
15 points
In approximately 80 words (or slightly more), describe your final project, covering the task description and your current progress. Note: You should have already received a confirmation email from the instructor with the subject "CA2024: Term Project." If you have not received it, promptly contact the instructor via email.
限用英文作答,用中文作答則不計分。字數不要太少都給分,順便檢查學員的期末專題內容。
B
General Matrix Multiply (GEMM) is a widely used algorithm in linear algebra, machine learning, statistics, and various other fields. It offers a more complex trade-off space compared to the previous tutorial, as there are multiple ways to structure the computation. These include techniques such as blocking, inner products, outer products, and systolic arrays. Below is the reference implementation:
Take note of the variables i
, j
, and p
used in the nested loops, as they play a key role in iterating over the computation.
Adjusting the order of i
, j
, and p
does not affect the result, but it can impact performance. Considering the cache, what is the optimal order for best performance? Answer in the form "i-j-p".
j-p-i
Thej-p-i
order is well-suited for cache prefetching, resulting in a higher L1 cache hit rate compared to theipj
order.
What order results in the worst performance?
i-p-j
Test the performance of a specific order across different data sizes. From the graph, it can be observed that as the data size increases, overall performance decreases (the fluctuations in the middle may be related to cache evictions and reloads).
It can be observed that as the data size increases, FLOPS (Floating-point operations per second) will decline. Why does FLOPS decrease rapidly as the matrix size grows larger?
When matrices A and B are smaller than the L2 cache, GEMM only needs to read memory equivalent to the size of A and B from DDR. However, when A and B exceed the size of the L2 cache, due to the row-major layout of B or the column-major layout of A being non-contiguous in memory, GEMM reads more memory from DDR than the size of A and B. This increases cache misses, leading to degraded performance.
To make GEMM faster, let's divide a large matrix into smaller submatrices so that each submatrix can fit entirely in the cache.
First, partition the matrix (along the - and -dimensions) without blocking the -dimension, and then expand:
As shown in the diagram:
The multiplication of the submatrix from and the submatrix from produces a submatrix in (the left one).
Use optimization techniques such as loop unrolling and register caching (reusing register results). Next, divide the large matrix into smaller submatrices to ensure they fit entirely in the cache, thereby improving access performance. The process involves splitting the large matrix into smaller submatrices that can fully reside in the cache for efficient access.
The parameters must meet certain constraints: must be less than half the size of the L2 cache.
Consider the corresponding code below:
jc * ldb + pc
pc * lda + ic
jc * ldc + ic
C
Determining the center of a peak in discrete data, such as a series of bins, can be useful for identifying the "center" of a signal, particularly in contexts like discrete Fourier transform (DFT) bins, touch sensors, or detecting impulses. This method works especially well with normal distributions but can also be effective for any symmetric or nearly symmetric distribution.
To locate the center, identify the highest peak in the dataset and examine the values of the bins immediately to its left and right. Using these values, you can calculate the center's position relative to the peak using the formula below, which estimates the offset from the highest cell:
This approach does not handle cases involving multiple peaks or multipath effects. In such scenarios, it is necessary to identify other peaks, account for their contributions, and iteratively refine the data to isolate and analyze additional peaks. Additionally, this method only applies to sources with a distinct hill-shaped distribution, as mathematically such centers can be detected.
For computational efficiency, consider using fixed-point arithmetic instead of floating-point. Fixed-point math provides higher accuracy with the same bit-width and is generally faster, particularly in embedded systems, even when a floating-point unit (FPU) is available. This makes it a practical choice for resource-constrained environments where performance and precision are critical.
Consider the code below:
This example illustrates the use of fixed-point arithmetic with 16 fractional bits, a common technique in embedded systems for efficient numerical computation. The variables a
and b
are represented in a fixed-point format, where the fractional part is scaled by . For instance, the value a = 132345
corresponds to , and b = 7491
corresponds to .
The addition operation a + b
combines the fixed-point representations directly without any conversion, keeping the result in the same fixed-point format. To display the result in a human-readable floating-point format, the program divides the sum by , which is the scaling factor for 16 fractional bits.
The program outputs the sum as 2.133728
, demonstrating how fixed-point arithmetic preserves computational efficiency while allowing precise representation of fractional numbers. This approach is particularly valuable in resource-constrained environments where performance and accuracy are critical.
The code below shows a method for computing the product while avoiding overflows.
Complete the code to ensure it works as expected. The variable a
must be defined before the variable big_b
. You should use shifts.
a >> 8
or equivalent
big_b >> 8
or equivalent
Let's perform division in fixed-point arithmetic, reversing the approach of multiplication.
The use of shifts achieves three goals:
Complete the code to ensure it works as expected. You should use shifts.
a << 12
or equivalent
b >> 4
or equivalent
The result, when converted back to floating-point by dividing by , is approximately , which is close to the expected value. This approach demonstrates how to manage precision and avoid overflow in fixed-point division while adhering to the constraints of the representation.
D
You are expected to calculate an approximate square root by determining the next power of 2 using the __builtin_clz
function provided by GCC/Clang.
Complete the code to ensure it works as expected. You should invoke the __builtin_clz
function.
(32 - __builtin_clz(i)) / 2
or equivalent
Here is the extracted description with LaTeX annotations:
The Fast Fourier Transform (FFT) is a computational method used to efficiently compute the discrete Fourier transform of a sequence. This implementation also includes a function for convolution, defined as:
This convolution function calculates the resulting sequence by summing the product of elements from the input sequences and , with one sequence reversed and shifted. It is particularly useful in signal processing and applications requiring fast computation of polynomial or data convolutions. Consider the corresponding code below:
The reference output:
Complete the code to ensure it works as expected. You should invoke the __builtin_clz
function.
32 - __builtin_clz(s)
av[i] * bv[i]
or equivalent
E
The core concept of data-level parallelism is vectorized computation, which involves performing operations on multiple elements of a single vector simultaneously.
Consider the following function, which computes the product of all elements in an array:
Your task is to vectorize this function using the RISC-V Vector extension to leverage parallel processing.
Complete the code to ensure it works as expected.
vsetvli
vlw.v
vsw.v
F
Your task is to implement a simulator for the RISC-V instruction set. Below is a partial C source code snippet for instruction decoding and execution.
CSR(imm) = t | R(rs1)
CSR(imm) = R(rs1)
R(rs1) + IMM(I)
16
2
4
0x3f
or equivalent
0x3f
or equivalent
NPC = PC + IMM(J)
or equivalent
0b111
or equivalent
0b110
or equivalent
0b000
or equivalent
0b1110011
or equivalent
0b1110011
or equivalent
0b010000
or equivalent
0b000000
or equivalent
0b1100111
or equivalent
0b0010111
or equivalent
0b0110111
or equivalent
0b1101111
or equivalent
R(0) = 0
or equivalent
G
Our processor features an 8-entry direct-mapped TLB, indexed using the lowest-order bits of the virtual page number. The program below operates on a matrix , which consists of 4 rows and 256 columns. Each element in is a 32-bit integer, laid out in row-major order (i.e., consecutive elements in the same row occupy contiguous memory locations). The program computes the sum of the entries in a top-right submatrix of matrix . Assume starts at virtual address 0x0000, and the result of the sum is stored in a register. Instruction fetches can be ignored.
How many TLB misses will this program encounter when and (i.e., when )?
32
Matrix spans 32 contiguous 128B pages. Since all elements in are accessed sequentially in the order they are laid out in memory, there will be a total of 32 TLB misses.
What is the highest possible TLB hit rate that this program can achieve?
Keep in mind that each page contains 32 elements of matrix . The maximum TLB hit rate occurs when there is 1 miss to load a page into the TLB, followed by 31 hits, resulting in a hit rate of .
To achieve this, must be , where , and can be any value.
It has been suggested that increasing the page size could significantly reduce TLB misses in the direct-mapped TLB for this program. For which values of (G03, range) and (G04, range) would doubling the page size fail to improve the TLB hit rate?
or equivalent
any
With the larger page size, each page now contains 64 elements, and a single row of spans 4 pages. For and any , the number of hits remains unchanged compared to smaller pages, as increasing the page size does not reduce compulsory misses.
What is the smallest page size, as a power of 2, that ensures our program incurs at least one TLB hit for all values of and where ?
2048B or equivalent
To determine the minimum page size, consider the scenario with the lowest hit rate (0%), where accessing one element per column resulted in no reuse, as elements from different columns belonged to different pages. Therefore, the minimum page size required to guarantee at least one TLB hit must be greater than 1024B. Since page sizes must be powers of two, the smallest such size is 2048B.
The program is now modified by swapping the order of the two nested loops, as shown below:
Assume . For which values of will doubling the page size enhance the TLB hit rate of the above program?
or equivalent
For , doubling the page size causes TLB entry conflicts between the first and third rows, as well as between the second and fourth rows.
H
This question involves analyzing an out-of-order machine. A program consisting of 50% integer and 50% floating-point instructions is profiled. The average latencies for these instructions, assuming infinite reservation station and commit queue sizes, are as follows:
Instruction Type | Decode to Issue | Decode to Commit | FU Latency |
---|---|---|---|
Integer | 3 cycles | 8 cycles | 2 cycles |
Floating-Point | 6 cycles | 20 cycles | 12 cycles |
If the processor commits an average of 0.5 instructions per cycle for this program, how many entries are occupied on average in the reservation stations and the commit queue?
Integer Reservation Station:
0.75
Floating-Point Reservation Station
1.5
Commit Queue:
7
We use Little's Law to calculate the occupancy ((N)) of each structure:
where is the throughput, and is the latency.First, the throughput for integer () and floating-point () instructions is 0.25 instructions per cycle each, as the total throughput is 0.5 instructions per cycle and the program consists of 50% integer and 50% floating-point instructions.
For the integer reservation station, the latency is 3 cycles. Using Little's Law, the occupancy is:
For the floating-point reservation station, the latency is 6 cycles. The occupancy is:
To compute the occupancy of the commit queue, we calculate the occupancy for each type of instruction separately and then sum them.For integer instructions, the latency is 8 cycles, so the occupancy is:
For floating-point instructions, the latency is 20 cycles, so the occupancy is:
The total commit queue occupancy is:
I
Suppose you are designing a branch predictor for a pipelined in-order processor with the following stages.
The processor operates with the following characteristics:
Within this pipeline, control flow instructions are handled as follows:
BLE
/BNE
) consult the branch predictor. If a branch is predicted to be taken, all subsequent instructions in the pipeline are flushed, and the PC is redirected to the calculated branch target address.JAL
instructions execute the jump to the target address in the B stage, flushing all subsequent instructions in the pipeline. The implementation of JALR
does not need to be considered.For the following questions, consider the given C code and its corresponding RISC-V assembly equivalent. Note that there are no branches other than those explicitly included in the assembly code.
This setup forms the basis for analyzing the control flow and behavior of the program.
Assume that branch B1
is always Not Taken, while the branch predictor predicts all branches as Taken. On average, how many instructions will the processor flush per iteration of the loop?
13
The loop involves two conditional branches. For the first branch, which is mispredicted as taken, 7 instructions are flushed. Additionally, the unconditionalJAL
is taken, resulting in another 3 instructions being flushed. Therefore, the total number of instructions flushed is .
The branch predictor uses a single branch history table (BHT) indexed by the lower 10 bits of the PC. Each entry in the table is a 1-bit counter that predicts "taken" if the value is 1 and "not taken" if the value is 0. The table is updated with the actual branch outcome at the end of the execute stage (1 for "taken," 0 for "not taken"). Given that the elements of array are uniformly distributed between , will the predictor achieve high or low accuracy for branches and ?
Branch B1
will have a prediction accuracy of approximately __ I02 __ (rate) since the branch direction is completely random.
50%
B2
is __ I03 __ (condition).
always taken or equivalent
J
To design a directory-based MSI coherence protocol, the directory uses a bit vector to represent the sharer set for each cache line. In an -core system, the directory maintains an -bit wide bit vector for each line it tracks. If the -th bit of the bit vector is set, it indicates that core 's cache holds a copy of the line in either the Shared (S) or Modified (M) state.
Assume the processor has cores, each with a 1KB private cache using 32B cache lines. How many entries must the directory contain to track all the cache lines in the private caches?
or equivalent
Each core has 32 private cache lines, and with ( N ) cores, the total number of cache lines is $32 \times N $.
The design of the sharer sets is modified to replace the bit vector with a set of sharer pointers. Each pointer stores the core ID of one sharer. For instance, if cores 10 and 12 hold a cache line in the Shared (S) state, the sharer set in the directory will consist of two pointers, "10" and "12." Each sharer set can hold a maximum of 16 sharer pointers.
In an -core system, where is a power of 2, how many total bits are required to represent all sharer pointers in a sharer set?
or equivalent
With 16 pointers and each pointer requiring bits to represent the core ID, the total number of bits needed is .
K
The following questions examine memory accesses from multiple cores in a cache-coherent shared memory system. Each question evaluates the possible outcomes under the following memory consistency models:
Assume all registers (e.g., r1
, r2
, …) and memory locations (e.g., a
, b
, …) are initialized to 0.
Consider a cache-coherent shared-memory system executing the following two threads on two different cores. Assume that memory locations a
, b
, and c
are initialized to 0.
Thread 1 (T1) | Thread 2 (T2) |
---|---|
ST (a) <- 1 |
LD r1 <- (a) |
LD r2 <- (b) |
ST (b) <- 1 |
ST (a) <- 2 |
Identify the memory consistency models where the final values r1 = 1
, r2 = 0
, and (a) = 1
are possible. (Answer in SC, TSO, and RMO)
TSO, RMO
Consider the following four threads executing on a cache-coherent shared-memory system:
Thread 1 (T1) | Thread 2 (T2) | Thread 3 (T3) | Thread 4 (T4) |
---|---|---|---|
ST (a) <- 1 |
ST (a) <- 2 |
LD r1 <- (a) |
LD r2 <- (a) |
LD r3 <- (a) |
LD r4 <- (a) |
Determine the memory consistency models where the final values r1 = 1
, r2 = 2
, r3 = 2
, and r4 = 1
are possible. (Answer in SC, TSO, and RMO)
RMO
Consider the following three threads executing on a cache-coherent shared-memory system:
Thread 1 (T1) | Thread 2 (T2) | Thread 3 (T3) |
---|---|---|
ST (a) <- 1 |
LD r1 <- (a) |
LD r3 <- (b) |
LD r2 <- (b) |
LD r4 <- (a) |
|
ST (b) <- 1 |
Determine the memory consistency models where the final values r1 = 1
, r2 = 0
, r3 = 1
, and r4 = 0
are possible. (Answer in SC, TSO, and RMO)
TSO, RMO
A sequence lock is a synchronization primitive used to allow a single writer thread to "publish" data that can be read by multiple reader threads. Its key property is that the writer is never blocked, though readers may be temporarily blocked. The code provided below is correct when executed on a system with sequential memory consistency but is not guaranteed to be correct under weaker memory consistency models.
The writer thread increments the sequence number twice—once before writing and once after. An odd sequence number indicates that a write operation is ongoing. The writer ensures that readers see either the previous consistent state or the fully updated state.
Readers check the sequence number before and after reading the object. If the sequence number changes during the read or is odd at the start, the reader retries. This ensures that the reader observes a consistent view of the data.
Notes
memcpy
is not atomic, readers can observe partial updates if the sequence lock's guarantees are violated.atomic_add
) do not act as memory barriers, which may lead to reordering of instructions under weaker memory consistency models.object_t
is assumed to be an opaque structure larger than 16 bytes, making it unsuitable for atomic memory operations. The sequence lock ensures that each reader observes a complete and consistent version of the object.If this sequence lock is used on a multicore system with TSO (Total Store Order) consistency, would the code remain correct? If yes, briefly explain why. If no, clearly specify the memory barriers that need to be added to ensure correctness.
Yes
(意思相近就給分)
The code would still be correct under TSO. TSO only allows stores to be re-ordered after loads.get_obj()
does not have any stores to shared data, so it is clearly correct.
publish()
is also correct, but it requires more justification. Let’s reason through the loads and stores it does to shared data (with atomics broken down into LD/ST pairs):
LD seq
<- cannot be reordered later due to RAW dependency.ST seq
<- cannot be reordered later because TSO doesn’t allow ST-ST reordering.ST object[0] ... object[n]
<- cannot be reordered later because TSO doesn’t allow ST-LD reordering.LD seq
<- cannot be reordered later due to RAW dependency.ST seq
If this sequence lock is used on a multicore system with RMO (Relaxed Memory Order) consistency, would the code remain correct? If yes, briefly explain why. If no, clearly specify the memory barriers that must be added to ensure correctness.
No
(意思相近就給分)
With RMO, we need to add fences in bothpublish()
andget_obj()
. Specifically, we need RR fences both before and after thememcpy()
inget_obj()
and WW fences before and after thememcpy()
inpublish()
.
The code above uses two atomic additions in the publish
function. Assuming a correct implementation on either TSO or RMO (with the necessary barriers in place), would replacing the atomic increments with ordinary non-atomic increments be sufficient? Why or why not?
Yes
Non-atomic instructions are fine.
The problem states that only a single thread will call
publish()
. Therefore, there will never be data races on&seqlock->seq
. We can simply regard the store to&seqlock->seq
as the serialization point.
L
This problem evaluates a virtual memory system with the following characteristics:
The page table structure is summarized below, including the sizes of the page tables and data pages (not drawn to scale).
The processor includes a data TLB with 64 entries, and each entry can map either a 4KB page or a 1MB page. After a TLB miss, a hardware engine walks the page table to reload the TLB. The TLB operates using a first-in/first-out (FIFO) replacement policy.
The following program adds the elements from two 1MB arrays and stores the results in a third 1MB array. Assume that , and the starting addresses of the arrays are as follows:
Assume this program is the only process running on the system, and ignore instruction memory or operating system overheads. The data TLB is initially empty. The system has no cache, and each memory lookup has a latency of 100 cycles.
If all data pages are 4KB, compute the ratio of cycles for address translation to cycles for data access.
Address translation cycles
300
100 + 100 +100 (for L1, L2 and L3 PTE)
Data access cycles
400K or equivalent
4K * 100
(there is no cache, this assumes that memory access is byte-wise)
If all data pages are 1MB, compute the ratio of cycles for address translation to cycles for data access.
Address translation cycles
200
100 + 100 (for L1, L2 PTE)
Data access cycles
100M or equivalent
1M * 100
(there is no cache, this assumes that memory access is byte-wise)
Assume the system includes a PTE cache with a latency of one cycle. The PTE cache stores page table entries and has unlimited capacity. Calculate the ratio of cycles spent on address translation to cycles spent on data access for the case where data pages are 4KB.
Address translation cycles
77200
(256*3 + 3 + 1) * 100
(Note that the arrays are contiguous and share some PTE entries. 256 L3 PTEs per array * 3 arrays, 1 L2 PTE per array * 3 arrays, 1 L1 PTE)
Data access cycles
300M or equivalent
3M*100
What is the minimum number of entries required in the PTE cache to achieve the same performance as an unlimited PTE cache? Assume the PTE cache does not store L3 PTE entries and all data pages are 4KB.
4
(1 for L1 and 3 for L2)
M
Suppose we have the following two functions, each running in its own thread:
thread1
:thread2
:Processor Design
The program runs on an in-order, two-way coarse-grained multithreaded processor with the following characteristics:
If each of these threads were executed individually on this processor, without multithreading, which thread would achieve a higher IPC?
thread2
Explain your reasoning.
(意思相近就給分)
Cache misses (100 cycle penalty) are much more expensive than branch mispredictions. So, even though thread2 can mispredict ~2 branches per iteration, the penalty is much smaller, resulting in higher IPC.
Suppose the core switches between threads upon encountering a cache miss. When a data cache miss occurs, the processor flushes the pipeline, switches to the other thread, and continues executing that thread until it encounters a miss. The pipeline flush discards the load instruction and all subsequent instructions, up to 6 instructions in total (including the load).
Would this design enable both threads to execute close to their peak single-threaded IPC in steady state?
No. thread2
has no memory instructions that could miss in cache. Therefore, once we switch to thread2, we would never have another cache miss again, starving thread1 entirely.
To fix this, we could switch on:
100
Now, consider running multiple instances of thread1
on this CPU. To achieve maximum IPC, more than 2-way multithreading will be required. What is the minimum number of thread1
instances that must run concurrently on this pipeline to maximize IPC?
In each inner-loop iteration, there are 6 instructions to execute, plus an additional 6 instructions that were flushed, resulting in a total of 12 instructions per loop iteration. To maximize IPC, at least ceil(100 / 12) = 9 threads are required.9
Each time a cache miss occurs, 6 instructions are flushed from the pipeline. These instructions must be re-executed when the thread is switched back, assuming the load will now hit in the cache.
Suppose we implement a policy of switching on branch instructions. In a coarse-grained multithreaded implementation, generating a "switch" signal for the multithreading control logic can occur at various stages of the pipeline. If the switch occurs at stage , stages through must be flushed.
Now, consider running two instances of thread2
. Which of the following switching points would result in the highest overall IPC? Select one of them.
a. Switch on every branch (as predicted by the BTB)
b. Switch on every branch misprediction (detected in the ALU)
c. Switch on every branch (as determined during decode)
d. Switch on every branch predicted taken (as determined by the branch predictor)
a
N
Multitasking is a fundamental concept in computer systems, allowing multiple tasks or processes to run concurrently, improving resource utilization and system responsiveness. Traditional multitasking in operating systems relies on threads and processes managed by the kernel. These kernel-level threads are preemptively scheduled, meaning the operating system decides when to switch between tasks. While effective, this approach introduces significant overhead due to context switching, where the CPU saves and restores registers, memory mappings, and other state information.
In scenarios where lightweight concurrency is needed, kernel-level multitasking often proves excessive. For instance, tasks such as cooperative multitasking, event-driven programming, or managing independent components within a simulation do not require preemption. Here, user-level constructs like coroutines or userspace threads become powerful tools.
Coroutines provide a mechanism for cooperative multitasking, where tasks explicitly yield control to other tasks at well-defined points. Unlike kernel-level threads, coroutines operate entirely in user space, requiring minimal overhead. This makes them an excellent choice for applications like asynchronous programming, where tasks need to pause while waiting for external events such as I/O completion, without blocking other operations. Coroutines maintain their execution state, including the program counter and local variables, allowing them to resume from where they left off seamlessly. This feature makes them particularly useful in game development, where behaviors like AI or animations require frequent context switching within a single-threaded environment.
Userspace threads, on the other hand, are an abstraction similar to coroutines but with a broader scope. They simulate traditional threads but are scheduled and managed entirely in user space, independent of the kernel. Userspace threads offer greater control over scheduling policies and avoid the overhead of kernel-mode context switches. However, unlike coroutines, userspace threads can preempt one another, making them closer in behavior to kernel threads but much more efficient for many workloads.
The trade-off between coroutines and userspace threads lies in complexity and flexibility. Coroutines are simpler, focusing on cooperative multitasking, while userspace threads provide additional features like preemption. In both cases, these constructs shine in environments where performance and fine-grained control are critical. They reduce the reliance on the kernel, avoid heavy context-switching overhead, and enable developers to implement concurrency with precision tailored to the application's needs.
For example, a high-performance web server might use coroutines to handle thousands of simultaneous connections without creating thousands of threads, which would strain the system's resources. Similarly, scientific simulations with many interacting entities might leverage userspace threads to model their behavior efficiently. Both approaches showcase how user-level multitasking constructs can outperform kernel-level alternatives in specific domains, enabling scalable and efficient multitasking solutions.
Implementing general-purpose coroutines typically requires a second call stack, a feature not natively supported by the C language. A practical, though platform-specific, approach involves using inline assembly to manipulate the stack pointer during the coroutine's initial setup. After obtaining a second call stack, the setjmp and longjmp functions from the standard C library can be used to switch between coroutines.
These functions work by saving and restoring the stack pointer, program counter, callee-saved registers, and other internal state required by the ABI. This ensures that returning to a coroutine after yielding restores its full state, as if resuming from a paused function call. Alternatively, minimalist implementations can achieve similar results by using inline assembly to swap only the stack pointer and program counter, ignoring other registers. While this approach clobbers all other registers, it can be much faster than relying on setjmp
and longjmp
, which must conservatively save all registers specified by the ABI. By contrast, the minimalist method allows the compiler to manage register spilling, saving only what is actively in use.
We now aim to implement a minimalist coroutine system on the RV32I architecture, assuming a 32-bit system without floating-point operations.
main.c
context.S
Build the above using the command:
Complete the code to ensure it works as expected.
-16
or equivalent
~(ALIGN - 1)
56
60