<?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 Aulipriyapromona on Medium]]></title>
        <description><![CDATA[Stories by Aulipriyapromona on Medium]]></description>
        <link>https://medium.com/@aulipriyapromona?source=rss-1104c90de02c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4d1uRoKcPyIlJ6vD.jpg</url>
            <title>Stories by Aulipriyapromona on Medium</title>
            <link>https://medium.com/@aulipriyapromona?source=rss-1104c90de02c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:55:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aulipriyapromona/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[We Deleted Our DataLoader Workers and Got 2x Faster]]></title>
            <link>https://medium.com/@aulipriyapromona/we-deleted-our-dataloader-workers-and-got-2x-faster-bae8ed8bc846?source=rss-1104c90de02c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bae8ed8bc846</guid>
            <category><![CDATA[dataloader]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Aulipriyapromona]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 11:14:48 GMT</pubDate>
            <atom:updated>2026-10-28T11:14:48.442Z</atom:updated>
            <content:encoded><![CDATA[<h3>What happens when your code runs from disk and your images live in S3</h3><p>Every PyTorch tutorial gives the same advice. Training loop slow? Increase num_workers. More worker processes load images in the background while the GPU works.</p><p>That advice is right for the world it was written in: images on a local SSD, where the slow part is decoding JPEGs on the CPU.</p><p>Our images are not on a local SSD. They are in an S3 bucket, several hundred thousand of them. We wanted to run every image through a model to get an embedding per image. When we timed the pipeline, the model was not the slow part. Waiting for the network was. And every worker process we added made it slightly slower, not faster.</p><p>The obvious answer is “move the code next to the data”. Sometimes we do. But it is not always an option. A typical week looks like this: new footage lands in the bucket on Monday, someone needs embeddings by Wednesday to decide whether it goes into the next training set, and the only free GPU is the workstation under their desk. Moving that job to a cloud GPU means a quota request, a container build, permissions, and a bill that runs while the GPU sits idle waiting for bytes. For a one-off job, that is a week of setup to save an afternoon.</p><p>And “in the cloud” is not “on disk” anyway. A cloud machine in the same region still reads every image from S3 over the network. It just has a shorter cable. So wherever the code runs, the loader has to be good at pulling images out of S3.</p><p>So we did the opposite of the tutorial. We set num_workers=0 and put the parallelism inside the dataset, using threads. Throughput went from about 1.2 images per second to 2.7 on the same machine, same model, same bucket.</p><p>Here is why, with the code</p><h3>The problem, in its simplest form</h3><p>You have 100,000 JPEGs in a bucket. You want to run a model over each one. The dataset looks like this:</p><pre>import boto3<br>from io import BytesIO<br>from PIL import Image<br>from torch.utils.data import Dataset<br><br><br>class S3ImageDataset(Dataset):<br>    def __init__(self, bucket, keys, transform):<br>        self.bucket = bucket<br>        self.keys = keys            # e.g. [&quot;images/000001.jpg&quot;, &quot;images/000002.jpg&quot;, ...]<br>        self.transform = transform<br>        self.s3 = boto3.client(&quot;s3&quot;)<br><br>    def __len__(self):<br>        return len(self.keys)<br><br>    def __getitem__(self, idx):<br>        key = self.keys[idx]<br>        body = self.s3.get_object(Bucket=self.bucket, Key=key)[&quot;Body&quot;].read()<br>        image = Image.open(BytesIO(body)).convert(&quot;RGB&quot;)<br>        return self.transform(image), key</pre><p>__getitem__ does two things: download the bytes, then decode them into an image. Everything in this article comes down to how long each of those two steps takes, and who is waiting while they happen.</p><h3>How the normal DataLoader works</h3><p>The standard setup:</p><pre>loader = DataLoader(dataset, batch_size=32, num_workers=8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5tloAER-aZhD3Kh5ZRdGw.jpeg" /><figcaption>Firgure 1: Main Process hands 8 workers tasks to perform</figcaption></figure><p>PyTorch starts 8 worker processes. Each one is a separate copy of Python with its own copy of the dataset. The main process hands each worker a list of indices. The worker calls dataset[i] for each index, one after another, stacks the results into a batch, and sends the batch back to the main process. The main process feeds the GPU.</p><h4>The arithmetic: who gets what</h4><p>The intuitive picture is that the 32 images in a batch are shared out across the 8 workers, 4 each. That is not what happens.</p><p>The loader cuts the index stream into lists of 32. It gives <strong>whole lists</strong> to the workers in turn: worker 0 gets batch 0, worker 1 gets batch 1, and so on up to worker 7, then worker 0 gets batch 8.</p><p>So with batch_size=32 and num_workers=8:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwshSMOBbr3jKyydUyrQsw.jpeg" /><figcaption>Table 1</figcaption></figure><p>The last row is the important one. Inside a worker, nothing overlaps. It downloads image 1, then image 2, then image 3. So each worker has exactly one download in flight, and 8 workers means 8 downloads in flight. Not 256. Not 32. Eight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXt77q6zQjbGIzSMo5eRPw.jpeg" /><figcaption>Firgure 2: Only 8 downloads in progress</figcaption></figure><p>Call the time for one download G and the time for one decode D. Then:</p><ul><li>One worker finishes a batch in about 32 × (G + D).</li><li>The main process receives a new batch about every 32 × (G + D) / 8, because 8 workers are running.</li><li>The number of downloads in flight is always num_workers, whatever the batch size.</li></ul><p>Making the batch bigger makes each worker take longer per batch. It does not put more downloads on the wire. The only knob that adds downloads in flight is num_workers, and each extra worker is a whole extra copy of Python.</p><h3>Why this is the wrong shape for S3</h3><p>The process design assumes one thing: <strong>the slow part of </strong>__getitem__<strong> is CPU work.</strong></p><p>On a local disk that is true. Reading the file is fast. Decoding the JPEG is the slow part, and it burns CPU. Python can only run one thread of Python code at a time (the “GIL”, the global interpreter lock), so to use 8 CPU cores you need 8 processes. That is why PyTorch uses processes.</p><p>Now swap the file read for an S3 download. The picture flips.</p><p>A download of a few hundred kilobytes from S3 takes tens to hundreds of milliseconds. Decoding takes a few milliseconds. So roughly 90% of each __getitem__ is spent <strong>waiting</strong> for bytes to arrive. During that wait the CPU does nothing. The worker holds no lock and uses no core. It is just sitting on a socket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4X1KmS9UeiEpMBmebFtviA.jpeg" /><figcaption>Figure 3: Downloading takes more time than decoding the image</figcaption></figure><blockquote>Waiting is a different kind of slow. You do not fix waiting with more CPUs. You fix it by <strong>waiting on more things at once</strong>. And processes are an expensive way to wait:</blockquote><ul><li><strong>Each process is a full copy of Python.</strong> Startup cost, duplicated memory, and a separate S3 client per process, each with its own connections and its own TLS handshakes.</li><li><strong>Downloads in flight equals the number of processes.</strong> S3 will happily serve dozens of requests at once from one machine. With 8 workers you use 8. To use more you must start more copies of Python, paying CPU and memory for something the network could give you for free.</li><li><strong>Every batch is copied between processes.</strong> The worker serialises the finished tensors, pushes them through a queue, and the main process deserialises them. Real work, spent only because the work happens in a different process.</li><li><strong>Errors are awkward.</strong> Dropped connections mid-download are normal when you pull hundreds of thousands of objects. Retrying inside a forked worker without losing the batch or stalling the queue is fiddly.</li></ul><p>We were paying for machinery that solves a CPU problem, and we did not have a CPU problem.</p><h3>The fix: threads inside the dataset</h3><p>The key fact: <strong>the GIL does not matter while you wait for the network.</strong> When a thread is blocked waiting for bytes from a socket, Python lets other threads run. So 32 threads each waiting on an S3 download are 32 real downloads happening at once. One process, one S3 client, no copying between processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYFI10dk88yoLT3LDgLRvQ.jpeg" /><figcaption>Figure 4: The job is being done faster with the same machine</figcaption></figure><p>PyTorch has a hook for this that few people use. If your dataset defines __getitems__ (plural), the DataLoader calls it <strong>once per batch</strong> with the whole list of indices, instead of calling __getitem__ 32 times in a loop. Inside __getitems__ you can fetch all 32 however you like. We use a thread pool:</p><pre>from concurrent.futures import ThreadPoolExecutor<br><br><br>class S3ImageDataset(Dataset):<br>    def __init__(self, bucket, keys, transform, num_threads=32):<br>        self.bucket = bucket<br>        self.keys = keys<br>        self.transform = transform<br>        self.num_threads = num_threads<br>        self.s3 = boto3.client(&quot;s3&quot;)<br>        self.pool = ThreadPoolExecutor(max_workers=num_threads)<br><br>    def __len__(self):<br>        return len(self.keys)<br><br>    def _load_one(self, key):<br>        body = self.s3.get_object(Bucket=self.bucket, Key=key)[&quot;Body&quot;].read()<br>        image = Image.open(BytesIO(body)).convert(&quot;RGB&quot;)<br>        return self.transform(image), key<br><br>    def __getitem__(self, idx):<br>        return self._load_one(self.keys[idx])<br><br>    def __getitems__(self, indices):<br>        # Called once per batch. pool.map keeps the order of `indices`,<br>        # so the returned list lines up with them.<br>        keys = [self.keys[i] for i in indices]<br>        return list(self.pool.map(self._load_one, keys))</pre><p>Reading it line by line:</p><ul><li>_load_one is the old __getitem__ body, split out so both entry points can call it.</li><li>__getitem__ still works for anything that asks for one item.</li><li>__getitems__ takes the 32 indices for a batch, looks up the 32 keys, and hands them to the thread pool. pool.map starts all 32 downloads, waits for all of them, and returns the results in the same order.</li></ul><h4>The arithmetic again</h4><p>Same batch of 32. Now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnkgqCj95D4ljZ66RE2SQQ.jpeg" /><figcaption>Table 2</figcaption></figure><p>A batch used to cost the <em>sum</em> of 32 downloads. Now it costs about the <em>slowest</em> of 32 downloads, because they all run at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hj0WBMYfjdtcjg9HyQw3Og.jpeg" /><figcaption>Figure 5: Downloads are handled parallelly so no waiting for 32 files to be downloaded</figcaption></figure><p>The loader itself becomes almost boringly simple:</p><pre># num_workers=0: everything runs in the main process. The parallelism<br># now lives inside S3ImageDataset.__getitems__ (the thread pool),<br># not in DataLoader worker processes.<br>loader = DataLoader(dataset, batch_size=32, num_workers=0)</pre><p>Normally num_workers=0 means &quot;no parallelism, this will be slow&quot;. Here it means &quot;the parallelism moved one layer down, to the place that knows what it is waiting for&quot;.</p><h3>Three details that make it actually work</h3><p>The thread pool is four lines. Making it survive a run of several hours over hundreds of thousands of objects took three more changes.</p><h4>1. Give the S3 client as many connections as you have threads</h4><p>This is the mistake that quietly eats your whole speedup.</p><p>boto3 keeps a pool of open connections to S3 and reuses them. By default the pool holds <strong>10</strong>. If you point 32 threads at a client with 10 connections, 22 of the threads queue up waiting for a free connection. You paid for 32 threads and got 10 downloads in flight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0huQSMennsbDEknRMOOPbA.jpeg" /><figcaption>Figure 6: Update s3 connection pool</figcaption></figure><p>The fix is one setting, tied to the thread count so the two numbers can never drift apart:</p><pre>from botocore.config import Config<br><br><br>def make_s3_client(num_threads):<br>    return boto3.client(<br>        &quot;s3&quot;,<br>        config=Config(<br>            max_pool_connections=num_threads,   # one connection per thread<br>            connect_timeout=10,<br>            read_timeout=300,<br>            retries={&quot;mode&quot;: &quot;adaptive&quot;, &quot;max_attempts&quot;: 5},<br>        ),<br>    )</pre><p>And in the dataset, self.s3 = make_s3_client(num_threads). If you take one thing from this article, take this one.</p><h4>2. Retry downloads that fail halfway</h4><p>boto3 retries requests that fail <em>before</em> S3 starts sending the body. It cannot retry a failure that happens <em>while</em> the body is streaming, because by then it has already handed you half a file. At scale, half-finished downloads are not rare. They happen every day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KM7LUpkB3SPb_XmNkOwAg.jpeg" /><figcaption>Figure 7: Rertry</figcaption></figure><pre>import time<br>from botocore.exceptions import (<br>    ConnectionClosedError,<br>    EndpointConnectionError,<br>    ReadTimeoutError,<br>    ResponseStreamingError,<br>)<br><br># Errors that can happen after get_object returns, while reading the body.<br>TRANSIENT_ERRORS = (<br>    ReadTimeoutError,<br>    EndpointConnectionError,<br>    ConnectionClosedError,<br>    ResponseStreamingError,<br>)<br><br><br>def fetch_bytes(s3, bucket, key, max_attempts=3):<br>    for attempt in range(max_attempts):<br>        try:<br>            return s3.get_object(Bucket=bucket, Key=key)[&quot;Body&quot;].read()<br>        except TRANSIENT_ERRORS as err:<br>            last_err = err<br>            time.sleep(0.5 * 2**attempt)   # 0.5 s, 1 s, 2 s<br>    raise last_err</pre><p>So the dataset retries the whole download itself:</p><p>Two choices worth noticing. We download the <strong>whole object again</strong> rather than trying to resume from where it broke, because a full download is simple and safe to repeat. And we back off a little longer each time, so a wobbly connection gets a moment to settle.</p><p>Without this, one dropped connection nine hours into a run kills the job. With it, one image pauses for half a second.</p><h4>3. List the bucket once, and make restarts cheap</h4><p>Threads speed up the <em>downloading</em>. They do nothing for the <em>listing</em>. Before you can download anything you have to know what is in the bucket, and listing a prefix with 100,000 objects is a slow, paginated call of its own.</p><p>Two habits help:</p><ul><li><strong>Build the key list once and pass it in.</strong> If you already have a CSV of filenames, build the keys from that and skip the listing. If several jobs share the same images, list once and hand each job its slice of keys. The dataset above takes keys as a plain list for exactly this reason.</li><li><strong>Skip what you have already done.</strong> Before a restart, read the output written so far, collect the keys that are finished, and drop them from keys. A multi-hour job <em>will</em> be interrupted at some point. Being able to restart from where it stopped, instead of from zero, changes how you feel about killing a run.</li></ul><h3>Side by side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GB9wqMqVesrHC8wHzwFdig.jpeg" /></figure><p>The last row is the whole point. Neither design is right in general. They are answers to two different bottlenecks, and the usual advice quietly assumes you have the CPU one.</p><h3>Honest caveats</h3><p><strong>Thread count is measured, not derived.</strong> 32 threads and batch size 32 came from trying values against one bucket, one region, one machine. There is no formula. Different object sizes and networks will land somewhere else. Measure yours.</p><p><strong>Do not combine threads with </strong>num_workers &gt; 0<strong>.</strong> If you set both, you get workers × threads downloads in flight and a connection pool sized for only one of them. The num_workers=0 is load-bearing. Leave a comment saying so.</p><p><strong>Downloading and inference still take turns.</strong> The loop is: download a batch (32 at once), run the model, download the next batch. While the model runs, the network is idle. While downloading, the GPU is idle. Keeping the next batch downloading while the current one is on the GPU is the obvious next step, and it is on our list rather than in our code.</p><p><strong>Local disk is still the CPU case.</strong> If your images are on a fast local disk, decoding <em>is</em> the slow part, and the standard multi-process advice is correct. This article is about the other case.</p><h3>The takeaway</h3><p>“Increase num_workers&quot; really means &quot;buy more CPU parallelism&quot;. That is the right purchase when you are decoding JPEGs off an SSD. It is the wrong purchase when you are waiting on a network, and it is an expensive wrong purchase: you pay in copies of Python, duplicated connection pools and serialised tensors for concurrency a thread pool would have given you for free.</p><p>Before you tune a dataloader, ask what it is actually waiting for. Then:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bae8ed8bc846" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterators and PyTorch DataLoaders — Explained Without the Scary Definitions]]></title>
            <link>https://medium.com/@aulipriyapromona/iterators-and-pytorch-dataloaders-explained-without-the-scary-definitions-ead352954b51?source=rss-1104c90de02c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ead352954b51</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytorch-dataloader]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[python-iterator]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Aulipriyapromona]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 09:45:16 GMT</pubDate>
            <atom:updated>2026-03-05T09:45:16.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2199DsEsrScdtFXiOsUusg.png" /></figure><p>Articles about iterators often start with abstract definitions that feel intimidating.<br> So instead of starting with theory, let’s start with something we already use every day: for loops</p><h3>Step 1: You Have Already Used Iterators</h3><p>Every time you write:</p><pre>for item in my_list:<br>   print(item)</pre><p>You are using an iterator.</p><p>Under the hood, Python converts this into:</p><pre>iterator = iter(my_list)<br>next(iterator)<br>next(iterator)<br>...</pre><p>An iterator is simply a class that implements two methods:</p><blockquote>__iter__() → returns the iterator object itself</blockquote><blockquote>__next__() → returns the next value in sequence</blockquote><p>When no values remain, StopIteration is raised.</p><p>That’s it. No magic. Just controlled access to “what comes next.”</p><h3>Step 2: Why Not Just Stick to a For Loop, Why go for Iterators?</h3><p>You might ask and you are right in your logic in asking this</p><p><em>If for loops already do this, why should I care?</em></p><p>Because sometimes we want <strong>custom control over how iteration happens. </strong>Although it doesn’t feel like it at first but ultimately you will run into a case where you don’t want to load everything into memory right away (which is what for loop does). You might want to shuffle the data before loading. Each sample loading might be expensive for memory that requires special care.</p><p>Image trying to load 50GB data with your 8 GB RAM with a standard list.</p><p>In all of these cases understanding iterators becomes powerful.</p><h3>Step 3 : Let’s Implement a custom iterator</h3><p>Let’s say we have an extremely large log file we have to process but we cannot do it with standard file operation as opening it would crush your machine right away. Therefore we would be taking the iterator path. We will write a custom iterator that will load and process one line at a time.</p><pre>class LogFileIterator:<br>    def __init__(self, file_path):<br>        self.file_path = file_path<br>        self.file = None<br><br>    def __iter__(self):<br>        # Open file only when iteration starts<br>        self.file = open(self.file_path, &quot;r&quot;)<br>        return self<br><br>    def __next__(self):<br>        line = self.file.readline()<br><br>        if not line:  # End of file<br>            self.file.close()<br>            raise StopIteration<br><br>        # Real-world processing step<br>        cleaned_line = line.strip()<br><br>        return cleaned_line</pre><p>Then we will use it as</p><pre>log_iterator = LogFileIterator(&quot;huge_training_log.txt&quot;)<br><br>for line in log_iterator:<br>    if &quot;ERROR&quot; in line:<br>        print(&quot;Found error:&quot;, line)</pre><p>Only <strong>one line</strong> is in memory at a time thus using resources in a controlled way. This is really powerful.</p><h3>Step 4: Similarity between PyTorch Dataset — DataLoader concept and iterators</h3><p>Now let’s move to something familiar.</p><p>When training a model in PyTorch we have used</p><pre>from torch.utils.data import DataLoader<br><br>train_loader = DataLoader(<br>   dataset=my_dataset,<br>   batch_size=32,<br>   shuffle=True,<br>   num_workers=2<br>)<br><br>for images, labels in train_loader:<br>   ...</pre><p>We treat train_loader like a list. I at least treated it like a fancy list. But it is NOT a list. It is an <strong>iterable built on the iterator concept. </strong>The day I realized data in <em>dataloader</em> is just static sugar for repeated <em>next()</em> calls, pytorch internals stopped becoming magical. It felt logical.</p><h4>Your Dataset is NOT an iterator.</h4><p>A PyTorch Dataset:</p><blockquote>Implements __len__()</blockquote><blockquote>Implements __getitem__(index)</blockquote><p>It behaves like a list:</p><p>dataset[0], dataset[1]</p><p>It does NOT implement <em>__next__()</em>. It does NOT control iteration.</p><p>It only defines:</p><p>“How do I load one sample?”</p><h4>DataLoader Is the Iterator Factory</h4><p>When you write:</p><pre>for batch in dataloader:</pre><p>Python does this:</p><pre>iterator = iter(dataloader)<br>batch1 = next(iterator)<br>batch2 = next(iterator)</pre><p>So:</p><ul><li>DataLoader is iterable</li><li>iter(dataloader) returns a DataLoader iterator</li><li>That iterator implements __next__()</li></ul><p>Each <em>__next__() </em>call:</p><ol><li>Gets index slice from sampler</li><li>Calls dataset.<em>__getitem__()</em> for each index</li><li>Applies collate_fn</li><li>Returns a batch</li></ol><p>If we try to reimagine dataloader and datasets with mundane terms it would likely be termed as the following — <br>A <strong>Dataset</strong> is like a library of books. It knows:</p><ul><li>How many books there are (__len__)</li><li>How to go grab one specific book (__getitem__)</li></ul><p>A <strong>DataLoader</strong> is the librarian. It uses the iterator logic to:</p><ul><li>Decide which books to grab (Sampling/Shuffling)</li><li>Grab a handful at a time (Batching)</li><li>Ask multiple assistants to help grab them (Multiprocessing/num_workers)</li></ul><h4>The Bug That Inspired This Article</h4><p>I needed the dataloader to load each batch with randomly chosen size for image. The catch was I had to synchronize multiple GPUs to have the same sizes of image during one iteration step. To achieve that I wrote something like,</p><pre>for i, _ in enumerate(loader):<br>    ## size synchronization step ## <br>    data=next(iter(loader))</pre><p>In my mind I thought as I was not ignoring the data during for loop control step the data was not being fetched. I completely disregarded the fact that the moment I wrapped the loader into the for loop statement it became an iterator itself and returned data at each call.</p><pre>data = next(iter(loader))</pre><p>This is the dangerous part. Everytime</p><p><em>iter(loader)</em> is called it creates a brand new iterator from index 0. <em>next()</em> calls the first batch</p><p>The result? I always returned the first batch of data for all iterations repeatedly.</p><h3>Step 5: The Iterator Philosophy in Deep Learning</h3><p>Why does PyTorch insist on this? Efficiency.</p><ul><li><strong>Memory Control:</strong> If you have 100,000 images, you don’t load them into a list. The DataLoader only keeps the current batch_size in memory.</li><li><strong>Speed:</strong> While the GPU is training on Batch A, the DataLoader (iterator) is already using CPU workers to fetch Batch B.</li></ul><h4>Because DataLoader performs lazy, controlled iteration.</h4><p>It does NOT load everything at once.</p><p>It loads:</p><ul><li>Only the current batch</li><li>Only when requested</li><li>Possibly in parallel</li><li>Possibly shuffled</li><li>Possibly distributed across machines</li></ul><p>That’s a massive difference.</p><p>If you load 100,000 images manually into a list:</p><p>all_images = [load_image(p) for p in paths]</p><p>You immediately consume memory for everything.</p><p>With DataLoader:</p><ul><li>Only one batch lives in memory at a time.</li><li>Workers load data in parallel.</li><li>Memory stays controlled.</li><li>GPU stays fed efficiently.</li></ul><p>This is iterator philosophy applied to deep learning.</p><h3>Step 6: The Three Building Blocks of a Custom Data Pipeline</h3><p>To build your own custom loader:</p><ol><li>torch.utils.data.Dataset<br> → defines how ONE sample is loaded</li><li>torch.utils.data.DataLoader<br> → defines how samples become BATCHES</li><li>collate_fn (optional, but powerful)<br> → defines how individual samples are merged</li></ol><p>This separation of concerns is elegant engineering.</p><h3>Step 6: Custom Dataloader</h3><p>Let’s write a custom dataloader . To achieve a custom dataloading pipeline you start with defining “ <strong>how to load one sample</strong>”.</p><pre><br>import torch<br>from torch.utils.data import Dataset<br>import random<br><br>class CustomDataLoader(Dataset):<br>   def __init__(self, image_path, labels_path, classes, transforms):<br>       self.image_path = image_path<br>       self.labels = pd.read_csv(labels_path)<br>       self.transforms = transforms<br>       self.classes = classes<br><br>   def __len__(self):<br>       return len(self.labels)<br><br>   def __transform_label__(self, labels):<br>       transformed_labels = {}<br>       for key in self.classes.keys():<br>           transformed_labels[key] = self.classes[key].index(labels[key].values[0])<br>       return transformed_labels<br><br>   def __getitem__(self, idx):<br>       try:<br>           row = self.labels.iloc[[idx]]<br>           transformed_labels = self.__transform_label__(row)<br>           image_file_path = os.path.join(f&quot;{self.image_path}&quot;, row[&quot;image_path&quot;].values[0])<br>           with Image.open(image_file_path) as image:<br>               transformed_image = self.transforms(image)<br>             return transformed_labels, transformed_image<br><br>       except Exception as e:<br>             raise e</pre><p>Inside the get_item we are loading the label from the labels file, getting the file path and opening the image file to perform transformations on the image. Then finally returning the transformed label and image to the caller or should I say the dataloader.</p><h3>Final Thoughts</h3><p>Iterators are an interesting python ‘quirk’ to have deep knowledge on as I just proved it comes handy on deep learning concepts as well as building custom flows for efficient resource consumption.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ead352954b51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My SQL Journey]]></title>
            <link>https://medium.com/@aulipriyapromona/my-sql-journey-75a1e7253794?source=rss-1104c90de02c------2</link>
            <guid isPermaLink="false">https://medium.com/p/75a1e7253794</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Aulipriyapromona]]></dc:creator>
            <pubDate>Fri, 10 May 2024 03:24:57 GMT</pubDate>
            <atom:updated>2024-05-10T03:24:57.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*GBydVwzK7O6CQRC4TsRhrw.png" /></figure><p>Let me start with the motivation behind going through re-learning SQL as an AI engineer who doesn’t actually need to do anything related to SQL in her day to day work projects. The things I work with are extremely specific skills and yes being an expert and having a niche is nice but you also need to blend in with other related categories. Data science and data analytics are closely related with AI. Although you do not need to work with AI models directly in case of data analysis but having an insight on this part of the world is not bad. So I thought to spread out my skills even more to better my chances of accelerating if my project needs some analysis work done on data or we need to bring in statistical insights ( data science ) . In all of these cases I will need SQL.</p><p>Here I want to give a full disclaimer, I am not a newbie in SQL. I am a Computer Engineering Major, so I had a database course in my second year where I had to learn SQL and not to toot my own horn but I got A+ on my practicals ( totally not flexing my nerdy pants). I also worked as a full stack web developer at the start of my career so I had to know and practice quite a lot of SQL on a daily basis. But that record is now dusty. During my interview in my current company they asked about SQL to check if I will be able to work on their data analytics team, I straight up passed on that, saying I haven’t worked on SQL for 3 years I strictly want to work on the vision part of the AI project. But that made me think, “Hey I used to love SQL, now I cannot answer the most basic SQL questions, that’s alarming! I am confining myself into a box” . So that’s when I decided to relearn sql but as most things in my tech journey didn’t follow through on that goal until recently I took a 3 months plan and finally jazzed up my SQL.</p><h4>First Step</h4><p>Okay let’s get into the steps now. First of all define what is your current knowledge level. As I mentioned I already knew SQL but didn’t remember anything or how to write basic queries due to lack of practice. But you could be someone who doesn’t have much idea about database. I didn’t need to study any theory in my journey but you might need to get a basic theoretical idea about databases. So the first step would be knowing where you stand.</p><h4>Second Step</h4><p>Second step would be to define a road map. Easier said then done as it’s a little tricky part. As soon as you learn about your knowledge level, you need to come up with a plan of how to bridge the gap between your current knowledge level and desired knowledge level. In my case specifically as I already mentioned, I didn’t need theory and I also hate long videos or class materials. So I looked for really short practical example videos on SQL basics to jog my memory. At this point I didn’t practice with the videos I just took notes to look back on to the syntax and rules. I had to try a couple of videos before I could find the one I felt comfortable with. I found this <a href="https://www.youtube.com/@becomingADS/featured">channel</a> which doesn’t have tons of videos but it was exactly what I needed. After going through these videos I needed to practice what I learned. At this point I turned to HackerRank to practice sql . So everyday I scheduled half to one hour to practice sql on hacker rank. If I couldn’t finish something on that scheduled hour I didn’t bother. I didn’t want to pressurize my brain over this. So it didn’t feel like a chore. Some of those questions are really silly I will admit. Especially the ones with easy tags, but I needed practice in a structured way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*tEFUXVoqiS-pdy0RQw40Pw.png" /></figure><p>So eventually I finished all the exercises. Interestingly as I progressed towards the harder questions, I encountered some concepts that I didn’t know earlier such as cte, etc. Therefore doing those exercises took more time and a little more reading on my part, I looked for articles on specific topics for better ideas to solve the questions. After finishing all the exercises I knew I needed something to show all that hard work. After all what we all are chasing after other than a validation on some form of social media these days. So I decided to opt for the hackerrank sql certifications. I didn’t go for all the levels in one day. I did that week by week to build my confidence, to be honest I was not confident that I could achieve the certifications. I am not naive, I know these are not the most fancy certificates for your SQL skills. For crying out loud they are free certificates, how can they hold any importance in the professional world? But you know what ? They actually do hold some importance, they show on your linkedin profile and your resume that you actually care about your skill development and you are serious about this. Later on if you have the money and time by all means get a fancier certification, I have my eyes on a very fancy 400 dollars course, which I will do some day. But for now these certificates feel like the milestone I needed to boost my SQL confidence and also showcase my skill set to the onlookers.</p><p>This might be clear from my story that I am actually trying to say there’s no one size fits all in case of learning any kind of skill. The channel I recommended might not be good for you, you might be someone who enjoys longer lectures and follows through hands-on lectures for practice. Do your own thing. The catch here is you have to identify how you learn something, how you will follow through something without getting bored. And that cannot be suggested by anyone on the internet. That’s why I said you have to build your own roadmap. My point of sharing my journey and not recommending or creating checkpoints for you to follow, was to showcase that I failed to follow through such road maps on various articles and videos. So I only believe in build your own roads (BYOR). Happy Learning!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75a1e7253794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Evaluation Graphs To Evaluate Your AI Models]]></title>
            <link>https://medium.com/@aulipriyapromona/basic-evaluation-graphs-to-evaluate-your-ai-models-295a49c60c2c?source=rss-1104c90de02c------2</link>
            <guid isPermaLink="false">https://medium.com/p/295a49c60c2c</guid>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyplot]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aulipriyapromona]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 08:24:02 GMT</pubDate>
            <atom:updated>2024-04-30T08:24:02.469Z</atom:updated>
            <content:encoded><![CDATA[<p>The evaluation graphs or the graphs we generally use to communicate the model’s performance are the most basic thing in machine learning but still we see engineers struggle to search the internet for the most basic graphs. So let’s start with one that is almost compulsory to create after each training session to evaluate the training process — Training vs Validation loss curve.</p><h3>Training VS Validation Loss</h3><p>If you are smart you will keep a dictionary of training and validation loss during training so that after the training is done you generate a graph within that single file. Let’s see how we can do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fEmW1XrVPxvgyhhL" /></figure><p>What do we have here? We imported all the libraries we will need to use. At first we will write the graph creation outside of the training code, preferably in a separate function so that the actual training code doesn’t become messy. At the end of the training session we will call this function to generate the graph for us. For the function itself we will send some parameters such as training data, validation data, title, xy labels of the graph and name of the image we are going to save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IkkI3aSqRbIk-6OA" /></figure><p>If you remember I already mentioned that for training and validation loss we will keep two dicts for each. Now why dict? Why not 2 lists of losses. Well, if we keep a dict with epoch as key and the epoch’s corresponding loss as the value, we don’t need to worry about generating epoch numbers in our precious graph creation function . Also, in this way, even if your epoch numbers for training and validation loss don’t match, you won’t have to worry about thinking of something clever to generate the numbers. I mean you can do that, but that will be a waste of your time. As you can see on the first line of the function, we have taken the dicts into another dict with keys training and validation loss, as these keys will work as our graph legends. Now we loop through the freshly generated dict. For each value we have the data to generate one graph. We extract all the epoch information as epochs in a list called x_items and another list for y_items to store the loss value. Then plot these two values with plt.plot . VOila. The main work is done. Additional arguments are there to beautify and make the graph readable. By looping through the graph_lines dict we just generated two line graphs. Outside this loop we have to provide some additional information to make this graph appealing , hence we add the title , xlabel, ylabel, create the grids, add the legends, show the graph and save the image. Remember these are image specific information so you want to add them outside the loop after the individual graphs have been generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*e70IySjhIq9rZ6hf" /><figcaption>Training vs Validation Loss Graph</figcaption></figure><h3>Evaluate Model’s Performance on Test Data</h3><p>But we don’t just evaluate our models on validation data. We have a test set, and more numbers to generate to paint a full picture to our client. Let’s say we are dealing with an image classification problem. In that case, we can determine the accuracy of the model, the precision recall for each label, the f1 score and a confusion matrix. Also let’s assume in a perfect world where we have no space issue, we saved all the models that were improving, i.e had less loss than the previous epoch. We have about 20 models saved from different epochs, and we want to know which performs best on our test data. So we want accuracy, precision-recall, auc, f1 and confusion matrix of each of the models.</p><p>The neater approach to calculate all these numbers for each of the saved models would be to keep it all in a separate file for evaluation. We will run this file after the training session is done and all the models are saved.</p><p>First of all let’s initialize all the counters we want to update for all the epochs. We are using dicts here so that we can store the epoch number as key, and the metric as value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*NoWtL62DrWeAe1rr" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*n14s-Wpq6NZij93P" /></figure><p>After we have declared these dicts let’s iterate each model, load the model and then evaluate their performance on our test set. At the beginning of this iteration loop we will again initialize all the counters we need to calculate each model’s accuracy, confusion matrix, roc curve and precision -recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*rqov_FoXnMcrTH4-" /></figure><p>In the previous block you can see we have populated class wise accurates dict with keys and initialized the count at 0. We also loaded our model.</p><p>Next we will iterate over the images, open them with PIL, perform necessary transformations for the model and infer the predictions for that image from the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*lh1jMBJsIlVIMQau" /></figure><p>As we can see, we get probabilities of the image belonging to each class. Functions like predict and load_model are inference related utility functions that I have created to keep the code clean. I am not describing them as it will be outside of the scope of this article. What we get from the predict function is a dict holding tensor predicting probabilities of each of the class value.</p><p>In my case, I am working with Single Label Classification right now, but the code is written to deal with both multiclass multi label classification and single label classification in most cases. Currently we get one label, holes, that has two values — A, B. We see that we get probability for both possible values. The tensor is of the following shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/0*UCQ-I3Tp8PWqJILu" /></figure><p>This is probability for one image. We will append this probability for our list of prediction probabilities called pred_probs. So we add each of the probabilities tensor to the pred_probs list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x2rO7jAn73rlI4Po" /></figure><p>This might look very messy and overwhelming, so let’s break it down.</p><p>Let’s focus on the if condition first. I already mentioned that this code is written to facilitate multilabel as well as single label. Therefore, the if condition is just checking if the probabilities variable has one key (single label) or more than one key (multi label). If there is only one label, we are just grabbing the tensor from the probabilities dict, squeezing i.e getting rid of the extra dimension, making it a list of two elements and appending that two element list to pred_probs list.</p><p>If we are working with more than one label the first half of the previous block works, i.e the portion before if condition. We do the same thing as the single label, but we are grabbing each tensor from the dict, squeezing to get rid of the extra dimension, making it a list. After this step we just turn two lists into a tuple and append to the pred_probs list. Therefore our pred_probs variable is a list of tuples where each tuple is a list if we are working with multi labels and it is a list of lists if we are working with single labels.</p><p>We then use our util function to postprocess the probability output and get a string prediction or in case of multi label classification, a dict of two string predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/0*A_t0eq9bSrkBvcet" /></figure><p>After getting the final prediction for each image we append the gt and preds list for that image. Again like the pred_probs appending situation, here we see the similar pattern of if condition checking if it’s a multilabel or single label problem then acting accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*bvxLlJwaStqxc2wV" /></figure><p>From this portion we get the index of the hole label from config. Remember that the label variable is loaded at the beginning of the image iteration loop by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*80fblmELuExpX3Qh" /></figure><p>In case of multi labels, the variable gt is a list where each element is a 2 element list that holds the index of each true label. On the other hand, in case of single labels, gt is list of index of true labels for each image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xdfedviVC2JKpzps" /></figure><p>Preds variable is prepared exactly like gt. It is a list of predictions made by the model for each image and it holds the indexes instead of the string predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sBBaehvIEYiMeR2l" /></figure><p>Now we update our accurates counter. The final predictions we got in a previous block, we compare that prediction with the ground truth label. If they are identical, add one to accurates and classwise_accurates. This portion is not accounted for multi label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sE_sLRpkTvN85kgF" /></figure><p>After we have iterated over all the images, we move on to calculating cm or confusion metrics and precision, recall, f1 for the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YWFWg4vNLzJ0EnNN" /></figure><p>As you can see we have two separate methods for generating a cm and creating a precision-recall graph to keep the code clean, as well as to reduce redundancy.</p><p>Let’s look at our generate_confusion_matrix function first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ssAxNpzvw6Zc3fn4" /></figure><p>Firstly we use the confusion_matrix function from sklearn. Which gives us something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*A3tZI4nXzABtm9XB" /></figure><p>Not very aesthetically pleasing, right? But to make our clients understand these numbers and also let’s admit to soothing our eyes, we will beautify this a bit and plot it as a graph. We will convert this matrix to a Pandas dataframe, which has our class values (no holes, holes ) as index and column names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*tLnG8f_kUDpee7f-" /></figure><p>Create a new pyplot figure and use sns’s heatmap function to map this dataframe. Leave everything else to the heatmap function. It will be a beautiful heatmap depending on the values of each class. Then do the usual for any kind of pyplot figure, like adding xylabels, adding title, save the image and show. The resulting heatmap of the confusion matrix will be like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*08nENnGUgD88u5_V" /></figure><p>As we can see, a much better representation than those multi dimensional arrays. We will generate these cm heatmaps for every model.</p><p>Now let’s look at our precision recall graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q_RDq62WR0oiXTUI" /></figure><p>First we need the cm to calculate the precision and recall for a particular model. We do the calculation according to the formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*qkVV-psWssuv-_SP" /></figure><p>Which will give us the following results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6yiexuIEvf8KT__D" /></figure><p>But again to satisfy our aesthetic minds we need to make a graph out of it.</p><p>First of all we will make a dataframe with the precision, recall and class values (no holes, holes). Then use the melt function to unpivot the dataframe from wide to long format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5VUwvl5EBAvrO7HU" /></figure><p>We create the following dataframe prec_rec from precision — recall values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/0*KRRMkS5u0ViTc60P" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/0*PA1a6ZhNrv3dr3dw" /></figure><p>After melting it, it takes the following form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*0KRKfLFQSTkZPXro" /></figure><p>We will now create a barplot with this dataframe using sns.barplot function where each value of the class will have a bar for precision and recall. We do all that by just typing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/0*ABUznydclZLBYZq_" /></figure><p>Each bar will display its value ( rounded to 2 decimal places) at the center of the bar and it will be written on the bar vertically. To do that we need to access the patches from the ax variable that is created by the barplot function. We will get the center position by adding each patch’s x to its half width values. We will set the text of each patch at its center position with 90 degree rotation with the following code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j3FlRGYQV-oXimqB" /></figure><p>We need some other information to calculate from this function. That is, we don’t want these many precision recall values for each class. We want a mean value to represent this model. We will also calculate the F1 score of the model to indicate its overall health.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OlkFW89QXFZQMaLq" /></figure><p>And thus we wrap up the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*GlYyfFslD9vlRzNc" /></figure><p>So we generated the cm graph, precision — recall barplot and calculated, precision, recall and f1 score. It’s time to store them on our dicts we created to store each model’s performance metric at the beginning of the evaluate function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MXRGI_wgjO7trT7I" /></figure><p>Also we aim to generate the roc curve and you guessed we wrote a separate function for it. So let’s look at this function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QrvjdeXVD7sE4EXa" /></figure><p>First of all, we initialize dict for false positive rate, true positive rate and roc_auc . We loop through each class , prepare gt_i, the ground truth variable for that class with 0/1 values depending on the true value. Prepare the pred_probs_i from pred_probs. Finally we use sklearn’s roc_curve and auc to generate roc and auc for each class value. After the rocs and aucs have been generated for each class value, we plot them with basic pyplot operation. After creating plots we add the title , x-y labels etc to make the plot look more appealing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tp4-dgSQuCBSc06b" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ePV8JnVmahqNdWu" /></figure><p>Thus we get a auc plot -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*UQ-6J1tvMGCfGTbQ" /></figure><p>Now as we have generated all the graphs for each model individually for each model, we get out of the loop of model paths iteration.</p><p>Next we update the general counter for each model of classwise_accuracies. If you remember, we have updated class wise accurates but we have an accuracy counter as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hC2R6DrQZ405AjN-" /></figure><p>Basically we divide the class wise accurates by classwise images to get the relevant accuracy.</p><p>Time to do something with all these general counters. We have continuously updated dicts that hold precision, recall, f1 and accuracies for each model. Therefore we have the numbers to present to clients. But rather than just presenting the numbers , let’s say accuracy for each model in a boring csv file, we can generate a separate barplot for each of these metrics. Which I personally believe to be more enticing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vGaGRSA6rVX2tXzx" /></figure><p>And yes we have a separate function to create barplot for any metric we want, that doesn’t need additional processing. So using this one function, we are creating 3 barplots. Let’s take a closer look at this function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aQwfcLfcujMOboe4" /></figure><p>First of all we create a dataframe from the given dict and create a barplot with sns’s barplot function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eT23jkUFzuTL8YaD" /></figure><p>Here again we use the patches to set vertical bar values on the center of each bar. And the rest is usual pyplot stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O8DjFRd61XuOwTbM" /></figure><p>It will generate something like this for precision, recall and f1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M1k1yfeRCqUnAHYH" /></figure><p>You can get the entire code on <a href="https://github.com/aulipriya/evaluation_graphs">this</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=295a49c60c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>