书生开源大模型-第2讲-笔记

news/发布时间2024/5/15 16:02:36

1.环境准备

1.1环境

先克隆我们的环境

bash /root/share/install_conda_env_internlm_base.sh internlm-demo

1.2 模型参数

下载或者复制下来,开发机中已经有一份参数了

mkdir -p /root/model/Shanghai_AI_Laboratory
cp -r /root/share/temp/model_repos/internlm-chat-7b /root/model/Shanghai_AI_Laboratory
# 下载会慢些
import torch
from modelscope import snapshot_download, AutoModel, AutoTokenizer
import os
model_dir = snapshot_download('Shanghai_AI_Laboratory/internlm-chat-7b', cache_dir='/root/model', revision='v1.0.3')

注意这里复制好参数后,在下面的代码中要替换成我们自己的模型参数位置。

web_demolode_model方法

def load_model():model = (AutoModelForCausalLM.from_pretrained("/root/model/Shanghai_AI_Laboratory/internlm-chat-7b", trust_remote_code=True).to(torch.bfloat16).cuda())tokenizer = AutoTokenizer.from_pretrained("/root/model/Shanghai_AI_Laboratory/internlm-chat-7b", trust_remote_code=True)return model, tokenizer

1.3代码

github上clone模型代码以及创建一个demo

cd /root/code
git clone https://gitee.com/internlm/InternLM.git# 切换 commit 版本,与教程 commit 版本保持一致,可以让大家更好的复现。
cd InternLM
git checkout 3028f07cb79e5b1d7342f4ad8d11efad3fd13d17

demo

import torch
from transformers import AutoTokenizer, AutoModelForCausalLMmodel_name_or_path = "/root/model/Shanghai_AI_Laboratory/internlm-chat-7b"tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, trust_remote_code=True, torch_dtype=torch.bfloat16, device_map='auto')
model = model.eval()system_prompt = """You are an AI assistant whose name is InternLM (书生·浦语).
- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.
- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.
"""messages = [(system_prompt, '')]print("=============Welcome to InternLM chatbot, type 'exit' to exit.=============")while True:input_text = input("User  >>> ")input_text = input_text.replace(' ', '')if input_text == "exit":breakresponse, history = model.chat(tokenizer, input_text, history=messages)messages.append((input_text, response))print(f"robot >>> {response}")

image-20240207161056747

2.web_demo

在我们本机上去运行一个demo。

2.1 SSH

首先创建我们的ssh密钥。(一直敲回车让他默认位置即可

ssh-keygen -t rsa

完成后使用cat ~\.ssh\id_rsa.pub即可查看。

我们将其全部复制下来,然后回到 InternStudio 控制台,点击配置 SSH Key。

image-20240207162602292

然后根据控制台上的端口号使用如下命令即可链接

ssh -CNg -L 6006:127.0.0.1:6006 root@ssh.intern-ai.org.cn -p {端口号}

2.2 运行

终端中输入

streamlit run web_demo.py --server.address 127.0.0.1 --server.port 6006

等待模型加载即可

image-20240207163042516

3.Lagent 智能体工具调用 Demo

3.1环境准备

跟1.1中一样

3.2 模型

cd /root/code
git clone https://gitee.com/internlm/lagent.git
cd /root/code/lagent
git checkout 511b03889010c4811b1701abb153e02b8e94fb5e # 尽量保证和教程commit版本一致
pip install -e . # 源码安装

3.3修改代码

应该做的也是修改模型参数文件

import copy
import osimport streamlit as st
from streamlit.logger import get_loggerfrom lagent.actions import ActionExecutor, GoogleSearch, PythonInterpreter
from lagent.agents.react import ReAct
from lagent.llms import GPTAPI
from lagent.llms.huggingface import HFTransformerCasualLMclass SessionState:def init_state(self):"""Initialize session state variables."""st.session_state['assistant'] = []st.session_state['user'] = []#action_list = [PythonInterpreter(), GoogleSearch()]action_list = [PythonInterpreter()]st.session_state['plugin_map'] = {action.name: actionfor action in action_list}st.session_state['model_map'] = {}st.session_state['model_selected'] = Nonest.session_state['plugin_actions'] = set()def clear_state(self):"""Clear the existing session state."""st.session_state['assistant'] = []st.session_state['user'] = []st.session_state['model_selected'] = Noneif 'chatbot' in st.session_state:st.session_state['chatbot']._session_history = []class StreamlitUI:def __init__(self, session_state: SessionState):self.init_streamlit()self.session_state = session_statedef init_streamlit(self):"""Initialize Streamlit's UI settings."""st.set_page_config(layout='wide',page_title='lagent-web',page_icon='./docs/imgs/lagent_icon.png')# st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')st.sidebar.title('模型控制')def setup_sidebar(self):"""Setup the sidebar for model and plugin selection."""model_name = st.sidebar.selectbox('模型选择:', options=['gpt-3.5-turbo','internlm'])if model_name != st.session_state['model_selected']:model = self.init_model(model_name)self.session_state.clear_state()st.session_state['model_selected'] = model_nameif 'chatbot' in st.session_state:del st.session_state['chatbot']else:model = st.session_state['model_map'][model_name]plugin_name = st.sidebar.multiselect('插件选择',options=list(st.session_state['plugin_map'].keys()),default=[list(st.session_state['plugin_map'].keys())[0]],)plugin_action = [st.session_state['plugin_map'][name] for name in plugin_name]if 'chatbot' in st.session_state:st.session_state['chatbot']._action_executor = ActionExecutor(actions=plugin_action)if st.sidebar.button('清空对话', key='clear'):self.session_state.clear_state()uploaded_file = st.sidebar.file_uploader('上传文件', type=['png', 'jpg', 'jpeg', 'mp4', 'mp3', 'wav'])return model_name, model, plugin_action, uploaded_filedef init_model(self, option):"""Initialize the model based on the selected option."""if option not in st.session_state['model_map']:if option.startswith('gpt'):st.session_state['model_map'][option] = GPTAPI(model_type=option)else:st.session_state['model_map'][option] = HFTransformerCasualLM('/root/model/Shanghai_AI_Laboratory/internlm-chat-7b')return st.session_state['model_map'][option]def initialize_chatbot(self, model, plugin_action):"""Initialize the chatbot with the given model and plugin actions."""return ReAct(llm=model, action_executor=ActionExecutor(actions=plugin_action))def render_user(self, prompt: str):with st.chat_message('user'):st.markdown(prompt)def render_assistant(self, agent_return):with st.chat_message('assistant'):for action in agent_return.actions:if (action):self.render_action(action)st.markdown(agent_return.response)def render_action(self, action):with st.expander(action.type, expanded=True):st.markdown("<p style='text-align: left;display:flex;'> <span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'>插    件</span><span style='width:14px;text-align:left;display:block;'>:</span><span style='flex:1;'>"  # noqa E501+ action.type + '</span></p>',unsafe_allow_html=True)st.markdown("<p style='text-align: left;display:flex;'> <span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'>思考步骤</span><span style='width:14px;text-align:left;display:block;'>:</span><span style='flex:1;'>"  # noqa E501+ action.thought + '</span></p>',unsafe_allow_html=True)if (isinstance(action.args, dict) and 'text' in action.args):st.markdown("<p style='text-align: left;display:flex;'><span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'> 执行内容</span><span style='width:14px;text-align:left;display:block;'>:</span></p>",  # noqa E501unsafe_allow_html=True)st.markdown(action.args['text'])self.render_action_results(action)def render_action_results(self, action):"""Render the results of action, including text, images, videos, andaudios."""if (isinstance(action.result, dict)):st.markdown("<p style='text-align: left;display:flex;'><span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'> 执行结果</span><span style='width:14px;text-align:left;display:block;'>:</span></p>",  # noqa E501unsafe_allow_html=True)if 'text' in action.result:st.markdown("<p style='text-align: left;'>" + action.result['text'] +'</p>',unsafe_allow_html=True)if 'image' in action.result:image_path = action.result['image']image_data = open(image_path, 'rb').read()st.image(image_data, caption='Generated Image')if 'video' in action.result:video_data = action.result['video']video_data = open(video_data, 'rb').read()st.video(video_data)if 'audio' in action.result:audio_data = action.result['audio']audio_data = open(audio_data, 'rb').read()st.audio(audio_data)def main():logger = get_logger(__name__)# Initialize Streamlit UI and setup sidebarif 'ui' not in st.session_state:session_state = SessionState()session_state.init_state()st.session_state['ui'] = StreamlitUI(session_state)else:st.set_page_config(layout='wide',page_title='lagent-web',page_icon='./docs/imgs/lagent_icon.png')# st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')model_name, model, plugin_action, uploaded_file = st.session_state['ui'].setup_sidebar()# Initialize chatbot if it is not already initialized# or if the model has changedif 'chatbot' not in st.session_state or model != st.session_state['chatbot']._llm:st.session_state['chatbot'] = st.session_state['ui'].initialize_chatbot(model, plugin_action)for prompt, agent_return in zip(st.session_state['user'],st.session_state['assistant']):st.session_state['ui'].render_user(prompt)st.session_state['ui'].render_assistant(agent_return)# User input form at the bottom (this part will be at the bottom)# with st.form(key='my_form', clear_on_submit=True):if user_input := st.chat_input(''):st.session_state['ui'].render_user(user_input)st.session_state['user'].append(user_input)# Add file uploader to sidebarif uploaded_file:file_bytes = uploaded_file.read()file_type = uploaded_file.typeif 'image' in file_type:st.image(file_bytes, caption='Uploaded Image')elif 'video' in file_type:st.video(file_bytes, caption='Uploaded Video')elif 'audio' in file_type:st.audio(file_bytes, caption='Uploaded Audio')# Save the file to a temporary location and get the pathfile_path = os.path.join(root_dir, uploaded_file.name)with open(file_path, 'wb') as tmpfile:tmpfile.write(file_bytes)st.write(f'File saved at: {file_path}')user_input = '我上传了一个图像,路径为: {file_path}. {user_input}'.format(file_path=file_path, user_input=user_input)agent_return = st.session_state['chatbot'].chat(user_input)st.session_state['assistant'].append(copy.deepcopy(agent_return))logger.info(agent_return.inner_steps)st.session_state['ui'].render_assistant(agent_return)if __name__ == '__main__':root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))root_dir = os.path.join(root_dir, 'tmp_dir')os.makedirs(root_dir, exist_ok=True)main()

3.4运行

与2.1中一样,先本机链接

ssh -CNg -L 6006:127.0.0.1:6006 root@ssh.intern-ai.org.cn -p {端口号}

然后远程终端运行即可

streamlit run /root/code/lagent/examples/react_web_demo.py --server.address 127.0.0.1 --server.port 6006

image-20240207164224609

我尝试了上传一张简单方程的图片,但是似乎失败了,模型并不能理解图中内容。(图中是3+x=6)image-20240207164257431

4.浦语·灵笔图文理解创作 Demo

4.1环境

从本地克隆一个已有的pytorch 2.0.1 的环境

/root/share/install_conda_env_internlm_base.sh xcomposer-demo

接下来运行以下命令,安装 transformersgradio 等依赖包

pip install transformers==4.33.1 timm==0.4.12 sentencepiece==0.1.99 gradio==3.44.4 markdown2==2.4.10 xlsxwriter==3.1.2 einops accelerate

4.2模型准备

复制比较快

mkdir -p /root/model/Shanghai_AI_Laboratory
cp -r /root/share/temp/model_repos/internlm-xcomposer-7b /root/model/Shanghai_AI_Laboratory

4.3代码

git clone https://gitee.com/internlm/InternLM-XComposer.git
cd /root/code/InternLM-XComposer
git checkout 3e8c79051a1356b9c388a6447867355c0634932d  # 最好保证和教程的 commit 版本一致

4.4运行

cd /root/code/InternLM-XComposer
python examples/web_demo.py  \--folder /root/model/Shanghai_AI_Laboratory/internlm-xcomposer-7b \--num_gpus 1 \--port 6006

image-20240207190028772

可以自动生成内容,并自动寻找合适图片!

其中还有多模态对话demo

image-20240207190344326

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

如若内容造成侵权/违法违规/事实不符,请联系编程老四网进行投诉反馈email:xxxxxxxx@qq.com,一经查实,立即删除!

相关文章

MPC自动驾驶横向控制算法实现 c++

参考博客&#xff1a; &#xff08;1&#xff09;无人车系统&#xff08;十一&#xff09;&#xff1a;轨迹跟踪模型预测控制(MPC)原理与python实现【40行代码】 &#xff08;2&#xff09;【自动驾驶】模型预测控制(MPC)实现轨迹跟踪 &#xff08;3&#xff09;自动驾驶——模…

【STM32 物联网】AT指令与TCP,发送与接收数据

文章目录 前言一、连接TCP服务器1.1 配置Wifi模式1.2 连接路由器1.3 查询ESP8266设备IP地址1.4 连接TCP服务器 二、向服务器接收数据和发送数据2.1 发送数据2.2 接收数据 总结 前言 随着物联网&#xff08;IoT&#xff09;技术的迅速发展&#xff0c;越来越多的设备和系统开始…

探索微信小程序的奇妙世界:从入门到进阶

文章目录 一、什么是微信小程序1.1 简要介绍微信小程序的定义和特点1.2 解释小程序与传统应用程序的区别 二、小程序的基础知识2.1 微信小程序的架构2.2 微信小程序生命周期的理解2.3 探索小程序的目录结构和文件类型 三、小程序框架和组件3.1 深入了解小程序框架的核心概念和原…

2024.02.22作业

1. 将互斥机制的代码实现重新敲一遍 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <…

由面试题“Redis是否为单线程”引发的思考

&#x1f468;‍&#x1f393;博主简介 &#x1f3c5;云计算领域优质创作者   &#x1f3c5;华为云开发者社区专家博主   &#x1f3c5;阿里云开发者社区专家博主 &#x1f48a;交流社区&#xff1a;运维交流社区 欢迎大家的加入&#xff01; &#x1f40b; 希望大家多多支…

Python 数据可视化之密度散点图 Density Scatter Plot

&#x1f349; CSDN 叶庭云&#xff1a;https://yetingyun.blog.csdn.net/ 密度散点图&#xff08;Density Scatter Plot&#xff09;&#xff0c;也称为密度点图或核密度估计散点图&#xff0c;是一种数据可视化技术&#xff0c;主要用于展示大量数据点在二维平面上的分布情况…

SCI一区 | Matlab实现GAF-PCNN-MSA格拉姆角场和双通道PCNN融合注意力机制的多特征分类预测

SCI一区 | Matlab实现GAF-PCNN-MSA格拉姆角场和双通道PCNN融合注意力机制的多特征分类预测 目录 SCI一区 | Matlab实现GAF-PCNN-MSA格拉姆角场和双通道PCNN融合注意力机制的多特征分类预测效果一览基本介绍模型描述程序设计参考资料 效果一览 基本介绍 1.【SCI一区级】Matlab实…

【Django】Django自定义后台表单——对一个关联外键对象同时添加多个内容

以官方文档为例&#xff1a; 一个投票问题包含多个选项&#xff0c;基本的表单设计只能一个选项一个选项添加&#xff0c;效率较低&#xff0c;如何在表单设计中一次性添加多个关联选项&#xff1f; 示例代码&#xff1a; from django.contrib import adminfrom .models impo…

十大基础排序算法

排序算法分类 排序&#xff1a;将一组对象按照某种逻辑顺序重新排列的过程。 按照待排序数据的规模分为&#xff1a; 内部排序&#xff1a;数据量不大&#xff0c;全部存在内存中&#xff1b;外部排序&#xff1a;数据量很大&#xff0c;无法一次性全部存在内存中&#xff0c;…

排序算法(一)

目录 一、插入排序 1.直接插入排序 &#xff08;1&#xff09;基本思想 &#xff08;2&#xff09;代码实现&#xff08;升序&#xff09; &#xff08;3&#xff09;分析 2.希尔排序 &#xff08;1&#xff09;基本思想 &#xff08;2&#xff09;代码实现&#xff08…

unity学习(36)——角色选取界面(自制美工)

1.添加一个背景图片&#xff0c;记不住可以查之前的资料&#xff08;4&#xff09; 图片拖入asset&#xff0c;属性设成sprite&#xff1b;把图片拖到source image中&#xff1b;colour白色&#xff08;透明&#xff0c;点一下右边的笔即可&#xff09;&#xff1b;material为…

C++--Linux基础使用

文章目录 几个简单命令开机关机重启查看当前目录切换当前目录列出当前目录下的目录和文件列出指定目录下的目录和文件清屏查看/设置时间 目录和文件目录概要目录详细说明相对路径和绝对路径 上古神器vi创建/打开文件vi 的两种模式vi 的常用命令 用户管理组管理用户管理修改用户…

阿里云ECS香港服务器性能强大_安全可靠香港免备案服务器

阿里云香港服务器中国香港数据中心网络线路类型BGP多线精品&#xff0c;中国电信CN2高速网络高质量、大规格BGP带宽&#xff0c;运营商精品公网直连中国内地&#xff0c;时延更低&#xff0c;优化海外回中国内地流量的公网线路&#xff0c;可以提高国际业务访问质量。阿里云服务…

一文了解大数据生态

大数据一词最早指的是传统数据处理应用软件无法处理的过于庞大或过于复杂的数据集。 现在&#xff0c;对“大数据”一词的使用倾向于使用预测分析、用户行为分析或者其他一些从大数据中提取价值的高级数据分析方法&#xff0c;很少用于表示特定规模的数据集。 定义 大数据是…

typescript类型详解

因为介绍了ts的全部类型,所以比较长,各位可以通过目录选择性观看 typescript类型概述typescript 类型注解概念-->监测类型变化 ts类型注解语法ts常用类型原始类型对象类型对象类型_数组类型 ts新增,联合类型ts函数类型ts 函数类型 voidts 函数类型可选参数 ts 对象类型ts 可…

docker之安装mongo创建运行环境

目录 一、docker pull 最新资源 二、启动mongo镜像 启动命令查看日志拉取低版本镜像成功启动 三、进入mongo容器 进入容器进入mongo环境查询当前所在库切换库至admin随意切换库 并 创建用户登录用户新增文档数据等 五、总结 版本兼容可备份操作 一、docker pull 最新资源…

RK3588平台开发系列讲解(视频篇)ffmpeg 的移植

文章目录 一、ffmpeg 介绍二、ffmpeg 的组成三、ffmpeg 依赖库沉淀、分享、成长,让自己和他人都能有所收获!😄 📢ffmpeg 是一种多媒体音视频处理工具,具备视频采集功能、视频抓取图像、视频格式转换、给视频加水印并能将视频转化为流等诸多强大的功能。它采用 LGPL 或 G…

第39期 | GPTSecurity周报

GPTSecurity是一个涵盖了前沿学术研究和实践经验分享的社区&#xff0c;集成了生成预训练Transformer&#xff08;GPT&#xff09;、人工智能生成内容&#xff08;AIGC&#xff09;以及大型语言模型&#xff08;LLM&#xff09;等安全领域应用的知识。在这里&#xff0c;您可以…

【人工智能学习思维脉络导图】

曾梦想执剑走天涯&#xff0c;我是程序猿【AK】 目录 知识图谱1. 基础知识2.人工智能核心概念3.实践与应用4.持续学习与进展5.挑战与自我提升6.人脉网络 知识图谱 人工智能学习思维脉络导图 1. 基础知识 计算机科学基础数学基础&#xff08;线性代数、微积分、概率论和统计学…

7 数据迁移至达梦数据库

无论使用哪种解决方案很大可能性都需要进行数据迁移&#xff0c;即将旧的非 达梦数据库的数据迁移到达梦数据库。 我们要把 Nacos 的数据或者 SQL 语句迁移到达梦数据库。借助 DM 数据迁移工具 &#xff0c;完成 Nacos 配置数据表迁移到达梦数据库。
推荐文章