Enterprise knowledge · Research feature

Retrieval-Augmented Generation for Scientific Code Understanding

A new local AI system for scientific code analysis outperforms cloud-based models by using retrieval-augmented generation with small, on-device models.

Adapted from research by Aaron Nobile, Andreas Adelmann, Mohsen Sadr.

arXiv preprint revision · 2026-09-10 · Attribution & reuse
In this article
Editorial illustration of linked workflow.

Editor’s introduction

The study evaluates a Retrieval-Augmented Generation system designed for understanding scientific C++ code from the IPPL codebase. It compares seven different language models across a 100-question benchmark, measuring accuracy via an independent frontier model. Results show that model family and retrieval quality are more influential than parameter size, with the Qwen3.5 model achieving the highest average score of 0.795. The system’s architecture separates offline code parsing and embedding from online inference, enabling small local models to deliver accurate, repository-specific answers. A key finding is that while newer models perform better, they also introduce higher latency. The data reveals that most answers—particularly with 7B and 32B models—are only partially correct, with 44 and 46 questions respectively marked as ‘Partial’. The Gemma4 model shows a lower rate of partial answers, with only 27 marked as such, indicating better consistency in response quality.

Introduction

Large language models (LLMs) have become capable assistants for software development, but the strongest systems generally depend on large, cloud-hosted models. This creates practical barriers for scientific software: repositories may be private, inference can be expensive, and the relevant knowledge is often distributed across years of specialized C++ development, a challenge also observed in repository-level code generation research. This work asks whether a smaller, locally executed model can answer technical questions about such a repository when the surrounding retrieval system does more of the code-understanding work in advance.

We present a retrieval-augmented system that separates expensive offline ingestion from lightweight online question answering. The offline stage parses source and documentation, constructs structural relationships, generates entity-level explanations, and embeds the resulting records. At query time, the system combines semantic retrieval, metadata reranking, query-intent routing, and structural expansion before prompting a local answering model. We evaluate the approach on 100 questions across eleven categories from the IPPL scientific C++ codebase. Our contributions are: (i) a code-aware ingestion pipeline that represents functions, files, modules, and call neighborhoods; (ii) a retrieval pipeline designed to provide concise, grounded context to small local models; and (iii) an empirical comparison of seven answering models and an agentic retrieval baseline.

Retrieval-Augmented Generation (RAG)

A major limitation of Large Language Models is that their knowledge is limited to the information contained in their training data and the context currently provided in the prompt. In the case of coding agents, this presents a challenge, as software projects often contain thousands of files and many years of development history that cannot be provided to the model at once. Retrieval-Augmented Generation (RAG) addresses this problem by combining information retrieval with language generation. Instead of relying solely on the model’s internal knowledge, a RAG system first searches an external knowledge source for information relevant to the user’s request and then provides the retrieved information as additional context to the LLM. In the context of coding agents, the external knowledge source is typically the source code repository itself. Files, functions, classes, documentation, and comments are indexed and stored in a searchable format. When the user asks a question or requests a code modification, the agent retrieves the most relevant pieces of information from the codebase and includes them in the prompt sent to the model. This approach allows a model to work with codebases that are significantly larger than its context window and to retrieve information from the current state of the repository rather than relying exclusively on knowledge stored in its parameters. These properties motivate our investigation of whether retrieval can compensate for some limitations of smaller local models. A typical RAG pipeline consists of three main stages. First, documents are processed and converted into vector representations known as embeddings. These embeddings capture the semantic meaning of the code and documentation. Second, a retrieval system performs a similarity search to identify the most relevant documents for a given query. Finally, the retrieved information is appended to the prompt and used by the LLM to generate a response. For coding agents, RAG serves as a bridge between the language model and the software project itself. Rather than attempting to memorize an entire codebase, the model can dynamically access the information it needs, improving both accuracy and scalability; repository-level retrieval has likewise been used to expose cross-file context to code models. This principle forms the basis of the retrieval system presented here.

Vector Store

The vector store is the “library” in which all vectorized content chunks get stored and where retriever.py fetches all Top-k chunks from it. The vector store gets built by the python script vector_store.py. Since generating embeddings and building the vector store is computationally demanding the vector store relies on a persisted manifest which signals the pipeline to not rebuild the vector store if unchanged.

Upon entering a specific user question the search function inside vector_store.py uses the embedded query vector to find top-k closest chunks. Each top-k retrieved chunk will be stored inside results array alongside the chunk content and the determined distance.

All previously shown implementations follow Attention based dense retrieval search only, however hybrid retrieval is important since dense retrieval can miss direct keyword search. For this the vector store appends the retrieved chunk list by using three functions: get_chunks_by_filenames, get_chunks_by_symbols and get_chunks_by_modulenames.

The vector store provides several exact-retrieval helpers in addition to normal semantic vector search. get_chunks_by_filenames retrieves file-level entities for explicitly mentioned files. It distinguishes between a full file name, such as BareField.hpp, and a base name without extension, such as BareField. If only the base name is mentioned, all existing file-level entities with that base name are injected, e.g. BareField.h and BareField.hpp, with distance 0.0. If a full file name is mentioned, the exact file receives distance 0.0, while sibling files with the same base name but different extensions are also added using their normal vector distance.

Retriever

The central component that orchestrates retrieval is retriever.py. Its primary task is to decide which retrieved content chunks are ultimately passed to the LLM and which candidates are filtered out. This functionality overlaps conceptually with parts of the vector store described in subsubsection 3.2.6, but the two components operate at different stages of the retrieval process. The functions in vector_store.py are responsible for storing chunks and computing their initial relevance to a query, including adjustments to the retrieval distance for exact file-name or symbol-name matches. In contrast, retriever.py works with the ranked candidates returned by the vector store and decides how these candidates should be combined, filtered, and balanced before being sent to the LLM.

In this sense, the vector store answers the question: “Which chunks exist, and how close are they to the query?” The retriever answers the follow-up question: “Which mixture of chunks should the LLM actually see?” This makes the retriever the final selection layer between similarity search and answer generation.

After extracting both the categoric terms with the reranker and the query intent with the QueryIntentRouter, the function calls up the implemented FAISS vector search implemented in vector_store.py. The candidate_count is determined both by the selected candidate number k and the self.candidate_k=20 set, which can be adjusted in the config. The semantic candidates are chosen from the search function inside the vector store file. Then exact filename/symbol targets and candidates are acquired by the corresponding functions inside the vector_store. For comparison intent the retriever uses a specific self._retrieve_comparison_candidates(…) function to prevent flooding the candidate pool with only one side of mentioned exact key-name hits.

After enlisting all possible candidates seperately _merge_candidates(…) concatenates all candidate sources. It priotizes injected candidates by order, semantic vector candidates last. Then removes all duplicate chunks. The actual scoring/ranking happens afterward in the reranker. After re-ranking the pipeline the candidates get refined a final time. _select_primary_candidates removes weak reranked primary candidates. _refine_primary_candidates applies query-intent logic and diversify and _ensure_exact_filename_chunks implements final exact-match ordering safeguard.

Metadata Reranker

The file reranker.py implements the metadata reranker used inside the retrieval pipeline. It takes the candidate chunks returned by the vector store and reranks them before the structural expansion step. As described in subsubsection 3.2.6, the vector store returns an L2 distance between the query embedding and each retrieved chunk embedding. The reranker converts this distance into a semantic score and combines it with metadata-based signals that describe how well a chunk matches the query on the level of file names, symbols, namespaces, source types, API calls, data-flow terms, and requested entity types.

The lexical_metadata_score captures direct textual and structural overlap between the query and a candidate chunk. It rewards exact filename matches, exact symbol matches, namespaced symbol matches, namespace matches, and overlap with file paths or symbol names. It also considers whether the query explicitly asks for a header, source, or documentation file and whether the chunk has the corresponding source_type.

The entity_target_score captures whether the chunk matches the type of entity requested by the query intent router. For example, if the user asks for a module, module-level chunks are boosted; if the user asks for a file, file-level chunks are preferred. This prevents lexically related but structurally wrong chunks from dominating the final ranking.

The reranker also contains several query-specific boosts. For API or location queries, it extracts API-bearing terms such as Kokkos::initialize and rewards chunks that contain the corresponding call sites. For data-flow questions, it detects directions such as grid-to-particles or particles-to-grid and boosts chunks containing terms such as gather, scatter, interpolation, or related particle/grid terminology. For comparison questions, it extracts the compared subjects and rewards chunks whose metadata or text matches one of those subjects.

Configuration and Runtime Setup

The configurable architecture of the software allows several important parameters for ingestion, embedding, prompting, retrieval, and model selection to be adjusted without changing the source code directly. These parameters are collected in config/runtime_settings.json. This file therefore acts as the central runtime configuration of the pipeline and defines how the codebase is parsed, which models are used, how explanations are generated, and how retrieved chunks are ranked before they are passed to the final answering model.

For embedding, the active backend is ollama, using nomic-embed-text as the embedding model. The embedder also supports a sentence-transformer backend through the sentence_transformer option, with BAAI/bge-code-v1 listed as the configured sentence-transformer model. In the current evaluation setup, however, embeddings are generated locally through Ollama.

The configuration also defines the model roles used throughout the pipeline. The chunk-level explanation model is set to qwen2.5-coder:32b, while the file-level, module-level, call-chain, and final answer models use qwen2.5-coder:32b-instruct-q4_K_M. This separates the model used for symbol-level code explanations from the instruction-tuned model used for higher-level summaries and final question answering.

Prompt behavior is also configured in runtime_settings.json. The final answering stage uses retrieval_answer_v2, while the preprocessing stages use dedicated prompt modes for chunk explanations, file-level summaries, module-level summaries, and call-chain summaries. This makes it possible to change the prompting strategy for one stage without affecting the others.

Architectural Advantages and Limitations

The architecture of the RAG-Scientific-Code-Agent differs from general-purpose coding agents such as Codex or Claude Code. Codex and Claude Code are designed as interactive agentic coding systems: they can inspect a repository, reason over the current task, edit files, run commands, execute tests, and iterate based on the results. In contrast, the system developed in this project focuses on retrieval-augmented code understanding. Its main architectural decision is to separate expensive retrieval preparation from later inference. The codebase is parsed, enriched with generated explanations, embedded, and stored in a vector store before the user asks questions.

This design has several advantages. First, expensive work is moved into an offline preprocessing stage. LLM-based chunk, file, module, and call-chain explanations only have to be generated once for a given codebase version and configuration. During inference, the system can reuse this prepared retrieval context instead of repeatedly asking the model to rediscover the structure of the repository. Second, the generated vector store is specialized for the target codebase. This is especially useful for scientific C++ projects, where relevant information is often distributed across templates, headers, implementation files, namespaces, and build or test directories. Third, the architecture improves reproducibility: the runtime settings, prompt modes, model names, and generated artifacts can be stored and compared across evaluation runs. Finally, because much of the code understanding is already encoded into retrieval-ready explanations and metadata, the final answering step can be performed with a smaller or more efficient local model than would otherwise be required.

However, this architecture also has disadvantages. The initial preprocessing step is computationally expensive and can require a powerful GPU node, especially when explanations are generated for many code entities. The vector store can also become stale: if the source code, parser, prompt templates, or model configuration changes, the index may need to be rebuilt. In addition, the system depends strongly on the quality of parsing, chunking, embedding, reranking, and structural expansion. If an entity is not extracted correctly or not retrieved, the final LLM cannot reason about it. Compared with agentic systems such as Codex or Claude Code, the system is also less autonomous. It does not directly modify code, run tests, inspect errors, or iteratively verify its own answer by executing commands.

The comparison therefore shows a trade-off between specialization and autonomy. Codex and Claude Code are more flexible for active software engineering tasks such as debugging, refactoring, writing tests, and creating pull requests. Their strength is the interactive agentic loop: gathering context, taking actions, observing results, and adapting. The RAG-Scientific-Code-Agent, on the other hand, is optimized for repeated question answering over a relatively stable scientific codebase. Its strength is controlled, reproducible, and domain-specific retrieval. It is therefore better suited for explaining and navigating a prepared codebase, while Codex- or Claude-style agents are better suited for changing and verifying code during active development.

Results

Evaluating the different models based on the explained setup in the previous section, showed interesting results. The older, well-established Qwen2.5 models underperformed with a range from 0.665 to 0.720. The Gemma4 models were also ranked among these values; however, the Qwen3.5 model is the clear winner out of the three. What was expected and can be clearly seen in the resulting data is that newer models or higher parameter counts tend to increase latency. Note that all latency was measured on the merlin6 ssh.

Discussion

The reason for this phenomenon can vary and is not clear. What is clear is that the benchmark rewards short, grounded, repository-specific answers. Large models often give broader answers. If the model includes irrelevant details, misses the exact source location, or wanders from the question, the score drops.

What can be accounted for scoring accuracy are the general generation settings, same prompt, temperature, context length, and max tokens do not affect every model equally. A setting that works well for Qwen3.5 9B may be suboptimal for Gemma4 31B or Qwen2.5 32B model.

This is also again underlined when comparing Qwen3.5 9B with the 32B model which only differences 0.03 in the benefit of the 9B model. When comparing the 9B model to other models of similar size, the pattern holds: within the smaller size class, the newer Qwen3.5 family clearly outperforms the older Qwen2.5-coder generation, confirming that architectural and alignment improvements outweigh raw scale for this task.

This supports the central hypothesis of the project: when the answering model is small, the quality of the prepared retrieval context matters more than the sophistication of the retrieval-time agent loop. Front-loading code understanding into the ingestion stage effectively compensates for the limited reasoning capacity of small models.