<?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 Merabet Asma on Medium]]></title>
        <description><![CDATA[Stories by Merabet Asma on Medium]]></description>
        <link>https://medium.com/@merabet.asma?source=rss-7f1b94387c80------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P--aDkvq87HGG4oFUECbaQ.jpeg</url>
            <title>Stories by Merabet Asma on Medium</title>
            <link>https://medium.com/@merabet.asma?source=rss-7f1b94387c80------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:01:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@merabet.asma/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[Training a Colon Cancer Histology Model on Cloud TPU with Native PyTorch (and the BatchNorm Bug I…]]></title>
            <link>https://medium.com/@merabet.asma/training-a-colon-cancer-histology-model-on-cloud-tpu-with-native-pytorch-and-the-batchnorm-bug-i-ba6c0be36073?source=rss-7f1b94387c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba6c0be36073</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tpu]]></category>
            <dc:creator><![CDATA[Merabet Asma]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 11:27:10 GMT</pubDate>
            <atom:updated>2026-11-24T11:27:10.837Z</atom:updated>
            <content:encoded><![CDATA[<h3>Training a Colon Cancer Histology Model on Cloud TPU with Native PyTorch (and the BatchNorm Bug I Found)</h3><h4>I fine-tuned a colon cancer histology classifier on a free Google Colab TPU using plain PyTorch. It reached <strong>96.9% validation and 93.3% test accuracy</strong>, and torch.compile made each training step <strong>1.86× faster</strong>. Along the way, I found a BatchNorm bug that silently broke evaluation, and a simple way to detect and work around it.</h4><h3>Why this project</h3><p>My PhD work is on explainable AI for colon cancer diagnosis. In medical imaging, a model that is accurate but unexplained is hard to trust. A pathologist needs to see <em>where</em> the model looked, not just what it predicted.</p><p>TorchTPU, released as open source by Google and the PyTorch team, makes Cloud TPUs behave like a standard PyTorch device. You write torch.device(&quot;tpu&quot;), and eager mode, torch.compile and autograd hooks work as you expect. I wanted to test that promise on a real medical-imaging workflow: training, timing, evaluation and Grad-CAM explanations.</p><p>This post walks through the full notebook. You can run it yourself for free on Colab.</p><h3>Setup: one line of TPU code</h3><p>In Colab, choose <strong>Runtime → Change runtime type → TPU</strong>, then install TorchTPU:</p><pre>pip install torch_tpu medmnist</pre><p>The only TPU-specific line in the whole notebook is the device:</p><pre>import torch<br>import torch_tpu  # registers the &quot;tpu&quot; device<br><br>device = torch.device(&quot;tpu&quot;)<br>x = torch.randn(4, 4, device=device)<br>print(torch.matmul(x, torch.ones(4, 4, device=device)).cpu())</pre><p>On Colab, TorchTPU printed Successfully renamed PrivateUse1 backend to &#39;tpu&#39;, and the tensor ran on tpu:0. Everything after this is the same PyTorch code you would write for a GPU.</p><h3>Data and model</h3><p>I used <strong>PathMNIST</strong> from MedMNIST v2: H&amp;E-stained colorectal tissue tiles in 9 classes, from adipose and mucus to colorectal adenocarcinoma epithelium. It is derived from the NCT-CRC-HE-100K dataset. The splits are 89,996 training, 10,004 validation and 7,180 test images. The test split comes from a different clinical centre (CRC-VAL-HE-7K), so it also measures how well the model generalises.</p><p>The model is an ImageNet-pretrained <strong>ResNet-18</strong> from torchvision, with a new 9-class head, trained with AdamW at a learning rate of 1e-3:</p><pre>m = torchvision.models.resnet18(weights=&quot;IMAGENET1K_V1&quot;)<br>m.fc = nn.Linear(m.fc.in_features, 9)<br>model = m.to(device)   # same code as on GPU</pre><p>One TPU habit matters from the start: <strong>keep tensor shapes static</strong>. The XLA compiler builds a program for each input shape it sees, so a smaller last batch triggers a recompilation. A fixed batch size of 128 with drop_last=True keeps every step identical:</p><pre>loader = DataLoader(train_ds, batch_size=128, shuffle=True, drop_last=True, num_workers=2)</pre><p>I used 64×64 images to keep the free Colab run short.</p><h3>Eager mode vs torch.compile: 1.86× faster steps</h3><p>TorchTPU runs <strong>eagerly by default</strong>, like any PyTorch device, which makes debugging easy. For speed, torch.compile captures the model as a graph and compiles it for the TPU:</p><pre>cmodel = torch.compile(model, backend=&quot;tpu&quot;)</pre><p>The compiled model shares its weights with model, so training just continues. I trained 300 steps in each mode.</p><p>Timing needs care. TPU work is asynchronous, so a timer around opt.step() only measures how fast Python queues work. I call loss.item() inside the timed region to force a sync, and I skip the first 10 steps, which include compilation:</p><pre>t0 = time.perf_counter()<br>opt.zero_grad(set_to_none=True)<br>loss = loss_fn(step_model(xb), yb)<br>loss.backward()<br>opt.step()<br>l = loss.item()                    # sync point -&gt; honest timing<br>times.append(time.perf_counter() - t0)</pre><p>Results on a Colab TPU, batch size 128:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkipGPbun4R8STx-LKWg5w.png" /></figure><p>That is a <strong>1.86× speed-up</strong>. In my first run, compilation took about 22 s on the first step. A second run of the same notebook in the same session started at 17 ms, because the compiled program was cached. An earlier run measured 1.72×, so expect some variation between sessions.</p><h3>The bug: 96% training accuracy, 11% evaluation accuracy</h3><p>After training, the model reached <strong>95.8% training accuracy</strong>. Validation accuracy in eval mode was <strong>10.6%</strong>, which is chance for 9 classes. The model predicted “background” for every single test tile.</p><p>The gap pointed at one layer type. In model.train(), BatchNorm normalises with the statistics of the current batch. In model.eval(), it uses its stored <strong>running statistics</strong> (running_mean and running_var), which are updated during training. If those buffers are wrong, inference breaks even when the weights are good.</p><p>I added a check that compares the same weights on TPU and on CPU, and inspects the buffers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqM-XgYJv4j9ruPc3K3igw.png" /></figure><p>Three conclusions follow. The CPU copy also failed, so the stored statistics were wrong, not the TPU’s eval kernel. Recalibrating on TPU left the buffers at their reset values of 0 and 1, so <strong>the TPU forward pass in train mode did not write the running statistics back</strong>. And recalibrating on CPU fixed everything, so the trained weights were fine all along.</p><p>The workaround is to recompute the BatchNorm statistics with forward passes only. No gradients or retraining are needed:</p><pre>@torch.no_grad()<br>def recalibrate_bn(m, dev, n_batches=100):<br>    for b in m.modules():<br>        if isinstance(b, nn.BatchNorm2d):<br>            b.reset_running_stats()<br>            b.momentum = None          # cumulative average<br>    m.train()<br>    for i, (xb, _) in enumerate(train_dl):<br>        if i &gt;= n_batches: break<br>        m(xb.to(dev))<br>    m.eval()</pre><p>The notebook runs this on TPU first. If accuracy is still wrong, it copies the weights to CPU, recalibrates there, and evaluates on CPU. In my run, training ran on TPU, and evaluation and Grad-CAM ran on CPU.</p><p>I ran TorchTPU on torch 2.14.1 and am reporting the issue to the TorchTPU team. The lesson applies to any new backend: <strong>high training accuracy does not prove eval mode works</strong>. Check eval-mode accuracy early, and compare against a CPU copy of the weights.</p><h3>Results: 96.9% validation, 93.3% test</h3><p>With recalibrated BatchNorm statistics, the model reached <strong>96.9% validation accuracy</strong> and <strong>93.3% test accuracy</strong>, with a macro F1 of 0.911. Test accuracy is lower because the test tiles come from a different clinical centre.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjJ9pE4a-2El53NI5CZYNQ.png" /></figure><p><em>Cancer-associated stroma is the hard class, with 61.7% recall. Smooth muscle and debris have the lowest precision (0.82 and 0.81), which suggests that is where many missed stroma tiles went. These tissues look alike at 64×64 pixels, so larger images are the first thing I would try.</em></p><h3>Explainability: Grad-CAM in plain PyTorch</h3><h3>What I learned</h3><ul><li><strong>Porting really is one line.</strong> torchvision models, DataLoader, AdamW and autograd hooks ran on the TPU with only torch.device(&quot;tpu&quot;) changed.</li><li><strong>torch.compile pays off quickly.</strong> After a one-time compilation, training steps were 1.86× faster on a free Colab TPU.</li><li><strong>Keep shapes static.</strong> A fixed batch size with drop_last=True avoids recompilation.</li><li><strong>Time honestly.</strong> Sync with .item() and skip the warm-up steps, or you measure Python, not the TPU.</li><li><strong>Check eval mode early on a new backend.</strong> Training accuracy hid a BatchNorm problem that made evaluation useless. A two-line comparison against a CPU copy found it.</li></ul><p>Next, I want to try 224×224 images, bfloat16, Vision Transformer backbones from Hugging Face, and more explanation methods such as LIME and SHAP.</p><h3>Try it yourself</h3><ul><li>Colab notebook: <a href="https://colab.research.google.com/drive/1AkodfmaoxT9yJMDuTyCXhMv2fq6WbUPn#scrollTo=b5a374df">https://colab.research.google.com/drive/1AkodfmaoxT9yJMDuTyCXhMv2fq6WbUPn#scrollTo=b5a374df</a></li><li>TorchTPU: <a href="https://docs.cloud.google.com/tpu/docs/colabs">Get started with PyTorch on Cloud TPU</a></li></ul><p>This project was built for the <strong>#TorchTPUSprint</strong>, organised by Google for AI GDEs and TPU Builders.</p><p><strong>Dataset citations.</strong> Yang, J. et al. <em>MedMNIST v2: A large-scale lightweight benchmark for 2D and 3D biomedical image classification.</em> Scientific Data, 2023. Kather, J.N. et al. <em>Predicting survival from colorectal cancer histology slides using deep learning.</em> PLOS Medicine, 2019.</p><p><em>Dr. Asma Merabet is a Google Developer Expert in AI and Lead Organizer of GDG Sétif. Her research focuses on explainable AI for medical imaging.</em></p><p>Tags: PyTorch, TPU, Google Cloud, Explainable AI, Medical Imaging</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba6c0be36073" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Too Little Data to Trustworthy AI: Few‑Shot Learning and Explainability for Colon Cancer]]></title>
            <link>https://medium.com/@merabet.asma/too-little-data-to-trustworthy-ai-few-shot-learning-and-explainability-for-colon-cancer-345d0946a8e5?source=rss-7f1b94387c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/345d0946a8e5</guid>
            <category><![CDATA[health]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[healthcare]]></category>
            <dc:creator><![CDATA[Merabet Asma]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 15:59:25 GMT</pubDate>
            <atom:updated>2025-11-29T16:01:41.449Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How a tiny dataset, a prototypical network, and pathologist‑validated explanations came together to build a more transparent colon cancer classifier.</em></p><blockquote>I am a PhD researcher working on AI for colon cancer histopathology, focusing on few‑shot learning and explainable AI with clinicians in the loop.​</blockquote><p>When starting this project, the goal was not “beat state‑of‑the‑art on some benchmark.” The goal was much more basic and much more clinical: can an AI system help pathologists detect colon cancer when labeled data are scarce, and can it explain its decisions in a way that doctors actually trust?​</p><p>A survey of colon‑cancer AI papers quickly revealed two persistent gaps. First, many models assume thousands of labeled slides per class, which is unrealistic in real hospitals where annotation time is expensive. Second, even when accuracy is high, explanations are often missing or purely technical, leaving clinicians unsure why one model is reliable and another is not.​</p><h3>Why colon histopathology is hard for AI</h3><p>Colon cancer is routinely diagnosed from histopathology slides, where a pathologist inspects tiny tissue regions under the microscope to distinguish benign from malignant patterns. These images are complex: subtle changes in glands, nuclei, and stroma can mean the difference between early and advanced disease.​</p><p>Public datasets like LC25000 provide valuable benchmarks, but they are small and simplified compared to true clinical practice, and overfitting to them can give a false sense of security. The core challenge is to train models that learn meaningful patterns from limited data while still generalizing to external collections such as EBHI.​</p><h3>Few-shot learning: doing more with very few labels</h3><p>Instead of scaling up the dataset, the project turned to few‑shot learning: teach a model to recognize new classes from only a handful of labeled examples. The idea is simple but powerful:​</p><ul><li>Use a ConvNeXt‑Tiny backbone to extract rich features from colon tissue tiles.​</li><li>Wrap it in a Prototypical Network that learns a “prototype” representation for each class (e.g., benign vs malignant) from a small support set.​</li></ul><p>At inference time, the model compares a new image to these prototypes and assigns the class with the closest feature representation, which naturally fits few‑shot scenarios where only a few labeled tiles per class are available. In practice, this framework achieved very high accuracy on small colon datasets without requiring the massive annotation effort that standard deep learning pipelines usually demand.​</p><h3>Bringing the model into the clinic: explainable AI</h3><p>High accuracy was not enough. When preliminary results were shown to clinicians, their feedback was clear: they wanted to understand <em>why</em> the system made each decision, not just whether the prediction was correct. That pushed the project toward integrating explainable AI directly into the pipeline.​</p><p>Two complementary techniques were used:</p><ul><li>Grad‑CAM to highlight the most influential regions of the image for the model’s decision.</li><li>LIME to perturb local regions and show how they affected the predicted class.​</li></ul><p>For each prediction, the system generated overlays that pathologists could inspect to see whether the model focused on clinically relevant structures such as tumor glands, dysplastic epithelium, or benign mucosa.​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHOp2s4Gujs9UN0VEYlvFQ.png" /></figure><h3>Human validation: closing the loop with pathologists</h3><p>A crucial step was inviting a pathologist to systematically review these explanation maps. Rather than treating Grad‑CAM and LIME as purely technical visualizations, the project used them as a communication layer between the model and the clinician.​</p><p>The expert examined multiple cases, rating whether the highlighted regions matched the tissue areas they would inspect in routine practice. In many positive examples, the explanations aligned well with malignant glandular structures or suspicious regions, which increased confidence in the model’s behaviour. In cases where the model misclassified or focused on irrelevant artefacts, those explanations revealed concrete failure modes, guiding future improvements and dataset curation.​</p><h3>Testing robustness: external generalization on EBHI</h3><p>To check whether the model was truly learning colon cancer morphology and not just memorizing one dataset, the few‑shot system was evaluated on an external dataset (EBHI) with different staining and acquisition conditions.​</p><p>Despite being trained on limited data, the model maintained strong performance when transferred to this new set, reaching around 90% accuracy on EBHI while preserving interpretable Grad‑CAM and LIME maps. This external validation suggested that the combination of prototypical few‑shot learning and multi‑technique explainability can yield models that are both data‑efficient and reasonably robust across domains.​</p><p>Of course, the work is not finished. The model has been tested on limited public datasets and a single external collection, so the next step is to validate it across more hospitals and scanners, and to build an agentic layer that can monitor its own uncertainty, select hard new cases, and ask pathologists for labels to keep improving over time.</p><h3>What this means for AI engineers and healthcare</h3><p>For ML engineers, this work shows that advanced architectures such as ConvNeXt can be combined with metric‑based few‑shot learning to deliver state‑of‑the‑art colon cancer classification even in low‑data regimes. Instead of collecting thousands of new labels, careful design of few‑shot episodes, support/query splits, and prototype learning can unlock strong performance.​</p><p>For AI in healthcare practitioners, the key message is that interpretability cannot be an afterthought. Validating Grad‑CAM and LIME with real pathologists transformed explanations from “nice heatmaps” into clinically meaningful tools that reveal when to trust the system and when to be cautious.​</p><h3>Looking ahead: from static models to agentic systems</h3><p>The current paper focuses on a <em>static</em> few‑shot model with robust explanations and external validation. The natural next step is to make the system <em>agentic</em>: let it monitor its own uncertainty on new hospitals’ data, select the most informative tiles, and ask for labels from clinicians to continuously improve itself.​</p><p>Such an agentic layer, combined with few‑shot learning and XAI, could turn a one‑time model into a long‑term collaborator that adapts to new scanners, staining variations, and rare colon cancer subtypes while keeping clinicians in the loop through transparent visual explanations.​</p><h3>Further reading</h3><p><a href="https://www.sciencedirect.com/science/article/pii/S1386505625003843">https://www.sciencedirect.com/science/article/pii/S1386505625003843</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=345d0946a8e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>