初始化#

  1. WSL 个人比较习惯 Linux,使用 WSL,参考 Windows安装WSL2并配置nVidia GPU

不过看起来现在也不用装驱动直接

ln -s /usr/lib/wsl/lib/nvidia-smi /usr/bin/nvidia-smi
  1. 设置源(可选)

直接在user目录中创建一个pip目录,如:C:\Users\xx\pip,新建文件pip.ini。

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

[install]
trusted-host=pypi.tuna.tsinghua.edu.cn

Linux 参考 pip 使用国内镜像源

  1. virtualenv

使用隔离环境是一个好习惯

pip install virtualenv
  1. 安装 jupyter
pip install jupyter
  1. 使用隔离环境
virtualenv myenv

source ./myenv/bin/activate


pip install notebook
  1. 启动
jupyter notebook
  1. 安装依赖
pip install transformers
pip install accelerate

Model#

  1. 下载模型
pip install -U huggingface_hub
  1. 使用镜像
export HF_ENDPOINT=https://hf-mirror.com
  1. 下载 qwen2.5-0.5B
huggingface-cli download --resume-download Qwen/Qwen2.5-0.5B --local-dir qwen2.5-0.5B 

第一次对话#

from transformers import AutoModelForCausalLM, AutoTokenizer

# 加载模型和 tokenizer (第一次加载的时候会进行下载)
model = AutoModelForCausalLM.from_pretrained(
    "qwen2.5-0.5B",
    device_map="cuda",
    torch_dtype="auto",
    trust_remote_code=True,
)

# step1: 生成 pipeline
# return_full_text=False 表示只返回新生成的文本,不包含输入的prompt
# return_full_text=True 则会返回完整文本,包含输入的prompt和生成的新文本
generator = pipeline(
    "text-generation", 
    model=model,
    tokenizer=tokenizer,
    return_full_text=False,  # 只返回新生成的文本部分
    max_new_tokens=500,
    do_sample=False
)

# step2: 构建 prompt
messages = [
    {"role": "user", "content": "写一个关于天气的笑话."}
]

# step3,输出并解码
output = generator(messages)
print(output[0]["generated_text"])
comments powered by Disqus