【问题标题】:Fine tune GPT-2 on large text for generate a domain text在大文本上微调 GPT-2 以生成域文本
【发布时间】:2021-01-02 19:22:58
【问题描述】:

尝试在非常大的文本上训练 GPT-2,以便从特定域生成文本。
使用 tensorflow2 。

例如,假设我拥有所有《哈利·波特》书籍 :)
而且我想在它们上训练 GPT-2,这样我以后就可以从哈利波特域中生成文本。

from tensorflow.keras.utils import get_file
from transformers import GPT2Tokenizer, TFGPT2Model

text = '...'
# Length of text: 474429 characters
# 84 unique characters

tokenizer = GPT2Tokenizer.from_pretrained('gpt2-medium')
model = TFGPT2Model.from_pretrained('gpt2-medium')

encoded_input = tokenizer(text, return_tensors='tf') # ERROR
output = model(encoded_input)

input_ids = tokenizer.encode('severus snape', return_tensors='tf')
greedy_output = model.generate(input_ids, max_length=50)
print(tokenizer.decode(greedy_output[0], skip_special_tokens=True))

错误:令牌索引序列长度大于指定 该模型的最大序列长度(149887 > 1024)。运行这个 通过模型的顺序将导致索引错误

那么我该如何让它发挥作用呢?
如何为模型提供一个大的新文本进行训练?

编辑:
尝试连接时,标记器可以工作,但模型不能:

from textwrap import wrap
text_batches = wrap(text, 1000)

encoded_input = None

for tb in text_batches:
    current = tokenizer(tb, return_tensors='tf')
  
    if encoded_input == None:
        encoded_input = current
    else:
        encoded_input['input_ids']      = tf.concat([encoded_input['input_ids'], current['input_ids']], axis=-1)
        encoded_input['attention_mask'] = tf.concat([encoded_input['attention_mask'], current['attention_mask']], axis=1)

output = model(encoded_input) # ERROR

错误: InvalidArgumentError: indices[0,1024] = 1024 不在 [0, 第1024章,【操作】

我错过了什么?

【问题讨论】:

    标签: tensorflow keras deep-learning nlp huggingface-transformers


    【解决方案1】:

    您的问题与不同领域的培训无关。相反,您只是提供了一个比模型可以支持的最大长度 (1024) 更长的文本长度(显然是 149887 个标记)。您有三个选择:

    1. 手动将您的输入字符串截断为最大标记长度。

    2. 在对标记器的调用中设置 max_length 参数,例如tokenizer(text, max_length=1024, ...)。请务必阅读 Tokenizer 类的所有可用选项。

    3. 重新审视为什么需要 149K 标记的文本字符串。这是正文的全部内容吗?你应该改用句子吗?

    【讨论】:

    • 感谢您的帮助。 1. 试过了 - 没用。将其添加到Q. 2.加载预训练模型时不能设置超过1024。 3.你会怎么用句子做?我希望我知道如何:)
    • 如果错误显示1024 is not in [0, 1024),那么您必须能够阅读简单的数学符号。 1024) 表示最多但不包括 1024,所以尝试 1023。
    • 如果你想将大文本解析成句子,那么你有三个选择:(a)使用正则表达式(我不会选择这种方法); (b) 使用 NLTK 句子解析器;或 (c) 使用 Spacy 句子解析器。所有三个选项都在一篇 StackOverflow 帖子中讨论:stackoverflow.com/questions/4576077/…
    • 欣赏输入,但每个 petrain 模型都有自己的标记。一个不同的标记器这不是要走的路。尤其是在使用嵌入时。也许我需要弄清楚如何在 1024 个大小的批次中训练模型?
    • 我没有说要使用不同的分词器。问题是您需要将每个示例的令牌数量限制为 1024(或给定模型的任何限制)。
    猜你喜欢
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2012-02-29
    • 2011-10-18
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多