<?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 Shreya Shukla on Medium]]></title>
        <description><![CDATA[Stories by Shreya Shukla on Medium]]></description>
        <link>https://medium.com/@shreyashukla04?source=rss-f71048cbf6bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zn2xDpcnGgnmJpDvnKAW3w.jpeg</url>
            <title>Stories by Shreya Shukla on Medium</title>
            <link>https://medium.com/@shreyashukla04?source=rss-f71048cbf6bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:37:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shreyashukla04/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[Multithreading Caveats 101: Two Threads, One random Friday]]></title>
            <link>https://levelup.gitconnected.com/multithreading-caveats-101-two-threads-one-random-friday-c8e4b44f99aa?source=rss-f71048cbf6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8e4b44f99aa</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shreya Shukla]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 03:14:28 GMT</pubDate>
            <atom:updated>2025-07-21T03:14:28.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y2oM7Tiel-ReTkFC" /><figcaption>Photo by <a href="https://unsplash.com/@zimbarus?utm_source=medium&amp;utm_medium=referral">A R</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One Friday, as my roommate and I were getting ready for dinner at a friend’s place, I asked if she knew what multithreading is. We come from different backgrounds and often end up sharing random things about our fields, whether we’re on the way to the grocery store, cooking, or, like now, getting ready to go out. To explain multithreading to her, I came up with a made-up scenario where she and I were two threads given a task to complete. As I was explaining it, I realized something was missing. I then took a moment to refine the made-up scenario, not only to explain the concept better but also to figure out if it was actually helpful or if we’d need something else. This article is inspired by our brief discussion.</p><h3><strong>Here is the scenario -</strong></h3><p>She (thread_jo) and I (thread_ss) are in the same room (core), inside an apartment (CPU). Our task (python function) is to count the frequency of words in a large document. The document is a PDF of <em>Harry Potter and the Philosopher’s Stone</em>. We are each given separate portions (chunks) of the document to process i.e. to count the frequency of words in our respective parts (local resource). As we count, we must keep merging the results into a shared frequency count dictionary (shared resource), which holds data like: harry → 100,000, meaning the word “harry” appears in the book 100,000 times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kJ8cO4KR6DPW1DbJ" /><figcaption>Figure 1: Made-up multithreading scenario (Image by Author)</figcaption></figure><p>We’d write the code to execute below steps-</p><ol><li>Read the document sequentially.</li><li>Divide it into two chunks for two threads.</li><li>Define the task/function that would clean data and count the words.</li><li>Define two threads that will execute the function.</li><li>Get the final shared frequency count dictionary.</li></ol><p>The python code would look something like below –</p><pre>class WordCount:<br>    def __init__(self):<br>        # Shared word count dictionary<br>        self.word_count_dictionary = defaultdict(int)<br><br>    # 3. Define the task/function that would clean data and count the words<br>    def task_clean_and_count(self, chunk, thread_name):<br>        print(f&quot;{thread_name} starting work&quot;)<br><br>        for index in range(len(chunk)):<br>        # Clean and process text<br>        # Calculate the word count<br>        # Update the shared word count dictionary<br><br>        print(f&quot;Thread {thread_name}: update complete&quot;)<br>    <br>if __name__ == &quot;__main__&quot;:<br>        # 1. Read the document sequentially, that mean not through multithreading but with the main thread instead<br>        doc = fitz.open(&#39;harry-potter-and-the-philosophers-stone-by-jk-rowling.pdf&#39;)<br>        num_pages = len(doc)<br>        <br>        # 2. Divide data into two chunks for two threads<br>        mid = num_pages // 2<br>        chunk1 = doc[:mid]<br>        chunk2 = doc[mid:]<br><br>        word_count = WordCount()<br><br>        print(&quot;Starting Task.&quot;) <br>        # 4. Define two threads that will execute the function<br>        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:<br>            # Thread 1<br>            executor.submit(word_count.task_clean_and_count, chunk1, &#39;thread_jo&#39;)<br>            # Thread 2<br>            executor.submit(word_count.task_clean_and_count, chunk2, &#39;thread_ss&#39;)<br> <br>        print(&quot;Task Ended.&quot;)<br><br>        # 5. Get the final shared frequency count dictionary<br>        top_words = sorted(word_count.word_count_dictionary.items(), key=lambda i: -i[1])[:5]<br>        print(f&quot;Top 10 words: {top_words}&quot;)</pre><h3><strong>Synchronization</strong></h3><p>It’s a bit more complicated than it seems, though. <strong>We need to make sure we’re not writing to the final frequency count dictionary (shared resource) at the same time</strong>, because we might overwrite each other’s updates and end up with incorrect results. To ‘synchronize’ our updates, <strong>we place a lock on the shared resource</strong>. When we want to update it, we first request the lock, if it’s available, we acquire it, make our update, and then release the lock so the other person can do their update. This also <strong>makes the shared resource thread-safe</strong>, which is something that can be safely used by multiple threads at the same time, without causing problems like data corruption etc.</p><p>Let’s add a lock to the above code –</p><pre><br><br>class WordCount:<br>    def __init__(self):<br>        # Shared word count dictionary<br>        self.word_count_dictionary = defaultdict(int)<br>        self._lock = threading.Lock()<br><br><br>    # 3. Define the task/function that would clean data and count the words<br>    def task_clean_and_count(self, chunk, thread_name):<br>        print(f&quot;{thread_name} starting work&quot;)<br>        time.sleep(0.5)<br><br>        for index in range(len(chunk)):<br>        # Clean and process text<br>        # Calculate the word count<br>             with self._lock:<br>             # Update the shared word count dictionary<br><br>        print(f&quot;Thread {thread_name}: update complete&quot;)<br>    <br>if __name__ == &quot;__main__&quot;:<br> <br>        # 1. Read the document sequentially, that mean not through multithreading but with the main thread instead<br>        doc = fitz.open(&#39;harry-potter-and-the-philosophers-stone-by-jk-rowling.pdf&#39;)<br>        num_pages = len(doc)<br>        <br>        # 2. Divide data into two chunks for two threads<br>        mid = num_pages // 2<br>        chunk1 = doc[:mid]<br>        chunk2 = doc[mid:]<br> <br>        word_count = WordCount()<br> <br>        # 4. Define two threads that will execute the function<br>        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:<br>            # Thread 1<br>            executor.submit(word_count.task_clean_and_count, chunk1, &#39;thread_jo&#39;)<br>            # Thread 2<br>            executor.submit(word_count.task_clean_and_count, chunk2, &#39;thread_ss&#39;)<br> <br>        # 5. Get the final shared frequency count dictionary<br>        top_words = sorted(word_count.word_count_dictionary.items(), key=lambda i: -i[1])[:10]<br>        print(f&quot;Top 10 words: {top_words}&quot;)</pre><p>It’s important to note that we have no way of predicting which thread will be working at any given moment, it’s random. Technically<strong>, thread scheduling is handled by the operating system (OS)</strong>, and it’s entirely out of our hands. We can sometimes influence it a little though with thread priorities or synchronization mechanisms.</p><p>If I add a delay, like time.sleep(0.5), in the code above, I can observe interleaving behavior.<strong> Interleaving means the two threads appear to take turns executing, switching back and forth as they progress.</strong> In the result below, which shows just 5 pages per thread, we can see that it seems both threads are working alternately. This is just one way to observe how multithreaded execution can be controlled to some extent, rather than being left entirely to the operating system.</p><pre>Starting Task.<br>thread_jo starting work<br>Thread thread_jo: Page 0<br>thread_ss starting work<br>Thread thread_ss: Page 0<br>thread_jo acquired lock<br>thread_jo released lock<br>Thread thread_jo: Page 1<br>thread_ss acquired lock<br>thread_ss released lock<br>Thread thread_ss: Page 1<br>thread_ss acquired lock<br>thread_ss released lock<br>Thread thread_ss: Page 2<br>thread_jo acquired lock<br>thread_jo released lock<br>Thread thread_jo: Page 2<br>thread_ss acquired lock<br>thread_ss released lock<br>Thread thread_ss: Page 3<br>thread_jo acquired lock<br>thread_jo released lock<br>Thread thread_jo: Page 3<br>thread_jo acquired lock<br>thread_jo released lock<br>Thread thread_jo: Page 4<br>thread_ss acquired lock<br>thread_ss released lock<br>Thread thread_ss: Page 4<br>thread_ss acquired lock<br>thread_ss released lock<br>Thread thread_ss: update complete<br>thread_jo acquired lock<br>thread_jo released lock<br>Thread thread_jo: update complete<br>Task Ended.</pre><h3><strong>Caveat of Multithreading</strong></h3><p>So, this seems fine, we can keep making progress on our own, keep updating the shared dictionary and just vibe with however OS schedules our run. But here’s what I missed explaining: <strong>we can’t actually do our work in parallel</strong>!!</p><p>We are basically using a Python function to calculate the counts, meaning we’re in a Python environment and Python has something called the <strong>Global Interpreter Lock (GIL).</strong> The <strong>GIL only allows one thread to run at a time.</strong> It’s like we have just one working laptop: even though both of us want to work, only one can use it at a time, so, we must take turns. Either she can work, or I can, but we can’t both work at the same time or in parallel.</p><p>In fact, when I run the complete code with multithreading versus a single thread (main), I get the same result, which in this case was around 0.34 seconds.</p><p>Complete code for multithreading -</p><pre># imports<br>from pypdf import PdfReader<br>import re<br>from nltk.corpus import stopwords<br>import nltk<br>from collections import defaultdict<br>import threading<br>import time<br>import concurrent.futures <br>import fitz<br> <br>nltk.download(&#39;stopwords&#39;, quiet=True)<br>stop_words = set(stopwords.words(&#39;english&#39;))<br><br><br>class WordCount:<br>    def __init__(self):<br>        # Shared word count dictionary<br>        self.word_count_dictionary = defaultdict(int)<br>        self._lock = threading.Lock()<br>    <br>    # 3. Define the task/function that would clean data and count the words<br>    def task_clean_and_count(self, chunk, thread_name):<br>        print(f&quot;{thread_name} starting work&quot;)<br>        for index in range(len(chunk)):<br>            # print(f&quot;Thread {thread_name}: Page {index}&quot;<br>            input_text = chunk[index].get_text()<br>            # time.sleep(0.5)<br><br>            # Clean and process text<br>            cleaned = re.sub(r&#39;[^A-Za-z\s]&#39;, &#39;&#39;, input_text).lower()<br>            cleaned = re.sub(r&#39;\s+&#39;, &#39; &#39;, cleaned).strip()<br>            words = cleaned.split()<br>            <br>            # Update shared dictionary with lock (page by page)<br>            with self._lock:<br>                # print(f&quot;{thread_name} acquired lock&quot;)<br>                for word in words:<br>                    if word not in stop_words:<br>                        self.word_count_dictionary[word] += 1<br>                # print(f&quot;{thread_name} released lock&quot;)<br> <br>        print(f&quot;Thread {thread_name}: update complete&quot;)<br>    <br> <br>if __name__ == &quot;__main__&quot;:<br>    <br>        # 1. Read the document sequentially, that mean not through multithreading but with the main thread instead<br>        doc = fitz.open(&#39;harry-potter-and-the-philosophers-stone-by-jk-rowling.pdf&#39;)<br>        num_pages = len(doc)<br>        <br>        # 2. Divide data into two chunks for two threads<br>        mid = num_pages // 2<br>        chunk1 = doc[:mid]<br>        chunk2 = doc[mid:]<br> <br>        print(&quot;Starting Task.&quot;)<br>        start_time = time.time()<br>        <br>        # 4. Define two threads that will execute the function<br>        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:<br>            executor.submit(word_count.task_clean_and_count, chunk1, &#39;thread_jo&#39;)<br>            executor.submit(word_count.task_clean_and_count, chunk2, &#39;thread_ss&#39;)<br> <br>        print(&quot;Task Ended.&quot;)<br> <br>        end_time = time.time()<br>        total_time = end_time - start_time<br>        print(f&quot;Total time taken: {total_time:.2f} seconds&quot;)<br>        <br>        # 5. Get the final shared frequency count dictionary<br>        top_words = sorted(word_count.word_count_dictionary.items(), key=lambda i: -i[1])[:10]<br>        print(f&quot;Top 10 words: {top_words}&quot;)</pre><h3><strong>Is Multithreading helpful?</strong></h3><p><em>She was confused and asked, “What’s even the point of both of us working? The time would be the same even if just one of us did the work.”</em></p><p>And she’s right. Multithreading might be more helpful in scenarios where there’s a mix of works — for example, if we had to fetch documents from outside our apartment (CPU), which is an I/O (Input/Output) task. In that case, we could save time when one person is calculating while the other is waiting for documents to arrive.</p><p><em>“It’s confusing, though,” she said. “Doesn’t that GIL thing you mentioned stop that from happening, like running two threads at the same time?”</em></p><p>So, <strong>counting words is a CPU-bound task, but reading files is an I/O-bound task. The GIL only limits Python code running on the CPU</strong>. If a thread is just waiting for something, like file or network access, it can let go of the GIL, and other threads can work in the meantime. So, when both types of work are involved, threads can still help since there is <strong>an overlap of waiting time with useful work.</strong></p><p><em>She understood but wasn’t fully convinced about using multithreading for this problem, and once again, she’s right.</em></p><h3><strong>How we optimized our time and what’s next?</strong></h3><p>Before I could tell her about the solution that might actually speed things up, our Uber arrived. So, while we were busy discussing multithreading in our apartment (CPU), she had already booked the cab (I/O) in parallel. Our conversation and the I/O task overlapped, thus saving time. <em>So, I guess, in the end, the two of us threads did manage to optimize our time a bit.</em></p><p>Let’s end with <strong>a scenario where multithreading might be helpful</strong>. Say we are web scraping and organizing metadata for a database. While organizing data is a CPU-bound operation and cannot be sped up using multiple threads (due to Python’s GIL), web scraping is an I/O-bound operation and can be parallelized using multithreading. So, while some threads are busy waiting for web responses, others can work on organizing data, effectively overlapping waiting time with useful work.</p><p><strong>But what can speed up CPU-bound tasks?</strong> Multiprocessing, maybe. We’ll save that for another random Friday, and you can find out in the next article if she’s convinced. Fingers crossed!!</p><p>References -</p><p><a href="https://realpython.com/intro-to-python-threading/">https://realpython.com/intro-to-python-threading/</a></p><p><a href="https://realpython.com/python-gil/">https://realpython.com/python-gil/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8e4b44f99aa" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/multithreading-caveats-101-two-threads-one-random-friday-c8e4b44f99aa">Multithreading Caveats 101: Two Threads, One random Friday</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Parallel Computing Principles to Programming for CPU and GPU Architectures]]></title>
            <link>https://medium.com/data-science/from-parallel-computing-principles-to-programming-for-cpu-and-gpu-architectures-dd06e1f30586?source=rss-f71048cbf6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd06e1f30586</guid>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[getting-started]]></category>
            <dc:creator><![CDATA[Shreya Shukla]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 17:59:43 GMT</pubDate>
            <atom:updated>2024-11-14T18:47:46.482Z</atom:updated>
            <content:encoded><![CDATA[<h4>For early ML Engineers and Data Scientists, to understand memory fundamentals, parallel execution, and how code is written for CPU and GPU.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mmGagEU0PoNCGycZ" /><figcaption>Photo by <a href="https://unsplash.com/@olav_ahrens?utm_source=medium&amp;utm_medium=referral">Olav Ahrens Røtne</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article aims to explain the fundamentals of parallel computing. We start with the basics, including understanding shared vs. distributed architectures and communication within these systems. We will explore GPU architecture and how coding elements (using C++ Kokkos) help map architectural principles to code implementation. Finally, we will measure performance metrics (speedup) using the runtime data obtained from running the Kokkos code on both CPU and GPU architectures for vector-matrix multiplication, one of the most common operations in the machine learning domain.</p><p>The central theme of the article is exploring and answering questions. It may seem like a lengthy journey, but it will be worth it. Let’s get started!</p><h3>Fundamentals of System Architecture</h3><h4>I get that parallel computing saves time by running multiple operations at once. But I’ve heard that system time is different from human time or wall-clock time. How is it different?</h4><p>The smallest unit of time in computing is called a <strong>clock tick</strong>. It represents the minimum time required to perform an operation, such as fetching data, executing computations, or during communication. A <strong>clock tick </strong>technically refers to the change of state necessary for an instruction.<strong> </strong>The state can be processor state, data state, memory state, or control signals.<strong> </strong>In one clock tick, a complete instruction, part of an instruction, or multiple instructions may be executed.</p><p><strong>CPU allows for a limited number of state changes per second</strong>. For example, a CPU with 3GHz clock speed allows for 3 billion changes of state per second. There is a limit to the allowable clock speed because each clock tick generates heat, and excessive speed can damage the CPU chip due to the heat generated.</p><p>Therefore, we want to utilize the available capacity by using parallel computing methodologies. The purpose is to hide <strong>memory latency</strong> (the time it takes for the first data to arrive from memory), increase <strong>memory bandwidth </strong>(the amount of data transferred per unit of time), and enhance <strong>compute throughput</strong> (the tasks performed in a clock tick).</p><p>To compare <strong>performance</strong>, such as when calculating efficiency of a parallel program, we use wall-clock time instead of clock ticks, since it includes all real-time overheads like memory latency and communication delays, that cannot be directly translated to clock ticks.</p><h4>What does the architecture of a basic system look like?</h4><p>A system can consist of a single processor, a node, or even a cluster. Some of the <strong>physical</strong> building blocks of a system are —</p><ol><li><strong>Node</strong> — A physical computer unit that has several processor chips. Multiple nodes combine to form a <strong>cluster</strong>.</li><li><strong>Processor Chips </strong>— Chips contain multiple processing elements called cores.</li><li><strong>Core</strong> — Each core is capable of running an independent <strong>thread</strong> of execution.</li></ol><p>In set terms, a node can have a one-to-many relationship with processor chips, and each processor chip can have a one-to-many relationship with cores. The image below gives a visual description of a node with processors and cores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*WCT5M5lJU1hPwn0zS2Xiig.gif" /><figcaption>Modern node with four eight-core processors that share a common memory pool. Ref: <a href="https://cvw.cac.cornell.edu/parallel/hpc/nodes">Cornell Virtual Workshop</a></figcaption></figure><p>The <strong>non-physical </strong>components of a system include threads and processes —</p><ol><li><strong>Thread</strong> — Thread is a <strong>sequence of CPU instructions</strong> that operating system treats as a single unit for scheduling and execution purposes.</li><li><strong>Process </strong>— In computing, a process is a <strong>coherent unit</strong> of resource allocation, including memory, file handlers, ports and devices. A single process may manage resources for several threads. <a href="https://cvw.cac.cornell.edu/parallel/terminology/threads-processes">Threads can be modelled as components of a process.</a></li></ol><h4>So, do threads run on cores on the same system, or can they be spread across different systems for a single program? And in either case, how do they communicate? How’s memory handled for these threads ? Do they share it, or do they each get their own separate memory?</h4><p>A single program can execute across multiple cores on the same or different systems/ nodes. The design of the system and the program determines whether it aligns with the desired execution strategy.</p><p>When designing a system, three key aspects must be considered: <strong>execution </strong>(how threads run), <strong>memory access</strong> (how memory is allocated to these threads), and <strong>communication</strong> (how threads communicate, especially when they need to update the same data). It’s important to note that these aspects are mostly interdependent.</p><p><strong>Execution</strong></p><p><strong>Serial execution<em> </em></strong><em>— </em>This uses a single thread of execution to work on a single data item at any time.</p><p><strong>Parallel execution </strong>— In this, more than one thing happens simultaneously. In computing, this can be —</p><ol><li><strong>One worker </strong>— A single thread of execution operating on multiple data items simultaneously (vector instructions in a CPU). Imagine a single person sorting a deck of cards by suit. With four suits to categorize, the individual must go through the entire deck to organize the cards for each suit.</li><li><strong>Working Together</strong> — Multiple threads of execution in a single process. It is equivalent to multiple people working together to sort a single deck of cards by suit.</li><li><strong>Working Independently</strong> — Multiple processes can work on the same problem, utilizing either the same node or multiple nodes. In this scenario, each person would be sorting their deck of cards.</li><li>Any combination of the above.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mxYaX9oCVZ1agibGg7CvQ.gif" /><figcaption>Working Together: Two workers need to insert cards from the same suit. Worker A is holding the partial results<br>for the clubs suit, so Worker B is temporarily blocked. Ref: <a href="https://cvw.cac.cornell.edu/parallel/intro/working-together">Cornell Virtual Workshop</a></figcaption></figure><p><strong>Memory Access</strong></p><ol><li><strong>Shared Memory </strong>— When a program runs on multiple cores (<strong>a single multithreaded process</strong>) on the same system, each thread within the process has access to memory in the same virtual address space.</li><li><strong>Distributed Memory </strong>— A distributed memory design is employed when a program utilizes <strong>multiple processes</strong> (whether on a single node or across different nodes). In this architecture, each process owns a portion of the data, and other processes must send messages to the owner to update their respective parts. Even when multiple processes run on a single node, each has its own virtual memory space. Therefore, such processes should use distributed memory programming for communication.</li><li><strong>Hybrid Strategy </strong>— <strong>Multithreaded processes</strong> that can run on the same or different nodes, designed to use multiple cores on a single node through shared memory programming. At the same time, they can employ distributed memory strategies to coordinate with processes on other nodes. Imagine multiple people or threads working in multiple cubicles in the image above. Workers in the same cubicle communicate using shared memory programming, while those in different cubicles interact through distributed memory programming.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lspL31BaeZGB8CTI4O5AKg.gif" /><figcaption>In a distributed memory design, parallel workers are assigned to different cubicles (processes). Ref: <a href="https://cvw.cac.cornell.edu/parallel/terminology/tasks">Cornell Virtual Workshop</a></figcaption></figure><p><strong>Communication</strong></p><p>The communication mechanism depends on the memory architecture. In <strong>shared memory architectures</strong>, application programming interfaces like <strong>OpenMP </strong>(Open Multi-Processing)<strong> </strong>enable communication between threads that share memory and data. On the other hand, <strong>MPI </strong>(Message Passing Interface) can be used for communication between processes running on the same or different nodes in <strong>distributed memory architectures</strong>.</p><h3>Parallelization Strategy and Performance</h3><h4>How can we tell if our parallelization strategy is working effectively?</h4><p>There are several methods, but here, we discuss efficiency and speedup. In parallel computing, efficiency refers to the proportion of available resources that are actively utilized during a computation. It is determined by comparing the actual resource utilization against the peak performance, i.e., optimal resource utilization.</p><p><strong>Actual processor utilization </strong>refers to the number of floating point operations (FLOP) performed over a specific period.</p><p><strong>Peak performance</strong> assumes that each processor core executes the maximum possible FLOPs during every clock cycle.</p><p><strong>Efficiency for parallel code</strong> is the ratio of actual floating-point operations per second (FLOPS) to the peak possible performance.</p><p><strong>Speedup </strong>is used to assess efficiency and is measured as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*nqn0qZIR1DiE0OcMd5l-JA.png" /></figure><p><a href="https://cvw.cac.cornell.edu/parallel/efficiency/about-efficiency">Speedup cannot be greater than the number of parallel resources</a> when programs are limited by computing speed of the processors.</p><p>Using speedup, parallel efficiency is measured as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*NzwvyEFj7F4JeqebOiMVew.png" /></figure><blockquote><a href="https://cvw.cac.cornell.edu/parallel/efficiency/about-efficiency"><em>Hence, a worthy goal for optimization of a parallel program is to bring its speedup as close as possible to the number of cores.</em></a></blockquote><p>Suppose the serial execution of code took 300 seconds. After parallelizing the tasks using 50 cores, the overall wall-clock<strong> </strong>time for parallel execution was 6 seconds. In this case, the speedup can be calculated as the wall-clock time for serial execution divided by the wall-clock time for parallel execution, resulting in a speedup of 300s/6s = 50. We get parallel efficiency by dividing the speedup by the number of cores, 50/50 ​= 1. This is an example of the best-case scenario: the workload is perfectly parallelized, and all cores are utilized efficiently.</p><h4>Will adding more computing units constantly improve performance if the data size or number of tasks increases?</h4><p>Only sometimes. In parallel computing, we have two types of scaling based on the problem size or the number of parallel tasks.</p><p><strong>Strong Scaling</strong> — Increasing the number of parallel tasks while keeping the problem size constant. However, even as we increase the number of computational units (cores, processors, or nodes) to process more tasks in parallel, there is an overhead associated with communication between these units or the host program, such as the time spent sending and receiving data.</p><blockquote><a href="https://cvw.cac.cornell.edu/parallel/efficiency/scaling"><em>Strong scaling performance is affected by the ratio of time communicating to the time spent computing. The larger the ratio, worse the strong scaling behaviour will be.</em></a></blockquote><p>Ideally, the execution time decreases as the number of parallel tasks increases. However, if the code doesn’t get faster with strong scaling, it could indicate that we’re using too many tasks for the amount of work being done.</p><p><strong>Weak Scaling — </strong>In this, problem size increases as the number of tasks increase, so computation per task remains constant. If your program has good weak scaling performance, you can run a problem twice as large on twice as many nodes in the same wall-clock time.</p><h4>There are restrictions around what we can parallelize since some operations can’t be parallelized. Is that right?</h4><p>Yes, parallelizing certain sequential operations can be quite challenging. Parallelizing depends on multiple instruction streams and/or multiple data streams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TVd6CHtrR8QIw2vUoYumuA.png" /><figcaption>Different types of parallel computing architectures. Ref: <a href="https://cvw.cac.cornell.edu/parallel/hpc/taxonomy-parallel-computers">Cornell Virtual Workshop</a></figcaption></figure><p>To understand what can be parallelized, let’s look at SIMD in CPUs, which is achieved using vectorization.</p><blockquote><em>Vectorization is a programming technique in which operations are applied to entire arrays at once rather than processing individual elements one by one. It is achieved using the vector unit in processors, which includes vector registers and vector instructions.</em></blockquote><p>Consider a scenario where we iterate over an array and perform multiple operations on a single element within a for loop. When the data is independent, writing vectorizable code becomes straightforward; see the example below:</p><pre>do i, n<br>  a(i) = b(i) + c(i)<br>  d(i) = e(i) + f(i)<br>end do</pre><p>In this loop, each iteration is independent — meaning a(i) is processed independently of a(i+1) and so on. Therefore, this code is vectorizable, that will allow multiple elements of array a to be computed in parallel using elements from b and c, as demonstrated below:</p><pre>b:  | b(i) | b(i+1) | b(i+2) | b(i+3) | ... |<br>c:  | c(i) | c(i+1) | c(i+2) | c(i+3) | ... |<br>------------------------------------------------<br>           Vectorized Addition (SIMD)<br><br>Vector Register 1 (loaded with b values):<br>      | b(i)   | b(i+1) | b(i+2) | b(i+3) | ... |<br><br>Vector Register 2 (loaded with c values):<br>      | c(i)   | c(i+1) | c(i+2) | c(i+3) | ... |<br><br>------------------------------------------------<br>Result in Vector Register 3:<br>      | a(i)   | a(i+1) | a(i+2) | a(i+3) | ... |</pre><blockquote><em>Modern compilers are generally capable of analyzing such loops and transforming them into sequences of vector operations. </em><a href="https://cvw.cac.cornell.edu/vector/coding/data-dependencies"><em>Problem arises when an operation in one iteration depends upon the result of a previous iteration. In this case, automatic vectorization might lead to incorrect results. This situation is known as a data dependency.</em></a></blockquote><p>Data dependencies commonly encountered in scientific code are -</p><p><strong>Read After Write (RAW) </strong>— <em>Not Vectorizable</em></p><pre>do i, n<br>  a(i) = a(i-1) +b(i)</pre><p><strong>Write After Read (WAR) </strong>— <em>Vectorizable</em></p><pre>do i, n<br>  a(i) = a(i+1) +b(i)</pre><p><strong>Write After Write (WAW)</strong> — <em>Not Vectorizable</em></p><pre>do i, n<br>  a(i%2) = a(i+1) +b(i)</pre><p><strong>Read After Read (RAR) </strong>— <em>Vectorizable</em></p><pre>do i, n<br>  a(i) = b(i%2) + c(i)</pre><p>Adhering to certain standard rules for vectorization — such as ensuring independent assignments in loop iterations, avoiding random data access, and preventing dependencies between iterations — can help write vectorizable code.</p><h3>GPU architecture and cross-architectural code</h3><h4>When data increases, it makes sense to parallelize as many parallelizable operations as possible to create scalable solutions, but that means we need bigger systems with lots of cores. Is that why we use GPUs? How are they different from CPUs, and what leads to their high throughput?</h4><p>YES!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMELFXYisIQC9hlacy6iIQ.png" /><figcaption>Comparing the relative capabilities of the basic elements of CPU and GPU architectures. Ref:<a href="https://cvw.cac.cornell.edu/gpu-architecture/gpu-characteristics/design"> Cornell Virtual Workshop</a></figcaption></figure><p><strong>GPUs (Graphics processing units) </strong>have many more processor units (green) and higher aggregate <em>memory bandwidth</em> (the amount of data transferred per unit of time) as compared to CPUs, which, on the other hand, have more sophisticated instruction processing and faster clock speed. As seen above, CPUs have more cache memory than GPUs. However, CPUs have fewer arithmetic logic units (ALUs) and floating point units (FPUs) than GPUs. Considering these points, <strong>using CPUs for complex workflow and GPUs for computationally intensive tasks is intuitive.</strong></p><p><a href="https://cvw.cac.cornell.edu/gpu-architecture/gpu-characteristics/performance">GPUs are designed to produce high computational throughput</a> using their massively parallel architecture. Their computational potential can be measured in billions of floating point operations per second (GFLOPS). GPU hardware comes in the form of standard graphic cards (NVIDIA quad), High-end accelerator cards (NVIDIA Tesla), etc.</p><p>Two key properties of the graphics pipeline that enable parallelization and, thus, high throughput are —</p><ol><li><strong>Independence of Objects — </strong>A typical graphics scene consists of many independent objects; each object can be processed separately without dependencies on the others.</li><li><strong>Uniform Processing Steps — </strong>The sequence of processing steps is the same for all objects.</li></ol><h4>So, multiple cores of GPUs work on different data at the same time, executing computations in parallel like a SIMD (Single Instruction Multiple Data) architecture. How are tasks divided between cores? Does each core run a single thread like in the CPU?</h4><p>In a GPU, <strong>Streaming Multiprocessors (SMs)</strong> are similar to cores in a CPU. Cores in GPUs are similar to vector lanes in CPUs. SMs are the hardware units that house cores.</p><p>When a function or computation, referred as a <strong>kernel, </strong>is executed on the GPU, it is often broken down into <strong>thread blocks</strong>. These thread blocks contain <strong>multiple threads; </strong>each SM can manage many threads across its cores. If there are more thread blocks than SMs, multiple thread blocks can be assigned to a single SM. Also, multiple threads can run on a single core.</p><p><a href="https://cvw.cac.cornell.edu/gpu-architecture/gpu-characteristics/simt_warp">Each SM further divides the <strong>thread blocks</strong> into groups called <strong>warps</strong>, with each warp consisting of <strong>32 threads</strong>.</a> These threads execute the same stream of instructions on different data elements, following a <strong>Single Instruction, Multiple Data (SIMD)</strong> model. The warp size is set to 32 because, in NVIDIA’s architecture, CUDA cores are grouped into sets of 32. This enables all threads in a warp to be processed together in parallel by the 32 CUDA cores, achieving high efficiency and optimized resource utilization.</p><p>In <strong>SIMD (Single Instruction, Multiple Data)</strong>, a single instruction acts uniformly on all data elements, with each data element processed in exactly the same way. <strong>SIMT (Single Instruction, Multiple Threads)</strong>, which is commonly used in GPUs, relaxes this restriction. In SIMT, threads can be activated or deactivated so that instruction and data are processed in active threads; however, the local data remains unchanged on inactive threads.</p><h4>I want to understand how we can code to use different architectures. Can similar code work for both CPU and GPU architectures? What parameters and methods can we use to ensure that the code efficiently utilizes the underlying hardware architecture, whether it’s CPUs or GPUs?</h4><p>Code is generally written in high-level languages like C or C++ and must be converted into binary code by a compiler since machines cannot directly process high-level instructions. While both GPUs and CPUs can execute the same kernel, as we will see in the example code, we need to use directives or parameters to run the code on a specific architecture to compile and generate an instruction set for that architecture. This approach allows us to use architecture-specific capabilities. To ensure compatibility, we can specify the appropriate flags for the compiler to produce binary code optimized for the desired architecture, whether it is a CPU or a GPU.</p><p>Various coding frameworks, such as SYCL, CUDA, and Kokkos, are used to write kernels or functions for different architectures. In this article, we will use examples from Kokkos.</p><p><strong>A bit about Kokkos — </strong>An open-source C++ programming model for performance portability for writing Kernels: it is implemented as a template library on top of CUDA, OpenMP, and other backends and aims to be descriptive, in the sense that we define <em>what</em> we want to do rather than prescriptive (how we want to do it). Kokkos Core provides a programming model for parallel algorithms that uses many-core chips and shares memory across those cores.</p><p>A <strong>kernel</strong> has three components —</p><ol><li><strong>Pattern — </strong>Structure of the computation: for, scan, reduction, task-graph</li><li><strong>Execution policy — </strong>How computations are executed: static scheduling, dynamic scheduling, thread teams.</li><li><strong>Computational Body — </strong>Code which performs each unit of work. e.g., loop body</li></ol><p>Pattern and policy drive computational body. In the example below, used just for illustration, ‘for<strong>’</strong> is the <em>pattern</em><strong>, </strong>the <em>condition</em> to control the pattern (element=0; element&lt;n; ++element) is the <em>policy</em>, and the <em>computational body</em> is the code executed within the pattern</p><pre>for (element=0; element&lt;n; ++element){<br>  total = 0;<br>  for(qp = 0; qp &lt; numQPs; ++qp){<br>    total += dot(left[element][qp], right[element][qp]);<br>  } <br>  elementValues[element] = total;<br>}</pre><p>The Kokkos framework allows developers to define parameters and methods based on three key factors: where the code will run <strong>(Execution Space)</strong>, what memory resources will be utilized <strong>(Memory Space)</strong>, and how data will be structured and managed <strong>(Data Structure and Data management</strong>).</p><p>We primarily discuss how to write the Kokkos kernel for the <strong>vector-matrix product</strong> to understand how these factors are implemented for different architectures.</p><p>But before that, let’s discuss the building blocks of the kernel we want to write.</p><p><strong>Memory Space —</strong></p><p>Kokkos provides a range of memory space options that enable users to control memory management and data placement on different computing platforms. Some commonly used memory spaces are —</p><ol><li><strong>HostSpace — </strong>This memory space represents the CPU’s main memory. It is used for computations on the CPU and is typically the default memory space when working on a CPU-based system.</li><li><strong>CudaSpace — </strong>CudaSpace is used for NVIDIA GPUs with CUDA. It provides memory allocation and management for GPU devices, allowing for efficient data transfer and computation.</li><li><strong>CudaUVMSpac — </strong>For Unified Virtual Memory (UVM) systems, such as those on some NVIDIA GPUs, CudaUVMSpace enables the allocation of memory accessible from both the CPU and GPU without explicit data transfers. Cuda runtime automatically handles data movement at a performance hit.</li></ol><p>It is also essential to discuss <strong>memory layout</strong>, which refers to the organization and arrangement of data in memory. Kokkos provides several memory layout options to help users optimize their data storage for various computations. Some commonly used memory layouts are —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*3bh5KUgypepnKvY6sCrRKg.png" /><figcaption>Row-major vs Column-major iteration of a matrix. Ref: <a href="https://en.wikipedia.org/wiki/Row-_and_column-major_order">Wikipedia</a></figcaption></figure><ol><li><strong>LayoutRight (also known as Row-Major) </strong>is the default memory layout for multi-dimensional arrays in C and C++. In LayoutRight, the rightmost index varies most rapidly in memory. If no layout is chosen, the default layout for HostSpace is LayoutRight.</li><li><strong>LayoutLeft (also known as Column-Major) — </strong>In LayoutLeft, the leftmost index varies most rapidly in memory. If no layout is chosen, the default layout for CudaSpace is LayoutLeft.</li></ol><p>In the programmatic implementation below, we defined memory space and layout as macros based on the compiler flag ENABLE_CUDA, which will be True if we want to run our code on GPU and False for CPU.</p><pre>    // ENABLE_CUDA is a compile time argument with default value true<br>    #define ENABLE_CUDA true<br>    <br>    // If CUDA is enabled, run the kernel on the CUDA (GPU) architecture<br>    #if defined(ENABLE_CUDA) &amp;&amp; ENABLE_CUDA<br>        #define MemSpace Kokkos::CudaSpace<br>        #define Layout Kokkos::LayoutLeft<br>    #else<br>    // Define default values or behavior when ENABLE_CUDA is not set or is false<br>        #define MemSpace Kokkos::HostSpace<br>        #define Layout Kokkos::LayoutRight<br>    #endif</pre><p><strong>Data Structure and Data Management —</strong></p><p><strong>Kokkos Views <em>— </em></strong>In Kokkos, a “view” is a <strong>fundamental data structure</strong> representing one-dimensional and multi-dimensional arrays, which can be used to store and access data efficiently. Kokkos views provide a high-level abstraction for managing data and is designed to work seamlessly with different execution spaces and memory layouts.</p><pre>    // View for a 2d array of data type double<br>    Kokkos::View&lt;double**&gt; myView(&quot;myView&quot;, numRows, numCols);<br>    // Access Views<br>    myView(i, j) = 42.0; <br>    double value = myView(i, j);</pre><p><strong>Kokkos Mirroring technique for data management </strong>— Mirrors are views of equivalent arrays residing in possible different memory spaces, which is when we need data in both CPU and GPU architecture. This technique is helpful for scenarios like reading data from a file on the CPU and subsequently processing it on the GPU. Kokkos’ mirroring creates a mirrored view of the data, allowing seamless sharing between the CPU and GPU execution spaces and facilitating data transfer and synchronization.</p><p>To create a mirrored copy of the primary data, we can use Kokkos’<em> create_mirror_view()</em> function. This function generates a mirror view in a specified execution space (e.g., GPU) with the same data type and dimensions as the primary view.</p><pre>    // Intended Computation -<br>    // &lt;y, A*x&gt; = y^T * A * x<br>    // Here:<br>    // y and x are vectors.<br>    // A is a matrix.<br>    <br>    // Allocate y, x vectors and Matrix A on device<br>    typedef Kokkos::View&lt;double*, Layout, MemSpace&gt;   ViewVectorType;<br>    typedef Kokkos::View&lt;double**, Layout, MemSpace&gt;  ViewMatrixType;<br>    <br>    // N and M are number of rows and columns<br>    ViewVectorType y( &quot;y&quot;, N );<br>    ViewVectorType x( &quot;x&quot;, M );<br>    ViewMatrixType A( &quot;A&quot;, N, M );<br>    <br>    // Create host mirrors of device views<br>    ViewVectorType::HostMirror h_y = Kokkos::create_mirror_view( y );<br>    ViewVectorType::HostMirror h_x = Kokkos::create_mirror_view( x );<br>    ViewMatrixType::HostMirror h_A = Kokkos::create_mirror_view( A );<br><br>    // Initialize y vector on host.<br>    for ( int i = 0; i &lt; N; ++i ) {<br>        h_y( i ) = 1;<br>    }<br><br>    // Initialize x vector on host.<br>    for ( int i = 0; i &lt; M; ++i ) {<br>        h_x( i ) = 1;<br>    }<br><br>    // Initialize A matrix on host.<br>    for ( int j = 0; j &lt; N; ++j ) {<br>        for ( int i = 0; i &lt; M; ++i ) {<br>            h_A( j, i ) = 1;<br>        }<br>    }<br><br>    // Deep copy host views to device views.<br>    Kokkos::deep_copy( y, h_y );<br>    Kokkos::deep_copy( x, h_x );<br>    Kokkos::deep_copy( A, h_A );</pre><p><strong>Execution Space —</strong></p><p>In Kokkos, the <strong>execution space</strong> refers to the specific computing environment or hardware platform where parallel operations and computations are executed. Kokkos abstracts the execution space, enabling code to be written in a descriptive manner while adapting to various hardware platforms.</p><p>We discuss two primary execution spaces —</p><ol><li><strong>Serial</strong>: The Serial execution space is a primary and portable option suitable for single-threaded CPU execution. It is often used for debugging, testing, and as a baseline for performance comparisons.</li><li><strong>Cuda</strong>: The Cuda execution space is used for NVIDIA GPUs and relies on CUDA technology for parallel processing. It enables efficient GPU acceleration and management of GPU memory.</li></ol><p>Either the ExecSpace can be defined, or it can be determined dynamically based on the Memory space as below:</p><pre><br>// Execution space determined based on MemorySpace<br>using ExecSpace = MemSpace::execution_space;</pre><h4>How can we use these building blocks to write an actual kernel? Can we use it to compare performance between different architectures?</h4><p>For the purpose of writing a kernel and performance comparison, we use following computation:</p><pre>&lt;y, A*x&gt; = y^T * (A * x)<br><br>Here:<br><br>y and x are vectors.<br><br>A is a matrix.<br><br>&lt;y, A*x&gt; represents the inner product or dot product of vectors y <br>and the result of the matrix-vector multiplication A*x.<br><br>y^T denotes the transpose of vector y.<br><br>* denotes matrix-vector multiplication.</pre><p>The kernel for this operation in Kokkos —</p><pre>    // Use a RangePolicy.<br>    typedef Kokkos::RangePolicy&lt;ExecSpace&gt;  range_policy;<br><br>    // The below code is run for multiple iterations across different <br>    // architectures for time comparison<br>    Kokkos::parallel_reduce( &quot;yAx&quot;, range_policy( 0, N ),<br>                KOKKOS_LAMBDA ( int j, double &amp;update ) {<br>                    double temp2 = 0;<br><br>                    for ( int i = 0; i &lt; M; ++i ) {<br>                        temp2 += A( j, i ) * x( i );<br>                    }<br>                    update += y( j ) * temp2;<br>            }, result );</pre><p>For the above kernel, parallel_reduce serves as the pattern, range_policy defines the policy, and the actual operations constitute the computational body.</p><p>I executed this kernel on a TACC Frontera node which has an NVIDIA Quadro RTX 5000 GPU. The experiments were performed with varying values of <strong>N</strong>, which refers to the lengths of the vectors <strong>y</strong> and <strong>x</strong>, and the number of rows in matrix <strong>A</strong>. Computation was performed 100 times to get notable results, and the execution time of the kernel was recorded for both Serial (Host) and CUDA execution spaces. I used <strong>ENABLE_CUDA</strong> compiler flag to switch between execution environments: <strong>True</strong> for GPU/CUDA execution space and <strong>False</strong> for CPU/serial execution space. The results of these experiments are presented below, with the corresponding speedup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a5ac03f862523e450722ea6518c61b1/href">https://medium.com/media/0a5ac03f862523e450722ea6518c61b1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJAOH1-RgGlhuI9oHe0u_g.png" /><figcaption>Speedup trend for varying data size (GPU vs CPU) Ref: Image by author</figcaption></figure><p>We notice that the speedup increases significantly with the size of N, indicating that the CUDA implementation becomes increasingly advantageous for larger problem sizes.</p><p>That’s all for now! I hope this article has been helpful in getting started on the right foot in exploring the domain of computing. Understanding the basics of the GPU architecture is crucial, and this article introduces one way of writing cross-architectural code that I experimented with. However, there are several methods and technologies worth exploring.</p><p>While I’m not a field expert, this article reflects my learning journey from my brief experience working at TACC in Austin, TX. I welcome feedback and discussions, and I would be happy to assist if you have any questions or want to learn more. Please refer to the excellent resources below for further learning. Happy computing!</p><h4>Acknowledgments</h4><p>This article draws from three primary sources. The first is the graduate-level course <strong>SDS394: Scientific and Technical Computing at UT Austin</strong>, which provided essential background knowledge on single-core multithreaded systems. The second is the <a href="https://cvw.cac.cornell.edu/parallel"><strong>Cornell Virtual Workshop: Parallel Programming Concepts and High Performance Computing</strong></a>, an excellent resource for learning about parallel computing. The Kokkos code implementation is primarily based on materials available at <a href="https://github.com/kokkos/kokkos-tutorials"><strong>Kokkos Tutorials on GitHub</strong></a>. These are all amazing resources for anyone interested in learning more about parallel computing.</p><p>— — — — — — — — — —</p><p>The development of C++ Kokkos kernels for performance comparison across different architectures was part of a project supported by the <strong>Intel OneAPI Center of Excellence</strong> and the <strong>TACC STAR Scholars program</strong>, funded through generous contributions from TACC industry partners, including <strong>Intel, Shell, Exxon,</strong> and <strong>Chevron</strong>.</p><p>— — — — — — — — — —</p><p>References/Resources:</p><ul><li><a href="https://github.com/VictorEijkhout/TheArtofHPC_pdfs/tree/main">GitHub - VictorEijkhout/TheArtofHPC_pdfs: All pdfs of Victor Eijkhout&#39;s Art of HPC books and courses</a></li><li><a href="https://docs.tacc.utexas.edu/hpc/frontera/">Frontera - TACC HPC Documentation</a></li><li><a href="https://cvw.cac.cornell.edu/parallel">Cornell Virtual Workshop: Parallel Programming Concepts and High Performance Computing</a></li><li><a href="https://cvw.cac.cornell.edu/gpu-architecture">Cornell Virtual Workshop: Understanding GPU Architecture</a></li><li><a href="https://cvw.cac.cornell.edu/vector">Cornell Virtual Workshop: Vectorization</a></li><li><a href="https://github.com/kokkos/kokkos-tutorials">GitHub - kokkos/kokkos-tutorials: Tutorials for the Kokkos C++ Performance Portability Programming Ecosystem</a></li><li><a href="https://github.com/kokkos/kokkos-tutorials/wiki/Kokkos-Lecture-Series">Kokkos Lecture Series</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd06e1f30586" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-parallel-computing-principles-to-programming-for-cpu-and-gpu-architectures-dd06e1f30586">From Parallel Computing Principles to Programming for CPU and GPU Architectures</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[t-Test : From Application to Theory]]></title>
            <link>https://medium.com/data-science/t-test-from-application-to-theory-5e5051b0f9dc?source=rss-f71048cbf6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e5051b0f9dc</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[experiment]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shreya Shukla]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 06:15:46 GMT</pubDate>
            <atom:updated>2024-07-12T06:15:46.406Z</atom:updated>
            <content:encoded><![CDATA[<h3>t-Test : From Application to Theory</h3><h4>To bridge the gap between mathematical computations and programmatic implementation of a two-sample t-Test, this article provides a step-by-step guide using a practical use case. It includes an overview of the statistical tools, the motivation behind using these tools, and an explanation of the results and their interpretation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzRCbq0YteK3d1TuvjuIwg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@steve_mushero?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Steve Mushero</a> on <a href="https://unsplash.com/photos/billiard-balls-on-billiard-table-Qok3vOrww_E?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Have you ever been stuck in a loop where you repeatedly go over the concepts of statistical tools, memorize them, and revisit them, but the concepts still don’t stick? You know how to use formulas but feel like that just gives surface-level knowledge of the concept. I was in the same boat until I TA’d for a physics lab course 105M at UT Austin and applied statistical tools relevant to the problems we were solving. It was then that I finally understood the theory and application of the Student’s t-Test, and now it truly sticks.</p><p>Let’s start with a question.</p><h4><em>Does Color Affect the Sliding Time of 2 Similar Balls Rolled Over a Ramp?</em></h4><p>Intuitively, the answer to this question might be NO! But let’s validate this hypothesis using prevalent statistical tests. In hypothesis testing terms :</p><ul><li><strong>Null Hypothesis</strong> would be that color doesn’t affect the rolling time (no effect)</li><li><strong>Alternative Hypothesis</strong> would suggest that color does affect the rolling time (there is an effect).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*nTRNuJg7i7e0yI3ZoQKHIg.png" /><figcaption>Experiment illustration — Two similar balls of different colors rolling down a ramp</figcaption></figure><h4>Data</h4><p>We start by measuring the time taken by two similar balls of different colors (for instance, one black and one red) as we roll them down the ramp one by one, in multiple trials (let’s say 10 trials each).</p><p>The difference in the rolling times obtained in different trials highlights the <strong>significance of conducting multiple trials</strong> instead of one, therefore helping in providing a more reliable estimate.</p><blockquote>It is also important to note that there can be many possible values (<strong>population</strong>) for the estimated rolling time, but we are capturing only a <strong>sample</strong> of these values with limited trials.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ad438824883f9d7e609b7d4ae43714f/href">https://medium.com/media/6ad438824883f9d7e609b7d4ae43714f/href</a></iframe><h4><strong>Best Estimate</strong></h4><p>Next, we calculate the expected value or the best estimate of the rolling time for each ball. We assume that the time recordings from different trials form a <strong>random distribution,</strong> and the expected value is best represented by the <strong>mean</strong> or the average value of the distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xh--GZSuuy5kIcMJhlEzUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdc5CQKPLdqN2avuUviKDg.png" /><figcaption>Mathematical computation for Best Estimate/Mean of the two distributions (units in seconds)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/941ef779078f88439542a46c1da94cdd/href">https://medium.com/media/941ef779078f88439542a46c1da94cdd/href</a></iframe><h4>Standard Error</h4><p>As mentioned earlier, we gathered limited data (<strong>sample</strong>) using just 10 trials out of all the possible values (<strong>population</strong>). Note that the calculated best estimate is from the sample distribution. However, to get a better estimate of the population mean, we calculate the standard error of the sample distribution. <strong>The standard error helps us determine the range within which our best estimate for the population is likely to fall. </strong>It is based on the variance of the distribution, which indicates how disperse the distribution is around mean.</p><p>To calculate the standard error, first find the standard deviation (square root of variance), then divide it by the square root of the number of data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*6Il7vAld6TNh7cvdSXtPpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZTTlOCGopdot0yUJSn1bw.png" /><figcaption>Mathematical computation for the Standard Deviation and Standard Error of the distributions (units in seconds)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc22030ff54b29b08fb1bab52cdc072/href">https://medium.com/media/4cc22030ff54b29b08fb1bab52cdc072/href</a></iframe><p>We observe that the best estimates and the standard errors for both balls are comparable (there is an overlap between the calculated ranges), prompting us to consider that distributions are similar and therfore color may not affect the rolling time of the balls. However, <strong>how statistically significant and reliable are these findings?</strong> In essence, do these values provide sufficient evidence for us to draw conclusions about the hypothesis?</p><p>To measure the certainty about our results and present evidence in a more communicable way, we use test statistics. <strong>These statistics help us measure the probability of obtaining these results, providing a measure of certainty. </strong>For instance, we use statistics like z-statistic if the population standard deviation is known and the t-statistic if only the sample standard deviation is known, as in our experiment.</p><h4>T-statistic</h4><p>We compare our two sample distributions (groups) using a <strong>Two-Sample t-Test</strong>, which relies on the best estimates and variances of the two groups. Depending on the similarity of the variances between the two groups, we decide between using <strong>pooled variance, as in Student’s t-Test for equal variances, or Welch’s t-Test, which is for unequal variances.</strong></p><blockquote>Using statistical tests such as the F-test or Levene’s test, we can assess the equality of variances.</blockquote><p>Since the calculated standard deviations (square root of variance) of both distributions are very similar, we proceed with a <strong>Student’s t-Test for equal variances</strong>. We conduct a two-tailed test to check for inequality of distributions rather than specifically looking for lesser or greater values.</p><p>We use the pooled standard deviation along with the averages obtained from our two distributions to calculate the t-score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*PSpO4Gj5kr44svRVH-YR6w.png" /><figcaption>Mathematical computation for Two sample Student’s t-Test for the two distributions</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be96b62a1c74ad170388fde3f4bceb8d/href">https://medium.com/media/be96b62a1c74ad170388fde3f4bceb8d/href</a></iframe><h4>Result Interpretation</h4><p>As we observed, the t-statistic is based on the difference of the means of the two samples. In our case, the t-statistic is very small (~-0.38), indicating that the difference between the means of the two distributions is also very small. This suggests that the recordings for the two balls are similar, hinting at the overall conclusion that color has no significant effect on the rolling time.</p><p>However, <strong>interpreting the t-statistic involves more than just observing the small difference in means</strong>, especially since we compared only two samples (limited trials) and not the entire populations. To make an informed inference, we need to determine the critical value and then compare out t-statistic with that critical value.</p><p>The <strong>critical value</strong> is determined based on the confidence interval (e.g., 95%) and the sample sizes (degrees of freedom). A <strong>95% confidence interval</strong> (CI) means that if the experiment is repeated several times, the true mean difference will fall within 95% of the calculated intervals.</p><p>To find the critical value or critical value range in our case (since we are checking for inequality), we use the t-distribution table. For a <strong>two-tailed test with a 95% CI</strong>, we look at the 0.05 significance level, which splits into 2.5% for each tail. Given our degrees of freedom (df = 18), the critical value range is approximately -2.101 to +2.101.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XG115G2Np6ETVTihJIp1uA.png" /><figcaption>Two-tailed t-distribution for for 95% Confidence interval and 18 degree of freedom</figcaption></figure><p><strong>Our t-statistic of -0.38 falls within the critical range for a 95% confidence interval, leading to two key inferences.</strong> Firstly, the observed difference in means between the rolling times of the red and black balls is very small, indicating that color has no effect on rolling time. Secondly, with 95% certainty, if we were to repeat this experiment multiple times, the true difference in means between the rolling times of the red and black balls would consistently fall within this range.</p><p><strong>Therefore, our results showing a low difference between the means of recording times for the two balls are statistically significant and reliable at the 95% confidence level, suggesting no meaningful difference in rolling times based on ball color.</strong></p><p><em>I am excited to have documented my understanding in the hope of assisting others who may have struggled, like me, with grasping these statistical tools. I look forward to seeing others implement these methods. Please feel free to reach out or refer to the references mentioned below for any unanswered questions.</em></p><p>Unless otherwise noted, all images are by the author.</p><p>References:</p><ul><li><a href="https://en.wikipedia.org/wiki/Student%27s_t-test">Student&#39;s t-test - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Standard_error">Standard error - Wikipedia</a></li><li><a href="https://numpy.org/doc/stable/reference/generated/numpy.std.html">numpy.std - NumPy v2.0 Manual</a></li><li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html">ttest_ind - SciPy v1.15.2 Manual</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e5051b0f9dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/t-test-from-application-to-theory-5e5051b0f9dc">t-Test : From Application to Theory</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DIY High-dimensional data visualisation using t-SNE!]]></title>
            <link>https://levelup.gitconnected.com/diy-high-dimensional-data-visualisation-using-t-sne-d55ef875e864?source=rss-f71048cbf6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d55ef875e864</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[image-similarity]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shreya Shukla]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 17:46:29 GMT</pubDate>
            <atom:updated>2024-07-16T16:13:24.447Z</atom:updated>
            <content:encoded><![CDATA[<h4>High-dimensional data visualization has many applications and is a simple method to effectively gauge the efficiency of classification models. It is also a valuable tool in multimodal solutions — such as those involving images, text, and signal data — for assessing the preservation of both inter-modality and intra-modality relationships. All enabled by visualising high-dimensional data into low-dimensional plots. In this article, we briefly discuss <strong>different methods to generate image embeddings</strong>. Our central objective is to provide a <strong>DIY code for generating and visualizing image embeddings</strong> generated from these methods.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*83GJ0qlVHYwloWeiJEittg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@shamblenstudios?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Shamblen Studios</a> on <a href="https://unsplash.com/photos/bunch-of-lollipops-61rFb1qnu1k?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In various use cases, high-dimensional data visualisation can help answer key questions:</p><ul><li><strong>Image Classification</strong>: How distinct are the clusters formed for similar images when visualised using embeddings generated from different methods, and how does this aid in method selection?</li><li><strong>Speech Recognition</strong>: What relationships do embeddings from the speech of the same individuals, or different individuals saying the same words, reveal?</li><li><strong>Signal Processing</strong>: Do EEG (Electroencephalogram) embeddings from patients with similar disorders cluster together, and do EEG scans for patients with normal scans exhibit similar embeddings?</li></ul><h4>Data Preparation</h4><p>We begin with data preparation using a Kaggle dataset containing images classified into 6 classes. To streamline, we select 10 images from each class. Each original image is represented as a 3-dimensional matrix of size (x * y * 3), where x and y denote the image dimensions, and 3 represents the RGB channels.</p><p>For visualization, we utilize the <strong>associated labels of the images</strong> alongside the <strong>embeddings generated from these images.</strong></p><pre># Imports<br><br>!pip install transformers<br><br>import os<br>import cv2<br>import numpy as np<br>import pandas as pd<br>from PIL import Image, ImageOps<br><br>import torch<br>from transformers import AutoImageProcessor, ResNetForImageClassification<br>from transformers import CLIPProcessor, CLIPModel<br><br>import plotly.express as px<br>import itertools<br><br>#t-SNE<br>from sklearn.manifold import TSNE<br>from sklearn.decomposition import PCA<br><br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;</pre><pre>!kaggle datasets download -d puneet6060/intel-image-classification &amp;&amp; unzip intel-image-classification.zip -d intel-image-classification</pre><pre># Function to read first 10 file names from the specified path<br>def read_10_files_from_path(directory, num_files=10):<br>    try:<br>        entries = (entry for entry in os.scandir(directory) if entry.is_file())<br>        files = list(itertools.islice(entries, num_files))<br>        return [file.path for file in files]<br>    except FileNotFoundError:<br>        return f&quot;The directory {directory} does not exist.&quot;<br>    except Exception as e:<br>        return f&quot;An error occurred: {e}&quot;<br><br># Get folder names (different labels) for images<br>base_path = &quot;/content/intel-image-classification/seg_test/seg_test&quot;<br>try:<br>    folder_names = [folder for folder in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, folder))]<br>except FileNotFoundError:<br>    print(f&quot;The directory {base_path} does not exist.&quot;)<br><br># Get Image file paths from folders (10 images each folder)<br>image_file_paths = []<br>for folder in folder_names:<br>    folder_file_paths = read_10_files_from_path(f&#39;{base_path}/{folder}&#39;)<br>    image_file_paths.extend(folder_file_paths)<br><br># Get Images from path<br># Total Images : 10 images  x 6 labels = 60 images<br>images = []<br>for image_path in image_file_paths:<br>    image = cv2.imread(str(image_path))<br>    images.append(image)<br><br># Associated labels (10 images  x 6 labels = 60 labels)<br>labels = [folder for folder in folder_names for i in range(10) ]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NX2FnlFDjohx6PUDYuOSmA.jpeg" /><figcaption>Sample Images and labels. Dataset Ref : <a href="https://www.kaggle.com/datasets/puneet6060/intel-image-classification">Intel Image Classification Dataset, Kaggle</a></figcaption></figure><p>Next, we employ three methods — image flattening, CLIP Visual Encoder, and ResNet-50 model — to generate embeddings with varying dimensions. These embeddings are then visualized in a 2D space use t-SNE plots.</p><h4>1. Flatten the Images</h4><p>The first method involves flattening the images, converting the original 3D image of size (x * y * 3) into a vector. Since the original images vary in dimensions x and y, padding is crucial to standardize all images to the same size. Consequently, the resultant embeddings from these processed images are vectors of size 67500, resulting in a <strong>67500-dimensional vector for each image.</strong></p><pre>flattened_images = []<br>for image in images:<br>    flattened_images.append(image.flatten())<br><br># Pad or truncate each image to have the same length<br>max_length = max(len(image) for image in flattened_images)<br>padded_images = [np.pad(image, (0, max_length - len(image))) if len(image) &lt; max_length else image[:max_length] for image in flattened_images]<br>padded_images = np.array(padded_images)<br><br># Preparing input for t-SNE.<br># Shape of processed_images_arr is (60, 67500), 60 images <br># each with a 1D array representation of size 67500<br>processed_images_arr = np.array(padded_images)</pre><h4>2. ResNet-50 Image Embeddings</h4><p>ResNet-50 is a widely recognized model in image classification that employs Convolutional Neural Networks (CNNs) to extract high-dimensional feature vectors from images. In this implementation, each image processed by ResNet-50 yields <strong>a 1000-dimensional feature vector</strong>.</p><pre># Load ResNet model and processor<br>resnet_model = ResNetForImageClassification.from_pretrained(&quot;microsoft/resnet-50&quot;).to(device)<br>resnet_processor = AutoImageProcessor.from_pretrained(&quot;microsoft/resnet-50&quot;)<br><br>resnet_embeddings = []<br>for image in images:<br>    inputs = resnet_processor(image, return_tensors=&quot;pt&quot;)<br>    with torch.no_grad():<br>        logits = resnet_model(**inputs).logits<br>        resnet_embeddings.append(logits)<br><br># Concatenate tensors into a single array<br>concatenated_array = np.concatenate([tensor.numpy().flatten() for tensor in resnet_embeddings], axis=0)<br><br># Preparing input for t-SNE. Input shape (60, 1000)<br>processed_images_arr = concatenated_array.reshape(len(resnet_embeddings), -1)</pre><h4>3. CLIP Image Embeddings</h4><p>CLIP is a multimodal neural network that trains an image encoder and a text encoder simultaneously to predict the correct pair of image and text from training examples. We utilize a pretrained visual encoder from CLIP to generate image embeddings, <strong>resulting in a 512-dimensional embedding for each image.</strong></p><pre># Load CLIP model and processor<br>clip_model = CLIPModel.from_pretrained(&quot;openai/clip-vit-base-patch16&quot;).to(device)<br>clip_processor = CLIPProcessor.from_pretrained(&quot;openai/clip-vit-base-patch16&quot;)<br><br>clip_embeddings = []<br>for image in images:<br>    inputs = clip_processor(images=image, return_tensors=&quot;pt&quot;).to(device)<br>    with torch.no_grad():<br>        embedding = clip_model.get_image_features(**inputs)<br>        # Move the tensor to the CPU<br>        embedding = embedding.cpu()<br>        # Convert the CPU tensor to a NumPy array<br>        embedding = embedding.numpy()<br>        clip_embeddings.append(embedding)<br><br># Preparing input for t-SNE. Input shape (60, 512)<br>processed_images_arr = np.reshape(np.array(clip_embeddings), (60, 512))</pre><h4>2d t-SNE Plot</h4><p>t-SNE (t-Distributed Stochastic Neighbor Embedding) is a probabilistic approach that computes pairwise similarities among data points in the high-dimensional space. Following this, the algorithm maps these higher-dimensional data points onto a lower-dimensional space while aiming to preserve these pairwise similarities. It aims to minimize the divergence between the probability distribution of data points in the original high-dimensional space and their counterparts in the lower-dimensional space.</p><pre># Code to generate 2d t-SNE plots from extracted embeddings<br># input : processed_images_arr<br>tsne = TSNE(random_state=0, perplexity=10)<br>projections_tsne_2d = tsne.fit_transform(processed_images_arr)<br>projections_tsne_2d_df = pd.DataFrame(projections_tsne_2d, columns=[&#39;x&#39;, &#39;y&#39;])<br><br>fig = px.scatter(<br>    projections_tsne_2d_df, x=&#39;x&#39;, y=&#39;y&#39;,<br>    color=labels, hover_data=[image_file_paths]<br>)<br>fig.update_traces(marker_size=8)<br>fig.show()</pre><p>Using embeddings of different dimensions — 67500, 1000, and 512 — we can create a 2D or 3D t-SNE plot. As observed from the plots, the ResNet-50 model effectively clusters similar images, followed by CLIP, while flattened images show random scattering. Such analysis helps in selecting the optimal method for the use cases discussed earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CprIkVlv7RUszaqf590EWQ.jpeg" /><figcaption>t-SNE plots of image embeddings obtained using various methods</figcaption></figure><p>In a nutshell, once we have an understanding of embedding dimensions, it’s a matter of plug-and-play with alternative plots like UMAP or a 3D t-SNE plot to find intriguing patterns or differences in clustering.</p><p><strong>I’m excited about the potential for others to utilize this DIY code to visualize other modalities such as signals or text. Please share your experiences if you give it a try!</strong></p><p>As a bonus, here’s the code for using PCA (Principal Component Analysis) to reduce embedding size and a 3D UMAP for further exploration.</p><p><em>Bonus Code</em></p><pre># Apply PCA to reduce dimensionality<br>clip_embeddings_reshaped = np.reshape(np.array(clip_embeddings), (60, 512))<br>pca = PCA(n_components=50)  # Choose the number of principal components<br>clip_embeddings_pca = pca.fit_transform(clip_embeddings_reshaped)</pre><pre># 3D UMAP<br><br>! pip install --upgrade umap-learn<br>import umap.umap_ as umap<br><br>projections_umap_clip = umap.UMAP(n_components=3).fit_transform(clip_embeddings_pca)<br>fig = px.scatter_3d(<br>    projections_umap_clip, x=0, y=1, z=2,<br>    color=labels, hover_data=[image_paths]<br>)<br>fig.update_traces(marker_size=8)<br>fig.show()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d55ef875e864" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/diy-high-dimensional-data-visualisation-using-t-sne-d55ef875e864">DIY High-dimensional data visualisation using t-SNE!</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence — A Reality]]></title>
            <link>https://medium.com/@shreyashukla04/artificial-intelligence-a-reality-734174b288d9?source=rss-f71048cbf6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/734174b288d9</guid>
            <category><![CDATA[uses-of-ai]]></category>
            <category><![CDATA[how-ai-works]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[fairness-and-bias]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Shreya Shukla]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 00:57:56 GMT</pubDate>
            <atom:updated>2024-03-09T04:33:53.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Intelligence — A Reality</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJJDNkLI3Tm_wtEpgR_mxQ.jpeg" /><figcaption>Source : Adobe Stock</figcaption></figure><p>Of all the things that have been said about Artificial Intelligence (AI), some are backed by science, and some are just opinions. There is a spectrum of people’s perception of AI that ranges from those who are optimistic about its possibilities to those who find it too artificial to impact their lives in any real way. This article is for a general audience but can benefit people who find it hard to understand what AI actually is, and especially those who are still in denial of its existence.</p><p>Believe it or not, AI is here to stay and is very much a ‘reality’. If you use any of the technologies or systems listed below, AI is already a part of your life:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zaMyNXkwgkQr7DXqJ9uFFA.png" /><figcaption>Figure 1 : Popular AI systems</figcaption></figure><p>Even without the information on what these icons represent; we see them and immediately understand what they represent, which is very similar to what AI systems do.</p><h4><strong>Why should we care?</strong></h4><p>Because, <strong>systems based on AI are making decisions for us</strong>. For instance, decisions such as whether a profile will be shortlisted for an interview when recruitment systems use AI to filter candidates, the kind of reels/videos social media platforms suggest to shape opinions on societal issues, and whether one would be comfortable undergoing a medical diagnosis suggested by an AI system. It’s similar to the government; every action it takes, every choice it makes impacts individuals either directly or indirectly. This analogy emphasizes how these systems have the power to influence both mundane and <strong>crucial decisions about people’s lives, work, and families</strong>. However, due to the lack of regulations in this evolving field, it becomes even more important to scrutinize these decisions.</p><p><strong>Bias in AI systems</strong> — Sometimes, a simple decision taken by a basic AI system can also have an impact, like an automatic soap dispenser in a washroom. As noted in earlier instances with automatic hand dispensers based on AI, they only worked for fair-colored hands and not for people with dark-colored hands (Bigotry Encoded: Racial Bias in Technology, n.d.). This decision seems insignificant in the sense that it wouldn’t drastically impact our lives, but what if this kind of bias exists in more critical decisions like shortlisting candidates for a job. Any form of <strong>bias based on color, region, race, or gender can be detrimental to fair access to resources and opportunities</strong>, and, most importantly, to a fair society.</p><h4><strong>How AI Works?</strong></h4><p><strong>Learn by example.</strong></p><p>Let’s develop a <strong>Pet Identification (PI) System</strong> for cats and dogs, so that when the system sees a picture of a dog, it recognizes it as a dog, and similarly for cats. This task is similar to how we recognize the Netflix icon or a country’s flag and understand their representations.</p><p>This AI based system has 2 major components -</p><ul><li><strong>Data</strong> — Images of dogs and cats with the label of whether it’s a dog or a cat.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*PBd1-WHDRwzteTGwZQ9F8A.png" /><figcaption>Figure 2 : Labeled data</figcaption></figure><p>Note that the real data will include many images of cats and dogs with various colors and sizes, but for now, let’s stick to these.</p><ul><li><strong>Algorithm</strong> — The algorithm is the brain of the AI system. It comprises a set of instructions that enable our system to learn and accurately assign labels to our pets. <strong>These instructions are learned from the data.</strong> This is what differentiates AI systems from non-AI systems, where instructions are predefined.</li></ul><h4><strong>Methodology — There are two steps that will help our PI System identify pets.</strong></h4><p><strong>First, we train the PI system — </strong>We utilize a portion of our data to <strong>‘train’ the algorithm</strong>. During this phase, we provide it with pet images along with their corresponding labels (e.g., an image of a dog with the label ‘dog’), and the algorithm learns by extracting features from the presented data.</p><p>Sample Algorithm for PI system based on our labeled data :</p><pre>If pet has bigger nose : then pet is a dog<br>If pet has whiskers : then pet is a cat<br>If pet is brown : then pet is a dog<br>If pet is black : then pet is a cat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlJXpwnL-cYC6T8f3M2paw.png" /><figcaption>Figure 3 : Training the PI system from labeled data</figcaption></figure><p>The real algorithm will be more complicated, however, the underlying concept remains the same: <strong>it learns from features within the images</strong>, such as shape, color, facial features, and the position of those facial features, among other factors.</p><p><strong>Next, we test the PI system — </strong>To test whether the PI system was able to learn well, <strong>we present unlabeled data to our Pet Identification system</strong> and evaluate the labels it generated for our images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hdoEiLEx-36knI1tWwCZw.png" /><figcaption>Figure 4 : Testing the PI system on unlabelled data</figcaption></figure><p>As observed above, our Pet Identification system was able to correctly identify each pet, classifying each Dog as Dog and Cat as Cat. This indicates that the features the algorithm extracted from the images to make these decisions are accurate.</p><p><strong>But, what will happen if other pets’ images are presented to this PI system, like a chick or a hamster?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6kYWWVAJDHWRi_54rBlOA.png" /><figcaption>Figure 5 : PI system possible incorrect results for chick and hamster</figcaption></figure><p>It might identify a chick as a cat and a hamster as a dog, or both as cats, or both as dogs. We don’t know. The point is that the system doesn’t recognize these pets, because the <strong>data for the training was limited to only cats and dogs.</strong></p><h4>Going back to the biased automatic soap dispenser</h4><p>This example has set up enough context for us to now delve deeply into the reasons behind bias in the automatic soap dispenser, which didn’t work for dark-colored hands and only worked for fair-colored hands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_6RGyIvVx4P8osQSC_ogw.png" /><figcaption>Figure 6 : Representation of a random soap dispenser that works effectively for fair-colored hands but not for dark-colored hands.</figcaption></figure><p>While there can be multiple reasons behind this bias, one possible reason is that the system didn’t have dark-colored hands in the data it was trained on. Another possibility is that the algorithm didn’t do a great job in extracting correct features from the data it was trained on, and then probably, while testing, the data wasn’t representative enough, and therefore it wasn’t tested on dark-colored hands. If the system was developed with <strong>best AI practices, like using diverse and representative dataset, ensuring effective feature extraction, and comprehensive testing</strong>, this issue could have easily been avoided.</p><h4>What can we do to ensure fair AI systems?</h4><p>AI is already making decisions for us, so it’s important that we stay proactive and begin asking questions to scrutinize these systems. We can start by getting comfortable with AI, learning about it, and reading about it. Then, <strong>we can ask questions about what data it was trained on, what data it was tested on, how representative it was, what the accuracy was, and what features were used by the algorithms to make these decisions</strong>. By asking these questions, we can identify biases and ensure that companies are creating systems that serve the public effectively. Finally, we can educate others. AI as a topic of discussion can be a little intimidating for some people, yet it’s crucial to make people aware of how these systems work. <strong>This not only sparks critical discussions but also uncovers opportunities within the field of AI.</strong></p><p>References -</p><p>Bigotry encoded: Racial bias in technology. (n.d.). <a href="https://reporter.rit.edu/tech/bigotry-encoded-racial-bias-technology">https://reporter.rit.edu/tech/bigotry-encoded-racial-bias-technology</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=734174b288d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>