科研王炸——MOSS语言模型

MOSS是由复旦大学开发的一种聊天型语言模型,可以帮助您完成各种语言任务。如果您想在自己的本地或远程服务器上使用MOSS,可以按照以下步骤进行部署:

下载本仓库内容至本地或远程服务器,可以使用以下命令:git clone https://github.com/OpenLMLab/MOSS.git

进入MOSS目录,并创建一个conda环境,可以使用以下命令:

conda create --name moss python=3.8

conda activate moss

安装依赖,可以使用以下命令:pip install -r requirements.txt

进行单卡部署(A100/A800):

可以使用以下示例代码在单张A100/A800CPU上运行MOSS

from transformers import AutoTokenizer, AutoModelForCausalLM

tokenizer = AutoTokenizer.from_pretrained("fnlp/moss-moon-003-sft", trust_remote_code=True)

model = AutoModelForCausalLM.from_pretrained("fnlp/moss-moon-003-sft", trust_remote_code=True).half().cuda()

model = model.eval()

在代码中,您可以使用自己的问题和话语与MOSS进行对话,如下所示:

query = "您好<eoh>\n:"

inputs = tokenizer(query, return_tensors="pt")

outputs = model.generate(inputs, do_sample=True, temperature=0.7, top_p=0.8, repetition_penalty=1.1, max_new_tokens=256)

response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)

print(response)

进行多卡部署(两张或以上3090):

可以使用以下代码在两张NVIDIA 3090显卡上运行MOSS推理:

import os

import torch

from huggingface_hub import snapshot_download

from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM

from accelerate import init_empty_weights, load_checkpoint_and_dispatch

os.environ['CUDA_VISIBLE_DEVICES'] = "0,1"

model_path = "fnlp/moss-moon-003-sft"

if not os.path.exists(model_path):

model_path = snapshot_download(model_path)

config = AutoConfig.from_pretrained("fnlp/moss-moon-003-sft", trust_remote_code=True)

tokenizer = AutoTokenizer.from_pretrained("fnlp/moss-moon-003-sft", trust_remote_code=True)

with init_empty_weights():

model = AutoModelForCausalLM.from_config(config, torch_dtype=torch.float16, trust_remote_code=True)

model.tie_weights()

model = load_checkpoint_and_dispatch(model, model_path, device_map="auto", no_split_module_classes=["MossBlock"], dtype=torch.float16)

以下是一个简单的调用moss-moon-003-sft生成对话的示例代码,您可以在单张A100/A800CPU上运行,使用FP16精度时约占用30GB显存:

06c756e7ea3c8f6bb4b0b4b1f0b7ad82.png

如果您有任何疑问,请在评论区留言。

特别鸣谢:

「段小草」https://www.zhihu.com/question/596908242/answer/2994650882

「孙天祥」https://www.zhihu.com/question/596908242/answer/2994534005

猜你喜欢

转载自blog.csdn.net/E_Magic_Cube/article/details/130717065