予測から指示への追従へ

読了まで約39 分分、10 節 節の 9 例 例。

第2026.11.16版 2026年11月19日時点で例が通過 86 例中 86 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.16)から翻訳した。 原文を読む

この章を終えると、次のトークンを予測するモデルがどのようにして要求に従うモデルになるのかを説明でき、それを実現する二つの訓練損失を構築でき、その変化が何を解決し何を解決しないのかを測定できる。同じ要求に対して基本モデルとその指示チューニング版を比較し、それぞれが商品の詳細をでっち上げる頻度を測り、でっち上げたときにモデルの確信度が警告になるかを調べ、与えられた文脈の中のどの位置でモデルが情報を見つけられなくなるのかを突き止める。

この本が扱うテキストは、家具・家庭用品店の商品名と商品説明であり、ここまでの本書のモデルはいずれも一つのことしかしてこなかった。訓練テキストに似たテキストの次のトークンを予測することである。第10章では、一般的なテキストでそのように訓練された公開モデルである SmolLM2-360M を読み、このモデルが店の商品名に、単語あたりで見て店独自の小さなモデルよりはるかに低い評価(悪いスコア)を与え、商品説明にも低い評価を与えることを確認した。人が求めているのは自分のテキストの続きではなく、自分の要求に対する答えである。モデルはそれを、さらに二段階の訓練で教え込まれる。

指示チューニング(教師あり微調整とも呼ばれる)は、要求と良い応答を対にした例でモデルの訓練を続ける手法であり、そのような対の次のトークンを予測することが、要求に答えることを意味するようになる。Wei らは、指示の形で表現された多数のタスクでチューニングすると、モデルが見たことのないタスクでも性能が向上することを見いだした(Wei et al., 2022)。続く選好チューニングは、同じ要求に対する二つの応答のうち良いほうを好むようにモデルを訓練する。Ouyang らは人に応答を順位付けさせ、その順位付けから学習した報酬モデルを用いた強化学習で訓練した(Ouyang et al., 2022)。直接選好最適化(Direct Preference Optimization、DPO)は、報酬モデルを使わず、選好の対そのものに対する単純な損失によって選好チューニングを行う(Rafailov et al., 2023)。

SmolLM2-360M-Instruct は、第10章の基本モデルに両方の段階を施したものである。すなわち、公開データセットと選別したデータセットによる教師あり微調整を行い、続いて UltraFeedback で DPO を行っている(モデルカード)。UltraFeedback の選好の対は、人ではなく大規模言語モデルによって採点されている(Cui et al., 2023)。この章では SmolLM2-360M を基本モデル、SmolLM2-360M-Instruct をチューニング済みモデルと呼ぶ。スクリプト recordings/instruction_tuning.py は、リビジョンを固定し、貪欲法でデコードして両モデルを一度ずつ実行した。したがって各答えはそのモデルにとって最も確からしいものであり、実行は正確に再現できる。スクリプトは、モデルが書いた内容と、書いた各トークンをどれだけ確からしいと見なしたかを保存した。二つのモデルについてのすべての測定値は、これらのファイルから得ている。

この部分はまだ翻訳されていないため、英語で表示している。

Build the two training losses by hand

最終変更:版2026.11.16

Both steps of tuning are training, with the loop of chapter 8; what changes is the loss. Instruction tuning uses the ordinary next-token loss with one difference: only the response's tokens count. The request is read, as context, but the model isn't trained to predict it, since the point is to answer requests, not to write them.

Lay one product out as a request and a response, its name as the request and its description as the response, the way the store's model already reads it. Then compute that model's loss over every token, and over the response's tokens only:

instruction-loss-by-hand.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Computes the store's model's loss on one product laid out as a request and a response, over every token and overthe response's tokens only. The prose's point rests on the last printed line, the average loss over the response only."""import numpy as npfrom lib import transformerfrom lib.store import load_products_, vocabulary, manifest = transformer.load()index = {token: i for i, token in enumerate(vocabulary)}# the name is unique in the validation split, so its one row is the productproduct = load_products("validation").query("name == 'double chaise patio furniture cover'").iloc[0]# the text is cut at the model's longest length, so a long description may end earlyids = transformer.product_ids(product["name"], product["description"], index, manifest["settings"]["longest"])sep = ids.index(index[transformer.SEP])           # the name plays the request; the description, the response# the last position predicts nothing, since no token follows it, so its row is droppedprobabilities = transformer.softmax(transformer.forward(ids)[:-1])# position i predicts the token at i + 1, so ids[1:] holds each position's target# each token's loss, given the tokens before itloss = -np.log(probabilities[np.arange(len(ids) - 1), ids[1:]])response = np.arange(1, len(ids)) > sep                             # the description's tokens and its endprint("tokens predicted in the text:", len(loss))print("tokens the instruction loss counts, the response's:", int(response.sum()))print("average loss over every token:", f"{loss.mean():.3f}")print("average loss over the response only:", f"{loss[response].mean():.3f}")
出力python instruction-loss-by-hand.py
tokens predicted in the text: 96
tokens the instruction loss counts, the response's: 90
average loss over every token: 2.267
average loss over the response only: 2.132

Training on the loss over the response alone, across many requests and responses, teaches a model to produce responses. For this product that loss is 2.132, against 2.267 over every token. The instruction loss counts 90 of the 96 tokens the model predicts: the description's tokens and its end.

DPO's loss works on a pair of responses to one request, one preferred and one rejected. DPO compares how much more likely the model being tuned makes each response than the reference model it started from, the model after instruction tuning, and rewards it for raising the preferred one more. With log-probabilities log π of each response under the tuned model and log π_ref under the reference, and a factor β that sets how far the model may move:

margin = β × [(log π(preferred) − log π_ref(preferred)) − (log π(rejected) − log π_ref(rejected))]

loss = −log σ(margin)

with σ the logistic function from chapter 4 (Rafailov et al., 2023, equation 7). Made-up log-probabilities keep the arithmetic in plain view, so this example uses them, with β = 0.1:

dpo-loss-by-hand.py Python 3.12.15 · numpy 2.5.5 合格
"""Computes the DPO margin and loss by hand for two made-up cases, with a fixed beta. The prose's point rests on thetwo loss lines, one for each case."""import numpy as npbeta = 0.1                                       # how far the tuned model may move from the referenceprint("beta:", beta)# Each case: (preferred, rejected) under the tuned model, then (preferred, rejected) under the reference model it# started from. Made-up numbers, to follow the arithmetic.cases = {"tuned model favours the preferred answer more than the reference does": (-12.0, -20.0, -14.0, -18.0),         "tuned model favours it less": (-15.0, -15.0, -14.0, -18.0)}for label, (preferred, rejected, preferred_reference, rejected_reference) in cases.items():    margin = beta * ((preferred - preferred_reference) - (rejected - rejected_reference))    loss = np.log1p(np.exp(-margin))             # -log σ(margin), written so it can't overflow    print(f"{label}, margin:", f"{margin:.2f}")    print(f"{label}, loss:", f"{loss:.3f}")
出力python dpo-loss-by-hand.py
beta: 0.1
tuned model favours the preferred answer more than the reference does, margin: 0.40
tuned model favours the preferred answer more than the reference does, loss: 0.513
tuned model favours it less, margin: -0.40
tuned model favours it less, loss: 0.913

Lowering the loss pushes the preferred response's probability up and the rejected one's down, measured against where the model started. When the tuned model favours the preferred response more than the reference does, the margin is 0.40 and the loss 0.513; when it favours it less, the margin is -0.40 and the loss rises to 0.913.

Working rule: Mask the request out of the loss when you tune a model on requests and responses, and keep the reference model's log-probabilities beside the tuned model's when you train on preferences. Both are small changes to a loop you already have.

ベースモデルとチューニング済みモデルに尋ねる

最終変更:版2026.11.11

ストアには、説明文のない商品の説明文が必要である。この作業は、第9章で専用の小さなモデルに任せたものである。ベースモデルの SmolLM2-360M には依頼ができず、続きを書かせることしかできない。そのため、商品一覧の冒頭部分として、Product:、商品名、Description: を与える。チューニング済みモデルの SmolLM2-360M-Instruct には、Write a short product description for: と商品名から成る依頼を与える。

どちらのモデルも、第9章の商品 front porch welcome sign wall décor から始める。それぞれが書いた文章を読み、続いて、記録が説明した 8 個の商品すべてについて測定する。各商品には、参照できる説明文がない。

base-and-tuned.py Python 3.12.15 合格
"""Prints what the base and the tuned model wrote for one product with no description, then measures every such product'stext for materials its name doesn't give and for repeated four-word phrases. The prose's points rest on the last fourprinted lines, the two models' invented-material counts and repeat shares."""from collections import Counterfrom lib import claims, recorded# the recording's saved texts for every product, read back rather than generated againdescribed = recorded.read("instruction-tuning", "descriptions")product = next(row for row in described if row["name"] == "front porch welcome sign wall décor")print("product:", product["name"])print("base model:", " ".join(product["base"]["text"].split()))print("tuned model:", " ".join(product["tuned"]["text"].split()))def repeats(text):    """The share of four-word phrases that repeat an earlier one in the text."""    words = text.lower().split()    # every window of four consecutive words, so a text of n words has n - 3 of them    phrases = [tuple(words[i:i + 4]) for i in range(len(words) - 3)]    # a phrase counts as repeated each time after its first appearance; max keeps a text of fewer than four words from dividing by zero    return sum(count - 1 for count in Counter(phrases).values()) / max(len(phrases), 1)print("products described, none of which has a description to draw on:", len(described))for role in ["base", "tuned"]:    texts = [row[role]["text"] for row in described]    # materials the text names that the product's name doesn't give: a set difference, not the text's whole list    invented = sum(bool(claims.materials(row[role]["text"]) - claims.materials(row["name"])) for row in described)    print(f"{role} model, descriptions that name a material the name doesn't:", f"{invented} of {len(described)}")    print(f"{role} model, repeated four-word phrases:", f"{sum(map(repeats, texts)) / len(texts):.0%}")
出力python base-and-tuned.py
product: front porch welcome sign wall décor
base model: Front porch welcome sign wall décor The front porch is a common feature of many homes. It is a place where people can relax and enjoy the outdoors. It is also a place where people can socialize and meet new friends. The front porch is a great place to hang out with your family
tuned model: "Welcome to our front porch welcome sign wall décor, a space that brings warmth and comfort to your home. This wall is a statement piece that showcases your personality and style. With a mix of rustic and modern elements, you can create a unique and inviting atmosphere that reflects your individuality.
products described, none of which has a description to draw on: 8
base model, descriptions that name a material the name doesn't: 2 of 8
base model, repeated four-word phrases: 14%
tuned model, descriptions that name a material the name doesn't: 1 of 8
tuned model, repeated four-word phrases: 0%

ベースモデルは、玄関ポーチについて The front porch is a common feature of many homes と書き、その後はくつろぎや友人との集まりについて書く。もっともらしい方向に文章を続けているが、その方向はストアが必要とするものではない。チューニング済みモデルは、a statement piece that showcases your personality and style のように商品説明の形をした文章を書く。しかし、このサインを a space と呼び、This wall とも呼んでいる。理解していない商品について流暢に書いているのである。商品全体で見ると、ベースモデルの文章では、4語のフレーズの 14% が重複しており、チューニング済みモデルでは 0% が繰り返される。チューニングのどの段階がループを止めたのかは、記録からは分からない。

どちらのモデルも、商品名以外に商品について何も知らない。商品名に含まれない素材を挙げた説明文は、ベースモデルでは 2 of 8 件、チューニング済みモデルでは 1 of 8 件あった。これらはいずれも、第9章の場合と同様に、ストアのデータではなくモデルから出たものである。

実践ルール: 依頼に従わせたいときはチューニング済みモデルを使い、直前の文章の文体で続きを書かせたいときはベースモデルを使う。流暢さを知識と取り違えてはならない。チューニング済みモデルは、事実が足りないことに変わりはなくても、形の整った説明文を書く。

モデルがチューニングされた形式でリクエストを整える

最終変更:版2026.11.16

前の節でチューニング済みモデルが応答できたのは、リクエストがチューニング時と同じレイアウトで届いたからである。チューニング済みモデルのチャットテンプレートとは、そのモデルが学習したレイアウトのことであり、システムメッセージ(ユーザーのリクエストの前に置かれる指示)、リクエスト本体、モデルの返答のそれぞれがどこで始まりどこで終わるかを示す特殊トークンから成る。モデルはこのレイアウトの中でのみリクエストに答えることを学習しているため、それ以外の形式のリクエストは、続きを書くべき単なるテキストにすぎない。モデルを読み込むライブラリは、モデルのトークナイザファイル(トークナイザ設定)からこのテンプレートを適用する。

チューニング済みモデルの完全なプロンプトと、同じリクエストをプレーンテキストとして与えたときの返答を並べると、モデルが実際に何を読んでいるかがわかる。

chat-template.py Python 3.12.15 合格
"""Prints the full prompt the tuned model read, with its chat template, and its reply with and without the template. Theprose's point rests on the last two printed lines: the same words, with and without the template."""from lib import recordedtemplate = recorded.read("instruction-tuning", "template")# the request is the text between the user marker and its end markerprint("request:", template["with"]["prompt"].split("<|im_start|>user\n")[1].split("<|im_end|>")[0])print("what the tuned model reads, with its chat template:")print(template["with"]["prompt"])print("tuned model, with the template:", " ".join(template["with"]["text"].split()))print("tuned model, without it:", " ".join(template["without"]["text"].split()))
出力python chat-template.py
request: Write a short product description for: front porch welcome sign wall décor
what the tuned model reads, with its chat template:
<|im_start|>system
You are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>
<|im_start|>user
Write a short product description for: front porch welcome sign wall décor<|im_end|>
<|im_start|>assistant

tuned model, with the template: "Welcome to our front porch welcome sign wall décor, a space that brings warmth and comfort to your home. This wall is a statement piece that showcases your personality and style. With a mix of rustic and modern elements, you can create a unique and inviting atmosphere that reflects your individuality.
tuned model, without it: .

チューニングでモデルが身につけたのは、特定のレイアウトのリクエストに従うことであり、リクエスト一般に従うことではない。テンプレートを使うと、リクエストは <|im_start|>user と <|im_end|> の間に置かれ、その前にはテンプレートが既定で追加するシステムメッセージ You are a helpful AI assistant named SmolLM, trained by Hugging Face があり、その後ろには、モデルの返答が始まる <|im_start|>assistant が続く。モデルは前の節の説明文で返答する。テンプレートなしで同じ言葉をプレーンテキストとして与えると、チューニング済みモデルは . と書いて止まる。

システムメッセージも重要である。これはモデルが読むすべてのリクエストの一部であるため、たとえば店舗の説明や口調を述べたものなど、別のシステムメッセージに替えるだけで、どの返答も変わりうる。したがって、第9章のデコード設定と同じく、選んで記録すべき設定の一つである。

実践ルール: チューニング済みモデルへのリクエストは、必ずそのモデル自身のチャットテンプレートで整える。テンプレートはモデルのトークナイザファイルからライブラリに適用させ、手作業で組み立ててはならない。モデルはリクエストのたびにテンプレートの既定のシステムメッセージを読むので、その内容を確認し、保存する回答にはすべて、整形後の完全なプロンプトを記録すること。

製品の詳細のでっち上げを測定する

最終変更:版2026.11.16

製品について事実のないまま文章を書くモデルは、事実をでっち上げるほかない。より公平な検証では、モデルに事実を与える。2つのSmolLM2モデルに、製品の名前と実際の説明を示し、次のように尋ねる。What material is this product made of? Answer in a few words, using only the description. チューニング済みモデルには、この問いをテンプレートに沿った依頼の形で与える。ベースモデルには、続きを書くべきリストとして与え、末尾を Question:、質問、そして Answer: で終える。製品のデータが素材を挙げている場合、良い回答はその素材を挙げる。挙げていない場合、良い回答は説明に書かれていないと答える。

回答の検査には素材を表す語のリストが必要である。wood や metal から polyester や leather までを含むリストが、本書の共有モジュール lib.claims にある。回答は、そこで挙げた素材がすべて製品の名前か説明に含まれていれば裏付けありとする。製品の名前と説明に含まれない素材を挙げていればでっち上げとする。製品のデータには書かれていないと述べていれば回避とし、素材を挙げず、回避もしていなければなしとする。この検査には限界があり、判断を伴う箇所もある。mdf や rubberwood のような加工木材は木材として数え、brushed nickel finish はニッケルを挙げたものとして数え、リストにない素材は見逃す。分類したすべての回答は、誰でも読めるように記録してある。入力に裏付けのない詳細をでっち上げることは、ハルシネーションと呼ばれるものの一種であり(Ji et al., 2023)、この検証はまさにその種類を測定する。

無作為に抽出した 40 個の製品について、各モデルの回答を分類し、製品のデータが素材を挙げているかどうかで分けて集計する。データが素材を挙げていない場合に、チューニング済みモデルはベースモデルよりでっち上げる素材が少なくなるだろうか。結果を見る前に予想を決めておくこと。

made-up-materials.py Python 3.12.15 合格
"""Classes both models' answers to the material question, split by whether the product's name or description names amaterial. The prose's point rests on the rows for products whose data names none: made up and declined."""from collections import Counterfrom lib import claims, recordedasked = recorded.read("instruction-tuning", "answers")print("products asked, each with its description given:", len(asked))# a product's data names a material if its description or its name does: the union of the two setsgiven = [bool(claims.materials(row["description"]) | claims.materials(row["name"])) for row in asked]print("products whose name or description names a material:", sum(given))print("products whose name and description name none:", len(given) - sum(given))for role in ["base", "tuned"]:    for label, keep in [("data names a material", True), ("data names none", False)]:        rows = [row for row, named in zip(asked, given) if named == keep]        # each answer is classed against the product's data, by the rules in lib.claims        counts = Counter(claims.classify(row[role]["text"], row["description"], row["name"]) for row in rows)        for kind in ["supported", "made up", "none", "declined"]:            print(f"{role} model, {label}, {kind}:", counts[kind])
出力python made-up-materials.py
products asked, each with its description given: 40
products whose name or description names a material: 28
products whose name and description name none: 12
base model, data names a material, supported: 24
base model, data names a material, made up: 2
base model, data names a material, none: 2
base model, data names a material, declined: 0
base model, data names none, supported: 0
base model, data names none, made up: 7
base model, data names none, none: 5
base model, data names none, declined: 0
tuned model, data names a material, supported: 23
tuned model, data names a material, made up: 3
tuned model, data names a material, none: 2
tuned model, data names a material, declined: 0
tuned model, data names none, supported: 0
tuned model, data names none, made up: 8
tuned model, data names none, none: 4
tuned model, data names none, declined: 0
回答 ベース、データが素材を挙げている チューニング済み、データが素材を挙げている ベース、データが素材を挙げていない チューニング済み、データが素材を挙げていない
裏付けあり 24 23 0 0
でっち上げ 2 3 7 8
なし 2 2 5 4
回避 0 0 0 0

名前にも説明にも素材が挙げられていない 12 個の製品では、正しい回答は説明に書かれていないというものであるが、どちらのモデルも一度もそう答えなかった。どちらも代わりに大半は素材をでっち上げ、残りの回答は理由を述べずに素材を挙げなかった。製品のうち 28 個はデータが素材を挙げており、それらについては両モデルとも大半がそのデータに基づいて答えている。

命令チューニングはこの問題を解消せず、これらの製品では、続きを書くべきリストを与えられたベースモデルも劣らなかった。依頼は説明だけを使うよう指示していたが、説明に答えがない場合でも、モデルはこの種の製品によくある素材を挙げて答えた。指示の形式に従うことと、自分が知らないことを知っていることは同じではない。

実践ルール: モデルは、入力から答えられる質問だけでなく、答えられない質問でも試し、でっち上げられた回答は別に数えること。モデルが製品について述べる事実上の主張はすべて、可能なら自動で、製品のデータと照合すること。lib.claims が素材について行っているのがその例である。

確信度が警告になるかを確かめる

最終変更:版2026.11.11

前の節では、調整済みモデルによる素材の質問への回答を、裏づけのあるものと作り話のものに分類した。作り話の回答に低い確信度が伴っていれば、低い確信度がそれらを見分ける目印になりうる。モデルの確信度が正答する頻度と一致しているとき、そのモデルは較正されている(calibrated)という。Guo らは、彼らが調べた深層ニューラルネットワークが較正されていないことが多く、精度が正当化する以上に確信度が高かったことを見いだした(Guo et al., 2017)。記録には、調整済みモデルが書いた各トークンに与えた確率が、終端トークンを含めて保存されている。そのため、各回答についてトークンあたりの確信度を、幾何平均として計算できる。

トークンあたりの確信度 = exp((log p₁ + … + log pₙ) / n)

これは対数確率の平均の指数であり、パープレキシティが逆数として用いるものと同じ平均である。したがって、短い回答と長い回答を同じ尺度で測れる。

確信度は二種類の回答を区別できるだろうか。調整済みモデルの、裏づけのある回答と作り話の回答に対する確信度を比べ、トークンあたり 0.5 のしきい値でそれぞれ何件が残るかを数える。

answer-confidence.py Python 3.12.15 · numpy 2.5.5 合格
"""Compares the tuned model's confidence in its supported and made-up answers to the material question, and counts what athreshold of 0.5 per token keeps. The prose's point rests on the two average confidences and the two threshold counts."""import numpy as npfrom lib import claims, recordedasked = recorded.read("instruction-tuning", "answers")# only supported and made-up answers are compared; declined and none answers are left outby_kind = {"supported": [], "made up": []}for row in asked:    kind = claims.classify(row["tuned"]["text"], row["description"], row["name"])    if kind in by_kind:        # the geometric mean of the token probabilities: exp of their average log-probability        by_kind[kind].append(np.exp(np.mean(np.log(row["tuned"]["token_probabilities"]))))for kind, confidence in by_kind.items():    print(f"tuned model, {kind} answers:", len(confidence))    print(f"tuned model, {kind} answers, average probability per token:", f"{np.mean(confidence):.2f}")# a fixed cut for the comparison, not one fitted to these answersthreshold = 0.5for kind, confidence in by_kind.items():    print(f"tuned model, {kind} answers above {threshold} per token:", f"{sum(c > threshold for c in confidence)} of {len(confidence)}")
出力python answer-confidence.py
tuned model, supported answers: 23
tuned model, supported answers, average probability per token: 0.65
tuned model, made up answers: 11
tuned model, made up answers, average probability per token: 0.45
tuned model, supported answers above 0.5 per token: 21 of 23
tuned model, made up answers above 0.5 per token: 3 of 11

確信度は信号であって、フィルタではない。確信度は見込みを変えるが、確信に満ちた誤りは通してしまう。作り話の回答の確信度は平均してより低く、トークンあたり 0.45 であり、裏づけのある回答では 0.65 である。しかし、トークンあたり 0.5 のしきい値では、裏づけのある回答が 21 of 23 件残り、それでも作り話の回答が 3 of 11 件通り抜ける。回答の数が少ないため、これらは頼りにできる比率ではなく、傾向を示すものにすぎない。

実践ルール: モデルの確信度だけで、回答を信頼するかどうかを決めてはならない。自分の質問で、確信度と正答との関係を測定せよ。しきい値を使う場合は、その測定結果から選び、それが何件を通すかを数えよ。

長いコンテキストが失うものを見つける

最終変更:版2026.11.11

素材に関する質問では、モデルに一度に1つの製品を与えた。ストアのアシスタントは、検索結果、カテゴリページ、比較表などのように、複数の製品のデータを同時に前にして、その中から目的の製品の詳細を見つけ出さなければならないことが多い。Liu らは、モデルは長いコンテキストの先頭と末尾にある情報を、中間にある情報よりもよく利用することを明らかにした(Liu et al., 2024)。

尋ねる対象の製品を、10件の製品リストの中の先頭、中間、末尾のいずれかに置く。次に、調整済みモデルである SmolLM2-360M-Instruct に、その製品が何でできているかを尋ねる。データに素材が記載されている14件の製品について、lib.claimsが検査するとおりに、その製品自身の素材だけを挙げた回答を数える。

answer-position.py Python 3.12.15 合格
"""Counts the tuned model's answers that name only the asked product's own materials, with the product first, in the middleor last of a context of listings. The prose's point rests on the three placement lines."""from collections import defaultdictfrom lib import claims, recordedcontext = recorded.read("instruction-tuning", "context")# the other listings in each context; the asked product is one more, as the first printed line showsothers = recorded.read("instruction-tuning", "manifest")["settings"]["context_others"]print("product listings in each context:", others + 1)results = defaultdict(list)for row in context:    # only products whose data names a material: a product with none gives an answer nothing to name    if claims.materials(row["description"]) | claims.materials(row["name"]):        # supported: every material the answer names is in the asked product's own data        results[row["place"]].append(claims.classify(row["tuned"]["text"], row["description"], row["name"]) == "supported")print("products asked about at each place:", len(results["first"]))for place in ["first", "middle", "last"]:    print(f"product placed {place}, answers that name only its own materials:", f"{sum(results[place])} of {len(results[place])}")
出力python answer-position.py
product listings in each context: 10
products asked about at each place: 14
product placed first, answers that name only its own materials: 12 of 14
product placed middle, answers that name only its own materials: 6 of 14
product placed last, answers that name only its own materials: 12 of 14

中間にある製品は最も見つかりにくく、これはLiu らがはるかに大きなモデルで見いだしたパターンと同じである。製品を先頭に置いた場合、その素材だけを挙げた回答は12 of 14件、末尾では12 of 14件、中間では6 of 14件である。件数は少ないが、差は大きい。ここでのコンテキストは数千文字と短く、モデルの上限には十分に余裕がある。コンテキストが満杯になるはるか前から、中間では詳細が失われるのである。

実践ルール: モデルが最も必要とする詳細は、コンテキストの中間ではなく先頭か末尾に置き、課題が許す範囲で無関係なテキストを与えないようにする。多数のデータの中から詳細を見つける能力をモデルに任せる前に、長いコンテキストからの検索を各位置で試験する。

自分のテキストにモデルを適応させる

最終変更:版2026.11.16

第10章では、汎用モデルが店の商品名に対して、単語あたりで見ると店の小さなモデルよりはるかに劣ることを確認した。指示チューニングが変えるのはモデルの答え方であり、一つの店についてモデルが何を知っているかではない。汎用モデルに店のテキストを教える方法はファインチューニングである。これは、そのテキストでモデルの学習を続けることであり、第8章と同じ学習ループを、ランダムな重みではなく汎用モデルの重みから始めて回す。

完全なファインチューニングはすべての重みを更新するため、数億個のパラメータを持つモデルでは時間もメモリも必要になる。LoRA(low-rank adaptation、低ランク適応)は、モデルの重みを固定し、その一部の重みの横に小さな補正を置いて学習する。k 個の数を d 個の数に写す重み行列に対し、d × r の行列 B と r × k の行列 A を学習し、その積を重みに加える。すなわち W + BA である(Hu et al., 2022)。ランク r を小さくすれば、学習し保存すべきものがはるかに少なくなる。Hu らは、彼らが試したタスクでは完全なファインチューニングに匹敵する結果が得られたと報告している。

LoRA の補正が学習する重みははるかに少ないはずである。実際に数えてみる。SmolLM2-360M で、すべての層のクエリ重みとバリュー重みを適応対象とし、二つのランクについて数え、完全なファインチューニングと比べる。クエリ重みは 960 個の数を 960 個に写す。バリュー重みは、キーとバリューがグループ化されているため、960 個を 320 個に写す。

lora-parameters.py Python 3.12.15 合格
"""Counts what LoRA would train on SmolLM2-360M, adapting the query and value weights of every layer at two ranks, andwhat full fine-tuning trains. The prose's point rests on the rank 8 lines and the full fine-tuning count."""from lib import open_modelconfig = open_model.config("SmolLM2-360M")width, layers = config["hidden_size"], config["num_hidden_layers"]# keys and values share heads, so their width is the query width scaled by the ratio of key-value heads to headskey_value_width = config["num_key_value_heads"] * width // config["num_attention_heads"]# every parameter of the model: the full fine-tuning count, and the denominator of each sharetotal = open_model.parameters(config)["total"]for rank in [8, 64]:    # LoRA adds two small matrices beside each adapted weight: width x rank, then rank x output width.    added = layers * (rank * (width + width) + rank * (width + key_value_width))       # on the query and value weights    print(f"rank {rank}, parameters trained:", f"{added:,}")    print(f"rank {rank}, share of the model's parameters:", f"{added / total:.2%}")print("parameters trained by full fine-tuning:", f"{total:,}")
出力python lora-parameters.py
rank 8, parameters trained: 819,200
rank 8, share of the model's parameters: 0.23%
rank 64, parameters trained: 6,553,600
rank 64, share of the model's parameters: 1.81%
parameters trained by full fine-tuning: 361,821,120

ランク 8 では、LoRA が学習するパラメータは 819,200 個で、モデル全体の 0.23% である。一方、完全なファインチューニングでは 361,821,120 個すべてを学習する。ランク 8 の補正は店自身の小さなモデルよりも小さく、基盤の重みを共有したまま、タスクごとに保存して入れ替えることができる。

本書ではこのファインチューニングを実行しない。店のテキストに対しては、LoRA であっても、ノートパソコンのプロセッサでは本書のどの記録よりもはるかに長い時間がかかる、というのが筆者の判断である。これは、汎用モデルに自店の文体で書かせたい店にとっての次の一歩である。カタログでファインチューニングを行い、第10章と同じように、その結果を店自身のモデルと単語あたりで比べて測定する。ファインチューニングには固有のリスクもある。カタログで学習したモデルは、テキストとともにその欠落も学んでしまう。第9章で店の小さなモデルが電球の説明を空欄のままにすることを学んだのと同じである。また、一つの狭いテキストで学習すると、モデルがそれまでに知っていたことが弱まることがある。Biderman らは、LoRA は完全なファインチューニングよりも忘却が少ないことを見いだした(Biderman et al., 2024)。どちらも、本書の他のすべてと同じやり方、すなわち、取り分けておいたテキストで、学習の前後に測定して確かめる。

実践ルール: 汎用モデルに自分のテキストを教えるには、そのテキストでファインチューニングする。メモリや保存容量が厳しい場合は LoRA を使い、結果は同種の保持したテキストで測定する。モデルがそもそも学んでいない知識を、指示チューニングや巧みなプロンプトが補ってくれると期待してはならない。

物差しを振り返る

最終変更:版2026.11.12

本書は第3章以降、名前に対するすべてのモデルを同じ方法で採点してきた。採点には、ストアのトークナイザーのトークン単位のパープレキシティを用い、ストアの検証用の名前で測る。テスト用の名前は取り分けておいた。これは、採用したエポックや混合の割合のように、検証用の名前を見て行った選択が結果を良く見せることのないようにするためである。この最後の比較では、候補となった五つのモデルを4,281のテスト用の名前で採点する。混合の割合は検証用の名前で選んだものを用いる。

test-names.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Scores the five models the book chose between on the test names, each name's tokens and its end, and prints eachmodel's test perplexity. The prose's point rests on the five test perplexity lines."""import numpy as npfrom lib import neural, transformerfrom lib.names import name_tokensfrom lib.ngrams import KneserNey, ngrams, padded# The test names, untouched until now: every model scores each name's tokens and its end. The mixing shares are the# ones chosen on the validation names, in chapters 5 and 8.test = name_tokens("test")counted = KneserNey(name_tokens("train"), 4)# padded adds the start marker three times and the end marker, so each name's first tokens have a context and its end is scoredfrom_counts = np.array([counted.probability(c, t) for text in test for c, t in ngrams(padded(text, 4), 4)])from_window = neural.token_probabilities(test)_, vocabulary, _ = transformer.load()index = {token: i for i, token in enumerate(vocabulary)}from_transformer = []for name in test:    # the transformer reads the start marker, the name, then <sep>, which ends a name where the counts end with </s>    ids = [index[transformer.START]] + [index[t] for t in name] + [index[transformer.SEP]]    probabilities = transformer.softmax(transformer.forward(ids)[:-1])    # position i predicts token i + 1, so ids[1:] is each token's target, the end of the name included    from_transformer += list(probabilities[np.arange(len(ids) - 1), ids[1:]])from_transformer = np.array(from_transformer)# pooled over every token of every name, not averaged per nameperplexity = lambda p: f"{np.exp(-np.log(p).mean()):.1f}"print("test names:", f"{len(test):,}")print("test perplexity, the 4-gram baseline:", perplexity(from_counts))print("test perplexity, the window model:", perplexity(from_window))# the mix averages the probabilities, not their logs: a share of 0.2 is 20% of the window modelprint("test perplexity, the window model mixed with the counts, share 0.2:", perplexity(0.2 * from_window + 0.8 * from_counts))print("test perplexity, the store's transformer:", perplexity(from_transformer))print("test perplexity, the store's transformer mixed with the counts, share 0.5:", perplexity((from_transformer + from_counts) / 2))
出力python test-names.py
test names: 4,281
test perplexity, the 4-gram baseline: 22.9
test perplexity, the window model: 35.4
test perplexity, the window model mixed with the counts, share 0.2: 21.6
test perplexity, the store's transformer: 23.7
test perplexity, the store's transformer mixed with the counts, share 0.5: 18.3

検証用の名前で行った選択が結果を良く見せた程度はごくわずかであり、テストの列は検証の列に近い値にとどまる。両者を並べると、本書の筋道が一つの表にまとまる。

モデル 章 検証用の名前 テスト用の名前
単一トークンの頻度、1-gram 3 687.2
トークン対の頻度、2-gram 3 46.9
四つのトークンの頻度、4-gramのベースライン 3 23.1 22.9
ウィンドウモデル、小さなニューラルネットワーク 5 36.4 35.4
頻度と混合したウィンドウモデル 5 21.9 21.6
ストアのトランスフォーマー 8 24.0 23.7
頻度と混合したストアのトランスフォーマー 8 18.4 18.3

ここからは三つの教訓が読み取れる。第一に、短く定型的なテキストでは、頻度の計数だけでかなりの水準に達する。名前だけを対象とした場合、本書の学習済みモデルのうち4-gramのベースラインを上回ったものはなく、二つの混合モデルはどちらもそれを上回った。第二に、学習済みモデルが価値を持つのは、頻度とは異なる箇所で誤るからである。このため、すべての混合モデルは、それを構成する二つのモデルのどちらをも上回った。第三に、遠く離れた文脈が重要になる長いテキストでは、第8章が説明文で測定したとおり、トランスフォーマーが単独で優位に立った。大きさだけでは何も決まらなかった。第10章の汎用モデルは数百倍の大きさがあるが、ストアの名前に対する1語あたりのスコアは54,352.8であり、ストアのトランスフォーマーの199.3に及ばなかった。

これらの数値は、モデルが有用かどうかを示すものではない。パープレキシティが測るのは、モデルが学習用テキストに似たテキストをどれだけうまく予測できるかであり、これはオートコンプリートに必要な性質である。しかし、説明文が真実かどうか、回答が依頼に沿っているかどうか、買い物客が目当ての商品を見つけられるかどうかは測れない。本章のテスト、すなわち作り話の素材、確信度、文脈の中での事実の位置は、パープレキシティを超えて、仕事そのものを測定するための第一歩である。

実践ルール: モデルを比較する物差しは、本書で行ったように一つに固定する。つまり、毎回同じテキスト、同じトークナイザー、同じ尺度を使う。そのうえで、モデルを実際の用途に供する前に、その仕事に合わせて作ったテストで仕事そのものを測定する。パープレキシティが低いことは、そのモデルをテストする理由にはなるが、出荷する理由にはならない。

本番環境で何が問題になるか

チューニング済みのモデルは、人が支援なしで使える種類のモデルであるが、その失敗は成功と同じように流暢な文章で現れる。

  • 分からないと答えるべき場面で答えてしまう。 ベースの SmolLM2 モデルもチューニング済みの SmolLM2 モデルも、データに素材が記載されていない製品の大半について素材を作り上げた。どちらも、データに記載がないと述べることは一度もなかった。買い物客に届く前に、あらゆる事実に関する主張を製品のデータと照合すること。
  • 確信度では誤りを防ぎきれない。 作り上げられた回答の確信度は平均では低かったが、正しい回答の大半を残すしきい値を設定しても、作り上げられた回答が 3 of 11 通過した。
  • 形式は学習の一部である。 チャットテンプレートを使わない場合、チューニング済みモデルは句点を一つ書いただけだった。モデルのファイルにあるテンプレートを適用し、すべての回答について完全なプロンプトを記録すること。
  • コンテキストの中央部分は失われる。 重要な詳細は先頭か末尾に置き、各位置で検索を試験すること。
  • モデルは利用者のテキストを知らない。 指示チューニングが教えるのは回答の形式であり、店舗のカタログではない。カタログでファインチューニングを行い、その効果を測定すること。
  • 流暢さは欠落を覆い隠す。 チューニング済みモデルの説明文はベースモデルのものより読みやすいが、含まれる事実は増えていない。生成されたテキストは、読んだ印象ではなく、その主張に対する検査によって判断すること。
  • 挙動はリビジョンとテンプレートの既定メッセージに依存する。 記録で行っているようにモデルのリビジョンを固定し、更新のたびにこれらの測定をやり直すこと。

この章で決めたこと

  • 本書は、基本モデルとチューニング済みモデルを同じ requests で比較する。 固定したリビジョンで一度だけ記録し、貪欲デコードで生成させ、その回答を、誰でも再実行できるチェックで測定する。素材に対する lib.claims がその一例である。
  • でっち上げの詳細は、入力から答えられる質問だけでなく、答えられない質問でも測定する。 ストアの商品で調べたところ、SmolLM2 の両モデルとも、データに素材の記載がない商品の大半について素材をでっち上げ、回答を控えたことは一度もなかった。そのため、生成された商品の事実は、必ず商品のデータと照合して確認する。
  • モデルの確信度は信号であり、フィルタではない。 ストア自身の質問で測定したしきい値とともにのみ使い、それをすり抜ける誤りは数え上げる。
  • モデルが必要とする詳細は、コンテキストの冒頭か末尾に置く。 他の商品の中に埋もれさせてはならない。
  • パープレキシティは、モデルを比較するための本書の物差しであり続ける。 毎回、同じテキスト、同じトークナイザ、同じイベントで測定し、各モデルが選ばれる目的の仕事は、その仕事向けに作ったテストで測定する。
  • 汎用モデルにストアのテキストを教えるには、ファインチューニングが必要である。 効果は単語ごとに、ストア自身のモデルと比べて測定する。インストラクションチューニングが変えるのはモデルの答え方であり、モデルが知っている内容ではない。本書の次トークンテストの範囲を超えて、アプリケーションの中でモデルを測定することは、それだけで一つの主題である。

この版における本章

第2026.11.16版2026年11月19日時点で例が通過この章の9 例件のうち9件が合格

英語版の書籍(版2026.11.16)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全11章中の第11章: 予測から指示への追従へ

  1. Build the two training losses by hand
  2. ベースモデルとチューニング済みモデルに尋ねる
  3. モデルがチューニングされた形式でリクエストを整える
  4. 製品の詳細のでっち上げを測定する
  5. 確信度が警告になるかを確かめる
  6. 長いコンテキストが失うものを見つける
  7. 自分のテキストにモデルを適応させる
  8. 物差しを振り返る
  9. 本番環境で何が問題になるか
  10. この章で決めたこと

ページの先頭に戻るすべての章