通义QwQ-32B+Milvus,消费级显卡布满血大模型与RAG的时代来了!

前言

最近,通义开源的QwQ-32B模型可谓是火的一塌糊涂。

作为一个中型推理模型,QwQ-32B只有320亿参数,但却在多个基准测试中展现出优秀的推理能力,几乎直逼满血版DeepSeek R1,在数学计算、写作与代码编程方面的表现更是相当不错。

最重要的是,QwQ-32B不仅性能强大,还极其“亲民”,它体积小、推理快,支持消费级显卡部署,像RTX 4090这样的显卡就能轻松运行,非常适合普通个人开发者或者资源不足的科研党上手学习。

不过,由于QwQ-32B采用的是密集模型,相比DeepSeek R1,在长文本复杂推理上,经常会出现无法识别前面内容,或者幻觉问题

因此,在本地场景中,基于QwQ-32B部署RAG就成了解决这美中不足的最强外挂。

接下来,在本篇文章中,我们会基于Ollama开源平台,手把手向大家展示如何利用QwQ-32B和Milvus高效、安全地构建RAG(检索增强生成)系统。

01

选型思路

(1)QwQ-32B VS DeepSeek R1如何选择

同为主打推理的大模型,DeepSeek-R1的架构为MoE结构,QwQ-32B则属于典型的密集模型。

通常来说,MoE模型更加适合知识密集型场景,例如知识问答系统、信息检索等,以及大规模数据处理,例如在处理大规模文本数据、图像数据时,MoE模型可以通过不同专家处理不同的数据子集,提高处理效率。

但MoE庞大的参数量决定了,部署满血大模型需要在云端或者自有服务器资源上运行。

而密集模型体积小,计算成本高,更适合需要深度连贯推理的场景,例如复杂的逻辑推理任务、深度阅读理解等,以及复杂算法设计等对实时性要求不高的场景。最大的优点在于非常适合本地部署,但有时候,也会出现废话过多的情况。

对比维度密集模型(QwQ-32B)MoE模型(DeepSeek-R1)
优点训练难度相对低,过程简单直接推理连贯性好,所有神经元都参与计算和推理,能整体把握上下文信息计算效率高,推理时只需激活部分专家模型容量大,可通过增加专家数量扩展
缺点计算成本高,训练和推理需大量计算资源和内存模型容量扩展受限,易过拟合,存储部署成本高训练复杂,需训练门控网络,考虑专家负载平衡存在路由开销,门控网络路由选择有额外计算和时间消耗

密集模型和 MoE 模型各有其独特的优势和局限性,不存在绝对的优劣之分。在实际应用中,我们需要根据具体的任务需求、数据特点、计算资源和预算等因素来选择合适的模型架构。

不过,在我看来,未来的发展趋势可能是将两者的优势相结合,例如在一些复杂的任务中,可以先使用 MoE 模型进行初步的知识检索和粗粒度的处理,然后再利用密集模型进行深度的推理和细化,以达到更好的性能。

(2)向量数据库选型

考虑到QwQ-32B容易出现幻觉的问题,我们可以在其本地部署过程中,引入Milvus 开源向量数据库。Milvus 专为存储和查询高维向量(如 XLNet 生成的向量)而生,能够处理数百万乃至数十亿级的向量数据,并支持混合检索、全文检索等一众特性需求,是 GitHub 上最受欢迎的向量数据库。

(3)部署平台选型

本次部署,平台方面,我们可以考虑采用Ollama开源平台。作为一个为专大型语言模型(LLM)提供本地运行和管理的解决方案,Ollama可以简化部署和管理流程,允许用户通过简单的命令行工具和Docker集成快速部署模型,同时支持Modelfile管理来简化模型版本控制和复用。其次,它提供了丰富的模型库,并具备跨平台与硬件适配的特点,支持macOS、Linux、Windows及Docker容器部署,并能自动检测GPU并优先启用加速。此外,Ollama提供了开发者友好的工具,如REST API和Python SDK,方便将模型集成到应用中。

02

准备工作

环境

! pip install pymilvus ollama

数据集准备

我们可以使用Milvus文档2.4. x中的FAQ页面作为RAG中的私有知识,这是构建一个基础RAG的良好数据源。

下载zip文件并将文档解压缩到文件夹milvus_docs

! wget https://github.com/milvus-io/milvus-docs/releases/download/v2.4.6-preview/milvus_docs_2.4.x_en.zip! unzip -q milvus_docs_2.4.x_en.zip -d milvus_docs

我们从文件夹milvus_docs/en/faq中加载所有markdown文件,对于每个文档,我们只需用“#”来分隔文件中的内容,就可以大致分隔markdown文件各个主要部分的内容。

from glob import glob
text_lines = []
for file_path in glob("milvus_docs/en/faq/*.md", recursive=True):    with open(file_path, "r") as file:        file_text = file.read()
    text_lines += file_text.split("# ")

准备 LLM 和Embedding模型

Ollama支持基于LLM的任务和Embedding的多种模型,从而可以轻松开发检索增强生成(RAG)应用程序。对于这种设置:

  • 我们将使用QwQ(32B)作为文本生成任务的LLM。
  • 对于Embedding模型,我们将使用mxbay-embed-size,这是一个针对语义相似性优化的334M参数模型。

在开始之前,确保两个模型都被下载到本地:

! ollama pull mxbai-embed-large

! ollama pull qwq

准备好这些模型后,我们可以开始LLM生成和基于Embedding的检索工作流程。

生成测试embedding并打印其维度和前几个元素。

import ollamafrom ollama import Client
ollama_client = Client(host="http://localhost:11434")def emb_text(text):    response = ollama_client.embeddings(model="mxbai-embed-large", prompt=text)    return response["embedding"]#testtest_embedding = emb_text("This is a test")embedding_dim = len(test_embedding)print(embedding_dim)print(test_embedding[:10])


1024[0.23217937350273132, 0.42540550231933594, 0.19742339849472046, 0.4618139863014221, -0.46017369627952576, -0.14087969064712524, -0.18214142322540283, -0.07724273949861526, 0.40015509724617004, 0.8331164121627808]
将数据加载到Milvus
创建集合
from pymilvus import MilvusClient
milvus_client = MilvusClient(uri="./milvus_demo.db")
collection_name = "my_rag_collection"

关于MilvusClient的参数设置:

  • 将URI设置为本地文件(例如…/milvus.db)是最便捷的方法,因为它会自动使用Milvus Lite将所有数据存储在该文件中。
  • 如果你有大规模数据,可以在Docker或Kubernetes上搭建性能更强的Milvus服务器。在这种情况下,请使用服务器的URI(例如http://localhost:19530)作为你的URI。
  • 如果你想使用Zilliz Cloud(Milvus的全托管云服务),请调整URI和令牌,它们分别对应Zilliz Cloud中的公共端点(Public Endpoint)和API密钥(Api key)。

检查集合是否已经存在,如果存在则将其删除。

if milvus_client.has_collection(collection_name):    milvus_client.drop_collection(collection_name)

创建一个具有指定参数的新集合。

如果未指定任何字段信息,Milvus将自动创建一个默认的ID字段作为主键,以及一个向量字段用于存储向量数据。一个预留的JSON字段用于存储未在模式中定义的字段及其值。

milvus_client.create_collection(    collection_name=collection_name,    dimension=embedding_dim,    metric_type="IP",  # Inner product distance    consistency_level="Strong",  # Strong consistency level)

插入数据

逐行遍历文本,创建嵌入向量,然后将数据插入Milvus。

下面是一个新的字段text,它是集合中的一个未定义的字段。它将自动创建一个对应的text字段(实际上它底层是由保留的JSON动态字段实现的) ,你不用关心其底层实现。

from tqdm import tqdm
data = []
for i, line in enumerate(tqdm(text_lines, desc="Creating embeddings")):    data.append({"id": i, "vector": emb_text(line), "text": line})
milvus_client.insert(collection_name=collection_name, data=data)


Creating embeddings: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████| 72/72 [00:06<00:00, 11.86it/s]
{'insert_count': 72, 'ids': [0, 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], 'cost': 0}

03

构建 RAG

检索数据

我们来指定一个关于Milvus的常见问题。

question = "How is data stored in milvus?"

在集合中搜索该问题,并检索语义上最匹配的前3个结果。

search_res = milvus_client.search(    collection_name=collection_name,    data=[        emb_text(question)    ],  # Use the `emb_text` function to convert the question to an embedding vector    limit=3,  # Return top 3 results    search_params={"metric_type": "IP", "params": {}},  # Inner product distance    output_fields=["text"],  # Return the text field)

我们来看看这个查询的搜索结果。

import json
retrieved_lines_with_distances = [    (res["entity"]["text"], res["distance"]) for res in search_res[0]]print(json.dumps(retrieved_lines_with_distances, indent=4))

[    [        " Where does Milvus store data?\n\nMilvus deals with two types of data, inserted data and metadata. \n\nInserted data, including vector data, scalar data, and collection-specific schema, are stored in persistent storage as incremental log. Milvus supports multiple object storage backends, including [MinIO](https://min.io/), [AWS S3](https://aws.amazon.com/s3/?nc1=h_ls), [Google Cloud Storage](https://cloud.google.com/storage?hl=en#object-storage-for-companies-of-all-sizes) (GCS), [Azure Blob Storage](https://azure.microsoft.com/en-us/products/storage/blobs), [Alibaba Cloud OSS](https://www.alibabacloud.com/product/object-storage-service), and [Tencent Cloud Object Storage](https://www.tencentcloud.com/products/cos) (COS).\n\nMetadata are generated within Milvus. Each Milvus module has its own metadata that are stored in etcd.\n\n###",        231.9922637939453    ],    [        "How does Milvus flush data?\n\nMilvus returns success when inserted data are loaded to the message queue. However, the data are not yet flushed to the disk. Then Milvus' data node writes the data in the message queue to persistent storage as incremental logs. If `flush()` is called, the data node is forced to write all data in the message queue to persistent storage immediately.\n\n###",        226.54090881347656    ],    [        "What is the maximum dataset size Milvus can handle?\n\n  \nTheoretically, the maximum dataset size Milvus can handle is determined by the hardware it is run on, specifically system memory and storage:\n\n- Milvus loads all specified collections and partitions into memory before running queries. Therefore, memory size determines the maximum amount of data Milvus can query.\n- When new entities and and collection-related schema (currently only MinIO is supported for data persistence) are added to Milvus, system storage determines the maximum allowable size of inserted data.\n\n###",        210.63682556152344    ]]

使用大型语言模型(LLM)构建检索增强生成(RAG)响应

将检索到的文档转换为字符串格式。

context = "\n".join(    [line_with_distance[0] for line_with_distance in retrieved_lines_with_distances])

为大语言模型提供系统提示(system prompt)和用户提示(user prompt)。这个提示是通过从Milvus检索到的文档生成的。

SYSTEM_PROMPT = """Human: You are an AI assistant. You are able to find answers to the questions from the contextual passage snippets provided."""USER_PROMPT = f"""Use the following pieces of information enclosed in <context> tags to provide an answer to the question enclosed in <question> tags.<context>{context}</context><question>{question}</question>"""

使用Ollama提供的QwQ(32B)模型,根据提示生成响应。

from ollama import chatfrom ollama import ChatResponse
response: ChatResponse = ollama_client.chat(    model="qwq",    messages=[        {"role": "system", "content": SYSTEM_PROMPT},        {"role": "user", "content": USER_PROMPT},    ],)print(response["message"]["content"])


<think>Okay, I need to answer the question "How is data stored in Milvus?" using the provided context. Let me start by reading through the context carefully.
First, looking at the first context section titled "Where does Milvus store data?". It mentions that Milvus handles two types of data: inserted data and metadata. 
Inserted data includes vectors, scalar data, and collection schema, stored as incremental logs in persistent storage. The supported backends are listed like MinIO, S3, GCS, etc. So I should note that inserted data goes to these object storages via incremental logs.
Then metadata is stored in etcd for each Milvus module. That's straightforward—metadata in etcd.
The second context about flushing data explains that data first goes to the message queue and then to persistent storage when flushed. But this might be more about the process rather than where it's stored, so maybe mention that insertion is into the message queue first before being written out.
Third section on maximum dataset size mentions hardware constraints: memory for queryable data and storage for persistence. This could relate to how data is managed in terms of memory vs disk. The user asked "how is data stored," which might include both where (like object stores, etcd) and the process (message queue then persistent logs).
Putting it all together, the answer should mention:
- Two types: inserted data and metadata.
For inserted data:- Stored as incremental logs in persistent storage using backends like MinIO, S3 etc.- Initially loaded into message queues, then written to disk. The flush() forces immediate writing if needed.
Metadata:- Stored in etcd for each module.
Also, the hardware part says that memory limits queryable data size and storage (like the object stores) limit total dataset size. So maybe mention these factors as part of how data is stored, considering capacity constraints.
I should structure this clearly, perhaps bullet points or sections on inserted vs metadata, then processes like flushing, and finally limitations based on hardware.</think>
Data in Milvus is stored in two main ways:  
1. **Inserted Data**:     - Includes vector data, scalar data, and collection schema.     - Stored as **incremental logs** in **persistent storage**, supported by object storage backends such as MinIO, AWS S3, Google Cloud Storage (GCS), Azure Blob Storage, Alibaba Cloud OSS, and Tencent Cloud Object Storage (COS).     - Initially loaded into a **message queue** when inserted. Milvus returns success upon insertion into the queue but does not immediately write to disk. A background process later writes this data to persistent storage. The `flush()` method can force immediate writing of all queued data to storage.  
2. **Metadata**:     - Generated internally by Milvus modules (e.g., collection configurations, partitions).     - Stored in **etcd**, a distributed key-value store.  
**Hardware Considerations**:  - **Memory**: The amount of data Milvus can query is limited by system memory since it loads specified collections/partitions into memory for queries.  - **Storage Capacity**: The maximum dataset size is constrained by the underlying storage backend (e.g., object storage), which stores all inserted data and schema incrementally.

以上就是一个基于Milvus和Ollama构建检索增强生成(RAG)的全流程。

如何学习大模型 AI ?

由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。

但是具体到个人,只能说是:

“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。

这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

在这里插入图片描述

第一阶段(10天):初阶应用

该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。

  • 大模型 AI 能干什么?
  • 大模型是怎样获得「智能」的?
  • 用好 AI 的核心心法
  • 大模型应用业务架构
  • 大模型应用技术架构
  • 代码示例:向 GPT-3.5 灌入新知识
  • 提示工程的意义和核心思想
  • Prompt 典型构成
  • 指令调优方法论
  • 思维链和思维树
  • Prompt 攻击和防范

第二阶段(30天):高阶应用

该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。

  • 为什么要做 RAG
  • 搭建一个简单的 ChatPDF
  • 检索的基础概念
  • 什么是向量表示(Embeddings)
  • 向量数据库与向量检索
  • 基于向量检索的 RAG
  • 搭建 RAG 系统的扩展知识
  • 混合检索与 RAG-Fusion 简介
  • 向量模型本地部署

第三阶段(30天):模型训练

恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。

到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?

  • 为什么要做 RAG
  • 什么是模型
  • 什么是模型训练
  • 求解器 & 损失函数简介
  • 小实验2:手写一个简单的神经网络并训练它
  • 什么是训练/预训练/微调/轻量化微调
  • Transformer结构简介
  • 轻量化微调
  • 实验数据集的构建

第四阶段(20天):商业闭环

对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。

  • 硬件选型
  • 带你了解全球大模型
  • 使用国产大模型服务
  • 搭建 OpenAI 代理
  • 热身:基于阿里云 PAI 部署 Stable Diffusion
  • 在本地计算机运行大模型
  • 大模型的私有化部署
  • 基于 vLLM 部署大模型
  • 案例:如何优雅地在阿里云私有部署开源大模型
  • 部署一套开源 LLM 项目
  • 内容安全
  • 互联网信息服务算法备案

学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。

如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。

这份完整版的大模型 AI 学习资料已经上传优快云,朋友们如果需要可以微信扫描下方优快云官方认证二维码免费领取【保证100%免费

在这里插入图片描述

<think>嗯,用户想了解如何部署qwq-32b模型到VLLM平台上。首先,我需要回忆一下VLLM的基本知识。VLLM是一个高效推理和部署框架,支持大规模语言模型,特别是优化了自回归模型的推理速度。那部署模型的一般步骤是什么呢?通常需要安装环境、下载模型、配置参数、启动服务。 接下来,用户提到的qwq-32b模型,我需要确认是否有相关的引用信息。查看用户提供的引用内容,引用[1]提到了模型下载的路径,引用[2]和[3]则涉及部署中的注意事项,比如量化版本和tokenizer的问题。特别是引用[3]提到需要修改tokenizer_config.json文件来解决输出问题,这可能是一个关键步骤。 首先,安装VLLM。用户可能需要安装最新版本,使用pip命令。然后,下载模型,根据引用[1]的路径,使用modelscope或者git lfs下载。需要注意模型文件的大小,引用[2]提到量化版本可能更适合消费级显卡,比如4bit的20G版本,这可能影响用户的选择。 然后配置环境,可能需要设置CUDA环境变量。启动服务时,使用vllm的命令行工具,指定模型路径、tensor并行数等参数。如果遇到不输出<think>的问题,引用[3]的解决方法是修改tokenizer配置文件,删除相关token,这需要用户找到对应的json文件进行调整。 还需要考虑硬件要求,比如GPU显存是否足够。如果用户使用消费级显卡,可能需要量化模型,如引用[2]提到的。此外,部署后如何测试服务,比如使用curl或Python客户端发送请求,验证是否正常工作。 可能用户遇到的问题包括模型路径错误、显存不足、tokenizer配置问题等,需要逐一排查。总结步骤应该是:安装依赖→下载模型→调整配置→启动服务→验证测试。同时,提醒用户注意量化版本的选择和可能的配置调整,确保部署顺利。</think>### 分步教程:使用vLLM部署QwQ-32B模型 #### 一、环境准备 1. 安装CUDA驱动 确保显卡驱动支持CUDA 11.8+,通过命令验证: ```bash nvidia-smi ``` 2. 创建虚拟环境(推荐) ```bash conda create -n vllm python=3.9 conda activate vllm ``` #### 二、模型下载 1. 通过ModelScope获取完整模型(需约60GB显存): ```bash pip install modelscope python -c "from modelscope.hub.snapshot_download import snapshot_download; snapshot_download('Qwen/QwQ-32B', cache_dir='./QwQ-32B')" [^1] ``` 2. (可选)下载4bit量化版本(约20GB): ```bash ollama pull QwQ-32B:4bit ``` #### 三、vLLM安装配置 1. 安装最新版vLLM: ```bash pip install vllm ``` 2. 修改tokenizer配置(解决不输出<think>问题): ```bash vim ./QwQ-32B/tokenizer_config.json # 删除"<think>"相关配置项[^3] ``` #### 四、启动推理服务 1. 基础启动命令(需A100 80G*2): ```bash python -m vllm.entrypoints.openai.api_server \ --model ./QwQ-32B \ --tensor-parallel-size 2 \ --gpu-memory-utilization 0.95 ``` 2. 消费级显卡启动(如RTX 3090 24G*2): ```bash python -m vllm.entrypoints.openai.api_server \ --model QwQ-32B:4bit \ --quantization awq \ --dtype half \ --tensor-parallel-size 2 ``` #### 五、服务验证 1. Python客户端测试: ```python from openai import OpenAI client = OpenAI(base_url="http://localhost:8000/v1") response = client.chat.completions.create( model="QwQ-32B", messages=[{"role": "user", "content": "解释量子纠缠"}] ) print(response.choices[0].message.content) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值