Momentum-Refreshed Retrieval Indexes for Code Comment Generation

Writing comments, docstrings and commit messages is the part of software work developers skip under deadline pressure, and the missing explanations pile up as documentation debt. Some of the strongest automatic comment writers are retrieval-augmented. For a given function, they look up similar functions that already have comments and use those comments as templates. The best of these systems also train the retriever itself, rewarding it for fetching examples that help the generator write a good comment. That joint training has a hidden cost. Every time the retriever's encoder changes, the stored vectors for the whole example corpus go out of date. JOINTCOM, which trains a CodeT5 retriever with feedback from the generator's loss, rebuilds its dense index only once per epoch because rebuilding after every step is too expensive. As a result the retriever spends most of each epoch searching an index built by an older version of itself.

We propose to keep that index fresh with the main idea from momentum contrastive learning. A second "key" encoder has weights that are a slow moving average of the trained encoder. It re-encodes a small rotating slice of the example corpus at every training step, so the whole index is refreshed many times per epoch. Because every stored vector comes from nearly the same slowly drifting encoder, the index stays internally consistent even though different slices were written at different times. The same index also serves as a large pool of negatives, which removes the retriever's dependence on a large physical batch on a single GPU. The bet is narrow and testable. At an equal budget of encoder passes, a momentum-refreshed index should give better retrieval and better comments than periodic full rebuilds with the live encoder. It should also absorb newly written code without a rebuild, which matters for repositories that keep changing.

Core Claim

Momentum Contrast (MoCo) addresses a problem that looks like JOINTCOM's. Negatives stored in a queue were encoded by an older network, and MoCo limits the damage by producing them with a key encoder updated as an exponential moving average, $\theta_k \leftarrow m\theta_k + (1-m)\theta_q$. Here $\theta_q$ is the trained (query) encoder, $\theta_k$ the key encoder, and $m$ a coefficient close to 1. MoCo v2 showed this lets a batch of 256 match or beat SimCLR at batch 8192 on ImageNet linear probing, using about 5GB of GPU memory. Nobody in this literature has used the moving-average encoder for the other half of the problem, which is keeping a retrieval index usable while the retriever learns.

Our claim is that a rolling, momentum-encoded index is a better use of a fixed encoding budget than periodic full rebuilds. The two failure modes differ. A periodically rebuilt index is consistent but stale: all its vectors come from one old encoder. A partially refreshed index built with the live encoder is fresh but inconsistent: different slices come from encoders that differ by many gradient steps. With a momentum encoder, the encoder drift across one full refresh cycle of $K$ steps scales roughly as $K(1-m)$. This follows directly from the per-step update moving $\theta_k$ a fraction $(1-m)$ of the way toward $\theta_q$. We therefore expect a design rule: choose the slice size so that $K(1-m) \ll 1$, and the index behaves as if it were rebuilt by a single encoder.

Research Program

We will build on the JOINTCOM setup: a shared CodeT5 backbone, a dense retriever that fetches the top-$k$ commented examples, and a generator whose loss on each retrieved example is fed back to train the retriever. We change three things. First, we add a key encoder updated by moving average, and at each step it re-encodes a fixed-size slice of the example corpus in a fixed rotation without gradient tracking. With $m=0.9999$ and an 85k-example corpus such as JCSD, a slice of about 85 functions per step refreshes the index every 1,000 steps. That costs roughly 2.6 times the encoding work of one per-epoch rebuild at batch 32, and we will report and match this cost explicitly. Second, the retriever is trained with a contrastive loss in which the positive is the example the generator found most useful. The negatives come from the momentum index, not just the current batch, which removes the batch-size ceiling that TransformCode reports for structural code encoders. Third, when the codebase changes, new functions are written into the index by the key encoder at insertion time, with no retraining or rebuild.

Two risks follow from treating the index as a negative pool. Code corpora contain many functions that are functionally the same but written differently, so some "negatives" are really positives. Following the diversity-sensitive weighting of CODER, which reweights queue negatives by the spread of their similarities to the anchor, we will test one simple guard. Negatives whose stored comment closely matches the target comment are masked out. This also partly addresses the offline filtering concern that CoRNStack handles with dual consistency filtering. We treat the guard as an ablation, not a core ingredient.

The analysis component measures staleness directly. At regular checkpoints we re-encode the full corpus with the current trained encoder. We then measure the average cosine gap between stored and fresh vectors, and how often the stored index's top-$k$ differs from the fresh top-$k$. We do this for each index-maintenance strategy and relate these quantities to final comment quality.

Baselines

The naive reference point is a frozen retriever. The encoder is fixed after initialization, the index is built once, and only the generator trains. This tells us whether joint retriever training is worth anything in our setup. A second naive point is lexical retrieval through Lucene, as used in EditSum and HGNN. HGNN's authors themselves name text-similarity retrieval as their limitation.

The strongest existing method is JOINTCOM with its per-epoch index refresh, run in our codebase with the same CodeT5 checkpoint, data splits, top-$k$, and generator. JOINTCOM reports gains of 7.6% to 28.4% over baselines across BLEU, METEOR, ROUGE-L and CIDEr on JCSD, and 9.6% to 30.0% on PCSD. The file gives these as relative gains only, and no reported absolute JOINTCOM score was found on Lacuna. We will therefore reproduce it and treat our reproduction as the reference. As an external sanity check on JCSD, ESALE reports improving UniXcoder by 6.83% BLEU and 13.62% METEOR through summary-focused objectives without retrieval. We will report ESALE-style training as a non-retrieval comparison.

The ablation that isolates our key ingredient is the same rolling slice refresh performed with the live trained encoder instead of the momentum encoder. It is matched in slice size, number of encoder passes, and negatives. A second ablation is periodic full rebuild with the live encoder at whatever frequency spends the same total encoding budget as our method, which for the example above is about 2.6 rebuilds per epoch. All methods get the same tuning budget: a sweep over learning rate plus each method's one maintenance hyperparameter (rebuild frequency or $m$), with three seeds each. Beating JOINTCOM means a gain on BLEU and METEOR on both JCSD and PCSD that exceeds seed variance at matched encoding compute. Beating the ablations is the claim that actually matters. If the live-encoder rolling refresh or the compute-matched periodic rebuild ties our method, the momentum encoder adds nothing and the claim is false.

Why not just…?

Why not just rebuild the index more often with the live encoder? This is the most serious threat, because extra rebuilds may be all JOINTCOM was missing. Our argument is that a budget-limited refresh must either be infrequent, and so stale, or partial, and so inconsistent across slices, and the momentum encoder avoids both. That argument is untested. The compute-matched periodic-rebuild and live rolling-refresh ablations settle it directly. The staleness measurements will show whether any gain comes from index consistency rather than freshness alone.

Why not just use lexical retrieval, which never goes stale? BM25 or Lucene has no staleness problem, but it retrieves by surface overlap. On the CodeSearchNet real-query evaluation, Husain et al. report ElasticSearch at 0.337 NDCG against 0.574 for a simple neural bag-of-words. JOINTCOM's gains are measured against such retrieval. Lucene remains a baseline here. If it matches the trained retrievers on project-split data, the retrieval-training story collapses regardless of how the index is maintained.

Why not just use Gradient Caching to get large in-batch negatives? Gradient Caching computes the exact large-batch contrastive gradient on small hardware, reaching 79.3% top-20 accuracy on Natural Questions on one RTX 2080 Ti with about 20% runtime overhead, and CodeXEmbed uses it for code retrieval. It enlarges the set of negatives, but it does nothing about the stale retrieval index that feeds the generator, which is the problem we target. We will still run a GradCache retriever at batch 4,096 with per-epoch rebuild. This separates how much of any gain comes from more negatives and how much from index freshness.

Why not just prompt a large language model? DocAgent reports that plain ChatGPT documentation reaches only 61.10% truthfulness (the share of mentioned entities that exist in the repository), against 95.74% for its dependency-aware agent. Prompting without grounding invents identifiers. Retrieved project-local exemplars are one cheap form of grounding. We include a few-shot LLM baseline that uses our retrieved exemplars. This tests whether better retrieval helps even a strong generator, without competing with it on raw fluency.

Proposed Experiments

The main experiments train every method on JCSD and PCSD using the splits from JOINTCOM. They report BLEU, METEOR, ROUGE-L and CIDEr. We also report EditSum's count of correctly generated rare words (frequency under 100), since project-specific identifiers are where retrieval should help most. For cross-language checks we use CCSD, where HGNN reports beating Rencos by 1.42 BLEU-4, and we will reproduce HGNN there. All runs log encoder forward passes, peak GPU memory and wall-clock time on a single GPU.

The first decisive check is the matched-compute comparison against the live-encoder ablations described above. Alongside it we sweep $m$ and slice size to test the $K(1-m)$ design rule. The rule predicts that comment quality should depend mainly on the product, not on either factor alone, and that quality should degrade once the product approaches one.

The second decisive check targets the evolving-repository setting that motivates the work. We use the project-partitioned 2-million-method Java corpus from EditSum and order projects by time. Models are trained on early projects, and later projects' commented functions are then inserted into the index. We compare three conditions: insertion by the momentum key encoder with no rebuild, insertion by the trained encoder, and a full rebuild. If momentum insertion matches the full rebuild at a fraction of its cost, that directly reduces the cost of maintaining automatic documentation as code changes. If it does not, the method is only an efficiency trick for training, and we will report it as such.