Skip to content

BOUND: Mitigating Package Hallucination in Large Language Models via Model EditingMitigating Package Hallucinations in Large Language Models via Model Editing

arXiv· arXiv:2607.02052· Shuhan Liu, Yukai Zhao, Xing Hu, Kui Liu, Xiaohu Yang, Xin XiaThe State Key Laboratory of Blockchain and Data Security, Zhejiang University; HuaweiIndexed by this site · 21 days ago· Originally publishedDefenses

Quick read

Defenses

Based on the paper PDF (AI-generated); refer to the original

The authors propose a model editing framework, BOUND, to mitigate LLM package hallucination; the authors state that on three open-source models Package-HR drops 79.9% on the edit set and 65.4% on unseen prompts.

Threat modelThe paper targets the model's own package hallucination (generating nonexistent package names), not an attacker's perspective; the authors note that hallucinated package names can be exploited by attackers registering malicious packages (package confusion). The defense directly modifies the internal behavior of open-source LLMs through model editing, without relying on external retrieval or inference-time pipelines.

Questions
In code tasks, LLMs generate nonexistent software package names (package hallucination), which attackers may exploit by registering malicious packages, threatening software supply chain security; existing external mitigation or full fine-tuning methods either do not change the model's internal behavior or are costly.
Methods
Proposes BOUND: first uses a boundary risk score with backpropagation to locate the top 5 modules most sensitive to the package validity boundary, then injects LoRA and jointly optimizes three objectives: valid package NLL, hallucinated package unlikelihood, and locality KL.
Experiments and results
On three open-source models, the authors report a 79.9% reduction on the edit set Package-HR and a 65.4% reduction on unseen prompts, with transfer to code generation (12.8% reduction) and pip install recommendation (34.0% reduction); baselines such as ROME and DINM reduce hallucination by suppressing package generation, with Valid-Rate dropping substantially.
Limitations and future work
The authors point out: results may not generalize to other LLMs; coverage is limited to the PyPI ecosystem and three package-related tasks; package name extraction relies on regex and generation is stochastic. The experiments include only three 8B-class open-source models, and no statistical significance tests are reported.
Experimental setupdeepseek-coder-6.7b-instruct、Qwen3-8B et al. · Spracklen et al. 包幻觉提示词数据集(Python 子集)、HumanEval · Sample-HR、Package-HR et al.
Evaluated models
deepseek-coder-6.7b-instructQwen3-8BLlama-3.1-8B-Instruct
Benchmarks
Spracklen et al. 包幻觉提示词数据集(Python 子集)HumanEval
Metrics
Sample-HRPackage-HRValid-Ratepass@1pass@10
AI summaryBOUND mitigates package hallucination in large language models—where the model generates nonexistent package names that can be exploited for supply chain attacks—through model editing. It first uses a risk-aware localization strategy to find relevant modules, then edits with LoRA adapters using a boundary-aware objective. In the package recommendation task, the package-level hallucination rate drops by 79.9% on edited prompts and 65.4% on unseen prompts, and by 12.8% and 34.0% for code generation and pip install recommendations, respectively.

BOUND mitigates package hallucination in large language models—where the model generates nonexistent package names that can be exploited for supply chain attacks—through model editing. It first uses a risk-aware localization strategy to find relevant modules, then edits with LoRA adapters using a boundary-aware objective. In the package recommendation task, the package-level hallucination rate drops by 79.9% on edited prompts and 65.4% on unseen prompts, and by 12.8% and 34.0% for code generation and pip install recommendations, respectively.

Paper analysis

6 questions; open one to read the full answer

  1. What problem does this paper attempt to solve?

    How to directly mitigate LLM package hallucination with lightweight model editing while preserving valid package recommendation capability.

    Core question: how to directly modify LLM internal behavior to reduce package hallucination (generating nonexistent software package names) while preserving valid package recommendation, without retraining or relying on external retrieval.

    • Scenario and importance: developers increasingly use LLMs to generate code, recommend libraries, and configure dependencies, and the package names output by the model are copied into import statements or handed to package managers for installation. The authors note that hallucinated package names can be registered by attackers as malicious packages, constituting a package confusion type of software supply chain risk.
    • Shortcomings of existing methods (per the paper): external mitigation (retrieval augmentation, self-correction) does not modify the model's internal behavior and introduces extra inference overhead or pipeline complexity; internal adaptation (e.g., supervised fine-tuning) updates many parameters, is computationally expensive, and may overfit and harm general capability.
    • Core observation: package hallucination is not simply a fact-rewriting problem—prompts contain complex task descriptions rather than explicit factual subjects, and valid and hallucinated packages often appear together in the same response. The authors therefore define it as a package-validity boundary problem: the model's ability to distinguish valid from hallucinated packages in a given task context (in Figure 1, Llama-3.1-8B gives both valid packages cffi, iris and hallucinated packages ecmwfr, pyeawr).
    • Proposed in the paper: BOUND, a lightweight local model editing framework: first risk-aware localization of modules related to package hallucination, then LoRA injection and editing with boundary-aware objectives.
    • Threat model: the paper is not from an attacker's perspective and targets the model's own hallucination behavior; the risk scenario the authors note is an attacker registering a malicious package with the same name as a hallucinated package, with the victims being developers and automated coding agents that use LLM outputs. The defense target is open-source LLMs whose weights can be modified.
  2. What related research exists?

    Related work falls into three categories: package hallucination research, hallucination mitigation strategies, and model editing; baselines are Full-FT, Self-Refinement, ROME, MEMIT, DINM.

    Package hallucination research

    • Spracklen et al. [12] (USENIX Security 2025)—systematically analyzes the package hallucination phenomenon in code-generating LLMs; Krishna et al. [13] measure package hallucination vulnerabilities. The paper notes that these empirical studies show package hallucination is prevalent across models, languages, scales, and task settings.
    • HFuzzer [14]—triggers package hallucination using phrase-based fuzzing.
    • Supply chain risk research [16][17][18][19]—discusses threats such as package confusion, slop squatting, and malicious registration.

    Hallucination mitigation strategies

    • Retrieval augmentation (e.g., [21][22])—uses external knowledge sources (e.g., PyPI, API documentation) to ground generation; self-refinement ([23][24])—has the model iteratively verify and correct outputs.
    • Inference-time/post-hoc editing (TruthX [47], PURR [48])—intervenes in internal representations or modifies generated outputs. The paper notes that these methods rely on external resources, require repeated inference, or do not correct the model's default behavior.
    • Model adaptation (e.g., Full-FT [12])—changes behavior through fine-tuning; the paper notes its high training cost.

    Model editing

    • Weight-preserving methods (SERAC, GRACE, IKE [52][53][54])—override predictions via external memory or in-context examples without changing parameters.
    • Weight-modifying methods: KnowledgeEditor, MEND [55][56] learn auxiliary networks to generate parameter updates; ROME, MEMIT, PMET [34][36][33] edit selected internal modules to rewrite factual associations; DINM [28] extends editing to behavioral tasks such as detoxification. The paper notes that some studies show aggressive or sequential editing may harm general capabilities or cause forgetting [57][58], and Huang et al. [31] found that existing editing methods may struggle to correct hallucinated outputs.

    Baselines and benchmarks: baselines are Full-FT, Self-Refinement (both from [12]), ROME, MEMIT, and DINM; data comes from the Python subset of the LLM-generated prompt dataset released by Spracklen et al. [12].

    Authors' positioning: package hallucination has not yet been explored in model editing; this paper targets task-conditioned package validity boundary editing rather than isolated fact rewriting.

  3. How does the paper address this problem?

    BOUND has two steps: a boundary risk score localizes the top 5 sensitive modules, then LoRA is injected and edited jointly with three objectives.

    Overall approach: package hallucination mitigation is formalized as the package validity boundary editing problem—the edited model should reduce the probability of generating hallucinated packages while preserving valid package recommendations, i.e., M_{\theta+\Delta}(x_i) \rightarrow G_i,\ M_{\theta+\Delta}(x_i) \not\rightarrow H_i (G_i is the set of valid packages, H_i is the set of hallucinated packages). BOUND has two stages (Figure 2).

    Key module localization

    • Candidate module space: the 7 projection matrices of each decoder layer (attention q/k/v/o and MLP gate/up/down), across all L layers. The authors argue that package hallucination involves not only the MLP but also attention modules that route task context information.
    • Boundary risk score: for each case in the localization case set Eloc, take the next-token logits at the response start position and construct Ri = LSE(zi[Hitok]) − λa LSE(zi[Gitok]), i.e., the difference between the smoothed aggregate logits of hallucinated package and valid package tokens, where λa controls the weight of the valid package anchor.
    • Saliency scoring: backpropagate R_i through the frozen model, compute for each module the mean absolute value of the element-wise product of gradients and weights as saliency, average across cases, rank, and select the top 5 modules as the editing set S. Parameters are not updated during the localization stage.

    Boundary-aware model editing

    • LoRA injection: inject a LoRA branch into each module in S (rank r=8, α=16, dropout 0.05), with original weights frozen; the LoRA initial output is zero, so model behavior is unchanged before editing.
    • Three joint objectives:
      • Valid Package NLL: negative log-likelihood on the formatted valid package answer yi, preserving valid package generation and preventing the model from reducing hallucination by suppressing package output;
      • Hallucinated Package Unlikelihood: an unlikelihood penalty on the sequence probability of each hallucinated package in H_i after the response prefix π, explicitly lowering the probability of hallucinated packages;
      • Locality KL: constrains the KL divergence of the next-token distribution before and after editing on the locality prompt set Ci (package-related prompts constructed from G_i + original task prompts xi), reducing behavioral drift.
    • Total objective: the three terms are weighted-summed with λv=1.0, λh=0.15, λl=0.03 and averaged over the editing case set; only LoRA parameters are optimized, with batch size 1, learning rate 2×10⁻⁴, and 3 training epochs.

    Data construction

    • Prompts come from the Python subset of the Spracklen et al. [12] dataset; a high-risk set is constructed separately for each model: each prompt is sampled 5 times, package validity is verified with PyPI metadata (exists on PyPI and was published before the model's knowledge cutoff), and prompts with Sample-HR > 0.5 are retained as high-risk.
    • Each model's high-risk set is split into 4 editing folds (50 each) + 1 unseen evaluation set (Table I: DeepSeekCoder 741/541, Qwen3 609/409, Llama-3.1 1,134/934).

    Success criteria and metrics

    • Sample-HR: the proportion of responses containing at least one hallucinated package; Package-HR: the proportion of hallucinated packages among extracted packages (defined as 0 when no package can be extracted); Valid-Rate: the proportion of responses containing at least one valid package, used to detect methods that "reduce hallucination by not generating packages."
  4. What experiments did the paper conduct?

    Comparison with 5 baselines on three open-source models, plus cross-task generalization, ablation, cost, and HumanEval impact tests.

    Experimental Setup

    • Models evaluated: deepseek-coder-6.7b-instruct, Qwen3-8B, Llama-3.1-8B-Instruct, loaded in bfloat16.
    • Data: the Python subset of the prompt dataset from Spracklen et al. [12]; for each model the high-risk set is split into 4 edit folds (50 each) + an unseen evaluation set (541/409/934, Table I).
    • Baselines: Full-FT, Self-Refinement (up to 5 rounds of iterative correction), ROME, MEMIT, DINM; trainable baselines use the same edit cases.
    • Metrics: Sample-HR, Package-HR, Valid-Rate (definitions in Question 3); package validity is checked with cutoff-aware PyPI metadata.
    • Generation settings: 5 samples per prompt, temperature 0.7, top_p 0.9; package recommendation and pip install up to 128 tokens, code generation 2,048 tokens.
    • Repetition and aggregation: report the average result after editing for each of the 4 edit folds; RQ2/RQ3 randomly sample 100 from the unseen evaluation set to control cost.

    Main Results

    Table II (package recommendation, average over 4 folds; lower Sample-HR/Package-HR is better, higher Valid-Rate is better):

    Swipe horizontally to read the table

    ModelMethodEdit50 Sample-HREdit50 Package-HREdit50 Valid-RateUnseen Package-HRUnseen Valid-Rate
    DeepSeekCoderBase0.81400.40910.82700.44140.7978
    DeepSeekCoderBOUND0.19800.07450.94800.17060.8909
    DeepSeekCoderFull-FT0.05800.01880.95000.21410.8991
    Llama-3.1Base0.83200.43080.81500.42950.8182
    Llama-3.1BOUND0.31800.14190.86900.19550.8353
    Llama-3.1ROME0.15900.42970.01100.43250.0147
    Qwen3Base0.90400.49910.76200.45550.7990
    Qwen3BOUND0.09900.05260.74100.09270.7434

    (MEMIT, DINM, Self-Refinement rows omitted; Self-Refinement unseen set not reported, shown as "–" in the table.)

    • The authors report three-model averages: edit set Sample-HR 0.8500→0.2050 (-75.9%), Package-HR 0.4463→0.0897 (-79.9%), Valid-Rate 0.8013→0.8527 (+6.4%); unseen set Sample-HR -63.7%, Package-HR 0.4421→0.1529 (-65.4%).
    • The authors state that the low hallucination rates of ROME and DINM are accompanied by a large drop in Valid-Rate (e.g., on Llama-3.1 ROME's edit set Valid-Rate is only 0.0110), and argue that these methods reduce hallucination by suppressing package recommendation behavior itself.
    • Exception: on the DeepSeekCoder edit set, Full-FT's Sample-HR (0.0580) and Package-HR (0.0188) are lower than BOUND's, but the authors state that its transfer on the unseen set is unstable (unseen Package-HR 0.2141 higher than BOUND's 0.1706); the authors report an average unseen-set Package-HR reduction of 65.4% for BOUND and 37.8% for Full-FT.

    Cross-task Generalization (RQ2, Table III)

    • Method: the edited model is used directly for code generation (extract import modules, map to PyPI package names using the unedited base model) and pip install recommendation (directly generate install commands), each sampling 100 unseen prompts.
    • Results: the authors report three-model averages: code generation Sample-HR -7.3%, Package-HR -12.8%, Valid-Rate +2.8%; pip install recommendation Sample-HR -35.7%, Package-HR -34.0%, Valid-Rate +12.8%.
    • Exceptions and authors' interpretation: under the pip install setting on Llama-3.1, ROME and Full-FT have Sample-HR, Package-HR, and Valid-Rate all 0, which the authors interpret as reflecting damage to the model's basic package-related capability rather than reduced hallucination; the authors suggest the smaller code generation gains may be because hallucination is introduced indirectly through import modules.

    Ablation (RQ3, Table IV, 100 unseen-set samples)

    • Full BOUND: three-model average Sample-HR 0.3207, Package-HR 0.1508, Valid-Rate 0.8248.
    • Effect of removing components: removing localization gives Sample-HR +18.3%, Package-HR +42.8%, Valid-Rate -11.5%; removing Valid-NLL drops Valid-Rate to 0.1512 (-81.7%); removing Hall-UL raises Package-HR to 0.5646 (+274.4%); removing Locality-KL gives Package-HR 0.5636 (+273.8%), Valid-Rate 0.3997 (-51.5%).
    • Authors' interpretation: localization and the three loss terms together maintain the balance between hallucination suppression and valid package retention.

    Other Ablations and Analyses

    • Cost (Table V): BOUND localization 23.81 s, editing 83.09 s, inference 11.30 s/example, artifact 731.03 KB; Full-FT editing 124.16 s, artifact 14.27 GB; the authors state the artifact is about 20,000 times smaller than a full fine-tuning checkpoint.
    • General capability (Table VI): on HumanEval, pass@1 change before and after editing is -1.38% (DeepSeekCoder), -1.36% (Qwen3), +0.60% (Llama-3.1); the authors state most changes are within ±2%.
    • The paper does not report statistical significance tests.
  5. What are some points that can be further explored?

    The authors list limitations including generalizability and ecosystem coverage; the experiments include only three open-source models and the PyPI ecosystem.

    Limitations and future directions noted by the authors

    • Model generalization: evaluation is conducted only on three open-source LLMs, and the authors note that results may not directly generalize to other LLMs; open-source models were chosen because their versions are stable and reproducible (Threats to Validity, External Validity).
    • Ecosystem coverage: only Python packages on PyPI are studied, because PyPI provides public metadata for validity verification; the authors plan to extend to other package ecosystems and languages (e.g., Java) (External Validity, Conclusion).
    • Task coverage: only three tasks are evaluated—package recommendation, code generation, and pip install recommendation; the authors note that real dependency management also involves configuration files, build scripts, and repository-level workflows, and plan to extend (External Validity).
    • Package name extraction: package names are extracted via regular expressions, which may not work as expected when model output formats are unstable; the authors mitigate with constrained output formats and one-shot prompting (Internal Validity).
    • Evaluation randomness: generation randomness causes fluctuation in hallucination rates; the authors mitigate with 5 samples per prompt and averaging over 4 folds (Internal Validity).
    • Localization noise: module localization may be affected by noisy gradients or the selected editing cases; the authors mitigate by aggregating localization signals across multiple cases (Internal Validity).

    Scope of experiments

    • The models tested are deepseek-coder-6.7b-instruct, Qwen3-8B, and Llama-3.1-8B-Instruct, 3 in total, all open-source models.
    • Data is the Python subset of the Spracklen et al. [12] dataset, with high-risk sets of 741/609/1,134 per model and 50 cases per editing fold (Table I).
    • Defense comparison covers 5 baselines: Full-FT, Self-Refinement, ROME, MEMIT, and DINM; RQ2/RQ3 evaluate 100 randomly sampled cases from the unseen set.
    • General capability impact is measured with HumanEval pass@1/pass@10 (Table VI).
    • The paper does not report statistical significance tests or human evaluation; the editing scale is 50 cases per fold, top 5 modules, and LoRA rank 8.
  6. Summarize the main content of the paper

    BOUND uses localization + LoRA editing to refine the package-validity boundary; the authors state that the hallucination rate drops substantially while valid package recommendation is preserved.

    A model editing paper for software supply chain security: addressing the problem of LLMs generating non-existent software package names (package hallucination), it proposes a lightweight local editing framework, BOUND.

    • Problem: Package hallucination can be exploited to register malicious packages; the authors argue that existing external mitigations do not change the model's internal behavior, full fine-tuning is costly, and existing model editing methods target isolated fact rewriting and are unsuitable for the scenario where "valid packages and hallucinated packages coexist in the same response."
    • Method: The problem is formalized as package validity boundary editing—the difference between the token logits of hallucinated packages and valid packages is used to construct a boundary risk score, backpropagation locates the top 5 sensitive modules, LoRA (rank 8) is injected and jointly optimized with three objectives: valid package NLL, hallucinated package unlikelihood, and locality KL; each fold uses only 50 editing cases.
    • Main results (average over three models, Table II): on the editing set, Package-HR drops from 0.4463 to 0.0897 (-79.9%), on unseen prompts from 0.4421 to 0.1529 (-65.4%), and Valid-Rate rises from 0.8013 to 0.8527.
    • Generalization (Table III): edits transfer to code generation (Package-HR -12.8%) and pip install recommendation (-34.0%); the authors state that ROME, DINM, and Full-FT push Valid-Rate close to 0 under some settings, reducing hallucination by suppressing package generation.
    • Cost: the average edited artifact is 731.03 KB (Table V), which the authors state is about 20,000 times smaller than a full fine-tuning checkpoint; HumanEval pass@1 changes within ±2% (Table VI).
    • Authors' conclusion: BOUND refines the model's package validity boundary without retraining and without relying on external retrieval; limitations are that it covers only three open-source models, the PyPI ecosystem, and three package-related tasks, and the authors plan to extend to more ecosystems and dependency management scenarios.
Read originalarxiv.org