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

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, AutoModelForCausalLM


model_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":
        break
    response, 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 os

import streamlit as st
from streamlit.logger import get_logger

from lagent.actions import ActionExecutor, GoogleSearch, PythonInterpreter
from lagent.agents.react import ReAct
from lagent.llms import GPTAPI
from lagent.llms.huggingface import HFTransformerCasualLM


class 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: action
            for action in action_list
        }
        st.session_state['model_map'] = {}
        st.session_state['model_selected'] = None
        st.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'] = None
        if '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_state

    def 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_name
            if '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_file

    def 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 E501
                    unsafe_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, and
        audios."""
        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 E501
                unsafe_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 sidebar
    if '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 changed
    if '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 sidebar
        if uploaded_file:
            file_bytes = uploaded_file.read()
            file_type = uploaded_file.type
            if '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 path
            file_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.mfbz.cn/a/395185.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

大数据信用风险检测,多久查一次比较好?

自从大数据技术的出现&#xff0c;就被广泛的运用到金融风控行业&#xff0c;逐渐成为不少银行和机构进行贷前风险排查的重要工具&#xff0c;大数据信用的重要性也日益的显现出来&#xff0c;那大数据信用风险检测&#xff0c;多久查一次比较好呢?本文为你详细讲讲。 大数据信…

[AudioRecorder]iPhone苹果通话录音汉化破解版-使用巨魔安装-ios17绕道目前还不支持

首先你必须有巨魔才能使用&#xff01;&#xff01; 不会安装的&#xff0c;还没安装的移步这里&#xff0c;ios17 以上目前装不了&#xff0c;别看了&#xff1a;永久签名 | 网址分类目录 | 路灯iOS导航-苹果签名实用知识网址导航-各种iOS技巧-后厂村路灯 视频教程 【Audio…

森林消防利器:智能高压森林应急消防泵

在森林火灾防控工作中&#xff0c;智能高压森林应急消防泵发挥着至关重要的作用。它是一种由高强度耐腐蚀材料加工制造而成的消防泵&#xff0c;具有体积小、重量轻、压力大、扬程高、流量大、输水距离远等优点&#xff0c;运行可靠&#xff0c;能够迅速扑灭森林火灾&#xff0…

SG-9101CB(可编程+105℃晶体振荡器)

SG-9101CB 系列是一款高精度可编程性的晶体振荡器&#xff0c;能够在0.67 MHz至170 MHz的频率范围内以1ppm的步长精确调整频率。这款振荡器支持宽范围的电源电压&#xff08;1.62 V至3.63V&#xff09;&#xff0c;并提供使能&#xff08;OE&#xff09;或待机&#xff08;ST&a…

Java学习第十七节之封装

封装 package oop.demo04;//类 private:私有 public class Student {//属性私有private String name;//名字private int id;//学号private char sex;//性别private int age;//年龄//提供一些可以操作这个属性的方法&#xff01;//提供一些 public 的 get&#xff0c;set 方法…

如何使用Net2FTP部署本地Web网站并实现远程文件共享

文章目录 1.前言2. Net2FTP网站搭建2.1. Net2FTP下载和安装2.2. Net2FTP网页测试 3. cpolar内网穿透3.1.Cpolar云端设置3.2.Cpolar本地设置 4.公网访问测试5.结语 1.前言 文件传输可以说是互联网最主要的应用之一&#xff0c;特别是智能设备的大面积使用&#xff0c;无论是个人…

做temu跨境电商,必读这五大秘诀!

随着互联网的飞速发展&#xff0c;电商行业呈现出前所未有的繁荣景象。新兴电商平台Temu成为了众多创业者的关注焦点。本文将为您解析如何在Temu电商蓝海项目中&#xff0c;从自身能力建设、了解市场环境到做好定位等方面&#xff0c;找到属于您的成功之路。 一、自身能力建设 …

【QCA6174】SDX12+QCA6174驱动屏蔽120/124/128信道修改方案

SDX12基线版本 SDX12.LE.1.0-00215-NBOOT.NEFS.PROD-1.39743.1 问题描述 对于欧洲国家来说,默认支持DFS信道,但是有三个信道比较特殊,是天气雷达信道,如下图所示120、124、128,天气雷达信道有个特点就是在信号可以发射之前需要检测静默15min,如果信道自动选择到了天气雷达…

原创!顶级SCI优化!一键实现ICEEMDAN-NRBO-BiLSTM-Attention多变量时间序列预测!以光伏数据集为例

声明&#xff1a;文章是从本人公众号中复制而来&#xff0c;因此&#xff0c;想最新最快了解各类智能优化算法及其改进的朋友&#xff0c;可关注我的公众号&#xff1a;强盛机器学习&#xff0c;不定期会有很多免费代码分享~ 目录 数据介绍 模型流程 创新点 结果展示 完整…

C++ STL详解:set

目录 一、简介 1.1键值对 1.2树形结构的关联式容器 二、set 2.1set简介 2.2set内部常用接口 2.1set的构造函数 2.2set迭代器 2.3判空及增删查改 三、使用例子 一、简介 在前几篇文章中&#xff0c;已经学习了二叉搜索树&#xff0c;二map和set的底层就是<key, va…

数据采集三防平板丨三防平板电脑丨停车场应用

随着现代科技的不断发展&#xff0c;三防平板已经成为许多人工作和生活的必备工具。在停车场这个场景中&#xff0c;三防平板的应用可以大大提高停车场管理的效率和安全性。 停车场是现代城市交通管理的重要组成部分&#xff0c;它直接关系到城市交通的流畅和公共安全。停车场…

国图公考:为什么考编?应届生考编有优势吗?

当下公务员和事业编成为大部分人的选择&#xff0c;事业编考试和公务员考试对比有哪些优势?为什么考编? 1.竞争激烈程度 虽然每年报考事业编的人有很多&#xff0c;但是和公务员相比起来竞争并没有那么激烈。 2.考试难度 事业编和公务员在考试内容上有一定的差异&#xf…

深度学习基础——卷积神经网络(一)

卷积操作与自定义算子开发 卷积是卷积神经网络中的基本操作&#xff0c;对于图像的特征提取有着关键的作用&#xff0c;本文首先介绍卷积的基本原理与作用&#xff0c;然后通过编写程序实现卷积操作&#xff0c;并展示了均值、高斯与sobel等几种经典卷积核的卷积效果&#xff…

达梦数据库——数据迁移sqlserver-dm报错问题_未完待续

记录SQL server到达梦数据迁移过程中遇到的问题&#xff0c;持续更新中... 报错情况一&#xff1a;Sql server迁移达梦连接报错’驱动程序无法通过使用安全套接字Q层(SSL)加密与SQL Server 建立安全连接。错误:“The server selected protocol version TLS10 is not accepted b…

AI应用第二弹:心焚-人工智能分类、推送、阅后即焚的新闻app

春节期间&#xff0c;爆肝开发了这款AI新闻客户端。这也是我多年前的愿望&#xff0c;但那时苦于没有合适的AI分类&#xff0c;一直拖到现在终于实现了。作为一个新闻剁手党&#xff0c;一直希望有一款app&#xff0c;只推送我感兴趣的重大新闻&#xff0c;看完拉倒&#xff0c…

E4982A LCR 表,1 MHz 至 300 MHz / 500 MHz / 1 GHz / 3 GHz

E4982A LCR 表 Keysight E4982A LCR 表的性能十分出色&#xff0c;适用于在 SMD 电感器和 EMI 滤波器等无源元器件的制造过程中提供高频&#xff08;1 MHz 至 300 MHz / 500 MHz / 1 GHz / 3 GHz&#xff09;阻抗测试。 E4982A 提供了列表测量等强大功能&#xff0c;不仅适用于…

电商数据分析工具(京东淘宝电商数据):电商运营过程中为什么要做数据分析?电商企业如何做好数据分析?

众所周知&#xff0c;电商企业进行数据分析是电商运营中的重要一环&#xff0c;电商数据分析是企业持续改进业务流程、提高运营效率、增加收入和利润的关键。 通过深入的数据分析&#xff0c;电商企业能够更有效地响应市场需求、提高客户满意度&#xff0c;最终实现可持续增长…

【AI绘画】2024最新Stable Diffusion 超详细讲解!!必收藏!!!!

手把手教你入门绘图超强的AI绘画&#xff0c;用户只需要输入一段图片的文字描述&#xff0c;即可生成精美的绘画。给大家带来了全新保姆级教程资料包 &#xff08;文末可获取&#xff09; Stable Diffusion 超详细讲解 这篇文章是 《Stable Diffusion原理详解》的后续&#x…

HCIP-MGRE实验配置、PPP的PAP认证与CHAP认证、MGRE、GRE网络搭建、NAT

实验要求 R5为ISP,只能进行IP地址配素&#xff0c;其所有地址均为公有IP地址R1和R5间使用PPP的PAP认证&#xff0c;R5为主认证方 R2与R5之间使用PPP的chap认证&#xff0c;R5为主认证方 R3与R5之间使用HDLC封装。R1/R2/R3构建一个MGRE环境&#xff0c;R1为中心站点;R1、R4间为…

如何使用Sora?Sora小白教程一文通

如果需要使用Sora或者GPT4&#xff0c;请参考文章&#xff1a;如何使用Sora&#xff1f;Sora小白教程一文通 什么是Sora Sora是OpenAI于2024年2月18日凌晨发布的新的文生视频大模型&#xff0c;名为 “ Sora ”。 从OpenAI在官网展示的Sora生成视频的效果来看&#xff0c;在生…