---
# System prepended metadata

title: Parallel Programming HW6 Report
tags: [Parallel Programming]

---

# Parallel Programming HW6 Report

### 312581029 廖永誠

### Q1

- Question: Explain your implementation. How do you optimize the performance of convolution?

- Answer:
    1. Create a command queue, a filter buffer, an input image buffer, an output image buffer, and a kernel.
    2. Set the global work size to {image width, image height}, which means each kernel will compute one convolution for a single pixel.
    3. My kernel computation is essentially a copy of the serial implementation, but it focuses exclusively on the convolution of one pixel.
        ```c++
        __kernel void convolution(__global const float* filter, const int filterWidth,
                              __global const float* inputImage, __global float* outputImage,
                              const int imageWidth, const int imageHeight, __local float* localFilter) {
        event_t e1 = async_work_group_copy(localFilter, filter, filterWidth * filterWidth, 0);

            int x = get_global_id(0); // col
            int y = get_global_id(1); // row
            int halffilterSize = filterWidth / 2;    
            float sum = 0.0;
            int k, l;

            wait_group_events(1, &e1);

            for (k = -halffilterSize; k <= halffilterSize; k++) {
                for (l = -halffilterSize; l <= halffilterSize; l++) {
                    if (y + k >= 0 && y + k < imageHeight && x + l >= 0 && x + l < imageWidth) {
                        sum += inputImage[(y + k) * imageWidth + x + l] * filter[(k + halffilterSize) * filterWidth + l + halffilterSize];
                    }
                }
            }
            outputImage[y * imageWidth + x] = sum; 
        }
        ```
         - To further enhance kernel performance, I will allocate a local filter buffer to each kernel and copy the data from global to local memory, thereby improving the efficiency of accessing filter data.
    5. After completing all kernel computations, read the data from the output image buffer into the host's output buffer.