DeepSparse 项目使用教程
1. 项目介绍
DeepSparse 是一个针对 CPU 的深度学习推理运行时,特别优化了稀疏性(sparsity)以加速神经网络的推理过程。通过与 SparseML(我们的优化库,用于模型剪枝和量化)结合,DeepSparse 能够在 CPU 硬件上提供卓越的推理性能。
主要特点
- 稀疏性优化:利用稀疏性加速推理过程。
- 支持多种模型:包括 BERT、ViT、ResNet、EfficientNet、YOLOv5/8 等。
- 支持 LLM:最新支持大型语言模型(LLM)的推理。
2. 项目快速启动
安装
首先,确保你的系统满足以下要求:
- 硬件:x86 AVX2, AVX-512, AVX-512 VNNI 和 ARM v8.2+
- 操作系统:Linux
- Python:3.8-3.11
- ONNX 版本:1.5.0-1.15.0,opset 版本 11 或更高
安装 DeepSparse:
pip install deepsparse
运行推理
以下是一个简单的示例,展示如何使用 DeepSparse 进行文本生成:
from deepsparse import TextGeneration
# 初始化模型
pipeline = TextGeneration(model="zoo:mpt-7b-dolly_mpt_pretrain-pruned50_quantized")
# 定义输入提示
prompt = """
Below is an instruction that describes a task, Write a response that appropriately completes the request.
### Instruction: what is sparsity?
### Response:
"""
# 运行推理
output = pipeline(prompt, max_new_tokens=75)
print(output.generations[0].text)
3. 应用案例和最佳实践
案例1:情感分析
使用 DeepSparse 进行情感分析,可以快速部署一个高效的情感分析模型:
from deepsparse import Pipeline
# 下载并设置情感分析管道
sentiment_analysis_pipeline = Pipeline.create(
task="sentiment-analysis",
model_path="zoo:nlp/sentiment_analysis/obert-base/pytorch/huggingface/sst2/pruned90_quant-none"
)
# 运行推理
prediction = sentiment_analysis_pipeline("I love using DeepSparse Pipelines")
print(prediction)
案例2:计算机视觉
DeepSparse 也支持计算机视觉任务,例如使用 YOLOv5 进行目标检测:
from deepsparse import Pipeline
# 下载并设置目标检测管道
object_detection_pipeline = Pipeline.create(
task="object-detection",
model_path="zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned85_quant-none"
)
# 运行推理
prediction = object_detection_pipeline("path/to/image.jpg")
print(prediction)
4. 典型生态项目
SparseML
SparseML 是 Neural Magic 开发的优化库,用于模型的剪枝和量化。它与 DeepSparse 紧密结合,帮助用户在推理过程中进一步优化模型性能。
SparseZoo
SparseZoo 是 Neural Magic 提供的优化模型库,包含了许多经过优化的模型,用户可以直接下载并使用这些模型进行推理。
Hugging Face
DeepSparse 与 Hugging Face 集成,用户可以直接使用 Hugging Face 上的模型进行推理,无需额外转换。
通过这些生态项目,DeepSparse 为用户提供了完整的解决方案,从模型优化到推理部署,都能高效完成。