跳到主要内容
训练指南章节 全部文档

Python SDK:方法、结果与错误

TrainingProject 方法的签名、参数、返回值和可恢复错误,并附完整 Python 示例。

所有语言版本中的命令和代码均保持英文。请将大写占位符替换为您账户和付费作业中的实际值;请勿将真实密钥粘贴到共享笔记本或日志中。

同一项目 API,共用一个底层引擎

CLI 与 Python 必须对配置、状态和交付物达成一致。
  1. from_file 加载配置,不更改权重
  2. plan 检查解析后的输入
  3. run / controls 管理 worker 与恢复
  4. evaluate / export 检查验收通过的本地输出

from_file: 加载配置,不更改权重. plan: 检查解析后的输入. run / controls: 管理 worker 与恢复. evaluate / export: 检查验收通过的本地输出

在 Python 中使用同一训练引擎

TrainingProject 与 TrainingClient 配合使用,不会取代它。加载配置和限定范围的 API key,检查计划,然后启动运行。项目对象公开其拥有的运行,供检查和控制;run 不会覆盖已有运行,而 resume 要求有效的恢复状态。

  • 路径可使用字符串或 os.PathLike 对象。方法选项只能作为关键字参数传入。
  • 调用 from_file 会验证本地配置;不会更新权重或发起教师请求。
  • Python 和 CLI 工作流使用相同的设置、指纹、预算和输出。
Python 项目完整参考
字段或接口类型或结果默认值或退出码行为与验证规则
TrainingProject.from_file(path, *, api_key) TrainingProject 必填 / 无默认值 读取并验证配置文件路径和非空密钥字符串。返回项目对象;不会更新权重,也不会请求教师模型。
plan(*, dry_run=True) dict true 只能为 True。返回 resolved_configuration、compatibility、data_sharing、budgets、topics、artifacts 和 fingerprints。
run() dict 必填 / 无默认值 阻塞至终止或暂停状态;操作成功时返回通用运行结果,否则抛出对应错误。
status() dict 必填 / 无默认值 读取 run_id、status、stop_reason、report_path 和 unmet_criteria,不会启动 worker。
pause() dict 必填 / 无默认值 等待 worker 确认并生成有效检查点;返回通用运行结果。状态无效时属于配置错误。
resume() dict 必填 / 无默认值 验证所有指纹并恢复本次运行拥有的 worker;操作成功时返回通用运行结果。
cancel() dict 必填 / 无默认值 等待本次运行拥有的 worker 停止并返回 cancelled 状态;无法确认安全终止时抛出 CancellationError。
evaluate(*, split="test") dict "test" 接受 validation 或 test。返回 run_id、split、accepted、criteria、regressions 和 report_path;验收失败时先保存报告,再抛出 EvaluationFailedError。
export(*, format="safetensors") dict "safetensors" 针对已验收且兼容的制品,返回 run_id、format、artifact_path、manifest_path 和 sha256。
register_evaluator(name, scorer, *, version) None 必填 / 无默认值 在规划或评估前注册可信的评分函数,并指定稳定名称和明确版本。函数接收 prediction、target 和 row,必须返回 0 到 1 之间的有限数值。不能覆盖内置指标。
示例 · python
import os
from fusionpointai_training import TrainingProject

project = TrainingProject.from_file(
    "./german-project/training.json",
    api_key=os.environ["FUSIONPOINTAI_API_KEY"],
)
plan = project.plan(dry_run=True)
print(plan["resolved_configuration"], plan["data_sharing"], plan["budgets"])
# Confirm the reviewed plan before starting real work.
result = project.run()
if result["status"] != "completed" or result["stop_reason"] != "accepted":
    raise RuntimeError("Training was not accepted; inspect the retained report.")
evaluation = project.evaluate(split="test")
# A failed required criterion raises EvaluationFailedError after saving its report.
artifact = project.export(format="safetensors")
print(artifact["manifest_path"])

检查结构化结果

下方返回契约描述的是数据结构,而非示例测量结果。部署前请检查 status、stop_reason 和 unmet_criteria。评估结果会逐项列出标准和回归情况。导出操作会返回本地路径和完整性元数据;它不会自动上传模型或替换生产推理服务。

  • 读取状态和清单数据时,不得产生新的教师请求。
  • 最终测试集评估与改进过程中使用的验证集评估相互独立。
  • 制品清单必须与真实文件、安全的相对路径、字节大小和 SHA-256 值一致。
示例 · text
TrainingProject return contract (dictionary shapes)
from_file: validates configuration, attaches its owned run; no weight updates.
plan: {schema_version, resolved_configuration, compatibility, data_sharing,
       budgets, topics, artifacts, fingerprints}; dry_run must be true.
run/resume: {run_id, status, stop_reason, report_path, unmet_criteria}.
status/pause/cancel: {run_id, status, stop_reason, report_path, unmet_criteria}.
stop_reason is null until terminal; run/resume block until terminal or paused.
pause blocks until owned workers acknowledge an atomic checkpoint.
cancel blocks until owned workers stop; a failed stop raises CancellationError.
evaluate: {run_id, split, accepted, criteria, regressions, report_path}.
export: {run_id, format, artifact_path, manifest_path, sha256}.
Returned paths are local, resolved paths; no model upload is implied.
Status output is redacted and may be read without opening an API connection.
from_file requires path: str | os.PathLike and a nonempty api_key: str.
plan accepts dry_run=True only; False is ConfigurationError, not execution.
evaluate accepts split="validation" or "test"; defaults to test.
export accepts safetensors or adapters when supported by the selected adapter.
All method keyword options are keyword-only. Unlisted arguments are rejected.

如实处理失败

项目错误类继承 TrainingError,并对应 CLI 退出码。配置或兼容性错误会在训练开始前发生。预算或评估失败会保留报告和未满足的标准。worker 停止或检查点错误在确认已安全清理前仍属于失败。

  • 方法成功时会返回文档规定的字典。若评估标准未通过,会先保存评估报告,再抛出 EvaluationFailedError。
  • 不要记录 API key、授权标头、完整环境变量或私人训练示例。
  • 不要自动重试异常;先读取 run 和服务状态。
Python 错误与 CLI 退出码映射
字段或接口类型或结果默认值或退出码行为与验证规则
ConfigurationError TrainingError 2 规范、参数、路径或状态无效,或覆盖项不受支持。修正输入后再重试。
CompatibilityError TrainingError 3 适配器、模型、硬件、精度、分布式执行或格式不受支持。
AuthenticationError TrainingError 4 API key 缺失或过期、权益被拒绝,或不允许共享教师数据;错误消息中绝不包含秘密。
BudgetExceededError TrainingError 5 有限预算在验收前耗尽。保留有效检查点和未达成的标准。
EvaluationFailedError TrainingError 6 必需标准未通过、改进停滞或回归持续存在。保留评估报告。
CheckpointError TrainingError 7 恢复状态无效、不完整或不匹配。绝不要强行恢复。
CancellationError TrainingError 7 无法确认本次运行拥有的 worker 已安全终止;清理工作仍须继续。
ExportError TrainingError 7 制品不受支持或无效、路径不安全或校验和失败;不要交付。
TrainingError Exception 7 训练基础错误。所列目标错误均继承此类;保留已脱敏的诊断信息。
示例 · python
import os
from fusionpointai_training import TrainingProject
from fusionpointai_training.errors import (
    AuthenticationError, BudgetExceededError, CompatibilityError,
    ConfigurationError, EvaluationFailedError, TrainingError,
)

try:
    project = TrainingProject.from_file(
        "./german-project/training.json",
        api_key=os.environ.get("FUSIONPOINTAI_API_KEY", ""),
    )
    project.plan(dry_run=True)
    project.run()
    result = project.evaluate(split="test")
except (ConfigurationError, CompatibilityError):
    print("Correct the configuration before starting a new run.")
except AuthenticationError:
    print("Check access without logging the key.")
except BudgetExceededError:
    print("Preserve the checkpoint. A larger approved budget requires a new plan.")
except EvaluationFailedError:
    print("Preserve failed criteria; do not publish this model as accepted.")
except TrainingError:
    print("Inspect redacted diagnostics; do not blindly repeat a write.")
# CancellationError, CheckpointError and ExportError also inherit TrainingError.
示例 · python
from fusionpointai_training import register_evaluator

def category_match(prediction, target, row):
    return float(prediction.strip().casefold() == target.strip().casefold())

register_evaluator("category_match", category_match, version="1")
# Register before project.plan() in the same Python process.
# In rubric.json: "metric": "category_match", "minimum_score": 0.85
# This scorer measures category equality, not open-ended semantic correctness.