当前位置:   article > 正文

LLM大语言模型(十六):最新开源 GLM4-9B 本地部署,带不动,根本带不动

glm4-9b

目录

前言

本机环境

GLM4代码库下载

模型文件下载:文件很大

修改为从本地模型文件启动

启动模型cli对话demo

慢,巨慢,一个字一个字的蹦

GPU资源使用情况 

GLM3资源使用情况对比


前言

GLM-4-9B 是智谱 AI 推出的最新一代预训练模型 GLM-4 系列中的开源版本。

在语义、数学、推理、代码和知识等多方面的数据集测评中, GLM-4-9B 及其人类偏好对齐的版本 GLM-4-9B-Chat 均表现出超越 Llama-3-8B 的卓越性能。

除了能进行多轮对话,GLM-4-9B-Chat 还具备网页浏览、代码执行、自定义工具调用(Function Call)和长文本推理(支持最大 128K 上下文)等高级功能。

本代模型增加了多语言支持,支持包括日语,韩语,德语在内的 26 种语言。

我们还推出了支持 1M 上下文长度(约 200 万中文字符)的 GLM-4-9B-Chat-1M 模型和基于 GLM-4-9B 的多模态模型 GLM-4V-9B。GLM-4V-9B 具备 1120 * 1120 高分辨率下的中英双语多轮对话能力,在中英文综合能力、感知推理、文字识别、图表理解等多方面多模态评测中,GLM-4V-9B 表现出超越 GPT-4-turbo-2024-04-09、Gemini 1.0 Pro、Qwen-VL-Max 和 Claude 3 Opus 的卓越性能。

本机环境

OS:Windows

CPU:AMD Ryzen 5 3600X 6-Core Processor

Mem:32GB

GPU:RTX 4060Ti 16G

GLM4代码库下载

参考:LLM大语言模型(一):ChatGLM3-6B本地部署_llm3 部署-CSDN博客

  1. # 下载代码库
  2. https://github.com/THUDM/GLM-4.git

模型文件下载:文件很大

建议从modelscope下载模型,这样就不用担心网络问题了。

模型链接如下: 

glm-4-9b-chat汇聚各领域最先进的机器学习模型,提供模型探索体验、推理、训练、部署和应用的一站式服务。icon-default.png?t=N7T8https://modelscope.cn/models/ZhipuAI/glm-4-9b-chat/files

  1. git lfs install # 以安装则忽略
  2. git clone https://www.modelscope.cn/ZhipuAI/glm-4-9b-chat.git

做好心理准备:接近20G(我的带宽只有300Mbps~~)

修改为从本地模型文件启动

修改此文件basic_demo/trans_cli_demo.py

修改这一行:

MODEL_PATH = os.environ.get('MODEL_PATH', 'D:\github\glm-4-9b-chat') 该为你下载的模型文件夹

  1. """
  2. This script creates a CLI demo with transformers backend for the glm-4-9b model,
  3. allowing users to interact with the model through a command-line interface.
  4. Usage:
  5. - Run the script to start the CLI demo.
  6. - Interact with the model by typing questions and receiving responses.
  7. Note: The script includes a modification to handle markdown to plain text conversion,
  8. ensuring that the CLI interface displays formatted text correctly.
  9. """
  10. import os
  11. import torch
  12. from threading import Thread
  13. from typing import Union
  14. from pathlib import Path
  15. from peft import AutoPeftModelForCausalLM, PeftModelForCausalLM
  16. from transformers import (
  17. AutoModelForCausalLM,
  18. AutoTokenizer,
  19. PreTrainedModel,
  20. PreTrainedTokenizer,
  21. PreTrainedTokenizerFast,
  22. StoppingCriteria,
  23. StoppingCriteriaList,
  24. TextIteratorStreamer
  25. )
  26. ModelType = Union[PreTrainedModel, PeftModelForCausalLM]
  27. TokenizerType = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
  28. # 改为你下载的模型文件夹
  29. MODEL_PATH = os.environ.get('MODEL_PATH', 'D:\github\glm-4-9b-chat')
  30. def load_model_and_tokenizer(
  31. model_dir: Union[str, Path], trust_remote_code: bool = True
  32. ) -> tuple[ModelType, TokenizerType]:
  33. model_dir = Path(model_dir).expanduser().resolve()
  34. if (model_dir / 'adapter_config.json').exists():
  35. model = AutoPeftModelForCausalLM.from_pretrained(
  36. model_dir, trust_remote_code=trust_remote_code, device_map='auto')
  37. tokenizer_dir = model.peft_config['default'].base_model_name_or_path
  38. else:
  39. model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=trust_remote_code, device_map='auto')
  40. tokenizer_dir = model_dir
  41. tokenizer = AutoTokenizer.from_pretrained(
  42. tokenizer_dir, trust_remote_code=trust_remote_code, encode_special_tokens=True, use_fast=False
  43. )
  44. return model, tokenizer
  45. model, tokenizer = load_model_and_tokenizer(MODEL_PATH, trust_remote_code=True)
  46. class StopOnTokens(StoppingCriteria):
  47. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
  48. stop_ids = model.config.eos_token_id
  49. for stop_id in stop_ids:
  50. if input_ids[0][-1] == stop_id:
  51. return True
  52. return False
  53. if __name__ == "__main__":
  54. history = []
  55. max_length = 8192
  56. top_p = 0.8
  57. temperature = 0.6
  58. stop = StopOnTokens()
  59. print("Welcome to the GLM-4-9B CLI chat. Type your messages below.")
  60. while True:
  61. user_input = input("\nYou: ")
  62. if user_input.lower() in ["exit", "quit"]:
  63. break
  64. history.append([user_input, ""])
  65. messages = []
  66. for idx, (user_msg, model_msg) in enumerate(history):
  67. if idx == len(history) - 1 and not model_msg:
  68. messages.append({"role": "user", "content": user_msg})
  69. break
  70. if user_msg:
  71. messages.append({"role": "user", "content": user_msg})
  72. if model_msg:
  73. messages.append({"role": "assistant", "content": model_msg})
  74. model_inputs = tokenizer.apply_chat_template(
  75. messages,
  76. add_generation_prompt=True,
  77. tokenize=True,
  78. return_tensors="pt"
  79. ).to(model.device)
  80. streamer = TextIteratorStreamer(
  81. tokenizer=tokenizer,
  82. timeout=60,
  83. skip_prompt=True,
  84. skip_special_tokens=True
  85. )
  86. generate_kwargs = {
  87. "input_ids": model_inputs,
  88. "streamer": streamer,
  89. "max_new_tokens": max_length,
  90. "do_sample": True,
  91. "top_p": top_p,
  92. "temperature": temperature,
  93. "stopping_criteria": StoppingCriteriaList([stop]),
  94. "repetition_penalty": 1.2,
  95. "eos_token_id": model.config.eos_token_id,
  96. }
  97. t = Thread(target=model.generate, kwargs=generate_kwargs)
  98. t.start()
  99. print("GLM-4:", end="", flush=True)
  100. for new_token in streamer:
  101. if new_token:
  102. print(new_token, end="", flush=True)
  103. history[-1][1] += new_token
  104. history[-1][1] = history[-1][1].strip()

启动模型cli对话demo

运行该py文件即可,效果如下:

模型运行时会报个warning:

C:\Users\Administrator\.cache\huggingface\modules\transformers_modules\glm-4-9b-chat\modeling_chatglm.pm.py:189: UserWarning: 1Torch was not compiled with flash attention. (Triggered internally at C:\cb\pytorc000h_1000000000000\work\aten\src\ATen\native\transformers\cuda\sdp_utils.cpp:263.)
  context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer, 

不过也没影响运行。

慢,巨慢,一个字一个字的蹦

GPU资源使用情况 

  • 16G显存,使用率90%+
  • 内存使用16G,50%

GLM3资源使用情况对比

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/695281
推荐阅读
相关标签
  

闽ICP备14008679号