Deep Buha

Systems Engineer

I build interpretability-driven systems for large language models at IIT Gandhinagar.

View Full Résumé

About

I'm a systems engineer with a focus on making large language models more efficient without sacrificing the semantics they've learned. My work sits at the intersection of interpretability, memory systems, and low-level C++ engineering.

Currently at IIT Gandhinagar, I'm building Aegis— an interpretability-driven KV cache eviction system that outperforms existing approaches like H2O on the Needle-in-a-Haystack benchmark, running entirely on consumer-grade hardware.

When I'm not deep in attention heads and cache lines, I read research papers obsessively and document what I learn in my daily log below.

Projects

Daily Log

Today was a turning point — I finally got Aegis generating text correctly after a week of fighting broken code. ## The Diagnosis I did a full code audit of `main.cpp` and found the root cause of my problems. The biggest bug was on this line: ```cpp llama_batch next_batch = llama_batch_get_one(&next_token, 1); next_batch.pos[0] = n_past; // ← THIS IS UNDEFINED BEHAVIOR ``` `llama_batch_get_one()` returns a batch where `pos` is `NULL`. That's intentional — `NULL` is the signal to llama.cpp to auto-track positions internally (it just counts up: 0, 1, 2, 3...). When I wrote `next_batch.pos[0] = n_past`, I was dereferencing a null pointer. The fact it didn't crash immediately was pure luck — it was writing to whatever memory address happened to be there. The fix was dead simple: delete that line entirely. Let auto-tracking do its job. ## Other Fixes Applied - **No GPU offloading**: `model_params.n_gpu_layers` defaulted to `0`, meaning all 24 layers ran on CPU. Added `model_params.n_gpu_layers = -1` to push everything to my RTX 3050. Inference went from painfully slow to instant. - **Double `llama_sampler_accept()`**: `llama_sampler_sample()` already calls accept internally (it's in the docs at llama.h:1462). I was calling it again manually, which double-notifies penalty samplers. Removed both redundant calls. - **No tokenization error check**: `llama_tokenize()` returns negative on failure. I wasn't checking. Added the guard. - **Buffer too small**: `buf[64]` for token-to-text conversion. Some tokens (Unicode, multi-byte) can exceed that. Bumped to `buf[256]`. ## The Sampling Seed Discovery After fixing the bugs, I switched from greedy sampling to `temp(0.8) + dist(42)` for creative output. But the output was identical every run. Spent 10 minutes confused before realizing: `42` is a **fixed seed**. Same seed → same random number sequence → same output. Changed to `LLAMA_DEFAULT_SEED` (0xFFFFFFFF) which tells llama.cpp to pick a random seed, and now I get different outputs each run as expected. ## Documentation Sprint Built an offline llama.cpp function reference since there's literally no documentation online that accurately describes the current API. Went through all 1571 lines of `llama.h` and documented every function I'm using — signatures, parameter meanings, return values, gotchas. Seven files covering lifecycle, tokenization, decoding, sampling, KV cache memory, logging, and a complete working generation template. This is my reference for when I go offline to write the real Aegis code. ## Where I Actually Stand The honest truth: my `main.cpp` is a working "hello world" for llama.cpp inference. It loads a model, tokenizes a prompt, runs the forward pass, and prints generated text token by token. But it has zero KV cache eviction logic — which is the entire point of Aegis. The real work starts now: reading the KV cache source code (`llama-kv-cache.h/cpp`), understanding cell tracking, and figuring out where to inject my S_i scoring formula into the inference pipeline. Current status: I can load a model and generate text. Next: understand the memory architecture well enough to modify it.

Today the Sponge effect was the topic i went in depth. which i knew at high level as problem of transformer so i didnt went in depth before. but now i understand it heavily. so first let me give the type or 2 effect different kind of sponge effect. 1.) Global Sponge (position-based): First few tokens absorb disproportionate attention from the ENTIRE sequence. "The" at position 0 gets attended to by every single token that comes after it. 2.)Local Sponge (structural/punctuation-based): Punctuation tokens like "." and "\n" absorb attention locally — from the tokens immediately around them, at sentence boundaries. Not as extreme as global sinks but still inflated relative to their semantic content. we have some terms also to know before going in depth: 1.) sink tokens - "The", ".", "\n" 2.) sparcity - Percentage of attention weights that are exactly zero. so in terms of this paper we know heavy hitters will be sinks, but it is not true the other way around. also even if the sentence is short that is where the distinction of H2O and AEGIS comes to picture as H2O takes all high scoring tokens and in Aegis we are trying to distinguish between them, as we wanna keep the semantic heavy hitters and not sinks. --> now the eviction policy comes to the picture. 1.) for n tokens we only choose Si rows and all other rows are 0. Q = R^nxd, K = R^nxd, V = R^nxd from this n rows let K<=i be the first i rows of K, and let k be the budget of space. and the Ksi is the sub matrix of K which selects si rows from K and else are 0 rows.

I went therogh the [Aandrej Kerapthy's](https://www.youtube.com/watch?v=kCc8FmEb1nY) nanoGPT tutorial. i have given detailed explaination of topics from the video and also i have added more explanations and some extra information and explainiation which i felt was also improtant to learn. other than this i have also read paper on H2O caching, where i learned 4 diffrent ways which they compared at the start which were pretty basic in terms of what they had implemented. 1.) Dynamic sparcity - computationally expensive 2.) static sparcity(strided) - Keeps a sliding window of recent tokens (the diagonal line) plus every $N$-th token from the past (the periodic vertical stripes). 3.) static sparcity(static) - Keeps only a fixed window of the most recent tokens. Everything older is trashed. 4.) Static Sparsity w. $H_2O$ (Heavy Hitters) - H2O keeps two sets of tokens: 1. Recent tokens — last W tokens always kept (local window) 2. Heavy hitters — tokens with highest ACCUMULATED attention score example : if token "Paris" received attention 0.4 from token 10, 0.3 from token 11, 0.5 from token 12 — its accumulated score = 1.2. Token "the" received 0.02 from token 10, 0.01 from token 11, 0.02 from token 12 — accumulated score = 0.05. H2O keeps "Paris", evicts "the". on top of just talking about the storing of KV-cache problem they also pointed out to problem for memory needed to compute attention, which is solved by a hardware hack known as flash attention as explained below: GPU has 2 parts i) HBM (High Bandwidth Memory) - The main memory, huge and slow. and ii)SRAM (Static RAM) - The memory right next to the compute cores, fast and small. all math happens in SRAM. and in flash attention we Load a small "tile" (block) of $Q, K,$ and $V$ from HBM into the fast SRAM. Calculates the attention scores for just that block.Calculates the softmax on the fly in SRAM (using a math trick called "online softmax"). Writes the final result directly back to HBM. though it is not at all related to the main problem of kv cahing, it was pretty interesting to learn about. what is a good KV-cache eviction policy? the given is a trade-off triangle --> to have a production system we need 1.) Small Cache Size (Memory) - This is the most important, that we cant store large amount of K, V vectors in memory 2.) Low Miss Rate (Accuracy) - we must keep correct tokens, giving highest attention scores. 3.) Low-Cost Eviction (Speed) - the algorithm must be fast 3 challanges - First, it is not immediately clear whether the size of the KV cache can be restricted—each decoding step might, in principle, require access to all previous attention keys and values. Second, identifying an optimal eviction policy that maintains generation accuracy is a combinatorial problem. Finally, even if an optimal policy can be brute-forced, it is infeasible for deployment on real-world applications.

Today I read the H2O paper (Heavy-Hitter Oracle) by Zhang et al. The core idea is elegant — track cumulative attention scores across generation steps and evict KV pairs that consistently receive low attention. Their "heavy hitter" tokens are the ones that accumulate disproportionate attention mass. This gives me a strong baseline to beat with Aegis. The gap I see: H2O still trusts raw attention as a proxy for importance, which Jain & Wallace showed is unreliable. My composite scoring function should outperform on adversarial needle-retrieval tasks where the "needle" token has diffuse attention.

Writings