GPT-2によるテキスト生成
GPT-2によるテキスト生成チュートリアル
Section titled “GPT-2によるテキスト生成チュートリアル”このチュートリアルでは、ONNX Runtimeを使用して、事前学習済みのGPT-2モデルでテキストを生成する方法を示します。
- ONNX Runtimeがインストールされていること
- Hugging Face Transformersライブラリがインストールされていること
- Hugging FaceモデルハブからGPT-2 ONNXモデルをダウンロードしていること
GPT-2 ONNXモデルのダウンロード
Section titled “GPT-2 ONNXモデルのダウンロード”Hugging FaceモデルハブからGPT-2 ONNXモデルをダウンロードできます。
wget https://huggingface.co/gpt2/resolve/main/onnx/model.onnxテキスト生成
Section titled “テキスト生成”次のPythonスクリリプトは、ONNX Runtimeを使用してテキストを生成する方法を示しています。
import onnxruntimefrom transformers import GPT2Tokenizerimport numpy as np
# ONNXモデルをロードsession = onnxruntime.InferenceSession("model.onnx")
# トークナイザをロードtokenizer = GPT2Tokenizer.from_pretrained("gpt2")
# プロンプトを定義prompt = "ONNX Runtimeは"
# プロンプトをトークン化input_ids = tokenizer.encode(prompt, return_tensors="np")
# テキストを生成output = session.run(None, {"input_ids": input_ids})
# 出力をデコードgenerated_text = tokenizer.decode(output[0][0], skip_special_tokens=True)
# 生成されたテキストを出力print(generated_text)このスクリプトは、プロンプトをトークン化し、ONNX Runtimeを使用してテキストを生成し、生成されたテキストを出力します。