<?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[Stories by Rustam on Medium]]></title>
        <description><![CDATA[Stories by Rustam on Medium]]></description>
        <link>https://medium.com/@fatlip?source=rss-c1d27b6b62ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DDLdCKSmupZAnYzRDVXTVw.png</url>
            <title>Stories by Rustam on Medium</title>
            <link>https://medium.com/@fatlip?source=rss-c1d27b6b62ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:43:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fatlip/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Graph-based SLAM basics]]></title>
            <link>https://medium.com/@fatlip/graph-based-slam-basics-f84501525f24?source=rss-c1d27b6b62ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/f84501525f24</guid>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[aml]]></category>
            <dc:creator><![CDATA[Rustam]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 14:27:45 GMT</pubDate>
            <atom:updated>2024-08-07T09:40:55.375Z</atom:updated>
            <content:encoded><![CDATA[<p>Simultaneous Localization and Mapping (SLAM) is the computational problem of constructing or updating a map of an unknown environment while simultaneously keeping track of an <em>robots</em> location within it.</p><p><strong>Graph-based SLAM</strong> represents the problem as a graph, where nodes correspond to robot poses and landmarks, and edges represent constraints between poses and landmarks based on sensor measurements. Accurate and flexible representation of the environment. Handles loop closures effectively. We will discuss this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sp3sJqf4rKjUzqw0LPvC0A.png" /><figcaption>Graph based SLAM example</figcaption></figure><h3>Background</h3><h4>1. Error function</h4><p>The error function quantifies the deviation between predicted and observed measurements. It represents how well the model’s predictions align with actual sensor data. The types of measurements for which the error function can be computed include:</p><ul><li><strong>Odometry Values:</strong> Errors in the estimated motion of the robot based on wheel encoders or inertial sensors.</li><li><strong>Range and Angle Measurements (LiDAR):</strong> Differences between predicted and observed distances and angles from LiDAR scans.</li><li><strong>Reprojection Error (Visual Landmarks):</strong> Errors between the observed positions of visual landmarks in images and their projected positions based on the estimated camera pose.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*AGvYZFNjWh3I4J01aPTLOQ.png" /></figure><ul><li><em>i,j — </em>pair of position or landmark ids within an edge</li><li>eᵢⱼ represents the error between the predicted and observed measurements: eᵢⱼ = predicted —observed</li><li>Ωᵢⱼ -​ is the<strong><em> information matrix</em></strong> (inverse of the covariance matrix). It is a crucial parameter in SLAM that significantly impacts the problem-solving process. A higher value in the information matrix indicates greater confidence in the corresponding measurement and therefore has a higher impact on the result deltas.</li></ul><p>The goal is to minimize the function <em>F​(x)</em>, which represents the sum of squared errors weighted by their information matrices. This minimization leads to finding the best estimate of the state variables <em>x</em>.</p><h4>2. Matrix H and vector b</h4><p>To minimize the error, we approximate the error function using its first-order Taylor expansion around the current initial guess <em>x</em>. This simplifies the optimization problem into a more tractable form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EHrD1PmlRpLGmmmq-NZig.png" /><figcaption>source: <a href="http://www2.informatik.uni-freiburg.de/~stachnis/pdf/grisetti10titsmag.pdf">http://www2.informatik.uni-freiburg.de/~stachnis/pdf/grisetti10titsmag.pdf</a></figcaption></figure><p>Where:</p><ul><li>c = eᵗe —ignore this term as it is constant and doesn’t depend on Δx</li><li>b = Je</li><li>H = JᵗJ</li></ul><p>After some manipulations:</p><ul><li><em>∇F(x+Δx) = 2b + 2HΔx</em></li><li><em>2b + 2HΔx = 0</em></li><li><strong><em>HΔx = -b &lt;— solve it</em></strong></li></ul><p>where:</p><ul><li><strong>H is a symmetric, sparse and block diagonal matrix</strong>, that represents a local approximation of the curvature around the current estimate.</li><li><strong>b is a vector</strong>, that represents the gradient of the cost function at the current estimate.</li></ul><p><strong>H </strong>and<strong> b</strong> work together to provide a local approximation of the optimization problem around a given point. This approximation is then used to iteratively improve the solution.</p><h4>3. Building H and b</h4><p>Dimension of a H matrix:</p><ul><li><strong>pc</strong> = <strong>positions_count</strong> * <strong>state_dimension</strong> (3 for 2d: [x, y, theta])</li><li><strong>lc</strong> = <strong>landmarks_count</strong> * <strong>landmarks_dimension</strong> (2 for 2d: [x, y])</li><li>Total: H = (pc + lc, pc + lc)</li></ul><p>Dimension of a vector b:</p><ul><li>b = (pc + lc, 1)</li></ul><ol><li><strong>Odometry edge:</strong></li></ol><ul><li>A = Jacobian of error respect to Pos1. 3x3. AA = transpose(A) * Ω * A</li><li>B = Jacobian of error respect to Pos2. 3x3. BB = transpose(B) * Ω * B</li><li>err = error vector (3x1, [x, y, theta])</li></ul><p>2D example: <strong>filling H and b for 2 positions and 2 landmarks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gAbhxhsOpYKMSI8WI6dIg.png" /><figcaption>Pos1 — Pos2</figcaption></figure><p>2. <strong>Landmark edge:</strong></p><ul><li>A = Jacobian of error respect to Pos1. 2x3.</li><li>B = Jacobian of error respect to Landmark1. 2x2.</li><li>err = error vector (2x1, [lm_x, lm_y])</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYnP1nw-rIx6DtGth8Zcdw.png" /><figcaption>Pos1 — Lm1</figcaption></figure><p>3. <strong>Landmark edge:</strong></p><ul><li>A = Jacobian of error respect to Pos1. 2x3.</li><li>B = Jacobian of error respect to Landmark2. 2x2.</li><li>err = error vector (2x1, [lm_x, lm_y])</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLedFgrHFjNb9TH5GHkwMA.png" /><figcaption>Pos1 — Lm2</figcaption></figure><p>etc…</p><blockquote>To build H, each matrix (A and B) should be multiplied by an Information matrix:</blockquote><pre>index1 = index of vertex 1 (robot pos or lm)<br>index2 = index of vertex 2 (robot pos or lm)<br>H[index1:index1 + STATE_SIZE, index1:index1 + STATE_SIZE] += A.T @ INF @ A<br>H[index2:index2 + LM_SIZE, index2:index2 + LM_SIZE] += B.T @ INF @ B<br>H[index1:index1 + STATE_SIZE, index2:index2 + LM_SIZE] += A.T @ INF @ B<br>H[index2:index2 + LM_SIZE, index1:index1 + STATE_SIZE] += B.T @ INF @ A<br>b[index1:index1 + STATE_SIZE] += A.T @ INF_W<br>b[index2:index2 + LM_SIZE] += B.T @ INF_W</pre><p>where:</p><ul><li>INF — information matrix</li><li>INF_W — information matrix * error vector</li></ul><h4>4.<strong> Some other types of edges:</strong></h4><ul><li><strong>Loop Closure Edge:</strong> Represents a constraint between two poses that are the same location but observed at different times, helping to correct drift over time.</li><li><strong>Virtual Edge:</strong> Used to model constraints or observations that are not directly measured but are inferred from other data.</li></ul><h4>5. Solving HΔx = -b</h4><p>Solve this equation using your favorite approach like Gauss-Newton or Levenberg-Marquardt:</p><pre>dx = solve(H_regularized, -b)<br>dx *= lr</pre><p><strong>5.1</strong>. <strong>Regularization.</strong> If <em>H</em> is not invertible (i.e., it is singular or nearly singular), solving HΔx = -b becomes problematic. Regularization adds a term to H to ensure it remains invertible and stable.</p><p><strong>Example:</strong> adding a term proportional to the identity matrix λI to the matrix H. The modified matrix becomes H+λI, where λ is a regularization parameter:</p><ul><li><strong>Prevents Singularities:</strong> Ensures that H is always invertible, thus avoiding numerical issues.</li><li><strong>Improves Stability:</strong> Stabilizes the optimization process by smoothing out large fluctuations and avoiding overfitting to noisy data.</li></ul><p><strong>5.2. Robust kernel</strong>. Using robust error functions, also known as robust kernels, can enhance optimization performance by reducing the influence of outliers or noisy data. Unlike standard least squares methods, which can be overly sensitive to large errors, robust error functions provide a more stable solution.</p><p><strong>Example:</strong></p><ul><li><strong>Huber Loss:</strong> Combines squared loss and absolute loss to handle small and large errors differently. It behaves like squared loss for small errors and like absolute loss for large errors, making it less sensitive to outliers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GmSGe7rlo47RghUamyPx7Q.png" /><figcaption>From wiki. Huber loss (green, δ = 1) vs Squared loss (blue)</figcaption></figure><p><strong>5.3. Learning rate. </strong>Controls how much the model parameters are updated in each iteration. Proper tuning of the learning rate can significantly impact the convergence of the optimization function.</p><p><strong>Effects of Learning Rate:</strong></p><ul><li><strong>Lower Value:</strong> Results in slower but more stable convergence. A smaller learning rate ensures that the updates are smaller, reducing the risk of overshooting the minimum.</li><li><strong>Higher Value:</strong> Speeds up convergence but can cause fluctuations in the error function. A larger learning rate might accelerate the optimization but risks instability and oscillations.</li></ul><h4>6. Updating step</h4><p>Update state variables using calculated delta:</p><pre>for pos_id in range(pos_count):<br>    index = pos_id * STATE_SIZE<br>    delta = dx[index:index + STATE_SIZE]<br>    self.graph.positions[pos_id] = \<br>        update_pos(self.graph.positions[pos_id], dd)</pre><pre>for lm_id in self.graph.landmarks:<br>    index = pos_count * STATE_SIZE + lm_id * LM_SIZE<br>    delta = dx[index:index + LM_SIZE]<br>    self.graph.landmarks[lm_id] += delta</pre><h3>Pros and cons Graph-Based SLAM</h3><h4>Pros:</h4><ul><li><strong>Flexibility and Scalability: </strong>Graph-based SLAM can handle large-scale environments efficiently because it can manage a large number of poses and landmarks without significant performance degradation.</li><li><strong>Flexible Representation:</strong> It can incorporate various types of constraints and measurements (e.g., odometry, LiDAR, visual landmarks) seamlessly.</li><li><strong>Global Optimization:</strong> By optimizing the entire graph, graph-based SLAM can provide globally consistent maps. This reduces the accumulation of errors over time, a common issue in sequential methods.</li><li><strong>Loop Closure Handling:</strong> It effectively handles loop closures, which are critical for correcting accumulated drift and improving map accuracy.</li><li><strong>Separation of Concerns:</strong> The separation between the front-end (sensor data processing and graph construction) and the back-end (graph optimization) allows for independent improvements and optimizations of each component.</li></ul><h3>Cons of Graph-Based SLAM</h3><ul><li><strong>High Computational Cost:</strong> The global optimization step can be computationally intensive, especially for very large graphs. It requires efficient algorithms and significant computational resources.</li><li><strong>Memory Consumption:</strong> Managing and storing large graphs can be memory-intensive, particularly in long-term mapping scenarios.</li><li><strong>Need for Good Initial Guess:</strong> Graph-based SLAM often requires a good initial guess for the optimization to converge to the correct solution. Poor initial estimates can lead to suboptimal results or convergence issues.</li><li><strong>Complex Implementation:</strong> Implementing a graph-based SLAM system can be complex and requires a deep understanding of both the graph theory and optimization techniques.</li><li><strong>Real-Time Constraints:</strong> Achieving real-time performance can be challenging due to the computational demands of graph optimization, especially in dynamic environments with frequent updates.</li></ul><h3>Implementation</h3><p>You can find a python implementation from scratch (w/o any additional libraries except numpy) here: <a href="https://github.com/fatlipp/ToySlam">https://github.com/fatlipp/ToySlam</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4P_gc_cjAfuux1XVGV5FA.png" /></figure><h3>Conclusion</h3><p>Thanks for reading, if you like this article, don’t forget to clap and subscribe :)</p><h3>Resources</h3><p><a href="http://www2.informatik.uni-freiburg.de/~stachnis/pdf/grisetti10titsmag.pdf">http://www2.informatik.uni-freiburg.de/~stachnis/pdf/grisetti10titsmag.pdf</a></p><p><a href="https://mengwenhe-cmu.github.io/Reading-Reports/Research/Localization/Graph_Optimization/g2o_A_General_Framework_for_Graph_Optimization/paper.pdf">https://mengwenhe-cmu.github.io/Reading-Reports/Research/Localization/Graph_Optimization/g2o_A_General_Framework_for_Graph_Optimization/paper.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f84501525f24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CUDA: Shared memory]]></title>
            <link>https://medium.com/@fatlip/cuda-shared-memory-23cd1a0d4e39?source=rss-c1d27b6b62ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/23cd1a0d4e39</guid>
            <category><![CDATA[memories]]></category>
            <category><![CDATA[shared-memory]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[nvidia]]></category>
            <dc:creator><![CDATA[Rustam]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 18:33:55 GMT</pubDate>
            <atom:updated>2024-04-04T18:34:41.001Z</atom:updated>
            <content:encoded><![CDATA[<p>CUDA shared memory is a type of memory accessible to all threads within the same block. It resides on the GPU chip itself, making it significantly faster to access compared to off-chip global memory.</p><p>Memory size depends on a GPU architecture and configuration. For example, in a GPU (compute capability 8.6), based on the Ampere architecture, the shared memory capacity per <em>SM</em> is up to 100 KB and maximum shared memory per <em>thread block</em> is 99 KB.</p><blockquote>The maximum amount of shared memory available per thread block is typically smaller than the maximum shared memory partition available per Streaming Multiprocessor (SM). 1 KB of Shared Memory is reserved for system use and is not made available to thread blocks.</blockquote><h4>Dynamic &amp; Static</h4><ul><li>The size of <strong>Statically</strong> allocated shared memory is known at compile time and remains constant throughout the execution of the kernel. <em>(Probably </em>may provide better performance as the compiler can optimize memory access patterns more effectively)</li></ul><pre>__shared__ int sharedMem[256];</pre><p>But static memory allocation has a restriction: one cannot allocate over 48KB of Shared Memory, it will lead to compile time error: “uses too much shared data”.</p><ul><li>To allocate memory a size is not known at compile time, one should use <strong>Dynamic Shared Memory</strong>. CUDA only supports a single dynamic allocation per block. This means that within a kernel, you should use extern __shared__ only once per block.</li></ul><p>If you need multiple dynamically allocated memory regions within a block, you must use pointers to offsets within a single shared memory allocation.</p><pre>// kernel<br>extern __shared__ int sharedMem[];<br>int* v1 = &amp;sharedMem[0];<br>int* v2 = &amp;sharedMem[10];<br>...<br><br>// specify a memory size as the 3rd parameter on kernel launch<br>kernel&lt;&lt;&lt;BLOCKS, THREADS, 20 * sizeof(int)&gt;&gt;&gt;(...);</pre><p>Also, if you need <strong>over 48KB</strong> dynamic Shared Memory, you need to call a method cudaFuncSetAttribute before launching a kernel:</p><pre>cudaFuncSetAttribute(KERNEL, <br>  cudaFuncAttributeMaxDynamicSharedMemorySize, <br>  SIZE);</pre><ul><li>KERNEL — kernel name</li><li>SIZE — size of shared memory in bytes per block (up to shared memory capacity per <em>SM</em>)</li></ul><h4>Occupancy</h4><p>When configuring an application, it’s crucial to consider the resources available on each Streaming Multiprocessor (SM). One important resource to manage is a Shared memory, which is distributed among thread blocks residing in the SM. If a thread block requires more shared memory than is available on an SM, that block won’t be scheduled and will wait for the first free SM where it can reside.</p><h4>Warp &amp; Banks</h4><p>Shared memory in CUDA consists of 32 <em>banks</em>, organized such that successive 32-bit words map to successive banks. Each bank has a bandwidth of 32 bits per clock cycle.</p><p>A <em>warp</em> is a group of 32 threads within the same thread block. When a thread attempts to access shared memory, the access pattern across the threads in the warp can impact memory performance due to bank conflicts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xF2UwJIMb4-qxwfctwzzmw.png" /></figure><h4>Bank Conflict</h4><blockquote>A bank conflict can occur only in the same warp</blockquote><p>A bank conflict occurs when multiple threads within the same warp attempt to access memory locations that belong to the same memory bank simultaneously. This can lead to serialization of memory accesses, reducing memory bandwidth utilization and <em>potentially</em> slowing down the kernel’s performance.</p><p>Example (8 banks, warp size = 8, data size = 2x8):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vByyNkrJpygkyYPS3Qf6PQ.png" /></figure><p>To fix it when accessing a 2D array by column, we can add an extra column to the matrix. While this column doesn’t contain useful data for our calculations, it helps to ensure that each thread within a warp accesses data from different memory banks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFauKFFQ6Hcc5h8S0IpSeg.png" /></figure><h4>Nvidia Nsight</h4><p>A simple example, that attempts to access to columns with a stride = 8:</p><pre>sharedData[block.thread_rank() * 8] += data[globalId];</pre><p>You can detect and analyze bank conflicts using Nvidia Nsight Compute. In the image below, you can observe that the source code exhibits 8-way bank conflicts, meaning each thread in a warp accesses to some banks 8 times. This results in increased load/store <em>wavefronts</em>, causing serialization and processing on different cycles, each occurring 8 times.</p><blockquote><strong><em>Wavefront</em></strong> is the maximum unit that can pass through that pipeline stage per cycle. If not all cache lines or sectors can be accessed in a single wavefront, multiple wavefronts are created and sent for processing one by one, i.e. in a serialized manner</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkI791G6_UxcyhZvHpbD-A.png" /><figcaption>Not OK — 896.000 BC’s</figcaption></figure><p>A fixed code block:</p><pre>sharedData[block.thread_rank()] += data[globalId];</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXd7GYq1PLSYZ_b02kGHog.png" /><figcaption>OK — no BC’s</figcaption></figure><h4>Broadcasting</h4><p>When 2 or more threads in a warp access to the same address in a bank, it will not result in a bank conflict. The data will be broadcasted with no affect to the performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgGIJzYWXTnchGzf4VcwRQ.png" /></figure><h4>More than the word size</h4><p>When dealing with data elements larger than the word size (4 bytes), such as double precision floating-point numbers (8 bytes), the hardware still needs to ensure proper access to the data, and this may involve multiple <em>transactions</em>. Each transaction fetches a chunk of data, often referred to as a “cache line” or “coalesced access unit.”</p><p>You don’t need to care about that, hardware will do it itself.</p><p>The same applies if the data size is less than the word size (&lt; 32 bits).</p><h4>L1/Shared Memory</h4><p>Shared Memory shares on-chip storage with the L1 cache. But Shared memory is explicitly controlled by the programmer and used for inter-thread communication and data sharing, while the L1 cache is managed by the GPU hardware and helps improve memory access latency and bandwidth by caching data and instructions fetched from global memory.</p><p>CUDA provides an API to set the <em>carveout</em>, i.e., the <em>preferred</em> shared memory capacity:</p><pre>cudaFuncSetAttribute(kernel_name, <br>  cudaFuncAttributePreferredSharedMemoryCarveout, <br>  carveout);</pre><p>It is considered a hint by the driver, it may choose a different configuration, if needed. The driver may choose a different configuration if required to execute the function or to avoid thrashing. Don’t use it if you are not sure, increasing carveout <em>may</em> lead to decreasing L1 hit rate, consequently — result in a worse performance.</p><h3>Conclusion</h3><p>Thanks for reading, feel free to comment with corrections or ideas. And don’t forget to clap if you like this article :)</p><h3>References</h3><p><a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capability-8-x">https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html</a></p><p><a href="https://docs.nvidia.com/cuda/ampere-tuning-guide/index.html">NVIDIA Ampere GPU Architecture Tuning Guide</a></p><p><a href="https://docs.nvidia.com/nsight-compute/ProfilingGuide/">https://docs.nvidia.com/nsight-compute</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23cd1a0d4e39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CUDA: QuadTree & Octree, p.1]]></title>
            <link>https://medium.com/@fatlip/cuda-quadtree-octree-72e65216866c?source=rss-c1d27b6b62ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/72e65216866c</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[quadtree]]></category>
            <dc:creator><![CDATA[Rustam]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 20:28:25 GMT</pubDate>
            <atom:updated>2024-03-23T18:40:39.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UP97xZj67E-q1S-u-qzV9A.png" /><figcaption><a href="https://www.open3d.org/docs/release/tutorial/geometry/octree.html">https://www.open3d.org/docs/release/tutorial/geometry/octree.html</a></figcaption></figure><p><strong>Octree</strong> is a hierarchical tree structure where each internal node has exactly eight children. The octree is primarily used to partition three-dimensional space recursively into smaller and smaller regions.</p><h4>QuadTree</h4><p>Let’s use a QuadTree as an example, as it is easier to visualize, and an Octree is simply a 3D extension of it.</p><p>A tree view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zlw8dCvZI7naF0Bs5WJf7Q.png" /></figure><p>A space partition view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oyn6q_GRnDNCsWzUUiPekQ.png" /></figure><p>I will not explain how to build it step-by-step, for that you can find tons of great articles. Purpose of this article is how to implement it using Nvidia CUDA.</p><h3>Overview</h3><p>Some of the CUDA features that we will leverage and incorporate into our implementation</p><h4>Dynamic Parallelism</h4><p>Dynamic Parallelism (DP) enables the launching of subkernels from a parent kernel running on the device. However, in the latest versions of CUDA, it’s not possible to synchronize them directly inside a kernel. Nevertheless, it is guaranteed that the main kernel will only exit once all subkernels have completed execution.</p><p>In out example, we can use this feature to execute each leaf in parallel <em>subkernels. </em>Starting from 1 main kernel, that divides a space into 4 subparts, then all of these subspaces will divided in 4 different <em>subkernels</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kc6aD06pEmJp8-qhraRQCA.png" /></figure><p>In the image above, each thread block is associated with a depth of the Tree and its leaves. Additionally, each node, if it contains enough items to divide, initiates four parallel blocks for each sub-partition.</p><h4>Cooperative Groups</h4><p>It allows threads within a block to synchronize and communicate more efficiently compared to traditional synchronization mechanisms like barriers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SWZtzKgr9Voo1Ak2RoF6Q.png" /><figcaption><a href="https://developer.nvidia.com/blog/cooperative-groups/">https://developer.nvidia.com/blog/cooperative-groups/</a></figcaption></figure><p>For a tree implementation, we need:</p><p>auto block = this_thread_block() — is used to obtain a handle to the current CUDA thread block</p><p>auto warp = cg::tiled_partition&lt;32&gt;(block)— to obtain a handle to thread block warps (32 threads)</p><p>Using these 2 variables, it is easy to synchronize and get access to threads in a block.</p><p>Other benefit of Cooperative Groups is that it introduces a more object-oriented programming (OOP) style to your application, providing a higher level of abstraction and organization for managing threads within a block.</p><h4>Warp Shuffle operations</h4><p>ballot(condition) — gives a mask of threads within a warp based on a condition</p><p>shfl(var, targetLaneId) — allows threads within a warp to exchange values with each other. targetLaneId- The source lane within the warp from which to fetch the data. Each thread in the warp specifies the source lane from which it fetches data.</p><p>shfl_up(var, offset) — each thread within the warp retrieves the value from the thread that is a specified number of lanes “up” (towards smaller thread indices) in the warp.</p><p>mask = thisWarp.ballot(CONDITION) — gives a mask of threads within a warp based on a condition. In out case, it will be used to determine, whether a point inside a partucular sub-tree or not.</p><p>More information about shfl in my previous article.</p><h3><strong>Implementation details</strong></h3><h4>Shared memory</h4><p>Shared memory is used to calculate points id’s and offsets within each block, i.e. leaf. Shared Memory size = 4 * warpsPerBlock — for QuadTree and 8 * warpsPerBlock for Octree. (i.e., it is equal to leaves count)</p><h4>Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8__5ItCkgjp-KV1atB6xg.png" /></figure><h4>Offset calculation</h4><p>Offsets contain start positions in side each leaf, where we should store points. For example, an image below shows, that the first leaf’s offset started from 0, the second leaf’s — from 18 (i.e. the first leaf contains 18 points), the third leaf’s — 84 (i.e. the second leaf contains 84–18=66 points, the fourth offset also = 84 =&gt; the 3&#39;rd leaf is empty).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*iVVpGNprDWzgquhoa2m0PA.png" /></figure><ol><li><strong>Each warp</strong> within a block will calculate points count for each leaf (Top Left, Top Right, Bottom Left, Bottom Right).</li></ol><pre>for (int i = startId + thisWarp.thread_rank(); <br>     thisWarp.any(i &lt; endId);<br>     i += thisWarp.size())<br>{<br>  const auto isInRange = i &lt; endId;<br>  const auto point = isInRange ? pointsExch[i] : float2{-1, -1};<br><br>  const auto isUpLeft = isInRange &amp;&amp; point.x &lt;= center.x &amp;&amp; point.y &gt; center.y;<br>  pointsInCellLocal[0] += __popc(thisWarp.ballot(isUpLeft));<br><br>  const auto isUpRight = isInRange &amp;&amp; point.x &gt; center.x &amp;&amp; point.y &gt; center.y;<br>  pointsInCellLocal[1] += __popc(thisWarp.ballot(isUpRight));<br><br>  ...<br>}</pre><p>mask = thisWarp.ballot(isUpLeft) — gives a mask of threads within a warp, that have points in a range (UpLeft, UpRight, etc)</p><p>__popc(val) — just return count of 1’s in a binary mask. Each 1 says, that this thread contains a point in the range</p><p>pointsInCellLocal[0] += thisWarp.shfl(summ, 0); — collects count of points, that belongs to the current leaf. The warp shuffle operation efficiently distributes data across threads within a warp and ensures that all threads within a warp are syncronized at this point.</p><blockquote>Important note: in the implementation above we cannot use if condition, for example: if (isInRange) { blabla } in will lead to deadlock on shfl functions.</blockquote><blockquote>Also, it’s important to note that pointsInCellLocal represents a per-warp value. Therefore, we must aggregate the values from each warp to obtain a total count.</blockquote><p>2. So, now that we have determined how many points should be in each leaf, it is time to aggregate these counts together.</p><blockquote>We need at least 4 warps (32 * 4 threads per block) for QuadTree and 8 warps <strong>(32 * 8threads per block)</strong> for Octree implementations. This requirement arises because a warpId is also used to determine a leaf Id within the tree structure. If the number of warps is insufficient, there&#39;s a risk of losing some points during leaf identification.</blockquote><pre>  if (warpId &lt; 4)<br>  {<br>      int totalPointsCountPerCell = thisWarp.thread_rank() &lt; warpsPerBlock<br>                      ? pointsInCell[thisWarp.thread_rank() * 4 + warpId]<br>                      : 0;<br><br>      for (int offset = 1; offset &lt; warpsPerBlock; offset *= 2)<br>      {<br>          int n = thisWarp.shfl_up(totalPointsCountPerCell, offset);<br>          <br>          if (thisWarp.thread_rank() &gt;= offset) <br>              totalPointsCountPerCell += n;<br>      }<br><br>      thisWarp.sync();<br><br>      if (thisWarp.thread_rank() &lt; warpsPerBlock)<br>      {<br>          pointsInCell[thisWarp.thread_rank() * 4 + warpId] = totalPointsCountPerCell;<br>      }<br>  }</pre><p>warpId — a cell id (TL, TR, BL, BR)</p><p>thread_rank — is used as an id for calculated counts per warp in the previous step</p><p>Latest thread will contain actual point counts for each leaf.</p><p>3. After that, you need to calculate <em>offsets </em>for each leaf. I will not explain it here, it is pretty straightforward.</p><h4>Subtree points update</h4><p>There is a somewhat tricky aspect: determining the position of each point within a leaf. To address this, I’ll need to delve into some technical details.</p><pre>for (int i = startId + thisWarp.thread_rank(); <br>       thisWarp.any(i &lt; endId);<br>       i += thisWarp.size())<br>{<br>  const auto isInRange = i &lt; endId;<br><br>  const auto point = isInRange ? pointsExch[i] : float2{};<br><br>  const auto isUpLeft = isInRange &amp;&amp; point.x &lt;= center.x &amp;&amp; point.y &gt; center.y;<br>  const auto mask1 = thisWarp.ballot(isUpLeft);<br>  const auto destId1 = offset1 + __popc(mask1 &amp; lane_mask_lt);<br>  if (isUpLeft)<br>  {<br>      points[destId1] = pointsExch[i];<br>  }<br>  // change offset to add the next pack of points in a correct position<br>  // using `shfl(...)` instead of `__popc(mask)` increases <br>  // performance for Octree<br>  offset1 += thisWarp.shfl(__popc(mask1), 0)<br><br> // same for other leaves<br>...</pre><p>lane_mask_lt — is a mask where the lanes with indices less than a specified value are = 1, and the rest are = 0. This can be used to conditionally activate threads based on the lane index within a warp.</p><pre>const int lane_mask_lt = (1 &lt;&lt; laneId) - 1;</pre><p>laneId — is a threadId within a warp</p><p>Example lane_mask_lt:</p><pre>0: (00000001 &lt;&lt; 0) - 1 = 00000000-1 = 00000000<br>1: (00000001 &lt;&lt; 1) - 1 = 00000010–1 = 00000001<br>2: (00000001 &lt;&lt; 2) - 1 = 00000100–1 = 00000011<br>3: (00000001 &lt;&lt; 3) - 1 = 00001000–1 = 00000111<br>…</pre><p>__popc(val) — just return count of 1’s in a binary number</p><p>mask = thisWarp.ballot(isUpLeft) — gives a mask of threads within a warp, that have points in a range (UPPER_LEFT, UPPER_RIGHT, etc)</p><p>mask &amp; lane_mask_lt — returns a position within a subarray, where a point should be placed.</p><p>offset1(2, 3, 4…) — is just contains amount of points, that belong to a particular leaf. [0–4) for QuadTree and [0–8) for Octree. We calculated it in the previous step.</p><p>mask &amp; lane_mask_lt</p><p>How it works? Let’s imagine we have 10 points, 2 warps (size = 5) and 2 leaves, where we should store each point (<em>green</em> and <em>blue</em> leaves)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*KUdZ7Wy70REGB8_uHSakhA.png" /></figure><p>We need to distribute them into 2 leaves (Green and Blue). We know how to calculate a mask and a mask_lt:</p><p>mask=ballot(isGreen) = 10110</p><p>lane_mask_lt = (1 &lt;&lt; laneId) — 1 = to example above</p><p>Here we have all necessary information and since warps are execution in parallel and synchronized (thanks to ballot).</p><pre>nextItemId: <br>popc(10110 &amp; 00000) = 0 // skip, since we don&#39;t want to store id=4<br>popc(10110 &amp; 00001) = 0 // store<br>popc(10110 &amp; 00011) = 1 // store<br>popc(10110 &amp; 00111) = 2 // skip, since we don&#39;t want to store id=1<br>popc(10110 &amp; 01111) = 2 // store<br><br>same for warp2:<br>...</pre><p>As you can see, each point has consequent id for each <strong><em>active</em></strong> mask. A value will be stored only if it meets conditions (if isGreen = true).</p><p>For a Tree implementation it is more complicated, but idea is the same.</p><h4>Dynamic Parallelism for Subdivision</h4><p>The next step is just subdivision into 4 (8) subtrees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*D7HMxk9T6fL0WTMVANl38w.png" /></figure><h3>Results</h3><p>Octree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlMVzFDatQmwkYyhslpDxw.png" /><figcaption>Airplane</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUmZKLfLnsVcQJNdPCvVcg.png" /><figcaption>10mln 3d random points</figcaption></figure><p>QuadTree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xf5mlXICOOoM9fJbPJ-zsA.png" /><figcaption>10mln 2d random points</figcaption></figure><p>A full source code is available here:</p><p><a href="https://github.com/fatlipp/cuda-tree">GitHub - fatlipp/cuda-tree: CUDA-based Tree builder</a></p><h3>Conclusion</h3><p>I want to emphasize that the underlying implementation idea is inspired by Nvidia’s QuadTree sample (cdpQuadtree)</p><p>Thanks for reading, please feel free to comment with corrections or ideas.</p><h3>Resources</h3><p><a href="https://en.wikipedia.org/wiki/Octree">https://en.wikipedia.org/wiki/Octree</a></p><p><a href="https://developer.nvidia.com/blog/cooperative-groups/">https://developer.nvidia.com/blog/cooperative-groups/</a></p><p><a href="https://developer.nvidia.com/blog/introduction-cuda-dynamic-parallelism/">Adaptive Parallel Computation with CUDA Dynamic Parallelism | NVIDIA Technical Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72e65216866c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CUDA: OpenGL interop]]></title>
            <link>https://medium.com/@fatlip/cuda-opengl-interop-e4edd8727c63?source=rss-c1d27b6b62ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4edd8727c63</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[Rustam]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 18:51:00 GMT</pubDate>
            <atom:updated>2024-09-11T10:46:55.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*dUhZHqz2EBFUJFAJLDvwKQ.png" /></figure><p><strong>OpenGL</strong> is a cross-platform, open-source graphics API that provides a set of functions for rendering 2D and 3D graphics. It is widely used in computer graphics for tasks such as rendering images, animations, and interactive applications, especially in the fields of video games, simulations, and scientific visualization.</p><p><strong>Nvidia CUDA</strong> (Compute Unified Device Architecture) is a parallel computing platform and application programming interface (API) model created by NVIDIA.</p><p><strong>CUDA-OpenGL interop</strong> is a feature that allows seamless communication between CUDA and OpenGL. It can be used for any tasks (e.g. physics simulation, image processing, etc), followed by rendering. Or for algorithms visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Qwdlc0yo-wOlucK_LU9qw.png" /><figcaption>CUDA-Opengl interop</figcaption></figure><h3>Basic concepts</h3><p>In this section I will show basic concepts of using OpenGL interop on an image processing example.</p><p>There are different options to map an image to CUDA:</p><h4>1. Using a TextureObject</h4><p>A TextureObject provides direct access to OpenGL Texture. Also efficent 2D access inside CUDA Kernel using a template method<em> text2D&lt;T&gt;(texture, x, y). </em>It also eliminates the need for copying from PBO to TextureObject on Rendering step. But you need to perform <em>device2device</em> copy from CUDA array to <em>Texture2d</em>.</p><figure><img alt="Device to Device copy" src="https://cdn-images-1.medium.com/max/745/1*ypfLllyNUrn5HQ0FKSK1Mg.png" /><figcaption>CUDA + Texture2d</figcaption></figure><p>An example of creating TextureObject for OpenGL’s Texture2D:</p><pre>// map a texture to CUDA array<br>// cudaTextureObj - registered pointer to OpenGL texture or RB object<br>cudaArray *cudaArray;<br>cudaGraphicsMapResources(1, &amp;cudaTexturePtr, 0);<br>cudaGraphicsSubResourceGetMappedArray(<br>    &amp;cudaArray, cudaTexturePtr, 0, 0);<br><br>// create a cudaTextureObject<br>cudaResourceDesc texRes;<br>memset(&amp;texRes, 0, sizeof(cudaResourceDesc));<br>texRes.resType = cudaResourceTypeArray;<br>texRes.res.array.array = cudaArray;<br><br>cudaTextureDesc texDescr;<br>memset(&amp;texDescr, 0, sizeof(cudaTextureDesc));<br>texDescr.normalizedCoords = false;<br>texDescr.filterMode = cudaFilterModePoint;<br>texDescr.addressMode[0] = cudaAddressModeWrap;<br>texDescr.readMode = cudaReadModeElementType;<br><br>cudaTextureObject_t texObject;<br>cudaCreateTextureObject(&amp;texObject, &amp;texRes, &amp;texDescr, NULL);<br><br>// CUDA kernel:<br>...<br>uchar4 p = tex2D&lt;uchar4&gt;(texObject, x, y);<br>...</pre><p>This object provides read-only access to a Texture. So, if you want to change it, you need to create another buffer, do some changes and perform a <em>device2device</em> copy back to <em>cudaArray</em> like here:</p><pre><br>// imagePrt - is an ptr, that stores a processed data <br>cudaMemcpy2DToArray(cudaArray, 0, 0, imagePrt,<br>                    sizeof(cudaTexturePtr[0]) * width, <br>                    sizeof(cudaTexturePtr[0]) * width, height,<br>                    cudaMemcpyDeviceToDevice);</pre><p>You can transer data from <em>cudaArray</em> to a <em>pointer</em>:</p><pre>// from cudaArray to a 1D raw pointer:<br>uchar4* data;<br>cudaMemcpy2DFromArray(data, sizeof(data[0]) * width, <br>  cudaArray, 0, 0, <br>  sizeof(data[0]) * width, height, cudaMemcpyDeviceToDevice);<br><br>// CUDA kernel:<br>...<br>data[x + w * y] = // change values;<br>...</pre><blockquote>Almost the same pipeline for <strong>RBO</strong> from a CUDA perspective.</blockquote><h4>2. Using a pointer to a PBO</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*qWtvtyGwvosaja2K-vmW3w.png" /><figcaption>CUDA + PBO</figcaption></figure><p>In this case, you can just map as a pointer and get direct access to the PBO:</p><pre>cudaGraphicsMapResources(1, &amp;cudaTexPtr, 0));<br>cudaGraphicsResourceGetMappedPointer(<br>    (void **)&amp;mappedPtr, &amp;numBytes, cudaTexPtr);<br>...<br>// launch kernel and use pointerToPbo toprocess a texture data  <br>...<br>cudaGraphicsUnmapResources(1, &amp;mappedPtr, 0);</pre><p>There is no need to copy the data back to the PBO. But you need to <em>unpack</em> the modified PBO into Texture2D.</p><blockquote>Unpacking — <em>OpenGL’s fast pixel data transfer to and from a graphics card through Direct Memory Access (DMA) without involing CPU.</em></blockquote><pre>glBindTexture(GL_TEXTURE_2D, texture);<br>glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);<br>glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, <br>    GL_RGB, GL_UNSIGNED_BYTE, 0);<br>glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);<br><br>// draw</pre><h4>VBO</h4><p>It is also possible to change the VBO. From a CUDA perspective, this is similar to using PBO with cudaGraphicsResourceGetMappedPointer and no data transfer is required. But the OpenGL part is very different.</p><h3>Pipeline</h3><p>In this section I will explain each step of the OpenGL interop pipeline</p><ul><li><strong>Create an OpenGL context:</strong> Before using, you need to create an OpenGL context using your favourite library, like GLFW, GLUT, SFML, VTK, etc. It could me a bit tricky if you use libraries like SFML. In this case you need to get a pointer to the OpenGL resource, allocated by a library.</li></ul><pre>// SFML<br>sf::Texture texture;<br>if (!texture.loadFromFile(&quot;/image.png&quot;))<br>    return EXIT_FAILURE;<br><br>sf::Sprite image(texture);<br>image.setPosition(sf::Vector2f(screen.size) / 2.f);<br>image.setOrigin(sf::Vector2f(texture.getSize()) / 2.f);<br><br>// get a pointer to Texture2D object via CUDA<br>auto textureHandle = texture.getNativeHandle();<br><br>//----<br>// Pure OpenGL handler to Texture2D<br>GLuint textureHandle;<br>glGenTextures(1, &amp;textureHandle);<br>glBindTexture(GL_TEXTURE_2D, textureHandle);<br>glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA,<br>        GL_UNSIGNED_BYTE, NULL);</pre><ul><li><strong>Initialize CUDA</strong> using the Runtime API. This involves selecting the GPU device, creating a CUDA context, and setting up any necessary configurations, writing a kernel for data processing, etc.</li><li><strong>Register OpenGL buffers </strong>(e.g., PBO, VBO, texture objects) using interop methods to establish a connection between the OpenGL and CUDA contexts. It <em>must</em> be called only once per resource.</li></ul><p>cudaGraphicsGLRegisterBuffer — register OpenGL buffer object, like a VBO, PBO</p><p>cudaGraphicsGLRegisterImage — registers an Texture2d or RenderBuffer object</p><pre>// register an image from prev. step<br>struct cudaGraphicsResource *cudaTexPtr;<br>cudaGraphicsGLRegisterImage(&amp;cudaTexPtr, textureHandle, <br>    GL_TEXTURE_2D, flag);</pre><ul><li><strong>Map</strong> <strong>OpenGL</strong> <strong>resources. </strong>Once a resource is registered, it should be mapped to CUDA pointers to allow CUDA kernels to access and manipulate data stored in OpenGL buffers:</li></ul><pre>cudaGraphicsMapResources(1, &amp;cudaTexPtr, 0);<br><br>cudaArray_t* mappedArray;<br>cudaGraphicsSubResourceGetMappedArray(mappedArray, cudaTexPtr, 0, 0);</pre><p>cudaGraphicsMapResources —maps a graphics resource for access by CUDA and it may be accessed by CUDA until it is unmapped. OpenGL shouldn’t use mapped resource until it is unmapped.</p><blockquote><strong>Limitation</strong>: you cannot map 1 resource twice, until it’s unmapped. But you can map 2 or more different resources and use them in your computations:</blockquote><pre>// Bad:<br>cudaGraphicsMapResources(1, &amp;cudaTexPtr, 0);<br>cudaGraphicsMapResources(1, &amp;cudaTexPtr, 0);<br><br>// Good:<br>cudaGraphicsMapResources(1, &amp;cudaTexPtr, 0);<br>cudaGraphicsMapResources(1, &amp;cudaTexPtr2, 0);</pre><ul><li><strong>After mapping, one need to get a mapped pointer:</strong></li></ul><p>cudaGraphicsResourceGetMappedPointer — get a pointer to the OpenGL mapped resource using cudaGraphicsGLRegisterBuffer. Useful, if you need to access to a buffer, like PBO, VBO, i.e. when structure is not a 2d array.</p><p>cudaGraphicsSubResourceGetMappedArray — get a pointer to the mapped array that got via cudaGraphicsGLRegisterImage.</p><ul><li><strong>Perform computation</strong> on OpenGL-registered buffers, that can be accessed my mappedArray object. As said above, if you want to change a texture, you can create a <em>cudaTextureObject</em>, and get access to a 2D texture using tex2D&lt;T&gt;(tex, x, y)</li><li><strong>Send changes back to an OpenGL buffer:</strong></li></ul><p>For resources, mapped via cudaGraphicsResourceGetMappedPointer , this step can be skipped. For mapped array, one need to copy back to a OpenGL buffer. For example, using cudaMemcpy2DToArray.</p><ul><li><strong>Unmap an OpenGL buffer:</strong> After completing CUDA computations, don’t forget to unmap the OpenGL resources:</li></ul><p>cudaGraphicsUnmapResource(count, ptr, streamID) ensures that the resources are properly synchronized between CUDA and OpenGL contexts. And used to make sure that OpenGL can resume control over the resource.</p><ul><li><strong>Render results using OpenGL: </strong>the results computed by CUDA can be directly visualized using OpenGL. This involves setting up shaders, textures, and other OpenGL rendering techniques to display the computed data.</li></ul><p>In the pipeline above, there were no operations in CPU, except data preparations step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nP6z5P02-taaGInRLlidBA.png" /><figcaption>P.S.: If you use objects like PBO, VBO, device2device copy step must be performed by OpenGL on a DRAW step.</figcaption></figure><h3>Examples</h3><h4>Edge Detection + merging 2 OpenGL textures using CUDA:</h4><ul><li>RGB to Grayscale</li><li>Apply a Sobel kernel</li><li>Merge with another image</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fl39pbIoqTG9PtYdlubF0w.png" /><figcaption>Edge detected in left image merged with another image on the right</figcaption></figure><h4>CUDA Spring + OpenGL VBO:</h4><p>In this example I used CUDA kernel for collision detection and spring calculations and a mapped pointer to a VBO</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fb1TVkWWkOUw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Db1TVkWWkOUw&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb03c6e4024e3c4730482d8541be10b7/href">https://medium.com/media/fb03c6e4024e3c4730482d8541be10b7/href</a></iframe><h4>QuadTree</h4><p>Example of a QuatTree visualization using <em>cudaArray</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*lBaQzz5TVyAgaFJyDi8esg.png" /></figure><h3>Git</h3><p>This repository doesn’t include the examples mentioned above, as I’ve simplified it to make the project easier to understand.</p><p><a href="https://github.com/fatlipp/CUinteropGL">https://github.com/fatlipp/CUinteropGL</a></p><h3>Conclusion</h3><p>Thanks for reading, feel free to comment with corrections or ideas. And don’t forget to clap (up to 50) if you like this article :)</p><h3>References</h3><p><a href="https://www.opengl.org/">https://www.opengl.org</a></p><ul><li><a href="https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__INTEROP.html">CUDA Runtime API :: CUDA Toolkit Documentation</a></li><li><a href="http://www.songho.ca/opengl/gl_pbo.html">OpenGL Pixel Buffer Object (PBO)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4edd8727c63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CUDA Sync & Co.]]></title>
            <link>https://medium.com/@fatlip/cuda-sync-co-b475c3dbd57f?source=rss-c1d27b6b62ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/b475c3dbd57f</guid>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <dc:creator><![CDATA[Rustam]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 19:04:22 GMT</pubDate>
            <atom:updated>2024-05-01T19:10:39.126Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will briefly introduce CUDA device-level synchronization tools, including atomic operations, shfl, and various other synchronization methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*wES9yDxFaPyCRspi8mZ3RQ.jpeg" /></figure><h3>1. Atomic</h3><p>Atomic operations work for both on shared and global memory. It is impossible to use it on local variables, since they are unique for each thread and stored in registers or in a local memory. However, atomic operations are not free, the use of atomic operations introduces a serialization, so that only one thread can perform the atomic operation at a time. When multiple threads attempt to perform an atomic operation on the same memory location concurrently, the hardware ensures that these operations are executed sequentially, one per clock.</p><ul><li>Lets imagine we have a simple CUDA kernel, that runs on 32 threads, that just increases a value of <em>the data:</em></li></ul><pre>__global__ void Kernel(int* data, const uint size)<br>{<br>    data += 1;<br>}</pre><p>In this code block the result is undefined, because each thread will try to access and change a value concurrently. It is impossible to predict the result. So, we need some functionality to change the value safely.</p><p><strong>atomicAdd(address, value)</strong> — performs read-modify-write as a single operation. No one thread can interfere this behavior.</p><p>Code below can fix data-racing problem (let’s close eyes that this code doesn’t make sense in a real application)</p><pre>__global__ void Kernel(int* data, const uint size)<br>{<br>    atomicAdd(&amp;data, 1);<br>}</pre><p><strong>atomicExch(address, value)</strong> — It atomically reads the current value stored at a given <em>address</em>, replaces it with a new <em>value</em>, and returns the old value.</p><pre>int old = atomicExch(&amp;address, 10);<br>// old will store an old value, not necessarily equal to 10</pre><p><strong><em>T atomicCAS(address, compare, newValue)</em></strong><em> — </em>compares a value from <em>address</em> with <em>compare</em>: if <em>old_value == compare</em>, then store newValue in the <em>address</em>, otherwise — doesn’t change anything. In both of cases it returns old value.</p><pre>// Pseudo code<br>atomic<br>{<br>    // 1.<br>    T val = oldValueFromAddress;<br>    <br>    // 2.<br>    if (val == compare)<br>        store a new value in ADDRESS;<br>    <br>    // 3.<br>    return val;<br>}</pre><p><strong>libcu++</strong> — the C++ Standard Library for CUDA, that provides standard C++ features and functionality for GPU programming using CUDA, including atomic.</p><h3>2. Mutex</h3><p>Since CUDA execution is designed for data-parallelism, traditional synchronization mechanisms, such as mutexes, are often not suitable for GPU architectures. But one can implement his own:</p><pre>// function that calls code that changes value in a critical section<br>template &lt;typename F&gt;<br>__device__ void CritialSectionFunc(int* mutex, F func)<br>{<br>    while (atomicExch(mutex, 0) != 1);<br><br>    func();<br>    <br>    atomicExch(mutex, 1);<br>}<br><br>...<br>mutex = 1;// default value<br><br>// a kernel body:<br>auto lambda = [data] __device__ (){ ++data[0]; };<br>CritialSectionFunc(&amp;mutex, lambda);<br>...</pre><p><em>This code will not work on GPU that doesn’t support Independent Thread Scheduling (older than Volta)</em>, because each thread inside the warp will wait for other threads to step forward. SM cannot run each thread independently. In this case you can use this approach:</p><pre>...<br>bool funcCalledInThread = false;<br>while (!funcCalledInThread)<br>{<br>    if (atomicExch(mutex, 0) == 1)<br>    {<br>        func();<br><br>        funcCalledInThread = true;<br><br>        atomicExch(mutex, 1);<br>    }<br>}<br>...</pre><p>In this example code works as expected, because each thread will enter into a while block and try to get a mutex in the loop.</p><blockquote>An important difference between above lock and traditional CPU mutexes is that a CPU uses hardware-level block and a thread will be inactive until a mutex is unlocked.</blockquote><blockquote>But current implementation is an app-level spin-lock and a thread is active and will just waste some GPU resources while waiting. It is better to avoid using them in CUDA and implement lock-free algorithms to achieve coordination without traditional mutexes. Or use built-in mechanisms like __syncthreads or cooperative groups.</blockquote><h3>3. __syncthreads, __threadfence, __syncwarp</h3><p><strong><em>__syncthreads</em></strong> is a synchronization primitive that is used for sync threads within a <em>block</em>. It ensures that all threads within the same block have reached the same point in the execution before any of them proceed further. It <em>can</em> lead to deadlock if you call it inside <em>if </em>statement:</p><pre>...<br>if (threadIdx.x &gt; 32)<br>{<br>    atomicAdd(&amp;globalVar, 1);<br>    __syncthreads(); // don&#39;t use sync here!<br>}<br>__syncthreads();<br>...</pre><p><strong>__threadfence</strong> enforces memory ordering, ensuring that all preceding memory operations issued by a thread are visible to other threads<em> (also in different blocks) </em>before any subsequent memory operations. It adds some kind of a <em>volatile </em>keyword so that memory will not be optimized and cached. But unlike __syncthreads, it doesn’t block a thread block until all threads reach this point, and can call some methods after the keyword, if they don’t need access to the memory blocked by __threadfence.</p><p><strong>__syncwarp — </strong>ensures that all threads within a warp reach a certain point in the execution before any of them proceed further. It helps in coordinating the execution of threads within the same warp. Small example with 1 kernel and 1 warp (32 threads):</p><pre>__shared__ int mutex;<br>mutex = 1;<br>...<br>if (threadIdx.x == 10)<br>{<br>    do0();<br>    data[10] = 1;<br>}<br>// __syncwarp(); // a sync point<br><br>if (data[10] == 1)<br>{<br>  do1();<br>}<br>do2();</pre><p>If __syncwarp is disabled, then most probably some threads will skip if condition. The same principle applies to the other synchronization methods described in this chapter.</p><h3>4. Warp Shuffle Functions</h3><p>__shfl_sync, __shfl_up_sync, __shfl_down_sync and __shfl_xor_sync are used to exchange a variable between threads within a warp. Since the data exchange is performed between registers, it is more efficient than getting value from shared memory, which requires a load, a store and an extra register to hold the address. And in addition, one doesn’t needed to sync threads after these functions.</p><blockquote>1. If the index is out of range, its own value is returned</blockquote><blockquote>2. lane — threadIdx inside a warp (0 — warpSize[32])</blockquote><p><strong>1. __shfl_up_sync, __shfl_down_sync</strong> — take 4 parameters:</p><ul><li><em>mask</em> —described in the next section. By default use -1 or 0xffffffff, i.e. all threads</li><li><em>variable</em> — variable name, that will be used to exchange</li><li><em>delta</em> — offset from caller thread Id (within a warp)</li><li><em>warp size</em> — (default: 32)</li></ul><p>The only one difference between 2 methods is that:</p><ul><li><em>UP</em> — gets value from <em>threadId — delta</em></li><li><em>DOWN — </em>takes value by <em>threadId + delta</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ohrWO0xJbciVUnl4-5wxFg.png" /><figcaption>__shfl_down_sync(mask, val, delta=3)</figcaption></figure><p><strong>2. __shfl_sync</strong> — takes 4 parameters, but <strong><em>srcLane</em> </strong>instead of <strong><em>delta</em>.</strong> This value will be applied for each thread in a warp. For example, if <strong><em>srcLane=0</em>, </strong>then each thread will use variable from <em>lane=0</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*zXuDPg_-xbQkRbZKiqOyDw.png" /><figcaption>__shfl_sync(mask, val, srcLane=0)</figcaption></figure><p><strong>3. </strong><strong>__shfl_xor_sync(mask, var, laneId)</strong> — provides a functionality to get a value using XOR for <em>targetLaneId = laneId ^ mask</em>. For example,</p><ul><li>if <em>laneId=2</em> and <em>mask=4</em>, then <em>targetLaneId = 2^4 =6</em>. =&gt; value will be taken from 6th lane in the warp.</li><li>if <em>laneId=6</em> and <em>mask=4:</em> 6^4 = 2</li><li>Therefore, values between 6th and4th lanes will be exchanged</li></ul><p>It can be used, for example, exchange/get value between pair of threads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hUx_EMStHlIud8cDtBwrBA.png" /><figcaption><strong>__shfl_xor_sync with offset = 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*8AptPJZplpO8Z7GBDuvkuw.png" /><figcaption><strong>__shfl_xor_sync with offset = 2</strong></figcaption></figure><h3>5. Mask</h3><blockquote>Threads can onl yread data from a thread participating in the shuffle command, i.e. the <strong>active</strong> thread. If the target thread is inactive (for example, thread is not under conditional code statement), it will lead to UB. Masks are used to deal with that cases.</blockquote><blockquote>-1 and 0xFFFFFFFF masks mean the same thing — all threads in a warp</blockquote><p><strong>__ballot_sync — </strong>is a function that is used to specify mask for <strong><em>shfl</em></strong> methods. It evaluates a predicate for every active thread within a warp and produces a result, where the <em>i’th</em> bit is set to 1 if the predicate yields a non-zero value for the <em>i’th</em> thread.</p><p>If you call a <em>shfl</em> method in divergent control flow paths, you need to specify a <em>mask</em>, that meets the branch condition. For example, this code will lead to UB:</p><pre>auto var = 1.0f;<br>auto offset = 4;<br>auto mask = 0xFFFFFFFF;<br><br>if (lane % 2 == 1)<br>{<br>  var = __shfl_down_sync(mask, var, offset);<br>}<br><br>// + on my device I get a deadlock here:<br>__syncthreads();</pre><p>To fix it, one need to use special mask, like:</p><pre>unsigned mask = __ballot_sync(0xFFFFFFFF, lane % 2 == 1);<br>const int offset = 2;<br>if (lane % 2 == 1)<br>{<br>  var = __shfl_down_sync(mask, var, offset);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Vg3330fgNFOnXez1e5Xtsw.png" /><figcaption>applying mask on data. Only green threads will be active and participated in a shfl method</figcaption></figure><blockquote><strong><em>Note</em></strong><em>: if </em>laneId+delta<em> doesn’t meet mask conditions (for example: proper </em>laneIds<em> after applying a mask </em>(laneId % 2 == 1) <em>are [1, 3, 5, 7…], but you are trying to get value from inactive thread (i.e.</em> offset=1)<em>, the result value will be UB, since it is out of active thread ids)</em></blockquote><p><strong>__activemask()</strong> — returns a mask of all active threads in the warp. One should use it properly, because if warp divergent branch is exists, this value may return an unexpected value. An example, that returns a different mask for some threads:</p><pre>int m1 = __activemask();<br>int m2 = __activemask();<br><br>if (threadIdLocal &gt; 15)<br>{<br>    // do some job here <br>    // volta+ code:<br>    while (atomicCAS(&amp;val, 1, 0) != 1)<br>    {<br>    }<br>}<br>atomicExch(&amp;val, 1);<br><br>// __syncthreads(); // it will help to get non-divergent mask<br><br>m2 = __activemask();<br>...</pre><p>The result: since the first 16 threads don’t have divergent branch, they have the same mask. But 16–31th threads are waiting for atomic <em>variable == 1 </em>one by one , and it result in different masks:</p><ul><li>-1 means that each thread has the same mask</li><li>(0–15 threads) 65535 = 00000000 00000000 11111111 11111111</li><li>65536 = 00000000 00000001 00000000 00000000</li><li>131072 = 00000000 00000010 00000000 00000000</li><li>262144 = 00000000 00000100 00000000 00000000</li><li>…</li></ul><pre>0)  =  mask1: -1, mask2: 65535<br>...<br>14)  =  mask1: -1, mask2: 65535<br>15)  =  mask1: -1, mask2: 65535<br>---<br>16)  =  mask1: -1, mask2: 65536<br>17)  =  mask1: -1, mask2: 131072<br>18)  =  mask1: -1, mask2: 262144<br>... </pre><blockquote>Long story short: use <strong>__ballot_sync </strong>if you need same mask for each thread and this method will sync all threads in a warp before getting a mask.</blockquote><blockquote>m2 = __ballot_sync(0xFFFFFFFF, 1); will return a mask that covers all threads in a warp.</blockquote><h3>6. Cooperative groups</h3><p>Starting from CUDA 9.0, Cooperative Groups provide a more flexible and expressive way to express synchronization patterns within a grid, thread blocks and a warp. It allows finer control over thread synchronization. I will explain it in the next article.</p><h3>Conclusion</h3><p>Thanks for reading, please feel free to comment with corrections or ideas.</p><h3>Resources</h3><ul><li><a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html">CUDA C++ Programming Guide (Legacy) - CUDA C++ Programming Guide</a></li><li><a href="https://docs.nvidia.com/cuda/parallel-thread-execution/index.html">PTX ISA 8.3</a></li></ul><p><a href="https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/">https://developer.nvidia.com/blog/using-cuda-warp-level-primitives/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b475c3dbd57f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>