コンテンツにスキップ

GPT-2によるテキスト生成

GPT-2によるテキスト生成チュートリアル

Section titled “GPT-2によるテキスト生成チュートリアル”

このチュートリアルでは、ONNX Runtimeを使用して、事前学習済みのGPT-2モデルでテキストを生成する方法を示します。

Hugging FaceモデルハブからGPT-2 ONNXモデルをダウンロードできます。

Terminal window
wget https://huggingface.co/gpt2/resolve/main/onnx/model.onnx

次のPythonスクリリプトは、ONNX Runtimeを使用してテキストを生成する方法を示しています。

import onnxruntime
from transformers import GPT2Tokenizer
import 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を使用してテキストを生成し、生成されたテキストを出力します。