下载离线大模型

在下载离线大模型前,要先在命令行执行下面的pip安装命令:

pip install modelscope

接着命令行通过cd命令进入Python工程的所在目录,再执行下面的模型下载命令:

modelscope download --model Qwen/Qwen1.5-1.8B-Chat --local_dir qwen1.5-1.8b-chat

上面下载命令的“--model”参数表示离线大模型为“Qwen/Qwen1.5-1.8B-Chat”,而“--local_dir”参数表示离线大模型的本地保存目录。

注意Qwen1.5-1.8B-Chat的总大小为3.69GB,下载过程较耗时,请耐心等待。下载完毕,即可在Python工程的目录下方找到qwen1.5-1.8b-chat文件夹,里面保存的便是Qwen1.5-1.8B-Chat的具体模型文件。

三、使用离线大模型输出摘要

接下来演示如何使用Qwen1.5-1.8B-Chat对一段文本生成摘要。在编写Python代码前,要先在命令行执行下面的pip安装命令:

pip install transformers

然后编写下面的Python摘要测试代码:

from transformers import AutoTokenizer, AutoModelForCausalLM

model_path = "./qwen1.5-1.8b-chat" # 离线大模型的本地保存目录

def local_model_summary(text: str, max_new_tokens=256) -> str:
    """
    加载本地离线模型 Qwen1.5-1.8B-Chat 做摘要
    【无需联网、无需下载、纯本地运行】
    """

    # 加载本地分词器 + 本地模型(完全离线)
    tokenizer = AutoTokenizer.from_pretrained(
        model_path,
        trust_remote_code=True  # Qwen 必须加这个
    )
    model = AutoModelForCausalLM.from_pretrained(
        model_path,
        trust_remote_code=True,  # Qwen 必须加这个
        dtype="auto",
        device_map="auto"
    ).eval()

    # 构造 Qwen1.5 官方对话格式
    messages = [
        {"role": "system", "content": "请对用户输入的内容做精简摘要,摘要文字压缩在50字以内"},
        {"role": "user", "content": text}
    ]

    # 官方模板构造
    text_input = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )

    inputs = tokenizer(
        [text_input],
        return_tensors="pt",
        truncation=True
    ).to(model.device)

    # 离线生成摘要
    outputs = model.generate(
        **inputs,
        max_new_tokens=max_new_tokens, # 返回文本最多占用多少Token
        temperature=0.3,
        top_p=0.7,
        do_sample=True,
        pad_token_id=tokenizer.eos_token_id
    )

    # 提取摘要结果
    response = outputs[0][len(inputs["input_ids"][0]):]
    summary = tokenizer.decode(response, skip_special_tokens=True)
    return summary.strip()

if __name__ == "__main__":
    content = """
    火山方舟是火山引擎推出的大模型平台,提供模型训练、推理、评测、精调等全方位功能与服务。
    平台支持多种主流大模型接入,具有稳定可靠、安全互信的特点。
    企业可以通过火山方舟快速构建自己的AI应用,降低开发成本与技术门槛。
    """

    print("正在使用【本地离线模型】生成摘要...\n")
    result = local_model_summary(content, max_new_tokens=28)
    print("【离线摘要结果】")
    print("-", result)

运行上面的Python代码,输出日志结果如下:

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐