<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[GPU Kernel Hacking for Engineers - Medium]]></title>
        <description><![CDATA[GPU Kernel Hacking for Engineers - Medium]]></description>
        <link>https://medium.com/gpu-kernel-hacking-for-engineers?source=rss----3d44069ea69e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>GPU Kernel Hacking for Engineers - Medium</title>
            <link>https://medium.com/gpu-kernel-hacking-for-engineers?source=rss----3d44069ea69e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:45:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/gpu-kernel-hacking-for-engineers" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Part 5: Hands-On Debugging — Tracing, Probing, and Custom Kernel Modules]]></title>
            <link>https://medium.com/gpu-kernel-hacking-for-engineers/part-5-hands-on-debugging-tracing-probing-and-custom-kernel-modules-04dd32f894e8?source=rss----3d44069ea69e---4</link>
            <guid isPermaLink="false">https://medium.com/p/04dd32f894e8</guid>
            <category><![CDATA[direct-memory-access]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[performance-engineering]]></category>
            <dc:creator><![CDATA[Nikheel Vishwas Savant]]></dc:creator>
            <pubDate>Mon, 26 May 2025 02:15:46 GMT</pubDate>
            <atom:updated>2025-05-26T02:15:46.551Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 5: Hands-On Debugging — Tracing, Probing, and Custom Kernel Modules</h3><p>Now that you’ve explored shared memory, PCIe, RDMA, BARs, and VFIO, it’s time to put that knowledge into action.</p><p>This final article of the series walks through:</p><ul><li>🔍 Setting up tracing tools like ftrace, bpftrace, and perf</li><li>🧵 Writing a minimal kernel module to intercept memory operations</li><li>🛠️ Capturing DMA, IOMMU, and RDMA activity live</li></ul><p>If you’ve ever asked: “Where did that cudaMemcpyPeer() really go?” — this article is for you.</p><h3>🔧 Setting Up Your Environment</h3><p>Before you begin:</p><ul><li>Ensure kernel headers and debug symbols are installed (/usr/src/linux-headers-*)</li><li>Enable debugfs:</li><li>mount -t debugfs none /sys/kernel/debug</li><li>Install tools: bpftrace, perf, trace-cmd, bcc-tools</li></ul><h3>📍 Using ftrace to Monitor DMA Events</h3><p>ftrace is built into the kernel and allows function-level tracing with minimal overhead.</p><h3>Step-by-Step:</h3><pre>echo function &gt; /sys/kernel/debug/tracing/current_tracer<br>echo &#39;dma_map*&#39; &gt; /sys/kernel/debug/tracing/set_ftrace_filter<br>echo 1 &gt; /sys/kernel/debug/tracing/tracing_on</pre><p>Run your GPU or RDMA workload.</p><p>Then:</p><pre>cat /sys/kernel/debug/tracing/trace | less</pre><p>This shows live kernel activity when devices map memory for DMA — including GPU buffers used in GPUDirect or peer-to-peer.</p><blockquote><em>🧠 Trace filtering supports globs (</em><em>dma_*, </em><em>nvidia_*, etc.).</em></blockquote><h3>🔬 Real-Time Observability with bpftrace</h3><p>bpftrace gives you programmable observability — attach live probes to kernel functions.</p><h3>Example: Trace RDMA Registration</h3><pre>sudo bpftrace -e &#39;kprobe:ib_umem_get { printf(&quot;RDMA registered %lx\n&quot;, arg1); }&#39;</pre><p>You can probe:</p><ul><li>nvidia_p2p_get_pages</li><li>vfio_pin_pages</li><li>iommu_map</li></ul><blockquote><em>🧠 Add </em><em>u or </em><em>k prefixes to trace user or kernel symbols.</em></blockquote><h3>🔥 Performance Profiling with perf</h3><p>perf helps analyze execution hotspots and track memory faults.</p><pre>perf record -e dma:dma_map_page,dma:dma_unmap_page -a<br>perf report</pre><p>Or use flame graphs:</p><pre>perf script | stackcollapse-perf.pl | flamegraph.pl &gt; flame.svg</pre><h3>🧑‍💻 Writing a Minimal Kernel Module to Hook GPU DMA</h3><p>Want full control? Build a custom kernel module.</p><h3>Minimal Example (observing dma_map_page):</h3><pre>#include &lt;linux/module.h&gt;<br>#include &lt;linux/init.h&gt;<br>#include &lt;linux/dma-mapping.h&gt;<br>#include &lt;linux/kprobes.h&gt;<br><br>static struct kprobe kp = {<br>    .symbol_name = &quot;dma_map_page&quot;,<br>};<br>static int handler_pre(struct kprobe *p, struct pt_regs *regs) {<br>    pr_info(&quot;dma_map_page called\n&quot;);<br>    return 0;<br>}<br>static int __init my_init(void) {<br>    kp.pre_handler = handler_pre;<br>    return register_kprobe(&amp;kp);<br>}<br>static void __exit my_exit(void) {<br>    unregister_kprobe(&amp;kp);<br>}<br>module_init(my_init);<br>module_exit(my_exit);<br>MODULE_LICENSE(&quot;GPL&quot;);</pre><p>Build with:</p><pre>make -C /lib/modules/$(uname -r)/build M=$PWD modules</pre><blockquote><em>⚠️ Use with caution — kprobes on high-frequency paths can introduce latency.</em></blockquote><h3>🕵️ Interpreting Common Trace Patterns</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kE4014yzcamo-ghm0ZfdJQ.png" /></figure><h3>🧪 Bonus: Trace Peer-to-Peer Setup Between Two GPUs</h3><ol><li>Enable ftrace filter:</li></ol><ul><li>echo &#39;nvidia_p2p_*&#39; &gt; /sys/kernel/debug/tracing/set_ftrace_filter</li></ul><p>2. Use this CUDA snippet:</p><ul><li>cudaSetDevice(0); cudaDeviceEnablePeerAccess(1, 0); cudaMemcpyPeer(dst, 1, src, 0, size);</li></ul><p>3. Inspect trace for:</p><ul><li>nvidia_p2p_get_pages</li><li>dam_map_resource</li><li>iommu_map</li></ul><h3>🔍 Diagnosing Real Failures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtKyzwrQV7i8cAPLz_oLkQ.png" /></figure><h3>📘 Further Reading &amp; Resources</h3><ul><li>NVIDIA GPUDirect RDMA whitepaper</li><li>bpftrace cheatsheet (by Brendan Gregg)</li><li>vfio documentation: /usr/share/doc/linux-doc/vfio.txt</li><li>iommu.txt, dma-mapping.txt in Linux source</li></ul><h3>💡 TL;DR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4a0f4R_5EkBEB6McspX_YQ.png" /></figure><h3>🎉 Series Wrap-Up</h3><p>This concludes the 5-part <strong>GPU Kernel Hacking for Engineers</strong> series:</p><ol><li>Intra-GPU: Warps, Shared Memory, Shuffle</li><li>Inter-GPU: PCIe, NVLink, BARs</li><li>Distributed GPU: RDMA, GPUDirect, NCCL</li><li>Kernel Internals: DMA, IOMMU, VFIO</li><li>Hands-On Debugging: ftrace, bpftrace, custom modules</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04dd32f894e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gpu-kernel-hacking-for-engineers/part-5-hands-on-debugging-tracing-probing-and-custom-kernel-modules-04dd32f894e8">Part 5: Hands-On Debugging — Tracing, Probing, and Custom Kernel Modules</a> was originally published in <a href="https://medium.com/gpu-kernel-hacking-for-engineers">GPU Kernel Hacking for Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4: Under the Hood — DMA, IOMMU, BARs, and VFIO]]></title>
            <link>https://medium.com/gpu-kernel-hacking-for-engineers/part-4-under-the-hood-dma-iommu-bars-and-vfio-45b4f13e545c?source=rss----3d44069ea69e---4</link>
            <guid isPermaLink="false">https://medium.com/p/45b4f13e545c</guid>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[dynamic-memory-allocation]]></category>
            <dc:creator><![CDATA[Nikheel Vishwas Savant]]></dc:creator>
            <pubDate>Mon, 26 May 2025 02:09:07 GMT</pubDate>
            <atom:updated>2025-05-26T02:09:07.873Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 4: Under the Hood — DMA, IOMMU, BARs, and VFIO</h3><p>If you’ve ever wondered <em>how</em> a GPU or NIC accesses memory, or what makes <strong>GPUDirect</strong> and <strong>P2P communication</strong> even possible, it’s time to lift the hood.</p><p>In this article, we explore the <strong>Linux kernel components that power GPU data flow</strong>:</p><ul><li>DMA mapping</li><li>IOMMU groups</li><li>PCIe BARs</li><li>VFIO and secure device passthrough</li></ul><p>By the end, you’ll understand the <strong>infrastructure that underpins fast, secure, and direct memory access between devices</strong> — essential knowledge for building secure AI, edge, and HPC systems.</p><h3>📦 DMA: Direct Memory Access</h3><p><strong>DMA (Direct Memory Access)</strong> allows hardware devices (GPUs, NICs, etc.) to read/write memory <strong>without CPU intervention</strong>.</p><h3>Key Functions (from dma-mapping.h)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLq1XDhIJZMGmocscxMfbQ.png" /></figure><blockquote><em>🔧 </em><em>nvidia.ko, </em><em>mlx5_core, and </em><em>vfio all rely on these APIs to enable RDMA and P2P GPU access.</em></blockquote><h3>🧭 IOMMU: Input-Output Memory Management Unit</h3><p>IOMMU acts as a <strong>memory translation and protection layer</strong> between devices and physical memory.</p><h3>Why It Matters:</h3><ul><li>Ensures a device only accesses <strong>authorized memory</strong></li><li>Supports <strong>address remapping</strong> (important for P2P, GPUDirect)</li><li>Enables <strong>device passthrough</strong> in VMs (via VFIO)</li></ul><h3>Linux Kernel Paths:</h3><ul><li>/sys/kernel/iommu_groups/ – lists devices grouped for IOMMU isolation</li><li>/proc/iomem – shows memory regions exposed to devices</li><li>/dev/iommu/ – user APIs (if enabled)</li></ul><blockquote><em>🧠 In containers or VMs, the IOMMU ensures each device has access only to its own memory space.</em></blockquote><h3>📍 PCIe BARs: Base Address Registers</h3><p><strong>BARs define the physical memory regions</strong> a PCIe device exposes to the host.</p><h3>For GPUs:</h3><ul><li><strong>BAR0</strong> → control registers</li><li><strong>BAR1</strong> → framebuffer (global memory)</li><li><strong>BAR2</strong> → (optional) peer-accessible memory for GPUDirect or P2P</li></ul><p>Check with:</p><pre>lspci -vv -s 01:00.0 | grep -i bar<br>cat /proc/iomem</pre><blockquote><em>⚠️ Your GPU driver (e.g., </em><em>nvidia.ko) must map BAR1 into kernel space for the NIC or other GPU to access it.</em></blockquote><h3>🔒 VFIO: Secure Device Access in User Space</h3><p><strong>VFIO (Virtual Function I/O)</strong> allows safe, isolated access to PCI devices <strong>from user space</strong>, making it critical for:</p><ul><li>Containerized GPU apps</li><li>Virtualized environments (QEMU/KVM)</li><li>Secure RDMA/NVMe control planes</li></ul><h3>Key Concepts:</h3><ul><li>Devices assigned to <strong>IOMMU groups</strong></li><li>Userspace gets <strong>file descriptors</strong> for DMA via /dev/vfio/*</li><li>Can <strong>bind/unbind</strong> drivers dynamically</li></ul><pre>echo 0000:01:00.0 &gt; /sys/bus/pci/devices/0000:01:00.0/driver/unbind<br>echo vfio-pci &gt; /sys/bus/pci/devices/0000:01:00.0/driver_override<br>modprobe vfio-pci</pre><blockquote><em>📦 Kubernetes with device plugins or libvirt with GPU passthrough both use VFIO under the hood.</em></blockquote><h3>🛠️ Kernel Debug Tools for GPU Communication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zF6L0FCUcAC3l5rsh1QTRQ.png" /></figure><h3>🧪 Mini Lab: Watch the Kernel Map GPU Memory</h3><ol><li>Enable tracing:</li></ol><p>echo function &gt; /sys/kernel/debug/tracing/current_tracer echo &#39;dma_map_resource&#39; &gt; /sys/kernel/debug/tracing/set_ftrace_filter echo 1 &gt; /sys/kernel/debug/tracing/tracing_on</p><p>2. Launch RDMA or P2P workload.</p><p>3. View output:</p><ul><li>cat /sys/kernel/debug/tracing/trace</li></ul><h3>🔍 GPU Kernel Memory Debugging Patterns</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKi_pjx6nfv27oTmgj7AZA.png" /></figure><h3>📘 What to Read or Try Next</h3><ul><li>/drivers/iommu/ in Linux source for IOMMU backend logic</li><li>NVIDIA’s nvidia_peermem and Mellanox’s mlx5_ib source</li><li>vfio documentation in /Documentation/driver-api/</li><li>rdma-core userspace tools for debugging verbs</li></ul><h3>💡 TL;DR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kmv5ewsPdLrPEZOoNBOl5w.png" /></figure><h3>🔜 Coming Next: Part 5 — Hands-On Kernel Debugging for GPU Engineers</h3><p>We’ll roll up our sleeves:</p><ul><li>Write a basic kernel module to observe DMA</li><li>Use ftrace and bpftrace for real-time tracking</li><li>Capture GPU communication faults live</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45b4f13e545c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gpu-kernel-hacking-for-engineers/part-4-under-the-hood-dma-iommu-bars-and-vfio-45b4f13e545c">Part 4: Under the Hood — DMA, IOMMU, BARs, and VFIO</a> was originally published in <a href="https://medium.com/gpu-kernel-hacking-for-engineers">GPU Kernel Hacking for Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: Distributed GPU Communication with RDMA, NCCL, and GPUDirect]]></title>
            <link>https://medium.com/gpu-kernel-hacking-for-engineers/part-3-distributed-gpu-communication-with-rdma-nccl-and-gpudirect-975b81f4987f?source=rss----3d44069ea69e---4</link>
            <guid isPermaLink="false">https://medium.com/p/975b81f4987f</guid>
            <category><![CDATA[hpc]]></category>
            <category><![CDATA[rdma]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Nikheel Vishwas Savant]]></dc:creator>
            <pubDate>Mon, 26 May 2025 00:50:26 GMT</pubDate>
            <atom:updated>2025-05-26T00:50:14.077Z</atom:updated>
            <content:encoded><![CDATA[<p>Once your models get big enough — and fast enough — you’ll inevitably outgrow a single machine. Whether it’s training billion-parameter transformers or coordinating real-time vision on a drone fleet, <strong>inter-node GPU communication</strong> is the cornerstone of distributed AI.</p><p>In this article, we break down how GPUs talk across machines using <strong>GPUDirect</strong>, <strong>RDMA</strong>, and <strong>NVIDIA’s NCCL</strong> — with an eye on the <strong>kernel drivers and system-level glue</strong> that make it all work.</p><h3>🚀 Why Distributed GPU Communication Matters</h3><p>When scaling workloads across servers, we want:</p><ul><li><strong>Low-latency data transfer</strong></li><li><strong>Zero CPU involvement</strong></li><li><strong>End-to-end memory coherence</strong></li></ul><p>Traditionally, GPU-to-GPU transfers required copying to host RAM → TCP stack → destination host RAM → destination GPU. That’s a lot of overhead.</p><p><strong>Enter RDMA + GPUDirect</strong> — the kernel-level enablers of <strong>zero-copy GPU-to-GPU communication over the network</strong>.</p><h3>🧠 RDMA: Remote Direct Memory Access</h3><p>RDMA allows a network interface card (NIC) to <strong>read/write directly into GPU or host memory</strong> without CPU intervention.</p><p>RDMA enables:</p><ul><li><strong>Bypassing the kernel</strong> for data movement</li><li><strong>No context switches</strong> or memcpy overhead</li><li><strong>High throughput, low latency</strong></li></ul><p><strong>Common transports</strong>:</p><ul><li><strong>InfiniBand (IB)</strong></li><li><strong>RDMA over Converged Ethernet (RoCE)</strong></li><li><strong>iWARP (legacy)</strong></li></ul><h3>🔗 GPUDirect: The Secret Sauce</h3><p><strong>GPUDirect RDMA</strong> allows a NIC to access GPU memory <strong>directly over PCIe</strong> or NVLink without staging through system RAM.</p><p><strong>Typical Flow:</strong></p><ol><li>App registers GPU memory (via CUDA APIs).</li><li>NIC driver accesses GPU memory via <strong>BAR mappings</strong>.</li><li>DMA transfer occurs over InfiniBand or RoCE.</li></ol><h3>Benefits:</h3><ul><li>🚫 No bounce buffering in host RAM</li><li>🔄 Zero-copy send/recv between remote GPUs</li><li>🚀 ~10–20x lower latency than TCP/IP stack</li></ul><h3>🧩 Key Linux Kernel Modules Involved</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhNdpjbvIY5BIAAK1x6Rug.png" /></figure><blockquote><em>🔧 You must load </em><em>nvidia_peermem.ko and </em><em>mlx5_core.ko for GPUDirect RDMA to function on NVIDIA + Mellanox hardware.</em></blockquote><h3>📦 NCCL: NVIDIA Collective Communications Library</h3><p><strong>NCCL (pronounced “Nickel”)</strong> is a CUDA-aware library that:</p><ul><li>Implements collectives (AllReduce, Broadcast, AllGather, ReduceScatter)</li><li>Abstracts <strong>topology-aware communication</strong></li><li>Supports <strong>multi-GPU + multi-node</strong></li></ul><p>NCCL chooses the best path:</p><ul><li>Intra-GPU: shared mem / warp shuffle</li><li>Inter-GPU: NVLink / PCIe P2P</li><li>Inter-node: GPUDirect RDMA</li></ul><p><strong>NCCL relies on:</strong></p><ul><li>CUDA-aware MPI or Gloo (PyTorch)</li><li>UCX (Unified Communication X) backend</li></ul><h3>🧰 Practical Setup Steps</h3><ol><li><strong>Ensure you have Mellanox OFED drivers installed</strong></li></ol><ul><li>modprobe mlx5_core</li><li>ethtool -i eth0 to verify kernel driver</li></ul><p><strong>2. Load peer memory kernel modules</strong></p><pre>sudo modprobe nvidia_peermem sudo modprobe ib_core</pre><p><strong>3. Register GPU memory for RDMA</strong></p><pre>cudaMalloc(&amp;buf, size); ibv_reg_mr(..., buf, size, IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_READ | IBV_ACCESS_REMOTE_WRITE);</pre><p><strong>4. Benchmark with </strong><strong>ib_write_bw and NCCL tests</strong></p><pre>ib_write_bw -d mlx5_0 -R -F NCCL_DEBUG=INFO ./nccl-tests/build/all_reduce_perf -b 8M -e 128M -f 2 -g 1</pre><h3>🧪 Debugging Tips</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-U7h9xZrBruKUoEluiIhvA.png" /></figure><h3>📘 Kernel Concepts Worth Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xv7ufmX55X_mlLZN3hpZ0w.png" /></figure><h3>📊 Performance Benchmarks (Typical)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDaM4sCpEqWDoVHMiR_5bg.png" /></figure><blockquote><em>🧠 Pro tip: GPUDirect only works if NIC and GPU are on the same PCIe root complex.</em></blockquote><h3>💡 TL;DR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySVOD1gROK7aPxJ_Cu2rig.png" /></figure><h3>🔜 Coming Next: Part 4 — Linux Kernel Internals for GPU Hacking</h3><p>We’ll open up the kernel toolbox — covering:</p><ul><li>IOMMU groups</li><li>DMA APIs (dma_map_resource())</li><li>PCIe BAR mapping</li><li>VFIO and container passthrough</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=975b81f4987f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gpu-kernel-hacking-for-engineers/part-3-distributed-gpu-communication-with-rdma-nccl-and-gpudirect-975b81f4987f">Part 3: Distributed GPU Communication with RDMA, NCCL, and GPUDirect</a> was originally published in <a href="https://medium.com/gpu-kernel-hacking-for-engineers">GPU Kernel Hacking for Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Inter-GPU Communication with PCIe, NVLink, and BARs]]></title>
            <link>https://medium.com/gpu-kernel-hacking-for-engineers/part-2-inter-gpu-communication-with-pcie-nvlink-and-bars-19c20d367f44?source=rss----3d44069ea69e---4</link>
            <guid isPermaLink="false">https://medium.com/p/19c20d367f44</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[nvlink]]></category>
            <category><![CDATA[p2p]]></category>
            <dc:creator><![CDATA[Nikheel Vishwas Savant]]></dc:creator>
            <pubDate>Mon, 26 May 2025 00:43:32 GMT</pubDate>
            <atom:updated>2025-05-26T00:43:22.030Z</atom:updated>
            <content:encoded><![CDATA[<p>In Part 1, we explored how threads inside a single GPU communicate using warps, shared memory, and barriers. But what happens when your kernel needs <strong>multiple GPUs to work together</strong>?</p><p>Welcome to <strong>inter-GPU communication</strong> — where data moves across PCIe lanes, memory regions are shared using BARs, and modern interconnects like <strong>NVLink</strong> unlock massive bandwidth for deep learning workloads.</p><p>If you’re building multi-GPU systems for AI, scientific computing, or 3D rendering, understanding the <strong>hardware pathways and kernel interfaces</strong> between GPUs is essential.</p><h3>🖥️ How GPUs Communicate Within a System</h3><p>When two or more GPUs are connected to the same host, they can interact in a few ways:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ap8tCocHsozBmyqJTfRSmQ.png" /></figure><blockquote><em>🧠 </em><strong><em>Your performance depends on avoiding CPU mediation</em></strong><em> and going full P2P or NVLink where possible.</em></blockquote><h3>🚇 PCIe: The Legacy Workhorse</h3><p>All GPUs communicate with the CPU via <strong>PCI Express</strong> (PCIe), a serial expansion bus.</p><ul><li>Most systems today use <strong>PCIe Gen 4 or Gen 5</strong></li><li>Each x16 slot provides up to <strong>32 GB/s (Gen 4)</strong> or <strong>64 GB/s (Gen 5)</strong> bidirectional</li></ul><h3>Linux Kernel Interfaces</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlZgYJCpkDyGQfpnPXHsWQ.png" /></figure><blockquote><em>Try: </em><em>lspci -vvv | grep -i nvidia to inspect link speed, width, and BARs.</em></blockquote><h3>🔁 Peer-to-Peer (P2P) GPU Communication</h3><p>P2P allows one GPU to <strong>read/write directly</strong> into another GPU’s memory — bypassing the CPU.</p><pre>cudaDeviceEnablePeerAccess(peer_device_id, 0);<br>cudaMemcpyPeer(...);</pre><p><strong>Requirements</strong>:</p><ul><li>Both GPUs must support P2P.</li><li>Must be in the <strong>same I/O hub domain</strong> (check with nvidia-smi topo -m).</li></ul><h3>What’s Happening Under the Hood?</h3><ul><li><strong>IOMMU and BAR windows</strong> expose one GPU’s memory into another’s address space.</li><li>Kernel sets up <strong>page table entries</strong> and <strong>address remapping</strong> via vfio, nvidia-uvm, and dma_map_resource().</li></ul><h3>🧠 NVLink: High-Speed GPU Interconnect</h3><p><strong>NVLink</strong> is NVIDIA’s proprietary interconnect with <strong>up to 300 GB/s bidirectional bandwidth</strong> (vs 64 GB/s for PCIe Gen 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-V7xG1dyJEE-WMnGC9QTxQ.png" /></figure><h3>Linux Kernel Involvement</h3><ul><li>Memory windows mapped via <strong>BAR1/BAR2</strong></li><li>nvidia.ko and nvidia_uvm.ko coordinate inter-device mappings</li><li>Data can be copied via <strong>DMA engines</strong> or <strong>memory aliasing</strong></li></ul><p>Use nvidia-smi topo -m to visualize NVLink connectivity.</p><h3>🔍 Understanding BARs (Base Address Registers)</h3><p>BARs define <strong>memory-mapped regions</strong> exposed by PCIe devices. For GPUs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0kAfyac4ZRwta7LgmrtpQ.png" /></figure><h3>Kernel Drivers and BAR Access</h3><ul><li>vfio-pci and nvidia.ko use <strong>BAR mappings</strong> to expose memory regions</li><li>Use /proc/iomem and lspci -vv to see their layout</li><li>Memory must be <strong>pinned</strong> and mapped with get_user_pages() or dma_map_resource()</li></ul><blockquote><em>🧠 DMA transfers between BAR1 of GPU A and BAR1 of GPU B can bypass the CPU entirely.</em></blockquote><h3>🧰 Debugging Inter-GPU Access</h3><p>Try these tools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ible5BGmUffts16xn9DWZA.png" /></figure><h3>🧪 Mini Lab: P2P Bandwidth Measurement</h3><pre>cudaMemcpyPeer(dst_ptr, dst_gpu, src_ptr, src_gpu, size);<br>cudaEventRecord(...);</pre><p>Run this benchmark:</p><ul><li>With cudaMemcpy() via host memory</li><li>With cudaMemcpyPeer() between GPUs</li><li>With NVLink-enabled GPUs</li></ul><p>Compare:</p><ul><li>Bandwidth (GB/s)</li><li>Latency (µs)</li></ul><h3>🔄 Synchronization Considerations</h3><p>Inter-GPU transfers are <strong>asynchronous</strong>, meaning you must sync:</p><pre>cudaDeviceSynchronize(); // Or cudaStreamSynchronize()</pre><p>Also ensure:</p><ul><li>Memory is allocated with cudaMalloc() or cudaMallocManaged()</li><li>Peer access is explicitly enabled</li></ul><h3>🧠 TL;DR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpieDvYk4OAEVagOfOEPew.png" /></figure><h3>P2P🔜 Coming Next: Part 3 — Distributed GPU Communication: RDMA, NCCL, and GPUDirect</h3><p>We’ll cover cross-node GPU data transfer, RDMA verbs, GPUDirect memory access, and kernel-level modules that make distributed AI fly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c20d367f44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gpu-kernel-hacking-for-engineers/part-2-inter-gpu-communication-with-pcie-nvlink-and-bars-19c20d367f44">Part 2: Inter-GPU Communication with PCIe, NVLink, and BARs</a> was originally published in <a href="https://medium.com/gpu-kernel-hacking-for-engineers">GPU Kernel Hacking for Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Intra-GPU Communication]]></title>
            <link>https://medium.com/gpu-kernel-hacking-for-engineers/part-1-intra-gpu-communication-3d61838ff847?source=rss----3d44069ea69e---4</link>
            <guid isPermaLink="false">https://medium.com/p/3d61838ff847</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <dc:creator><![CDATA[Nikheel Vishwas Savant]]></dc:creator>
            <pubDate>Mon, 26 May 2025 00:37:11 GMT</pubDate>
            <atom:updated>2025-05-26T00:36:58.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern GPUs aren’t just fast — they’re <em>parallelism monsters</em>. With thousands of threads executing simultaneously, effective <strong>intra-GPU communication</strong> is what separates a naïve kernel from an optimized one.</p><p>This post kicks off the series by exploring <strong>thread coordination</strong>, <strong>shared memory</strong>, <strong>warp-level primitives</strong>, and what every systems engineer should know to unlock performance within a single GPU.</p><h3>🧠 Why Intra-GPU Communication Matters</h3><p>Each GPU has multiple <strong>Streaming Multiprocessors (SMs)</strong>, and each SM executes <strong>warps</strong> (groups of 32 threads). These warps operate on independent data, but often need to share intermediate values.</p><p>Inefficient communication means:</p><ul><li>🔁 Redundant memory accesses</li><li>❌ Thread divergence</li><li>🐌 L2 cache thrashing</li></ul><p>Understanding <strong>how</strong> and <strong>where</strong> to communicate makes the difference between a sluggish kernel and a finely tuned compute engine.</p><h3>🧩 Levels of Intra-GPU Communication</h3><p>Here’s how communication looks inside a GPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*algTnQdBiPVZ4QkuBSTA0A.png" /></figure><p>Let’s break them down.</p><h3>🔄 Register-Level: The Ultimate Locality</h3><p>Registers are the <strong>fastest memory</strong> available to a thread.</p><p>Each thread gets its own register file. No communication between threads happens here — but understanding register pressure is crucial. Too many register allocations can <strong>reduce occupancy</strong> (fewer threads per SM).</p><p>Use nvcc --ptxas-options=-v to inspect register usage per kernel.</p><h3>🔀 Warp-Level Primitives: __shfl_sync</h3><p>When you want threads in the <strong>same warp</strong> to exchange values <strong>without shared memory</strong>, you use <strong>shuffle instructions</strong>.</p><pre>__device__ int warp_add(int value) {<br>    for (int offset = 16; offset &gt; 0; offset /= 2)<br>        value += __shfl_down_sync(0xffffffff, value, offset);<br>    return value;<br>}</pre><ul><li>Fast</li><li>No bank conflicts</li><li>Sits at the instruction level (SHFL in SASS)</li><li>Ideal for reductions, broadcasts, and prefix sums</li></ul><blockquote><em>🧠 Tip: Works only </em>within<em> a warp. No sync across warps.</em></blockquote><h3>📦 Shared Memory: The Block’s Scratchpad</h3><p>Shared memory is a <strong>low-latency memory block</strong> (typically 48 KB per SM) that’s accessible to <strong>all threads within a block</strong>.</p><pre>__shared__ int buffer[256];<br>buffer[threadIdx.x] = threadIdx.x;<br>__syncthreads(); // Barrier</pre><p><strong>Best Use Cases</strong>:</p><ul><li>Block-level reductions</li><li>Matrix tile reuse</li><li>Histogram or scan accumulators</li></ul><h3>⚠️ Pitfalls:</h3><ul><li>Bank conflicts: Accesses to the same memory bank slow performance.</li><li>Occupancy trade-offs: More shared memory used → fewer blocks can run concurrently.</li></ul><p>Use cudaFuncSetAttribute() or __launch_bounds__() to control this.</p><h3>🧵 Synchronization and Barriers</h3><p>Inside a block, you <strong>must</strong> synchronize threads when they share memory:</p><pre>__syncthreads(); // All threads wait here</pre><p>Missing this can cause:</p><ul><li>Race conditions</li><li>Read-after-write hazards</li><li>Divergent execution paths</li></ul><blockquote><em>🧠 Use </em><em>__syncwarp() for intra-warp barriers.</em></blockquote><h3>🐌 Global Memory: The Communication of Last Resort</h3><p>All threads can access global memory, but it comes with a cost: <strong>400–800 clock cycles</strong> on average.</p><p>Use global memory communication sparingly. When you do, optimize:</p><ul><li><strong>Access patterns</strong> (coalesced reads/writes)</li><li><strong>Memory alignment</strong></li><li><strong>Use of caches</strong></li></ul><h3>🔧 Kernel Debugging &amp; Analysis Tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDnPGi9FXCgB71c-Oq20xw.png" /></figure><h3>🧪 Mini Lab: Warp-Optimized Reduction</h3><p>Try this code snippet:</p><pre>__device__ float warpReduce(float val) {<br>    for (int offset = 16; offset &gt; 0; offset /= 2)<br>        val += __shfl_down_sync(0xffffffff, val, offset);<br>    return val;<br>}</pre><p>Benchmark it against:</p><ol><li>Shared memory version</li><li>Global memory atomic reduction</li></ol><p>Observe:</p><ul><li>Execution time</li><li>Occupancy</li><li>DRAM traffic</li></ul><h3>📘 What to Read Next</h3><ul><li><a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#memory-hierarchy">CUDA Programming Guide — Memory Model</a></li><li><a href="https://github.com/NVIDIA/cuda-samples">SASS by Example</a></li><li><a href="https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/">Parallel For All — Shuffle Instructions Deep Dive</a></li></ul><h3>💡 TL;DR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnT5nTb9ZOZTADxr9PZATw.png" /></figure><h3>🔜 Coming Next: Part 2 — Inter-GPU Communication with PCIe, NVLink, and BARs</h3><p>Want to see how GPUs talk to each other across buses, BARs, and memory windows? Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d61838ff847" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gpu-kernel-hacking-for-engineers/part-1-intra-gpu-communication-3d61838ff847">Part 1: Intra-GPU Communication</a> was originally published in <a href="https://medium.com/gpu-kernel-hacking-for-engineers">GPU Kernel Hacking for Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>