🚀 RoFormer模型項目
RoFormer是一種增強型的Transformer模型,採用了旋轉位置嵌入(Rotary Position Embedding)技術,本項目提供了該模型在不同深度學習框架下的實現及使用示例,可用於自然語言處理任務。
🚀 快速開始
本項目提供了RoFormer模型在TensorFlow和PyTorch框架下的實現,你可以通過以下鏈接獲取對應版本的代碼:
💻 使用示例
基礎用法 - PyTorch版本
import torch
from transformers import RoFormerForMaskedLM, RoFormerTokenizer
text = "今天[MASK]很好,我[MASK]去公園玩。"
tokenizer = RoFormerTokenizer.from_pretrained("junnyu/roformer_chinese_char_small")
pt_model = RoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_char_small")
pt_inputs = tokenizer(text, return_tensors="pt")
with torch.no_grad():
pt_outputs = pt_model(**pt_inputs).logits[0]
pt_outputs_sentence = "pytorch: "
for i, id in enumerate(tokenizer.encode(text)):
if id == tokenizer.mask_token_id:
tokens = tokenizer.convert_ids_to_tokens(pt_outputs[i].topk(k=5)[1])
pt_outputs_sentence += "[" + "||".join(tokens) + "]"
else:
pt_outputs_sentence += "".join(
tokenizer.convert_ids_to_tokens([id], skip_special_tokens=True))
print(pt_outputs_sentence)
基礎用法 - TensorFlow 2.0版本
import tensorflow as tf
from transformers import RoFormerTokenizer, TFRoFormerForMaskedLM
text = "今天[MASK]很好,我[MASK]去公園玩。"
tokenizer = RoFormerTokenizer.from_pretrained("junnyu/roformer_chinese_char_small")
tf_model = TFRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_char_small")
tf_inputs = tokenizer(text, return_tensors="tf")
tf_outputs = tf_model(**tf_inputs, training=False).logits[0]
tf_outputs_sentence = "tf2.0: "
for i, id in enumerate(tokenizer.encode(text)):
if id == tokenizer.mask_token_id:
tokens = tokenizer.convert_ids_to_tokens(
tf.math.top_k(tf_outputs[i], k=5)[1])
tf_outputs_sentence += "[" + "||".join(tokens) + "]"
else:
tf_outputs_sentence += "".join(
tokenizer.convert_ids_to_tokens([id], skip_special_tokens=True))
print(tf_outputs_sentence)
📄 引用
如果你使用了本項目的代碼或模型,請按照以下格式進行引用:
@misc{su2021roformer,
title={RoFormer: Enhanced Transformer with Rotary Position Embedding},
author={Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu},
year={2021},
eprint={2104.09864},
archivePrefix={arXiv},
primaryClass={cs.CL}
}