Changes

Jump to: navigation, search

GPUSquad

18,226 bytes added, 13:21, 10 November 2023
m
Team Members
</source>
== Team Members ==
# [mailto:tsarkar3@myseneca.ca?subject=dps915 Tanvir Sarkar]TS
# [mailto:moverall@myseneca.ca?subject=dps915 Michael Overall]
# [mailto:ikrasnyanskiy@myseneca.ca?subject=gpu610 Igor Krasnyanskiy]
# [mailto:tsarkar3@myseneca.ca;moverall@myseneca.ca;ikrasnyanskiy@myseneca.ca?subject=dps915gpu610 Email All]
== Progress ==
PNG image should be created in the same folder as the jacobi out.# files
</source>
 
The images look something like this:
m = 32, n = 1024
 
[[File:dps915_gpusquad_jacobi_output.png]]
<nowiki>************************</nowiki>
</source>
<nowiki>************************</nowiki><pre style="color: green">
The hotspot seems to be the double for-loop based on m and n in the Jacobi iterations code of the dojacobi() function. I believe these matrix calculations could be parallelized for improved performance. Note that the for-loop that the double loop is inside of is based on a constant numbers, iters, so it doesn't grow with the problem size. It would be O(iters * n^2) which is still O(n^2) not O(n^3).
</pre>
==== Idea 2 - LZW Compression ====
POTENTIAL FOR PARALLELIZATION:
The compress() function performs similar operations on a collection of text, however it relies on a dictionary and an expanding string to be tokenized in a dictrionary. This could potentially be paralellized through a divide and conquer strategy where gpu blocks with shared caches share their own dictionary dictionaries and iterate over their own block of text. This, however would not be particularly useful because LZW compression relies on a globally accessible dictionary that can be continuously modified. Having multiple threads try to access the same dictionary tokens in global memory would create race conditions, and creating block-local dictionaries in shared memory would reduce the efficacy of having a large globally available dictionary to tokenize strings. What all of this means is that LZW compression would probably be a poor candidate for parallelization due to the way that parallel memory would try to update the token dictionary.
==== Idea 3 - MergeSort ====
=== Assignment 2 ===
 
We chose to move forward with the Jacobi Method for 2D Poisson Equations code.
 
We parallelized the original code by placing the jacobi calculations into a kernel. For this initial parallel version, we only used 1D threading and had each thread run a for loop for the other dimension.
 
The iters loop launches a kernel for each iteration and we use double buffering (where we choose to launch the kernel with either d_a, d_b or d_b, d_a) since we can't simply swap pointers like in the serial code.
 
Double buffering is needed so that there is a static version of the the matrix before the current set of calculations are done. Since an element of the matrix is calculated based on elements on all four sides, if one of those elements updated itself while calculations were being done on another element, you would end up with the wrong answer/race conditions.
 
<nowiki>****************</nowiki>
 
CODE
 
<nowiki>****************</nowiki>
 
<source>
int ymin, int ymax, float dx, float dy, float dxxinv, float dyyinv) {//MODIFY to suit algorithm
int j = blockDim.x * blockIdx.x + threadIdx.x + 1; 
//above: we are using block and thread indexes to replace some of the iteration logic
if (j < n - 1) {
}
</source>
 
<nowiki>****************</nowiki>
 
A2 TIMINGS
 
<nowiki>****************</nowiki>
[[File:dps915_gpusquad_a2_chart.png]]
=== Assignment 3 ===
Optimization techniques usedattempted
* Get rid of the for loop in the kernel and use 2D threading within blocks
* Use gpu constant memory for jacobi calculation constants
* Utilize the ghost cell pattern for shared memory within blocks
 
The ghost cell pattern is a technique used to allow threads in a particular block to access data that would normally be inside another block.
We make a shared memory array larger than the number of threads per block in a particular dimension, then when we are at the first or last thread,
can copy a neighbouring cells' data based on a global index, to our local ghost cell.
 
The following info and images are taken from: http://people.csail.mit.edu/fred/ghost_cell.pdf
 
Ghost Cell Pattern Abstract:
<pre>
Many problems consist of a structured grid of points that
are updated repeatedly based on the values of a fixed set
of neighboring points in the same grid. To parallelize these
problems we can geometrically divide the grid into chunks
that are processed by different processors. One challenge
with this approach is that the update of points at the periphery
of a chunk requires values from neighboring chunks.
These are often located in remote memory belonging to different
processes. The naive implementation results in a lot
of time spent on communication leaving less time for useful
computation. By using the Ghost Cell Pattern communication
overhead can be reduced. This results in faster time to
completion.
</pre>
 
In our code, our main jacobi calculations look like this (when using global indexing):
<source>
a[ij] = (input + dxxinv*(b[ij - 1] + b[ij + 1])
+ dyyinv*(b[ij - m] + b[ij + m]))*dcent;
</source>
* b[ij - 1] is a cell's left neighbour
* b[ij + 1] is a cell's right neighbour
* b[ij - m] is a cell's top neighbour (we represent a 2D array as a 1D array, so subtract row length to go one cell up)
* b[ij + m] is a cell's bottom neighbour (add row to go one cell down)
 
[[File:Dps_915_gpusquad_needneighbour.png]]
 
[[File:Dps_915_gpusquad_ghostcellexample.png]]
 
We use a 1D grid of blocks which have 2D threads.
Thus the first block needs ghost cells on the right side, the last block needs ghost cells on the left side, and
all other blocks in the middle need ghost cells on both the left and right sides.
 
In A2 and A3 we only scaled the columns (we would have, had we not mixed up the indexing--the 2d version scales along the n dimension, while the 1d versions scale properly along the n dimension), and the other dimension always stayed at 32. This made it easy for us to keep the grid of blocks one dimensional.
If we scaled the rows as well as the columns we would most likely have need to use a two dimensional grid of blocks.
This would make the problem more difficult as we would then not only need ghost columns, but also ghost rows on the top and bottom of blocks. This would likely cause synchronization problems because we would need to make sure that block execution was synchronized along 2 dimensions instead of just one.
 
[[File:dps915_gpusquad_2Dghostcells.png]]
 
<nowiki>****************</nowiki>
 
CODE FOR 1D GRID WITH 2D THREAD SETUP (kernel contains shared and global memory versions)
 
<nowiki>****************</nowiki>
 
<source>
#include <cuda.h>
#include "cuda_runtime.h"
#include <device_launch_parameters.h>
#include <stdio.h>
#include <device_functions.h>
#include <cuda_runtime_api.h>
#ifndef __CUDACC__
#define __CUDACC__
#endif
// Load standard libraries
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include <chrono>
using namespace std;
const int ntpb = 1024;//TOTAL number of threads per block
const int ntpbXY = 32;
__device__ __constant__ int d_m;
__device__ __constant__ int d_n;
__device__ __constant__ float d_xmin;
__device__ __constant__ float d_xmax;
__device__ __constant__ float d_ymin;
__device__ __constant__ float d_ymax;
__device__ __constant__ float d_pi;
__device__ __constant__ float d_omega;
__device__ __constant__ float d_dx;
__device__ __constant__ float d_dy;
__device__ __constant__ float d_dxxinv;
__device__ __constant__ float d_dyyinv;
__device__ __constant__ float d_dcent;
__device__ __constant__ int d_nBlocks;
__device__ __constant__ int d_ntpbXY;
void check(cudaError_t err) {
if (err != cudaSuccess)
std::cerr << "ERROR: *** " << cudaGetErrorString(err) << " ****" << std::endl;
}
 
</source>
<pre style="color: blue">
//every thread does a single calculation--remove iterations
//-take everything from one dimensional global, and put into 2d shared--shared has ghost b/c need for threads--
//--global is 1d indexed ,shared is 2d indexed.
//TODO: remove for loop from kernel and index entirely with blockIdx, blockDim, and threadIdx (check workshop 7 for indexing by shared memory within blocks)
__global__ void matrixKernel(float* a, float* b) {//MODIFY to suit algorithm
//int j= blockDim.x*blockIdx.x + threadIdx.x+1;//TODO: CHECK THIS DOESN'T MESS UP GLOBAL EXECUTION
int j = threadIdx.y;
int i = blockDim.x*blockIdx.x + threadIdx.x;
//int i = threadIdx.y + 1;//original code has k = 1 and <=total_iters--since k will now start at 0, set end at < total_iters
//above: we are using block and thread indexes to replace some of the iteration logic
int tj = threadIdx.y;
int ti = threadIdx.x;
int tij = threadIdx.x + ntpbXY*threadIdx.y;
 
int ij = i + d_m*j;
 
//GLOBAL MEMORY VERSION (COMMENT OUT SHARED SECTION BELOW TO RUN):==================================
// if (!(blockIdx.x == 0 && threadIdx.x == 0 || blockIdx.x == (d_nBlocks - 1) && threadIdx.x == (d_ntpbXY - 1)) && threadIdx.y != 0 && threadIdx.y != (d_ntpbXY - 1)) {
// float x = d_xmin + i*d_dx, y = d_ymin + j*d_dy;
// float input = abs(x) > 0.5 || abs(y) > 0.5 ? 0 : 1;
// a[ij] = (input + d_dxxinv*(b[ij - 1] + b[ij + 1])
// + d_dyyinv*(b[ij - d_m] + b[ij + d_m]))*d_dcent;
// }
 
 
//SHARED MEMORY SETUP (COMMENT OUT FOR GLOBAL VERSION)
__shared__ float bShared[ntpbXY+2][ntpbXY];
//NOTES ON SHARED INDEX OFFSET:
//x offset is -1, so to get the current index for the thread for global, it is bShared[ti+i][tj]
//-to get global x index -1 is bShared[ti][tj]
//-to get global x index is bShared[ti+1][tj]
//-to get global x index +1 is bShared[ti+2][tj]
 
//set left ghost cells
if (threadIdx.x == 0 && blockIdx.x != 0)
bShared[ti][tj] = b[ij - 1];
 
//set right ghost cells
if (threadIdx.x == ntpbXY - 1 && blockIdx.x != d_nBlocks - 1)
bShared[ti+2][tj] = b[ij+1];
 
//set ghost cell for current thread relative to global memory
bShared[ti+1][tj] = b[d_m* j + i];
 
__syncthreads();
 
//SHARED MEMORY VERSION:==========
if (!(blockIdx.x == 0 && threadIdx.x == 0 || blockIdx.x == (d_nBlocks - 1) && threadIdx.x == (d_ntpbXY - 1)) && threadIdx.y != 0 && threadIdx.y != (d_ntpbXY - 1)) {
float x = d_xmin + i*d_dx, y = d_ymin + j*d_dy;
float input = abs(x) > 0.5 || abs(y) > 0.5 ? 0 : 1;
a[d_m* j + i] = (input + d_dxxinv*(bShared[ti][tj] + bShared[ti+2][tj])//TODO: does the program logic allow for this to go out of range??
+ d_dyyinv*(bShared[ti+1][tj-1] + bShared[ti+1][tj+1]))*d_dcent;
__syncthreads();
}
}
</pre>
<source>
// Set grid size and number of iterations
const int save_iters = 20;
const int total_iters = 5000;
const int error_every = 2;
//HERE:
const int m = 32, n =32 ;
const float xmin = -1, xmax = 1;
const float ymin = -1, ymax = 1;
// Compute useful constants
const float pi = 3.1415926535897932384626433832795;
const float omega = 2 / (1 + sin(2 * pi / n));
const float dx = (xmax - xmin) / (m - 1);//TODO: modify to fit kernel?
const float dy = (ymax - ymin) / (n - 1);//TODO: modify to fit kernel?
const float dxxinv = 1 / (dx*dx);
const float dyyinv = 1 / (dy*dy);
const float dcent = 1 / (2 * (dxxinv + dyyinv));
// Input function
inline float f(int i, int j) {
float x = xmin + i*dx, y = ymin + j*dy;
return abs(x) > 0.5 || abs(y) > 0.5 ? 0 : 1;
}
// Common output and error routine
void outputImage(char* filename, float *a) {
// Computes the error if sn%error every==0
// Saves the matrix if sn<=save iters
int i, j, ij = 0, ds = sizeof(float);
float x, y, data_float; const char *pfloat;
pfloat = (const char*)&data_float;
ofstream outfile;
static char fname[256];
sprintf(fname, "%s.%d", filename, 101);
outfile.open(fname, fstream::out
| fstream::trunc | fstream::binary);
data_float = m; outfile.write(pfloat, ds);
for (i = 0; i < m; i++) {
x = xmin + i*dx;
data_float = x; outfile.write(pfloat, ds);
}
for (j = 0; j < n; j++) {
y = ymin + j*dy;
data_float = y;
outfile.write(pfloat, ds);
for (i = 0; i < m; i++) {
data_float = a[ij++];
outfile.write(pfloat, ds);
}
}
outfile.close();
}
void dojacobi() {
int i, j, ij, k;
float error, z;
float *a, *b;
float *u;
float *v;
u = new float[m*n];
v = new float[m*n];
// Set initial guess to be identically zero
for (ij = 0; ij < m*n; ij++) u[ij] = v[ij] = 0;
a = v; b = u;
float* d_a;
float* d_b;
int nBlocks = ((n*m + ntpb - 1) / ntpb);
//malloc
cudaMalloc((void**)&d_a, m*n * sizeof(float));
cudaMalloc((void**)&d_b, m*n * sizeof(float));
cudaMemcpy(d_a, a, n* m * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_b, b, n* m * sizeof(float), cudaMemcpyHostToDevice);
dim3 dGrid(nBlocks, 1);//1D grid of blocks (means we don't have to ghost 1st and last rows of matrices w/i a block
dim3 dBlock(32, 32);
cudaMemcpyToSymbol(d_nBlocks, &nBlocks, sizeof(int));
cudaMemcpyToSymbol(d_ntpbXY, &ntpbXY, sizeof(int));
// Carry out Jacobi iterations
for (k = 1; k <= total_iters; k++) {
if (k % 2 == 0) {
cudaError_t error = cudaGetLastError();
//RUN KERNEL:
matrixKernel << <dGrid, dBlock >> > (d_a, d_b);
cudaDeviceSynchronize();
check(cudaGetLastError());
}
else {
cudaError_t error = cudaGetLastError();
matrixKernel << <dGrid, dBlock >> > (d_b, d_a);
cudaDeviceSynchronize();
if (cudaGetLastError()) {
std::cout << "error";
}
}
}
cudaMemcpy(a, d_a, n* m * sizeof(float), cudaMemcpyDeviceToHost);
outputImage("jacobi out", a);
cudaFree(d_a);
cudaFree(d_b);
delete[] u;
delete[] v;
}
int main() {
cudaError_t cuerr;
cuerr = cudaMemcpyToSymbol(d_m, &m, sizeof(int));
if (cudaGetLastError()) {
std::cout << cudaGetErrorString(cuerr) << std::endl;
}
</source>
<pre style="color: blue">
cudaMemcpyToSymbol(d_n, &n, sizeof(int));
cudaMemcpyToSymbol(d_xmin, &xmin, sizeof(float));
cudaMemcpyToSymbol(d_xmax, &xmax, sizeof(float));
cudaMemcpyToSymbol(d_ymin, &ymin, sizeof(float));
cudaMemcpyToSymbol(d_ymax, &ymax, sizeof(float));
cudaMemcpyToSymbol(d_pi, &pi, sizeof(float));
cudaMemcpyToSymbol(d_omega, &pi, sizeof(float));
cudaMemcpyToSymbol(d_dx, &dx, sizeof(float));
cudaMemcpyToSymbol(d_dy, &dy, sizeof(float));
</pre>
<source>
cuerr = cudaMemcpyToSymbol(d_dxxinv, &dxxinv, sizeof(float));
if (cudaGetLastError()) {
std::cout << "error" << std::endl;
std::cout << cudaGetErrorString(cuerr) << std::endl;
}
cudaMemcpyToSymbol(d_dyyinv, &dyyinv, sizeof(float));
cuerr = cudaMemcpyToSymbol(d_dcent, &dcent, sizeof(float));
if (cudaGetLastError()) {
//std::cout << "error";
std::cout << cudaGetErrorString(cuerr) << std::endl;
}
std::chrono::steady_clock::time_point ts, te;
ts = std::chrono::steady_clock::now();
dojacobi();
te = std::chrono::steady_clock::now();
std::chrono::steady_clock::duration duration = te - ts;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
std::cout << "Parallel Code Time: " << ms.count() << " ms" << std::endl;
cudaDeviceReset();
return 0;
}
</source>
 
<nowiki>****************</nowiki>
 
A NOTE ON SCALABILITY:
 
In our attempts to make the kernel scalable with ghost cells, we scaled along one dimension. However, we were inconsistent in our scaling. The 1D kernel scaled along the n (y) dimension while the 2d kernels scaled along the m (x) dimension. Scaling along the x dimension, while allowing results to be testable between serial and 2D parallelized versions of the code, produced distributions that were strangely banded and skewed. In other words, we made the code render weird things faster:
 
[[File:MDimensionScale.png]]
 
FINAL TIMINGS <pre style="color: red"> THE GRAPH IMMEDIATELY BELOW IS INCORRECT: there was an error recording the 1D runtimes for assignment 2</pre>
 
<nowiki>****************</nowiki>
 
[[File:dps915_gpusquad_a3chart.png]]
 
<nowiki>****************</nowiki>
 
PROPER TIMINGS:
 
[[File:Code_timings2.png]]
 
Blue = Serial (A1)
Orange = Parallel (A2)
Grey = Optimized Global (A3)
Yellow = Optimized Shared (A3)
 
The above graph includes the total run times for the serial code, the 1D kernel from assignment 2, a kernel with global and constant memory with a 2D thread arrangement, and the same 2D arrangement but with shared memory utilizing ghost cells.
 
We found that the most efficient version of the code was the 2d version that used constant memory and did not use shared memory. Because the shared memory version of the kernel required synchronization of threads to allocate shared memory every time a kernel was run, and a kernel was run 5000 times for each version of our code, this increased overhead for memory setup actually made the execution slower than the version with global memory.
 
We found that the most efficient version of the code was the 2d version that used constant memory and did not use shared memory. Because the shared memory version of the kernel required synchronization of threads to allocate shared memory every time a kernel was run, and a kernel was run 5000 times for each version of our code, the if statements required to set up the ghost cells for shared memory may have created a certain amount of warp divergence, thus slowing down the runtimes of each individual kernel.
 
Below, are two images that show 4 consecutive kernel runs for both global and shared versions of the code. It is apparent that shared kernel runs actually take more time than the global memory versions.
 
 
TIMES FOR THE GLOBAL KERNEL
[[File:kernelGlobalTimes.png]]
 
 
TIMES FOR THE SHARED KERNEL
 
[[File:sharedKernelTimes.png]]
 
Note how the run times for each kernel with shared memory are significantly longer than those with global.
 
To try to determine if this issue was one of warp divergence, we tried to time a kernel with global memory that also initialized shared memory, although referenced global memory when carrying out the actual calculations:
 
[[File:GlobalInitSharedKernelTimes.png]]
 
The run of a kernel that allocated shared memory using a series of if statements, but executed instructions using global memory is shown in the figure above. While slightly longer than the run with global memory where shared memory is not initialized for ghost cells, it still takes less time to run than the version with Global memory. It is likely that Our group's attempts to employ shared memory failed because we did not adequately schedule or partition the shared memory, and the kernel was slowed as a result. The supposed occupancy of a block of shared memory was 34x32 (the dimensions of the shared memory matrix) x 4 (the size of a float) which equals 4,352 bytes per block, which is supposedly less than the maximum of about 49KB stated for a device with a 5.0 compute capability (which this series of tests on individual kernel run times was performed on). With this is mind it is still unclear as to why the shared memory performed more poorly that the global memory implementation.
 
Unfortunately our group's inability to effectively use profiling tools has left this discrepancy as a mystery.
 
In conclusion, while it may be possible to parallelize the algorithm we chose well, the effort to do so would involve ensuring that shared memory is properly synchronized in two block dimensions (2 dimensions of ghost cells rather than the 1 we implemented), and to ensure that shared memory is allocated appropriately such that maximum occupancy is established within the GPU. Unfortunately, our attempts fell short, and while implementing constant memory seemed to speed up the kernel a bit, our solution was not fully scalable in both dimensions, and shared memory was not implemented in a way that improved kernel efficiency.
93
edits

Navigation menu