> ## Documentation Index
> Fetch the complete documentation index at: https://dragonwingdocs.qualcomm.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 Genie 运行 LLM

借助 [Qualcomm Gen AI Inference Extensions (Genie)](https://www.qualcomm.com/developer/software/gen-ai-inference-extensions)，部分大语言模型（LLM）和视觉语言模型（VLM）可以在您的 Dragonwing 开发板的 NPU 上运行。这些模型已由 Qualcomm 移植和优化，以便在硬件上尽可能高效地运行。Genie 仅支持手动移植的部分模型，因此如果您喜欢的模型不在列表中，请参阅[使用 llama.cpp 运行 LLM / VLM](/zh/ai-workflows/llama-cpp)，作为备选方案在 GPU 上运行模型。

**IQ-9075 EVK 不支持：** 目前尚无适用于 IQ-9075 EVK 的模型。请改用 [llama.cpp](/zh/ai-workflows/llama-cpp)。

## 安装 AI Runtime SDK - Community Edition

首先安装 [AI Runtime SDK - Community Edition](https://softwarecenter.qualcomm.com/catalog/item/Qualcomm_AI_Runtime_Community)。打开开发板上的终端，或与开发板建立 ssh 会话，然后运行：

```shell theme={null}
# Install the SDK
wget -qO- https://cdn.edgeimpulse.com/qc-ai-docs/device-setup/install_ai_runtime_sdk.sh | bash

# Use the SDK in your current session
source ~/.bash_profile
```

## 查找支持的模型

Genie 兼容的 LLM 模型可以在以下几处找到。下面的示例适用于基于 QCS6490 的开发板，如 RB3 Gen 2 Vision Kit 和 RUBIK Pi 3。IQ-9075 EVK/QCS9075 目前不支持 Genie 模型；在支持的 Genie 模型可用之前，请在 IQ-9075 EVK 上使用 [llama.cpp](/zh/ai-workflows/llama-cpp)。

* [Aplux 模型库](https://aiot.aidlux.com/en/models)：

  1. 在 'Chipset' 下选择：

     * RB3 Gen 2 Vision Kit：'Qualcomm QCS6490'
     * RUBIK Pi 3：'Qualcomm QCS6490'

  2. 在 'NLP' 下选择 "Text Generation"。

* [Qualcomm AI Hub](https://aihub.qualcomm.com/models?domain=Generative+AI)：

  1. 在 'Chipset' 下选择：

     * RB3 Gen 2 Vision Kit：'Qualcomm QCS6490 (Proxy)'
     * RUBIK Pi 3：'Qualcomm QCS6490 (Proxy)'

  2. 在 'Domain/Use Case' 下选择 "Generative AI"。

作为示例，我们来部署 [Qwen2.5-0.5B-Instruct](https://aiot.aidlux.com/en/models/detail/149?modelType=9\&soc=2) 模型，它可以在基于 QCS6490 的 Dragonwing 开发板（如 RUBIK Pi 3 和 RB3 Gen 2 Vision Kit）上运行。

## 运行 Qwen2.5-0.5B-Instruct

下载模型时，您需要 3 个文件：

* 一个或多个 `*.serialized.bin` 文件——包含模型的权重。
* `tokenizer.json`——一个序列化配置文件，定义如何将文本拆分为 token，以及字符、子词与 LLM 使用的整数 ID 之间的映射。通常可以从 HuggingFace 上的模型空间下载。Genie 支持模型的链接列表见 [quic/ai-hub-apps: LLM On-Device Deployment > Prepare Genie configs](https://github.com/quic/ai-hub-apps/tree/main/tutorials/llm_on_genie)。
* 一个 Genie 配置文件——包含如何通过 Genie 运行此模型的说明。AI Hub 中模型的配置文件可以在 GitHub 上找到：[quic/ai-hub-apps: tutorials/llm\_on\_genie/configs/genie](https://github.com/quic/ai-hub-apps/tree/main/tutorials/llm_on_genie/configs/genie)。

让我们获取所有这些文件并运行 Qwen2.5-0.5B-Instruct。打开开发板上的终端，或与开发板建立 ssh 会话，然后：

1. 将模型下载到您的开发板。可以：

   * 从我们的 CDN 下载模型（仅提供 Qwen 模型）：

     ```
     wget -O qnn229_qcs6490_cl4096.zip https://cdn.edgeimpulse.com/qc-ai-docs/models/qwen2.5_0.5b_instruct_aplux_qnn229_qcs6490_cl4096.zip
     ```

   * 从 Aplux 模型库下载模型：

     1. 前往 [Aplux 模型库：Qwen2.5-0.5B-Instruct](https://aiot.aidlux.com/en/models/detail/149?modelType=9\&soc=2)。

     2. 注册一个 Aplux 账户。

     3. 在 'Device' 下选择 QCS6490。

     4. 点击 "Download Model & Test code"。

        <Frame caption="下载适用于 QCS6490 的 Genie 兼容模型">
          <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/images/ai-workflows/aplux1.png" />
        </Frame>

     5. 下载后，通过 ssh 将 ZIP 文件推送到您的开发板：

        1. 查找开发板的 IP 地址。在开发板上运行：

           ```
           ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'

           # ... Example:
           # 192.168.1.253
           ```

        2. 推送 .zip 文件。在您的计算机上运行：

           ```
           scp qnn229_qcs6490_cl4096.zip ubuntu@192.168.1.253:~/qnn229_qcs6490_cl4096.zip
           ```

2. 解压模型。在您的开发板上：

   ```shell theme={null}
   mkdir -p ~/genie-models/
   unzip -d ~/genie-models/qwen2.5-0.5b-instruct/ qnn229_qcs6490_cl4096.zip
   rm qnn229_qcs6490_cl4096.zip
   ```

3. 运行您的模型：

   ```shell theme={null}
   cd ~/genie-models/qwen2.5-0.5b-instruct/

   genie-t2t-run -c ./qwen2.5-0.5b-instruct-htp.json -p '<|im_start|>system
       You are Qwen, created by Alibaba Cloud. You are a helpful assistant that responds in English.<|im_end|><|im_start|>user
       What is the capital of the Netherlands?<|im_end|><|im_start|>assistant'

   # Using libGenie.so version 1.9.0
   #
   # [BEGIN]:
   # The capital of the Netherlands is Amsterdam.[END]
   ```

太棒了！您现在已经通过 Genie 运行了这个 LLM。

## 通过 QAI AppBuilder 提供 UI 或 API 服务

要在您的应用程序中使用 Genie 模型，可以使用 [QAI AppBuilder](https://github.com/quic/ai-engine-direct-helper) 仓库。AppBuilder 仓库既提供 OpenAI 兼容的 chat completion API，也提供用于与模型交互的 Web UI（就像 [llama.cpp](/zh/ai-workflows/llama-cpp) 一样）。

**开发迭代频繁：** AppBuilder 正在密集开发中。我们已尽可能固定版本，但使用较新版本的 AppBuilder 可能与以下说明不兼容。

1. 安装 AppBuilder：

   ```python theme={null}
   # Build dependency
   sudo apt update && sudo apt install -y yq

   # Clone the repository
   git clone https://github.com/quic/ai-engine-direct-helper
   cd ai-engine-direct-helper
   git checkout 92d9cad
   git submodule update --init --recursive

   # Create a new venv
   python3 -m venv .venv
   source .venv/bin/activate

   # Build the wheel
   pip3 install setuptools
   python setup.py bdist_wheel
   pip3 install ./dist/qai_appbuilder-*-linux_aarch64.whl

   # Install other dependencies
   pip3 install \
       uvicorn==0.35.0 \
       pydantic_settings==2.10.1 \
       fastapi==0.116.1 \
       langchain==0.3.27 \
       langchain-core==0.3.75 \
       langchain-community==0.3.29 \
       sse_starlette==3.0.2 \
       pypdf==6.0.0 \
       python-pptx==1.0.2 \
       docx2txt==0.9 \
       openai==1.107.0 \
       json-repair==0.50.1 \
       qai_hub==0.36.0 \
       py3_wget==1.0.13 \
       torch==2.8.0 \
       transformers==4.56.1 \
       gradio==5.44.1 \
       diffusers==0.35.1

   # Where you've downloaded the weights, and created the config files before
   WEIGHTS_DIR=~/genie-models/qwen2.5-0.5b-instruct/
   MODEL_NAME=qwen2_5-0_5b-instruct

   # Create a new directory and link the files
   mkdir -p samples/genie/python/models/$MODEL_NAME
   cd samples/genie/python/models/$MODEL_NAME

   # Patch up config
   cp $WEIGHTS_DIR/*instruct-htp.json config.json
   jq --arg pwd "$PWD" '.dialog.tokenizer.path |= if startswith($pwd + "/") then . else $pwd + "/" + . end' config.json > tmp && mv tmp config.json
   jq --arg pwd "$PWD" '.dialog.engine.backend.extensions |= if startswith($pwd + "/") then . else $pwd + "/" + . end' config.json > tmp && mv tmp config.json
   jq --arg pwd "$PWD" '.dialog.engine.model.binary["ctx-bins"] |= map(if startswith($pwd + "/") then . else $pwd + "/" + . end)' config.json > tmp && mv tmp config.json

   # Symlink other files
   ln -s $WEIGHTS_DIR/*.json .
   ln -s $WEIGHTS_DIR/*okenizer.json tokenizer.json
   ln -s $WEIGHTS_DIR/*.serialized.bin .
   echo "prompt_tags_1: <|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n<|im_start|>user\nGive me a short introduction to large language model.
   prompt_tags_2: <|im_end|>\n<|im_start|>assistant\n" > prompt.conf

   # Navigate back to samples/ directory
   cd ../../../..

   # Create empty tokenizer files, otherwise they will be downloaded... (which will fail)
   if [ ! -f genie/python/models/Phi-3.5-mini/tokenizer.json ]; then
       echo '{}' > genie/python/models/Phi-3.5-mini/tokenizer.json
   fi
   if [ ! -f genie/python/models/IBM-Granite-v3.1-8B/tokenizer.json ]; then
       echo '{}' > genie/python/models/IBM-Granite-v3.1-8B/tokenizer.json
   fi
   ```

2. 运行 Web UI（在 `samples/` 目录中）：

   ```
   # Find the IP address of your development board
   ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'

   # ... Example:
   # 192.168.1.253

   # Run the Web UI
   python webui/GenieWebUI.py
   ```

   现在在您计算机的网页浏览器中打开 [http://192.168.1.253:8976](http://192.168.1.253:8976) （替换为您的 IP）与模型交互。请务必先使用 "models" 下拉菜单选择模型。

   <Frame caption="ai-engine-direct-helper WebUI 演示">
     <img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/images/ai-workflows/genie-webui.png" />
   </Frame>

3. 您还可以使用 OpenAI Chat Completions API 以编程方式访问此服务器。例如，通过 Python：

   1. 启动服务器（在 `samples/` 目录中）：

      ```
      python genie/python/GenieAPIService.py --modelname "qwen2_5-0_5b-instruct"   --loadmodel --profile
      ```

   2. 在*新终端*中，创建一个新的 venv 并安装 `requests`：

      ```
      mkdir -p ~/genie-api-demo
      cd ~/genie-api-demo

      python3 -m venv .venv
      source .venv/bin/activate
      pip3 install requests
      ```

   3. 创建一个新文件 `chat.py`：

      ```
      import requests

      # if running from your own computer, replace localhost with the IP address of your development board
      url = "http://localhost:8910/v1/chat/completions"

      payload = {
          "model": "qwen2_5-0_5b-instruct",
          "messages": [
              {"role": "system", "content": "You are a helpful assistant."},
              {"role": "user", "content": "Explain Qualcomm in one sentence."}
          ],
          "temperature": 0.7,
          "max_tokens": 200
      }

      response = requests.post(url, headers={ "Content-Type": "application/json" }, json=payload)
      print(response.json())
      ```

   4. 运行 `chat.py`：

      ```
      python3 chat.py

      # {'id': 'genie-llm', 'model': 'IBM-Granite', 'object': 'chat.completion', 'created': 1757512757, 'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': 'Qualcomm is a leading American technology company that designs, manufactures, and markets mobile phone chips and other wireless communication products.', 'tool_call_id': None, 'tool_calls': None}, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}}
      ```

      （模型似乎总是返回 `IBM-Granite`，您可以忽略这一点）

## 提示与技巧

### 从 HuggingFace 下载需要身份验证的文件

如果您想下载需要权限或身份验证的文件，例如 [Llama-3.2-1B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct/) 的 `tokenizer.json` 文件：

1. 前往 [HuggingFace 上的模型页面](https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct/)，登录（或注册），并填写表单以获取模型访问权限。

2. 在 [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) 创建一个具有 'Read' 权限的新 HuggingFace 访问令牌，并在您的开发板上配置它：

   ```
   export HF_TOKEN=hf_gs...

   # Optionally add ^ to ~/.bash_profile to ensure it gets loaded automatically in the future.
   ```

3. 获得访问权限后，您就可以下载 tokenizer：

   ```
   wget --header="Authorization: Bearer $HF_TOKEN" https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct/resolve/main/tokenizer.json
   ```
