<?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 Oserebameh Beckley  on Medium]]></title>
        <description><![CDATA[Stories by Oserebameh Beckley  on Medium]]></description>
        <link>https://medium.com/@osebeckley?source=rss-dcac8c9d2ede------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JEHJF7Wyv8uhMXce</url>
            <title>Stories by Oserebameh Beckley  on Medium</title>
            <link>https://medium.com/@osebeckley?source=rss-dcac8c9d2ede------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:10:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@osebeckley/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[GPU Optimization in WebGPU: Solving Atomic Contention with Parallel Reduction]]></title>
            <link>https://medium.com/@osebeckley/gpu-optimization-in-webgpu-solving-atomic-contention-with-parallel-reduction-037819e5f7ed?source=rss-dcac8c9d2ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/037819e5f7ed</guid>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[webgpu]]></category>
            <dc:creator><![CDATA[Oserebameh Beckley ]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 10:27:29 GMT</pubDate>
            <atom:updated>2026-02-28T14:33:07.216Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why “safety” Kills Performance and how to use Tournament Trees to make your Compute Shaders in wgsl Fly.</h4><h3><strong>The Story So Far</strong></h3><p>In <a href="https://medium.com/@osebeckley/webgpu-compute-shaders-explained-a-mental-model-for-workgroups-threads-and-dispatch-eaefcd80266a"><strong>part 1</strong></a>, we traded the sequential “Hotel Manager” mindset for that of a City Architect. We learned that mastering compute shaders in WebGPU means organizing a massive, parallel army. We built our “City of Threads”, grouping them into workgroups (apartment buildings) where residents can talk to each other, and laid them out across a dispatch grid to cover our entire dataset.</p><p>But building a fast city is only half the battle. If you design the roads poorly, you’ll still end up with a traffic jam, just a faster traffic jam than a CPU situation.</p><h3><strong>The New Challenge</strong></h3><p>Now that our city is built, we need our 256 residents to calculate something critical: the <strong>Maximum Gradient Magnitude </strong>of an MRI scan.</p><p>In medical imaging, calculating the gradient of a voxel (a 3D pixel) tells us how rapidly the surrounding tissues are changing. A very high value indicates a sharp contrast — like the boundary between the skull and the air. A low value indicates homogenous regions, meaning the surrounding voxels likely belong to the same tissue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Q1cP2nA6fyk9_emrOCFYLg.png" /><figcaption>Graph plot showing distribution of meaningful voxels (3D pixels) within an MRI scan. Voxels lower than the threshold represent non-brain tissue. The different bins would indicate regions where intensity changes rapidly i.e non-homogenous tissues (Gray matter, white matter, CSF).</figcaption></figure><p>When building accesible neurotech tools that need to run efficiently without supercomputers, optimizing these calculations is essential. We successfully sent thousands of workers into the building simultaneously to find lit bulbs. Now, we face a harder question: “if all the rooms have lit bulbs, which room has the absolute brightest?”.</p><h3><strong>1. </strong><em>The Naive Approach: Understanding Atomic Contention in WebGPU</em></h3><p>In Part 1, we set up a “whiteboard” in the lobby ( var&lt;workgroup&gt;) and used a barrier ( workgroupBarrier()) to ensure resident #0 could wipe it clean before anyone else wrote on it:</p><pre>var&lt;workgroup&gt; localMaxGradient: atomic&lt;u32&gt;;<br><br>@compute @workgroup_size(8, 8, 4)<br>fn main(<br>    @builtin(global_invocation_id) global_id: vec3u, <br>    @builtin(local_invocation_index) local_index: u32<br>) {<br>    if (local_index == 0u) {<br>        atomicStore(&amp;localMaxGradient, 0u);<br>    }<br>    workgroupBarrier();<br>// ...</pre><p>To find the maximum gradient, each thread needs to calculate its local gradient, compare it to the current hightest value on the whiteboard, and update it if it’s higher. The easiest, most intuitive way to code this is using an atomic operation like atomicMax<strong>.</strong></p><pre>let myValue: u32 = calculateGradient(); <br>atomicMax(&amp;localMaxGradient, myValue); //returns the higher value</pre><h4><strong>The Analogy: The Lobby Turnstile</strong></h4><p>We have 256 residents. We tell them: “<em>Go to the lobby and write your score on the whiteboard. If your score is higher than what’s already there, overwrite it.”</em></p><p>Because the whiteboard is just one variable, the GPU enforces “Atomic Safety”. Atomic operations act like a turnstile. Only one person can write at a time to prevent data corruption. So:</p><ul><li>Resident #1 steps up and writes.</li><li>Resident #2 has to wait.</li><li>Resident #3 has to wait.</li><li>Resident #255 is stuck in line.</li></ul><p>Note that while all are performing their gradient calculations simultanaeously, it is this final step that turns your massively parallel GPU into a “slow”, single-lane DMV line. This introduces the<a href="https://medium.com/@ogundipe.eniola/understanding-o-n-time-complexity-a-guide-to-linear-efficiency-6d490870381e"> <strong>O(N) complexity</strong></a> inside your workgroup. The more threads you have, the slower it gets because you have created <strong>contention. </strong>This occurs when massive numbers of threads compete for shared resources — memory bandwidth, caches, compute units, or PCIe bus — resulting in stalled warps, reduced parallelism, and severe performance bottlenecks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*Af0D-AIhwuGYb1J8JfshdA.png" /><figcaption>Illustrating the performance bottleneck when contention is introduced</figcaption></figure><h3>2. <em>Optimizing with Parallel Reduction: The O(log N) Solution</em></h3><p>If we want to maintain the blistering speed of the GPU, we have to stop making our threads wait in line. Instead of a single whiteboard, we give every resident a private clipboard (an array in shared memory) and we host a heavily synchronised knockout tournament.</p><p><strong>The Group Stage (Initialization &amp; Qualification)</strong></p><p>Before the bracket begins , everyone has to qualify. All 256 residents simultaneously calculate their own local gradient magnitude. No waiting, no turnstiles. Once calculated, all 256 residents write thier scores onto their designated slots on the shared scoreboard at the exact same time.</p><ul><li><em>The Whistle: </em>We call a workgroupBarrier() to ensure every single resident has posted their score before the knockouts begin.</li></ul><p><strong>The Round of 128 (The First Knockout)</strong></p><p>We immediately cut the active workforce in half. We tell the bottom half of the bracket (residents #128 through #255) to go back to sleep — their job is done.</p><p>The top half (residents #0 through #127) become the referees.</p><ul><li>Resisdent #0 compares their score with resident #128.</li><li>Resident #1 compares with Resident #129.</li><li>The higher score (the “winner”) is written into the referee’s slot on the scoreboard.</li><li><em>The Whistle: </em>Another workgroupBarrier() ensures all 128 matches finish before the next round.</li><li>At the end of the tournament #0 will hold the winner of the top half while #1 will hold the winner of the bottom half.</li></ul><p><strong>The Round of 64 to the Quarter-Finals</strong></p><p>We halve the active referees again.</p><ul><li>In the Round of 64, Resident #0 compares the winner of their previous match against Resident #64’s winner.</li><li>This rapid-fire halving continues: Round of 32, Round of 16, Round of 8…</li></ul><p><strong>The Semi-Finals &amp; The Final</strong></p><p>Now we are down to just 4 active threads, then 2.</p><p>In the Grand Final, resident #0, which is the highest score from the entire left side of the bracket compares against resident #1, highest score from the right side. resident #0 writes the ultimate winning score to the board.</p><p><strong>The Champion is Crowned</strong></p><p>Resident #0 is now holding the absolute maximum gradient magnitude for the entire apartment building. Because we only have one undisputed champion, Resident #0 is the <em>only</em> thread that walks out to the global memory (the city-wide database) to report the building’s highest score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*V8_WuTNLJf5T-604uB_zJg.png" /><figcaption>Illustrating the parallel reduction stages as a tournament.</figcaption></figure><p>In this WGSL compute shader, we use workgroup shared memory to avoid atomic contention:</p><pre>// Update local max using parallel reduction<br>    whiteBoard[local_index] = bitcast&lt;u32&gt;(gradientMagnitude);<br>    <br>    workgroupBarrier();<br><br>    // Parallel reduction loop<br>    for (var i: u32 = 128u; i &gt; 0u; i &gt;&gt;= 1u) {<br>        if (local_index &lt; i) {<br>            let otherThread: u32 = whiteBoard[local_index + i];<br>            if (otherThread &gt; whiteBoard[local_index]) {<br>                whiteBoard[local_index] = otherThread;<br>            }<br>        }<br>        workgroupBarrier();<br>    }<br><br>    if (local_index == 0u) {<br>        atomicMax(&amp;globalStats.maxGradient, whiteBoard[0]);<br>    }</pre><p><em>The loop </em><em>for (var i: u32 = 128u; i &gt; 0u; i&gt;&gt; = 1u)is simply the tournament official announcing that the field of play is being cut in half every round. If you’re not familiar </em><em>i&gt;&gt;=1u is a rightward shift in bit operations.</em></p><h4>Why This Wins Championships</h4><p>By organizing a tournament, we eliminated the turnstile entirely.</p><p>Instead of 256 sequential, agonizing wait times (<a href="https://medium.com/@ogundipe.eniola/understanding-o-n-time-complexity-a-guide-to-linear-efficiency-6d490870381e"><strong>O(N)complexity</strong></a>), our tournament crowned a champion in exactly 8 parallel rounds (<a href="https://medium.com/@monidavies/understanding-o-log-n-time-complexity-20e5f7a942d7"><strong>O(log N) complexity</strong>)</a>. We replaced a chaotic, single-lane traffic jam with a beautifully synchronized, high-speed logarithmic sweep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*KWx0k_0QVK1B4CGjaHLJKw.png" /><figcaption>Performance comparison of naive atomic contention (one-by-one updates, O(N) steps) vs. parallel reduction (logarithmic knockout rounds, O(log N) steps) when finding the maximum gradient magnitude inside a workgroup</figcaption></figure><h4>Conclusion</h4><p>In the end, the choice between “safety-first” atomics and a disciplined parallel reduction tournament isn’t just about code style — it’s about respecting the GPU’s massive parallelism. By turning a potential traffic jam into a logarithmic sprint, you unlock the true speed of your compute shaders, whether you’re edge-detecting MRI boundaries or crunching any other workgroup-scale aggregation. The lesson? On GPUs, blind synchronization is the enemy of performance; smart, barrier-coordinated cooperation is the path to championships.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=037819e5f7ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Vs COVID-19: How AI Accelerated CT Diagnosis During a Global Crisis]]></title>
            <link>https://medium.com/@osebeckley/deep-learning-vs-covid-19-how-ai-accelerated-ct-diagnosis-during-a-global-crisis-cc1fab215e85?source=rss-dcac8c9d2ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc1fab215e85</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Oserebameh Beckley ]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 20:09:36 GMT</pubDate>
            <atom:updated>2026-01-13T20:09:36.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The year 2020 heralded an unprecedented challenge for the world of radiology. As the novel coronavirus (COVID-19) spread rapidly, healthcare systems faced a critical bottleneck. While PCR tests eventually became the gold standard for confirmation, Computed Tomography (CT) scans remained the most efficient tool for immediate triage and severity assessment. However, the sheer volume of cases accelerated faster than the available workforce. Radiologists found themselves overwhelmed, particularly as the detection of early-stage infection foci required the time-consuming review of high-resolution, thin-slice scans. This backlog didn’t just exhaust doctors ; it delayed isolation and treatment, directly affecting the control of the pandemic.</p><p><strong>This creates a fundamental problem:</strong> <strong>How do you scale diagnostic expertise when the number of patients vastly outnumbers the doctors?</strong></p><p>I chose to analyze the 2020 Scientific Reports paper, “Deep learning-based model for detecting 2019 novel coronavirus pneumonia on high-resolution computed tomography” by Chen et al., because it directly addresses this crisis at Renmin Hospital in Wuhan, China (the epicenter of the pandemic). through deep learning. As a researcher currently building a browser-based GPU graphics pipeline for neuroimaging segmentation, I found their use of deep learning to segment “ground-glass-opacities” (lesions) in the lungs particularly relevant as it parallels the mathematical challenges I encounter when segmenting brain anatomy, highlighting the universal power of computational imaging across modalities.</p><h3>Background</h3><p>To understand the significance of this study, one must first grasp the clinical presentation of COVID-19. Unlike bacterial pneumonia, which often appears as dense consolidation, early-stage COVID-19 typically manifests as “Ground-Glass Opacities” (GGO) — hazy, faint increases in lung density that preserve underlying bronchial and vascular margins.</p><p>Detecting these subtle features requires high-resolution CT (HRCT) protocols, generating hundreds of thin slices (often &lt;1mm) per patient. For a human radiologist, distinguishing these GGOs from other viral pneumonias (like Influenza A) or non-infectious conditions is cognitively demanding and prone to variability, especially under fatigue.</p><p>This research sits at the intersection of Computer-Aided Diagnosis (CAD) and pandemic response. It builds upon established deep learning architectures, specifically U-Net and ResNet-50, which had previously revolutionized biomedical image segmentation by allowing algorithms to classify individual pixels rather than just whole images. Prior to this study, these models were primarily deployed for lung cancer nodule detection. Chen et al. pivoted this existing theory, challenging the application scope by retraining these networks to recognize novel viral pathology instead of tumors.</p><p>In the broader context of bioinformatics, this work represents a critical shift from “static” analysis to “acute” deployment. By integrating deep learning into the clinical workflow, the study addresses a classic data science problem: the scarcity of labeled data during an emerging crisis. It demonstrates how transfer learning — specifically leveraging pre-trained weights from models that already “know” how to detect basic edges and shapes from unrelated datasets like ImageNet — can rapidly accelerate model development when historical medical data does not yet exist for a new disease.</p><h3>Methodology</h3><p>To build a system capable of specific diagnosis during a pandemic, the researchers curated a massive library of 46,096 CT images from Renmin Hospital in Wuhan — the epicenter of the outbreak. This wasn’t just raw data; it was a carefully structured comparison between lab-confirmed COVID-19 cases and non-viral control patients. After rigorously filtering out scans with poor visibility or artifacts, they refined this down to a training set of nearly 35,000 high-resolution slices, splitting them into retrospective training and testing sets. This massive scale was essential to ensure the model learned to recognize pathology in the messy reality of clinical scans.</p><p>To analyze this data, they utilized U-Net++, a specialized deep neural network architecture. Unlike standard classification networks that simply output a binary label (“Healthy” vs. “Sick”), U-Net++ was chosen for its ability to perform semantic segmentation — generating a pixel-by-pixel map that outlines the exact shape and location of infection lesions. This is crucial in radiology, where quantifying the volume of infection is as important as detection.</p><p>To address the challenge of limited training data during the early outbreak, the team applied Transfer Learning. They utilized a ResNet-50 backbone pre-trained on the ImageNet dataset. This method was appropriate because it allowed the model to inherit capable feature detectors (for edges and textures) from millions of general images, rather than learning from scratch, which would have required a much larger medical dataset to avoid overfitting.</p><p>The processing pipeline was implemented using the Keras framework. It involved three distinct stages: first, extracting valid lung areas; second, predicting suspicious lesions with a confidence threshold of 0.50; and third, applying temporal logic. The model only flagged a positive case if lesions were detected in three consecutive slices. This statistical consistency — similar to consensus algorithms used in bioinformatics — was essential for filtering out random noise and imaging artifacts that typically occur in single frames.</p><h3>Results</h3><p>The research yielded results that went beyond simple accuracy metrics, fundamentally altering the workflow for pandemic radiology. The most significant finding was the impact on clinical efficiency: when radiologists used the AI model as an assistant, their reading time dropped by 65% (from ~116 seconds to ~41 seconds per case). This directly validated the authors’ primary hypothesis: that deep learning could alleviate the overwhelming pressure on medical staff without compromising diagnostic quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xeRmqNs6Y8QGYw4vneqVgg.png" /></figure><p>In terms of diagnostic performance, the model demonstrated remarkable robustness. On the internal retrospective dataset, it achieved a per-patient accuracy of 95.24% and a sensitivity of 100%, meaning it missed zero positive cases. Crucially, the model maintained this high performance (96% accuracy) on an external dataset from a completely different hospital (Qianjiang Central Hospital). This was a surprising and positive outcome, as medical AI models typically suffer huge performance drops when tested on data from scanners they weren’t trained on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzA8xA9KgPs8oSUPxGFhUw.png" /></figure><p>A deeper look at the data reveals an interesting statistical divergence between “Per-Patient” and “Per-Image” metrics. While the model was perfect at flagging patients (100% sensitivity), its specificity was higher on a per-image basis. This suggests that while the model might occasionally flag a healthy slice in a sick patient, it effectively aggregates these signals to make the correct diagnosis for the patient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PaEe7vdYUEqY72et5NoVw.png" /></figure><p>I made these graph plots to visualize thier results using this <a href="https://github.com/Bahdmanbabzo/Stanford-blog-post">python script</a> I wrote with the help of Gemini 3 Pro.</p><h3><strong>Discussion</strong></h3><p>The implications of these results extend far beyond simple accuracy statistics; they offer a blueprint for integrating artificial intelligence into crisis response. The most profound impact of this research is not the model’s ability to detect COVID-19 — radiologists can already do that — but its ability to democratize expert-level diagnostics at scale. By reducing the reading time per case from nearly two minutes to under 45 seconds, the model effectively acts as a force multiplier, allowing a single radiologist to do the work of three. In the context of a rapidly spreading pandemic where medical staff are often the first to fall ill, this efficiency is a critical survival mechanism for the healthcare system.</p><p>Theoretically, the study represents a significant step forward in solving the “robustness problem” in medical imaging. A recurring failure in bioinformatics is the inability of models trained in one hospital to perform well in another due to subtle differences in scanner calibration or protocols. The fact that this model maintained 96% accuracy on an external dataset from Qianjiang Central Hospital suggests that the deep learning architecture successfully learned the pathological features of the virus rather than the noise of the specific machine.</p><p>However, the discrepancy between per-patient sensitivity (100%) and per-image specificity highlights a lingering challenge in bioinformatics: the “black box” aggregation of data. While the model reaches the correct final conclusion, it occasionally misinterprets individual healthy slices. Future research must focus on refining these granular predictions to build greater trust with clinicians, ensuring that the AI is right for the right reasons. Ultimately, this work shifts the paradigm from “AI replacing doctors” to “AI enhancing human bandwidth.”</p><h3>Reflection</h3><p>As a medical student and researcher, reading Chen et al.’s work was particularly illuminating in light of my recent work implementing real-time MRI tissue-segmentation pipelines within the browser using Python/R for data analysis and WebGPU for the graphics pipeline.</p><p>Currently, my workflow involves a rigid, painstaking process of manually tuning mathematical thresholds using a mix of differential equations and geometry to describe sulci, gyri and tissue tracts in the brain. Drawing on statistical analysis principles I learned through the Stanford School of Medicine’s Department of Genetics (specifically the Fundamentals of Data Science and Precision Medicine course), I rely on a combination of mathematical and anatomical intuition to differentiate tissue homogeneity from boundaries. This allows me to manually delineate complex structures like the optic pathway, lateral ventricles, and the deep cerebral venous plexus.</p><p>This study demonstrated the inevitable “next step” in that technical evolution: employing U-Net architectures to learn these high-dimensional boundary definitions automatically from data, rather than hard-coding them.</p><p>The most significant finding for me was not just the raw accuracy, but the 65% reduction in radiologist reading time. This empirical evidence shifts the prevailing narrative of medical AI from “replacement” to “augmentation,” proving its value as a force multiplier during a crisis and its potential to catch subtle patterns that the human eyes might otherwise miss.</p><p>However, it also raises critical questions about robustness. While the authors utilized an external dataset, the challenge of “domain shift”, where a model trained on one machine fails on another remains a hurdle. As I continue developing neuroimaging tools, this research challenges me to look beyond static graphics pipelines and consider hybrid approaches — combining the explainability of explicit geometric processing with the scalability of deep learning — to build diagnostic systems that are both fast and trustworthy.</p><h3>Conclusion</h3><p>The study by Chen et al. stands as a landmark example of rapid-response engineering during a global health crisis. By adapting the U-Net++ architecture to identify COVID-19 pneumonia, the team created a tool that did more than just match human accuracy — it solved the logistical bottleneck of the pandemic. The resulting 65% reduction in reading time proved that deep learning is not merely an experimental novelty, but a vital infrastructure for modern healthcare capable of scaling expertise when it is needed most.</p><p>As we move toward an era of precision medicine, this research offers a blueprint for the future. It demonstrates that the true power of AI lies not in replacing clinicians, but in handling the tedious tasks of segmentation and quantification. This allows medical experts to focus on what matters most: accurate diagnosis, timely treatment, and patient survival in the face of uncertainty.</p><h3>Reference</h3><ul><li>Chen, J., Wu, L., Zhang, J. <em>et al.</em> Deep learning-based model for detecting 2019 novel coronavirus pneumonia on high-resolution computed tomography. <em>Sci Rep</em> <strong>10</strong>, 19196 (2020). <a href="https://doi.org/10.1038/s41598-020-76282-0">https://doi.org/10.1038/s41598-020-76282-0</a></li></ul><p><em>Stanford Data Ocean provides Stanford certificate training in precision medicine without costs to anyone whose annual income is under $70,000 USD/ year. Apply for scholarship here: </em><a href="https://docs.google.com/forms/d/e/1FAIpQLSfi6ucNOQZwRLDjX_ZMScpkX-ct_p2i8ylP24JYoMlgR8Kz_Q/viewform"><em>https://docs.google.com/forms/d/e/1FAIpQLSfi6ucNOQZwRLDjX_ZMScpkX-ct_p2i8ylP24JYoMlgR8Kz_Q/viewform</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc1fab215e85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebGPU Compute Shaders Explained: A Mental Model for Workgroups, Threads and Dispatch]]></title>
            <link>https://medium.com/@osebeckley/webgpu-compute-shaders-explained-a-mental-model-for-workgroups-threads-and-dispatch-eaefcd80266a?source=rss-dcac8c9d2ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaefcd80266a</guid>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[webgpu]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Oserebameh Beckley ]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 06:41:56 GMT</pubDate>
            <atom:updated>2026-02-27T20:57:47.712Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering Threads, Shared Memory, and Dispatch through real-world, “<em>City and Apartment” </em>analogies.</h4><p>When moving from CPU programming to GPU (Shader) programming, the syntax is the easy part. The hard part is the mental model.</p><p>On a CPU, you write a loop that executes one step after another. On a GPU, you are commanding an army of millions. If you try to apply “Sequential Thinking” to a parallel problem, your code won’t just be slow — it will be broken.</p><p>To master WebGPU, you need to stop thinking like a hotel manager and start thinking like a city architect.</p><h3><strong>1. The Startup Logic vs. The GPU Logic</strong></h3><p>Imagine you want to find the brightest pixel in an image.</p><ul><li><strong>The CPU Approach:</strong> You hire one person to walk through every room in a hotel, check the lightbulb, and write down the brightest one (synchronous execution). It’s thorough, but it takes ages.</li><li><strong>The GPU Approach:</strong> You don’t hire one person. You hire 32,000 people and drop them all into the hotel at the exact same time (parallel execution).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URD0In2NYPw1G5ndywxTfA.png" /><figcaption>“Single-threaded execution vs. Massively Parallel Compute: A visual representation of WebGPU dispatch logic.”</figcaption></figure><h3>2. The Architecture: Building the City</h3><p>Let’s look at a typical WebGPU setup for processing an MRI volume (256 X 256 X 128 voxels).</p><h4>The Workgroup (The Apartment Building)</h4><p>In your shader code, you define your team size:</p><pre>@compute @workgroup_size(8, 8, 4)<br>fn main(...) { ... }</pre><p>Crucial Point: This is not the size of your data; this is the size of a Team.</p><p>Think of a Workgroup as a single Apartment Building:</p><ul><li>The building is 8 rooms wide, 8 rooms deep, and 4 floors high.</li><li>Total Residents<strong>:</strong> 8 X 8 X4 = 256 Workers.</li><li>The Rule<strong>:</strong> Residents inside a building can talk to each other (via <strong>Shared Memory</strong>), but they cannot shout across the street to other buildings.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v07c3uQ5W5FcGv-KjPY5Fw.png" /></figure><h4>The Dispatch (The City Grid)</h4><p>If our MRI is 256 pixels wide, and each building handles 8 pixels, we need a grid:</p><ul><li>256 / 8 = 32 buildings.</li><li>To cover the 3D volume, we build a city grid of 32 X 32 X 32<strong> </strong>buildings.</li></ul><p>In your javascript code, this would look like this:</p><pre><br>const volumeDict = { width: 256, height: 256, depth: 128};<br>const workgroupSize = { x: 8, y: 8, z: 4 };<br><br>passEncoder.dispatchWorkgroups(<br>  Math.ceil(volumeDict.width / workgroupSize.x),  // 32<br>  Math.ceil(volumeDict.height / workgroupSize.y), // 32<br>  Math.ceil(volumeDict.depth / workgroupSize.z)   // 32<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0RwykzuzL3kKv_OLMF4pw.png" /><figcaption>Multiple workgroups as buildings in a city</figcaption></figure><h4>The Roles: Global vs. Local</h4><p>When writing compute shaders in WebGPU, you’ll constantly see global_id and local_invocation_id. Here is how to keep them straight:</p><ul><li><strong>global_id (The GPS Coordinate):</strong> This is your absolute address in the city. <em>&quot;I am working on Pixel #500.&quot;</em> This is what you use to read from your main texture.</li><li><strong>local_index (The Apartment Number):</strong> This is your ID relative only to your neighbors. <em>&quot;I am Resident #0 in this building.&quot;</em></li></ul><h4>The Problem: “The Whiteboard”</h4><p>Imagine we want to find the “Maximum Gradient” (the brightest spot in the MRI scan) within just our building. We put a whiteboard (var&lt;workgroup&gt;) in the lobby.</p><p>Before we start, someone has to clean the board. We can call the resident of apartment #0 in that building to do it for us. But there’s a catch, the GPU runs code execution in parallel, meaning that resident#52 can run downstairs and write their highscore on the board before #0 has finished erasing it, this is called a <em>race condition</em>. If resident #0 wipes the board after #52 writes on it, the data is lost forever. So we use a workgroupBarrier() to make sure everyone waits in order before clearing the board.</p><p>The code will look like this :</p><pre>var&lt;workgroup&gt; localMaxGradient: atomic&lt;u32&gt;;<br>@compute @workgroup_size(8, 8, 4)<br>fn main(@builtin(global_invocation_id) global_id: vec3u, @builtin(local_invocation_index) local_index: u32) {<br>    if (local_index == 0u) {<br>        atomicStore(&amp;localMaxGradient, 0u);<br>    }<br>    workgroupBarrier();</pre><h4>Summary: The Rules of the GPU Road</h4><p>Mastering WebGPU isn’t just about learning WGSL syntax; it’s about understanding the sociology of your threads. By treating your workgroups like apartment buildings in a massive city, the logic becomes clear:</p><ul><li>Workgroups are Teams: They are your units of organization (Buildings). Residents inside can share data locally, which is incredibly fast.</li><li>Dispatch is the Grid: This determines how many buildings you construct to cover your entire dataset.</li><li>Barriers represent Time: workgroupBarrier() represents the inevitable wait times required to keep your parallel army synchronized. without them, you have chaos.</li><li>Roles Matter: Use global_id to find where you are on the map, and local_index to find who you are in the team.</li></ul><p>In<a href="https://medium.com/@osebeckley/gpu-optimization-in-webgpu-solving-atomic-contention-with-parallel-reduction-037819e5f7ed"> <strong>Part 2</strong></a>, we will address the elephant in the room: What happens when all 256 residents try to write on that lobby whiteboard at the exact same time? We will explore why “Atomic Safety” can kill performance, and how to use Parallel Reduction (Tournament Trees) to make your compute shaders fly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaefcd80266a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Allocation and Bytes Alignment in WebGPU (Ray Tracing Tutorial)]]></title>
            <link>https://medium.com/@osebeckley/memory-allocation-and-bytes-alignment-in-webgpu-ray-tracing-tutorial-b53f99385ab3?source=rss-dcac8c9d2ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/b53f99385ab3</guid>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webgpu]]></category>
            <dc:creator><![CDATA[Oserebameh Beckley ]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 07:33:46 GMT</pubDate>
            <atom:updated>2025-08-24T13:12:02.537Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing my journey of building a ray tracer from scratch in WebGPU/WGSL, today I want to talk about one of the trickiest bugs I’ve encountered so far: <strong>memory allocation and bytes alignment. </strong>This type of bug is especially hard to spot because:</p><ul><li>It doesn’t always throw errors.</li><li>Your code can look perfectly valid.</li><li>Yet, the GPU ends up reading your data incorrectly, leading to silent rendering issues.</li></ul><h4>Grouping Scene Objects in a WebGPU Ray Tracer</h4><p>To render a scene, we first need to group all the objects. For now, let’s assume all objects are spheres with metal materials.</p><pre>export class Hittable {<br>    constructor(position, radius,material, albedo, fuzz) {<br>    this.position = position;<br>    this.radius = radius; <br>    this.material = material; <br>    this.albedo = albedo;<br>    this.fuzz = fuzz;<br>    }<br><br>    get arrayFormat() {<br>        return [<br>            ...this.position, <br>            this.radius, <br>            this.material,<br>            ...this.albedo, <br>            this.fuzz,<br>        ];<br>    }<br>}<br><br></pre><h4>Writing Data to a GPU Storage Buffer</h4><p>We create instances of the spheres and flatten into a <em>Float32Array </em>before writing them to a storage buffer:</p><pre>const spheres = [<br>    new Hittable([0.0, 0.0, -6.0, 0.0], 1.0, 1.0, [1.0, 0.6, 0.2, 0.0], 0.03),<br>    new Hittable([2.0, 0.0, -7.0, 0.0], 0.5, 1.0, [1.0, 1.0, 1.0, 0.0], 0.3),<br>    new Hittable([-2.0, 0.0, -8.0, 0.0], 0.5, 1.0, [0.8, 0.8, 1.0, 0.0], 0.1)<br>  ];<br>  const allData = spheres.flatMap(sphere =&gt; sphere.arrayFormat);<br>  const hittablesData = new Float32Array(allData);<br>  const hittablesBuffer = device.createBuffer({<br>    size: 192,<br>    usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST<br>  });<br>  device.queue.writeBuffer(hittablesBuffer, 0, hittablesData);</pre><h4>Defining Structs in WGSL(WebGPU Shading Language)</h4><p>In wgsl, we define a <em>hittable </em>struct to receive data from the CPU:</p><pre>struct Hittable {<br>    position: vec4f,<br>    radius: f32,<br>    material: f32,<br>    albedo: vec4f,<br>    fuzz: f32,<br>};</pre><p>The syntax is correct, type definitions too, everything seems good EXCEPT the memory allocation. This lacks proper alignment and i’d explain what this means.</p><h4>Alignment Rules in WebGPU</h4><p>Each member of a struct must:</p><ul><li>Be aligned to it’s natural alignment (e.g vec4f -&gt; 16bytes , vec3f -&gt; 16bytes, vec2f -&gt; 8bytes, f32 -&gt; 4bytes).</li><li>Start at an offset that is a multiple of it’s alignment.</li><li>Padding must be added before a misaligned member .</li></ul><p>If these rules are broken the data would be read starting at wrong offsets. The image below illustrates what is wrong with our current implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*5h8vDNMWBPaYVtPeD4AV4w.png" /><figcaption>Wrong layout alignment</figcaption></figure><p>The correct layout should be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*Q_m-mOQnxiE-N31hXbrOCQ.png" /><figcaption>Correct layout alignment</figcaption></figure><p>Modifying our arrayFormat function to account for this would be:</p><pre> get arrayFormat() {<br>        return [<br>            ...this.position, <br>            this.radius, <br>            this.material,<br>            0.0, 0.0, // 2 floats of 4 bytes each<br>            ...this.albedo, <br>            this.fuzz,<br>            0.0, 0.0, 0.0 // 3 floats of 4 bytes each <br>        ];<br>    }</pre><h4>Key Takeaway for WebGPU Developers</h4><p>In GPU programming with WebGPU, memory alignment is non-negotiable. To avoid silent bugs:</p><ul><li>Always follow wgsl struct alignment rules.</li><li>Add padding explicitly in both wgsl structs and javascript arrays.</li><li>Debug by checking offsets, not just syntax.</li></ul><p>This post is part of my series documenting the process of building a ray tracer from scratch in WebGPU. If you’re just joining, start with my earlier write-up on <a href="https://medium.com/@osebeckley/building-an-efficient-gpu-style-rejection-algorithm-part-2-analytical-method-1f9230c618a9">generating random vectors that lie on the surface of a sphere</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b53f99385ab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Efficient GPU-style Rejection Algorithm (part 2): Analytical Method.]]></title>
            <link>https://medium.com/@osebeckley/building-an-efficient-gpu-style-rejection-algorithm-part-2-analytical-method-1f9230c618a9?source=rss-dcac8c9d2ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f9230c618a9</guid>
            <category><![CDATA[3d-website-development]]></category>
            <category><![CDATA[webgpu]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <dc:creator><![CDATA[Oserebameh Beckley ]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 07:54:05 GMT</pubDate>
            <atom:updated>2025-08-21T07:54:05.956Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last<a href="https://medium.com/@osebeckley/building-an-efficient-gpu-style-rejection-algorithm-a6657d7a7436"> blog</a>, I tried to write a simple function that rejcts vector positions outside the bounds of a sphere by directly adapting the code from <a href="https://raytracing.github.io/books/RayTracingInOneWeekend.html">Raytracing In One Weekend </a>written in C++ to wgsl. But using a while-loop would be computationally expensive so this blog takes advantage of GPU-parallelism to arrive at the same result much faster with less calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGjdUs17PnU-h90_74lzEQ.png" /></figure><p>V is a random vec3 generated by the rand_vec3 function when it is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*_YOwfgliOasGMsc76OxqEw.png" /><figcaption>Function to derive a random vec3f</figcaption></figure><p><em>U1 </em>and<em> U2</em> are the x and y coordinates of the generated vector respectively. <em>Z </em>maps <em>u1</em> to uniform distribution i.e <em>[-1,1] ; </em>it represents the height. <em>r </em>is the radius and satifies the equation of a sphere with unit radius which gives:</p><p><em>x² + y² + z² = 1</em></p><p>if <em>x² + y² = 1 — z² and x² + y² = r</em></p><p>then</p><pre>r = sqrt(max(0.0, 1.0-z * z)); </pre><p>The code snippet solves for r and using the <em>max</em> function, it’ll always take the value that is &gt; 0.0.</p><pre>let phi = 2 * 3.142.... * u2; </pre><p>Phi represents the azimuthal angle around the z-axis. The diagram below should help to visualise all this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdYGqV_fd8b4V4L8ajDrhg.png" /><figcaption>Illustration showing the various variables</figcaption></figure><p>The last line returns the vector but in cartesian coordinates. In essence, what this code snippet does is that it only generates vectors that would result in r=1 in order to satisfy that equation. Therefore, in a sphere of unit radius, any vector generated with r=1 would lie on it’s surface, hence the code snippet only generates vectors lying directly on the sphere surface, removing the need for generating multiple vectors and rejecting them till we find a best fit.</p><p>This approach highlights one of the key lessons I’m learning in GPU programming: sometimes, the fastest solution isn’t about more loops or brute force — it’s about rethinking the problem mathematically and leveraging the GPU’s natural strengths in parallel computation. By moving from rejection sampling to an analytical method, I’ve been able to generate valid vectors directly on the unit sphere surface with less overhead. In the next step of my journey, I’ll explore how to extend this method for <strong>diffuse scattering</strong> inside the sphere, not just on its surface, to get closer to realistic ray tracing results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f9230c618a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an efficient GPU-style Rejection Algorithm]]></title>
            <link>https://medium.com/@osebeckley/building-an-efficient-gpu-style-rejection-algorithm-a6657d7a7436?source=rss-dcac8c9d2ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6657d7a7436</guid>
            <category><![CDATA[3d-computer-graphics]]></category>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[webgpu]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <dc:creator><![CDATA[Oserebameh Beckley ]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 14:58:37 GMT</pubDate>
            <atom:updated>2025-08-19T14:58:37.951Z</atom:updated>
            <content:encoded><![CDATA[<p>This week, I learned why something that works in C++ can break when moved to GPU code. Here’s what happened when I tried to build a rejection algorithm for random vectors in WGSL</p><p>I don’t know anything about the topic but I’m learning from <a href="https://raytracing.github.io/books/RayTracingInOneWeekend.html">Raytracing in One Weekend</a>. As at the time of writing this, I’m trying to make a diffuse material in wgsl following the related section in the book.</p><p>The aim of the algorithm is to generate random vectors and then determine if that vector lies within the sphere or outside of it. If it lies outside, reject it .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXL2_QR8bOG0hpz6TMs4Vg.png" /><figcaption>First try at refactoring the source code.</figcaption></figure><p>The code snippet tries to achieve this while limiting the number of tries to 8 (as in the while loop).</p><pre>let v = randVec3(seed + f32(attempts) * 1.234) * 2.0 - vec3f(1.0, 1.0, 1.0); </pre><p>v represents a vector. Adding <em>seed</em> to <em>f32(attemps) * 1.234</em> is just to make sure that each result is unique. The remainder is a common computer graphics method to put the result within the range [-1,1]. Lensq stores the result of a different way to find the magnitude of that vector.</p><pre>if (lensq &lt;= 1.0 &amp;&amp; lensq &gt; 1e-8){<br>return normalize(v);<br>attempt = attempt + 1<br>}; <br>return vec3(1.0, 1.0, 1.0); </pre><p>Since the sphere is a unit sphere(radius = 1.0 and magnitude = 1.0), I’m comparing the magnitude of the vector against this. If <em>lensq ≤ 1.0</em> then it lies within the sphere. Also I’m checking that it’s not too close to zero hence <em>lensq &gt; 1e-8 (1 * 10 ^ -8)</em> . If these are true, return the vector normalised else return a fallback : <em>vec3(1.0, 1.0, 1.0)</em>.</p><p>This would be a good adaptation from the c++ code example in the book but the problem is wgsl writes to the GPU not the CPU as in c++. GPU code runs in parallel. When the fragment shader is reached and the function is executed, it runs at the same time for every pixel on the screen making the use of the while loop computationally expensive and a bit too much.</p><p>This attempt works, but it’s not GPU-friendly. In my next post, I’ll explore how to rewrite this function without while-loops, using GPU-native approaches like parallel sampling and rejection, to take full advantage of WebGPU’s architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6657d7a7436" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>