diff --git a/C_task1_3/task1.c b/C_task1_3/task1.c new file mode 100644 index 0000000000000000000000000000000000000000..b9fbb36708d2ebf51a9d076ec1af6c3f3e866f4c --- /dev/null +++ b/C_task1_3/task1.c @@ -0,0 +1,13 @@ +#include <omp.h> +#include <stdio.h> + +int main() { + int n = 1000000; + double sum = 0.0; + +/**This segment will need to be filled by the participants.**/ + + printf("Sum: %f\n", sum); + + return 0; +} diff --git a/C_task1_3/task2.c b/C_task1_3/task2.c new file mode 100644 index 0000000000000000000000000000000000000000..c7d4357b1f577c3ed98e902ace9bf12b319191f5 --- /dev/null +++ b/C_task1_3/task2.c @@ -0,0 +1,22 @@ +#include <mpi.h> +#include <stdio.h> + +int main(int argc, char** argv) { + MPI_Init(NULL, NULL); + + int world_size; + MPI_Comm_size(MPI_COMM_WORLD, &world_size); + + int world_rank; + MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); + +/**This segment will need to be filled by the participants.**/ + //TODO: + + if (world_rank == 0) { + printf("Global sum: %f\n", global_sum); + } + + MPI_Finalize(); + return 0; +} diff --git a/C_task1_3/task3.c b/C_task1_3/task3.c new file mode 100644 index 0000000000000000000000000000000000000000..80306cf3d52a930d4ac465b9554b2dd7c2eb1385 --- /dev/null +++ b/C_task1_3/task3.c @@ -0,0 +1,25 @@ +#include <mpi.h> +#include <omp.h> +#include <stdio.h> + +int main(int argc, char** argv) { + MPI_Init(NULL, NULL); + + int world_size; + MPI_Comm_size(MPI_COMM_WORLD, &world_size); + + int world_rank; + MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); + + double global_sum = 0.0; + + /**This segment will need to be filled by the participants.**/ + // TODO: Scatter the array sum and gather it back in final_sum + + if (world_rank == 0) { + printf("Final sum: %f\n", final_sum); + } + + MPI_Finalize(); + return 0; +} diff --git a/README.md b/README.md index b65b5c6c177f2b763c0cc0a657b913d0907cff80..aef59025d5494d694856719ac40bae48e7bafdbe 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,60 @@ -# ESDE Parallel +# Escape Room HPC Parallelization Strategies +## Introduction +Welcome to the HPC Parallelization Strategies Escape Room! This repository is designed to provide hands-on experience with parallelization strategies using High-Performance Computing (HPC). You'll navigate through five tasks, each demonstrating different parallelization techniques, to ultimately solve the escape room puzzle and win the final prize. -## Getting started +## Repository Structure -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +The repository is organized as follows: -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! -## Add your files +- **task1.py to task5.py**: Python scripts for each task. +- **task1.sh to task5.sh**: Job submission scripts for each task. +- **README.md**: This file. -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +## Tasks Overview -``` -cd existing_repo -git remote add origin https://gitlab.jsc.fz-juelich.de/vasireddy1/ESDE_Parallel.git -git branch -M main -git push -uf origin main -``` +### Task 1 - Parallel Processing (Multi-threading Single Process) +**File**: `task1.py` +**Job Script**: `task1.sh` +**Description**: Demonstrates basic parallel processing using multi-threading within a single process. Part of the code is missing and needs to be filled by participants to achieve parallel execution. -## Integrate with your tools +### Task 2 - Message Passing Interface (Multi-processing) +**File**: `task2.py` +**Job Script**: `task2.sh` +**Description**: Implements message passing interface for multi-processing. Complete the code to effectively use multiple processors for parallel computation. -- [ ] [Set up project integrations](https://gitlab.jsc.fz-juelich.de/vasireddy1/ESDE_Parallel/-/settings/integrations) +### Task 3 - CUDA (GPU Memory Computation) +**File**: `task3.py` +**Job Script**: `task3.sh` +**Description**: Introduces GPU acceleration using CUDA. Participants will complete the code to utilize GPU resources for memory-intensive computations. -## Collaborate with your team +### Task 4 - CUDA Aware MPI (GPU with Multi-processing) +**File**: `task4.py` +**Job Script**: `task4.sh` +**Description**: Combines GPU acceleration with MPI for multi-processing. The task requires filling in the missing code to distribute GPU tasks across multiple nodes. -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) +### Task 5 - DDP Parallelization +**File**: `task5.py` +**Job Script**: `task5.sh` +**Description**: Focuses on Distributed Data Parallel (DDP) strategies. This task is unrelated to the first four but demonstrates another parallelization technique. Participants must complete the code to achieve parallel execution using DDP. -## Test and Deploy +## Instructions -Use the built-in continuous integration in GitLab. +1. **Clone the Repository**: + ```sh + git clone https://github.com/yourusername/escape-room-hpc.git + cd escape-room-hpc -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +2. **Navigate to Tasks**: +Each task's Python script and corresponding job script are located in the root directory. -*** +3. **Complete the Tasks**: +Open each taskX.py file and fill in the missing code. Use the corresponding jobX.sh script to submit the job and test your solution. -# Editing this README +4. **Find the Clue**: +Each task provides a part of the final clue. Combine the clues from all tasks to reveal the final goal. -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +## Final Goal +To win the final prize, you must successfully solve all tasks and combine the clues from each task to form a complete solution. The clues will guide you to the final answer which unlocks the prize. \ No newline at end of file diff --git a/task1.py b/task1.py new file mode 100644 index 0000000000000000000000000000000000000000..39fa386a33f5bb337f4fa803b459f731585f8f59 --- /dev/null +++ b/task1.py @@ -0,0 +1,23 @@ +from multiprocessing import Pool +import timeit + +def compute_sum(start, end): + sum_value = 0 + for i in range(start, end): + sum_value += i * 0.001 + return sum_value + +def main(): + n = 10000000 + num_workers = 64 + chunk_size = n // num_workers #156250 + ranges = [(i * chunk_size, (i + 1) * chunk_size) for i in range(num_workers)] + + # TODO: sum arrays with 64 worker threads HERE and return total_sum with total sum + + return total_sum + +if __name__ == "__main__": + total_sum = main() + print(f"Sum of array:{total_sum}") + print(f"Execution time:{timeit.timeit('main()', globals=globals(), number=7)/7}") diff --git a/task1.sh b/task1.sh new file mode 100644 index 0000000000000000000000000000000000000000..e142e1a6b03463b187013edcc20c07ab2bb190fc --- /dev/null +++ b/task1.sh @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=task1 # Job name +#SBATCH --partition=booster # Partition name +#SBATCH --ntasks=4 # Number of tasks (MPI ranks) +#SBATCH --cpus-per-task=64 # Number of CPU cores per task +#SBATCH --gres=gpu:4 # Number of GPUs +#SBATCH --account=deepacf # Account name +#SBATCH --output=job_output_%j.log # Output file (%j is replaced by the job ID) +#SBATCH --error=job_error_%j.log # Error file (%j is replaced by the job ID) +#SBATCH --time=00:10:00 # Time limit of 10 minutes + +# Run the task +srun -v python3 task1.py diff --git a/task2.py b/task2.py new file mode 100644 index 0000000000000000000000000000000000000000..f44f9b522cd3bff5217c395627595645b6b6fa2f --- /dev/null +++ b/task2.py @@ -0,0 +1,24 @@ +from mpi4py import MPI +import timeit + +def main(rank, size): + array_length = 10000000 + local_partial_array = array_length // size + + # TODO: sum partial arrays HERE and return total_sum with total sum + + return total_sum + +if __name__ == "__main__": + comm = MPI.COMM_WORLD + rank = comm.Get_rank() + size = comm.Get_size() + print(f"I'm {rank + 1} of {size}.") + + if rank == 0: + start_time = timeit.default_timer() + total_sum = main(rank, size) + if rank == 0: + execution_time = (timeit.default_timer() - start_time) + print(f"Sum of array: {total_sum}") + print(f"Execution time: {execution_time}") diff --git a/task2.sh b/task2.sh new file mode 100644 index 0000000000000000000000000000000000000000..d5505072d0e8a2cd6b526d634bb4bf82c00729ce --- /dev/null +++ b/task2.sh @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=task2 # Job name +#SBATCH --partition=booster # Partition name +#SBATCH --ntasks=4 # Number of tasks (MPI ranks) +#SBATCH --cpus-per-task=64 # Number of CPU cores per task +#SBATCH --gres=gpu:4 # Number of GPUs +#SBATCH --account=deepacf # Account name +#SBATCH --output=job_output_%j.log # Output file (%j is replaced by the job ID) +#SBATCH --error=job_error_%j.log # Error file (%j is replaced by the job ID) +#SBATCH --time=00:10:00 # Time limit of 10 minutes + +# Run the task +srun -v python3 task2.py diff --git a/task3.py b/task3.py new file mode 100644 index 0000000000000000000000000000000000000000..1d7035bb652ca558b49b6e7540a194fca3fd2b05 --- /dev/null +++ b/task3.py @@ -0,0 +1,48 @@ +from numba import cuda, float32 +import numpy as np +import timeit + +TPB = 1024 # Number of threads per block + +@cuda.jit +def parallel_sum(arr, result): + sdata = cuda.shared.array(shape=TPB, dtype=float32) + + tid = cuda.threadIdx.x + i = cuda.grid(1) + + if i < arr.size: + sdata[tid] = arr[i] + else: + sdata[tid] = 0.0 + + cuda.syncthreads() + + #TODO: Perform parallel reduction HERE and synchronize the result back + + + if tid == 0: + result[cuda.blockIdx.x] = sdata[0] + +def main(arr): + number_of_gpus_per_node = len(cuda.gpus) + n = arr.size + d_arr = cuda.to_device(arr) + d_result = cuda.device_array((n + TPB - 1) // TPB, dtype=np.float32) + + block = TPB + grid = (n + block - 1) // block # Ensure enough blocks to cover the array size + + parallel_sum[grid, block](d_arr, d_result) + + result = d_result.copy_to_host() + + return np.sum(result) + +if __name__ == "__main__": + arr = np.arange(10000000) + start_time = timeit.default_timer() + result = main(arr) + print(f"Sum of array: {result}") + execution_time = (timeit.default_timer() - start_time) + print(f"Execution time: {execution_time}") diff --git a/task3.sh b/task3.sh new file mode 100644 index 0000000000000000000000000000000000000000..ebae76c9be1bdba90abee3d1430e2fc82e941a48 --- /dev/null +++ b/task3.sh @@ -0,0 +1,13 @@ +#!/bin/bash +#SBATCH --job-name=task3 # Job name +#SBATCH --partition=booster # Partition name +#SBATCH --ntasks=4 # Number of tasks (MPI ranks) +#SBATCH --cpus-per-task=64 # Number of CPU cores per task +#SBATCH --gres=gpu:4 # Number of GPUs +#SBATCH --account=deepacf # Account name +#SBATCH --output=job_output_%j.log # Output file (%j is replaced by the job ID) +#SBATCH --error=job_error_%j.log # Error file (%j is replaced by the job ID) +#SBATCH --time=00:10:00 # Time limit of 10 minutes + +# Run the task +srun -v python3 task3.py diff --git a/task4.py b/task4.py new file mode 100644 index 0000000000000000000000000000000000000000..fd51b9361e7009441b220b28429b1adbafbb574a --- /dev/null +++ b/task4.py @@ -0,0 +1,83 @@ +import cupy +import mpi4py.MPI as MPI +from numba import cuda +import timeit + +TPB = 1024 + +@cuda.jit +def sum_values(v, a): + """Sum all values in v. + Parameters + ---------- + v: numpy.ndarray + One-dimensional array with values to be summed. + a: numpy.ndarray + One-element array to store the sum. + """ + # Shared memory array for partial sums + shared = cuda.shared.array(shape=TPB, dtype=cupy.float32) + + tid = cuda.threadIdx.x + i = cuda.grid(1) + + if i < v.size: + shared[tid] = v[i] + else: + shared[tid] = 0.0 + + cuda.syncthreads() + + # TODO: Perform parallel reduction in shared memory + + if tid == 0: + a[cuda.blockIdx.x] = shared[0] + +def main(): + comm = MPI.COMM_WORLD + my_rank = comm.Get_rank() + number_of_ranks = comm.Get_size() + number_of_gpus_per_node = len(cuda.gpus) + print(f"Rank {number_of_ranks} on {number_of_gpus_per_node}") + device_id = my_rank % number_of_gpus_per_node + cuda.select_device(device_id) + gpu_info = comm.gather((my_rank, device_id), root=0) + + N = 10000000 + a_partial = cupy.empty(N // number_of_ranks, dtype=cupy.float32) + partial_sum = cupy.zeros((a_partial.size + TPB - 1) // TPB, dtype=cupy.float32) + + # Set up the launch configuration for the GPU + block = TPB + grid = (a_partial.size + block - 1) // block + + # Printing GPU information from rank 0 to verify + if my_rank == 0: + for rank, gpu_id in gpu_info: + print(f"Rank {rank} is using GPU {gpu_id}") + + # Create an array with N elements on the root process + if my_rank == 0: + a = cupy.arange(N, dtype=cupy.float32) + else: + a = None + + # TODO: Use MPI to scatter the array to all processes and sum the values into total_Sum + # Hint: Use Task2 and Task3 for reference + + proc_info = comm.gather((my_rank, partial_sum,a_partial), root=0) + if my_rank == 0: + for rank_proc,psum,part in proc_info: + print(f"Rank {rank_proc}/{number_of_ranks} for array {part.size}/{a.size} partial sum {psum}") + + if my_rank == 0: + return total_sum + +if __name__ == "__main__": + start_time = timeit.default_timer() + result = main() + if result is not None: + print(f"Sum of array: {result}") + print(f"Direct sum of array: {cupy.sum(cupy.arange(10000000))}") + execution_time = (timeit.default_timer() - start_time) + print(f"Execution time: {execution_time}") diff --git a/task4.sh b/task4.sh new file mode 100644 index 0000000000000000000000000000000000000000..71b085cf9bfbe56184c8bdec35eb839c5adefd3a --- /dev/null +++ b/task4.sh @@ -0,0 +1,24 @@ +#!/bin/bash +#SBATCH --job-name=task4 # Job name +#SBATCH --partition=booster # Partition name +#SBATCH --ntasks=4 # Number of tasks (MPI ranks) +#SBATCH --cpus-per-task=64 # Number of CPU cores per task +#SBATCH --gres=gpu:4 # Number of GPUs +#SBATCH --account=deepacf # Account name +#SBATCH --output=job_output_%j.log # Output file (%j is replaced by the job ID) +#SBATCH --error=job_error_%j.log # Error file (%j is replaced by the job ID) +#SBATCH --time=00:30:00 # Time limit of 30 minutes since it is shared memory on 4 GPUs + +# Set CUDA_VISIBLE_DEVICES environment variable +export CUDA_VISIBLE_DEVICES=0,1,2,3 + +# Enable CUDA Multi-Process Service (MPS) +export CUDA_MPS_PIPE_DIRECTORY=/tmp/mps_$SLURM_JOB_ID +export CUDA_MPS_LOG_DIRECTORY=/tmp/mps_logs_$SLURM_JOB_ID +nvidia-cuda-mps-control -d + +# Run the task +srun -v --cuda-mps python3 task4.py + +# Disable CUDA MPS after the job is done +echo quit | nvidia-cuda-mps-control