File size: 22,540 Bytes
a96e05b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 | # 使用示例
本文档提供 HOS Model Optimizer 的详细使用示例,涵盖量化、推理、训练、部署等核心功能。
## 目录
- [量化示例](#量化示例)
- [推理示例](#推理示例)
- [训练示例](#训练示例)
- [部署示例](#部署示例)
- [评测示例](#评测示例)
- [性能测试示例](#性能测试示例)
- [8GB VRAM 场景优化示例](#8gb-vram-场景优化示例)
---
## 量化示例
### GGUF 量化(推荐 8GB VRAM 场景)
GGUF 是 llama.cpp 的原生格式,支持 CPU+GPU 混合推理,是 8GB VRAM 场景的首选。
```bash
# 基础 GGUF 量化(Q4_K_M,平衡速度和精度)
hos-quantize --method gguf --model ./model --output ./model.gguf
# 指定量化类型
hos-quantize --method gguf --model ./model --output ./model-q4.gguf --quant-type Q4_K_M
hos-quantize --method gguf --model ./model --output ./model-q5.gguf --quant-type Q5_K_M
hos-quantize --method gguf --model ./model --output ./model-q8.gguf --quant-type Q8_0
# 指定 llama.cpp 路径
hos-quantize --method gguf --model ./model --output ./model.gguf \
--llama-cpp-path /path/to/llama.cpp
```
**Python API 示例**:
```python
from hos_optimizer.quantize import quantize_gguf
# GGUF 量化
output_path = quantize_gguf(
model_path="./model",
output_path="./model.gguf",
quant_type="Q4_K_M",
llama_cpp_path=None # 从 PATH 查找
)
print(f"量化完成: {output_path}")
```
### AWQ 量化
AWQ(Activation-aware Weight Quantization)通过保护显著权重通道实现高精度 4-bit 量化。
```bash
# AWQ 4-bit 量化
hos-quantize --method awq --bits 4 --model ./model --output ./model-awq
# 自定义分组大小
hos-quantize --method awq --bits 4 --group-size 128 --model ./model --output ./model-awq
```
**Python API 示例**:
```python
from hos_optimizer.quantize import quantize_awq
# AWQ 量化
output_path = quantize_awq(
model_path="./model",
output_path="./model-awq",
bits=4,
group_size=128
)
```
### GPTQ 量化
GPTQ 基于 Optimal Brain Quantization 框架,通过逐层量化和误差补偿实现高精度。
```bash
# GPTQ 4-bit 量化
hos-quantize --method gptq --bits 4 --model ./model --output ./model-gptq
# GPTQ 8-bit 量化(精度更高)
hos-quantize --method gptq --bits 8 --model ./model --output ./model-gptq-8bit
# 自定义参数
hos-quantize --method gptq --bits 4 --group-size 128 --model ./model --output ./model-gptq
```
**Python API 示例**:
```python
from hos_optimizer.quantize import quantize_gptq
# GPTQ 量化
output_path = quantize_gptq(
model_path="./model",
output_path="./model-gptq",
bits=4,
group_size=128,
desc_act=False
)
```
### 量化质量评估
评估量化后模型的 PPL(Perplexity),用于选择最佳量化方案。
```bash
# 评估量化模型 PPL
hos-quantize --method evaluate --model ./model-awq
# 指定评估数据集和样本数
hos-quantize --method evaluate --model ./model-gptq
```
**Python API 示例**:
```python
from hos_optimizer.quantize import evaluate_perplexity
# 评估 PPL
ppl = evaluate_perplexity(
model_path="./model-awq",
dataset="wikitext",
max_samples=100,
stride=512
)
print(f"PPL: {ppl:.2f}")
```
### 格式转换
在不同量化格式之间转换。
```bash
# HuggingFace -> GGUF
hos-quantize --method convert --from hf --to gguf --model ./model --output ./model.gguf
# HuggingFace -> AWQ
hos-quantize --method convert --from hf --to awq --model ./model --output ./model-awq
# HuggingFace -> GPTQ
hos-quantize --method convert --from hf --to gptq --model ./model --output ./model-gptq
```
**Python API 示例**:
```python
from hos_optimizer.quantize import convert_format
# 格式转换
output_path = convert_format(
model_path="./model",
output_path="./model-awq",
from_format="hf",
to_format="awq",
bits=4
)
```
---
## 推理示例
### llama-cpp 推理(GGUF 格式)
llama-cpp 是 8GB VRAM 场景的首选后端,支持 CPU+GPU 混合推理。
```bash
# 单次推理
hos-infer --backend llama-cpp --model ./model.gguf --prompt "什么是SQL注入?"
# 启动 API 服务
hos-infer --backend llama-cpp --model ./model.gguf --serve --port 8080
# 交互模式
hos-infer --backend llama-cpp --model ./model.gguf --chat
# 自定义参数
hos-infer --backend llama-cpp --model ./model.gguf --prompt "你好" \
--max-tokens 256 --temperature 0.7 --top-p 0.9
```
**Python API 示例**:
```python
from hos_optimizer.inference import UnifiedInferenceEngine
# 创建引擎(llama-cpp 后端)
engine = UnifiedInferenceEngine(
model_path="./model.gguf",
backend="llama-cpp",
n_gpu_layers=-1, # 全部 offload 到 GPU
n_ctx=512,
n_batch=512
)
# 单次推理
result = engine.generate(
prompt="什么是SQL注入?",
max_tokens=256,
temperature=0.7
)
print(result.text)
# 批量推理
prompts = ["问题1", "问题2", "问题3"]
results = engine.generate_batch(prompts, max_tokens=128)
for r in results:
print(r.text)
# 获取性能统计
stats = engine.get_stats()
print(stats.summary())
# 关闭引擎
engine.shutdown()
```
### vLLM 推理(高吞吐场景)
vLLM 使用 PagedAttention 和 Continuous Batching,适合高吞吐场景。
```bash
# 单次推理
hos-infer --backend vllm --model ./model-awq --prompt "什么是XSS攻击?"
# 启动 API 服务
hos-infer --backend vllm --model ./model-awq --serve --port 8000
# 自定义参数
hos-infer --backend vllm --model ./model-awq --prompt "你好" \
--gpu-memory-utilization 0.9 --max-model-len 512
```
**Python API 示例**:
```python
from hos_optimizer.inference import UnifiedInferenceEngine
# 创建引擎(vLLM 后端)
engine = UnifiedInferenceEngine(
model_path="./model-awq",
backend="vllm",
gpu_memory_utilization=0.9,
max_model_len=512,
max_num_seqs=128,
dtype="float16"
)
# 单次推理
result = engine.generate(
prompt="什么是XSS攻击?",
max_tokens=256,
temperature=0.7
)
print(result.text)
# 批量推理(利用 Continuous Batching)
prompts = ["问题1", "问题2", "问题3"]
results = engine.generate_batch(prompts, max_tokens=128)
# 性能统计
stats = engine.get_stats()
print(f"吞吐量: {stats.throughput_tokens_per_s:.1f} tokens/s")
engine.shutdown()
```
### SGLang 推理(结构化生成)
SGLang 支持 RadixAttention 和 JSON Schema 约束生成,适合多轮对话和结构化输出。
```bash
# 单次推理
hos-infer --backend sglang --model ./model-awq --prompt "什么是渗透测试?"
# 启动 API 服务
hos-infer --backend sglang --model ./model-awq --serve --port 30000
# 交互模式
hos-infer --backend sglang --model ./model-awq --chat
```
**Python API 示例**:
```python
from hos_optimizer.inference import UnifiedInferenceEngine
# 创建引擎(SGLang 后端)
engine = UnifiedInferenceEngine(
model_path="./model-awq",
backend="sglang",
mem_fraction_static=0.9,
context_length=512,
tp_size=1
)
# 单次推理
result = engine.generate(
prompt="什么是渗透测试?",
max_tokens=256,
temperature=0.7
)
print(result.text)
# 约束生成(JSON Schema)
json_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name", "age"]
}
result = engine.generate(
prompt="生成一个用户信息",
json_schema=json_schema,
max_tokens=128
)
print(result.text) # 输出符合 JSON Schema
# 批量推理(利用 RadixAttention)
prompts = [
"系统提示:你是助手。\n用户:你好",
"系统提示:你是助手。\n用户:再见"
]
results = engine.generate_batch(prompts) # 共享前缀会自动缓存
engine.shutdown()
```
### 自动选择后端
不指定后端时,系统会自动检测最优后端。
```bash
# 自动选择后端
hos-infer --model ./model --prompt "你好"
# 性能基准测试
hos-infer --model ./model --benchmark
```
**Python API 示例**:
```python
from hos_optimizer.inference import UnifiedInferenceEngine
# 自动选择后端
engine = UnifiedInferenceEngine(
model_path="./model",
backend=None, # 自动检测
auto_load=True
)
print(f"使用的后端: {engine.backend_name}")
result = engine.generate("你好")
print(result.text)
engine.shutdown()
```
---
## 训练示例
### QLoRA 训练(8GB VRAM 可用)
QLoRA 使用 4-bit 量化 + LoRA,大幅降低显存需求。
```bash
# 基础 QLoRA 训练
hos-train --model Qwen/Qwen2.5-0.5B --dataset ./data.json --method qlora
# 自定义训练参数
hos-train --model ./model --dataset ./data.json --method qlora \
--epochs 3 --batch-size 2 --lr 2e-4 \
--lora-rank 16 --lora-alpha 32 \
--max-seq-length 512
# 训练后自动合并
hos-train --model ./model --dataset ./data.json --method qlora --merge
# 指定数据格式
hos-train --model ./model --dataset ./data.json --method qlora \
--format alpaca # 或 sharegpt
```
**Python API 示例**:
```python
from hos_optimizer.train import TrainingConfig, train
# 创建训练配置
config = TrainingConfig(
model_name_or_path="Qwen/Qwen2.5-0.5B",
dataset_path="./data.json",
dataset_format="alpaca",
finetuning_type="qlora",
use_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
lora_rank=16,
lora_alpha=32,
lora_dropout=0.05,
num_train_epochs=3,
per_device_train_batch_size=2,
gradient_accumulation_steps=8,
learning_rate=2e-4,
max_seq_length=512,
output_dir="./output",
gradient_checkpointing=True,
use_unsloth=True # 如果可用
)
# 执行训练
train(config)
```
### LoRA 训练
LoRA 使用全精度 + LoRA,精度更高但显存需求更大。
```bash
# LoRA 训练
hos-train --model ./model --dataset ./data.json --method lora
# 自定义参数
hos-train --model ./model --dataset ./data.json --method lora \
--epochs 3 --batch-size 1 --lr 1e-4 \
--lora-rank 8 --lora-alpha 16
```
**Python API 示例**:
```python
from hos_optimizer.train import TrainingConfig, train
# LoRA 配置
config = TrainingConfig(
model_name_or_path="./model",
dataset_path="./data.json",
finetuning_type="lora",
use_4bit=False, # 不使用 4-bit
lora_rank=8,
lora_alpha=16,
num_train_epochs=3,
per_device_train_batch_size=1,
learning_rate=1e-4,
output_dir="./output"
)
train(config)
```
### 模型合并
将 LoRA adapter 合并到基础模型。
```bash
# 合并模型
hos-merge --base-model ./base --adapter ./adapter --output ./merged
```
**Python API 示例**:
```python
from hos_optimizer.train import merge_model
# 合并模型
merge_model(
base_model_path="./base",
adapter_path="./adapter",
output_path="./merged",
trust_remote_code=True
)
```
### 数据集格式
#### Alpaca 格式
```json
[
{
"instruction": "什么是SQL注入?",
"input": "",
"output": "SQL注入是一种常见的Web安全漏洞..."
},
{
"instruction": "解释XSS攻击",
"input": "请举例说明",
"output": "XSS(跨站脚本攻击)是..."
}
]
```
#### ShareGPT 格式
```json
[
{
"conversations": [
{"from": "human", "value": "你好"},
{"from": "gpt", "value": "你好!有什么可以帮助你的吗?"}
]
}
]
```
---
## 部署示例
### 一键部署
自动检测硬件并选择最优配置。
```bash
# 部署 7B 模型
hos-deploy --model ./model.gguf --model-size 7.0
# 指定使用场景
hos-deploy --model ./model.gguf --model-size 7.0 --use-case general
hos-deploy --model ./model.gguf --model-size 7.0 --use-case high_concurrency
hos-deploy --model ./model.gguf --model-size 7.0 --use-case multi_turn
# 自定义端口
hos-deploy --model ./model.gguf --model-size 7.0 --port 8000
# 仅生成配置,不启动服务
hos-deploy --model ./model.gguf --model-size 7.0 --no-auto-start
```
**Python API 示例**:
```python
from hos_optimizer.deploy import deploy_model
# 一键部署
launcher = deploy_model(
model_path="./model.gguf",
model_size_b=7.0,
use_case="general",
host="0.0.0.0",
port=8000,
auto_start=True
)
if launcher:
print("服务已启动")
# 等待用户中断
try:
launcher.process.wait()
except KeyboardInterrupt:
launcher.stop()
```
### 手动配置部署
```python
from hos_optimizer.deploy import HardwareDetector, ConfigSelector, ServiceLauncher
# 1. 检测硬件
hardware = HardwareDetector.get_hardware_info()
print(f"GPU: {hardware.gpu_name}, VRAM: {hardware.gpu_memory_gb:.1f}GB")
# 2. 选择配置
config = ConfigSelector.select_config(
hardware=hardware,
model_size_b=7.0,
use_case="general"
)
print(f"推荐配置: {config.recommended_for}")
# 3. 启动服务
launcher = ServiceLauncher(
config=config,
model_path="./model.gguf",
host="0.0.0.0",
port=8000
)
if launcher.start():
print("服务已启动")
# 健康检查
from hos_optimizer.deploy import HealthChecker
checker = HealthChecker(host="localhost", port=8000)
if checker.check_model_loaded(timeout=300):
print("模型加载完成")
```
---
## 评测示例
### 单模型评测
使用 `hos-evaluate` 命令对模型进行质量评测。
```bash
# 基础评测(默认使用 BLEU 和 ROUGE 指标)
hos-evaluate --model ./model --dataset ./test.json
# 指定评测指标
hos-evaluate --model ./model --dataset ./test.json \
--metrics bleu rouge f1 exact_match
# 指定输出格式为 Markdown
hos-evaluate --model ./model --dataset ./test.json \
--metrics bleu rouge --output result.md
# 限制评测样本数
hos-evaluate --model ./model --dataset ./test.json \
--max-samples 100
# 使用 4-bit 量化加载(节省显存)
hos-evaluate --model ./model --dataset ./test.json \
--load-in-4bit --metrics bleu rouge
# 指定数据集格式
hos-evaluate --model ./model --dataset ./test.json \
--format alpaca --metrics bleu
# 自定义生成参数
hos-evaluate --model ./model --dataset ./test.json \
--max-new-tokens 512 --temperature 0.8 --top-p 0.95
```
**Python API 示例**:
```python
from hos_optimizer.evaluate import EvaluationConfig, evaluate_model
# 创建评测配置
config = EvaluationConfig(
model_path="./model",
dataset_path="./test.json",
metrics=["bleu", "rouge", "f1"],
max_samples=100,
max_new_tokens=256,
temperature=0.7,
output_format="json",
output_path="./evaluation_result.json"
)
# 执行评测
result = evaluate_model(config)
# 查看结果
print(f"BLEU: {result.metrics_summary.get('bleu', 0):.2f}")
print(f"ROUGE: {result.metrics_summary.get('rouge', 0):.2f}")
print(f"F1: {result.metrics_summary.get('f1', 0):.2f}")
print(f"评测样本数: {result.total_samples}")
print(f"耗时: {result.elapsed_seconds:.2f}s")
```
### 多模型对比评测
对比多个模型在相同数据集上的表现。
```bash
# 对比两个模型
hos-evaluate --model ./model_v1 --model ./model_v2 \
--dataset ./test.json --metrics bleu rouge f1 \
--output comparison.md
# 对比三个模型
hos-evaluate --model ./base_model --model ./lora_model --model ./merged_model \
--dataset ./test.json --metrics bleu rouge \
--output-format markdown --output comparison.md
```
**Python API 示例**:
```python
from hos_optimizer.evaluate import EvaluationConfig, compare_models
# 创建评测配置
config = EvaluationConfig(
dataset_path="./test.json",
metrics=["bleu", "rouge", "f1", "exact_match"],
max_samples=50,
output_format="markdown",
output_path="./model_comparison.md"
)
# 执行多模型对比
model_paths = ["./model_v1", "./model_v2", "./model_v3"]
results = compare_models(model_paths, config)
# 分析结果
print("\n=== 模型对比结果 ===")
for result in results:
print(f"\n模型: {result.model_path}")
for metric, score in result.metrics_summary.items():
print(f" {metric}: {score:.2f}")
```
### 评测数据集格式
评测模块支持三种数据格式,会自动检测:
#### Alpaca 格式
```json
[
{
"instruction": "什么是SQL注入?",
"input": "",
"output": "SQL注入是一种常见的Web安全漏洞,攻击者通过在应用程序中注入恶意SQL代码..."
},
{
"instruction": "解释XSS攻击",
"input": "请举例说明",
"output": "XSS(跨站脚本攻击)是一种注入攻击,攻击者向Web页面注入恶意脚本..."
}
]
```
#### ShareGPT 格式
```json
[
{
"conversations": [
{"from": "human", "value": "什么是渗透测试?"},
{"from": "gpt", "value": "渗透测试是一种模拟恶意攻击者的方法来评估计算机系统或网络安全性..."}
]
}
]
```
#### Messages 格式
```json
[
{
"messages": [
{"role": "user", "content": "如何防范DDoS攻击?"},
{"role": "assistant", "content": "防范DDoS攻击需要多层次的防御策略..."}
]
}
]
```
### 自定义评测指标
```python
from hos_optimizer.evaluate import EvaluationConfig, EvaluationEngine, DatasetLoader
# 加载数据集
loader = DatasetLoader()
samples = loader.load("./test.json", dataset_format="alpaca")
# 创建评测引擎
config = EvaluationConfig(
model_path="./model",
metrics=["bleu", "rouge"],
max_new_tokens=256
)
engine = EvaluationEngine(config)
engine.load_model()
# 生成预测
predictions = engine.generate_predictions(samples)
references = [ref for _, ref in samples]
# 计算指标
metrics = engine.compute_metrics(predictions, references)
# 自定义后处理
print("评测完成:")
for metric_name, score in metrics.items():
print(f" {metric_name}: {score:.4f}")
engine.shutdown()
```
### 评测结果分析
```python
import json
from pathlib import Path
# 加载评测结果
with open("./evaluation_result.json", "r", encoding="utf-8") as f:
result = json.load(f)
# 分析样本级别的评测结果
print(f"总样本数: {result['total_samples']}")
print(f"平均指标:")
for metric, score in result['metrics_summary'].items():
print(f" {metric}: {score:.4f}")
# 找出表现最好和最差的样本
sample_results = result['sample_results']
if sample_results:
# 按综合得分排序
for sample in sorted(sample_results, key=lambda x: x['metrics'].get('bleu', 0), reverse=True)[:5]:
print(f"\n最佳样本 #{sample['index']}:")
print(f" Prompt: {sample['prompt'][:100]}...")
print(f" BLEU: {sample['metrics'].get('bleu', 0):.4f}")
```
---
## 性能测试示例
### 推理性能基准测试
```bash
# 运行基准测试
hos-infer --model ./model --benchmark
# 指定后端
hos-infer --backend vllm --model ./model --benchmark
```
**Python API 示例**:
```python
from hos_optimizer.inference import UnifiedInferenceEngine, run_benchmark
# 创建引擎
engine = UnifiedInferenceEngine(
model_path="./model",
backend="vllm"
)
# 运行基准测试
run_benchmark(
engine=engine,
num_warmup=2, # 预热次数
num_runs=5 # 测试次数
)
# 获取性能统计
stats = engine.get_stats()
print(stats.summary())
engine.shutdown()
```
### 显存监控
```python
from hos_optimizer.inference import get_gpu_memory_usage_mb, get_total_gpu_memory_mb
# 获取当前显存占用
used_mb = get_gpu_memory_usage_mb()
total_mb = get_total_gpu_memory_mb()
print(f"显存占用: {used_mb:.1f} / {total_mb:.1f} MB")
print(f"使用率: {used_mb / total_mb * 100:.1f}%")
```
---
## 8GB VRAM 场景优化示例
### 推理优化
```python
from hos_optimizer.config import ConfigManager
# 生成 8GB VRAM 最优配置
manager = ConfigManager()
config = manager.generate_optimal_config(
scenario="inference_7b",
model_path="./model",
vram_gb=8.0
)
print(f"推荐后端: {config['backend']}")
print(f"上下文长度: {config['inference']['n_ctx']}")
print(f"预期性能: {config['expected_performance']['tokens_per_second']} tokens/s")
```
### 训练优化
```python
from hos_optimizer.train import TrainingConfig
# 8GB VRAM 训练配置
config = TrainingConfig(
model_name_or_path="./model",
dataset_path="./data.json",
finetuning_type="qlora",
use_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
lora_rank=8, # 降低 rank 节省显存
lora_alpha=16,
num_train_epochs=3,
per_device_train_batch_size=1, # 小批次
gradient_accumulation_steps=32, # 大累积步数
learning_rate=1e-4,
max_seq_length=512, # 限制序列长度
gradient_checkpointing=True, # 启用梯度检查点
optim="paged_adamw_32bit", # 分页优化器
output_dir="./output"
)
```
### 配置模板
```bash
# 列出所有配置模板
hos-config --list-templates
# 导出 8GB VRAM 推理配置
hos-config --export-template llama_cpp --output ./llama_cpp_8gb.yaml
# 生成特定场景配置
hos-config --generate --scenario inference_7b --model-path ./model --vram 8.0
# 自动生成最优配置
hos-config --auto --model-size 7.0 --task inference --vram 8.0
```
### 实际场景示例
#### 场景 1:8GB VRAM + 7B 模型推理
```bash
# 1. 量化模型
hos-quantize --method gguf --model ./model --output ./model-q4.gguf --quant-type Q4_K_M
# 2. 推理测试
hos-infer --backend llama-cpp --model ./model-q4.gguf --prompt "你好" \
--n-gpu-layers -1 --n-ctx 512
# 3. 启动服务
hos-deploy --model ./model-q4.gguf --model-size 7.0
```
#### 场景 2:8GB VRAM + 7B 模型训练
```bash
# QLoRA 训练
hos-train --model Qwen/Qwen2.5-0.5B --dataset ./data.json --method qlora \
--epochs 3 --batch-size 1 --grad-accum 32 \
--lora-rank 8 --lora-alpha 16 \
--max-seq-length 512 --lr 1e-4
```
#### 场景 3:高吞吐服务部署
```bash
# 使用 vLLM 后端
hos-deploy --model ./model-awq --model-size 7.0 --use-case high_concurrency
# 或手动配置
hos-infer --backend vllm --model ./model-awq --serve --port 8000 \
--gpu-memory-utilization 0.9 --max-model-len 512 --max-tokens 256
```
#### 场景 4:多轮对话优化
```bash
# 使用 SGLang 后端(RadixAttention)
hos-deploy --model ./model-awq --model-size 7.0 --use-case multi_turn
# 或手动配置
hos-infer --backend sglang --model ./model-awq --serve --port 30000 \
--mem-fraction-static 0.9 --context-length 1024
```
---
## 更多资源
- [API 文档](API.md) - 详细 API 参考
- [架构文档](docs/architecture.md) - 系统设计说明
- [安装指南](INSTALL.md) - 安装和配置
|