A context tracing tool for LLM
Project description
Searching for Needles in a Haystack with TracLLM
This repository provides the official PyTorch implementation of our paper, presenting a general framework for finding the critical texts within a lengthy context that contribute to the LLM's answer:
Searching for Needles in a Haystack: Context Tracing for Unraveling Outputs of Long Context LLMs
Yanting Wang1†, Wei Zou1†, Runpeng Geng 1, Jinyuan Jia 1,1Penn State University
†Co-first author
🗂️ Code Structure
TracLLM/
├── tracllm/
│ ├── models/ # Models and LLMs code
│ ├── attribute/ # Perturbation-based (including our TracLLM) and self-citation-based attribution methods
│ ├── evaluate.py # Evaluation code
│ ├── load_dataset.py # Load LongBench, PoisonedRAG, and NeedleInHaystack datasets
│ ├── prompts.py # Prompt template
│ └── utils.py # some small helper functions
├── PromptInjectionAttacks/ # Different prompt injection attacks to LongBench
├── main.py # main function for running the experiments
└── scripts/ # scripts for running the experiments
🔨 Setup environment
Please run the following commands to set up the environment:
conda env create -f environment.yml
conda activate TracLLM
or
conda env create TracLLM
conda activate TracLLM
pip install -r requirements.txt
🔑 Set API key
Please enter your api key in model_configs/llama3.1-8b_config.json to use LLaMA-3.1.
For LLaMA-3.1, the api key is your HuggingFace Access Tokens. You could visit LLaMA-3.1's HuggingFace Page first if you don't have the access token.
Please enter your api key here:
"api_key_info":{
"api_keys":[
"Your api key here"
],
"api_key_use": 0
},
📝 Getting Started
Explore TracLLM with our example notebook quick_start.ipynb.
To use TracLLM, first generate the model and attribution object:
from src.models import create_model
from src.attribution import PerturbationBasedAttribution
from src.prompts import wrap_prompt
model_name = 'llama3.1-8b'
llm = create_model(f'model_configs/{model_name}_config.json', device = "cuda:0")
score_funcs = ['stc','loo','denoised_shapley'] #input more than one scoring function for ensembling
attr = PerturbationBasedAttribution(llm,explanation_level = "sentence", attr_type = "tracllm",score_funcs= score_funcs,sh_N = 5)
Then, you can craft the prompt and get the LLM's answer:
context = """Heretic is a 2024 American psychological horror[4][5][6] film written and directed by Scott Beck and Bryan Woods. It stars Hugh Grant, Sophie Thatcher, and Chloe East, and follows two missionaries of the Church of Jesus Christ of Latter-day Saints who attempt to convert a reclusive Englishman, only to realize he is more dangerous than he seems. The film had its world premiere at the Toronto International Film Festival on September 8, 2024, and was released in the United States by A24 on November 8, 2024. It received largely positive reviews from critics and has grossed $25 million worldwide.
\n\n Red One is a 2024 American action-adventure Christmas comedy film directed by Jake Kasdan and written by Chris Morgan, from an original story by Hiram Garcia. The film follows the head of North Pole security (Dwayne Johnson) teaming up with a notorious hacker (Chris Evans) in order to locate a kidnapped Santa Claus (J. K. Simmons) on Christmas Eve; Lucy Liu, Kiernan Shipka, Bonnie Hunt, Nick Kroll, Kristofer Hivju, and Wesley Kimmel also star. The film is seen as the first of a Christmas-themed franchise, produced by Amazon MGM Studios in association with Seven Bucks Productions, Chris Morgan Productions, and The Detective Agency.[7][8] Red One was released internationally by Warner Bros. Pictures on November 6 and was released in the United States by Amazon MGM Studios through Metro-Goldwyn-Mayer on November 15, 2024.[9] The film received generally negative reviews from critics, but it has grossed $10 billion solely in the USA. M.O.R.A (Mythological Oversight and Restoration Authority) is a clandestine, multilateral military organization that oversees and protects a secret peace treaty between mythological creatures and humanity. Callum Drift, head commander of Santa Claus's ELF (Enforcement Logistics and Fortification) security, requests to retire after one last Christmas run, as he has become disillusioned with increased bad behavior in the world, exemplified by the growth of Santa's Naughty List.
"""
question= "Which movie earned more money, Heretic or Red one?"
prompt = wrap_prompt(question, [context])
answer = llm.query(prompt)
print("Answer: ", answer)
Finally, you can get the attribution results of TracLLM by calling attr.attribute:
texts,important_ids, importance_scores, _,_ = attr.attribute(question, [context], answer)
attr.visualize_results(texts,question,answer, important_ids,importance_scores, width = 60)
🔬 Experiments
Execute the scripts below to replicate our experimental findings for LongBench (with prompt injection attacks), PoisonedRAG, and NeedleInHaystack.
- script_prompt_injection.py: tracing malicious instructions injected into long contexts from LongBench.
- script_PoisonedRAG.py: finding corrupted knowledge from retrieved texts of a RAG system.
- script_needle_in_haystack.py: tracing needles in a haystack.
For example, to run the prompt injection experiment to LongBench under the default setting of TracLLM, execute:
python scripts/script_prompt_injection.py
To speed up the computation, you can set sh_N (the number of permutations for shapley/denoised_shapley) to 5:
python main.py --dataset_name musique --model_name llama3.1-8b --prompt_injection_attack default --inject_times 5 --sh_N 5
Acknowledgement
- This project incorporates code from PoisonedRAG and corpus-poisoning.
- This project incorporates datasets from LongBench and Needle In A Haystack.
- This project draws inspiration from ContextCite and AgentPoison.
- The model component of this project is based on Open-Prompt-Injection.
- This project utilizes contriever for retrieval augmented generation (RAG).
Citation
@article{wang2024tracllm,
title={Searching for Needles in a Haystack: Context Tracing for Unraveling Outputs of Long Context LLMs},
author={Wang Yanting, Zou Wei, Geng Runpeng and Jia Jinyuan},
year={2024}
}
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tracllm-0.1.1.tar.gz.
File metadata
- Download URL: tracllm-0.1.1.tar.gz
- Upload date:
- Size: 6.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.10.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e0b0c2118a56e8816982a8db3081e515cc0e7667d2fe8e5e70d08ffee568f8b0
|
|
| MD5 |
fafb3f6bcf87162839d44693b1624685
|
|
| BLAKE2b-256 |
619840cffc85da9ea247c184dcc7983bb18c0a136806cf3aae19125a8fe7d166
|
File details
Details for the file tracllm-0.1.1-py3-none-any.whl.
File metadata
- Download URL: tracllm-0.1.1-py3-none-any.whl
- Upload date:
- Size: 5.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.0.1 CPython/3.10.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f103881498b4a6ab1068b8647deb9648563dc39409963feb9ba2f952ac29e401
|
|
| MD5 |
8c700bf6941da22ee1949e8342e1a8a4
|
|
| BLAKE2b-256 |
2305582dae0d8ebc07a279acb148cb0d43031cc684d591ab6e8c45532aa50a7b
|