文档导航

微调

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