Skip to content

EMNLP papers

Search EMNLP papers by title, author, or track. Open a paper’s abstract to read more.

Explore the EMNLP analysis

Search results

181–200 of 279

  • EMNLP · Findings

    Larger Context Window, Fewer Overcorrections: Optimizing Prompts and Batching for Minimal-Edit Grammatical Error Correction

    Kateryna Karpo, Artem Chernodub

    Abstract

    Minimal-edit Grammatical Error Correction (GEC) is a challenging task for zero- and few-shot prompted Large Language Models (LLMs), which systematically overcorrect and degrade F_{0.5} by rewriting well-formed spans. While fine-tuning provides an effective solution, it imposes substantial infrastructure demands. We introduce a prompt-based approach that closes the gap to fine-tuned models through three advances in GEC prompting methodology. First, we introduce taxonomy-based instructions to enforce minimal-edit constraints with a comprehensive list of grammatical error rules, equipping the LLM with a bounded, metric-aligned scope of correctable edits, which benefits the strongest models while remaining model-dependent overall. Second, we show that batching multiple uncorrected sentences into a single input context acts as a targeted regularizer against overcorrection, systematically reducing the edit rate across diverse LLM families; we hypothesize this arises from attention dilution effect induced by the bounded capacity of self-attention scores. Finally, LLM-assisted Prompt Optimization refines these instructions. Powered by Gemini 3.1-Pro, our prompt achieves F_{0.5}=78.32 on the BEA-2019 test set — establishing a new prompt-based SOTA while shrinking the gap to the fine-tuned single-model SOTA (Staruch et al., 2025) to a mere 0.38 points. Code, prompts, and outputs are publicly available.

    Abstract source
  • EMNLP · Findings

    SIN-Bench: Tracing Native Evidence Chains in Long-Context Multimodal Scientific Interleaved Literature

    Junjie Wang, Yiming Ren, Yuxin Meng, Yihang Shi, Zhiqiang Lin, Yulin Song, Ruihang Chu, Yiran Xu, Ziming Li, Yunfei Zhao, Zihan Wang, Yu Qiao, Ruiming Tang, Minghao Liu, Yujiu Yang

    Abstract

    Evaluating multimodal large language models (MLLMs) on long-form scientific papers requires measuring not only answer correctness, but also whether answers are supported by traceable cross-modal evidence. Existing answer-only metrics and synthetic “Needle-In-A-Haystack” tests mainly assess answer matching or isolated retrieval, leaving evidence-grounded support under-examined. We introduce “Fish-in-the-Ocean” (FITO), an evidence-chain evaluation lens for native scientific documents, and instantiate it with SIN-Data, a scientific interleaved corpus that preserves text–figure coupling. Built on SIN-Data, SIN-Bench comprises four evidence-auditing tasks: evidence discovery, hypothesis verification, grounded QA, and evidence-anchored synthesis. We further propose “No Evidence, No Score”, which credits predictions only when linked to verifiable anchors and diagnoses evidence quality through matching, relevance, and logic. Experiments on 10 MLLMs show a clear correctness–grounding gap: Gemini-3-pro obtains the best average overall score (0.566), while GPT-5 reaches the highest SIN-QA answer accuracy (0.767) but lower evidence-aligned scores. Code and data are available at https://github.com/IIGROUP/sin-bench .

    Abstract source
  • EMNLP · Findings

    ASP: Adaptive Semantic Preservation for Context Compression

    Shaoshen Chen, Peiyang Li, Jiaming Mu, Guixiong Chen, Fengting Li, Chao Feng

    Abstract

    Context compression has emerged as a vital approach to mitigate both performance degradation and resource consumption for large language models (LLMs) in long context scenarios. Current state-of-the-art methods allocate the compression budget at fixed-size block granularity, either uniformly or with adaptation across blocks. Both strategies fragment sentence-level semantic units and overlook the relevance variation within each block. In this paper, we propose the Adaptive Semantic Preservation (ASP) compressor, built on two innovations: (1) To preserve semantic units, our Semantic-Preserving Segmentation partitions context along natural sentence boundaries while maintaining the morphological atomicity of words. (2) To prioritize critical information, our task-aware Adaptive Budget Allocation dynamically assigns compression budget based on each sentence’s informational salience for the task instruction. Extensive experiments across diverse long-context scenarios show that ASP outperforms strong task-aware and task-agnostic compression baselines on both Llama-3-8B-Instruct and Qwen-2.5-7B-Instruct. In particular, ASP delivers stronger robustness compared with other baselines even at the extreme 16\times high compression ratio.

    Abstract source
  • EMNLP · Findings

    BioELX: Context-Aware Cross-lingual Biomedical Entity Linking without Task-Specific Supervision

    Yi Wang, Corina Dima, Liangyu Zhong, Steffen Staab

    Abstract

    Cross-lingual biomedical entity linking (BEL) maps mentions in any language to unique identifiers in a biomedical knowledge base, supporting clinical and biomedical NLP applications. We identify two issues affecting current systems. First, the UMLS aliases used to train cross-lingual BEL retrievers are heavily skewed toward English, so retrievers generalize poorly to non-English mentions. Second, although context is often necessary for disambiguation, naively injecting context into retrievers trained only to align aliases severely degrades retrieval. We propose BioELX, a retrieve-rerank framework that addresses both issues. For retrieval, we continue training SapBERT_{\mbox{multi}} using Wikidata-derived cross-lingual alias supervision, forming shared concept neighborhoods across languages. For reranking, we adapt pretrained LLM rerankers to entity linking through mention-anchored prompting, which marks the target mention so that rerankers score candidates with respect to the intended mention rather than other salient tokens in the context. Experiments show that BioELX achieves new state-of-the-art results on four cross-lingual BEL benchmarks, improving Recall@1 by 4.8 to 18.2 percentage points over prior best results, without any task-specific BEL annotations.

    Abstract source
  • EMNLP · Findings

    Compile, Don’t Memorize: A Context Compilation Architecture (CCA) for In-Context Learning

    Jinhu Qi, Minda Hu, Wentao Zhang, Weiqiang Jin, Yanyu Chen, Junli Wang, Irwin King

    Abstract

    Large language models (LLMs) increasingly handle in-context learning (ICL) tasks where a long, novel context defines the rules, knowledge, and output schema for a series of questions. On benchmarks that grade against every detail of the context, even strong open-weights models pass only 12-16% of tasks: a single overlooked rule fails the whole response. We argue this brittleness is structural—the dominant "read-and-reason" paradigm asks the model to extract, plan, generate, and self-verify in one forward pass—and ask whether explicit context compilation can fix it, how it compares to existing long-context strategies (gist retrieval, multi-agent self-play), and where the resulting harness benefit holds across task structure and model scale. We propose the Context Compilation Architecture (CCA): compile the given context into a structured IR of rules, schemas, and exact terms; generate executable verifiers from the IR; run a checked reasoning loop that corrects any violation those verifiers flag. On CL-bench (1,899 tasks across 4 open base models), CCA outperforms vanilla prompting and two long-context baselines (ReadAgent-P, Ctx2Skill) on every base model, lifting Kimi K2.5 from 15.4% to 21.4% with gains concentrated on rule-dense sub-categories.

    Abstract source
  • EMNLP · Findings

    Diagnosing Decision-Boundary Induction in Few-Shot In-Context Learning

    Mingyang Li, Xinlang Yue, Muyang Li, Yongqi Liu, Kaiqiao Zhan

    Abstract

    Few-shot in-context learning is usually evaluated by final accuracy, but correct predictions do not guarantee recovery of the intended task boundary. We formulate few-shot ICL as decision-boundary induction and decompose performance into boundary induction and rule execution. Using controlled binary verification tasks with decomposable boundaries, we diagnose which necessary components are behaviorally enforced and, under chain-of-thought, explicitly recognized. Across three tasks and multiple model families, we show that few-shot ICL often induces component-biased verifiers rather than the full target boundary. Stronger models are more robust to this bias, while chain-of-thought reshapes rather than uniformly improves boundary recovery. An explicit-rule intervention further shows that improvements come from both recovering missing boundary components and executing recognized ones more reliably. These results suggest that evaluating few-shot ICL should go beyond aggregate accuracy and directly test boundary recovery. Code is available at https://github.com/limy805/boundary-icl.

    Abstract source
  • EMNLP · Findings

    Beyond Visual Neglect: Context-Preference Activation Steering for Mitigating MLLM Hallucinations

    Jingwen Wu, Xijun Zhang, Ge Song

    Abstract

    Object hallucination remains a primary obstacle to the reliable deployment of Multimodal Large Language Models (MLLMs). Current inference-time mitigation methods mainly assume that hallucinations stem from visual neglect and therefore steer models toward greater visual reliance. In contrast, our systematic interventions on multiple MLLMs show that increasing visual reliance may exacerbate hallucinations on some models, whereas reducing it may mitigate them. This result suggests that visual neglect alone provides an incomplete explanation of hallucination. We characterize the image as a context that competes with both the model’s parametric knowledge and its textual context. Based on this characterization, we propose a training-free framework, Context-Preference Activation Steering (CAS). CAS extracts two Context Preference Vectors (CPVs), designed to capture different context-preference relationships, from two small sets of conflict samples and injects signed residuals into the MLP-sublayer outputs before residual addition at four mid-early layers in a single forward pass. Experiments show that CAS substantially mitigates object hallucinations with negligible decoding overhead while maintaining F1, lexical diversity, and repetition rates close to those of the base models. Code and data are available at https://github.com/wss7/CAS.

    Abstract source
  • EMNLP · Findings

    Context-anchored Asymmetric Conformal Prediction for Uncertainty-aware Reasoning over Knowledge Graphs

    Boyang Fan, Ziyue Qiao, Wei Ju, Xiao Luo

    Abstract

    This paper studies the problem of uncertainty-aware reasoning over knowledge graphs (KGs), which aims to incorporate uncertainty quantification into unseen knowledge predictions over KGs. Previous works typically incorporate uncertainty measurement tools such as conformal predictions into graph representation learning. Despite the progress, the performance of these approaches remains limited since they usually neglect both structural information in KGs and intrinsic asymmetry between over-estimation and under-estimation. Towards this end, we propose a novel approach named Context-anchored Asymmetric Conformal Prediction for uncertainty-aware REasoning over KGs (CARE). The core of our CARE is to identify the context of each query using anchors, which guide the construction of triple-specific asymmetry prediction intervals. In particular, we first take the subset of the calibration set as a reference pool. For each triple query, we summarize the KG structural statistics into a vector, which guides the identification of its anchor samples from the pool. The confidence residuals between query and anchors are utilized to quantify over-estimation and under-estimation, producing contextual nonconformity scores. Finally, we utilize the unselected calibration dataset to determine cutoff levels for constructing asymmetric prediction intervals. Extensive experiments on benchmark datasets validate the effectiveness of CARE. The code can be found at https://github.com/fanboyang/CARE.

    Abstract source
  • EMNLP · Findings

    LongTraceRL: Learning Long-Context Reasoning from Search Agent Trajectories with Rubric Rewards

    Nianyi Lin, Jiajie Zhang, Lei Hou, Juanzi Li

    Abstract

    Long-context reasoning remains a central challenge for large language models, which often fail to locate and integrate key information in extensive distracting content. Reinforcement learning with verifiable rewards (RLVR) has shown promise for this task, yet existing methods are limited by low-confusability distractors and sparse, outcome-only reward signals that cannot supervise intermediate reasoning steps. To address these issues, we introduce LongTraceRL. For data construction, we generate multi-hop questions via knowledge graph random walks and leverage search agent trajectories to build tiered distractors: documents the agent read but did not cite (high confusability) and documents that appeared in search results but were never opened (low confusability), producing training contexts that are far more challenging than those built by random sampling or naive search. For reward design, we propose a rubric reward that uses the gold entities along each reasoning chain as fine-grained, entity-level process supervision. This rubric reward is applied only to responses with correct final answers (positive-only strategy), distinguishing the reasoning quality among correct responses and preventing reward hacking. Experiments on three reasoning LLMs (4B–30B) across five long-context benchmarks demonstrate that LongTraceRL consistently outperforms strong baselines and encourages comprehensive, evidence-grounded reasoning.

    Abstract source
  • EMNLP · Findings

    ACRE: An Acoustic-Cue and Contextual-Knowledge Reasoning Enhancement Framework for Speech Relation Extraction

    Wenxuan Mu, Jinzhong Ning, Di Zhao, Yijia Zhang

    Abstract

    Speech relation extraction (SpeechRE) aims to extract structured relational triples directly from speech. However, existing studies still face three major challenges: **the lack of Chinese SpeechRE benchmarks**, **insufficient modeling of speech-specific cues**, and **evaluation bias introduced by character-level exact matching** in Chinese scenarios. To address these challenges, we first construct **CSRTE**, a real-world Chinese SpeechRE benchmark built from human speech, providing unified data and evaluation settings. We then propose **ACRE**, a reasoning enhancement framework for SpeechRE, which integrates acoustic-cue and contextual-knowledge into a structured acoustic-semantic reasoning chain, enabling the model to go beyond literal semantic content **(what-to-say)** and capture speech-specific features **(how-to-say)** for relation reasoning. We further combine supervised fine-tuning with reinforcement learning and design composite rewards to improve the quality of the model’s reasoning process. In addition, we propose pronunciation-aware evaluation **(PAE)**, which considers pronunciation and tone consistency during entity matching to reduce the evaluation bias. Experiments on both Chinese and English SpeechRE benchmarks demonstrate the effectiveness of ACRE and the usefulness of PAE. Our source code and datasets are available at https://github.com/MWXGOD/CSRTE.

    Abstract source
  • EMNLP · Findings

    ReContext: Recursive Evidence Replay as LLM Harness for Long-Context Reasoning

    Yanjun Zhao, Ruizhong Qiu, Tianxin Wei, Yuanchen Bei, Zhining Liu, Lingjie Chen, Ismini Lourentzou, Hanghang Tong, Jingrui He

    Abstract

    Understanding and reasoning over long contexts has become a key requirement for deploying large language models (LLMs) in realistic applications. Although recent LLMs support increasingly long context windows, they often fail to use relevant evidence that is already present in the input, revealing a gap between context access and effective context utilization. In this work, we propose Recursive Evidence Replay as LLM Harness for Long-Context Reasoning (RECONTEXT), a training-free inference method for improving long-context reasoning. RECONTEXT uses model-internal relevance signals to construct a query-conditioned evidence scaffold and replays it before final generation while preserving the full original context. This recursive sifting process separates evidence organization from answer generation without training, external memory, or context pruning. We also provide a theoretical analysis based on associative memory, which characterizes the context as a memory store, the question as a retrieval cue, attention as cue-trace association, and replay as trace reactivation. Experiments on eight long-context datasets with 128K context length show that RECONTEXT consistently improves evidence utilization across Qwen3-4B, Qwen3-8B, and Llama3-8B, achieving the best average rank on all three backbones. Code is available in the supplementary software.

    Abstract source
  • EMNLP · Findings

    Extending LLM Context via Associative Recurrent Memory

    Gleb Kuzmin, Ivan Rodkin, Aydar Bulatov, Yuri Kuratov, Lyudmila Rvanova, Mikhail Katkov, Ilia Sochenkov, Misha Tsodyks, Timothy Baldwin, Mikhail Burtsev, Artem Shelmanov

    Abstract

    Extending the context length of large language models (LLMs) is critical for many real-world applications, yet standard transformers remain constrained by quadratic compute and linear memory scaling. In this work, we investigate the Associative Recurrent Memory Transformer (ARMT) as a practical approach for enabling long-context processing in LLMs, constant memory scaling, and better efficiency. We make three main contributions. First, we construct two domain-specific long-context datasets designed to evaluate realistic workloads, focusing on narrow-domain fine-tuning scenarios. Second, we propose a comprehensive training recipe for ARMT-based context extension, combining continued pre-training, synthetic long-context data generation, curriculum learning, and selective integration of associative memory into chosen model layers. Third, we present an extensive experimental study demonstrating that ARMT-augmented models: (i) process inputs well beyond their original context limits without degrading performance relative to in-limit baselines; (ii) generalize more effectively to out-of-distribution context lengths; and (iii) need 30% fewer FLOPs while preserving baseline performance within the original context window.

    Abstract source
  • EMNLP · Findings

    When Users Don’t Ask: Benchmarking Context-Driven Memory Retrieval in Conversational Agents

    Wen Yu Chang, Yun-Nung Chen

    Abstract

    Large Language Models (LLMs) are increasingly deployed as long-horizon conversational agents, motivating growing interest in memory systems. However, existing benchmarks primarily evaluate memory through QA-style probing rather than in-situ conversational usage. We introduce LOCOMO-CONV, a conversational memory benchmark derived from LoCoMo with four query styles: dialog, implicit, counterfactual, and composed. Across four representative memory systems, we evaluate both retrieval recall and end-to-end response quality. Our experiments show that conversational framing exposes substantial retrieval gaps overlooked by QA benchmarks, especially on implicit and composed queries, which multi-facet query rewriting narrows for raw-turn but not abstractive memory. We further find that strong retrieval does not fully translate into response quality, and that implicit queries exhibit silent grounding, where memory improves contextual grounding without explicitly surfacing the gold fact. These results point to reasoning-based memory elaboration as a promising direction, and we release auxiliary supportive_memory annotations capturing conversationally useful context beyond the original gold evidence.

    Abstract source
  • EMNLP · Findings

    Context Modeling for LLM-Based Behavioral Simulation

    Dongyang Zhen, Ruize Qin, Ali Mansouri, Abdolmajid Erfani, Qingbin Cui

    Abstract

    Large language models (LLMs) offer new opportunities for simulating human decision making at scale, yet prompting-based approaches often fail to recover realistic population-level response distributions, particularly for heterogeneous demographic groups and high-entropy questions. This paper introduces context modeling with agentic AI, a structured simulation framework that explicitly constructs latent, individual-level decision contexts prior to response generation. By separating persona construction from decision making and introducing structured stochasticity through context sampling, the method captures within-group heterogeneity and mitigates mode collapse inherent in single-prompt simulations. Extensive empirical evaluation across population-level and group-conditioned settings shows that context modeling consistently improves simulation fidelity, with especially strong gains on high-entropy questions and demographic subpopulations, while preserving performance on low-entropy tasks. Detailed tail analysis further reveals that the primary improvement arises from recovering minority and low-probability response options that are systematically underrepresented by direct prompting. Overall, the results demonstrate that faithful behavioral simulation requires explicit modeling of contextual heterogeneity and structured uncertainty, establishing context modeling as a robust foundation for LLM-based behavioral simulation.

    Abstract source
  • EMNLP · Findings

    Dropping the Anchor: Statistical Context Summarization for Distributed Systems via Pulsar Attention

    Aryan Sood, Shantanu Acharya, Gaurav Kumar Nayak

    Abstract

    Inference with large language models (LLMs) on long sequences is computationally expensive due to the quadratic complexity of self-attention. Distributed blockwise methods such as Star Attention reduce this cost by sharding context across hosts, but rely on prepending a static, content-blind copy of the first block to every host. We propose Pulsar Attention, which replaces the static anchor with two lightweight, content-aware components: a small attention-sink prefix that stabilizes softmax, and compact cross-block summaries built via a Max-IDF heuristic that selects chunks containing globally rare tokens. This reduces the Phase 1 per-GPU FLOPs by up to 3.3\times over Star Attention while retaining an identical KV cache footprint. On RULER with Llama-3.1-8B-Instruct, Pulsar Attention outperforms Star Attention at sequence lengths up to 128K tokens and remains competitive with dense attention across most tasks, with task-dependent absolute gains of up to 4.7% over the dense baseline.

    Abstract source
  • EMNLP · Findings

    Folding Context into Executable States: Structured Strategy Folding for Long-Horizon Reasoning Agent

    Zhengyu Chen, Luan Zhang, Zhaoyi Li, Jinluan Yang, Zheqi Lv, Teng Xiao, Wei Wang, Jingang Wang

    Abstract

    Current Large Language Model (LLM) agents struggle with long-horizon reasoning tasks, such as competition-level mathematics, where sustaining precision over hundreds of steps is critical. A primary bottleneck is the reliance on natural language context or summaries to track progress; these linguistic representations are inherently "lossy," introducing semantic drift and accumulating errors that derail the reasoning chain. To address this, we propose Structured Strategy Folding (SSF), a novel paradigm that shifts the agent’s memory mechanism from linguistic description to computational verification. Instead of compressing history into text, SSF "folds" the reasoning trajectory into a sequence of Executable Symbolic States (ESS). Each ESS serves as a verifiable anchor—comprising either executed code artifacts or formally judged symbolic lemmas—generated through a dual-pathway validation mechanism. By interacting with these rigorous state artifacts rather than raw textual history, the agent effectively eliminates ambiguity and prevents error propagation. Experiments on challenging mathematical benchmarks demonstrate that SSF significantly outperforms standard Chain-of-Thought and existing summarization baselines, achieving substantial accuracy improvements while maintaining robust performance over extended reasoning horizons.

    Abstract source
  • EMNLP · Findings

    Measuring Cultural Alignment Beyond the Average: A Framework for Evaluating Maternal-Health LLM Interactions in Indian Contexts

    Umaira Izhar, Gunjan Arora, Pushpendra Singh

    Abstract

    Existing evaluation methods for healthcare LLMs primarily assess factual correctness, safety, and fluency, while providing limited insight into whether generated interactions reflect culturally situated healthcare reasoning. This limitation is particularly important in maternal health, where care decisions are shaped by social and relational norms. We introduce MH-INDIC, a culturally grounded evaluation framework for maternal-health interactions in Indian contexts that operationalises cultural behaviour through ten dimensions of maternal-health reasoning. Using a 26-item survey administered to 102 pregnant and postpartum women from urban and semi-urban North India, we evaluate ten LLMs under profile-conditioned prompting. Our evaluation separates aggregate cultural alignment and context-dependent sensitivity to demographic and household factors. While several proprietary models approximate human population-level distributions, all evaluated systems exhibit substantially reduced behavioural variation across profiles. We further show that human-grounded conditioning enhances the realism and contextual coherence of synthetic maternal health dialogues. Together, our findings highlight the importance of evaluating healthcare LLMs not only for factual correctness but also for their ability to model socially situated reasoning in culturally embedded healthcare settings.

    Abstract source
  • EMNLP · Findings

    Randomized YaRN Improves Length Generalization for Long-Context Reasoning

    Manas Mehta, Fangcong Yin, Greg Durrett

    Abstract

    Large language models (LLMs) are typically pretrained on short sequences and then extended to work on longer sequences with additional training. However, LLMs still struggle to generalize to very long sequences. We propose Randomized YaRN, a training method that improves length generalization by combining YaRN-based positional extrapolation with randomized positional encoding and a length curriculum. During training on short context data, tokens are assigned YaRN positional encodings sampled from a larger position range, exposing the model to out-of-distribution positional representations without requiring long-context inputs. We evaluate Randomized YaRN on two challenging long-context reasoning benchmarks, BABILong and Multi-Round Coreference Resolution (MRCR). When training on data with <8K context, Randomized YaRN consistently improves reasoning performance on context lengths from 16K to 128K and outperforms standard fine-tuning baselines, with the largest gains appearing at far out-of-distribution lengths. Our results suggest that progressively exposing models to OOD positional distributions provides an effective recipe for generalizable long-context reasoning.

    Abstract source
  • EMNLP · Findings

    Long-Context Demonstration Selection Using State Space Models

    Ziniu Zhang, Zhenshuo Zhang, Ruoxuan Xiong, Gene Cooperman, Hongyang R. Zhang

    Abstract

    We study the problem of demonstration selection, which involves selecting a subset of examples for pre-pending to a query to a language model. This problem is closely related to in-context learning and model inference. Since the inference cost of a transformer model scales quadratically with sequence length, the selection problem becomes especially challenging in a long-context scenario. In this paper, we tackle this problem by building on state space models (SSMs), which has linear inference time given the input embeddings. Our approach works in two stages. First, we learn a small set of SSMs through a distillation procedure — given a (trained) transformer model, we partition all the layers into consecutive (layer) groups — for each group, we learn one SSM to mimic the input-output behavior, thereby capturing structural similarity in adjacent layers. Second, we map the SSM outputs to a small set of tokens, and apply them for downstream demonstration selection. We run extensive experiments in both synthetic and real-world datasets to validate this approach. We show that the SSMs trained from distillation incur a relative approximation error of less than 0.7%. As for downstream demonstration selection, we find that on several text classification and reasoning tasks, our approach reduces FLOPs by 14.2\times and improves accuracy by 6.48% relative to baseline selection methods.

    Abstract source
  • EMNLP · Findings

    MegaCode: A Repository-Level Dataset for Long-Context Code Reasoning

    Wenyang Luo, Shuang Sun, Yiwen Hu, Fei Bai, Yanzipeng Gao, Shuo Wang, Hongyu Lu, Xin Zhao, Ji-Rong Wen

    Abstract

    Code reasoning is essential for building AI systems that can understand, generate, and verify complex software. Yet most open-source code corpora focus on isolated snippets or single functions, failing to capture the long-range dependencies and cross-file interactions that define real-world repositories. We introduce MegaCode, a 300B repository-level corpus designed to support structured code reasoning and long-context modeling. MegaCode preserves full project structure—including build scripts, configuration files, and inter-file links—and is constructed through a multi-stage curation pipeline combining deduplication, rule-based filtering, and model-based quality assessment. Models pretrained on MegaCode demonstrate consistent gains on code reasoning and long-context benchmarks compared with those trained on flattened code datasets. Also, we validate the effectiveness of adding repo relevent infomation such as LSP, repo structure and repo summary. These results highlight the importance of maintaining repository structure for next-generation code intelligence. We release the dataset, curation pipeline, and evaluation suite to facilitate research on large-scale code pretraining and repository-level understanding.

    Abstract source