🚀 字符级Reformer语言模型,在enwik8数据集上训练
本项目的字符级Reformer语言模型是在enwik8数据集上进行训练的。enwik8是一个基于维基百科构建的数据集,常被用于衡量模型对数据的压缩能力,例如在赫特奖(Hutter Prize)的范畴内:https://en.wikipedia.org/wiki/Hutter_Prize 。
reformer-enwik8
模型在enwik8数据集的前9000万个字符上进行了预训练,文本被分割成大小为65536个字符(即2^16)的批次。模型权重取自https://console.cloud.google.com/storage/browser/trax-ml/reformer/enwik8 ,并转换为Hugging Face的PyTorch ReformerLM模型ReformerModelWithLMHead
。
该模型是一个基于字符的语言模型,因此无需分词器。可以使用以下函数进行编码和解码:
💻 使用示例
基础用法
import torch
def encode(list_of_strings, pad_token_id=0):
max_length = max([len(string) for string in list_of_strings])
attention_masks = torch.zeros((len(list_of_strings), max_length), dtype=torch.long)
input_ids = torch.full((len(list_of_strings), max_length), pad_token_id, dtype=torch.long)
for idx, string in enumerate(list_of_strings):
if not isinstance(string, bytes):
string = str.encode(string)
input_ids[idx, :len(string)] = torch.tensor([x + 2 for x in string])
attention_masks[idx, :len(string)] = 1
return input_ids, attention_masks
def decode(outputs_ids):
decoded_outputs = []
for output_ids in outputs_ids.tolist():
decoded_outputs.append("".join([chr(x - 2) if x > 1 else "" for x in output_ids]))
return decoded_outputs
高级用法
from transformers import ReformerModelWithLMHead
model = ReformerModelWithLMHead.from_pretrained("google/reformer-enwik8")
encoded, attention_masks = encode(["In 1965, Brooks left IBM to found the Department of"])
decode(model.generate(encoded, do_sample=True, max_length=150))
⚠️ 重要提示
使用ReformerModelWithLMHead
进行文本生成尚未经过优化,速度较慢。