文件導航

微調

laya.train 單獨匯入(from laya.train import finetune, TrainConfig);它不從頂層包再匯出。 laya-train 是它的命令列。微調指南展示了兩者的用法。

執行一次微調

名稱、型別、預設值與程式碼保持英文;其餘為譯文(尚未翻譯的條目暫顯示英文原文)。

TrainConfig

TrainConfig()

訓練旋鈕。預設值按已釋出的 notebook 的方式訓練。

notebook 的有效批次 64,是每個 micro-batch 8 × 2 塊 GPU × 4 次累積;在單裝置上就是 micro_batch=8, grad_accum=8。

max_len / head_max_len 預設取 checkpoint 自己的配置。實際用到的值會寫進儲存下來的配置,所以推理看到的預算與訓練時相同。amp 僅在 CUDA 上預設開啟;gradient_checkpointing 預設跟隨 amp。option_layout 預設取 checkpoint 自己的(所有已釋出的都是 "sequential");"parallel" 按 common.parallel_layout 訓練,並寫入儲存下來的配置。

finetune

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

預處理、訓練、校準並儲存;返回這次執行的摘要。

data 是一個 JSONL 檔案,裡面是 {state, questions, gold} 或 {state, questions, expected} 行;或者是一個帶文本列與標籤列的 CSV 檔案。model_dir 是一個本地 checkpoint 目錄 —— 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 的兩半

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;返回每個 epoch 的平均 loss。

參數

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]]

把一個每行一個帶標籤列的 CSV 檔案讀成 {state, questions, expected} 行。

發現 label_column 裡各不相同的標籤(保留出現順序),並用這些標籤構建一個 choice 問題,標籤作為 criteria 列表,讓每個選項都被渲染一次。使用 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} schema。非字串的 choice 標籤還會按它的 JSON 鍵去查。機率之和為零的行會變成均勻分佈,與腳本里一致。出現負數或非有限機率會拋 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 答案歸一得到的目標分佈,按選項順序排列。

expected_val 是:

  • choice 問題:一個 choice 標籤(字串,或與某個 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(目標的條目數與選項數對不上)、options_collapsed(決策頭預算讓兩個選項擁有了同樣的 token span,#538),以及當給了 max_len 時的 options_beyond_max_len(決策頭比 max_len 還長,於是 build_sequence 丟掉了最後幾個選項的 marker —— 就是 Agent 在推理時以 "only N of its M option markers fit" 拒絕的那種情況)。在它們任何一個上訓練,都會讓模型去區分它看不出差別的選項,或者因為目標比它的 marker 還長而讓整批崩掉。

參數

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 rank、每次重跑都留出同樣的項。

參數

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

notebook 的目標函式:在加噪 logits 上的一個策略梯度項,加上軟交叉熵。

對分離(detached)的 logits 加上零均值高斯噪聲(按 sigma 縮放,並投影到每一行自己的選項上);每個樣本按 proper_reward 相對目標獲得獎勵,歸一後的優勢給該樣本的高斯對數密度加權。

參數

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

checkpoint

resolve_checkpoint_dir

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

把一個本地路徑、模型別名('multilingual'、'english')或 Hub repo ID 解析成一個本地目錄。

參數

model_id_or_pathstr
tokenOptional[str]= None

load_checkpoint

load_checkpoint(model_dir: str)

從本地 checkpoint 目錄或 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 權重、encoder 配置、tokenizer、配置。

參數

model
tok
cfgDict[str, Any]
pathstr