<?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 Rafał Bodziony on Medium]]></title>
        <description><![CDATA[Stories by Rafał Bodziony on Medium]]></description>
        <link>https://medium.com/@rafalb?source=rss-9364fa570430------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BgZYyJyCR5WTO1ICNMcOAw.jpeg</url>
            <title>Stories by Rafał Bodziony on Medium</title>
            <link>https://medium.com/@rafalb?source=rss-9364fa570430------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:45:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafalb/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[I Restored a Forgotten 1971 Film with Open-Source AI — for a Projector Night with Friends]]></title>
            <link>https://medium.com/@rafalb/i-restored-a-forgotten-1971-film-with-open-source-ai-for-a-projector-night-with-friends-edc9eccdaf45?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/edc9eccdaf45</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[film]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 08:12:47 GMT</pubDate>
            <atom:updated>2026-09-25T08:12:47.622Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From a 512×384 TV rip to a 1080p black-and-white master, a colour version and clean audio. Plus a few of us hidden among the extras.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PE5UeEy3JXA_GL5rTbelAg.jpeg" /><figcaption><em>The same frame three times: the TV rip I started from, the restored black-and-white master, and the colour version.</em></figcaption></figure><p>I wanted to watch <em>Kardiogram</em>, a 1971 Polish film, with friends on a projector. It turned out to be a small adventure.</p><p>At the time I started the project, I couldn’t find the film on any VOD service. Filmweb pointed me to where a copy might exist, and the only one I could find was an old TV recording on a well-known video site:</p><ul><li>512×384 pixels;</li><li>a TV channel logo burned into the corner;</li><li>compressed mono sound.</li></ul><p>On a laptop screen it’s watchable. On a two-metre projector screen it’s a blurry mess.</p><p>So I spent a couple of hours (and a few hours of GPUs humming) turning it into something worth projecting. I built the pipeline together with an AI coding agent, which wrote and ran the scripts while I made the calls on taste. This post covers what worked, what didn’t, and the numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfVkHUuuyMUpQ8Zl9doisA.png" /><figcaption>The whole pipeline, from the TV rip to the files we played</figcaption></figure><h3>Rule #1: a two-minute pilot</h3><p>Before touching the whole film (124,366 frames), I cut a two-minute pilot. It had:</p><ul><li>dialogue;</li><li>faces, close and in the background;</li><li>a night scene;</li><li>shop signs;</li><li>the logo.</li></ul><p>I tested every idea there first and judged it on the screen it was meant for. This saved me from at least three expensive mistakes.</p><p>The analysis also found something I hadn’t expected. The film was shot at 24 fps, but the TV transfer runs at 25 fps. That’s the classic PAL speed-up: everything is 4% faster, and voices are slightly higher. The restoration goes back to 24 fps, with pitch-corrected audio. The film now runs 86 minutes instead of 83.</p><h3>Clean before you upscale</h3><p>AI upscalers amplify whatever you feed them, including compression blocks, dust and the halos from an over-sharpened TV transfer. So cleaning comes first. It runs in VapourSynth, in this order:</p><ol><li><strong>Deblocking</strong> with DPIR at a low strength (0.3). At 0.5 and above, faces started to look plastic.</li><li><strong>Dust removal</strong> with a motion-compensated temporal median.</li><li><strong>Dehalo:</strong> removing the bright outlines around edges. This was the most important step for this particular transfer.</li><li><strong>Light degrain</strong> with MVTools.</li></ol><p><em>The same frame through the cleanup steps and the final upscale.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gRANaqRUrkgofH2mjGjhzQ.jpeg" /><figcaption>The same frame through the cleanup steps and the final upscale</figcaption></figure><h3>Removing the TV logo</h3><p>The channel logo sat in the corner for the whole film. <strong>ProPainter</strong>, a video inpainting model, reconstructs the area behind it from the neighbouring frames, and the result survives even a 4x zoom.</p><p>Two lessons from running it on a whole film:</p><ul><li>ProPainter keeps the whole clip in GPU memory. One 2.5-minute shot ran a 32 GB card out of memory.</li><li>A false scene cut produced a one-frame “shot”, which crashed it as well.</li></ul><p>The fix was to split long shots at 600 frames and merge tiny ones. The runs are also resumable now, so a crash doesn’t cost everything that was already done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQ5xoEl3lbRHKpzhR4Y28Q.jpeg" /><figcaption>Left: the TV logo. Right: after ProPainter inpainting</figcaption></figure><h3>Upscaling: what failed and what worked</h3><p><strong>What failed:</strong> a popular fast 2x upscaler (SPAN). It looked sharp at first glance, but it turned small and medium faces into masks with black eye sockets. I checked the raw source too, and the upscaler itself caused it, not my cleanup. For a film made of faces, that’s a deal-breaker.</p><p><strong>What worked:</strong> <strong>SeedVR2</strong> (3B, FP16), a diffusion-based video restoration model. It rebuilds plausible detail instead of just sharpening edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjQya_qPNorDxjw080KODA.jpeg" /><figcaption><em>Same face, same frame. Left: the TV rip upscaled. Right: SeedVR2.</em></figcaption></figure><p>It is slow, though.</p><ul><li><strong>720p output + Lanczos to 1080p</strong> looked almost identical to native 1080p and was 2.3 times faster.</li><li>Locally, on an RTX A6000, that’s still <strong>1–2 days</strong> for the whole film.</li><li>In the cloud, I rented one machine with <strong>8× RTX 5090 </strong>and split the film into 8 parts at scene cuts, one per GPU.</li><li>Each GPU managed ~0.5 s per frame.</li><li>The upscale itself took about 2.2 hours.</li><li>The whole rental, including setup and downloading, was about 3 hours and roughly <strong>$12</strong>.</li></ul><p><strong>Lesson learned the hard way:</strong> keep the <em>clean</em> upscaled output, with no grain, grading or resizing, before you destroy the cloud machine. I baked film grain into the cloud output, so every later brightness tweak had to be applied on top of it.</p><h3>A grade for the projector</h3><p>TV rips are graded for old TV sets, and on a projector this one looked dark and muddy. I compared it with professional Polish restorations of films from the same era. They keep true blacks, lift the midtones and have more local contrast. We tried three looks and picked the middle one:</p><ul><li>a black point;</li><li>a gamma lift;</li><li>a touch of local contrast.</li></ul><p>“Better too bright than too dark” was the rule for projection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_vJI8KeKcPpPXrHr5nHiw.jpeg" /><figcaption>Top and bottom: TV-rip levels (left) versus the projector grade (right).</figcaption></figure><h3>Colour</h3><p>Colourisation is still controversial for classics, so the black-and-white master stays the main version. But we wanted to try it.</p><p><strong>What failed:</strong> DDColor keyframes. Everything got a magenta/purple cast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHZYlD_1in2ANG2Obj0x4g.jpeg" /><figcaption>DDColor (left) gave a magenta cast; Qwen-Image-Edit (right) looked natural.</figcaption></figure><p><strong>What worked</strong> was a two-step approach:</p><ol><li><strong>Qwen-Image-Edit-2511</strong> (a GGUF Q8 build with the Lightning 8-step LoRA) coloured <strong>360 keyframes</strong>: one per shot, plus one every 500 frames. That took about 23 seconds per frame, 2.3 hours in total.</li><li><strong>CMNET2</strong>, an exemplar-based video colourisation network, propagated that colour through every frame, shot by shot. That took about 6 hours overnight.</li></ol><p>We take only the colour channels from this step. The brightness comes 1:1 from the restored black-and-white master, so both versions share the same detail and the same projector grade.</p><p>Projectors wash colours out a bit, so we compared saturation levels and settled on 1.15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eP-EE12ldR6yH7pZ6WwDig.jpeg" /><figcaption>Saturation 1.0, 1.15 and 1.4. At 1.4, faces go orange</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9NkiXWFC6IW1uYbS5WegQ.jpeg" /><figcaption>A few frames from the colour version.</figcaption></figure><h3>Sound: you can see it, even if you can’t hear it here</h3><p>The mono track had three problems:</p><ul><li>constant hiss;</li><li>a 50 Hz mains hum with its harmonics;</li><li>a boomy, reverberant room sound.</li></ul><p>The chain that finally worked:</p><ol><li><strong>AI hiss removal first:</strong> a Mel-RoFormer denoise model on the whole mix. In quiet passages, the energy above 4 kHz dropped from −51 dB to −99 dB.</li><li><strong>Gentle de-reverb</strong> (MDX23C), keeping about a third of the room so it doesn’t sound dead.</li><li><strong>Dialogue/background separation</strong> with BandIt Plus, then <strong>DeepFilterNet3</strong> on the dialogue only. On the full mix it also cut the music by 5.5 dB.</li><li><strong>Dialogue +7 dB above 180 Hz only.</strong> A full-band boost made the low end “pump” with every word.</li><li>Gentle ducking of the background under speech.</li><li>Loudness normalisation to −23 LUFS.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61RIgvb9YI4JVWbW8EFFcA.jpeg" /><figcaption>Spectrogram of the same 20 seconds: original TV audio (top) and restored (bottom).</figcaption></figure><p><em>The same 20 seconds. The hiss (the purple haze) is gone, and the speech stays.</em></p><p>Archival restorers usually keep a light, stable hiss. I tried that, and my ears preferred it clean, with clear dialogue. The original TV track is still in the file as a second audio track.</p><h3>The Easter egg</h3><p>For the screening, we added a small game. We picked a few scenes with extras and put our own faces on them, so during the screening everyone hunts for the others. I’m not showing those frames here (my friends deserve their privacy), so here is FaceFusion’s own demo image instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*oCGFvDSZcP8Us0mWECY7Kw.jpeg" /><figcaption><em>Image: FaceFusion’s own demo image (source, target, output), from github.com/facefusion/facefusion</em></figcaption></figure><p>The tool was <strong>FaceFusion 3.9</strong> with the <strong>HyperSwap</strong> model. The tricks that mattered on an old black-and-white film:</p><ul><li><strong>Turn on the face tracker.</strong> It is off by default, and without it every frame is matched on its own, so the face “jumps” whenever one frame fails.</li><li><strong>Feed several photos of the person.</strong> FaceFusion averages them into one identity, which gives a more stable face than a single portrait.</li><li><strong>Use the box mask on bearded or moustached targets.</strong> The occlusion mask treats facial hair as an obstacle, so the original moustache flickers through.</li><li><strong>Clean up colour blobs.</strong> The swapper leaves small purple blobs on grey faces, and I inpaint any coloured pixel before splicing.</li><li><strong>Swap only the moments where the face is really visible.</strong> Head turns and bent heads just flicker.</li></ul><h3>Delivery</h3><p>The masters are HEVC 10-bit MKV files. For the laptop and the Mac I also made MP4 copies (H.264 + AAC), which play in QuickTime, Windows and VLC and on TV/projector USB players. Each copy is about 9 GB, so I carried them on an <strong>exFAT</strong> drive; FAT32 can’t hold files over 4 GB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbvb3Iy6NErFY4EmA2fcOg.jpeg" /><figcaption>Before | after.</figcaption></figure><h3>What I learned</h3><ol><li><strong>Pilot first, on the target screen.</strong> Monitor judgments don’t transfer to a projector.</li><li>On this source, diffusion SR (<strong>SeedVR2</strong>) handled faces much better than the <strong>GAN</strong> upscalers I tested</li><li><strong>Clean the source before upscaling.</strong> Deblock, dehalo and remove dust first.</li><li><strong>Keep every expensive intermediate</strong> before you destroy a cloud machine.</li><li><strong>Colour from keyframes plus propagation</strong> beats frame-by-frame colourisation for consistency, and the keyframe model decides the palette.</li><li><strong>Audio is half of the experience.</strong> Separating dialogue from the background makes AI denoising safe.</li><li><strong>Keep a decision log.</strong> Every test, number and verdict went into one file. It made the work reproducible, and it made this article easy to write.</li></ol><h3>What’s next</h3><p>The scripts are still tied to this film and to my machine. The plan is to clean them up:</p><ul><li>one config file per film;</li><li>a model download manifest;</li><li>standalone environments;</li><li>a set of Claude Code skills, one per stage.</li></ul><p>Then I’ll publish them as open source. If you’d like to restore an old family film or a forgotten classic this way, follow me and I’ll post the repository here.</p><p><em>I’m not sharing the film itself. This was a private screening, and the frames above are here only to show the process.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edc9eccdaf45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agents Are Becoming Infrastructure. Workflows Are the Product.]]></title>
            <link>https://medium.com/@rafalb/agents-are-becoming-infrastructure-workflows-are-the-product-759baff65e91?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/759baff65e91</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 16:21:56 GMT</pubDate>
            <atom:updated>2026-06-18T16:21:56.818Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lh5GmyRNwqFKpg6E" /><figcaption>Photo by <a href="https://unsplash.com/@motaehdaei?utm_source=medium&amp;utm_medium=referral">Mota Ehdaei</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is not about “agents are the future”. That sentence is too vague to be useful.</p><p>The more interesting signal is different: <strong>general agent runtime and capability discovery are becoming infrastructure</strong>. They are moving down the stack. The real problem is moving up: work structure, domain workflows, contracts, validation, and ownership.</p><p>In the last few days, we got two good signals. <a href="https://vercel.com/eve"><em>Vercel introduced </em><strong><em>eve</em></strong></a>, an open-source framework for building, running, and scaling agents in production. It includes durable execution, sandboxed compute, human-in-the-loop approvals, subagents, evals, and other production pieces that many teams would otherwise rebuild by hand.</p><p><a href="https://developers.googleblog.com/announcing-the-agentic-resource-discovery-specification/"><em>Google also announced the </em><strong><em>Agentic Resource Discovery</em></strong><em> specification</em></a>. ARD defines a way for agents to discover and verify external capabilities such as MCP servers, A2A agents, OpenAPI tools, skills, APIs, and other callable resources through things like ai-catalog.json and discovery services.</p><p>Both announcements point in the same direction. The bottom of the agent stack is becoming more structured. But it does not solve the hardest enterprise problem.</p><h3>Eve Is a Signal That Agent Runtime Is Getting a Production Shape</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKUd7L4Vvp38pKbJPfujMg.png" /><figcaption><a href="https://vercel.com/eve">Vercel Eve Page</a></figcaption></figure><p>Most agent demos are simple. An LLM gets a prompt, calls a tool, returns an answer, and maybe writes something to a file.</p><p>But the real agent may need to wait for human approval. It may run for hours. It may be called slow systems. It may crash in the middle of execution. It may need to resume after deployment. It may need a sandbox because the generated code should not run directly on the main system. It may need evals because nobody wants to trust a black box with production actions.</p><p>This is the area where frameworks like Eve matter.</p><p>Eve treats an agent as a directory of files. Instructions, tools, skills, subagents, channels, and schedules live in conventional places. The directory tells us what the agent is, what it can do, where it runs, and when it acts on its own.</p><p>When agent logic is just a pile of prompts and scripts, it is hard to review. It is hard to onboard another engineer. It is hard to understand what should be deployed, tested, approved, or removed.</p><blockquote>A filesystem-first structure is boring in a good way.</blockquote><p>It shows where the market is going. Durable execution, sandboxes, approvals, channels, schedules, and evals are not unique product ideas forever. They are common runtime requirements.</p><p>If enough teams need them, platforms and open-source frameworks will provide them.</p><h3>ARD Is a Signal That Discovery Is Also Becoming a Layer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GNUUafpQ1YzAW12_.jpg" /><figcaption><a href="https://developers.googleblog.com/announcing-the-agentic-resource-discovery-specification/">Agentic Resource Discovery</a></figcaption></figure><p>Runtime is not the only part getting standardized. An agent also needs to know what it can call.</p><p>Today this is often handled manually. We wire tools into the agent. We paste tool descriptions into context. We configure MCP servers. We add API credentials. We maintain our own internal list of capabilities.</p><p>However, it becomes painful when every team exposes its own tools, APIs, workflows, skills, or agents.</p><p>Google’s ARD specification tries to solve this part of the stack. A provider can publish an ai-catalog.json file on its domain. Discovery services can index available capabilities. An AI client can search for resources before invoking them. ARD sits before execution and does not replace the runtime, MCP, A2A, skills, or APIs.</p><p>This distinction is important.</p><blockquote>ARD does not tell the agent how to run.</blockquote><p>It tells the agent how to find what exists and how to reason about trust before connecting to it. It also suggests that “agent as a catalog” is a good direction. But it is still not enough.</p><p>A catalog of agents is not the same thing as a catalog of work.</p><h3>The Generic Harness Will Be Commodity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeOWGpMbPgBR7zwefQLUbQ.png" /></figure><p>The first wave of agent products focused on the harness.</p><ul><li>Prompt loop</li><li>Tool calling</li><li>Skills and MD files</li><li>Memory</li><li>Retries</li><li>Sandbox</li><li>Approvals</li><li>Maybe evals</li><li>Maybe subagents</li><li>Maybe schedules</li></ul><p>This was necessary. The early stack was messy, and every team needed some orchestration layer. But building another generic agent framework without a domain process around it will make less sense over time.</p><p>The big platforms will provide this. Open-source will provide this. Cloud vendors will provide this. The most important developer tools will provide this.</p><p>The generic runtime becomes the place where competition is brutal. Every feature can be copied. Every abstraction can be rebuilt. Every missing runtime primitive becomes a checklist item.</p><p>But most companies do not win because they built a slightly better internal queue. They win because they know which business process should be automated, how it should be verified, and who owns it when it fails.</p><p>Agents will follow the same path.</p><h3>The Missing Layer Is Work Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQspvRLf70e5ZGq5OVee-Q.png" /></figure><p>The hard part in companies is rarely “can we call a tool from an LLM?”.</p><p>The hard part is usually this:</p><ul><li>What exactly should the agent do?</li><li>Which data can it read?</li><li>Which source is authoritative?</li><li>What is the expected output?</li><li>Who approves risky decisions?</li><li>What counts as a correct result?</li><li>Where should artefacts be written?</li><li>How do we reproduce the result next month?</li><li>Who maintains this after the first demo?</li></ul><p>This is where many agent projects break. The runtime works. The demo works. The tool call works. The Slack bot responds. And then the project gets stuck because the agent has no clear work structure.</p><p>It does not know the business process, review gate, data contract, metrics and artefact. So the agent becomes another interface over organizational ambiguity.</p><p>And ambiguity does not become easier just because an LLM is involved.</p><h3>A Useful Map of the Agent Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fu8e5-iV48vINvW7OcjQUw.png" /></figure><p>I would split the stack into five layers.</p><h4>Layer 1: Runtime</h4><p>Examples: Eve, Claude Code, Codex, Hermes, OpenCode.</p><p>The runtime executes the agent.</p><p>It handles tool use, sandboxing, approvals, durable execution, subagents, evals, schedules, and communication channels.</p><p>This layer answers:</p><blockquote>How does the agent run safely and reliably?</blockquote><h4>Layer 2: Discovery / Trust</h4><p>Examples: Google ARD, ai-catalog.json, registries.</p><p>This layer helps agents find capabilities and check whether they should trust them.</p><p>It answers:</p><blockquote>What capability exists, who published it, and can the agent use it?</blockquote><h4>Layer 3: Protocols / Tools</h4><p>Examples: MCP, OpenAPI, A2A, native APIs.</p><p>This layer connects agents to systems.</p><p>It answers:</p><blockquote>How does the agent call the system?</blockquote><h4>Layer 4: Knowledge / Context</h4><p>Examples: repositories, docs, Markdown files, YAML configs, OKF-like knowledge, data catalogs, run logs, decision logs.</p><p>This layer gives the agent context.</p><p>It answers:</p><blockquote>What does the organization already know, and what happened before?</blockquote><h4>Layer 5: Domain Workflow</h4><p>Examples: data science workflow, ML experimentation workflow, regulatory workflow, document workflow, code maintenance workflow.</p><p>This layer defines the work.</p><p>It answers:</p><blockquote>What should be done, in what order, under which constraints, and how do we know the result is correct?</blockquote><p><strong>This last layer is the most important one. It is also the least solved.</strong></p><h4>Runtime Tells the Agent How to Act. Workflow Tells It What Work Means.</h4><p>A runtime tells an agent how to behave. It handles the mechanics: which tool to call, when to wait for approval, whether to run something in a sandbox, how to retry after failure, where to checkpoint progress, and how to evaluate the output.</p><p>That matters, but it is not the same as defining the work.</p><p>A workflow gives the agent the actual shape of the job. It tells the agent where to begin, what constraints to collect, which data contracts to check, what metric matters, how to plan execution, when to run an experiment, how to detect leakage, how to verify reproducibility, what the final report should include, and who owns the result.</p><p>So the difference is simple: the runtime tells the agent how to act, while the workflow tells the agent what the work actually means.</p><p>Without a workflow, the agent may still look capable. It can call tools, follow steps, and produce outputs. But it is operating without enough context about the real goal, the standards of success, or the risks involved. That can look impressive in a demo, but it becomes dangerous in a production system.</p><h3>Example: Data and ML Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QWEJ6wNmeHXC1bU-0RILg.png" /></figure><p>Data science is a good example because the hard part is almost never “train a model.”</p><p>That is the visible part. It is also usually the easiest part. The mess starts before that. Someone says they want a model. Fine. For what?</p><p>Better predictions? Lower support cost? Fewer manual reviews? Better ranking? Faster research? Less fraud? More revenue? These are not the same problem, and they do not lead to the same workflow.</p><p>Then comes the data question, which is where things usually get ugly.</p><p>What is the agent allowed to read? Production tables? Customer data? PII? Only anonymised datasets? Which table is actually trusted? Which one is just convenient? Who owns it? When was it last updated? Does anyone know?</p><p>Then the labels.</p><p>Are they stable? Were they created by humans? By another model? By business rules that changed three times last year? Are timestamps reliable, or are we accidentally training on data from the future? Are the joins safe, or are we quietly leaking information across tables?</p><p>This is why “just run experiments” is not enough.</p><p>Even the metric can be a trap. Accuracy can look good while the model is useless. AUC can hide the cost of false positives. High recall can flood an ops team with junk. A beautiful model can be too slow to use in production.</p><p>The runtime does not solve any of this.</p><p>A runtime can tell the agent how to call tools, where to run code, when to ask for approval, how to retry, and how to log progress. Good. We need that.</p><p>But it does not know which data is safe, which metric matters, which table is trusted, or what failure looks like for the business.</p><p>That has to come from the workflow.</p><p>For an ML agent, the workflow should force the boring questions early: what are we trying to change, what data is allowed, what constraints matter, what output is expected, and who will own the result.</p><p>Then it should make the agent check the data before touching the model. Schema, freshness, missing values, label quality, table ownership, known issues, and possible leakage.</p><p>Only after that should the agent plan an experiment: baseline, metric, validation strategy, features, tracking, and review gates.</p><p>Then it can run the work. Profile the data. Generate features. Train models. Compare runs. Write analysis. Open a pull request. Prepare the report.</p><p>That is where agents are useful. Not as magic data scientists.</p><blockquote>More like execution layers inside a workflow that already knows what good work looks like.</blockquote><p>Without that workflow, the agent can still produce notebooks, charts, metrics, and reports. It may look productive. But it is just producing artefacts around an undefined problem.</p><p>And that is how you get impressive demos and bad systems.</p><h3>The Catalog of Work Matters More Than the Catalog of Agents</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qJzK3MpGzYUfHEN6nVhzg.png" /></figure><p><strong>The catalog of work matters more than the catalog of agents.</strong></p><p>Discovery is useful. A company should know which agents exist, which tools they can call, which APIs are available, and which MCP servers are connected.</p><p>But discovery is not the hard part.</p><p>An agent can find a forecasting tool. That does not mean it knows whether forecasting is the right answer. It can find a SQL tool. That does not mean it knows which table people actually trust. It can find a document generator. That does not mean it knows which legal template applies. It can find a code maintenance agent. That does not mean it knows who has to review the change before it lands.</p><p>This is the weak point in most “agent catalog” thinking. It assumes that once capabilities are discoverable, useful work will happen. That is wrong.</p><p>Capabilities are not work.</p><p>A tool catalog might say:</p><pre>Tool: run_sql<br>Description: Run SQL against the warehouse</pre><p>That is not enough. The system also needs to know the shape of the work around that tool.</p><p>For example:</p><pre>Workflow: ML experiment review<br>Owner: Data Science Platform team<br>Allowed data: curated feature tables<br>Required checks: leakage, reproducibility, metric review<br>Approval gate: model owner<br>Final artifact: experiment report in the project repository<br>Maintenance owner: project team after handoff</pre><p>That is much less exciting than announcing a new agent framework. It is also much closer to the real problem.</p><p>Most companies do not fail because they lack one more generic agent. They fail because nobody has encoded how the work is supposed to happen.</p><p>This is where the real opportunity is.</p><p><strong>Not another generic agent platform with a chat box, tool calling, memory, retries, and approvals. That layer will become crowded fast.</strong></p><p>The better opportunity is domain workflows for specific classes of work.</p><p>Data science. ML research. Regulatory review. Public procurement documents. Backend code maintenance. Cloud cost optimization. Security triage. Incident analysis. Architecture review.</p><p>Each of these has its own rules. Different inputs, different artifacts, different review gates, different failure modes, different owners.</p><p>A useful agentic system for one of these domains should not start with a blank chat box.</p><p>It should start with the work process.</p><p>Here are the inputs. Here are the constraints. Here are the allowed tools. Here is the validation. Here is the approval path. Here is the final artifact. Here is who owns it afterward.</p><blockquote>The agent is just the executor. The workflow is the product.</blockquote><h3>Trade-Offs</h3><p>The right starting point is usually not to write a custom agent from day one.</p><p>In the beginning, it makes more sense to use the agents that already exist: Claude Code, Codex, Kimi, and similar tools. They are already good enough for many coding, analysis, and automation tasks. They are maintained by teams that spend far more time on model behavior, tool use, code review, sandboxing, and developer experience than most companies can afford internally.</p><p>So the first question should not be,</p><blockquote>“How do we build our own agent?”</blockquote><p>The better question is,</p><blockquote>“What work do we want the agent to do, and what structure does that work need?”</blockquote><p>Start with a generic agent, but put it inside a simple workflow. Define the input, the constraints, the allowed tools, the expected output, the review step, and the owner. Then let the generic agent execute parts of that process.</p><p>After that, watch what happens.</p><p>If the same task repeats, the same checks are needed, the same output format is expected, and the same failure modes appear, then you have a real workflow. At that point, you can decide whether the generic agent is still enough or whether a custom agent is worth building.</p><p>In many cases, the answer may be: <strong>stay generic</strong>.</p><p>That is not a failure. It may be the better architecture.</p><p>A generic agent can become something like a database or cloud service. Someone else builds the engine, improves it, patches it, optimizes it, and keeps it current. You do not rebuild Postgres just because your company has data. You use the database, but you still design your schema, permissions, queries, backups, and operating rules.</p><p>Agents may work the same way.</p><p>The generic agent is the execution engine. The company-owned workflow is the schema around the work.</p><p>The trade-off is control.</p><p>With a generic agent, you move faster and benefit from outside improvements, but you have less control over behavior, internals, and long-term guarantees.</p><p>With a custom agent, you get more control, tighter integration, and clearer ownership, but you also take on the cost of building, testing, maintaining, and updating it.</p><p>So the practical path is:</p><blockquote>start with generic agents, wrap them in workflows, learn from repeated use, and only build custom agents where the generic ones fail in a way that actually matters.</blockquote><p>The product is not the custom agent. The product is the working system around it.</p><h3><strong>The Workflow Is the Product</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtJreldyOi52wGt6brcnFQ.png" /></figure><p>Use workflow-first agents when the task has real consequences.</p><p>Not for every small automation. Not for a one-off summary. Not when the team is still exploring the problem and does not yet know what the process should be.</p><p>But once the agent touches company data, writes reports, creates pull requests, prepares decisions, changes systems, or produces artifacts that other people will rely on, the structure starts to matter.</p><p>At that point, the agent should not be treated as the product.</p><p>The product is the workflow around it.</p><p>That workflow defines what data the agent can use, what checks it must run, who reviews the output, where the final artifact lives, and who owns the result after handoff.</p><p>Without that structure, the agent may still look useful for a week. It may answer questions, call tools, and produce impressive output. But it will be hard to audit, hard to reproduce, and hard to trust inside a real operating process.</p><p>This is the larger shift in the agent stack.</p><p>Runtimes are getting better. Tool discovery is becoming more standard. Protocols are improving. Generic agents are getting stronger.</p><p>All of that matters.</p><p><strong>But most companies do not lack another way to call tools from an LLM. They lack a clear definition of the work itself: the contracts, gates, artifacts, owners, and criteria for correctness.</strong></p><p>That is why the better opportunity is not just another generic agent harness.</p><p>It is building workflows for concrete domains where agents act as executors inside a process.</p><p>Runtime tells the agent how to act.</p><p>Workflow tells it what the work means.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=759baff65e91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AI Tennis Match Reporter. It Failed in the Most Useful Way.]]></title>
            <link>https://medium.com/@rafalb/i-built-an-ai-tennis-match-reporter-it-failed-in-the-most-useful-way-9722356d51be?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/9722356d51be</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sport-analytics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tennis]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 08:31:00 GMT</pubDate>
            <atom:updated>2026-06-12T08:31:00.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*alkEWBXq_4CoAgznXCVUow.png" /></figure><p><em>One game. One YouTube URL. One Gemini call. A very nice dashboard. And a very useful failure.</em></p><p>I play tennis. I watch tennis. I also like building weird AI demos that sit somewhere between useful and stupid.</p><p>After the recent Maja Chwalińska run at Roland Garros, Polish tennis Twitter was alive again. That was enough of an excuse for me to test an idea I had been thinking about for a while:</p><blockquote>Can a video reasoning model watch a tennis match and generate a structured “match follow” log — point by point, shot by shot, like a sports newsroom or match analytics tool?</blockquote><p>Not a generic recap.</p><p>Not “Nadal played well.”</p><p>I wanted data.</p><p>Something like:</p><pre>{<br>  &quot;point&quot;: 1,<br>  &quot;score_before&quot;: &quot;0-0&quot;,<br>  &quot;score_after&quot;: &quot;15-0&quot;,<br>  &quot;serve&quot;: &quot;second serve in&quot;,<br>  &quot;rally&quot;: [<br>    &quot;return&quot;,<br>    &quot;forehand&quot;,<br>    &quot;volley&quot;,<br>    &quot;lob&quot;,<br>    &quot;overhead winner&quot;<br>  ],<br>  &quot;ending&quot;: &quot;winner&quot;,<br>  &quot;winner&quot;: &quot;player_a&quot;<br>}</pre><p>The dream version is simple:</p><pre>YouTube video<br>→ Gemini video reasoning<br>→ structured tennis event log<br>→ dashboard / live follow / article</pre><p>If this worked, you could imagine doing this for lower-level tournaments, club matches, academies, YouTube highlights, or niche sports where no live data provider exists.</p><p>So I tested it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*1joIdB6gYwONu6AMvLw07w.gif" /></figure><h3>Why Gemini looked perfect for this</h3><p>Gemini API can take video input, including public YouTube URLs. That is already a big deal. I did not need to download the video, cut it, upload it, or build a media pipeline just to test the idea.</p><p>I could send:</p><pre>YouTube URL<br>start time<br>end time<br>FPS<br>prompt<br>schema</pre><p>and ask for structured output.</p><p>For a quick prototype, that is ideal.</p><p>The first version of the prompt asked for:</p><ul><li>players</li><li>scoreboard</li><li>point-by-point timeline</li><li>serve attempts</li><li>return and rally contacts</li><li>stroke type</li><li>hand used</li><li>ball zones</li><li>spin / pace / height</li><li>point ending</li><li>winner/error</li><li>short point summary</li></ul><p>I tested this on one game from a Nadal vs Hurkacz practice video.</p><p>One game. Four points. Very small scope.</p><p>That should have been easy.</p><p>It was not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9eoZrlpEM9vFGU82RucSg.png" /></figure><h3>The first dashboard looked convincing</h3><p>The output looked impressive at first.</p><p>I had:</p><ul><li>player names</li><li>a game score</li><li>point cards</li><li>serve attempts</li><li>rally length</li><li>shot chains</li><li>final shots</li><li>error types</li><li>court zones</li><li>a static HTML dashboard</li></ul><p>The dashboard looked like a small “AI Tennis Match Follow” product.</p><p>Five KPI cards:</p><ul><li>Game result</li><li>Service control</li><li>First-serve pressure</li><li>Rally profile</li><li>Point endings</li></ul><p>Then a point-by-point timeline:</p><pre>Point 1: 0–0 → 15–0<br>Point 2: 15–0 → 30–0<br>Point 3: 30–0 → 40–0<br>Point 4: 40–0 → GAME–0</pre><p>Then shot chains like:</p><pre>Serve → Return → Forehand → Backhand → Forehand winner</pre><p>Visually, it started to look like something.</p><p>But when I checked it as a tennis player, the problem was obvious:</p><blockquote>The JSON looked professional, but the tennis was wrong.</blockquote><h3>What went wrong</h3><p>The model did not just make small label errors. It changed the actual story of the points. In one point, what I saw was roughly:</p><pre>serve<br>return<br>crosscourt<br>crosscourt<br>Nadal volley / net-play setup<br>Hurkacz lob<br>Nadal overhead / smash-like finish</pre><p>Gemini often turned that into:</p><pre>baseline rally<br>forehand/backhand exchange<br>Hurkacz backhand error</pre><p>That is not a small difference.</p><p>That is a different point.</p><p>The same pattern repeated:</p><ul><li>It confused forehand and backhand.</li><li>It confused the first serve and the second serve.</li><li>It confused return errors with winners.</li><li>It sometimes skipped net-play actions.</li><li>It inserted normal baseline rallies where the actual action was more specific.</li><li>It gave high confidence to wrong actions.</li></ul><p>The last point is the worst.</p><p>A model saying “unclear” is useful.</p><p>A model saying the wrong thing with 0.90 confidence is dangerous.</p><h3>Higher FPS helped, but did not solve it</h3><p>I tested different settings.</p><p>At low FPS, the model was too vague and often collapsed rallies into generic tennis language. At <strong>10 FPS</strong>, it got better. At <strong>higher image settings</strong>, it sometimes caught more details, including overhead/smash-like actions.</p><p>But it still was not stable.</p><p>The core issue stayed the same:</p><blockquote>The model can describe tennis-looking motion, but it does not reliably preserve the actual event structure of the point.</blockquote><p>In tennis, that structure matters.</p><p>A point is not just “a rally happened.”</p><p>A point has a very specific order:</p><pre>first serve<br>maybe fault<br>second serve<br>return<br>rally contacts<br>point ending<br>score update</pre><p>If the model gets that order wrong, everything downstream is poisoned.</p><p>A dashboard built on bad event data is just a nice-looking lie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCHObqx_2-ohSQjJveDUbg.png" /></figure><h3>The real issue: VLMs are not sports event parsers</h3><p>This is where the experiment became more interesting.</p><p>The problem was not JSON. The problem was not “bad UI.” The problem was that the model does not really understand the sport state machine.</p><p>It sees frames. It sees players. It sees a ball sometimes. It can produce a plausible description.</p><p>But a tennis event parser needs to know:</p><ul><li>who served</li><li>whether the first serve was fault or in</li><li>whether the return cleared the net</li><li>whether a ball bounced before contact</li><li>whether a shot was a forehand, backhand, volley, lob, or overhead</li><li>where the ball landed</li><li>who won the point</li><li>how the score changed</li><li>when the next point started</li></ul><p>That is not just visual captioning.</p><p>That is structured temporal understanding.</p><p>And right now, at least in this test, Gemini was not reliable enough to be the source of truth.</p><h3>Could this work with prompting?</h3><p>Maybe a little. A better prompt helped. A simpler prompt helped. Asking for a plain point-by-point timeline instead of JSON helped. Higher FPS helped. But none of it fully fixed the issue. Prompting can improve format. Prompting can force the model to be more careful. Prompting cannot fully replace a model that understands tennis-specific events.</p><p>If a model cannot reliably tell whether Hurkacz hit a forehand or backhand, or whether Nadal finished with an overhead instead of a baseline forehand, no prompt will magically turn it into Hawk-Eye.</p><h3>What would probably work</h3><p>The right architecture is not:</p><pre>Gemini watches full game<br>→ perfect event JSON</pre><p>The right architecture is more likely:</p><pre>video<br>→ scoreboard OCR<br>→ point boundary detection<br>→ player tracking<br>→ ball/contact detection<br>→ short clip classifier per contact<br>→ tennis scoring validator<br>→ structured event log<br>→ LLM writes the article / match follow</pre><p>In that setup, the LLM is not the referee.</p><p>The LLM is the writer.</p><p>The source of truth comes from:</p><ul><li>computer vision</li><li>domain-specific models</li><li>scoreboard extraction</li><li>deterministic tennis rules</li><li>maybe human review</li></ul><p>Then the LLM can turn the structured data into:</p><ul><li>a live blog</li><li>a match report</li><li>tactical notes</li><li>multilingual copy</li><li>an article</li></ul><p>That part still makes sense. The idea is good. The model choice and trust boundary were wrong.</p><h3>Could this be real-time?</h3><p>With pure Gemini-style video reasoning?</p><p>I doubt it.</p><p>Not for reliable tennis analytics. Maybe for rough commentary or draft match notes. But for real-time event parsing, you would probably need a hybrid system:</p><pre>classic CV / deep learning<br>+ sport-specific event models<br>+ LLM for language</pre><p>For example:</p><ul><li>OCR reads the scoreboard.</li><li>A detector finds serves and contacts.</li><li>A classifier labels strokes from short clips.</li><li>A scoring engine validates the point sequence.</li><li>An LLM turns the data into readable match follow copy.</li></ul><p>That is a much more realistic path.</p><h3>So was this a failure?</h3><p>As a product demo: partly. As a learning experiment: no.</p><p>I learned something useful:</p><blockquote>Today’s VLMs can generate a plausible sports event log, but plausible is not enough for sport.</blockquote><p>Sport is unforgiving because the truth is discrete. The ball was in or out. The serve was first or second. The stroke was forehand or backhand. The point was won by one player, not both. A wrong event log still looks clean in JSON.</p><p><strong>That is the trap.</strong></p><p>There is also a cost angle here.</p><p>For one short game, less than two minutes of video, the high-resolution Gemini run consumed roughly <strong>300k</strong> input tokens. The structured output for the game was around 10k tokens.</p><p>That is not insane for an experiment. For a prototype or a one-off analysis, it is actually quite accessible. The workflow is fast, there is no video ingestion pipeline, and being able to point the model directly at a YouTube URL is genuinely useful.</p><p>But the business case depends on what you are trying to sell.</p><p>If the output is a draft for a journalist, coach, analyst, or content creator, maybe that cost is acceptable. You are paying for a quick first pass: scoreboard, players, rough timeline, possible article angles, and a structured starting point.</p><p>If the output is supposed to be the source of truth for match analytics, the economics change. You cannot pay for a high-resolution video reasoning call, get a confident but wrong event log, and then spend human time correcting every point anyway. At that point, the expensive part is not the model call.<strong> The expensive part is trust</strong>.</p><p>This is where the product boundary matters.</p><ul><li>A VLM-generated draft can be useful.</li><li>A VLM-generated official event feed is a different problem.</li></ul><h3>What I would test next</h3><p>I would not build a bigger dashboard.</p><p>I would build a benchmark.</p><p>Take 20–50 tennis games and label:</p><ul><li>point start/end</li><li>score before/after</li><li>serve result</li><li>point winner</li><li>final shot type</li><li>ending type</li><li>error player</li><li>maybe shot sequence for visible rallies</li></ul><p>Then compare:</p><ul><li>Gemini at 1 FPS</li><li>Gemini at 10 FPS</li><li>high-res Gemini</li><li>per-point clips</li><li>maybe another VLM</li><li>maybe simple CV heuristics</li></ul><blockquote>The key metric is not “does the output look good?”</blockquote><p>The key metric is:</p><blockquote>How often is the event log actually right?</blockquote><p>That is the asset. Not another AI dashboard.</p><h3>Final take</h3><p>The final lesson is simple.</p><p>General video reasoning models are getting good at producing structured sports-looking output. But sports are not just visual captioning. It is a sequence of discrete events with rules, state, causality and scoring.</p><p>For tennis, the model cannot just sound right. It has to know whether the first serve was a fault, whether the second serve landed in, whether Player hit a forehand or backhand, and how that changes the score.</p><p>In my test, Gemini could produce a convincing draft. It could not yet act as the source of truth.</p><p>The product idea is still interesting. But the architecture should probably be less magical:</p><ul><li>Computer Vision for events.</li><li>Sport-specific models for strokes and contacts.</li><li>A deterministic scoring engine for validation.</li><li>An LLM at the end for sequencing, explanation and writing.</li></ul><p>Less impressive in a demo. Much closer to something that actually works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9722356d51be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do Not Give Network Access When Operation Access Is Enough]]></title>
            <link>https://medium.com/@rafalb/do-not-give-network-access-when-operation-access-is-enough-fa419d9695cc?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa419d9695cc</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 07:31:00 GMT</pubDate>
            <atom:updated>2026-06-08T07:31:00.733Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical AWS pattern for exposing controlled operations across VPC boundaries without handing out broad network access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tKvWVpfIVP7KmJ_H" /><figcaption>Photo by <a href="https://unsplash.com/@jouwdan?utm_source=medium&amp;utm_medium=referral">Jordan Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>Sometimes, one service needs something from another VPC.</em></blockquote><p>The standard AWS practice is to connect the VPCs.</p><p>You set up VPC Peering, Transit Gateway, PrivateLink, or VPC Lattice. After that, you update route tables, security groups, NACLs, DNS, IAM, documentation, and diagrams. Sometimes, you even start a Slack thread that everyone forgets about in two weeks.</p><p>Sometimes this is the right answer. But not always.</p><p>The better question is not:</p><blockquote>How do we give Service Y access to VPC X?</blockquote><p>The better question is:</p><blockquote>Does Service Y need network access, or does it only need one operation?</blockquote><p>That’s the main point of this article.</p><p><strong>Lambda does not replace any of those services. It solves a different problem.</strong></p><p>It’s about exposing a small, controlled business operation within a single VPC without granting another service broad network access.</p><h3>The problem</h3><p>Assume we have this architecture:</p><pre>VPC X<br>  EC2 / Redis / RDS / internal API / NAT Gateway path<br><br>VPC Y<br>  An application service that needs something from VPC X</pre><p>The first version of the requirement usually sounds like this:</p><pre>Service Y needs access to Redis in VPC X.</pre><p>Or:</p><pre>Service Y needs access to an internal API in VPC X.</pre><p>Or:</p><pre>Service Y needs to call an external operator via the whitelisted IP<br>address in VPC X.</pre><p>In many cases, the actual requirement is far more limited.</p><pre>getTenantConfig(tenantId)<br><br>fetchFeatureFlags(serviceName)<br><br>reserveInventory(itemId)<br><br>writeAuditEvent(payload)<br><br>callExternalOperator(payload)</pre><p>These are not the same thing.</p><p>The first version says:</p><blockquote><strong>Give this system a network path.</strong></blockquote><p>The second version says:</p><blockquote><strong>Allow this system to perform one controlled operation.</strong></blockquote><p>One scenario requires network architecture; another only needs a purpose-built adapter.</p><h3>Why “just connect the VPCs” is not always the right first answer</h3><p>AWS gives us several ways to connect VPCs. The problem comes when we use a network-level tool to solve a business-level need.</p><p>If you only need one small operation, setting up broad networking can create more work than it solves:</p><pre>More routes<br>More security group rules<br>More DNS behavior<br>More blast radius<br>More ownership questions<br>More places in which traffic can go by accident<br>More documentation that will be outdated by next quarter</pre><p>Six months later, someone asks:</p><blockquote>Why can this service reach that subnet?</blockquote><p>Nobody knows. But the route is still there.</p><p>That’s classic cloud archaeology.</p><h3>Network access vs operation access</h3><p>Before connecting anything, ask yourself:</p><blockquote>Does the caller need the resource protocol, or only the result of a business operation?</blockquote><p>Bad abstraction:</p><pre>Service Y needs Redis access</pre><p>Better abstraction:</p><pre>Service Y needs to read SmallCacheRecord(key)</pre><p>Bad abstraction:</p><pre>Service Y needs RDS access</pre><p>Better abstraction:</p><pre>Service Y needs to getTenantConfig(tenantId)</pre><p>Bad abstraction:</p><pre>Service Y needs the same outbound operator path as VPC X.</pre><p>Better abstraction:</p><pre>Service Y needs callExternalOperator(payload)</pre><p>If the consumer needs arbitrary SQL queries, raw Redis commands, direct TCP access, very low latency, high throughput, or full protocol control, use proper networking.</p><p>If the consumer needs a small number of defined operations, a Lambda boundary adapter may be cleaner.</p><h3>Lambda as a VPC boundary adapter</h3><p>The pattern is simple.</p><pre>VPC Y / Service<br>|<br>| Lambda Invoke<br>v<br>Lambda Boundary Adapter<br>|<br>| private ENI / SG<br>v<br>VPC X / private resources</pre><p>The Lambda approach does not connect the networks. It exposes an operation.</p><p>A Lambda function can be configured with VPC access. That allows it to reach private resources through selected subnets and security groups.</p><p>So the boundary becomes:</p><pre>IAM permission<br>Lambda input contract<br>Validation<br>Logs<br>Rate limits<br>Private resource access inside VPC X</pre><p>Not:</p><pre>CIDR-to-CIDR network access</pre><p>That is a very different control model.</p><h3>Example 1: whitelisted NAT and external operator IP</h3><p>This is one of the most practical cases.</p><p>Assume VPC X already has:</p><pre>Private subnets<br>NAT Gateway<br>Elastic IP<br>External operator/vendor has this public IP whitelisted</pre><p>Now a service in VPC Y also needs to call the same operator API.</p><p>The default architecture may become:</p><pre>Connect VPC Y to VPC X<br>Route traffic using shared egress<br>Update route tables<br>Update security groups<br>Deal with DNS<br>Explain the new path to security<br>Hope nothing else starts using it</pre><p>Maybe this is correct. But if Service Y only needs one operator call, another option is:</p><pre>VPC Y / App<br>|<br>| invoke Lambda<br>v<br>Lambda in VPC X<br>|<br>| outbound through NAT Gateway with whitelisted EIP<br>v<br>External operator API</pre><p>The goal is not to avoid networking for its own sake. The goal is cleaner ownership. VPC Y doesn’t need the entire egress path. It just needs one approved operation through a path that’s already allowed.</p><h3>Example 2: private resource in another VPC</h3><p>Now take a more common internal example.</p><pre>VPC X<br>  Redis / Valkey / ElastiCache<br>  RDS<br>  internal HTTP service<br>  private API<br>VPC Y<br>  service that needs one read or write operation</pre><p>The weak requirement is:</p><pre>Give Service Y access to Redis.</pre><p>The better requirement may be:</p><pre>getTenantConfig(tenantId)<br><br>fetchFeatureFlags(serviceName)<br><br>reserveInventory(itemId)<br><br>writeAuditEvent(payload)</pre><p>The Lambda boundary adapter sits inside VPC X and communicates with the private resource on behalf of a single controlled operation.</p><pre>VPC Y / Service<br>|<br>| InvokeFunction: getTenantConfig<br>v<br>Lambda Boundary Adapter<br>|<br>| TCP / HTTP inside VPC X only<br>v<br>Redis / RDS / internal API</pre><p>The private resource stays private.</p><p>The caller never receives:</p><pre>Redis endpoint<br>database hostname<br>database credentials<br>internal API URL<br>security group access<br>route-table path</pre><p>It only gets the result of the operation.</p><h4>Where this becomes bad</h4><p>This pattern breaks down when the Lambda becomes a generic proxy.</p><p>Bad signs:</p><pre>executeSql(query)<br><br>redisCommand(command, args)<br><br>httpProxy(method, path, headers, body)<br><br>tcpTunnel(destination, payload)</pre><p>At that point, you are not exposing an operation.</p><p>You end up rebuilding network access, but with worse latency, less effective tools, and probably harder debugging.</p><p>Lambda is good for narrow request/response operations.</p><ul><li>It is not a good fake TCP tunnel.</li><li>It is not a good generic SQL proxy.</li><li>It is not good as a generic Redis proxy.</li><li>It is not good as a high-throughput database access layer for five teams, because no one wanted to touch the network diagram.</li></ul><p><strong>That is not architecture. That is technical debt with an AWS logo.</strong></p><h3>Why this is mostly about control</h3><p>The strongest argument for this pattern is not always cost but control. With direct networking, the consumer often receives a path to a resource or subnet. With a Lambda boundary adapter, the consumer receives permission to perform a specific operation.</p><h3>IAM access to the operation</h3><p>Access can be expressed as:</p><pre>Principal X can invoke the function getTenantConfig-prod</pre><p>Instead of:</p><pre>CIDR A can reach CIDR B on port 6379</pre><p>Both controls can be valid, but they solve different problems. Networking controls packets, while IAM controls who can call the operation.</p><p><strong>For business operations, IAM is often a better fit for the real requirement.</strong></p><h4>Secrets stay on the owner’s side</h4><p>The Lambda in VPC X can own:</p><pre>database credentials<br>operator API keys<br>Redis auth<br>internal service tokens<br>request signing keys</pre><p>The caller doesn’t need these secrets. This is especially helpful if VPC X is owned by another team or AWS account.</p><p>Instead of sharing network paths and credentials, the owner exposes a contract.</p><p>A Lambda operation gives you better audit points:</p><pre>who invoked the function<br>which operation was called<br>which tenantId was requested<br>which validation rule rejected the payload<br>how long the downstream call took<br>how often throttling happened<br>which version handled the request</pre><p>You can build auditing with direct networking too. But then every consuming service has to implement it correctly, which can be nearly impossible.</p><h4>Input validation before private resources</h4><p>The adapter can reject bad requests before they hit the private resource.</p><p>For example:</p><pre>tenantId must match the expected format<br>payload size must be limited<br>caller must be allowed to access this tenant<br>operation must be idempotent<br>SQL must not be accepted from caller input<br>Redis command must not be accepted from caller input<br>destination URL must not be caller-controlled</pre><p>The last three are important.</p><p>If your Lambda accepts raw SQL, raw Redis commands, or any destination URL, you haven’t created a boundary. You’ve just made a tunnel using JSON.</p><p><strong>The point isn’t that Lambda is always best. The real point is that your requirements should decide which tool you use.</strong></p><h3>Final Rule</h3><p>To make this choice clear, here are the main criteria for choosing between Lambda boundary adapters and network-level connectivity:</p><p>Choose Lambda boundary adapters when:</p><ul><li>The consuming system only needs one or a few specific business operations from the private resource.</li><li>Direct protocol access (Redis, SQL, HTTP, TCP) is not required.</li><li>You want to limit the blast radius and keep resources private.</li><li>Fine-grained IAM permissions and audit trails are important.</li><li>You need to avoid sharing credentials or connection details.</li><li>Input validation and operation-specific contracts are needed at the boundary.</li></ul><p>Choose network connectivity (such as VPC Peering, Transit Gateway, PrivateLink, or Lattice) when:</p><ul><li>The consumer requires full protocol access to the resource.</li><li>Many different or complex queries are needed, especially with large or frequent payloads.</li><li>Lower latency and high throughput are necessary.</li><li>The operation time could exceed Lambda’s limits.</li><li>The pattern starts looking like generic proxying (for example, raw SQL, Redis, TCP tunneling, or HTTP proxy).</li></ul><p>Finally, the requirement should decide the tool.</p><ul><li><strong>Use networking when the other system really needs network access.</strong></li><li><strong>Use Lambda when only a controlled operation is needed.</strong></li></ul><h4>If you like this, leave a clap or tweet at <a href="https://twitter.com/BodzionyRafal">@BodzionyRafal</a> to say hello✌️</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa419d9695cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS NAT Gateway Is Boring. Until Your Video Traffic Finds It]]></title>
            <link>https://medium.com/@rafalb/aws-nat-gateway-is-boring-until-your-video-traffic-finds-it-2a45be07c438?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a45be07c438</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 07:22:40 GMT</pubDate>
            <atom:updated>2026-06-02T08:06:08.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nHK0B_iI-TFS9oD4" /><figcaption>Photo by <a href="https://unsplash.com/@thomascpark?utm_source=medium&amp;utm_medium=referral">Thomas Park</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>AWS NAT Gateway is usually the correct default.</strong></blockquote><p>It is managed, simple to deploy, and removes an operational task from the team. You create it in a public subnet, update the route table for private subnets, and private workloads can reach the internet without becoming directly exposed.</p><p>That is exactly what we want in most systems.</p><p>Nobody wakes up happy because they have to patch a Linux box whose only job is to pretend to be a router. At least I do not.</p><p>But there is one case where this very simple architecture starts to be less obvious:</p><p><strong>high-volume traffic.</strong></p><p>The thesis is simple:</p><p><strong><em>A managed service is usually the right default until the data processing bill exceeds the operational value it provides.</em></strong></p><p>This article is not about replacing NAT Gateway everywhere. That would be a bad default. It is about knowing when a NAT Gateway is still the right tool and when a self-managed NAT instance on EC2 is worth evaluating.</p><h3>The Default Problem NAT Solves</h3><p>A common AWS VPC architecture has <strong>public</strong> and <strong>private</strong> subnets.</p><p>Public subnets contain resources that can be reached from the internet, such as:</p><ul><li>Application Load Balancers,</li><li>Network Load Balancers,</li><li>bastion hosts,</li><li>public NAT devices.</li></ul><p>Private subnets contain workloads that should not be directly exposed, such as:</p><ul><li>ECS services,</li><li>EKS nodes,</li><li>EC2 workers,</li><li>batch jobs,</li><li>internal APIs,</li><li>databases,</li><li>video processing workers.</li></ul><p>The problem is simple.</p><p><strong>Private workloads often still need outbound internet access.</strong></p><p>They may need to:</p><ul><li>pull container images,</li><li>download packages,</li><li>call external APIs,</li><li>send telemetry,</li><li>connect to SaaS services,</li><li>reach partner systems,</li><li>push selected processed data outside AWS.</li></ul><p>But we still do not want those workloads to accept inbound connections from the public internet.</p><p>NAT solves this by allowing private resources to initiate outbound connections while hiding their private IP addresses behind a controlled network exit point.</p><p>A typical AWS architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mRG6vC3LyPiUvuXA.gif" /><figcaption>Network Infrastructure with VPC, IGW, NAT, and Subnet Routing by <a href="https://medium.com/@jetti.dinesh?source=post_page---byline--629269dc54b4---------------------------------------">DINESH REDDY JETTI</a></figcaption></figure><h3>Why NAT Gateway Is Usually the Right Default</h3><p>AWS NAT Gateway exists because most teams should not manage NAT themselves.</p><p>With NAT Gateway, AWS owns the network appliance. You do not manage:</p><ul><li>the operating system,</li><li>iptables or nftables,</li><li>source/destination checks,</li><li>instance type sizing,</li><li>failover scripts,</li><li>patching,</li><li>Auto Scaling Groups,</li><li>broken route table automation written by someone who left two years ago.</li></ul><p><strong>AWS also recommends NAT Gateway over NAT instances because it provides better availability and bandwidth and requires less administration from the team.</strong></p><p>For a normal backend service, NAT Gateway is a good trade-off.</p><p>For example, imagine an ECS service in private subnets that calls a few APIs, downloads some packages, sends logs, and occasionally reaches the public internet. In that case, NAT Gateway cost is usually not the main architectural problem.</p><p>The operational simplicity is more valuable.</p><p>You create one NAT Gateway per Availability Zone, route private subnets in the same AZ to the local NAT Gateway, and move on with your life.</p><p>This is the boring answer.</p><p>And boring answers are often the ones that survive production.</p><h3>Where NAT Gateway Starts to Hurt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pGr6UZ2rBiOqZ5Db.png" /><figcaption><a href="https://cloudchipr.com/blog/aws-nat-gateway-pricing">https://cloudchipr.com/blog/aws-nat-gateway-pricing</a></figcaption></figure><p><strong>The situation changes when the NAT starts processing a lot of data.</strong></p><p>NAT Gateway pricing has two important parts:</p><ul><li><strong>hourly charge</strong> for the NAT Gateway being available,</li><li><strong>data processing charge</strong> for every GB that passes through it.</li></ul><p>AWS also applies standard data transfer charges when data leaves AWS through the NAT Gateway. That means NAT Gateway is not only “a small router fee”. It can become part of the data path cost.</p><p>For small traffic, this is fine.</p><p><strong>For video workloads, it can become visible very quickly.</strong></p><p>A JSON API may send kilobytes or megabytes.</p><p>A video pipeline can move terabytes without even trying to be impressive.</p><p>And if this traffic goes through NAT Gateway, the NAT Gateway does not care that it is “just routing”.</p><p>It processes GBs.</p><p>And you pay for those GBs.</p><p>This is usually the moment when the invoice stops being a PDF and starts being a monitoring alert.</p><h3>50 TB through NAT is a simple way to increase the bills</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mqYME39NQ30QKmsj" /><figcaption>Photo by <a href="https://unsplash.com/@shutter_speed_?utm_source=medium&amp;utm_medium=referral">Shutter Speed</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now let’s use a concrete example. Assume the system runs in a European AWS region.</p><p>Assumptions:</p><ul><li><strong>3 Availability Zones</strong>,</li><li><strong>730 hours</strong> per month,</li><li><strong>50 TB per month</strong> through the NAT layer,</li><li><strong>$0.052/hour</strong> NAT Gateway price assumption,</li><li><strong>$0.052/GB</strong> NAT Gateway data processing price assumption,</li><li><strong>$0.005/hour</strong> per public IPv4 address,</li><li>Workloads are aligned with NAT resources in the same AZ,</li><li>Standard traffic data transfer out is excluded from the comparison.</li></ul><p><strong>The last point is important.</strong></p><p>If 50 TB leaves AWS to the internet, AWS data transfer out usually applies in both designs. I am comparing the <strong>NAT layer cost</strong>, not the full internet delivery bill.</p><h3>NAT Gateway per AZ</h3><p>Monthly NAT Gateway hourly cost:</p><pre>3 NAT Gateways * 730 hours * $0.052 = $113.88</pre><p>Monthly NAT Gateway data processing cost:</p><pre>51,200 GB * $0.052 = $2,662.40</pre><p>Public IPv4 cost:</p><pre>3 IPv4 addresses * 730 hours * $0.005 = $10.95</pre><p>Approximate NAT-layer cost:</p><pre>$113.88 + $2,662.40 + $10.95 = $2,787.23 / month</pre><p>That is not a catastrophic number for every business.</p><p>But it is also not nothing. It is especially not nothing when the engineering team says, “Wait, this line item is just for passing traffic through NAT?”</p><h3>NAT Instance per AZ</h3><p>Now, assume we run one NAT instance per AZ.</p><p>For example, a network-oriented EC2 family such as c6gn or c7gn, depending on region availability, throughput requirements, and real load tests.</p><p>Assume a c6gn.xlarge-like a cost model at roughly <strong>$0.173/hour</strong>.</p><p>Monthly EC2 cost:</p><pre>3 instances * 730 hours * $0.173 = $378.87</pre><p>Public IPv4 cost:</p><pre>3 IPv4 addresses * 730 hours * $0.005 = $10.95</pre><p>Add EBS, monitoring, logs, and some operational buffer:</p><pre>Estimated NAT instance infrastructure cost: ~$420–$500 / month</pre><p><strong>So the simplified comparison becomes:</strong></p><pre>NAT Gateway NAT-layer cost:      ~$2,787 / month<br>NAT EC2 NAT-layer cost:          ~$420–$500 / month<br>Difference:                      roughly $2,300 / month<br>Annualized difference:           roughly $27,000+ / year</pre><p>This is where NAT Gateway stops being “just the default route” and becomes a cost review topic.</p><p>And 50 TB per month is not a crazy number for video.</p><p>It is a normal workload, wearing a slightly heavier jacket.</p><h3>What Happens at Higher Traffic?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FzWzWKWYTIup-DjX" /><figcaption>Photo by <a href="https://unsplash.com/@omilaev?utm_source=medium&amp;utm_medium=referral">Igor Omilaev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The hourly cost stays mostly the same; however, the data processing cost does not.</p><p>Using <strong>$0.052/GB</strong> processing assumption:</p><pre>10 TB/month   -&gt;  10,240 GB * $0.052 = $532.48<br>50 TB/month   -&gt;  51,200 GB * $0.052 = $2,662.40<br>100 TB/month  -&gt; 102,400 GB * $0.052 = $5,324.80<br>200 TB/month  -&gt; 204,800 GB * $0.052 = $10,649.60</pre><p><strong>This is only NAT Gateway data processing.</strong></p><p>At 200 TB per month, the NAT Gateway processing fee alone is over <strong>$10k/month</strong>.</p><p>At that point, nobody says “it is just networking”</p><h3>But This Is Not Free Money</h3><p>It would be easy to stop here and say:</p><p><strong>“Use NAT instances. They are cheaper.”</strong></p><p>That would be incomplete.</p><p>A NAT instance changes the ownership model. With NAT Gateway, AWS owns the appliance. With NAT instance, you own the appliance.</p><p>That means you now care about:</p><ul><li>operating system patching,</li><li>AMI updates,</li><li>security hardening,</li><li>source/destination check configuration,</li><li>iptables or nftables,</li><li>kernel forwarding settings,</li><li>connection tracking limits,</li><li>instance network limits,</li><li>CPU saturation,</li><li>CloudWatch alarms,</li><li>failover,</li><li>route table updates,</li><li>Auto Scaling behavior,</li><li>testing after instance replacement.</li></ul><p>The AWS bill may go down. The operational bill goes up. And this bill is paid by engineers. Sometimes this is still a good deal.</p><p>Sometimes it is just moving the cost from the invoice to the on-call rotation, which is the cloud version of hiding dirty dishes in the oven.</p><h3>What NAT Instance Gives You Besides Cost</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qdEHbxQmSotG1aOl" /><figcaption>Photo by <a href="https://unsplash.com/@privecstasy?utm_source=medium&amp;utm_medium=referral">Privecstasy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A NAT instance is not only about cost.</p><p><strong>It also gives control.</strong></p><p>With NAT Gateway, you cannot install custom software on the NAT device. You cannot use it as a general-purpose firewall appliance. You cannot attach a security group directly to it. You cannot run custom routing logic on it.</p><p>Again, that is not a flaw.</p><p>That is the point of a managed service.</p><p>With a NAT instance, you can:</p><ul><li><strong>attach security groups,</strong></li><li><strong>add custom firewall rules,</strong></li><li><strong>run a VPN client,</strong></li><li><strong>route selected traffic differently,</strong></li><li><strong>log traffic at the OS level,</strong></li><li><strong>inspect behavior with standard Linux tools,</strong></li><li><strong>tune connection tracking,</strong></li><li><strong>build egress rules specific to your system.</strong></li></ul><p>This is useful when NAT is not just “internet access”. Sometimes NAT becomes the controlled egress point of the system.</p><p>That happens when:</p><ul><li>external services require IP allowlisting,</li><li>security wants strict outbound filtering,</li><li>traffic must go through a tunnel,</li><li>only selected destinations should be reachable,</li><li>traffic volume makes NAT Gateway processing cost too high,</li><li>OS-level logs help debugging or audit.</li></ul><h3>NAT Gateway vs NAT Instance</h3><p>Here is the practical comparison:</p><pre>AWS NAT Gateway<br>---------------<br>Ownership:        Managed by AWS<br>Maintenance:      Minimal<br>Availability:     Managed service behavior inside AZ<br>Scaling:          Managed by AWS<br>Cost model:       Hourly + per-GB processing<br>Customization:    Low<br>Best for:         Standard production outbound internet access</pre><pre>NAT Instance on EC2<br>-------------------<br>Ownership:        Managed by you<br>Maintenance:      Patching, hardening, monitoring<br>Availability:     You design failover<br>Scaling:          Depends on instance type and architecture<br>Cost model:       EC2 + EBS + IPv4 + operations<br>Customization:    High<br>Best for:         High-volume or specialized egress requirements</pre><p>The decision is not really:</p><p><strong>“NAT Gateway vs NAT instance.”</strong></p><p>The decision is:</p><pre>Managed reliability vs custom control</pre><p>That is the trade-off.</p><h3>The Biggest Mistake: Comparing Only the AWS Line Item</h3><p>The wrong comparison is:</p><pre>NAT Gateway: expensive<br>NAT instance: cheap</pre><p>The better comparison is:</p><pre>NAT Gateway:<br>managed, scalable, less operational work, per-GB processing cost</pre><pre>NAT instance:<br>cheaper at high traffic volume, more control, more operational work</pre><ul><li>A NAT instance that fails during deployment can break private workloads.</li><li>A NAT instance that runs out of conntrack entries can create strange intermittent failures.</li><li>A NAT instance that is patched manually every few months becomes another snowflake.</li><li>A NAT instance without tested failover is not cost optimization.</li></ul><p>It is an incident with a discount label.</p><p>So the real question is not:</p><p><strong>“Can EC2 be cheaper?”</strong></p><p>Of course it can.</p><p>The real question is:</p><p><strong>“Is the monthly saving large enough to justify owning this network appliance?”</strong></p><p>For 500 GB per month, probably not.</p><p>For 50 TB per month, maybe.</p><p>For 200 TB per month, it is hard not to at least evaluate.</p><h3>How I Would Review a Video Architecture</h3><p>Video systems should be reviewed differently from normal web systems. A normal API architecture often optimises for request count, latency, and compute. A video architecture must also optimise for data paths.</p><p>The checklist is simple:</p><ul><li>Where does the video enter?</li><li>Where is it stored?</li><li>Where is it processed?</li><li>Where does it leave AWS?</li><li>Does it cross Availability Zones?</li><li>Does it go through NAT?</li><li>Does it go through a VPC endpoint?</li><li>Does it go to CloudFront, S3, an external CDN, or a partner endpoint?</li><li>Is the traffic mostly inbound, outbound, internal, or cross-region?</li></ul><p>For a video ingest or streaming system, I would start with this:</p><pre>1. Keep S3 traffic away from NAT by using Gateway VPC Endpoints.<br>2. Add Interface Endpoints for AWS APIs used heavily from private subnets.<br>3. Keep NAT resources in the same AZ as private workloads.<br>4. Separate low-volume API egress from high-volume media egress.<br>5. Measure NAT Gateway bytes in CloudWatch before redesigning anything.<br>6. Compare NAT Gateway data processing cost against NAT instance operation cost.<br>7. Test NAT instance throughput under realistic bursts, not only average traffic.</pre><p>The keyword is <strong>measure</strong>.</p><p>Do not redesign NAT based on feelings.</p><p>Feelings are good for music and terrible for cloud invoices.</p><p>Use Cost Explorer, CloudWatch, VPC Flow Logs, and real traffic numbers.</p><h3>A Practical Recommendation</h3><ol><li>Start with NAT Gateway.</li><li>Then remove unnecessary traffic from NAT.</li><li>Use VPC endpoints for S3 and other AWS services where it makes sense.</li><li>After that, check what is still going through NAT.</li><li>If the remaining traffic is small, keep NAT Gateway.</li><li>If the remaining traffic is large, especially in workloads like video streaming or ingest, build a cost model.</li></ol><p>Not a theoretical one.</p><p>A simple one:</p><pre>Monthly NAT Gateway cost =<br>(number of NAT Gateways * hourly price * 730)<br>+<br>(GB processed * NAT processing price)<br>+<br>(public IPv4 cost)</pre><p>Then compare it with:</p><pre>Monthly NAT instance cost =<br>(number of NAT instances * EC2 hourly price * 730)<br>+<br>(EBS)<br>+<br>(public IPv4 cost)<br>+<br>(monitoring/logging)<br>+<br>(engineering ownership)</pre><p>The last line is the hardest one.</p><p>Engineering ownership does not show up in the AWS calculator.</p><p>But it shows up during incidents.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UEpj0_PnSmONXezn" /><figcaption>Photo by <a href="https://unsplash.com/@tingeyinjurylawfirm?utm_source=medium&amp;utm_medium=referral">Tingey Injury Law Firm</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AWS NAT Gateway is not bad.</p><p>It is probably the correct default.</p><p>Standard private subnet egress provides a managed, scalable, low-maintenance solution. That is valuable.</p><p>But high-volume systems change the equation.</p><p>In a video ingest or streaming architecture, the NAT Gateway per-GB processing charge can become much larger than the hourly fee. At tens of terabytes per month, the difference between managed NAT and EC2-based NAT can be thousands of dollars.</p><p>That does not automatically mean NAT instance is better.</p><p>It means the decision should be explicit.</p><p>NAT Gateway gives managed reliability.</p><p>NAT instance gives control and sometimes a much better cost model.</p><p>The correct question is not:</p><p><strong>“Which one is cheaper?”</strong></p><p>The correct question is:</p><p><strong>“Is the cost of managed NAT data processing still worth the simplicity it gives us?”</strong></p><p>Sometimes the answer is yes.</p><p>Sometimes, especially when video traffic starts moving through the network path, the answer deserves a second look.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a45be07c438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing Python Design Patterns for Machine Learning: A Dive Into Five Paradigms]]></title>
            <link>https://medium.com/@rafalb/harnessing-python-design-patterns-for-machine-learning-a-dive-into-five-paradigms-c696d4970a37?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/c696d4970a37</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[architecture-design]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 18:59:42 GMT</pubDate>
            <atom:updated>2023-10-05T18:59:42.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v4MgwDOlm_japKvV" /><figcaption>Photo by <a href="https://unsplash.com/@drmakete?utm_source=medium&amp;utm_medium=referral">drmakete lab</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>In machine learning</strong>, it’s essential to prioritize code readability and easy implementation to take a project to the next level. With so much data and algorithms to sift through, design patterns act as sturdy boats that help navigate inefficiencies and code redundancy, leading to a clean, organized, and robust codebase. The saying “Simplicity is the ultimate sophistication” applies to design patterns, and they can significantly benefit your ML projects. This post will explore five Python design patterns and how they can be game-changers in your Machine Learning toolkit.</p><h3>Uncovering the Factory Pattern in Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cb_pg10_Wp6rIi-SiAl4Kg.jpeg" /></figure><p>When coding, it’s essential to be adaptable to tackle various tasks. As ML practitioners, we often have to manage different algorithms, each with its settings and features. To help keep things organized and manageable, design patterns are helpful. One such pattern is the Factory Pattern, which creates objects without specifying the exact class of objects created.</p><p>The Factory Pattern is part of the creational design pattern family, which deals with object creation mechanisms. The essence of this pattern lies in providing an interface for creating objects but allowing subclasses to alter the type of objects that will be created. This adds a layer of abstraction, making the code more modular, easy to extend, and maintain.<br>In the machine learning landscape, the Factory Pattern finds its utility when we need to create objects representing different algorithms or models. It shines when there’s a need to decouple the model creation logic from the main application.</p><h4>The Enigmatic Factory Pattern Unveiled</h4><p>Let’s unveil the magic of the Factory Pattern with a Python snippet illustrating a simplistic scenario in ML:</p><pre>class ModelFactory:<br>    def create_model(model_type):<br>        if model_type == &#39;logistic_regression&#39;:<br>            return LogisticRegression()<br>        elif model_type == &#39;decision_tree&#39;:<br>            return DecisionTreeClassifier()<br>        elif model_type == &#39;svm&#39;:<br>            return SVC()<br>        else:<br>            raise ValueError(f&#39;Model type {model_type} not recognized.&#39;)<br><br>class LogisticRegression:<br>    def train(self, data):<br>        print(&quot;Training Logistic Regression on data...&quot;)<br><br>class DecisionTreeClassifier:<br>    def train(self, data):<br>        print(&quot;Training Decision Tree on data...&quot;)<br><br>class SVC:<br>    def train(self, data):<br>        print(&quot;Training SVM on data...&quot;)<br><br># Usage:<br>model_type = &#39;svm&#39;<br>model_factory = ModelFactory()<br>model = model_factory.create_model(model_type)<br>model.train(data)</pre><p>In this snippet, ModelFactory is our factory class that creates different machine-learning models based on the input model_type. This way, the code calling the factory doesn’t need to know about the specific model classes, making it more readable and extendable.</p><p>The real-life analogy of this pattern can be likened to a card factory. A card factory can produce birthdays, anniversaries, or any card you need. Similarly, our ModelFactory can generate various machine-learning models as required. The abstraction of creation logic allowed us to easily integrate new machine-learning models into our system as the project evolved.</p><h3>Bridging Gaps: The Adapter Pattern in Action in Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvwtFJMu3GN3Hk8Wro2XTQ.jpeg" /></figure><p>As a Machine Learning (ML) practitioner, it’s important to integrate different systems and libraries smoothly. In this constantly evolving field, we may encounter situations where the libraries or components we want to use don’t work with our current system. This is where the Adapter Pattern comes in — a structural design pattern that lets us use incompatible interfaces together.</p><h4>Adapting to the Inevitable: The Adapter Pattern</h4><p>The Adapter Pattern resolves the problem of incompatible interfaces by using a wrapper to translate calls from one interface to another. This pattern is handy when integrating new features or libraries with different interfaces than our system expects. For instance, let’s say we have a legacy ML system that processes data in a particular format, and we want to integrate a new analytics library that requires data in a different format. We can use the Adapter Pattern to solve the problem in this situation.</p><pre>class LegacyMLSystem:<br>    def process_data(self, data):<br>        # process data<br>        pass<br><br>class NewAnalyticsLibrary:<br>    def analyze(self, json_data):<br>        # analyze data<br>        pass<br><br>class AnalyticsAdapter:<br>    def __init__(self, analytics):<br>        self.analytics = analytics<br><br>    def process_data(self, data):<br>        json_data = convert_to_json(data)  # Assume this function converts data to JSON format<br>        self.analytics.analyze(json_data)<br><br># Usage:<br>legacy_system = LegacyMLSystem()<br>new_analytics = NewAnalyticsLibrary()<br>adapter = AnalyticsAdapter(new_analytics)<br><br>legacy_system.process_data = adapter.process_data  # Now legacy_system can use the new analytics library</pre><p>The need for advanced analytics arose amid one of my projects aimed at monitoring real-time data. The project was initially set up to process data in XML format. However, the analytics library we decided to employ was compatible only with JSON data. This scenario resonated with the common problem many developers face: integrating disparate systems.</p><p>The implementation of the Adapter Pattern paved the way for a seamless integration. We encapsulated the analytics library within an adapter, which handled the data format conversion. This minimal yet effective change facilitated the use of a robust analytics library and upheld the integrity of our existing codebase.</p><h3>Elevating Functionality: The Decorator Pattern in Machine Learning Scenarios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oflhhh5zjLQusrpK5NwNqQ.jpeg" /></figure><p>Sometimes, there is a need to enhance the capabilities of existing objects without changing their structure. That’s where the Decorator Pattern comes in, providing a flexible and reusable way to extend object functionalities.</p><h4>Layering Enhancements: Unveiling the Decorator Pattern</h4><p>Consider a data engineering project scenario with a basic data pipeline responsible for extracting, transforming, and loading (ETL) operations. Over time, the need arises to add logging, error handling, and data validation steps without disrupting the existing pipeline structure.</p><pre>class BasicPipeline:<br>    def execute(self, data):<br>        # Extract, Transform, Load<br>        pass<br><br>class PipelineDecorator:<br>    def __init__(self, pipeline):<br>        self._pipeline = pipeline<br><br>    def execute(self, data):<br>        self._pipeline.execute(data)<br><br>class LoggerDecorator(PipelineDecorator):<br>    def execute(self, data):<br>        print(&quot;Logging data flow...&quot;)<br>        super().execute(data)<br><br>class ErrorHandlerDecorator(PipelineDecorator):<br>    def execute(self, data):<br>        try:<br>            super().execute(data)<br>        except Exception as e:<br>            print(f&quot;Error: {e}&quot;)<br><br>class DataValidatorDecorator(PipelineDecorator):<br>    def execute(self, data):<br>        if data_is_valid(data):  # Assuming data_is_valid is a predefined function<br>            super().execute(data)<br>        else:<br>            print(&quot;Invalid data&quot;)<br><br># Usage:<br>basic_pipeline = BasicPipeline()<br>enhanced_pipeline = DataValidatorDecorator(ErrorHandlerDecorator(LoggerDecorator(basic_pipeline)))<br>enhanced_pipeline.execute(data)  # data is the dataset to be processed</pre><p>While I was employed at a company focused on data, we were tasked with improving our ETL pipelines to include real-time data validation, error handling, and logging. The traditional approach would have required a complete overhaul of our current classes, which would have been a lengthy process given the project’s scale.</p><p>However, after researching design patterns, I discovered we needed the Decorator Pattern solution. We created decorator classes for each new functionality, expanding our base pipeline class. This allowed us to enhance our data pipeline and modularly gradually.</p><h3>Singleton Pattern</h3><p>Singleton Pattern ensures a class has only one instance and provides a global point to this instance for the entire application. This pattern comes in handy when one wants to limit the instantiation of a class to only one object, which can be useful in situations like logging, driver objects, caching, thread pools, or database connections.</p><h4>Singleton for Model Configuration Management</h4><p>Consider an ML project where multiple models are tested simultaneously on different data partitions or modalities. There’s a need to ensure that the configuration (like learning rate, batch size, regularization terms, etc.) remains consistent for a particular model type.</p><pre>class ModelConfig:<br>    _instance = None<br>    _config = {}<br><br>    def __new__(cls):<br>        if cls._instance is None:<br>            cls._instance = super(ModelConfig, cls).__new__(cls)<br>        return cls._instance<br><br>    def set_config(self, model_name, **kwargs):<br>        self._config[model_name] = kwargs<br><br>    def get_config(self, model_name):<br>        return self._config.get(model_name, {})<br><br># Usage<br>config_manager = ModelConfig()<br>config_manager.set_config(&quot;NeuralNet&quot;, learning_rate=0.001, batch_size=32, epochs=10)<br><br># Later in the pipeline<br>model_config = ModelConfig().get_config(&quot;NeuralNet&quot;)<br>print(model_config)  # Outputs: {&#39;learning_rate&#39;: 0.001, &#39;batch_size&#39;: 32, &#39;epochs&#39;: 10}</pre><p>Adopting the Singleton Pattern for model configuration management, we ensured that once a configuration for a specific model was set, it remained consistent across all instances and usages. This approach centralized our hyperparameter management, reduced conflicts, and provided a consistent set of parameters for each model.</p><h3>Template Pattern in Machine Learning Pipelines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6w9ghSaaZILMd_Uf" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When orchestrating machine learning workflows, often there’s a defined sequence of steps to build a model — data preprocessing, model training, evaluation, and finally, model deployment. Even though the sequence is standard, the specific implementation details of each step might differ based on the data type or the model being used. This is where the Template Method Pattern shines, defining the skeleton of the algorithm in the superclass but allowing subclasses to override specific steps.</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br><br>class BaseModel:<br>    def pipeline(self, data, labels):<br>        data = self.preprocess(data)<br>        train_data, test_data, train_labels, test_labels = self.split(data, labels)<br>        model = self.train(train_data, train_labels)<br>        self.evaluate(model, test_data, test_labels)<br><br>    def preprocess(self, data):<br>        raise NotImplementedError<br><br>    def split(self, data, labels):<br>        return train_test_split(data, labels, test_size=0.2)<br><br>    def train(self, data, labels):<br>        raise NotImplementedError<br><br>    def evaluate(self, model, data, labels):<br>        predictions = model.predict(data)<br>        accuracy = accuracy_score(labels, predictions)<br>        print(f&quot;Model Accuracy: {accuracy:.2f}&quot;)<br><br>class SVMModel(BaseModel):<br>    def preprocess(self, data):<br>        # Implement SVM-specific preprocessing<br>        pass<br><br>    def train(self, data, labels):<br>        # Implement SVM training<br>        pass<br><br>class RandomForestModel(BaseModel):<br>    def preprocess(self, data):<br>        # Implement Random Forest-specific preprocessing<br>        pass<br>    <br>    def train(self, data, labels):<br>        # Implement Random Forest training<br>        pass<br><br># Usage<br>svm = SVMModel()<br>svm.pipeline(data, labels)<br><br>rf = RandomForestModel()<br>rf.pipeline(data, labels)</pre><p>While working on a project which involved testing various ML models on genomics data, each model had to undergo a set sequence of steps but demanded unique processing and training methods due to the nuances in the data and algorithm requirements. The Template Method Pattern emerged as a saviour.</p><p>By defining a base template for the ML workflow and allowing each model to inherit from this, implementing their specific details, we maintained a coherent structure while allowing flexibility. This not only organized the code, making it easier to understand, but also facilitated a plug-and-play style of adding new models into our experimentation framework, thereby saving development time and enhancing team productivity.</p><h3>Unveiling a Symphony of Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lyzt-GqtLDomnTfR" /><figcaption>Photo by <a href="https://unsplash.com/@gwundrig?utm_source=medium&amp;utm_medium=referral">Manuel Nägeli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Navigating the complex machine learning (ML) world, our exploration into Python design patterns has paved a path towards code simplicity, maintainability, and elegant structuring amid algorithmic complexity. The <strong>Factory</strong>, <strong>Adapter</strong>, <strong>Decorator</strong>, <strong>Singleton</strong>, and <strong>Template Method</strong> patterns each offer a unique lens, ensuring our ML projects are robust and scalable and gracefully adapted to the evolving demands of technology. May this foray into design patterns light the way towards a more streamlined and effective approach in your future ML adventures.</p><h4>If you like this, leave a clap or tweet at <a href="https://twitter.com/BodzionyRafal">@BodzionyRafal</a> to say hello✌️</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c696d4970a37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Tools to Add to Your Machine Learning Project Before Shipping to Production]]></title>
            <link>https://medium.com/@rafalb/4-tools-to-add-to-your-machine-learning-project-before-shipping-to-production-c9bc9f6582bb?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9bc9f6582bb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 19:17:13 GMT</pubDate>
            <atom:updated>2023-09-22T06:28:52.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhZKSu7c4XNX7xWwaMmDjA.png" /></figure><p>Machine Learning has witnessed a dramatic rise in recent years. As businesses tap into the power of ML, there&#39;s an increasing emphasis on the importance of production-ready software. From seamless scalability to debugging capabilities, the production environment demands more than an accurate model.</p><p>This article delves into <strong>four tools and techniques</strong> to upgrade your ML project, ensuring it&#39;s ready for production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0DFxiMJdLvEvisqj" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Dockerizing Your Machine Learning Pipeline</h3><p><a href="https://www.docker.com/">Docker</a> provides a platform to package your ML project with all its dependencies into a container. This containerization ensures that the software runs uniformly across different environments.</p><h4>Why use Docker?</h4><ul><li><strong>Consistency</strong>: Your project will work in production as it does in your development setup.</li><li><strong>Isolation</strong>: Dependencies of different projects are kept separate.</li><li><strong>Scalability</strong>: Containers can be easily replicated across multiple servers.</li></ul><h4>Challenges &amp; Tradeoffs:</h4><p>Balancing image size with functionality is critical. Larger images take longer to download and deploy but might have the necessary tools or libraries. There&#39;s a continuous need to strike a balance between minimalism and functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oS0rHLO0G6ng7sOrKjDqwQ.gif" /></figure><h3>Queues, Threading, Multiprocessing, and Async Operations</h3><p>Concurrent programming, a concept in which multiple tasks run simultaneously, is indispensable when building efficient software, especially with Machine Learning. Python offers several built-in libraries to help with concurrent programming, such as <em>threading</em>, <em>multiprocessing</em>, and <em>asyncio</em>. Each has advantages and tradeoffs, which we&#39;ll explore in this section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26b25cb5cd65623f031560eca6435cfa/href">https://medium.com/media/26b25cb5cd65623f031560eca6435cfa/href</a></iframe><h4>Why use them?</h4><ul><li><strong>Performance</strong>: Exploit the full power of your hardware with multiprocessing.</li><li><strong>Responsiveness</strong>: Ensure the application remains responsive even during CPU or I/O-bound operations using threading and async functions.</li><li><strong>Flexibility</strong>: Since Python provides these libraries out-of-the-box, they can be easily integrated into any program, enhancing its concurrency capabilities.</li><li><strong>Cleaner Code</strong>: Async programming allows for more readable code, especially when dealing with multiple I/O-bound operations.</li></ul><h4>Challenges &amp; Tradeoffs:</h4><p>Concurrency introduces complexity, whether via threads, processes, or async operations. Issues like deadlocks, race conditions, or resource contention are potential pitfalls. Balancing between these methods, understanding their strengths and limitations, and choosing the right tool for the task is vital.</p><p>In conclusion, whether it&#39;s handling data concurrently with queues, speeding up CPU-bound tasks with multiprocessing, or ensuring responsiveness with async, Python offers a rich set of tools for concurrent programming. Understanding and leveraging these tools effectively can significantly elevate the efficiency of your ML projects.</p><h3>Monitoring and Logging</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*yBWwhWtbj-x6FM6m.gif" /><figcaption><a href="https://grafana.com/products/cloud/logs/">Grafana dashboard</a></figcaption></figure><p>Monitoring and logging are critical components of deploying machine learning projects in production. They ensure the system&#39;s smooth operation, provide insights into its performance, and enable fast detection and resolution of issues.</p><h4>Why use these methods?</h4><ul><li><strong>Transparency &amp; Accountability</strong>: Logging offers insights into the internal workings of a system. It helps identify what happened when it happened, and in what sequence.</li><li><strong>Problem Detection &amp; Debugging</strong>: Issues can be detected and addressed faster through monitoring and logging. If a model starts performing poorly or an API begins to slow down, these tools provide the necessary information to diagnose and fix the problem.</li><li><strong>Performance Insights</strong>: Monitoring tools can provide real-time statistics on system health, such as memory usage, CPU utilization, and network bandwidth. This can guide scaling and optimization decisions.</li><li><strong>Model Management</strong>: A model registry ensures that every model version is tracked. This aids in model reproducibility, simplifies rollback to previous versions if needed, and provides a clear history of model performance over time.</li></ul><h3>Mike Driscoll on Twitter: &quot;Logging in #Python is a popular topic and it&#39;s a really useful one to understand.Today we are going to learn more about that!🧵🐍👇 / Twitter&quot;</h3><p>Logging in #Python is a popular topic and it&#39;s a really useful one to understand.Today we are going to learn more about that!🧵🐍👇</p><h4>Challenges &amp; Tradeoffs:</h4><ul><li><strong>Volume</strong>: High-traffic systems can produce a vast amount of logs. Managing, storing, and sifting through these logs to find relevant information can be daunting.</li><li><strong>Complexity</strong>: Setting up monitoring and alert systems requires initial effort. Deciding on the granularity of logs or metrics also adds to the complexity.</li><li><strong>Performance Overhead</strong>: While minimal, logging and monitoring can introduce overhead, affecting system performance.</li><li><strong>Data Sensitivity</strong>: Logging too much information can lead to data privacy issues, especially if sensitive or personal data is inadvertently stored.</li></ul><h4>Examples:</h4><ul><li><strong>Standard Python Logging</strong>: A built-in module in Python, it provides flexible logging of messages to different outputs.</li><li><strong>Loguru</strong>: A third-party Python library that offers a more accessible and more intuitive logging setup.</li><li><strong>AWS CloudWatch</strong>: A monitoring and observability service built for DevOps engineers, developers, and IT managers. It provides data and actionable insights for monitoring applications, understanding performance bottlenecks, and optimizing resource utilization.</li><li><strong>Grafana</strong>: An open-source platform for monitoring and observability. It integrates with various data sources, including CloudWatch, and provides a customizable dashboard to visualize metrics.</li><li><strong>MLflow</strong>: An open-source platform to manage the ML lifecycle, including experimentation, reproducibility, and deployment. It also includes a model registry to manage and track models across their lifecycle.</li><li><strong>S3 for Model Registry</strong>: Amazon S3 can be used as a storage backend for a model registry. It offers scalability, data availability, security, and performance.</li></ul><h3>Harnessing the Power of Optimization in Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLFDmHBhc_Q_9d8Q07qwXA.png" /><figcaption><a href="https://developer.nvidia.com/tensorrt">TensorRT Engine</a></figcaption></figure><p>Optimization plays a crucial role in fine-tuning machine learning projects. From computational speedups to refining deployment procedures, optimization tools and methods ensure that projects work and excel in real-world scenarios. This section delves into three tools: Numba for Just-In-Time Compilation, Scikit-learn for seamless data pipelines, and TensorRT for deep learning model optimization.</p><h4>Numba JIT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZW0VSJLtvj8xcBi-RFtfLQ.gif" /></figure><p>Numba is an open-source JIT compiler that translates a subset of Python and NumPy code into fast machine code.</p><h4>Why use Numba?</h4><ul><li><strong>Performance Boost</strong>: It can accelerate Python functions to performance comparable to C or FORTRAN.</li><li><strong>Easy Integration</strong>: By simply adding a decorator to your Python function.</li></ul><h4>Challenges &amp; Tradeoffs:</h4><ul><li><strong>Limited Scope</strong>: Not all Python features are supported.</li><li><strong>Initial Compilation Overhead</strong>: The first time a JIT-compiled function is called, it may introduce a slight delay.</li></ul><h4>Scikit-learn Pipelines</h4><p>Scikit-learn&#39;s Pipeline class ensures the sequential application of transformers and a final estimator, ensuring the workflow&#39;s consistency and reproducibility.</p><h4>Why use Scikit-learn Pipelines?</h4><ul><li><strong>Workflow Simplification</strong>: Combines multiple steps into a single cohesive process.</li><li><strong>Avoid Leakage</strong>: Guarantees that data transformations in training are identically applied to validation/testing.</li></ul><p><strong>Challenges &amp; Tradeoffs:</strong></p><ul><li><strong>Complexity</strong>: The initial setup might be intricate, especially with custom transformers.</li><li><strong>Performance Overhead</strong>: Some redundant operations might introduce inefficiencies if not structured correctly.</li></ul><h4>TensorRT and Model Quantization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbNey1wd_OktI0W6odf65w.png" /><figcaption><a href="https://developer.nvidia.com/blog/accelerating-quantized-networks-with-qat-toolkit-and-tensorrt/"><em>Latency performance evaluation on various models in the ResNet and EfficientNet families</em></a></figcaption></figure><p>TensorRT is a high-performance deep learning inference optimizer and runtime. It comes equipped with support for quantization, allowing models to be converted to reduced precision (like FP16 or INT8).</p><h4>Why use TensorRT and Quantization?</h4><ul><li><strong>Improved Inference Speed</strong>: Quantized models run faster and consume less memory.</li><li><strong>Reduced Model Size</strong>: This is especially advantageous for deployment on edge devices with limited storage.</li></ul><h4>Challenges &amp; Tradeoffs:</h4><ul><li><strong>Accuracy Degradation</strong>: A minor compromise in model precision might be observed.</li><li><strong>Compatibility</strong>: Not all model layers or architectures might be harmonious with all quantization techniques.</li></ul><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kevwM2FM9P8_j0U6" /><figcaption>Photo by <a href="https://unsplash.com/@whileimout?utm_source=medium&amp;utm_medium=referral">Gabe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the rapidly advancing realm of machine learning, ensuring projects are production-ready is paramount. The fusion of Docker’s consistency, Python’s concurrency capabilities, detailed insights from monitoring and logging solutions like Grafana and Loguru, and the performance enhancement from optimization tools like Numba and TensorRT underlines the importance of a holistic approach to ML deployments. These aren’t mere add-ons but the bedrock of a robust ML solution. Embracing these tools equips developers to craft accurate, efficient, and scalable machine-learning projects primed for real-world challenges.</p><h4>If you like this, leave a clap or tweet at <a href="https://twitter.com/BodzionyRafal">@BodzionyRafal</a> to say hello✌️</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9bc9f6582bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Journey Through Machine Learning: From Ideation to Deployment and Beyond]]></title>
            <link>https://medium.com/@rafalb/journey-through-machine-learning-from-ideation-to-deployment-and-beyond-be224e545319?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/be224e545319</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 09:25:02 GMT</pubDate>
            <atom:updated>2023-09-19T09:25:02.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UhrGXjxRt3gEE1lz" /><figcaption>Photo by <a href="https://unsplash.com/@heyerlein?utm_source=medium&amp;utm_medium=referral">h heyerlein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Machine learning projects are an adventure filled with possibilities and complexities. Whether you’re stepping in as an industry expert or an emerging engineer, this guide will demystify the process.</p><h4>Aligning with Business Goals</h4><p>Machine learning is more than a mere technical exercise. It’s a bridge between algorithmic challenges and overarching business goals. While algorithms are the heartbeat, understanding the business pulse is key. Whether you prioritize performance enhancement or accuracy, keep in mind the evolving nature of data and the inevitable need for model tweaks and maintenance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7ggk8UQeBgFQLxAT" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Preprocessing &amp; Exploring Data</h4><p><em>“Knowledge of the domain is like a compass in the vast sea of data.</em>”<br>Consider this: a profound grasp of customer habits can redefine data interpretation in marketing. It’s essential to embark with a well-chosen data subset, ensuring quicker, relevant insights. Regular conversations with team members about the data can unveil fresh perspectives. It’s best to commence with simple data explorations, refining them based on discoveries.</p><h4>Splitting &amp; Validating Data</h4><p>Ensuring consistent data is foundational. It lays a steady ground when experimenting with various algorithms. Interestingly, even simple techniques like decision trees can offer invaluable insights into crucial data aspects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z95jLrn2xAnR6vBM" /><figcaption>Photo by <a href="https://unsplash.com/@roonz_nl?utm_source=medium&amp;utm_medium=referral">RoonZ nl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Training &amp; Optimizing Model</strong></h4><p>Begin with basics. Initial trials with sample data can offer foundational insights. For more structured dilemmas, AutoML can be a game-changer. Sometimes, elementary algorithms like trees can be eye-openers, shedding light on areas like feature importance. Monitor, use checkpoints, and start with tried-and-tested setups. Gradually, as familiarity grows, refine and optimize for heightened efficiency.</p><h4>Evaluating &amp; Interpreting Model</h4><p>Deployment is a milestone, not the endpoint. Think of your model as a cog in a vast machinery. Whether it churns out raw predictions, works in real-time, or opts for cloud solutions, every decision should be tailored to your unique needs. Establish defined protocols, from monitoring to error handling. Design with adaptability at the forefront, ensuring future model tweaks or replacements are hassle-free.</p><h4>Going Live and Monitoring</h4><p>Deploying an ML model goes beyond mere activation; it integrates within a broader system. Define the model’s role: does it give raw predictions or need post-processing? Decide if it should operate in real-time or in batches. Choose between cloud or on-premise solutions as per your requirements. Pinpoint critical metrics for monitoring performance and establish protocols for error logging. Set maxima, highlighting latency expectations and max request capacities. Plan with adaptability in mind, facilitating effortless model updates. Recognizing the overarching system ensures your model performs seamlessly and aligns with adjacent components.</p><p>Every model deployment signals a new chapter, not the end of the story. ML models demand continuous nurturing with changing data landscapes, evolving hardware, and updated components. The launch is just the overture to a symphony of refinement and evolution. Stay committed, stay curious, and let your model evolve, for therein lies the heart of innovation.</p><h4>If you like this, leave a clap or tweet at <a href="https://twitter.com/BodzionyRafal">@BodzionyRafal</a> to say hello✌️</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be224e545319" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Succeed in Machine Learning Freelancing Industry]]></title>
            <link>https://medium.com/@rafalb/succeed-in-machine-learning-freelancing-industry-8f6a12537796?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f6a12537796</guid>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[bussiness]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Sat, 04 Jun 2022 06:53:45 GMT</pubDate>
            <atom:updated>2022-06-04T06:53:45.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9mKbNapTWglFQHA9" /><figcaption>Photo by <a href="https://unsplash.com/@instagramfotografin?utm_source=medium&amp;utm_medium=referral">Peggy Anke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Machine Learning has been growing enormously over the past few years. The fast-growing industry causes new ways to jump in and be independent. Building a startup, being a consultant, a freelancer, or a buzzy digital nomad <em>is at your fingertips</em> advertisements scream everywhere. Although it is possible to grow up within this massive environment, it is hard enough to enter correctly and don’t get frustrated at the beginning.</p><p>We can read enormous numbers from <a href="https://www.upwork.com/research/freelance-forward-2021">Upwork 2021 report</a> about freelancer skills, growing insights, flexibility and freedom. For example, when writing this blog post, I have found over <strong>5 500</strong> work proposals in Machine Learning related categories (data analysis, ETL, machine learning, ai, data mining, etc.) on Upwork.</p><p>Of course, I have also found many people identifying as machine learning engineers with an hourly rate from 10$ to 300$. However, those people already have a portfolio, satisfied clients, and most importantly, knowledge of succeeding in the industry.</p><p>Quite hard, isn’t it?</p><p>Probably, You can be discouraged by the hourly rate, the number of people, and job posts, but if you are still here, I assume you are thinking about a freelancing machine learning job and searching to boost your chance for success. Here are <strong>my best five tips to optimize your start as a freelancer in the machine learning industry.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ffo7URGO8QtGPToGZrk%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Ffo7URGO8QtGPToGZrk%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Ffo7URGO8QtGPToGZrk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="181" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc8bab736f8f988421472004dd5d54c1/href">https://medium.com/media/bc8bab736f8f988421472004dd5d54c1/href</a></iframe><h4>The story has begun</h4><p>You probably wonder why I advise you on freelancing in machine learning and are those recommendations practical? Well, it just happened in 2020 when I wanted to get my hands dirty. So I read a few articles about getting started, signed in on a freelancing website, and filled out my profile as an article said and</p><p><strong><em>I was shocked….</em></strong></p><p>I have seen hundreds of work offers and dozens of proposals from other freelancers for jobs that I found interesting. Unfortunately, what I have seen were only low salaries and high expectations. I will never forget a live interview with one of my first clients. I recognized it as my first success, of course, totally free.</p><p>However, I gave myself 100 days to check if freelancing was for me and kept trying till the first confirmed contract. As a result, today, freelancing is not my main job (and that was the initial assumption). Nevertheless, I have completed over 20 works for around $ 3,500, met people from all over the world, learned a lot about anomaly detection and computer vision, built a portfolio, and increased my independence.</p><p>I did all this by following simple rules that led me to my initial goal.</p><h4>Be best in specific domains</h4><p>I assume that you already have more/less experience in the data industry. If so, list the <em>hotspots</em> where you used machine learning and those you would like to start. <strong>Be as precise as possible</strong>, and please don’t lie even if you think you can accomplish tough topics (9/10 times, you can’t). It is the easiest way to lose your opinion in a short time.</p><p>If you have already built your domains of interest, you will be able to select offers faster. Moreover, you already have experience and probably well-established work patterns, which would translate into efficiency and effectiveness.</p><p>A specific domain will translate into another point in these rules</p><h4><strong>Templating everywhere</strong></h4><p>The template is nothing more than an offer you will submit if you find an exciting job. <strong>Try to stand out from other candidates</strong>. If you can’t show off with experience, you have to make up for it with <strong>marketing</strong>. I have managed to use four golden rules that allowed me to stand out from the crowd and attract my future clients:</p><ul><li>Offer a free consultation before starting.</li><li>Provide information that you are new and write that you are ready to offer a discount on the job.</li><li>If you have a computing server or a powerful computer, write about this!</li><li>Give an example of solutions related to the offer that can be used.</li></ul><p>If the above advice does not tell you too much, I present one answer to a job offer related to computer vision and object detection.</p><blockquote>Hello,</blockquote><blockquote>I see that you need some help with some kind of CV algorithm. I can help with that and can start right away!<strong> </strong>I have had experience with TensorFlow, OpenCV, Image recognition, detection and segmentation.</blockquote><blockquote>I have done a project where the primary purpose was to recognize the flow of the object. Currently, I have been working in a company strongly related to computer vision. We have been using Tensorflow Object Detection API, MMDetection, and many architectures like Yolo, RCNN, and Unet.</blockquote><blockquote><strong>&lt;Proposition of components&gt;</strong></blockquote><blockquote>I have found that fast one stage architecture like YOLO or SSD for electronics components inspection would be feasible. If inference runs on the edge, it will be good to implement it with Deepstream to have near real-time information. I have also found two electronics component image datasets with an open licence. I can also make a thoroughly tagging pipeline if it is needed.</blockquote><blockquote><strong>&lt;….&gt;</strong></blockquote><blockquote><strong>I have my own server with an A6000 48Gb GPU card, so model training, validating and optimizing are included in the proposed terms.</strong></blockquote><blockquote><strong>I usually start work during the interview process, you can send me the documents, and I will look at them as soon as possible</strong>.<strong> Then, if the results are satisfying, we might discuss hiring and paid hours. If the above offer sounds like something you would be interested in, I would love to hear from you.</strong></blockquote><blockquote><strong>I am new to Upwork and looking to get a few clients that I can build upon. So if you look at my work and feel that I could help you, I’ll do it for a 10% discount (included in the bid).</strong></blockquote><blockquote>Kinds regards, Rafal</blockquote><p>Doesn’t that look appealing?</p><p><strong>Yes</strong></p><p>Because the client receives a <strong>free consultation</strong>, information about the <strong>discount</strong> and confirmation that you have the appropriate <strong>hardware</strong>. Additionally, several <strong>suggestions</strong> for solving the problem. I copy bolded text every time I want to post a proposal. It took me <strong>5 minutes</strong> to write this message from the template. Feel free to copy and modify it based on your experience.</p><p><em>Of course, attaching excellent infographics to prove your skills would boost you, but this template method with four rules gave me around a 3/10 response rate at the beginning.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FKCqjrcPfL55q3MkgHZ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FKCqjrcPfL55q3MkgHZ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FKCqjrcPfL55q3MkgHZ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e53fb37c365cea9412305c8cb646b93/href">https://medium.com/media/8e53fb37c365cea9412305c8cb646b93/href</a></iframe><h4>Little step ahead, one proposal a day</h4><p>You still don’t know how to succeed, am I right? So, Try to spend a moment every day discovering a new job offer and sending your templated proposal.</p><p><strong>That’s it. That’s enough.</strong></p><p>If you assume a success rate of 1% at the beginning of your journey, you may get your first paid job after 100 days. <strong>You are probably better than average if you get your first job faster</strong>! You can only be glad that your goal was achieved much quicker.</p><h4>Customer Retention is better than Customer Acquisition</h4><p>Memorize this sentence and follow it in your relations with clients. Remember that you are responsible for the entire process as a freelancer, from consultation to implementation and proposing new system versions.</p><p>For example, if the client needs to prove a hypothesis, suggest an attractive alternative solution in the next step. Do you know how to implement the model in the cloud? Cool! Indicate you can implement the model, continuous development, and monitoring.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRIWR3fxTcLys7jnKSW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRIWR3fxTcLys7jnKSW%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FRIWR3fxTcLys7jnKSW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/f77a94667178da2914dade5d1c5f8f91/href">https://medium.com/media/f77a94667178da2914dade5d1c5f8f91/href</a></iframe><p>Keep in mind how long it took you to find a contract and how long it will take to write a proposal for the following phases for a regular client. Also, remember that getting into a new project can be as time-consuming as completing the next steps of a project you know.</p><p>Personally, this is how I have been maintaining relationships with three clients, proposing something completely new that could work.</p><p><strong>If your customers make money, you make money too!</strong></p><h4>Summary</h4><p>Keep those simple rules until you meet 100 days deadline, and you will see how easy it is to reach your first, second and subsequent clients. Remember to update your profile, optimize the above template and develop new freelancing soft skills.</p><p>It would make you even better in your daily job to understand customers, get a true business value and build the portfolio.</p><p>Thank you for reading to the end of this article! We can see that simple steps can help you jump into the freelancing world. Do not give up. Keep trying and expand your knowledge.</p><h4>If you like this, leave a clap or tweet at <a href="https://twitter.com/BodzionyRafal">@BodzionyRafal</a> to say hello✌️</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f6a12537796" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning with SageMaker (or AWS): Build-in Services part 2]]></title>
            <link>https://medium.com/@rafalb/machine-learning-with-sagemaker-or-aws-build-in-services-part-2-4b6fbad01edc?source=rss-9364fa570430------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b6fbad01edc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Rafał Bodziony]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 19:33:51 GMT</pubDate>
            <atom:updated>2022-02-03T19:33:51.153Z</atom:updated>
            <content:encoded><![CDATA[<p>The truth is Machine Learning has mastered the world, and big companies like AWS never sleep. It was unusual to build an object detector or text recognizer as a service a few years ago. It was a domain of increased volume of AI startups, which, to be honest — cost a lot and usually work only in presentations…</p><p>Nowadays, we have multiple options to decompose the AI part of the project and prototype comfortably within complete black-box services, open-source projects, or even writing programs from scratch. But, most importantly, AWS Services give us the possibility to make it (without faking it).</p><h3>AWS Machine Learning</h3><p>Okay, I&#39;d wanted to post about AWS SageMaker build-in services and marketplace possibilities. But, I was amazed by the amount of content when I looked through the Machine Learning services listed on the main console page. So, that&#39;s why today&#39;s article will be about a large group of ready-to-use Machine Learning services from AWS. These could be used to check the hypothesis quickly, create POC for the client or manager, or make a fancy AI startup…</p><p>AWS offers over <strong>20 AI/ML services</strong> to analyze images, text, or time series, do speech recognition or get hands-on with a fully autonomous car race. Below I have explained a few of them.</p><p><a href="https://aws.amazon.com/codeguru/"><strong>CodeGuru</strong></a><strong> </strong>— Provides intelligent recommendations for improving application performance, efficiency, and code quality in your Java and Python applications. It has a profiler and reviewer to visualize applications performances and evaluate code against best practices.</p><p><a href="https://aws.amazon.com/comprehend/"><strong>Amazon Comprehend</strong></a><strong> </strong>— Natural language processing service finding insight and relationships in the text. It can discover entities and key phrases, detect language, predict sentiment, and more. The service currently supports 12 languages, from German to Chinese.</p><p><a href="https://aws.amazon.com/forecast/"><strong>Amazon Forecast</strong></a><strong> — </strong>Fully automated time-series forecasting service based on Machine Learning. Any business can use it for product demand forecasting, supply chain management, etc. It combines multiple state-of-the-art algorithms with auto ML to produce better results.</p><p><a href="https://aws.amazon.com/fraud-detector/"><strong>Amazon Fraud Detector</strong></a><strong> — </strong>Fully managed service which enables to classify suspicious activities based on data. The good news is we can use a free tier for up to 30,000 fraud predictions per month!</p><p><a href="https://aws.amazon.com/rekognition/"><strong>Amazon</strong></a><strong> </strong><a href="https://aws.amazon.com/rekognition/"><strong>Rekognition</strong></a><strong> — </strong>Computer vision service which can extract insights and information from images and videos. From content moderation, face search to text detection and PPE.</p><p><strong>And many more are listed on the </strong><a href="https://aws.amazon.com/machine-learning/"><strong>AWS website</strong></a><strong>…</strong></p><h3>Let&#39;s prototype something…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*eTDQ3PpsINOoVGZ5" /></figure><p>Suppose we have a client who wants to have a workspace safety application. They have turnstiles with some optical systems in a critical place in the company, but they are not good at recognizing personal protective equipment.</p><p>They want to enhance the system with Deep Learning to recognize helmets, masks and gloves. Also, they want to have alerts and recognition near real-time with some analysis at the end of each week. Finally, our team proposes a cloud-based solution to connect turnstiles with AWS services.</p><p>Of course, as Machine Learning engineers, we are responsible for the PPE recognition demo. After some research, we have found a ready-to-use solution named AWS Rekognition. After a while, we prepared the base architecture for the entire pipeline, and so luckily, it was accepted!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*nqaYcSpKllpvM0rssnYudw.png" /><figcaption>AWS architecture generating with Cloudcraft</figcaption></figure><p>How good would an architecture be without an estimated cost? <a href="https://www.cloudcraft.co/">Cloudcraft</a> gives us this possibility! We can generate diagrams (as above) and estimate costs similar to AWS calculators. Therefore, the estimated cost for this model would be around <strong>~70$ per month</strong>. The price includes 250 Gb S3 storage, Lambda, DynamoDB, SNS and <strong>50,000</strong> Rekognition requests (not bad for MVP)</p><p>We will be using python AWS CDK and the GitHub repository forked from the <a href="https://github.com/aws-samples/aws-cdk-examples/tree/master/python/rekognition-lambda-s3-trigger">aws public repo</a> to build this service. I have added additional code for PPE, and different dynamo DB table indexes.</p><h3>CDK is all you need</h3><p>To prepare the environment and aws cloud stack, we will be using <a href="https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html">AWS CDK</a> python bindings. The complete code is available on my <a href="https://github.com/g0lemXIV/medium-articles/tree/master/aws_part2">GitHub</a>. We assumed that developers would integrate the client system and S3. Also, they can use Dynamo DB information. So our role is to create a stack with Lambda, Recognition API and DynamoDB.</p><p>We want to define five operations with our cloud formation stack:</p><ul><li>Create IAM permission</li><li>Make a bucket where we can upload images</li><li>Build a DynamoDB table with proper indexes</li><li>Build a Lambda function that processes events</li><li>Attach notification to create Lambda functions when any object image arrives</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39cbba68c52aae6494756c8b077f3ea5/href">https://medium.com/media/39cbba68c52aae6494756c8b077f3ea5/href</a></iframe><p>Next, we need to develop a Lambda handler, which would be responsible for data transition from images to JSON and DynamoDB Items. But, those operations could be packed into one function because we operate on one image per call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a68ea9d38c33a56f2d1579f8535c111d/href">https://medium.com/media/a68ea9d38c33a56f2d1579f8535c111d/href</a></iframe><p>Someone may ask:</p><p><em>&quot;Why do you use only one detection and this kind of index?&quot;</em></p><p>And we can respond:</p><p><em>&quot;Because we want to be sure only the person in the queue will be detected before entering. Also, we want to have a reasonable query index to fast filter time and images where people don&#39;t have masks, helmets or gloves.&quot;</em></p><p>This type of indexing technique can achieve high availability for any query. For example, If we are interested in images from a given period where people don&#39;t have helmets, we can query HEAD#0 &amp; timestamp between given periods . That&#39;s it, and it is as simple as that!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*FXqjpk6OGwv4vMHFvBRduQ.gif" /><figcaption>Demo pipeline</figcaption></figure><h3>Summary</h3><p>Finally, the manager was delighted with this MVP, and we got a raise 👻. It also should be noted that we spent a day or two making this, but this recognition is due to the fantastic AWS community, developers and services!</p><p>The next step is to transform the in-service model into a custom one with a sagemaker (because it generates 70% of the costs). This is work for the future. Most important is establishing a full stack with Python code, an entirely scaleable and reusable solution.</p><p>Thank you for reading to the end of this article! We can see that AWS can help design MVP with well-architected and scalable services, which wouldn&#39;t shame any AI fancy startups.</p><h4>If you like this, leave a clap or tweet at <a href="https://twitter.com/BodzionyRafal">@BodzionyRafal</a> to say hello✌️</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b6fbad01edc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>