LightRAG/examples/vram_management_demo.py

122 lines
3.4 KiB
Python
Raw Normal View History

2024-10-20 11:27:47 +08:00
import os
import time
2025-03-03 18:33:42 +08:00
import asyncio
2024-10-20 11:27:47 +08:00
from lightrag import LightRAG, QueryParam
from lightrag.llm.ollama import ollama_model_complete, ollama_embed
2024-10-20 11:27:47 +08:00
from lightrag.utils import EmbeddingFunc
2025-03-03 18:33:42 +08:00
from lightrag.kg.shared_storage import initialize_pipeline_status
2024-10-20 11:27:47 +08:00
2024-10-20 18:08:49 +08:00
# Working directory and the directory path for text files
2024-10-20 11:27:47 +08:00
WORKING_DIR = "./dickens"
TEXT_FILES_DIR = "/llm/mt"
2024-10-20 18:08:49 +08:00
# Create the working directory if it doesn't exist
2024-10-20 11:27:47 +08:00
if not os.path.exists(WORKING_DIR):
os.mkdir(WORKING_DIR)
2025-03-03 18:40:03 +08:00
2025-03-03 18:33:42 +08:00
async def initialize_rag():
# Initialize LightRAG
rag = LightRAG(
working_dir=WORKING_DIR,
llm_model_func=ollama_model_complete,
llm_model_name="qwen2.5:3b-instruct-max-context",
embedding_func=EmbeddingFunc(
embedding_dim=768,
max_token_size=8192,
func=lambda texts: ollama_embed(texts, embed_model="nomic-embed-text"),
),
)
await rag.initialize_storages()
await initialize_pipeline_status()
return rag
2024-10-20 11:27:47 +08:00
2025-03-03 18:40:03 +08:00
2024-10-20 18:08:49 +08:00
# Read all .txt files from the TEXT_FILES_DIR directory
2024-10-20 11:27:47 +08:00
texts = []
for filename in os.listdir(TEXT_FILES_DIR):
2024-10-25 13:32:25 +05:30
if filename.endswith(".txt"):
2024-10-20 11:27:47 +08:00
file_path = os.path.join(TEXT_FILES_DIR, filename)
2024-10-25 13:32:25 +05:30
with open(file_path, "r", encoding="utf-8") as file:
2024-10-20 11:27:47 +08:00
texts.append(file.read())
2024-10-25 13:32:25 +05:30
2024-10-20 18:08:49 +08:00
# Batch insert texts into LightRAG with a retry mechanism
2024-10-20 11:27:47 +08:00
def insert_texts_with_retry(rag, texts, retries=3, delay=5):
for _ in range(retries):
try:
rag.insert(texts)
return
except Exception as e:
2024-10-25 13:32:25 +05:30
print(
f"Error occurred during insertion: {e}. Retrying in {delay} seconds..."
)
2024-10-20 11:27:47 +08:00
time.sleep(delay)
raise RuntimeError("Failed to insert texts after multiple retries.")
2024-10-25 13:32:25 +05:30
2025-03-03 18:33:42 +08:00
def main():
# Initialize RAG instance
rag = asyncio.run(initialize_rag())
insert_texts_with_retry(rag, texts)
2024-10-20 11:27:47 +08:00
2025-03-03 18:33:42 +08:00
# Perform different types of queries and handle potential errors
try:
print(
rag.query(
"What are the top themes in this story?", param=QueryParam(mode="naive")
)
2024-10-25 13:32:25 +05:30
)
2025-03-03 18:33:42 +08:00
except Exception as e:
print(f"Error performing naive search: {e}")
2024-10-20 11:27:47 +08:00
2025-03-03 18:33:42 +08:00
try:
print(
rag.query(
"What are the top themes in this story?", param=QueryParam(mode="local")
)
2024-10-25 13:32:25 +05:30
)
2025-03-03 18:33:42 +08:00
except Exception as e:
print(f"Error performing local search: {e}")
2024-10-20 11:27:47 +08:00
2025-03-03 18:33:42 +08:00
try:
print(
rag.query(
2025-03-03 18:40:03 +08:00
"What are the top themes in this story?",
param=QueryParam(mode="global"),
2025-03-03 18:33:42 +08:00
)
2024-10-25 13:32:25 +05:30
)
2025-03-03 18:33:42 +08:00
except Exception as e:
print(f"Error performing global search: {e}")
2024-10-20 11:27:47 +08:00
2025-03-03 18:33:42 +08:00
try:
print(
rag.query(
2025-03-03 18:40:03 +08:00
"What are the top themes in this story?",
param=QueryParam(mode="hybrid"),
2025-03-03 18:33:42 +08:00
)
2024-10-25 13:32:25 +05:30
)
2025-03-03 18:33:42 +08:00
except Exception as e:
print(f"Error performing hybrid search: {e}")
# Function to clear VRAM resources
def clear_vram():
os.system("sudo nvidia-smi --gpu-reset")
2024-10-25 13:32:25 +05:30
2025-03-03 18:33:42 +08:00
# Regularly clear VRAM to prevent overflow
clear_vram_interval = 3600 # Clear once every hour
start_time = time.time()
2024-10-25 13:32:25 +05:30
2025-03-03 18:33:42 +08:00
while True:
current_time = time.time()
if current_time - start_time > clear_vram_interval:
clear_vram()
start_time = current_time
time.sleep(60) # Check the time every minute
2024-10-20 11:27:47 +08:00
2025-03-03 18:40:03 +08:00
2025-03-03 18:33:42 +08:00
if __name__ == "__main__":
main()