<?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 Garvit Joshi on Medium]]></title>
        <description><![CDATA[Stories by Garvit Joshi on Medium]]></description>
        <link>https://medium.com/@garvitjoshi46?source=rss-3480059874f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-SB7lTaZH0nQHNJyOA4vdw.png</url>
            <title>Stories by Garvit Joshi on Medium</title>
            <link>https://medium.com/@garvitjoshi46?source=rss-3480059874f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:26:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@garvitjoshi46/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[A Video Is Just a Tensor: The Mathematics of Turning Pixels into Data]]></title>
            <link>https://medium.com/@garvitjoshi46/a-video-is-just-a-tensor-the-mathematics-of-turning-pixels-into-data-15df387118db?source=rss-3480059874f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/15df387118db</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Garvit Joshi]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 15:36:29 GMT</pubDate>
            <atom:updated>2026-11-06T15:36:29.195Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Part 1 — Understanding the Input | From raw video files to numerical representations inside neural networks</blockquote><p><strong>Before a neural network can recognize an action, detect an event, or understand what is happening in a video, it must first convert that video into numbers.</strong></p><p>We watch a video and see people, objects, movement, and events. A computer does not see any of those things directly.</p><p>It receives encoded data, reconstructs individual frames, represents pixels as numerical values, and organizes those values into multidimensional arrays called tensors.</p><p>This transformation might sound like a simple preprocessing operation. In reality, it determines what information reaches the model, how much memory the model requires, how much computation it performs, and sometimes whether it can recognize an event at all.</p><p>In this article, we will follow a video through this entire process:</p><p><strong>Video file → Decoded frames → Pixel values → Preprocessing → Frame sampling → Tensor construction → Neural network input</strong></p><p>We will derive the mathematics behind every stage, calculate the memory requirements of a real example, and implement the preprocessing pipeline using Python and PyTorch.</p><p>By the end, you should understand exactly what a video neural network receives before its first layer performs a single computation.</p><h3>1. What Does a Computer Actually Receive When We Give It a Video?</h3><p>Consider a video recorded using a mobile phone.</p><p>When we play it, we see continuous movement. A person walks, a vehicle moves, or an object changes position.</p><p>However, digital video does not store movement as one continuous visual object.</p><p>It represents the visual information as a sequence of individual images called <strong>frames</strong>.</p><p>Each frame is a two-dimensional arrangement of pixels. When these frames are displayed in chronological order at an appropriate speed, our eyes perceive continuous motion.</p><p>For example, consider a video recorded at 30 frames per second.</p><p>This means that approximately 30 individual frames are displayed every second.</p><p>If the video lasts 10 seconds, its total number of frames is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJsFeYRFeXNHWw2hR83tng.png" /></figure><p>Therefore, the video contains approximately 300 frames.</p><p>The word approximately matters here. Some video formats use variable frame rates, and the actual frame count and presentation timestamps may not follow a perfectly uniform schedule.</p><h3>A frame is not the same thing as a video</h3><p>A single frame describes the visual appearance of a scene at a particular time.</p><p>A video contains a sequence of such observations.</p><p>Mathematically, we can represent the video as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*kkzZ2iMswCRmzJ65smvSlw.png" /></figure><p>Where:</p><ul><li>V = represents the complete video.</li><li>F_t = represents the frame at temporal index (t).</li><li>T = represents the total number of frames.</li></ul><p>Each frame contains pixel information arranged across two spatial dimensions.</p><p>For a color image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*GZCtIJlJCVelCegB-Qpehg.png" /></figure><p>Here:</p><ul><li>H = image height.</li><li>W = image width.</li><li>C = number of color channels.</li></ul><p>For a standard RGB image, (C=3).</p><p>Combining all the frames gives us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*hjfQnKCQZUKIS1kd8_Ze-w.png" /></figure><p>This is one mathematical representation of a video as a multidimensional array.</p><p>It is important to understand that this is a representation of the decoded video, not the internal structure of the original compressed video file.</p><figure><img alt="Source: https://www.techscience.com/csse/v47n2/53674/html" src="https://cdn-images-1.medium.com/max/700/0*5fsLZ0MQJJkESupO" /></figure><p><em>A digital video can be understood as an ordered sequence of individual frames. Motion is represented through changes in visual information over time.</em></p><h3>2. Understanding the Structure of a Digital Frame</h3><p>Let’s move one level deeper.</p><p>Suppose we extract one frame from a video.</p><p>That frame is not stored as a collection of objects such as people, vehicles, buildings, or roads.</p><p>At the pixel level, it is a grid of numerical measurements.</p><p>A pixel represents the color information at a particular spatial location.</p><p>For example, a frame with a resolution of 224 × 224 contains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*ZjW572ypCqbUDQK1cgTKwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*qFB_tVxIVlioGSdrQO80Iw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*u2t0GA7RyRkNcNP-LSxteQ.png" /></figure><p>That gives us 50,176 spatial locations.</p><p>But a color pixel usually contains more than one numerical value.</p><h3>Understanding RGB representation</h3><p>Most commonly encountered color images are represented using three color channels:</p><ul><li>Red (R)</li><li>Green (G)</li><li>Blue (B)</li></ul><p>These channels are combined to represent different colors.</p><p>For example, a pixel might have the following values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*CAKgTJbA0hZZ92O2rQ6Bdg.png" /></figure><p>This represents pure red in the conventional 8-bit RGB representation.</p><p>Similarly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*ZCKOWov089DXqpdPn_q1Hw.png" /></figure><p>represents green, while:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*BI2BmgHz6dS_4u67HHuzGg.png" /></figure><p>represents blue.</p><p>A white pixel is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*mLLJO57E_AZaiVd5YmuCRQ.png" /></figure><p>And a black pixel is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*AWXeEMrQvNI6i_eufADtkw.png" /></figure><p>Each channel typically contains an integer between 0 and 255 when represented using 8-bit unsigned integers.</p><p>Therefore, one RGB pixel requires:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*J0o83iyrhnF5m3XbWRbLiw.png" /></figure><p>This is commonly described as 24-bit color.</p><h3>Why three channels?</h3><p>The RGB representation is based on additive color mixing.</p><p>Different intensities of red, green, and blue can be combined to represent a wide range of colors.</p><p>For a frame of dimensions (224 x 224) , the total number of individual channel values is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*D2N-aET2h8ClsQGmEh1QMg.png" /></figure><p>Notice the distinction:</p><ul><li>50,176 represents the number of pixels.</li><li>150,528 represents the number of individual RGB values.</li></ul><p>A neural network processes numerical values, not the visual concept of a red pixel.</p><figure><img alt="Source: https://habr.com/ru/companies/skillfactory/articles/565232/?" src="https://cdn-images-1.medium.com/max/550/0*KHprDdOOU3Y8Uau6" /></figure><p>RGB photograph decomposed into red, green, and blue channels, with an enlarged pixel showing its channel values.</p><h3>3. From Pixel Intensities to Numerical Input</h3><p>We now have an image represented using integer values.</p><p>But neural networks generally perform their computations using floating-point numbers.</p><p>This is where normalization becomes important.</p><h3>3.1 Converting pixel values into a numerical range</h3><p>For an 8-bit RGB image, each channel has a value between 0 and 255.</p><p>A simple normalization operation converts these values into the range [0,1].</p><p>The mathematical operation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*TtB3Y4-utci9t5sPm6UjWQ.png" /></figure><p>Consider a pixel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*vXYbS2v61LLpiIRSfiybVQ.png" /></figure><p>After normalization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*7E1FaERwY0QksuDBySqLKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*CEOlj5p4YtsL4C6GMZoefw.png" /></figure><p>The relative color information is preserved, but the numerical range changes.</p><p>Why is this useful?</p><p>Neural networks repeatedly perform operations involving multiplication, addition, activation functions, and gradient calculations.</p><p>Very different numerical scales can make optimization more difficult. Consistent input scaling is therefore a common preprocessing practice.</p><p>However, normalization to [0,1] is not a universal requirement. The correct preprocessing must match the model’s training configuration.</p><h3>3.2 Mean and standard deviation normalization</h3><p>Many pretrained computer vision models use an additional normalization step.</p><p>The transformation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*GIgHn7VhM-hKwrEmGnf0EA.png" /></figure><p>Where:</p><ul><li>X = is the normalized input value.</li><li>µ = is the channel-specific mean.</li><li>σ is the channel-specific standard deviation.</li><li>X´ = is the resulting standardized value.</li></ul><p>For example, suppose a normalized red-channel value is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*NGpF6Hm2sdPqfQYAFaqbcg.png" /></figure><p>The resulting value is no longer restricted to [0,1].</p><p>This is expected.</p><p>The purpose is to transform the input distribution according to the statistics used by the model.</p><p><strong>An important engineering rule:</strong> if you use a pretrained model, do not arbitrarily change its preprocessing pipeline. Incorrect normalization can significantly reduce prediction quality even when the model architecture and weights are correct.</p><p>For video models, the expected normalization may be different from that of an ordinary image classifier.</p><h3>4. Understanding the Video File Before Frame Extraction</h3><p>So far, we have discussed decoded images.</p><p>But where do those images come from?</p><p>A video file is usually a container format such as MP4 or MOV.</p><p>The container can hold multiple streams, including:</p><ul><li>Video data.</li><li>Audio data.</li><li>Timestamps.</li><li>Stream metadata.</li><li>Other synchronization information.</li></ul><p>The actual video stream is commonly compressed using a codec such as H.264 or H.265.</p><p>This compression is necessary because storing every frame as an uncompressed image would consume enormous amounts of storage.</p><h3>4.1 Why compression is necessary</h3><p>Consider a 10-second video containing 300 frames, each with dimensions of 224 × 224 and three color channels.</p><p>If each channel uses one byte, the uncompressed pixel data requires:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*HXnXOlOjWeSNS6eHJoRkNg.png" /></figure><p>This is approximately 45.16 MB using decimal units.</p><p>A compressed video can require substantially less storage.</p><p>Video codecs achieve this by exploiting spatial and temporal redundancy.</p><p>For example:</p><ul><li>Spatial compression reduces redundancy within individual frames.</li><li>Temporal compression exploits similarities between different frames.</li></ul><p>Many video codecs use a combination of intra-coded frames and inter-frame prediction.</p><p>This means that a compressed video does not necessarily contain a complete independently stored image for every displayed frame.</p><p>Some frames are reconstructed using information from other frames.</p><p>The decoder performs the necessary operations to reconstruct the displayed images.</p><h3>4.2 Why timestamps matter</h3><p>A video is not just a list of frames. Each frame is associated with timing information.</p><p>The frame rate tells us how frequently frames are presented, but timestamps provide information about when individual frames should be displayed.</p><p>For constant-frame-rate video, a simplified timestamp relationship is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*qcq0wiedLpuTeRGcqIoE0Q.png" /></figure><p>Where:</p><ul><li>i = is the frame index.</li><li>f = is the frame rate.</li><li>t_i = is the timestamp in seconds, assuming the first frame starts at zero.</li></ul><p>At 30 FPS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*BytBpzZJgMLygVJ-6skNtg.png" /></figure><p>And so on.</p><p>For variable-frame-rate video, this simplified formula may not hold. Actual presentation timestamps must be used.</p><p>Why does this matter for machine learning?</p><p>Because the temporal distance between two sampled frames influences how much motion information the model receives.</p><p>Sampling two frames 0.03 seconds apart is not equivalent to sampling two frames one second apart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yndf095BhTg2fuoD" /></figure><p><em>Video decoding and frame extraction pipeline from an MP4 container to decoded RGB images.</em></p><h3>5. Frame Sampling: Why We Usually Don’t Process Every Frame</h3><p>We now have a sequence of decoded frames.</p><p>The next question is:</p><p><strong>Should we send every frame into the neural network?</strong></p><p>Not necessarily.</p><p>Processing every frame can be computationally expensive, especially for long videos and high-resolution footage.</p><p>Instead, many video classification systems sample a smaller number of frames or short clips.</p><p>This is called frame sampling.</p><h3>5.1 Uniform frame sampling</h3><p>Suppose we have a video containing 300 frames.</p><p>Instead of processing all 300 frames, we decide to extract 16 frames uniformly across the video.</p><p>A simplified sampling strategy can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*ewZZTHy7MT8ePLL7s4VRvg.png" /></figure><p>Where:</p><ul><li>T = is the total number of available frames.</li><li>K = is the number of frames we want to sample.</li><li>k = is the sampled-frame position, from 0 to (K-1).</li><li>i_k = is the original frame index.</li></ul><p>For our example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5E3OEq2w7hOgMamHUbPKPw.png" /></figure><p>We have reduced the number of frames from 300 to 16.</p><p>That is a significant reduction in input size.</p><p>However, uniform sampling introduces an important trade-off.</p><p>Suppose an event occurs between frames 100 and 105.</p><p>If the sampling strategy selects frame 99 and frame 119, the event might not be represented clearly in the sampled input.</p><p>The model cannot reliably identify visual information that was never provided to it.</p><h3>5.2 Temporal resolution</h3><p>The temporal distance between uniformly sampled frames is approximately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*F0EVMaCAysHOOn6tJuU70Q.png" /></figure><p>Where:</p><ul><li>D = is the video duration.</li><li>K = is the number of sampled frames.</li></ul><p>For a 10-second video with 16 sampled frames:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*9l1Grw0_9REQ22KeNFaZig.png" /></figure><p>The model receives approximately one observation every 0.667 seconds.</p><p>Compare this with the original 30 FPS video, where a frame is presented approximately every:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*Z9Wz1jW3CyLoaM2rUwAAhA.png" /></figure><p>The sampled representation is therefore much less temporally dense.</p><h3>5.3 What happens when we sample too few frames?</h3><p>Consider a short action that lasts only 0.2 seconds.</p><p>If our sampling interval is approximately 0.667 seconds, there is a substantial risk that none of the selected frames will capture the action clearly.</p><p>This is especially important for tasks involving:</p><ul><li>Brief physical interactions.</li><li>Sudden movements.</li><li>Falls.</li><li>Fast-moving objects.</li><li>Short-lived events.</li></ul><p>More frames can preserve more temporal detail, but they also increase computational cost.</p><p>There is no universally optimal frame count. It depends on the task, the model architecture, the training configuration, and the speed of the events being detected.</p><h3>5.4 Alternative sampling strategies</h3><p>Uniform sampling is only one option.</p><p>Other strategies include:</p><ol><li><strong>Random sampling:</strong> Randomly select frames or clips during training to introduce temporal variation.</li><li><strong>Dense sampling:</strong> Extract frames at smaller time intervals to preserve more temporal information.</li><li><strong>Segment-based sampling:</strong> Divide the video into temporal segments and sample from each segment.</li><li><strong>Event-oriented sampling:</strong> Use an additional mechanism to identify potentially important intervals before running a more expensive model.</li></ol><p>Each strategy has different implications for training and inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*XAajf6Zh41PbC5Vq" /></figure><p><em>Comparison of a complete video frame sequence and a sparse 16-frame sampling strategy.</em></p><h3>6. Resizing: Why the Original Resolution Is Often Changed</h3><p>Videos are frequently recorded at resolutions such as:</p><ul><li>1920 × 1080.</li><li>1280 × 720.</li><li>3840 × 2160.</li></ul><p>These resolutions can be expensive for neural networks to process, particularly when multiple frames are involved.</p><p>For this reason, models often use a smaller input resolution.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*jZEPgnDxkwSlGD2kt4xiVw.png" /></figure><p>However, this transformation is not simply a matter of deleting pixels.</p><p>Resizing uses interpolation to estimate pixel values at new spatial positions.</p><h3>6.1 Understanding nearest-neighbor interpolation</h3><p>The simplest interpolation approach is nearest-neighbor interpolation.</p><p>For every output pixel, the algorithm selects the nearest corresponding input pixel.</p><p>This is computationally inexpensive, but it can produce blocky results when an image is enlarged or noticeable detail loss when it is reduced.</p><h3>6.2 Understanding bilinear interpolation</h3><p>Bilinear interpolation estimates a new pixel using four neighboring pixels.</p><p>Suppose the four surrounding values are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*iCgSguYZswPbg9X1kK3okg.png" /></figure><p>For horizontal and vertical interpolation weights (a) and (b), the estimated value is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JNtXr4ykCiM2fjCs5d7Zg.png" /></figure><p>This calculation is performed independently for the relevant color channels.</p><p>Bilinear interpolation generally produces smoother results than nearest-neighbor interpolation.</p><p>Other interpolation methods, such as bicubic interpolation, use a larger neighborhood.</p><h3>6.3 Resizing versus cropping</h3><p>There is another important distinction.</p><p>If we directly resize a 1920 × 1080 image into 224 × 224, we change its aspect ratio.</p><p>The original aspect ratio is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*QktIPRPRnkHAXkFRml4uQg.png" /></figure><p>Consequently, objects can become distorted.</p><p>An alternative is to preserve the aspect ratio and then crop or pad the image.</p><p>These approaches have different trade-offs:</p><ul><li>Direct resizing is straightforward but can distort objects.</li><li>Resize-and-crop preserves proportions but can remove important regions.</li><li>Resize-and-pad preserves the full image but introduces additional padding.</li></ul><p>The correct choice depends on the model’s expected preprocessing and the visual requirements of the task.</p><p>For video models, the same spatial transformation should generally be applied consistently across frames. Otherwise, changing crop positions can introduce artificial visual motion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rXZiespJJRLvN32T" /></figure><h3>7. Converting the Video into a Tensor</h3><p>We have now completed several transformations:</p><ol><li>Decoded the video.</li><li>Extracted frames.</li><li>Converted pixel values into RGB representation.</li><li>Normalized the pixel intensities.</li><li>Sampled a smaller number of frames.</li><li>Resized the frames to the required dimensions.</li></ol><p>We can finally construct the tensor.</p><p>Let’s define our example:</p><ul><li>Video duration: 10 seconds.</li><li>Original frame rate: 30 FPS.</li><li>Total frames: 300.</li><li>Sampled frames: 16.</li><li>Target height: 224 pixels.</li><li>Target width: 224 pixels.</li><li>Color channels: 3.</li></ul><p>The resulting video representation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*yuXp_K1bBJUH3fK8WbpNjw.png" /></figure><p>This is commonly called a four-dimensional tensor.</p><h3>7.1 Understanding the tensor dimensions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*6ikqtWhEY6HLCwi3UUwtAw.png" /></figure><p>refers to the value at:</p><ul><li>Temporal position (t).</li><li>Vertical position (h).</li><li>Horizontal position (w).</li><li>Color channel ©.</li></ul><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*Qt5bfFb_DHkSqfUJjw9CbA.png" /></figure><p>refers to the red-channel value at row 100 and column 120 of the first sampled frame.</p><p>The tensor is effectively a structured numerical representation of the video.</p><h3>7.2 Why tensor layout matters</h3><p>There is an important complication.</p><p>Not every deep learning framework expects video data in the same dimension order.</p><p>A common representation for video data is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*LX3EZ1Tb-tAUxP9zD2qSMw.png" /></figure><p>Another common representation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*9cOIlTnmHnHNkToZOJdJNg.png" /></figure><p>For example, PyTorch’s standard 3D convolution expects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*9cOIlTnmHnHNkToZOJdJNg.png" /></figure><p>Where:</p><ul><li>N = batch size.</li><li>C = channels.</li><li>T = temporal dimension.</li><li>H = height.</li><li>W = width.</li></ul><p>If we process one video with 16 frames, the expected shape for a standard PyTorch 3D CNN would typically be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*SX4P9DdDQs2Zq29ajYiUdQ.png" /></figure><p>The first dimension represents the batch size.</p><p>The second dimension represents the three color channels.</p><p>The remaining dimensions represent time, height, and width.</p><p>This difference is not cosmetic.</p><p>A tensor with the correct values but incorrect dimension ordering can produce shape errors or, in some cases, unintended computation.</p><p><strong>[IMAGE 6 — PLACE AFTER THIS SECTION]</strong></p><p>Visual: A tensor-shape diagram showing the transformation:</p><p>(16, 224, 224, 3) → Permute dimensions → (3, 16, 224, 224) → Add batch dimension → (1, 3, 16, 224, 224).</p><p>Represent the dimensions using labeled blocks: Channels, Time, Height, Width, Batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gMkuPxBynwz_sdih" /></figure><p><em>Video tensor being transformed from frame-major RGB layout into the batch-channel-time-height-width layout used by PyTorch 3D convolutions.</em></p><h3>8. The Memory Mathematics: How Much Space Does a Video Tensor Require?</h3><p>This is where the importance of preprocessing becomes especially clear.</p><p>Let’s calculate the memory requirements of our example.</p><p>We have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*lgwo18Hw4u-Guo3mjx2RtA.png" /></figure><p>The total number of individual values is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*EVVax2b4aW3pmqczb_SVCA.png" /></figure><p>Substituting the values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*wGextY56ajWSYZLtvFfwXg.png" /></figure><p>Therefore, the tensor contains 2,408,448 individual numerical values.</p><p>But the amount of memory required depends on the data type.</p><h3>8.1 Understanding data types</h3><p>A few common numerical formats used in deep learning are:</p><p>Data typeStorage per valueTypical useuint81 byteDecoded image pixelsfloat162 bytesReduced-precision computationbfloat162 bytesReduced-precision computationfloat324 bytesCommon model input and training precisionfloat648 bytesHigher-precision numerical computation</p><p>For a float32 tensor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*ykz_mKW90OmRKexzZZa4MQ.png" /></figure><p>Converting into decimal megabytes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*HqqGuVUPIOMg6i7kJPdDgw.png" /></figure><p>Converting into binary mebibytes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*nJUihUjuV2D3cBQhbWfIyg.png" /></figure><p>That is the memory required to store the sampled video tensor alone.</p><h3>8.2 What if we process every frame?</h3><p>Now consider the original 300-frame video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*wtZlsLo1KQ-gxGJ2os_JHw.png" /></figure><p>For float32:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Z2vkZzkX-lVAEIoQzra7PA.png" /></figure><p>Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*NLbrAmIQQes_zKOfUwy8Dw.png" /></figure><p>Or approximately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*x-jHVlzipiyApB_O06plFQ.png" /></figure><p>Compare the two representations:</p><p>Configuration Frames Float32 memory, Full video 300180.63 MB Sampled video169.63 MB</p><p>The sampled representation requires approximately 18.75 times less memory.</p><p>This is a major reduction.</p><p>But there is a trade-off: fewer frames mean less temporal information.</p><h3>8.3 Memory is not the same as total GPU usage</h3><p>There is a common misconception that the memory occupied by the input tensor represents the total memory required by a neural network.</p><p>It does not.</p><p>During model execution, additional memory is required for:</p><ul><li>Model parameters.</li><li>Intermediate feature maps.</li><li>Temporary computational buffers.</li><li>Gradients during training.</li><li>Optimizer states.</li><li>Other tensors involved in preprocessing and inference.</li></ul><p>For training, intermediate activations often account for a substantial portion of GPU memory because they must be retained for backpropagation.</p><p>For this reason, a video model may consume several times more memory than the input tensor alone.</p><p>The exact requirement depends on the architecture, batch size, precision, activation checkpointing, and implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gqqymDyQLKj3_ULM" /></figure><p><em>Comparison of the memory requirements of full-video and sampled-video tensors.</em></p><h3>9. Putting Everything Together: Building the Preprocessing Pipeline in Python</h3><p>We have derived the mathematical process.</p><p>Now let’s implement it.</p><p>The following example uses OpenCV to decode a video and PyTorch to construct the final tensor.</p><p>Install the dependencies:</p><pre>pip install opencv-python numpy torch</pre><h3>9.1 Extract and sample frames</h3><pre>import cv2<br>import numpy as np<br>import torch</pre><pre>VIDEO_PATH = &quot;sample_video.mp4&quot;</pre><pre>NUM_FRAMES = 16<br>HEIGHT = 224<br>WIDTH = 224<br></pre><pre>def extract_video_frames(video_path):<br>    cap = cv2.VideoCapture(video_path)</pre><pre>    if not cap.isOpened():<br>        raise RuntimeError(&quot;Could not open video&quot;)</pre><pre>    fps = cap.get(cv2.CAP_PROP_FPS)<br>    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))</pre><pre>    if total_frames &lt;= 0:<br>        cap.release()<br>        raise RuntimeError(&quot;Video contains no readable frames&quot;)</pre><pre>    # Uniformly sample frame indices.<br>    indices = np.linspace(<br>        0,<br>        total_frames - 1,<br>        NUM_FRAMES,<br>        dtype=np.int64<br>    )</pre><pre>    selected_frames = []<br>    frame_timestamps = []</pre><pre>    target_index = 0<br>    frame_index = 0</pre><pre>    while True:<br>        success, frame = cap.read()</pre><pre>        if not success:<br>            break</pre><pre>        if (<br>            target_index &lt; len(indices)<br>            and frame_index == indices[target_index]<br>        ):</pre><pre>            # OpenCV returns BGR, so convert to RGB.<br>            frame = cv2.cvtColor(<br>                frame,<br>                cv2.COLOR_BGR2RGB<br>            )</pre><pre>            # Resize to the target dimensions.<br>            frame = cv2.resize(<br>                frame,<br>                (WIDTH, HEIGHT),<br>                interpolation=cv2.INTER_LINEAR<br>            )</pre><pre>            selected_frames.append(frame)</pre><pre>            # Approximate timestamps for constant-FPS video.<br>            timestamp = frame_index / fps if fps &gt; 0 else None<br>            frame_timestamps.append(timestamp)</pre><pre>            target_index += 1</pre><pre>        frame_index += 1</pre><pre>    cap.release()</pre><pre>    if not selected_frames:<br>        raise RuntimeError(&quot;No frames were extracted&quot;)</pre><pre>    if len(selected_frames) != NUM_FRAMES:<br>        raise RuntimeError(<br>            f&quot;Expected {NUM_FRAMES} frames, &quot;<br>            f&quot;but extracted {len(selected_frames)}&quot;<br>        )</pre><pre>    return np.stack(selected_frames), frame_timestamps<br></pre><pre>frames, timestamps = extract_video_frames(VIDEO_PATH)</pre><pre>print(&quot;Frame shape:&quot;, frames.shape)<br>print(&quot;Sampled timestamps:&quot;, timestamps)</pre><p>Expected frame shape:</p><pre>Frame shape: (16, 224, 224, 3)</pre><p>This is our frame-major RGB representation.</p><p>A production decoder should use actual presentation timestamps where required. The example uses frame indices and an FPS-based timestamp approximation, so it is best suited to constant-frame-rate video with reliable frame-count metadata.</p><h3>9.2 Convert the frames into a PyTorch tensor</h3><pre># Convert uint8 pixel values into float32.<br>video_tensor = torch.from_numpy(frames).float()</pre><pre># Normalize pixel values from [0, 255] to [0, 1].<br>video_tensor = video_tensor / 255.0</pre><pre># Convert from (T, H, W, C)<br># to (C, T, H, W).<br>video_tensor = video_tensor.permute(3, 0, 1, 2)</pre><pre># Add batch dimension.<br>video_tensor = video_tensor.unsqueeze(0)</pre><pre>print(&quot;Final tensor shape:&quot;, video_tensor.shape)<br>print(&quot;Data type:&quot;, video_tensor.dtype)<br>print(&quot;Memory:&quot;, video_tensor.numel() * video_tensor.element_size())</pre><p>Expected output:</p><pre>Final tensor shape: torch.Size([1, 3, 16, 224, 224])<br>Data type: torch.float32<br>Memory: 9633792</pre><p>We have now created a video tensor in the standard input layout expected by a PyTorch 3D convolution.</p><p>However, this is not yet guaranteed to be a valid input for every pretrained video model.</p><p>Some models require:</p><ul><li>Specific frame counts.</li><li>Particular temporal sampling intervals.</li><li>Different spatial resolutions.</li><li>Specific normalization statistics.</li><li>Particular resizing or cropping policies.</li></ul><p>Always follow the preprocessing configuration associated with the model weights.</p><h3>9.3 Inspect the tensor</h3><p>We can verify the shape and numerical range:</p><pre>print(&quot;Shape:&quot;, video_tensor.shape)<br>print(&quot;Minimum:&quot;, video_tensor.min().item())<br>print(&quot;Maximum:&quot;, video_tensor.max().item())<br>print(&quot;Mean:&quot;, video_tensor.mean().item())</pre><p>The minimum and maximum should fall between 0 and 1 for this simple normalization pipeline.</p><p>We can also inspect the memory:</p><pre>memory_bytes = (<br>    video_tensor.numel()<br>    * video_tensor.element_size()<br>)</pre><pre>memory_mb = memory_bytes / 1_000_000<br>memory_mib = memory_bytes / (1024 ** 2)</pre><pre>print(f&quot;Memory: {memory_mb:.2f} MB&quot;)<br>print(f&quot;Memory: {memory_mib:.2f} MiB&quot;)</pre><p>Expected output:</p><pre>Memory: 9.63 MB<br>Memory: 9.19 MiB</pre><p>This confirms the memory calculation we performed mathematically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*dgEstWpi1jL48trw" /></figure><p><em>Python terminal displaying the final video tensor shape and its numerical properties.</em></p><h3>10. What Have We Actually Achieved?</h3><p>Let’s revisit the complete pipeline.</p><p>We started with a compressed video file.</p><p>The decoder reconstructed individual frames. Each frame contained a grid of pixels. Each pixel contained numerical color values.</p><p>We normalized those values, selected a subset of frames, resized the images, and organized the result into a multidimensional tensor.</p><p>Our transformation can be summarized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u100j_e2HdXuTdX6CxhH5Q.png" /></figure><p>And finally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*4U9gpfD0R855WHvluMnuQg.png" /></figure><p>This is the representation that a compatible 3D convolutional neural network can receive.</p><p>But notice something important.</p><p>At this stage, the tensor does not contain explicit labels such as:</p><ul><li>Person walking.</li><li>Vehicle approaching.</li><li>Object falling.</li><li>Physical interaction.</li><li>Abnormal activity.</li></ul><p>It contains numerical representations of visual observations.</p><p>The neural network must learn useful features from these numbers during training.</p><p>This brings us to the next fundamental question:</p><p><strong>How does a neural network extract meaningful information from millions of pixel values?</strong></p><p>How does it learn to recognize edges, textures, shapes, objects, and increasingly complex visual patterns?</p><p>That is the job of convolutional layers.</p><p>And understanding convolution is the next step in understanding how a video neural network actually works.</p><h3>11. Key Takeaways</h3><ol><li>A digital video is represented as a temporally ordered sequence of frames, not as one continuous image.</li><li>A decoded RGB frame contains three numerical values per pixel.</li><li>Normalization changes the numerical scale of pixel values to match the model’s expected input distribution.</li><li>Video decoding reconstructs frames from compressed video streams.</li><li>Frame sampling reduces computational requirements but can remove important temporal information.</li><li>Resizing and cropping determine which spatial details are preserved.</li><li>Tensor dimension ordering matters because different architectures expect different layouts.</li><li>The input tensor’s memory consumption is only one part of total GPU memory usage.</li><li>Preprocessing must match the model’s training configuration.</li><li>A video tensor provides numerical observations; meaningful visual understanding must be learned by the neural network.</li></ol><p><em>This article is Part 1 of the series “From Pixels to Predictions: Understanding Video Neural Networks.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15df387118db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Tried Building Real AI Systems. The Hardest Part Wasn’t the Model]]></title>
            <link>https://medium.com/@garvitjoshi46/i-tried-building-real-ai-systems-the-hardest-part-wasnt-the-model-9c80f041d6c4?source=rss-3480059874f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c80f041d6c4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Garvit Joshi]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 16:13:47 GMT</pubDate>
            <atom:updated>2026-11-01T16:13:47.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HhI4sfQogUBvuE40_FhOA.png" /></figure><p><em>Building AI taught me something tutorials rarely explain: getting a model to run is one problem. Getting it to work reliably in the real world is another.</em></p><p>When I started learning machine learning, I thought the difficult part was understanding algorithms, training models, and getting good evaluation metrics.</p><p>Learn Python. Understand the mathematics. Train a model. Deploy it.</p><p>That sounded like a reasonable roadmap.</p><p>Then I started working on actual AI systems.</p><p>I experimented with computer vision, video-based violence detection, and multilingual speech recognition. Each project exposed a different gap between what I expected AI to do and what it could reliably do.</p><p>The most important lessons didn’t come from a successful training run.</p><p>They came from discovering what happened after the model produced its output.</p><p>And that changed how I think about AI engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xlZmObIAVFY_nOH1sw2RA.png" /></figure><h3>1. A Model Can Run Successfully and Still Fail at Its Job</h3><p>Consider a computer vision system designed to detect violence in surveillance footage.</p><p>At first glance, the problem seems straightforward.</p><p>Collect videos. Label them. Train a neural network. Evaluate the predictions. Connect the model to an alert system.</p><p>I experimented with a dataset containing 2,000 videos: 1,000 labeled as violence and 1,000 as nonviolence.</p><p>I used PyTorch and a pretrained video classification model as the starting point for training.</p><p>The dataset was balanced, the videos could be decoded, and the training pipeline could run on my laptop’s NVIDIA RTX 3050 GPU.</p><p>Technically, these were useful milestones.</p><p>But they weren’t evidence that I had built a reliable violence detection system.</p><p>Think about what the model actually needs to understand.</p><p>Two people arguing isn’t necessarily violence.</p><p>Someone running isn’t necessarily escaping an attack.</p><p>A crowded street can look chaotic without anything criminal happening.</p><p>A physical fight might last only a few seconds in a much longer video.</p><p>The model must learn meaningful temporal patterns rather than simply associating particular visual scenes with a label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBU_dd5sBJMOS8i9XDynDg.png" /></figure><p>Even if it performs well on a test dataset, it could fail when exposed to unfamiliar camera angles, poor lighting, occlusion, different environments, or footage that differs from its training data.</p><p><strong>A model that performs well on a dataset has demonstrated something about that dataset. It has not automatically demonstrated that it can solve the real-world problem.</strong></p><p>That distinction matters.</p><p>A balanced dataset doesn’t guarantee representative data. Successful training doesn’t guarantee generalization. A high accuracy score doesn’t tell us how costly false alarms will be.</p><p>For a surveillance application, these aren’t minor details.</p><p>A false positive could unnecessarily trigger an emergency response. A false negative could mean a genuine incident goes unnoticed.</p><p>Before calling such a system production-ready, I’d want to evaluate it on independent footage, measure false positives and false negatives, assess performance across different conditions, and test how reliably it detects incidents over time.</p><p>I’d also want human verification before an automated detection could trigger a consequential real-world response.</p><p>The model is only one component of the system.</p><h3>2. Speech Recognition Taught Me Another Lesson: Plausible Output Isn’t Necessarily Correct Output</h3><p>Another project I explored involved multilingual speech recognition.</p><p>The idea was practical: a person speaks in a regional Indian language, the system transcribes the speech, converts the information into English, extracts relevant details, and generates a structured document.</p><p>For example, a medical intake workflow might capture a patient’s reported symptoms, allergies, and other information for review by a healthcare professional.</p><p>It sounds like a natural application of modern AI.</p><p>But there’s a problem.</p><p><strong>Speech recognition can produce text that looks perfectly reasonable while misrepresenting what the speaker actually said.</strong></p><p>I experimented with AI4Bharat’s IndicConformer multilingual speech recognition model.</p><p>When I tested Punjabi audio, I encountered inconsistent outputs across different language configurations. The resulting text could differ substantially from the intended speech.</p><p>That was an important reminder that multilingual speech recognition isn’t simply a matter of loading a model and accepting its output.</p><p>Language identification matters. So does the recording quality, the acoustic similarity between languages, the model’s training data, and the particular speech patterns of the speaker.</p><p>There is also a difference between transcription and translation.</p><p>Transcription attempts to preserve what was spoken in the original language.</p><p>Translation attempts to preserve its meaning in another language.</p><p>Combining the two without checking either stage can make errors difficult to identify.</p><p>Imagine a medical workflow in which the system incorrectly transcribes a medication name or omits an allergy.</p><p>The generated document might look professional. Its formatting might be excellent. The underlying information could still be wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sH-elRNxiAAFvbCLxBWITw.png" /></figure><p>A better architecture would separate the stages:</p><ol><li>Record the audio and preserve the original recording.</li><li>Identify the likely language, allowing uncertainty.</li><li>Generate a transcription in the original language.</li><li>Let the user or a qualified reviewer correct the transcription.</li><li>Translate the verified text when necessary.</li><li>Extract structured fields while preserving their source.</li><li>Flag missing, ambiguous, or conflicting information.</li><li>Generate the final document only after the appropriate checks.</li></ol><p>The exact implementation would depend on the use case, available models, and operational constraints.</p><p>But the underlying principle is simple: don’t confuse a polished output with a verified result.</p><h3>3. The Real Engineering Problem Is Everything Around the Model</h3><p>Machine learning tutorials often focus on a relatively contained task.</p><p>Given a dataset, train a model to minimize a loss function and evaluate its performance.</p><p>Real applications are less contained.</p><p>A deployed AI system must deal with problems that don’t appear neatly in a training notebook.</p><h3>Data quality</h3><ul><li>Are the labels reliable?</li><li>Does the dataset represent the environments in which the system will operate?</li><li>Are there duplicates, corrupted files, or data leakage between training and evaluation?</li></ul><h3>Inference</h3><ul><li>Can the model process new inputs within the required latency?</li><li>Will it fit within the available GPU memory?</li><li>What happens when the input is too large, too short, corrupted, or outside the expected format?</li></ul><h3>Reliability</h3><ul><li>Does the model behave consistently across different conditions?</li><li>Can the system recognize uncertainty?</li><li>What happens when the model returns an empty response, an invalid prediction, or an output that violates the expected schema?</li></ul><h3>Deployment</h3><ul><li>Can the application be packaged and deployed reproducibly?</li><li>Can the model be monitored after deployment?</li><li>Can a previous version be restored if a new version performs worse?</li></ul><h3>Evaluation</h3><ul><li>Does the evaluation measure what actually matters to the user?</li></ul><p>For a classification problem, accuracy might be useful. For a safety-related application, recall, precision, false-alarm rates, detection delays, and performance under different conditions may be equally or more important.</p><p>These questions are not separate from AI engineering.</p><p>They are AI engineering.</p><p>A sophisticated model inside an unreliable application can produce a worse user experience than a simpler model inside a well-designed system.</p><h3>4. I Started Seeing AI Projects as Systems, Not Models</h3><p>This changed the way I approached project development.</p><p>Instead of asking only, “Which model should I use?”, I began thinking about the entire workflow.</p><p>Consider a video-based incident detection application.</p><p>The complete system might look like this:</p><p><strong>Video stream → Frame sampling → Model inference → Temporal analysis → Confidence and event filtering → Alert generation → Human verification → Incident record</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WZiw8C_AIEBBZlfE0GVng.png" /></figure><p>Each component introduces its own engineering decisions.</p><ul><li>How frequently should frames be sampled?</li><li>Should predictions be aggregated across multiple frames?</li><li>How can repeated detections of the same event be prevented from generating dozens of alerts?</li><li>What happens when the video stream disconnects?</li><li>How do we distinguish a model failure from a camera failure?</li><li>How should the system record the evidence behind an alert?</li><li>What should happen when confidence is too low?</li></ul><p>These questions can determine whether the application is useful, regardless of which neural network sits at its center.</p><p>The same reasoning applies to speech recognition.</p><p>A speech-to-document application isn’t just a transcription model. It’s a pipeline involving audio capture, transcription, correction, translation, information extraction, validation, and document generation.</p><p>Every stage has failure modes.</p><p>If those failures are not handled explicitly, they propagate downstream.</p><p>For example, a transcription error can become a translation error, then an extraction error, and finally an incorrect field in a generated report.</p><p>The solution isn’t necessarily to use a larger model at every stage.</p><p>Sometimes the better solution is to add validation, preserve the original input, expose uncertainty, or ask a human to resolve ambiguity.</p><p><strong>Good AI engineering isn’t about eliminating every error. It’s about understanding errors, measuring their consequences, and designing the system to handle them safely.</strong></p><h3>5. Bigger Models Aren’t Always the Answer</h3><p>There’s a tendency to respond to an AI problem by searching for a better model.</p><ol><li>The current model isn’t accurate enough? Try a larger one.</li><li>Inference is slow? Look for a newer architecture.</li><li>The output is inconsistent? Replace the model.</li></ol><p>Sometimes those are the correct decisions.</p><p>But they shouldn’t be the default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IK-oCf0TXLg6RDdP3cSvw.png" /></figure><p>Suppose a model performs poorly because its training data doesn’t represent the intended environment.</p><p>A larger model trained on similarly unrepresentative data might not solve the problem.</p><p><strong>Suppose a speech recognition system struggles with a particular language</strong></p><p>Before replacing it, investigate whether the issue comes from language identification, audio quality, decoding settings, domain-specific vocabulary, or limitations in the model’s language coverage.</p><p><strong>Suppose a video model generates too many alerts</strong></p><p>The problem might involve temporal aggregation, thresholds, duplicate suppression, or the definition of a positive event rather than the underlying architecture alone.</p><p>A useful debugging process begins with measurement.</p><p>Establish a baseline. Inspect the failures. Categorize them. Identify the likely cause. Change one component. Evaluate again.</p><p>That approach is less exciting than announcing that you’ve discovered a revolutionary model.</p><p>It is also more likely to produce a working system.</p><p>And it encourages a more important skill: learning how to reason about failures instead of randomly changing components until the results look better.</p><h3>6. What This Means for Someone Trying to Become an AI Engineer</h3><p>If you’re learning AI because you want to work in the industry, there’s an important distinction to understand.</p><ul><li>Knowing how to train a model is valuable.</li><li>Knowing how to build a reliable application around it is a different skill.</li></ul><p>You don’t need to become an expert in every area before building something useful. But you should understand the major components of the systems you create.</p><p>I’d focus on five areas.</p><p><strong>1. Machine learning fundamentals</strong></p><p>Understand train, validation, and test splits; overfitting; data leakage; evaluation metrics; and generalization.</p><p>You should be able to explain why a model performs well and where that conclusion might be misleading.</p><p><strong>2. Software engineering</strong></p><p>Learn to write maintainable Python, structure projects into modules, manage dependencies, validate inputs, handle exceptions, and test important behavior.</p><p>A notebook is a useful experimentation environment. It is not automatically a deployable application.</p><p><strong>3. Model evaluation and debugging</strong></p><p>Don’t stop at the headline metric.</p><p>Inspect individual failures. Build error categories. Compare baselines. Track experiments. Understand what changes when you modify the data, preprocessing, or model.</p><p><strong>4. Deployment and infrastructure</strong></p><p>Learn how to expose models through APIs, package applications with Docker, manage model artifacts, and measure inference latency and resource usage.</p><p>You don’t need an elaborate cloud architecture for every project. Start with the simplest deployment that satisfies the requirements.</p><p><strong>5. Product thinking</strong></p><p>Ask who will use the system, what decision it helps them make, what happens when it fails, and whether the improvement is worth the operational cost.</p><p>A technically impressive model is not necessarily a useful product.</p><p>The strongest portfolio projects demonstrate more than a model checkpoint and a screenshot.</p><p>They explain the problem, document the data, justify the evaluation method, expose the limitations, and show how the application behaves when things go wrong.</p><p>That is much closer to the work an engineer performs outside a tutorial.</p><h3>7. The Question I Now Ask Before Choosing a Model</h3><p>I still find model architectures, training techniques, and new AI research interesting.</p><p>But I think a better starting question is:</p><p><strong>What would have to be true for this AI system to be useful in the real world?</strong></p><p>For a speech recognition application, the answer might involve reliable transcription, clear handling of uncertainty, and a practical correction workflow.</p><p>For an incident detection system, it might involve acceptable false-alarm rates, timely detection, robust performance across cameras, and a responsible alert process.</p><p>For a document extraction system, it might involve field-level accuracy, traceability to the source, and a way to review uncertain values.</p><p>Once those requirements are clear, model selection becomes more meaningful.</p><p>You can decide what to measure, which data you need, what failure modes matter, and which parts of the architecture deserve the most attention.</p><p>You can also discover that a proposed system isn’t ready for deployment, even if the model appears promising.</p><p>That isn’t a failure of engineering.</p><p>Recognizing the gap between an experiment and a dependable product is part of engineering.</p><h3>Final Thoughts</h3><p>I’m still learning, and the systems I’ve experimented with have exposed more questions than they have answered.</p><p>That’s precisely why I think building real projects is useful.</p><p>A tutorial can teach you how to train a model. An experiment can teach you how your assumptions break. A deployed system can teach you which failures matter to actual users.</p><p>Those are different kinds of learning.</p><p>If you’re working toward becoming an AI engineer, don’t measure your progress only by the number of models you’ve trained or frameworks you’ve used.</p><p>Ask yourself:</p><ul><li>Can you explain why your model fails?</li><li>Can you reproduce your experiments?</li><li>Can you evaluate it without misleading yourself?</li><li>Can you build an application that handles unexpected inputs?</li><li>Can you identify the risks of using its output?</li><li>And can you explain what evidence would convince you that the system is ready for its intended use?</li></ul><p>You don’t need perfect answers to all these questions before you start.</p><p>But the more seriously you investigate them, the more your work begins to resemble engineering rather than experimentation alone.</p><p><strong>The goal isn’t just to make AI work once. It’s to understand when it works, when it doesn’t, and what to do about the difference.</strong></p><p>I’m interested in hearing from other developers working on AI applications:</p><p><em>What’s been the hardest part of building a real AI system for you: finding the right model, getting good data, evaluating reliability, or deploying the complete application?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c80f041d6c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Features: Why Linear Algebra is the Unsung Hero of Modern Machine Learning]]></title>
            <link>https://medium.com/@garvitjoshi46/behind-the-features-why-linear-algebra-is-the-unsung-hero-of-modern-machine-learning-a72aee37ff51?source=rss-3480059874f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a72aee37ff51</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Garvit Joshi]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 14:53:54 GMT</pubDate>
            <atom:updated>2026-10-21T14:53:54.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cd2pcmJoEKTheGBCjPcJQw.jpeg" /></figure><h3>An Engineer’s POV on the High-Dimensional Operations That Power Our Daily Infrastructure</h3><p>When you’re first entering the Machine Learning (ML) field, it’s easy to get swept up in the high-level frameworks. It feels like our job is about model.fit(), API endpoints, and data pipelines.</p><p>But as any practicing ML Engineer eventually realizes, if software engineering is about writing code, ML engineering is about <strong>scaling math</strong>. Specifically, <strong>Linear Algebra</strong>.</p><p>Linear algebra isn’t just a prerequisite course you pass and forget. It is the very scaffolding of machine learning. Whether you are fine-tuning a Transformer, optimizing a recommendation engine, or trying to reduce inference latency, you are ultimately manipulating high-dimensional vector spaces.</p><p>Let’s look under the hood to see why Linear Algebra is so crucial, how it drives real-world ML systems, and exactly where it shows up in an engineer’s day-to-day workflow.</p><h3>The Real-World Picture: Linear Algebra in the ML Engineer’s Notebook</h3><p>When we conceptualize these systems, we aren’t thinking in abstract algebraic theorems. We are thinking about data flows, hardware utilization, and multi-dimensional spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VabjA2hMQ4w5R_OM.png" /><figcaption>Image Source: <a href="https://medium.com/analytics-vidhya/linear-algebra-how-uses-in-artificial-intelligence-2e1e001c65">https://medium.com/analytics-vidhya/linear-algebra-how-uses-in-artificial-intelligence-2e1e001c65</a></figcaption></figure><h3>1. The Core Real-Time Use Cases: How Linear Algebra Powers the Features</h3><p>If you look closely at almost any modern ML application, you will find a linear algebra problem disguised as a product feature. Here are the most prominent real-world applications where this math comes alive:</p><h4>A. Vector Embeddings and Recommendation Systems (The Dot Product)</h4><ul><li><strong>The Problem:</strong> How does Spotify suggest your next favorite song, or how does a retail site find products similar to what you just bought?</li><li><strong>The Math:</strong> When we convert items (text, songs, movies) into continuous numeric representations, we get <strong>vectors</strong> in a high-dimensional space. To find out how “similar” two items are, we don’t use heuristic rules; we calculate the <strong>Dot Product</strong> or <strong>Cosine Similarity</strong> ($\cos \theta$) between their embedding vectors.</li></ul><p><strong>Engineering Impact:</strong> For an ML Engineer, calculating these similarity metrics is the difference between a sluggish <strong>O(N²)</strong> search and a fast <strong>O(logN)</strong> <a href="https://www.geeksforgeeks.org/machine-learning/approximate-nearest-neighbor-ann-search/">approximate nearest neighbor (ANN)</a> search using vector databases (like Pinecone, Milvus, or Qdrant). Understanding the geometry of these spaces helps you debug why your search system returns irrelevant results — often due to vector drift or poor scaling.</p><h4>B. High-Dimensional Data &amp; Compression (Dimensionality Reduction via SVD/PCA)</h4><ul><li><strong>The Problem:</strong> Training models on datasets with thousands of features is computationally expensive and prone to the “curse of dimensionality.”</li><li><strong>The Math:</strong> By using Singular Value Decomposition (SVD) or Principal Component Analysis (PCA), you can find <strong>eigenvectors</strong> and <strong>eigenvalues</strong> to identify the directions (principal components) along which your high-dimensional data has the most variance.</li><li><strong>Engineering Impact:</strong> In practice, an ML Engineer uses this to compress huge feature sets (like genomics or user behavioral history) into a fraction of their size, without losing the critical signal. Running PCA before feeding data into your training pipeline can cut API response times and drastically reduce your cloud compute costs.</li></ul><h4>C. Neural Network Transforms and the Attention Mechanism (Matrix Multiplication)</h4><ul><li><strong>The Problem:</strong> How does a model “understand” the context of a sentence or process a digital image?</li><li><strong>The Math:</strong> Modern Neural Networks (like transformers powering LLMs) are essentially cascading series of matrix multiplications. For example, in self-attention, we project input vectors into Query (Q), Key (K), and Value (V) matrices. The calculation is purely linear algebra.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xzf3E5KeAkH71fgvtVgxpQ.png" /></figure><ul><li><strong>Engineering Impact:</strong> Behind every Transformer inference or training job is a massive matrix multiplication. Engineers have to care about how these matrices are clustered, partitioned, and stored in memory to prevent GPUs from running out of VRAM (OOM errors) during scale-up.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*MUjjI2YqtOMJfkAqtXEulg.png" /></figure><h3>2. The GPU Bottleneck: Why Matrices Rule ML Infrastructure</h3><p>As a software or ML engineer, you spend a lot of your time optimizing latency and throughput. This is where linear algebra crosses over from math into computer systems.</p><p>CPUs are designed to handle complex, sequential tasks, one at a time. However, ML workloads don’t need complex logic; they need to perform billions of trivial additions and multiplications simultaneously.</p><p>This is why GPUs and TPUs exist. They are hardware specifically designed to perform parallelized matrix operations. When you use frameworks like PyTorch or TensorFlow, your high-level Python code is compiled down to CUDA operations that perform <strong>GEMM (General Matrix Multiply)</strong> at the silicon level.</p><p>If you understand matrix dimension alignment and memory pooling, you can optimize your neural networks. For example:</p><ul><li><strong>Batching:</strong> Processing multiple inputs at once by stacking them into a single 2D or 3D tensor (matrix) to maximize GPU memory bandwidth.</li><li><strong>Quantization:</strong> Reducing the precision of matrix values (from 32-bit floats to 8-bit integers) so the hardware can perform matrix math much faster with lower memory usage.</li></ul><h3>3. How Linear Algebra Shows Up in an ML Engineer’s Daily Job</h3><p>You don’t need to be solving pen-and-paper equations all day, but linear algebra dictates how you write and debug your systems:</p><ol><li><strong>Debugging Tensor Shape Errors:</strong> The absolute most common bug in deep learning is the mismatch of matrix dimensions (e.g., trying to multiply an <strong>(8, 512) matrix</strong> by a <strong>(256, 128) matrix</strong>). You must know the rules of matrix multiplication to trace these errors in your logs.</li><li><strong>Optimizing Loss Functions:</strong> To train models, you are finding the minimum of a complex, multi-dimensional function. Calculating the <strong>Gradients</strong> (using the Jacobian and Hessian matrices) tells the optimization algorithm which way to update the model’s weights.</li><li><strong>Deploying to Production (Vector search/RAG):</strong> When implementing Retrieval-Augmented Generation (RAG) for an enterprise LLM, you are designing a pipeline that embeds, index, and retrieves vectors. You need to ensure the system is scaling properly, which requires an understanding of distance metrics and vector similarity.</li></ol><h3>The Takeaway: It’s the “Machine Code” of Intelligence</h3><p>At the end of the day, machine learning is just linear algebra applied to real-world datasets. Knowing the math gives you a superpower: you stop treating ML models as “black boxes” and start seeing them for what they really are — dynamic, high-speed geometric transformations.</p><p>The next time you train a model, optimize a feature set, or scale a vector search database, remember that you are directing a massive, digital orchestra of matrices, vectors, and coordinate spaces. Designing these systems is where software engineering meets the math that makes computers smart.</p><p><em>Have you run into tricky tensor-shape mismatches or optimized a vector search pipeline? Share your thoughts below! Check out my Medium profile at </em><a href="https://medium.com/@garvitjoshi46"><em>medium.com/@garvitjoshi46</em></a><em> for more visual engineering breakdowns.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a72aee37ff51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying ChatGPT’s Amnesiac Click: What Actually Happens When You Clear Memory?]]></title>
            <link>https://medium.com/@garvitjoshi46/demystifying-chatgpts-amnesiac-click-what-actually-happens-when-you-clear-memory-578ed2c58b38?source=rss-3480059874f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/578ed2c58b38</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <dc:creator><![CDATA[Garvit Joshi]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 08:07:12 GMT</pubDate>
            <atom:updated>2026-10-19T08:07:12.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXXUU3ttHsgWTcoRjxRJCw.jpeg" /></figure><h3>A system-architecture deep dive into state management, vector databases, prompt assembly pipelines, and distributed cache invalidation in modern LLM platforms.</h3><p>When you click <strong>“Clear ChatGPT Memory”</strong> or tell ChatGPT to <em>“forget everything you know about me,”</em> it feels like granting an artificial intelligence a moment of selective amnesia. Within milliseconds, a message pops up: <em>“Memory updated.”</em></p><p>To the end user, it seems like the AI wiped a section of its digital brain. But under the hood, something far more interesting is happening.</p><p>Large Language Models (LLMs) like GPT-4o are <strong>fundamentally stateless</strong>. They have no internal dynamic memory that changes when you chat with them. The core weights of the model are frozen during inference.</p><p>So how does ChatGPT “remember” that you prefer Python over JavaScript, live in San Francisco, or like concise bullet points? And more importantly: <strong>what actually gets destroyed when you click that clear button?</strong></p><p>In this deep dive, we will peel back the layers of OpenAI’s infrastructure and trace the exact system-level sequence of events that occurs when you wipe ChatGPT’s memory.</p><h3>1. The Core Architecture: The Stateless Illusion</h3><p>To understand how memory is deleted, we must first understand how memory is <em>simulated</em>.</p><p>When you interact with ChatGPT, every request to the model runtime is an isolated execution. The neural network itself remembers <strong>nothing</strong> between API calls.</p><p>ChatGPT creates the illusion of long-term memory through a technique called <strong>Context Injection</strong>. Before your prompt ever reaches the transformer attention layers, an upstream <strong>Context Assembly Engine</strong> intercepts your input and constructs a massive prompt payload.</p><pre>+-----------------------------------------------------------------------------------+<br>|                            THE CONTEXT WINDOW PAYLOAD                             |<br>+-----------------------------------------------------------------------------------+<br>|  1. SYSTEM DIRECTIVES      | Base instructions, safety guardrails, system persona |<br>+----------------------------+------------------------------------------------------+<br>|  2. SAVED USER MEMORIES    | Persistent facts extracted across past sessions      |<br>|                            | (e.g., &quot;User is a senior backend engineer&quot;)          |<br>+----------------------------+------------------------------------------------------+<br>|  3. CUSTOM INSTRUCTIONS    | Manual user overrides (&quot;How you&#39;d like ChatGPT to...&quot;)|<br>+----------------------------+------------------------------------------------------+<br>|  4. SESSION METADATA       | Date, time, platform, locale                          |<br>+----------------------------+------------------------------------------------------+<br>|  5. CONVERSATION HISTORY   | Sliding window of recent turn-by-turn messages        |<br>+----------------------------+------------------------------------------------------+<br>|  6. ACTIVE USER PROMPT     | &quot;Can you review this code snippet?&quot;                  |<br>+-----------------------------------------------------------------------------------+</pre><p>When you click “Clear Memory,” you are not modifying neural weights or fine-tuning models. You are targeting <strong>Layer 2: Saved User Memories</strong> inside the external data platform that feeds this context pipeline.</p><h3>2. Where Memory Lives: The 3-Tier Storage Engine</h3><p>ChatGPT does not store long-term memories as raw text files. It relies on a multi-tiered database setup designed for ultra-fast retrieval during prompt assembly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZH5sAODZrQ-CnUO7yGWaw.png" /></figure><h3>Tier A: The Relational Key-Value Store (Metadata &amp; Explicit Facts)</h3><ul><li><strong>Technology:</strong> PostgreSQL / Amazon DynamoDB / CockroachDB</li><li><strong>Purpose:</strong> Holds explicit, discrete fact strings extracted by the memory agent.</li><li><strong>Schema:</strong></li></ul><p>{ &quot;user_id&quot;: &quot;usr_99827361&quot;, &quot;memory_id&quot;: &quot;mem_01J8A4K&quot;, &quot;fact&quot;: &quot;Prefers TypeScript for frontend development&quot;, &quot;source_chat_id&quot;: &quot;chat_773192&quot;, &quot;created_at&quot;: &quot;2026-03-12T10:15:30Z&quot;, &quot;status&quot;: &quot;ACTIVE&quot; }</p><h3>Tier B: The Vector Database (Semantic Retrieval / RAG)</h3><ul><li><strong>Technology:</strong> Pinecone / Qdrant / Milvus / pgvector</li><li><strong>Purpose:</strong> Converts memory text into high-dimensional vector embeddings ($1536$ or $3072$ dimensions).</li><li><strong>Function:</strong> When you ask a question like <em>“What language should we use for this UI project?”</em>, the system performs a vector similarity search (using cosine distance) against your memory embeddings to fetch only relevant facts into the active context window.</li></ul><h3>Tier C: In-Memory Context Caches</h3><ul><li><strong>Technology:</strong> Redis / Memcached clusters</li><li><strong>Purpose:</strong> Caches pre-compiled prompt payloads for active user sessions to minimize latency and database query overhead on every turn.</li></ul><h3>3. The Execution Path: What Happens When You Click “Clear Memory”?</h3><p>When you trigger a memory wipe in the UI or ask ChatGPT in natural language to <em>“delete all my memories,”</em> a coordinated multi-service cascade is set off across the system.</p><pre>[ Client UI ]<br>       |<br>       |  1. DELETE /api/v1/user/memories/clear<br>       v<br>  [ API Gateway &amp; Auth ]<br>       |<br>       |  2. Validates JWT &amp; User Session Token<br>       v<br>  [ Memory Service Manager ]<br>       |<br>       +-------------------+-------------------+-------------------+<br>       |                   |                   |                   |<br>       v                   v                   v                   v<br>  [ Relational DB ]   [ Vector Index ]   [ Redis Caches ]   [ Analytics Audit ]<br>  Hard/Soft Delete     Purge Embeddings   Evict Keys         Record Event Log<br>  `status = DELETED`   from HNSW Graph    `DEL user:123:*`   (GDPR Compliance)</pre><p>Let’s break down each step in this pipeline:</p><h3>Step 1: Request Dispatch &amp; Auth Verification</h3><p>The frontend sends an authenticated HTTP request (e.g., DELETE /v1/user/memories) containing your bearer token and user_id. The API Gateway validates your permissions and routes the job to the <strong>Memory Management Microservice</strong>.</p><h3>Step 2: Relational Database Mutation</h3><p>The microservice executes a query against the primary store. Depending on privacy settings, this is either a <strong>hard delete</strong> (DELETE FROM user_memories WHERE user_id = &#39;usr_123&#39;) or a <strong>soft delete</strong> where rows are marked with a tombstone (status = &#39;PURGED&#39;, deleted_at = NOW()).</p><h3>Step 3: Vector Index Un-indexing</h3><p>This is the most compute-intensive part. Vector databases use graph-based structures (like HNSW — Hierarchical Navigable Small World) to enable fast similarity search.</p><p>When memories are deleted:</p><ul><li>The memory ID node is removed from the vector graph index.</li><li>Filter tags (e.g., user_id == usr_123) are invalidated so semantic vector searches during prompt assembly immediately return empty results (k=0).</li></ul><h3>Step 4: Redis Payload Cache Eviction</h3><p>If you are mid-session, your system prompt payload is likely cached in Redis to save database roundtrips. The Memory Service broadcasts an invalidation event over a Pub/Sub message bus. Redis nodes execute a key deletion (DEL session_prompt:usr_123), forcing the next message in your chat to rebuild the context payload from scratch.</p><h3>Step 5: Context Re-assembly Verification</h3><p>On your next message, the <strong>Context Builder Engine</strong> query looks like this:</p><pre># Simplified Context Assembly Logic<br>def build_prompt_context(user_id, current_message):<br>    system_prompt = load_base_system_prompt()<br>    <br>    # Query database for user memories<br>    active_memories = db.query(<br>        &quot;SELECT fact FROM user_memories WHERE user_id = %s AND status = &#39;ACTIVE&#39;&quot;, <br>        (user_id,)<br>    )<br>    <br>    # After clearing memory, active_memories is []<br>    if active_memories:<br>        memory_block = &quot;User Background:\n&quot; + &quot;\n&quot;.join(active_memories)<br>    else:<br>        memory_block = &quot;&quot;  # NO MEMORIES INJECTED<br>        <br>    return f&quot;{system_prompt}\n\n{memory_block}\n\nUser: {current_message}&quot;</pre><p>Because active_memories returns an empty array, <strong>no persistent context is prepended</strong>. The model receives only the clean system prompt and your active message. To the model, you are now a completely new user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ie8VdAtNtPxhGpv0C_76w.png" /></figure><h3>4. Comparing the 3 Types of Erasure in ChatGPT</h3><p>Users often confuse clearing memory with starting a new chat or deleting custom instructions. Here is how they differ at the storage layer:</p><p><strong>OperationScopeAffected ComponentDoes it clear active chat context?</strong></p><p><strong>Clear Memory</strong></p><p>Long-term background facts extracted across all past sessions.</p><p>Relational DB &amp; Vector Store embeddings bound to user_id.</p><p><strong>No.</strong> Active thread history remains until you start a new chat.</p><p><strong>New Chat</strong></p><p>Active conversation turn history.</p><p>In-memory conversation buffer / thread history DB.</p><p><strong>Yes.</strong> Resets the current sliding window.</p><p><strong>Delete Custom Instructions</strong></p><p>System-level prompt behavior preferences manually typed by the user.</p><p>User Profile settings table.</p><p><strong>No.</strong> Stored separately from extracted memory facts.</p><h3>5. What About Model Training Data and Privacy?</h3><p>A common question from security-conscious engineers is: <strong>“Does clearing memory remove my data from OpenAI’s trained models?”</strong></p><p>The answer lies in the fundamental difference between <strong>In-Context Memory</strong> and <strong>Parametric Weight Memory</strong>.</p><ul><li><strong>In-Context Memory (What Memory Uses):</strong> Information is stored externally in databases and fed through the prompt context window. When you clear memory, database rows are deleted. It is immediate, deterministic, and total.</li><li><strong>Parametric Memory (Model Weights):</strong> If your account has “Improve the model for everyone” enabled, chat logs may be periodically processed in asynchronous batch pipelines for offline reinforcement learning (RLHF) or fine-tuning.</li></ul><p>When you request memory deletion or account data deletion under regulations like GDPR or CCPA:</p><ol><li>Production databases and vector indexes drop the keys instantly.</li><li>Backup snapshots purge the deleted records within standard rotation windows (typically 30 days).</li><li>Data pipelines exclude opted-out or deleted user IDs from future training runs.</li></ol><h3>Summary: The Magic Behind the Amnesiac Click</h3><p>When you clear ChatGPT’s memory, you are not performing AI brain surgery or retraining neural network weights.</p><p>Instead, you are executing a precise, high-performance database deletion script across a distributed data pipeline. By purging key-value rows, un-indexing vector embeddings, and evicting Redis caches, OpenAI ensures that the next time you press enter, the context assembly engine has no past facts to hand over to the model.</p><p>The AI didn’t “forget” you — its pipeline simply stopped telling the AI who you were.</p><h3>Key Takeaways for Engineers &amp; System Designers</h3><ul><li><strong>LLMs are stateless engines;</strong> dynamic memory is always an orchestration layer pattern (RAG + Prompt Engineering).</li><li><strong>Clearing memory is a database CRUD operation,</strong> targeting vector stores and relational stores, not transformer weights.</li><li><strong>Cache invalidation is critical;</strong> clearing persistent DB entries without purging Redis session stores will lead to memory “hallucination leaks” during active sessions.</li></ul><p><em>Enjoyed this breakdown? Follow for more system architecture analyses of real-world AI platforms.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=578ed2c58b38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>