【BERTとGPTの比較】
■ BERT(Encoder-only)
目的: テキストを「理解」する
訓練: マスクされた単語を予測(穴埋め問題)
方向: 双方向(前後の文脈を同時に見る)
例(マスク予測):
入力: “The [MASK] sat on the mat”
BERT: “[MASK] = cat” と予測
BERTは「cat」を予測するとき、
左側 “The” と右側 “sat on the mat” の両方を見ます。
■ GPT(Decoder-only)
目的: テキストを「生成」する
訓練: 次の単語を予測
方向: 単方向(左から右のみ)
例(次単語予測):
入力: “The cat sat on the”
GPT: “mat” と予測
GPTは「mat」を予測するとき、
左側 “The cat sat on the” だけを見ます。
右側(未来)は見てはいけません。
【なぜGPTは右側を見ないのか?】
生成時のことを考えてみましょう:
“The cat sat on the ___”
まだ「___」の部分は存在しません。
存在しないものは見れません。
訓練時も同じ条件にすることで、
訓練と推論の条件を一致させています。
【Autoregressive生成の流れ】
開始プロンプト: “Once upon a time”
【ステップ1】
入力: “Once upon a time”
GPTが処理 → 次の単語の確率分布を出力
“there”: 25%
“in”: 18%
“a”: 15%
“,”: 12%
…
サンプリング → “there” を選択
【ステップ2】
入力: “Once upon a time there” ← “there”を追加
GPTが処理 → 次の単語の確率分布を出力
“was”: 45%
“lived”: 20%
“were”: 10%
…
サンプリング → “was” を選択
【ステップ3】
入力: “Once upon a time there was”
GPTが処理 → 次の単語の確率分布を出力
“a”: 38%
“an”: 15%
“the”: 12%
…
サンプリング → “a” を選択
【ステップ4】
入力: “Once upon a time there was a”
GPTが処理 → “princess” を選択
…(繰り返し)
【終了条件】
・特殊トークン <EOS> が生成される
・指定した最大長に達する
・ユーザーが停止する
最終出力:
“Once upon a time there was a princess who lived
in a beautiful castle by the sea…”
【重要なポイント】
1. 1単語ずつ生成
→ 全体を一度に出力するわけではない
2. 生成した単語は次の入力に追加
→ 自分の出力を参照して次を生成(自己回帰)
3. 確率からサンプリング
→ 毎回同じ出力にはならない(温度などで調整可能)
Prompt: Once upon a time, there was a
==================================================
Generated text:
Once upon a time, there was a young boy who lived in
a small village by the sea. He loved to explore the
forest and dream about adventures in faraway lands.
One day, he discovered an old map hidden in his
grandfather’s attic…
6-4. 温度パラメータの影響を確認
# ========================================
# 温度パラメータの影響を確認
# ========================================
prompt = “The future of artificial intelligence is”
print(f”Prompt: {prompt}”)
print(“=” * 60)
# 異なる温度で生成
temperatures = [0.3, 0.7, 1.0, 1.5]
for temp in temperatures:
print(f”\n— Temperature = {temp} —“)
generated = generate_text(prompt, max_length=60, temperature=temp)
print(generated)
print(“-” * 40)
実行結果(例):
Prompt: The future of artificial intelligence is
============================================================
— Temperature = 0.3 —
The future of artificial intelligence is likely to be
dominated by machine learning and deep learning algorithms.
These technologies are already being used in many
applications, from autonomous vehicles to medical diagnosis.
—————————————-
— Temperature = 0.7 —
The future of artificial intelligence is exciting and full
of possibilities. We can expect AI to play an increasingly
important role in healthcare, education, and entertainment.
—————————————-
— Temperature = 1.0 —
The future of artificial intelligence is uncertain, but
fascinating. Some experts predict AGI within decades, while
others remain skeptical about the timeline.
—————————————-
— Temperature = 1.5 —
The future of artificial intelligence is quantum raspberry
cosmic synthesizers dancing through nebulous datastreams
while transcendent algorithms…
(意味不明になっている)
—————————————-
✅ 温度の効果
Temperature = 0.3: 保守的で予測可能な文章
Temperature = 0.7: バランスが良い(推奨)
Temperature = 1.0: 創造的だが時々不安定
Temperature = 1.5: ランダムすぎて意味不明に
6-5. 複数のバリエーションを生成
# ========================================
# 複数のバリエーションを生成
# ========================================
def generate_multiple(prompt, num_sequences=3, max_length=80):
“””
同じプロンプトから複数のバリエーションを生成
Args:
prompt: 開始プロンプト
num_sequences: 生成する系列の数
max_length: 最大トークン数
Returns:
生成されたテキストのリスト
“””
input_ids = tokenizer.encode(prompt, return_tensors=’pt’).to(device)
with torch.no_grad():
outputs = model.generate(
input_ids,
max_length=max_length,
temperature=0.8,
top_p=0.9,
do_sample=True,
num_return_sequences=num_sequences, # 複数生成
pad_token_id=tokenizer.eos_token_id
)
generated_texts = []
for output in outputs:
text = tokenizer.decode(output, skip_special_tokens=True)
generated_texts.append(text)
return generated_texts
# テスト
prompt = “In the year 2050, humans”
print(f”Prompt: {prompt}”)
print(“=” * 60)
texts = generate_multiple(prompt, num_sequences=3)
for i, text in enumerate(texts, 1):
print(f”\n— Variation {i} —“)
print(text)
実行結果(例):
Prompt: In the year 2050, humans
============================================================
— Variation 1 —
In the year 2050, humans will have colonized Mars and
established permanent settlements on the red planet.
The journey to Mars will take only three months thanks
to advanced propulsion systems.
— Variation 2 —
In the year 2050, humans will live alongside advanced
AI systems that can think and feel. The line between
human and machine will become increasingly blurred.
— Variation 3 —
In the year 2050, humans will have solved climate change
through revolutionary clean energy technologies. Solar
and fusion power will meet all of humanity’s energy needs.