Abstract
We introduce a novel method to enhance cross-language code translation from Fortran to C++ by integrating task-specific embedding alignment into a Retrieval-Augmented Generation (RAG) framework. Unlike conventional retrieval approaches that utilize generic embeddings agnostic to the downstream task, our strategy aligns the retrieval model directly with the objective of maximizing translation quality, as quantified by the CodeBLEU metric. This alignment ensures that the embeddings are semantically and syntactically meaningful for the specific code translation task. Our methodology involves constructing a dataset of 25,000 Fortran code snippets sourced from the Stack-V2 dataset and generating their corresponding C++ translations using the LLaMA 3.1-8B language model. We compute pairwise CodeBLEU scores between the generated translations and ground truth examples to capture fine-grained similarities. These scores serve as supervision signals in a contrastive learning framework, where we optimize the embedding model to retrieve Fortran-C++ pairs that are most beneficial for improving the language model's translation performance. By integrating these CodeBLEU-optimized embeddings into the RAG framework, our approach significantly enhances both retrieval accuracy and code generation quality over methods employing generic embeddings. On the HPC Fortran2C++ dataset, our method elevates the average CodeBLEU score from 0.64 to 0.73, achieving a 14% relative improvement. On the Numerical Recipes dataset, we observe an increase from 0.52 to 0.60, marking a 15% relative improvement. Importantly, these gains are realized without any fine-tuning of the language model, underscoring the efficiency and practicality of our approach.
Introduction
Scientific computing continues to rely heavily on legacy Fortran codebases, yet modern production environments increasingly favor C++ for its performance, portability, and extensive library ecosystem. Manually translating millions of lines of legacy code is a monumental task, fraught with the potential for human error and high costs. While Large Language Models (LLMs) have shown promise in code translation, they often struggle with niche or legacy languages due to a scarcity of high-quality parallel datasets.
Standard Retrieval-Augmented Generation (RAG) offers a solution by providing the LLM with relevant examples to guide the generation process. However, conventional RAG systems typically employ generic embedding models for retrieval. These models often prioritize surface-level textual similarity, which may not correlate with the functional or structural relevance required for high-quality code translation. This paper addresses this gap by proposing a task-specific embedding alignment strategy that optimizes the retriever specifically for the translation objective.
Methodology: Task-Specific Embedding Alignment
The core of our approach is the customization of the embedding model (StarEncoder) to better serve the Fortran-to-C++ translation task. This process, illustrated in Figure 1, involves several key steps.
Synthetic Data Generation and Scoring
Due to the limited availability of parallel Fortran-C++ data, we utilized 25,000 high-quality Fortran snippets from the Stack-V2 dataset. We then employed Llama 3.1-70B to generate "pseudo-parallel" C++ translations. To capture the nuances of code similarity, we calculated pairwise CodeBLEU scores between these translations. CodeBLEU is a specialized metric that accounts for keywords, syntax trees, and data flow, providing a more robust measure of code equivalence than standard text-based metrics.
Contrastive Learning with S-InfoNCE
The calculated CodeBLEU scores were used as supervision signals to train the embedding model using a modified contrastive learning objective called Soft Information Noise-Contrastive Estimation (S-InfoNCE). Unlike standard contrastive loss, which uses binary labels, S-InfoNCE utilizes the continuous CodeBLEU score as a "soft" signal. This teaches the model that Fortran snippets resulting in similar C++ translations should have proximal embeddings, effectively aligning the embedding space with the downstream translation quality.
Evaluation and Datasets
We evaluated our approach using two primary benchmarks:
- HPC Fortran2CPP: A dataset comprising 315 parallel code pairs specifically designed for high-performance computing contexts.
- Numerical Recipes: A benchmark consisting of 298 parallel code pairs from the classic numerical methods text.
The "aligned" retriever was integrated into a RAG pipeline and tested with various state-of-the-art LLMs, including Llama 3.1 (8B and 70B), Mistral 123B, and Mixtral 8x22B.
Results and Discussion
Our results demonstrate that task-specific alignment significantly outperforms standard RAG across all tested models and datasets.
As shown in Figure 3, the aligned retriever consistently shifts the distribution of CodeBLEU scores upward. On the HPC Fortran2C++ dataset, the average CodeBLEU score improved from 0.64 to 0.73, a 14% relative gain. Similarly, on the Numerical Recipes dataset, scores rose from 0.52 to 0.60, a 15% relative improvement.
Key Insights
- The Importance of the Retriever: Enhancing the "librarian" (the retriever) can be as effective as using a larger LLM. By finding more relevant reference material, we significantly boost the performance of even smaller models like Llama 3.1-8B.
- Efficiency of Alignment: Our method is computationally efficient, requiring only the fine-tuning of a 125M parameter embedding model rather than a multi-billion parameter LLM.
- Few-Shot Effectiveness: Aligned retrieval notably enhances few-shot prompting. We observed that providing one or two well-chosen examples often yields the best balance between performance and context window constraints.
Conclusion and Future Work
We have demonstrated that aligning embedding models with task-specific metrics like CodeBLEU can substantially improve the performance of RAG systems for legacy code translation. This approach provides a practical, efficient pathway for modernizing scientific codebases without the need for extensive LLM fine-tuning.
Future research will focus on large-scale functional verification—ensuring that translated code not only looks correct but also compiles and executes accurately. Additionally, we aim to explore the applicability of this alignment technique to other legacy language pairs, such as COBOL to Java, to further support legacy system modernization.
Summary updated