在本地调用大语言模型

1.下载大模型到本地

将模型下载到本地,方便调用。jinxia千问1.5-0.5B-Chat · 模型库

下载好的文件移动到D盘的文件夹里,D:\AI_Model\Qwen1.5-0.5B-Chat。

2.整理一下环境,防止C盘爆掉

因为大模型的相关环境文件比较大,最好把conda的环境文件都放到d盘。

C:\Users\用户\.cache\huggingface整个文件夹剪切到 D 盘,比如D:\AI_Cache\huggingface。

打开管理员 CMD,执行下面的命令创建软链接:

复制代码
mklink /J "C:\Users\HUANG\.cache\huggingface" "D:\AI_Cache\huggingface"

这样以后所有模型缓存都会写到 D 盘,C 盘只是一个 "假入口"。同时,代码里也要加上环境变量:

复制代码
import os
os.environ["HF_HOME"] = "D:\\AI_Cache\\huggingface"

3.运行

创建run_model.py

复制代码
import os
os.environ["HF_HOME"] = "D:\\AI_Cache\\huggingface"

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

# 改成你解压后的本地文件夹路径
model_id = "D:/AI_Model/Qwen1.5-0.5B-Chat"

device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    low_cpu_mem_usage=True,
    torch_dtype=torch.float32
).to(device)

print("模型和分词器加载完成!")

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "你好,请介绍你自己。"}
]

text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)

model_inputs = tokenizer([text], return_tensors="pt").to(device)
print("\n编码后的输入文本:")
print(model_inputs)

generated_ids = model.generate(
    model_inputs.input_ids,
    max_new_tokens=512
)

generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]

response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
print("\n模型的回答:")
print(response)

运行效果:

4调参

参数设置为 :固定不变输出版本

python 复制代码
generated_ids = model.generate(
    model_inputs.input_ids,
    max_new_tokens=512,
    do_sample=False
)

运行效果:

均衡随机版本:

python 复制代码
generated_ids = model.generate(
    model_inputs.input_ids,
    max_new_tokens=512,
    do_sample=True,
    temperature=0.7,
    top_p=0.9
)

运行效果(每次答案是不一样的):

高随机版本:

python 复制代码
generated_ids = model.generate(
    model_inputs.input_ids,
    max_new_tokens=512,
    do_sample=True,
    temperature=1.5,
    top_p=0.95
)

运行效果:

相关推荐
圣殿骑士-Khtangc1 小时前
智谱AI完成5亿美元融资 + AutoGLM 2.0发布:对标GPT-5 Agent Mode
人工智能
LLM落地研习社1 小时前
一行命令部署 NIM:Docker 容器化生产级最佳实践
人工智能
十有八七1 小时前
🧩 组件库死亡倒计时?—— AI 编码冲击下的前端基础设施重构
前端·人工智能
bryant_meng1 小时前
【Hugging Face】The GitHub of Open-Source AI Models
人工智能·github·qwen·hugging face·clip
有味道的男人1 小时前
从采集到铺货:AI 对接京东数据完整落地流程
人工智能
风止何安啊1 小时前
我一个前端仔,居然用 Python 搞起了 AI?从零到一,撸了个 AI 聊天框小 demo
前端·人工智能·后端
装不满的克莱因瓶1 小时前
图像尺寸调整:缩放矩阵如何改变像素坐标?
人工智能·线性代数·数学·算法·机器学习·矩阵
GlobalInfo1 小时前
八旋翼无人机产业洞察与市场占有率演变:2026年趋势分析报告
人工智能·无人机
GISer_Jing1 小时前
Claude Code插件系统全解析
前端·人工智能·ai·架构