【记录】初次本地搭建的模型-MiniCPM 2B

news2025/2/7 3:58:47

前言

        查阅众多开源大模型后,打算动手尝试搭建端侧模型,看看效果。选中MiniCPM主要是因为参数小,同时中文支持相对较好。

        首先对按照官网提供的demo进行了尝试,然后在colab中完成了一个webui程序并测试,最后通过docker环境在本地搭建并测试成功。

        

Colab Demo测试

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
torch.manual_seed(0)

path = # model path 
tokenizer = AutoTokenizer.from_pretrained(path)
model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.float32, device_map='cuda', trust_remote_code=True)

responds, history = model.chat(tokenizer, "山东省最高的山是哪座山, 它比黄山高还是矮?差距多少?", temperature=0.8, top_p=0.8)
print(responds)

编写程序

from typing import List

import argparse
import gradio as gr
import torch
from threading import Thread
from transformers import (
    AutoModelForCausalLM, 
    AutoTokenizer,
    TextIteratorStreamer
)

import warnings
warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')

parser = argparse.ArgumentParser()
parser.add_argument("--model_path", type=str, default="")
parser.add_argument("--torch_dtype", type=str, default="bfloat16")
parser.add_argument("--server_name", type=str, default="127.0.0.1")
parser.add_argument("--server_port", type=int, default=7860)

args = parser.parse_args()

# init model torch dtype
torch_dtype = args.torch_dtype
if torch_dtype =="" or torch_dtype == "bfloat16":
    torch_dtype = torch.bfloat16
elif torch_dtype == "float32":
    torch_dtype = torch.float32
else:
    raise ValueError(f"Invalid torch dtype: {torch_dtype}")

# init model and tokenizer
path = args.model_path
tokenizer = AutoTokenizer.from_pretrained(path)
#无显卡auto改为cpu
model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch_dtype, device_map="auto", trust_remote_code=True)

# init gradio demo host and port
server_name=args.server_name
server_port=args.server_port

def hf_gen(dialog: List, top_p: float, temperature: float, max_dec_len: int):
    """generate model output with huggingface api

    Args:
        query (str): actual model input.
        top_p (float): only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
        temperature (float): Strictly positive float value used to modulate the logits distribution.
        max_dec_len (int): The maximum numbers of tokens to generate.

    Yields:
        str: real-time generation results of hf model
    """    
    inputs = tokenizer.apply_chat_template(dialog, tokenize=False, add_generation_prompt=False)
    #无显卡去掉.to("cuda")
    enc = tokenizer(inputs, return_tensors="pt").to("cuda")
    streamer = TextIteratorStreamer(tokenizer)
    generation_kwargs = dict(
        enc,
        do_sample=True,
        top_p=top_p,
        temperature=temperature,
        max_new_tokens=max_dec_len,
        pad_token_id=tokenizer.eos_token_id,
        streamer=streamer,
    )
    thread = Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()
    answer = ""
    for new_text in streamer:
        answer += new_text
        yield answer[4 + len(inputs):]


def generate(chat_history: List, query: str, top_p: float, temperature: float, max_dec_len: int):
    """generate after hitting "submit" button

    Args:
        chat_history (List): [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n]]. list that stores all QA records
        query (str): query of current round
        top_p (float): only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
        temperature (float): strictly positive float value used to modulate the logits distribution.
        max_dec_len (int): The maximum numbers of tokens to generate.

    Yields:
        List: [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n], [q_n+1, a_n+1]]. chat_history + QA of current round.
    """    
    assert query != "", "Input must not be empty!!!"
    # apply chat template
    model_input = []
    for q, a in chat_history:
        model_input.append({"role": "user", "content": q})
        model_input.append({"role": "assistant", "content": a})
    model_input.append({"role": "user", "content": query})
    # yield model generation
    chat_history.append([query, ""])
    for answer in hf_gen(model_input, top_p, temperature, max_dec_len):
        chat_history[-1][1] = answer.strip("</s>")
        yield gr.update(value=""), chat_history


def regenerate(chat_history: List, top_p: float, temperature: float, max_dec_len: int):
    """re-generate the answer of last round's query

    Args:
        chat_history (List): [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n]]. list that stores all QA records
        top_p (float): only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
        temperature (float): strictly positive float value used to modulate the logits distribution.
        max_dec_len (int): The maximum numbers of tokens to generate.

    Yields:
        List: [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n]]. chat_history
    """    
    assert len(chat_history) >= 1, "History is empty. Nothing to regenerate!!"
    # apply chat template
    model_input = []
    for q, a in chat_history[:-1]:
        model_input.append({"role": "user", "content": q})
        model_input.append({"role": "assistant", "content": a})
    model_input.append({"role": "user", "content": chat_history[-1][0]})
    # yield model generation
    for answer in hf_gen(model_input, top_p, temperature, max_dec_len):
        chat_history[-1][1] = answer.strip("</s>")
        yield gr.update(value=""), chat_history


def clear_history():
    """clear all chat history

    Returns:
        List: empty chat history
    """    
    return []


def reverse_last_round(chat_history):
    """reverse last round QA and keep the chat history before

    Args:
        chat_history (List): [[q_1, a_1], [q_2, a_2], ..., [q_n, a_n]]. list that stores all QA records

    Returns:
        List: [[q_1, a_1], [q_2, a_2], ..., [q_n-1, a_n-1]]. chat_history without last round.
    """    
    assert len(chat_history) >= 1, "History is empty. Nothing to reverse!!"
    return chat_history[:-1]


# launch gradio demo
with gr.Blocks(theme="soft") as demo:
    gr.Markdown("""# MiniCPM Gradio Demo""")

    with gr.Row():
        with gr.Column(scale=1):
            top_p = gr.Slider(0, 1, value=0.8, step=0.1, label="top_p")
            temperature = gr.Slider(0.1, 2.0, value=0.8, step=0.1, label="temperature")
            max_dec_len = gr.Slider(1, 1024, value=1024, step=1, label="max_dec_len")
        with gr.Column(scale=5):
            chatbot = gr.Chatbot(bubble_full_width=False, height=400)
            user_input = gr.Textbox(label="User", placeholder="Input your query here!", lines=8)
            with gr.Row():
                submit = gr.Button("Submit")
                clear = gr.Button("Clear")
                regen = gr.Button("Regenerate")
                reverse = gr.Button("Reverse")

    submit.click(generate, inputs=[chatbot, user_input, top_p, temperature, max_dec_len], outputs=[user_input, chatbot])
    regen.click(regenerate, inputs=[chatbot, top_p, temperature, max_dec_len], outputs=[user_input, chatbot])
    clear.click(clear_history, inputs=[], outputs=[chatbot])
    reverse.click(reverse_last_round, inputs=[chatbot], outputs=[chatbot])

demo.queue()
demo.launch(server_name=server_name, server_port=server_port, show_error=True)

Colab程序测试

本地搭建

容器环境

        本地搭建一般个人比较倾向使用 Docker 作为运行环境,在投入很少额外资源的情况下,能够快速获得纯净、可复现的一致性非常棒的环境。

        除此之外,为了高效运行模型,推荐使用 Nvidia 官方的容器镜像(nvcr.io/nvidia/pytorch:24.01-py3[4])。

        我们可以基于上面的内容,快速搭建一个干净、高效的基础运行环境。

        考虑到我们可能会将模型应用运行在不同的环境,比如云主机和服务器,它们的网络环境可能有所不同。

        当我们本地进行 Docker 镜像构建的时候,配置软件镜像来加速可以大幅改善开发者体验。所以,稍加调整,我们可以得到下面的 Dockerfile 文件:

FROM nvcr.io/nvidia/pytorch:24.01-py3
LABEL maintainer="554686223@qq.com"

# setup Ubuntu and PyPi mirrors, refs: https://github.com/soulteary/docker-stable-diffusion-webui/blob/main/docker/Dockerfile.base
ARG USE_CHINA_MIRROR=true
RUN if [ "$USE_CHINA_MIRROR" = "true" ]; then \
        pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple && \
        sed -i 's/security.ubuntu.com/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list && \
        sed -i 's/archive.ubuntu.com/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list; \
    fi

# install dependencies、

RUN pip install torch==2.2.1 -i https://pypi.tuna.tsinghua.edu.cn/simple


RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple transformers==4.37.2 gradio==4.16.0 accelerate==0.26.1


RUN pip uninstall transformer-engine

将上面的内容保存为 Dockerfile,然后执行下面的命令,可以进行镜像构建:

docker build -t my-gpt -f=dockerfile --no-cache .

下载模型

        根据自身网络情况,选择HuggingFace、ModelScope、WiseModel中最适合你的模型下载或者在线推理平台。

        这里选择了wisemodel,git链接 

         git clone https://www.wisemodel.cn/OpenBMB/miniCPM-dpo-fp32.git

简单测试

启动容器

docker run --rm -it -p 7860:7860 --gpus all --ipc=host --ulimit memlock=-1 -v D:/weiyisoftware/gpttest/gptdocker/models:/app/models -v D:/weiyisoftware/gpttest/gptdocker/workspace:/workspace my-gpt python app.py --model_path=/app/models/OpenBMB/miniCPM-dpo-fp32/ --server_name=0.0.0.0 --torch_dtype=float32

成功后:http://localhost:7860。

ps:因为电脑配置问题,回复很慢。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1703195.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MySQL(二)基本SQL语句以及基本函数应用

1、基本SQL语句 MySQL中定义数据字段的类型对你数据库的优化是非常重要的。 MySQL支持多种类型&#xff0c;大致可以分为三类&#xff1a;数值、日期/时间和字符串&#xff08;字符&#xff09;类型。 - 函数应用在sql语句中 -- 临时表 select now() from dual;-- 数…

分布式一致性必备:一文读懂Raft算法

本文作者:小米,一个热爱技术分享的29岁程序员。如果你喜欢我的文章,欢迎关注我的微信公众号“软件求生”,获取更多技术干货! 大家好!我是小米,一个热爱分享技术的29岁程序员哥哥。今天我们来聊聊分布式系统中的一个重要算法——Raft。这个算法专门用于管理分布式系统中…

学习100个Unity Shader (18) --- 几何着色器(Geometry Shader)

文章目录 概述编写格式举例应用举例&#xff08;用预制体球的每个顶点画一个立方体&#xff09;参考 概述 vertex shader --> [geometry shader] --> fragment shader。[]: 可选阶段。输入图元 —> geometry shader —> 其他图元 编写格式 [maxcertexcount(N)] …

会声会影2024旗舰版神器,让你的视频秒变大片,小白也能轻松上手

在数字时代&#xff0c;视频已经成为了人们表达自我、记录生活的重要方式。无论是旅行中的美景&#xff0c;还是生活中的点滴瞬间&#xff0c;我们都渴望能够用镜头捕捉下来&#xff0c;并通过精心剪辑&#xff0c;将这些美好的画面永远珍藏。然而&#xff0c;对于大多数人来说…

百川大模型拿下国产第一,AI助手「百小应」上线,比Kimi强不少

最近几天&#xff0c;国内 AI 创业公司正在连续刷新大模型的能力上限。 5 月 22 日&#xff0c;百川智能发布最新一代基座大模型 Baichuan 4&#xff0c;同时推出了首款 AI 助手「百小应」。 相较 1 月份发布的 Baichuan 3&#xff0c;新一代模型在各项能力上均有大幅提升&am…

OrangePi AIpro评测 - 基础操作篇

0. 环境 ●OrangePi AIpro ●win10笔记本 ●路由器 准备下win10电脑、路由器&#xff0c;这些板卡通常是在网络正常的环境下才方便测试。 还要准备OrangePi AIpro的官方资料&#xff1a; http://www.orangepi.cn/html/hardWare/computerAndMicrocontrollers/service-and-suppo…

牛客NC164 最长上升子序列(二)【困难 贪心+二分 Java/Go/PHP/C++】

题目 题目链接&#xff1a; https://www.nowcoder.com/practice/4af96fa010c44638a7e112abf65f7237 思路 贪心二分 所谓贪心&#xff0c;就是往死里贪&#xff0c;所以对于最大上升子序列&#xff0c;结尾元素越小&#xff0c;越有利于后面接上其他的数&#xff0c;也就可能变…

麒麟系统firewalld限制指定的ip访问指定的端口

先开放所有端口 然后第三个限制会把第四个第五个拦住 so 这个是错误案例 accecpt 接受 reject 拒绝

为什么短剧突然爆火?背后究竟谁在为流量买单?

为什么短剧突然爆火&#xff1f;背后究竟谁在为流量买单&#xff1f; 文丨微三云营销总监胡佳东&#xff0c;点击上方“关注”&#xff0c;为你分享市场商业模式电商干货。 - 今年很多朋友交流的更多的商业热门话题就是“短剧”&#xff0c;目前我国拥有超10亿的短视频用户&a…

利用ESP32(Arduino IDE)向匿名上位机发送欧拉角

文章目录 一. 匿名上位机介绍二. 匿名协议说明1. 匿名协议官方说明文档2. 协议说明 三. 向匿名上位机发送数据(基于Arduino IDE的esp32)四. 运行效果 一. 匿名上位机介绍 匿名上位机官方介绍视频 匿名上位机官方下载 二. 匿名协议说明 1. 匿名协议官方说明文档 官方对于协…

2024年短视频评论区批量爬取采集软件

一、背景说明 前言 评论区引流&#xff0c;顾名思义&#xff0c;是通过在视频下方进行留言评论、回复评论&#xff0c;吸引用户的注意&#xff0c;从而和你的账号产生互动、交易。比如&#xff0c;在一个关于健身的视频下方&#xff0c;留言分享自己的健身经验或者提出问题。…

西门子S7-1200加入MRP 环网用法

MRP&#xff08;介质冗余&#xff09;功能概述 SIMATIC 设备采用标准的冗余机制为 MRP&#xff08;介质冗余协议&#xff09;&#xff0c;符合 IEC62439-2 标准&#xff0c;典型重新组态时间为 200ms&#xff0c;每个环网最多支持 50个设备。​博途TIA/WINCC社区VX群 ​博途T…

springboot+vue+mybatis基于java web的公益网站的设计与实现+jsp+PPT+论文+讲解+售后

现代经济快节奏发展以及不断完善升级的信息化技术&#xff0c;让传统数据信息的管理升级为软件存储&#xff0c;归纳&#xff0c;集中处理数据信息的管理方式。本公益网站就是在这样的大环境下诞生&#xff0c;其可以帮助管理者在短时间内处理完毕庞大的数据信息&#xff0c;使…

docker搭建gitlab及默认密码修改及配置修改

推荐官方文档 https://docs.gitlab.com/17.0/ee/install/docker.html 我使用的是docker run的方式&#xff0c;官方文档后面有docker-compose、swarm、k8s的部署文档 版本说明 1&#xff1a;可以部署gitlab-ce社区版和gitlab-ee企业版&#xff0c;然后&#xff0c;鉴于是个人…

上海AI lab发布MathBench,GPT-4o的数学能力有多强?

大模型数学能力哪家强&#xff1f; 最近&#xff0c;上海AI lab构建了一个全面的多语言数学基准——MathBench。与现有的基准不同的是&#xff0c;MathBench涵盖从小学、初中、高中、大学不同难度&#xff0c;从基础算术题到高阶微积分、统计学、概率论等丰富类别的数学题目&a…

基于51单片机的函数发生器设计

一.硬件方案 此函数信号发生器是基于单片机AT89C51设计而成的&#xff0c;能够产生频率范围在0Hz—535Hz的锯齿波、正弦波、三角波、矩形波四种波形&#xff0c;并且能够通过液晶屏1602显示各自的波形类型以及频率数值。电路主要由51单片机最小系统DA0832模数转换模块运放模块…

Star CCM+绘图显示设置

前言 如前文介绍&#xff0c;根据报告创建监视器与绘图后&#xff0c;在绘图中会出现报告绘图。此处可以自定义绘图的格式&#xff0c;如网格显示、字体大小、曲线的粗细等。同时也可以根据需要创建右坐标&#xff0c;分别监测不同类型的函数数值。为此方便后期输出仿真报告。…

nginx文件解析漏洞测试

环境条件:ubuntu14,已安装docker,docker pull ubuntu:14.04.5 一、Nginx配置 1、使用docker启动容器&#xff1a; docker run -itd --name ubuntu -p 8088:80 ubuntu:14.04.5 2、进入容器&#xff1a; docker exec -it ubuntu /bin/bash 3、然后使用以下语句安装相关环境…

超详细的前后端实战项目(Spring系列加上vue3)前后端篇(四)(一步步实现+源码)

兄弟们&#xff0c;继昨天的代码之后&#xff0c;继续完成最后的用户模块开发&#xff0c; 昨天已经完成了关于用户的信息编辑页面这些&#xff0c;今天再完善一下&#xff0c; 从后端这边开始吧&#xff0c;做一个拦截器&#xff0c;对用户做身份校验&#xff0c; 拦截器 这…

无线蓝牙耳机品牌推荐:倍思M2s Pro,让旅途更添乐趣

随着端午节的临近,许多人开始规划起出游计划。出游除了要做好行程安排,还需准备一些实用的物品来提升旅途的舒适度。特别是在高铁等长途旅行中,一款优质的降噪蓝牙耳机无疑是消磨时光、享受音乐的绝佳选择。那么,在众多的无线蓝牙耳机品牌中,有哪些值得推荐的呢?今天,我们就来…