lanny xu commited on
Commit
c33bb69
·
1 Parent(s): c844813

resolve conflict

Browse files
COLAB_CONTINUE_FROM_TIMEOUT.py DELETED
@@ -1,229 +0,0 @@
1
- """
2
- 在 Colab 中从超时处继续处理的完整脚本
3
- 直接复制到 Colab 代码单元格运行
4
- """
5
-
6
- print("🚀 GraphRAG 超时恢复脚本")
7
- print("="*60)
8
-
9
- # ==================== 步骤 0: 检查前置条件 ====================
10
- print("\n📋 步骤 0: 检查前置条件...")
11
-
12
- import sys
13
- import os
14
-
15
- # 挂载 Google Drive(如果还没有挂载)
16
- try:
17
- from google.colab import drive
18
- if not os.path.exists('/content/drive'):
19
- print(" 挂载 Google Drive...")
20
- drive.mount('/content/drive')
21
- else:
22
- print(" ✅ Google Drive 已挂载")
23
- except:
24
- print(" ⚠️ 不在 Colab 环境中")
25
-
26
- # 设置路径
27
- project_path = '/content/drive/MyDrive/adaptive_RAG'
28
- sys.path.insert(0, project_path)
29
-
30
- print(f" 项目路径: {project_path}")
31
-
32
- # ==================== 步骤 1: 重启 Ollama ====================
33
- print("\n🔄 步骤 1: 重启 Ollama 服务...")
34
-
35
- import subprocess
36
- import time
37
-
38
- # 杀掉旧进程
39
- !pkill -9 ollama 2>/dev/null
40
-
41
- time.sleep(2)
42
-
43
- # 启动新进程
44
- print(" 启动 Ollama 服务...")
45
- ollama_process = subprocess.Popen(
46
- ["ollama", "serve"],
47
- stdout=subprocess.PIPE,
48
- stderr=subprocess.PIPE,
49
- preexec_fn=os.setpgrp
50
- )
51
-
52
- time.sleep(5)
53
-
54
- # 验证服务
55
- import requests
56
- try:
57
- response = requests.get('http://localhost:11434/api/tags', timeout=5)
58
- if response.status_code == 200:
59
- print(" ✅ Ollama 服务运行正常")
60
- else:
61
- print(f" ⚠️ Ollama 响应异常: {response.status_code}")
62
- except Exception as e:
63
- print(f" ❌ Ollama 服务未响应: {e}")
64
- print(" 请检查 Ollama 是否正确安装")
65
-
66
- # ==================== 步骤 2: 加载配置和文档 ====================
67
- print("\n📚 步骤 2: 加载配置和文档...")
68
-
69
- # 导入配置
70
- from config import setup_environment
71
-
72
- try:
73
- setup_environment()
74
- print(" ✅ 环境配置加载成功")
75
- except Exception as e:
76
- print(f" ⚠️ 环境配置警告: {e}")
77
-
78
- # 检查是否已经有 doc_splits 变量
79
- if 'doc_splits' in dir():
80
- print(f" ✅ 检测到已有 doc_splits: {len(doc_splits)} 个文档")
81
- use_existing_docs = True
82
- else:
83
- print(" ⚠️ 未检测到 doc_splits,需要重新加载文档")
84
- use_existing_docs = False
85
-
86
- # 如果没有 doc_splits,重新加载
87
- if not use_existing_docs:
88
- print("\n 正在加载文档...")
89
- from document_processor import DocumentProcessor
90
-
91
- doc_processor = DocumentProcessor()
92
-
93
- # 使用默认 URL 或自定义 URL
94
- urls = [
95
- "https://lilianweng.github.io/posts/2023-06-23-agent/",
96
- "https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/",
97
- "https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/"
98
- ]
99
-
100
- vectorstore, retriever, doc_splits = doc_processor.setup_knowledge_base(
101
- urls=urls,
102
- enable_graphrag=True
103
- )
104
-
105
- print(f" ✅ 文档加载完成: {len(doc_splits)} 个文档片段")
106
-
107
- # ==================== 步骤 3: 修复超时配置 ====================
108
- print("\n⚙️ 步骤 3: 修复超时配置...")
109
-
110
- # 方案:直接修改 entity_extractor.py 文件内容
111
- entity_extractor_path = os.path.join(project_path, 'entity_extractor.py')
112
-
113
- # 读取原文件
114
- with open(entity_extractor_path, 'r', encoding='utf-8') as f:
115
- content = f.read()
116
-
117
- # 检查是否已经修改过
118
- if 'timeout: int = 180' in content:
119
- print(" ✅ entity_extractor.py 已经包含超时修复")
120
- else:
121
- print(" 📝 修改 entity_extractor.py...")
122
-
123
- # 替换初始化方法的签名
124
- content = content.replace(
125
- 'def __init__(self, timeout: int = 60, max_retries: int = 3):',
126
- 'def __init__(self, timeout: int = 180, max_retries: int = 5):'
127
- )
128
-
129
- # 保存修改
130
- with open(entity_extractor_path, 'w', encoding='utf-8') as f:
131
- f.write(content)
132
-
133
- print(" ✅ 已将默认超时时间改为 180 秒,重试次数改为 5 次")
134
-
135
- # 重新加载模块
136
- import importlib
137
-
138
- if 'entity_extractor' in sys.modules:
139
- importlib.reload(sys.modules['entity_extractor'])
140
- print(" 🔄 entity_extractor 模块已重新加载")
141
-
142
- if 'graph_indexer' in sys.modules:
143
- importlib.reload(sys.modules['graph_indexer'])
144
- print(" 🔄 graph_indexer 模块已重新加载")
145
-
146
- # ==================== 步骤 4: 确定继续处理的起点 ====================
147
- print("\n📊 步骤 4: 确定处理起点...")
148
-
149
- # 让用户选择从哪里开始
150
- print("\n请选择继续处理的方式:")
151
- print(" 1. 从文档 #56 重新开始(包含 #56)")
152
- print(" 2. 跳过文档 #56,从 #57 开始")
153
- print(" 3. 从头开始处理所有文档")
154
- print(" 4. 自定义起始位置")
155
-
156
- # 默认选项(可以修改)
157
- choice = 1 # 👈 修改这里来选择不同的选项
158
-
159
- if choice == 1:
160
- start_index = 55 # 文档 #56 的索引
161
- print(f"\n ✅ 选择: 从文档 #56 开始(索引 {start_index})")
162
- elif choice == 2:
163
- start_index = 56 # 跳过 #56
164
- print(f"\n ✅ 选择: 跳过文档 #56,从 #57 开始(索引 {start_index})")
165
- elif choice == 3:
166
- start_index = 0
167
- print(f"\n ✅ 选择: 从头开始处理所有文档")
168
- else:
169
- # 自定义
170
- start_index = 55 # 👈 修改这里来自定义起始位置
171
- print(f"\n ✅ 选择: 自定义起始位置(索引 {start_index})")
172
-
173
- remaining_docs = doc_splits[start_index:]
174
- print(f" 待处理文档数: {len(remaining_docs)} 个")
175
-
176
- # ==================== 步骤 5: 开始处理 ====================
177
- print("\n🚀 步骤 5: 开始处理文档...")
178
- print("="*60)
179
-
180
- from graph_indexer import GraphRAGIndexer
181
-
182
- # 创建索引器
183
- indexer = GraphRAGIndexer()
184
-
185
- # 开始索引
186
- try:
187
- graph = indexer.index_documents(
188
- documents=remaining_docs,
189
- batch_size=3, # 👈 可以调整批次大小(1-5 推荐)
190
- save_path=os.path.join(project_path, "knowledge_graph_recovered.pkl")
191
- )
192
-
193
- print("\n" + "="*60)
194
- print("✅ 处理完成!")
195
- print("="*60)
196
-
197
- # 显示统计信息
198
- stats = graph.get_statistics()
199
- print(f"\n📊 知识图谱统计:")
200
- print(f" • 节点数: {stats['num_nodes']}")
201
- print(f" • 边数: {stats['num_edges']}")
202
- print(f" • 社区数: {stats['num_communities']}")
203
- print(f" • 图密度: {stats['density']:.4f}")
204
-
205
- except KeyboardInterrupt:
206
- print("\n⚠️ 处理被用户中断")
207
- print(" 可以记录当前进度,稍后继续")
208
-
209
- except Exception as e:
210
- print(f"\n❌ 处理过程中出现错误:")
211
- print(f" {type(e).__name__}: {e}")
212
- print("\n建议:")
213
- print(" 1. 检查上面的错误信息")
214
- print(" 2. 如果是某个文档超时,尝试跳过它")
215
- print(" 3. 如果是 Ollama 问题,重启服务")
216
-
217
- import traceback
218
- print("\n完整错误堆栈:")
219
- traceback.print_exc()
220
-
221
- # ==================== 完成 ====================
222
- print("\n" + "="*60)
223
- print("脚本执行完成")
224
- print("="*60)
225
- print("\n💡 提示:")
226
- print(" • 如果遇到超时,检查上面的错误信息")
227
- print(" • 可以修改 choice 变量来跳过问题文档")
228
- print(" • 可以修改 batch_size 来调整处理速度")
229
- print(" • 图谱已保存到: knowledge_graph_recovered.pkl")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
COLAB_FILES_SUMMARY.md DELETED
@@ -1,305 +0,0 @@
1
- # 📦 Google Colab GPU测试文件总结
2
-
3
- ## ✅ 已创建的文件
4
-
5
- | 文件名 | 类型 | 用途 | 推荐度 |
6
- |--------|------|------|--------|
7
- | **colab_gpu_demo.ipynb** | Jupyter Notebook | 完整的交互式GPU测试 | ⭐⭐⭐⭐⭐ |
8
- | **colab_quick_test.py** | Python脚本 | 一键快速GPU测试 | ⭐⭐⭐⭐⭐ |
9
- | **colab_gpu_test.py** | Python脚本 | 模块化GPU测试工具 | ⭐⭐⭐⭐ |
10
- | **COLAB_GPU_GUIDE.md** | 文档 | 详细使用指南 | ⭐⭐⭐⭐⭐ |
11
-
12
- ---
13
-
14
- ## 🚀 快速开始(3种方式)
15
-
16
- ### 方式1: Notebook交互式测试 ⭐推荐
17
-
18
- **适合**: 第一次使用,想要详细了解每个步骤
19
-
20
- ```bash
21
- # 步骤1: 上传文件
22
- 上传 colab_gpu_demo.ipynb 到 Google Colab
23
-
24
- # 步骤2: 启用GPU
25
- 运行时 → 更改运行时类型 → GPU
26
-
27
- # 步骤3: 运行
28
- 运行时 → 全部运行
29
- ```
30
-
31
- **优势**:
32
- - ✅ 可视化输出
33
- - ✅ 分步执行,易于理解
34
- - ✅ 支持实时修改
35
- - ✅ Markdown说明清晰
36
-
37
- ---
38
-
39
- ### 方式2: 快速一键测试 ⭐最快
40
-
41
- **适合**: 快速验证GPU性能
42
-
43
- ```python
44
- # 在Colab新建笔记本,运行以下代码:
45
-
46
- # 1. 启用GPU (运行时 → GPU)
47
-
48
- # 2. 复制并运行
49
- !wget https://your-repo/colab_quick_test.py
50
- !python colab_quick_test.py
51
-
52
- # 或直接复制代码到单元格运行
53
- ```
54
-
55
- **优势**:
56
- - ✅ 零配置
57
- - ✅ 自动安装依赖
58
- - ✅ 5分钟完成全部测试
59
- - ✅ 一次性输出完整报告
60
-
61
- ---
62
-
63
- ### 方式3: 模块化测试工具
64
-
65
- **适合**: 开发者深度定制
66
-
67
- ```python
68
- # 在Colab中
69
- !wget https://your-repo/colab_gpu_test.py
70
- !python colab_gpu_test.py
71
- ```
72
-
73
- **优势**:
74
- - ✅ 代码结构清晰
75
- - ✅ 易于扩展
76
- - ✅ 可集成到其他项目
77
-
78
- ---
79
-
80
- ## 📊 测试内容对比
81
-
82
- | 测试项目 | Notebook | Quick Test | GPU Test |
83
- |---------|----------|------------|----------|
84
- | GPU环境检测 | ✅ | ✅ | ✅ |
85
- | 矩阵运算测试 | ✅ | ✅ | ✅ |
86
- | 文本嵌入测试 | ✅ | ✅ | ✅ |
87
- | GraphRAG组件 | ✅ | ❌ | ❌ |
88
- | 显存监控 | ✅ | ✅ | ✅ |
89
- | 性能报告 | ✅ | ✅ | ✅ |
90
- | 交互式说明 | ✅ | ❌ | ❌ |
91
- | nvidia-smi | ✅ | ✅ | ✅ |
92
-
93
- ---
94
-
95
- ## 🎯 使用场景推荐
96
-
97
- ### 场景1: 首次测试GPU
98
- **推荐**: `colab_gpu_demo.ipynb`
99
- - 详细的说明文档
100
- - 分步执行,便于学习
101
- - 可视化效果好
102
-
103
- ### 场景2: 快速验证性能
104
- **推荐**: `colab_quick_test.py`
105
- - 一键运行
106
- - 5分钟得到结果
107
- - 完整性能报告
108
-
109
- ### 场景3: 集成到CI/CD
110
- **推荐**: `colab_gpu_test.py`
111
- - 模块化设计
112
- - 易于自动化
113
- - 返回标准化结果
114
-
115
- ### 场景4: 学习GPU优化
116
- **推荐**: `COLAB_GPU_GUIDE.md` + `colab_gpu_demo.ipynb`
117
- - 理论+实践
118
- - 详细的性能分析
119
- - 优化建议
120
-
121
- ---
122
-
123
- ## 📈 预期性能提升
124
-
125
- ### Google Colab T4 GPU (免费版)
126
-
127
- | 任务 | CPU | GPU | 加速比 |
128
- |------|-----|-----|--------|
129
- | 矩阵运算 (5000x5000) | 8秒 | 0.3秒 | **25x** |
130
- | 文本嵌入 (1000条) | 35秒 | 6秒 | **6x** |
131
- | GraphRAG索引 (100文档) | 15分钟 | 4分钟 | **3.8x** |
132
-
133
- ### Google Colab A100 GPU (Pro版)
134
-
135
- | 任务 | CPU | GPU | 加速比 |
136
- |------|-----|-----|--------|
137
- | 矩阵运算 | 8秒 | 0.2秒 | **40x** |
138
- | 文本嵌入 | 35秒 | 3秒 | **12x** |
139
- | GraphRAG索引 | 15分钟 | 2.5分钟 | **6x** |
140
-
141
- ---
142
-
143
- ## 🔧 完整GraphRAG部署流程
144
-
145
- ### 步骤1: GPU性能测试
146
- ```python
147
- # 运行quick test验证GPU
148
- !python colab_quick_test.py
149
- ```
150
-
151
- ### 步骤2: 上传项目文件
152
- ```python
153
- # 方式A: 从Google Drive
154
- from google.colab import drive
155
- drive.mount('/content/drive')
156
- !cp -r /content/drive/MyDrive/adaptive_RAG /content/
157
- %cd /content/adaptive_RAG
158
-
159
- # 方式B: 从GitHub
160
- !git clone YOUR_REPO_URL
161
- %cd adaptive_RAG
162
- ```
163
-
164
- ### 步骤3: 安装依赖
165
- ```python
166
- !pip install -q -r requirements.txt
167
- !pip install -q -r requirements_graphrag.txt
168
- ```
169
-
170
- ### 步骤4: 配置API密钥
171
- ```python
172
- import os
173
- from getpass import getpass
174
- os.environ['TAVILY_API_KEY'] = getpass('TAVILY_API_KEY: ')
175
- ```
176
-
177
- ### 步骤5: 运行GraphRAG
178
- ```python
179
- !python main_graphrag.py
180
- ```
181
-
182
- ### 步骤6: 下载结果
183
- ```python
184
- from google.colab import files
185
- files.download('data/knowledge_graph.json')
186
- ```
187
-
188
- ---
189
-
190
- ## 💡 优化技巧
191
-
192
- ### 1. 批处理大小
193
- ```python
194
- # config.py
195
- GRAPHRAG_BATCH_SIZE = 20 # GPU环境可增大
196
- ```
197
-
198
- ### 2. 嵌入模型选择
199
- ```python
200
- # GPU环境使用更大模型
201
- EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
202
- ```
203
-
204
- ### 3. 混合精度训练
205
- ```python
206
- import torch
207
- torch.set_float32_matmul_precision('medium')
208
- ```
209
-
210
- ### 4. 数据持久化
211
- ```python
212
- # 定期保存到Drive
213
- import shutil
214
- shutil.copy(
215
- 'data/knowledge_graph.json',
216
- '/content/drive/MyDrive/backup.json'
217
- )
218
- ```
219
-
220
- ---
221
-
222
- ## ⚠️ 注意事项
223
-
224
- ### Colab免费版限制
225
- - ⏰ 连续使用: 最多12小时
226
- - 🔄 GPU配额: 每周有限
227
- - ⏸️ 闲置超时: 90分钟
228
-
229
- ### 建议
230
- - 💾 定期保存进度
231
- - ⬇️ 及时下载结果
232
- - 🔄 使用后台任务保持活跃
233
-
234
- ---
235
-
236
- ## 📚 文件使用优先级
237
-
238
- ### 新手用户
239
- 1. 📖 先阅读 `COLAB_GPU_GUIDE.md`
240
- 2. 🚀 运行 `colab_gpu_demo.ipynb`
241
- 3. ✅ 验证性能后部署完整项目
242
-
243
- ### 高级用户
244
- 1. ⚡ 直接运行 `colab_quick_test.py`
245
- 2. 📊 查看性能报告
246
- 3. 🔧 根据需求调整配置
247
-
248
- ### 开发者
249
- 1. 🔍 研究 `colab_gpu_test.py` 源码
250
- 2. 🛠️ 根据需求定制功能
251
- 3. 🔄 集成到自动化流程
252
-
253
- ---
254
-
255
- ## 🎯 关键性能指标
256
-
257
- ### 必须达到的基准
258
- - ✅ GPU检测: CUDA可用
259
- - ✅ 矩阵加速: >10x
260
- - ✅ 嵌入加速: >5x
261
- - ✅ 显存使用: <80%
262
-
263
- ### 如果低于基准
264
- 1. 检查GPU类型 (应该是T4或A100)
265
- 2. 重启运行时
266
- 3. 检查依赖版本
267
-
268
- ---
269
-
270
- ## 📞 获取帮助
271
-
272
- ### 常见问题
273
- - 查看 `COLAB_GPU_GUIDE.md` 的FAQ部分
274
-
275
- ### 性能问题
276
- - 运行 `colab_quick_test.py` 获取诊断报告
277
-
278
- ### 技术支持
279
- - 提供测试报告输出
280
- - 说明具体错误信息
281
-
282
- ---
283
-
284
- ## ✅ 总结
285
-
286
- | 文件 | 何时使用 |
287
- |------|---------|
288
- | `colab_gpu_demo.ipynb` | 首次使用、学习、演示 |
289
- | `colab_quick_test.py` | 快速验证、CI/CD、批量测试 |
290
- | `colab_gpu_test.py` | 深度定制、集成开发 |
291
- | `COLAB_GPU_GUIDE.md` | 参考文档、问题排查 |
292
-
293
- **推荐流程**:
294
- 1. 阅读 `COLAB_GPU_GUIDE.md` (5分钟)
295
- 2. 运行 `colab_quick_test.py` (5分钟)
296
- 3. 如果性能符合预期,部署完整GraphRAG项目
297
-
298
- **预期结果**:
299
- - GPU可用 ✅
300
- - 3-6倍整体加速 ✅
301
- - 节省10+分钟时间 ✅
302
-
303
- ---
304
-
305
- 🚀 **立即开始**: 上传任一文件到 [Google Colab](https://colab.research.google.com/) 并启用GPU!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
COLAB_GPU_GUIDE.md DELETED
@@ -1,271 +0,0 @@
1
- # 🚀 Google Colab GPU 测试指南
2
-
3
- ## 📋 概述
4
-
5
- 我为您创建了两个文件用于在Google Colab上测试GPU性能:
6
-
7
- 1. **`colab_gpu_demo.ipynb`** - Jupyter Notebook版本(推荐)
8
- 2. **`colab_gpu_test.py`** - Python脚本版本
9
-
10
- ## 🎯 使用方法
11
-
12
- ### 方法1: 使用Notebook(推荐)
13
-
14
- #### 步骤1: 上传到Colab
15
-
16
- 1. 打开 [Google Colab](https://colab.research.google.com/)
17
- 2. 点击 `文件` → `上传笔记本`
18
- 3. 选择 `colab_gpu_demo.ipynb`
19
-
20
- #### 步骤2: 启用GPU
21
-
22
- 1. 点击顶部菜单 `运行时` → `更改运行时类型`
23
- 2. 硬件加速器选择 `GPU`
24
- 3. GPU类型选择 `T4`(免费版)或 `A100`(Colab Pro)
25
- 4. 点击 `保存`
26
-
27
- #### 步骤3: 运行测试
28
-
29
- 1. 点击 `运行时` → `全部运行`
30
- 2. 或者逐个单元格运行(Shift + Enter)
31
-
32
- ### 方法2: 使用Python脚本
33
-
34
- #### 步骤1: 上传文件
35
-
36
- 1. 在Colab中创建新笔记本
37
- 2. 点击左侧文件夹图标
38
- 3. 上传 `colab_gpu_test.py`
39
-
40
- #### 步骤2: 运行脚本
41
-
42
- ```python
43
- # 在Colab单元格中运行
44
- !python colab_gpu_test.py
45
- ```
46
-
47
- ## 📊 测试内容
48
-
49
- ### 1. GPU环境检测 ✅
50
- - CUDA可用性检查
51
- - GPU型号和显存信息
52
- - nvidia-smi输出
53
-
54
- ### 2. 矩阵运算性能测试 ⚡
55
- - CPU vs GPU 5000x5000矩阵乘法
56
- - 预期加速比: **10-50x**
57
-
58
- ### 3. 文本嵌入性能测试 📝
59
- - 使用sentence-transformers
60
- - 1000个文本的嵌入生成
61
- - CPU vs GPU对比
62
- - 预期加速比: **5-10x**
63
-
64
- ### 4. GraphRAG组件测试 🔍
65
- - 简化版知识图谱构建
66
- - 实体和关系管理
67
- - GPU加速的向量检索
68
-
69
- ### 5. 显存监控 💾
70
- - 实时显存使用情况
71
- - 内存分配统计
72
-
73
- ## 📈 预期结果
74
-
75
- ### Google Colab 免费版 (T4 GPU)
76
-
77
- | 测试项目 | CPU时间 | GPU时间 | 加速比 |
78
- |---------|---------|---------|--------|
79
- | 矩阵运算 (5000x5000) | ~8-10秒 | ~0.3-0.5秒 | 20-30x |
80
- | 文本嵌入 (1000文本) | ~30-40秒 | ~5-8秒 | 5-7x |
81
- | GraphRAG索引 (100文档) | ~15分钟 | ~3-5分钟 | 3-5x |
82
-
83
- ### Google Colab Pro (A100 GPU)
84
-
85
- | 测试项目 | CPU时间 | GPU时间 | 加速比 |
86
- |---------|---------|---------|--------|
87
- | 矩阵运算 | ~8秒 | ~0.2秒 | 40x |
88
- | 文本嵌入 | ~35秒 | ~3秒 | 10-12x |
89
- | GraphRAG索引 | ~15分钟 | ~2-3分钟 | 5-7x |
90
-
91
- ## 🔧 运行完整GraphRAG项目
92
-
93
- 如果GPU测试成功,可以在Colab上运行完整的GraphRAG项目:
94
-
95
- ### 步骤1: 上传项目文件
96
-
97
- 在Colab中创建新的单元格:
98
-
99
- ```python
100
- # 方式1: 从Google Drive加载
101
- from google.colab import drive
102
- drive.mount('/content/drive')
103
-
104
- # 复制项目文件
105
- !cp -r /content/drive/MyDrive/adaptive_RAG /content/
106
- %cd /content/adaptive_RAG
107
- ```
108
-
109
- 或者:
110
-
111
- ```python
112
- # 方式2: 从GitHub克隆
113
- !git clone YOUR_GITHUB_REPO_URL
114
- %cd adaptive_RAG
115
- ```
116
-
117
- ### 步骤2: 安装依赖
118
-
119
- ```python
120
- # 安装基础依赖
121
- !pip install -q -r requirements.txt
122
-
123
- # 安装GraphRAG依赖
124
- !pip install -q -r requirements_graphrag.txt
125
- ```
126
-
127
- ### 步骤3: 配置API密钥
128
-
129
- ```python
130
- import os
131
- from getpass import getpass
132
-
133
- # 安全输入API密钥
134
- os.environ['TAVILY_API_KEY'] = getpass('输入 TAVILY_API_KEY: ')
135
-
136
- # 验证
137
- print("✅ API密钥已设置")
138
- ```
139
-
140
- ### 步骤4: 运行GraphRAG
141
-
142
- ```python
143
- # 运行主程序
144
- !python main_graphrag.py
145
- ```
146
-
147
- ### 步骤5: 下载结果
148
-
149
- ```python
150
- # 下载构建好的知识图谱
151
- from google.colab import files
152
-
153
- # 下载图谱文件
154
- files.download('data/knowledge_graph.json')
155
-
156
- print("✅ 图谱已下载到本地")
157
- ```
158
-
159
- ## 💡 优化建议
160
-
161
- ### 1. 批处理大小优化
162
-
163
- 在 `config.py` 中调整:
164
-
165
- ```python
166
- # GPU优化配置
167
- GRAPHRAG_BATCH_SIZE = 20 # GPU可以处理更大批次
168
- ```
169
-
170
- ### 2. 使用GPU优化的模型
171
-
172
- ```python
173
- # 使用更大的嵌入模型(GPU环境)
174
- EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
175
- ```
176
-
177
- ### 3. 启用混合精度
178
-
179
- ```python
180
- # 在entity_extractor.py中
181
- import torch
182
- torch.set_float32_matmul_precision('medium') # 提升性能
183
- ```
184
-
185
- ## ⚠️ 注意事项
186
-
187
- ### Colab资源限制
188
-
189
- 1. **免费版限制**:
190
- - 连续使用时间: 最多12小时
191
- - GPU使用配额: 每周有限
192
- - 闲置超时: 90分钟自动断开
193
-
194
- 2. **建议**:
195
- - 定期保存进度到Google Drive
196
- - 使用`files.download()`下载重要结果
197
- - 避免长时间空闲
198
-
199
- ### 数据持久化
200
-
201
- ```python
202
- # 定期保存到Google Drive
203
- from google.colab import drive
204
- drive.mount('/content/drive')
205
-
206
- # 保存图谱
207
- import shutil
208
- shutil.copy(
209
- 'data/knowledge_graph.json',
210
- '/content/drive/MyDrive/graphrag_backup.json'
211
- )
212
- ```
213
-
214
- ## 🐛 常见问题
215
-
216
- ### Q1: GPU连接失败
217
-
218
- **A**: 检查运行时类型
219
- ```python
220
- import torch
221
- print(f"CUDA可用: {torch.cuda.is_available()}")
222
- # 如果False,重新设置运行时类型
223
- ```
224
-
225
- ### Q2: 内存不足
226
-
227
- **A**: 减小批处理大小
228
- ```python
229
- GRAPHRAG_BATCH_SIZE = 5 # 降低批次
230
- ```
231
-
232
- ### Q3: 会话超时
233
-
234
- **A**: 使用Colab Pro或定期运行代码保持活跃
235
- ```python
236
- # 在后台定期执行
237
- import time
238
- while True:
239
- print("Keep alive...")
240
- time.sleep(300) # 每5分钟执行一次
241
- ```
242
-
243
- ## 📚 参考资源
244
-
245
- - [Google Colab官方文档](https://colab.research.google.com/notebooks/intro.ipynb)
246
- - [GPU加速指南](https://colab.research.google.com/notebooks/gpu.ipynb)
247
- - [Colab Pro定价](https://colab.research.google.com/signup)
248
-
249
- ## 🎓 下一步学习
250
-
251
- 1. **理解GPU加速原理**: 查看测试代码中的性能对比
252
- 2. **优化GraphRAG参数**: 根据GPU性能调整配置
253
- 3. **扩展到生产环境**: 考虑使用AWS/GCP的GPU实例
254
-
255
- ---
256
-
257
- ## ✅ 总结
258
-
259
- | 优势 | 说明 |
260
- |------|------|
261
- | 🆓 免费GPU | T4 GPU免费使用 |
262
- | ⚡ 高性能 | 3-10倍加速 |
263
- | 🔄 零配置 | 无需本地安装 |
264
- | 💾 自动保存 | 集成Google Drive |
265
- | 🌐 随时访问 | 仅需浏览器 |
266
-
267
- **推荐**: 在本地CPU环境速度慢时,使用Colab GPU可以大幅提升GraphRAG索引构建速度!
268
-
269
- ---
270
-
271
- **立即开始**: 上传 `colab_gpu_demo.ipynb` 到 [Google Colab](https://colab.research.google.com/) 并启用GPU! 🚀
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
COLAB_OLLAMA_GUIDE.md DELETED
@@ -1,421 +0,0 @@
1
- # GraphRAG Colab 完整运行指南
2
-
3
- ## 🎯 在Colab中运行Ollama的3种方法
4
-
5
- ### 方法1: 后台运行Ollama(推荐)⭐⭐⭐⭐⭐
6
-
7
- 在Colab中,您可以在单个单元格中后台启动Ollama,然后在另一个单元格运行GraphRAG。
8
-
9
- #### 步骤1: 安装Ollama
10
-
11
- ```bash
12
- # 单元格1: 安装Ollama
13
- !curl -fsSL https://ollama.com/install.sh | sh
14
- ```
15
-
16
- #### 步骤2: 后台启动Ollama服务
17
-
18
- ```python
19
- # 单元格2: 后台启动Ollama
20
- import subprocess
21
- import time
22
- import os
23
-
24
- # 启动Ollama服务(后台)
25
- ollama_process = subprocess.Popen(
26
- ["ollama", "serve"],
27
- stdout=subprocess.PIPE,
28
- stderr=subprocess.PIPE,
29
- preexec_fn=os.setpgrp
30
- )
31
-
32
- print("⏳ 等待Ollama服务启动...")
33
- time.sleep(5)
34
-
35
- # 验证服务是否启动
36
- !curl -s http://localhost:11434/api/tags | head -5
37
-
38
- print(f"✅ Ollama服务已启动 (PID: {ollama_process.pid})")
39
- ```
40
-
41
- #### 步骤3: 下载Mistral模型
42
-
43
- ```bash
44
- # 单元格3: 下载模型
45
- !ollama pull mistral
46
- ```
47
-
48
- #### 步骤4: 安装Python依赖
49
-
50
- ```bash
51
- # 单元格4: 安装依赖
52
- !pip install -q langchain langchain-community langchain-core langgraph
53
- !pip install -q chromadb sentence-transformers tiktoken
54
- !pip install -q tavily-python python-dotenv networkx python-louvain
55
- ```
56
-
57
- #### 步骤5: 配置API密钥
58
-
59
- ```python
60
- # 单元格5: 配置环境
61
- import os
62
- from getpass import getpass
63
-
64
- os.environ['TAVILY_API_KEY'] = getpass('输入TAVILY_API_KEY: ')
65
- print("✅ API密钥已设置")
66
- ```
67
-
68
- #### 步骤6: 运行GraphRAG
69
-
70
- ```python
71
- # 单元格6: 运行GraphRAG
72
- !python main_graphrag.py
73
- ```
74
-
75
- #### 步骤7: 下载结果(可选)
76
-
77
- ```python
78
- # 单元格7: 下载生成的图谱
79
- from google.colab import files
80
- files.download('data/knowledge_graph.json')
81
- ```
82
-
83
- ---
84
-
85
- ### 方法2: 使用tmux(高级)⭐⭐⭐⭐
86
-
87
- ```bash
88
- # 单元格1: 安装tmux
89
- !apt-get install -y tmux
90
-
91
- # 单元格2: 在tmux会话中启动Ollama
92
- !tmux new-session -d -s ollama 'ollama serve'
93
-
94
- # 单元格3: 检查会话
95
- !tmux ls
96
-
97
- # 单元格4: 下载模型
98
- !ollama pull mistral
99
-
100
- # 单元格5: 运行GraphRAG
101
- !python main_graphrag.py
102
-
103
- # 单元格6: 停止tmux会话(清理)
104
- !tmux kill-session -t ollama
105
- ```
106
-
107
- ---
108
-
109
- ### 方法3: 使用nohup(简单)⭐⭐⭐
110
-
111
- ```bash
112
- # 单元格1: 后台启动Ollama
113
- !nohup ollama serve > /tmp/ollama.log 2>&1 &
114
-
115
- # 单元格2: 等待启动
116
- import time
117
- time.sleep(5)
118
-
119
- # 单元格3: 检查日志
120
- !tail -20 /tmp/ollama.log
121
-
122
- # 单元格4: 下载模型
123
- !ollama pull mistral
124
-
125
- # 单元格5: 运行GraphRAG
126
- !python main_graphrag.py
127
-
128
- # 单元格6: 停止Ollama(清理)
129
- !pkill -f 'ollama serve'
130
- ```
131
-
132
- ---
133
-
134
- ## 🚀 一键运行脚本(最简单)⭐⭐⭐⭐⭐
135
-
136
- 我已经为您创建了一个自动化脚本 `colab_setup_and_run.py`,它会:
137
- 1. ✅ 自动安装Ollama
138
- 2. ✅ 后台启动服务
139
- 3. ✅ 下载Mistral模型
140
- 4. ✅ 安装Python依赖
141
- 5. ✅ 配置环境变量
142
- 6. ✅ 运行GraphRAG
143
-
144
- ### 使用方法:
145
-
146
- ```bash
147
- # 方法A: 直接运行脚本
148
- !python colab_setup_and_run.py
149
-
150
- # 方法B: 或者在Python中
151
- import subprocess
152
- subprocess.run(["python", "colab_setup_and_run.py"])
153
- ```
154
-
155
- ---
156
-
157
- ## 📊 完整的Colab Notebook示例
158
-
159
- 创建一个新的Colab笔记本,按顺序运行以下单元格:
160
-
161
- ### 单元格1: 环境准备
162
-
163
- ```python
164
- # 检测GPU
165
- import torch
166
- print(f"GPU可用: {torch.cuda.is_available()}")
167
- if torch.cuda.is_available():
168
- print(f"GPU型号: {torch.cuda.get_device_name(0)}")
169
- ```
170
-
171
- ### 单元格2: 安装Ollama
172
-
173
- ```bash
174
- %%bash
175
- curl -fsSL https://ollama.com/install.sh | sh
176
- echo "✅ Ollama安装完成"
177
- ```
178
-
179
- ### 单元格3: 后台启动Ollama
180
-
181
- ```python
182
- import subprocess
183
- import time
184
- import os
185
-
186
- print("🔄 启动Ollama服务...")
187
-
188
- # 后台启动
189
- process = subprocess.Popen(
190
- ["ollama", "serve"],
191
- stdout=subprocess.PIPE,
192
- stderr=subprocess.PIPE,
193
- preexec_fn=os.setpgrp
194
- )
195
-
196
- # 等待启动
197
- time.sleep(5)
198
-
199
- # 验证
200
- import requests
201
- try:
202
- response = requests.get("http://localhost:11434/api/tags", timeout=3)
203
- if response.status_code == 200:
204
- print(f"✅ Ollama服务运行正常 (PID: {process.pid})")
205
- else:
206
- print("⚠️ 服务响应异常")
207
- except:
208
- print("⚠️ 无法连接服务,但进程已启动")
209
-
210
- # 保存进程ID(重要!)
211
- ollama_pid = process.pid
212
- print(f"📝 保存的PID: {ollama_pid}")
213
- ```
214
-
215
- ### 单元格4: 下载模型
216
-
217
- ```bash
218
- %%bash
219
- echo "📥 下载Mistral模型..."
220
- ollama pull mistral
221
- echo "✅ 模型下载完成"
222
- ollama list
223
- ```
224
-
225
- ### 单元格5: 上传项目文件
226
-
227
- ```python
228
- # 方式A: 从Google Drive
229
- from google.colab import drive
230
- drive.mount('/content/drive')
231
-
232
- # 复制项目文件
233
- !cp -r /content/drive/MyDrive/adaptive_RAG /content/
234
- %cd /content/adaptive_RAG
235
-
236
- # 方式B: 手动上传
237
- # from google.colab import files
238
- # uploaded = files.upload()
239
- ```
240
-
241
- ### 单元格6: 安装依赖
242
-
243
- ```bash
244
- %%bash
245
- pip install -q -r requirements.txt
246
- pip install -q -r requirements_graphrag.txt
247
- echo "✅ 依赖安装完成"
248
- ```
249
-
250
- ### 单元格7: 配置环境
251
-
252
- ```python
253
- import os
254
- from getpass import getpass
255
-
256
- # 设置API密钥
257
- if not os.path.exists('.env'):
258
- api_key = getpass('输入TAVILY_API_KEY: ')
259
- with open('.env', 'w') as f:
260
- f.write(f'TAVILY_API_KEY={api_key}\n')
261
- print("✅ .env文件已创建")
262
- else:
263
- print("✅ 使用现有.env文件")
264
- ```
265
-
266
- ### 单元格8: 运行GraphRAG
267
-
268
- ```python
269
- # 方式A: 直接运行
270
- !python main_graphrag.py
271
-
272
- # 方式B: 在Python中运行(可以捕获输出)
273
- import subprocess
274
-
275
- result = subprocess.run(
276
- ["python", "main_graphrag.py"],
277
- capture_output=True,
278
- text=True
279
- )
280
-
281
- print(result.stdout)
282
- if result.returncode != 0:
283
- print("错误信息:")
284
- print(result.stderr)
285
- ```
286
-
287
- ### 单元格9: 下载结果
288
-
289
- ```python
290
- # 下载生成的知识图谱
291
- from google.colab import files
292
-
293
- if os.path.exists('data/knowledge_graph.json'):
294
- files.download('data/knowledge_graph.json')
295
- print("✅ 文件已下载")
296
- else:
297
- print("❌ 未找到图谱文件")
298
-
299
- # 保存到Google Drive
300
- import shutil
301
- shutil.copy(
302
- 'data/knowledge_graph.json',
303
- '/content/drive/MyDrive/graphrag_backup.json'
304
- )
305
- print("✅ 已备份到Google Drive")
306
- ```
307
-
308
- ### 单元格10: 清理(可选)
309
-
310
- ```python
311
- # 停止Ollama服务
312
- import os
313
- import signal
314
-
315
- try:
316
- os.kill(ollama_pid, signal.SIGTERM)
317
- print(f"✅ Ollama服务已停止 (PID: {ollama_pid})")
318
- except:
319
- print("⚠️ 停止服务失败,手动停止:")
320
- !pkill -f 'ollama serve'
321
- ```
322
-
323
- ---
324
-
325
- ## ⚠️ 常见问题
326
-
327
- ### Q1: Ollama服务启动后立即退出
328
-
329
- **A**: 使用 `subprocess.Popen` 而不是 `subprocess.run`:
330
-
331
- ```python
332
- # ❌ 错误方式
333
- !ollama serve & # 会立即退出
334
-
335
- # ✅ 正确方式
336
- import subprocess
337
- process = subprocess.Popen(["ollama", "serve"])
338
- ```
339
-
340
- ### Q2: 连接被拒绝 (Connection refused)
341
-
342
- **A**: 等待服务完全启动:
343
-
344
- ```python
345
- import time
346
- time.sleep(10) # 增加等待时间
347
- ```
348
-
349
- ### Q3: 进程管理困难
350
-
351
- **A**: 使用PID文件:
352
-
353
- ```python
354
- # 保存PID
355
- with open('/tmp/ollama.pid', 'w') as f:
356
- f.write(str(process.pid))
357
-
358
- # 后续停止
359
- with open('/tmp/ollama.pid', 'r') as f:
360
- pid = int(f.read())
361
- os.kill(pid, signal.SIGTERM)
362
- ```
363
-
364
- ### Q4: 会话超时导致服务停止
365
-
366
- **A**: 定期执行代码保持活跃:
367
-
368
- ```python
369
- import time
370
- while True:
371
- print("Keep alive...")
372
- time.sleep(300) # 每5分钟
373
- ```
374
-
375
- ---
376
-
377
- ## 📚 推荐的完整流程
378
-
379
- 1. ✅ **运行自动化脚本** - `!python colab_setup_and_run.py`
380
- 2. ✅ **或按照Notebook示例** - 逐步执行每个单元格
381
- 3. ✅ **定期保存结果** - 到Google Drive
382
-
383
- ---
384
-
385
- ## 💡 最佳实践
386
-
387
- 1. **始终保存Ollama的PID**: 方便后续管理
388
- 2. **使用try-finally**: 确保清理后台进程
389
- 3. **定期备份**: 保存中间结果到Drive
390
- 4. **监控显存**: 避免OOM错误
391
-
392
- ```python
393
- # 最佳实践示例
394
- import subprocess
395
- import atexit
396
- import signal
397
-
398
- # 启动Ollama
399
- ollama_process = subprocess.Popen(["ollama", "serve"])
400
-
401
- # 注册清理函数
402
- def cleanup():
403
- try:
404
- ollama_process.terminate()
405
- print("✅ Ollama已停止")
406
- except:
407
- pass
408
-
409
- atexit.register(cleanup)
410
-
411
- # 运行您的代码
412
- try:
413
- # ... 您的GraphRAG代码 ...
414
- pass
415
- finally:
416
- cleanup()
417
- ```
418
-
419
- ---
420
-
421
- **推荐**: 直接使用 `colab_setup_and_run.py` 脚本,它已经处理了所有这些细节!🚀
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
COLAB_QUICK_CONTINUE.py DELETED
@@ -1,121 +0,0 @@
1
- """
2
- Colab 快速继续脚本 - 从超时处恢复
3
- 复制到 Colab 运行,会自动检测并继续处理
4
- """
5
-
6
- print("🚀 GraphRAG 恢复脚本 v2.0")
7
- print("="*60)
8
-
9
- import sys
10
- import os
11
-
12
- # ==================== 1. 设置环境 ====================
13
- print("\n1️⃣ 设置环境...")
14
-
15
- # 设置项目路径
16
- project_path = '/content/drive/MyDrive/adaptive_RAG'
17
- if project_path not in sys.path:
18
- sys.path.insert(0, project_path)
19
- print(f" ✅ 项目路径: {project_path}")
20
-
21
- # ==================== 2. 重启 Ollama ====================
22
- print("\n2️⃣ 重启 Ollama...")
23
-
24
- import subprocess
25
- import time
26
-
27
- subprocess.run(['pkill', '-9', 'ollama'], stderr=subprocess.DEVNULL)
28
- time.sleep(2)
29
-
30
- ollama_process = subprocess.Popen(
31
- ["ollama", "serve"],
32
- stdout=subprocess.PIPE,
33
- stderr=subprocess.PIPE
34
- )
35
- time.sleep(5)
36
-
37
- import requests
38
- try:
39
- r = requests.get('http://localhost:11434/api/tags', timeout=5)
40
- print(f" ✅ Ollama 运行正常" if r.status_code == 200 else f" ⚠️ 状态码: {r.status_code}")
41
- except:
42
- print(" ❌ Ollama 未响应")
43
-
44
- # ==================== 3. 加载文档 ====================
45
- print("\n3️⃣ 加载文档...")
46
-
47
- from config import setup_environment
48
- from document_processor import DocumentProcessor
49
-
50
- setup_environment()
51
-
52
- # 创建文档处理器
53
- doc_processor = DocumentProcessor()
54
-
55
- # 加载文档(使用默认 URLs)
56
- vectorstore, retriever, doc_splits = doc_processor.setup_knowledge_base(
57
- enable_graphrag=True
58
- )
59
-
60
- print(f" ✅ 已加载 {len(doc_splits)} 个文档")
61
-
62
- # ==================== 4. 修改超时配置 ====================
63
- print("\n4️⃣ 增加超时时间...")
64
-
65
- entity_file = os.path.join(project_path, 'entity_extractor.py')
66
- with open(entity_file, 'r', encoding='utf-8') as f:
67
- content = f.read()
68
-
69
- # 修改默认参数
70
- if 'timeout: int = 60' in content:
71
- content = content.replace(
72
- 'timeout: int = 60, max_retries: int = 3',
73
- 'timeout: int = 180, max_retries: int = 5'
74
- )
75
- with open(entity_file, 'w', encoding='utf-8') as f:
76
- f.write(content)
77
- print(" ✅ 超时已改为 180 秒,重试改为 5 次")
78
- else:
79
- print(" ℹ️ 已经是修改后的配置")
80
-
81
- # 重新加载模块
82
- import importlib
83
- for mod in ['entity_extractor', 'graph_indexer']:
84
- if mod in sys.modules:
85
- importlib.reload(sys.modules[mod])
86
-
87
- # ==================== 5. 继续处理 ====================
88
- print("\n5️⃣ 继续处理文档...")
89
- print("="*60)
90
-
91
- from graph_indexer import GraphRAGIndexer
92
-
93
- # 配置起始位置
94
- START_INDEX = 55 # 👈 从文档 #56 开始,修改这里可以跳过某些文档
95
- BATCH_SIZE = 3 # 👈 批次大小,可以改为 1-5
96
-
97
- print(f"\n 起始位置: 文档 #{START_INDEX + 1}")
98
- print(f" 批次大小: {BATCH_SIZE}")
99
- print(f" 待处理: {len(doc_splits) - START_INDEX} 个文档\n")
100
-
101
- remaining_docs = doc_splits[START_INDEX:]
102
-
103
- indexer = GraphRAGIndexer()
104
-
105
- try:
106
- graph = indexer.index_documents(
107
- documents=remaining_docs,
108
- batch_size=BATCH_SIZE,
109
- save_path=f"{project_path}/knowledge_graph_recovered.pkl"
110
- )
111
-
112
- print("\n✅ 处理完成!")
113
- stats = graph.get_statistics()
114
- print(f"📊 节点: {stats['num_nodes']}, 边: {stats['num_edges']}, 社区: {stats['num_communities']}")
115
-
116
- except Exception as e:
117
- print(f"\n❌ 错误: {e}")
118
- print("\n建议:")
119
- print(" • 如果文档 #56 超时,修改 START_INDEX = 56 跳过它")
120
- print(" • 如果 Ollama 崩溃,重新运行此脚本")
121
- print(" • 减小 BATCH_SIZE 到 1 或 2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
colab_gpu_demo.ipynb DELETED
@@ -1,588 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "# 🚀 GraphRAG GPU检测与测试 - Google Colab版本\n",
8
- "\n",
9
- "本Notebook用于在Google Colab上检测GPU可用性并测试GraphRAG系统的性能。\n",
10
- "\n",
11
- "## 📋 使用步骤\n",
12
- "\n",
13
- "1. **启用GPU**: 运行时 → 更改运行时类型 → 硬件加速器 → GPU (T4)\n",
14
- "2. **运行所有单元格**: 依次执行下面的代码\n",
15
- "3. **查看结果**: 检查GPU加速效果\n",
16
- "\n",
17
- "---"
18
- ]
19
- },
20
- {
21
- "cell_type": "markdown",
22
- "metadata": {},
23
- "source": [
24
- "## 1️⃣ GPU环境检测"
25
- ]
26
- },
27
- {
28
- "cell_type": "code",
29
- "execution_count": null,
30
- "metadata": {},
31
- "outputs": [],
32
- "source": [
33
- "# 检测GPU可用性\n",
34
- "import torch\n",
35
- "import subprocess\n",
36
- "import sys\n",
37
- "\n",
38
- "print(\"=\"*60)\n",
39
- "print(\"🔍 GPU环境检测\")\n",
40
- "print(\"=\"*60)\n",
41
- "\n",
42
- "# PyTorch GPU检测\n",
43
- "cuda_available = torch.cuda.is_available()\n",
44
- "print(f\"\\n✅ CUDA可用: {cuda_available}\")\n",
45
- "\n",
46
- "if cuda_available:\n",
47
- " print(f\" GPU数量: {torch.cuda.device_count()}\")\n",
48
- " print(f\" 当前GPU: {torch.cuda.current_device()}\")\n",
49
- " print(f\" GPU名称: {torch.cuda.get_device_name(0)}\")\n",
50
- " print(f\" CUDA版本: {torch.version.cuda}\")\n",
51
- " \n",
52
- " # 显存信息\n",
53
- " total_memory = torch.cuda.get_device_properties(0).total_memory / (1024**3)\n",
54
- " print(f\" 总显存: {total_memory:.2f} GB\")\n",
55
- " \n",
56
- " # nvidia-smi信息\n",
57
- " print(\"\\n📊 nvidia-smi 输出:\")\n",
58
- " print(\"-\"*60)\n",
59
- " !nvidia-smi\n",
60
- "else:\n",
61
- " print(\"\\n⚠️ 警告: 未检测到GPU\")\n",
62
- " print(\" 请检查: 运行时 → 更改运行时类型 → 硬件加速器 → GPU\")\n",
63
- "\n",
64
- "print(\"\\n\" + \"=\"*60)"
65
- ]
66
- },
67
- {
68
- "cell_type": "markdown",
69
- "metadata": {},
70
- "source": [
71
- "## 2️⃣ GPU性能基准测试"
72
- ]
73
- },
74
- {
75
- "cell_type": "code",
76
- "execution_count": null,
77
- "metadata": {},
78
- "outputs": [],
79
- "source": [
80
- "# GPU vs CPU 性能对比\n",
81
- "import time\n",
82
- "import numpy as np\n",
83
- "\n",
84
- "print(\"=\"*60)\n",
85
- "print(\"⚡ GPU vs CPU 矩阵运算性能测试\")\n",
86
- "print(\"=\"*60)\n",
87
- "\n",
88
- "# 测试参数\n",
89
- "matrix_size = 5000\n",
90
- "\n",
91
- "# CPU测试\n",
92
- "print(f\"\\n🔵 CPU测试 (矩阵大小: {matrix_size}x{matrix_size})\")\n",
93
- "a_cpu = torch.randn(matrix_size, matrix_size)\n",
94
- "b_cpu = torch.randn(matrix_size, matrix_size)\n",
95
- "\n",
96
- "start = time.time()\n",
97
- "c_cpu = torch.mm(a_cpu, b_cpu)\n",
98
- "cpu_time = time.time() - start\n",
99
- "print(f\" CPU时间: {cpu_time:.2f} 秒\")\n",
100
- "\n",
101
- "# GPU测试\n",
102
- "if cuda_available:\n",
103
- " print(f\"\\n🟢 GPU测试 (矩阵大小: {matrix_size}x{matrix_size})\")\n",
104
- " a_gpu = torch.randn(matrix_size, matrix_size).cuda()\n",
105
- " b_gpu = torch.randn(matrix_size, matrix_size).cuda()\n",
106
- " \n",
107
- " # 预热GPU\n",
108
- " _ = torch.mm(a_gpu, b_gpu)\n",
109
- " torch.cuda.synchronize()\n",
110
- " \n",
111
- " start = time.time()\n",
112
- " c_gpu = torch.mm(a_gpu, b_gpu)\n",
113
- " torch.cuda.synchronize()\n",
114
- " gpu_time = time.time() - start\n",
115
- " print(f\" GPU时间: {gpu_time:.2f} 秒\")\n",
116
- " \n",
117
- " speedup = cpu_time / gpu_time\n",
118
- " print(f\"\\n🚀 加速比: {speedup:.2f}x\")\n",
119
- " print(f\" GPU比CPU快 {speedup:.1f} 倍!\")\n",
120
- "else:\n",
121
- " print(\"\\n⚠️ 跳过GPU测试(GPU不可用)\")\n",
122
- "\n",
123
- "print(\"\\n\" + \"=\"*60)"
124
- ]
125
- },
126
- {
127
- "cell_type": "markdown",
128
- "metadata": {},
129
- "source": [
130
- "## 3️⃣ 安装GraphRAG依赖"
131
- ]
132
- },
133
- {
134
- "cell_type": "code",
135
- "execution_count": null,
136
- "metadata": {},
137
- "outputs": [],
138
- "source": [
139
- "# 克隆项目(如果需要)\n",
140
- "import os\n",
141
- "\n",
142
- "print(\"📦 安装GraphRAG依赖...\\n\")\n",
143
- "\n",
144
- "# 安装核心依赖\n",
145
- "!pip install -q langchain langchain-community langchain-core langgraph\n",
146
- "!pip install -q chromadb sentence-transformers transformers\n",
147
- "!pip install -q tiktoken beautifulsoup4 requests\n",
148
- "!pip install -q tavily-python python-dotenv\n",
149
- "!pip install -q networkx python-louvain\n",
150
- "!pip install -q torch --index-url https://download.pytorch.org/whl/cu118\n",
151
- "\n",
152
- "print(\"\\n✅ 依赖安装完成!\")"
153
- ]
154
- },
155
- {
156
- "cell_type": "markdown",
157
- "metadata": {},
158
- "source": [
159
- "## 4️⃣ 上传项目文件\n",
160
- "\n",
161
- "**选项A**: 从GitHub克隆\n",
162
- "```python\n",
163
- "!git clone https://github.com/your-repo/adaptive_RAG.git\n",
164
- "%cd adaptive_RAG\n",
165
- "```\n",
166
- "\n",
167
- "**选项B**: 手动上传文件到Colab\n",
168
- "- 使用左侧文件浏览器上传以下核心文件:\n",
169
- " - `config.py`\n",
170
- " - `entity_extractor.py`\n",
171
- " - `knowledge_graph.py`\n",
172
- " - `graph_indexer.py`\n",
173
- " - `graph_retriever.py`\n",
174
- " - `.env` (包含API密钥)"
175
- ]
176
- },
177
- {
178
- "cell_type": "code",
179
- "execution_count": null,
180
- "metadata": {},
181
- "outputs": [],
182
- "source": [
183
- "# 创建必要的目录\n",
184
- "!mkdir -p data\n",
185
- "\n",
186
- "# 如果使用选项A,运行下面的命令\n",
187
- "# !git clone YOUR_REPO_URL\n",
188
- "# %cd adaptive_RAG\n",
189
- "\n",
190
- "print(\"✅ 目录准备完成\")"
191
- ]
192
- },
193
- {
194
- "cell_type": "markdown",
195
- "metadata": {},
196
- "source": [
197
- "## 5️⃣ 配置API密钥"
198
- ]
199
- },
200
- {
201
- "cell_type": "code",
202
- "execution_count": null,
203
- "metadata": {},
204
- "outputs": [],
205
- "source": [
206
- "# 设置API密钥(替换为您的真实密钥)\n",
207
- "import os\n",
208
- "from getpass import getpass\n",
209
- "\n",
210
- "print(\"🔑 配置API密钥\\n\")\n",
211
- "\n",
212
- "# 方式1: 直接设置(不安全,仅用于测试)\n",
213
- "# os.environ['TAVILY_API_KEY'] = 'your_tavily_api_key_here'\n",
214
- "\n",
215
- "# 方式2: 安全输入\n",
216
- "if 'TAVILY_API_KEY' not in os.environ:\n",
217
- " os.environ['TAVILY_API_KEY'] = getpass('输入 TAVILY_API_KEY: ')\n",
218
- " print(\"✅ TAVILY_API_KEY 已设置\")\n",
219
- "else:\n",
220
- " print(\"✅ TAVILY_API_KEY 已存在\")\n",
221
- "\n",
222
- "print(\"\\n注意: GraphRAG在Colab上使用HuggingFace嵌入,不需要NOMIC_API_KEY\")"
223
- ]
224
- },
225
- {
226
- "cell_type": "markdown",
227
- "metadata": {},
228
- "source": [
229
- "## 6️⃣ 简化版GraphRAG测试代码"
230
- ]
231
- },
232
- {
233
- "cell_type": "code",
234
- "execution_count": null,
235
- "metadata": {},
236
- "outputs": [],
237
- "source": [
238
- "# 简化版GraphRAG核心组件\n",
239
- "# 适用于Colab快速测试,无需完整项目文件\n",
240
- "\n",
241
- "from typing import List, Dict\n",
242
- "import networkx as nx\n",
243
- "from sentence_transformers import SentenceTransformer\n",
244
- "import torch\n",
245
- "\n",
246
- "class SimpleGraphRAG:\n",
247
- " \"\"\"简化版GraphRAG用于GPU性能测试\"\"\"\n",
248
- " \n",
249
- " def __init__(self, use_gpu=True):\n",
250
- " print(\"🚀 初始化SimpleGraphRAG...\")\n",
251
- " \n",
252
- " # 检测设备\n",
253
- " self.device = 'cuda' if use_gpu and torch.cuda.is_available() else 'cpu'\n",
254
- " print(f\" 设备: {self.device.upper()}\")\n",
255
- " \n",
256
- " # 加载嵌入模型\n",
257
- " print(f\" 加载嵌入模型...\")\n",
258
- " self.embedder = SentenceTransformer(\n",
259
- " 'sentence-transformers/all-MiniLM-L6-v2',\n",
260
- " device=self.device\n",
261
- " )\n",
262
- " \n",
263
- " # 知识图谱\n",
264
- " self.graph = nx.Graph()\n",
265
- " self.entities = {}\n",
266
- " \n",
267
- " print(\"✅ 初始化完成!\")\n",
268
- " \n",
269
- " def add_sample_data(self):\n",
270
- " \"\"\"添加示例数据\"\"\"\n",
271
- " print(\"\\n📊 添加示例数据...\")\n",
272
- " \n",
273
- " # 示例实体\n",
274
- " entities = [\n",
275
- " {\"name\": \"LLM\", \"type\": \"CONCEPT\", \"desc\": \"大语言模型\"},\n",
276
- " {\"name\": \"GPT\", \"type\": \"TECHNOLOGY\", \"desc\": \"生成式预训练转换器\"},\n",
277
- " {\"name\": \"Transformer\", \"type\": \"CONCEPT\", \"desc\": \"注意力机制架构\"},\n",
278
- " {\"name\": \"OpenAI\", \"type\": \"ORGANIZATION\", \"desc\": \"人工智能研究公司\"},\n",
279
- " {\"name\": \"Attention\", \"type\": \"CONCEPT\", \"desc\": \"注意力机制\"},\n",
280
- " ]\n",
281
- " \n",
282
- " for entity in entities:\n",
283
- " self.graph.add_node(\n",
284
- " entity[\"name\"],\n",
285
- " type=entity[\"type\"],\n",
286
- " description=entity[\"desc\"]\n",
287
- " )\n",
288
- " self.entities[entity[\"name\"]] = entity\n",
289
- " \n",
290
- " # 示例关系\n",
291
- " relations = [\n",
292
- " (\"GPT\", \"LLM\", \"IS_A\"),\n",
293
- " (\"GPT\", \"Transformer\", \"USES\"),\n",
294
- " (\"Transformer\", \"Attention\", \"CONTAINS\"),\n",
295
- " (\"OpenAI\", \"GPT\", \"DEVELOPS\"),\n",
296
- " ]\n",
297
- " \n",
298
- " for source, target, rel_type in relations:\n",
299
- " self.graph.add_edge(source, target, relation=rel_type)\n",
300
- " \n",
301
- " print(f\" ✅ 添加了 {len(entities)} 个实体\")\n",
302
- " print(f\" ✅ 添加了 {len(relations)} 个关系\")\n",
303
- " \n",
304
- " def test_gpu_embedding(self, texts: List[str]):\n",
305
- " \"\"\"测试GPU嵌入性能\"\"\"\n",
306
- " print(f\"\\n⚡ 测试嵌入性能 ({len(texts)} 个文本)...\")\n",
307
- " \n",
308
- " import time\n",
309
- " \n",
310
- " start = time.time()\n",
311
- " embeddings = self.embedder.encode(\n",
312
- " texts,\n",
313
- " show_progress_bar=True,\n",
314
- " batch_size=32\n",
315
- " )\n",
316
- " elapsed = time.time() - start\n",
317
- " \n",
318
- " print(f\" ✅ 完成! 耗时: {elapsed:.2f}秒\")\n",
319
- " print(f\" 📊 嵌入维度: {embeddings.shape}\")\n",
320
- " print(f\" 🚀 速度: {len(texts)/elapsed:.1f} 文本/秒\")\n",
321
- " \n",
322
- " return embeddings\n",
323
- " \n",
324
- " def query(self, question: str):\n",
325
- " \"\"\"简单查询\"\"\"\n",
326
- " print(f\"\\n🔍 查询: {question}\")\n",
327
- " \n",
328
- " # 简单的关键词匹配\n",
329
- " results = []\n",
330
- " for entity_name in self.entities:\n",
331
- " if entity_name.lower() in question.lower():\n",
332
- " neighbors = list(self.graph.neighbors(entity_name))\n",
333
- " results.append({\n",
334
- " \"entity\": entity_name,\n",
335
- " \"info\": self.entities[entity_name],\n",
336
- " \"neighbors\": neighbors\n",
337
- " })\n",
338
- " \n",
339
- " print(f\"\\n📋 找到 {len(results)} 个相关实体:\")\n",
340
- " for r in results:\n",
341
- " print(f\" • {r['entity']} ({r['info']['type']})\")\n",
342
- " print(f\" 描述: {r['info']['desc']}\")\n",
343
- " print(f\" 关联: {', '.join(r['neighbors'])}\")\n",
344
- " \n",
345
- " return results\n",
346
- "\n",
347
- "print(\"✅ SimpleGraphRAG类定义完成\")"
348
- ]
349
- },
350
- {
351
- "cell_type": "markdown",
352
- "metadata": {},
353
- "source": [
354
- "## 7️⃣ 运行GPU性能测试"
355
- ]
356
- },
357
- {
358
- "cell_type": "code",
359
- "execution_count": null,
360
- "metadata": {},
361
- "outputs": [],
362
- "source": [
363
- "# 初始化GraphRAG(GPU版本)\n",
364
- "print(\"=\"*60)\n",
365
- "print(\"🎯 GraphRAG GPU性能测试\")\n",
366
- "print(\"=\"*60)\n",
367
- "\n",
368
- "graph_rag = SimpleGraphRAG(use_gpu=True)\n",
369
- "\n",
370
- "# 添加示例数据\n",
371
- "graph_rag.add_sample_data()\n",
372
- "\n",
373
- "# 准备测试文本\n",
374
- "test_texts = [\n",
375
- " \"Large Language Models are transforming AI\",\n",
376
- " \"GPT uses Transformer architecture\",\n",
377
- " \"Attention mechanism is key to modern NLP\",\n",
378
- " \"OpenAI develops cutting-edge AI models\",\n",
379
- "] * 25 # 100个文本\n",
380
- "\n",
381
- "print(f\"\\n准备了 {len(test_texts)} 个测试文本\")\n",
382
- "\n",
383
- "# GPU嵌入测试\n",
384
- "embeddings = graph_rag.test_gpu_embedding(test_texts)\n",
385
- "\n",
386
- "# 测试查询\n",
387
- "graph_rag.query(\"What is GPT?\")\n",
388
- "graph_rag.query(\"Tell me about Transformer\")\n",
389
- "\n",
390
- "print(\"\\n\" + \"=\"*60)\n",
391
- "print(\"✅ GPU性能测试完成!\")\n",
392
- "print(\"=\"*60)"
393
- ]
394
- },
395
- {
396
- "cell_type": "markdown",
397
- "metadata": {},
398
- "source": [
399
- "## 8️⃣ CPU vs GPU 性能对比"
400
- ]
401
- },
402
- {
403
- "cell_type": "code",
404
- "execution_count": null,
405
- "metadata": {},
406
- "outputs": [],
407
- "source": [
408
- "# CPU vs GPU 嵌入性能对比\n",
409
- "import time\n",
410
- "\n",
411
- "print(\"=\"*60)\n",
412
- "print(\"📊 CPU vs GPU 嵌入性能对比\")\n",
413
- "print(\"=\"*60)\n",
414
- "\n",
415
- "# 准备大量测试文本\n",
416
- "large_test_texts = test_texts * 10 # 1000个文本\n",
417
- "print(f\"\\n测试数据: {len(large_test_texts)} 个文本\\n\")\n",
418
- "\n",
419
- "# CPU测试\n",
420
- "print(\"🔵 CPU测试...\")\n",
421
- "graph_rag_cpu = SimpleGraphRAG(use_gpu=False)\n",
422
- "start = time.time()\n",
423
- "embeddings_cpu = graph_rag_cpu.embedder.encode(\n",
424
- " large_test_texts,\n",
425
- " show_progress_bar=False,\n",
426
- " batch_size=32\n",
427
- ")\n",
428
- "cpu_time = time.time() - start\n",
429
- "print(f\" CPU时间: {cpu_time:.2f}秒\")\n",
430
- "print(f\" 速度: {len(large_test_texts)/cpu_time:.1f} 文本/秒\")\n",
431
- "\n",
432
- "# GPU测试\n",
433
- "if cuda_available:\n",
434
- " print(\"\\n🟢 GPU测试...\")\n",
435
- " graph_rag_gpu = SimpleGraphRAG(use_gpu=True)\n",
436
- " start = time.time()\n",
437
- " embeddings_gpu = graph_rag_gpu.embedder.encode(\n",
438
- " large_test_texts,\n",
439
- " show_progress_bar=False,\n",
440
- " batch_size=32\n",
441
- " )\n",
442
- " gpu_time = time.time() - start\n",
443
- " print(f\" GPU时间: {gpu_time:.2f}秒\")\n",
444
- " print(f\" 速度: {len(large_test_texts)/gpu_time:.1f} 文本/秒\")\n",
445
- " \n",
446
- " speedup = cpu_time / gpu_time\n",
447
- " print(f\"\\n🚀 加速比: {speedup:.2f}x\")\n",
448
- " print(f\" GPU比CPU快 {speedup:.1f} 倍!\")\n",
449
- " \n",
450
- " # 节省的时间\n",
451
- " time_saved = cpu_time - gpu_time\n",
452
- " print(f\" ⏱️ 节省时间: {time_saved:.2f}秒\")\n",
453
- "else:\n",
454
- " print(\"\\n⚠️ GPU不可用,跳过GPU测试\")\n",
455
- "\n",
456
- "print(\"\\n\" + \"=\"*60)"
457
- ]
458
- },
459
- {
460
- "cell_type": "markdown",
461
- "metadata": {},
462
- "source": [
463
- "## 9️⃣ 显存使用监控"
464
- ]
465
- },
466
- {
467
- "cell_type": "code",
468
- "execution_count": null,
469
- "metadata": {},
470
- "outputs": [],
471
- "source": [
472
- "# 监控GPU显存使用\n",
473
- "if cuda_available:\n",
474
- " print(\"=\"*60)\n",
475
- " print(\"💾 GPU显存使用情况\")\n",
476
- " print(\"=\"*60)\n",
477
- " \n",
478
- " allocated = torch.cuda.memory_allocated(0) / (1024**3)\n",
479
- " reserved = torch.cuda.memory_reserved(0) / (1024**3)\n",
480
- " total = torch.cuda.get_device_properties(0).total_memory / (1024**3)\n",
481
- " \n",
482
- " print(f\"\\n已分配: {allocated:.2f} GB\")\n",
483
- " print(f\"已保留: {reserved:.2f} GB\")\n",
484
- " print(f\"总显存: {total:.2f} GB\")\n",
485
- " print(f\"使用率: {(allocated/total)*100:.1f}%\")\n",
486
- " \n",
487
- " print(\"\\n详细信息:\")\n",
488
- " print(torch.cuda.memory_summary(0, abbreviated=True))\n",
489
- " \n",
490
- " print(\"\\n\" + \"=\"*60)\n",
491
- "else:\n",
492
- " print(\"⚠️ GPU不可用\")"
493
- ]
494
- },
495
- {
496
- "cell_type": "markdown",
497
- "metadata": {},
498
- "source": [
499
- "## 🔟 性能总结报告"
500
- ]
501
- },
502
- {
503
- "cell_type": "code",
504
- "execution_count": null,
505
- "metadata": {},
506
- "outputs": [],
507
- "source": [
508
- "# 生成性能报告\n",
509
- "print(\"=\"*60)\n",
510
- "print(\"📈 GraphRAG GPU性能测试报告\")\n",
511
- "print(\"=\"*60)\n",
512
- "\n",
513
- "print(\"\\n🖥️ 硬件信息:\")\n",
514
- "if cuda_available:\n",
515
- " print(f\" GPU型号: {torch.cuda.get_device_name(0)}\")\n",
516
- " print(f\" 显存: {torch.cuda.get_device_properties(0).total_memory / (1024**3):.2f} GB\")\n",
517
- " print(f\" CUDA版本: {torch.version.cuda}\")\n",
518
- "else:\n",
519
- " print(\" ⚠️ GPU不可用\")\n",
520
- "\n",
521
- "print(f\"\\n PyTorch版本: {torch.__version__}\")\n",
522
- "print(f\" Python版本: {sys.version.split()[0]}\")\n",
523
- "\n",
524
- "print(\"\\n⚡ 性能测试结果:\")\n",
525
- "print(f\" 矩阵运算加速: ~{speedup if cuda_available else 'N/A'}x\")\n",
526
- "print(f\" 文本嵌入加速: ~{cpu_time/gpu_time if cuda_available else 'N/A'}x\")\n",
527
- "\n",
528
- "print(\"\\n💡 建议:\")\n",
529
- "if cuda_available:\n",
530
- " print(\" ✅ GPU运行良好!建议在Colab上运行完整的GraphRAG索引构建\")\n",
531
- " print(\" ✅ 预计索引构建时间将大幅缩短\")\n",
532
- " print(\" ✅ 可以处理更大规模的文档集\")\n",
533
- "else:\n",
534
- " print(\" ⚠️ 建议启用GPU以获得最佳性能\")\n",
535
- " print(\" ⚠️ 路径: 运行时 → 更改运行时类型 → GPU\")\n",
536
- "\n",
537
- "print(\"\\n\" + \"=\"*60)\n",
538
- "print(\"✅ 测试完成!\")\n",
539
- "print(\"=\"*60)"
540
- ]
541
- },
542
- {
543
- "cell_type": "markdown",
544
- "metadata": {},
545
- "source": [
546
- "---\n",
547
- "\n",
548
- "## 📚 下一步\n",
549
- "\n",
550
- "如果GPU测试成功,您可以:\n",
551
- "\n",
552
- "1. **上传完整项目**: 将整个adaptive_RAG项目上传到Colab\n",
553
- "2. **运行GraphRAG索引**: 使用GPU加速构建知识图谱\n",
554
- "3. **保存结果**: 将构建好的图谱下载到本地\n",
555
- "\n",
556
- "### 运行完整GraphRAG的命令:\n",
557
- "\n",
558
- "```python\n",
559
- "# 上传项目后运行\n",
560
- "!python main_graphrag.py\n",
561
- "```\n",
562
- "\n",
563
- "### 预期加速效果:\n",
564
- "\n",
565
- "- 实体提取: 使用GPU的LLM推理会更快\n",
566
- "- 文本嵌入: **5-10倍加速**\n",
567
- "- 向量相似度计算: **10-20倍加速**\n",
568
- "- 总体索引构建时间: **3-5倍加速**\n",
569
- "\n",
570
- "---"
571
- ]
572
- }
573
- ],
574
- "metadata": {
575
- "accelerator": "GPU",
576
- "kernelspec": {
577
- "display_name": "Python 3",
578
- "language": "python",
579
- "name": "python3"
580
- },
581
- "language_info": {
582
- "name": "python",
583
- "version": "3.10.0"
584
- }
585
- },
586
- "nbformat": 4,
587
- "nbformat_minor": 0
588
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
colab_gpu_test.py DELETED
@@ -1,269 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Google Colab GPU检测和GraphRAG性能测试脚本
4
- 可以直接在Colab中运行:python colab_gpu_test.py
5
- """
6
-
7
- import sys
8
- import time
9
- import torch
10
- import numpy as np
11
- from typing import List, Dict
12
-
13
- def print_section(title: str):
14
- """打印分节标题"""
15
- print("\n" + "="*60)
16
- print(f"{title}")
17
- print("="*60 + "\n")
18
-
19
-
20
- def test_gpu_availability():
21
- """测试GPU可用性"""
22
- print_section("🔍 GPU环境检测")
23
-
24
- cuda_available = torch.cuda.is_available()
25
- print(f"✅ CUDA可用: {cuda_available}")
26
-
27
- if cuda_available:
28
- print(f" GPU数量: {torch.cuda.device_count()}")
29
- print(f" 当前GPU: {torch.cuda.current_device()}")
30
- print(f" GPU名称: {torch.cuda.get_device_name(0)}")
31
- print(f" CUDA版本: {torch.version.cuda}")
32
-
33
- total_memory = torch.cuda.get_device_properties(0).total_memory / (1024**3)
34
- print(f" 总显存: {total_memory:.2f} GB")
35
-
36
- return True
37
- else:
38
- print("\n⚠️ 警告: 未检测到GPU")
39
- print(" 在Colab中启用GPU: 运行时 → 更改运行时类型 → GPU")
40
- return False
41
-
42
-
43
- def benchmark_matrix_multiplication(matrix_size=5000):
44
- """GPU vs CPU 矩阵运算性能测试"""
45
- print_section("⚡ GPU vs CPU 矩阵运算性能测试")
46
-
47
- print(f"矩阵大小: {matrix_size}x{matrix_size}\n")
48
-
49
- # CPU测试
50
- print("🔵 CPU测试...")
51
- a_cpu = torch.randn(matrix_size, matrix_size)
52
- b_cpu = torch.randn(matrix_size, matrix_size)
53
-
54
- start = time.time()
55
- c_cpu = torch.mm(a_cpu, b_cpu)
56
- cpu_time = time.time() - start
57
- print(f" CPU时间: {cpu_time:.2f} 秒")
58
-
59
- # GPU测试
60
- if torch.cuda.is_available():
61
- print("\n🟢 GPU测试...")
62
- a_gpu = torch.randn(matrix_size, matrix_size).cuda()
63
- b_gpu = torch.randn(matrix_size, matrix_size).cuda()
64
-
65
- # 预热GPU
66
- _ = torch.mm(a_gpu, b_gpu)
67
- torch.cuda.synchronize()
68
-
69
- start = time.time()
70
- c_gpu = torch.mm(a_gpu, b_gpu)
71
- torch.cuda.synchronize()
72
- gpu_time = time.time() - start
73
- print(f" GPU时间: {gpu_time:.2f} 秒")
74
-
75
- speedup = cpu_time / gpu_time
76
- print(f"\n🚀 加速比: {speedup:.2f}x")
77
- print(f" GPU比CPU快 {speedup:.1f} 倍!")
78
-
79
- return speedup
80
- else:
81
- print("\n⚠️ 跳过GPU测试(GPU不可用)")
82
- return 1.0
83
-
84
-
85
- def test_text_embedding_performance():
86
- """测试文本嵌入性能(需要sentence-transformers)"""
87
- print_section("📝 文本嵌入性能测试")
88
-
89
- try:
90
- from sentence_transformers import SentenceTransformer
91
-
92
- # 准备测试数据
93
- test_texts = [
94
- "Large Language Models are transforming AI",
95
- "GraphRAG combines knowledge graphs with retrieval",
96
- "GPU acceleration significantly improves performance",
97
- "Natural language processing is advancing rapidly",
98
- ] * 250 # 1000个文本
99
-
100
- print(f"测试数据: {len(test_texts)} 个文本\n")
101
-
102
- # CPU测试
103
- print("🔵 CPU嵌入测试...")
104
- model_cpu = SentenceTransformer(
105
- 'sentence-transformers/all-MiniLM-L6-v2',
106
- device='cpu'
107
- )
108
- start = time.time()
109
- embeddings_cpu = model_cpu.encode(test_texts, show_progress_bar=False, batch_size=32)
110
- cpu_time = time.time() - start
111
- print(f" CPU时间: {cpu_time:.2f}秒")
112
- print(f" 速度: {len(test_texts)/cpu_time:.1f} 文本/秒")
113
-
114
- # GPU测试
115
- if torch.cuda.is_available():
116
- print("\n🟢 GPU嵌入测试...")
117
- model_gpu = SentenceTransformer(
118
- 'sentence-transformers/all-MiniLM-L6-v2',
119
- device='cuda'
120
- )
121
- start = time.time()
122
- embeddings_gpu = model_gpu.encode(test_texts, show_progress_bar=False, batch_size=32)
123
- gpu_time = time.time() - start
124
- print(f" GPU时间: {gpu_time:.2f}秒")
125
- print(f" 速度: {len(test_texts)/gpu_time:.1f} 文本/秒")
126
-
127
- speedup = cpu_time / gpu_time
128
- print(f"\n🚀 加速比: {speedup:.2f}x")
129
- print(f" 节省时间: {cpu_time - gpu_time:.2f}秒")
130
-
131
- return speedup
132
- else:
133
- print("\n⚠️ 跳过GPU测试")
134
- return 1.0
135
-
136
- except ImportError:
137
- print("⚠️ sentence-transformers未安装")
138
- print(" 安装: pip install sentence-transformers")
139
- return None
140
-
141
-
142
- def monitor_gpu_memory():
143
- """监控GPU显存使用"""
144
- if not torch.cuda.is_available():
145
- return
146
-
147
- print_section("💾 GPU显存使用情况")
148
-
149
- allocated = torch.cuda.memory_allocated(0) / (1024**3)
150
- reserved = torch.cuda.memory_reserved(0) / (1024**3)
151
- total = torch.cuda.get_device_properties(0).total_memory / (1024**3)
152
-
153
- print(f"已分配: {allocated:.2f} GB")
154
- print(f"已保留: {reserved:.2f} GB")
155
- print(f"总显存: {total:.2f} GB")
156
- print(f"使用率: {(allocated/total)*100:.1f}%")
157
-
158
-
159
- def generate_performance_report(matrix_speedup, embedding_speedup):
160
- """生成性能报告"""
161
- print_section("📈 性能测试总结报告")
162
-
163
- print("🖥️ 硬件信息:")
164
- if torch.cuda.is_available():
165
- print(f" GPU型号: {torch.cuda.get_device_name(0)}")
166
- print(f" 显存: {torch.cuda.get_device_properties(0).total_memory / (1024**3):.2f} GB")
167
- print(f" CUDA版本: {torch.version.cuda}")
168
- else:
169
- print(" ⚠️ GPU不可用")
170
-
171
- print(f"\n PyTorch版本: {torch.__version__}")
172
- print(f" Python版本: {sys.version.split()[0]}")
173
-
174
- print("\n⚡ 性能测试结果:")
175
- print(f" 矩阵运算加速: {matrix_speedup:.2f}x")
176
- if embedding_speedup:
177
- print(f" 文本嵌入加速: {embedding_speedup:.2f}x")
178
-
179
- print("\n💡 建议:")
180
- if torch.cuda.is_available():
181
- print(" ✅ GPU运行良好!")
182
- print(" ✅ 建议在Colab上运行完整的GraphRAG索引构建")
183
- print(" ✅ 预计索引构建时间将缩短 3-5 倍")
184
-
185
- # 估算时间节省
186
- if embedding_speedup and embedding_speedup > 1:
187
- print(f"\n⏱️ 时间节省估算:")
188
- print(f" 100文档CPU耗时: ~15分钟")
189
- print(f" 100文档GPU耗时: ~{15/embedding_speedup:.1f}分钟")
190
- print(f" 节省: ~{15 - 15/embedding_speedup:.1f}分钟")
191
- else:
192
- print(" ⚠️ 建议启用GPU以获得最佳性能")
193
- print(" ⚠️ Colab启用GPU: 运行时 → 更改运行时类型 → GPU")
194
-
195
-
196
- def install_dependencies():
197
- """安装必要的依赖(仅在Colab中)"""
198
- try:
199
- import google.colab
200
- is_colab = True
201
- except:
202
- is_colab = False
203
-
204
- if is_colab:
205
- print_section("📦 安装依赖")
206
- print("检测到Colab环境,安装必要的包...\n")
207
-
208
- import subprocess
209
- packages = [
210
- 'sentence-transformers',
211
- 'networkx',
212
- 'python-louvain',
213
- ]
214
-
215
- for package in packages:
216
- try:
217
- __import__(package.replace('-', '_'))
218
- print(f"✅ {package} 已安装")
219
- except ImportError:
220
- print(f"📥 安装 {package}...")
221
- subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', package])
222
- print(f"✅ {package} 安装完成")
223
-
224
-
225
- def main():
226
- """主函数"""
227
- print("\n" + "="*60)
228
- print("🚀 Google Colab GPU检测和GraphRAG性能测试")
229
- print("="*60)
230
-
231
- # 检查是否在Colab中运行
232
- try:
233
- import google.colab
234
- print("\n✅ 运行环境: Google Colab")
235
- except:
236
- print("\n⚠️ 警告: 未检测到Colab环境")
237
- print(" 本脚本专为Google Colab设计")
238
-
239
- # 安装依赖
240
- install_dependencies()
241
-
242
- # 1. GPU检测
243
- gpu_available = test_gpu_availability()
244
-
245
- # 2. 矩阵运算性能测试
246
- matrix_speedup = benchmark_matrix_multiplication(matrix_size=5000)
247
-
248
- # 3. 文本嵌入性能测试
249
- embedding_speedup = test_text_embedding_performance()
250
-
251
- # 4. 显存监控
252
- if gpu_available:
253
- monitor_gpu_memory()
254
-
255
- # 5. 生成报告
256
- generate_performance_report(matrix_speedup, embedding_speedup)
257
-
258
- print("\n" + "="*60)
259
- print("✅ 测试完成!")
260
- print("="*60)
261
-
262
- print("\n📚 下一步:")
263
- print(" 1. 如果GPU测试成功,可以上传完整的adaptive_RAG项目")
264
- print(" 2. 运行 main_graphrag.py 进行完整的知识图谱构建")
265
- print(" 3. 享受GPU带来的3-5倍速度提升!")
266
-
267
-
268
- if __name__ == "__main__":
269
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
colab_install_deps.py DELETED
@@ -1,99 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Colab环境依赖安装脚本
4
- 确保所有LangChain相关包都是最新版本,避免导入错误
5
- """
6
-
7
- import subprocess
8
- import sys
9
-
10
- def install_package(package):
11
- """安装单个包"""
12
- subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", package])
13
-
14
- def main():
15
- print("="*70)
16
- print("📦 Colab GraphRAG 依赖安装")
17
- print("="*70)
18
-
19
- # 关键包列表(指定版本以确保兼容性)
20
- packages = [
21
- # LangChain核心包(最新版本)
22
- "langchain>=0.1.0",
23
- "langchain-core>=0.1.52",
24
- "langchain-community>=0.0.38",
25
- "langchain-text-splitters>=0.0.1",
26
- "langgraph>=0.0.40",
27
-
28
- # Ollama支持
29
- "langchain-ollama>=0.1.0",
30
-
31
- # 向量数据库和嵌入
32
- "chromadb>=0.4.22",
33
- "sentence-transformers>=2.2.0",
34
-
35
- # 文档处理
36
- "tiktoken>=0.5.0",
37
- "beautifulsoup4>=4.12.0",
38
- "requests>=2.31.0",
39
-
40
- # 网络搜索
41
- "tavily-python>=0.3.0",
42
-
43
- # 工具库
44
- "python-dotenv>=1.0.0",
45
-
46
- # GraphRAG特定
47
- "networkx>=3.1",
48
- "python-louvain>=0.16",
49
-
50
- # PyTorch和Transformers
51
- "torch>=2.0.0",
52
- "transformers>=4.30.0",
53
- ]
54
-
55
- print("\n🔄 开始安装依赖包...\n")
56
-
57
- for i, package in enumerate(packages, 1):
58
- try:
59
- print(f"[{i}/{len(packages)}] 安装 {package}...")
60
- install_package(package)
61
- print(f" ✅ {package} 安装成功")
62
- except Exception as e:
63
- print(f" ❌ {package} 安装失败: {e}")
64
-
65
- print("\n" + "="*70)
66
- print("✅ 依赖安装完成!")
67
- print("="*70)
68
-
69
- # 验证关键导入
70
- print("\n🔍 验证关键导入...")
71
-
72
- imports_to_check = [
73
- ("langchain", "LangChain"),
74
- ("langchain_core", "LangChain Core"),
75
- ("langchain_community", "LangChain Community"),
76
- ("langchain_text_splitters", "LangChain Text Splitters"),
77
- ("chromadb", "ChromaDB"),
78
- ("sentence_transformers", "Sentence Transformers"),
79
- ("networkx", "NetworkX"),
80
- ]
81
-
82
- all_ok = True
83
- for module, name in imports_to_check:
84
- try:
85
- __import__(module)
86
- print(f" ✅ {name}")
87
- except ImportError as e:
88
- print(f" ❌ {name}: {e}")
89
- all_ok = False
90
-
91
- if all_ok:
92
- print("\n🎉 所有依赖验证通过!")
93
- else:
94
- print("\n⚠️ 部分依赖验证失败,请检查错误信息")
95
-
96
- print("\n" + "="*70)
97
-
98
- if __name__ == "__main__":
99
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
colab_quick_test.py DELETED
@@ -1,278 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Google Colab一键GPU测试脚本
4
- 复制此文件内容到Colab单元格中直接运行
5
-
6
- 使用方法:
7
- 1. 在Colab中创建新笔记本
8
- 2. 启用GPU (运行时 → 更改运行时类型 → GPU)
9
- 3. 复制并运行此脚本
10
- """
11
-
12
- # ============================================================
13
- # 🔧 自动安装依赖
14
- # ============================================================
15
- print("📦 检查并安装依赖...")
16
- import subprocess
17
- import sys
18
-
19
- def install(package):
20
- subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", package])
21
-
22
- # 检查必要的包
23
- required_packages = {
24
- 'torch': 'torch',
25
- 'sentence_transformers': 'sentence-transformers',
26
- 'networkx': 'networkx',
27
- 'numpy': 'numpy'
28
- }
29
-
30
- for import_name, package_name in required_packages.items():
31
- try:
32
- __import__(import_name)
33
- print(f"✅ {package_name} 已安装")
34
- except ImportError:
35
- print(f"📥 安装 {package_name}...")
36
- install(package_name)
37
-
38
- print("\n" + "="*70)
39
- print("🚀 Google Colab GPU性能测试 - GraphRAG加速验证")
40
- print("="*70)
41
-
42
- # ============================================================
43
- # 1️⃣ GPU检测
44
- # ============================================================
45
- import torch
46
- import time
47
-
48
- print("\n" + "="*70)
49
- print("🔍 步骤1: GPU环境检测")
50
- print("="*70)
51
-
52
- cuda_available = torch.cuda.is_available()
53
- print(f"\n{'✅' if cuda_available else '❌'} CUDA可用: {cuda_available}")
54
-
55
- if cuda_available:
56
- print(f" 📊 GPU型号: {torch.cuda.get_device_name(0)}")
57
- print(f" 💾 显存大小: {torch.cuda.get_device_properties(0).total_memory / (1024**3):.2f} GB")
58
- print(f" 🔢 CUDA版本: {torch.version.cuda}")
59
- print(f" 📈 PyTorch版本: {torch.__version__}")
60
- else:
61
- print("\n⚠️ GPU未启用!")
62
- print(" 请按照以下步骤启用GPU:")
63
- print(" 1. 点击顶部菜单 '运行时'")
64
- print(" 2. 选择 '更改运行时类型'")
65
- print(" 3. 硬件加速器选择 'GPU'")
66
- print(" 4. 点击 '保存'")
67
- print(" 5. 重新运行此单元格")
68
- print("\n⚠️ 测试将继续,但GPU相关测试会被跳过")
69
-
70
- # ============================================================
71
- # 2️⃣ 矩阵运算性能测试
72
- # ============================================================
73
- print("\n" + "="*70)
74
- print("⚡ 步骤2: 矩阵运算性能测试")
75
- print("="*70)
76
-
77
- matrix_size = 5000
78
- print(f"\n测试配置: {matrix_size}x{matrix_size} 矩阵乘法\n")
79
-
80
- # CPU测试
81
- print("🔵 CPU性能测试...")
82
- a_cpu = torch.randn(matrix_size, matrix_size)
83
- b_cpu = torch.randn(matrix_size, matrix_size)
84
-
85
- start = time.time()
86
- c_cpu = torch.mm(a_cpu, b_cpu)
87
- cpu_time = time.time() - start
88
-
89
- print(f" ⏱️ CPU耗时: {cpu_time:.3f}秒")
90
-
91
- # GPU测试
92
- if cuda_available:
93
- print("\n🟢 GPU性能测试...")
94
- a_gpu = torch.randn(matrix_size, matrix_size).cuda()
95
- b_gpu = torch.randn(matrix_size, matrix_size).cuda()
96
-
97
- # 预热
98
- _ = torch.mm(a_gpu, b_gpu)
99
- torch.cuda.synchronize()
100
-
101
- start = time.time()
102
- c_gpu = torch.mm(a_gpu, b_gpu)
103
- torch.cuda.synchronize()
104
- gpu_time = time.time() - start
105
-
106
- print(f" ⏱️ GPU耗时: {gpu_time:.3f}秒")
107
-
108
- speedup = cpu_time / gpu_time
109
- print(f"\n 🚀 性能提升: {speedup:.1f}x")
110
- print(f" 💡 GPU比CPU快 {speedup:.1f} 倍!")
111
-
112
- matrix_speedup = speedup
113
- else:
114
- print("\n⚠️ 跳过GPU测试")
115
- matrix_speedup = 1.0
116
-
117
- # ============================================================
118
- # 3️⃣ 文本嵌入性能测试
119
- # ============================================================
120
- print("\n" + "="*70)
121
- print("📝 步骤3: 文本嵌入性能测试 (GraphRAG核心组件)")
122
- print("="*70)
123
-
124
- try:
125
- from sentence_transformers import SentenceTransformer
126
-
127
- # 准备测试数据
128
- test_texts = [
129
- "GraphRAG combines knowledge graphs with retrieval augmented generation",
130
- "GPU acceleration significantly improves machine learning performance",
131
- "Large language models benefit from efficient embedding computation",
132
- "Knowledge graph construction requires entity and relation extraction",
133
- ] * 250 # 1000条文本
134
-
135
- print(f"\n测试配置: {len(test_texts)}条文本嵌入\n")
136
-
137
- # CPU嵌入
138
- print("🔵 CPU嵌入测试...")
139
- model_cpu = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2', device='cpu')
140
-
141
- start = time.time()
142
- embeddings_cpu = model_cpu.encode(test_texts, show_progress_bar=False, batch_size=32)
143
- cpu_emb_time = time.time() - start
144
-
145
- print(f" ⏱️ CPU耗时: {cpu_emb_time:.2f}秒")
146
- print(f" 📊 处理速度: {len(test_texts)/cpu_emb_time:.1f} 文本/秒")
147
-
148
- # GPU嵌入
149
- if cuda_available:
150
- print("\n🟢 GPU嵌入测试...")
151
- model_gpu = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2', device='cuda')
152
-
153
- start = time.time()
154
- embeddings_gpu = model_gpu.encode(test_texts, show_progress_bar=False, batch_size=32)
155
- gpu_emb_time = time.time() - start
156
-
157
- print(f" ⏱️ GPU耗时: {gpu_emb_time:.2f}秒")
158
- print(f" 📊 处理速度: {len(test_texts)/gpu_emb_time:.1f} 文本/秒")
159
-
160
- emb_speedup = cpu_emb_time / gpu_emb_time
161
- print(f"\n 🚀 性能提升: {emb_speedup:.1f}x")
162
- print(f" ⏱️ 节省时间: {cpu_emb_time - gpu_emb_time:.2f}秒")
163
- else:
164
- print("\n⚠️ 跳过GPU测试")
165
- emb_speedup = 1.0
166
-
167
- except ImportError:
168
- print("\n⚠️ sentence-transformers未安装,跳过此测试")
169
- emb_speedup = None
170
-
171
- # ============================================================
172
- # 4️⃣ GraphRAG场景模拟
173
- # ============================================================
174
- print("\n" + "="*70)
175
- print("🔍 步骤4: GraphRAG实际场景模拟")
176
- print("="*70)
177
-
178
- if cuda_available and emb_speedup:
179
- print("\n模拟GraphRAG索引构建过程...\n")
180
-
181
- # 假设100个文档块的索引构建
182
- documents_count = 100
183
-
184
- # 实体提取时间 (每个文档约1秒)
185
- entity_extraction_time = documents_count * 1.0
186
-
187
- # 文本嵌入时间 (基于实际测试)
188
- # 假设每个文档平均产生10个实体,共1000个实体需要嵌入
189
- entities_count = documents_count * 10
190
-
191
- cpu_total_time = entity_extraction_time + (entities_count / (len(test_texts)/cpu_emb_time))
192
- gpu_total_time = entity_extraction_time + (entities_count / (len(test_texts)/gpu_emb_time))
193
-
194
- print(f"📊 场景: {documents_count}个文档的GraphRAG索引构建\n")
195
- print(f"🔵 CPU预计时间:")
196
- print(f" - 实体提取: {entity_extraction_time/60:.1f}分钟")
197
- print(f" - 向量嵌入: {(entities_count / (len(test_texts)/cpu_emb_time))/60:.1f}分钟")
198
- print(f" - 总计: {cpu_total_time/60:.1f}分钟")
199
-
200
- print(f"\n🟢 GPU预计时间:")
201
- print(f" - 实体提取: {entity_extraction_time/60:.1f}分钟 (相同)")
202
- print(f" - 向量嵌入: {(entities_count / (len(test_texts)/gpu_emb_time))/60:.1f}分钟")
203
- print(f" - 总计: {gpu_total_time/60:.1f}分钟")
204
-
205
- total_speedup = cpu_total_time / gpu_total_time
206
- time_saved = (cpu_total_time - gpu_total_time) / 60
207
-
208
- print(f"\n🚀 整体加速: {total_speedup:.1f}x")
209
- print(f"⏱️ 节省时间: {time_saved:.1f}分钟")
210
-
211
- # ============================================================
212
- # 5️⃣ GPU显存监控
213
- # ============================================================
214
- if cuda_available:
215
- print("\n" + "="*70)
216
- print("💾 步骤5: GPU显存使用监控")
217
- print("="*70)
218
-
219
- allocated = torch.cuda.memory_allocated(0) / (1024**3)
220
- reserved = torch.cuda.memory_reserved(0) / (1024**3)
221
- total = torch.cuda.get_device_properties(0).total_memory / (1024**3)
222
-
223
- print(f"\n 已分配: {allocated:.2f} GB")
224
- print(f" 已保留: {reserved:.2f} GB")
225
- print(f" 总显存: {total:.2f} GB")
226
- print(f" 使用率: {(allocated/total)*100:.1f}%")
227
-
228
- # ============================================================
229
- # 6️⃣ 性能总结
230
- # ============================================================
231
- print("\n" + "="*70)
232
- print("📈 最终性能报告")
233
- print("="*70)
234
-
235
- print("\n🖥️ 硬件配置:")
236
- if cuda_available:
237
- print(f" GPU: {torch.cuda.get_device_name(0)}")
238
- print(f" 显存: {torch.cuda.get_device_properties(0).total_memory / (1024**3):.1f} GB")
239
- print(f" CUDA: {torch.version.cuda}")
240
- else:
241
- print(" ⚠️ GPU未启用")
242
-
243
- print(f"\n⚡ 性能测试结果:")
244
- print(f" 矩阵运算加速: {matrix_speedup:.1f}x")
245
- if emb_speedup:
246
- print(f" 文本嵌入加速: {emb_speedup:.1f}x")
247
- if cuda_available:
248
- print(f" GraphRAG整体加速: {total_speedup:.1f}x")
249
-
250
- print("\n💡 结论和建议:")
251
- if cuda_available:
252
- print(" ✅ GPU性能测试成功!")
253
- print(" ✅ 强烈建议在Colab GPU环境运行GraphRAG")
254
- print(f" ✅ 预计可节省 {time_saved:.0f}+ 分钟的索引构建时间")
255
- print("\n📚 下一步:")
256
- print(" 1. 上传adaptive_RAG项目文件到Colab")
257
- print(" 2. 运行 main_graphrag.py 构建完整知识图谱")
258
- print(" 3. 下载结果到本地使用")
259
- else:
260
- print(" ⚠️ 请启用GPU以获得最佳性能")
261
- print(" ⚠️ 路径: 运行时 → 更改运行时类型 → GPU")
262
-
263
- print("\n" + "="*70)
264
- print("✅ 测试完成! 感谢使用GraphRAG GPU测试工具")
265
- print("="*70)
266
-
267
- # ============================================================
268
- # 7️⃣ 可选: 显示nvidia-smi
269
- # ============================================================
270
- if cuda_available:
271
- print("\n📊 nvidia-smi 详细信息:")
272
- print("="*70)
273
- import subprocess
274
- try:
275
- result = subprocess.run(['nvidia-smi'], capture_output=True, text=True)
276
- print(result.stdout)
277
- except:
278
- print("⚠️ 无法执行nvidia-smi命令")