pipeline 是 Transformers 库的高级API,它把"加载模型 → 预处理 → 推理 → 后处理"的完整流程封装成一行代码

pipeline 支持的常见任务

任务管道名称用途
文本生成"text-generation"GPT类模型,续写文本
文本分类"text-classification"情感分析、主题分类
问答"question-answering"从文本中找答案
翻译"translation"语言翻译
摘要"summarization"文本摘要
完形填空"fill-mask"BERT类掩码预测

pipeline 的参数详解

# 完整的pipeline创建
generator = pipeline(
    task="text-generation",           # 任务类型
    model=model,                      # 模型对象或名称
    tokenizer=tokenizer,              # 分词器
    device=0,                         # GPU设备(-1表示CPU)
    torch_dtype=torch.float16,        # 半精度推理
    framework="pt",                   # 框架:"pt"或"tf"
)

# 生成时的参数
result = generator(
    "你好,我是",
    max_length=100,                   # 生成的最大长度
    min_length=20,                    # 生成的最小长度
    num_return_sequences=3,           # 返回几个结果
    temperature=0.7,                  # 温度(控制随机性)
    top_p=0.9,                        # 核采样参数
    top_k=50,                         # 只从top-k中采样
    do_sample=True,                   # 是否采样(False则贪婪解码)
    repetition_penalty=1.2,           # 重复惩罚
)

pipeline 的输出格式

result = generator("输入文本", ...)

# 输出通常是列表,每个元素是字典
print(type(result))      # <class 'list'>
print(type(result[0]))   # <class 'dict'>

# 不同任务的输出结构
tasks_output = {
    "text-generation": [{"generated_text": "生成的完整文本"}],
    "text-classification": [{"label": "LABEL", "score": 0.99}],
    "question-answering": {"answer": "答案", "score": 0.95, "start": 10, "end": 20},
    "translation": [{"translation_text": "翻译结果"}],
}

离线调用本地GPT2代码:

from transformers import AutoModelForCausalLM,AutoTokenizer,pipeline

# 包含config.json的目录为模型的根目录,设置该目录,只支持绝对路径
md_dir = r"D:\develop\pypro\LLM\LLMPro\01-大模型应用基础\model\uer\gpt2-chinese-cluecorpussmall\models--uer--gpt2-chinese-cluecorpussmall\snapshots\c2c0249d8a2731f269414cc3b22dff021f8e07a3"

# 加载模型
model = AutoModelForCausalLM.from_pretrained(md_dir)
# 加载分词器
tokenizers = AutoTokenizer.from_pretrained(md_dir)
# 使用加载的模型和分词器生成创建文本的pipeline
pl = pipeline("text-generation", model=model, tokenizer=tokenizers, device="cpu")
text = pl("你好,我是大语言模型", max_length=50, num_return_sequences=1)
# 提取生成的文本
print(text[0]['generated_text'])

这是我的运行结果,有些简单~~,而且结果也不对呀,不是50个字符以内吗?

Device set to use cpu
Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=True` to explicitly truncate examples to max length. Defaulting to 'longest_first' truncation strategy. If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy more precisely by providing a specific strategy to `truncation`.
Both `max_new_tokens` (=256) and `max_length`(=50) seem to have been set. `max_new_tokens` will take precedence. Please refer to the documentation for more information. (https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)
你好,我是大语言模型 , 我 是 大 语 言 模 型 的 制 作 人 , 我 来 分 享 一 下 我 的 一 些 想 法 , 希 望 能 对 大 家 有 所 帮 助 。 首 先 , 讲 故 事 。 我 是 一 个 大 语 言 模 型 的 制 作 人 , 我 从 事 的 是 大 型 网 站 的 创 作 , 所 以 我 能 分 享 的 内 容 并 不 多 , 故 事 的 主 要 内 容 有 : 1. 大 型 网 站 的 创 作 , 是 一 个 个 的 故 事 , 我 们 可 以 看 到 大 大 的 故 事 , 这 些 故 事 是 我 们 平 时 生 活 中 一 个 个 的 事 件 , 所 以 我 想 , 这 个 故 事 应 该 可 以 是 一 个 个 的 小 故 事 。 大 家 可 以 看 到 我 们 平 时 生 活 中 一 个 个 的 故 事 , 这 些 故 事 也 可 以 是 一 个 个 的 小 故 事 , 有 的 是 一 个 个 的 故 事 , 有 的 是 一 个 个 的 小 故 事 。 如 果 我 们 平 时 这 个 故 事 有 点 小 , 我 们 可 以 去 看 一 些 小 故 事 , 这 些 故 事 也 是 我 们 平

进程已结束,退出代码为 0

从警告可以看到:因为 max_new_tokens=256 的优先级高于 max_length=50。同时,模型在重复和发散。这是GPT-2小模型的常见问题,需要调整一些参数,修改后的代码为:

from transformers import AutoModelForCausalLM,AutoTokenizer,pipeline

# 包含config.json的目录为模型的根目录,设置该目录,只支持绝对路径
md_dir = r"D:\develop\pypro\LLM\LLMPro\01-大模型应用基础\model\uer\gpt2-chinese-cluecorpussmall\models--uer--gpt2-chinese-cluecorpussmall\snapshots\c2c0249d8a2731f269414cc3b22dff021f8e07a3"

# 加载模型
model = AutoModelForCausalLM.from_pretrained(md_dir)
# 加载分词器
tokenizers = AutoTokenizer.from_pretrained(md_dir)
# 使用加载的模型和分词器生成创建文本的pipeline
pl = pipeline("text-generation", model=model, tokenizer=tokenizers, device="cpu")
text = pl("你好,我是大语言模型",
          max_new_tokens=50,
          truncation=True,
          temperature=0.7,              # 降低随机性,避免发散
          repetition_penalty=1.3,       # 增加重复惩罚
          no_repeat_ngram_size=2,       # 禁止2-gram重复
          do_sample=True,
          top_p=0.9,
          num_return_sequences=1)
# 提取生成的文本
print(text[0]['generated_text'])


修改后,运行结果如下,看起来好多了:

Device set to use cpu
你好,我是大语言模型 , 想 请 教 一 下 关 于 这 个 问 题 的 讨 论 。 如 果 你 不 知 道 怎 么 回 答 , 可 以 用 微 信 添 加 朋 友 yxk - mt ( 长 按 复 制 ) 进

进程已结束,退出代码为 0

所以说,要注意参数优先级问题,最好明确设置 truncation=True

  • 改用 max_new_tokens:比 max_length 更直观
  • 总是设置 truncation=True:避免警告
  • 添加重复控制repetition_penaltyno_repeat_ngram_size
  • 适当降低 temperature:对于小模型,0.7左右效果更好
Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐