EasyEdit
repository·main·Indexed 25 days ago
https://github.com/zjunlp/easyeditA unified framework for knowledge and model editing of Large Language Models (LLMs). EasyEdit enables the control and modification of LLM knowledge and behavior through insertion, updating, and erasing. It includes implementations such as SafeEdit for toxic region editing, DeCo (Dynamic Correction Decoding) and DoLa (Decoding by Contrasting Layers) for hallucination mitigation and steering in LLMs and MLLMs, and tools for identifying and manipulating knowledge neurons in BERT, GPT2, and GPT-Neo.
What's inside EasyEdit
- The ROME (Rank-One Model Editing) package provides a self-contained implementation of the ROME editing algorithm. The process consists of three main stages: $u$ selection, $v_*$ optimization, and $v$ insertion. The implementation is modularized into specific components for each stage and hyperparameter management.
Overview of PEFT (Parameter-Efficient Fine-Tuning)
mainPEFT is a library designed to efficiently adapt pre-trained language models (PLMs) to downstream applications. Instead of fine-tuning all model parameters, PEFT methods only fine-tune a small number of extra parameters, which significantly reduces computational and storage costs while maintaining performance comparable to full fine-tuning. It integrates with 🤗 Accelerate for large-scale models using DeepSpeed and Big Model Inference.Overview of EasyEdit Framework
mainEasyEdit is a Python package designed to efficiently edit the behavior of Large Language Models (LLMs) like
GPT-J,Llama,GPT-NEO,GPT2, andT5(supporting models from 1B to 65B) within specific domains without degrading general performance.The framework is organized into three core components:
- Editor: Defines the editing scenario (e.g.,
BaseEditorfor Factual Knowledge and Generation, orMultiModalEditorfor Multimodal Knowledge). - Method: The specific knowledge editing technique applied (e.g.,
ROME,MEND). - Evaluate: Metrics used to assess performance, including
Reliability,Generalization,Locality, andPortability.
- Editor: Defines the editing scenario (e.g.,
Overview of EasyEdit2 steering methods
mainEasyEdit2 implements several categories of steering methods to control LLM behavior:
Activation-based Methods
- Contrastive Activation Addition (CAA): Computes activation differences between positive and negative example pairs.
- LM-Steer: Applies a lightweight linear transformation to output embeddings.
- SAE Feature Steering: Uses features from Sparse Autoencoders (SAEs) to select specific concepts.
- Steering Target Atoms (STA): Refines CAA using SAEs for better control.
- Reference-free Preference Steering (RePS): Uses a bidirectional preference objective to promote/suppress concepts.
- Vector Prompt: Transforms prompts into steering vectors.
Prompt-Based Methods
- Manually Designed Prompts: Direct control via tailored input prompts.
- Automated Prompt Generation: Model autonomously generates steering prompts based on a provided concept.
Decoding-based Methods
- (Coming soon)
Understand Prompting methods (Hard vs Soft)
mainPrompting primes a frozen pretrained model for a specific downstream task using a text prompt. There are two main categories:
- Hard prompts: Manually handcrafted text prompts consisting of discrete input tokens. They require significant effort to create effective prompts.
- Soft prompts: Learnable tensors concatenated with input embeddings. These are optimized against a dataset and are not human-readable (they are 'virtual tokens').
Soft prompt methods included in PEFT are prompt tuning, prefix tuning, and P-tuning.
Explore Knowledge Editing Scenarios
mainEasyEdit provides implementations for several knowledge editing scenarios:
- Factual Knowledge Editing: Includes Knowledge insert (injecting new facts), Knowledge update (updating outdated facts), and Knowledge erase (removing sensitive information).
- Safety Editing: Focuses on detoxifying LLMs to correct toxic behaviors using small amounts of data.
- MultiModal Model Editing: Editing tasks for Image Captioning and Visual Question Answering (VQA).
- Personality Editing: Editing LLM opinions on specific topics based on personality traits (e.g., BIG FIVE theory).
Generate steering vectors with BaseVectorGenerator
mainTo create steering vectors for a language model, follow these steps:
- Select a steering method: Configure a method-specific parameter file (e.g.,
hparams/Steer/caa_hparams/generate_caa.yaml). For CAA, use:alg_name: caa layers: [17] multiple_choice: false - Configure top-level settings: Edit
hparams/Steer/vector_generate.yamlto specify themodel_name_or_path,dtype,device, and the paths forsteer_train_hparam_paths,steer_train_dataset, andsteer_vector_output_dir. - Prepare input data: Provide a dictionary of datasets where each entry contains
question,matching, andnot_matchingkeys, or useprepare_train_datasets(top_cfg). - Run generation: Initialize
BaseVectorGeneratorwith your configuration and callgenerate_vectors(datasets).
Vectors are saved to:
{steer_vector_output_dir}/{steer_train_dataset}/{method_name}_vector.# Example workflow for generating vectors vector_generator = BaseVectorGenerator(top_cfg) vector_generator.generate_vectors(datasets)- Select a steering method: Configure a method-specific parameter file (e.g.,
Perform Concept Consistency evaluation
mainTo evaluate
Concept Consistency(semantic similarity of generated concept definitions), follow these steps:- In
run_concept_editing.py, uncomment line 113:concept_consistency = True. - In
easyeditor/editors/concept_editor.py, modify line 184 to settest_concept_consistency=concept_consistency. - Re-run the main execution command (Step 1 in the Run guide).
- To convert the generated sentences into a JSON file for GPT-4 evaluation, run the transformation script.
python examples/conceptedit_transform_check.py --method FT --model llama2chat --module intra- In
Preprocess token classification datasets with word alignment
mainWhen working with datasets where text is already split into words (like BioNLP2004), you must use
is_split_into_words=Truein the tokenizer. You also need to align the labels with the subword tokens generated by the tokenizer.Use
tokenizer.word_ids(batch_index=i)to map subword tokens back to their original word indices. Set labels for special tokens to-100to ignore them during training.def tokenize_and_align_labels(examples): tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True) labels = [] for i, label in enumerate(examples[f"tags"]): word_ids = tokenized_inputs.word_ids(batch_index=i) previous_word_idx = None label_ids = [] for word_idx in word_ids: if word_idx is None: label_ids.append(-100) elif word_idx != previous_word_idx: label_ids.append(label[word_idx]) else: label_ids.append(-100) previous_word_idx = word_idx labels.append(label_ids) tokenized_inputs["labels"] = labels return tokenized_inputsConfigure Fully Sharded Data Parallel (FSDP) with 🤗 Accelerate
mainTo use FSDP for distributed training of large models, you must first create a configuration file using the
accelerate configcommand. This file defines your sharding strategy, CPU offloading settings, and auto-wrap policies.Run the following command to start the interactive configuration process and save it to a specific file:
accelerate config --config_file fsdp_config.yamlKey configuration arguments to consider:
Sharding Strategy:[1] FULL_SHARD: Shards optimizer states, gradients, and parameters.[2] SHARD_GRAD_OP: Shards optimizer states and gradients.[3] NO_SHARD
Offload Params: Determines whether to offload parameters and gradients to the CPU.Auto Wrap Policy:[1] TRANSFORMER_BASED_WRAP: Wraps layers based on specific class names.[2] SIZE_BASED_WRAP: Wraps layers based on parameter count.[3] NO_WRAP
Transformer Layer Class to Wrap: A comma-separated string of case-sensitive transformer layer class names (e.g.,T5Block,BertLayer) used whenTRANSFORMER_BASED_WRAPis selected.Backward Prefetch:[1] BACKWARD_PRE,[2] BACKWARD_POST, or[3] NO_PREFETCH.State Dict Type:[1] FULL_STATE_DICT,[2] LOCAL_STATE_DICT, or[3] SHARDED_STATE_DICT.
Run Conceptual Knowledge Editing experiments
mainBefore running, ensure the following directories exist and are properly configured:
./data,./hparams, and./hugging_cache.Move
run_concept_editing.pyto the root directory (./) before execution.Supported editing methods include:
FT,ROME,MEMIT, andPROMPT.Note for Llama2 users: If using
LlaMA2-13B-Chatinstead ofLlaMA2-13B-Base, you must manually update themodel_namein the corresponding.yamlfile (e.g.,./hparams/[METHOD]/llama-7b.yaml) or provide your own configuration file.python run_concept_editing.py --editing_method=ROME --edited_model gptj --hparams_dir=./hparams/ROME/gpt-j-6B --interInstall dependencies for P-tuning
mainTo use P-tuning for sequence classification, ensure you have
peft,transformers,datasets, andevaluateinstalled.!pip install -q peft transformers datasets evaluate