[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-srush--GPU-Puzzles":3,"tool-srush--GPU-Puzzles":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",160784,2,"2026-04-19T11:32:54",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",109154,"2026-04-18T11:18:24",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[52,13,15,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":32,"last_commit_at":59,"category_tags":60,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":67,"readme_en":68,"readme_zh":69,"quickstart_zh":70,"use_case_zh":71,"hero_image_url":72,"owner_login":73,"owner_name":74,"owner_avatar_url":75,"owner_bio":76,"owner_company":77,"owner_location":78,"owner_email":79,"owner_twitter":80,"owner_website":81,"owner_url":82,"languages":83,"stars":92,"forks":93,"last_commit_at":94,"license":95,"difficulty_score":10,"env_os":96,"env_gpu":97,"env_ram":96,"env_deps":98,"category_tags":104,"github_topics":105,"view_count":32,"oss_zip_url":109,"oss_zip_packed_at":109,"status":17,"created_at":110,"updated_at":111,"faqs":112,"releases":143},9776,"srush\u002FGPU-Puzzles","GPU-Puzzles","Solve puzzles. Learn CUDA.","GPU-Puzzles 是一款专为初学者设计的交互式学习工具，旨在帮助用户轻松掌握 CUDA GPU 编程。在机器学习领域，GPU 架构至关重要，但许多从业者往往只停留在调用高层抽象库的层面，缺乏对底层并行计算原理的直观理解。GPU-Puzzles 通过“解谜”的方式解决了这一痛点：它摒弃了枯燥的理论文档，让用户直接在一个类似 Jupyter Notebook 的环境中编写代码，即时构建和测试 GPU 内核。\n\n该工具的核心亮点在于利用 Numba 库，让用户使用熟悉的 Python 语法来编写实际上等同于低级 CUDA 的代码。用户无需配置复杂的本地开发环境，只需在 Google Colab 中开启 GPU 模式即可开始挑战。从简单的向量映射（Map）到更复杂的并行操作，一系列精心设计的谜题引导用户逐步理解线程索引、内存访问等核心概念。通过完成这些练习，用户能在几小时内建立起对支撑现代深度学习算法的并行计算机制的深刻直觉。\n\nGPU-Puzzles 非常适合希望深入理解硬件加速原理的机器学习工程师、数据科学家以及计算机专业学生。对于那些已经熟练使用 PyTorch 或 TensorF","GPU-Puzzles 是一款专为初学者设计的交互式学习工具，旨在帮助用户轻松掌握 CUDA GPU 编程。在机器学习领域，GPU 架构至关重要，但许多从业者往往只停留在调用高层抽象库的层面，缺乏对底层并行计算原理的直观理解。GPU-Puzzles 通过“解谜”的方式解决了这一痛点：它摒弃了枯燥的理论文档，让用户直接在一个类似 Jupyter Notebook 的环境中编写代码，即时构建和测试 GPU 内核。\n\n该工具的核心亮点在于利用 Numba 库，让用户使用熟悉的 Python 语法来编写实际上等同于低级 CUDA 的代码。用户无需配置复杂的本地开发环境，只需在 Google Colab 中开启 GPU 模式即可开始挑战。从简单的向量映射（Map）到更复杂的并行操作，一系列精心设计的谜题引导用户逐步理解线程索引、内存访问等核心概念。通过完成这些练习，用户能在几小时内建立起对支撑现代深度学习算法的并行计算机制的深刻直觉。\n\nGPU-Puzzles 非常适合希望深入理解硬件加速原理的机器学习工程师、数据科学家以及计算机专业学生。对于那些已经熟练使用 PyTorch 或 TensorFlow 等框架，却想揭开“黑盒”面纱、探索底层性能优化之道的开发者来说，这是一个不可多得的入门阶梯。它以寓教于乐的形式，让高门槛的 GPU 编程变得触手可及。","# GPU Puzzles\n- by [Sasha Rush](http:\u002F\u002Frush-nlp.com) - [srush_nlp](https:\u002F\u002Ftwitter.com\u002Fsrush_nlp)\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_GPU-Puzzles_readme_97918d3d9435.png)\n\nGPU architectures are critical to machine learning, and seem to be\nbecoming even more important every day. However, you can be an expert\nin machine learning without ever touching GPU code. It is hard to gain\nintuition working through abstractions. \n\nThis notebook is an attempt to teach beginner GPU programming in a\ncompletely interactive fashion. Instead of providing text with\nconcepts, it throws you right into coding and building GPU\nkernels. The exercises use NUMBA which directly maps Python\ncode to CUDA kernels. It looks like Python but is basically\nidentical to writing low-level CUDA code. \nIn a few hours, I think you can go from basics to\nunderstanding the real algorithms that power 99% of deep learning\ntoday. If you do want to read the manual, it is here:\n\n[NUMBA CUDA Guide](https:\u002F\u002Fnumba.readthedocs.io\u002Fen\u002Fstable\u002Fcuda\u002Findex.html)\n\nI recommend doing these in Colab, as it is easy to get started.  Be\nsure to make your own copy, turn on GPU mode in the settings (`Runtime \u002F Change runtime type`, then set `Hardware accelerator` to `GPU`), and\nthen get to coding.\n\n[![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fsrush\u002FGPU-Puzzles\u002Fblob\u002Fmain\u002FGPU_puzzlers.ipynb)\n\n(If you are into this style of puzzle, also check out my [Tensor\nPuzzles](https:\u002F\u002Fgithub.com\u002Fsrush\u002FTensor-Puzzles) for PyTorch.)\n\n[Walkthrough Guide](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=K4T-YwsOxrM)\n\n\n```python\n!pip install -qqq git+https:\u002F\u002Fgithub.com\u002Fdanoneata\u002Fchalk@srush-patch-1\n!wget -q https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fraw\u002Fmain\u002Frobot.png https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fraw\u002Fmain\u002Flib.py\n```\n\n\n```python\nimport numba\nimport numpy as np\nimport warnings\nfrom lib import CudaProblem, Coord\n```\n\n\n```python\nwarnings.filterwarnings(\n    action=\"ignore\", category=numba.NumbaPerformanceWarning, module=\"numba\"\n)\n```\n\n## Puzzle 1: Map\n\nImplement a \"kernel\" (GPU function) that adds 10 to each position of vector `a`\nand stores it in vector `out`.  You have 1 thread per position.\n\n**Warning** This code looks like Python but it is really CUDA! You cannot use\nstandard python tools like list comprehensions or ask for Numpy properties\nlike shape or size (if you need the size, it is given as an argument).\nThe puzzles only require doing simple operations, basically\n+, *, simple array indexing, for loops, and if statements.\nYou are allowed to use local variables. \nIf you get an\nerror it is probably because you did something fancy :). \n\n*Tip: Think of the function `call` as being run 1 time for each thread.\nThe only difference is that `cuda.threadIdx.x` changes each time.*\n\n\n```python\ndef map_spec(a):\n    return a + 10\n\n\ndef map_test(cuda):\n    def call(out, a) -> None:\n        local_i = cuda.threadIdx.x\n        # FILL ME IN (roughly 1 lines)\n\n    return call\n\n\nSIZE = 4\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Map\", map_test, [a], out, threadsperblock=Coord(SIZE, 1), spec=map_spec\n)\nproblem.show()\n```\n\n    # Map\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_14_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0. 0. 0.]\n    Spec : [10 11 12 13]\n\n\n## Puzzle 2 - Zip\n\nImplement a kernel that adds together each position of `a` and `b` and stores it in `out`.\nYou have 1 thread per position.\n\n\n```python\ndef zip_spec(a, b):\n    return a + b\n\n\ndef zip_test(cuda):\n    def call(out, a, b) -> None:\n        local_i = cuda.threadIdx.x\n        # FILL ME IN (roughly 1 lines)\n\n    return call\n\n\nSIZE = 4\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\nb = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Zip\", zip_test, [a, b], out, threadsperblock=Coord(SIZE, 1), spec=zip_spec\n)\nproblem.show()\n```\n\n    # Zip\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_17_1.svg)\n    \n\n\n\n\n```python\n\n```\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0. 0. 0.]\n    Spec : [0 2 4 6]\n\n\n## Puzzle 3 - Guards\n\nImplement a kernel that adds 10 to each position of `a` and stores it in `out`.\nYou have more threads than positions.\n\n\n```python\ndef map_guard_test(cuda):\n    def call(out, a, size) -> None:\n        local_i = cuda.threadIdx.x\n        # FILL ME IN (roughly 2 lines)\n\n    return call\n\n\nSIZE = 4\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Guard\",\n    map_guard_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(8, 1),\n    spec=map_spec,\n)\nproblem.show()\n```\n\n    # Guard\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_21_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0. 0. 0.]\n    Spec : [10 11 12 13]\n\n\n## Puzzle 4 - Map 2D\n\nImplement a kernel that adds 10 to each position of `a` and stores it in `out`.\nInput `a` is 2D and square. You have more threads than positions.\n\n\n```python\ndef map_2D_test(cuda):\n    def call(out, a, size) -> None:\n        local_i = cuda.threadIdx.x\n        local_j = cuda.threadIdx.y\n        # FILL ME IN (roughly 2 lines)\n\n    return call\n\n\nSIZE = 2\nout = np.zeros((SIZE, SIZE))\na = np.arange(SIZE * SIZE).reshape((SIZE, SIZE))\nproblem = CudaProblem(\n    \"Map 2D\", map_2D_test, [a], out, [SIZE], threadsperblock=Coord(3, 3), spec=map_spec\n)\nproblem.show()\n```\n\n    # Map 2D\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_24_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [[0. 0.]\n     [0. 0.]]\n    Spec : [[10 11]\n     [12 13]]\n\n\n## Puzzle 5 - Broadcast\n\nImplement a kernel that adds `a` and `b` and stores it in `out`.\nInputs `a` and `b` are vectors. You have more threads than positions.\n\n\n```python\ndef broadcast_test(cuda):\n    def call(out, a, b, size) -> None:\n        local_i = cuda.threadIdx.x\n        local_j = cuda.threadIdx.y\n        # FILL ME IN (roughly 2 lines)\n\n    return call\n\n\nSIZE = 2\nout = np.zeros((SIZE, SIZE))\na = np.arange(SIZE).reshape(SIZE, 1)\nb = np.arange(SIZE).reshape(1, SIZE)\nproblem = CudaProblem(\n    \"Broadcast\",\n    broadcast_test,\n    [a, b],\n    out,\n    [SIZE],\n    threadsperblock=Coord(3, 3),\n    spec=zip_spec,\n)\nproblem.show()\n```\n\n    # Broadcast\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_27_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [[0. 0.]\n     [0. 0.]]\n    Spec : [[0 1]\n     [1 2]]\n\n\n## Puzzle 6 - Blocks\n\nImplement a kernel that adds 10 to each position of `a` and stores it in `out`.\nYou have fewer threads per block than the size of `a`.\n\n*Tip: A block is a group of threads. The number of threads per block is limited, but we can\nhave many different blocks. Variable `cuda.blockIdx` tells us what block we are in.*\n\n\n```python\ndef map_block_test(cuda):\n    def call(out, a, size) -> None:\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        # FILL ME IN (roughly 2 lines)\n\n    return call\n\n\nSIZE = 9\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Blocks\",\n    map_block_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(4, 1),\n    blockspergrid=Coord(3, 1),\n    spec=map_spec,\n)\nproblem.show()\n```\n\n    # Blocks\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_31_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0. 0. 0. 0. 0. 0. 0. 0.]\n    Spec : [10 11 12 13 14 15 16 17 18]\n\n\n## Puzzle 7 - Blocks 2D\n\nImplement the same kernel in 2D.  You have fewer threads per block\nthan the size of `a` in both directions.\n\n\n```python\ndef map_block2D_test(cuda):\n    def call(out, a, size) -> None:\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        # FILL ME IN (roughly 4 lines)\n\n    return call\n\n\nSIZE = 5\nout = np.zeros((SIZE, SIZE))\na = np.ones((SIZE, SIZE))\n\nproblem = CudaProblem(\n    \"Blocks 2D\",\n    map_block2D_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(3, 3),\n    blockspergrid=Coord(2, 2),\n    spec=map_spec,\n)\nproblem.show()\n```\n\n    # Blocks 2D\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_34_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [[0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]]\n    Spec : [[11. 11. 11. 11. 11.]\n     [11. 11. 11. 11. 11.]\n     [11. 11. 11. 11. 11.]\n     [11. 11. 11. 11. 11.]\n     [11. 11. 11. 11. 11.]]\n\n\n## Puzzle 8 - Shared\n\nImplement a kernel that adds 10 to each position of `a` and stores it in `out`.\nYou have fewer threads per block than the size of `a`.\n\n**Warning**: Each block can only have a *constant* amount of shared\n memory that threads in that block can read and write to. This needs\n to be a literal python constant not a variable. After writing to\n shared memory you need to call `cuda.syncthreads` to ensure that\n threads do not cross.\n\n(This example does not really need shared memory or syncthreads, but it is a demo.)\n\n\n```python\nTPB = 4\ndef shared_test(cuda):\n    def call(out, a, size) -> None:\n        shared = cuda.shared.array(TPB, numba.float32)\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n\n        if i \u003C size:\n            shared[local_i] = a[i]\n            cuda.syncthreads()\n\n        # FILL ME IN (roughly 2 lines)\n\n    return call\n\n\nSIZE = 8\nout = np.zeros(SIZE)\na = np.ones(SIZE)\nproblem = CudaProblem(\n    \"Shared\",\n    shared_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(TPB, 1),\n    blockspergrid=Coord(2, 1),\n    spec=map_spec,\n)\nproblem.show()\n```\n\n    # Shared\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             1 |             0 |             0 |             1 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_39_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0. 0. 0. 0. 0. 0. 0.]\n    Spec : [11. 11. 11. 11. 11. 11. 11. 11.]\n\n\n## Puzzle 9 - Pooling\n\nImplement a kernel that sums together the last 3 position of `a` and stores it in `out`.\nYou have 1 thread per position. You only need 1 global read and 1 global write per thread.\n\n*Tip: Remember to be careful about syncing.*\n\n\n```python\ndef pool_spec(a):\n    out = np.zeros(*a.shape)\n    for i in range(a.shape[0]):\n        out[i] = a[max(i - 2, 0) : i + 1].sum()\n    return out\n\n\nTPB = 8\ndef pool_test(cuda):\n    def call(out, a, size) -> None:\n        shared = cuda.shared.array(TPB, numba.float32)\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n        # FILL ME IN (roughly 8 lines)\n\n    return call\n\n\nSIZE = 8\nout = np.zeros(SIZE)\na = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Pooling\",\n    pool_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(TPB, 1),\n    blockspergrid=Coord(1, 1),\n    spec=pool_spec,\n)\nproblem.show()\n```\n\n    # Pooling\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_43_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0. 0. 0. 0. 0. 0. 0.]\n    Spec : [ 0.  1.  3.  6.  9. 12. 15. 18.]\n\n\n## Puzzle 10 - Dot Product\n\nImplement a kernel that computes the dot-product of `a` and `b` and stores it in `out`.\nYou have 1 thread per position. You only need 2 global reads and 1 global write per thread.\n\n*Note: For this problem you don't need to worry about number of shared reads. We will\n handle that challenge later.*\n\n\n```python\ndef dot_spec(a, b):\n    return a @ b\n\nTPB = 8\ndef dot_test(cuda):\n    def call(out, a, b, size) -> None:\n        shared = cuda.shared.array(TPB, numba.float32)\n\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n        # FILL ME IN (roughly 9 lines)\n    return call\n\n\nSIZE = 8\nout = np.zeros(1)\na = np.arange(SIZE)\nb = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Dot\",\n    dot_test,\n    [a, b],\n    out,\n    [SIZE],\n    threadsperblock=Coord(SIZE, 1),\n    blockspergrid=Coord(1, 1),\n    spec=dot_spec,\n)\nproblem.show()\n```\n\n    # Dot\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_47_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0.]\n    Spec : 140\n\n\n## Puzzle 11 - 1D Convolution\n\nImplement a kernel that computes a 1D convolution between `a` and `b` and stores it in `out`.\nYou need to handle the general case. You only need 2 global reads and 1 global write per thread.\n\n\n```python\ndef conv_spec(a, b):\n    out = np.zeros(*a.shape)\n    len = b.shape[0]\n    for i in range(a.shape[0]):\n        out[i] = sum([a[i + j] * b[j] for j in range(len) if i + j \u003C a.shape[0]])\n    return out\n\n\nMAX_CONV = 4\nTPB = 8\nTPB_MAX_CONV = TPB + MAX_CONV\ndef conv_test(cuda):\n    def call(out, a, b, a_size, b_size) -> None:\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n\n        # FILL ME IN (roughly 17 lines)\n\n    return call\n\n\n# Test 1\n\nSIZE = 6\nCONV = 3\nout = np.zeros(SIZE)\na = np.arange(SIZE)\nb = np.arange(CONV)\nproblem = CudaProblem(\n    \"1D Conv (Simple)\",\n    conv_test,\n    [a, b],\n    out,\n    [SIZE, CONV],\n    Coord(1, 1),\n    Coord(TPB, 1),\n    spec=conv_spec,\n)\nproblem.show()\n```\n\n    # 1D Conv (Simple)\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_50_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0. 0. 0. 0. 0.]\n    Spec : [ 5.  8. 11. 14.  5.  0.]\n\n\nTest 2\n\n\n```python\nout = np.zeros(15)\na = np.arange(15)\nb = np.arange(4)\nproblem = CudaProblem(\n    \"1D Conv (Full)\",\n    conv_test,\n    [a, b],\n    out,\n    [15, 4],\n    Coord(2, 1),\n    Coord(TPB, 1),\n    spec=conv_spec,\n)\nproblem.show()\n```\n\n    # 1D Conv (Full)\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_53_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n    Spec : [14. 20. 26. 32. 38. 44. 50. 56. 62. 68. 74. 80. 41. 14.  0.]\n\n\n## Puzzle 12 - Prefix Sum\n\nImplement a kernel that computes a sum over `a` and stores it in `out`.\nIf the size of `a` is greater than the block size, only store the sum of\neach block.\n\nWe will do this using the [parallel prefix sum](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FPrefix_sum) algorithm in shared memory.\nThat is, each step of the algorithm should sum together half the remaining numbers.\nFollow this diagram:\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_GPU-Puzzles_readme_5b347f99a6eb.png)\n\n\n```python\nTPB = 8\ndef sum_spec(a):\n    out = np.zeros((a.shape[0] + TPB - 1) \u002F\u002F TPB)\n    for j, i in enumerate(range(0, a.shape[-1], TPB)):\n        out[j] = a[i : i + TPB].sum()\n    return out\n\n\ndef sum_test(cuda):\n    def call(out, a, size: int) -> None:\n        cache = cuda.shared.array(TPB, numba.float32)\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n        # FILL ME IN (roughly 12 lines)\n\n    return call\n\n\n# Test 1\n\nSIZE = 8\nout = np.zeros(1)\ninp = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Sum (Simple)\",\n    sum_test,\n    [inp],\n    out,\n    [SIZE],\n    Coord(1, 1),\n    Coord(TPB, 1),\n    spec=sum_spec,\n)\nproblem.show()\n```\n\n    # Sum (Simple)\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_58_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0.]\n    Spec : [28.]\n\n\nTest 2\n\n\n```python\nSIZE = 15\nout = np.zeros(2)\ninp = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Sum (Full)\",\n    sum_test,\n    [inp],\n    out,\n    [SIZE],\n    Coord(2, 1),\n    Coord(TPB, 1),\n    spec=sum_spec,\n)\nproblem.show()\n```\n\n    # Sum (Full)\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_61_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [0. 0.]\n    Spec : [28. 77.]\n\n\n## Puzzle 13 - Axis Sum\n\nImplement a kernel that computes a sum over each column of `a` and stores it in `out`.\n\n\n```python\nTPB = 8\ndef sum_spec(a):\n    out = np.zeros((a.shape[0], (a.shape[1] + TPB - 1) \u002F\u002F TPB))\n    for j, i in enumerate(range(0, a.shape[-1], TPB)):\n        out[..., j] = a[..., i : i + TPB].sum(-1)\n    return out\n\n\ndef axis_sum_test(cuda):\n    def call(out, a, size: int) -> None:\n        cache = cuda.shared.array(TPB, numba.float32)\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n        batch = cuda.blockIdx.y\n        # FILL ME IN (roughly 12 lines)\n\n    return call\n\n\nBATCH = 4\nSIZE = 6\nout = np.zeros((BATCH, 1))\ninp = np.arange(BATCH * SIZE).reshape((BATCH, SIZE))\nproblem = CudaProblem(\n    \"Axis Sum\",\n    axis_sum_test,\n    [inp],\n    out,\n    [SIZE],\n    Coord(1, BATCH),\n    Coord(TPB, 1),\n    spec=sum_spec,\n)\nproblem.show()\n```\n\n    # Axis Sum\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_64_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [[0.]\n     [0.]\n     [0.]\n     [0.]]\n    Spec : [[ 15.]\n     [ 51.]\n     [ 87.]\n     [123.]]\n\n\n## Puzzle 14 - Matrix Multiply!\n\nImplement a kernel that multiplies square matrices `a` and `b` and\nstores the result in `out`.\n\n*Tip: The most efficient algorithm here will copy a block into\n shared memory before computing each of the individual row-column\n dot products. This is easy to do if the matrix fits in shared\n memory.  Do that case first. Then update your code to compute\n a partial dot-product and iteratively move the part you\n copied into shared memory.* You should be able to do the hard case\n in 6 global reads.\n\n\n```python\ndef matmul_spec(a, b):\n    return a @ b\n\n\nTPB = 3\ndef mm_oneblock_test(cuda):\n    def call(out, a, b, size: int) -> None:\n        a_shared = cuda.shared.array((TPB, TPB), numba.float32)\n        b_shared = cuda.shared.array((TPB, TPB), numba.float32)\n\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        j = cuda.blockIdx.y * cuda.blockDim.y + cuda.threadIdx.y\n        local_i = cuda.threadIdx.x\n        local_j = cuda.threadIdx.y\n        # FILL ME IN (roughly 14 lines)\n\n    return call\n\n# Test 1\n\nSIZE = 2\nout = np.zeros((SIZE, SIZE))\ninp1 = np.arange(SIZE * SIZE).reshape((SIZE, SIZE))\ninp2 = np.arange(SIZE * SIZE).reshape((SIZE, SIZE)).T\n\nproblem = CudaProblem(\n    \"Matmul (Simple)\",\n    mm_oneblock_test,\n    [inp1, inp2],\n    out,\n    [SIZE],\n    Coord(1, 1),\n    Coord(TPB, TPB),\n    spec=matmul_spec,\n)\nproblem.show(sparse=True)\n```\n\n    # Matmul (Simple)\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_67_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [[0. 0.]\n     [0. 0.]]\n    Spec : [[ 1  3]\n     [ 3 13]]\n\n\nTest 2\n\n\n```python\nSIZE = 8\nout = np.zeros((SIZE, SIZE))\ninp1 = np.arange(SIZE * SIZE).reshape((SIZE, SIZE))\ninp2 = np.arange(SIZE * SIZE).reshape((SIZE, SIZE)).T\n\nproblem = CudaProblem(\n    \"Matmul (Full)\",\n    mm_oneblock_test,\n    [inp1, inp2],\n    out,\n    [SIZE],\n    Coord(3, 3),\n    Coord(TPB, TPB),\n    spec=matmul_spec,\n)\nproblem.show(sparse=True)\n```\n\n    # Matmul (Full)\n     \n       Score (Max Per Thread):\n       |  Global Reads | Global Writes |  Shared Reads | Shared Writes |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_70_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    Failed Tests.\n    Yours: [[0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]]\n    Spec : [[  140   364   588   812  1036  1260  1484  1708]\n     [  364  1100  1836  2572  3308  4044  4780  5516]\n     [  588  1836  3084  4332  5580  6828  8076  9324]\n     [  812  2572  4332  6092  7852  9612 11372 13132]\n     [ 1036  3308  5580  7852 10124 12396 14668 16940]\n     [ 1260  4044  6828  9612 12396 15180 17964 20748]\n     [ 1484  4780  8076 11372 14668 17964 21260 24556]\n     [ 1708  5516  9324 13132 16940 20748 24556 28364]]\n\n","# GPU 拼图\n- 作者：[Sasha Rush](http:\u002F\u002Frush-nlp.com) - [srush_nlp](https:\u002F\u002Ftwitter.com\u002Fsrush_nlp)\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_GPU-Puzzles_readme_97918d3d9435.png)\n\nGPU 架构对机器学习至关重要，而且似乎每天都在变得更加重要。然而，你完全可以在不接触 GPU 代码的情况下成为机器学习专家。在抽象层面上工作很难培养直观的理解。\n\n这个笔记本旨在以完全交互式的方式教授初学者 GPU 编程。它没有提供包含概念的文字说明，而是直接让你动手编写和构建 GPU 内核。这些练习使用 NUMBA，它可以将 Python 代码直接映射到 CUDA 内核。虽然看起来像 Python，但实际上与编写低级 CUDA 代码几乎相同。\n我认为，在几个小时内，你就可以从基础知识入手，理解当今驱动 99% 深度学习的真正算法。如果你想阅读官方文档，可以在这里找到：\n\n[NUMBA CUDA 指南](https:\u002F\u002Fnumba.readthedocs.io\u002Fen\u002Fstable\u002Fcuda\u002Findex.html)\n\n我建议在 Colab 中完成这些练习，因为它很容易上手。请务必先复制一份自己的副本，在设置中启用 GPU 模式（`Runtime \u002F Change runtime type`，然后将 `Hardware accelerator` 设置为 `GPU`），然后再开始编码。\n\n[![在 Colab 中打开](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fsrush\u002FGPU-Puzzles\u002Fblob\u002Fmain\u002FGPU_puzzlers.ipynb)\n\n（如果你喜欢这种拼图风格，也可以看看我的 [Tensor Puzzles](https:\u002F\u002Fgithub.com\u002Fsrush\u002FTensor-Puzzles)，适用于 PyTorch。）\n\n[操作指南](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=K4T-YwsOxrM)\n\n\n```python\n!pip install -qqq git+https:\u002F\u002Fgithub.com\u002Fdanoneata\u002Fchalk@srush-patch-1\n!wget -q https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fraw\u002Fmain\u002Frobot.png https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fraw\u002Fmain\u002Flib.py\n```\n\n\n```python\nimport numba\nimport numpy as np\nimport warnings\nfrom lib import CudaProblem, Coord\n```\n\n\n```python\nwarnings.filterwarnings(\n    action=\"ignore\", category=numba.NumbaPerformanceWarning, module=\"numba\"\n)\n```\n\n## 拼图 1：映射\n\n实现一个“内核”（GPU 函数），将向量 `a` 的每个位置加 10，并将结果存储在向量 `out` 中。每个位置对应一个线程。\n\n**警告** 这段代码看起来像 Python，但实际上是 CUDA！你不能使用标准的 Python 工具，比如列表推导式，也不能询问 NumPy 数组的形状或大小（如果需要大小，会作为参数传入）。这些拼图只需要进行简单的操作，基本上是 +、*、简单的数组索引、for 循环和 if 语句。你可以使用局部变量。如果你遇到错误，那很可能是因为你尝试了过于复杂的操作 :).\n\n*提示：可以把函数 `call` 看作是为每个线程运行一次。唯一的区别是每次调用时 `cuda.threadIdx.x` 都会变化。*\n\n\n```python\ndef map_spec(a):\n    return a + 10\n\n\ndef map_test(cuda):\n    def call(out, a) -> None:\n        local_i = cuda.threadIdx.x\n        # 填充此处（大约 1 行）\n\n    return call\n\n\nSIZE = 4\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Map\", map_test, [a], out, threadsperblock=Coord(SIZE, 1), spec=map_spec\n)\nproblem.show()\n```\n\n    # Map\n     \n       分数（每线程最大值）：\n       | 全局读取 | 全局写入 | 共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_14_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[0. 0. 0. 0.]\n    标准答案：[10 11 12 13]\n\n\n## 拼图 2 - Zip\n\n实现一个内核，将 `a` 和 `b` 的每个位置相加，并将结果存储在 `out` 中。每个位置对应一个线程。\n\n\n```python\ndef zip_spec(a, b):\n    return a + b\n\n\ndef zip_test(cuda):\n    def call(out, a, b) -> None:\n        local_i = cuda.threadIdx.x\n        # 填充此处（大约 1 行）\n\n    return call\n\n\nSIZE = 4\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\nb = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Zip\", zip_test, [a, b], out, threadsperblock=Coord(SIZE, 1), spec=zip_spec\n)\nproblem.show()\n```\n\n    # Zip\n     \n       分数（每线程最大值）：\n       | 全局读取 | 全局写入 | 共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_17_1.svg)\n    \n\n\n\n\n```python\n\n```\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[0. 0. 0. 0.]\n    标准答案：[0 2 4 6]\n\n\n## 拼图 3 - 保护\n\n实现一个内核，将向量 `a` 的每个位置加 10，并将结果存储在向量 `out` 中。线程数量多于位置数量。\n\n\n```python\ndef map_guard_test(cuda):\n    def call(out, a, size) -> None:\n        local_i = cuda.threadIdx.x\n        # 填充此处（大约 2 行）\n\n    return call\n\n\nSIZE = 4\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Guard\",\n    map_guard_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(8, 1),\n    spec=map_spec,\n)\nproblem.show()\n```\n\n    # Guard\n     \n       分数（每线程最大值）：\n       | 全局读取 | 全局写入 | 共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_21_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[0. 0. 0. 0.]\n    标准答案：[10 11 12 13]\n\n\n## 拼图 4 - 二维映射\n\n实现一个内核，将矩阵 `a` 的每个位置加 10，并将结果存储在矩阵 `out` 中。输入矩阵 `a` 是正方形的二维矩阵。线程数量多于位置数量。\n\n\n```python\ndef map_2D_test(cuda):\n    def call(out, a, size) -> None:\n        local_i = cuda.threadIdx.x\n        local_j = cuda.threadIdx.y\n        # 填充此处（大约 2 行）\n\n    return call\n\n\nSIZE = 2\nout = np.zeros((SIZE, SIZE))\na = np.arange(SIZE * SIZE).reshape((SIZE, SIZE))\nproblem = CudaProblem(\n    \"Map 2D\", map_2D_test, [a], out, [SIZE], threadsperblock=Coord(3, 3), spec=map_spec\n)\nproblem.show()\n```\n\n    # Map 2D\n     \n       分数（每线程最大值）：\n       | 全局读取 | 全局写入 | 共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_24_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[[0. 0.]\n     [0. 0.]]\n    标准答案：[[10 11]\n     [12 13]]\n\n## 谜题 5 - 广播\n\n实现一个内核，将 `a` 和 `b` 相加，并将结果存储在 `out` 中。\n输入 `a` 和 `b` 是向量。线程的数量多于元素的位置数。\n\n\n```python\ndef broadcast_test(cuda):\n    def call(out, a, b, size) -> None:\n        local_i = cuda.threadIdx.x\n        local_j = cuda.threadIdx.y\n        # 填充我（大约 2 行）\n\n    return call\n\n\nSIZE = 2\nout = np.zeros((SIZE, SIZE))\na = np.arange(SIZE).reshape(SIZE, 1)\nb = np.arange(SIZE).reshape(1, SIZE)\nproblem = CudaProblem(\n    \"Broadcast\",\n    broadcast_test,\n    [a, b],\n    out,\n    [SIZE],\n    threadsperblock=Coord(3, 3),\n    spec=zip_spec,\n)\nproblem.show()\n```\n\n    # 广播\n     \n       每线程得分（最大值）：\n       | 全局读取 | 全局写入 | 共享内存读取 | 共享内存写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_27_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试未通过。\n    您的结果：[[0. 0.]\n     [0. 0.]]\n    规范结果：[[0 1]\n     [1 2]]\n\n\n## 谜题 6 - 块\n\n实现一个内核，将 `a` 的每个位置加上 10，并将结果存储在 `out` 中。\n每个块中的线程数量少于 `a` 的大小。\n\n*提示：块是一组线程。每个块的线程数量是有限的，但我们可以有多个不同的块。变量 `cuda.blockIdx` 告诉我们当前所在的块编号。*\n\n\n```python\ndef map_block_test(cuda):\n    def call(out, a, size) -> None:\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        # 填充我（大约 2 行）\n\n    return call\n\n\nSIZE = 9\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Blocks\",\n    map_block_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(4, 1),\n    blockspergrid=Coord(3, 1),\n    spec=map_spec,\n)\nproblem.show()\n```\n\n    # 块\n     \n       每线程得分（最大值）：\n       | 全局读取 | 全局写入 | 共享内存读取 | 共享内存写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_31_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试未通过。\n    您的结果：[0. 0. 0. 0. 0. 0. 0. 0. 0.]\n    规范结果：[10 11 12 13 14 15 16 17 18]\n\n\n## 谜题 7 - 二维块\n\n以 2D 方式实现相同的内核。每个块中的线程数量在两个方向上都少于 `a` 的大小。\n\n\n```python\ndef map_block2D_test(cuda):\n    def call(out, a, size) -> None:\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        # 填充我（大约 4 行）\n\n    return call\n\n\nSIZE = 5\nout = np.zeros((SIZE, SIZE))\na = np.ones((SIZE, SIZE))\n\nproblem = CudaProblem(\n    \"Blocks 2D\",\n    map_block2D_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(3, 3),\n    blockspergrid=Coord(2, 2),\n    spec=map_spec,\n)\nproblem.show()\n```\n\n    # 二维块\n     \n       每线程得分（最大值）：\n       | 全局读取 | 全局写入 | 共享内存读取 | 共享内存写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_34_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试未通过。\n    您的结果：[[0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0.]]\n    规范结果：[[11. 11. 11. 11. 11.]\n     [11. 11. 11. 11. 11.]\n     [11. 11. 11. 11. 11.]\n     [11. 11. 11. 11. 11.]\n     [11. 11. 11. 11. 11.]]\n\n\n## 谜题 8 - 共享内存\n\n实现一个内核，将 `a` 的每个位置加上 10，并将结果存储在 `out` 中。\n每个块中的线程数量少于 `a` 的大小。\n\n**警告**：每个块只能拥有*固定*大小的共享内存，该块内的线程可以读写。这必须是一个字面意义上的 Python 常量，而不是变量。在写入共享内存后，需要调用 `cuda.syncthreads` 来确保线程之间不会发生交叉。 \n\n（这个示例实际上并不需要共享内存或 syncthreads，但这是一个演示。）\n\n\n```python\nTPB = 4\ndef shared_test(cuda):\n    def call(out, a, size) -> None:\n        shared = cuda.shared.array(TPB, numba.float32)\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n\n        if i \u003C size:\n            shared[local_i] = a[i]\n            cuda.syncthreads()\n\n        # 填充我（大约 2 行）\n\n    return call\n\n\nSIZE = 8\nout = np.zeros(SIZE)\na = np.ones(SIZE)\nproblem = CudaProblem(\n    \"Shared\",\n    shared_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(TPB, 1),\n    blockspergrid=Coord(2, 1),\n    spec=map_spec,\n)\nproblem.show()\n```\n\n    # 共享内存\n     \n       每线程得分（最大值）：\n       | 全局读取 | 全局写入 | 共享内存读取 | 共享内存写入 |\n       |             1 |             0 |             0 |             1 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_39_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试未通过。\n    您的结果：[0. 0. 0. 0. 0. 0. 0. 0.]\n    规范结果：[11. 11. 11. 11. 11. 11. 11. 11.]\n\n\n## 谜题 9 - 池化\n\n实现一个内核，将 `a` 的最后 3 个位置相加，并将结果存储在 `out` 中。\n每个位置对应 1 个线程。每个线程只需要 1 次全局读取和 1 次全局写入。\n\n*提示：请记住要小心同步。*\n\n\n```python\ndef pool_spec(a):\n    out = np.zeros(*a.shape)\n    for i in range(a.shape[0]):\n        out[i] = a[max(i - 2, 0) : i + 1].sum()\n    return out\n\n\nTPB = 8\ndef pool_test(cuda):\n    def call(out, a, size) -> None:\n        shared = cuda.shared.array(TPB, numba.float32)\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n        # 填充我（大约 8 行）\n\n    return call\n\n\nSIZE = 8\nout = np.zeros(SIZE)\na = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Pooling\",\n    pool_test,\n    [a],\n    out,\n    [SIZE],\n    threadsperblock=Coord(TPB, 1),\n    blockspergrid=Coord(1, 1),\n    spec=pool_spec,\n)\nproblem.show()\n```\n\n    # 池化\n     \n       每线程得分（最大值）：\n       | 全局读取 | 全局写入 | 共享内存读取 | 共享内存写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_43_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试未通过。\n    您的结果：[0. 0. 0. 0. 0. 0. 0. 0.]\n    规范结果：[ 0.  1.  3.  6.  9. 12. 15. 18.]\n\n## 谜题10 - 点积\n\n实现一个内核，计算 `a` 和 `b` 的点积，并将结果存储在 `out` 中。\n每个线程对应一个位置。每个线程只需要2次全局读取和1次全局写入。\n\n*注意：对于这个问题，你不需要担心共享内存的读取次数。我们稍后再处理这个挑战。*\n\n\n```python\ndef dot_spec(a, b):\n    return a @ b\n\nTPB = 8\ndef dot_test(cuda):\n    def call(out, a, b, size) -> None:\n        shared = cuda.shared.array(TPB, numba.float32)\n\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n        # 填充我 (大约9行)\n    return call\n\n\nSIZE = 8\nout = np.zeros(1)\na = np.arange(SIZE)\nb = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Dot\",\n    dot_test,\n    [a, b],\n    out,\n    [SIZE],\n    threadsperblock=Coord(SIZE, 1),\n    blockspergrid=Coord(1, 1),\n    spec=dot_spec,\n)\nproblem.show()\n```\n\n    # Dot\n     \n       分数 (每线程最大值)：\n       |  全局读取 | 全局写入 |  共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_47_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[0.]\n    标准答案：140\n\n\n## 谜题11 - 一维卷积\n\n实现一个内核，计算 `a` 和 `b` 之间的一维卷积，并将结果存储在 `out` 中。\n你需要处理一般情况。每个线程只需要2次全局读取和1次全局写入。\n\n\n```python\ndef conv_spec(a, b):\n    out = np.zeros(*a.shape)\n    len = b.shape[0]\n    for i in range(a.shape[0]):\n        out[i] = sum([a[i + j] * b[j] for j in range(len) if i + j \u003C a.shape[0]])\n    return out\n\n\nMAX_CONV = 4\nTPB = 8\nTPB_MAX_CONV = TPB + MAX_CONV\ndef conv_test(cuda):\n    def call(out, a, b, a_size, b_size) -> None:\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n\n        # 填充我 (大约17行)\n\n    return call\n\n\n# 测试1\n\nSIZE = 6\nCONV = 3\nout = np.zeros(SIZE)\na = np.arange(SIZE)\nb = np.arange(CONV)\nproblem = CudaProblem(\n    \"1D Conv (Simple)\",\n    conv_test,\n    [a, b],\n    out,\n    [SIZE, CONV],\n    Coord(1, 1),\n    Coord(TPB, 1),\n    spec=conv_spec,\n)\nproblem.show()\n```\n\n    # 1D Conv (Simple)\n     \n       分数 (每线程最大值)：\n       |  全局读取 | 全局写入 |  共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_50_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[0. 0. 0. 0. 0. 0.]\n    标准答案：[ 5.  8. 11. 14.  5.  0.]\n\n\n测试2\n\n\n```python\nout = np.zeros(15)\na = np.arange(15)\nb = np.arange(4)\nproblem = CudaProblem(\n    \"1D Conv (Full)\",\n    conv_test,\n    [a, b],\n    out,\n    [15, 4],\n    Coord(2, 1),\n    Coord(TPB, 1),\n    spec=conv_spec,\n)\nproblem.show()\n```\n\n    # 1D Conv (Full)\n     \n       分数 (每线程最大值)：\n       |  全局读取 | 全局写入 |  共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_53_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n    标准答案：[14. 20. 26. 32. 38. 44. 50. 56. 62. 68. 74. 80. 41. 14.  0.]\n\n\n## 谜题12 - 前缀和\n\n实现一个内核，对 `a` 进行求和，并将结果存储在 `out` 中。\n如果 `a` 的大小大于块大小，则只存储每个块的和。\n\n我们将使用共享内存中的[并行前缀和](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FPrefix_sum)算法来实现这一点。\n也就是说，算法的每一步都应该将剩余数字的一半相加。请按照下图所示进行操作：\n\n![](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_GPU-Puzzles_readme_5b347f99a6eb.png)\n\n\n```python\nTPB = 8\ndef sum_spec(a):\n    out = np.zeros((a.shape[0] + TPB - 1) \u002F\u002F TPB)\n    for j, i in enumerate(range(0, a.shape[-1], TPB)):\n        out[j] = a[i : i + TPB].sum()\n    return out\n\n\ndef sum_test(cuda):\n    def call(out, a, size: int) -> None:\n        cache = cuda.shared.array(TPB, numba.float32)\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n        # 填充我 (大约12行)\n\n    return call\n\n\n# 测试1\n\nSIZE = 8\nout = np.zeros(1)\ninp = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Sum (Simple)\",\n    sum_test,\n    [inp],\n    out,\n    [SIZE],\n    Coord(1, 1),\n    Coord(TPB, 1),\n    spec=sum_spec,\n)\nproblem.show()\n```\n\n    # Sum (Simple)\n     \n       分数 (每线程最大值)：\n       |  全局读取 | 全局写入 |  共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_58_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[0.]\n    标准答案：[28.]\n\n\n测试2\n\n\n```python\nSIZE = 15\nout = np.zeros(2)\ninp = np.arange(SIZE)\nproblem = CudaProblem(\n    \"Sum (Full)\",\n    sum_test,\n    [inp],\n    out,\n    [SIZE],\n    Coord(2, 1),\n    Coord(TPB, 1),\n    spec=sum_spec,\n)\nproblem.show()\n```\n\n    # Sum (Full)\n     \n       分数 (每线程最大值)：\n       |  全局读取 | 全局写入 |  共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_61_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[0. 0.]\n    标准答案：[28. 77.]\n\n\n## 谜题13 - 轴向求和\n\n实现一个内核，对 `a` 的每一列进行求和，并将结果存储在 `out` 中。\n\n\n```python\nTPB = 8\ndef sum_spec(a):\n    out = np.zeros((a.shape[0], (a.shape[1] + TPB - 1) \u002F\u002F TPB))\n    for j, i in enumerate(range(0, a.shape[-1], TPB)):\n        out[..., j] = a[..., i : i + TPB].sum(-1)\n    return out\n\n\ndef axis_sum_test(cuda):\n    def call(out, a, size: int) -> None:\n        cache = cuda.shared.array(TPB, numba.float32)\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        local_i = cuda.threadIdx.x\n        batch = cuda.blockIdx.y\n        # 填充我 (大约12行)\n\n    return call\n\n\nBATCH = 4\nSIZE = 6\nout = np.zeros((BATCH, 1))\ninp = np.arange(BATCH * SIZE).reshape((BATCH, SIZE))\nproblem = CudaProblem(\n    \"Axis Sum\",\n    axis_sum_test,\n    [inp],\n    out,\n    [SIZE],\n    Coord(1, BATCH),\n    Coord(TPB, 1),\n    spec=sum_spec,\n)\nproblem.show()\n```\n\n    # Axis Sum\n     \n       分数 (每线程最大值)：\n       |  全局读取 | 全局写入 |  共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_64_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[[0.]\n     [0.]\n     [0.]\n     [0.]]\n    标准答案：[[ 15.]\n     [ 51.]\n     [ 87.]\n     [123.]]\n\n## 谜题 14 - 矩阵乘法！\n\n实现一个核函数，用于将方阵 `a` 和 `b` 相乘，并将结果存储在 `out` 中。\n\n*提示：这里最高效的算法是先将一个块复制到共享内存中，然后再计算每个单独的行-列点积。如果矩阵可以完全放入共享内存，则很容易做到这一点。请先实现这种情况，然后更新你的代码以计算部分点积，并迭代地移动你复制到共享内存中的那一部分。* 你应该能够在只进行 6 次全局读取的情况下完成更复杂的情况。\n\n\n```python\ndef matmul_spec(a, b):\n    return a @ b\n\n\nTPB = 3\ndef mm_oneblock_test(cuda):\n    def call(out, a, b, size: int) -> None:\n        a_shared = cuda.shared.array((TPB, TPB), numba.float32)\n        b_shared = cuda.shared.array((TPB, TPB), numba.float32)\n\n        i = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x\n        j = cuda.blockIdx.y * cuda.blockDim.y + cuda.threadIdx.y\n        local_i = cuda.threadIdx.x\n        local_j = cuda.threadIdx.y\n        # 填充此处（大约 14 行）\n\n    return call\n\n# 测试 1\n\nSIZE = 2\nout = np.zeros((SIZE, SIZE))\ninp1 = np.arange(SIZE * SIZE).reshape((SIZE, SIZE))\ninp2 = np.arange(SIZE * SIZE).reshape((SIZE, SIZE)).T\n\nproblem = CudaProblem(\n    \"矩阵乘法（简单）\",\n    mm_oneblock_test,\n    [inp1, inp2],\n    out,\n    [SIZE],\n    Coord(1, 1),\n    Coord(TPB, TPB),\n    spec=matmul_spec,\n)\nproblem.show(sparse=True)\n```\n\n    # 矩阵乘法（简单）\n     \n       分数（每线程最大值）：\n       | 全局读取 | 全局写入 | 共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_67_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[[0. 0.]\n     [0. 0.]]\n    标准答案：[[ 1  3]\n     [ 3 13]]\n\n\n测试 2\n\n\n```python\nSIZE = 8\nout = np.zeros((SIZE, SIZE))\ninp1 = np.arange(SIZE * SIZE).reshape((SIZE, SIZE))\ninp2 = np.arange(SIZE * SIZE).reshape((SIZE, SIZE)).T\n\nproblem = CudaProblem(\n    \"矩阵乘法（完整）\",\n    mm_oneblock_test,\n    [inp1, inp2],\n    out,\n    [SIZE],\n    Coord(3, 3),\n    Coord(TPB, TPB),\n    spec=matmul_spec,\n)\nproblem.show(sparse=True)\n```\n\n    # 矩阵乘法（完整）\n     \n       分数（每线程最大值）：\n       | 全局读取 | 全局写入 | 共享读取 | 共享写入 |\n       |             0 |             0 |             0 |             0 | \n    \n\n\n\n\n\n    \n![svg](GPU_puzzlers_files\u002FGPU_puzzlers_70_1.svg)\n    \n\n\n\n\n```python\nproblem.check()\n```\n\n    测试失败。\n    你的结果：[[0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]\n     [0. 0. 0. 0. 0. 0. 0. 0.]]\n    标准答案：[[  140   364   588   812  1036  1260  1484  1708]\n     [  364  1100  1836  2572  3308  4044  4780  5516]\n     [  588  1836  3084  4332  5580  6828  8076  9324]\n     [  812  2572  4332  6092  7852  9612 11372 13132]\n     [ 1036  3308  5580  7852 10124 12396 14668 16940]\n     [ 1260  4044  6828  9612 12396 15180 17964 20748]\n     [ 1484  4780  8076 11372 14668 17964 21260 24556]\n     [ 1708  5516  9324 13132 16940 20748 24556 28364]]","# GPU-Puzzles 快速上手指南\n\nGPU-Puzzles 是一个交互式学习工具，旨在通过编写代码谜题帮助开发者直观理解 GPU 架构和 CUDA 编程核心概念。它使用 Numba 将 Python 代码直接映射为 CUDA 内核，让你在不离开 Python 环境的情况下掌握深度学习底层的并行计算原理。\n\n## 环境准备\n\n*   **系统要求**：支持 CUDA 的 NVIDIA GPU（推荐使用 Google Colab 云端环境，无需本地配置显卡驱动）。\n*   **前置依赖**：\n    *   Python 3.x\n    *   `numba` (用于 JIT 编译 CUDA 代码)\n    *   `numpy` (用于数组操作)\n    *   `chalk` (本项目特定的可视化工具库)\n*   **推荐平台**：**Google Colab**。这是最快捷的启动方式，已预装大部分依赖并提供免费 GPU 资源。\n\n## 安装与启动步骤\n\n### 方案一：使用 Google Colab（推荐）\n\n1.  打开项目 Notebook：\n    [![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fsrush\u002FGPU-Puzzles\u002Fblob\u002Fmain\u002FGPU_puzzlers.ipynb)\n2.  **关键步骤**：点击菜单栏 `运行时 (Runtime)` -> `更改运行时类型 (Change runtime type)`。\n3.  在 `硬件加速器 (Hardware accelerator)` 下拉菜单中选择 **GPU**，然后点击保存。\n4.  在 Notebook 的第一个代码单元格中运行以下命令以安装特定依赖并下载辅助文件：\n\n```python\n!pip install -qqq git+https:\u002F\u002Fgithub.com\u002Fdanoneata\u002Fchalk@srush-patch-1\n!wget -q https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fraw\u002Fmain\u002Frobot.png https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fraw\u002Fmain\u002Flib.py\n```\n\n### 方案二：本地环境安装\n\n如果你拥有本地 NVIDIA GPU 并希望在本机运行：\n\n1.  确保已安装 NVIDIA 驱动和 CUDA Toolkit。\n2.  安装 Python 依赖：\n\n```bash\npip install numba numpy\npip install git+https:\u002F\u002Fgithub.com\u002Fdanoneata\u002Fchalk@srush-patch-1\n```\n\n3.  克隆项目并下载必要文件：\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles.git\ncd GPU-Puzzles\nwget https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fraw\u002Fmain\u002Frobot.png\nwget https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fraw\u002Fmain\u002Flib.py\n```\n\n## 基本使用\n\nGPU-Puzzles 的核心是通过完成一系列“谜题”来学习。每个谜题要求你填充一段看似 Python 实为 CUDA 的代码。\n\n### 1. 导入模块\n在代码单元格中运行以下初始化代码：\n\n```python\nimport numba\nimport numpy as np\nimport warnings\nfrom lib import CudaProblem, Coord\n\n# 忽略 Numba 的性能警告，保持输出整洁\nwarnings.filterwarnings(\n    action=\"ignore\", category=numba.NumbaPerformanceWarning, module=\"numba\"\n)\n```\n\n### 2. 解题示例：Puzzle 1 (Map)\n**目标**：实现一个内核，将向量 `a` 的每个位置加 10 并存入 `out`。每个线程处理一个位置。\n\n**操作步骤**：\n1.  阅读题目描述，理解 `cuda.threadIdx.x` 代表当前线程的索引。\n2.  在 `# FILL ME IN` 处编写逻辑。\n3.  运行 `problem.check()` 验证答案。\n\n**代码示例**：\n\n```python\ndef map_spec(a):\n    return a + 10\n\ndef map_test(cuda):\n    def call(out, a) -> None:\n        local_i = cuda.threadIdx.x\n        # 在此处填写代码：读取 a[local_i]，加 10，写入 out[local_i]\n        out[local_i] = a[local_i] + 10\n\n    return call\n\nSIZE = 4\nout = np.zeros((SIZE,))\na = np.arange(SIZE)\n\n# 定义问题配置\nproblem = CudaProblem(\n    \"Map\", map_test, [a], out, threadsperblock=Coord(SIZE, 1), spec=map_spec\n)\n\n# 显示当前状态和评分标准\nproblem.show()\n\n# 检查答案是否正确\nproblem.check()\n```\n\n### 3. 进阶练习\n按照 Notebook 顺序依次完成后续谜题，难度逐渐递增：\n*   **Puzzle 2 (Zip)**: 双向量相加。\n*   **Puzzle 3 (Guards)**: 处理线程数多于数据量的情况（边界检查）。\n*   **Puzzle 4 & 5 (2D\u002FBroadcast)**: 二维索引与广播机制。\n*   **Puzzle 6 & 7 (Blocks)**: 多块（Multi-block）协作与全局索引计算。\n*   **Puzzle 8 (Shared)**: 共享内存与线程同步 (`cuda.syncthreads`)。\n*   **Puzzle 9 (Pooling)**: 复杂的归约操作。\n\n> **提示**：代码虽然像 Python，但不能使用列表推导式或 `len()` 等高级特性。仅支持基础运算、索引、循环和条件判断。如遇错误，通常是因为使用了不支持的 Python 语法。","某深度学习框架研发团队的初级工程师，在尝试优化自定义算子性能时，因缺乏底层 GPU 架构直觉而陷入瓶颈。\n\n### 没有 GPU-Puzzles 时\n- **理论脱节**：工程师虽熟悉 PyTorch 高层 API，但面对 CUDA 线程块、共享内存等抽象概念时，只能死记硬背文档，无法建立直观的空间映射感。\n- **试错成本高**：直接编写原生 CUDA C++ 代码极易出现内存越界或线程同步错误，调试过程繁琐，往往花费数天排查一个索引偏移问题。\n- **环境门槛高**：配置本地 GPU 编译环境复杂，新手常在安装驱动、编译器版本匹配上耗费大量精力，迟迟无法进入核心逻辑学习。\n- **反馈周期长**：修改代码后需重新编译、部署并运行完整测试脚本，无法即时验证对单个线程行为的理解是否正确。\n\n### 使用 GPU-Puzzles 后\n- **交互式直觉构建**：通过“地图（Map）”、“压缩（Zip）”等拼图游戏，工程师在 Colab 中直接用 Python 语法编写 CUDA 内核，瞬间理解 `threadIdx.x` 如何对应数据位置。\n- **即时正向反馈**：每完成一个谜题，系统立即可视化线程执行流程并评分，将原本晦涩的并行逻辑转化为可见的得分奖励，快速纠正认知偏差。\n- **零配置上手**：无需安装本地 CUDA 工具链，依托 Google Colab 云端 GPU 环境，打开链接即可开始编写和调试内核，几分钟内进入心流状态。\n- **平滑过渡实战**：从简单的向量加法的谜题入手，逐步掌握归约、卷积等核心算法模式，几小时内即可具备阅读和优化真实深度学习算子源码的能力。\n\nGPU-Puzzles 将枯燥的底层并行计算原理转化为直观的编程闯关体验，让开发者在数小时内跨越从“调用者”到“掌控者”的认知鸿沟。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_GPU-Puzzles_97918d3d.png","srush","Sasha Rush","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fsrush_0d88b2d1.jpg","Cornell Tech \u002F Hugging Face","Cornell","New York","srush.research@gmail.com","srush_nlp","http:\u002F\u002Frush-nlp.com","https:\u002F\u002Fgithub.com\u002Fsrush",[84,88],{"name":85,"color":86,"percentage":87},"Jupyter Notebook","#DA5B0B",98.8,{"name":89,"color":90,"percentage":91},"Python","#3572A5",1.2,12050,932,"2026-04-18T10:07:48","MIT","未说明","需要支持 CUDA 的 NVIDIA GPU（推荐在 Google Colab 中运行，需开启 GPU 模式）",{"notes":99,"python":96,"dependencies":100},"该项目是一个交互式教程，旨在通过 Numba 将 Python 代码直接映射为 CUDA 内核来教授 GPU 编程。强烈建议在 Google Colab 环境中运行，需在运行时设置中将硬件加速器更改为 GPU。代码中使用了特定的 chalk 库分支和自定义的 lib.py 文件，需按 README 中的指令预先安装和下载。",[101,102,103],"numba","numpy","chalk (特定分支)",[14],[106,107,108],"cuda","machine-learning","puzzles",null,"2026-03-27T02:49:30.150509","2026-04-20T04:05:16.137774",[113,118,123,128,133,138],{"id":114,"question_zh":115,"answer_zh":116,"source_url":117},43897,"如何将 Numba CUDA 代码与 PyTorch 结合使用？","你可以通过将 PyTorch 张量转换为 NumPy 数组来调用 Numba CUDA 函数，例如：`your_function(x.numpy())`。但需注意，这种方法不支持自动求导（autograd），且涉及数据在 GPU -> CPU -> GPU 之间的传输，效率较低。若需更高效率的集成，建议研究 `dlpack` 协议或查阅 PyTorch 相关文档以实现零拷贝交互。","https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fissues\u002F1",{"id":119,"question_zh":120,"answer_zh":121,"source_url":122},43898,"为什么创建共享内存数组时使用变量大小会报错 TypingError？","CUDA 对共享数组的大小限制极其严格，大小必须在编译时确定为常量，不能使用运行时变量。即使该变量在逻辑上是固定的，Numba 也无法处理。解决方法是定义一个全局常量（如 `TPB = 10`）或直接使用字面量数值（如 `10`），确保在编译期已知。例如：`cuda.shared.array(10, numba.float32)` 或 `cuda.shared.array(TPB, numba.float32)`（其中 TPB 为模块级常量）。","https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fissues\u002F6",{"id":124,"question_zh":125,"answer_zh":126,"source_url":127},43899,"在 Puzzle 9 (Pooling) 中，为什么使用循环累加共享内存会导致结果错误（重复计算）？","这是因为在循环中直接对共享内存数组进行读写操作（read-modify-write），可能导致线程间竞争或逻辑上的重复累加。正确的做法是使用每个线程私有的局部标量变量来存储累加和，完成计算后再写入输出数组。Numba CUDA 允许在核函数中使用普通的 Python 局部变量作为临时存储，这比直接操作共享内存更安全且高效。","https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fissues\u002F5",{"id":129,"question_zh":130,"answer_zh":131,"source_url":132},43900,"Puzzle 11 (1D Convolution) 中如何处理超出当前块范围的卷积边界数据？","你不需要创建一个巨大的共享内存数组来容纳所有可能的边界数据。允许定义多个独立的共享内存数组来分别存储不同的数据块。此外，可以根据需要扩展共享内存的大小（例如 `TPB + MAX_CONV + (MAX_CONV - 1)`），以覆盖卷积操作中所需的最大邻域范围，同时确保全局读取次数符合题目约束。","https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fissues\u002F17",{"id":134,"question_zh":135,"answer_zh":136,"source_url":137},43901,"在二维输出数组赋值时遇到 IndexError 或断言错误怎么办？","如果输出数组 `out` 是二维的（例如形状为 `[batch, 1]`），而代码中使用了 `out[batch] = temp`，这会引发错误。必须显式指定所有维度的索引，改为 `out[batch, 0] = temp`。确保索引维度与数组实际形状完全匹配。","https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fissues\u002F8",{"id":139,"question_zh":140,"answer_zh":141,"source_url":142},43902,"如何在 Colab 中解决 'metadata-generation-failed' 安装错误？","虽然具体报错信息被截断，但此类错误通常源于 Colab 环境中依赖包版本冲突或构建工具缺失。建议尝试以下通用步骤：1. 升级 pip、setuptools 和 wheel (`!pip install --upgrade pip setuptools wheel`)；2. 清除缓存后重新安装 (`!pip cache purge` 然后重试安装命令)；3. 如果涉及特定包，尝试安装其预编译的二进制版本或指定兼容的版本号。","https:\u002F\u002Fgithub.com\u002Fsrush\u002FGPU-Puzzles\u002Fissues\u002F22",[]]