DCU异构程序--矩阵乘

embedded/2025/1/16 12:14:15/

目录

一、概述

二、程序实现

三、编译运行


一、概述

        HIP属于显式编程模型,需要在程序中明确写出并行控制语句,包括数据传输、核函数启动等。核函数是运行在DCU上的函数,在CPU端运行的部分称为主机端(主要是执行管理和启动),DCU端运行的部分称为设备端(用于执行计算)。大概的流程如下图:

HIP程序流程

        ①主机端将需要并行计算的数据通过hipMemcpy()传递给DCU(将CPU存储的内容传递给DCU的显存);

        ②调用核函数启动函数hipLaunchKernelGGL()启动DCU,开始执行计算;

        ③设备端将计算好的结果数据通过hipMemcpy()从DCU复制回CPU。

        hipMemcpy()是阻塞式的,数据复制完成后才可以执行后续的程序;hipLanuchKernelGGL()是非阻塞式的,执行完后程序继续向后执行,但是在Kernel没有计算完成之前,最后一个hipMemcpy()是不会开始的,这是由于HIP的Stream机制。

二、程序实现

        下面是对矩阵乘的具体实现,MatrixMul.cpp:

#include <stdio.h>
#include <assert.h>
#include "hip/hip_runtime.h"
#include "helper_functions.h"
#include "helper_hip.h"template <int BLOCK_SIZE> __global__ void MatrixMulCUDA(float *C, float *A, float *B, int wA, int wB)
{int bx = blockIdx.x;int by = blockIdx.y;int tx = threadIdx.x;int ty = threadIdx.y;int aBegin = wA * BLOCK_SIZE * by;int aEnd   = aBegin + wA - 1;int aStep  = BLOCK_SIZE;int bBegin = BLOCK_SIZE * bx;int bStep  = BLOCK_SIZE * wB;float Csub = 0;for(int a = aBegin, b = bBegin; a <= aEnd; a += aStep, b += bStep){__shared__ float As[BLOCK_SIZE][BLOCK_SIZE];__shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];As[ty][tx] = A[a + wA * ty + tx];Bs[ty][tx] = B[b + wB * ty + tx];__syncthreads();#pragma unrollfor(int k = 0; k < BLOCK_SIZE; ++k){Csub += As[ty][k] * Bs[k][tx];}__syncthreads();}int c = wB * BLOCK_SIZE * by + BLOCK_SIZE * bx;C[c + wB * ty + tx] = Csub;
}void ConstantInit(float *data, int size, float val)
{for(int i = 0; i < size; ++i){data[i] = val;}
}int MatrixMultiply(int argc, char **argv, int block_size, const dim3 &dimsA, const dim3 &dimsB)
{unsigned int size_A = dimsA.x * dimsA.y;unsigned int mem_size_A = sizeof(float) * size_A;float *h_A = reinterpret_cast<float *>(malloc(mem_size_A));unsigned int size_B = dimsB.x * dimsB.y;unsigned int mem_size_B = sizeof(float) * size_B;float *h_B = reinterpret_cast<float *>(malloc(mem_size_B));hipStream_t stream;const float valB = 0.01f;ConstantInit(h_A, size_A, 1.0f);ConstantInit(h_B, size_B, valB);float *d_A, *d_B, *d_C;dim3 dimsC(dimsB.x, dimsA.y, 1);unsigned int mem_size_C = dimsC.x * dimsC.y * sizeof(float);float *h_C = reinterpret_cast<float *>(malloc(mem_size_C));if(h_C == NULL){fprintf(stderr, "Failed to allocate host matrix C!\n");exit(EXIT_FAILURE);}checkHIPErrors(hipMalloc(reinterpret_cast<void **>(&d_A), mem_size_A));checkHIPErrors(hipMalloc(reinterpret_cast<void **>(&d_B), mem_size_B));checkHIPErrors(hipMalloc(reinterpret_cast<void **>(&d_C), mem_size_C));hipEvent_t start, stop;checkHIPErrors(hipEventCreate(&start));checkHIPErrors(hipEventCreate(&stop));checkHIPErrors(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking));checkHIPErrors(hipMemcpyAsync(d_A, h_A, mem_size_A, hipMemcpyHostToDevice, stream));checkHIPErrors(hipMemcpyAsync(d_B, h_B, mem_size_B, hipMemcpyHostToDevice, stream));dim3 threads(block_size, block_size);dim3 grid(dimsB.x/threads.x, dimsA.y/threads.y);printf("Computing result using CUDA Kernel...\n");if(block_size == 16){hipLaunchKernelGGL(HIP_KERNEL_NAME(MatrixMulCUDA<16>), dim3(grid), dim3(threads), 0, stream, d_C, d_A, d_B, dimsA.x, dimsB.x);}else{hipLaunchKernelGGL(HIP_KERNEL_NAME(MatrixMulCUDA<32>), dim3(grid), dim3(threads), 0, stream, d_C, d_A, d_B, dimsA.x, dimsB.x);}printf("Done\n");checkHIPErrors(hipStreamSynchronize(stream));checkHIPErrors(hipEventRecord(start, stream));int nIter = 300;for(int j = 0; j < nIter; j++){if(block_size == 16){hipLaunchKernelGGL(HIP_KERNEL_NAME(MatrixMulCUDA<16>), dim3(grid), dim3(threads), 0, stream, d_C, d_A, d_B, dimsA.x, dimsB.x);}else{hipLaunchKernelGGL(HIP_KERNEL_NAME(MatrixMulCUDA<32>), dim3(grid), dim3(threads), 0, stream, d_C, d_A, d_B, dimsA.x, dimsB.x);}}checkHIPErrors(hipEventRecord(stop, stream));checkHIPErrors(hipEventSynchronize(stop));float msecTotal = 0.0f;checkHIPErrors(hipEventElapsedTime(&msecTotal, start, stop));float msecPerMatrixMul = msecTotal/nIter;double flopsPerMatrixMul = 2.0 * static_cast<double>(dimsA.x) * static_cast<double>(dimsA.y) * static_cast<double>(dimsB.x);double gigaFlops = (flopsPerMatrixMul * 1.0e-9f) / (msecPerMatrixMul/1000.0f);printf("Performance = %.2f GFlop/s, Time = %.3f msec, Size = %.0f Ops, WorkgroupSize = %u threads/block\n", gigaFlops, msecPerMatrixMul, flopsPerMatrixMul, threads.x * threads.y);checkHIPErrors(hipMemcpyAsync(h_C, d_C, mem_size_C, hipMemcpyDeviceToHost, stream));checkHIPErrors(hipStreamSynchronize(stream));printf("Checking computed result for correctness:");bool correct = true;double eps = 1.e-6;for(int i = 0; i < static_cast<int>(dimsC.x * dimsC.y); i++){double abs_err = fabs(h_C[i] - (dimsA.x * valB));double dot_length = dimsA.x;double abs_val = fabs(h_C[i]);double rel_err = abs_err / abs_val / dot_length;if(rel_err > eps){printf("Error! Matrix[%05d] = %.8f, ref = %.8f error term is > %E\n", i, h_C[i], dimsA.x * valB, eps);correct = false;}}printf("%s\n", correct ? "Result = PASS" : "Result = FAIL");free(h_A);free(h_B);free(h_C);checkHIPErrors(hipFree(d_A));checkHIPErrors(hipFree(d_B));checkHIPErrors(hipFree(d_C));checkHIPErrors(hipEventDestroy(start));checkHIPErrors(hipEventDestroy(stop));printf("\nNOTE: The CUDA Samples are not meant for performance measurement. Results may vary when GPU Boost is enabled.\n");if(correct){return EXIT_SUCCESS;}else{return EXIT_FAILURE;}
}int main(int argc, char *argv[])
{printf("[Matrix Multiply Using CUDA] - Starting...\n");if(checkCmdLineFlag(argc, (const char **)argv, "help") || checkCmdLineFlag(argc, (const char **)argv, "?")){printf("Usage -device=n (n >= 0 for deviceID)\n");printf("      -wA=WidthA -hA=HeightA (Width x Height of Matrix A)\n");printf("      -wB=WidthB -hB=HeightB (Width x Height of Matrix B)\n");printf("  Note: Outer matrix dimensions of A & B matrices must be equal.\n");exit(EXIT_SUCCESS);}int dev = findHIPDevice(argc, (const char **)argv);int block_size = 32;dim3 dimsA(5 * 2 * block_size, 5 * 2 * block_size, 1);dim3 dimsB(5 * 4 * block_size, 5 * 2 * block_size, 1);if(checkCmdLineFlag(argc, (const char **)argv, "wA")){dimsA.x = getCmdLineArgumentInt(argc, (const char **)argv, "wA");}if(checkCmdLineFlag(argc, (const char **)argv, "hA")){dimsA.y = getCmdLineArgumentInt(argc, (const char **)argv, "hA");}if(checkCmdLineFlag(argc, (const char **)argv, "wB")){dimsB.x = getCmdLineArgumentInt(argc, (const char **)argv, "wB");}if(checkCmdLineFlag(argc, (const char **)argv, "hB")){dimsB.y = getCmdLineArgumentInt(argc, (const char **)argv, "hB");}if(dimsA.x != dimsB.y){printf("Error: outer matrix dimensions must be equal. (%d != %d) \n", dimsA.x, dimsB.y);exit(EXIT_FAILURE);}printf("Matrix A(%d, %d), Matrix B(%d, %d)\n", dimsA.x, dimsA.y, dimsB.x, dimsB.y);int matrix_result = MatrixMultiply(argc, argv, block_size, dimsA, dimsB);exit(matrix_result);
}

三、编译运行

        HIP程序采用hipcc编译

影响结果:


http://www.ppmy.cn/embedded/154389.html

相关文章

YOLOv9改进,YOLOv9自研检测头融合HAttention用于图像修复的混合注意力检测头

参考文章 完成本篇内容,首先完成这篇文章,并把代码添加到 YOLOv9 中: YOLOv9改进,YOLOv9引入HAttention注意机制用于图像修复的混合注意力转换器,CVPR2023,超分辨率重建 下文都是手把手教程,跟着操作即可添加成功 目录 参考文章🎓一、YOLOv9原始版本代码下载🍀🍀…

npx和npm区别

npx 和 npm 是 Node.js 生态中的两个工具&#xff0c;它们有不同的用途和功能&#xff1a; 1. npm&#xff08;Node Package Manager&#xff09; 主要作用&#xff1a; 包管理工具&#xff1a; 用来安装、管理、卸载 Node.js 的包&#xff08;module/library&#xff09;。提…

PyCharm与GitHub完美对接: 详细步骤指南

在现代软件开发中,版本控制系统已经成为不可或缺的工具。GitHub作为最流行的代码托管平台,与PyCharm这款强大的Python IDE的结合,可以极大地提高开发效率。本文将为您详细介绍如何在PyCharm中无缝对接GitHub,助您轻松实现代码版本管理和团队协作。 © ivwdcwso (ID: u0…

从0开始学习搭网站第二天

前言&#xff1a;今天比较惭愧&#xff0c;中午打铲吃了一把&#xff0c;看着也到钻二了&#xff0c;干脆顺手把这个赛季的大师上了&#xff0c;于是乎一直到网上才开始工作&#xff0c;同样&#xff0c;今天的学习内容大多来自mdn社区mdn 目录 怎么把文件上传到web服务器采用S…

算法3(力扣83)-删除链表中的重复元素

1、题目&#xff1a;给定一个已排序的链表的头 head &#xff0c; 删除所有重复的元素&#xff0c;使每个元素只出现一次 。返回 已排序的链表 。 2、实现&#xff08; 因为已排序&#xff0c;所以元素若重复&#xff0c;必然在其下一位&#xff09;&#xff08;这里为在vscod…

音频DSP的发展历史

音频数字信号处理&#xff08;DSP&#xff09;的发展历史是电子技术、计算机科学和音频工程共同进步的结果。这个领域的进展不仅改变了音乐制作、音频后期制作和通信的方式&#xff0c;也影响了音频设备的设计和功能。以下是对音频DSP发展历史的概述&#xff1a; 早期概念和理论…

【GRACE学习-1】JPL数据下载

网站&#xff1a;https://podaac.jpl.nasa.gov/dataset/TELLUS_GRAC-GRFO_MASCON_CRI_GRID_RL06.3_V4# 后续就是一直点-------------------------------------------------------------------------------------------------------------

R语言贝叶斯方法在生态环境领域中的高阶技术

包括回归及结构方程模型概述及数据探索&#xff1b;R和Rstudio简介及入门和作图基础&#xff1b;R语言数据清洗-tidyverse包&#xff1b;贝叶斯回归与混合效应模型&#xff1b;贝叶斯空间自相关、时间自相关及系统发育相关数据分析&#xff1b;贝叶斯非线性数据分析;贝叶斯结构…