PPMP_char3

news2024/10/6 20:38:26

PMPP char3 – Multidimensional grids and data

​ 五一过后,有些工作要赶,抽出时间更新一下。这一章基本都熟练掌握,在做习题过程中有一些思考。这里涉及到了一点点GEMM(矩阵乘),GEMM有太多可深挖的了,推荐一篇博客How to Optimize a CUDA Matmul Kernel for cuBLAS-like Performance: a Worklog (siboehm.com)。另外,我还发现上一篇博客,有写错的地方,这篇博客的末尾做了一下勘误。这里记录我的个人理解,有不正确的地方,欢迎留言或者私信讨论。

课后习题

  1. In this chapter we implemented a matrix multiplication kernel that has each
    thread produce one output matrix element. In this question, you will
    implement different matrix-matrix multiplication kernels and compare them.
    a. Write a kernel that has each thread produce one output matrix row. Fill in
    the execution configuration parameters for the design.
    b. Write a kernel that has each thread produce one output matrix column. Fill
    in the execution configuration parameters for the design.
    c. Analyze the pros and cons of each of the two kernel designs.

答案:

a 部分 (来自大模型)

__global__ void matrixMulRow(float *A, float *B, float *C, int m, int n, int k) {
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    if (row < m) {
        for (int col = 0; col < k; ++col) {
            float sum = 0;
            for (int i = 0; i < n; ++i) {
                sum += A[row * n + i] * B[i * k + col];
            }
            C[row * k + col] = sum;
        }
    }
}
dim3 threadsPerBlock(1, 256);
dim3 blocksPerGrid(1, (m + threadsPerBlock.y - 1) / threadsPerBlock.y);
matrixMulRow<<<blocksPerGrid, threadsPerBlock>>>(A, B, C, m, n, k);

b部分 (来自大模型)

__global__ void matrixMulCol(float *A, float *B, float *C, int m, int n, int k) {
    int col = blockIdx.x * blockDim.x + threadIdx.x;
    if (col < k) {
        for (int row = 0; row < m; ++row) {
            float sum = 0;
            for (int i = 0; i < n; ++i) {
                sum += A[row * n + i] * B[i * k + col];
            }
            C[row * k + col] = sum;
        }
    }
}
dim3 threadsPerBlock(256, 1);
dim3 blocksPerGrid((k + threadsPerBlock.x - 1) / threadsPerBlock.x, 1);
matrixMulCol<<<blocksPerGrid, threadsPerBlock>>>(A, B, C, m, n, k);

c部分

假设A、B、C都是行主序;这里也不使用共享内存。一次读入一个缓存行,访问一行数据的话,存在访存局部性,需要用到的数据就在缓存中;访问一列数据的话,不存在访存局部性,需要用到的数据就不在缓存中,需要再读一个缓存行。假设一个缓存行时64B,对应16个float32。

访问A访问B访问C
一个线程处理C中的一行连续访问,只访问一行。访存次数=K/16不连续访问,一次访问一列,访存次数=K;总共要访问N列,访问次数=N*K连续访问,只访问一行。访存次数=K/16
一个线程处理C中的一列不连续访问,只访问一列。访存次数=M不连续访问,一次访问一列,访存次数=K;总共要访问N列,访问次数=N*K不连续访问,只访问一列。访存次数=M

如果访存数据量较小,也就是a那种,可以直接放到寄存器中,这样访存cycle更短。

如果访存数据量较大,reg的容量就不够用,需要一部分存到L1上面,甚至L1也装不下,要从global里读取。涉及多个存储数据一致性、data hazard的问题,效率就很低。

  1. A matrix-vector multiplication takes an input matrix B and a vector C and
    produces one output vector A. Each element of the output vector A is the dot
    product of one row of the input matrix B and C, that is, A[i] = ΣB[i][j] * C[j].
    For simplicity we will handle only square matrices whose elements are single-
    precision floating-point numbers. Write a matrix-vector multiplication kernel and
    the host stub function that can be called with four parameters: pointer to the output
    matrix, pointer to the input matrix, pointer to the input vector, and the number of
    elements in each dimension. Use one thread to calculate an output vector element.

答案:

​ 其实,这道题就是参考gemm,实现gemv。就是把输出C的一个变量(C[i])映射到一个线程上,这个线程遍历j个变量,再各自点乘+求和(也就是j维度上做规约)。

​ 以下是大模型写出来的程序,我看了下没啥问题,测试了下也是ok的。输入为A和B,输出为C。

#include <iostream>
#include <vector>
#include <random>
#include <cuda_runtime.h>

#define CHECK(call) \
{ \
    const cudaError_t error = call; \
    if (error != cudaSuccess) { \
        std::cout << "Error: " << __FILE__ << ":" << __LINE__ << ", " << cudaGetErrorString(error) << std::endl; \
        exit(1); \
    } \
}

__global__ void matrixVectorMultiply(const float* A, const float* B, float* C, int rows, int cols) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < rows) {
        float sum = 0.0f;
        for (int j = 0; j < cols; ++j) {
            sum += A[j] * B[i * cols + j];
        }
        C[i] = sum;
    }
}

int main() {
    int rows = 1024;
    int cols = 768;

    std::vector<float> hostA(cols);
    std::vector<float> hostB(rows * cols);
    std::vector<float> hostC(rows);
    std::vector<float> resultC(rows);

    // 初始化输入数据
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<float> dis(-1.0, 1.0);

    for (int j = 0; j < cols; ++j) {
        hostA[j] = dis(gen);
    }

    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            hostB[i * cols + j] = dis(gen);
        }
    }

    // 分配设备内存
    float* deviceA;
    float* deviceB;
    float* deviceC;
    CHECK(cudaMalloc(&deviceA, cols * sizeof(float)));
    CHECK(cudaMalloc(&deviceB, rows * cols * sizeof(float)));
    CHECK(cudaMalloc(&deviceC, rows * sizeof(float)));

    // 将输入数据从主机复制到设备
    CHECK(cudaMemcpy(deviceA, hostA.data(), cols * sizeof(float), cudaMemcpyHostToDevice));
    CHECK(cudaMemcpy(deviceB, hostB.data(), rows * cols * sizeof(float), cudaMemcpyHostToDevice));

    // 启动内核
    int threadsPerBlock = 256;
    int blocksPerGrid = (rows + threadsPerBlock - 1) / threadsPerBlock;
    matrixVectorMultiply<<<blocksPerGrid, threadsPerBlock>>>(deviceA, deviceB, deviceC, rows, cols);
    CHECK(cudaGetLastError());

    // 将输出数据从设备复制到主机
    CHECK(cudaMemcpy(hostC.data(), deviceC, rows * sizeof(float), cudaMemcpyDeviceToHost));

    // 验证结果正确性
    for (int i = 0; i < rows; ++i) {
        float sum = 0.0f;
        for (int j = 0; j < cols; ++j) {
            sum += hostA[j] * hostB[i * cols + j];
        }
        resultC[i] = sum;
    }

    for (int i = 0; i < rows; ++i) {
        if (std::abs(hostC[i] - resultC[i]) > 1e-5) {
            std::cout << "Result verification failed at index " << i << std::endl;
            return 1;
        }
    }

    std::cout << "Result verification passed" << std::endl;

    // 释放设备内存
    CHECK(cudaFree(deviceA));
    CHECK(cudaFree(deviceB));
    CHECK(cudaFree(deviceC));

    return 0;
}
  1. Consider the following CUDA kernel and the corresponding host function that
    calls it:

a. What is the number of threads per block?
b. What is the number of threads in the grid?

c. What is the number of blocks in the grid?
d. What is the number of threads that execute the code on line 05?

在这里插入图片描述

答案:a、16*32=512;b、48640;c、95;d、45000

  1. Consider a 2D matrix with a width of 400 and a height of 500. The matrix is
    stored as a one-dimensional array. Specify the array index of the matrix
    element at row 20 and column 10:
    a. If the matrix is stored in row-major order.
    b. If the matrix is stored in column-major order.

答案:a、20*400+10=8010

​ b、10*500+20=5020

  1. Consider a 3D tensor with a width of 400, a height of 500, and a depth of 300

    The tensor is stored as a one-dimensional array in row-major order.
    Specify the array index of the tensor element at x 5 10, y 5 20, and z 5 5.

答案: 5 * (400 * 500) + 10 * 400 + 5 = 1004005

勘误

在这里插入图片描述

​ 上一篇博客中,这个图里面的d_a的类型写错了,应该是int* d_a,而不是void* d_a。传入函数的是(void**)&d_a,函数结束后,d_a还是int*类型。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1669035.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Ubuntu24 文件目录结构——用户——权限 详解

目录 权限 用户 文件目录结构 一个目录可以有程序&#xff0c;目录&#xff0c;文件&#xff0c;以及这三者的链接。可以看到还分别有使用者和权限信息。 每个文件和目录都有与之关联的三个主要属性&#xff1a;所有者&#xff08;owner&#xff09;、组&#xff08;group&a…

【ESP32接入ATK-MO1218 GPS模块】

【ESP32接入ATK-MO1218 GPS模块】 1. 引言2. ATK-MO1218 GPS模块概述3. 接入ATK-MO1218 GPS模块的步骤4. 示例代码5. 结论1. 引言 在现代的嵌入式系统和物联网项目中,精确的位置信息是至关重要的。ATK-MO1218 GPS模块作为一款高性能的GPS/北斗双模定位模块,为开发者提供了强…

【Qt 学习笔记】Qt常用控件 | 容器类控件 | Tab Widget的使用及说明

博客主页&#xff1a;Duck Bro 博客主页系列专栏&#xff1a;Qt 专栏关注博主&#xff0c;后期持续更新系列文章如果有错误感谢请大家批评指出&#xff0c;及时修改感谢大家点赞&#x1f44d;收藏⭐评论✍ Qt常用控件 | 容器类控件 | Tab Widget的使用及说明 文章编号&#xf…

实现红黑树

目录 红黑树的概念 红黑树的节点结构定义 红黑树的插入 红黑树的验证 实现红黑树完整代码 红黑树的概念 红黑树 &#xff0c;是一种 二叉搜索树 &#xff0c;但 在每个结点上增加一个存储位表示结点的颜色&#xff0c;可以是 Red 或 Black 。 通过对 任何一条从根到叶子的…

You Only Cache Once:YOCO 基于Decoder-Decoder 的一个新的大语言模型架构

这是微软再5月刚刚发布的一篇论文提出了一种解码器-解码器架构YOCO&#xff0c;因为只缓存一次KV对&#xff0c;所以可以大量的节省内存。 以前的模型都是通过缓存先前计算的键/值向量&#xff0c;可以在当前生成步骤中重用它们。键值(KV)缓存避免了对每个词元再次编码的过程&…

基于SSM的“网约车用户服务平台”的设计与实现(源码+数据库+文档)

基于SSM的“网约车用户服务平台”的设计与实现&#xff08;源码数据库文档) 开发语言&#xff1a;Java 数据库&#xff1a;MySQL 技术&#xff1a;SSM 工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统展示 系统功能 首页 站内新闻浏览 打车信息查询功能 在线打车功能…

Linux 服务器配置共享文件夹(NFS)

一、准备三台 linux 服务器 三台服务器: manger:172.16.11.178 ap1:172.16.11.179 ap2:172.16.11.180 /root/serverfiles/ 为共享目录 二、配置步骤 1、在服务端01的机器上安装nfs和rpcbind程序 yum -y install nfs* yum -y install rpcbind* 2、在安装完nfs以及rpcb…

MySQL查询篇-聚合函数-窗口函数

文章目录 distinct 关键字聚合函数常见的聚合函数group by和having 分组过滤 窗口函数with as窗口聚合函数排名窗口函数值窗口函数 distinct 关键字 distinct 去重数据&#xff0c;ps:null值也会查出来 select distinct column from table;聚合函数 常见的聚合函数 select …

【保姆级教程】VMware Workstation Pro的虚拟机导入vritualbox详细教程

解决方案 1、OVF格式2、VMX格式 1、OVF格式 选定需要导出的虚拟机&#xff08;关闭或者挂起状态下&#xff09;依次选择文件-导出为ovf 在Vritualbox导入刚刚导出的.ovf文件 更改路径&#xff0c;按实际需要修改 成功导入 2、VMX格式 如果在VMware Workstation Pro导出的…

rs6(vmp)瑞某,药某局,商某局,专某局,维某网,cookie + 后缀 的分析解析

文章目录 说在前面rs vmp 特征 介绍解决方法算法补环境运行报错 代码联调补环境框架 补环境导出结果导出cookie导出后缀 效果展示 vx lyj_txd qq 1416279170 # 加我备注来意说在前面 免责声明&#xff1a; 本篇文章只做学习讨论&#xff0c;无商务用途&#xff0c; 未对目标…

APP反抓包 - 服务端证书验证

案例引入: app:泡泡聊天 版本:v1.7.4 发送登录请求,抓包发现提示:403 Forbidden 这里就是使用了服务端证书校验,因为charles没有安装证书,所以到达服务器的响应没有通过验证,返回异常。 美之图: 一,校验逻辑 在安卓开发时,在客户端预设证书(p12/bks),客户端…

C++基础与深度解析 | C++初探 | Hello World | 系统I/O | 控制流 | 结构体与自定义数据类型

文章目录 一、从Hello World谈起二、系统I/O三、控制流四、结构体与自定义数据类型 一、从Hello World谈起 #include <iostream>void fun(const char *pInfo) {std::cout << pInfo << std::endl; }int main() {fun("Hello World!");fun("Hel…

从 Oracle 到 TiDB,国有大行打造本地生活 APP 新体验

导读 本文介绍了某国有大行推出的本地生活服务类 APP 在数字时代的创新应用实践。该 APP 利用金融科技和互联网平台模式&#xff0c;打造“金融非金融”的线上生态服务平台&#xff0c;满足了用户多样化的生活需求。为应对用户增长和数据量增加带来的挑战&#xff0c;该 APP 决…

【网络编程】Servlet的前后端练习 | 表白墙 | 前后端交互 | 提交消息 | 获取消息

文章目录 一、Servlet的前后端练习1.表白墙服务器要实现的逻辑&#xff1a;1.获取消息 &#xff1a;2.提交消息&#xff1a;完整前端代码&#xff1a;完整后端代码&#xff1a; 一、Servlet的前后端练习 1.表白墙 服务器要实现的逻辑&#xff1a; 1.页面加载时&#xff0c;网…

47-Qt控件详解:Buttons Containers1

一 QPushButton (命令按钮) #ifndef MAINWINDOW_H #define MAINWINDOW_H#include <QMainWindow> #include <QPushButton>//引入QPushButton类对应的头文件class MainWindow : public QMainWindow {Q_OBJECTpublic:MainWindow(QWidget *parent nullptr);~MainWind…

YOLOv8独家原创改进: AKConv(可改变核卷积)

1.AKConv原理介绍 地址:2311.11587 (arxiv.org) 摘要:基于卷积运算的神经网络在深度学习领域取得了令人瞩目的成果,但标准卷积运算存在两个固有的缺陷。一方面,卷积运算仅限于局部窗口,无法捕获其他位置的信息, 并且它的采样形状是固定的。 另一方面,卷积核的大小固定为…

vue3土味情话pinia可以持久保存再次修改App样式

我是不是你最疼爱的人-失去爱的城市 <template><div class"talk"><button click"getLoveTalk">土味情话</button><ul><li v-for"talk in talkStore.talkList" :key"talk.id">{{ talk.title }}<…

HarmonyOS开发案例:【UIAbility内和UIAbility间页面的跳转】

UIAbility内和UIAbility间页面的跳转&#xff08;ArkTS&#xff09; 介绍 基于Stage模型下的UIAbility开发&#xff0c;实现UIAbility内和UIAbility间页面的跳转。包含如下功能&#xff1a; UIAbility内页面的跳转。跳转到指定UIAbility的首页。跳转到指定UIAbility的指定页…

AtCoder Regular Contest 177 D. Earthquakes(概率 单调栈)

题目 D - Earthquakes 思路来源 官方题解 题解 对于不存在连锁反应的区间&#xff0c;每个区间独立处理&#xff0c;最后求个乘积 对于每个区间&#xff0c;相邻的两个杆子距离都小于H&#xff0c; 意味着没倒的区间是个连续的区间&#xff0c;假设要算i的概率 一定是第i…

软考144-下午题-【试题三】:UML图-类图、用例图

一、分值与目标 题型&#xff1a; 问题一~问题三&#xff08;扩展/UML——>设计模式&#xff09; 二、UML基础知识回顾 2-1、关系 UML中有四种关系&#xff1a;依赖、关联、泛化、实现。 1、关联 关联是一种结构关系&#xff0c;它描述了一组链&#xff0c;链是对象之间的…