EasyEdit

zjunlpMIT活跃维护

面向大语言模型的知识编辑框架,支持对模型内部事实知识进行定位、修改与评估,覆盖多种编辑算法和模型,方便研究和落地。

[ACL 2024] An Easy-to-use Knowledge Editing Framework for LLMs.

暂无版本2,938star +1 / 7 天376fork同步于 2026-11-10 11:42 UTC

怎么上手

由 README 提炼,执行前请确认
README 中安装章节内容被截断,未给出可确认的 pip 安装命令
硬件要求按 README 说明

README 未说明具体显存要求,仅提及有「Editing GPU memory usage」章节但内容被截断;未说明 CPU 运行与 GPU 厂商型号。

支持 Apple Silicon多卡 / 张量并行
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

一个面向大模型的知识编辑框架,统一实现知识插入、修改与擦除并配套评测

面向大语言模型的知识编辑框架,支持对模型内部事实知识进行定位、修改与评估,覆盖多种编辑算法和模型,方便研究和落地。

核心能力

  • 统一 BaseEditor 接口封装多种知识编辑算法
  • 支持知识插入、知识更新与知识擦除三类任务
  • 内置 KnowEdit 基准数据集与评测脚本
  • 提供 Trainer 支持训练式编辑方法
  • EasyEdit2 支持推理时 steering 的可控性框架

容易踩的坑

KnowEdit 基准需从 Hugging Face 等平台单独下载;README 提到 Counterfact 与 WikiData_Counterfact 并非同一数据集,勿混用;EasyEdit2 与 EasyEdit1.0 机制不同,需分别参考各自 README

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

0 个版本

暂无 release 数据(可能没有发版,或尚未同步)。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    License: MIT Static Badge


    ✨ EasyEdit blog published! We have also published a blog post titled "Take Control of What Your LLM Knows and Does — with the EasyEdit Tool Series", where you can learn more about how EasyEdit empowers you to control and edit your LLM’s knowledge and behavior.  

    Table of Contents

    🔔News

    • 2026-07-13, 🎉 EasyEdit has been selected for the CCF ODTC open source incentive program.
    • 2026-07-08, 🚀 EasyEdit has received a major upgrade, bringing Transformers 5.x compatibility, new models support, more reliable multi-GPU editing, enhanced multimodal pipelines, a unified EasyEdit2 steering workflow, expanded vLLM support, and faster multi-worker deployment.
    • 2026-03-04, 🎉 SteerEval is released — a hierarchical benchmark for evaluating LLM controllability across behavioral domains and granularity levels, with an automated data synthesis pipeline.
    • 2025-10-12, ⚡ LightMem is released — a lightweight and efficient memory framework empowering LLMs and AI agents with long-term memory capabilities!
    • 2025-10-02, 👑 SimIE has arrived — a general framework for lifelong model editing, which restores the strong performance of parameter-modifying methods from standard model editing in a lifelong context!
    • 2025-09-10, 🎉🎉 EasyEdit2 Paper has been accepted by the EMNLP 2025 System Demonstration Track.
    • 2025-07-24, 🚀🚀the EasyEdit has added three new unstructured long-form knowledge editing datasets AKEW, LEME and UNKE. In addition, EasyEdit also incorporated two of the currently most popular unstructured editing methods UNKE and AnyEdit. EasyEdit2 also supports the representation steering method RePS and provides initial support for AxBench-style evaluation.
    • 2025-06-07, 👑 UltraEdit has arrived — powered by a lifelong normalization strategy that continuously updates feature statistics across turns, it can edit 20K samples on a 7B model in just 5 minutes and scales stably to millions !
    • 2025-06-05, 🌟🌟the EasyEdit has added a new model editing algorithm CORE, designed to strengthen context robustness by minimizing context-sensitive variance in hidden states of the model for edited knowledge.
    • 2025-05-28, 🌟🌟the EasyEdit has added a new model editing algorithm NAMET, which introduces noise during memory extraction via a one-line modification to MEMIT. Thanks to @ybdai7 for contribution!
    • 2025-05-15, 🚀🚀We released a new blog Reflection on Knowledge Editing: Charting the Next Steps discussing the next step for knowledge editing research.
    • 2025-04-03, 🚀🚀We have upgraded EasyEdit and introduced EasyEdit2! EasyEdit2 provides an easy-to-use steering framework for editing large language models with precision and flexibility. This upgrade enhances the framework’s capabilities, making it more robust and adaptable for various steering methods. More details can be found in our paper, in the README and on our website.

    A Comprehensive Study of Knowledge Editing for Large Language Models [paper][benchmark][code]

    IJCAI 2024 Tutorial Google Drive

    COLING 2024 Tutorial Google Drive

    AAAI 2024 Tutorial Google Drive

    AACL 2023 Tutorial [Google Drive] [Baidu Pan]

    Editing Demo

    There is a demonstration of editing. The GIF file is created by Terminalizer.

    We provide a handy Jupyter Notebook! It allows you to edit a LLM's knowledge of the US president, switching from Biden to Trump and even back to Biden. This includes methods like WISE, AlphaEdit, AdaLoRA, and Prompt-based editing.

    Knowledge Editing

    Task Definition

    Deployed models may still make unpredictable errors. For example, LLMs notoriously hallucinate, perpetuate bias, and factually decay, so we should be able to adjust specific behaviors of pre-trained models.

    Knowledge editing aims to adjust base model's $(f_\theta)$ behavior on the particular edit descriptor $[x_e, y_e]$​​​ efficiently.

    Multi Setting

    Single Knowledge Editing

    Evaluating the performance of the model after a single edit. The model reloads the original weights (e.g. LoRA discards the adapter weights) after a single edit. You should set sequential_edit=False

    $$\theta' \leftarrow \text{arg} \min\limits_{\theta} (\Vert f_\theta(x_e) - y_e \Vert)$$

    Continuous Knowledge Editing

    This requires sequentially editing, and evaluation is performed after all knowledge updates have been applied:

    $$\theta' \leftarrow \text{arg} \min\limits_{\theta} \sum_{e=1}^{\Vert X_e \Vert} (\Vert f_\theta(x_e) - y_e \Vert)$$

    It makes parameter adjustments for $(x_e, y_e)$, where $x_e \in X_e$ and $f_\theta'(x_e) = y_e$. Here, $X_e$​ represents the whole edit set. To enable continuous editing, you can set sequential_edit=True: README (for more details).

    Multi Scenario

    Knowledge insert
    • Inject knowledge that LLMs have not seen before. such as:
      • How many times has Messi won the World Cup? 0 $\rightarrow$ 1:
    Knowledge update
    • Update outdated knowledge. such as:
      • The president of USA: Donald Trump $\rightarrow$ Joe Biden:
    Knowledge erase
    • Erase sensitive information. such as:
      • The phone number of someone is XXXX $\rightarrow$ __

    Without influencing the model behavior on unrelated samples, the ultimate goal is to create an edited model $(f_\theta')$​​.

    Editing Task for Image Captioning and Visual Question Answering. README

    The proposed task takes the preliminary attempt to edit LLMs' personalities by editing their opinions on specific topics, given that an individual's opinions can reflect aspects of their personality traits. We draw upon the established BIG FIVE theory as a basis for constructing our dataset and assessing the LLMs' personality expressions. README

    Evaluation

    Logits-based

    • ES: evaluating the editing success rate based on the logits of pre-generated text.
    • DD: evaluating whether the model changes opinions on other topics based on the logits of pre-generated text.

    Generation-based

    • Acc: the accuracy of the generated text after editing the model on target personality.
    • TPEI: measuring whether generated opinion text from the edited model leans more towards the target personality.
    • PAE: utilizing GPT-4 to evaluate the personality traits in generated text.

    While for assessing Acc and TPEI, you can download the trained classifier from here.

    Comparisons of different technologies

    Evaluation

    The knowledge editing process generally impacts the predictions for a broad set of inputs that are closely associated with the edit example, called the editing scope.

    A successful edit should adjust the model’s behavior within the editing scope while remaining unrelated inputs:

    $$ f_{\theta_{e}}(x) = \begin{cases} y_e & \text{if } x \in I(x_e,y_e) \ f_{\theta}(x) & \text{if } x \in O(x_e, y_e) \end{cases} $$

    • Reliability: the success rate of editing with a given editing descriptor
    • Generalization: the success rate of editing within the editing scope
    • Locality: whether the model's output changes after editing for unrelated inputs
    • Portability: the success rate of editing for reasoning/application(one hop, synonym, logical generalization)
    • Efficiency: time and memory consumption

    🌟Overview

    EasyEdit is a Python package for edit Large Language Models (LLM) like GPT-J, Llama, GPT-NEO, GPT2, T5(support models from 1B to 65B), the objective of which is to alter the behavior of LLMs efficiently within a specific domain without negatively impacting performance across other inputs. It is designed to be easy to use and easy to extend.

    • EasyEdit contains a unified framework for Editor, Method and Evaluate, respectively representing the editing scenario, editing technique, and evaluation method.

    • Each Knowledge Editing scenario comprises of three components:

      • Editor: such as BaseEditor(Factual Knowledge and Generation Editor) for LM, MultiModalEditor(MultiModal Knowledge).
      • Method: the specific knowledge editing technique used(such as ROME, MEND, ..).
      • Evaluate: Metrics for evaluating knowledge editing performance.
        • Reliability, Generalization, Locality, Portability
    • The current supported knowledge editing techniques are as follows:

      Note 1: Due to the limited compatibility of this toolkit, some knowledge editing methods including T-Patcher, KE, CaliNet are not supported.

      Note 2: Similarly, the MALMEN method is only partially supported due to the same reasons and will continue to be improved.

    Current Implementation

    You can choose different editing methods according to your specific needs. GPT series includes GPT-2, GPT-J and GPT-NEO.

    MethodT5GPT seriesLlaMABaichuanChatGLMInternLMQwenMistral
    FT✅✅✅✅✅✅✅✅
    AdaLoRA✅✅
    SERAC✅✅✅
    IKE✅✅✅✅✅✅✅✅
    MEND✅✅✅✅✅✅✅✅
    KN✅✅✅✅✅✅✅✅
    ROME✅✅✅✅✅✅✅
    r-ROME✅✅✅✅✅✅✅
    MEMIT✅✅✅✅✅✅✅
    EMMET✅✅
    GRACE✅✅
    MELO✅
    PMET✅✅
    InstructEdit✅✅
    DINM✅✅✅
    WISE✅✅✅✅
    Defer✅✅✅
    AlphaEdit✅✅
    UltraEdit✅✅✅✅

    ❗️❗️ If you intend to use Mistral, please update the transformers library to version 4.34.0 manually. You can use the following code: pip install transformers==4.34.0.

    We also support some knowledge editing methods for LMMs (Large Multimodal Models). Please refer to MultimodalEdit.md for more details.

    MethodMiniGPT-4BLIP-2LLaVA-OneVisionQwen2-VL
    MEND✅✅
    SERAC✅✅
    IKE✅✅
    LoRA✅✅
    GRACE✅✅
    WISE✅✅
    Quick Start on Some Works
    WorkDescriptionPath
    InstructEditInstructEdit: Instruction-based Knowledge Editing for Large Language ModelsQuick Start
    DINMDetoxifying Large Language Models via Knowledge EditingQuick Start
    WISEWISE: Rethinking the Knowledge Memory for Lifelong Model Editing of Large Language ModelsQuick Start
    ConceptEditEditing Conceptual Knowledge for Large Language ModelsQuick Start
    MMEditCan We Edit Multimodal Large Language Models?Quick Start
    PersonalityEditEditing Personality For Large Language ModelsQuick Start
    PROMPTPROMPT-based knowledge editing methodsQuick Start

    Dataset

    Benchmark: KnowEdit [Hugging Face][WiseModel][ModelScope]

    ❗️❗️ To be noted, KnowEdit is constructed by re-organizing and extending existing datasests including WikiBio, ZsRE, WikiDataCounterfact, WikiDataRecent, convsent, Sanitation to make a comprehensive evaluation for knowledge editing. Special thanks to the builders and maintainers of the those datasets.

    Please note that Counterfact and WikiDataCounterfact are not the same dataset.

    We provide detailed scripts for user to easily use KnowEdit, please refer to examples.

    • ZsRE: is a context-free question-answering task. Given a question based on the subject and relation, the model is expected to provide the correct object as the answer.
    • Wikirecent: This dataset specifically focuses on triplets that have been recently inserted into WikiData after July 2022.
    • WikiBio: The original dataset was created by prompting GPT-3 to generate 238 Wikipedia-style biographies using subjects from the WikiBio.
    • WikiDatacounterfact: Since tail entities are often not captured by models, and therefore are not suitable for testing modification edits, RippleEdit collects triplets about popular entities, where the subject corresponds to one of the top-viewed pages in Wikipedia.
    • Convsent: This is a sentiment editing task that assesses the model's ability to modify a dialog agent's sentiment on a specific topic without affecting its responses to other topics.
    • Sanitation: This dataset specifically addresses privacy concerns associated with learned language models.
    knowedit
    ├── WikiBio
    │   ├── wikibio-test-all.json
    │   └── wikibio-train-all.json
    ├── ZsRE
    │   └── ZsRE-test-all.json
    ├── wiki_counterfact
    │   ├── test_cf.json
    │   └── train_cf.json
    ├── convsent
    │   ├── blender_test.json
    │   ├── blender_train.json
    │   └── blender_val.json
    ├── convsent
    │   ├── trivia_qa_test.json
    │   └── trivia_qa_train.json
    └── wiki_recent
        ├── recent_test.json
        └── recent_train.json
    

    Datasets for Chinese Knowledge: CKnowEdit
    datasetHuggingFaceWiseModelModelScopeDescription
    CKnowEdit[HuggingFace][WiseModel][ModelScope]dataset for editing Chinese Knowledge
    • Here, you can follow CKnowEdit.md to find more details about CKnowEdit and run Chinese knowledge editing experiments.

    CKnowEdit is a high-quality Chinese-language dataset for knowledge editing which is highly characterized by the Chinese language, with all data sourced from Chinese knowledge bases. It is meticulously designed to more deeply discern the nuances and challenges inherent in the comprehension of the Chinese language by current LLMs, providing a robust resource for refining Chinese-specific knowledge within LLMs.

    The field descriptions for the data in CKnowEdit are as follows:

    "prompt": query inputed to the model (str)
    "target_old": the incorrect response previously generated by the model (str)
    "target_new": the accurate answer of the prompt (str)
    "portability_prompt": new prompts related to the target knowledge (list or None)
    "portability_answer": accurate answers corresponding to the portability_prompt (list or None)
    "locality_prompt": new prompts unrelated to the target knowledge (list or None)
    "locality_answer": accurate answers corresponding to the locality_prompt (list or None)
    "rephrase": alternative ways to phrase the original prompt (list)
    
    CknowEdit
    ├── Chinese Literary Knowledge
    │   ├── Ancient Poetry
    │   ├── Proverbs
    │   └── Idioms
    ├── Chinese Linguistic Knowledge
    │   ├── Phonetic Notation
    │   └── Classical Chinese
    ├── Chinese Geographical Knowledge
    └── Ruozhiba
    

    Datasets for Factual Knowledge
    datasetGoogle DriveBaiduNetDiskDescription
    ZsRE plus[Google Drive][BaiduNetDisk]Question Answering dataset using question rephrasings
    Counterfact plus[Google Drive][BaiduNetDisk]Counterfact dataset using Entity replacement

    We provide zsre and counterfact datasets to verify the effectiveness of knowledge editing. You can download them here. [Google Drive], [BaiduNetDisk].

    • For locality, in addition to testing unrelated instances, we also provide tests on distracting (reference: Detecting Edit Failures...), other attribution, and other downstream tasks (such as commonsense reasoning).
    • For portability, it tests whether the model can apply edited instances for inference. We provide evaluations for one-hop reasoning, subject alias, and inverse relation (eg, a one-to-one relationship between spouses should be bidirectionally edited).
    editing-data
    ├── counterfact
    │   ├── counterfact-edit.json
    │   ├── counterfact-train.json
    │   └── counterfact-val.json
    ├── locality
    │   ├── Commonsense Task
    │   │   ├── piqa_valid-labels.lst
    │   │   └── piqa_valid.jsonl
    │   ├── Distracting Neighbor
    │   │   └── counterfact_distracting_neighbor.json
    │   └── Other Attribution
    │       └── counterfact_other_attribution.json
    ├── portability
    │   ├── Inverse Relation
    │   │   └── zsre_inverse_relation.json
    │   ├── One Hop
    │   │   ├── counterfact_portability_gpt4.json
    │   │   └── zsre_mend_eval_portability_gpt4.json
    │   └── Subject Replace
    │       ├── counterfact_subject_replace.json
    │       └── zsre_subject_replace.json
    └── zsre
        ├── zsre_mend_eval.json
        ├── zsre_mend_train_10000.json
        └── zsre_mend_train.json
    
    • counterfact: original counterfact dataset using Entity replacement
    • zsre: original question answering dataset using question rephrasings
    • locality (evaluation for locality, see details in this paper)
      • Commonsense Task: evaluation for other downstream tasks such as commonsense task
      • Distracting Neighbor: test on distracting neighborhood (reference: Detecting Edit Failures...)
      • Other Attribution
    • portability
      • Inverse Relation: evaluation for one-to-one relationship such as spouse
      • One Hop: evaluation for one-hop reasoning
      • Subject Replace: evaluation for synonym replacement

    Datasets for Conceptual Knowledge: ConceptEdit
    datasetGoogle DriveHuggingFace DatasetDescription
    ConceptEdit[Google Drive][HuggingFace Dataset]dataset for editing conceptual knowledge
    • Here, you can follow ConceptEdit.md to run concept editing experiments.
    data
    └──concept_data.json
        ├──final_gpt2_inter.json
        ├──final_gpt2_intra.json
        ├──final_gptj_inter.json
        ├──final_gptj_intra.json
        ├──final_llama2chat_inter.json
        ├──final_llama2chat_intra.json
        ├──final_mistral_inter.json
        └──final_mistral_intra.json
    

    Concept Specific Evaluation Metrics

    • Instance Change: capturing the intricacies of these instance-level changes
    • Concept Consistency: the semantic similarity of generated concept definition

    Datasets for Multimodal Knowledge: MMEdit
    datasetGoogle DriveBaiduNetDiskDescription
    E-IC[Google Drive][BaiduNetDisk]dataset for editing Image Captioning
    E-VQA[Google Drive][BaiduNetDisk]dataset for editing Visual Question Answering
    ComprehendEdit[Google Drive][BaiduNetDisk]dataset for editing Visual Question Answering
    • All images used in E-IC and E-VQA are available for download at Google Drive
    • For locality, it is the same as factual editing in order to measure whether unrelated facts retain their outputs.
    • For multimodal locality, it assesses the impact of editing on the visual module, which is similar to regular locality.
    • The details of the impact of editing on other in-domain samples are in ComprehendEdit.
    editing-data
    ├── caption
    │   ├── caption_train_edit.json
    │   └── caption_eval_edit.json
    ├── locality
    │   ├── NQ dataset
    │   │   ├── train.json
    │   │   └── validation.json
    ├── multimodal_locality
    │   ├── OK-VQA dataset
    │   │   ├── okvqa_loc.json
    └── vqa
        ├── vqa_train.json
        └── vqa_eval.json
    
    • Multimodal locality (evaluation for multimodal locality, see dataset's details in this paper)

    Datasets for detoxifying LLMs: SafeEdit
    datasetHuggingFace DatasetDescription
    SafeEdit[HuggingFace Dataset]dataset for detoxifying LLMs
    • Here, you can follow SafeEdit.md to run detoxification editing experiments.
    data
    └──SafeEdit_train.json
    └──SafeEdit_val.json
    └──SafeEdit_test.json
        
    

    Detoxifying Specific Evaluation Metrics

    • Defense Duccess (DS): the detoxification success rate of edited LLM for adversarial input (attack prompt + harmful question), which is used to modify LLM.
    • Defense Generalization (DG): the detoxification success rate of edited LLM for out-of-domain malicious inputs.
    • General Performance: the side effects for unrelated task performance.
    Tutorial notebook
    MethodDescriptionGPT-2LlaMA
    IKEIn-Context Learning (ICL) Edit[Colab-gpt2][Colab-llama]
    ROMELocate-Then-Edit Neurons[Colab-gpt2][Colab-llama]
    MEMITLocate-Then-Edit Neurons[Colab-gpt2][Colab-llama]

    Datasets for Real-World Lifelong Knowledge Editing: WikiBigEdit
    datasetHuggingFace DatasetDescription
    WikiBigEdit[HuggingFace Dataset]500k knowledge edits from Wikidata

    Requirements

    🔧Pip Installation

    Note: Please use Python 3.9+ for EasyEdit To get started with pip, simply install conda and run:

    git clone https://github.com/zjunlp/EasyEdit.git
    cd EasyEdit
    conda create -n EasyEdit python=3.10
    conda activate EasyEdit
    pip install -r requirements.txt
    
    ⚡uv Installation

    You can also use uv for faster dependency installation:

    git clone https://github.com/zjunlp/EasyEdit.git
    cd EasyEdit
    conda create -n EasyEdit python=3.10
    conda activate EasyEdit
    pip install uv
    uv pip install --torch-backend cu128 -r requirements.txt
    

    If you are installing for a CPU-only environment, replace the last command with:

    uv pip install --torch-backend cpu -r requirements.txt
    

    After installation, you can verify the environment with:

    uv pip check
    
    Editing GPU memory usage

    Our results are all based on the default configuration

    llama-2-7Bchatglm2gpt-j-6bgpt-xl
    FT60GB58GB55GB7GB
    SERAC42GB32GB31GB10GB
    IKE52GB38GB38GB10GB
    MEND46GB37GB37GB13GB
    KN42GB39GB40GB12GB
    ROME31GB29GB27GB10GB
    MEMIT33GB31GB31GB11GB
    AdaLoRA29GB24GB25GB8GB
    GRACE27GB23GB6GB
    WISE34GB27GB7GB

    📌Use EasyEdit

    • Edit large language models(LLMs) around 5 seconds

    • Following example shows you how to perform editing with EasyEdit. More examples and tutorials can be found at examples

    BaseEditor

    BaseEditoris the class for Language Modality Knowledge Editing. You can choose the appropriate editing method based on your specific needs.

    • Due to different transformer versions and different GPU models, the editing results may fluctuate slightly.
    Introduction by a Simple Example

    With the modularity and flexibility of EasyEdit, you can easily use it to edit model.

    Step1: Define a PLM as the object to be edited. Choose the PLM to be edited. EasyEdit supports partial models(T5, GPTJ, GPT-NEO, LlaMA so far) retrievable on HuggingFace. The corresponding configuration file directory is hparams/YUOR_METHOD/YOUR_MODEL.YAML, such as hparams/MEND/gpt2-xl.yaml, set the corresponding model_name to select the object for knowledge editing.

    model_name: gpt2-xl
    model_class: GPT2LMHeadModel
    tokenizer_class: GPT2Tokenizer
    tokenizer_name: gpt2-xl
    model_parallel: false # true for multi-GPU editing
    

    Step2: Choose the appropriate Knowledge Editing Method

    ## In this case, we use MEND method, so you should import `MENDHyperParams`
    from easyeditor import MENDHyperParams
    ## Loading config from hparams/MEMIT/gpt2-xl.yaml
    hparams = MENDHyperParams.from_hparams('./hparams/MEND/gpt2-xl')
    

    Step3: Provide the edit descriptor and edit target

    ## edit descriptor: prompt that you want to edit
    prompts = [
        'What university did Watts Humphrey attend?',
        'Which family does Ramalinaceae belong to',
        'What role does Denny Herzig play in football?'
    ]
    ## You can set `ground_truth` to None !!!(or set to original output)
    ground_truth = ['Illinois Institute of Technology', 'Lecanorales', 'defender']
    ## edit target: expected output
    target_new = ['University of Michigan', 'Lamiinae', 'winger']
    

    Step4: Combine them into a BaseEditor EasyEdit provides a simple and unified way to init Editor, like huggingface: from_hparams.

    ## Construct Language Model Editor
    editor = BaseEditor.from_hparams(hparams)
    

    Step5: Provide the data for evaluation Note that the data for portability and locality are both optional(set to None for basic editing success rate evaluation only). The data format for both is a dict, for each measurement dimension, you need to provide the corresponding prompt and its corresponding ground truth. Here is an example of the data:

    locality_inputs = {
        'neighborhood':{
            'prompt': ['Joseph Fischhof, the', 'Larry Bird is a professional', 'In Forssa, they understand'],
            'ground_truth': ['piano', 'basketball', 'Finnish']
        },
        'distracting': {
            'prompt': ['Ray Charles, the violin Hauschka plays the instrument', 'Grant Hill is a professional soccer Magic Johnson is a professional', 'The law in Ikaalinen declares the language Swedish In Loviisa, the language spoken is'],
            'ground_truth': ['piano', 'basketball', 'Finnish']
        }
    }
    

    In the above example, we evaluate the performance of the editing methods about "neighborhood" and "distracting".

    Step6: Edit and Evaluation Done! We can conduct Edit and Evaluation for your model to be edited. The edit function will return a series of metrics related to the editing process as well as the modified model weights. [sequential_edit=True for continuous editing]

    metrics, edited_model, _ = editor.edit(
        prompts=prompts,
        ground_truth=ground_truth,
        target_new=target_new,
        locality_inputs=locality_inputs,
        sequential_edit=False # True: start continuous editing ✈️
    )
    ## metrics: edit success, rephrase success, locality e.g.
    ## edited_model: post-edit model
    

    The maximum input length for EasyEdit is 512. If this length is exceeded, you will encounter the error "CUDA error: device-side assert triggered." You can modify the maximum length in the following file:LINK

    Step7: RollBack In sequential editing, if you are not satisfied with the outcome of one of your edits and you do not wish to lose your previous edits, you can use the rollback feature to undo your previous edit. Currently, we only support the GRACE method. All you need to do is a single line of code, using the edit_key to revert your edit.

    editor.rolllback('edit_key')
    

    In EasyEdit, we default to using target_new as the edit_key

    Evaluation

    We specify the return metrics as dict format, including model prediction evaluations before and after editing. For each edit, it will include the following metrics:

    • rewrite_acc $\rightarrow$ Reliablilty
    • rephrase_acc $\rightarrow$ Generalization
    • locality $\rightarrow$ Locality
    • portablility $\rightarrow$ Portablility
    {
        "post": {
            "rewrite_acc": ,
            "rephrase_acc": ,
            "locality": {
                "YOUR_LOCALITY_KEY": ,
                //...
            },
            "portablility": {
                "YOUR_PORTABILITY_KEY": ,
                //...
            },
        },
        "pre": {
            "rewrite_acc": ,
            "rephrase_acc": ,
            "portablility": {
                "YOUR_PORTABILITY_KEY": ,
                //...
            },
        }
    }
    
    • For evaluation for Reliablilty, you only need to provide the corresponding editing prompts and editing target_new.
    • For evaluation for Generalization, rephrase_prompts are required.
    • For evaluation for Locality and Portablility, you need to define the name of the corresponding metric, as well as prompts and ground_truth.
      • Note: the length needs to be equal to the edit prompts

    Trainer

    • meta-learning based: MEND
    • memory-based routing: SERAC

    For above editing methods, pre-training of corresponding meta-networks or classifiers is required. Therefore, in EasyEdit, we provide a unified framework for pretraining the relevant network structures. Take the training MEND for example:

    • Step 1 and Step 2 are the same as the example above, which involves selecting the appropriate editing model and editing method.

    Step3: Provide the edit training set The currently supported and available datasets are: zsre and counterfact(Google Drive). Please place them in the "data" directory and initialize the dataset_class (ZsreDataset for zsre and CounterFactDataset for counterfact) to load the corresponding training set.

    train_ds = ZsreDataset('./data/zsre_mend_train.json', config=training_hparams)
    eval_ds = ZsreDataset('./data/zsre_mend_eval.json', config=training_hparams)
    

    Step4: Combine them into a Trainer

    trainer = EditTrainer(
        config=training_hparams,
        train_set=train_ds,
        val_set=eval_ds
    )
    

    Step5: Run and Edit Done! We can conduct Run and Evaluation.

    trainer.run()
    
    • Run: The CHECKPOINT will be saved to the path results_dir.
    • Edit: Set the archive field in the hparams file to CHECKPOINT. EasyEdit will automatically load the corresponding pre-trained weights during the editing process(Go to edit).

    Training Example

    from easyeditor import EditTrainer, MENDTrainingHparams, ZsreDataset
    
    training_hparams = MENDTrainingHparams.from_hparams('hparams/TRAINING/MEND/llama-7b.yaml')
    train_ds = ZsreDataset('./data/zsre/zsre_mend_train.json', config=training_hparams)
    eval_ds = ZsreDataset('./data/zsre/zsre_mend_eval.json', config=training_hparams)
    trainer = EditTrainer(
        config=training_hparams,
        train_set=train_ds,
        val_set=eval_ds
    )
    trainer.run()
    

    Use EasyEdit with KnowEdit

    Dataset

    KnowEdit is a benchmark dataset of knowledge editing for LLMs. You can easily obtain KnowEdit from HuggingFace, HuggingFace, and ModelScope.

    | dataset | HuggingFace| HuggingFace | ModelScope | | :--------: | :-----------------------------------------------------------------------------------------------: | :---