当前位置: 首页 > news >正文

huggingface笔记:文本生成Text generation

1 加载LLM模型

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import osmodel = AutoModelForCausalLM.from_pretrained("gpt2",device_map="auto",  # 自动分配到所有可用设备(优先 GPU)torch_dtype=torch.bfloat16
)

2 编码输入并生成文本

tokenizer = AutoTokenizer.from_pretrained("gpt2", padding_side="left")
model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt")
model_inputs
'''
{'input_ids': tensor([[  32, 1351,  286, 7577,   25, 2266,   11, 4171]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1]])}
'''

2.1 调用 generate() 并使用 batch_decode() 还原文本:'

generated_ids = model.generate(**model_inputs)
generated_ids
'''
tensor([[  32, 1351,  286, 7577,   25, 2266,   11, 4171,   11, 4077,   11, 4171,11, 7872,   11, 7872,   11, 4077,   11, 4171,   11, 7872,   11, 4077,11, 4171,   11, 7872]])
'''
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
#A list of colors: red, blue, green, blue, yellow, yellow, green, blue, yellow, green, blue, yellow

3 常用参数

max_new_tokens最大生成 token 数
do_sample

是否使用采样策略(默认为False)

根据词表中每个 token 的概率随机抽取

num_beamsBeam search 会在每一步保留num_beams个候选序列(称为 beam),最终选择总体概率最高的那一条。
temperature

控制生成随机性(>0.8 适合创意任务,<0.4 更“严谨”)

需配合 do_sample=True

repetition_penalty>1 可减少重复内容
generated_ids = model.generate(**model_inputs,max_new_tokens=50,do_sample=True,temperature=0.9)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'''
A list of colors: red, blue, white , yellow and purpleThere is a separate link in the sidebar of this page to see how this affects the colors of the text. Click the "Color Information" button. Then click "Next" to add this color information to your
'''

http://www.dtcms.com/a/270288.html

相关文章:

  • EXCEL(带图)转html
  • 基于LiteOS与SLE的多任务无线控制器项目实战
  • 深圳凭物联网软件开发构建智慧‘城市大脑‘
  • 什么是 3D 文件?
  • UE material advance 学习笔记
  • 【时时三省】(C语言基础)怎样引用指针变量
  • 免安装图片修改软件,一键批量处理
  • 16018.UE4+Airsim仿真环境搭建
  • 详细页智能解析算法:洞悉海量页面数据的核心技术
  • 软件系统测试的基本流程
  • 【PyTorch项目实战】VisRAG:基于视觉的多模态文档检索增强生成(文本+图像)
  • Android 事件分发机制深度解析
  • Android 中的多线程编程全面解析
  • YOLO融合[ICLR2025]PolaFormer中的极性感知线性注意力
  • docker proxy
  • C 解压文件
  • Day55 序列预测任务介绍
  • Subject vs Flowable vs Observable 对比
  • 【零基础学AI】第31讲:目标检测 - YOLO算法
  • 每日算法刷题Day44 7.8:leetcode前缀和4道题,用时1h40min
  • JVM 为什么使用元空间(Metaspace)替换了永久代(PermGen)?——深入理解 Java 方法区与类元数据存储的演进
  • 视频能转成gif动图吗?怎么弄?
  • [NOIP][C++]洛谷P1376 [USACO05MAR] Yogurt factory 机器工厂
  • 没合适的组合wheel包,就自行编译flash_attn吧
  • 行业实践案例:金融行业数据治理体系全景解析
  • Java 关键字详解:掌握所有保留关键字的用途与最佳实践
  • Apache Atlas编译打包,可运行包下载地址
  • DMA技术与音频数据的存储和播放
  • C++STL-vector
  • 【c++学习记录】状态模式,实现一个登陆功能