<?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 Miko on Medium]]></title>
        <description><![CDATA[Stories by Miko on Medium]]></description>
        <link>https://medium.com/@mikovilla?source=rss-82b370999035------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a76FQ2_fq5r8rdOF3pk_Pg.jpeg</url>
            <title>Stories by Miko on Medium</title>
            <link>https://medium.com/@mikovilla?source=rss-82b370999035------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 23:03:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikovilla/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[Nine Ways to Find a Lung, and the One Question That Breaks Most of Them]]></title>
            <link>https://mikovilla.medium.com/nine-ways-to-find-a-lung-and-the-one-question-that-breaks-most-of-them-9e99a27a3d12?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e99a27a3d12</guid>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 17:40:25 GMT</pubDate>
            <atom:updated>2026-10-03T17:41:38.211Z</atom:updated>
            <content:encoded><![CDATA[<p>A box drawn around a lung and a lung’s actual outline are not the same problem, even though they sound like one. On our test set, a plain convolutional detector finds both lungs with a mean IoU of 0.948; ask a classical segmentation method to trace the boundary pixel by pixel instead, under the same conditions, and the best of nine approaches reaches a Dice score of 0.617. That gap, more than anything comparing hand-crafted rules to learned models, is what this project ended up being about.</p><h3>The setup</h3><p>We built the comparison on two public tuberculosis-screening collections from the U.S. National Library of Medicine: 138 radiographs from Montgomery County, Maryland, and 566 from Shenzhen, each paired with a hand-annotated lung mask, 704 images in total, split 70/15/15 and stratified by source, and packaged together on Kaggle as the <a href="https://www.kaggle.com/datasets/nikhilpandey360/chest-xray-masks-and-labels">Chest X-ray Masks and Labels</a> dataset. The two sources don’t even share a resolution range; Montgomery originals average roughly 4300×4600 pixels against Shenzhen’s 2700×2800, so every image is letterboxed onto a common 512×512 canvas before anything else happens to it, followed by denoising, CLAHE, and normalization, in that order. Denoising has to come first, since CLAHE is a local-contrast operation that would otherwise amplify whatever noise survived into it.</p><p>Against that pipeline we ran nine classical segmentation methods: Otsu and adaptive thresholding, Canny edge detection, region growing, K-means and a Gaussian mixture model, watershed, a graph-based method (Felzenszwalb), and template matching, none of them tuned against ground truth beyond a first inspection pass. Alongside them, two detectors: a convolutional network (YOLO26n, fine-tuned from a COCO checkpoint) and a much simpler PCA-plus-linear-SVM pipeline that projects 152×330 pixel patches onto 50 principal components before a linear classifier sorts them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2on2yxi__PyWLrog-CjFA.png" /><figcaption><em>The eight leading principal components learned from training patches, informally called the “eigenlungs,” visibly encode lung-shaped contrast rather than arbitrary texture.</em></figcaption></figure><h3>Breaking the images on purpose</h3><p>Every method above is scored once on clean images, and again on 20 degraded conditions, because “how good is this method” and “how good is this method once the film is underexposed” are different questions and deserve different answers.</p><p>The degradations enter at two separate points, which turns out to matter more than which degradation you pick. One track degrades the raw image and sends it through our own denoise-and-CLAHE pipeline, the way a deployed system would receive a poorly acquired film. The other degrades the image after preprocessing, isolating the method from anything the pipeline might be doing to help it. Five degradation families sit underneath those two tracks: low contrast and scatter fog model optical physics, the second based on a 1987 transmission-scatter model from Love and Kruger; Gaussian and quantum noise model sensor behavior and photon-counting statistics respectively; and a fifth, low dose, compounds scatter with quantum noise to approximate a genuinely bad acquisition rather than a textbook one. Altogether that’s 20 test conditions across 106 held-out images, 2,120 generated test cases, run once and shared across every method so the comparisons stay apples-to-apples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29x7tp2pBN4dKfjQjY9fqw.png" /><figcaption><em>The same chest X-ray under three severity levels of several degradation families, with the pixel-intensity histogram over the valid image region shown at right.</em></figcaption></figure><h3>What actually held up</h3><p>The headline result: nothing we tested was uniformly degradation-tolerant, and the specific way a method failed usually told us more than its average score did.</p><p>Pixel accuracy turned out to be nearly useless as a metric here. Every one of the nine classical methods landed between 0.68 and 0.77 pixel accuracy, including region growing’s 0.725, recorded on an image where its Dice score was 0.009. Lungs occupy roughly a quarter of each frame, so a method can be almost entirely wrong about the organ and still look fine by a metric dominated by background.</p><p>Rank order shifted depending on what you were asking. Canny’s edge detector, thresholded on gradient magnitude rather than raw intensity, was the strongest classical segmenter on clean images (0.617 Dice); Otsu came a close second at 0.506 despite needing no hand-picked parameter at all, since it maximizes between-class variance directly from each image’s own histogram. Region growing, by contrast, depends on an absolute intensity tolerance around a seed pixel, and if that seed lands outside the body instead of inside a lung, which happens more than you’d like on an untuned pipeline, it collapses to a Dice of 0.009. Before any tuning at all, six of the nine classical methods scored below the trivial baseline of labeling every pixel “lung” (itself Dice 0.41).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSjUhuIbq9VjuNlkkNpVIg.png" /><figcaption><em>One test image segmented by all nine classical methods, each panel labeled with its Dice score against the ground-truth mask shown in green.</em></figcaption></figure><p>Post-processing was a genuine double-edged tool, not a free upgrade. A border-removal step that discards any region touching the edge of the frame recovered 0.12 to 0.21 Dice for the methods most prone to leaking into the surrounding air on clean images. Under scatter fog or low-dose conditions, though, the same step turned actively harmful for K-means and the Gaussian mixture model, dropping Dice by as much as 0.44, because once a lung visually fuses with the air around it, “drop anything touching the border” deletes the lung along with the leak. A fix that helps on clean data and hurts under degradation isn’t a fix you apply unconditionally; it’s a fix you apply with a condition attached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfaDZorcg7eEGfQKuRX9YQ.png" /><figcaption><em>Where each method’s errors cluster across the test set: false positives in orange, false negatives in blue, on clean images (top two rows) versus under strong noise (bottom two rows).</em></figcaption></figure><p>Detection held up differently than segmentation did. Where the mean-IoU gap between YOLO26n and the much simpler PCA+SVM detector was a modest 12 points (0.948 vs. 0.830), the fixed decision thresholds each detector used were calibrated for clean images and broke in different ways once conditions changed. A validation-tuned SVM threshold missed every lung outright under strong contrast loss, while a more permissive, untuned threshold on the same detector kept working, at the cost of already missing about 31 percent of clean images to begin with. YOLO26n’s confidence threshold, left uncapped, let through spurious boxes on up to three-quarters of images under mild noise; capping it to the top two detections per image fixed that at moderate noise levels, but under the strongest noise condition, the same detector collapsed from the opposite direction, finding both lungs in only 15 of 106 images. A detector that looks reliable at one operating point and one noise level isn’t necessarily reliable at either a different threshold or a different exposure.</p><h3>Why the testing protocol mattered</h3><p>None of this would have been trustworthy without deciding, in advance, what counted as a result. Every tunable parameter was fixed on a training subset only, candidates were re-scored once on a held-out validation set, and the test split, degradation settings, and scoring rules were all locked by a cryptographic hash before a single test image was touched. Method comparisons ran as paired statistical tests, Wilcoxon signed-rank with Holm correction inside pre-declared families, plus Friedman tests for overall rankings, rather than a ranked table of averages.</p><p>That discipline earned its cost. Locking the protocol before results came in caught an early claim that didn’t actually hold under a properly fair comparison, a padding artifact in the detection validator, and a race condition between two processes writing to the same results file, the kind of bugs a results-first, hypothesis-second workflow would likely have let through unnoticed. It also meant reporting, plainly, that two of our seven pre-registered hypotheses weren’t supported: one reversed direction entirely under the average-precision metric, and another predicted a specific failure mode for a graph-based method that simply didn’t show up in the data. Reporting a hypothesis as wrong is a less satisfying ending than confirming it, but it’s the only version of this comparison worth trusting.</p><h3>The takeaway</h3><p>If there’s one idea worth taking from this, it’s that “degradation-tolerant” is not a property a method carries around on its own. It’s a property of a method plus a preprocessing pipeline plus an operating point plus the specific way an image got worse, and changing any one of those can flip the ranking. A technique that looks state-of-the-art on a clean benchmark can lose to a simpler one the moment the acquisition gets even slightly worse, and the only way to know which is which is to test under the conditions you actually expect to see, not just the ones that make the comparison easy to report. So, back to the question: no, most of these methods don’t survive a degraded X-ray on their own terms…</p><h3>Acknowledgments</h3><p>This project would read very differently without two people who pushed specific parts of it further than I would have alone. Mr. Mark Lester Dampios, now at Secuna Software Technologies Inc., built the entire degradation and robustness-testing framework described above: the physics-based noise models, the dual injection tracks, the parameter-tuning comparisons, and the statistical protocol that caught the bugs mentioned earlier. The finding that post-processing can help on clean data and actively hurt under degradation is his. Ms. Shiela Dona Manlapaz, of Camarines Sur Polytechnic Colleges, grounded the whole comparison against the published literature and wrote the interpretation that connects these numbers back to what segmentation methods with anatomical priors already achieve elsewhere, Dice in the 0.94 to 0.96 range, against our best prior-free Dice of 0.54, work that kept the rest of us honest about what we had and hadn’t actually shown. Research like this holds together because the people doing it keep each other’s claims accurate, and I’m glad to have had both of them checking mine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e99a27a3d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Looks like nobody had denoised an image with this algorithm for a long time. So, I tried it.]]></title>
            <link>https://mikovilla.medium.com/looks-like-nobody-had-denoised-an-image-with-this-algorithm-for-a-long-time-so-i-tried-it-664c363b27c9?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/664c363b27c9</guid>
            <category><![CDATA[denoise]]></category>
            <category><![CDATA[mls]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 19:41:12 GMT</pubDate>
            <atom:updated>2026-08-28T19:41:12.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0cN620fVLXG4tfhtqnOrg.jpeg" /><figcaption>Title of my isekai lol (AI-generated)</figcaption></figure><p>A few weeks ago, I went down a rabbit hole that started with a literature review. I was reading five 2026 papers on LMS adaptive filtering; an old technique that’s still, apparently, getting new papers written about it every year, and I noticed something. All five of them were doing the same kind of thing: cleaning up a signal over time. Magnetometer readings on a drone. Heartbeat sounds. A fetal ECG buried under the mother’s own heartbeat. Not one of them touched an image.</p><p>Which felt like an oversight. LMS filters are, at their core, just prediction machines: look at your recent inputs, guess the next value, compare your guess to reality, nudge your weights a little in the direction that would’ve made you less wrong, repeat forever. Nothing about that description requires “recent” to mean “earlier in time.” It could just as easily mean “nearby in space.” So instead of feeding the filter the last few samples of a signal, what if I fed it the pixels sitting around the one it’s trying to clean up?</p><p>Nobody in my reading pile had done this. A quick search turned up a handful of papers from the 1980s and 90s that had the same idea — but nothing recent. So, I built one myself, mostly to see what would happen.</p><h3><strong>The setup, in plain terms</strong></h3><p>Take a clean image. Corrupt it nine different ways — Gaussian noise, salt-and-pepper, Poisson, speckle, the works — because I didn’t want to build a filter that only looks good against the one noise type it happens to be lucky with. Then hand the noisy image to two versions of the filter.</p><p>The first version is unsupervised: for every pixel, it looks at a little window of neighboring pixels, predicts what the center pixel <em>*should*</em> be, and adjusts itself based on how wrong that prediction was compared to the noisy value it actually sees. It never gets to look at the clean image. It’s flying blind, the way any real denoising filter would have to.</p><p>The second version cheats, on purpose. It gets to see the actual clean image during training, so its “how wrong was I” signal is the real error, not a noisy proxy for it. I built this one specifically to establish a ceiling — if this is the best the filter architecture <em>*can*</em> do with perfect information, then the unsupervised version’s job is to see how close it can get without that luxury.</p><p>Both get compared against the dumbest possible baseline: a plain 3×3 box blur. No adaptation, no learning, just averaging your neighbors and hoping for the best. If my fancy adaptive filter can’t beat a box blur, I have no business calling it adaptive.</p><h3><strong>Where it immediately went wrong</strong></h3><p>The first real lesson had nothing to do with images at all — it was about the step size, the single number (usually called mu (μ)) that controls how aggressively the filter updates its weights after each mistake.</p><p>Set it too small and the filter barely learns anything. At mu = 0.0001, the thing crawls along at an MSE of 363, which is barely better than doing nothing. Bump it up to 0.01 and suddenly it’s actually working — MSE drops to 228. Get greedy and push it to 0.2, thinking more learning must be better, and the filter doesn’t just get worse, it falls apart entirely. On Gaussian noise the error trace just refuses to settle. On exponential noise it overflows into NaN partway through the sweep, which is a genuinely funny way to find out you’ve broken conservation of numbers.</p><p>This looks like a known trade-off in adaptive filtering — one of the papers I’d read derives it from first principles and shows, mathematically, that no single step size wins on both speed and final accuracy at once. But there’s a difference between reading that in a paper and watching your own error curve go to infinity in a Jupyter cell at 1am lol. I believed the theorem a lot more after that.</p><p>Then I made it worse for myself on purpose by adding a second dial: the size of the neighborhood window. A bigger window should mean more context, which should mean better predictions, right? Sort of. What actually happens is that a step size that’s perfectly stable for a 3×3 window becomes unstable for a 9×9 one — same mu, same noise, same image, and the MSE gets <em>*worse*</em> as the window grows, purely from instability, not from any real loss of denoising power. It took scaling the step size down as the window grew (mu divided by the number of taps, roughly) before the real trade-off underneath the instability — bigger window, more context, but also more blur — actually became visible. Before that, I was just watching two unrelated failure modes wearing the same trench coat.</p><h3><strong>The result that humbled me</strong></h3><p>Going in, I had a hypothesis I was fairly proud of: periodic noise — the kind with a regular, repeating pattern — should be the <em>*easiest*</em> case for an adaptive filter, because a repeating pattern is, structurally, predictable. That’s what these filters are supposedly good at.</p><p>I was completely wrong, and not in an interesting, ambiguous way. Across every noise amplitude and every kernel size I tested, the unsupervised filter did <em>*worse*</em> than the box blur on periodic noise. Worse than doing almost nothing.</p><p>Once I sat with it, the reason was obvious in hindsight, which is the most annoying kind of obvious. The filter can’t tell the difference between “these neighboring pixels are correlated because there’s a real edge or texture here” and “these neighboring pixels are correlated because someone painted a repeating stripe pattern of noise across the whole image.” Correlation is correlation, as far as the math is concerned. The filter didn’t fail to learn the noise pattern — it succeeded, which was the problem. It learned to predict the noise faithfully, and predicting noise faithfully is exactly the opposite of removing it.</p><p>I like this result more than any of the ones where the filter performed well, honestly, because it’s the kind of thing you only find by actually building the thing and watching it fail, rather than reasoning about it from an armchair.</p><h3><strong>The mystery I never solved</strong></h3><p>Not everything wrapped up in a tidy lesson. On exponential noise specifically, at high intensities, the unsupervised filter started beating the box blur — which was unexpected, since exponential noise is skewed and non-symmetric, exactly the kind of thing I’d have guessed would confuse a filter built around minimizing squared error. I had a hypothesis about why (something to do with how the filter’s weights redistribute under skewed noise), went and measured the weight sums directly to check it, and the measurement didn’t cleanly support the story I’d told myself.</p><p>So that one just goes in the notebook as unresolved. I could have massaged it into a satisfying paragraph about “the filter’s implicit regularization under asymmetric noise distributions” or something equally impressive-sounding, but that would’ve been making something up to fill a gap where I genuinely don’t know the answer yet. I’d rather leave the loose thread visible than sew a fake ending onto it.</p><h3><strong>The part where I checked my own work</strong></h3><p>There’s a specific failure mode I’d read about in one of the papers in my literature pile: a team reports a method that wins on one metric and loses on two others, and then the abstract only mentions the metric it wins on. It’s not fraud, exactly — it’s just the natural gravity of wanting your result to look good. I noticed myself pulled toward the same gravity more than once, and made a rule for the kernel-size analysis specifically: a configuration only counted as an “improvement” if it beat the baseline on <em>*both*</em> the accuracy metric and the sharpness metric, together. A few candidates that looked great on one and mediocre on the other got quietly demoted from “win” to “trade-off” in my own notes, which was a little deflating in the moment and probably the most useful discipline I imposed on the whole project.</p><p>I’ll also say plainly what this project isn’t: it’s one image, run through each noise type once, not averaged over dozens of trials the way a properly rigorous study would do it. That’s a real limitation, not a footnote I’m hiding. If I ran this again with different noise seeds, some of these numbers would move. But the <em>*shape*</em> of what I found — the step-size cliff, the periodic-noise failure, the metric-cherry-picking trap — feels like it would hold up, because none of those are artifacts of a lucky or unlucky draw. They’re the algorithm doing exactly what the math says it should do.</p><h3><strong>Why bother</strong></h3><p>The honest answer is that nobody asked me to do this. There’s no deadline, no deep-learning benchmark I’m trying to beat, no reason a sliding-window LMS filter needed to exist in 2026 when a five-line neural network would probably denoise this image better and faster. I did it because the gap in the literature was sitting right there, and it seemed more interesting to go find out what’s actually on the other side of “nobody’s published this recently” than to keep reading about magnetometers.</p><p>What I got back wasn’t a state-of-the-art denoiser. It was a much better feel for <em>*why*</em> adaptive filters behave the way they do — the kind of intuition that only shows up after you’ve watched your own step size blow up in real time, argued with your own hypothesis, and lost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=664c363b27c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Expected Wavelets to Win. They Didn’t — and the Reason Why Was the Actual Lesson]]></title>
            <link>https://mikovilla.medium.com/i-expected-wavelets-to-win-they-didnt-and-the-reason-why-was-the-actual-lesson-8bd15b6606fe?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd15b6606fe</guid>
            <category><![CDATA[wavelet-transform]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 08:55:59 GMT</pubDate>
            <atom:updated>2026-08-13T08:55:59.006Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A hands-on comparison of the Fourier and Haar wavelet transforms, tested on eight synthetic images built specifically to settle the question instead of just repeating the textbook answer.</em></p><p>I went into this with a working assumption, the kind you absorb from a hundred lecture slides without ever testing it yourself: the Fourier transform tells you <em>what</em> frequencies are in an image, and the wavelet transform tells you <em>what and where</em>. Locality is supposed to be the wavelet’s whole advantage; it’s built from small, spatially confined pieces, while a sine wave stretches across the entire image with no regard for where anything actually is. Edges and texture are local phenomena. So, a local basis should represent them better.</p><p>I believed that going in. It’s true for exactly one of the four things I measured. For the other two, the opposite happened, and figuring out <em>why</em> turned into the more interesting part of the project.</p><h3>Building a test where I control the answer</h3><p>Real photographs are a bad place to test this. Complexity in a photo is tangled up with sensor noise, JPEG artifacts, lighting, and scene content — you can’t isolate “how much texture is in this image” from everything else that also varies. So instead of sourcing photos, I generated eight 256×256 grayscale images from scratch, each one targeting a specific, known property:</p><ul><li><strong>01_flat_gradient</strong> — a plain linear ramp. Almost no detail.</li><li><strong>02_sharp_edges</strong> — filled shapes (square, rectangle, disc, bars, a diagonal line) on a flat background. Hard boundaries, low texture.</li><li><strong>03_smooth_blobs</strong> — a sum of soft Gaussian blobs. Low-frequency content, no hard edges at all.</li><li><strong>04_texture_checker</strong> — a checkerboard, 8-pixel squares. Periodic and high-frequency by design.</li><li><strong>05_noisy_shapes</strong> — a few shapes buried in additive Gaussian noise. Broadband content.</li><li><strong>06_mixed_scene</strong> — three different regimes stitched into one frame: a smooth field, a hard-edged block, and an angled grating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0EPus0Lwr5h2VSYqRWWvg.png" /><figcaption>Core set</figcaption></figure><p>Then I built a seventh and eighth image as a matched pair, purpose-built to test <em>only</em> spatial localization and nothing else: loc_A_split puts a widely-spaced stripe pattern on the left half of the frame and a tightly-spaced one on the right, blended smoothly at the seam. loc_B_superposed contains the exact same two frequencies, in the exact same amounts, but summed together and spread across the whole frame instead of separated by location. Same frequency content, same total energy — the only thing that differs is <em>where</em> it sits. If a transform genuinely encodes spatial position, this pair is where that should show up. If it can&#39;t tell the two apart, it isn&#39;t really &quot;local,&quot; whatever the textbook diagram implies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*EkNivWjTMyCvb6FrxOmKMg.png" /><figcaption>Localization Pair</figcaption></figure><p>Every image went through a 2D FFT and a single-level Haar wavelet decomposition, and I compared the two representations on four axes: frequency localization, spatial localization, edge representation, and texture representation, using <strong>compaction</strong> as the yardstick — how few of the transform’s coefficients, sorted by magnitude, are needed to capture 90% of the image’s total energy. Fewer coefficients needed means a more efficient representation of that image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*523FO0tC9xXx14BYhchAdg.png" /><figcaption>Log-scaled log(1 + |F|), zero-frequency centered. 01. reduces to a single faint horizontal line; 02. shows a bright cross plus adiagonal streak on a grainy broadband halo; 03. concentrates almost allvisible energy in a tight cross at the center; 04. collapses to a sparse, regularlattice of discrete points, 05. shows a low-frequency core sitting on auniform noise floor; and 06. combines a central cross with extra off-axisbands contributed by its angled grating third. loc_A_sp<em>lit</em> segregates the two gratings by side; loc_B_superposed sums them everywhere at once.</figcaption></figure><h3>Round one: spatial localization, exactly as predicted</h3><p>This is the one place my assumption held up cleanly. The Haar wavelet was the <em>only</em> representation that could tell loc_A_split and loc_B_superposed apart at all. Its HL band recovered a near-total split — about 1.7% of the energy on one side of the frame, 98.3% on the other — for the segregated image, while showing the same striped pattern spread evenly across the full width for the superposed one. The FFT, meanwhile, had nothing to say. Same frequencies, same energy, so as far as a global sine-wave basis is concerned, the two images are identical. It genuinely cannot see where anything is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*vvEcoqHSglPjtk6L_hoJ9w.png" /><figcaption>Share of total DWT detail-band energy (LH + HL + HH)in the left half versus the right half of each image.</figcaption></figure><p>Unsurprising, in hindsight — that’s exactly what compact support in a wavelet basis is supposed to buy you. But it was the <em>only</em> test where the prediction survived contact with the data.</p><h3>Round two: edges and texture, where the prediction broke</h3><p>Here’s where it got interesting. To reach 90% of the energy in 02_sharp_edges, the FFT needed just 0.13% of its coefficients. The DWT needed 6.74% — more than fifty times as many. On 04_texture_checker, the gap was worse: 0.02% for the FFT against 11.25% for the DWT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*uRUTLfUoWnBkFyxjlpZm_A.png" /><figcaption>Percentage (and approximate count) of coefficientsneeded to reach 90% of total energy, 02_sharp_edges.png.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*biAJOvGRR228m6bsbGKOnw.png" /><figcaption>Percentage (and approximate count) of coefficientsneeded to reach 90% of total energy, 04_texture_checker.png.</figcaption></figure><p>I sat with that result longer than I want to admit, because it directly contradicts the “wavelets are local, so they’re good at local things” intuition. The resolution turned out to be that I’d been treating “local” and “compact” as the same property, and they aren’t. A single Haar split works by pooling neighboring pixels together — that pooling is exactly <em>why</em> it’s local, and pooling is also exactly what determines how few coefficients a simple, low-orientation image needs. A global sinusoid basis, it turns out, is a remarkably efficient way to describe content that’s geometrically simple, completely independent of how spatially localized that content happens to be. I would not have predicted that without actually running the numbers.</p><h3>The checkerboard almost fooled me a second time</h3><p>04_texture_checker produced a result that looked, at first glance, like a wavelet win: all three Haar detail bands come back at <em>exactly</em> zero. Not small — zero. The obvious read is that the DWT has packed everything useful into the low-frequency approximation band, for free.</p><p>It hasn’t. That approximation band is still a 128×128 checkerboard, still alternating value to value with no smoothing at all, and it still needs a large share of its own coefficients to reach 90% of its energy — which is exactly where that 11.25% figure above comes from. The zero-detail result isn’t the wavelet recognizing periodic structure. It’s a coincidence: the checkerboard’s 8-pixel tiles line up <em>exactly</em> with the Haar filter’s 2-pixel window. Shift the whole board by a single pixel and that alignment — and the free-looking result — disappears. It’s a property of this specific grid, not a general property of the transform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Nh3wc1VYmyh1M15jIZG9aw.png" /><figcaption>Single-level Haar decomposition into LL (approximation), LH(horizontal detail), HL (vertical detail), and HH (diagonal detail). Notably, 04_texture_checker ‘s three detail bands are uniformly black (identicallyzero, not merely faint), discussed in Section V.D. In 06_mixed_scene, all three detail bands visibly concentrate their energy in the right-hand third of the frame, tracking the angled grating located there.</figcaption></figure><h3>Checking my own numbers against someone else’s</h3><p>A result measured on one set of eight images is a claim about those eight images. It isn’t yet a claim about the transform. So once <strong>Dr. Ricky Jay Riel</strong>, of Cavite State University — Naic, made his independently built five-image dataset and independently written Haar implementation available (his, coded from scratch, rather than pulled from a library the way mine was), I ran both pipelines against both datasets — his five images through my code, my eight through his, and everything against itself.</p><p>The short version: the results were close to identical no matter which pipeline computed them, on either dataset. Where they diverged, the gap was small and traceable rather than mysterious. The compaction gap between the two transforms held up on every one of his five images too — the FFT reaching 90% energy in thirteen coefficients or fewer every time, the DWT needing 11–22%. The two independently-written wavelet implementations agreed with each other <em>exactly</em> on every image that started out as grayscale (a Haar filter is exactly two samples wide, matching the downsampling factor, so there’s no boundary-handling choice for two implementations to disagree about). The only place any drift showed up was on his images that started out in color, where his grayscale-conversion formula (a standard luminance-weighted mix) and mine (a plain channel average) had genuinely different, small things to disagree about. On the one image in his set that was pure black and white to begin with, red, green, and blue were already equal — so there was nothing for the two conversion formulas to differ on, and the two pipelines matched exactly there too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiT6vnQy2GMVX6aVa3G4cw.png" /><figcaption>Dr. Riel’s five images, each run through his pipeline and mine.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tlbQz2X7nCPuDvUu4ltTw.png" /><figcaption>My eight images, each run through Dr. Riel’s pipeline and mine.</figcaption></figure><p>That’s a more useful outcome than either dataset alone would have given me: the compaction gap isn’t an artifact of my specific images, and the one place a number <em>did</em> move by a couple of points has a specific, boring cause rather than an unexplained one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FP1kJ_70Gmi4SNXFTIXgbw.png" /><figcaption>The localization pair after grayscale conversion. loc_A_split (left) segregates the two gratings by side; loc_B_superposed (right) sums them everywhere at once.</figcaption></figure><h3>What this actually shows — and where I’d stop trusting it</h3><p>A few honest limits, because a result this clean deserves some skepticism about <em>why</em> it’s clean:</p><ul><li>Every image here is mathematically exact — perfect gradients, perfect checkerboards, no compression, no color. Real photographs won’t behave this tidily.</li><li>The images are 256×256, a convenient power of two that lets wavelet decomposition split cleanly in half. Other sizes need different handling.</li><li>This is a <em>single</em> level of Haar decomposition. The leftover approximation band after one split is still a fairly large, mostly-unprocessed 128×128 image. Letting it split again would very likely narrow the compaction gap on edges and texture, maybe close it entirely — that’s the natural next experiment, not a disclaimer tacked on at the end.</li><li>The 90% energy threshold isn’t a principled constant. Set it at 100% and the metric becomes meaningless — nearly every coefficient is required regardless of the image. Set it too low and a single dominant coefficient satisfies it outright, and every image starts looking equally “sparse.” Ninety percent is just the threshold that still discriminates between images instead of collapsing them all to the same answer, and it’s worth saying that out loud rather than presenting the number as if it fell out of nowhere.</li></ul><h3>The actual takeaway</h3><p>“Wavelets are local, therefore better for local content” is the kind of claim that sounds airtight until you separate its two halves and test them one at a time. Locality and compactness turned out to be different properties measuring different things, and the only way I found that out was by building a pair of images specifically designed to isolate one variable, running a compaction metric that could actually break, and then checking the whole thing again against a second dataset and a second, independently written implementation before trusting any of it.</p><p>The Fourier transform won the efficiency contest on every single image in this dataset, edge-heavy or not. The wavelet transform won the one contest that was actually about location. Both of those are true, and neither one is the <em>general</em> headline the textbook diagram implies.</p><blockquote>Special thanks to Dr. Ricky Jay Riel, of Cavite State University — Naic, for the second dataset and the independently-written implementation that made it possible to check these results against something other than themselves.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd15b6606fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Added AWS Cognito to a Private Static Web App]]></title>
            <link>https://mikovilla.medium.com/how-i-added-aws-cognito-to-a-private-static-web-app-64ca51e27361?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ca51e27361</guid>
            <category><![CDATA[aws-cognito]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 18:37:16 GMT</pubDate>
            <atom:updated>2026-01-10T18:37:16.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*VwYuIe1oYUflIJwf22SWZw.png" /><figcaption>AWS Cognito Login Page</figcaption></figure><p>When I first decided to put up a small personal web app on the internet, I expected the hardest part to be the UI. Maybe polishing the animations. Maybe getting the layout to look presentable enough so I wouldn’t be embarrassed sharing it with friends.</p><p>What I didn’t expect was to get stuck on something as simple as “How do I keep this private?”</p><p>Most tutorials assume you’re building a SaaS platform or a startup MVP, with hundreds or thousands of users signing up. None of that applied to me. My app was not meant for the world; just for me (and maybe a handful of people who knew what it was). I didn’t want a signup form. I didn’t want random users. I didn’t want the public internet. I just wanted a secure door that opened for the right people, and stayed closed for everyone else.</p><p>And that tiny requirement turned out to be surprisingly slippery.</p><p>I tried to overcorrect; worrying about OAuth providers, managing users, hashing passwords, and all the other mechanisms that felt like too much engineering for too little audience. The spectrum seemed binary: either fully public, or full enterprise-grade authentication. There wasn’t a comfortable in-between space for “just private enough.”</p><p>That was the moment I stumbled into AWS Cognito.</p><p>At first, it felt like a heavyweight option. Cognito is the kind of thing you imagine powering corporate dashboards and regulated apps with a thousand policy controls. But the deeper I went, the more I realized it was exactly what I needed: a pre-built, secure login gateway; without running my own auth server, storing my own passwords, or engineering an entire identity system for an audience of one.</p><p>This isn’t just a narrative about stumbling into authentication by accident; I actually want to share some codes to those who wants to follow along. But before diving into it, I think there’s value in understanding the why behind it. Because the moment you decide something should be private; even if you’re the only person using it; authentication stops being optional.</p><p>And that’s when things get interesting.</p><h3>Discovering AWS Cognito for a Personal App</h3><p>AWS Cognito wasn’t something I initially planned to use. When you hear “Cognito,” you picture enterprise dashboards, corporate access control, and user pools with thousands of accounts. My project was the complete opposite; a quiet little static web app that only I cared about, living out in the open internet where anyone could knock on its front door.</p><p>At first, I tried ignoring the authentication problem entirely. Then I tried overthinking it. I considered rolling my own login system, hashing passwords, storing them somewhere, and hoping I didn’t accidentally reinvent security vulnerabilities from 2009. It didn’t take long to realize that building authentication, even for a single user, isn’t as “small” as it looks.</p><p>That’s when Cognito started making sense. Instead of writing a login system, I could borrow one. Cognito handled everything I didn’t want to build; user management, sign-in, sign-out, password resets, hosted UI, and security policies. It was overkill on paper, but exactly the right amount of responsibility in practice.</p><p>More importantly, Cognito gave me something surprisingly rare; a clean, private login experience without turning my personal app into a full SaaS product. No sign-up pages, no public onboarding flow, no social logins or marketing emails. Just a secure door that only opens for the people I choose.</p><p>Once I saw that, the next question was no longer “should I build authentication?” but “how do I integrate Cognito into a tiny static app without going insane?”</p><p>So here’s how I set this up:</p><pre># Create the user pool<br>aws cognito-idp create-user-pool \<br>  --region &lt;REGION&gt; \<br>  --pool-name &lt;POOL_NAME&gt; \<br>  --username-attributes email \<br>  --auto-verified-attributes email \<br>  --admin-create-user-config &#39;{&quot;AllowAdminCreateUserOnly&quot;: true}&#39; \<br>  --policies &#39;{<br>    &quot;PasswordPolicy&quot;: {<br>      &quot;MinimumLength&quot;: 8,<br>      &quot;RequireUppercase&quot;: true,<br>      &quot;RequireLowercase&quot;: true,<br>      &quot;RequireNumbers&quot;: true,<br>      &quot;RequireSymbols&quot;: true<br>    }<br>  }&#39; \<br>  --query &#39;UserPool.Id&#39; --output text<br><br># Create the user pool client<br>aws cognito-idp create-user-pool-client \<br>  --region &lt;REGION&gt; \<br>  --user-pool-id &lt;USER_POOL_ID&gt; \<br>  --client-name &lt;CLIENT_NAME&gt; \<br># No secret needed. This is SPA and the browser can&#39;t keep one safe anyway.<br>  --no-generate-secret \ <br>  --allowed-o-auth-flows-user-pool-client \<br>  --allowed-o-auth-flows code \<br>  --allowed-o-auth-scopes openid email profile \<br>  --callback-urls &lt;CALLBACK_URLS&gt; \<br>  --logout-urls &lt;LOGOUT_URLS&gt; \<br>  --supported-identity-providers COGNITO \<br>  --prevent-user-existence-errors ENABLED \<br>  --query &#39;UserPoolClient.ClientId&#39; --output text<br><br># Create the domain prefix<br>aws cognito-idp create-user-pool-domain \<br>  --region &lt;REGION&gt; \<br>  --domain &lt;DOMAIN_PREFIX&gt; \<br>  --user-pool-id &lt;USER_POOL_ID&gt;<br><br># Create user via admin <br># disabled user registration<br>aws cognito-idp admin-create-user \<br>  --region &lt;REGION&gt; \<br>  --user-pool-id &lt;USER_POOL_ID&gt; \<br>  --username &lt;EMAIL&gt; \<br>  --user-attributes Name=email,Value=&lt;EMAIL&gt; \<br>  --message-action SUPPRESS<br><br># Set the user password<br>aws cognito-idp admin-set-user-password \<br>  --region &lt;REGION&gt; \<br>  --user-pool-id &lt;USER_POOL_ID&gt; \<br>  --username &lt;EMAIL&gt; \<br>  --password &quot;&lt;PASSWORD&gt;&quot; \<br>  --permanent<br><br># Sanity Checks<br>aws cognito-idp list-user-pools --region &lt;REGION&gt; --max-results 20<br><br>aws cognito-idp describe-user-pool-client \<br>  --region &lt;REGION&gt; \<br>  --user-pool-id &lt;USER_POOL_ID&gt; \<br>  --client-id &lt;CLIENT_ID&gt;</pre><h3>Putting My Name on It: Custom Domain + ACM</h3><p>Once Cognito was running, I hit a new realization: logging in was nice, but doing it through an auto-generated AWS URL felt like walking into my own house through the neighbor’s garage. Functional, but not mine. If I was going to secure this tiny personal web app, it deserved an address that actually belonged to me.</p><p>That’s where Cognito’s custom domain support came in; and with it, the AWS Certificate Manager (ACM). I always assumed SSL certificates were something you bought once a year from domain registrars, but ACM quietly handled the entire certificate side without me filing a single support ticket or fiddling with weird certificate files. The only real requirement was proving that I owned the domain, which felt fair. If I’m going to put a lock on a door, I need to prove the house is mine.</p><p>And suddenly, the experience became more professional than I expected. Instead of signing in through something.auth.region.amazoncognito.com, I could type in a clean, branded domain that matched my app and identity. No corporate context. No startup vanity. Just a private entrance designed for my personal use.</p><p>It also sparked a funny thought; the internet tends to glamorize custom domains as branding tools. But in my case, it wasn’t about growth or marketing. It was for the quiet satisfaction of knowing the door to my private web app lived under a name I chose, secured with a certificate I didn’t have to babysit; and for the chance to explore how these small pieces of the web actually work behind the scenes.</p><p>Once that was in place, the login flow finally felt complete. Private, secure, and unmistakably mine.</p><pre># ACM<br>aws acm request-certificate \<br>  --domain-name &lt;SUBDOMAIN&gt;.&lt;APEX.TLD&gt; \<br>  --validation-method DNS \<br>  --key-algorithm RSA_2048 \<br>  --region us-east-1 # us-east-1 only; <br># Cognito always uses an underlying CloudFront distribution for custom domains<br># CloudFront only supports ACM certificates issued in us-east-1<br><br># describe the certificateArn returned by the script above<br>aws acm describe-certificate --certificate-arn &lt;CERTIFICATE_ARN&gt;<br><br># status returned by the script above this should be PENDING_VALIDATION<br># take note of the DomainValidationOptions.ResourceRecord<br># add the CNAME record in your DNS Provider<br># HOST: DomainValidationOptions.ResourceRecord.Name *<br># VALUE: DomainValidationOptions.ResourceRecord.Value<br># * remove the apex, but retain the subdomain<br># once added, run `describe` again, and the status should change to ISSUED<br><br># Add Custom Domain for Cognito<br>aws cognito-idp create-user-pool-domain \<br>  --domain &lt;DOMAIN&gt; \<br>  --user-pool-id &lt;POOL_ID&gt; \<br>  --custom-domain-config CertificateArn=&lt;CERTIFICATE_ARN&gt;<br><br># Describe the domain, and get the CloudFrontDistribution<br>aws cognito-idp describe-user-pool-domain \<br>  --domain &lt;DOMAIN&gt;<br># Add the CloudFrontDistribution as the value for your CNAME&#39;s subdomain<br><br># sanity check<br># visit https://cognito-idp.ap-southeast-1.amazonaws.com<br># /&lt;USER_POOL_ID&gt;/.well-known/openid-configuration<br># check if the endpoints are updated to your custom domain</pre><h3>Bringing It All Together with a Static Web App</h3><p>With Cognito in place and a custom domain I actually liked typing, the final piece of the puzzle was the app itself. I chose Blazor for a much simpler reason: I’m a C# developer, and it’s the language I’m most comfortable building with. Instead of switching mental modes and wrestling with a JavaScript stack, Blazor let me stay in a world I already understood.</p><p>The real challenge wasn’t writing Blazor components; it was making sure Cognito and the browser were on speaking terms. Redirects, tokens, and callbacks suddenly became part of my vocabulary, even though none of them were the reason I started this app in the first place. But once those pieces locked in, the experience felt solid. The login happened, Blazor loaded, and my tiny personal app had a private life of its own.</p><pre>// appsettings.cs<br>// Create this under the wwwroot folder<br>{<br>  &quot;Cognito&quot;: {<br>    &quot;Authority&quot;: &quot;https://cognito-idp.ap-southeast-1.amazonaws.com/&lt;USER_POOL_ID&quot;,<br>    &quot;ClientId&quot;: &quot;&lt;CLIENT_ID&gt;&quot;,<br>    &quot;ResponseType&quot;: &quot;code&quot;,<br>    &quot;DefaultScopes&quot;: &quot;openid profile email&quot;,<br>    &quot;RedirectUri&quot;: &quot;&lt;LOGIN_CALLBACK_URL&gt;&quot;,<br>    &quot;PostLogoutRedirectUri&quot;: &quot;&lt;LOGOUT_URL&gt;&quot;<br>  }<br>}<br><br>// Program.cs<br>builder.Services.AddAuthorizationCore();<br>builder.Services.AddOidcAuthentication(options =&gt; {<br>    builder.Configuration.Bind(&quot;Cognito&quot;, options.ProviderOptions);<br>});<br>await builder.Build().RunAsync();<br><br>// _Imports.razor<br>// You may also need the following<br>@using Microsoft.AspNetCore.Authorization<br>@using Microsoft.AspNetCore.Components.Authorization<br>@using Microsoft.AspNetCore.Components.WebAssembly.Authentication<br><br>// App.razor<br>// Provides user auth state to the entire Blazor component tree <br>// so pages can react to logged-in or logged-out status.<br>&lt;CascadingAuthenticationState&gt;<br>    &lt;Router AppAssembly=&quot;@typeof(App).Assembly&quot;&gt;<br>        &lt;Found Context=&quot;routeData&quot;&gt;<br>            &lt;AuthorizeRouteView RouteData=&quot;@routeData&quot; DefaultLayout=&quot;@typeof(MainLayout)&quot;&gt;<br>                &lt;Authorizing&gt;<br>                    Working on it<br>                &lt;/Authorizing&gt;<br>                &lt;NotAuthorized&gt;<br>                    ...<br>                &lt;/NotAuthorized&gt;<br>            &lt;/AuthorizeRouteView&gt;<br>        &lt;/Found&gt;<br>        &lt;NotFound&gt;<br>            &lt;LayoutView Layout=&quot;@typeof(MainLayout)&quot;&gt;<br>                &lt;p&gt;Sorry, there’s nothing at this address.&lt;/p&gt;<br>            &lt;/LayoutView&gt;<br>        &lt;/NotFound&gt;<br>    &lt;/Router&gt;<br>&lt;/CascadingAuthenticationState&gt;<br><br>// Home.razor<br>// Say you want only authorized users to view your / page.<br>@page &quot;/&quot;<br>@attribute [Authorize]<br><br>// Login.razor<br>// This is where you<br><br>&lt;AuthorizeView&gt;<br>    &lt;Authorizing&gt;<br>        &lt;span&gt;&lt;/span&gt;<br>    &lt;/Authorizing&gt;<br>    &lt;Authorized&gt;<br>        &lt;button @onclick=&quot;Logout&quot;&gt;Logout&lt;/button&gt;<br>    &lt;/Authorized&gt;<br>    &lt;NotAuthorized&gt;<br>        &lt;button @onclick=&quot;Login&quot;&gt;Login&lt;/button&gt;<br>    &lt;/NotAuthorized&gt;<br>&lt;/AuthorizeView&gt;<br><br>@code {<br>    [Inject] NavigationManager Nav { get; set; } = default!;<br>    [Inject] IJSRuntime JS { get; set; } = default!;<br><br>    void Login() =&gt; Nav.NavigateTo(&quot;authentication/login&quot;, forceLoad: true);<br>    async Task Logout(){<br>        <br>        // removes the session from browser<br>        await System.Threading.Tasks.Task.Yield();<br>        await JS.InvokeVoidAsync(&quot;localStorage.clear&quot;);<br>        await JS.InvokeVoidAsync(&quot;sessionStorage.clear&quot;);<br><br>        Nav.NavigateTo(&quot;authentication/logged-out&quot;, forceLoad: true);<br>    }<br>}<br><br>// index.html<br>// Make sure to add this script just right above before you close the body<br>&lt;script src=&quot;_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js&quot;&gt;&lt;/script&gt;</pre><p>PS: I’m not a designer, so the UI and styling are entirely up to you. My focus was on making the app work, not on picking fonts and colors.</p><h3>Conclusion</h3><p>What started as another simple static web app turned into a crash course in authentication, identity, certificates, and redirect flows; all for an audience of one. It’s funny how “personal” projects tend to push us into parts of the stack we’ve never touched before, and Cognito became that rabbit hole for me. Along the way I learned that privacy isn’t just a feature, it’s a boundary, and it deserves real security even if the user base fits around a single dining table.</p><p>Now, pairing Blazor with Cognito, a custom domain, and ACM turned out to be a surprisingly elegant way to give a small app a proper entrance without reinventing identity from scratch. And the best part is that Cognito plays nicely during development and doesn’t fight you on localhost, which makes experimentation feel less like work and more like exploration.</p><p>If you’re building something just for yourself; or for a tiny circle of people; don’t underestimate the value of securing it properly. Tools like Cognito exist for more than enterprise dashboards; they give indie projects and personal ideas a chance to stay private without cutting corners on safety. And if you’re anything like me, you might find that the journey of wiring all these pieces together ends up being just as rewarding as the app you set out to build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ca51e27361" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure with AWS? Communication Across Clouds]]></title>
            <link>https://mikovilla.medium.com/azure-with-aws-communication-across-clouds-abd425d6cd8e?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/abd425d6cd8e</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 16:12:31 GMT</pubDate>
            <atom:updated>2026-01-03T09:18:02.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*f0vb3Pg4_xdZle_VoW3qAQ.png" /><figcaption>Building a simple serverless backend pageview counter</figcaption></figure><p>I wanted to add a simple pageview counter to my personal website; nothing fancy, just a reliable way to track visits without pulling in heavyweight analytics or third-party scripts.</p><p>Quick backstory: previously, my site was hosted using AWS Amplify with DNS managed by Amazon Route 53. While this setup worked technically, it didn’t make sense financially for my use case. I was incurring monthly Route 53 charges that I couldn’t really justify or fully utilize, especially for a low-traffic personal site. On top of that, Amplify’s limitation around apex domains; requiring the domain to live in Route 53; made the setup feel more constrained than it needed to be.</p><p>Eventually, I decided to switch. I moved the site to Azure Static Web Apps, kept the code in GitHub, and managed DNS through Namecheap. This combination gave me exactly what I needed: zero hosting cost for a static site, native GitHub integration, and full control over my apex domain; without recurring DNS fees that didn’t scale with value.</p><p>That said, I’m still very much an AWS person. Even though the site itself is hosted in Azure, I prefer building backend components in AWS ; where I’m most comfortable with the tooling, security model, and operational patterns. So instead of trying to force everything into a single cloud, I treated the visit counter as a small, self-contained backend service and built it the AWS way.</p><p>With the frontend settled, the remaining question was simple: how do I add a safe, scalable page visit counter without breaking the low-cost, low-maintenance goal?</p><p>That’s where AWS Lambda, DynamoDB, and API Gateway come into play.</p><h3>DynamoDB</h3><p>Before wiring up any compute or public endpoints, the first thing to set up is the data layer. For this use case, Amazon DynamoDB is a natural fit: it’s fully managed, scales automatically, and most importantly; it supports atomic counter updates out of the box. Since the visit counter will be incremented concurrently by multiple requests, relying on atomic updates ensures accuracy without needing locks, queues, or additional coordination logic. The table itself is intentionally minimal: a single primary key representing the page and a numeric attribute that stores the visit count. There’s no need for secondary indexes, streams, or complex schemas here; simplicity keeps costs low and failure modes small. Once the table design is clear, you can run the AWS CLI scripts below to create the table and verify that atomic increments work as expected before moving on to Lambda.</p><pre>aws dynamodb create-table --table-name PageView \ <br>--attribute-definitions AttributeName=Id,AttributeType=S \ <br>--key-schema AttributeName=Id,KeyType=HASH \ <br>--billing-mode PAY_PER_REQUEST<br><br>aws dynamodb put-item \<br>  --table-name PageView \<br>  --item &#39;{<br>    &quot;Id&quot;:   {&quot;S&quot;: &quot;&lt;PAGE&gt;&quot;},<br>    &quot;Views&quot;: {&quot;N&quot;: &quot;0&quot;}<br>  }&#39;</pre><h3>Lambda</h3><p>With DynamoDB in place, the next step is the compute layer: an AWS Lambda function that receives a page identifier, performs a single atomic increment in DynamoDB, and returns the updated count. I’m writing this in .NET for a simple reason: I’m a .NET developer, and it’s the ecosystem I’m most productive in. AWS Lambda’s .NET runtime makes this straightforward: you can keep the handler small, structure the logic cleanly, and still benefit from Lambda’s scaling and pay-per-request model. In the code below, you’ll see a minimal Lambda that focuses on one job only: validate the input, call DynamoDB with an atomic update, and return a lightweight response that my static site can call safely.</p><pre>using Amazon.DynamoDBv2;<br>using Amazon.DynamoDBv2.Model;<br>using Amazon.Lambda.APIGatewayEvents;<br>using Amazon.Lambda.Core;<br>using System.Text.Json;<br><br>[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]<br><br>namespace Miko.Lambda;<br><br>public class Function<br>{<br>    private static readonly AmazonDynamoDBClient _ddb = new AmazonDynamoDBClient();<br>    private readonly string _tableName = Environment.GetEnvironmentVariable(&quot;TABLE_NAME&quot;) ?? &quot;PageView&quot;;<br><br>    public async Task&lt;APIGatewayProxyResponse&gt; FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)<br>    {<br>        // hardcode this to guarantee all updates are atomic against a single, well-known record<br>        var id = &quot;&lt;PAGE&gt;&quot;; <br><br>        if (request?.QueryStringParameters != null &amp;&amp;<br>            request.QueryStringParameters.TryGetValue(&quot;id&quot;, out var qsId) &amp;&amp;<br>            !string.IsNullOrWhiteSpace(qsId))<br>        {<br>            id = qsId.Trim();<br>        }<br><br>        var update = new UpdateItemRequest<br>        {<br>            TableName = _tableName,<br>            Key = new Dictionary&lt;string, AttributeValue&gt;<br>            {<br>                [&quot;id&quot;] = new AttributeValue { S = id }<br>            },<br>            UpdateExpression = &quot;ADD #views :inc&quot;,<br>            ExpressionAttributeNames = new Dictionary&lt;string, string&gt;<br>            {<br>                [&quot;#views&quot;] = &quot;views&quot;<br>            },<br>            ExpressionAttributeValues = new Dictionary&lt;string, AttributeValue&gt;<br>            {<br>                [&quot;:inc&quot;] = new AttributeValue { N = &quot;1&quot; }<br>            },<br>            ReturnValues = ReturnValue.UPDATED_NEW<br>        };<br><br>        var resp = await _ddb.UpdateItemAsync(update);<br><br>        var views = resp.Attributes.TryGetValue(&quot;views&quot;, out var av) ? int.Parse(av.N) : 0;<br><br>        var origin = &quot;https://&lt;PAGE&gt;&quot;;<br>        var body = JsonSerializer.Serialize(new { id, views });<br><br>        return new APIGatewayProxyResponse<br>        {<br>            StatusCode = 200,<br>            Headers = new Dictionary&lt;string, string&gt;<br>            {<br>                [&quot;Content-Type&quot;] = &quot;application/json&quot;,<br>                [&quot;Access-Control-Allow-Origin&quot;] = origin,<br>                [&quot;Access-Control-Allow-Methods&quot;] = &quot;POST&quot;,<br>                [&quot;Access-Control-Allow-Headers&quot;] = &quot;Content-Type&quot;<br>            },<br>            Body = body<br>        };<br>    }<br>}</pre><p>Once the Lambda is ready, the next step is deployment. Since the function is written in .NET, I use Amazon.Lambda.Tools, the official AWS CLI extension for building and deploying .NET Lambda applications. This tool fits naturally into a .NET workflow and removes the need to manually package artifacts or upload ZIP files. At the end of this step, you’ll have a live Lambda function wired to DynamoDB, ready to be invoked; either directly for testing or later through API Gateway.</p><pre># make sure that Lambda.Tools is installed in your machine; if not, run:<br># dotnet tool install -g Amazon.Lambda.Tools<br><br># navigate to your Lambda Project directory, and run the following line:<br>dotnet lambda deploy-function incrementPageView<br><br># choose or create a new IAM Role: `IncrementPageViewLambdaRole`<br># attach `LambdaBasicExecutionRole` to the role<br><br># check if your lambda function has been created<br>aws lambda get-function --function-name incrementPageView<br><br># optional: to cut cost, reduce the memory size and timeout values<br>aws lambda update-function-configuration \<br>  --function-name incrementPageView \<br>  --memory-size 128 \<br>  --timeout 5<br><br># Attach an inline policy to IncrementPageViewLambdaRole<br>aws iam put-role-policy \<br>  --role-name IncrementPageViewLambdaRole \<br>  --policy-name dynamodb-update-pageview \<br>  --policy-document &#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>      {<br>        &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>        &quot;Effect&quot;: &quot;Allow&quot;,<br>        &quot;Action&quot;: &quot;dynamodb:UpdateItem&quot;,<br>        &quot;Resource&quot;: &quot;arn:aws:dynamodb:&lt;REGION&gt;:&lt;ACCOUNT_ID&gt;:table/PageView&quot;<br>      }<br>    ]<br>  }&#39;</pre><h3>API Gateway</h3><p>With the Lambda deployed, the next layer is API Gateway; this is what turns the function into a clean, public-facing API that your static site can call safely. In API Gateway, I created an API, defined a simple route (for example, an increment endpoint that takes a page key), and wired that route to the Lambda via an integration so requests flow straight through to the function. The real reason I put API Gateway in front (instead of exposing Lambda directly) is control: API Gateway gives you a predictable URL structure, request/response handling, and most importantly for a public counter: throttling. Since this endpoint is callable by anyone who can load the page, throttling acts as a built-in guardrail against accidental traffic spikes, aggressive crawlers, or simple abuse. By setting a sensible steady-state rate and burst limit at the stage (or usage plan) level, the counter stays responsive for real visitors while limiting how much damage a noisy client can do to your Lambda concurrency and DynamoDB write capacity.</p><pre># create the API Gateway and get the API_ID<br>aws apigatewayv2 create-api \<br>  --name analytics-api \<br>  --protocol-type HTTP \<br>  --cors-configuration &#39;{<br>    &quot;AllowOrigins&quot;: [&quot;&lt;PAGE&gt;&quot;],<br>    &quot;AllowHeaders&quot;: [&quot;content-type&quot;],<br>    &quot;AllowMethods&quot;: [&quot;POST&quot;]<br>  }&#39; \<br>  --query ApiId \<br>  --output text<br><br># create the integration and get the INTEGRATION_ID<br>aws apigatewayv2 create-integration \<br>  --api-id &lt;API_ID&gt; \<br>  --integration-type AWS_PROXY \<br>  --integration-uri &lt;INTEGRATION_ID&gt; \<br>  --payload-format-version &quot;2.0&quot; \<br>  --query IntegrationId \<br>  --output text<br><br># create the route<br>aws apigatewayv2 create-route \<br>  --api-id &lt;API_ID&gt; \<br>  --route-key &quot;POST /analytics/pageview&quot; \<br>  --target &quot;integrations/&lt;INTEGRATION_ID&quot;<br><br># create stage with throttling<br>aws apigatewayv2 create-stage \<br>  --api-id &lt;API_ID&gt; \<br>  --stage-name prod \<br>  --auto-deploy \<br>  --default-route-settings &#39;{<br>    &quot;ThrottlingBurstLimit&quot;: 5,<br>    &quot;ThrottlingRateLimit&quot;: 2<br>  }&#39;<br><br># allow API Gateway to invoke lambda<br>aws lambda add-permission \<br>  --function-name incrementPageView \<br>  --statement-id apigateway-pageview \<br>  --action lambda:InvokeFunction \<br>  --principal apigateway.amazonaws.com \<br>  --source-arn &quot;arn:aws:execute-api:&lt;REGION&gt;:&lt;ACCOUNT_ID&gt;:&lt;API_ID&gt;/*/*/analytics/pageview&quot;<br><br># get the URL and test the route<br>aws apigatewayv2 get-api \<br>  --api-id &lt;API_ID&gt; \<br>  --query ApiEndpoint \<br>  --output text</pre><h3>Certificate Manager</h3><p>The final step is to make the API feel like a first-class part of the site by putting it behind a custom domain. Instead of exposing the raw API Gateway URL, I configured a custom domain in API Gateway and secured it using AWS Certificate Manager. ACM handles certificate issuance and renewal automatically, which means there’s no manual certificate management and no ongoing maintenance overhead. Once the certificate is in place, the custom domain can be mapped to the API stage, giving you a clean, HTTPS endpoint that’s safe to call directly from a browser. This also keeps the architecture consistent with the rest of the site: even though the frontend is hosted in Azure, the backend API still presents a trusted, branded domain with proper TLS , without adding cost or operational complexity.</p><pre># make sure to run `aws configure`<br>aws acm request-certificate \<br>  --domain-name &lt;SUBDOMAIN&gt;.&lt;APEX.TLD&gt; \<br>  --validation-method DNS \<br>  --key-algorithm RSA_2048 \<br>  --region ap-southeast-1<br><br># describe the certificateArn returned by the script above<br>aws acm describe-certificate --certificate-arn &lt;CertificateArn&gt;<br><br># status returned by the script above this should be PENDING_VALIDATION<br># take note of the DomainValidationOptions.ResourceRecord<br># add the CNAME record in your DNS Provider<br># HOST: DomainValidationOptions.ResourceRecord.Name *<br># VALUE: DomainValidationOptions.ResourceRecord.Value<br># * remove the apex, but retain the subdomain<br># once added, run `describe` again, and the status should change to ISSUED<br><br># create the domain name in API Gateway<br>aws apigatewayv2 create-domain-name \<br>  --domain-name &lt;SUBDOMAIN&gt;.&lt;APEX.TLD&gt; \<br>  --domain-name-configurations CertificateArn=&lt;CERT_ARN&gt;,EndpointType=REGIONAL,SecurityPolicy=TLS_1_2 \<br>  --region ap-southeast-1<br><br># create the api mapping<br>aws apigatewayv2 create-api-mapping \<br>  --domain-name &lt;SUBDOMAIN&gt;.&lt;APEX.TLD&gt; \<br>  --api-id &lt;API_ID&gt; \<br>  --stage prod \<br>  --api-mapping-key &quot;&quot; \<br>  --region ap-southeast-1<br><br># get the api gateway domain name<br>aws apigatewayv2 get-domain-name \ <br>--domain-name &lt;SUBDOMAIN&gt;.&lt;APEX.TLD&gt; \ <br>--region ap-southeast-1 \ <br>--query DomainNameConfigurations[0].ApiGatewayDomainName \ <br>--output text<br><br># Create a CNAME record in your DNS Provider with the following values:<br># Host: api<br># Value: &lt;API_GATEWAY_DOMAIN_NAME&gt;</pre><h3>Conclusion</h3><p>What started as a simple page visit counter ended up being a small but practical exercise in intentional architecture. By keeping the frontend static and low-cost while building the backend in AWS, I was able to combine the best of both worlds: zero-maintenance hosting on Azure and a serverless, pay-per-use backend on AWS.</p><p>At first glance, this setup might look over-engineered for something as simple as a visit counter; and that’s a fair reaction. But the goal here wasn’t just to count page views. It was to explore AWS services in a way that’s safe, scalable, and as cheap as possible, while still following patterns you’d actually use in real systems. For a personal project, this strikes a good balance: low monthly cost, clear boundaries, and an excuse to stay hands-on with AWS without spinning up infrastructure that idles and charges you anyway.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abd425d6cd8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Windows to Ubuntu: My Chromebox Makeover]]></title>
            <link>https://mikovilla.medium.com/from-windows-to-ubuntu-my-chromebox-makeover-7cd4d0aca710?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cd4d0aca710</guid>
            <category><![CDATA[chromebox]]></category>
            <category><![CDATA[ubuntu-server]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 22:52:44 GMT</pubDate>
            <atom:updated>2025-09-13T01:00:24.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*VY3qrp6j_Hw-3-P7hWCkgw.png" /></figure><p><a href="https://medium.com/p/668e46e0a95d">About two years ago, I picked up a Chromebox from Facebook Marketplace on a whim</a>. Back then, I thought it would be fun to turn it into a little Windows Server machine just to see what it could do. It worked fine, but after a while, it started feeling a bit… boring. So now I’m giving it a second life by installing Ubuntu Server instead. It’s a simple switch, but one that makes the whole thing feel fresh again; kind of like rediscovering an old gadget with a new twist. Let’s get started</p><p>Here are the requirements:</p><ul><li>Chromebox (flashed with MrChromebox UEFI firmware)</li><li>Flashdrive (at least 4GB storage)</li><li><a href="https://rufus.ie/en/">r<strong>ufus-4.9p.exe</strong></a> (Rufus 4.9 Portable)</li><li><a href="https://ubuntu.com/download/server"><strong>Ubuntu Server ISO</strong></a></li></ul><p>Here is the Rufus configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*p9WspzHdeQVso1UeeVmbjQ.png" /></figure><p>The actual installation couldn’t have been easier. Once I had Rufus and the Ubuntu Server ISO set up on a USB, it was pretty much just a matter of plugging it in and clicking “Next” until the end. I didn’t have to wrestle with complicated configs or secret tricks. It’s pretty straightforward, no-fuss setup.</p><p>Once the install wrapped up and I was inside Ubuntu Server, I wanted to make sure I could use it headless. That’s where <strong>XRDP</strong> and <strong>XFCE</strong> come in. XRDP lets me connect remotely using the familiar Windows Remote Desktop app, so I can manage everything straight from my laptop. XFCE adds a lightweight graphical desktop environment, giving me a clean and simple interface without weighing down the hardware. Together, they turn the Chromebox into a fully usable server that I can control anytime, without ever needing to attach peripherals.</p><pre>sudo apt update<br>sudo apt install xfce4 xfce4-goodies xrdp -y<br>sudo systemctl enable xrdp<br>sudo systemctl restart xrdp</pre><p>When you first log in through XRDP, you’ll notice it asks you to pick a session type. The list usually shows options like Xorg, Xvnc, neutrinordp-any, and vnc-any. Each one is just a different way of handling the remote desktop session:</p><ul><li><strong>Xorg</strong> — The most common choice. It connects you directly to the Linux graphical session using the Xorg display server.</li><li><strong>Xvnc</strong> — Uses a built-in VNC server. This can be useful if you want to share sessions or connect with other VNC clients.</li><li><strong>neutrinordp-any</strong> — An experimental backend for RDP that’s lighter but not as widely used.</li><li><strong>vnc-any</strong> — Lets you connect to an existing VNC server if you have one running on your machine.</li></ul><p>For most people (myself included), Xorg is the easiest and most reliable option to pick; it just works out of the box.</p><p><strong>Note:</strong> sometimes you may hit an error saying <em>“Something has gone wrong. Please log out and try again.”</em> If that happens, it usually means XRDP doesn’t know to use XFCE yet. The fix is to edit the XRDP startup script:</p><pre>sudo nano /etc/xrdp/startwm.sh<br><br># Replace the following lines: <br># test -x /etc/X11/Xsession &amp;&amp; exec /etc/X11/Xsession<br># exec /bin/sh /etc/X11/Xsession<br><br># with...<br># startxfce4<br># then restart XRDP<br><br>sudo systemctl restart xrdp<br><br># This ensures XRDP always launches XFCE instead of <br># falling back to a broken default session<br><br># Note your IP Address:<br>ip a</pre><p>And that’s it! My little Chromebox experiment turned Ubuntu Server setup. What started as a second-hand find on Facebook Marketplace is now a handy headless server I can tinker with, connect to remotely, and keep running without a hitch. If you’ve got an old device lying around, don’t be afraid to give it a second life; you might be surprised how far a simple setup can go. Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cd4d0aca710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mamba-SSM + GPU Support on WSL]]></title>
            <link>https://mikovilla.medium.com/mamba-ssm-gpu-support-on-wsl-f3504354079f?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3504354079f</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[mamba-ssm]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 19:00:27 GMT</pubDate>
            <atom:updated>2025-08-30T19:00:27.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Sb6YoThioA9_Vkg" /><figcaption>Photo by <a href="https://unsplash.com/@glencarrie?utm_source=medium&amp;utm_medium=referral">Glen Carrie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I decided to start writing this because I’ve been wanting to dive into sentiment analysis,<strong> </strong>but with a twist. Instead of the usual deep learning or off-the-shelf NLP libraries, I’m curious about trying it with <strong>State Space Models (SSM)</strong>. It’s not the most common choice for sentiment analysis (which is exactly why it caught my interest), and I thought it would be fun to document the whole journey.</p><p>Before jumping into getting the Mamba-SSM up and running on WSL, let’s make sure we’ve got the basics covered. Nothing too fancy, just a few things you’ll want ready, so Mamba runs smoothly on WSL.</p><h3>Requirements</h3><ul><li><a href="https://learn.microsoft.com/en-us/windows/wsl/install">WSL2</a></li><li>NVIDIA GPU + drivers that support CUDA 12.x (for Blackwell GPU)</li><li>An internet connection (since everything is pulled from online repos)</li></ul><h3>My Setup</h3><ul><li>OS: Windows 11 V24H2</li><li>WSL Linux Distro: Ubuntu 22.04</li><li>GPU: Nvidia RTX 5070 Ti</li></ul><h3>Miniconda</h3><p>To keep things lightweight, we’ll use <strong>Miniconda</strong> instead of the full Anaconda distribution. Miniconda gives you the essentials for managing environments and packages without pulling in a ton of extras you might not need. Once it’s installed, we’ll be able to add Mamba on top of it.</p><pre># Update your system, and install a few helpful tools<br>sudo apt update<br>sudo apt install -y curl bzip2 git build-essential<br><br># Download the latest Miniconda installer<br>curl -L -o \ <br>Miniconda3.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh<br><br># To temporarily let you start using conda right away without restarting your terminal<br>eval &quot;$($HOME/miniconda/bin/conda shell.bash hook)&quot;<br># To make conda automatically initialized and ready to use<br>conda init bash<br>exec bash<br><br># Optional: Create a new environment dedicated to this project<br># We will need Python 3.12 for Mamba 2.2.5<br>conda create -n ssm-nlp python=3.12<br>conda activate ssm-nlp<br># Optional: install a couple of helpful packages inside the environment:<br>conda install numpy pandas<br><br># Install JupyterLab and/or install the class Jupyter Notebook<br>conda install -c conda-forge jupyterlab<br>conda install -c conda-forge notebook <br><br># Launch JupyterLab<br>jupyter lab<br># Or<br># jupyter notebook</pre><h3>GPU Support on WSL</h3><p>One of the biggest perks of using WSL is that you can tap into your GPU directly from Linux. This is especially handy for deep learning work. Training models on a CPU alone can feel like watching paint dry. To get the most out of PyTorch, we’ll set it up with <strong>CUDA 12.8</strong> so it can talk to your GPU, and we’ll also install nvcc, the CUDA compiler, in case you want to build or experiment with custom CUDA code later on.</p><pre># Update your system and install GNU Privacy Guard for encryption and verifying software signatures<br>sudo apt update<br>sudo apt install -y wget gnupg<br><br># Download and install CUDA keyring package<br>wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb<br>sudo dpkg -i cuda-keyring_1.1-1_all.deb<br><br># Install CUDA toolkit 12.8<br>sudo apt install cuda-toolkit-12-8<br><br># Add the following to environment variables: <br># Points to the root of your CUDA Toolkit installation.<br>export CUDA_HOME=/usr/local/cuda-12.8<br># Add bin to run the command `nvcc`<br>export PATH=&quot;$CUDA_HOME/bin:$PATH&quot;<br># Points to CUDA&#39;s shared libraries<br>export LD_LIBRARY_PATH=&quot;$CUDA_HOME/lib64:${LD_LIBRARY_PATH:-}&quot;<br><br># remove conda-installed torch, if any<br>conda remove -y pytorch torchvision torchaudio pytorch-cuda || true<br># remove pip-installed torch, to avoid mixing<br>pip uninstall -y torch torchvision torchaudio || true<br><br># Install PyTorch built for CUDA 12.8<br>pip install --upgrade --index-url https://download.pytorch.org/whl/cu128 \<br>  torch torchvision torchaudio<br><br># Installs the GNU C and C++ compilers, version 11 to build CUDA kernels<br>sudo apt install -y gcc-11 g++-11<br>export CC=gcc-11<br>export CXX=g++-11<br># sm_120 compute capability for Blackwell GPU<br>export TORCH_CUDA_ARCH_LIST=&quot;12.8&quot;</pre><h3>Mamba-SSM</h3><blockquote><em>Mamba is a new state space model architecture showing promising performance on information-dense data such as language modeling, where previous subquadratic models fall short of Transformers. It is based on the line of progress on </em><a href="https://github.com/state-spaces/s4"><em>structured state space models</em></a><em>, with an efficient hardware-aware design and implementation in the spirit of </em><a href="https://github.com/Dao-AILab/flash-attention"><em>FlashAttention</em></a><em>.</em></blockquote><blockquote><em>— </em><a href="https://github.com/albertfgu"><em>albertfgu (Albert Gu)</em></a></blockquote><pre><br># Remove any currently installed mamba-ssm<br># pip uninstall -y mamba-ssm<br># forces a fresh download and rebuild<br># pip cache purge 2&gt;/dev/null || true<br><br># Install mamba-ssm<br>python -m pip install --no-build-isolation -v \<br>  &quot;mamba-ssm @ git+https://github.com/state-spaces/mamba.git&quot;<br><br># Check if mamba-ssm is successfully installed<br>pip show mamba-ssm</pre><p>After installing the mamba-ssm, a simple way to test it is to try running a <strong>tiny model forward pass</strong>. That will confirm the library:</p><ul><li>works,</li><li>is linked to PyTorch,</li><li>and can use your GPU if available.</li></ul><pre>import torch<br>from mamba_ssm import Mamba<br><br># Create a dummy Mamba model<br>model = Mamba(<br>    d_model=16,   # hidden size<br>    d_state=16,   # state size<br>    d_conv=4,     # convolution size<br>    expand=2      # expansion factor<br>)<br><br># Move model to GPU if available<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>model = model.to(device)<br><br># Dummy input: batch of 2 sequences, each length 8, embedding dim = 16<br>x = torch.randn(2, 8, 16).to(device)<br><br># Forward pass<br>y = model(x)<br><br>print(&quot;Torch:&quot;, torch.__version__, &quot;CUDA:&quot;, torch.version.cuda)<br>print(&quot;CUDA available?&quot;, torch.cuda.is_available())<br>print(&quot;Torch path:&quot;, torch.__file__)<br>print(&quot;Input shape:&quot;, x.shape)<br>print(&quot;Output shape:&quot;, y.shape)</pre><p>The result should look like this:</p><pre>Torch: 2.8.0+cu128 CUDA: 12.8<br>CUDA available? True<br>Torch path: /home/miko/miniconda/envs/ssm-nlp/lib/python3.12/site-packages/torch/__init__.py<br>Input shape: torch.Size([2, 8, 16])<br>Output shape: torch.Size([2, 8, 16])</pre><h3>Conclusion</h3><p>Getting Mamba-SSM + GPU Support on WSL took a few extra steps, but now the setup is solid: Conda (or Miniconda) for managing environments, Mamba-SSM installed from source, and CUDA + PyTorch working hand-in-hand on the GPU. With this foundation in place, I can finally dive into experimenting with State Space Models for sentiment analysis, which is the whole reason I started this journey. Hopefully, this walkthrough helps anyone else trying to explore Mamba-SSM on WSL without getting stuck in setup headaches.</p><h3>References</h3><ul><li>Albert Gu &amp; Tri Dao. <em>Mamba: Linear-Time Sequence Modeling with Selective State Spaces</em>. arXiv, 2023. arXiv:2312.00752</li><li>Tri Dao &amp; Albert Gu. <em>Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality</em>. ICML, 2024.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3504354079f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WSL2 in Windows Server]]></title>
            <link>https://mikovilla.medium.com/wsl2-in-windows-server-668e46e0a95d?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/668e46e0a95d</guid>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[windows-server]]></category>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[chromebox]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 16:31:13 GMT</pubDate>
            <atom:updated>2023-03-20T16:31:13.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/953/0*KLfNaRSMKmlp5oFa" /><figcaption><a href="https://ubuntu.com/wsl">WSL | Ubuntu</a></figcaption></figure><p>I’ve been really eager to build a homelab (or just a simple personal lab) for a few years now. And luckily, I saw a Chromebox listed at the Facebook Marketplace. It was flashed with UEFI bios and has a Windows 10 installed. I asked for more details like its hardware specs, warranty, and more. I haggled and bought it the next day.</p><p>Quick specs:</p><ul><li>i7 8550U</li><li>16GB (2 x 8GB) 2666mHz DDR4</li><li>128GB SSD</li></ul><p>I bought it for less than a hundred dollars, which was a great deal. I’ve been using this box, for more than a week now without any issues; aside from <a href="https://github.com/MrChromebox/firmware/issues/360">Asus Chromebox 3 HDMI no audio output · Issue #360 · MrChromebox/firmware · GitHub</a>. Anyway, I access it remotely and use remote audio, and I don’t have any intentions of plugging a display to it (except for the initial setup).</p><p>I tried setting up Windows Server 2019, but it just lasted for hours as it turned out that <a href="https://techcommunity.microsoft.com/t5/itops-talk-blog/wsl2-now-available-on-windows-server-2022/ba-p/3447570">WSL2 is only available in Windows Server 2022</a> (and I like WSL2). So, I set up Windows Server 2022 instead. It was smooth, until I was installing Ubuntu. I couldn’t make it work and ; I am getting an error:</p><blockquote>An error occurred during installation. Distribution Name: ‘Ubuntu’ Error Code: 0x8000ffff</blockquote><p>I am unsure if I was doing it incorrectly, but still got it working after following the steps below:</p><ol><li>Open PowerShell and run this command to download the distro: `Invoke-WebRequest -Uri {distroUrl} -OutFile {distro}.appx -UseBasicParsing`</li><li>Rename the appx file to zip: `Rename-Item .\{distro}.appx .\{distro}.zip`</li><li>Extract the zip: `Expand-Archive .\{distro}.zip .\{distro}`</li><li>Navigate to the distro folder, then run: `Add-AppxPackage .\{distro}.appx`</li></ol><p>Finally, after hours of figuring out how to set it up, I have successfully had it running. What a fun way to start my Homelab journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=668e46e0a95d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by step guide on how to setup LocalStack (S3) in a Windows machine]]></title>
            <link>https://mikovilla.medium.com/step-by-step-guide-on-how-to-setup-localstack-s3-in-a-windows-machine-a0303b5eb8ff?source=rss-82b370999035------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0303b5eb8ff</guid>
            <category><![CDATA[docker-in-wsl2]]></category>
            <category><![CDATA[localstack]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[wsl-2]]></category>
            <category><![CDATA[wsl]]></category>
            <dc:creator><![CDATA[Miko]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 16:34:05 GMT</pubDate>
            <atom:updated>2022-12-07T16:37:14.866Z</atom:updated>
            <content:encoded><![CDATA[<p>On this blog, I spun up Windows 10 virtual machine. And here are the things I needed to successfully setup S3 LocalStack in my windows machine:</p><ul><li>VMWare</li><li>Windows 10</li><li>WSL2</li><li>PowerShell</li><li>Docker Desktop</li><li>Visual Studio Code</li><li>Postman</li></ul><p><strong>VMWare Setup (optional)</strong></p><p>On your virtual machine settings, under Hardware &gt; Processors &gt; Virtualization Engine make sure that Virtualize Intel VT-x/EPT or AMD/V-RVI is checked.</p><p><strong>WSL Installation</strong></p><ol><li>Click start and search for appwiz.cpl , then hit Enter</li><li>On the side bar of the Control Panel. Click Turn Windows Features on or off</li><li>Check Windows Subsystem for Linux and Virtual Machine Platform then click OK</li><li>Restart your machine</li><li>You may also need to download and install Linux kernel update package for setting versions from WSL1 to WSL2, which can be found <a href="https://learn.microsoft.com/en-us/windows/wsl/install-manual#step-4---download-the-linux-kernel-update-package">here</a>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*SeLyrGQ4t0rKrIDUVB4liw.png" /><figcaption>Windows Features</figcaption></figure><p><strong>Verify WSL is running on your windows machine</strong></p><ol><li>Click start and search for Windows PowerShell, then hit Enter</li><li>On PowerShell type wsl --list --online and hit Enter</li><li>If successful, it will show a list of valid distributions that you can install</li><li>Install an Ubuntu distribution by running wsl --install -d Ubuntu</li><li>Now, type wsl -l -v and check the Ubuntu version</li><li>If version is <strong>1 </strong>then run wsl --set-version Ubuntu 2</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*t1kZF_jw3i991NyQO-Qgvg.png" /><figcaption>Ubuntu WSL running on Version 2</figcaption></figure><p><strong>Docker Installation</strong></p><ol><li>Download and install <a href="https://www.docker.com/products/docker-desktop/">Docker</a></li><li>Make sure that the configuration is set to Use WSL2 instead of Hyper-V recommended</li><li>Restart your machine</li><li>Accept the Docker Subscription Service Agreement</li><li>Open Docker Desktop and sign in</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*QUMO63Xp7kB7AFem2T9yow.png" /><figcaption>Successful docker-desktop installation running on WSL2 engine</figcaption></figure><p><strong>Running Localstack via docker-compose</strong></p><ol><li>Open VSCode and create a <em>docker-compose.yml </em>with contents from below</li><li>Open new terminal and type docker-compose up and hit Enter.</li><li>Once the setup is finish, open up a browser and go to <a href="http://localhost:4566/">http://localhost:4566</a> (if it shows a blank page and doesn’t show any errors, it means the setup is successful)</li></ol><pre>version: &#39;3.8&#39;<br>services:<br>  localstack:<br>    image: localstack/localstack<br>    ports:<br>      - &#39;4566:4566&#39;<br>    environment:<br>      - SERVICES=s3<br>      - DEBUG=1<br>      - DATA_DIR=/var/lib/localstack/data<br>      - DOCKER_HOST=unix:///var/run/docker.sock<br>    volumes:<br>      - &#39;${TMPDIR:-/var/lib/localstack}:/var/lib/localstack&#39;<br>      - &#39;/var/run/docker.sock:/var/run/docker.sock&#39;</pre><p><strong>Connecting to LocalStack Container</strong></p><ol><li>Open Windows PowerShell</li><li>On PowerShell, check active containers by running docker container ls or docker ps</li><li>Take note of the localstack name you are trying to connect into</li><li>Then type docker exec -it localstack-localstack-1 /bin/bash</li></ol><p><strong>Configure AWS in LocalStack and Setting up S3 Bucket</strong></p><ol><li>While connected to LocalStack container. (Still on Windows PowerShell) Type aws configure</li><li>On configuration, put values to Access Key Id and Secret Access Key</li><li>To create a bucket, type aws s3 --endpoint-url=http://localhost:4566 mb s3://test (where <em>test</em> is the name of the bucket), then hit Enter</li><li>Verify the bucket created by running aws s3 --endpoint-url=http://localhost:4566 ls</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZS9pm0QOBtyUpO8TSMzS7A.png" /><figcaption>Localstack container connection</figcaption></figure><p><strong>Creating objects via Postman</strong></p><ol><li>Create a new Postman request</li><li>On the authorization, select AWS Signature as type. Then fill in the fields with values from your aws configuration</li><li>Select PUT as the HttpMethod</li><li>And on the URL, type http://localhost:4566/test/helloworld.txt (where <em>test</em> is the name of the bucket, and <em>helloworld.txt </em>is the name of the file we are creating).</li><li>Under <strong>Body</strong>, choose Raw and Text , and type anything under the content box</li><li>Hit Send. If successful, you should receive HTTP 200</li><li>Change the HttpMethod to GET</li><li>Hit Send. If successful you should receive whatever content you have submitted as the response.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBa9XtEtk3Wml840QLuOLg.png" /><figcaption>Postman Authorization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhxh1slzBRo-eIiGws0rrA.png" /><figcaption>Payload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwGoGiN3EoSHa04pGOHkrA.png" /><figcaption>HTTP GET</figcaption></figure><p>End.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0303b5eb8ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>