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

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.xdnf.cn/news/15103.html

相关文章:

  • WinUI3入门16:Order自定义排序
  • WouoUI-Page移植
  • 一个vue项目的基本构成
  • 实时音视频通过UDP打洞实现P2P优先通信
  • 方法论汇总
  • ACE-Step:AI音乐生成基础模型
  • 【python】 time_str = time_str.strip() 与 time_str = str(time_str).strip() 的区别
  • Mac安装Docker(使用orbstack代替)
  • 云原生详解:构建现代化应用的未来
  • 【Node.js】文本与 pdf 的相互转换
  • eslint扁平化配置
  • 牛市来临之际,如何用期权抢占反弹先机?
  • rabbitMQ读取不到ThreadLocal消息的bug
  • 如何利用机器学习(ML)检测异常登录行为
  • 视频号账号矩阵运营中定制开发开源 AI 智能名片 S2B2C 商城小程序的赋能研究
  • AR 双缝干涉实验亮相:创新科技实验范式,开拓 AR 技术新局​
  • 开源 python 应用 开发(三)python语法介绍
  • Linux操作系统:再谈虚拟地址空间
  • IT 技术领域创作者三周年纪念日
  • 026_类的定义(属性 / 方法 / 构造器)
  • 怪物机制分析(有限状态机、编辑器可视化、巡逻机制)
  • NumPy-随机数生成详解
  • 在Docker中安装nexus3(作为maven私服)
  • 5.6.2、ZeroMQ源码分析
  • 瞄准Win10难民,苹果正推出塑料外壳、手机CPU的MacBook
  • C++ 的 copy and swap 惯用法
  • 开疆智能Profinet转DeviceNet网关连接掘场空气流量计配置案例
  • qt-C++语法笔记之Stretch与Spacer的关系分析
  • [特殊字符] AlphaGo:“神之一手”背后的智能革命与人机博弈新纪元
  • C++高频知识点(五)