TL;DR
Standard Retrieval-Augmented Generation (RAG) relies on general-purpose embeddings that retrieve superficially similar examples rather than snippets that optimize downstream code generation. This paper introduces a method to align source-language code embeddings (specifically Fortran) using contrastive learning weighted by pairwise target-language CodeBLEU scores. Without fine-tuning the underlying large language model (LLM), this metric-aligned retrieval yields a 14–15% boost in Fortran-to-C++ translation quality.
What Problem Does This Paper Address?
Scientific computing still heavily depends on legacy Fortran code, but modern production environments favor C++ for its optimization ecosystem and maintainability. While LLMs can translate code between languages, fine-tuning them on niche language pairs is computationally expensive and bottlenecked by limited parallel data.
Few-shot RAG offers a lightweight alternative by retrieving parallel translation examples to guide the LLM at inference. However, existing RAG systems rely on off-the-shelf code embedding models (such as StarEncoder or CodeBERT). These generic embeddings retrieve snippets based on broad lexical or high-level semantic similarity rather than retrieving examples that genuinely assist the LLM in generating syntactically and semantically correct target code.
Methods
The authors introduce a framework that directly aligns the Fortran embedding space with downstream translation quality:
- Synthetic Translation Generation: Starting with unaligned Fortran snippets ($f_i$), the authors generate corresponding C++ candidate translations ($\hat{c}_i$) using a base LLM (
llama3.1-8b) without retrieval. - Quality-Weighted Supervision: In the absence of ground-truth parallel pairs for training, pairwise syntactic and semantic similarity between generated C++ candidates is quantified using CodeBLEU ($c_{ij} = \text{CodeBLEU}(\hat{c}_i, \hat{c}_j)$).
-
Contrastive Embedding Alignment: A base code embedding model (StarEncoder) is trained using a modified InfoNCE loss. The loss scales the normalized cosine similarity $s_{ij}$ between Fortran snippet embeddings with the continuous CodeBLEU score $c_{ij}$ of their translated counterparts: $$\mathcal{L} = -\frac{1}{N} \sum_{i=1}^N \sum_{j=1}^N c_{ij} \log \left( \frac{\exp(s_{ij})}{\sum_{k=1}^N \exp(s_{ik})} \right)$$ This forces Fortran snippets that yield structurally and semantically similar C++ code closer together in the representation space.
-
Few-Shot RAG Inference: During inference, the query Fortran code retrieves the top-$k$ nearest Fortran-C++ pairs using the aligned encoder, which are prepended as few-shot in-context examples for an LLM (
llama3.1-8borllama3.1-70b).
Datasets
- Stack-V2 (Training/Alignment): 25,000 Fortran snippets sampled from files $>500$ bytes with high star and fork counts.
llama3.1-70bwas used to extract executable Fortran, andllama3.1-8btranslated them to C++ to form pairwise supervision scores. - HPC Fortran2C++ (Evaluation): A parallel benchmark consisting of 315 Fortran–C++ code pairs representing high-performance computing patterns.
- Numerical Recipes (Evaluation): A collection of 298 parallel Fortran–C++ algorithm pairs.
Key Insights and Ideas
- Target-Metric-Driven Retrieval: Standard retrieval assumes semantic closeness in the source space translates to prompt utility. By supervising the encoder with downstream target metrics (CodeBLEU on C++), the retriever explicitly learns what constitutes a "helpful" example for code generation.
- Bootstrapping Without Parallel Ground Truth: The embedding alignment does not require expensive, human-curated parallel datasets for training; it bootstraps supervision directly from model-generated translations evaluated pairwise.
- Diminishing Returns with Shot Count: For both models, translation performance plateaus around 2-shot prompting, suggesting that providing two high-quality, task-aligned reference pairs saturates the context utility for this translation task.
Key Results
- HPC Fortran2C++ Benchmark:
- Average CodeBLEU score improved from 0.64 to 0.73 (a 14% relative improvement) over unaligned StarEncoder embeddings across configurations.
- For
llama3.1-70b, 3-shot prompting achieved a CodeBLEU gain of +0.377 over the zero-shot baseline (0.364) with aligned embeddings, compared to +0.281 using unaligned embeddings. - Numerical Recipes Benchmark:
- Average CodeBLEU score increased from 0.52 to 0.60 (a 15% relative improvement).
- For
llama3.1-8b, 2-shot prompting with aligned embeddings increased CodeBLEU by +0.292 over zero-shot (0.276), outperforming unaligned retrieval (+0.195). - Scatter plot analysis across all test cases revealed that the aligned embedding model consistently produced equal or superior translation fidelity compared to standard generic retrieval.
Limitations and Future Work
- Metric Dependency: The approach relies heavily on CodeBLEU as the proxy for translation quality. While CodeBLEU captures AST and dataflow overlap, it does not guarantee execution correctness or functional equivalence (e.g., passing unit tests).
- Synthetic Pairing Quality: Pairing supervision relies on zero-shot translations generated by an 8B-parameter model; compounding translation errors in complex scientific libraries could introduce noisy alignment signals.
- Scope: The study focuses exclusively on Fortran-to-C++. Future work proposed by the authors includes expanding to other source/target language pairs and incorporating multi-faceted evaluation metrics (e.g., unit test execution or compilation checks) directly into the alignment loss.
Summary updated