当前位置:   article > 正文

DataWhale训练营个人笔记1:关于ChatGLM3部署后代码的进一步注释(以哔站其它ChatGML教程的详细解释为准)_chatgml3

chatgml3

推荐食用顺序:

1.直接按教程先部署上。

2.看代码注释,然后你就会发现全是掉包,毫无难度。

3.了解一些概念,比如量化。

4.进阶学习模型,看ptuining教程。大头在那里呢,这年头掉包侠没人要了。

个人基础介绍:

LLM大模型零基础,研一,有少部分ML和大数据分析经验,有一咩咩前后端经验。

课程评价:

首先,它完全免费。其次,教程里相当于手把手教学,但只教操作不教原因,也就是说,里面的代码需要你自己弄懂怎么回事。

web_demo.py文件

  1. #demo.py文件
  2. from transformers import AutoModel, AutoTokenizer
  3. import gradio as gr
  4. import mdtex2html
  5. from utils import load_model_on_gpus
  6. #加载预训练tokenizer,且表示信任远程代码
  7. tokenizer = AutoTokenizer.from_pretrained("../../pretrain", trust_remote_code=True)
  8. #加载预训练模型到CUDA设备上,默认是fp16.如果设备算力不够可以改成int8int4之类不同量化版本的模型。
  9. #model = AutoModel.from_pretrained("../../pretrain", trust_remote_code=True).quantize(8)cuda()就是改成int8
  10. model = AutoModel.from_pretrained("../../pretrain", trust_remote_code=True).cuda()
  11. # 多显卡支持,使用下面两行代替上面一行,将num_gpus改为你实际的显卡数量
  12. # from utils import load_model_on_gpus
  13. # model = load_model_on_gpus("THUDM/chatglm3-6b", num_gpus=2)
  14. #实例化模型
  15. model = model.eval()
  16. """Override Chatbot.postprocess"""
  17. # 自定义Chatbot.postprocess方法,处理模型的输出结果
  18. def postprocess(self, y):
  19. if y is None:
  20. return []
  21. for i, (message, response) in enumerate(y):
  22. # 将message和response使用mdtex2html库转换格式
  23. y[i] = (
  24. None if message is None else mdtex2html.convert((message)),
  25. None if response is None else mdtex2html.convert(response),
  26. )
  27. return y
  28. # 将自定义的postprocess方法应用到Chatbot类
  29. gr.Chatbot.postprocess = postprocess
  30. # 解析文本格式的输入
  31. def parse_text(text):
  32. """copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
  33. lines = text.split("\n")
  34. lines = [line for line in lines if line != ""]
  35. count = 0
  36. for i, line in enumerate(lines):
  37. if "```" in line:
  38. count += 1
  39. items = line.split('`')
  40. if count % 2 == 1:
  41. lines[i] = f'<pre><code class="language-{items[-1]}">'
  42. else:
  43. lines[i] = f'<br></code></pre>'
  44. else:
  45. if i > 0:
  46. if count % 2 == 1:
  47. line = line.replace("`", "\`")
  48. line = line.replace("<", "&lt;")
  49. line = line.replace(">", "&gt;")
  50. line = line.replace(" ", "&nbsp;")
  51. line = line.replace("*", "&ast;")
  52. line = line.replace("_", "&lowbar;")
  53. line = line.replace("-", "&#45;")
  54. line = line.replace(".", "&#46;")
  55. line = line.replace("!", "&#33;")
  56. line = line.replace("(", "&#40;")
  57. line = line.replace(")", "&#41;")
  58. line = line.replace("$", "&#36;")
  59. lines[i] = "<br>"+line
  60. text = "".join(lines)
  61. return text
  62. # 预测方法
  63. def predict(input, chatbot, max_length, top_p, temperature, history, past_key_values):
  64. chatbot.append((parse_text(input), "")) # 将输入添加到chatbot中
  65. for response, history, past_key_values in model.stream_chat(tokenizer, input, history, past_key_values=past_key_values,
  66. return_past_key_values=True,
  67. max_length=max_length, top_p=top_p,
  68. temperature=temperature):
  69. # 更新chatbot的最后一个对话结果
  70. chatbot[-1] = (parse_text(input), parse_text(response))
  71. # 返回chatbot、history和past_key_values
  72. yield chatbot, history, past_key_values
  73. # 重置用户输入
  74. def reset_user_input():
  75. return gr.update(value='')
  76. #重置状态
  77. def reset_state():
  78. return [], [], None
  79. # 创建交互式界面
  80. with gr.Blocks() as demo:
  81. gr.HTML("""<h1 align="center">ChatGLM3-6B</h1>""")
  82. chatbot = gr.Chatbot()
  83. with gr.Row():
  84. with gr.Column(scale=4):
  85. with gr.Column(scale=12):
  86. user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10).style(
  87. container=False)
  88. with gr.Column(min_width=32, scale=1):
  89. submitBtn = gr.Button("Submit", variant="primary")
  90. with gr.Column(scale=1):
  91. emptyBtn = gr.Button("Clear History")
  92. max_length = gr.Slider(0, 8192, value=8192, step=1.0, label="Maximum length", interactive=True)
  93. top_p = gr.Slider(0, 1, value=0.8, step=0.01, label="Top P", interactive=True)
  94. temperature = gr.Slider(0, 1, value=0.95, step=0.01, label="Temperature", interactive=True)
  95. # 定义需要保存的状态
  96. history = gr.State([])
  97. past_key_values = gr.State(None)
  98. # 设置按钮的点击事件
  99. submitBtn.click(predict, [user_input, chatbot, max_length, top_p, temperature, history, past_key_values],
  100. [chatbot, history, past_key_values], show_progress=True)
  101. submitBtn.click(reset_user_input, [], [user_input])
  102. emptyBtn.click(reset_state, outputs=[chatbot, history, past_key_values], show_progress=True)
  103. # 启动交互式界面
  104. demo.queue().launch(share=True, server_name="0.0.0.0",server_port=7000)

 web_demo2.py文件

  1. # 导入所需的模块
  2. from transformers import AutoModel, AutoTokenizer # 导入transformers库的AutoModel和AutoTokenizer
  3. import streamlit as st # 导入streamlit库用于构建交互式界面
  4. # 设置页面配置
  5. st.set_page_config(
  6. page_title="ChatGLM3-6b 演示",
  7. page_icon=":robot:",
  8. layout='wide'
  9. )
  10. # 从缓存中获取模型
  11. @st.cache_resource
  12. def get_model():
  13. tokenizer = AutoTokenizer.from_pretrained("../../pretrain", trust_remote_code=True)
  14. model = AutoModel.from_pretrained("../../pretrain", trust_remote_code=True).cuda()
  15. # 多显卡支持,使用下面两行代码代替上面一行代码。将num_gpus改为你实际的显卡数量。
  16. # from utils import load_model_on_gpus
  17. # model = load_model_on_gpus("THUDM/chatglm3-6b", num_gpus=2)
  18. model = model.eval()
  19. return tokenizer, model
  20. tokenizer, model = get_model()
  21. # 设置页面标题
  22. st.title("ChatGLM3-6B")
  23. # 设置侧边栏选项
  24. max_length = st.sidebar.slider(
  25. 'max_length', 0, 8192, 8192, step=1
  26. )
  27. top_p = st.sidebar.slider(
  28. 'top_p', 0.0, 1.0, 0.8, step=0.01
  29. )
  30. temperature = st.sidebar.slider(
  31. 'temperature', 0.0, 1.0, 0.8, step=0.01
  32. )
  33. # 检查会话状态中是否存在历史记录
  34. if 'history' not in st.session_state:
  35. st.session_state.history = []
  36. # 检查会话状态中是否存在过去的键值
  37. if 'past_key_values' not in st.session_state:
  38. st.session_state.past_key_values = None
  39. # 显示历史对话记录
  40. for i, message in enumerate(st.session_state.history):
  41. if message["role"] == "user":
  42. with st.chat_message(name="user", avatar="user"):
  43. st.markdown(message["content"])
  44. else:
  45. with st.chat_message(name="assistant", avatar="assistant"):
  46. st.markdown(message["content"])
  47. # 显示用户输入框
  48. with st.chat_message(name="user", avatar="user"):
  49. input_placeholder = st.empty()
  50. # 显示助手回复框
  51. with st.chat_message(name="assistant", avatar="assistant"):
  52. message_placeholder = st.empty()
  53. # 显示用户输入区域
  54. prompt_text = st.text_area(label="用户命令输入",
  55. height=100,
  56. placeholder="请在这儿输入您的命令")
  57. # 显示发送按钮
  58. button = st.button("发送", key="predict")
  59. # 如果点击了发送按钮
  60. if button:
  61. input_placeholder.markdown(prompt_text)
  62. history, past_key_values = st.session_state.history, st.session_state.past_key_values
  63. # 使用模型预测并生成回复
  64. for response, history, past_key_values in model.stream_chat(tokenizer, prompt_text, history,
  65. past_key_values=past_key_values,
  66. max_length=max_length, top_p=top_p,
  67. temperature=temperature,
  68. return_past_key_values=True):
  69. message_placeholder.markdown(response)
  70. # 更新会话状态中的历史记录和过去的键值
  71. st.session_state.history = history
  72. st.session_state.past_key_values = past_key_values
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/814029
推荐阅读
  

闽ICP备14008679号