From 3f1716d9d9ba479e2724b2880ed5f3bcd2434dd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=95=85=E7=92=83?= Date: Tue, 1 Dec 2026 14:33:33 +0800 Subject: [PATCH 1/2] feat(finetune): report parameter sources and cost flags; align dataset caps with docs finetune - `finetune create` preview reports `parameter_sources` for every hyper-parameter (user / schema_default / schema_recommend / train_option_default / profile_default); schema defaults and recommended values are now resolved separately - Text create validates `batch_size` as a positive power of two when the parameter schema declares intInputNumber (new `not_power_of_two` issue) - RL run rejects `max_prompt_length >= max_length` after merging YAML and --hp - `finetune price` adds `--batch-size` / `--max-length` and echoes the hyper-parameters used for the estimate - Console workspace mismatch hint lists the requested ID, match count and up to 10 accessible workspace IDs dataset - Raise the fine-tune upload cap from 200 MB to 300 MB and lower the image/video ZIP cap from 2 GB to 1 GB per the official upload rules; collapse CPT/decision constants into MAX_DATASET_BYTES / MAX_MEDIA_ZIP_BYTES - Add resolveDatasetMaxBytes(schema) and resolveDatasetMaxBytesForFile(): ZIPs without --schema are sniffed via detectModality so image/video get 1 GB automatically, falling back to 300 MB when undetectable - Oversize error reports exact bytes and cap with a bilingual hint; unsupported format error names the file - `dataset upload`: surface failed_uploads count/file/code in the hint and the response key layout when no file ID is returned; carry `apiCode` in AEM telemetry Regenerate dataset/finetune reference and update e2e/output fixtures and the telemetry agent doc. --- docs/agents/telemetry-change.md | 24 +-- .../commands/src/commands/dataset/upload.ts | 25 +-- .../commands/src/commands/dataset/validate.ts | 11 +- .../commands/src/commands/finetune/create.ts | 54 +++++-- .../commands/src/commands/finetune/price.ts | 60 +++++-- .../commands/src/commands/finetune/rl-run.ts | 6 + .../commands/src/commands/shared/workspace.ts | 30 +++- .../commands/tests/e2e/dataset.e2e.test.ts | 23 ++- .../tests/e2e/finetune-rl.e2e.test.ts | 21 +++ .../commands/tests/e2e/finetune.e2e.test.ts | 148 ++++++++++++++++++ packages/commands/tests/e2e/topic-routes.ts | 1 + .../tests/output/console-read-output.test.ts | 15 +- .../output/fixtures/training-deployment.json | 58 ++++++- packages/core/src/dataset/api.ts | 15 +- packages/core/src/dataset/index.ts | 5 +- packages/core/src/dataset/inspect.ts | 31 ++++ packages/core/src/dataset/types.ts | 2 + packages/core/src/dataset/validate/common.ts | 43 ++--- packages/core/src/dataset/validate/index.ts | 3 +- .../core/src/dataset/validate/registry.ts | 6 +- packages/core/src/finetune/preflight.ts | 48 +++++- packages/core/src/finetune/price.ts | 26 +-- packages/core/src/finetune/profiles/cpt.ts | 5 +- .../core/src/finetune/profiles/sft-lora.ts | 1 + packages/core/src/finetune/rl/config.ts | 20 +++ packages/core/src/finetune/types.ts | 5 +- packages/core/src/telemetry/event.ts | 11 +- packages/core/src/telemetry/tracker.ts | 6 +- packages/core/tests/batch-api.test.ts | 7 +- packages/core/tests/dataset-validate.test.ts | 118 +++++++++++++- .../core/tests/finetune-preflight.test.ts | 51 +++++- packages/core/tests/finetune-price.test.ts | 41 +++++ packages/core/tests/rl-config.test.ts | 30 ++++ packages/core/tests/telemetry-tracker.test.ts | 27 ++++ skills/bailian-finetune/reference/dataset.md | 5 +- skills/bailian-finetune/reference/finetune.md | 43 ++--- 36 files changed, 873 insertions(+), 152 deletions(-) create mode 100644 packages/core/tests/finetune-price.test.ts diff --git a/docs/agents/telemetry-change.md b/docs/agents/telemetry-change.md index 8a79e0762..35bdded35 100644 --- a/docs/agents/telemetry-change.md +++ b/docs/agents/telemetry-change.md @@ -100,7 +100,7 @@ source-config 只用于百炼 / DashScope API 侧消费,不发送到通用网 - `callerType`(必填:`agent` | `script` | `unknown`) - `callerName`:`agent` 与 `script` 时发送(缺省/非法 → `"unknown"`);`skillName` / `skillVersion` 仅 `agent` 时可选发送 - `bizFrom`:全局 `--biz-from` 声明的业务来源(可选);经 `normalizeBizFrom` 归一化(缺省省略,空白/非法 → `"unknown"`),与 `callerName` 独立;映射到 AEM `c6` 专用扁平列 -- 失败时的 `errorMessage`、`exitCode`、`httpStatus`、`requestId` +- 失败时的 `errorMessage`、`exitCode`、`httpStatus`、`requestId`,以及服务端业务错码 `apiCode`(来自 `BailianError.api.apiCode`,例如上传 HTTP 200 但 `failed_uploads[].code` 非空;随 `ext` 上报,不进 `c1`—`c6`) - 安全 allowlist 过滤后的 `params` - 仅 `npmPackage=bailian-cli`:已有合法 `~/.bailian/install.json` 时,命令事件带 `installChannel`,不带安装日,也不发 `first_install`。新用户的 `first_installed_at` 在安装成功写盘后单独发一条事件名 `first_install` 的事件,`ext` 里是 `firstInstalledAt`、`installChannel`、`timestamp`(上报时刻)和 `cliVersion`。每个安装日只入队一次,次数记在 `~/.bailian/first-install-reported.json`;远端入队失败不计入,也不改由后续命令补发。`DO_NOT_TRACK=1` 和配置 `telemetry: false` 都不写文件、不发事件,与普通命令同一个开关。没有安装日的老用户不发 `first_install`。命令不创建、不修补 `install.json`。`kscli` 不读这份文件。bootstrap 事件也不读取它 @@ -209,17 +209,17 @@ mmstat 网关对任何 POST 都返回 `200` + GIF,端点或 pid 写错不会 AEM 映射: -| AEM 字段 | 内容 | -| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| event name | 命令路径 | -| `et` | `EXP` | -| `ext` | 除 `command`、`params` 外的结构化事件字段,含 `commandPrefix`、`callerType`、`site`、可选 `siteReason`、可选 `dryRun`(仅 `--dry-run` 时为 `true`)、失败时的 `exitCode`,以及读到的 `installChannel`。安装日不在命令事件里 | -| `c1` | allowlist 参数 | -| `c2` | `success` / `failure` | -| `c3` | HTTP status | -| `c4` | 错误文案,最多 500 字符 | -| `c5` | request ID | -| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | +| AEM 字段 | 内容 | +| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| event name | 命令路径 | +| `et` | `EXP` | +| `ext` | 除 `command`、`params` 外的结构化事件字段,含 `commandPrefix`、`callerType`、`site`、可选 `siteReason`、可选 `dryRun`(仅 `--dry-run` 时为 `true`)、失败时的 `exitCode` 与可选 `apiCode`,以及读到的 `installChannel`。安装日不在命令事件里 | +| `c1` | allowlist 参数 | +| `c2` | `success` / `failure` | +| `c3` | HTTP status | +| `c4` | 错误文案,最多 500 字符 | +| `c5` | request ID | +| `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | `siteReason` 为粗粒度枚举(`product-domestic` / `product-international` / `positive-domestic` / `positive-international` / `default-fallback` / `unknown-host`),**禁止**带原始 host。`product-*` 表示归属来自产品声明,`positive-*` 表示来自用户配置信号,两者不能混算。漏判量化用国内站 `siteReason` 兜底类占比;不要用「国内 pid 出现 `site=international`」做告警(国际事件不会进国内 pid)。 diff --git a/packages/commands/src/commands/dataset/upload.ts b/packages/commands/src/commands/dataset/upload.ts index 3ba1f3a89..a3972f1a5 100644 --- a/packages/commands/src/commands/dataset/upload.ts +++ b/packages/commands/src/commands/dataset/upload.ts @@ -5,10 +5,7 @@ import { validateDataset, parseDatasetSchemaFlag, formatIssue, - MAX_DATASET_BYTES, - MAX_CPT_BYTES, - MAX_DECISION_DATASET_BYTES, - MAX_MEDIA_ZIP_BYTES, + resolveDatasetMaxBytesForFile, BailianError, ExitCode, type FlagsDef, @@ -20,9 +17,9 @@ const UPLOAD_FLAGS = { valueHint: "", description: { "en-US": - "Local dataset file (.jsonl or .zip; ≤200MB SFT/DPO, ≤300MB CPT/decision, ≤2GB media zip)", + "Local dataset file (.jsonl or .zip; ≤300MB text/CPT/decision/TTS, ≤1GB image/video zip)", "zh-CN": - "本地数据集文件(.jsonl 或 .zip;SFT/DPO 不超过 200MB,CPT/决策模型不超过 300MB,媒体 ZIP 不超过 2GB)", + "本地数据集文件(.jsonl 或 .zip;文本/CPT/决策/TTS 不超过 300MB,图像/视频 ZIP 不超过 1GB)", }, required: true, }, @@ -94,9 +91,9 @@ export default defineCommand({ }, { "en-US": - "Upload cap: 200MB SFT/DPO text, 300MB CPT/decision data, 2GB media zip. For decision files over 200MB, pass --schema decision so the correct cap is applied. Upload uses the OpenAI-compatible /compatible-mode/v1/files endpoint so the purpose tag is persisted.", + "Upload cap: 300MB for text, CPT, decision and TTS data; 1GB for image/video ZIPs. Without --schema, ZIP archives are sniffed from their first data.jsonl record so image/video ZIPs get 1GB automatically; pass --schema only to override. Upload uses the OpenAI-compatible /compatible-mode/v1/files endpoint so the purpose tag is persisted.", "zh-CN": - "上传上限:SFT/DPO 文本 200MB、CPT/决策模型数据 300MB、媒体 ZIP 2GB。决策数据超过 200MB 时请显式传入 --schema decision,以应用正确上限。上传使用 OpenAI 兼容的 /compatible-mode/v1/files 接口,以确保持久化 purpose 标签。", + "上传上限:文本、CPT、决策与 TTS 数据 300MB;图像/视频 ZIP 1GB。未指定 --schema 时会读取 ZIP 内 data.jsonl 的首条记录自动识别,图像/视频 ZIP 自动适用 1GB;仅在需要覆盖时传 --schema。上传使用 OpenAI 兼容的 /compatible-mode/v1/files 接口,以确保持久化 purpose 标签。", }, ], async run(ctx) { @@ -104,15 +101,9 @@ export default defineCommand({ const filePath = flags.file; const purpose = flags.purpose || "fine-tune"; const schema = parseDatasetSchemaFlag(flags.schema); - // 大小上限按平台数据类型区分;自动识别仍采用保守的文本上限,避免放宽已有格式。 - const isMediaSchema = schema === "image" || schema === "video"; - const maxBytes = isMediaSchema - ? MAX_MEDIA_ZIP_BYTES - : schema === "decision" - ? MAX_DECISION_DATASET_BYTES - : schema === "cpt" - ? MAX_CPT_BYTES - : MAX_DATASET_BYTES; + // 大小上限按 --schema 区分:图像/视频 ZIP 1GB,其余文本类 300MB;未传 --schema 时先嗅探 ZIP 内容。 + // 与 dataset validate 共用同一解析。 + const maxBytes = await resolveDatasetMaxBytesForFile(schema, filePath); if (!flags.noValidate) { const result = await validateDataset(filePath, { diff --git a/packages/commands/src/commands/dataset/validate.ts b/packages/commands/src/commands/dataset/validate.ts index 6de1fe5ee..6db87789d 100644 --- a/packages/commands/src/commands/dataset/validate.ts +++ b/packages/commands/src/commands/dataset/validate.ts @@ -2,7 +2,7 @@ import { defineCommand, validateDataset, parseDatasetSchemaFlag, - MAX_DECISION_DATASET_BYTES, + resolveDatasetMaxBytesForFile, BailianError, ExitCode, type FlagsDef, @@ -82,6 +82,12 @@ export default defineCommand({ "zh-CN": "ZIP 归档(.zip)除逐条检查记录内容外,还会执行结构验证(存在 data.jsonl、媒体引用可解析)。使用 --full-validate 对每一行执行 JSON.parse。", }, + { + "en-US": + "Size cap follows --schema, same as dataset upload: 300MB for text, CPT, decision and TTS data; 1GB for image/video ZIPs. Without --schema, ZIP archives are sniffed from their first data.jsonl record so image/video ZIPs get 1GB automatically.", + "zh-CN": + "大小上限与 dataset upload 一致,随 --schema 而定:文本、CPT、决策与 TTS 数据 300MB;图像/视频 ZIP 1GB。未指定 --schema 时会读取 ZIP 内 data.jsonl 的首条记录自动识别,图像/视频 ZIP 自动适用 1GB。", + }, ], async run(ctx) { const { settings, flags } = ctx; @@ -104,7 +110,8 @@ export default defineCommand({ const result = await validateDataset(filePath, { fullValidate: flags.fullValidate, schema, - maxBytes: schema === "decision" ? MAX_DECISION_DATASET_BYTES : undefined, + // 与 dataset upload 共用上限解析,避免两命令对同一文件结论不一致。 + maxBytes: await resolveDatasetMaxBytesForFile(schema, filePath), }); ctx.output.result( diff --git a/packages/commands/src/commands/finetune/create.ts b/packages/commands/src/commands/finetune/create.ts index e3746e9c9..cab52421a 100644 --- a/packages/commands/src/commands/finetune/create.ts +++ b/packages/commands/src/commands/finetune/create.ts @@ -9,6 +9,7 @@ import { preflightBatchSizeGate, validateFineTuneHyperParameterOverrides, getFineTuneHyperParameterDefaultNumber, + resolveFineTuneHyperParameterDefaultNumber, DEFAULT_TRAINING_TYPE, preflightDecisionSampleGate, readDecisionQuestionSignature, @@ -27,6 +28,7 @@ import { type FineTuneHyperParameterIssue, type DataModality, type FineTuneParamHyperParam, + type FineTuneSchemaValueSource, type FlagsDef, type LocalizedText, type ParsedFlags, @@ -237,12 +239,17 @@ const COST_REQUIRED_HYPER_PARAMETERS = ["n_epochs", "batch_size", "max_length"] function applySchemaDefaultHyperParameters( hp: FineTuneHyperParameters, parameterSchema: FineTuneParamHyperParam[], -): void { +): Record { + const sources: Record = {}; for (const parameterName of COST_REQUIRED_HYPER_PARAMETERS) { if (hp[parameterName] !== undefined) continue; - const defaultValue = getFineTuneHyperParameterDefaultNumber(parameterSchema, parameterName); - if (defaultValue !== undefined) hp[parameterName] = defaultValue; + const resolved = resolveFineTuneHyperParameterDefaultNumber(parameterSchema, parameterName); + if (resolved !== undefined) { + hp[parameterName] = resolved.value; + sources[parameterName] = resolved.source; + } } + return sources; } export function formatHyperParameterIssue( @@ -281,6 +288,11 @@ export function formatHyperParameterIssue( "en-US": `${issue.parameter}=${value} must follow ${issue.expected}.`, "zh-CN": `${issue.parameter}=${value} 必须满足 ${issue.expected}。`, }); + case "not_power_of_two": + return context.localize({ + "en-US": `${issue.parameter}=${value} must be a positive power of two (for example 16 or 32).`, + "zh-CN": `${issue.parameter}=${value} 必须是正的 2 的幂(例如 16 或 32)。`, + }); } } @@ -697,9 +709,9 @@ const TEXT_NOTES = [ }, { "en-US": - "Before upload, the command queries the selected model and training type's parameter schema. Explicit overrides must satisfy its editability, type, enum, range, and step constraints. The create API requires n_epochs, batch_size and max_length: an omitted one is filled from the schema's default (query it with the finetune params command); every other omitted value uses the platform default.", + "Before upload, the command queries the selected model and training type's parameter schema. Explicit overrides must satisfy its editability, type, enum, range, and step constraints. When the schema declares batch_size as intInputNumber, text creation also requires a positive power of two. The create API requires n_epochs, batch_size and max_length: an omitted one is filled from the schema's default or explicitly marked recommendation; every other omitted value uses the platform default. Dry-run includes parameter_sources so user, schema default, schema recommendation and profile-default values remain distinguishable.", "zh-CN": - "上传前会查询所选模型和训练类型的参数配置。显式覆盖值必须满足可编辑性、类型、枚举、范围和步长约束。创建任务 API 要求 n_epochs、batch_size、max_length 必填:未指定时按参数配置中的默认值补齐(可用 finetune params 命令查询);其余未指定项使用平台默认值。", + "上传前会查询所选模型和训练类型的参数配置。显式覆盖值必须满足可编辑性、类型、枚举、范围和步长约束;当配置将 batch_size 声明为 intInputNumber 时,文本创建还要求它是正的 2 的幂。创建任务 API 要求 n_epochs、batch_size、max_length 必填:未指定时按参数配置中的默认值或明确标记的推荐值补齐;其余未指定项使用平台默认值。dry-run 包含 parameter_sources,用于区分用户覆盖、配置默认值、配置推荐值和 Profile 默认值。", }, { "en-US": "Learning rate is forwarded as a string to avoid JSON-number precision loss.", @@ -870,6 +882,8 @@ async function runCreate( modality, flags as Record, ) as FineTuneHyperParameters; + let schemaParameterSources: Record = {}; + const trainOptionDefaultNames = new Set(); if (commandModality === "text") { const extraParameters: Record = { @@ -959,6 +973,7 @@ async function runCreate( ); for (const [optionName, optionValue] of Object.entries(resolved.context)) { hp[optionName] = optionValue; + if (userTrainOptions[optionName] === undefined) trainOptionDefaultNames.add(optionName); } } @@ -996,6 +1011,7 @@ async function runCreate( const overrideIssues = validateFineTuneHyperParameterOverrides( parameterSchema, explicitHyperParameterOverrides(commandModality, flags), + { integerBatchSizePowerOfTwo: commandModality === "text" }, ); if (overrideIssues.length > 0) { throw new BailianError( @@ -1011,7 +1027,7 @@ async function runCreate( // Runs after override validation so an invalid explicit value still fails // first, and before the dry-run snapshot so the preview shows what is sent. if (commandModality === "text") { - applySchemaDefaultHyperParameters(hp, parameterSchema); + schemaParameterSources = applySchemaDefaultHyperParameters(hp, parameterSchema); } if ( @@ -1145,14 +1161,32 @@ async function runCreate( if (suffix) body.finetuned_output_suffix = suffix; if (settings.dryRun) { + const explicitNames = new Set( + Object.keys(explicitHyperParameterOverrides(commandModality, flags)), + ); + if (commandModality === "text") { + if (flags.dataAugmentation !== undefined || flags.augmentationTypes !== undefined) + explicitNames.add("data_augmentation"); + if (flags.augmentationTypes !== undefined) explicitNames.add("augmentation_types"); + if (flags.augmentationRatio !== undefined) explicitNames.add("augmentation_ratio"); + } + const parameterSources = Object.fromEntries( + Object.keys(hp).map((parameterName) => [ + parameterName, + explicitNames.has(parameterName) + ? "user" + : (schemaParameterSources[parameterName] ?? + (trainOptionDefaultNames.has(parameterName) + ? "train_option_default" + : "profile_default")), + ]), + ); const pending = [ ...training.localPaths.map((path) => ({ field: "datasets", path })), ...(validation?.localPaths ?? []).map((path) => ({ field: "validations", path })), ]; - const resultData1 = - pending.length > 0 - ? { action: "finetune.create", body, pending_uploads: pending } - : { action: "finetune.create", body }; + const preview = { action: "finetune.create", body, parameter_sources: parameterSources }; + const resultData1 = pending.length > 0 ? { ...preview, pending_uploads: pending } : preview; ctx.output.result( resultData1, ctx.settings.output === "text" ? { text: JSON.stringify(resultData1, null, 2) } : undefined, diff --git a/packages/commands/src/commands/finetune/price.ts b/packages/commands/src/commands/finetune/price.ts index 8e0d4ec53..dd4f009f3 100644 --- a/packages/commands/src/commands/finetune/price.ts +++ b/packages/commands/src/commands/finetune/price.ts @@ -43,15 +43,31 @@ const PRICE_FLAGS = { "zh-CN": "训练轮数(默认:3)", }, }, + batchSize: { + type: "number", + valueHint: "", + description: { + "en-US": "Batch size used for estimation (default: 16); match the planned create request", + "zh-CN": "估价使用的批大小(默认:16);应与计划创建任务的参数一致", + }, + }, + maxLength: { + type: "number", + valueHint: "", + description: { + "en-US": + "Maximum sequence length used for estimation (default: 8192); match the planned create request", + "zh-CN": "估价使用的最大序列长度(默认:8192);应与计划创建任务的参数一致", + }, + }, } satisfies FlagsDef; const SUPPORTED_TRAINING_TYPES = ["sft", "dpo", "cpt"]; -// Fixed hyper-parameters used for estimation. Only n_epochs materially affects -// the estimate; the rest are held at representative defaults (not exposed as -// flags to keep the command surface minimal). -const ESTIMATE_BATCH_SIZE = 16; -const ESTIMATE_MAX_LENGTH = 8192; +// Defaults are used only when the corresponding flag is omitted. Callers can +// align all three cost-driving values with `finetune create`. +const DEFAULT_BATCH_SIZE = 16; +const DEFAULT_MAX_LENGTH = 8192; const DEFAULT_N_EPOCHS = 3; export default defineCommand({ @@ -61,12 +77,13 @@ export default defineCommand({ "zh-CN": "估算微调任务的训练费用(按 Token 计费)", }, auth: "console", - usageArgs: "--base-model --datasets [--training-type ] [--n-epochs ]", + usageArgs: + "--base-model --datasets [--training-type ] [--n-epochs ] [--batch-size ] [--max-length ]", flags: PRICE_FLAGS, exampleArgs: [ "--base-model qwen3-8b --datasets file-ft-xxx", - "--base-model qwen3-8b --datasets file-ft-xxx,file-ft-yyy --n-epochs 2", - "--base-model qwen3-8b --datasets file-ft-xxx --training-type cpt", + "--base-model qwen3-8b --datasets file-ft-xxx,file-ft-yyy --n-epochs 2 --batch-size 32 --max-length 4096", + "--base-model qwen3-8b --datasets file-ft-xxx --training-type cpt --batch-size 16 --max-length 16384", ], notes: [ { @@ -81,8 +98,9 @@ export default defineCommand({ }, { "en-US": - "Hyper-parameters other than --n-epochs are fixed at representative defaults for estimation.", - "zh-CN": "除 --n-epochs 外,其他超参数会使用具有代表性的固定默认值进行估算。", + "Pass the same --n-epochs, --batch-size and --max-length as the planned create request. Other hyper-parameters use fixed estimation defaults; mixed-data coverage is determined by the server response.", + "zh-CN": + "请传入与计划创建任务相同的 --n-epochs、--batch-size 和 --max-length。其他超参使用固定估价默认值;混训用量是否已覆盖以服务端回执为准。", }, ], async run(ctx) { @@ -93,7 +111,12 @@ export default defineCommand({ .map((datasetId) => datasetId.trim()) .filter(Boolean); const trainingType = (flags.trainingType ?? "sft").toLowerCase(); - const nEpochs = flags.nEpochs ?? DEFAULT_N_EPOCHS; + const hyperParams = { + nEpochs: flags.nEpochs ?? DEFAULT_N_EPOCHS, + batchSize: flags.batchSize ?? DEFAULT_BATCH_SIZE, + maxLength: flags.maxLength ?? DEFAULT_MAX_LENGTH, + }; + const nEpochs = hyperParams.nEpochs; if (!SUPPORTED_TRAINING_TYPES.includes(trainingType)) { throw new BailianError( @@ -112,6 +135,8 @@ export default defineCommand({ datasets: datasetIds, trainingType, nEpochs, + batchSize: hyperParams.batchSize, + maxLength: hyperParams.maxLength, }; ctx.output.result( resultData1, @@ -135,12 +160,8 @@ export default defineCommand({ // Per-epoch token estimate (min/max range). const estimate = trainingType === "cpt" - ? await estimateCptTokens(ctx.client, model, datasetIds.join(","), nEpochs) - : await estimateSftDpoTokens(ctx.client, datasetIds, { - nEpochs, - batchSize: ESTIMATE_BATCH_SIZE, - maxLength: ESTIMATE_MAX_LENGTH, - }); + ? await estimateCptTokens(ctx.client, model, datasetIds.join(","), hyperParams) + : await estimateSftDpoTokens(ctx.client, datasetIds, hyperParams); const minPerEpoch = estimate.estimatedDatasetConsumedTokensMinPerEpoch ?? 0; const maxPerEpoch = estimate.estimatedDatasetConsumedTokensMaxPerEpoch ?? 0; @@ -157,6 +178,11 @@ export default defineCommand({ model, training_type: trainingType, n_epochs: nEpochs, + hyper_parameters: { + n_epochs: hyperParams.nEpochs, + batch_size: hyperParams.batchSize, + max_length: hyperParams.maxLength, + }, unit_price: unitPrice, price_unit: priceInfo.priceUnit ?? "千Token", estimated_tokens: { min: minTokens, max: maxTokens }, diff --git a/packages/commands/src/commands/finetune/rl-run.ts b/packages/commands/src/commands/finetune/rl-run.ts index c7cb2241e..d0a5f334a 100644 --- a/packages/commands/src/commands/finetune/rl-run.ts +++ b/packages/commands/src/commands/finetune/rl-run.ts @@ -31,6 +31,12 @@ export default defineCommand({ "zh-CN": "在隔离沙箱内执行。请先用 `finetune runtime prepare` 准备运行时,或传入 --install-runtime。", }, + { + "en-US": + "max_prompt_length must be smaller than max_length so generated responses have room. This is checked after merging YAML and --hp, including during --dry-run.", + "zh-CN": + "max_prompt_length 必须小于 max_length,为生成回答预留长度。该规则在合并 YAML 与 --hp 后检查,--dry-run 同样生效。", + }, { "en-US": "Timing out with --watch stops waiting only; it does not cancel the cloud job.", "zh-CN": "--watch 超时仅停止等待,不会取消云端任务。", diff --git a/packages/commands/src/commands/shared/workspace.ts b/packages/commands/src/commands/shared/workspace.ts index 3c0a026d4..48bafdb35 100644 --- a/packages/commands/src/commands/shared/workspace.ts +++ b/packages/commands/src/commands/shared/workspace.ts @@ -10,6 +10,7 @@ import { type Client, type CommandContext, type FlagsDef, + type LocalizedText, type Settings, } from "bailian-cli-core"; @@ -126,6 +127,29 @@ export async function listConsoleWorkspaces(client: Client): Promise workspace.workspaceId); + const overflow = detail.workspaces.length - listed.length; + const visible = + listed.length === 0 + ? "(none)" + : `${listed.join(", ")}${overflow > 0 ? `, ... (+${overflow} more)` : ""}`; + return { + "en-US": `Requested workspace: ${detail.workspaceId}; matched ${detail.matches} of ${detail.workspaces.length} accessible workspace(s): ${visible}. Check --workspace-id and access permissions (console account, --console-region/--console-site). No business request was sent.`, + "zh-CN": `请求的工作空间:${detail.workspaceId};命中 ${detail.matches} 个,可访问 ${detail.workspaces.length} 个:${visible}。请核对 --workspace-id 以及访问权限(Console 登录账号、--console-region/--console-site)。未发送业务请求。`, + }; +} + /** workspaceId 是资源标识,tenantId 是同一空间的 Console switchAgent;只覆盖本次请求。 */ export async function resolveConsoleWorkspaceAgent( ctx: Pick, @@ -142,11 +166,7 @@ export async function resolveConsoleWorkspaceAgent( "zh-CN": "无法从可访问的工作空间列表中唯一解析请求的工作空间。", }), ExitCode.GENERAL, - ctx.localize({ - "en-US": - "Check --workspace-id and access permissions in the selected console region/site. No business request was sent.", - "zh-CN": "请核对 --workspace-id 及所选控制台地域/站点的访问权限。未发送业务请求。", - }), + ctx.localize(workspaceMismatchHint({ workspaceId, matches: matches.length, workspaces })), ); } const tenantId = matches[0].tenantId; diff --git a/packages/commands/tests/e2e/dataset.e2e.test.ts b/packages/commands/tests/e2e/dataset.e2e.test.ts index 2c733106c..30c8d46eb 100644 --- a/packages/commands/tests/e2e/dataset.e2e.test.ts +++ b/packages/commands/tests/e2e/dataset.e2e.test.ts @@ -217,8 +217,8 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: dataset (offline)", () => { expect(data.schema).toBe("dpo"); }); - test("dataset upload --schema image --no-validate --dry-run 采用 2GB 媒体上限", async () => { - // image schema raises the upload cap to 2 GiB (vs 300 MB for text). + test("dataset upload --schema image --no-validate --dry-run 采用 1GB 媒体上限", async () => { + // image schema raises the upload cap to 1 GiB (vs 300 MB for text). // --no-validate keeps this offline (the jsonl fixture is not a real zip). const file = join(e2eFixturesDir, ".dataset-valid.jsonl"); const { stdout, stderr, exitCode } = await runCommandE2e(DATASET_ROUTES, [ @@ -237,10 +237,13 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: dataset (offline)", () => { const data = parseStdoutJson<{ action: string; schema: string; max_bytes: number }>(stdout); expect(data.action).toBe("dataset.upload"); expect(data.schema).toBe("image"); - expect(data.max_bytes).toBe(2 * 1024 * 1024 * 1024); + expect(data.max_bytes).toBe(1024 * 1024 * 1024); }); - test.each(["tts", "image"])("dataset upload --dry-run 接受媒体 schema %s", async (schema) => { + test.each([ + ["tts", 300 * 1024 * 1024], + ["image", 1024 * 1024 * 1024], + ])("dataset upload --dry-run 接受媒体 schema %s 并采用对应上限", async (schema, maxBytes) => { const file = join(e2eFixturesDir, ".dataset-valid.jsonl"); const { stdout, stderr, exitCode } = await runCommandE2e(DATASET_ROUTES, [ "dataset", @@ -255,9 +258,15 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: dataset (offline)", () => { "json", ]); expect(exitCode, stderr).toBe(0); - const data = parseStdoutJson<{ action: string; schema: string }>(stdout); + const data = parseStdoutJson<{ + action: string; + schema: string; + max_bytes: number; + }>(stdout); expect(data.action).toBe("dataset.upload"); expect(data.schema).toBe(schema); + // tts shares the 300 MB fine-tune cap; only image/video ZIPs get 1 GiB. + expect(data.max_bytes).toBe(maxBytes); }); test("dataset validate --schema video 接受视频 schema(按记录结构校验)", async () => { @@ -279,7 +288,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: dataset (offline)", () => { expect(`${stdout}\n${stderr}`).toMatch(/first_frame_path/); }); - test("dataset upload --schema video --no-validate --dry-run 采用 2GB 媒体上限", async () => { + test("dataset upload --schema video --no-validate --dry-run 采用 1GB 媒体上限", async () => { const file = join(e2eFixturesDir, ".dataset-valid.jsonl"); const { stdout, stderr, exitCode } = await runCommandE2e(DATASET_ROUTES, [ "dataset", @@ -297,7 +306,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: dataset (offline)", () => { const data = parseStdoutJson<{ action: string; schema: string; max_bytes: number }>(stdout); expect(data.action).toBe("dataset.upload"); expect(data.schema).toBe("video"); - expect(data.max_bytes).toBe(2 * 1024 * 1024 * 1024); + expect(data.max_bytes).toBe(1024 * 1024 * 1024); }); test("dataset delete --dry-run 发出结构化动作", async () => { diff --git a/packages/commands/tests/e2e/finetune-rl.e2e.test.ts b/packages/commands/tests/e2e/finetune-rl.e2e.test.ts index c7c19b47c..533a20e4e 100644 --- a/packages/commands/tests/e2e/finetune-rl.e2e.test.ts +++ b/packages/commands/tests/e2e/finetune-rl.e2e.test.ts @@ -220,6 +220,27 @@ describe("e2e: finetune rl/opd offline contracts", () => { expect(data.watch).toBe(false); }); + test("rl run dry-run rejects prompts that leave no generation length (2)", async () => { + const { stderr, exitCode } = await runCommandInProcess(FINETUNE_ROUTES, [ + "finetune", + "rl", + "run", + "--model", + "qwen3.5-9b", + "--hp", + "max_prompt_length=4096", + "--hp", + "max_length=4096", + "--dry-run", + ...DUMMY_KEY, + "--output", + "json", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/max_prompt_length/); + expect(stderr).toMatch(/max_length/); + }); + test("opd run without --yes requires confirmation (7)", async () => { const { stderr, exitCode } = await runCommandInProcess(FINETUNE_ROUTES, [ "finetune", diff --git a/packages/commands/tests/e2e/finetune.e2e.test.ts b/packages/commands/tests/e2e/finetune.e2e.test.ts index fc05ab2d6..c9f919ba5 100644 --- a/packages/commands/tests/e2e/finetune.e2e.test.ts +++ b/packages/commands/tests/e2e/finetune.e2e.test.ts @@ -20,11 +20,43 @@ let lastSchemaQuery: URLSearchParams | null = null; /** Vision-only dynamic-option base mirroring qwen3.6-plus-base-2026-04-02. */ const DYNAMIC_OPTION_MODEL = "qwen3.6-plus-base-2026-04-02"; +const INTEGER_BATCH_MODEL = "integer-batch-model"; function parameterSchema( inputModel: string, hyperParametersRaw: string | null, ): Array> { + if (inputModel === INTEGER_BATCH_MODEL) { + return [ + { + name: "batch_size", + type: "intInputNumber", + data_range: ["8", "64"], + step: 8, + editable: true, + defaultValue: "16", + }, + { name: "n_epochs", type: "number", editable: true, defaultValue: "3" }, + { + name: "max_length", + type: "intInputNumber", + editable: true, + defaultValue: "4096", + }, + ]; + } + if (inputModel === "recommend-only-model") { + return [ + { name: "batch_size", type: "number", editable: true, recommend_value: "16" }, + { name: "n_epochs", type: "number", editable: true, recommend_value: "4" }, + { + name: "max_length", + type: "intInputNumber", + editable: true, + recommend_value: "4096", + }, + ]; + } if (inputModel === DYNAMIC_OPTION_MODEL) { // Mirror the platform: dynamic-option models return an empty schema unless // hyper_parameters carries a legal option context (modality fixed vision). @@ -280,6 +312,7 @@ describe("e2e: finetune (schema-gated)", () => { training_type: string; hyper_parameters: Record; }; + parameter_sources: Record; }>(stdout); expect(data.action).toBe("finetune.create"); expect(data.body.model).toBe("qwen3-8b"); @@ -293,6 +326,121 @@ describe("e2e: finetune (schema-gated)", () => { batch_size: 8, max_length: 32768, }); + expect(data.parameter_sources).toEqual({ + n_epochs: "schema_default", + batch_size: "schema_default", + max_length: "schema_default", + }); + }); + + test("finetune create dry-run 将推荐值明确标为 schema_recommend", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + "recommend-only-model", + "--datasets", + "file-aaa", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + body: { hyper_parameters: Record }; + parameter_sources: Record; + }>(stdout); + expect(data.body.hyper_parameters).toEqual({ + n_epochs: 4, + batch_size: 16, + max_length: 4096, + }); + expect(data.parameter_sources).toEqual({ + n_epochs: "schema_recommend", + batch_size: "schema_recommend", + max_length: "schema_recommend", + }); + }); + + test("finetune create 对整数批大小 Schema 拒绝非 2 的幂", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + INTEGER_BATCH_MODEL, + "--datasets", + "file-aaa", + "--batch-size", + "24", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/power of two|2 的幂/); + }); + + test("finetune create 接受整数批大小 Schema 中的 2 的幂", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + INTEGER_BATCH_MODEL, + "--datasets", + "file-aaa", + "--batch-size", + "32", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(parseStdoutJson(stdout)).toMatchObject({ + body: { hyper_parameters: { batch_size: 32 } }, + parameter_sources: { batch_size: "user" }, + }); + }); + + test("finetune price --help 展示与创建对齐的估价超参", async () => { + const { stderr, exitCode } = await runCommandHelp(FINETUNE_ROUTES, [ + "finetune", + "price", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--n-epochs/); + expect(stderr).toMatch(/--batch-size/); + expect(stderr).toMatch(/--max-length/); + }); + + test("finetune price --dry-run 预览完整估价超参", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "price", + "--base-model", + "qwen3-8b", + "--datasets", + "file-aaa", + "--n-epochs", + "2", + "--batch-size", + "32", + "--max-length", + "4096", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(parseStdoutJson(stdout)).toMatchObject({ + action: "finetune.price", + nEpochs: 2, + batchSize: 32, + maxLength: 4096, + }); }); test("finetune create --dry-run 转发训练类型与超参", async () => { diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index bc7a59236..f8ac7f293 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -410,6 +410,7 @@ export const FINETUNE_ROUTES: E2eRouteExports = { "finetune watch": "finetuneWatch", "finetune capability": "finetuneCapability", "finetune params": "finetuneParams", + "finetune price": "finetunePrice", "finetune train-options": "finetuneTrainOptions", "finetune preset-datasets": "finetunePresetDatasets", "finetune metrics": "finetuneMetrics", diff --git a/packages/commands/tests/output/console-read-output.test.ts b/packages/commands/tests/output/console-read-output.test.ts index 7edc02562..224aab2ce 100644 --- a/packages/commands/tests/output/console-read-output.test.ts +++ b/packages/commands/tests/output/console-read-output.test.ts @@ -414,7 +414,9 @@ async function invoke(scenario: Scenario, display: Display = { format: "json" }) return { stdout, stderr, stdoutAtError, thrown, exitCode, client }; } -function diagnostics(stderr: string): Array<{ debug?: unknown; error: { message: string } }> { +function diagnostics( + stderr: string, +): Array<{ debug?: unknown; error: { message: string; hint?: string } }> { return stderr.trim() ? stderr .trimEnd() @@ -515,6 +517,17 @@ for (const scenario of scenarios) { expect(calls[0]!.cornerstone.switchAgent).toBe(111); expect(diagnostics(result.stderr)).toHaveLength(1); expect(diagnostics(result.stderr)[0]!.error.message).toContain("Cannot uniquely resolve"); + // The hint names the requested ID and the accessible list so the user can + // tell "wrong account" from "wrong ID" without re-running with --verbose. + const hint = diagnostics(result.stderr)[0]!.error.hint; + expect(hint).toContain("Requested workspace: fixture-workspace"); + const accessible = + matches === "none" ? ["fixture-unrelated"] : ["fixture-workspace", "fixture-workspace"]; + expect(hint).toContain( + `matched ${matches === "none" ? 0 : 2} of ${accessible.length} accessible workspace(s)`, + ); + expect(hint).toContain(`: ${accessible.join(", ")}.`); + expect(hint).not.toContain("765432"); }, ); diff --git a/packages/commands/tests/output/fixtures/training-deployment.json b/packages/commands/tests/output/fixtures/training-deployment.json index 28f2fb555..2910cb143 100644 --- a/packages/commands/tests/output/fixtures/training-deployment.json +++ b/packages/commands/tests/output/fixtures/training-deployment.json @@ -616,12 +616,12 @@ ] }, "dataset upload preview": { - "stdout": "{\n \"action\": \"dataset.upload\",\n \"file\": \"/tmp/output-training-fixture.jsonl\",\n \"purpose\": \"fine-tune\",\n \"max_bytes\": 209715200,\n \"validate\": false,\n \"schema\": \"auto\"\n}\n", + "stdout": "{\n \"action\": \"dataset.upload\",\n \"file\": \"/tmp/output-training-fixture.jsonl\",\n \"purpose\": \"fine-tune\",\n \"max_bytes\": 314572800,\n \"validate\": false,\n \"schema\": \"auto\"\n}\n", "data": { "action": "dataset.upload", "file": "/tmp/output-training-fixture.jsonl", "purpose": "fine-tune", - "max_bytes": 209715200, + "max_bytes": 314572800, "validate": false, "schema": "auto" }, @@ -637,13 +637,15 @@ "requests": [] }, "training price preview": { - "stdout": "{\n \"action\": \"finetune.price\",\n \"model\": \"qwen-fixture\",\n \"datasets\": [\n \"file-fixture\"\n ],\n \"trainingType\": \"sft\",\n \"nEpochs\": 3\n}\n", + "stdout": "{\n \"action\": \"finetune.price\",\n \"model\": \"qwen-fixture\",\n \"datasets\": [\n \"file-fixture\"\n ],\n \"trainingType\": \"sft\",\n \"nEpochs\": 3,\n \"batchSize\": 16,\n \"maxLength\": 8192\n}\n", "data": { "action": "finetune.price", "model": "qwen-fixture", "datasets": ["file-fixture"], "trainingType": "sft", - "nEpochs": 3 + "nEpochs": 3, + "batchSize": 16, + "maxLength": 8192 }, "requests": [] }, @@ -744,7 +746,7 @@ "requests": [] }, "text training create preview": { - "stdout": "{\n \"action\": \"finetune.create\",\n \"body\": {\n \"model\": \"qwen2.5-7b-instruct\",\n \"training_file_ids\": [\n \"file-fixture\"\n ],\n \"training_type\": \"efficient_sft\",\n \"hyper_parameters\": {\n \"batch_size\": 4,\n \"n_epochs\": 3\n }\n }\n}\n", + "stdout": "{\n \"action\": \"finetune.create\",\n \"body\": {\n \"model\": \"qwen2.5-7b-instruct\",\n \"training_file_ids\": [\n \"file-fixture\"\n ],\n \"training_type\": \"efficient_sft\",\n \"hyper_parameters\": {\n \"batch_size\": 4,\n \"n_epochs\": 3\n }\n },\n \"parameter_sources\": {\n \"batch_size\": \"user\",\n \"n_epochs\": \"schema_default\"\n }\n}\n", "data": { "action": "finetune.create", "body": { @@ -755,6 +757,10 @@ "batch_size": 4, "n_epochs": 3 } + }, + "parameter_sources": { + "batch_size": "user", + "n_epochs": "schema_default" } }, "requests": [ @@ -766,7 +772,7 @@ ] }, "audio training create preview": { - "stdout": "{\n \"action\": \"finetune.create\",\n \"body\": {\n \"model\": \"cosyvoice-v3.5\",\n \"training_file_ids\": [\n \"file-fixture\"\n ],\n \"training_type\": \"efficient_sft\",\n \"hyper_parameters\": {\n \"lm_max_epoch\": 60,\n \"lm_step\": 5,\n \"lm_num\": 3,\n \"lm_batch_size\": 1000,\n \"fm_max_epoch\": 100,\n \"fm_step\": 10,\n \"fm_num\": 3,\n \"fm_batch_size\": 2000\n }\n }\n}\n", + "stdout": "{\n \"action\": \"finetune.create\",\n \"body\": {\n \"model\": \"cosyvoice-v3.5\",\n \"training_file_ids\": [\n \"file-fixture\"\n ],\n \"training_type\": \"efficient_sft\",\n \"hyper_parameters\": {\n \"lm_max_epoch\": 60,\n \"lm_step\": 5,\n \"lm_num\": 3,\n \"lm_batch_size\": 1000,\n \"fm_max_epoch\": 100,\n \"fm_step\": 10,\n \"fm_num\": 3,\n \"fm_batch_size\": 2000\n }\n },\n \"parameter_sources\": {\n \"lm_max_epoch\": \"profile_default\",\n \"lm_step\": \"profile_default\",\n \"lm_num\": \"profile_default\",\n \"lm_batch_size\": \"profile_default\",\n \"fm_max_epoch\": \"profile_default\",\n \"fm_step\": \"profile_default\",\n \"fm_num\": \"profile_default\",\n \"fm_batch_size\": \"profile_default\"\n }\n}\n", "data": { "action": "finetune.create", "body": { @@ -783,6 +789,16 @@ "fm_num": 3, "fm_batch_size": 2000 } + }, + "parameter_sources": { + "lm_max_epoch": "profile_default", + "lm_step": "profile_default", + "lm_num": "profile_default", + "lm_batch_size": "profile_default", + "fm_max_epoch": "profile_default", + "fm_step": "profile_default", + "fm_num": "profile_default", + "fm_batch_size": "profile_default" } }, "requests": [ @@ -794,7 +810,7 @@ ] }, "image training create preview": { - "stdout": "{\n \"action\": \"finetune.create\",\n \"body\": {\n \"model\": \"wan2.7\",\n \"training_file_ids\": [\n \"file-fixture\"\n ],\n \"training_type\": \"efficient_sft\",\n \"hyper_parameters\": {\n \"learning_rate\": \"3e-5\",\n \"max_steps\": 800,\n \"eval_steps\": 200,\n \"max_token_length\": \"1k\",\n \"gradient_clip\": 0.5,\n \"weight_decay\": 0.02,\n \"max_pixels\": \"2k\",\n \"val_img_size\": \"2k\",\n \"generation_type\": \"t2i\",\n \"lora_rank\": 32,\n \"save_total_limit\": 10,\n \"split\": 0.9\n }\n }\n}\n", + "stdout": "{\n \"action\": \"finetune.create\",\n \"body\": {\n \"model\": \"wan2.7\",\n \"training_file_ids\": [\n \"file-fixture\"\n ],\n \"training_type\": \"efficient_sft\",\n \"hyper_parameters\": {\n \"learning_rate\": \"3e-5\",\n \"max_steps\": 800,\n \"eval_steps\": 200,\n \"max_token_length\": \"1k\",\n \"gradient_clip\": 0.5,\n \"weight_decay\": 0.02,\n \"max_pixels\": \"2k\",\n \"val_img_size\": \"2k\",\n \"generation_type\": \"t2i\",\n \"lora_rank\": 32,\n \"save_total_limit\": 10,\n \"split\": 0.9\n }\n },\n \"parameter_sources\": {\n \"learning_rate\": \"profile_default\",\n \"max_steps\": \"profile_default\",\n \"eval_steps\": \"profile_default\",\n \"max_token_length\": \"profile_default\",\n \"gradient_clip\": \"profile_default\",\n \"weight_decay\": \"profile_default\",\n \"max_pixels\": \"profile_default\",\n \"val_img_size\": \"profile_default\",\n \"generation_type\": \"profile_default\",\n \"lora_rank\": \"profile_default\",\n \"save_total_limit\": \"profile_default\",\n \"split\": \"profile_default\"\n }\n}\n", "data": { "action": "finetune.create", "body": { @@ -815,6 +831,20 @@ "save_total_limit": 10, "split": 0.9 } + }, + "parameter_sources": { + "learning_rate": "profile_default", + "max_steps": "profile_default", + "eval_steps": "profile_default", + "max_token_length": "profile_default", + "gradient_clip": "profile_default", + "weight_decay": "profile_default", + "max_pixels": "profile_default", + "val_img_size": "profile_default", + "generation_type": "profile_default", + "lora_rank": "profile_default", + "save_total_limit": "profile_default", + "split": "profile_default" } }, "requests": [ @@ -826,7 +856,7 @@ ] }, "video training create preview": { - "stdout": "{\n \"action\": \"finetune.create\",\n \"body\": {\n \"model\": \"wan2.6-i2v\",\n \"training_file_ids\": [\n \"file-fixture\"\n ],\n \"training_type\": \"efficient_sft\",\n \"hyper_parameters\": {\n \"n_epochs\": 50,\n \"learning_rate\": \"2e-5\",\n \"split\": 0.5,\n \"max_split_val_dataset_sample\": 5,\n \"eval_epochs\": 20,\n \"save_total_limit\": 10,\n \"lora_rank\": 32,\n \"lora_alpha\": 32,\n \"batch_size\": 4,\n \"max_pixels\": 262144\n }\n }\n}\n", + "stdout": "{\n \"action\": \"finetune.create\",\n \"body\": {\n \"model\": \"wan2.6-i2v\",\n \"training_file_ids\": [\n \"file-fixture\"\n ],\n \"training_type\": \"efficient_sft\",\n \"hyper_parameters\": {\n \"n_epochs\": 50,\n \"learning_rate\": \"2e-5\",\n \"split\": 0.5,\n \"max_split_val_dataset_sample\": 5,\n \"eval_epochs\": 20,\n \"save_total_limit\": 10,\n \"lora_rank\": 32,\n \"lora_alpha\": 32,\n \"batch_size\": 4,\n \"max_pixels\": 262144\n }\n },\n \"parameter_sources\": {\n \"n_epochs\": \"profile_default\",\n \"learning_rate\": \"profile_default\",\n \"split\": \"profile_default\",\n \"max_split_val_dataset_sample\": \"profile_default\",\n \"eval_epochs\": \"profile_default\",\n \"save_total_limit\": \"profile_default\",\n \"lora_rank\": \"profile_default\",\n \"lora_alpha\": \"profile_default\",\n \"batch_size\": \"user\",\n \"max_pixels\": \"profile_default\"\n }\n}\n", "data": { "action": "finetune.create", "body": { @@ -845,6 +875,18 @@ "batch_size": 4, "max_pixels": 262144 } + }, + "parameter_sources": { + "n_epochs": "profile_default", + "learning_rate": "profile_default", + "split": "profile_default", + "max_split_val_dataset_sample": "profile_default", + "eval_epochs": "profile_default", + "save_total_limit": "profile_default", + "lora_rank": "profile_default", + "lora_alpha": "profile_default", + "batch_size": "user", + "max_pixels": "profile_default" } }, "requests": [ diff --git a/packages/core/src/dataset/api.ts b/packages/core/src/dataset/api.ts index 8dc4de1ba..65e4a6c52 100644 --- a/packages/core/src/dataset/api.ts +++ b/packages/core/src/dataset/api.ts @@ -87,19 +87,30 @@ export async function uploadDataset( const failedUploads = body.data?.failed_uploads; if (Array.isArray(failedUploads) && failedUploads.length > 0) { const first = failedUploads[0] ?? {}; + // 服务端 message 原样透传,不翻译;被拒文件数、文件名和错误码放进 hint, + // 埋点里的 apiCode 则由 err.api.apiCode 携带。 + const rejectedLabel = failedUploads.length > 1 ? `${failedUploads.length} files` : "the file"; + const rejectedFile = first.file_name ?? first.name; throw new BailianError( first.message ?? "Upload failed without a service message. / 上传失败,服务端未提供错误消息。", ExitCode.GENERAL, - undefined, + `The server accepted the request but rejected ${rejectedLabel}${rejectedFile ? ` (${rejectedFile})` : ""}. Code: ${first.code ?? "(none)"}. Inspect stored files and quota before retrying. / 服务端已接收请求但拒绝了${failedUploads.length > 1 ? ` ${failedUploads.length} 个文件` : "该文件"}${rejectedFile ? `(${rejectedFile})` : ""}。错误码:${first.code ?? "(none)"}。请先检查已存储文件与配额后再重试。`, { api: { httpStatus: 200, apiCode: first.code, requestId: body.request_id }, rawResponse: JSON.stringify(body), }, ); } + // 没有 failed_uploads 时服务端没给任何原因,把响应的顶层结构写进 message, + // 让本地 JSONL / AEM 里的失败能直接看出服务端到底返回了什么形状。 + const dataKeys = + body.data && typeof body.data === "object" + ? Object.keys(body.data as Record).join(";") + : "(none)"; + const bodyKeys = Object.keys(body).join(";"); throw new BailianError( - `Upload response for ${fileName} has no usable file ID. / ${fileName} 的上传响应缺少可用文件 ID。`, + `Upload response for ${fileName} has no usable file ID (keys: ${bodyKeys}; data: ${dataKeys}). / ${fileName} 的上传响应缺少可用文件 ID(字段:${bodyKeys};data:${dataKeys})。`, ExitCode.GENERAL, "Success cannot be verified; inspect the file list before retrying. / 无法验证上传成功,请先检查文件列表,再决定是否重试。", { api: { httpStatus: 200, requestId: body.request_id }, rawResponse: JSON.stringify(body) }, diff --git a/packages/core/src/dataset/index.ts b/packages/core/src/dataset/index.ts index a7796d7ec..08c3b11cd 100644 --- a/packages/core/src/dataset/index.ts +++ b/packages/core/src/dataset/index.ts @@ -2,16 +2,15 @@ export * from "./types.ts"; export * from "./api.ts"; export * from "./console.ts"; export * from "./prepare/index.ts"; -export { detectModality } from "./inspect.ts"; +export { detectModality, resolveDatasetMaxBytesForFile } from "./inspect.ts"; export { validateDataset, pickValidator, registerValidator, listSupportedFormats, MAX_DATASET_BYTES, - MAX_CPT_BYTES, - MAX_DECISION_DATASET_BYTES, MAX_MEDIA_ZIP_BYTES, + resolveDatasetMaxBytes, parseDatasetSchemaFlag, formatIssue, } from "./validate/index.ts"; diff --git a/packages/core/src/dataset/inspect.ts b/packages/core/src/dataset/inspect.ts index 9a556aef6..107245cdd 100644 --- a/packages/core/src/dataset/inspect.ts +++ b/packages/core/src/dataset/inspect.ts @@ -22,6 +22,8 @@ import { extname } from "path"; import { BailianError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; import { openZipAndFindEntry } from "./validate/zip.ts"; +import { resolveDatasetMaxBytes } from "./validate/common.ts"; +import type { DatasetSchema } from "./validate/types.ts"; import type { DataModality } from "../finetune/profiles/types.ts"; /** @@ -46,6 +48,35 @@ export async function detectModality(filePath: string): Promise { ); } +/** Map a detected media modality onto the record schema that owns its size cap. */ +function mediaSchemaFromModality(modality: DataModality): DatasetSchema | undefined { + if (modality === "audio") return "tts"; + if (modality === "image" || modality === "image-i2i") return "image"; + if (modality === "video" || modality === "video-kf2v") return "video"; + return undefined; +} + +/** + * Size cap for a dataset file. `--schema` wins. Without it a ZIP is sniffed + * from its first `data.jsonl` record (one entry read, not the whole archive) + * so image/video archives get the 1 GB cap and audio archives stay at the + * 300 MB fine-tune cap. Anything that cannot be sniffed falls back to the + * conservative cap — the validator then reports the real structural problem + * instead of a misleading size error. + */ +export async function resolveDatasetMaxBytesForFile( + schema: DatasetSchema | undefined, + filePath: string, +): Promise { + if (schema) return resolveDatasetMaxBytes(schema); + if (extname(filePath).toLowerCase() !== ".zip") return resolveDatasetMaxBytes(undefined); + try { + return resolveDatasetMaxBytes(mediaSchemaFromModality(await detectModality(filePath))); + } catch { + return resolveDatasetMaxBytes(undefined); + } +} + /** * Read the first non-blank line of a JSONL file and determine the modality. */ diff --git a/packages/core/src/dataset/types.ts b/packages/core/src/dataset/types.ts index e1d72873f..9a1f39b09 100644 --- a/packages/core/src/dataset/types.ts +++ b/packages/core/src/dataset/types.ts @@ -77,7 +77,9 @@ export interface DatasetUploadResponse { failed_uploads?: Array<{ code?: string; message?: string; + /** The upload API doc example uses `name`; accept both spellings. */ file_name?: string; + name?: string; }>; }; } diff --git a/packages/core/src/dataset/validate/common.ts b/packages/core/src/dataset/validate/common.ts index f9784307a..2d76bf4ad 100644 --- a/packages/core/src/dataset/validate/common.ts +++ b/packages/core/src/dataset/validate/common.ts @@ -6,33 +6,41 @@ * and we get one place to tune limits if the platform changes them. */ import { existsSync, statSync } from "fs"; -import { extname } from "path"; +import { basename, extname } from "path"; import { BailianError } from "../../errors/base.ts"; import { ExitCode } from "../../errors/codes.ts"; import type { DatasetSchema, ValidationIssue, ValidationStats } from "./types.ts"; /** - * The platform caps SFT/DPO text dataset uploads at 200MB per file. - * `bl dataset upload` enforces this client-side so users learn early. - * CPT uses 300MB (see MAX_CPT_BYTES); API general upload is also 300MB. + * Single-file cap for every `purpose=fine-tune` upload (SFT / DPO / CPT / + * decision / TTS alike): 300 MB per the file upload API. The 200 MB figure in + * the tuning-data guide is the console limit; this CLI uploads via the API. */ -export const MAX_DATASET_BYTES = 200 * 1024 * 1024; +export const MAX_DATASET_BYTES = 300 * 1024 * 1024; /** - * CPT text dataset size cap — 300 MB per the platform docs. - * CPT requires at least 50M tokens; larger files are expected. + * Image / video generation training ZIP cap — 1 GB per the file upload API and + * the Wan fine-tuning guides. Used by `bl dataset upload` for media schemas and + * by the `sft-lora` training profile for image / video validation. (The 2 GB + * figure in the tuning-data guide applies to multimodal *evaluation* sets only.) */ -export const MAX_CPT_BYTES = 300 * 1024 * 1024; - -/** 决策模型训练数据单文件上限,按平台文档为 300MB。 */ -export const MAX_DECISION_DATASET_BYTES = 300 * 1024 * 1024; +export const MAX_MEDIA_ZIP_BYTES = 1024 * 1024 * 1024; /** - * Image / video ZIP size cap — 2 GB per the platform docs. Used by - * `bl dataset upload` for media schemas and by the `sft-lora` training - * profile for image / video validation. + * Cap for a given record schema. Text-like schemas (chatml / dpo / cpt / + * decision / tts) share the fine-tune purpose cap; only image / video ZIPs get + * the larger media cap. Shared by `dataset upload` and `dataset validate` so + * both commands reject the same files. */ -export const MAX_MEDIA_ZIP_BYTES = 2 * 1024 * 1024 * 1024; +export function resolveDatasetMaxBytes(schema: DatasetSchema | undefined): number { + return schema === "image" || schema === "video" ? MAX_MEDIA_ZIP_BYTES : MAX_DATASET_BYTES; +} + +/** Human-readable size with enough precision to never round back to the cap. */ +function formatSizeLabel(bytes: number): string { + if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)}GB`; + return `${(bytes / (1024 * 1024)).toFixed(2)}MB`; +} export interface PreflightResult { bytes: number; @@ -56,11 +64,10 @@ export function preflight(filePath: string, maxBytes = MAX_DATASET_BYTES): Prefl throw new BailianError(`File is empty: ${filePath}`, ExitCode.USAGE); } if (stat.size > maxBytes) { - const mb = (stat.size / (1024 * 1024)).toFixed(1); - const cap = (maxBytes / (1024 * 1024)).toFixed(0); throw new BailianError( - `File too large: ${mb}MB exceeds the ${cap}MB dataset upload cap.`, + `File too large: ${basename(filePath)} is ${stat.size} bytes (${formatSizeLabel(stat.size)}), exceeding the ${formatSizeLabel(maxBytes)} dataset upload cap (${maxBytes} bytes).`, ExitCode.USAGE, + "Caps follow --schema or, for ZIPs without --schema, the detected content: text / CPT / decision / TTS files 300 MB, image / video ZIPs 1 GB. Split the file; if an image/video ZIP was not detected, pass --schema image|video. / 上限随 --schema 而定,未传 --schema 的 ZIP 按识别内容判定:文本 / CPT / decision / TTS 为 300 MB,图像 / 视频 ZIP 为 1 GB。请拆分文件;若图像 / 视频 ZIP 未被识别,请补传 --schema image|video。", ); } return { diff --git a/packages/core/src/dataset/validate/index.ts b/packages/core/src/dataset/validate/index.ts index 43e6418c6..bbc7295d0 100644 --- a/packages/core/src/dataset/validate/index.ts +++ b/packages/core/src/dataset/validate/index.ts @@ -6,9 +6,8 @@ export { } from "./registry.ts"; export { MAX_DATASET_BYTES, - MAX_CPT_BYTES, - MAX_DECISION_DATASET_BYTES, MAX_MEDIA_ZIP_BYTES, + resolveDatasetMaxBytes, parseDatasetSchemaFlag, } from "./common.ts"; export { formatIssue } from "./format.ts"; diff --git a/packages/core/src/dataset/validate/registry.ts b/packages/core/src/dataset/validate/registry.ts index 1be491af4..f83f8b570 100644 --- a/packages/core/src/dataset/validate/registry.ts +++ b/packages/core/src/dataset/validate/registry.ts @@ -12,7 +12,7 @@ * 2. Import it here and append to `REGISTRY`. * That's it. Nothing else in this folder needs to change. */ -import { extname } from "path"; +import { basename, extname } from "path"; import { BailianError } from "../../errors/base.ts"; import { ExitCode } from "../../errors/codes.ts"; import { jsonlValidator } from "./jsonl.ts"; @@ -29,9 +29,9 @@ export function pickValidator(filePath: string): ValidatorSpec { if (!v) { const supported = REGISTRY.flatMap((s) => s.extensions).join(", "); throw new BailianError( - `Unsupported dataset format "${ext || "(none)"}". Supported: ${supported}`, + `Unsupported dataset format "${ext || "(none)"}" for "${basename(filePath)}". Supported: ${supported}`, ExitCode.USAGE, - `Convert your data to one of the supported formats and re-run.`, + "Convert your data to one of the supported formats and re-run. / 请将数据转换为支持的格式后重试。", ); } return v; diff --git a/packages/core/src/finetune/preflight.ts b/packages/core/src/finetune/preflight.ts index e03a77b35..b234c2ca2 100644 --- a/packages/core/src/finetune/preflight.ts +++ b/packages/core/src/finetune/preflight.ts @@ -148,7 +148,8 @@ export type FineTuneHyperParameterIssueCode = | "invalid_type" | "not_supported" | "out_of_range" - | "invalid_step"; + | "invalid_step" + | "not_power_of_two"; export interface FineTuneHyperParameterIssue { parameter: string; @@ -169,9 +170,15 @@ function isStepAligned(value: number, origin: number, step: number): boolean { return Math.abs(quotient - Math.round(quotient)) < 1e-9; } +export interface FineTuneHyperParameterValidationOptions { + /** Apply the platform integer-batch rule only in training scopes known to use it. */ + integerBatchSizePowerOfTwo?: boolean; +} + export function validateFineTuneHyperParameterOverrides( schema: FineTuneParamHyperParam[], overrides: Record, + options: FineTuneHyperParameterValidationOptions = {}, ): FineTuneHyperParameterIssue[] { const definitions = new Map( schema.flatMap((parameter) => (parameter.name ? [[parameter.name, parameter] as const] : [])), @@ -254,6 +261,21 @@ export function validateFineTuneHyperParameterOverrides( code: "invalid_step", expected: `step ${definition.step} from ${minimum ?? 0}`, }); + continue; + } + + if ( + parameter === "batch_size" && + options.integerBatchSizePowerOfTwo === true && + definition.type === "intInputNumber" && + (numeric <= 0 || !Number.isInteger(Math.log2(numeric))) + ) { + issues.push({ + parameter, + value, + code: "not_power_of_two", + expected: "a positive power of two", + }); } continue; } @@ -275,10 +297,30 @@ export function validateFineTuneHyperParameterOverrides( return issues; } +export type FineTuneSchemaValueSource = "schema_default" | "schema_recommend"; + +export interface FineTuneSchemaNumericValue { + value: number; + source: FineTuneSchemaValueSource; +} + +/** Resolve a numeric schema value without confusing a recommendation with a default. */ +export function resolveFineTuneHyperParameterDefaultNumber( + schema: FineTuneParamHyperParam[], + parameter: string, +): FineTuneSchemaNumericValue | undefined { + const definition = schema.find((candidate) => candidate.name === parameter); + const defaultValue = numericValue(definition?.defaultValue); + if (defaultValue !== undefined) return { value: defaultValue, source: "schema_default" }; + const recommendedValue = numericValue(definition?.recommend_value); + if (recommendedValue !== undefined) + return { value: recommendedValue, source: "schema_recommend" }; + return undefined; +} + export function getFineTuneHyperParameterDefaultNumber( schema: FineTuneParamHyperParam[], parameter: string, ): number | undefined { - const definition = schema.find((candidate) => candidate.name === parameter); - return numericValue(definition?.defaultValue ?? definition?.recommend_value); + return resolveFineTuneHyperParameterDefaultNumber(schema, parameter)?.value; } diff --git a/packages/core/src/finetune/price.ts b/packages/core/src/finetune/price.ts index 64651ae56..f71983be0 100644 --- a/packages/core/src/finetune/price.ts +++ b/packages/core/src/finetune/price.ts @@ -38,6 +38,13 @@ export interface TokenEstimate { [key: string]: unknown; } +/** Cost-driving hyper-parameters shared by the text estimation entry points. */ +export interface TrainingEstimateHyperParams { + nEpochs: number; + batchSize: number; + maxLength: number; +} + // --------------------------------------------------------------------------- // API wrappers // --------------------------------------------------------------------------- @@ -63,7 +70,7 @@ export async function fetchTrainingModelPrice( export async function estimateSftDpoTokens( client: Client, datasetIds: string[], - hyperParams: { nEpochs: number; batchSize: number; maxLength: number }, + hyperParams: TrainingEstimateHyperParams, ): Promise { const raw = await client.console>(CALC_DATASETS_TOKENS_API, { input: { trainDatasetIds: datasetIds, hyperParams }, @@ -77,28 +84,29 @@ export async function estimateSftDpoTokens( * The console API requires `hyperParams` as a **JSON string** with a full * `userDefinedObj` payload (captured from the console frontend), plus several * top-level fields (`algorithmType`, `bizType`, `priority`, …). Only - * `n_epochs` / `max_length` materially affect the estimate; the remaining - * hyper-parameters are fixed defaults. + * `n_epochs` / `batch_size` / `max_length` come from the caller so the estimate + * can use the same cost-driving values as the planned creation request; the + * remaining hyper-parameters are fixed defaults. */ export async function estimateCptTokens( client: Client, model: string, datasetIdsCsv: string, - nEpochs: number, + hyperParams: TrainingEstimateHyperParams, ): Promise { const userDefinedObj = { - batch_size: 16, + batch_size: hyperParams.batchSize, eval_steps: 50, learning_rate: "7e-6", lr_scheduler_type: "linear", - max_length: 8192, - n_epochs: nEpochs, + max_length: hyperParams.maxLength, + n_epochs: hyperParams.nEpochs, split: 0.9, save_total_limit: "3", resume_from_checkpoint: false, save_strategy: "epoch", }; - const hyperParams = JSON.stringify({ + const serializedHyperParams = JSON.stringify({ useDefault: false, userDefinedObj, useQwenMixedStrategy: false, @@ -110,7 +118,7 @@ export async function estimateCptTokens( algorithmType: 100, bizType: 100, trainDatasetIds: datasetIdsCsv, - hyperParams, + hyperParams: serializedHyperParams, bailianTrainModel: model, validationDatasetIds: "", jobName: `${model}_cli_estimate`, diff --git a/packages/core/src/finetune/profiles/cpt.ts b/packages/core/src/finetune/profiles/cpt.ts index f96294455..10ecaf39e 100644 --- a/packages/core/src/finetune/profiles/cpt.ts +++ b/packages/core/src/finetune/profiles/cpt.ts @@ -1,13 +1,12 @@ /** * `cpt` profile — Continual Pre-Training (full-parameter). * Maps to the server's `cpt` training type. CPT record schema. - * CPT allows larger files (300 MB) compared to SFT/DPO (200 MB). + * Shares the 300 MB fine-tune upload cap with every text schema. */ import type { TrainingProfile, DataModality } from "./types.ts"; import type { ValidateOpts, ValidationResult } from "../../dataset/validate/types.ts"; import { validateDataset } from "../../dataset/validate/registry.ts"; import { resolveTextHyperParameters } from "./common.ts"; -import { MAX_CPT_BYTES } from "../../dataset/validate/common.ts"; export const cptProfile: TrainingProfile = { clientTrainingType: "cpt", @@ -19,7 +18,7 @@ export const cptProfile: TrainingProfile = { _modality: DataModality, opts: ValidateOpts, ): Promise { - return validateDataset(filePath, { ...opts, schema: "cpt", maxBytes: MAX_CPT_BYTES }); + return validateDataset(filePath, { ...opts, schema: "cpt" }); }, resolveHyperParameters( diff --git a/packages/core/src/finetune/profiles/sft-lora.ts b/packages/core/src/finetune/profiles/sft-lora.ts index c79538413..cc56d0b03 100644 --- a/packages/core/src/finetune/profiles/sft-lora.ts +++ b/packages/core/src/finetune/profiles/sft-lora.ts @@ -153,6 +153,7 @@ export const sftLoraProfile: TrainingProfile = { if (modality === "audio") { // ZIP validation: structure check + JSONL content via tts schema. // The zip validator internally calls jsonlValidator for data.jsonl. + // Audio ZIPs share the 300 MB fine-tune upload cap (default maxBytes). return validateDataset(filePath, { ...opts, schema: "tts" }); } if (isImage(modality)) { diff --git a/packages/core/src/finetune/rl/config.ts b/packages/core/src/finetune/rl/config.ts index 35b89e0ba..e5e752137 100644 --- a/packages/core/src/finetune/rl/config.ts +++ b/packages/core/src/finetune/rl/config.ts @@ -115,6 +115,25 @@ function buildDatasetEntries( return entries; } +function numericHyperParameter(value: unknown): number | undefined { + if (typeof value === "number") return Number.isFinite(value) ? value : undefined; + if (typeof value !== "string" || value.trim() === "") return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; +} + +/** Prompt tokens must leave room for generated responses in ordinary RL. */ +function validateRlPromptLength(spec: RlJobSpec): void { + const hyperParameters = spec.training?.hyper_parameters; + const promptLength = numericHyperParameter(hyperParameters?.max_prompt_length); + const maxLength = numericHyperParameter(hyperParameters?.max_length); + if (promptLength === undefined || maxLength === undefined || promptLength < maxLength) return; + throw new UsageError( + `max_prompt_length (${promptLength}) must be smaller than max_length (${maxLength}). / max_prompt_length(${promptLength})必须小于 max_length(${maxLength})。`, + "Reduce max_prompt_length or increase max_length to reserve space for generated responses. / 请减小 max_prompt_length 或增大 max_length,为生成回答预留长度。", + ); +} + /** * Merge CLI params over an optional YAML document into a single SDK spec. * Enforces model presence and the RL/OPD type constraints. @@ -290,6 +309,7 @@ export function resolveTrainingSpec(params: RlRunParams, yamlText?: string): IRe ); } if (!spec.training.type) spec.training.type = "reinforcement"; + validateRlPromptLength(spec); } if (!spec.model?.name) { diff --git a/packages/core/src/finetune/types.ts b/packages/core/src/finetune/types.ts index 91319196a..7103edc3a 100644 --- a/packages/core/src/finetune/types.ts +++ b/packages/core/src/finetune/types.ts @@ -258,8 +258,9 @@ export interface GetFineTuneResponse { /** * GET /api/v1/fine-tunes/fine-tunes-params 的 `output.hyper_params[]` 元素。 - * `defaultValue` 是服务端保留的兼容字段名(与 recommend_value 同值),不改名为 - * default_value。`visibility` / `required` 等其他可选字段不在此依赖,缺失不算失败。 + * 保留服务端字段名。`defaultValue` 表示默认值,`recommend_value` 只表示推荐值; + * 推荐值被用于请求时必须单独标记,不能视为任务实际生效的默认值。 + * `visibility` / `required` 等其他可选字段不在此依赖,缺失不算失败。 */ export interface FineTuneParamHyperParam { name?: string; diff --git a/packages/core/src/telemetry/event.ts b/packages/core/src/telemetry/event.ts index beedd8c42..ced2f709a 100644 --- a/packages/core/src/telemetry/event.ts +++ b/packages/core/src/telemetry/event.ts @@ -14,6 +14,8 @@ export interface TrackingEvent { exitCode?: number; httpStatus?: number; requestId?: string; + /** Business error code from the server body (HTTP 200 + error payload cases). */ + apiCode?: string; cliVersion: string; commandPrefix: string; nodeVersion: string; @@ -56,7 +58,13 @@ export function createTrackingEvent(opts: { command: string; durationMs: number; success: boolean; - error?: { message?: string; exitCode?: number; httpStatus?: number; requestId?: string }; + error?: { + message?: string; + exitCode?: number; + httpStatus?: number; + requestId?: string; + apiCode?: string; + }; identity: Identity; authMethod?: AuthRequirement; params?: Record; @@ -102,6 +110,7 @@ export function createTrackingEvent(opts: { if (opts.error.exitCode !== undefined) event.exitCode = opts.error.exitCode; if (opts.error.httpStatus !== undefined) event.httpStatus = opts.error.httpStatus; if (opts.error.requestId) event.requestId = opts.error.requestId; + if (opts.error.apiCode) event.apiCode = opts.error.apiCode; } if (opts.params && Object.keys(opts.params).length > 0) { diff --git a/packages/core/src/telemetry/tracker.ts b/packages/core/src/telemetry/tracker.ts index a12d92148..f263a8b43 100644 --- a/packages/core/src/telemetry/tracker.ts +++ b/packages/core/src/telemetry/tracker.ts @@ -191,6 +191,7 @@ export async function trackCommandExecution( let exitCode: number | undefined; let httpStatus: number | undefined; let requestId: string | undefined; + let apiCode: string | undefined; try { await fn(); @@ -201,6 +202,7 @@ export async function trackCommandExecution( exitCode = err.exitCode; httpStatus = err.api?.httpStatus; requestId = err.api?.requestId; + apiCode = err.api?.apiCode; } else if (err instanceof Error) { errorMessage = err.message; } @@ -222,7 +224,9 @@ export async function trackCommandExecution( command: commandPath.join(" "), durationMs, success, - error: success ? undefined : { message: errorMessage, exitCode, httpStatus, requestId }, + error: success + ? undefined + : { message: errorMessage, exitCode, httpStatus, requestId, apiCode }, identity: deps.identity, authMethod: deps.authMethod, params: extractParams(flags), diff --git a/packages/core/tests/batch-api.test.ts b/packages/core/tests/batch-api.test.ts index 6a6e802dc..656b43950 100644 --- a/packages/core/tests/batch-api.test.ts +++ b/packages/core/tests/batch-api.test.ts @@ -136,6 +136,7 @@ describe("Batch 请求接缝", () => { ).rejects.toMatchObject({ message: "服务原始消息", exitCode: 1, + hint: expect.stringContaining("Code: ServiceCode"), api: { httpStatus: 200, apiCode: "ServiceCode", requestId: "req-one" }, }); }); @@ -145,7 +146,11 @@ describe("Batch 请求接缝", () => { .mockResolvedValue(Response.json({ request_id: "req-one" })); await expect( uploadDataset(client(), { filePath: "input.jsonl", fileBlob: new Blob(["test"]) }), - ).rejects.toMatchObject({ exitCode: 1, hint: expect.stringMatching(/inspect the file list/) }); + ).rejects.toMatchObject({ + exitCode: 1, + message: expect.stringContaining("(keys: request_id; data: (none))"), + hint: expect.stringMatching(/inspect the file list/), + }); expect(fetch).toHaveBeenCalledTimes(1); }); test.each([400, 404, 429, 500])("Batch HTTP %s 错误原样透传而不换端点重试", async (status) => { diff --git a/packages/core/tests/dataset-validate.test.ts b/packages/core/tests/dataset-validate.test.ts index ac66a3b28..56c7b838a 100644 --- a/packages/core/tests/dataset-validate.test.ts +++ b/packages/core/tests/dataset-validate.test.ts @@ -2,7 +2,67 @@ import { afterAll, describe, expect, test } from "vite-plus/test"; import { mkdirSync, rmSync, writeFileSync } from "fs"; import { join } from "path"; import { tmpdir } from "os"; -import { validateDataset, parseDatasetSchemaFlag } from "../src/index.ts"; +import { + validateDataset, + parseDatasetSchemaFlag, + pickValidator, + resolveDatasetMaxBytes, + resolveDatasetMaxBytesForFile, +} from "../src/index.ts"; + +/** Minimal ZIP writer (stored entries only) so tests can build archives yauzl can open. */ +function buildStoredZip(files: Record): Buffer { + const crcTable = Array.from({ length: 256 }, (_, index) => { + let value = index; + for (let bit = 0; bit < 8; bit++) { + value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1; + } + return value >>> 0; + }); + const crc32 = (data: Buffer): number => { + let crc = 0xffffffff; + for (const byte of data) crc = crcTable[(crc ^ byte) & 0xff]! ^ (crc >>> 8); + return (crc ^ 0xffffffff) >>> 0; + }; + const localParts: Buffer[] = []; + const centralParts: Buffer[] = []; + let offset = 0; + for (const [name, content] of Object.entries(files)) { + const nameBuf = Buffer.from(name, "utf8"); + const data = Buffer.from(content, "utf8"); + const crc = crc32(data); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); // version needed + local.writeUInt16LE(0, 8); // method: stored + local.writeUInt32LE(crc, 14); + local.writeUInt32LE(data.length, 18); + local.writeUInt32LE(data.length, 22); + local.writeUInt16LE(nameBuf.length, 26); + localParts.push(local, nameBuf, data); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(20, 4); // version made by + central.writeUInt16LE(20, 6); // version needed + central.writeUInt16LE(0, 10); // method: stored + central.writeUInt32LE(crc, 16); + central.writeUInt32LE(data.length, 20); + central.writeUInt32LE(data.length, 24); + central.writeUInt16LE(nameBuf.length, 28); + central.writeUInt32LE(offset, 42); + centralParts.push(central, nameBuf); + offset += local.length + nameBuf.length + data.length; + } + const centralDir = Buffer.concat(centralParts); + const entryCount = Object.keys(files).length; + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(entryCount, 8); + eocd.writeUInt16LE(entryCount, 10); + eocd.writeUInt32LE(centralDir.length, 12); + eocd.writeUInt32LE(offset, 16); + return Buffer.concat([...localParts, centralDir, eocd]); +} const tmp = join(tmpdir(), `bl-dpo-test-${process.pid}`); mkdirSync(tmp, { recursive: true }); @@ -874,3 +934,59 @@ describe("parseDatasetSchemaFlag", () => { expect(() => parseDatasetSchemaFlag("sft")).toThrow(/Unsupported --schema/); }); }); + +describe("dataset size caps (file upload API: fine-tune 300MB, image/video zip 1GB)", () => { + test("text-like schemas share 300MB; only image/video get 1GB; auto-detect stays conservative", () => { + const textCap = 300 * 1024 * 1024; + for (const schema of ["chatml", "dpo", "cpt", "decision", "tts", undefined] as const) { + expect(resolveDatasetMaxBytes(schema)).toBe(textCap); + } + expect(resolveDatasetMaxBytes("image")).toBe(1024 * 1024 * 1024); + expect(resolveDatasetMaxBytes("video")).toBe(1024 * 1024 * 1024); + }); + + test("oversized file reports exact bytes, cap and the --schema-dependent hint", async () => { + const p = file("tiny.jsonl", [SFT_OK]); + await expect(validateDataset(p, { maxBytes: 10 })).rejects.toThrow( + /^File too large: tiny\.jsonl is \d+ bytes \(0\.00MB\), exceeding the 0\.00MB dataset upload cap \(10 bytes\)\.$/, + ); + await expect(validateDataset(p, { maxBytes: 10 })).rejects.toMatchObject({ + hint: expect.stringContaining("image / video ZIPs 1 GB"), + }); + }); + + test("unsupported format names the file so telemetry can point at the culprit", () => { + // A dotfile such as `.size-probe` has no extension: extname() returns "". + expect(() => pickValidator("/tmp/.size-probe")).toThrow( + 'Unsupported dataset format "(none)" for ".size-probe". Supported: .jsonl, .zip', + ); + }); + + test("zip without --schema is sniffed from its first data.jsonl record", async () => { + const textCap = 300 * 1024 * 1024; + const gigabyte = 1024 * 1024 * 1024; + const imageZip = join(tmp, "sniff-image.zip"); + writeFileSync(imageZip, buildStoredZip({ "data.jsonl": '{"img_path":"1.png","text":"cat"}' })); + const videoZip = join(tmp, "sniff-video.zip"); + writeFileSync( + videoZip, + buildStoredZip({ "data.jsonl": '{"first_frame_path":"1.jpg","video_path":"1.mp4"}' }), + ); + const audioZip = join(tmp, "sniff-audio.zip"); + writeFileSync( + audioZip, + buildStoredZip({ "data.jsonl": '{"wav_fn":"train/1.wav","text":"hi"}' }), + ); + const brokenZip = join(tmp, "sniff-broken.zip"); + writeFileSync(brokenZip, "not-a-real-zip"); + + expect(await resolveDatasetMaxBytesForFile(undefined, imageZip)).toBe(gigabyte); + expect(await resolveDatasetMaxBytesForFile(undefined, videoZip)).toBe(gigabyte); + // Audio archives stay at the fine-tune cap even though they are ZIPs. + expect(await resolveDatasetMaxBytesForFile(undefined, audioZip)).toBe(textCap); + // Unreadable archive → conservative cap; the validator reports the real error. + expect(await resolveDatasetMaxBytesForFile(undefined, brokenZip)).toBe(textCap); + // An explicit --schema still wins over the content. + expect(await resolveDatasetMaxBytesForFile("tts", imageZip)).toBe(textCap); + }); +}); diff --git a/packages/core/tests/finetune-preflight.test.ts b/packages/core/tests/finetune-preflight.test.ts index 2e31ca7b6..d1989d8a8 100644 --- a/packages/core/tests/finetune-preflight.test.ts +++ b/packages/core/tests/finetune-preflight.test.ts @@ -5,6 +5,7 @@ import { INSUFFICIENT_SAMPLES_CODE, preflightBatchSizeGate, preflightDecisionSampleGate, + resolveFineTuneHyperParameterDefaultNumber, validateFineTuneHyperParameterOverrides, type FineTuneParamHyperParam, } from "../src/index.ts"; @@ -212,9 +213,55 @@ describe("validateFineTuneHyperParameterOverrides", () => { ]); }); - test("uses defaultValue before recommend_value for numeric service defaults", () => { + test("applies the power-of-two rule only to integer batch sizes in an enabled scope", () => { + const integerBatchSchema: FineTuneParamHyperParam[] = [ + { + name: "batch_size", + type: "intInputNumber", + data_range: ["8", "64"], + step: 8, + editable: true, + }, + ]; + expect( + validateFineTuneHyperParameterOverrides( + integerBatchSchema, + { batch_size: 24 }, + { integerBatchSizePowerOfTwo: true }, + ), + ).toEqual([ + expect.objectContaining({ code: "not_power_of_two", expected: "a positive power of two" }), + ]); + expect( + validateFineTuneHyperParameterOverrides( + integerBatchSchema, + { batch_size: 16 }, + { integerBatchSizePowerOfTwo: true }, + ), + ).toEqual([]); + expect(validateFineTuneHyperParameterOverrides(integerBatchSchema, { batch_size: 24 })).toEqual( + [], + ); + expect( + validateFineTuneHyperParameterOverrides( + schema, + { batch_size: 40 }, + { integerBatchSizePowerOfTwo: true }, + ), + ).toEqual([]); + }); + + test("uses defaultValue before recommend_value and preserves the value source", () => { + expect(resolveFineTuneHyperParameterDefaultNumber(schema, "batch_size")).toEqual({ + value: 32, + source: "schema_default", + }); + expect(resolveFineTuneHyperParameterDefaultNumber(schema, "fallback_default")).toEqual({ + value: 7, + source: "schema_recommend", + }); expect(getFineTuneHyperParameterDefaultNumber(schema, "batch_size")).toBe(32); expect(getFineTuneHyperParameterDefaultNumber(schema, "fallback_default")).toBe(7); - expect(getFineTuneHyperParameterDefaultNumber(schema, "missing")).toBeUndefined(); + expect(resolveFineTuneHyperParameterDefaultNumber(schema, "missing")).toBeUndefined(); }); }); diff --git a/packages/core/tests/finetune-price.test.ts b/packages/core/tests/finetune-price.test.ts new file mode 100644 index 000000000..99d2056dd --- /dev/null +++ b/packages/core/tests/finetune-price.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test, vi } from "vite-plus/test"; +import { + CALC_DATASETS_TOKENS_API, + ESTIMATE_FINETUNE_TOKENS_API, + estimateCptTokens, + estimateSftDpoTokens, + type Client, +} from "../src/index.ts"; + +const hyperParams = { nEpochs: 2, batchSize: 32, maxLength: 4096 }; + +describe("training token estimation parameters", () => { + test("SFT/DPO forwards all cost-driving values", async () => { + const consoleCall = vi.fn(async () => ({})); + const client = { console: consoleCall } as unknown as Client; + + await estimateSftDpoTokens(client, ["file-a", "file-b"], hyperParams); + + expect(consoleCall).toHaveBeenCalledWith(CALC_DATASETS_TOKENS_API, { + input: { trainDatasetIds: ["file-a", "file-b"], hyperParams }, + }); + }); + + test("CPT writes the same values into userDefinedObj", async () => { + const consoleCall = vi.fn(async () => ({})); + const client = { console: consoleCall } as unknown as Client; + + await estimateCptTokens(client, "qwen-test", "file-a,file-b", hyperParams); + + const [api, request] = consoleCall.mock.calls[0] as unknown as [ + string, + { input: { hyperParams: string } }, + ]; + expect(api).toBe(ESTIMATE_FINETUNE_TOKENS_API); + expect(JSON.parse(request.input.hyperParams).userDefinedObj).toMatchObject({ + n_epochs: 2, + batch_size: 32, + max_length: 4096, + }); + }); +}); diff --git a/packages/core/tests/rl-config.test.ts b/packages/core/tests/rl-config.test.ts index 998d6294d..bdca26adc 100644 --- a/packages/core/tests/rl-config.test.ts +++ b/packages/core/tests/rl-config.test.ts @@ -235,6 +235,36 @@ describe("resolveTrainingSpec type constraints", () => { test("base model is required", () => { expect(() => resolveTrainingSpec({})).toThrow(/base model is required/); }); + + test("RL requires max_prompt_length to be smaller than max_length after merging", () => { + const yamlText = ` +model: + name: m +training: + hyper_parameters: + max_prompt_length: 4096 + max_length: 4096 +`; + expect(() => resolveTrainingSpec({ model: "m" }, yamlText)).toThrow( + /max_prompt_length.*must be smaller than max_length/, + ); + expect(() => + resolveTrainingSpec( + { model: "m", hp: ["max_prompt_length=8192", "max_length=4096"] }, + yamlText, + ), + ).toThrow(/max_prompt_length \(8192\).*max_length \(4096\)/); + }); + + test("RL accepts a shorter prompt limit and leaves missing length checks to the server", () => { + expect( + resolveTrainingSpec({ + model: "m", + hp: ["max_prompt_length=4095", "max_length=4096"], + }).spec.training?.hyper_parameters, + ).toEqual({ max_prompt_length: 4095, max_length: 4096 }); + expect(() => resolveTrainingSpec({ model: "m", hp: ["max_prompt_length=4096"] })).not.toThrow(); + }); }); describe("buildTaskYaml path rewriting", () => { diff --git a/packages/core/tests/telemetry-tracker.test.ts b/packages/core/tests/telemetry-tracker.test.ts index 86dc99768..5b3cba31d 100644 --- a/packages/core/tests/telemetry-tracker.test.ts +++ b/packages/core/tests/telemetry-tracker.test.ts @@ -115,6 +115,33 @@ test("derives event version and prefix from identity", () => { }); }); +test("server business apiCode rides along with httpStatus and requestId on failure", async () => { + sinkMocks.localSink.mockClear(); + await expect( + trackCommandExecution( + { identity, settings: { telemetry: true } as Settings, caller: unknownCaller }, + ["dataset", "upload"], + {}, + async () => { + throw new BailianError("Out of space", ExitCode.GENERAL, undefined, { + api: { httpStatus: 200, apiCode: "BadRequest.TooLarge", requestId: "req-quota" }, + }); + }, + ), + ).rejects.toThrow("Out of space"); + const event = asCommand(sinkMocks.localSink.mock.calls[0]![0]); + expect(event).toMatchObject({ + success: false, + exitCode: ExitCode.GENERAL, + httpStatus: 200, + requestId: "req-quota", + apiCode: "BadRequest.TooLarge", + }); + // apiCode is an ext field, not a dedicated c-column (c1-c6 are taken). + expect(buildRemoteAemOptions(event).ext).toMatchObject({ apiCode: "BadRequest.TooLarge" }); + expect(buildRemoteAemOptions(event)).not.toHaveProperty("c7"); +}); + test("resolveSite runs in finally and attaches site fields", async () => { sinkMocks.localSink.mockClear(); sinkMocks.remoteSink.mockClear(); diff --git a/skills/bailian-finetune/reference/dataset.md b/skills/bailian-finetune/reference/dataset.md index 061bd6d61..df8769504 100644 --- a/skills/bailian-finetune/reference/dataset.md +++ b/skills/bailian-finetune/reference/dataset.md @@ -296,7 +296,7 @@ bl dataset split --input labeled.jsonl --dev-ratio 0.2 --dry-run | Flag | Type | Required | Description | | ------------------ | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `--file ` | string | yes | Local dataset file (.jsonl or .zip; ≤200MB SFT/DPO, ≤300MB CPT/decision, ≤2GB media zip) | +| `--file ` | string | yes | Local dataset file (.jsonl or .zip; ≤300MB text/CPT/decision/TTS, ≤1GB image/video zip) | | `--purpose ` | string | no | Dataset purpose tag (default: "fine-tune") | | `--schema ` | string | no | Record schema: "chatml" (SFT), "dpo" (chosen/rejected), "cpt" (raw text), "decision" (state/questions), "tts" (audio), "image" (image generation), or "video" (video generation). Default auto-detects per record. | | `--no-validate` | switch | no | Skip the local JSONL pre-flight check (not recommended) | @@ -308,7 +308,7 @@ bl dataset split --input labeled.jsonl --dev-ratio 0.2 --dry-run - Supports .jsonl (text/decision) and .zip (audio/image/video archives with a data.jsonl manifest). Seven record schemas are recognized: chatml = {messages:[...]} (SFT); dpo = {messages:[...], chosen, rejected}; cpt = {text:"..."}; decision = {state:{content}, questions:{...}}; tts = {wav_fn:"train/xxx.wav", text:"..."}; image = {img_path:"..."}; video = {first_frame_path:...}. - With no --schema, state/questions is validated as decision data, wav_fn as TTS, img_path as image, chosen/rejected as DPO, text (no messages) as CPT, otherwise ChatML. -- Upload cap: 200MB SFT/DPO text, 300MB CPT/decision data, 2GB media zip. For decision files over 200MB, pass --schema decision so the correct cap is applied. Upload uses the OpenAI-compatible /compatible-mode/v1/files endpoint so the purpose tag is persisted. +- Upload cap: 300MB for text, CPT, decision and TTS data; 1GB for image/video ZIPs. Without --schema, ZIP archives are sniffed from their first data.jsonl record so image/video ZIPs get 1GB automatically; pass --schema only to override. Upload uses the OpenAI-compatible /compatible-mode/v1/files endpoint so the purpose tag is persisted. #### Examples @@ -363,6 +363,7 @@ bl dataset upload --file train.jsonl --no-validate - Schemas: chatml = {messages:[...]}; dpo = {messages:[...], chosen, rejected}; cpt = {text:"..."}; decision = {state:{content}, questions:{...}}; tts = {wav_fn:"train/xxx.wav", text:"..."}; image = {img_path:"..."}; video = {first_frame_path:"...", video_path:"..."}. - With no --schema, state/questions is validated as decision data, wav_fn as TTS, img_path as image, first_frame_path/video_path as video, chosen/rejected as DPO, text (no messages) as CPT, otherwise ChatML. - ZIP archives (.zip) are validated structurally (data.jsonl present, media references resolve) in addition to per-record content checks. Use --full-validate to JSON.parse every line. +- Size cap follows --schema, same as dataset upload: 300MB for text, CPT, decision and TTS data; 1GB for image/video ZIPs. Without --schema, ZIP archives are sniffed from their first data.jsonl record so image/video ZIPs get 1GB automatically. #### Examples diff --git a/skills/bailian-finetune/reference/finetune.md b/skills/bailian-finetune/reference/finetune.md index d99734b2d..a64681bb8 100644 --- a/skills/bailian-finetune/reference/finetune.md +++ b/skills/bailian-finetune/reference/finetune.md @@ -1286,31 +1286,33 @@ bl finetune preset-datasets --base-model qwen3-8b --dry-run ### `bl finetune price` -| Field | Value | -| ------------------ | --------------------------------------------------------------------------------------------------- | -| **Name** | `finetune price` | -| **Description** | Estimate the training cost for a fine-tune job (token billing) | -| **Authentication** | Console | -| **Usage** | `bl finetune price --base-model --datasets [--training-type ] [--n-epochs ]` | +| Field | Value | +| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `finetune price` | +| **Description** | Estimate the training cost for a fine-tune job (token billing) | +| **Authentication** | Console | +| **Usage** | `bl finetune price --base-model --datasets [--training-type ] [--n-epochs ] [--batch-size ] [--max-length ]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------------ | ------ | -------- | ------------------------------------------------------------------ | -| `--base-model ` | string | yes | Base model to fine-tune (e.g. qwen3-8b; not the output model name) | -| `--datasets ` | string | yes | Training dataset file IDs, comma-separated (required) | -| `--training-type ` | string | no | Training type: sft \| dpo \| cpt (default: sft) | -| `--n-epochs ` | number | no | Number of training epochs (default: 3) | -| `--console-region ` | string | no | Console gateway region (e.g. cn-beijing, ap-southeast-1) | -| `--console-site ` | string | no | Console site: domestic, international | -| `--console-switch-agent ` | number | no | Switch agent UID for delegated access | -| `--workspace-id ` | string | no | Workspace ID (env: BAILIAN_WORKSPACE_ID) | +| Flag | Type | Required | Description | +| ------------------------------ | ------ | -------- | --------------------------------------------------------------------------------------------- | +| `--base-model ` | string | yes | Base model to fine-tune (e.g. qwen3-8b; not the output model name) | +| `--datasets ` | string | yes | Training dataset file IDs, comma-separated (required) | +| `--training-type ` | string | no | Training type: sft \| dpo \| cpt (default: sft) | +| `--n-epochs ` | number | no | Number of training epochs (default: 3) | +| `--batch-size ` | number | no | Batch size used for estimation (default: 16); match the planned create request | +| `--max-length ` | number | no | Maximum sequence length used for estimation (default: 8192); match the planned create request | +| `--console-region ` | string | no | Console gateway region (e.g. cn-beijing, ap-southeast-1) | +| `--console-site ` | string | no | Console site: domestic, international | +| `--console-switch-agent ` | number | no | Switch agent UID for delegated access | +| `--workspace-id ` | string | no | Workspace ID (env: BAILIAN_WORKSPACE_ID) | #### Notes - Estimate only — the server computes token usage from the datasets; final cost is subject to the bill. - Covers token billing for sft / dpo / cpt. Training-unit (MTU) billing is not supported by this command. -- Hyper-parameters other than --n-epochs are fixed at representative defaults for estimation. +- Pass the same --n-epochs, --batch-size and --max-length as the planned create request. Other hyper-parameters use fixed estimation defaults; mixed-data coverage is determined by the server response. #### Examples @@ -1319,11 +1321,11 @@ bl finetune price --base-model qwen3-8b --datasets file-ft-xxx ``` ```bash -bl finetune price --base-model qwen3-8b --datasets file-ft-xxx,file-ft-yyy --n-epochs 2 +bl finetune price --base-model qwen3-8b --datasets file-ft-xxx,file-ft-yyy --n-epochs 2 --batch-size 32 --max-length 4096 ``` ```bash -bl finetune price --base-model qwen3-8b --datasets file-ft-xxx --training-type cpt +bl finetune price --base-model qwen3-8b --datasets file-ft-xxx --training-type cpt --batch-size 16 --max-length 16384 ``` ### `bl finetune rl authorize` @@ -1582,6 +1584,7 @@ bl finetune rl logs --job-id rl-xxx --offset 0 --lines 100 #### Notes - Runs inside an isolated sandbox. Prepare the runtime first with `finetune runtime prepare`, or pass --install-runtime. +- max_prompt_length must be smaller than max_length so generated responses have room. This is checked after merging YAML and --hp, including during --dry-run. - Timing out with --watch stops waiting only; it does not cancel the cloud job. #### Examples @@ -1811,7 +1814,7 @@ bl finetune runtime prepare --dry-run - --datasets / --validations accept either file-ids (from `dataset upload`) or local paths. Local paths are validated and uploaded first, then their file-ids are submitted — a one-step upload-and-train. - Training-type values use the `` / `-lora` convention: sft (full) | sft-lora (LoRA) | dpo (full) | dpo-lora (LoRA) | cpt. These map to the server's training_type at the interface boundary, so the rest of the CLI never sees the raw server strings. - Before submitting (non dry-run) the job, the model's training capability is checked via listFoundationModels (no console login required); an unsupported training type fails fast with the list the model actually supports. -- Before upload, the command queries the selected model and training type's parameter schema. Explicit overrides must satisfy its editability, type, enum, range, and step constraints. The create API requires n_epochs, batch_size and max_length: an omitted one is filled from the schema's default (query it with the finetune params command); every other omitted value uses the platform default. +- Before upload, the command queries the selected model and training type's parameter schema. Explicit overrides must satisfy its editability, type, enum, range, and step constraints. When the schema declares batch_size as intInputNumber, text creation also requires a positive power of two. The create API requires n_epochs, batch_size and max_length: an omitted one is filled from the schema's default or explicitly marked recommendation; every other omitted value uses the platform default. Dry-run includes parameter_sources so user, schema default, schema recommendation and profile-default values remain distinguishable. - Learning rate is forwarded as a string to avoid JSON-number precision loss. - Pre-submit gate: if the training dataset's sample count is not greater than batch_size, the job is rejected before upload or quota consumption (the platform would otherwise fail ~10 min in, after data processing). - --modality / --reasoning-mode are training options forwarded as hyper_parameters entries, independent of the dataset format fixed by the subcommand. Models with dynamic train options require them to resolve the parameter schema (e.g. a vision-only CPT base needs --modality vision); models without dynamic options reject them. Invalid combinations are rejected by the server and surfaced as-is. From cee2e11b6e453e6c3d90716c213dde6659b9bbca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=95=85=E7=92=83?= Date: Tue, 1 Dec 2026 14:37:26 +0800 Subject: [PATCH 2/2] chore(release): prepare 2.14.1 --- CHANGELOG.md | 18 ++++++++++++++++++ CHANGELOG.zh.md | 18 ++++++++++++++++++ packages/bailian-kb-dsh/package.json | 2 +- packages/bailian-memo-dsh/package.json | 2 +- packages/cli/package.json | 2 +- packages/commands/package.json | 2 +- packages/core/package.json | 2 +- packages/kscli/package.json | 2 +- packages/runtime/package.json | 2 +- skills/bailian-cli/SKILL.md | 2 +- skills/bailian-finetune/SKILL.md | 2 +- skills/bailian-gen/SKILL.md | 2 +- skills/bailian-knowledge/SKILL.md | 2 +- skills/bailian-managed-agent/SKILL.md | 2 +- skills/bailian-memory/SKILL.md | 2 +- skills/bailian-opd/SKILL.md | 2 +- skills/bailian-protocol/SKILL.md | 2 +- skills/bailian-sandbox/SKILL.md | 2 +- skills/bailian-web-search/SKILL.md | 2 +- 19 files changed, 53 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c97b4274e..b4419d4d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and [中文版](CHANGELOG.zh.md) · [README](README.md) · [Contributing](CONTRIBUTING.md) +## [2.14.1] - 2026-12-01 + +### Added + +- **Hyper-parameter provenance**: `bl finetune create` output adds `parameter_sources`, reporting for every hyper-parameter whether it came from the user, the parameter schema default or recommended value, a train option default, or the training profile. +- **`bl finetune price` cost inputs**: new `--batch-size` and `--max-length` flags align the estimate with the planned create request; the result reports the `hyper_parameters` used for the estimate. + +### Changed + +- **Dataset upload caps**: fine-tune datasets (text, CPT, decision, TTS) now accept files up to 300 MB (was 200 MB); image and video ZIPs accept up to 1 GB (was 2 GB), matching the official upload rules. Without `--schema`, ZIP archives are inspected from their first `data.jsonl` record so image and video archives get the 1 GB cap automatically; pass `--schema image|video` when detection fails. Applies to `bl dataset upload` and `bl dataset validate`. +- **`batch_size` power of two**: `bl finetune text create` rejects a `batch_size` that is not a positive power of two when the parameter schema declares an integer input. +- **RL `max_prompt_length`**: `bl finetune rl run` rejects `max_prompt_length >= max_length` after merging the YAML spec and `--hp`; `--dry-run` runs the same check. +- **Console workspace hint**: when `--workspace-id` does not match an accessible workspace, the error hint lists the requested ID, the match count and up to 10 accessible workspace IDs. + +### Fixed + +- **Dataset upload errors**: `bl dataset upload` now reports the rejected file, server code and rejected count when the server returns `failed_uploads`, and lists the response key layout when no file ID is returned. Oversize errors report the exact file size and cap; unsupported formats name the file. + ## [2.14.0] - 2026-11-27 ### Added diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index 6c5fbaaea..316e7a674 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -6,6 +6,24 @@ [English](CHANGELOG.md) · [README](README.zh.md) · [参与贡献](CONTRIBUTING.zh.md) +## [2.14.1] - 2026-12-01 + +### 新增 + +- **超参来源**:`bl finetune create` 输出新增 `parameter_sources`,逐个超参标明取值来源:用户指定、参数配置默认值或推荐值、训练选项默认值、训练 Profile 默认值。 +- **`bl finetune price` 估价参数**:新增 `--batch-size` 与 `--max-length`,使估价与计划创建任务参数一致;结果新增估价所用的 `hyper_parameters`。 + +### 变更 + +- **数据集上传上限**:文本、CPT、decision、TTS 微调数据集上限改为 300 MB(原 200 MB);图像、视频 ZIP 改为 1 GB(原 2 GB),与官方上传规则对齐。未传 `--schema` 时,从 ZIP 内第一条 `data.jsonl` 记录识别内容,图像、视频 ZIP 自动采用 1 GB;识别失败时请传 `--schema image|video`。适用于 `bl dataset upload` 与 `bl dataset validate`。 +- **`batch_size` 2 的幂校验**:参数配置声明为整数输入时,`bl finetune text create` 会拒绝不是正的 2 的幂的 `batch_size`。 +- **RL `max_prompt_length`**:`bl finetune rl run` 在合并 YAML 与 `--hp` 后校验 `max_prompt_length >= max_length` 并拒绝;`--dry-run` 同样生效。 +- **Console 工作空间提示**:`--workspace-id` 未匹配到可访问工作空间时,错误提示会列出请求的 ID、命中数量及最多 10 个可访问的工作空间 ID。 + +### 修复 + +- **数据集上传报错**:服务端返回 `failed_uploads` 时,`bl dataset upload` 会报出被拒文件、服务端错误码与被拒数量;未返回文件 ID 时列出响应字段结构。超限报错给出精确的文件大小与上限;不支持的格式会带出文件名。 + ## [2.14.0] - 2026-11-27 ### 新增 diff --git a/packages/bailian-kb-dsh/package.json b/packages/bailian-kb-dsh/package.json index 6984a8563..7c650aae8 100644 --- a/packages/bailian-kb-dsh/package.json +++ b/packages/bailian-kb-dsh/package.json @@ -1,6 +1,6 @@ { "name": "bailian-kb-dsh", - "version": "2.14.0", + "version": "2.14.1", "description": "Bailian knowledge-base tools for DeepSeek Harness: kb_search and kb_chat over the DashScope RAG API, plus the bl CLI management skill.", "keywords": [ "alibaba-cloud", diff --git a/packages/bailian-memo-dsh/package.json b/packages/bailian-memo-dsh/package.json index 9e4030ca3..e5ad839c7 100644 --- a/packages/bailian-memo-dsh/package.json +++ b/packages/bailian-memo-dsh/package.json @@ -1,6 +1,6 @@ { "name": "bailian-memo-dsh", - "version": "2.14.0", + "version": "2.14.1", "description": "Bailian personal memory for DeepSeek Harness: automatic recall, silent curation, and user-controlled remember/forget.", "keywords": [ "alibaba-cloud", diff --git a/packages/cli/package.json b/packages/cli/package.json index f9249ca2b..724de7322 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli", - "version": "2.14.0", + "version": "2.14.1", "description": "CLI for Aliyun Model Studio (DashScope) AI Platform.", "keywords": [ "agent", diff --git a/packages/commands/package.json b/packages/commands/package.json index 985baa15b..5475a4c18 100644 --- a/packages/commands/package.json +++ b/packages/commands/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-commands", - "version": "2.14.0", + "version": "2.14.1", "description": "Command library for bailian-cli products (knowledge, memory, media, …). See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/core/package.json b/packages/core/package.json index 1d663ee5a..fb8a53196 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-core", - "version": "2.14.0", + "version": "2.14.1", "description": "Core SDK for bailian-cli. See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/kscli/package.json b/packages/kscli/package.json index 9bd1bed13..1426f968e 100644 --- a/packages/kscli/package.json +++ b/packages/kscli/package.json @@ -1,6 +1,6 @@ { "name": "knowledge-studio-cli", - "version": "2.14.0", + "version": "2.14.1", "description": "Lightweight RAG CLI for Aliyun Model Studio — focused on knowledge-base retrieval.", "keywords": [ "alibaba-cloud", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 5dbcc4870..820beb839 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-runtime", - "version": "2.14.0", + "version": "2.14.1", "description": "Runtime framework for bailian-cli (createCli, registry, args, output, pipeline). See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/skills/bailian-cli/SKILL.md b/skills/bailian-cli/SKILL.md index 3310be336..a3659a0a9 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-cli metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-finetune/SKILL.md b/skills/bailian-finetune/SKILL.md index d621971ba..af23b3a9f 100644 --- a/skills/bailian-finetune/SKILL.md +++ b/skills/bailian-finetune/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-finetune metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index ffd0cd901..b0163b7a1 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-gen metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-knowledge/SKILL.md b/skills/bailian-knowledge/SKILL.md index a5f850afe..d646060fc 100644 --- a/skills/bailian-knowledge/SKILL.md +++ b/skills/bailian-knowledge/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-knowledge metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-managed-agent/SKILL.md b/skills/bailian-managed-agent/SKILL.md index 313307f0e..c9edb0010 100644 --- a/skills/bailian-managed-agent/SKILL.md +++ b/skills/bailian-managed-agent/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-managed-agent metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-memory/SKILL.md b/skills/bailian-memory/SKILL.md index bae973077..6314a7175 100644 --- a/skills/bailian-memory/SKILL.md +++ b/skills/bailian-memory/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-memory metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-opd/SKILL.md b/skills/bailian-opd/SKILL.md index caa192ca6..a30ad2d4e 100644 --- a/skills/bailian-opd/SKILL.md +++ b/skills/bailian-opd/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-opd metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl", "node"] description: >- diff --git a/skills/bailian-protocol/SKILL.md b/skills/bailian-protocol/SKILL.md index 1250d2b8a..24ef2f2d4 100644 --- a/skills/bailian-protocol/SKILL.md +++ b/skills/bailian-protocol/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-protocol metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-sandbox/SKILL.md b/skills/bailian-sandbox/SKILL.md index 44479d86b..a55aa6ae5 100644 --- a/skills/bailian-sandbox/SKILL.md +++ b/skills/bailian-sandbox/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-sandbox metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-web-search/SKILL.md b/skills/bailian-web-search/SKILL.md index ae78d608c..22af90fa4 100644 --- a/skills/bailian-web-search/SKILL.md +++ b/skills/bailian-web-search/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-web-search metadata: - version: "2.14.0" + version: "2.14.1" requires: bins: ["bl"] description: >-