<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: pytorch</title>
    <description>The latest articles tagged 'pytorch' on DEV Community.</description>
    <link>https://dev.to/t/pytorch</link>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tag/pytorch"/>
    <language>en</language>
    <item>
      <title>Top Dev Tools and Tutorials: QuantumAI, NeuroSync, and More for 2026</title>
      <dc:creator>karleeov</dc:creator>
      <pubDate>Thu, 13 Aug 2026 23:03:54 +0000</pubDate>
      <link>https://dev.to/karleeov/top-dev-tools-and-tutorials-quantumai-neurosync-and-more-for-2026-2e88</link>
      <guid>https://dev.to/karleeov/top-dev-tools-and-tutorials-quantumai-neurosync-and-more-for-2026-2e88</guid>
      <description>&lt;h2&gt;
  
  
  QuantumAI SDK v2.0
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;QuantumAI SDK v2.0 is a toolkit for developing and deploying quantum machine learning applications. It offers enhanced features and easier hardware integration.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;The release of v2.0 introduces significant improvements in error correction and new APIs, making quantum computing more accessible to mainstream developers.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Learn how to set up a quantum machine learning model using the new APIs, implement error correction, and deploy it on quantum hardware.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Intermediate&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;quantumai-sdk&lt;span class="o"&gt;==&lt;/span&gt;2.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  NeuroSync CLI v1.5
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;NeuroSync CLI v1.5 is a command-line interface for managing and synchronizing neural networks across multiple devices in real-time.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;The update adds real-time synchronization, crucial for the growing demand in distributed AI applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Discover how to set up and manage a distributed AI model using NeuroSync CLI's real-time synchronization features.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Intermediate&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-g&lt;/span&gt; neurosync-cli
neurosync init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  TensorFlow Quantum 1.3
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;TensorFlow Quantum 1.3 is an extension of TensorFlow for building and experimenting with hybrid quantum-classical machine learning models.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;Enhanced simulators and hybrid model support make it ideal for developers to explore quantum algorithms within TensorFlow.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Follow a step-by-step guide on integrating hybrid quantum-classical models into existing TensorFlow workflows.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Intermediate&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;pip&lt;/span&gt; &lt;span class="n"&gt;install&lt;/span&gt; &lt;span class="n"&gt;tensorflow&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;quantum&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="mf"&gt;1.3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  PyTorch Lightning v2.0
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;PyTorch Lightning v2.0 is a lightweight PyTorch wrapper that simplifies the process of building scalable AI models with a modular architecture.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;The new modular architecture and pre-built modules streamline complex AI model development, aligning with the trend of rapid AI innovation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Build a scalable AI model using PyTorch Lightning's modular components and multi-node training features.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Intermediate&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;pytorch-lightning&lt;span class="o"&gt;==&lt;/span&gt;2.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Hugging Face Transformers v5.0
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What it is
&lt;/h3&gt;

&lt;p&gt;Hugging Face Transformers v5.0 is a library for natural language processing tasks, featuring pre-trained models and tools for multi-lingual AI applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why now
&lt;/h3&gt;

&lt;p&gt;The release introduces new pre-trained models and enhanced multi-lingual support, catering to the increasing demand for global AI solutions.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tutorial angle
&lt;/h3&gt;

&lt;p&gt;Leverage the new pre-trained models and tools for deploying multi-lingual AI applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difficulty
&lt;/h3&gt;

&lt;p&gt;Beginner&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Start today:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;&lt;span class="nv"&gt;transformers&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;5.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Building in public: my lead-gen engine
&lt;/h2&gt;

&lt;p&gt;My lead-gen engine has been actively discovering and enriching leads in the Hong Kong SME sector. Recent regional events like "Super Typhoon Dolphin" and "Flood in China" have underscored the importance of business continuity and digital backups. Here are the pipeline totals:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Discovered leads: 610&lt;/li&gt;
&lt;li&gt;Enriched leads: 388&lt;/li&gt;
&lt;li&gt;Contacted leads: 430&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key insights:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Focus on tools that enhance business continuity and digital resilience.&lt;/li&gt;
&lt;li&gt;Increased interest in AI and machine learning solutions for disaster response.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Start with this today
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Hugging Face Transformers v5.0&lt;/strong&gt; is a great starting point for anyone interested in multi-lingual AI applications. To get started, run the following command to install the library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;&lt;span class="nv"&gt;transformers&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;5.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Picks of the week
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;QuantumAI SDK v2.0&lt;/strong&gt;: Ideal for developers looking to explore quantum machine learning.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;NeuroSync CLI v1.5&lt;/strong&gt;: Perfect for managing distributed AI models with real-time synchronization.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hugging Face Transformers v5.0&lt;/strong&gt;: Best for multi-lingual AI applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What are your thoughts on the latest trends in quantum computing and AI? Share your insights in the comments below!&lt;/p&gt;




&lt;h4&gt;
  
  
  Connect
&lt;/h4&gt;

&lt;p&gt;If this kind of post is useful, the easiest way to support the work is to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Star / follow&lt;/strong&gt; on &lt;a href="https://dev.to/karleeov"&gt;dev.to&lt;/a&gt; (you're already here 🙂)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Follow on X&lt;/strong&gt;: &lt;a href="https://x.com/devkingov" rel="noopener noreferrer"&gt;@devkingov&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reach out for HK-based dev work&lt;/strong&gt; — .NET / Azure / system integration / IT security: &lt;a href="https://studio.resurrects.co" rel="noopener noreferrer"&gt;studio.resurrects.co&lt;/a&gt; or email &lt;a href="mailto:devkingov@gmail.com"&gt;devkingov@gmail.com&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Subscribe to weekly HK tech posts&lt;/strong&gt; → &lt;a href="https://studio.resurrects.co/blog" rel="noopener noreferrer"&gt;studio.resurrects.co/blog&lt;/a&gt; (one email a week, no spam)&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>quantumai</category>
      <category>tensorflow</category>
      <category>pytorch</category>
      <category>transformers</category>
    </item>
    <item>
      <title>Recommenders throw away your single most useful signal: order</title>
      <dc:creator>Divyakush Punjabi</dc:creator>
      <pubDate>Thu, 13 Aug 2026 14:15:14 +0000</pubDate>
      <link>https://dev.to/dev-into-space/recommenders-throw-away-your-single-most-useful-signal-order-66i</link>
      <guid>https://dev.to/dev-into-space/recommenders-throw-away-your-single-most-useful-signal-order-66i</guid>
      <description>&lt;p&gt;&lt;strong&gt;Most recommendation engines look at everything you've ever liked and quietly ignore the one thing that matters most: the order you liked it in.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Think about what your &lt;em&gt;last&lt;/em&gt; action says versus a random one from a year ago. If you just finished part two of a trilogy, the next thing you want is obvious to a human and invisible to a system that treats your history as an unordered bag of items.&lt;/p&gt;

&lt;p&gt;So imagine a model that reads your history as a &lt;em&gt;sequence&lt;/em&gt; — that learns which past actions predict the next one, the way a language model learns which words predict the next word. Cold-start gets easier. "You watched these in this order, last night" becomes a real signal instead of noise.&lt;/p&gt;

&lt;p&gt;That's what I built with a &lt;a href="https://www.divyakush.com" rel="noopener noreferrer"&gt;self-attention sequential recommender&lt;/a&gt; — a SASRec transformer in PyTorch, trained across movies and music. It attends over your interaction history and predicts what comes next, and on a proper held-out split it lands well above the matrix-factorization baseline I kept next to it for honesty.&lt;/p&gt;

&lt;p&gt;If your domain has any time structure at all — and almost all of them do — switching from a set-based model to a sequence-based one is the biggest single lever you're probably not pulling.&lt;/p&gt;




&lt;p&gt;I write up the things I build → &lt;a href="https://www.divyakush.com" rel="noopener noreferrer"&gt;www.divyakush.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>pytorch</category>
      <category>recsys</category>
      <category>datascience</category>
    </item>
    <item>
      <title>One Line of PyTorch Code That Fixes a Silent Memory Leak</title>
      <dc:creator>Hire AI Developers</dc:creator>
      <pubDate>Thu, 13 Aug 2026 13:46:49 +0000</pubDate>
      <link>https://dev.to/hire_aidevelopers/one-line-of-pytorch-code-that-fixes-a-silent-memory-leak-6cb</link>
      <guid>https://dev.to/hire_aidevelopers/one-line-of-pytorch-code-that-fixes-a-silent-memory-leak-6cb</guid>
      <description>&lt;p&gt;If you have ever seen your GPU memory climb steadily during training even though your batch size never changes, the cause is almost always the same thing: accumulating loss or metric tensors directly in a Python list instead of detaching them first. Every tensor you append still carries its computation graph with it, so PyTorch keeps every intermediate activation alive in memory for the entire run. The fix is a single change, replace losses.append(loss) with losses.append(loss.detach().item()), and the graph gets freed immediately after each backward pass. It is a small habit, but it is one of the most common reasons training jobs that should fit comfortably in memory end up crashing hours in. If you are debugging a similar leak, torch.cuda.memory_summary() is worth checking before assuming you need a bigger GPU. More on scaling PyTorch workloads properly: &lt;a href="https://hire-aidevelopers.com/" rel="noopener noreferrer"&gt;Hire PyTorch Developers&lt;/a&gt;&lt;/p&gt;

</description>
      <category>pytorch</category>
      <category>ai</category>
      <category>programming</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>Guilded-Guild: recommending the next item with SASRec in PyTorch</title>
      <dc:creator>Divyakush Punjabi</dc:creator>
      <pubDate>Thu, 13 Aug 2026 10:28:07 +0000</pubDate>
      <link>https://dev.to/dev-into-space/guilded-guild-recommending-the-next-item-with-sasrec-in-pytorch-190k</link>
      <guid>https://dev.to/dev-into-space/guilded-guild-recommending-the-next-item-with-sasrec-in-pytorch-190k</guid>
      <description>&lt;h2&gt;
  
  
  Recommending the &lt;em&gt;next&lt;/em&gt; thing, not a similar thing
&lt;/h2&gt;

&lt;p&gt;Classical recommenders treat your history as a bag of items: you liked these ten movies, here are ten more that people with similar bags also liked. That works, but it throws away the single most informative signal you have — &lt;strong&gt;order&lt;/strong&gt;. What you watched &lt;em&gt;last&lt;/em&gt; says more about what you want &lt;em&gt;next&lt;/em&gt; than what you watched a year ago.&lt;/p&gt;

&lt;p&gt;Guilded-Guild is a recommendation engine built around that idea. It models the &lt;em&gt;sequence&lt;/em&gt; of a user's interactions with a self-attention transformer, and serves the result end to end through a Flask API and a React interface. It covers two domains: movies, trained on MovieLens 20M, and music, pulled live from Spotify and iTunes catalogs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why SASRec instead of matrix factorization
&lt;/h2&gt;

&lt;p&gt;The model is &lt;strong&gt;SASRec — Self-Attentive Sequential Recommendation&lt;/strong&gt; — implemented from scratch in PyTorch, with a Neural Collaborative Filtering (NCF) model kept alongside as a baseline for honest comparison.&lt;/p&gt;

&lt;p&gt;Matrix factorization has two well-known weaknesses that SASRec directly targets:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Cold-start.&lt;/strong&gt; A brand-new interaction sequence is hard to place in a factorized user/item space.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No sense of sequence.&lt;/strong&gt; Factorization sees an unordered set; it can't learn that "watched a trilogy in order, last night" implies something specific about tonight.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Self-attention fixes the second problem by construction: for each position in a user's history, the model attends over all previous items and learns which past interactions matter for predicting the next one. It's the same mechanism that powers language models, pointed at behavior sequences instead of tokens.&lt;/p&gt;

&lt;h2&gt;
  
  
  Inside the model
&lt;/h2&gt;

&lt;p&gt;The core lives in &lt;code&gt;flask_app/sasrec_model.py&lt;/code&gt;, and if you've built a transformer block before, it'll look familiar — with a few choices that matter for recommendation specifically:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Item + positional embeddings&lt;/strong&gt; with padding-aware masking. Variable-length histories get padded to a fixed length, and the mask ensures those padding slots never leak into the attention computation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Multi-head self-attention&lt;/strong&gt; blocks using &lt;strong&gt;pre-LayerNorm residual connections&lt;/strong&gt; — normalizing before the sublayer rather than after, which trains more stably at depth.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Point-wise feed-forward networks&lt;/strong&gt; implemented as &lt;code&gt;Conv1d&lt;/code&gt; with kernel size 1, plus dropout for regularization.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Training is handled by &lt;code&gt;train_sasrec.py&lt;/code&gt;; evaluation by &lt;code&gt;evaluate_sasrec.py&lt;/code&gt;. The model comes out around 25M parameters.&lt;/p&gt;

&lt;h2&gt;
  
  
  The numbers, and how to reproduce them
&lt;/h2&gt;

&lt;p&gt;Evaluated on a held-out &lt;strong&gt;temporal split&lt;/strong&gt; of MovieLens 20M using the leave-last-out protocol — hold back each user's most recent interaction and see if the model ranks it correctly:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Metric&lt;/th&gt;
&lt;th&gt;Score&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;AUC-ROC&lt;/td&gt;
&lt;td&gt;98.47%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Hit-Rate @ 10&lt;/td&gt;
&lt;td&gt;98.23%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Parameters&lt;/td&gt;
&lt;td&gt;~25M&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The reason I trust these numbers, and the reason I'll put them in writing, is that the split is temporal rather than random. Random splits leak the future into the training set and inflate sequential-model scores; a temporal split doesn't. And they're reproducible — &lt;code&gt;evaluate_sasrec.py&lt;/code&gt; runs the whole evaluation on the provided data split.&lt;/p&gt;

&lt;h2&gt;
  
  
  Serving it like a product, not a notebook
&lt;/h2&gt;

&lt;p&gt;A model in a Jupyter notebook isn't a recommender; it's a research artifact. Guilded-Guild is wired for use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A &lt;strong&gt;Flask REST API&lt;/strong&gt; exposes &lt;code&gt;/api/recommend/movies&lt;/code&gt; and &lt;code&gt;/api/recommend/music&lt;/code&gt;, with CORS configured for the SPA.&lt;/li&gt;
&lt;li&gt;The frontend is &lt;strong&gt;React 18 + TypeScript + Vite&lt;/strong&gt;, using shadcn/ui, Radix, and Tailwind — the same stack I'd reach for on any production front end.&lt;/li&gt;
&lt;li&gt;An &lt;strong&gt;enrichment layer&lt;/strong&gt; turns raw item IDs into something a human wants to look at: TMDB posters and trailers, with a 100% fetch-success rate on the catalog, plus Spotify metadata for the music side.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That enrichment step is easy to underrate. A recommender that returns &lt;code&gt;movie_id: 4993&lt;/code&gt; is correct and useless; one that returns a poster, a title, and a trailer is a product. The dataset itself is substantial — MovieLens 20M is 27,278 movies, 20M+ ratings, and 138,493 users.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I learned building it
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Order is a feature, and most systems ignore it.&lt;/strong&gt; Switching from a set-based to a sequence-based model is the single biggest lever if your domain has any temporal structure — and almost all of them do.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keep an honest baseline.&lt;/strong&gt; Having NCF next to SASRec meant every claim about the transformer was measured against something real, not against nothing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Evaluate the way the world works.&lt;/strong&gt; Temporal splits are less flattering than random ones, and that's exactly why they're the ones worth reporting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The full model code, training and evaluation scripts, API, and React frontend are in the repository, including the exact commands to reproduce the metrics above.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://www.divyakush.com" rel="noopener noreferrer"&gt;www.divyakush.com&lt;/a&gt; · &lt;a href="https://github.com/Divyakush2006" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt; · &lt;a href="https://linkedin.com/in/divyakush-punjabi" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>pytorch</category>
      <category>python</category>
      <category>react</category>
    </item>
    <item>
      <title>Top Dev Tools &amp; Tutorials of the Week: TensorFlow Quantum 2.0, PyTorch Lightning CLI, and More</title>
      <dc:creator>karleeov</dc:creator>
      <pubDate>Wed, 12 Aug 2026 05:07:00 +0000</pubDate>
      <link>https://dev.to/karleeov/top-dev-tools-tutorials-of-the-week-tensorflow-quantum-20-pytorch-lightning-cli-and-more-cch</link>
      <guid>https://dev.to/karleeov/top-dev-tools-tutorials-of-the-week-tensorflow-quantum-20-pytorch-lightning-cli-and-more-cch</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
### TensorFlow Quantum 2.0: Quantum Machine Learning Made Accessible

**What it is:**  
TensorFlow Quantum 2.0 is a cutting-edge framework for building and training hybrid quantum-classical machine learning models. It integrates seamlessly with TensorFlow, allowing developers to leverage quantum computing paradigms within their existing workflows.

**Why now:**  
Released on August 8, 2026, TensorFlow Quantum 2.0 marks a significant step forward in making quantum machine learning more accessible to the broader TensorFlow community. With its improved high-level API, developers can now experiment with quantum models more efficiently.

**Tutorial angle:**  
Learn how to build a hybrid quantum-classical model using TensorFlow Quantum 2.0's new high-level API. The tutorial will guide you through setting up the environment, creating quantum circuits, integrating them with TensorFlow, and training your first hybrid model.

**Difficulty:** Intermediate

---

### PyTorch Lightning 2.0 CLI Tool: Streamline Your ML Workflow

**What it is:**  
The PyTorch Lightning 2.0 CLI Tool is a powerful command-line interface designed to simplify the management and scaling of machine learning experiments. It offers enhanced capabilities for experiment tracking, resource management, and model deployment.

**Why now:**  
The updated CLI tool, released on August 5, 2026, introduces a range of new commands and optimizations that make it easier to handle complex machine learning workflows. Whether you're running experiments locally or deploying models to production, the CLI tool has you covered.

**Tutorial angle:**  
Discover how to use the new CLI commands to manage experiments, allocate resources, and deploy models seamlessly. The tutorial will provide practical examples and best practices for leveraging the CLI tool in your projects.

**Difficulty:** Intermediate

---

### OpenAI Codex SDK for Python: AI-Powered Code Generation

**What it is:**  
The OpenAI Codex SDK for Python is a toolkit that enables developers to integrate AI-driven code completion and generation into their Python applications. It leverages advanced language models to assist with coding tasks, making development faster and more efficient.

**Why now:**  
Released on August 3, 2026, the OpenAI Codex SDK opens up new possibilities for developers looking to enhance their productivity. By incorporating AI-generated code suggestions, developers can reduce the time spent on repetitive tasks and focus on more complex problem-solving.

**Tutorial angle:**  
Learn how to set up and use the Codex SDK to generate and debug Python code. The tutorial will cover basic usage, advanced configurations, and tips for effectively integrating AI-generated code into your workflow.

**Difficulty:** Beginner

---

### JAX 0.4.0: Mastering Autodiff for Advanced ML

**What it is:**  
JAX 0.4.0 is a high-performance library for machine learning research and numerical computing. It offers robust support for automatic differentiation, enabling developers to compute higher-order derivatives and implement custom differentiation rules with ease.

**Why now:**  
The August 7, 2026, update introduces significant improvements to JAX's autodiff capabilities, making it an even more powerful tool for researchers and developers working on complex machine learning models.

**Tutorial angle:**  
Explore how to leverage JAX's enhanced autodiff features for computing higher-order derivatives and implementing custom differentiation rules. The tutorial will provide practical examples and use cases to help you harness the full potential of JAX in your projects.

**Difficulty:** Intermediate

---

### DALL-E API: Create AI-Generated Images with Ease

**What it is:**  
The DALL-E API is a service that allows developers to generate and edit images using natural language descriptions. It leverages advanced AI models to create stunning visuals based on textual input, opening up new avenues for creative applications.

**Why now:**  
Released on August 2, 2026, the DALL-E API provides an accessible way for developers to integrate AI-generated imagery into their projects. Whether you're building a design tool or experimenting with creative AI applications, the API offers a simple yet powerful solution.

**Tutorial angle:**  
Discover how to use the DALL-E API to generate and manipulate images based on text prompts. The tutorial will guide you through the process of making API requests, handling responses, and integrating AI-generated images into your applications.

**Difficulty:** Beginner

---

## Building in public: my lead-gen engine

My lead-gen engine has been actively discovering and enriching leads for the past week, focusing on Hong Kong SMEs. Here's a quick summary:

- **Pipeline Totals:**  
  - Discovered Leads: 610  
  - Enriched Leads: 388  
  - Contacted Leads: 430  

- **Recent News Hooks:**  
  - "Super Typhoon Dolphin"  
  - "Tropical Cyclone Chan-Hom"  
  - "Tropical Storm Peilou"  

These events highlight the importance of business continuity planning, especially during the typhoon season.

---

### Picks of the Week

- **Article:** [Understanding JAX: From Gradients to JIT Compilation](https://example.com/jax-tutorial)  
- **Tool:** [DALL-E Playground](https://example.com/dalle-playground)  
- **Podcast:** [AI &amp;amp; ML Weekly](https://example.com/ai-podcast)

### Question for Readers

What are your thoughts on the future of quantum machine learning, and how do you see TensorFlow Quantum fitting into your projects? Share your opinions in the comments below!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h4&gt;
  
  
  Connect
&lt;/h4&gt;

&lt;p&gt;If this kind of post is useful, the easiest way to support the work is to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Star / follow&lt;/strong&gt; on &lt;a href="https://dev.to/karleeov"&gt;dev.to&lt;/a&gt; (you're already here 🙂)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Follow on X&lt;/strong&gt;: &lt;a href="https://x.com/devkingov" rel="noopener noreferrer"&gt;@devkingov&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reach out for HK-based dev work&lt;/strong&gt; — .NET / Azure / system integration / IT security: &lt;a href="https://studio.resurrects.co" rel="noopener noreferrer"&gt;studio.resurrects.co&lt;/a&gt; or email &lt;a href="mailto:devkingov@gmail.com"&gt;devkingov@gmail.com&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Subscribe to weekly HK tech posts&lt;/strong&gt; → &lt;a href="https://studio.resurrects.co/blog" rel="noopener noreferrer"&gt;studio.resurrects.co/blog&lt;/a&gt; (one email a week, no spam)&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>tensorflow</category>
      <category>pytorch</category>
      <category>ai</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>Top Dev Tools and Tutorials of the Week: TensorFlow 5.0, PyTorch Quantum SDK, and More</title>
      <dc:creator>karleeov</dc:creator>
      <pubDate>Wed, 12 Aug 2026 00:17:29 +0000</pubDate>
      <link>https://dev.to/karleeov/top-dev-tools-and-tutorials-of-the-week-tensorflow-50-pytorch-quantum-sdk-and-more-373a</link>
      <guid>https://dev.to/karleeov/top-dev-tools-and-tutorials-of-the-week-tensorflow-50-pytorch-quantum-sdk-and-more-373a</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;


### TensorFlow 5.0 Release

**What it is:**  
TensorFlow 5.0 is the latest iteration of the popular machine learning framework, now featuring native quantum computing integration and enhanced deployment capabilities.

**Why now:**  
With the introduction of groundbreaking quantum computing support, developers need to adapt and leverage this technology to stay ahead in AI and ML.

**Tutorial angle:**  
Learn how to set up and deploy a quantum-classical hybrid model using TensorFlow 5.0's new API.

**Difficulty:**  
Intermediate

### PyTorch Quantum SDK

**What it is:**  
The PyTorch Quantum SDK is a new tool that bridges quantum computing with PyTorch, enabling the creation of hybrid quantum-classical models.

**Why now:**  
As quantum computing becomes more accessible, this SDK provides a practical platform for developers to experiment with quantum AI.

**Tutorial angle:**  
Build a simple hybrid quantum-classical model by integrating PyTorch with the Quantum SDK.

**Difficulty:**  
Intermediate

### OpenAI Codex CLI Tool

**What it is:**  
The OpenAI Codex CLI Tool is a command-line interface for interacting with OpenAI's Codex AI model, designed for code generation and debugging.

**Why now:**  
This tool offers developers an AI assistant directly in their terminal, streamlining the coding and debugging process.

**Tutorial angle:**  
Discover how to use the Codex CLI for generating, debugging, and documenting code snippets efficiently.

**Difficulty:**  
Beginner

### LangChain 2.0 Framework

**What it is:**  
LangChain 2.0 is an upgraded natural language processing framework with improved context handling and expanded multi-language support.

**Why now:**  
The enhanced NLP capabilities and multi-language support make it ideal for international AI projects requiring robust language processing.

**Tutorial angle:**  
Implement multi-language support in your AI application using the latest features of LangChain 2.0.

**Difficulty:**  
Intermediate

### Hugging Face Transformers CLI Tool

**What it is:**  
The Hugging Face Transformers CLI Tool is a command-line interface for managing, training, and deploying transformer models from Hugging Face.

**Why now:**  
This tool simplifies working with transformer models, making AI integration more accessible and efficient.

**Tutorial angle:**  
Deploy a pre-trained transformer model to a cloud platform using the Hugging Face CLI.

**Difficulty:**  
Beginner

## Building in public: my lead-gen engine

My lead-gen engine has been actively discovering and enriching leads in the tech sector, focusing on Hong Kong SMEs. Here's a quick summary of its current status:

- **Pipeline Totals:**  
  - Discovered Leads: 610  
  - Enriched Leads: 388  
  - Contacted Leads: 430  

- **News Hooks:**  
  - Recent regional events like "Super Typhoon Dolphin" and "Tropical Storm Peilou" emphasize the importance of business continuity, which is a key topic for tech companies in typhoon-prone areas.

### Picks of the Week

- **TensorFlow 5.0:** A must-try for those interested in quantum-classical AI models.
- **PyTorch Quantum SDK:** Perfect for developers eager to experiment with quantum computing.
- **OpenAI Codex CLI Tool:** An essential addition for coders looking to enhance productivity with AI.

### Question for Readers

Which of these tools are you most excited to try, and why? Share your thoughts in the comments!

---

#### Connect

If this kind of post is useful, the easiest way to support the work is to:
- **Star / follow** on [dev.to](https://dev.to/karleeov) (you're already here 🙂)
- **Follow on X**: [@devkingov](https://x.com/devkingov)
- **Reach out for HK-based dev work** — .NET / Azure / system integration / IT security: [studio.resurrects.co](https://studio.resurrects.co) or email [devkingov@gmail.com](mailto:devkingov@gmail.com)
- **Subscribe to weekly HK tech posts** → [studio.resurrects.co/blog](https://studio.resurrects.co/blog) (one email a week, no spam)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>tensorflow</category>
      <category>pytorch</category>
      <category>ai</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>Evaluating Open Source AI Frameworks for Computer Vision: A Comparative Analysis of TensorFlow and PyTorch Part 1: Introduction</title>
      <dc:creator>Vijay Vinoth</dc:creator>
      <pubDate>Tue, 11 Aug 2026 06:59:15 +0000</pubDate>
      <link>https://dev.to/vijay_vinoth_8e7abfd3f5b5/evaluating-open-source-ai-frameworks-for-computer-vision-a-comparative-analysis-of-tensorflow-and-4a19</link>
      <guid>https://dev.to/vijay_vinoth_8e7abfd3f5b5/evaluating-open-source-ai-frameworks-for-computer-vision-a-comparative-analysis-of-tensorflow-and-4a19</guid>
      <description>&lt;h2&gt;
  
  
  Evaluating Open Source AI Frameworks for Computer Vision: A Comparative Analysis of TensorFlow and PyTorch Part 1: Introduction to Computer Vision
&lt;/h2&gt;

&lt;p&gt;As a Lead Programmer Analyst with expertise in PHP, PERL, Python, and Shell, I have had the opportunity to work on various projects that involve computer vision. Based on my technical understanding as a Lead Programmer Analyst, I can attest that computer vision is a rapidly evolving field that has numerous applications in areas such as image recognition, object detection, and facial recognition. With the increasing demand for computer vision applications, the need for robust and efficient open-source AI frameworks has become more pressing than ever. In this article, we will delve into the world of computer vision and explore two of the most popular open-source AI frameworks: TensorFlow and PyTorch.&lt;/p&gt;

&lt;p&gt;Computer vision is a subset of artificial intelligence that deals with the interpretation and understanding of visual data from the world. It involves the use of algorithms and statistical models to enable computers to perform tasks such as image recognition, object detection, and tracking. Computer vision has numerous applications in areas such as self-driving cars, surveillance systems, and medical diagnosis. With the rapid advancements in deep learning techniques, computer vision has become an integral part of many industries, and its applications continue to grow.&lt;/p&gt;

&lt;p&gt;When it comes to building computer vision applications, choosing the right framework can be a daunting task. There are several open-source AI frameworks available, each with its strengths and weaknesses. TensorFlow and PyTorch are two of the most popular frameworks used in computer vision. In a recent article, PyTorch vs. TensorFlow for Your Computer Vision Projects, the authors compared the two frameworks across key areas such as usability, flexibility, and deployment.&lt;/p&gt;

&lt;p&gt;Another article, Top Computer Vision Tools, Libraries &amp;amp; Frameworks in 2026, provided a comprehensive guide to the best computer vision tools in 2026, covering deep learning frameworks such as PyTorch, TensorFlow, and OpenCV.&lt;/p&gt;

&lt;p&gt;In a video, Which Deep Learning Framework Should You Choose?, the authors compared PyTorch and TensorFlow across several key areas, including ease of use, development, and deployment.&lt;/p&gt;

&lt;p&gt;In addition to TensorFlow and PyTorch, there are other AI frameworks and tools available for deep learning and computer vision. For example, AI Frameworks &amp;amp; Tools for Deep Learning and Computer Vision provides an introduction to PyTorch, TensorFlow, OpenCV, Detectron2, and YOLO.&lt;/p&gt;

&lt;p&gt;When it comes to choosing a library for computer vision research, the choice between TensorFlow and PyTorch can be difficult. In a recent article, Which library should I use for computer vision research, Tensorflow or PyTorch?, the author discussed the pros and cons of each framework.&lt;/p&gt;

&lt;p&gt;In the next part of this series, we will delve deeper into the comparison of TensorFlow and PyTorch, exploring their strengths and weaknesses, and discussing how to choose the right framework for your computer vision project.&lt;/p&gt;

&lt;h3&gt;
  
  
  📚 References &amp;amp; Further Reading
&lt;/h3&gt;

&lt;p&gt;PyTorch Official Documentation&lt;br&gt;
Hugging Face Transformers&lt;br&gt;
OpenAI Research&lt;br&gt;
arXiv e-Print Archive&lt;br&gt;
Towards Data Science&lt;/p&gt;

&lt;h3&gt;
  
  
  Your Turn
&lt;/h3&gt;

&lt;p&gt;What are some of the most significant challenges you have faced when working on computer vision projects, and how did you overcome them? Share your experiences and insights in the comments below.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://artificial-inteligence.phptutorial.co.in/evaluating-open-source-ai-frameworks-for-computer-vision-a-comparative-analysis-of-tensorflow-and-pytorch-part-1-introduction-to-computer-vision/" rel="noopener noreferrer"&gt;https://artificial-inteligence.phptutorial.co.in&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>computervision</category>
      <category>tensorflow</category>
      <category>pytorch</category>
    </item>
    <item>
      <title>Chạy Jupyter PyTorch và pandas bị OOM RAM ở ngưỡng nào</title>
      <dc:creator>Review Laptop</dc:creator>
      <pubDate>Tue, 11 Aug 2026 03:25:37 +0000</pubDate>
      <link>https://dev.to/hung_phatlaptop_a651fc86/chay-jupyter-pytorch-va-pandas-bi-oom-ram-o-nguong-nao-1eje</link>
      <guid>https://dev.to/hung_phatlaptop_a651fc86/chay-jupyter-pytorch-va-pandas-bi-oom-ram-o-nguong-nao-1eje</guid>
      <description>&lt;p&gt;Nói thẳng, khi thực hiện pipeline Data Science gồm Jupyter Lab, pandas và PyTorch trên cùng một máy, rào cản lớn nhất không phải là tốc độ CPU mà là trần bộ nhớ RAM. Khi phân tích các tác vụ như trong &lt;a href="https://www.reviewlaptop.vn/chatbot-ai-van-phong-tinh-nang-chi-phi/" rel="noopener noreferrer"&gt;bài gốc&lt;/a&gt; về xử lý dữ liệu và mã Python, nhiều người thường đánh giá thấp lượng RAM thực tế mà các thư viện này tiêu thụ.&lt;/p&gt;

&lt;h2&gt;
  
  
  pandas load CSV ngốn RAM gấp 4 lần dung lượng file
&lt;/h2&gt;

&lt;p&gt;Một tập dữ liệu CSV dung lượng 2 GB trên đĩa cứng không có nghĩa là bạn chỉ cần 2 GB RAM để làm việc. Khi gọi &lt;code&gt;pd.read_csv()&lt;/code&gt;, pandas sẽ chuyển đổi các chuỗi ký tự thành đối tượng trong bộ nhớ, tạo bản sao trung gian và phân bổ lại bộ đệm. Thực tế thì lượng RAM tiêu thụ thường vọt lên gấp 3 đến 5 lần dung lượng file gốc, tức là chạm mốc 8 GB đến 10 GB RAM chỉ riêng cho bảng dữ liệu.&lt;/p&gt;

&lt;p&gt;Nếu không tối ưu kiểu dữ liệu (&lt;code&gt;category&lt;/code&gt; thay cho &lt;code&gt;object&lt;/code&gt;, &lt;code&gt;int16&lt;/code&gt; thay cho &lt;code&gt;int64&lt;/code&gt;), hệ thống sẽ cạn RAM trước khi bạn kịp thực hiện câu lệnh &lt;code&gt;df.groupby()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;pandas&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;psutil&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;check_ram&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;process&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;psutil&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Process&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getpid&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;RAM in use: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;memory_info&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="n"&gt;rss&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;1024&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="si"&gt;:&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt; MB&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Load file CSV 2GB
&lt;/span&gt;&lt;span class="nf"&gt;check_ram&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;df&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_csv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;large_dataset.csv&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;engine&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;c&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nf"&gt;check_ram&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;# RAM tăng từ 150MB lên ~8.2GB
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  PyTorch batch size và hiện tượng tràn RAM sang Swap
&lt;/h2&gt;

&lt;p&gt;Khi đưa dataframe này sang PyTorch &lt;code&gt;DataLoader&lt;/code&gt; để huấn luyện mô hình trên iGPU hoặc CPU, bộ nhớ tiếp tục bị nhân đôi do dữ liệu chuyển đổi sang &lt;code&gt;torch.Tensor&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Nếu đặt &lt;code&gt;batch_size=128&lt;/code&gt; hoặc &lt;code&gt;256&lt;/code&gt; mà không xả bộ nhớ rác (&lt;code&gt;gc.collect()&lt;/code&gt;), tổng dung lượng bộ nhớ yêu cầu sẽ vượt quá RAM vật lý. Lúc này, hệ điều hành buộc phải kích hoạt bộ nhớ ảo (Swap).&lt;/p&gt;

&lt;p&gt;Khi Swap hoạt động:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tốc độ đọc ghi dữ liệu giảm từ hàng chục GB/s trên RAM xuống còn vài trăm MB/s trên SSD.&lt;/li&gt;
&lt;li&gt;Giao diện Jupyter Notebook bị đơ do kernel ngừng phản hồi.&lt;/li&gt;
&lt;li&gt;Tiến trình tự động bị hủy với lỗi &lt;code&gt;Killed&lt;/code&gt; (OOM Killer trên Linux).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ví dụ với file 3 GB, ngưỡng OOM xuất hiện ngay khi bộ nhớ chạm 95% dung lượng RAM hệ thống.&lt;/p&gt;

&lt;p&gt;Lời khuyên thực tế là luôn kiểm tra dung lượng từng cột bằng &lt;code&gt;df.info(memory_usage='deep')&lt;/code&gt;, chia nhỏ file thành các chunk với &lt;code&gt;chunksize&lt;/code&gt; khi đọc pandas, và duy trì &lt;code&gt;batch_size&lt;/code&gt; nhỏ từ 32 đến 64 khi huấn luyện.&lt;/p&gt;

</description>
      <category>gpt4o</category>
      <category>datascience</category>
      <category>pytorch</category>
      <category>python</category>
    </item>
    <item>
      <title>40% Adam Optimizer Improvement: PyTorch Benchmarks</title>
      <dc:creator>Michael Yang</dc:creator>
      <pubDate>Sun, 09 Aug 2026 16:06:29 +0000</pubDate>
      <link>https://dev.to/michael_yang_a9925b515901/40-adam-optimizer-improvement-pytorch-benchmarks-4mhd</link>
      <guid>https://dev.to/michael_yang_a9925b515901/40-adam-optimizer-improvement-pytorch-benchmarks-4mhd</guid>
      <description>&lt;h1&gt;
  
  
  40% Adam Optimizer Improvement
&lt;/h1&gt;

&lt;p&gt;If you are training deep learning models in PyTorch, default optimizer implementations leave performance on the table.&lt;/p&gt;

&lt;p&gt;Check out this project demonstrating up to a &lt;strong&gt;40% Adam optimizer improvement&lt;/strong&gt;:&lt;br&gt;
&lt;a href="https://github.com/yangofzeal/adam/" rel="noopener noreferrer"&gt;https://github.com/yangofzeal/adam/&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Highlights
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;40% faster step execution time in PyTorch.&lt;/li&gt;
&lt;li&gt;Drop-in replacement for standard Adam.&lt;/li&gt;
&lt;li&gt;Open-source implementation available on GitHub: &lt;a href="https://github.com/yangofzeal/adam/" rel="noopener noreferrer"&gt;https://github.com/yangofzeal/adam/&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>pytorch</category>
      <category>python</category>
      <category>machinelearning</category>
      <category>ai</category>
    </item>
    <item>
      <title>Model DNA, Analyzed: Verifying 'From-Scratch' LLM Claims with Architecture, Tokenizer, and CKA (PyTorch)</title>
      <dc:creator>ai maya</dc:creator>
      <pubDate>Sun, 09 Aug 2026 08:12:38 +0000</pubDate>
      <link>https://dev.to/ai_maya_063fc568e157562fd/model-dna-analyzed-verifying-from-scratch-llm-claims-with-architecture-tokenizer-and-cka-2k4h</link>
      <guid>https://dev.to/ai_maya_063fc568e157562fd/model-dna-analyzed-verifying-from-scratch-llm-claims-with-architecture-tokenizer-and-cka-2k4h</guid>
      <description>&lt;p&gt;&lt;strong&gt;TL;DR.&lt;/strong&gt; A public method called &lt;strong&gt;&lt;a href="https://huggingface.co/blog/mayafree/model-dna" rel="noopener noreferrer"&gt;Model DNA&lt;/a&gt;&lt;/strong&gt; — with a &lt;a href="https://huggingface.co/spaces/mayafree/Model-Genome-Korea" rel="noopener noreferrer"&gt;live tool&lt;/a&gt; — lets outsiders estimate whether an LLM was trained from scratch or derived from an open-weight base, using nothing but public artifacts: &lt;code&gt;config.json&lt;/code&gt;, &lt;code&gt;tokenizer.json&lt;/code&gt;, and embedding weights. This is a technical deep-dive that &lt;em&gt;cites and reproduces&lt;/em&gt; that method in PyTorch, then analyzes where it holds up and where it breaks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Three public signals&lt;/strong&gt; — architecture config, tokenizer overlap, and embedding-space similarity via &lt;strong&gt;Linear CKA&lt;/strong&gt; — combine to place a model on a lineage spectrum.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;One matching field is noise; five at once is a fingerprint.&lt;/strong&gt; Provenance is a preponderance-of-evidence judgment, not a single test.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The method's real strengths&lt;/strong&gt; are reproducibility and rotation-invariant similarity; its real limits are the &lt;em&gt;continued-pretraining&lt;/em&gt; gray zone, threshold sensitivity, and an embedding-only view.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fingerprinting reveals lineage, not intent.&lt;/strong&gt; Building on an open-weight base is a legitimate, industry-standard practice; the output is a &lt;em&gt;label&lt;/em&gt;, not an accusation.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Why this matters in 2026
&lt;/h2&gt;

&lt;p&gt;Every few weeks a lab announces a "from-scratch, self-developed" foundation model. In mid-2026 those claims stopped being taken on faith. A &lt;a href="https://www.zhihu.com/roundtable/llmrun2026" rel="noopener noreferrer"&gt;Zhihu roundtable on the summer model wave&lt;/a&gt; and a &lt;a href="https://www.zhihu.com/question/2067512422555029717" rel="noopener noreferrer"&gt;thread with millions of views&lt;/a&gt; became the venue where "self-developed" claims were publicly stress-tested — and several were found more derivative than advertised (&lt;a href="https://www.gamersky.com/news/202608/2181600.shtml" rel="noopener noreferrer"&gt;coverage&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Model DNA matters because it moved the argument from vibes to a reproducible procedure, and it has been run across major Korean foundation-model builders — among them LG, NAVER, Kakao, SKT, KT, NCSOFT, Upstage, and Motif. (This piece stays at the method level and assigns no verdict to any named company; per-model labels belong to the tool, not to a blog post.) What follows reproduces the procedure in PyTorch and evaluates it as a method, within the scope the source already made public.&lt;/p&gt;

&lt;h2&gt;
  
  
  The three signals (cited and reproduced)
&lt;/h2&gt;

&lt;p&gt;The premise: no leaked internals required. Everything is read from a model's public files.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Architecture fingerprint — &lt;code&gt;config.json&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;Compare the structural fields a lab chooses at design time: &lt;code&gt;model_type&lt;/code&gt;, &lt;code&gt;vocab_size&lt;/code&gt;, &lt;code&gt;hidden_size&lt;/code&gt;, &lt;code&gt;intermediate_size&lt;/code&gt;, &lt;code&gt;num_hidden_layers&lt;/code&gt;, &lt;code&gt;num_attention_heads&lt;/code&gt;, &lt;code&gt;num_key_value_heads&lt;/code&gt;. Independently designed models rarely align on all of them at once.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;

&lt;span class="n"&gt;ARCH_FIELDS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;model_type&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;vocab_size&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;hidden_size&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;intermediate_size&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;num_hidden_layers&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;num_attention_heads&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;num_key_value_heads&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;max_position_embeddings&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;rope_theta&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;arch_match_count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cfg_a&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cfg_b&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;ARCH_FIELDS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;Number of structural fields that match simultaneously.&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;
              &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;cfg_a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;cfg_a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;cfg_b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Reading rule (as the source puts it):&lt;/strong&gt; a single coincidental field means nothing; five simultaneously is a fingerprint. How many to treat as a threshold depends on the diversity of your candidate base pool.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  2. Tokenizer overlap — &lt;code&gt;tokenizer.json&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;Two models trained truly independently almost never converge on the same vocabulary. Normalize shared tokens against the &lt;em&gt;smaller&lt;/em&gt; vocabulary.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;tokenizer_overlap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vocab_a&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;vocab_b&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;sa&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sb&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vocab_a&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vocab_b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sa&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;sb&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="nf"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sa&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sb&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A supporting signal only — see Trap 2.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Embedding similarity — Linear CKA
&lt;/h3&gt;

&lt;p&gt;The most robust signal compares representation geometry. Naive cosine comparison is fooled by rotation (Trap 1), so the method uses &lt;strong&gt;Linear CKA (Centered Kernel Alignment)&lt;/strong&gt; — from Kornblith et al. (2019), &lt;em&gt;Similarity of Neural Network Representations Revisited&lt;/em&gt; (ICML) — which is invariant to rotation, orthogonal transforms, and isotropic scaling.&lt;/p&gt;

&lt;p&gt;For row-centered matrices &lt;code&gt;X ∈ ℝ^{n×d1}&lt;/code&gt; and &lt;code&gt;Y ∈ ℝ^{n×d2}&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CKA(X, Y) = ||Yᵀ X||²_F / ( ||Xᵀ X||_F · ||Yᵀ Y||_F )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Crucially, it is defined even when &lt;code&gt;d1 ≠ d2&lt;/code&gt;, so models with different hidden sizes compare directly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;

&lt;span class="nd"&gt;@torch.no_grad&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;linear_cka&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;X&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Y&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;float&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="c1"&gt;# X:(n,d1), Y:(n,d2) — embeddings over the SAME token set (rows aligned)
&lt;/span&gt;    &lt;span class="n"&gt;X&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;X&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;X&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepdim&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;Y&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Y&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;Y&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepdim&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;Y&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;t&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;X&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;den&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sqrt&lt;/span&gt;&lt;span class="p"&gt;(((&lt;/span&gt;&lt;span class="n"&gt;X&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;t&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;X&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;Y&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;t&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;Y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
    &lt;span class="nf"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;den&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;clamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;item&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Alignment is the catch.&lt;/strong&gt; The two embedding matrices must index the &lt;em&gt;same tokens&lt;/em&gt;. In practice you take the shared-token subset of the two tokenizers and gather those rows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;aligned_embeddings&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;emb_a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;vocab_a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;emb_b&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;vocab_b&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;shared&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vocab_a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vocab_b&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="n"&gt;idx_a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tensor&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;vocab_a&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;shared&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="n"&gt;idx_b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tensor&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;vocab_b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;shared&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;emb_a&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx_a&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;emb_b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx_b&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The genotype framework
&lt;/h2&gt;

&lt;p&gt;The tool collapses the three signals into four labels — a clean way to read any result (&lt;a href="https://huggingface.co/spaces/mayafree/Model-Genome-Korea" rel="noopener noreferrer"&gt;Model Genome Korea&lt;/a&gt;):&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Genotype&lt;/th&gt;
&lt;th&gt;Meaning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;🟢 &lt;strong&gt;Native&lt;/strong&gt;
&lt;/td&gt;
&lt;td&gt;Self-designed architecture &lt;strong&gt;and&lt;/strong&gt; from-scratch weights&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;🔵 &lt;strong&gt;Adapted&lt;/strong&gt;
&lt;/td&gt;
&lt;td&gt;Mostly original, &lt;strong&gt;one&lt;/strong&gt; borrowed axis&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;🟡 &lt;strong&gt;Mixed&lt;/strong&gt;
&lt;/td&gt;
&lt;td&gt;Partial inheritance on &lt;strong&gt;both&lt;/strong&gt; axes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;🔴 &lt;strong&gt;Ported&lt;/strong&gt;
&lt;/td&gt;
&lt;td&gt;Exact foreign architecture match &lt;strong&gt;and&lt;/strong&gt; inherited weights&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Two traps that produce confident wrong answers
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Trap 1 — row-wise cosine similarity looks rigorous but isn't.&lt;/strong&gt; It is fooled by rotation invariance: a genuinely derived model can be rotated to look "different," and a naive check clears it. That is exactly why CKA and config signals carry the weight.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trap 2 — a shared tokenizer proves nothing alone.&lt;/strong&gt; Tokenizer reuse is often a licensing or convenience decision. Treat overlap as supporting evidence, never a conclusion.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deep analysis: how far can you trust it?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Strengths&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Reproducibility.&lt;/strong&gt; All three signals compute from public artifacts in a few dozen lines. Claim and verification live on the same plane.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Right invariance.&lt;/strong&gt; Choosing Linear CKA is correct — it neutralizes the most common disguise (orthogonal transforms) that defeats cosine comparisons.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Evidence fusion.&lt;/strong&gt; Judging on the &lt;em&gt;simultaneous&lt;/em&gt; agreement of three axes suppresses both false positives and false negatives.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Limits (must be acknowledged)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Continued-pretraining gray zone.&lt;/strong&gt; Embedding CKA identifies from-scratch training well but does not cleanly separate derivatives that keep a base's weights and train heavily on top. Here the verdict is probabilistic and config/tokenizer evidence dominates.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Threshold sensitivity.&lt;/strong&gt; "How many fields," "what CKA cutoff" depend on the candidate pool. Hard-coding constants makes conclusions wobble when the pool changes — which is why this write-up prescribes none.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Embedding bias.&lt;/strong&gt; Looking only at the embedding layer is cheap, but a model's "identity" also lives in mid and upper layers. A &lt;strong&gt;layer-wise CKA profile&lt;/strong&gt; improves resolution in the gray zone.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Alignment dependence.&lt;/strong&gt; Few shared tokens (language- or domain-specific tokenizers) shrink the CKA sample and inflate variance. Report shared-token count alongside CKA.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Improvements worth adopting&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Extend single-layer embedding CKA to a &lt;strong&gt;layer-wise CKA curve&lt;/strong&gt; (input → mid → output).&lt;/li&gt;
&lt;li&gt;Score against the &lt;strong&gt;entire candidate base pool&lt;/strong&gt; and judge by &lt;em&gt;relative rank&lt;/em&gt;, not an absolute cutoff.&lt;/li&gt;
&lt;li&gt;Report shared-token counts and bootstrap confidence intervals for &lt;strong&gt;statistical significance&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;In short, Model DNA fuses the &lt;em&gt;right signals&lt;/em&gt; under the &lt;em&gt;right invariance&lt;/em&gt; — a solid starting point. It only avoids misjudgment when read as a &lt;strong&gt;spectrum with uncertainty&lt;/strong&gt;, not a from-scratch/not binary.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  What fingerprinting cannot tell you
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lineage, not intent.&lt;/strong&gt; It can show B shares structure with A; it cannot say whether that was disclosed, licensed, or hidden — ethics and paperwork, not linear algebra.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;"From scratch" is a spectrum,&lt;/strong&gt; not a boolean. Data, init, architecture, and post-training each sit on a continuum of originality.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Building on open weights is legitimate.&lt;/strong&gt; The goal is transparency and accurate labeling, not accusation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  FAQ
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Can you tell if an LLM was really trained from scratch?&lt;/strong&gt;&lt;br&gt;
Usually, with high probability. Cross-check architecture config, tokenizer overlap, and embedding CKA against candidate bases; agreement across all three indicates derivation, divergence supports from-scratch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Model DNA / model provenance?&lt;/strong&gt;&lt;br&gt;
Estimating a model's origin — original vs. derived from an open-weight base — from public artifacts alone (config, tokenizer, weights), without training data or internal logs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Is building on Llama, Qwen, or DeepSeek legitimate?&lt;/strong&gt;&lt;br&gt;
Yes. Fine-tuning or continued-pretraining an open-weight base is standard, licensed practice. Provenance tools report lineage, not misconduct.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How do you tell a fine-tuned model from a from-scratch one?&lt;/strong&gt;&lt;br&gt;
From-scratch models diverge on architecture and tokenizer and show low embedding CKA to any base. Derivatives keep the base's skeleton and tokenizer and retain high similarity — the hardest case, where config and tokenizer evidence matter most.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Linear CKA instead of cosine?&lt;/strong&gt;&lt;br&gt;
Because CKA is robust to rotation and scaling — the transforms a derived model uses to look "different."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Can models with different hidden sizes be compared?&lt;/strong&gt;&lt;br&gt;
Yes. CKA compares n×n Gram matrices, so &lt;code&gt;d1 ≠ d2&lt;/code&gt; is fine — as long as embedding rows are aligned to the same tokens.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources &amp;amp; related links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Method under analysis: &lt;a href="https://huggingface.co/blog/mayafree/model-dna" rel="noopener noreferrer"&gt;Model DNA — architecture &amp;amp; weight lineage&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Live tool (space): &lt;a href="https://huggingface.co/spaces/mayafree/Model-Genome-Korea" rel="noopener noreferrer"&gt;Model Genome Korea&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Announcement post: &lt;a href="https://huggingface.co/posts/mayafree/340116886441122" rel="noopener noreferrer"&gt;Architecture lineage of Korea's sovereign-AI models&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Academic basis: Kornblith, Norouzi, Lee, Hinton (2019), &lt;em&gt;Similarity of Neural Network Representations Revisited&lt;/em&gt;, ICML.&lt;/li&gt;
&lt;li&gt;The debate: &lt;a href="https://www.zhihu.com/roundtable/llmrun2026" rel="noopener noreferrer"&gt;Zhihu roundtable "大模型卷一夏"&lt;/a&gt; · &lt;a href="https://www.zhihu.com/question/2067512422555029717" rel="noopener noreferrer"&gt;Zhihu thread&lt;/a&gt; · &lt;a href="https://www.gamersky.com/news/202608/2181600.shtml" rel="noopener noreferrer"&gt;coverage&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Provenance is becoming a norm, not a gotcha. The healthiest version is one where "we trained it from scratch" arrives with — or at least survives — the fingerprint. If you build models, publish the check yourself.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>machinelearning</category>
      <category>pytorch</category>
    </item>
    <item>
      <title>ResKV: Recovering Evicted Token Contributions via Residual KV Cache — LongBench 32/32</title>
      <dc:creator>Chaeyeon Mia Lee</dc:creator>
      <pubDate>Thu, 06 Aug 2026 08:14:45 +0000</pubDate>
      <link>https://dev.to/cofldus/reskv-recovering-evicted-token-contributions-via-residual-kv-cache-longbench-3232-10i4</link>
      <guid>https://dev.to/cofldus/reskv-recovering-evicted-token-contributions-via-residual-kv-cache-longbench-3232-10i4</guid>
      <description>&lt;h2&gt;
  
  
  TL;DR
&lt;/h2&gt;

&lt;p&gt;KV cache eviction permanently throws away tokens. KV cache merging corrupts the values of surviving tokens. ResKV (arXiv:2607.29591) does neither — it splits a fixed budget into a main cache that keeps exact tokens and a residual cache that reconstructs the attention contribution of evicted tokens. Both caches participate in the same softmax, so neither numerator nor denominator is distorted. Result: improvements across all 32 LongBench configurations and 63 of 64 RULER configurations vs. prior methods at identical budgets.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Problem
&lt;/h2&gt;

&lt;p&gt;Long-context LLM inference is memory-bound. A single 32K-token forward pass with Llama-3-8B can exhaust gigabytes of KV cache. The fix everyone reaches for is KV cache compression: keep only the "important" tokens, drop the rest.&lt;/p&gt;

&lt;p&gt;The two mainstream approaches both have a fundamental flaw baked in.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Eviction methods&lt;/strong&gt; (H2O, SnapKV, PyramidKV): drop low-importance tokens permanently. Clean and fast, but those dropped tokens had nonzero attention weights. Once dropped, their contribution to the softmax numerator and denominator is gone. Under tight budgets, performance degrades sharply on tasks requiring distributed evidence across the context window.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Merging methods&lt;/strong&gt;: instead of dropping, fold evicted tokens into surviving ones. Information is preserved in aggregate, but the merge corrupts the value vectors of retained tokens and breaks the softmax denominator. The resulting attention distribution is biased in ways that compound across layers.&lt;/p&gt;

&lt;p&gt;Both approaches accept that you cannot recover what you've compressed away. ResKV challenges that assumption.&lt;/p&gt;




&lt;h2&gt;
  
  
  How It Works
&lt;/h2&gt;

&lt;p&gt;The core idea: &lt;strong&gt;split the KV budget&lt;/strong&gt; $b$ into a main cache of size $m$ and a residual cache of size $r$:&lt;/p&gt;

&lt;p&gt;$$b = m + r$$&lt;/p&gt;

&lt;p&gt;The main cache stores exact KV pairs for the top-$m$ important tokens. The residual cache stores compact summaries of the evicted tokens' attention contributions — not the tokens themselves, but their aggregated effect on the softmax.&lt;/p&gt;

&lt;h3&gt;
  
  
  Shared-Softmax Integration
&lt;/h3&gt;

&lt;p&gt;The key design decision: residual entries participate in the &lt;strong&gt;same softmax normalization&lt;/strong&gt; as main-cache tokens. Standard attention is:&lt;/p&gt;

&lt;p&gt;$$\text{Attn}(q, K, V) = \frac{\sum_{i \in \mathcal{M}} e^{q \cdot k_i} v_i + \sum_{j \in \mathcal{E}} e^{q \cdot k_j} v_j}{\sum_{i \in \mathcal{M}} e^{q \cdot k_i} + \sum_{j \in \mathcal{E}} e^{q \cdot k_j}}$$&lt;/p&gt;

&lt;p&gt;Eviction methods zero out the $\mathcal{E}$ terms. ResKV approximates them with residual entries $(k_l^{\text{res}}, v_l^{\text{res}})$:&lt;/p&gt;

&lt;p&gt;$$\text{Attn}&lt;em&gt;{\text{ResKV}} = \frac{\sum&lt;/em&gt;{i \in \mathcal{M}} e^{q \cdot k_i} v_i + \sum_{l=1}^{r} e^{q \cdot k_l^{\text{res}}} v_l^{\text{res}}}{\sum_{i \in \mathcal{M}} e^{q \cdot k_i} + \sum_{l=1}^{r} e^{q \cdot k_l^{\text{res}}}}$$&lt;/p&gt;

&lt;p&gt;Both numerator mass (value contribution) and denominator mass (normalization weight) of the evicted set are approximated and restored.&lt;/p&gt;

&lt;h3&gt;
  
  
  Validation Proxy
&lt;/h3&gt;

&lt;p&gt;Not all layers and heads benefit equally from residual slots. ResKV uses a &lt;strong&gt;validation proxy&lt;/strong&gt; at cache construction time to allocate $r$ unevenly across layers and heads — giving more residual slots to positions where the approximation quality is higher and the eviction loss is larger.&lt;/p&gt;

&lt;h3&gt;
  
  
  Dynamic Gate
&lt;/h3&gt;

&lt;p&gt;At decode time, the query's attention pattern varies. When attention is sharp (concentrated on a few tokens), residual entries matter less — the main cache already dominates. When attention is diffuse (spread across many tokens), residual contributions are critical.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;dynamic gate&lt;/strong&gt; $\alpha_q$ scales residual contributions per query based on attention sharpness over the main cache:&lt;/p&gt;

&lt;p&gt;$$\alpha_q = \text{gate}(\text{sharpness}(q, \mathcal{M}))$$&lt;/p&gt;

&lt;p&gt;High entropy in the main-cache attention distribution increases residual weight.&lt;/p&gt;




&lt;h2&gt;
  
  
  Show Me The Code
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;torch.nn.functional&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;F&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;dataclasses&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dataclass&lt;/span&gt;

&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ResKVConfig&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;total_budget&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;        &lt;span class="c1"&gt;# b = m + r
&lt;/span&gt;    &lt;span class="n"&gt;residual_ratio&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;float&lt;/span&gt;    &lt;span class="c1"&gt;# fraction of budget for residual (e.g. 0.2)
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ResKVCache&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ResKVConfig&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;num_heads&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;head_dim&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total_budget&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;residual_ratio&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;total_budget&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;   &lt;span class="c1"&gt;# (B, H, m, D) exact tokens
&lt;/span&gt;        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;     &lt;span class="c1"&gt;# (B, H, r, D) eviction summaries
&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;importance_scores&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;Prefill: select top-m tokens, cluster evicted into r residual slots.&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_k&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_v&lt;/span&gt;
            &lt;span class="n"&gt;B&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;H&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;D&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zeros&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;B&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;H&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;D&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;device&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;new_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;device&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;new_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zeros_like&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="n"&gt;all_k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cat&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_k&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;all_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cat&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_v&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;all_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;all_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;all_v&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;

        &lt;span class="c1"&gt;# Keep top-m by importance
&lt;/span&gt;        &lt;span class="n"&gt;topk_idx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;importance_scores&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;topk&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="n"&gt;indices&lt;/span&gt;
        &lt;span class="n"&gt;evict_mask&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_evict_mask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;all_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;topk_idx&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;all_k&lt;/span&gt;&lt;span class="p"&gt;[...,&lt;/span&gt; &lt;span class="o"&gt;~&lt;/span&gt;&lt;span class="n"&gt;evict_mask&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;:]&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;all_v&lt;/span&gt;&lt;span class="p"&gt;[...,&lt;/span&gt; &lt;span class="o"&gt;~&lt;/span&gt;&lt;span class="n"&gt;evict_mask&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;:]&lt;/span&gt;

        &lt;span class="c1"&gt;# Compress evicted tokens into r residual slots
&lt;/span&gt;        &lt;span class="n"&gt;evicted_k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;all_k&lt;/span&gt;&lt;span class="p"&gt;[...,&lt;/span&gt; &lt;span class="n"&gt;evict_mask&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;:]&lt;/span&gt;
        &lt;span class="n"&gt;evicted_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;all_v&lt;/span&gt;&lt;span class="p"&gt;[...,&lt;/span&gt; &lt;span class="n"&gt;evict_mask&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;:]&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_cluster&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;evicted_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;evicted_v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;attend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;Shared-softmax attention over main + gated residual caches.&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
        &lt;span class="n"&gt;gate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_gate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cat&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_k&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;gate&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cat&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;res_v&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;gate&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;scale&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;0.5&lt;/span&gt;
        &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;F&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;softmax&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;transpose&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;scale&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_gate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;Dynamic gate: high entropy -&amp;gt; higher residual contribution.&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
        &lt;span class="n"&gt;scale&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;0.5&lt;/span&gt;
        &lt;span class="n"&gt;logits&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;main_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;transpose&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;scale&lt;/span&gt;
        &lt;span class="n"&gt;probs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;F&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;softmax&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;logits&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;entropy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;probs&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;probs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;clamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;1e-9&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;()).&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sigmoid&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;entropy&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;item&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_cluster&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;evicted_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;evicted_v&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;Chunk-average evicted tokens into r residual slots.&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
        &lt;span class="n"&gt;E&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;evicted_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="n"&gt;chunk&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;E&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;rk&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rv&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;min&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;E&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;E&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;rk&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zeros&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;evicted_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;[:&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;evicted_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                                       &lt;span class="n"&gt;device&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;evicted_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;device&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;evicted_k&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
                &lt;span class="n"&gt;rv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zeros_like&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rk&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]))&lt;/span&gt;
            &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;rk&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;evicted_k&lt;/span&gt;&lt;span class="p"&gt;[...,&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;:].&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepdim&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
                &lt;span class="n"&gt;rv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;evicted_v&lt;/span&gt;&lt;span class="p"&gt;[...,&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;:].&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepdim&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rk&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rv&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nd"&gt;@staticmethod&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_evict_mask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;seq_len&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;topk_idx&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;mask&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ones&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;seq_len&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;device&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;topk_idx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;device&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;mask&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;topk_idx&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;  &lt;span class="c1"&gt;# simplified; broadcast over batch/heads in practice
&lt;/span&gt;        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;mask&lt;/span&gt;


&lt;span class="c1"&gt;# Drop-in usage
&lt;/span&gt;&lt;span class="n"&gt;cfg&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ResKVConfig&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;total_budget&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;512&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;residual_ratio&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# 410 main + 102 residual
&lt;/span&gt;&lt;span class="n"&gt;cache&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ResKVCache&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cfg&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;num_heads&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;head_dim&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;128&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# During prefill
&lt;/span&gt;&lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;layer_k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;layer_v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;importance_scores&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;cumulative_attn_weights&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# During decode
&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;attend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# numerator + denominator both restored
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Benchmark Results
&lt;/h2&gt;

&lt;p&gt;All comparisons use identical KV budgets. ResKV splits the budget $b = m + r$ while baselines use the full budget for exact tokens only.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LongBench&lt;/strong&gt; (16 long-context tasks: single/multi-doc QA, summarization, code completion):&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Setting&lt;/th&gt;
&lt;th&gt;H2O&lt;/th&gt;
&lt;th&gt;SnapKV&lt;/th&gt;
&lt;th&gt;PyramidKV&lt;/th&gt;
&lt;th&gt;ResKV&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;All 32 configurations tested&lt;/td&gt;
&lt;td&gt;baseline&lt;/td&gt;
&lt;td&gt;baseline&lt;/td&gt;
&lt;td&gt;baseline&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;best in all 32&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Performance gap is largest at tight budgets (10-20% retention rate), where eviction methods lose the most information and ResKV's residual recovery provides the greatest advantage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;RULER&lt;/strong&gt; (synthetic tasks: retrieval, multi-hop aggregation, chain tracing):&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Configurations improved&lt;/th&gt;
&lt;th&gt;H2O&lt;/th&gt;
&lt;th&gt;SnapKV&lt;/th&gt;
&lt;th&gt;ResKV&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Out of 64 tested&lt;/td&gt;
&lt;td&gt;—&lt;/td&gt;
&lt;td&gt;—&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;63 / 64&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;RULER tasks explicitly require gathering distributed evidence across the context window — exactly the scenario where dropped token contributions hurt most. ResKV's residual cache directly addresses this failure mode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Efficiency:&lt;/strong&gt; Negligible memory overhead (residual slots come from the same budget $b$, not additional allocation). Decode throughput is stable at extended context lengths.&lt;/p&gt;




&lt;h2&gt;
  
  
  Gotchas &amp;amp; Limitations
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Residual cache goes stale during long generation.&lt;/strong&gt; ResKV builds the residual cache at prefill and freezes it. Tokens generated during decoding are added to the main cache (with further eviction), but the residual cache doesn't update. For very long generations, early evicted tokens' summaries may become stale.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Clustering quality limits recovery.&lt;/strong&gt; Evicted tokens are summarized into $r$ slots by chunked averaging or k-means. If evicted tokens are semantically diverse, a single cluster centroid poorly represents all of them. Recovery is approximate by design, but heterogeneous eviction sets degrade it further.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;No flash-attention kernel integration.&lt;/strong&gt; The shared-softmax over concatenated main + residual caches doesn't map to standard flash-attention implementations. Current inference requires a custom attention kernel or a two-pass approach, which adds latency.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Layer/head allocation is fixed at prefill.&lt;/strong&gt; The validation proxy assigns residual slots per layer and head once at cache construction time. It doesn't adapt as the decode proceeds and actual attention patterns evolve.&lt;/p&gt;




&lt;h2&gt;
  
  
  Try It Today
&lt;/h2&gt;

&lt;p&gt;Paper: &lt;a href="https://arxiv.org/abs/2607.29591" rel="noopener noreferrer"&gt;arXiv:2607.29591&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;ResKV is a drop-in upgrade for any eviction-based KV cache. To apply it:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Define your total budget $b$ and residual ratio (start with 10-20% residual).&lt;/li&gt;
&lt;li&gt;At prefill, replace standard eviction with ResKV's &lt;code&gt;update()&lt;/code&gt; — cluster evicted tokens into residual slots instead of discarding.&lt;/li&gt;
&lt;li&gt;At decode, use &lt;code&gt;attend()&lt;/code&gt; for shared-softmax over main + residual.&lt;/li&gt;
&lt;li&gt;Optionally enable the validation proxy to allocate residual slots non-uniformly across layers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The biggest wins will be in tasks with sparse, distributed evidence across long contexts: RAG over large corpora, multi-document reasoning, long-form code context.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;What's your experience with KV cache compression in production? Drop a comment.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Sources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;arXiv paper: &lt;a href="https://arxiv.org/abs/2607.29591" rel="noopener noreferrer"&gt;https://arxiv.org/abs/2607.29591&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;arXiv HTML: &lt;a href="https://arxiv.org/html/2607.29591" rel="noopener noreferrer"&gt;https://arxiv.org/html/2607.29591&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>llm</category>
      <category>machinelearning</category>
      <category>performance</category>
      <category>pytorch</category>
    </item>
    <item>
      <title>GPU-Accelerating MSCRED with CUDA, im2col, GEMM, and a Custom PyTorch Extension</title>
      <dc:creator>ranjithvutnoor</dc:creator>
      <pubDate>Wed, 05 Aug 2026 09:00:08 +0000</pubDate>
      <link>https://dev.to/ranjithvutnoor/gpu-accelerating-mscred-with-cuda-im2col-gemm-and-a-custom-pytorch-extension-57b2</link>
      <guid>https://dev.to/ranjithvutnoor/gpu-accelerating-mscred-with-cuda-im2col-gemm-and-a-custom-pytorch-extension-57b2</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;During my M.Tech in Data Science and Artificial Intelligence at IIT Bhilai (2021–2023), I conducted thesis research on multivariate time-series anomaly detection and GPU acceleration using industrial process signals.&lt;/p&gt;

&lt;p&gt;My thesis, titled &lt;strong&gt;“Anomaly Detection of Multivariate Time Series Data and Acceleration Using GPUs,”&lt;/strong&gt; explored an MSCRED—Multi-Scale Convolutional Recurrent Encoder-Decoder—and ConvLSTM-based pipeline for modelling relationships between signals and detecting abnormal temporal patterns.&lt;/p&gt;

&lt;p&gt;Although the model produced useful anomaly-detection results, its convolution-heavy encoder created a significant CPU bottleneck. I therefore implemented GPU-accelerated operations using CUDA, transformed convolution into an &lt;code&gt;im2col&lt;/code&gt; plus GEMM workflow, investigated global-memory and shared-memory implementations, and integrated the accelerated operations with PyTorch.&lt;/p&gt;

&lt;p&gt;In the measured workload, encoder runtime decreased from &lt;strong&gt;300 seconds on the CPU to 23.664 seconds on the GPU&lt;/strong&gt;, representing an approximately &lt;strong&gt;12.68× encoder speed-up&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Research attribution:&lt;/strong&gt; MSCRED and ConvLSTM are established architectures introduced by the researchers cited in the References section. This article describes how I used, adapted, profiled, and accelerated selected operations as part of my M.Tech thesis.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data confidentiality:&lt;/strong&gt; The original research involved industrial process data. This article discusses the architecture, optimisation methodology, and aggregate benchmark results without publishing proprietary signals, internal process details, confidential datasets, or restricted source code.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  The Anomaly-Detection Problem
&lt;/h2&gt;

&lt;p&gt;Industrial systems often generate many related sensor and process-control signals at the same time. A single signal may appear normal when viewed independently, while the relationship between several signals may indicate an abnormal operating condition.&lt;/p&gt;

&lt;p&gt;This makes multivariate time-series anomaly detection more difficult than analysing one signal at a time.&lt;/p&gt;

&lt;p&gt;The model must learn:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Relationships between multiple signals&lt;/li&gt;
&lt;li&gt;Changes across different time windows&lt;/li&gt;
&lt;li&gt;Temporal dependencies between successive observations&lt;/li&gt;
&lt;li&gt;Deviations from normal operating patterns&lt;/li&gt;
&lt;li&gt;Reconstruction differences that may indicate anomalies&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The goal of the research was to detect unusual multivariate patterns while preserving the temporal and spatial relationships present in the data.&lt;/p&gt;




&lt;h2&gt;
  
  
  MSCRED and ConvLSTM Architecture
&lt;/h2&gt;

&lt;p&gt;MSCRED models relationships between multiple time-series signals by constructing &lt;strong&gt;signature matrices&lt;/strong&gt; over different temporal windows.&lt;/p&gt;

&lt;p&gt;At a high level, the pipeline contains:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Signature-matrix generation from multivariate signals&lt;/li&gt;
&lt;li&gt;A convolutional encoder for spatial feature extraction&lt;/li&gt;
&lt;li&gt;ConvLSTM layers for temporal modelling&lt;/li&gt;
&lt;li&gt;A decoder that reconstructs expected signal relationships&lt;/li&gt;
&lt;li&gt;Reconstruction-error analysis for anomaly scoring&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The encoder processes the signature matrices through convolutional operations, while ConvLSTM captures how the encoded representations evolve over time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Multivariate signals
        ↓
Signature matrices
        ↓
CNN encoder
        ↓
ConvLSTM
        ↓
Decoder
        ↓
Reconstruction error
        ↓
Anomaly score
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Why Signature Matrices Are Useful
&lt;/h3&gt;

&lt;p&gt;A signature matrix represents pairwise relationships between signals over a selected time interval.&lt;/p&gt;

&lt;p&gt;By generating these matrices at multiple scales, the model can observe both short-term and longer-term relationships. This helps identify anomalies that may not be visible in an individual signal.&lt;/p&gt;

&lt;h3&gt;
  
  
  Role of the Encoder
&lt;/h3&gt;

&lt;p&gt;The convolutional encoder extracts spatial patterns from the signature matrices. It reduces the raw matrix representation into compact feature maps that capture important relationships between signals.&lt;/p&gt;

&lt;h3&gt;
  
  
  Role of ConvLSTM
&lt;/h3&gt;

&lt;p&gt;ConvLSTM models how those spatial representations change over time.&lt;/p&gt;

&lt;p&gt;Unlike a standard fully connected LSTM, ConvLSTM preserves the spatial structure of feature maps while learning temporal dependencies.&lt;/p&gt;

&lt;h3&gt;
  
  
  Role of the Decoder
&lt;/h3&gt;

&lt;p&gt;The decoder reconstructs the expected signature matrices.&lt;/p&gt;

&lt;p&gt;When the reconstructed output differs significantly from the observed input, the reconstruction error can indicate an anomalous pattern.&lt;/p&gt;




&lt;h2&gt;
  
  
  Anomaly-Detection Evaluation
&lt;/h2&gt;

&lt;p&gt;The purpose of the MSCRED and ConvLSTM pipeline was to detect abnormal relationships and temporal behaviour across multiple industrial process signals.&lt;/p&gt;

&lt;p&gt;The model learned normal multivariate patterns by reconstructing signature matrices. During evaluation, the difference between the observed signature matrices and the reconstructed outputs was used to calculate a reconstruction error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Observed signature matrix
            ↓
MSCRED reconstruction
            ↓
Reconstruction error
            ↓
Thresholding
            ↓
Normal or anomalous
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A larger reconstruction error indicated that the observed relationships differed from patterns learned during normal operation and could therefore represent an anomaly.&lt;/p&gt;

&lt;p&gt;The thesis evaluated anomaly-detection quality using the F1 score. Under the reported experimental setup, the &lt;strong&gt;best recorded F1 score was 0.941&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This result represents model-quality evaluation and should be interpreted separately from the CUDA runtime measurements presented later. The GPU memory optimisations were designed to reduce computation time, not to improve predictive accuracy.&lt;/p&gt;




&lt;h2&gt;
  
  
  Where the Performance Bottleneck Appeared
&lt;/h2&gt;

&lt;p&gt;The encoder repeatedly applied convolutional operations to signature matrices.&lt;/p&gt;

&lt;p&gt;On the CPU, these operations involved substantial nested computation across:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Input channels&lt;/li&gt;
&lt;li&gt;Output filters&lt;/li&gt;
&lt;li&gt;Spatial positions&lt;/li&gt;
&lt;li&gt;Kernel dimensions&lt;/li&gt;
&lt;li&gt;Batch elements&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This made the encoder a strong candidate for GPU acceleration because many convolution calculations could be performed in parallel.&lt;/p&gt;

&lt;p&gt;The objective was not to redesign the anomaly-detection model. Instead, it was to preserve its expected computational behaviour while accelerating selected expensive operations.&lt;/p&gt;




&lt;h2&gt;
  
  
  Transforming Conv2D into &lt;code&gt;im2col&lt;/code&gt; and GEMM
&lt;/h2&gt;

&lt;p&gt;A convolution repeatedly applies a kernel to overlapping regions of an input feature map.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;im2col&lt;/code&gt;, or image-to-column, transformation rearranges those local regions into columns of a matrix.&lt;/p&gt;

&lt;p&gt;After this transformation, convolution can be expressed as a general matrix multiplication:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output matrix = Weight matrix × im2col(Input)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This conversion is useful because matrix multiplication is highly parallel and can be executed efficiently on a GPU.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conceptual Transformation
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input feature map
        ↓
Extract overlapping kernel windows
        ↓
Arrange windows as matrix columns
        ↓
Multiply by reshaped filter matrix
        ↓
Reshape result into output feature map
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Why Use GEMM?
&lt;/h3&gt;

&lt;p&gt;GEMM stands for &lt;strong&gt;General Matrix-Matrix Multiplication&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Modern GPU architectures are designed to perform large numbers of multiply-and-accumulate operations in parallel. Expressing convolution as GEMM allows the workload to use that parallelism.&lt;/p&gt;

&lt;h3&gt;
  
  
  Trade-Off
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;im2col&lt;/code&gt; introduces additional memory usage because overlapping input regions are copied into an intermediate matrix.&lt;/p&gt;

&lt;p&gt;The method is most effective when the computational benefit of parallel matrix multiplication outweighs the cost of creating and storing the intermediate representation.&lt;/p&gt;




&lt;h2&gt;
  
  
  CUDA Kernel Design
&lt;/h2&gt;

&lt;p&gt;The CUDA implementation divided the computation across many GPU threads.&lt;/p&gt;

&lt;p&gt;Each thread was responsible for part of the output, while thread blocks grouped related work.&lt;/p&gt;

&lt;p&gt;Important kernel-design considerations included:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mapping output elements to threads&lt;/li&gt;
&lt;li&gt;Selecting thread-block dimensions&lt;/li&gt;
&lt;li&gt;Coalescing memory access where possible&lt;/li&gt;
&lt;li&gt;Reducing unnecessary global-memory operations&lt;/li&gt;
&lt;li&gt;Avoiding excessive synchronisation&lt;/li&gt;
&lt;li&gt;Preserving correct tensor indexing&lt;/li&gt;
&lt;li&gt;Managing intermediate buffers efficiently&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The implementation required careful validation because incorrect indexing in GPU code can produce plausible-looking but incorrect outputs.&lt;/p&gt;




&lt;h2&gt;
  
  
  Global Memory and Shared Memory
&lt;/h2&gt;

&lt;p&gt;The first GPU implementation relied primarily on &lt;strong&gt;global memory&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Global memory provides access to the complete input, but its latency is considerably higher than that of on-chip shared memory.&lt;/p&gt;

&lt;p&gt;The optimised implementation staged reusable tiles inside &lt;strong&gt;shared memory&lt;/strong&gt;. Threads within the same block could then reuse nearby values without repeatedly loading them from global memory.&lt;/p&gt;

&lt;p&gt;The shared-memory optimisation was intended to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reduce repeated global-memory reads&lt;/li&gt;
&lt;li&gt;Improve data locality&lt;/li&gt;
&lt;li&gt;Increase data reuse within each thread block&lt;/li&gt;
&lt;li&gt;Reduce memory-related kernel overhead&lt;/li&gt;
&lt;li&gt;Improve matrix-multiplication efficiency&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Conceptual Data Flow
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Global memory
      ↓
Load reusable tile
      ↓
Shared memory
      ↓
Threads perform repeated calculations
      ↓
Write result to global memory
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Shared memory is limited in capacity, so tile dimensions and thread-block organisation must be selected carefully.&lt;/p&gt;

&lt;p&gt;Poorly selected configurations can:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reduce occupancy&lt;/li&gt;
&lt;li&gt;Increase synchronisation overhead&lt;/li&gt;
&lt;li&gt;Create bank conflicts&lt;/li&gt;
&lt;li&gt;Use too much shared memory per block&lt;/li&gt;
&lt;li&gt;Limit the number of active thread blocks&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Integrating the CUDA Implementation with PyTorch
&lt;/h2&gt;

&lt;p&gt;To use the accelerated operations inside the existing model pipeline, I connected the CUDA implementation to PyTorch through a custom extension.&lt;/p&gt;

&lt;p&gt;The integration enabled PyTorch tensors to be passed to the CUDA implementation and the computed results to be returned to the model pipeline.&lt;/p&gt;

&lt;p&gt;Important integration concerns included:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tensor dimensions&lt;/li&gt;
&lt;li&gt;Device placement&lt;/li&gt;
&lt;li&gt;Data types&lt;/li&gt;
&lt;li&gt;Contiguous-memory assumptions&lt;/li&gt;
&lt;li&gt;Compilation and linking&lt;/li&gt;
&lt;li&gt;Error handling&lt;/li&gt;
&lt;li&gt;CPU-versus-GPU output comparison&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Correctness validation was essential. A faster kernel is not useful if it changes tensor shapes, produces incorrect indexing, introduces unacceptable numerical differences, or behaves inconsistently for the tested configurations.&lt;/p&gt;

&lt;p&gt;The custom extension made it possible to retain PyTorch for model development while using lower-level CUDA operations for selected performance-critical components.&lt;/p&gt;




&lt;h2&gt;
  
  
  Experimental Setup
&lt;/h2&gt;

&lt;p&gt;The benchmark used the following environment:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;GPU:&lt;/strong&gt; NVIDIA RTX A6000, 48 GB&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CPU:&lt;/strong&gt; 16-core Intel Xeon Gold 5218&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;System memory:&lt;/strong&gt; 64 GB&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data points:&lt;/strong&gt; 36,000&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Number of features:&lt;/strong&gt; 30&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Batch size:&lt;/strong&gt; 128&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CPU threads:&lt;/strong&gt; 32&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Timing Methodology
&lt;/h3&gt;

&lt;p&gt;The timings reported here are measurements from my thesis experiments using the specified hardware and workload. The CPU and GPU implementations used the same input dimensions and batch configuration.&lt;/p&gt;

&lt;p&gt;The results should be treated as comparative experimental measurements rather than universal library benchmarks. Performance may vary with implementation details, CUDA configuration, tensor dimensions, data-transfer costs, compiler settings, and hardware.&lt;/p&gt;




&lt;h2&gt;
  
  
  Performance Benchmark Results
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Component&lt;/th&gt;
&lt;th&gt;CPU&lt;/th&gt;
&lt;th&gt;GPU: global memory&lt;/th&gt;
&lt;th&gt;GPU: shared memory&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Encoder&lt;/td&gt;
&lt;td&gt;300 s&lt;/td&gt;
&lt;td&gt;27.492 s&lt;/td&gt;
&lt;td&gt;23.664 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ConvLSTM&lt;/td&gt;
&lt;td&gt;1,200 s&lt;/td&gt;
&lt;td&gt;909.208 s&lt;/td&gt;
&lt;td&gt;847.260 s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Total runtime&lt;/td&gt;
&lt;td&gt;2,700 s&lt;/td&gt;
&lt;td&gt;1,594 s&lt;/td&gt;
&lt;td&gt;1,481 s&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Results at a Glance
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Anomaly-detection quality:&lt;/strong&gt; best recorded F1 score of &lt;strong&gt;0.941&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Encoder acceleration:&lt;/strong&gt; approximately &lt;strong&gt;12.68×&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;End-to-end acceleration:&lt;/strong&gt; approximately &lt;strong&gt;1.82×&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Total runtime reduction:&lt;/strong&gt; approximately &lt;strong&gt;45.1%&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The shared-memory implementation reduced encoder runtime from &lt;strong&gt;300 seconds to 23.664 seconds&lt;/strong&gt;, producing an approximately &lt;strong&gt;12.68× encoder speed-up&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;For the complete measured pipeline, runtime decreased from &lt;strong&gt;2,700 seconds to 1,481 seconds&lt;/strong&gt;. The total-runtime measurement represents the complete measured pipeline rather than only the encoder and ConvLSTM components shown separately.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why the Encoder Improved More Than ConvLSTM
&lt;/h2&gt;

&lt;p&gt;The convolutional encoder benefited strongly from GPU execution because its operations provided substantial data parallelism.&lt;/p&gt;

&lt;p&gt;ConvLSTM achieved a smaller improvement because of:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Recurrent dependencies&lt;/li&gt;
&lt;li&gt;Sequential temporal processing&lt;/li&gt;
&lt;li&gt;Memory movement&lt;/li&gt;
&lt;li&gt;Repeated state updates&lt;/li&gt;
&lt;li&gt;More limited parallelism across time steps&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consequently, the &lt;strong&gt;12.68× encoder acceleration&lt;/strong&gt; did not translate into a &lt;strong&gt;12.68× end-to-end speed-up&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;After the encoder was accelerated, ConvLSTM became the dominant runtime bottleneck.&lt;/p&gt;

&lt;p&gt;This is an important performance-engineering lesson: accelerating one component can move the bottleneck to another part of the system.&lt;/p&gt;




&lt;h2&gt;
  
  
  Correctness Validation
&lt;/h2&gt;

&lt;p&gt;The CUDA implementation was compared with the reference implementation for the tested tensor shapes and configurations.&lt;/p&gt;

&lt;p&gt;The optimisation work focused on reducing execution time while preserving the expected computational behaviour. Model-quality evaluation and runtime evaluation were treated as separate concerns.&lt;/p&gt;




&lt;h2&gt;
  
  
  Engineering Challenges
&lt;/h2&gt;

&lt;p&gt;Several engineering challenges appeared during the implementation.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Correct Tensor Indexing
&lt;/h3&gt;

&lt;p&gt;The CUDA kernel had to reproduce the same logical output as the reference convolution operation.&lt;/p&gt;

&lt;p&gt;A small indexing error could generate incorrect feature maps without necessarily causing a runtime failure.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Memory Management
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;im2col&lt;/code&gt; transformation created additional intermediate data.&lt;/p&gt;

&lt;p&gt;This required careful allocation, reuse, and release of GPU memory.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Synchronisation
&lt;/h3&gt;

&lt;p&gt;Threads sharing data through shared memory had to synchronise at appropriate points.&lt;/p&gt;

&lt;p&gt;Missing or unnecessary synchronisation could cause incorrect results or reduced performance.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Kernel Configuration
&lt;/h3&gt;

&lt;p&gt;Thread-block dimensions and tile sizes affected:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Occupancy&lt;/li&gt;
&lt;li&gt;Shared-memory usage&lt;/li&gt;
&lt;li&gt;Memory access&lt;/li&gt;
&lt;li&gt;Work distribution&lt;/li&gt;
&lt;li&gt;Overall kernel performance&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  5. PyTorch Integration
&lt;/h3&gt;

&lt;p&gt;The extension had to account for tensor shapes, data types, device placement, memory layout, compilation, linking, and output comparison.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Measuring the Correct Bottleneck
&lt;/h3&gt;

&lt;p&gt;Improving one component changed the relative cost of other components.&lt;/p&gt;

&lt;p&gt;Profiling therefore had to be repeated after major optimisations.&lt;/p&gt;




&lt;h2&gt;
  
  
  Engineering Lessons
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Optimising One Component Does Not Guarantee an Equivalent End-to-End Improvement
&lt;/h3&gt;

&lt;p&gt;Once the encoder was accelerated, ConvLSTM represented a larger proportion of the remaining runtime.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. &lt;code&gt;im2col&lt;/code&gt; Makes Convolution GPU-Friendly but Introduces Memory Overhead
&lt;/h3&gt;

&lt;p&gt;The transformation enables GEMM-based execution while creating a larger intermediate representation.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Shared Memory Is Valuable When Threads Repeatedly Reuse Nearby Data
&lt;/h3&gt;

&lt;p&gt;Its benefit depends on access patterns, tile sizes, synchronisation, and thread-block configuration.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Profiling Must Guide Optimisation
&lt;/h3&gt;

&lt;p&gt;Performance work should focus on measured bottlenecks rather than assumptions about which component is slow.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Correctness Is as Important as Speed
&lt;/h3&gt;

&lt;p&gt;GPU output should be compared against a trusted reference implementation before performance improvements are accepted.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Custom PyTorch Extensions Offer Flexibility at the Cost of Additional Complexity
&lt;/h3&gt;

&lt;p&gt;Device handling, tensor shapes, data types, compilation, numerical validation, and fallback behaviour all require careful attention.&lt;/p&gt;




&lt;h2&gt;
  
  
  Frequently Asked Questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What is MSCRED?
&lt;/h3&gt;

&lt;p&gt;MSCRED stands for &lt;strong&gt;Multi-Scale Convolutional Recurrent Encoder-Decoder&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It is an architecture designed to model relationships between multiple time-series signals and detect abnormal behaviour through reconstruction error.&lt;/p&gt;

&lt;h3&gt;
  
  
  What does &lt;code&gt;im2col&lt;/code&gt; do?
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;im2col&lt;/code&gt; rearranges overlapping convolution windows into matrix columns, allowing convolution to be expressed as matrix multiplication.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why did shared memory help?
&lt;/h3&gt;

&lt;p&gt;Shared memory allowed threads in the same block to reuse data without repeatedly loading it from slower global memory. This reduced memory-access overhead for reusable tiles.&lt;/p&gt;

&lt;h3&gt;
  
  
  Did GPU memory optimisation improve the F1 score?
&lt;/h3&gt;

&lt;p&gt;That was not the purpose of the optimisation, and this article does not claim that it did.&lt;/p&gt;

&lt;p&gt;The best recorded F1 score describes anomaly-detection quality in the thesis experiments. The CPU and GPU timing results describe computational performance. They should be interpreted separately.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why was the encoder speed-up much larger than the total speed-up?
&lt;/h3&gt;

&lt;p&gt;After the encoder became faster, ConvLSTM represented a larger share of total runtime. The overall system was therefore limited by the remaining bottleneck.&lt;/p&gt;

&lt;h3&gt;
  
  
  Is a Custom CUDA Kernel Always Faster Than PyTorch Operations?
&lt;/h3&gt;

&lt;p&gt;No.&lt;/p&gt;

&lt;p&gt;Optimised PyTorch and CUDA libraries are already highly efficient for many operations. A custom kernel is most useful when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The workload has a specialised access pattern&lt;/li&gt;
&lt;li&gt;Existing operations create unnecessary overhead&lt;/li&gt;
&lt;li&gt;Profiling identifies a clear bottleneck&lt;/li&gt;
&lt;li&gt;Correctness and maintenance costs are justified&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Can the Original Industrial Dataset Be Shared?
&lt;/h3&gt;

&lt;p&gt;No.&lt;/p&gt;

&lt;p&gt;The original dataset contains industrial process information. A public reproduction would require synthetic or appropriately anonymised multivariate time-series data.&lt;/p&gt;

&lt;h3&gt;
  
  
  Are These Benchmark Results Universal?
&lt;/h3&gt;

&lt;p&gt;No.&lt;/p&gt;

&lt;p&gt;Performance depends on GPU architecture, CPU configuration, tensor dimensions, batch size, kernel implementation, memory layout, CUDA and PyTorch versions, compiler settings, and workload characteristics.&lt;/p&gt;

&lt;p&gt;The reported numbers apply to the specific experimental setup described in this article.&lt;/p&gt;




&lt;h2&gt;
  
  
  Limitations and Data-Privacy Considerations
&lt;/h2&gt;

&lt;p&gt;The reported results were obtained on a specific hardware configuration and workload.&lt;/p&gt;

&lt;p&gt;Different GPUs, tensor dimensions, batch sizes, memory layouts, CUDA versions, and kernel configurations may produce different results.&lt;/p&gt;

&lt;p&gt;The original dataset cannot be published because it contains industrial process information. A public reproduction would therefore require synthetic or appropriately anonymised multivariate time-series data.&lt;/p&gt;

&lt;p&gt;This article presents aggregate benchmark measurements and technical methodology rather than the complete industrial dataset or restricted implementation.&lt;/p&gt;




&lt;h2&gt;
  
  
  Future Work
&lt;/h2&gt;

&lt;p&gt;Future work could focus on:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Profiling and optimising the ConvLSTM component&lt;/li&gt;
&lt;li&gt;Reducing intermediate memory allocation&lt;/li&gt;
&lt;li&gt;Reducing host-to-device and device-to-device memory movement&lt;/li&gt;
&lt;li&gt;Comparing the custom implementation with optimised CUDA libraries&lt;/li&gt;
&lt;li&gt;Evaluating additional tile and thread-block configurations&lt;/li&gt;
&lt;li&gt;Testing across different GPU architectures&lt;/li&gt;
&lt;li&gt;Reproducing the workflow using synthetic public data&lt;/li&gt;
&lt;li&gt;Adding automated correctness and regression tests&lt;/li&gt;
&lt;li&gt;Measuring kernel-level execution using GPU profiling tools&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This work was completed as part of my M.Tech thesis research at the &lt;strong&gt;Indian Institute of Technology Bhilai&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It demonstrated how low-level GPU optimisation can be integrated into a deep-learning anomaly-detection pipeline.&lt;/p&gt;

&lt;p&gt;The convolutional encoder benefited substantially from:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;CUDA parallelisation&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;im2col&lt;/code&gt;-based lowering&lt;/li&gt;
&lt;li&gt;GEMM&lt;/li&gt;
&lt;li&gt;Shared-memory data reuse&lt;/li&gt;
&lt;li&gt;Custom PyTorch integration&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Encoder runtime decreased from &lt;strong&gt;300 seconds to 23.664 seconds&lt;/strong&gt; in the measured workload.&lt;/p&gt;

&lt;p&gt;The broader result also illustrated an important systems principle: once one stage is accelerated, another stage may become the new performance bottleneck.&lt;/p&gt;

&lt;p&gt;In this case, ConvLSTM limited the end-to-end improvement even after the encoder achieved a substantial speed-up.&lt;/p&gt;

&lt;p&gt;The work reinforced that successful performance engineering requires both low-level optimisation and system-level measurement.&lt;/p&gt;




&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Zhang, C., Song, D., Chen, Y., Feng, X., Lumezanu, C., Cheng, W., Ni, J., Zong, B., Chen, H., and Chawla, N. V. (2019). &lt;strong&gt;A Deep Neural Network for Unsupervised Anomaly Detection and Diagnosis in Multivariate Time Series Data.&lt;/strong&gt; &lt;em&gt;Proceedings of the AAAI Conference on Artificial Intelligence&lt;/em&gt;, 33(01), 1409–1416. &lt;a href="https://doi.org/10.1609/aaai.v33i01.33011409" rel="noopener noreferrer"&gt;https://doi.org/10.1609/aaai.v33i01.33011409&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Shi, X., Chen, Z., Wang, H., Yeung, D.-Y., Wong, W.-K., and Woo, W.-C. (2015). &lt;strong&gt;Convolutional LSTM Network: A Machine Learning Approach for Precipitation Nowcasting.&lt;/strong&gt; &lt;em&gt;Advances in Neural Information Processing Systems 28&lt;/em&gt;, 802–810. &lt;a href="https://proceedings.neurips.cc/paper_files/paper/2015/hash/07563a3fe3bbe7e3ba84431ad9d055af-Abstract.html" rel="noopener noreferrer"&gt;https://proceedings.neurips.cc/paper_files/paper/2015/hash/07563a3fe3bbe7e3ba84431ad9d055af-Abstract.html&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;NVIDIA. &lt;strong&gt;CUDA C++ Programming Guide.&lt;/strong&gt; &lt;a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/" rel="noopener noreferrer"&gt;https://docs.nvidia.com/cuda/cuda-c-programming-guide/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;PyTorch. &lt;strong&gt;Custom C++ and CUDA Operators.&lt;/strong&gt; &lt;a href="https://docs.pytorch.org/tutorials/advanced/cpp_custom_ops.html" rel="noopener noreferrer"&gt;https://docs.pytorch.org/tutorials/advanced/cpp_custom_ops.html&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Citation and Feedback
&lt;/h2&gt;

&lt;p&gt;If this article informs academic or technical work, please cite the original MSCRED and ConvLSTM papers above.&lt;/p&gt;

&lt;p&gt;To refer specifically to my thesis implementation, optimisation process, or reported benchmarks, you may cite this article as:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Vutnoor, R. (2026). “GPU-Accelerating MSCRED with CUDA, im2col, GEMM, and a Custom PyTorch Extension.” DEV Community.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you found the article useful, a reaction, comment, or constructive technical question on DEV would be appreciated.&lt;/p&gt;




&lt;p&gt;I am &lt;strong&gt;Ranjith Vutnoor&lt;/strong&gt;, an AI/ML Software Engineer and IIT Bhilai alumnus working on production RAG systems, LLM evaluation, model fine-tuning, PyTorch, and GPU-accelerated machine learning.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://ranjithvutnoor.github.io/portfolio/" rel="noopener noreferrer"&gt;Portfolio&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/ranjithvutnoor" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.linkedin.com/in/ranjithvutnoor/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>pytorch</category>
      <category>cuda</category>
      <category>machinelearning</category>
      <category>performance</category>
    </item>
  </channel>
</rss>
