跑LLM的记录(持续更新)

本文介绍了如何从HuggingFace下载并部署开源模型vicuna-7b进行推理,包括下载方法、处理模型过大的技巧,以及解决tokenizer加载错误和安装问题的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 下载开源模型并进行推理的方法(以vicuna-7b为例):

  1. 【方法一】从网站(https://huggingface.co/lmsys/vicuna-7b-v1.5/tree/main)下载源文件。注意,要下载全部源文件。一般会包含LLM的weights,以及tokenizer的相关文件,全部上传到服务器,放在同一个文件夹里。
    【方法二】或者在本地运行如下代码进行下载,然后再上传到服务器。注意,在windows下,运行如下代码会将模型和相关文件下载到C:\Users\用户名.cache\huggingface\hub\models–lmsys–vicuna-7b-v1.5,里边会包含多个文件夹,模型文件的路径为C:\Users\用户名.cache\huggingface\hub\models–lmsys–vicuna-7b-v1.5\snapshots\de56c35b1763eaae20f4d60efd64af0a9091ebe5。
    from transformers import AutoTokenizer, AutoModelForCausalLM
    import torch
    tokenizer = AutoTokenizer.from_pretrained("lmsys/vicuna-7b-v1.5")
    model = AutoModelForCausalLM.from_pretrained("lmsys/vicuna-7b-v1.5")
    torch.save(model, "D:/Documemts/experiments/huggingface_download/downloaded_models/vicuna-7b-v1.5-model.pt")
    torch.save(model, "D:/Documemts/experiments/huggingface_download/downloaded_models/vicuna-7b-v1.5-tokenizer.pt")
    
  2. 服务器端加载模型并推理:
    from transformers import pipeline
    import torch
    from transformers import AutoTokenizer, AutoModelForCausalLM
    
    # 加载模型
    device="cuda:7"
    model = AutoModelForCausalLM.from_pretrained("/checkpoints/models--lmsys--vicuna-7b-v1.5/snapshots/de56c35b1763eaae20f4d60efd64af0a9091ebe5")
    model.half()
    model.to(device)
    print('模型加载完毕')
    # 加载分词器
    tokenizer = AutoTokenizer.from_pretrained("/checkpoints/models--lmsys--vicuna-7b-v1.5/snapshots/de56c35b1763eaae20f4d60efd64af0a9091ebe5",use_fast=False)
    print('分词器加载完毕')
    # 创建pipeline
    device_id = int(device.split(":")[-1])
    gen = pipeline("text-generation", model=model, tokenizer=tokenizer, device=device_id)
    # 使用pipeline生成文本时设置参数
    prompt = "If a movie review is positive, you need to output '111'. If a movie review is negative, you need to output '222'. Movie review: the movie is lovely and excellent."
    generated_texts = gen(prompt,
                          max_length=50,
                          temperature=0.4,
                          top_k=50,
                          top_p=0.95,
                          repetition_penalty=1.2,
                          length_penalty=1.0,
                          num_return_sequences=1)
    
    # 打印生成的文本
    print("##############Model output###############")
    for generated_text in generated_texts:
        print(generated_text["generated_text"])
    

2. 模型太大,load到一张gpu里装不下时,可以考虑使用model.half()

from transformers import AutoTokenizer, AutoModelForCausalLM
# 加载模型
device="cuda:7"
model = AutoModelForCausalLM.from_pretrained("/path/to/your/model")
model.half()
model.to(device)

3. ValueError: Couldn’t instantiate the backend tokenizer from one of: (1) a tokenizers library serialization file, (2) a slow tokenizer instance to convert or (3) an equivalent slow tokenizer class to instantiate and convert. You need to have sentencepiece installed to convert a slow tokenizer to a fast one.

错误描述:运行如下代码加载tokenizer时出错:

tokenizer = AutoTokenizer.from_pretrained("/checkpoints/models--lmsys--vicuna-7b-v1.5")

解决办法:在AutoTokenizer.from_pretrained中加入use_fast=False参数

tokenizer = AutoTokenizer.from_pretrained("/checkpoints/models--lmsys--vicuna-7b-v1.5",use_fast=False)

4. Installation error: symbol cublasLtGetStatusString version libcublasLt.so.11 not defined

错误描述:执行from transformers import pipeline时报错。
解决办法:删除虚拟环境中的如下文件夹:my_env(你的虚拟环境名)/lib/python3.10/site-packages/nvidia/cublas

5. 生成更可控的输出的小技巧

有时当你的prompt太复杂,导致模型无法理解,从而可能不产生输出。这时可以通过min_length参数强行限制模型输出一定长度的文本。注意,min_length表示的是:输入prompt+生成的文本的token总长。因此,若想控制生成文本的长度下限,需要加上input的长度。下面代码里input_ids.shape[1]表示输入文本经过tokenizer之后得到的token的长度。input_ids的形状是[bsz, max_token_length]。
【其他参数的作用请见下面代码的注释部分】

# 将输入prompt进行tokenization
encoded_inputs = tokenizer(prompts, padding=True, return_tensors="pt", truncation=True, max_length=512)
input_ids = encoded_inputs["input_ids"].to(device) # 形状:[bsz, max_token_length]

# 模型推理
with torch.no_grad():
	generated_ids = model.generate(
	            input_ids=input_ids,
	            max_length=input_ids.shape[1]+args.max_length, # 输入prompt+生成的文本的token总长
	            min_length=input_ids.shape[1]+args.min_length,
	            temperature=0.5, # 越高,生成的随机性越大
	            top_k=1, # 每次从k个最可能的词中选一个作为下一个生成的词
	            top_p=0.85, # 所选词的概率阈值,大于这个阈值才选
	            repetition_penalty=1.2, # 越大,模型越不容易生成重复的内容
	            length_penalty=1.0, # 越大,越不容易生成End of Sentence符
	            num_return_sequences=1,
	            pad_token_id=tokenizer.eos_token_id  # Ensure generation stops at the end of the sentence
	        )
### 在阿里云 ECS 上部署和运行 LLM 模型 #### 1. 环境准备 在阿里云 ECS 实例上运行大型语言模型 (LLM),需要先完成基础环境的配置。这包括选择合适的实例规格以及操作系统版本。推荐选用 GPU 支持的实例类型,因为大多数 LLM 推理任务对计算能力的要求较高[^1]。 ```bash # 登录到您的 ECS 实例 ssh root@your_ecs_ip_address ``` #### 2. 安装依赖项 为了顺利运行 LLM 模型,需安装必要的软件包和库文件。以下是具体操作: - **Python 和 Conda** 使用 Anaconda 或 Miniconda 来管理 Python 环境,便于后续安装深度学习框架和其他依赖项[^4]。 ```bash wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh conda create -n llm_env python=3.9 conda activate llm_env ``` - **深度学习框架** 基于所选的大规模预训练模型(如 Hugging Face Transformers),安装对应的 PyTorch 或 TensorFlow 版本。 ```bash pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117 pip install transformers datasets accelerate ``` #### 3. 下载并加载模型 利用 DeepGPU-LLM 工具或其他开源项目来加速模型推理性能。对于常见模型系列(例如 Llama、ChatGLM 等),可以直接从官方仓库下载权重文件。 ```python from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", device_map="auto", trust_remote_code=True) def generate_text(prompt): inputs = tokenizer.encode(prompt, return_tensors="pt").to('cuda') outputs = model.generate(inputs, max_length=50, num_return_sequences=1) result = tokenizer.decode(outputs[0], skip_special_tokens=True) return result ``` #### 4. 自动化部署方案 如果希望进一步简化流程,则可以通过基础设施即代码 (IaC) 方法实现自动化部署。借助 ROS 提供的功能模块快速构建所需的服务架构[^3]。 ```yaml Resources: MyInstance: Type: 'ALIYUN::ECS::Instance' Properties: InstanceType: ecs.gn6i-large ImageId: ubuntu_18_04_64 SecurityGroupId: sg-bpxxxxxxxx VSwitchId: vsw-bpxxxxxxxx KeyPairName: mykeypair ``` #### 5. 性能优化建议 当面对复杂的混合云或多云场景时,可引入资源调度模型以提高整体效率;同时采用适当的数据迁移策略减少延迟开销[^2]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值