Transformers documentation

生成特性

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

生成特性

generate() API 支持若干功能,便于在其之上构建应用程序。

本指南将向您展示如何使用这些功能。

流式

流式处理会在文本生成的同时立即返回,因此您无需等待整个生成响应一次性呈现。这在面向用户的应用中非常重要,因为它能降低感知延迟,并让用户实时查看生成进度。

有关流式传输的更多信息,请参阅 Text Generation Inference 文档。

使用分词器创建一个 TextStreamer 实例。将 TextStreamer 传递给 generate() 中的 streamer 参数,即可逐词流式输出结果。

from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer

tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
inputs = tokenizer(["The secret to baking a good cake is "], return_tensors="pt")
streamer = TextStreamer(tokenizer)

_ = model.generate(**inputs, streamer=streamer, max_new_tokens=20)

streamer 参数兼容任何具有 put() 和 end() 方法的类。put() 用于推送新的 token,end() 用于标记生成结束。只要包含这两个方法,您就可以创建自己的 streamer 类,也可以使用 Transformers 提供的基础 streamer 类。

水印

水印技术可用于检测文本是否由模型生成。Transformers 中的 watermarking strategy 会随机将一部分 token 标记为“绿色”。当生成绿色 token 时,会在其 logits 上添加一个小的偏置,从而提高其被生成的概率。你可以通过比较生成文本中绿色 token 的比例与人类生成文本中通常出现的绿色 token 比例,来检测文本是否由模型生成。

Transformers 支持为任意生成式模型添加水印,且无需额外的分类模型来检测带水印的文本。

创建一个 WatermarkingConfig,指定要添加到 logits 的偏置值以及水印算法。下面的示例使用了 "selfhash" 算法,其中绿色 token 的选择仅取决于当前 token。将 WatermarkingConfig 传递给 generate()。

WatermarkDetector 类用于检测生成文本中绿色 token 的比例,因此当提示文本远长于生成文本时,建议先去除提示文本。填充(padding)也可能影响 WatermarkDetector 的结果。

from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig

model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
tokenizer.pad_token_id = tokenizer.eos_token_id
tokenizer.padding_side = "left"

inputs = tokenizer(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt")
input_len = inputs["input_ids"].shape[-1]

watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash")
out = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20)

创建一个 WatermarkDetector 实例,并将模型输出传入其中,以检测文本是否由机器生成。WatermarkDetector 必须使用与生成阶段相同的 WatermarkingConfig。

detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config)
detection_out = detector(out, return_dict=True)
detection_out.prediction
array([True, True])
Update on GitHub