# Lab 5 : Systolic Array Integration and Cache Coherence


## Goal of this lab
---
- [Basic Exercise 1 - Integrate Systolic Array - 30%](#basic-exercise-1-integrate-systolic-array-30)
- [Basic Exercise 2 - Hardware Cache Coherence - 30%](#basic-exercise-2-hardware-cache-coherence-30)
- [Advanced Exercise - Accelerate Convolution - 20%](#advanced-exercise-accelerate-convolution-20)
- [Questions in the Demo - 20%](#questions-in-the-demo-20)

## Extra File
```text
Platform/
└── sw/
    └── project/
        ├── lab5_api.h/.cc
        └── systolic_array_test.h/.cc
Platform/
└── sw/
    └── tflm_patches/.../conv.h
```

## Introduction
---
After finishing lab 3-2, the implementation of a systolic array for GEMV, we are going to integrate it into our SoC platform. The integrated design will also serve as a starting point for accelerating convolution.

To successfully integrate your systolic array, you will design custom-instruction operations that configure and start GEMV computations.

In previous Labs, we provide you `CBO` operations to avoid cache coherence problem. In this lab, you may still use CBOs while validating Basic Exercise 1. In Basic Exercise 2, GEMV must remain correct without software CBO assistance in its execution path; hardware must provide the necessary coordination.

## Basic Exercise 1 - Integrate Systolic Array - 30%
---

Software places matrix A and vector B in memory and invokes the NPU through custom instructions. The NPU accesses the operands through its AXI master interface, performs GEMV using the integrated systolic array, and makes the resulting vector C available in memory for subsequent CPU reads.
<img src="images/lab5/block_diagram_axi_new.png" width="600px">

<!-- The key word spotting model we intend to accelerate uses int8, and since negative values occur during computation, we need to modify it to support operations with signed integers.

You may use the below command under the lab 3 directory `AAML2025-Lab3/` to make sure it can deal with ***signed*** int8 correctly.
```
$ make verif_signed
```
The pattern generator will generate 50 sets of two 16*16 matrix using int8 ∈ [-128, 128) and pass it to your systolic array and check the answers. -->
### Get started
Now you are ready to do the integration! Create a new copy project folder of Lab4. We use the Lab4 environment. You can also reuse your Lab 3-2 modules like TPU, PE, etc., (board_bram), in your project. You are allowed to add some supporting modules in `Platform/hw/srcs`.

<!-- As shown in the block diagram, we will also be intergrating global buffer A, B and C into the CFU, we have provide a global buffer that utilises the BRAM resources of the FPGA instead of flip-flop, **please mind that this buffer does not have an async reset**.
```{important}
 [global_buffer_bram.v](https://raw.githubusercontent.com/nycu-caslab/AAML2025/refs/heads/main/lab5_util/global_buffer_bram.v) for the global buffer using BRAM and the example to instantiates it. -->

It's totally fine if you want to use something else instead of using LAB 3-2 BRAM buffer, as long as you can integrate your systolic array into the NPU and pass the tests.

### Testing
After integrating the accelerator and defining how software configures and starts it, it is nice to do some verification now. We provide a systolic_array_test before you really dive into the complicated inference of the MobileViT model.  
```{important}
A is a row-major M × K signed int8 matrix, B is a K-element signed int8 vector, and C contains M signed int32 results. Public and hidden GEMV tests satisfy 1 ≤ M, K ≤ 254 and ceil(M / 4) × K ≤ 1024. Test dimensions and values may differ from the public examples.
```
```{important}
The complete FPGA design must achieve **WNS >= 0 ns** for setup timing and **WHS >= 0** for hold timing in the final post-route Design Timing Summary generated by Vivado.

Use the provided clock and timing constraints. Do not reduce the required clock frequency or relax timing constraints to satisfy this requirement. A synthesis timing estimate or a timing report for an isolated accelerator module is not sufficient.

Passing functional tests on the FPGA does not waive this timing requirement.
```
1. In `proj_menu.cc`, include `systolic_array_test.h` or declare extern void systolic_test();, then add a menu entry that calls `systolic_test()`.
```c++
// For example
MENU_ITEM('s', "run Lab5 tests", systolic_test)
```

2. Design your `lab5_api.h/cc`. We have provided examples in the file, but you can make your own design to support your work.
```{important}
Do not modify `systolic_array_test.h/.cc` and the `do_gemv_test` declaration.
```
```{important}
In this part, you can still use CBO extension to pass the test. (You may need it)
```
```c++
void do_gemv_test(int M, int K, const int8_t* matA, const int8_t* matB, int32_t* matC);
```

A successful run reports that all provided GEMV cases passed. The following image shows an example:
<img src="images/lab5/sa_test_result.png" width="600px">


## Basic Exercise 2 - Hardware Cache Coherence - 30%
Because our NPU directly access memory through AXI without passing through the D-cache, you may encounter cache coherence problem under several situations.  
We provide you some scenarios to think about:

| Scenario | Problem |
|---|---|
| A/B are dirty cache lines newly written by the CPU | The NPU reads the old A/B from DDR |
| C is a clean cache line previously read by the CPU | The NPU completes writing C, but the CPU continues to read the old C |
| C is a dirty cache line modified by the CPU | The old C is later written back, overwriting the NPU's new result |

To solve cache coherence problems without CBO, we use hardware to deal with it.  
This section is a little bit complex, you may need to trace codes of `CPU(I/O to Backend_top)`, `Backend_top`, `dcache_pro`, `(MEM)` in `Platform/hw/srcs/sources_1/imports` to understand how they work and interact with each other. And you may need to modify them or add new modules in the same folder and use `Block Design`.

Here is a guideline of BD: [Here](https://hackmd.io/@yanyoulin/H1xq5Pk0zg)

For every GEMV operation, the NPU must use the latest A and B values written by the CPU. Once the operation completes, CPU reads of C must return the NPU's results, and older cached values must not overwrite C later. Hardware must provide these guarantees without software cache-maintenance operations in the Lab5 GEMV execution path. You may choose how to coordinate the CPU cache and NPU.  

One possible design is to let the NPU request D-cache writeback or invalidation when needed around its AXI memory accesses. Other hardware approaches are also valid.

After you finish your work, you can still use `systolic_array_test` to test your work. But before you test, make sure you delete or comment all CBO extension use.
```{important}
During testing, we will remove cbo.h before compiling, so you must ensure it compiles without any errors.
```

## Advanced Exercise - Accelerate Convolution - 20%
Now you have a working systolic array that can do GEMV correctly, it's time to **accelerate convolution**.  

We provide `conv.h` with the code used to measure **Counter 2**. You may modify this file to integrate your systolic array and implement your acceleration method. **Keep the Perf Start and Perf End code unchanged and in their original locations.**

### Restrictions
- No CBO operations. We will remove `cbo.h` before compiling.
- You may have noticed that dynamic memory allocation, such as using new or malloc, is not supported in our SoC. Therefore, we recommend declaring fixed-size arrays.

### Hints
- **im2col:** One possible approach is to reorganize input patches for matrix-based computation.
- **Tiling:** Consider dividing the computation into smaller tiles when the full workload does not fit the storage available to your design.
- **Input offset:** Quantized convolution includes an input offset. Make sure your accelerated result matches the reference computation, including at padded boundaries.

```{Note}
Other than the shapes of convolution, it is also crucial to handle parameters such as **stride, dilation and padding** correctly to ensure the matrices are constructed properly for the convolution.

For simplicity, in this lab, **you can ignore batch and group parameters, assuming both are set to 1**. This assumption will still allow you to pass all the required tests.
```

### Evaluation Criteria
We will test the performance of your implementation based on the MobileViT model provided in lab4.

Also, to earn the score for this part, you still need to complete the `TFLM inference, verification, and cycles` without any failures.
```{important} 
You will get **0%** if you can't pass the `TFLM inference, verification, and cycles` or didn't meet the requirement.
```

**Here is the hardware maximum usage.**  
You can check the informations in `Platform\build\reports\post_route_utilization_npu.rpt`.
| Resource| Maximum NPU usage |
| ---  | ---: |
| LUTs | 5,000 |
| Flip-flop | 3,000 |
| DSP | 16 |
| RAMB18 | 10 |
| RAMB36 | 10 |

```{important} 
You will get **0%** if you didn't meet the requirement.
```

result example:
```
==============================================
 Counter |       Total | Starts |   Average   
---------+-------------+--------+-------------
    0    |     xxxxxxx |     xx |     xxxxxxx
    1    |     xxxxxxx |     xx |      xxxxxx
    2    |   xxxxxxxxx |     xx |     xxxxxxx
    3    |           0 |      0 |         n/a
    4    |           0 |      0 |         n/a
    5    |           0 |      0 |         n/a
    6    |           0 |      0 |         n/a
    7    |           0 |      0 |         n/a
    8    |           0 |      0 |         n/a
    9    |           0 |      0 |         n/a
==============================================
Cycles: xxx
Time (50000000 Hz): xxx ms
---
```

| Average Cycles of Counter 2 | > 150M  | 150~15M  | 15~10M | < 10M |
| ------------------- | ------- | --------- |:-------- |:------ |
| Score               | 0       | 10        | 15       | 20     |


## Questions in the Demo - 20%
---
You will be asked several questions about the concepts covered in this lab and your implementation. This section accounts for 20% of the total lab score.


## Submission
---
Please organize your submission files into a zip archive structured as follows:
```
aaml-lab5-[id].zip
└── aaml-lab5-[id]/
    ├── hw/
    |   └── srcs/
    |       ├── NPU.v
    |       ├── {TPU, PE}
    |       ├── {any other required modules}
    |       └── sources_1/
    |           ├── imports/
    |           |   ├── CPU.v
    |           |   ├── Backend_top.v
    |           |   ├── dcache_pro.v
    |           |   └── {any other required modules}
    |           └── bd/
    |               ├── MMIO.bd
    |               └── {any other required modules}
    └── sw/
        ├── lab5_api.h/.cc
        ├── conv.h
        └── {any other required headers or source files}
```

```{important}
TAs should be able to run your project without any modification. If TAs cannot compile or run your code, **you won't receive any points, even if you passed the DEMO**. Also, **PLAGIARISM is not allowed**.
```
