🚀 字符級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
進行文本生成尚未經過優化,速度較慢。