rmanluo commited on
Commit
c8a2164
Β·
verified Β·
1 Parent(s): 15d1a73

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +312 -0
README.md ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
4
+
5
+ # GFM-RAG: Graph Foundation Model for Retrieval Augmented Generation
6
+
7
+ <div align="left">
8
+ <p>
9
+ <a href='https://rmanluo.github.io/gfm-rag/'><img src='https://img.shields.io/badge/Project-Page-Green'></a>
10
+ <a href='https://www.arxiv.org/abs/2502.01113'><img src='https://img.shields.io/badge/arXiv-2502.01113-b31b1b'></a>
11
+ <a href="https://pypi.org/project/gfmrag/">
12
+ </p>
13
+ <p>
14
+ <img src='https://img.shields.io/github/stars/RManLuo/gfm-rag?color=green&style=social' />
15
+ <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/gfmrag">
16
+ </a>
17
+ <a href="https://pypi.org/project/gfmrag/">
18
+ <img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/gfmrag">
19
+ </a>
20
+ <a href="https://github.com/RManLuo/gfm-rag/issues">
21
+ <img alt="GitHub Issues" src="https://img.shields.io/github/issues/RManLuo/gfm-rag">
22
+ </a>
23
+ <a href="https://github.com/RManLuo/gfm-rag/discussions">
24
+ <img alt="GitHub Discussions" src="https://img.shields.io/github/discussions/RManLuo/gfm-rag">
25
+ </a>
26
+ </p>
27
+ </div>
28
+
29
+ The GFM-RAG is the first graph foundation powered RAG pipeline that combines the power of graph neural networks to reason over knowledge graphs and retrieve relevant documents for question answering.
30
+
31
+ We first build a knowledge graph index (KG-index) from the documents to capture the relationships between knowledge. Then, we feed the query and constructed KG-index into the pre-trained graph foundation model (GFM) retriever to obtain relevant documents for LLM generation. The GFM retriever experiences large-scale training and can be directly applied to unseen datasets without fine-tuning.
32
+
33
+ For more details, please refer to our [project page](https://rmanluo.github.io/gfm-rag/) and [paper](https://www.arxiv.org/abs/2502.01113).
34
+
35
+
36
+ ## Features
37
+
38
+ - **Graph Foundation Model (GFM)**: A graph neural network-based retriever that can reason over the KG-index.
39
+ - **Knowledge Graph Index**: A knowledge graph index that captures the relationships between knowledge.
40
+ - **Efficiency**: The GFM-RAG pipeline is efficient in conduct multi-hop reasoning with single step retrieval.
41
+ - **Generalizability**: The GFM-RAG can be directly applied to unseen datasets without fine-tuning.
42
+ - **Transferability**: The GFM-RAG can be fine-tuned on your own dataset to improve performance on specific domains.
43
+ - **Compatibility**: The GFM-RAG is compatible with arbitrary agent-based framework to conduct multi-step reasoning.
44
+ - **Interpretability**: The GFM-RAG can illustrate the captured reasoning paths for better understanding.
45
+
46
+ ## Dependencies
47
+
48
+ - Python 3.12
49
+ - CUDA 12 and above
50
+
51
+ ## Installation
52
+
53
+ Conda provides an easy way to install the CUDA development toolkit which is required by GFM-RAG
54
+
55
+ Install packages
56
+ ```bash
57
+ conda create -n gfmrag python=3.12
58
+ conda activate gfmrag
59
+ conda install cuda-toolkit -c nvidia/label/cuda-12.4.1 # Replace with your desired CUDA version
60
+ pip install gfmrag
61
+ ```
62
+
63
+ Install other dependencies
64
+ ```bash
65
+ TORCH=$(python -c "import torch; print(torch.__version__)")
66
+ pip install torch_scatter torch_sparse -f https://data.pyg.org/whl/torch-${TORCH}.html
67
+ ```
68
+
69
+ ## Quick Start
70
+
71
+ ### Prepare Data
72
+
73
+ You need to prepare the following files:
74
+
75
+ - `dataset_corpus.json`: A JSON file containing the entire document corpus.
76
+ - `train.json` (optional): A JSON file containing the training data.
77
+ - `test.json` (optional): A JSON file containing the test data.
78
+
79
+ Place your files in the following structure:
80
+ ```
81
+ data_name/
82
+ β”œβ”€β”€ raw/
83
+ β”‚ β”œβ”€β”€ dataset_corpus.json
84
+ β”‚ β”œβ”€β”€ train.json # (optional)
85
+ β”‚ └── test.json # (optional)
86
+ └── processed/ # Output directory
87
+ ```
88
+
89
+ #### `dataset_corpus.json`
90
+
91
+ The `dataset_corpus.json` is a dictionary where each key is the title or unique id of a document and the value is the text of the document.
92
+
93
+ ```json
94
+ {
95
+ "Fred Gehrke":
96
+ "Clarence Fred Gehrke (April 24, 1918 – February 9, 2002) was an American football player and executive. He played in the National Football League (NFL) for the Cleveland / Los Angeles Rams, San Francisco 49ers and Chicago Cardinals from 1940 through 1950. To boost team morale, Gehrke designed and painted the Los Angeles Rams logo in 1948, which was the first painted on the helmets of an NFL team. He later served as the general manager of the Denver Broncos from 1977 through 1981. He is the great-grandfather of Miami Marlin Christian Yelich"
97
+ ,
98
+ "Manny Machado":
99
+ "Manuel Arturo Machado (] ; born July 6, 1992) is an American professional baseball third baseman and shortstop for the Baltimore Orioles of Major League Baseball (MLB). He attended Brito High School in Miami and was drafted by the Orioles with the third overall pick in the 2010 Major League Baseball draft. He bats and throws right-handed."
100
+ ,
101
+ ...
102
+ }
103
+ ```
104
+
105
+ #### `train.json` and `test.json` (optional)
106
+ If you want to train and evaluate the model, you need to provide training and test data in the form of a JSON file. Each entry in the JSON file should contain the following fields:
107
+
108
+ - `id`: A unique identifier for the example.
109
+ - `question`: The question or query.
110
+ - `supporting_facts`: A list of supporting facts for the question. Each supporting fact is a list containing the title of the document that can be found in the `dataset_corpus.json` file.
111
+
112
+ Each entry can also contain additional fields depending on the task. For example:
113
+
114
+ - `answer`: The answer to the question.
115
+
116
+ The additional fields will be copied during the following steps of the pipeline.
117
+
118
+ Example:
119
+ ```json
120
+ [
121
+ {
122
+ "id": "5adf5e285542992d7e9f9323",
123
+ "question": "When was the judge born who made notable contributions to the trial of the man who tortured, raped, and murdered eight student nurses from South Chicago Community Hospital on the night of July 13-14, 1966?",
124
+ "answer": "June 4, 1931",
125
+ "supporting_facts": [
126
+ "Louis B. Garippo",
127
+ "Richard Speck"
128
+ ]
129
+ },
130
+ {
131
+ "id": "5a7f7b365542992097ad2f80",
132
+ "question": "Did the Beaulieu Mine or the McIntyre Mines yield gold and copper?",
133
+ "answer": "The McIntyre also yielded a considerable amount of copper",
134
+ "supporting_facts": [
135
+ "Beaulieu Mine",
136
+ "McIntyre Mines"
137
+ ]
138
+ }
139
+ ...
140
+ ]
141
+ ```
142
+
143
+ ### Index Dataset
144
+
145
+ You need to create a KG-index [configuration file](gfmrag/workflow/config/stage1_index_dataset.yaml).
146
+
147
+ Details of the configuration parameters are explained in the [KG-index Configuration](https://rmanluo.github.io/gfm-rag/config/kg_index_config/) page.
148
+
149
+ ```bash
150
+ python -m gfmrag.workflow.stage1_index_dataset
151
+ ```
152
+
153
+ This method performs two main tasks:
154
+
155
+ 1. Creates and saves knowledge graph related files (`kg.txt` and `document2entities.json`) from the `dataset_corpus.json` file
156
+ 2. Identify the query entities and supporting entities in training and testing data if available in the raw data directory.
157
+
158
+ Files created:
159
+
160
+ - `kg.txt`: Contains knowledge graph triples
161
+ - `document2entities.json`: Maps documents to their entities
162
+ - `train.json`: Processed training data (if raw exists)
163
+ - `test.json`: Processed test data (if raw exists)
164
+
165
+ Directory structure:
166
+ ```
167
+ root/
168
+ └── data_name/
169
+ β”œβ”€β”€ raw/
170
+ β”‚ β”œβ”€β”€ dataset_corpus.json
171
+ β”‚ β”œβ”€β”€ train.json (optional)
172
+ β”‚ └── test.json (optional)
173
+ └── processed/
174
+ └── stage1/
175
+ β”œβ”€β”€ kg.txt
176
+ β”œβ”€β”€ document2entities.json
177
+ β”œβ”€β”€ train.json
178
+ └── test.json
179
+ ```
180
+
181
+ ### GFM-RAG Retrieval
182
+
183
+ You need to create a [configuration file](gfmrag/workflow/config/stage3_qa_ircot_inference.yaml) for inference.
184
+
185
+ Details of the configuration parameters are explained in the [GFM-RAG Configuration](https://rmanluo.github.io/gfm-rag/config/gfmrag_retriever_config/) page.
186
+
187
+ #### Initialize GFMRetriever
188
+
189
+ You can initialize the GFMRetriever with the following code. It will load the pre-trained GFM-RAG model and the KG-index for retrieval.
190
+
191
+ ```python
192
+ import logging
193
+ import os
194
+
195
+ import hydra
196
+ from hydra.core.hydra_config import HydraConfig
197
+ from omegaconf import DictConfig, OmegaConf
198
+
199
+ from gfmrag import GFMRetriever
200
+
201
+ logger = logging.getLogger(__name__)
202
+
203
+
204
+ @hydra.main(
205
+ config_path="config", config_name="stage3_qa_ircot_inference", version_base=None
206
+ )
207
+ def main(cfg: DictConfig) -> None:
208
+ output_dir = HydraConfig.get().runtime.output_dir
209
+ logger.info(f"Config:\n {OmegaConf.to_yaml(cfg)}")
210
+ logger.info(f"Current working directory: {os.getcwd()}")
211
+ logger.info(f"Output directory: {output_dir}")
212
+
213
+ gfmrag_retriever = GFMRetriever.from_config(cfg)
214
+ ```
215
+
216
+ #### Document Retrieval
217
+
218
+ You can use GFM-RAG retriever to reason over the KG-index and obtain documents for a given query.
219
+ ```python
220
+ docs = retriever.retrieve("Who is the president of France?", top_k=5)
221
+ ```
222
+
223
+ #### Question Answering
224
+
225
+ ```python
226
+ from hydra.utils import instantiate
227
+ from gfmrag.llms import BaseLanguageModel
228
+ from gfmrag.prompt_builder import QAPromptBuilder
229
+
230
+ llm = instantiate(cfg.llm)
231
+ qa_prompt_builder = QAPromptBuilder(cfg.qa_prompt)
232
+
233
+ message = qa_prompt_builder.build_input_prompt(current_query, retrieved_docs)
234
+ answer = llm.generate_sentence(message) # Answer: "Emmanuel Macron"
235
+ ```
236
+
237
+ ## GFM Fine-tuning
238
+
239
+ During fine-tuning, the GFM model will be trained on the query-documents pairs `train.json` from the labeled dataset to learn complex relationships for retrieval.
240
+
241
+ It can be conduced on your own dataset to improve the performance of the model on your specific domain.
242
+
243
+ A example of the training data:
244
+
245
+ ```json
246
+ [
247
+ {
248
+ "id": "5abc553a554299700f9d7871",
249
+ "question": "Kyle Ezell is a professor at what School of Architecture building at Ohio State?",
250
+ "answer": "Knowlton Hall",
251
+ "supporting_facts": [
252
+ "Knowlton Hall",
253
+ "Kyle Ezell"
254
+ ],
255
+ "question_entities": [
256
+ "kyle ezell",
257
+ "architectural association school of architecture",
258
+ "ohio state"
259
+ ],
260
+ "supporting_entities": [
261
+ "10 million donation",
262
+ "2004",
263
+ "architecture",
264
+ "austin e knowlton",
265
+ "austin e knowlton school of architecture",
266
+ "bachelor s in architectural engineering",
267
+ "city and regional planning",
268
+ "columbus ohio united states",
269
+ "ives hall",
270
+ "july 2002",
271
+ "knowlton hall",
272
+ "ksa",
273
+ ]
274
+ },
275
+ ...
276
+ ]
277
+ ```
278
+
279
+ You need to create a [configuration file](gfmrag/workflow/config/stage2_qa_finetune.yaml) for fine-tuning.
280
+
281
+ Details of the configuration parameters are explained in the [GFM-RAG Fine-tuning Configuration](https://rmanluo.github.io/gfm-rag/config/gfmrag_finetune_config/) page.
282
+
283
+ You can fine-tune the pre-trained GFM-RAG model on your dataset using the following command:
284
+
285
+ ```bash
286
+ python -m gfmrag.workflow.stage2_qa_finetune
287
+ # Multi-GPU training
288
+ torchrun --nproc_per_node=4 gfmrag.workflow.stage2_qa_finetune
289
+ # Multi-node Multi-GPU training
290
+ torchrun --nproc_per_node=4 --nnodes=2 gfmrag.workflow.stage2_qa_finetune
291
+ ```
292
+
293
+ ## Acknowledgements
294
+
295
+ We greatly appreciate the following repositories for their help to this project:
296
+
297
+ * [DeepGraphLearning/ULTRA](https://github.com/DeepGraphLearning/ULTRA): The ULTRA model is used as the base GNN model for the GFM retriever.
298
+ * [OSU-NLP-Group/HippoRAG](https://github.com/OSU-NLP-Group/HippoRAG): We get great inspiration from the KG construction process of HippoRAG.
299
+ * [microsoft/graphrag](https://github.com/microsoft/graphrag): We get great inspiration from the project design of GraphRAG.
300
+
301
+ ## Citation
302
+
303
+ If you find this repository helpful, please consider citing our paper:
304
+
305
+ ```bibtex
306
+ @article{luo2025gfmrag,
307
+ title={GFM-RAG: Graph Foundation Model for Retrieval Augmented Generation},
308
+ author={Luo, Linhao and Zhao, Zicheng and Haffari, Gholamreza and Phung, Dinh and Gong, Chen and Pan, Shirui},
309
+ journal={arXiv preprint arXiv:2502.01113},
310
+ year={2025}
311
+ }
312
+ ```