ドキュメント

ファインチューニング

laya.train はそれ単体でインポートします(from laya.train import finetune, TrainConfig)。 トップレベルパッケージからは再エクスポートされません。laya-train がそのコマンドラインです。 ファインチューニングのガイドで両者の 使い方を示します。

ファインチューニングを実行する

名前・型・既定値・コードは英語のまま、それ以外は翻訳です(未翻訳の項目は英語原文のまま表示されます)。

TrainConfig

TrainConfig()

学習のつまみ。既定は公開ノートブックと同じように学習します。

ノートブックの実効バッチ 64 は、マイクロバッチあたり 8 × GPU 2 台 × 蓄積 4 ステップです。1 台のデバイスでは micro_batch=8, grad_accum=8 になります。

max_len / head_max_len は既定でチェックポイント自身の config を使います。使われたものは保存される config に書き込まれるので、推論は学習と同じ予算を見ます。amp は既定で CUDA にだけオンになります。gradient_checkpointing は既定で amp に従います。option_layout は既定でチェックポイント自身のもの(公開されているものはすべて "sequential")です。"parallel" は common.parallel_layout で学習し、保存される config に書き込まれます。

finetune

finetune(
    data: str,
    model_dir: str,
    output_dir: str,
    config: Optional[TrainConfig] = None,
    device: Optional[str] = "auto",
) -> Dict[str, Any]

前処理し、学習し、較正して保存します。実行の要約を返します。

data は {state, questions, gold} または {state, questions, expected} の行からなる JSONL ファイル、または text 列と label 列を持つ CSV ファイルです。 model_dir はローカルのチェックポイントディレクトリで、laya.load が読むレイアウトです。output_dir の結果は laya.load(output_dir) で読み込めます。

引数

datastr
model_dirstr
output_dirstr
configOptional[TrainConfig]= None
deviceOptional[str]= "auto"

dry_run

dry_run(
    data: str,
    model_dir: str,
    config: Optional[TrainConfig] = None,
) -> Dict[str, Any]

モデルの重みを読み込まずにデータセットを調べ、アイテムを組み立てます。データセットの統計を返します。

引数

datastr
model_dirstr
configOptional[TrainConfig]= None

finetune の 2 つの半分

train_model

train_model(
    model,
    tok,
    items: Sequence[Dict[str, Any]],
    config: TrainConfig,
    device: torch.device,
    max_len: int,
    head_max_len: int,
    on_epoch_end: Optional[Callable[[int, float], None]] = None,
    parallel: bool = False,
) -> List[float]

items 上で model をその場で学習します。各エポックの平均損失を返します。

引数

model
tok
itemsSequence[Dict[str, Any]]
configTrainConfig
devicetorch.device
max_lenint
head_max_lenint
on_epoch_endOptional[Callable[[int, float], None]]= None
parallelbool= False

calibration_records

calibration_records(
    model,
    tok,
    items: Sequence[Dict[str, Any]],
    device: torch.device,
    max_len: int,
    head_max_len: int,
    batch_size: int = 16,
    parallel: bool = False,
)

fit_temperature_map 用の (qtype, logits, target, k) レコード。選択肢は正準順です。

引数

model
tok
itemsSequence[Dict[str, Any]]
devicetorch.device
max_lenint
head_max_lenint
batch_sizeint= 16
parallelbool= False

calibration_report

calibration_report(
    records: Sequence[Tuple[int, Any, Any, int]],
    temperature: Sequence[float],
) -> Dict[str, Dict[str, Any]]

質問の型ごとに:キャリブレーションアイテムが何件あったか、何が当てはめられたか、何を疑うべきか。

records は温度を当てはめた calibration_records で、temperature は fit_temperature_map が返した型ごとのスカラーです。各型は、キャリブレーションアイテム上の items、temperature、accuracy、mean_confidence(当てはめた温度での最高確率)と、issues のリストを持ちます。何もおかしくなければ空です:

  • MIN_TYPE_N 未満のアイテム:温度は当てはめられず、1.0 のままです。
  • CALIB_WARN_N 未満のアイテム:当てはめられましたが、根拠が乏しいです。
  • [TEMP_MIN, TEMP_MAX] のクランプに当たりました。
  • 当てはめたのに 1.0 のまま変わらず返りました。これは通常、アイテムが当てはめに直すものを何も与えなかったことを意味します —— モデルがそれらに対してすでに確信を持って正しいときに生じるものです。

キャリブレーションアイテムがまったくない型は issues を持ちません。それはデータになかったのです。

引数

recordsSequence[Tuple[int, Any, Any, int]]
temperatureSequence[float]

データを読む

read_data

read_data(
    path: str,
    text_column: str = "text",
    label_column: str = "label",
    question_id: str = "label",
    instructions: Optional[str] = None,
) -> List[Dict[str, Any]]

JSONL ファイルまたは CSV ファイルから学習/評価の行を読みます。

引数

pathstr
text_columnstr= "text"
label_columnstr= "label"
question_idstr= "label"
instructionsOptional[str]= None

rows_from_csv

rows_from_csv(
    path: str,
    text_column: str = "text",
    label_column: str = "label",
    question_id: str = "label",
    instructions: Optional[str] = None,
) -> List[Dict[str, Any]]

1 行にラベル付きの列を 1 つ持つ CSV ファイルを、{state, questions, expected} の行として読みます。

label_column の重複を除いたラベルを(出現順を保って)見つけ、それらのラベルを criteria のリストとする choice 質問を組み立て、各選択肢を 1 度ずつレンダリングします。utf-8-sig エンコーディングを使うので、Excel の UTF-8 BOM ヘッダーも透過的に扱われます。

引数

pathstr
text_columnstr= "text"
label_columnstr= "label"
question_idstr= "label"
instructionsOptional[str]= None

学習アイテムを組み立てる

items_from_rows

items_from_rows(
    tok,
    rows: Iterable[Dict[str, Any]],
    max_len: int,
    head_max_len: int,
    label_smoothing: float = 0.0,
) -> Tuple[List[Dict[str, Any]], Dict[str, int]]

{state, questions, gold} または {state, questions, expected} の行からアイテムを作ります。(items, skipped) を返します。

skipped は、ラベルは付いていたがアイテムになれなかった質問を理由ごとに数えます:empty_text、empty_label、invalid_question、invalid_target(to_internal、target_from_gold、target_from_expected からの ValueError)、さらに make_item が与える理由です。gold の項目も expected の項目も持たない質問は数えられません —— その行は単にそれらにラベルを付けていないだけです。

引数

tok
rowsIterable[Dict[str, Any]]
max_lenint
head_max_lenint
label_smoothingfloat= 0.0

target_from_gold

target_from_gold(q: Dict[str, Any], gold_q: Dict[str, Any]) -> List[float]

内部の質問(to_internal)の、選択肢順の正規化されたターゲット分布です。

gold_q["probabilities"] は、choice ではラベル、noul では "false"/"true"、score ではレベルインデックスを文字列にしたものをキーにします —— docs/finetune.md の {state, questions, gold} スキーマです。文字列でない choice ラベルは、その JSON キーとしても引かれます。確率の合計が 0 の行は、スクリプトと同様に一様になります。負または非有限の確率は ValueError を送出します。

引数

qDict[str, Any]
gold_qDict[str, Any]

target_from_expected

target_from_expected(
    q: Dict[str, Any],
    expected_val: Any,
    label_smoothing: float = 0.0,
) -> List[float]

単一の期待される答えから、選択肢順の正規化されたターゲット分布を作ります。

expected_val は:

  • choice 質問では choice ラベル(str、または criterion に一致する値)
  • noul 質問では真偽値
  • score 質問では整数のレベルインデックスまたはレベル文字列

label_smoothing > 0 のときは、確率の質量を一様に平滑化します: target[i] = (1 - eps) * one_hot[i] + eps / K。

引数

qDict[str, Any]
expected_valAny
label_smoothingfloat= 0.0

to_internal

to_internal(qid: Any, question: Dict[str, Any]) -> Dict[str, Any]

推論が質問を見るままの形です:Agent._check_question の後に Agent._to_internal です。

他のレンダリングで学習すると、モデルに推論では決して見ない選択肢テキストを教えてしまいます —— リスト形式の choice、カスタムの noul labels、非文字列の instruction などです。

引数

qidAny
questionDict[str, Any]

make_item

make_item(
    tok,
    q: Dict[str, Any],
    target: Sequence[float],
    state_ids: List[int],
    head_max_len: int,
    max_len: Optional[int] = None,
) -> Tuple[Optional[Dict[str, Any]], Optional[str]]

(item, None)、または質問が書かれているままでは学習できないときは (None, reason) を返します。

q は内部の質問(to_internal)です。理由は target_mismatch(ターゲットが選択肢ごとに 1 つのエントリを持たない)、options_collapsed(head 予算が 2 つの選択肢を同じトークン幅にしてしまった、#538)、そして max_len が与えられたときは options_beyond_max_len(head が max_len より長いので、build_sequence が最後の選択肢のマーカーを落とす —— Agent が推論時に「M 個の選択肢マーカーのうち N 個しか収まらない」と拒否する場合です)です。どれかで学習すると、モデルに、違うものと見分けられない選択肢を見分けさせたり、マーカーより長いターゲットでバッチをクラッシュさせたりします。

引数

tok
qDict[str, Any]
targetSequence[float]
state_idsList[int]
head_max_lenint
max_lenOptional[int]= None

encode_item

encode_item(
    tok,
    item: Dict[str, Any],
    max_len: int,
    head_max_len: int,
    option_order: Optional[List[int]] = None,
    parallel: bool = False,
) -> Dict[str, Any]

アイテムのモデル入力で、選択肢は option_order の順、照合すべきターゲット付きです。

build_sequence は選択肢 option_order[s] をスロット s に置くので、スロット順のターゲットは target[option_order[s]] です —— 推論時に unpermute_probs がすることの逆です。

引数

tok
itemDict[str, Any]
max_lenint
head_max_lenint
option_orderOptional[List[int]]= None
parallelbool= False

draw_option_order

draw_option_order(
    item: Dict[str, Any],
    rng: random.Random,
    shuffle_types: Sequence[str],
) -> Optional[List[int]]

型が shuffle_types にあるアイテムにはランダムな順列を、それ以外には None(正準)を返します。

引数

itemDict[str, Any]
rngrandom.Random
shuffle_typesSequence[str]

split_calibration

split_calibration(
    items: Sequence[Any],
    calib_max: int,
    calib_frac: float,
    seed: int,
) -> Tuple[List[Any], List[Any]]

(train, calibration) で、キャリブレーションスライスは学習の前に取り分けられます。

実行が学習したアイテムに温度を当てはめると、キャリブレーションではなく当てはまりを測ってしまいます(docs/finetune.md)。分割は seed とアイテム数にだけ依存するので、すべての DDP ランクと再実行が同じアイテムを取り分けます。

引数

itemsSequence[Any]
calib_maxint
calib_fracfloat
seedint

損失

soft_ce_loss

soft_ce_loss(
    logits: torch.Tensor,
    target: torch.Tensor,
    mask: torch.Tensor,
) -> torch.Tensor

ターゲット分布に対するクロスエントロピーで、各行自身の選択肢の上だけで計算します。

引数

logitstorch.Tensor
targettorch.Tensor
masktorch.Tensor

rlcd_loss

rlcd_loss(
    logits: torch.Tensor,
    target: torch.Tensor,
    mask: torch.Tensor,
    qtype: torch.Tensor,
    sigma: float,
    samples: int = 4,
    w_sph: float = 0.75,
    w_rps: float = 1.0,
) -> torch.Tensor

ノートブックの目的関数:ノイズ付きロジットに対する方策勾配の項と、ソフトクロスエントロピーです。

ゼロ平均のガウスノイズ(sigma でスケールし、各行の選択肢へ射影)を、detach したロジットに加えます。各サンプルはターゲットに対して proper_reward で報酬付けされ、正規化されたアドバンテージがそのサンプルのガウス対数密度を重み付けします。

引数

logitstorch.Tensor
targettorch.Tensor
masktorch.Tensor
qtypetorch.Tensor
sigmafloat
samplesint= 4
w_sphfloat= 0.75
w_rpsfloat= 1.0

チェックポイント

resolve_checkpoint_dir

resolve_checkpoint_dir(model_id_or_path: str, token: Optional[str] = None) -> str

ローカルパス、モデルの別名('multilingual'、'english')、または Hub リポジトリ ID を、ローカルディレクトリに解決します。

引数

model_id_or_pathstr
tokenOptional[str]= None

load_checkpoint

load_checkpoint(model_dir: str)

ローカルのチェックポイントディレクトリまたは Hub ID から (model, tokenizer, cfg) を返します。モデルは CPU 上の fp32 です。

引数

model_dirstr

save_checkpoint

save_checkpoint(model, tok, cfg: Dict[str, Any], path: str) -> None

laya.load が読むレイアウトを書き出します:fp16 の重み、エンコーダ config、トークナイザー、config。

引数

model
tok
cfgDict[str, Any]
pathstr