`enforce_stop_tokens` 如何在 LangChain 中与 Huggingface 模型一起工作?

2024-04-08

当我们查看 HuggingFaceHub 模型的使用情况时langchain有这部分作者不知道如何停止生成,https://github.com/hwchase17/langchain/blob/master/langchain/llms/huggingface_pipeline.py#L182 https://github.com/hwchase17/langchain/blob/master/langchain/llms/huggingface_pipeline.py#L182:

class HuggingFacePipeline(LLM):
        ...
    def _call(
        ...
        if stop is not None:
            # This is a bit hacky, but I can't figure out a better way to enforce
            # stop tokens when making calls to huggingface_hub.
            text = enforce_stop_tokens(text, stop)
        return text

我应该使用什么来将停止标记添加到模板的末尾?


如果我们看一下https://github.com/hwchase17/langchain/blob/master/langchain/llms/utils.py https://github.com/hwchase17/langchain/blob/master/langchain/llms/utils.py,它只是一个正则表达式分割,根据停用词列表分割输入字符串,然后取第一个分区re.split

re.split("|".join(stop), text)[0]

让我们尝试从 Huggingface 模型获取生成输出,例如

from transformers import pipeline
from transformers import GPT2LMHeadModel, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')

generator = pipeline('text-generation', model=model, tokenizer=tokenizer)
output = generator("Hey Pizza! ")
output

[out]:

[{'generated_text': 'Hey Pizza! 」\n\n「Hurry up, leave the place! 」\n\n「Oi! 」\n\nWhile eating pizza and then, Yuigahama came in contact with Ruriko in the middle of the'}]

如果我们应用re.split:

import re
def enforce_stop_tokens(text, stop):
    """Cut off the text as soon as any stop words occur."""
    return re.split("|".join(stop), text)[0]

stop = ["up", "then"]
text = output[0]['generated_text']

re.split("|".join(stop), text)

[out]:

['Hey Pizza! 」\n\n「Hurry ',
 ', leave the place! 」\n\n「Oi! 」\n\nWhile eating pizza and ',
 ', Yuigahama came in contact with Ruriko in the middle of the']

但这没有用,我想在一代结束时分裂。我可以使用哪些令牌来“enforce_stop_tokens”?


您可以通过将 eos_token_id 设置为停止项来做到这一点——在我的测试中,它似乎适用于列表。参见下文:正则表达式截断停用词,eos_token_id 在停用词之后截断(“once Upon a time”与“once Upon a”)


from transformers import GPT2LMHeadModel, GPT2Tokenizer
import regex as re

tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')

# Define your custom stop terms
stop_terms = [ "right", "time"]

# Ensure the stop terms are in the tokenizer's vocabulary
for term in stop_terms:
    if term not in tokenizer.get_vocab():
        tokenizer.add_tokens([term])
        model.resize_token_embeddings(len(tokenizer))

def enforce_stop_tokens(text, stop):
    """Cut off the text as soon as any stop words occur."""
    return re.split("|".join(stop), text)[0]

# Get the token IDs for your custom stop terms
eos_token_ids_custom = [tokenizer.encode(term, add_prefix_space=True)[0] for term in stop_terms]

# Generate text
input_text = "Once upon "
input_ids = tokenizer.encode(input_text, return_tensors='pt')
output_ids = model.generate(input_ids, eos_token_id=eos_token_ids_custom, max_length=50)

# Decode the output IDs to text
generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)

print(generated_text) # Once upon a time

print("ENFORCE STOP TOKENS")

truncated_text = enforce_stop_tokens(generated_text, stop_terms)

print(truncated_text) # Once upon a 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

`enforce_stop_tokens` 如何在 LangChain 中与 Huggingface 模型一起工作? 的相关文章

随机推荐

  • MongoDB 连接被对等方重置

    我研究过其他解决方案 例如 Mongodb 连接被对等方重置 https stackoverflow com questions 2961648 mongodb connection reset by peer Mongodb 自动重新连接
  • 如何将 Facebook 聊天工具添加到 Next.js?

    我尝试在 Next js 应用程序中添加 Facebook 客户聊天 但不起作用 我找不到我的代码有任何问题 如何在我的 Next js 应用程序中添加 Facebook 客户聊天 我的代码有什么错误吗 有更好的实现来解决这个问题吗 这是我
  • 如何从控制器返回 JavaScript?

    我正在处理 ASP NET Core 2 2 项目 需要从控制器返回 JavaScript 但是 我怀疑没有直接的方法 因此 我遵循this https stackoverflow com a 42698821 4753489操作系统回答并
  • 错误:未定义无法解析模块`@react-navigation/bottom-tabs`

    一直在寻找有关导航错误模块的解决方案 我尝试过重置缓存 删除 nodu modules 重新安装模块 但仍然无法正常工作 错误的完整详细信息 Unable to resolve module react navigation native
  • 使用 Interface Builder 在 nib 中设计 UICollectionView 单元格(无故事板)

    我正在尝试设计一个定制的UICollectionViewCell原型 在 Xcode 5 0 2 中 但是 Interface Builder 不允许我向我的UICollectionView在设计笔尖时 如果我使用故事板 我可以设置项目 单
  • 指向具有不同参数的成员函数的指针的容器

    我到处寻找 现代 C 设计和合作 但我找不到一种好方法来存储一组接受不同参数并对不同类进行操作的回调 我需要这个 因为我希望应用程序的每个对象都有可能将其方法之一的执行推迟到主对象Clock对象 跟踪当前时间 可以在正确的时刻调用此方法 我
  • 类型错误:names_to_saveables 必须是将字符串名称映射到张量/变量的字典

    我正在尝试使用 freeze graph py 转换 MobileNet 0 50 的重新训练版本 这是我的代码 python m tensorflow python tools freeze graph input checkpoint
  • DB 连接关闭后从 Oracle DB 读取 CLOB

    在我正在查看的 Java 类之一中 我看到以下代码 private oracle sql CLOB getCLOB oracle sql CLOB xmlDocument null CallableStatement cstmt null
  • php - 输出值到屏幕中间循环

    在长 foreach 循环期间是否可以将任何内容输出到屏幕 每当我执行一个需要很长时间的循环时 在循环完全完成之前 屏幕上不会输出任何内容 即使 echo 语句位于循环内部 有没有办法改变这种行为 您需要刷新缓冲区 如何执行取决于您的服务器
  • 如何在 CUDA 应用程序中构建数据以获得最佳速度

    我正在尝试编写一个简单的粒子系统 利用 CUDA 来更新粒子位置 现在 我定义的粒子有一个对象 该对象的位置由三个浮点值定义 速度也由三个浮点值定义 更新粒子时 我向速度的 Y 分量添加一个常量值以模拟重力 然后将速度添加到当前位置以得出新
  • 为什么删除不完整的类型实际上是未定义的行为?

    考虑这个经典的例子来解释什么not与前向声明有关 in Handle h file class Body class Handle public Handle Handle delete impl private Body impl in
  • JQUERY DOM:选择 Dom 加载后创建的元素

    我正在开发一个项目 在该项目中 我需要在调用函数时更改某个类的所有选择输入的值 问题是一些选择输入在 dom 首次加载时并不存在 它们是通过 Javascript 动态创建的 该函数适用于选择页面加载时存在的所有选择输入 但不适用于动态添加
  • Delphi REST API 帖子示例

    有人可以发布一个使用 Delphi 2005 向 API 发送 JSON POST 请求的简单示例 我发现了许多使用 GET 的示例 但 API 提供程序不允许通过 HTTP GET 请求 也不支持 URL 编码参数 我对调用 REST 服
  • 什么时候在排序之外使用太空船运算符?

    我只见过 Perl 宇宙飞船运算符 在数字排序例程中使用 但它在其他情况下似乎很有用 我只是想不出实际用途 什么时候可以在 Perl 排序之外使用它 This is a best practice question 我正在为机器人乔编写一个
  • App.Config 应该是应用程序的伴随文件还是放在自己的组件中?

    当我创建 Windows Installer 程序包 例如使用 WiX 并安装该应用程序时App exe以及App exe config配置文件应该有自己的组件还是应该是应用程序可执行文件的伴随文件
  • Netty 处理程序未调用

    我正在尝试使用简单的服务器客户端应用程序进入 Netty 代码见下文 我正在努力解决两个问题 ConfigServerHandler 分别ConfigClientHandler 被正确调用 但是 FeedbackServerHandler
  • 有没有办法为 Swift 4.2 随机数生成器提供种子

    我喜欢新的 Swift 4 2 RandomNumberGenerator 东西 但我没有看到那里有种子的可能性 我是否遗漏了一些东西 或者有什么方法可以通过调用底层低级函数来为这些生成器提供种子 我有很多代码 它们在默认数字类型上使用默认
  • 创建APK时Android应用程序图标变得模糊

    创建 APK 时我的应用程序图标变得模糊 我尝试下载一个具有非常尖锐图标的 Android 应用程序的 APK 并将其放入我的 APK 中 但得到了相同的结果 为什么我的图标变得模糊 而我在使用相同图标的其他应用程序中看到它却非常清晰 当然
  • 转换时我得到 LINQ to Entities Int32 ToInt32(System.String)

    当 Convert i 尝试 int Parse SqlFunction 和 EdmFunction 时 我得到 LINQ to Entities Int32 ToInt32 System String 但问题仍然存在 例外 System
  • `enforce_stop_tokens` 如何在 LangChain 中与 Huggingface 模型一起工作?

    当我们查看 HuggingFaceHub 模型的使用情况时langchain有这部分作者不知道如何停止生成 https github com hwchase17 langchain blob master langchain llms hu