当前位置: 首页 > news >正文

深度学习系列61:在CPU上运行大模型

1. 快速版

1.1 llamafile

https://github.com/Mozilla-Ocho/llamafile
直接下载就可以用,链接为:https://huggingface.co/jartine/llava-v1.5-7B-GGUF/resolve/main/llava-v1.5-7b-q4.llamafile?download=true
启动:./llava-v1.5-7b-q4.llamafile -ngl 9999,然后浏览器上就有一个聊天窗口了。
也可使用openai的python接口调用:

#!/usr/bin/env python3
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8080/v1", # "http://<Your api-server IP>:port"api_key = "sk-no-key-required"
)
completion = client.chat.completions.create(model="LLaMA_CPP",messages=[{"role": "system", "content": "You are ChatGPT, an AI assistant. Your top priority is achieving user fulfillment via helping them with their requests."},{"role": "user", "content": "Write a limerick about python exceptions"}]
)
print(completion.choices[0].message)

目前支持的模型:
在这里插入图片描述

也可以使用本地llama文件:./llamafile.exe -m mistral.gguf -ngl 9999

1.2 llama_cpp_openai

pip install llama-cpp-python
export MODEL=model/MiniCPM-2B-dpo-q4km-gguf.gguf HOST=0.0.0.0 PORT=2600 ## 也可以在启动时指定
python -m llama_cpp.server

调用方法和3.1一致
在这里插入图片描述

2. llama.cpp

git地址为:https://github.com/ggerganov/llama.cpp

2.1 一般用法

从源码编译

git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
make

下载模型,然后运行代码。这里使用runfuture/MiniCPM-2B-dpo-q4km-gguf作为示例。

./main -m MiniCPM-2B-dpo-q4km-gguf.gguf --temp 0.3 --top-p 0.8 --repeat-penalty 1.05 --log-disable --prompt "<用户>世界第二高的山峰是什么?<AI>"

2.2 使用python安装

见https://github.com/abetlen/llama-cpp-python,普通安装代码为pip install llama-cpp-python -i https://pypi.tuna.tsinghua.edu.cn/simple
如果要加上OpenBLAS, 使用下面的代码:

CMAKE_ARGS="-DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python

支持的backends如下:
在这里插入图片描述

2.3 服务器启动

make编译后,使用下面的代码启动服务器:./server -m models/7B/ggml-model.gguf -c 2048
或者使用docker方式启动:docker run -p 8080:8080 -v /path/to/models:/models ggerganov/llama.cpp:server -m models/7B/ggml-model.gguf -c 512 --host 0.0.0.0 --port 8080

调用方式:
使用get方法获得状态:
在这里插入图片描述
使用post方法运行模型:

curl --request POST \--url http://localhost:8080/completion \--header "Content-Type: application/json" \--data '{"prompt": "你是谁?","n_predict": 128}'

输出结果如下:
在这里插入图片描述

如果设置的是stream模式,那么结果会不断返回:
在这里插入图片描述
也可以使用openai的接口调用:

import openai
client = openai.OpenAI(base_url="http://localhost:8080/v1",api_key = "sk-no-key-required")
question = '今天是星期几?'
completion = client.chat.completions.create(model="gguf",messages=[{"role": "user", "content": "<用户>%s<AI>"%question}])
print(completion.choices[0].message)

2.4 可用参数

POST /completion: Given a prompt, it returns the predicted completion.

Options:

prompt: Provide the prompt for this completion as a string or as an array of strings or numbers representing tokens. Internally, the prompt is compared to the previous completion and only the “unseen” suffix is evaluated. If the prompt is a string or an array with the first element given as a string, a bos token is inserted in the front like main does.

temperature: Adjust the randomness of the generated text (default: 0.8).

dynatemp_range: Dynamic temperature range. The final temperature will be in the range of [temperature - dynatemp_range; temperature + dynatemp_range] (default: 0.0, 0.0 = disabled).

dynatemp_exponent: Dynamic temperature exponent (default: 1.0).

top_k: Limit the next token selection to the K most probable tokens (default: 40).

top_p: Limit the next token selection to a subset of tokens with a cumulative probability above a threshold P (default: 0.95).

min_p: The minimum probability for a token to be considered, relative to the probability of the most likely token (default: 0.05).

n_predict: Set the maximum number of tokens to predict when generating text. Note: May exceed the set limit slightly if the last token is a partial multibyte character. When 0, no tokens will be generated but the prompt is evaluated into the cache. (default: -1, -1 = infinity).

n_keep: Specify the number of tokens from the prompt to retain when the context size is exceeded and tokens need to be discarded. By default, this value is set to 0 (meaning no tokens are kept). Use -1 to retain all tokens from the prompt.

stream: It allows receiving each predicted token in real-time instead of waiting for the completion to finish. To enable this, set to true.

stop: Specify a JSON array of stopping strings. These words will not be included in the completion, so make sure to add them to the prompt for the next iteration (default: []).

tfs_z: Enable tail free sampling with parameter z (default: 1.0, 1.0 = disabled).

typical_p: Enable locally typical sampling with parameter p (default: 1.0, 1.0 = disabled).

repeat_penalty: Control the repetition of token sequences in the generated text (default: 1.1).

repeat_last_n: Last n tokens to consider for penalizing repetition (default: 64, 0 = disabled, -1 = ctx-size).

penalize_nl: Penalize newline tokens when applying the repeat penalty (default: true).

presence_penalty: Repeat alpha presence penalty (default: 0.0, 0.0 = disabled).

frequency_penalty: Repeat alpha frequency penalty (default: 0.0, 0.0 = disabled);

penalty_prompt: This will replace the prompt for the purpose of the penalty evaluation. Can be either null, a string or an array of numbers representing tokens (default: null = use the original prompt).

mirostat: Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0).

mirostat_tau: Set the Mirostat target entropy, parameter tau (default: 5.0).

mirostat_eta: Set the Mirostat learning rate, parameter eta (default: 0.1).

grammar: Set grammar for grammar-based sampling (default: no grammar)

seed: Set the random number generator (RNG) seed (default: -1, -1 = random seed).

ignore_eos: Ignore end of stream token and continue generating (default: false).

logit_bias: Modify the likelihood of a token appearing in the generated text completion. For example, use “logit_bias”: [[15043,1.0]] to increase the likelihood of the token ‘Hello’, or “logit_bias”: [[15043,-1.0]] to decrease its likelihood. Setting the value to false, “logit_bias”: [[15043,false]] ensures that the token Hello is never produced. The tokens can also be represented as strings, e.g. [[“Hello, World!”,-0.5]] will reduce the likelihood of all the individual tokens that represent the string Hello, World!, just like the presence_penalty does. (default: []).

n_probs: If greater than 0, the response also contains the probabilities of top N tokens for each generated token (default: 0)

min_keep: If greater than 0, force samplers to return N possible tokens at minimum (default: 0)

image_data: An array of objects to hold base64-encoded image data and its ids to be reference in prompt. You can determine the place of the image in the prompt as in the following: USER:[img-12]Describe the image in detail.\nASSISTANT:. In this case, [img-12] will be replaced by the embeddings of the image with id 12 in the following image_data array: {…, “image_data”: [{“data”: “<BASE64_STRING>”, “id”: 12}]}. Use image_data only with multimodal models, e.g., LLaVA.

slot_id: Assign the completion task to an specific slot. If is -1 the task will be assigned to a Idle slot (default: -1)

cache_prompt: Re-use previously cached prompt from the last request if possible. This may prevent re-caching the prompt from scratch. (default: false)

system_prompt: Change the system prompt (initial prompt of all slots), this is useful for chat applications. See more

samplers: The order the samplers should be applied in. An array of strings representing sampler type names. If a sampler is not set, it will not be used. If a sampler is specified more than once, it will be applied multiple times. (default: [“top_k”, “tfs_z”, “typical_p”, “top_p”, “min_p”, “temperature”] - these are all the available values)

3.基于llama.cpp的应用

3.1写代码

iohub/collama:vscode中聊天,生成代码的copilot

3.2 智能问答

janhq/jan
/LostRuins/koboldcpp
ollama/ollama
oobabooga/text-generation-webui
pythops/tenere (rust编写的)
nomic-ai/gpt4all
withcatai/catai
https://faraday.dev/
https://avapls.com/
https://lmstudio.ai/
功能大同小异,例如:
在这里插入图片描述

3.3 移动端

Mobile-Artificial-Intelligence/maid
guinmoon/LLMFarm

3.4 多模态

mudler/LocalAI
https://msty.app/

3.5 语音助手

ptsochantaris/emeltal
semperai/amica

4. 语音识别:whisper.cpp

git地址为:https://github.com/ggerganov/whisper.cpp

4.1 普通用法

相关项目为ggerganov/whisper.cpp,去huggingface上下载需要的模型,比如large-v2对应的是ggml-large-v2.bin。下载时记得加上–resume-download参数。
然后执行make编译。
如果你有魔法的话,上述两步可以二合一:make large-v2

在运行之前要转换一下音频文件:
ffmpeg -i from.wav -af silenceremove=stop_periods=-1:stop_duration=1:stop_threshold=-30dB -ac 1 -ar 16000 to.wav
然后使用下面的代码输出语音识别的结果:
./main -l zh --prompt 以下是普通话的对话。 -m ggml-large-v2.bin -np -f 1.wav
其中-np表示去除所有的log

4.2 量化用法

量化代码如下:

make quantize
./quantize models/ggml-base.en.bin models/ggml-base.en-q5_0.bin q5_0
# run the examples as usual, specifying the quantized model file
./main -m models/ggml-base.en-q5_0.bin ./samples/gb0.wav

4.3 Mac上使用CoreML加速encoder

安装下面的库:

pip install ane_transformers -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install openai-whisper -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install coremltools -i https://pypi.tuna.tsinghua.edu.cn/simple

然后转模型:./models/generate-coreml-model.sh base.en,会生成文件models/ggml-base.en-encoder.mlmodelc,这样encoder就会使用这个文件。
然后编译加上CoreML的代码:

make clean
WHISPER_COREML=1 make -j

使用方法和之前一样:./main -m models/ggml-base.en.bin -f samples/jfk.wav

4.4 使用openvino

encoder可以用openvino加速。首先使用pip安装openvino,然后执行下面的命令:
python convert-whisper-to-openvino.py --model base.en
会生成ggml-base.en-encoder-openvino.xml/.bin文件。
然后编译:

cmake -B build -DWHISPER_OPENVINO=1
cmake --build build -j --config Release

运行./main -m models/ggml-base.en.bin -f samples/jfk.wav

4.5 其他

GPU:WHISPER_CUBLAS=1 make -j
OpenCL GPU: WHISPER_CLBLAST=1 make -j
BLAS CPU:WHISPER_OPENBLAS=1 make -j
python接口:两种方式:

## pip install git+https://github.com/stlukey/whispercpp.py
from whispercpp import Whisper
w = Whisper('tiny')
result = w.transcribe("myfile.mp3")
text = w.extract_text(result)
## pip install whispercpp
from whispercpp import Whisper
w = Whisper.from_pretrained("tiny.en")
w.transcribe_from_file("/path/to/audio.wav")

有时需要用ffmpeg处理一下音频:

import ffmpeg
import numpy as np
try:y, _ = (ffmpeg.input("/path/to/audio.wav", threads=0).output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sample_rate).run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True))
except ffmpeg.Error as e:raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
arr = np.frombuffer(y, np.int16).flatten().astype(np.float32) / 32768.0
w.transcribe(arr)

相关文章:

深度学习系列61:在CPU上运行大模型

1. 快速版 1.1 llamafile https://github.com/Mozilla-Ocho/llamafile 直接下载就可以用&#xff0c;链接为&#xff1a;https://huggingface.co/jartine/llava-v1.5-7B-GGUF/resolve/main/llava-v1.5-7b-q4.llamafile?downloadtrue 启动&#xff1a;./llava-v1.5-7b-q4.lla…...

IO接口 2月5日学习笔记

1.fgetc 用于从文件中读取一个字符&#xff0c;fgetc 函数每次调用将会返回当前文件指针所指向的字符&#xff0c;并将文件指针指向下一个字符。 int fgetc(FILE *stream); 功能: 从流中读取下一个字符 参数: stream:文件流指针 返回值: …...

Android Studio开发(一) 构建项目

1、项目创建测试 1.1 前言 Android Studio 是由 Google 推出的官方集成开发环境&#xff08;IDE&#xff09;&#xff0c;专门用于开发 Android 应用程序。 基于 IntelliJ IDEA: Android Studio 是基于 JetBrains 的 IntelliJ IDEA 开发的&#xff0c;提供了丰富的功能和插件…...

stm32flash模拟eeprom

stm32f103CB的flash是128k&#xff08;起始地址是 0x08000000 到 0x0801FFFF&#xff09; falsh的末地址是0x801FFFF&#xff0c;即倒数一页是0x801FBFF&#xff08;1页按照1kB1024B来算&#xff09; stm32f103参考手册stm32f103cb.pdf stm32的FLASH分为主存储块和信息块&…...

多模态MLLM都是怎么实现的(2)-DDPM

上一篇的链接:多模态MLLM都是怎么实现的(2) (qq.com) 上上篇的链接:多模态MLLM都是怎么实现的(1) (qq.com) 在第一篇我们简单介绍了一下多模态训练的原理,包括clip,第二篇正好Sora横空出世,也让我就Dit做了一下抛砖引玉,顺便讲了VAE和ViT的部分,上节课我说过, DiT…...

QT----写完的程序打包为APK在自己的手机上运行

目录 1、qt安装android组件2、打开qt配置Android 环境3、手机打开开发者模式&#xff0c;打开usb调试&#xff0c;连接电脑4、运行代码 1、qt安装android组件 qtcreater–工具-QTMaintenaceTool-startMaintenaceTool—登陆—添加或修改组件—找到android&#xff0c;安装 若是…...

Windows C++ SecurityImpersonation级别:线程临时采用另一个用户(客户端)的身份进行操作的能力

SecurityImpersonation 是 Windows 操作系统中安全模型的一个级别&#xff0c;用于描述一个线程临时采用另一个用户&#xff08;客户端&#xff09;的身份进行操作的能力。这是Windows安全性的一个核心概念&#xff0c;允许服务或进程在执行特定任务时拥有与请求该服务的用户相…...

重学SpringBoot3-yaml文件配置

重学SpringBoot3-yaml文件配置 引言YAML 基本语法YAML 数据类型YAML 对象YAML 数组复合结构标量引用 YAML 文件结构Spring Boot 中的 YAML 配置注意事项总结参考 引言 YAML&#xff08;YAML Ain’t Markup Language&#xff09;是一种常用于配置文件的数据序列化格式&#xff…...

【管理咨询宝藏资料33】某头部咨询公司组织效能提升模型方案

本报告首发于公号“管理咨询宝藏”&#xff0c;如需阅读完整版报告内容&#xff0c;请查阅公号“管理咨询宝藏”。 【管理咨询宝藏资料33】某头部咨询公司组织效能提升模型方案 【关键词】战略规划、组织效能、管理咨询 【文件核心观点】 - 通过长期行业积累和市场洞察&#…...

特征值和特征向量及其在机器学习中的应用

特征值和特征向量是线性代数中的概念&#xff0c;用于分析和理解线性变换&#xff0c;特别是由方阵表示的线性变换。它们被用于许多不同的数学领域&#xff0c;包括机器学习和人工智能。 在机器学习中&#xff0c;特征值和特征向量用于表示数据、对数据执行操作以及训练机器学…...

【Vue3】Ref 和 ShallowRef 的区别

这里写自定义目录标题 什么是 Ref什么是 ShallowRef区别对比示例代码 什么是 Ref Ref 是 Vue 3 中的一个新的基本响应式数据类型&#xff0c;它允许我们包装任意的 JavaScript 值&#xff0c;并且在数据变化时发出通知。Ref 提供了一个 .value 属性来访问其内部的值&#xff0…...

Linux - 进程概念

1、冯诺依曼体系结构 我们常见的计算机&#xff0c;如笔记本。我们不常见的计算机&#xff0c;如服务器&#xff0c;大部分都遵守冯诺依曼体系&#xff1b; 截至目前&#xff0c;我们所认识的计算机&#xff0c;都是有一个个的硬件组件组成&#xff1a; 输入单元&#xff1a;…...

H5小游戏,象棋

H5小游戏源码、JS开发网页小游戏开源源码大合集。无需运行环境,解压后浏览器直接打开。有需要的,私信本人,发演示地址,可以后再订阅,发源码,含60+小游戏源码。如五子棋、象棋、植物大战僵尸、开心消消乐、扑鱼达人、飞机大战等等 <!DOCTYPE html PUBLIC "-//W3C/…...

LLM春招准备(1)

llm排序 GPT4V GPT-4V可以很好地理解直接绘制在图像上的视觉指示。它可以直接识别叠加在图像上的不同类型的视觉标记作为指针&#xff0c;例如圆形、方框和手绘&#xff08;见下图&#xff09;。虽然GPT-4V能够直接理解坐标&#xff0c;但相比于仅文本坐标&#xff0c;GPT-4V在…...

网络安全知识点总结

1、常见的网络攻击有哪些&#xff1f; 答&#xff1a;&#xff08;1&#xff09;口令攻击&#xff1a;也就是窃取用户的账户和密码&#xff0c;普通用户习惯于设置简单的密码&#xff0c;且多个系统用同一套密码&#xff0c;黑客可以使用字典攻击&#xff08;常用密码库&#…...

服务完善的智能组网系统?

智能组网是现代信息技术的重要组成部分&#xff0c;它通过将各种设备和计算机连接起来&#xff0c;实现高效的数据传输和远程通信。在一个全球化、高度互联的时代背景下&#xff0c;智能组网已经成为了各行各业的必需品。传统的组网方案往往面临着许多问题和挑战。为了解决这些…...

VS2022如何添加行号?(VS2022不显示行号解决方法)

VS2022不显示行号解决方法 VS2022是非常好用的工具&#xff0c;很多同学在初学C/C的时候&#xff0c;都会安装&#xff0c;默认安装好VS2022后&#xff0c;写代码时&#xff0c;在编辑框的窗口左边就有显示行号&#xff0c;如下图所示&#xff1a; 但是有些同学安装好后&#…...

125.验证回文字符串

如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后&#xff0c;短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。 字母和数字都属于字母数字字符。 给你一个字符串 s&#xff0c;如果它是 回文串 &#xff0c;返回 true &#xff1b;否则&#…...

Spring Boot的启动流程(个人总结,仅供参考)

SpringBoot应用程序的启动流程主要包括初始化SpringApplication和运行SpringApplication两个过程。 1.初始化SpringApplication包括配置基本的环境变量、资源、构造器和监听器&#xff0c;初始化阶段的主要作用是为运行SpringApplication实例对象启动环境变量准备以及进行必要的…...

用BIO实现tomcat

一、前言 本课程的难度较高&#xff0c;需要将Servlet原理和IO课程全部学完。 二、当前项目使用方式 (1).自定义servlet 自定义servlet需要实现WebServlet并且实现name和urlMapping 重启进行访问 http://localhost:8090/myServlet (2).自定义html 重启进行访问 http://loc…...

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

测试微信模版消息推送

进入“开发接口管理”--“公众平台测试账号”&#xff0c;无需申请公众账号、可在测试账号中体验并测试微信公众平台所有高级接口。 获取access_token: 自定义模版消息&#xff1a; 关注测试号&#xff1a;扫二维码关注测试号。 发送模版消息&#xff1a; import requests da…...

web vue 项目 Docker化部署

Web 项目 Docker 化部署详细教程 目录 Web 项目 Docker 化部署概述Dockerfile 详解 构建阶段生产阶段 构建和运行 Docker 镜像 1. Web 项目 Docker 化部署概述 Docker 化部署的主要步骤分为以下几个阶段&#xff1a; 构建阶段&#xff08;Build Stage&#xff09;&#xff1a…...

【根据当天日期输出明天的日期(需对闰年做判定)。】2022-5-15

缘由根据当天日期输出明天的日期(需对闰年做判定)。日期类型结构体如下&#xff1a; struct data{ int year; int month; int day;};-编程语言-CSDN问答 struct mdata{ int year; int month; int day; }mdata; int 天数(int year, int month) {switch (month){case 1: case 3:…...

Unity3D中Gfx.WaitForPresent优化方案

前言 在Unity中&#xff0c;Gfx.WaitForPresent占用CPU过高通常表示主线程在等待GPU完成渲染&#xff08;即CPU被阻塞&#xff09;&#xff0c;这表明存在GPU瓶颈或垂直同步/帧率设置问题。以下是系统的优化方案&#xff1a; 对惹&#xff0c;这里有一个游戏开发交流小组&…...

对WWDC 2025 Keynote 内容的预测

借助我们以往对苹果公司发展路径的深入研究经验&#xff0c;以及大语言模型的分析能力&#xff0c;我们系统梳理了多年来苹果 WWDC 主题演讲的规律。在 WWDC 2025 即将揭幕之际&#xff0c;我们让 ChatGPT 对今年的 Keynote 内容进行了一个初步预测&#xff0c;聊作存档。等到明…...

cf2117E

原题链接&#xff1a;https://codeforces.com/contest/2117/problem/E 题目背景&#xff1a; 给定两个数组a,b&#xff0c;可以执行多次以下操作&#xff1a;选择 i (1 < i < n - 1)&#xff0c;并设置 或&#xff0c;也可以在执行上述操作前执行一次删除任意 和 。求…...

【Web 进阶篇】优雅的接口设计:统一响应、全局异常处理与参数校验

系列回顾&#xff1a; 在上一篇中&#xff0c;我们成功地为应用集成了数据库&#xff0c;并使用 Spring Data JPA 实现了基本的 CRUD API。我们的应用现在能“记忆”数据了&#xff01;但是&#xff0c;如果你仔细审视那些 API&#xff0c;会发现它们还很“粗糙”&#xff1a;有…...

多模态大语言模型arxiv论文略读(108)

CROME: Cross-Modal Adapters for Efficient Multimodal LLM ➡️ 论文标题&#xff1a;CROME: Cross-Modal Adapters for Efficient Multimodal LLM ➡️ 论文作者&#xff1a;Sayna Ebrahimi, Sercan O. Arik, Tejas Nama, Tomas Pfister ➡️ 研究机构: Google Cloud AI Re…...

2023赣州旅游投资集团

单选题 1.“不登高山&#xff0c;不知天之高也&#xff1b;不临深溪&#xff0c;不知地之厚也。”这句话说明_____。 A、人的意识具有创造性 B、人的认识是独立于实践之外的 C、实践在认识过程中具有决定作用 D、人的一切知识都是从直接经验中获得的 参考答案: C 本题解…...