diff --git a/CHANGELOG.md b/CHANGELOG.md index 315510771..f141bbaa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and [中文版](CHANGELOG.zh.md) · [README](README.md) · [Contributing](CONTRIBUTING.md) +## [2.12.1] - 2026-11-27 + +### Added + +- **`bl finetune preset-datasets`**: New command listing the preset datasets that can be mixed into a fine-tuning job for a base model and training type (`--base-model`, `--training-type`, optional `--model-version`). Entries keep the server fields verbatim (`dataset_code`, `dataset_title`, `dataset_desc`); an empty result is a success. +- **Mixed training**: `bl finetune text create` accepts `--augmentation-types` (preset dataset codes, sent lowercased) and `--augmentation-ratio` (one ratio per type, `0.0`–`2.0`; the two flags must be given together). Passing types turns on data augmentation. +- **OSS-mounted datasets**: `--datasets` / `--validations` of `bl finetune text create` accept `oss:///` entries that the service reads in place, skipping local validation, upload and the sample-count pre-check. `--oss-region` sets the bucket region (default `cn-beijing`) and is sent as given. + +### Changed + +- **`bl finetune train-options` status**: the result carries a `status` that explains a null `training_options`: `configured`, `not_configured` (the model is confirmed in the trainable catalog and has no dynamic options) or `unverified` (no options were returned and the catalog lookup failed). A model id that is not in the catalog now fails with a usage error instead of returning null, and an unrecognized response shape is reported as an error. + +### Fixed + +- **Required hyper-parameters**: `bl finetune text create` fills an omitted `n_epochs`, `batch_size` or `max_length` from the model's parameter schema defaults; the create API rejects a job when one of them is missing. + ## [2.12.0] - 2026-11-25 ### Added diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index fd6d5a04d..cee63087c 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -6,6 +6,22 @@ [English](CHANGELOG.md) · [README](README.zh.md) · [参与贡献](CONTRIBUTING.zh.md) +## [2.12.1] - 2026-11-27 + +### 新增 + +- **`bl finetune preset-datasets`**:新增命令,查询指定基础模型与训练类型下可混入训练的预置数据集(`--base-model`、`--training-type`、可选 `--model-version`)。结果原样保留服务端字段(`dataset_code`、`dataset_title`、`dataset_desc`);结果为空属于成功。 +- **混合训练**:`bl finetune text create` 新增 `--augmentation-types`(预置数据集编码,按小写下发)与 `--augmentation-ratio`(按位置对应每种数据集的混合倍率,范围 0.0~2.0,两者必须同时提供)。传入 `--augmentation-types` 即开启数据增强。 +- **OSS 挂数据集**:`bl finetune text create` 的 `--datasets` / `--validations` 支持 `oss:///` 条目,由服务端原地读取,不做本地校验、不上传,并跳过样本数预检。`--oss-region` 指定 Bucket 所在地域(默认 `cn-beijing`),原样下发。 + +### 变更 + +- **`bl finetune train-options` 的 status**:结果新增 `status` 字段,说明 `training_options` 为 null 的原因:`configured`(返回了选项)、`not_configured`(模型已在可训练目录中确认存在但没有动态选项)、`unverified`(未返回选项且目录查询失败)。模型 ID 不在目录中时改为报用法错误,不再返回 null;无法识别的响应结构也会报错。 + +### 修复 + +- **必填超参数**:`bl finetune text create` 未指定 `n_epochs`、`batch_size` 或 `max_length` 时,按模型参数配置中的默认值补齐;创建任务接口在缺少这三项时会拒绝任务。 + ## [2.12.0] - 2026-11-25 ### 新增 diff --git a/docs/agents/command-flag-change.md b/docs/agents/command-flag-change.md index 5ddffc005..36c15d84f 100644 --- a/docs/agents/command-flag-change.md +++ b/docs/agents/command-flag-change.md @@ -63,3 +63,4 @@ pnpm -F bailian-cli exec tsx src/main.ts --new-flag x # 实测一遍 - ✗ 改默认值忘记更新 description 里的 "(default: xxx)" 文案 - ✗ 在 `usageArgs` / `exampleArgs` 里写死 `bl `,导致其它产品入口复用时 help 错 - ✗ required flag 缺失又在 `run()` 里重复手写校验,与 parser/`validate` 的错误文案不一致 +- ✗ 给 `finetune create` 加 `hyper_parameters` flag 时,把它登记进 `explicitHyperParameterOverrides` 就会对照模型参数 schema 校验;API 文档有、但 `finetune params` 实测 schema 不返回的参数(如混合训练的 `data_augmentation` / `augmentation_types` / `augmentation_ratio`)必须绕过该校验交给服务端裁决,否则 flag 一用就报 unsupported。加这类 flag 前先用真实模型查一次 `--param-type hyper` diff --git a/packages/bailian-kb-dsh/package.json b/packages/bailian-kb-dsh/package.json index e0889c5d8..6f64f7039 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.12.0", + "version": "2.12.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 c7c71de90..dd718443c 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.12.0", + "version": "2.12.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 b901c0348..071fd5312 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli", - "version": "2.12.0", + "version": "2.12.1", "description": "CLI for Aliyun Model Studio (DashScope) AI Platform.", "keywords": [ "agent", diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 2a4438bb9..6243f0498 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -212,6 +212,7 @@ import { finetunePrice, finetuneParams, finetuneTrainOptions, + finetunePresetDatasets, finetuneMetrics, finetuneCompressTemplates, finetuneCompressCreate, @@ -616,6 +617,7 @@ export const commands: Record = { "finetune price": finetunePrice, "finetune params": finetuneParams, "finetune train-options": finetuneTrainOptions, + "finetune preset-datasets": finetunePresetDatasets, "finetune metrics": finetuneMetrics, "finetune compress templates": finetuneCompressTemplates, "finetune compress create": finetuneCompressCreate, diff --git a/packages/commands/package.json b/packages/commands/package.json index d6bd14198..46d0f10b9 100644 --- a/packages/commands/package.json +++ b/packages/commands/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-commands", - "version": "2.12.0", + "version": "2.12.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/commands/src/commands/finetune/create.ts b/packages/commands/src/commands/finetune/create.ts index 7c18652ae..e3746e9c9 100644 --- a/packages/commands/src/commands/finetune/create.ts +++ b/packages/commands/src/commands/finetune/create.ts @@ -9,28 +9,60 @@ import { preflightBatchSizeGate, validateFineTuneHyperParameterOverrides, getFineTuneHyperParameterDefaultNumber, - isTrainingTypeCli, - TRAINING_TYPES_CLI, DEFAULT_TRAINING_TYPE, preflightDecisionSampleGate, readDecisionQuestionSignature, compareDecisionQuestionTables, BailianError, ExitCode, + buildOssMountDataset, + DEFAULT_OSS_MOUNT_REGION, + isOssMountToken, + parseOssMountUri, type HttpDeps, type CommandContext, type CreateFineTuneRequest, + type FineTuneDatasetDescriptor, type FineTuneHyperParameters, type FineTuneHyperParameterIssue, type DataModality, + type FineTuneParamHyperParam, type FlagsDef, + type LocalizedText, + type ParsedFlags, } from "bailian-cli-core"; -import { analyzeDatasetTokens, isLocalPath, uploadResolvedLocal } from "./dataset-input.ts"; -import { preflightTrainOptions } from "./train-options-shared.ts"; +import { + analyzeDatasetTokens, + isLocalPath, + splitDatasetEntries, + uploadResolvedLocal, + type AnalyzeDatasetOptions, + type ResolvedDataset, +} from "./dataset-input.ts"; +import { + preflightTrainOptions, + resolveTrainingTypeCli, + trainOptionFlags, + trainingTypeFlag, + type HelpClause, +} from "./train-options-shared.ts"; + +/** How `finetune text create` phrases the CLI-to-server training-type mapping. */ +const CREATE_TRAINING_TYPE_MAPPING: HelpClause = { + "en-US": + "Mapping to the server happens at the interface boundary (e.g. sft-lora -> efficient_sft, dpo -> dpo_full)", + "zh-CN": "在接口边界转换为服务端值(例如 sft-lora -> efficient_sft、dpo -> dpo_full)", +}; /** The modality a `finetune create` subcommand is bound to. */ type CommandModality = "text" | "audio" | "image" | "video" | "decision"; +/** + * Explicit hyper-parameter overrides to check against the model's parameter + * schema. Mixed-training parameters (data_augmentation / augmentation_types / + * augmentation_ratio) are deliberately absent: they are documented on the + * create API but missing from the schema, so the server stays the authority. + */ function explicitHyperParameterOverrides( commandModality: CommandModality, flags: Record, @@ -53,7 +85,6 @@ function explicitHyperParameterOverrides( saveSteps: "save_steps", split: "split", maxSplitValDatasetSample: "max_split_val_dataset_sample", - dataAugmentation: "data_augmentation", }, image: { learningRate: "learning_rate" }, video: { @@ -73,12 +104,147 @@ function explicitHyperParameterOverrides( for (const [flagName, parameterName] of Object.entries(mappings[commandModality])) { const value = flags[flagName]; if (value !== undefined) { - overrides[parameterName] = flagName === "dataAugmentation" ? value === "true" : value; + overrides[parameterName] = value; } } return overrides; } +/** + * Cross-flag rules for mixed training. Runs in `validate`, before auth and + * dataset analysis, so an invalid pair never reaches the network. + */ +function validateMixedTrainingFlags( + flags: ParsedFlags, +): LocalizedText | undefined { + if (flags.augmentationTypes === undefined && flags.augmentationRatio === undefined) { + return undefined; + } + if (flags.augmentationTypes === undefined || flags.augmentationRatio === undefined) { + return { + "en-US": "--augmentation-types and --augmentation-ratio must be provided together.", + "zh-CN": "--augmentation-types 与 --augmentation-ratio 必须同时提供。", + }; + } + if (flags.dataAugmentation === "false") { + return { + "en-US": "--augmentation-types cannot be combined with --data-augmentation false.", + "zh-CN": "--augmentation-types 不能与 --data-augmentation false 同时使用。", + }; + } + const codes = splitCsv(flags.augmentationTypes); + const ratios = splitCsv(flags.augmentationRatio); + if (codes.includes("") || ratios.includes("")) { + return { + "en-US": "--augmentation-types / --augmentation-ratio must not contain empty items.", + "zh-CN": "--augmentation-types / --augmentation-ratio 不能包含空项。", + }; + } + if (codes.length !== ratios.length) { + return { + "en-US": `--augmentation-ratio must give one ratio per --augmentation-types entry (${codes.length} types, ${ratios.length} ratios).`, + "zh-CN": `--augmentation-ratio 须与 --augmentation-types 逐项对应(${codes.length} 项,${ratios.length} 个倍率)。`, + }; + } + for (const ratio of ratios) { + const numeric = Number(ratio); + if (!Number.isFinite(numeric) || numeric < 0 || numeric > 2) { + return { + "en-US": `--augmentation-ratio "${ratio}" must be within [0, 2].`, + "zh-CN": `--augmentation-ratio "${ratio}" 必须在 0.0~2.0 之间。`, + }; + } + } + return undefined; +} + +function splitCsv(raw: string): string[] { + return raw.split(",").map((item) => item.trim()); +} + +/** + * `oss://` entries of --datasets / --validations, checked in `validate` before + * auth: the data is not on disk, so this shape check is the only local check a + * mount gets. The bucket and key themselves are judged by the server. + */ +function validateOssMountEntries(flags: ParsedFlags): LocalizedText | undefined { + for (const flagName of ["datasets", "validations"] as const) { + const raw = flags[flagName]; + if (raw === undefined) continue; + for (const entry of splitDatasetEntries(raw)) { + if (!isOssMountToken(entry)) continue; + const mount = parseOssMountUri(entry); + if (!mount.valid) { + return { + "en-US": `--${flagName} entry "${entry}" ${mount.reason["en-US"]}`, + "zh-CN": `--${flagName} 条目 "${entry}" ${mount.reason["zh-CN"]}`, + }; + } + } + } + return undefined; +} + +/** + * Dataset entries of one field: file-ids first, then mounts. The order across + * the two kinds carries no meaning. + */ +function datasetEntries(resolved: ResolvedDataset, region: string): FineTuneDatasetDescriptor[] { + return [ + ...resolved.fileIds.map((fileId) => ({ + data_source_type: "file_id" as const, + file_id: fileId, + })), + ...resolved.ossMounts.map((location) => buildOssMountDataset(location, region)), + ]; +} + +/** + * Mixed training. `augmentation_types` names the preset datasets to mix in + * and `augmentation_ratio` gives one ratio per type; the server is the + * authority for both. Codes are sent lowercased: the preset-datasets API + * returns e.g. `mix_V2` while the documented API values are lowercase. + * Cross-flag rules were already enforced by `validateMixedTrainingFlags`. + */ +function applyDataAugmentation(hp: FineTuneHyperParameters, flags: Record): void { + const typesRaw = + typeof flags.augmentationTypes === "string" ? flags.augmentationTypes : undefined; + const ratiosRaw = + typeof flags.augmentationRatio === "string" ? flags.augmentationRatio : undefined; + if (typesRaw === undefined || ratiosRaw === undefined) { + if (flags.dataAugmentation !== undefined) + hp.data_augmentation = flags.dataAugmentation === "true"; + return; + } + hp.data_augmentation = true; + hp.augmentation_types = splitCsv(typesRaw) + .map((code) => code.toLowerCase()) + .join(","); + hp.augmentation_ratio = splitCsv(ratiosRaw).join(","); +} + +/** + * The create API requires these (they drive the training cost) and rejects the + * job when one is missing. + */ +const COST_REQUIRED_HYPER_PARAMETERS = ["n_epochs", "batch_size", "max_length"] as const; + +/** + * Fill a cost-driving parameter the user omitted with the model's schema + * default. A parameter the schema lists without a usable default, or omits + * entirely, is left alone for the server to judge; no value is invented here. + */ +function applySchemaDefaultHyperParameters( + hp: FineTuneHyperParameters, + parameterSchema: FineTuneParamHyperParam[], +): void { + for (const parameterName of COST_REQUIRED_HYPER_PARAMETERS) { + if (hp[parameterName] !== undefined) continue; + const defaultValue = getFineTuneHyperParameterDefaultNumber(parameterSchema, parameterName); + if (defaultValue !== undefined) hp[parameterName] = defaultValue; + } +} + export function formatHyperParameterIssue( context: Pick, issue: FineTuneHyperParameterIssue, @@ -179,6 +345,37 @@ const COMMON_FLAGS = { */ const TEXT_FLAGS = { ...COMMON_FLAGS, + // Text alone can mount a dataset from OSS, so its data flags say so. + datasets: { + ...COMMON_FLAGS.datasets, + valueHint: "", + description: { + "en-US": + "Comma-separated dataset file IDs, local paths (.jsonl) or OSS mounts (oss:///). Local paths are uploaded (validated) first, then their file-ids are used. An OSS mount is read in place by the service, so it is not validated or uploaded here", + "zh-CN": + "数据集文件 ID、本地路径(.jsonl)或 OSS 挂载(oss:///),以逗号分隔。本地路径会先验证并上传,再使用对应的 file-id。OSS 挂载由服务端原地读取,CLI 不做本地校验和上传", + }, + }, + validations: { + ...COMMON_FLAGS.validations, + valueHint: "", + description: { + "en-US": + "Comma-separated validation dataset file IDs, local paths or OSS mounts (oss:///), handled like --datasets", + "zh-CN": + "验证数据集文件 ID、本地路径或 OSS 挂载(oss:///),以逗号分隔,处理方式与 --datasets 相同", + }, + }, + ossRegion: { + type: "string", + valueHint: "", + description: { + "en-US": + "Region ID of the OSS buckets mounted by the oss:// entries of --datasets / --validations (default: cn-beijing); sent as given, whether the service can mount from it is judged by the service", + "zh-CN": + "--datasets / --validations 中 oss:// 条目所在 OSS Bucket 的地域 ID(默认:cn-beijing);原样下发,能否挂载由服务端判断", + }, + }, jobName: { type: "string", valueHint: "", @@ -264,21 +461,36 @@ const TEXT_FLAGS = { }, dataAugmentation: { type: "string", - valueHint: "", + valueHint: "", description: { - "en-US": "Mix platform training data (true or false)", - "zh-CN": "是否混入平台训练数据(true 或 false)", + "en-US": + "Mix platform preset training data into the job (true or false). Only honored for sft and sft-lora; turned on automatically by --augmentation-types", + "zh-CN": + "是否混入平台预置训练数据(true 或 false)。仅 sft 与 sft-lora 生效;传 --augmentation-types 时自动开启", }, choices: ["true", "false"] as const, }, - trainingType: { + augmentationTypes: { type: "string", - valueHint: "", + valueHint: "", description: { - "en-US": `Training type: ${TRAINING_TYPES_CLI.join(" | ")} (default: ${DEFAULT_TRAINING_TYPE}). Mapping to the server happens at the interface boundary (e.g. sft-lora -> efficient_sft, dpo -> dpo_full).`, - "zh-CN": `训练类型:${TRAINING_TYPES_CLI.join(" | ")}(默认:${DEFAULT_TRAINING_TYPE})。在接口边界转换为服务端值(例如 sft-lora -> efficient_sft、dpo -> dpo_full)。`, + "en-US": + "Preset datasets to mix in, comma-separated. Codes come from finetune preset-datasets and are sent lowercased (e.g. mix_V2 -> mix_v2). Requires --augmentation-ratio", + "zh-CN": + "要混入的预置数据集,以逗号分隔。编码来自 finetune preset-datasets,按小写下发(例如 mix_V2 -> mix_v2)。需与 --augmentation-ratio 同时使用", }, }, + augmentationRatio: { + type: "string", + valueHint: "", + description: { + "en-US": + "Mix ratio per preset dataset, comma-separated and positionally matching --augmentation-types; each is 0.0~2.0 of the training data volume", + "zh-CN": + "每种预置数据集的混合倍率,以逗号分隔并与 --augmentation-types 按位置对应;每项为训练数据量的 0.0~2.0 倍", + }, + }, + trainingType: trainingTypeFlag(DEFAULT_TRAINING_TYPE, CREATE_TRAINING_TYPE_MAPPING), nEpochs: { type: "number", valueHint: "", @@ -308,28 +520,20 @@ const TEXT_FLAGS = { valueHint: "", description: { "en-US": "Max sequence length", "zh-CN": "最大序列长度" }, }, - modality: { - type: "string", - valueHint: "", - description: { + ...trainOptionFlags({ + modality: { "en-US": "Training-option modality sent as hyper_parameters.modality (not the dataset format fixed by this subcommand). Only for models with dynamic train options; valid values come from the model's parameter schema.", "zh-CN": "训练选项模态,作为 hyper_parameters.modality 发送(与本子命令固定的数据格式无关)。仅适用于配置了动态训练选项的模型;合法值以该模型的参数配置为准。", }, - choices: ["text", "vision"] as const, - }, - reasoningMode: { - type: "string", - valueHint: "", - description: { + reasoningMode: { "en-US": "Reasoning mode sent as hyper_parameters.reasoning_mode. Only for models with dynamic train options; valid values come from the model's parameter schema.", "zh-CN": "思考模式,作为 hyper_parameters.reasoning_mode 发送。仅适用于配置了动态训练选项的模型;合法值以该模型的参数配置为准。", }, - choices: ["instruct", "thinking"] as const, - }, + }), } satisfies FlagsDef; /** @@ -373,7 +577,7 @@ const IMAGE_FLAGS = { } satisfies FlagsDef; const TEXT_USAGE = - "--base-model --datasets [--validations ] [--job-name ] [--priority ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ] [--modality ] [--reasoning-mode ]"; + "--base-model --datasets [--validations ] [--oss-region ] [--job-name ] [--priority ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ] [--data-augmentation ] [--augmentation-types ] [--augmentation-ratio ] [--modality ] [--reasoning-mode ]"; const AUDIO_USAGE = "--base-model --datasets [--validations ] [--model-name ] [--suffix ]"; @@ -493,9 +697,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; omitted values use platform defaults.", + "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.", "zh-CN": - "上传前会查询所选模型和训练类型的参数配置。显式覆盖值必须满足可编辑性、类型、枚举、范围和步长约束;未指定项使用平台默认值。", + "上传前会查询所选模型和训练类型的参数配置。显式覆盖值必须满足可编辑性、类型、枚举、范围和步长约束。创建任务 API 要求 n_epochs、batch_size、max_length 必填:未指定时按参数配置中的默认值补齐(可用 finetune params 命令查询);其余未指定项使用平台默认值。", }, { "en-US": "Learning rate is forwarded as a string to avoid JSON-number precision loss.", @@ -513,6 +717,18 @@ const TEXT_NOTES = [ "zh-CN": "--modality / --reasoning-mode 是训练选项,作为 hyper_parameters 条目发送,与子命令固定的数据格式无关。配置了动态训练选项的模型需要它们才能解析参数配置(例如仅支持视觉训练的 CPT 基座需要 --modality vision);未配置动态选项的模型会拒绝这两个 flag。非法组合由服务端拒绝并原样透传错误。", }, + { + "en-US": + "Mixed training: --data-augmentation turns it on; --augmentation-types selects preset datasets (list them with finetune preset-datasets; codes are sent lowercased, e.g. mix_V2 -> mix_v2) and --augmentation-ratio gives one ratio (0.0~2.0) per type, positionally. Passing types turns data_augmentation on. These three are documented on the create API but absent from the model's parameter schema, so they are not part of the schema check; whether the selected model and training type honors them is decided by the server (documented for sft and sft-lora), and mixed data is billed as training tokens.", + "zh-CN": + "混合训练:--data-augmentation 开启;--augmentation-types 选择预置数据集(用 finetune preset-datasets 查询,编码按小写下发,例如 mix_V2 -> mix_v2),--augmentation-ratio 按位置给出每种数据集的混合倍率(0.0~2.0)。传 --augmentation-types 时自动开启 data_augmentation。这三个参数在创建任务的 API 文档中有说明,但不在模型返回的参数配置里,因此不参与参数配置校验;是否对所选模型和训练类型生效以服务端为准(文档为 sft 与 sft-lora),混入的数据按训练 Token 计费。", + }, + { + "en-US": + "OSS mount: an oss:/// entry of --datasets / --validations is read in place, so it skips local validation, upload and the sample-count pre-check. Upload the uncompressed dataset folder to OSS as-is (a zip cannot be mounted) and, for a multi-file dataset, point at its data.jsonl. Every oss:// entry shares --oss-region. A request with an OSS mount sends training_datasets / validation_datasets instead of training_file_ids / validation_file_ids.", + "zh-CN": + "OSS 挂载:--datasets / --validations 中的 oss:/// 条目由服务端原地读取,因此不做本地校验、不上传,也跳过样本数预检。请将未压缩的数据集文件夹原样上传到 OSS(zip 无法挂载);多文件数据集指向其 data.jsonl。所有 oss:// 条目共用 --oss-region。含 OSS 挂载的请求以 training_datasets / validation_datasets 下发,不再使用 training_file_ids / validation_file_ids。", + }, ]; const AUDIO_NOTES = [ @@ -581,14 +797,10 @@ async function runCreate( // enforce the right record schema (DPO jobs require chosen/rejected on // every record). Whitelist is the single source of truth in core // (TRAINING_TYPES_CLI); any other value is rejected up-front. - const trainingType = (flags.trainingType as string | undefined) || DEFAULT_TRAINING_TYPE; - if (!isTrainingTypeCli(trainingType)) { - throw new BailianError( - `--training-type "${trainingType}" is not supported.`, - ExitCode.USAGE, - `Supported values: ${TRAINING_TYPES_CLI.join(", ")} (default: ${DEFAULT_TRAINING_TYPE}).`, - ); - } + const trainingType = resolveTrainingTypeCli( + flags.trainingType as string | undefined, + DEFAULT_TRAINING_TYPE, + ); // Profile: single source of truth for how this training type behaves // (validation rules, hyper-parameters, gates, capability check). @@ -619,6 +831,10 @@ async function runCreate( if (detected === "video-kf2v") modality = "video-kf2v"; } + // Only text can carry a mount: its request switches to the dataset entries + // that hold one. Other modalities keep the flat file-id fields, so analyze + // rejects an oss:// entry there before any request is made. + const datasetOptions: AnalyzeDatasetOptions = { ossMount: commandModality === "text" }; const training = await analyzeDatasetTokens( ctx, datasetsRaw, @@ -627,6 +843,7 @@ async function runCreate( modality, model, firstLocalPath ? { path: firstLocalPath, modality } : undefined, + datasetOptions, ); const trainingFileIds = training.fileIds; @@ -638,6 +855,8 @@ async function runCreate( profile, modality, model, + undefined, + datasetOptions, ) : undefined; const validationFileIds = validation?.fileIds; @@ -715,8 +934,7 @@ async function runCreate( ExitCode.USAGE, ); } - if (flags.dataAugmentation !== undefined) - hp.data_augmentation = flags.dataAugmentation === "true"; + applyDataAugmentation(hp, flags); if (hp.save_strategy === "steps" && hp.save_steps === undefined) { throw new BailianError( "save_strategy=steps requires --save-steps. / 按步保存时必须指定 --save-steps。", @@ -790,6 +1008,12 @@ 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); + } + if ( !settings.dryRun && training.recordCount !== undefined && @@ -896,14 +1120,23 @@ async function runCreate( } } + // A mount cannot travel in the flat file-id fields, so a request with one + // uses the dataset entries for both fields. Every other request keeps the + // flat form it has always sent. + const ossRegion = (flags.ossRegion as string | undefined) ?? DEFAULT_OSS_MOUNT_REGION; + const mountsOss = training.ossMounts.length > 0 || (validation?.ossMounts.length ?? 0) > 0; const body: CreateFineTuneRequest = { model, - training_file_ids: trainingFileIds, + ...(mountsOss + ? { training_datasets: datasetEntries(training, ossRegion) } + : { training_file_ids: trainingFileIds }), // Profile maps the CLI training type to the server value at the boundary. training_type: profile.serverTrainingType, hyper_parameters: hp, }; - if (validationFileIds && validationFileIds.length > 0) { + if (mountsOss) { + if (validation) body.validation_datasets = datasetEntries(validation, ossRegion); + } else if (validationFileIds && validationFileIds.length > 0) { body.validation_file_ids = validationFileIds; } if (typeof flags.jobName === "string") body.job_name = flags.jobName; @@ -953,12 +1186,15 @@ export const finetuneTextCreate = defineCommand({ "--base-model qwen3-8b --datasets file-aaa,./extra.jsonl", "--base-model qwen3-8b --datasets ./train.jsonl --training-type sft", "--base-model qwen3-8b --datasets ./jev-train.jsonl --job-name jev-train-v1 --priority L0 --lora-rank 8 --lora-alpha 16 --lora-dropout 0.1 --lr-scheduler-type linear --eval-steps 50 --save-strategy epoch --save-total-limit 3 --split 0.9 --max-split-val-dataset-sample 1000 --data-augmentation false --dry-run", + "--base-model qwen3-8b --datasets ./train.jsonl --training-type sft-lora --augmentation-types mix_V2 --augmentation-ratio 0.5", '--base-model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4', "--base-model qwen3.6-plus-base-2026-04-02 --datasets file-xxx --training-type cpt --modality vision --reasoning-mode instruct", "--base-model qwen3-8b --datasets file-xxx --output json", + "--base-model qwen3-8b --datasets oss://my-bucket/datasets/train/data.jsonl --oss-region cn-beijing", "--base-model qwen3-8b --datasets file-xxx --dry-run", ], notes: TEXT_NOTES, + validate: (flags) => validateOssMountEntries(flags) ?? validateMixedTrainingFlags(flags), run: (ctx) => runCreate("text", ctx), }); diff --git a/packages/commands/src/commands/finetune/dataset-input.ts b/packages/commands/src/commands/finetune/dataset-input.ts index 89a4fdb12..e372fa5fe 100644 --- a/packages/commands/src/commands/finetune/dataset-input.ts +++ b/packages/commands/src/commands/finetune/dataset-input.ts @@ -2,7 +2,8 @@ * Shared dataset-input pipeline for `finetune create` and * `finetune opd run`: resolve comma-separated file-id / local-path tokens, * validate local files through the training profile, and defer upload until - * pre-flight checks pass. + * pre-flight checks pass. An `oss://` token names a dataset the service reads + * in place; it is accepted only where the request can carry a mount. */ import { existsSync, statSync } from "fs"; import { basename } from "path"; @@ -11,10 +12,13 @@ import { ExitCode, formatCommand, formatIssue, + isOssMountToken, + parseOssMountUri, uploadDataset, type CommandContext, type DataModality, type DatasetFile, + type OssMountLocation, type TrainingProfile, } from "bailian-cli-core"; @@ -31,7 +35,8 @@ export function isLocalPath(token: string): boolean { export interface ResolvedDataset { /** - * Tokens in input order. Local paths are kept as-is here (a placeholder + * File-id and local-path tokens in input order (OSS mounts are kept apart in + * `ossMounts`). Local paths are kept as-is here (a placeholder * until `uploadResolvedLocal` swaps them for real file-ids); bare file-ids * pass through untouched. In dry-run the paths stay (the previewed body * reflects exactly what the user typed). @@ -49,6 +54,27 @@ export interface ResolvedDataset { * fall through to the platform rather than risk a false positive. */ recordCount?: number; + /** + * OSS mounts in input order. The data is not on disk, so it is neither + * validated nor uploaded, and it does not count towards `recordCount`. + */ + ossMounts: OssMountLocation[]; +} + +export interface AnalyzeDatasetOptions { + /** + * Accept `oss://` entries. Only a command whose request carries mounts may + * turn this on; elsewhere an `oss://` entry is rejected instead of being + * forwarded as a file-id it is not. + */ + ossMount?: boolean; +} + +export function splitDatasetEntries(raw: string): string[] { + return raw + .split(",") + .map((token) => token.trim()) + .filter(Boolean); } /** @@ -64,7 +90,7 @@ export interface ResolvedDataset { * validated (the preview never touches the network or the disk beyond stat). */ export async function analyzeDatasetTokens( - context: Pick, + context: Pick, raw: string, label: string, profile: TrainingProfile, @@ -72,12 +98,10 @@ export async function analyzeDatasetTokens( model: string, /** Pre-detected modality for a known path (avoids re-opening the file). */ knownModality?: { path: string; modality: DataModality }, + options: AnalyzeDatasetOptions = {}, ): Promise { const { settings } = context; - const tokens = raw - .split(",") - .map((token) => token.trim()) - .filter(Boolean); + const tokens = splitDatasetEntries(raw); if (tokens.length === 0) { throw new BailianError(`--${label} must contain at least one entry.`, ExitCode.USAGE); } @@ -91,8 +115,27 @@ export async function analyzeDatasetTokens( // flip to unknown and stop accumulating to avoid an undercount that could // trip the batch-size gate falsely. let recordCountKnown = true; + const ossMounts: OssMountLocation[] = []; for (const token of tokens) { + if (isOssMountToken(token)) { + if (!options.ossMount) { + throw new BailianError( + context.localize({ + "en-US": `OSS mount (${token}) is only supported by finetune text create.`, + "zh-CN": `OSS 挂载(${token})仅 finetune text create 支持。`, + }), + ExitCode.USAGE, + ); + } + const mount = parseOssMountUri(token); + if (!mount.valid) { + throw new BailianError(context.localize(mount.reason), ExitCode.USAGE); + } + ossMounts.push(mount.location); + recordCountKnown = false; + continue; + } if (!isLocalPath(token)) { fileIds.push(token); recordCountKnown = false; @@ -158,6 +201,7 @@ export async function analyzeDatasetTokens( localPaths, firstSize, recordCount: recordCountKnown ? recordCount : undefined, + ossMounts, }; } diff --git a/packages/commands/src/commands/finetune/opd-run.ts b/packages/commands/src/commands/finetune/opd-run.ts index 1b073b471..6c24ebae1 100644 --- a/packages/commands/src/commands/finetune/opd-run.ts +++ b/packages/commands/src/commands/finetune/opd-run.ts @@ -11,6 +11,7 @@ import { validateFineTuneHyperParameterOverrides, type CreateFineTuneRequest, type FineTuneDatasetDescriptor, + type FineTuneDatasetSlot, type FineTuneHyperParameters, type FineTuneParamHyperParam, type FineTuneResourceConfig, @@ -188,7 +189,7 @@ function readOpdJsonObject(filePath: string, flagName: string): Record ({ type, data_source_type: "file_id", file_id: fileId })); } diff --git a/packages/commands/src/commands/finetune/params.ts b/packages/commands/src/commands/finetune/params.ts index d5ae1853d..c1bbbb84c 100644 --- a/packages/commands/src/commands/finetune/params.ts +++ b/packages/commands/src/commands/finetune/params.ts @@ -1,31 +1,18 @@ import { defineCommand, getFineTuneParams, - isTrainingTypeCli, - TRAINING_TYPES_CLI, DEFAULT_TRAINING_TYPE, TRAINING_TYPE_MAP, - BailianError, - ExitCode, type FlagsDef, } from "bailian-cli-core"; -import { preflightTrainOptions } from "./train-options-shared.ts"; - -/** - * Build the training-option context from the dedicated flags. The OpenAPI - * expects it as one `hyper_parameters` query parameter holding a JSON string - * (e.g. {"modality":"vision","reasoning_mode":"thinking"}); models without - * dynamic train options simply omit it. - */ -function buildTrainOptions( - modality: string | undefined, - reasoningMode: string | undefined, -): Record { - const options: Record = {}; - if (modality) options.modality = modality; - if (reasoningMode) options.reasoning_mode = reasoningMode; - return options; -} +import { + TRAIN_OPTIONS_PRECHECK_NOTE, + buildTrainOptions, + preflightTrainOptions, + resolveTrainingTypeCli, + trainOptionFlags, + trainingTypeFlag, +} from "./train-options-shared.ts"; const PARAMS_FLAGS = { baseModel: { @@ -37,14 +24,7 @@ const PARAMS_FLAGS = { }, required: true, }, - trainingType: { - type: "string", - valueHint: "", - description: { - "en-US": `Training type: ${TRAINING_TYPES_CLI.join(" | ")} (default: ${DEFAULT_TRAINING_TYPE}). Mapped to the server's training_type (e.g. sft-lora -> efficient_sft).`, - "zh-CN": `训练类型:${TRAINING_TYPES_CLI.join(" | ")}(默认:${DEFAULT_TRAINING_TYPE})。会映射为服务端 training_type(例如 sft-lora -> efficient_sft)。`, - }, - }, + trainingType: trainingTypeFlag(DEFAULT_TRAINING_TYPE), mtuSpecCode: { type: "string", valueHint: "", @@ -62,28 +42,7 @@ const PARAMS_FLAGS = { }, choices: ["hyper", "resource"] as const, }, - modality: { - type: "string", - valueHint: "", - description: { - "en-US": - "Training modality: text | vision. Only meaningful for models with dynamic train options; sent as modality inside hyper_parameters.", - "zh-CN": - "训练模态:text | vision。仅对配置了动态训练选项的模型有意义;作为 hyper_parameters 中的 modality 发送。", - }, - choices: ["text", "vision"] as const, - }, - reasoningMode: { - type: "string", - valueHint: "", - description: { - "en-US": - "Reasoning mode: instruct (non-thinking) | thinking. Only meaningful for models with dynamic train options; sent as reasoning_mode inside hyper_parameters.", - "zh-CN": - "思考模式:instruct(非思考)| thinking(思考)。仅对配置了动态训练选项的模型有意义;作为 hyper_parameters 中的 reasoning_mode 发送。", - }, - choices: ["instruct", "thinking"] as const, - }, + ...trainOptionFlags(), lang: { type: "string", valueHint: "", @@ -121,12 +80,7 @@ export default defineCommand({ "zh-CN": "调用 GET /api/v1/fine-tunes/fine-tunes-params。每条 hyper_params 原样保留服务端字段名(recommend_value、defaultValue、is_advanced_parameter 等)。", }, - { - "en-US": - "--modality / --reasoning-mode travel as one hyper_parameters query parameter (JSON). When a console session is available, the combination is prechecked against the model's supported combinations and omitted options are completed from its defaults; invalid combinations fail with a usage error. Without a console session the check is skipped with a warning and the server result is authoritative.", - "zh-CN": - "--modality / --reasoning-mode 会合并为单个 hyper_parameters query 参数(JSON)发送。控制台会话可用时,会按模型支持的组合预检,并从默认值补齐未传的选项;非法组合报用法错误。无控制台会话时跳过预检并输出警告,以服务端结果为准。", - }, + TRAIN_OPTIONS_PRECHECK_NOTE, { "en-US": "resume_from_checkpoint in the output reports whether the training type supports resuming training.", @@ -136,14 +90,7 @@ export default defineCommand({ async run(ctx) { const { settings, flags } = ctx; - const trainingTypeCli = flags.trainingType || DEFAULT_TRAINING_TYPE; - if (!isTrainingTypeCli(trainingTypeCli)) { - throw new BailianError( - `--training-type "${trainingTypeCli}" is not supported.`, - ExitCode.USAGE, - `Supported values: ${TRAINING_TYPES_CLI.join(", ")} (default: ${DEFAULT_TRAINING_TYPE}).`, - ); - } + const trainingTypeCli = resolveTrainingTypeCli(flags.trainingType, DEFAULT_TRAINING_TYPE); const trainingType = TRAINING_TYPE_MAP[trainingTypeCli].server; let trainOptions = buildTrainOptions(flags.modality, flags.reasoningMode); diff --git a/packages/commands/src/commands/finetune/preset-datasets.ts b/packages/commands/src/commands/finetune/preset-datasets.ts new file mode 100644 index 000000000..25bd638c1 --- /dev/null +++ b/packages/commands/src/commands/finetune/preset-datasets.ts @@ -0,0 +1,129 @@ +import { + defineCommand, + listPresetDatasets, + DEFAULT_TRAINING_TYPE, + TRAINING_TYPE_MAP, + type FlagsDef, + type PresetDataset, +} from "bailian-cli-core"; +import { + TRAIN_OPTIONS_PRECHECK_NOTE, + buildTrainOptions, + preflightTrainOptions, + resolveTrainingTypeCli, + trainOptionFlags, + trainingTypeFlag, +} from "./train-options-shared.ts"; + +const PRESET_DATASETS_FLAGS = { + baseModel: { + type: "string", + valueHint: "", + description: { + "en-US": "Base model to list preset datasets for (e.g. qwen3-8b)", + "zh-CN": "要查询预置数据集的基础模型(例如 qwen3-8b)", + }, + required: true, + }, + trainingType: trainingTypeFlag(DEFAULT_TRAINING_TYPE), + modelVersion: { + type: "string", + valueHint: "", + description: { + "en-US": + "Base-model training-config version. Omit to use the latest applicable config (or, when resuming, the source job's version).", + "zh-CN": "基模训练配置版本。不传取适用的最新配置;续训时沿用源任务的基模版本。", + }, + }, + ...trainOptionFlags(), +} satisfies FlagsDef; + +/** One dataset per two lines: `code title`, then the indented description. */ +function formatPresetDataset(dataset: PresetDataset): string { + const heading = [dataset.dataset_code, dataset.dataset_title].filter(Boolean).join(" "); + return dataset.dataset_desc ? `${heading}\n ${dataset.dataset_desc}` : heading; +} + +export default defineCommand({ + defaultOutput: "json", + description: { + "en-US": "List the preset datasets that can be mixed into a fine-tuning job", + "zh-CN": "查询可混入训练的预置数据集", + }, + auth: "apiKey", + optionalConsole: true, + usageArgs: + "--base-model [--training-type ] [--model-version ] [--modality ] [--reasoning-mode ]", + flags: PRESET_DATASETS_FLAGS, + exampleArgs: [ + "--base-model qwen3-8b", + "--base-model qwen3-8b --training-type sft-lora --output json", + "--base-model qwen3.6-plus-base-2026-04-02 --training-type sft --modality vision --reasoning-mode instruct", + "--base-model qwen3-8b --training-type dpo", + "--base-model qwen3-8b --dry-run", + ], + notes: [ + { + "en-US": + "Queries GET /api/v1/fine-tunes/preset-datasets. Each entry keeps the server field names verbatim (dataset_code, dataset_title, dataset_desc); dataset_code is case-sensitive as returned; finetune text create sends it lowercased as augmentation_types (e.g. mix_V2 -> mix_v2). An empty output (nothing to mix for this model and training type) is a success with exit code 0.", + "zh-CN": + "调用 GET /api/v1/fine-tunes/preset-datasets。每条数据原样保留服务端字段名(dataset_code、dataset_title、dataset_desc);把 dataset_code 传给 finetune text create 的 --augmentation-types 时按小写下发(例如 mix_V2 -> mix_v2)。output 为空(该模型与训练类型下没有可混入的数据集)属于成功,退出码为 0。", + }, + TRAIN_OPTIONS_PRECHECK_NOTE, + ], + async run(ctx) { + const { settings, flags } = ctx; + + const trainingTypeCli = resolveTrainingTypeCli(flags.trainingType, DEFAULT_TRAINING_TYPE); + const trainingType = TRAINING_TYPE_MAP[trainingTypeCli].server; + let trainOptions = buildTrainOptions(flags.modality, flags.reasoningMode); + + if (settings.dryRun) { + const resultData = { + action: "finetune.preset-datasets", + base_model: flags.baseModel, + training_type: trainingType, + ...(flags.modelVersion ? { version: flags.modelVersion } : {}), + ...(Object.keys(trainOptions).length > 0 + ? { hyper_parameters: JSON.stringify(trainOptions) } + : {}), + ...(settings.workspaceId ? { workspace_id: settings.workspaceId } : {}), + }; + ctx.output.result( + resultData, + ctx.settings.output === "text" ? { text: JSON.stringify(resultData, null, 2) } : undefined, + ); + return; + } + + // Same best-effort console precheck as finetune params: rejects option + // combinations the model does not support. A missing console session + // degrades to a warning and passes the user options through unchanged. + const resolved = await preflightTrainOptions(ctx, flags.baseModel, trainingType, trainOptions); + trainOptions = resolved.context; + + const response = await listPresetDatasets(ctx.client, { + inputModel: flags.baseModel, + trainingType, + version: flags.modelVersion || undefined, + trainOptions, + workspaceId: settings.workspaceId, + }); + + const payload = { ...response, precheck: resolved.precheck }; + if (ctx.settings.output === "text") { + const datasets = response.output ?? []; + ctx.output.result(payload, { + text: + datasets.length > 0 + ? datasets.map((dataset) => formatPresetDataset(dataset)).join("\n") + : ctx.localize({ + "en-US": `No preset datasets to mix for ${flags.baseModel} (${trainingType}).`, + "zh-CN": `${flags.baseModel}(${trainingType})没有可混入的预置数据集。`, + }), + }); + return; + } + ctx.output.result(payload); + }, +}); diff --git a/packages/commands/src/commands/finetune/train-options-shared.ts b/packages/commands/src/commands/finetune/train-options-shared.ts index eeb1302f5..a513d6e6b 100644 --- a/packages/commands/src/commands/finetune/train-options-shared.ts +++ b/packages/commands/src/commands/finetune/train-options-shared.ts @@ -1,11 +1,134 @@ import { fetchModelTrainOptions, resolveTrainOptions, + BailianError, + ExitCode, + TRAINING_TYPES_CLI, UsageError, + isTrainingTypeCli, type CommandContext, + type FlagDef, + type FlagsDef, + type LocalizedText, type TrainOptionsIssue, + type TrainingTypeCli, } from "bailian-cli-core"; +/** User-visible bilingual text for one flag description. */ +export interface HelpClause { + readonly "en-US": string; + readonly "zh-CN": string; +} + +type TrainOptionKey = "modality" | "reasoningMode"; + +/** + * Build the training-option context from the dedicated flags. The OpenAPI + * expects it as one `hyper_parameters` query parameter holding a JSON string + * (e.g. {"modality":"vision","reasoning_mode":"thinking"}); models without + * dynamic train options simply omit it. + */ +export function buildTrainOptions( + modality: string | undefined, + reasoningMode: string | undefined, +): Record { + const options: Record = {}; + if (modality) options.modality = modality; + if (reasoningMode) options.reasoning_mode = reasoningMode; + return options; +} + +const HYPER_PARAMETERS_QUERY_DESCRIPTIONS: Record = { + modality: { + "en-US": + "Training modality: text | vision. Only meaningful for models with dynamic train options; sent as modality inside hyper_parameters.", + "zh-CN": + "训练模态:text | vision。仅对配置了动态训练选项的模型有意义;作为 hyper_parameters 中的 modality 发送。", + }, + reasoningMode: { + "en-US": + "Reasoning mode: instruct (non-thinking) | thinking. Only meaningful for models with dynamic train options; sent as reasoning_mode inside hyper_parameters.", + "zh-CN": + "思考模式:instruct(非思考)| thinking(思考)。仅对配置了动态训练选项的模型有意义;作为 hyper_parameters 中的 reasoning_mode 发送。", + }, +}; + +/** + * `--modality` / `--reasoning-mode` flags. The default descriptions fit the + * GET APIs that carry train options in the `hyper_parameters` query parameter; + * `finetune text create` passes its own wording because it sends them in the + * request body and its subcommand also fixes a data format. + */ +export function trainOptionFlags(descriptions: Partial> = {}) { + return { + modality: { + type: "string", + valueHint: "", + description: descriptions.modality ?? HYPER_PARAMETERS_QUERY_DESCRIPTIONS.modality, + choices: ["text", "vision"] as const, + }, + reasoningMode: { + type: "string", + valueHint: "", + description: descriptions.reasoningMode ?? HYPER_PARAMETERS_QUERY_DESCRIPTIONS.reasoningMode, + choices: ["instruct", "thinking"] as const, + }, + } satisfies FlagsDef; +} + +const SERVER_TRAINING_TYPE_MAPPING: HelpClause = { + "en-US": "Mapped to the server's training_type (e.g. sft-lora -> efficient_sft)", + "zh-CN": "会映射为服务端 training_type(例如 sft-lora -> efficient_sft)", +}; + +/** + * `--training-type` flag. `defaultValue` is the command's own default and is + * spelled out in the help; `mappingNote` only varies in how the CLI-to-server + * mapping is phrased. + */ +export function trainingTypeFlag( + defaultValue: TrainingTypeCli, + mappingNote: HelpClause = SERVER_TRAINING_TYPE_MAPPING, +) { + return { + type: "string", + valueHint: "", + description: { + "en-US": `Training type: ${TRAINING_TYPES_CLI.join(" | ")} (default: ${defaultValue}). ${mappingNote["en-US"]}.`, + "zh-CN": `训练类型:${TRAINING_TYPES_CLI.join(" | ")}(默认:${defaultValue})。${mappingNote["zh-CN"]}。`, + }, + } satisfies FlagDef; +} + +/** + * Resolve `--training-type`: fall back to `fallback` when omitted and reject + * values outside the CLI whitelist before any request is sent. Returns the CLI + * value; callers map it to the server code with TRAINING_TYPE_MAP at the + * interface boundary. + */ +export function resolveTrainingTypeCli( + value: string | undefined, + fallback: TrainingTypeCli, +): TrainingTypeCli { + const trainingType = value || fallback; + if (!isTrainingTypeCli(trainingType)) { + throw new BailianError( + `--training-type "${trainingType}" is not supported.`, + ExitCode.USAGE, + `Supported values: ${TRAINING_TYPES_CLI.join(", ")} (default: ${fallback}).`, + ); + } + return trainingType; +} + +/** Help paragraph shared by the commands that run {@link preflightTrainOptions}. */ +export const TRAIN_OPTIONS_PRECHECK_NOTE: LocalizedText = { + "en-US": + "--modality / --reasoning-mode travel as one hyper_parameters query parameter (JSON). When a console session is available, the combination is prechecked against the model's supported combinations and omitted options are completed from its defaults; invalid combinations fail with a usage error. Without a console session the check is skipped with a warning and the server result is authoritative.", + "zh-CN": + "--modality / --reasoning-mode 会合并为单个 hyper_parameters query 参数(JSON)发送。控制台会话可用时,会按模型支持的组合预检,并从默认值补齐未传的选项;非法组合报用法错误。无控制台会话时跳过预检并输出警告,以服务端结果为准。", +}; + export interface TrainOptionsPreflight { /** Validated options with omitted values completed from the model defaults. */ context: Record; diff --git a/packages/commands/src/commands/finetune/train-options.ts b/packages/commands/src/commands/finetune/train-options.ts index 191236f07..2262f38c8 100644 --- a/packages/commands/src/commands/finetune/train-options.ts +++ b/packages/commands/src/commands/finetune/train-options.ts @@ -1,14 +1,19 @@ import { defineCommand, + BailianError, + ExitCode, + fetchModelCapability, fetchModelTrainOptions, MODEL_TRAIN_OPTIONS_API, - isTrainingTypeCli, - TRAINING_TYPES_CLI, TRAINING_TYPE_MAP, - BailianError, - ExitCode, + type CommandContext, type FlagsDef, + type HttpDeps, } from "bailian-cli-core"; +import { resolveTrainingTypeCli, trainingTypeFlag } from "./train-options-shared.ts"; + +/** How a result's `training_options` came about. */ +export type TrainOptionsStatus = "configured" | "not_configured" | "unverified"; const TRAIN_OPTIONS_FLAGS = { baseModel: { @@ -20,14 +25,7 @@ const TRAIN_OPTIONS_FLAGS = { }, required: true, }, - trainingType: { - type: "string", - valueHint: "", - description: { - "en-US": `Training type: ${TRAINING_TYPES_CLI.join(" | ")} (default: sft). Mapped to the server's training_type (e.g. sft-lora -> efficient_sft).`, - "zh-CN": `训练类型:${TRAINING_TYPES_CLI.join(" | ")}(默认:sft)。会映射为服务端 training_type(例如 sft-lora -> efficient_sft)。`, - }, - }, + trainingType: trainingTypeFlag("sft"), } satisfies FlagsDef; export default defineCommand({ @@ -48,34 +46,27 @@ export default defineCommand({ notes: [ { "en-US": - "Calls the console gateway model-train-options API and requires a console login session. The result keeps the server field names verbatim (optionKeys, optionDefinitions, defaults, supportedCombinations). Models without dynamic train options return training_options: null.", + "Calls the console gateway model-train-options API and requires a console login session. The result keeps the server field names verbatim (optionKeys, optionDefinitions, defaults, supportedCombinations) and carries a status: configured (options were returned), not_configured (the model is confirmed in the trainable catalog and has no dynamic options, so training_options is null) or unverified (no options were returned and the catalog lookup failed). A model id that is not a trainable base model fails with an error instead of returning null.", "zh-CN": - "调用控制台网关 model-train-options 接口,需要控制台登录态。结果原样保留服务端字段名(optionKeys、optionDefinitions、defaults、supportedCombinations)。未配置动态训练选项的模型返回 training_options: null。", + "调用控制台网关 model-train-options 接口,需要控制台登录态。结果原样保留服务端字段名(optionKeys、optionDefinitions、defaults、supportedCombinations),并带一个 status:configured(返回了选项)、not_configured(模型已在可训练目录中确认存在但没有动态选项,此时 training_options 为 null)、unverified(未返回选项且目录查询失败)。模型 ID 不是可训练基础模型时直接报错,不会返回 null。", }, { "en-US": - "supportedCombinations is the authority for valid option combinations. finetune params and finetune text create call this same API once as a best-effort precheck when a console session is available: omitted options are completed from defaults and invalid combinations are rejected; without a session the check is skipped with a warning.", + "supportedCombinations is the authority for valid option combinations. finetune params, finetune preset-datasets and finetune text create call this same API once as a best-effort precheck when a console session is available: omitted options are completed from defaults and invalid combinations are rejected; without a session the check is skipped with a warning.", "zh-CN": - "supportedCombinations 是选项组合合法性的唯一权威。finetune params 与 finetune text create 在控制台会话可用时会调用同一接口做一次尽力预检:从 defaults 补齐未传选项并拒绝非法组合;无会话时跳过预检并输出警告。", + "supportedCombinations 是选项组合合法性的唯一权威。finetune params、finetune preset-datasets 与 finetune text create 在控制台会话可用时会调用同一接口做一次尽力预检:从 defaults 补齐未传选项并拒绝非法组合;无会话时跳过预检并输出警告。", }, { "en-US": - "Pass the selected options to finetune params / finetune text create via --modality / --reasoning-mode; they travel as hyper_parameters to the training API.", + "Pass the selected options to finetune params / finetune preset-datasets / finetune text create via --modality / --reasoning-mode; they travel as hyper_parameters to the training API.", "zh-CN": - "选定的选项通过 --modality / --reasoning-mode 传给 finetune params / finetune text create;它们会作为 hyper_parameters 发送给训练接口。", + "选定的选项通过 --modality / --reasoning-mode 传给 finetune params / finetune preset-datasets / finetune text create;它们会作为 hyper_parameters 发送给训练接口。", }, ], async run(ctx) { const { settings, flags } = ctx; - const trainingTypeCli = flags.trainingType || "sft"; - if (!isTrainingTypeCli(trainingTypeCli)) { - throw new BailianError( - `--training-type "${trainingTypeCli}" is not supported.`, - ExitCode.USAGE, - `Supported values: ${TRAINING_TYPES_CLI.join(", ")} (default: sft).`, - ); - } + const trainingTypeCli = resolveTrainingTypeCli(flags.trainingType, "sft"); const trainingType = TRAINING_TYPE_MAP[trainingTypeCli].server; if (settings.dryRun) { @@ -91,21 +82,38 @@ export default defineCommand({ return; } + const diagnostics: Pick = { + debug: (diagnostic) => ctx.output.debug(diagnostic), + }; const options = await fetchModelTrainOptions( ctx.client.console.bind(ctx.client), flags.baseModel, trainingType, ); + const status: TrainOptionsStatus = options + ? "configured" + : await resolveNullStatus(ctx, flags.baseModel, diagnostics); const result = { model: flags.baseModel, training_type: trainingType, + status, training_options: options, }; if (settings.output === "text") { const lines: string[] = []; if (!options) { - lines.push(`No dynamic train options configured for ${flags.baseModel} (${trainingType}).`); + lines.push( + status === "not_configured" + ? ctx.localize({ + "en-US": `No dynamic train options are configured for ${flags.baseModel} (${trainingType}); the model is a valid trainable base model and needs no --modality / --reasoning-mode.`, + "zh-CN": `模型 ${flags.baseModel}(${trainingType})未配置动态训练选项;该模型是有效的可训练基础模型,无需传 --modality / --reasoning-mode。`, + }) + : ctx.localize({ + "en-US": `No dynamic train options were returned for ${flags.baseModel} (${trainingType}); the model could not be verified in the catalog.`, + "zh-CN": `接口未返回 ${flags.baseModel}(${trainingType})的动态训练选项,且无法在模型目录中确认该模型存在。`, + }), + ); } else { for (const definition of options.optionDefinitions ?? []) { const values = (definition.supportValues ?? []).join(" | "); @@ -135,3 +143,47 @@ export default defineCommand({ ctx.output.result(result); }, }); + +/** + * Explain a null from the Console API. It is only reported as + * `not_configured` once the model is confirmed in the trainable catalog, so a + * mistyped model id fails instead of reading as "no dynamic options". Runs + * after the Console call on purpose: a model the catalog omits but the Console + * configures still gets its options through. A failed catalog lookup only + * warns and leaves the result `unverified`. + * + * Only model existence is taken from the catalog. Its training-type capability + * is known to disagree with the API for some models, so it is never consulted. + */ +async function resolveNullStatus( + ctx: CommandContext, + model: string, + diagnostics: Pick, +): Promise> { + let capability: Awaited> | undefined; + try { + capability = await fetchModelCapability(ctx.settings, model, diagnostics); + } catch (error) { + ctx.output.warning({ + code: "TRAINING_CAPABILITY_LOOKUP_FAILED", + message: { + "en-US": "Model catalog lookup failed; whether the model exists could not be verified.", + "zh-CN": "模型目录查询失败;无法确认该模型是否存在。", + }, + details: { reason: error instanceof Error ? error.message : undefined }, + }); + return "unverified"; + } + if (capability) return "not_configured"; + throw new BailianError( + ctx.localize({ + "en-US": `No trainable base model named "${model}" was found in the model catalog, and it has no dynamic train options.`, + "zh-CN": `模型目录中未找到名为 "${model}" 的可训练基础模型,且它没有动态训练选项。`, + }), + ExitCode.USAGE, + ctx.localize({ + "en-US": `Check the model id with finetune capability --base-model ${model}.`, + "zh-CN": `用 finetune capability --base-model ${model} 核对模型 ID。`, + }), + ); +} diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index f7034b112..fcec12708 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -214,6 +214,7 @@ export { default as finetuneCapability } from "./commands/finetune/capability.ts export { default as finetunePrice } from "./commands/finetune/price.ts"; export { default as finetuneParams } from "./commands/finetune/params.ts"; export { default as finetuneTrainOptions } from "./commands/finetune/train-options.ts"; +export { default as finetunePresetDatasets } from "./commands/finetune/preset-datasets.ts"; export { default as finetuneMetrics } from "./commands/finetune/metrics.ts"; export { default as finetuneCompressTemplates } from "./commands/finetune/compress-templates.ts"; export { default as finetuneCompressCreate } from "./commands/finetune/compress-create.ts"; diff --git a/packages/commands/tests/e2e/finetune.e2e.test.ts b/packages/commands/tests/e2e/finetune.e2e.test.ts index b86ab8c44..fc05ab2d6 100644 --- a/packages/commands/tests/e2e/finetune.e2e.test.ts +++ b/packages/commands/tests/e2e/finetune.e2e.test.ts @@ -94,6 +94,7 @@ function parameterSchema( data_range: ["1", "200"], step: 1, editable: true, + defaultValue: "3", }, { name: "learning_rate", type: "input", editable: true }, { @@ -101,6 +102,7 @@ function parameterSchema( type: "intInputNumber", data_range: ["500", "65536"], editable: true, + defaultValue: "32768", }, { name: "eval_steps", @@ -167,12 +169,8 @@ function parameterSchema( data_range: ["1", "2147483647"], editable: true, }, - { - name: "data_augmentation", - type: "select", - support_values: ["true", "false"], - editable: true, - }, + // Mixed-training parameters (data_augmentation / augmentation_types / + // augmentation_ratio) are deliberately absent, as on the real service. ]; } @@ -257,7 +255,7 @@ describe("e2e: finetune (schema-gated)", () => { expect(stderr).toMatch(/--base-model|--datasets/i); }); - test("finetune create --dry-run 构造 SFT 默认请求体", async () => { + test("finetune create --dry-run 用参数配置默认值补齐必填超参", async () => { const { stdout, stderr, exitCode } = await runSchemaCommand([ "finetune", "text", @@ -288,7 +286,13 @@ describe("e2e: finetune (schema-gated)", () => { expect(data.body.training_file_ids).toEqual(["file-aaa", "file-bbb"]); expect(data.body.validation_file_ids).toEqual(["file-ccc"]); expect(data.body.training_type).toBe("efficient_sft"); - expect(data.body.hyper_parameters).toEqual({}); + // The create API rejects a job without n_epochs / batch_size / max_length, + // so omitted ones are sent with the schema's defaults. + expect(data.body.hyper_parameters).toEqual({ + n_epochs: 3, + batch_size: 8, + max_length: 32768, + }); }); test("finetune create --dry-run 转发训练类型与超参", async () => { @@ -392,7 +396,7 @@ describe("e2e: finetune (schema-gated)", () => { expect(exitCode, stdout + stderr).not.toBe(0); }); - test("finetune text create --help 展示训练选项 flag", async () => { + test("finetune text create --help 展示训练选项与混合训练 flag", async () => { const { stderr, exitCode } = await runCommandHelp(FINETUNE_ROUTES, [ "finetune", "text", @@ -402,6 +406,11 @@ describe("e2e: finetune (schema-gated)", () => { expect(exitCode, stderr).toBe(0); expect(stderr).toMatch(/--modality/); expect(stderr).toMatch(/--reasoning-mode/); + expect(stderr).toMatch(/--data-augmentation/); + expect(stderr).toMatch(/--augmentation-types/); + expect(stderr).toMatch(/--augmentation-ratio/); + expect(stderr).toMatch(/--oss-region/); + expect(stderr).toMatch(/oss:\/\//); }); test("finetune create --dry-run 动态选项模型透传 modality/reasoning_mode 并作为 schema 查询上下文", async () => { @@ -441,6 +450,30 @@ describe("e2e: finetune (schema-gated)", () => { ); }); + test("finetune create 只补参数配置里有默认值的必填超参", async () => { + // This schema gives batch_size a default, lists n_epochs without one and has + // no max_length: only batch_size is filled, nothing is invented. + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + DYNAMIC_OPTION_MODEL, + "--datasets", + "file-aaa", + "--training-type", + "cpt", + "--modality", + "vision", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ body: { hyper_parameters: Record } }>(stdout); + expect(data.body.hyper_parameters).toEqual({ batch_size: 8, modality: "vision" }); + }); + test("finetune create 动态选项模型缺 modality 时空 schema 闸门给出训练选项提示", async () => { const { stderr, exitCode } = await runSchemaCommand([ "finetune", @@ -802,6 +835,83 @@ describe("e2e: finetune (schema-gated)", () => { expect(stderr).toMatch(/--base-model|Missing required argument/i); }); + test("finetune preset-datasets --help 展示必填项与可选 flag", async () => { + const { stderr, exitCode } = await runSchemaCommand(["finetune", "preset-datasets", "--help"]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--base-model/); + expect(stderr).toMatch(/--model-version/); + expect(stderr).toMatch(/--console-region/); + }); + + test("finetune preset-datasets --dry-run 离线预览 query,未传的可选项不出现", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "preset-datasets", + "--base-model", + "qwen3-8b", + "--dry-run", + ]); + expect(exitCode, stderr).toBe(0); + expect(parseStdoutJson(stdout)).toEqual({ + action: "finetune.preset-datasets", + base_model: "qwen3-8b", + training_type: "efficient_sft", + }); + }); + + test("finetune preset-datasets --dry-run 带上显式训练类型与可选项", async () => { + // --modality / --reasoning-mode merge into one hyper_parameters JSON query + // string; the training type stays the server value of the CLI mapping. + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "preset-datasets", + "--base-model", + DYNAMIC_OPTION_MODEL, + "--training-type", + "sft", + "--model-version", + "v1", + "--modality", + "vision", + "--reasoning-mode", + "instruct", + "--workspace-id", + "ws-123", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(parseStdoutJson(stdout)).toEqual({ + action: "finetune.preset-datasets", + base_model: DYNAMIC_OPTION_MODEL, + training_type: "sft", + version: "v1", + hyper_parameters: '{"modality":"vision","reasoning_mode":"instruct"}', + workspace_id: "ws-123", + }); + }); + + test("finetune preset-datasets 非法训练类型退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "preset-datasets", + "--base-model", + "qwen3-8b", + "--training-type", + "nope", + "--dry-run", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--training-type|nope/); + }); + + test("finetune preset-datasets 缺少 --base-model 时退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSchemaCommand(["finetune", "preset-datasets", "--quiet"]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--base-model|Missing required argument/i); + }); + test("finetune metrics --dry-run 默认 page_no=1 且显式 page_size=100", async () => { // The OpenAPI default is 1000 per page; the CLI keeps the legacy 100-page // shape by sending page_size explicitly unless the user overrides it. @@ -1576,3 +1686,306 @@ describe("finetune complete recipe (offline)", () => { expect(result.exitCode).toBe(2); }); }); + +describe("finetune text create mixed training (offline)", () => { + const baseArgs = [ + "finetune", + "text", + "create", + "--base-model", + "qwen3-8b", + "--datasets", + "file-aaa", + "--dry-run", + "--output", + "json", + ]; + + async function previewHyperParameters(extra: string[]): Promise> { + const { stdout, stderr, exitCode } = await runSchemaCommand([...baseArgs, ...extra]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ body: { hyper_parameters: Record } }>(stdout); + return data.body.hyper_parameters; + } + + test("--augmentation-types 按小写下发并自动开启 data_augmentation", async () => { + // preset-datasets returns `mix_V2`; the create API documents lowercase codes. + expect( + await previewHyperParameters([ + "--augmentation-types", + "mix_V2", + "--augmentation-ratio", + "0.5", + ]), + ).toMatchObject({ + data_augmentation: true, + augmentation_types: "mix_v2", + augmentation_ratio: "0.5", + }); + }); + + test("多个数据集与倍率按位置对应并去掉空白", async () => { + expect( + await previewHyperParameters([ + "--augmentation-types", + " mix_V2 , vl_mix ", + "--augmentation-ratio", + "0.5, 1.25", + ]), + ).toMatchObject({ + data_augmentation: true, + augmentation_types: "mix_v2,vl_mix", + augmentation_ratio: "0.5,1.25", + }); + }); + + test("--data-augmentation 不在参数配置里也原样下发", async () => { + // The real schema has no data_augmentation entry; the flag must not be + // rejected by the schema check. + expect(await previewHyperParameters(["--data-augmentation", "true"])).toMatchObject({ + data_augmentation: true, + }); + }); + + test("未传混合训练 flag 时请求体不带相关字段", async () => { + const hyperParameters = await previewHyperParameters([]); + expect( + Object.keys(hyperParameters).some((parameterName) => /augmentation/.test(parameterName)), + ).toBe(false); + }); + + test.each([ + ["only --augmentation-types", ["--augmentation-types", "mix_V2"], /--augmentation-ratio/], + ["only --augmentation-ratio", ["--augmentation-ratio", "0.5"], /--augmentation-types/], + [ + "conflict with --data-augmentation false", + [ + "--augmentation-types", + "mix_V2", + "--augmentation-ratio", + "0.5", + "--data-augmentation", + "false", + ], + /--data-augmentation false/, + ], + [ + "empty item", + ["--augmentation-types", "mix_V2,,vl_mix", "--augmentation-ratio", "0.5,1"], + /empty items|空项/, + ], + [ + "ratio count mismatch", + ["--augmentation-types", "mix_V2,vl_mix", "--augmentation-ratio", "0.5"], + /one ratio per|逐项对应/, + ], + [ + "ratio above 2", + ["--augmentation-types", "mix_V2", "--augmentation-ratio", "2.5"], + /within \[0, 2\]|0\.0~2\.0/, + ], + [ + "non-numeric ratio", + ["--augmentation-types", "mix_V2", "--augmentation-ratio", "abc"], + /within \[0, 2\]|0\.0~2\.0/, + ], + ])("rejects %s as a usage error before any request", async (_case, extra, pattern) => { + const queryBefore = lastSchemaQuery; + const { stdout, stderr, exitCode } = await runSchemaCommand([...baseArgs, ...extra]); + expect(exitCode, stdout + stderr).toBe(2); + expect(stderr).toMatch(pattern); + expect(lastSchemaQuery).toBe(queryBefore); + }); +}); + +describe("finetune text create OSS mount (offline)", () => { + const commandArgs = ["finetune", "text", "create", "--base-model", "qwen3-8b"]; + const previewArgs = (datasets: string): string[] => [ + ...commandArgs, + "--datasets", + datasets, + "--dry-run", + "--output", + "json", + ]; + + interface DatasetEntry { + data_source_type: string; + file_id?: string; + mount_storage?: { region: string; bucket: string; file_path: string }; + } + + interface PreviewBody { + training_file_ids?: string[]; + validation_file_ids?: string[]; + training_datasets?: DatasetEntry[]; + validation_datasets?: DatasetEntry[]; + } + + interface Preview { + body: PreviewBody; + pending: Array<{ field: string; path: string }>; + } + + async function preview(args: string[]): Promise { + const { stdout, stderr, exitCode } = await runSchemaCommand(args); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + body: PreviewBody; + pending_uploads?: Array<{ field: string; path: string }>; + }>(stdout); + return { body: data.body, pending: data.pending_uploads ?? [] }; + } + + test("oss:// entry is sent as a mount in the default region, replacing the flat file-id field", async () => { + const { body } = await preview(previewArgs("oss://my-bucket/datasets/train/data.jsonl")); + expect(body.training_datasets).toEqual([ + { + data_source_type: "oss_mount", + mount_storage: { + region: "cn-beijing", + bucket: "my-bucket", + file_path: "datasets/train/data.jsonl", + }, + }, + ]); + expect(body).not.toHaveProperty("training_file_ids"); + }); + + test("--oss-region applies to every mount of both fields", async () => { + const { body } = await preview([ + ...commandArgs, + "--datasets", + "oss://train-bucket/train/data.jsonl,oss://other-bucket/more/data.jsonl", + "--validations", + "oss://eval-bucket/eval/data.jsonl", + "--oss-region", + "ap-southeast-1", + "--dry-run", + "--output", + "json", + ]); + const regions = [...(body.training_datasets ?? []), ...(body.validation_datasets ?? [])].map( + (entry) => entry.mount_storage?.region, + ); + expect(regions).toEqual(["ap-southeast-1", "ap-southeast-1", "ap-southeast-1"]); + }); + + test("--oss-region is sent as given: the service judges whether it can mount", async () => { + const { body } = await preview([ + ...previewArgs("oss://my-bucket/data.jsonl"), + "--oss-region", + "cn-hangzhou", + ]); + expect(body.training_datasets?.[0]?.mount_storage?.region).toBe("cn-hangzhou"); + }); + + test("file-ids and local paths share the dataset entries with a mount, both in training and validation", async () => { + const localPath = join(e2eFixturesDir, ".dataset-valid.jsonl"); + const { body, pending } = await preview([ + ...commandArgs, + "--datasets", + `file-aaa,${localPath},oss://my-bucket/train/data.jsonl`, + "--validations", + "file-ccc", + "--dry-run", + "--output", + "json", + ]); + expect(body.training_datasets).toEqual([ + { data_source_type: "file_id", file_id: "file-aaa" }, + { data_source_type: "file_id", file_id: localPath }, + { + data_source_type: "oss_mount", + mount_storage: { + region: "cn-beijing", + bucket: "my-bucket", + file_path: "train/data.jsonl", + }, + }, + ]); + expect(body.validation_datasets).toEqual([ + { data_source_type: "file_id", file_id: "file-ccc" }, + ]); + expect(pending).toEqual([{ field: "datasets", path: localPath }]); + expect(body).not.toHaveProperty("training_file_ids"); + expect(body).not.toHaveProperty("validation_file_ids"); + }); + + test("an OSS mount on the validation set alone also moves the training set to dataset entries", async () => { + const { body } = await preview([ + ...previewArgs("file-aaa"), + "--validations", + "oss://my-bucket/eval/data.jsonl", + ]); + expect(body.training_datasets).toEqual([{ data_source_type: "file_id", file_id: "file-aaa" }]); + expect(body.validation_datasets?.[0]?.mount_storage).toEqual({ + region: "cn-beijing", + bucket: "my-bucket", + file_path: "eval/data.jsonl", + }); + expect(body).not.toHaveProperty("training_file_ids"); + }); + + test("without an OSS mount the request keeps the flat file-id form", async () => { + const { body } = await preview(previewArgs("file-aaa")); + expect(body.training_file_ids).toEqual(["file-aaa"]); + expect(body).not.toHaveProperty("training_datasets"); + expect(body).not.toHaveProperty("validation_datasets"); + }); + + test.each([ + [ + "no object key", + ["--datasets", "oss://my-bucket"], + /--datasets entry .*oss:\/\/my-bucket.* is missing the object key/, + ], + [ + "no bucket", + ["--datasets", "oss:///data.jsonl"], + /--datasets entry .*oss:\/\/\/data.jsonl.* is missing the bucket/, + ], + ["a zip on the training set", ["--datasets", "oss://my-bucket/train.zip"], /zip file/], + [ + "a zip on the validation set", + ["--datasets", "file-aaa", "--validations", "oss://my-bucket/eval.zip"], + /--validations entry .*eval\.zip.* points at a zip file/, + ], + ])("rejects %s as a usage error before any request", async (_case, extra, pattern) => { + const queryBefore = lastSchemaQuery; + const { stdout, stderr, exitCode } = await runSchemaCommand([ + ...commandArgs, + ...extra, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).toBe(2); + expect(stderr).toMatch(pattern); + expect(lastSchemaQuery).toBe(queryBefore); + }); + + test.each([ + ["audio", ["finetune", "audio", "create", "--base-model", "cosyvoice-v3-flash"]], + [ + "decision", + ["finetune", "decision", "create", "--base-model", "decision-model-preview-2026-09-24"], + ], + ])( + "rejects an oss:// entry on %s create: that request cannot carry a mount", + async (_modality, command) => { + const queryBefore = lastSchemaQuery; + const { stdout, stderr, exitCode } = await runSchemaCommand([ + ...command, + "--datasets", + "oss://my-bucket/train/data.jsonl", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).toBe(2); + expect(stderr).toMatch(/only supported by finetune text create/); + expect(lastSchemaQuery).toBe(queryBefore); + }, + ); +}); diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index 076dd13c3..b639e77e6 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -402,6 +402,7 @@ export const FINETUNE_ROUTES: E2eRouteExports = { "finetune capability": "finetuneCapability", "finetune params": "finetuneParams", "finetune train-options": "finetuneTrainOptions", + "finetune preset-datasets": "finetunePresetDatasets", "finetune metrics": "finetuneMetrics", "finetune compress templates": "finetuneCompressTemplates", "finetune compress create": "finetuneCompressCreate", diff --git a/packages/commands/tests/output/finetune-preset-datasets.test.ts b/packages/commands/tests/output/finetune-preset-datasets.test.ts new file mode 100644 index 000000000..fac075ae9 --- /dev/null +++ b/packages/commands/tests/output/finetune-preset-datasets.test.ts @@ -0,0 +1,282 @@ +import { join } from "node:path"; +import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; +import { + buildSettings, + Client, + httpTransport, + MODEL_TRAIN_OPTIONS_API, + type AnyCommand, + type LocalizedText, +} from "bailian-cli-core"; +import { createOutputReporter } from "bailian-cli-runtime"; +import { enterIsolatedHome } from "e2e/isolation"; +import finetunePresetDatasets from "../../src/commands/finetune/preset-datasets.ts"; + +const identity = { binName: "bl", version: "test", clientName: "test", npmPackage: "test" }; +const DYNAMIC_MODEL = "qwen3.6-plus-base-2026-04-02"; + +const dynamicOptions = { + enabled: true, + optionKeys: ["modality", "reasoning_mode"], + optionDefinitions: [ + { name: "modality", supportValues: ["vision"], required: true, editable: false }, + { + name: "reasoning_mode", + supportValues: ["instruct", "thinking"], + required: true, + editable: true, + }, + ], + defaults: { modality: "vision", reasoning_mode: "instruct" }, + supportedCombinations: [{ modality: "vision", reasoning_mode: "instruct" }], +}; + +// dataset_code keeps its server casing and the response keeps server field names. +const presetDatasets = [ + { dataset_code: "mix_V2", dataset_title: "Mix v2", dataset_desc: "General mix." }, + { dataset_code: "bare_Set", dataset_title: "Bare set" }, +]; + +let isolated: ReturnType; +let presetQueries: { search: URLSearchParams; headers: Headers; method: string }[]; +let consoleApis: string[]; +let serverOutput: unknown; +let serverError: { status: number; body: unknown } | undefined; +let consoleFailure: Error | undefined; + +beforeEach(() => { + isolated = enterIsolatedHome(); + presetQueries = []; + consoleApis = []; + serverOutput = presetDatasets; + serverError = undefined; + consoleFailure = undefined; + vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Unexpected unmocked HTTP")); + vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + // Console gateway: form-encoded POST carrying the zelda API name. + if (typeof init?.body === "string") { + const form = new URLSearchParams(init.body); + const params = JSON.parse(form.get("params")!) as { + Api: string; + Data: { input?: { models?: string[] } }; + }; + consoleApis.push(params.Api); + if (consoleFailure) throw consoleFailure; + if (params.Api !== MODEL_TRAIN_OPTIONS_API) { + throw new Error(`Unexpected console API: ${params.Api}`); + } + const model = params.Data.input?.models?.[0] ?? ""; + const entries = model === DYNAMIC_MODEL ? [{ model, trainingOptions: dynamicOptions }] : []; + return Response.json({ + code: "200", + successResponse: true, + data: { + success: true, + DataV2: { ret: ["SUCCESS::ok"], data: { code: "200", data: entries, success: true } }, + }, + }); + } + // DashScope OpenAPI: the preset-datasets GET. + if (url.pathname === "/api/v1/fine-tunes/preset-datasets") { + presetQueries.push({ + search: url.searchParams, + headers: new Headers(init?.headers), + method: init?.method ?? "GET", + }); + if (serverError) return Response.json(serverError.body, { status: serverError.status }); + return Response.json({ request_id: "req-preset", output: serverOutput }); + } + throw new Error(`Unexpected request: ${url.pathname}`); + }); +}); + +afterEach(() => { + try { + expect(globalThis.fetch).not.toHaveBeenCalled(); + } finally { + vi.restoreAllMocks(); + isolated.restore(); + } +}); + +async function invoke(command: AnyCommand, flags: Record) { + let stdout = ""; + let stderr = ""; + const language = "en-US"; + const settings = buildSettings({ + flags: { output: "json", ...flags }, + file: { language, telemetry: false }, + env: {}, + configPath: join(isolated.configDir, "config.json"), + }); + const localize = (text: LocalizedText) => (typeof text === "string" ? text : text[language]); + const reporter = createOutputReporter({ + settings, + localize, + stdout: { write: (chunk) => (stdout += chunk) }, + stderr: { write: (chunk) => (stderr += chunk) }, + }); + const client = new Client({ + identity, + settings, + baseUrl: "https://api.example.invalid", + apiCred: { + token: "fixture-api-key", + baseUrl: "https://api.example.invalid", + source: "flag" as const, + }, + consoleCred: { + token: "fixture-console-token", + source: "flag" as const, + region: "cn-beijing", + site: "domestic" as const, + switchAgent: 111, + }, + debug: (diagnostic) => reporter.output.debug(diagnostic), + }); + let exitCode = 0; + try { + await command.run({ + flags, + settings, + identity, + localize, + client, + output: reporter.output, + } as never); + } catch (error) { + exitCode = reporter.error(error); + } + return { stdout, stderr, exitCode }; +} + +/** JSON diagnostics the reporter wrote to stderr, one object per line. */ +function diagnostics(stderr: string): Record[] { + return stderr + .split("\n") + .filter((line) => line.trim().length > 0) + .map((line) => JSON.parse(line) as Record); +} + +test("returns the server payload verbatim plus precheck metadata", async () => { + const { stdout, exitCode } = await invoke(finetunePresetDatasets, { baseModel: "qwen3-8b" }); + expect(exitCode).toBe(0); + expect(JSON.parse(stdout)).toEqual({ + request_id: "req-preset", + output: presetDatasets, + precheck: { performed: true, dynamic_options: false }, + }); + expect(consoleApis).toEqual([MODEL_TRAIN_OPTIONS_API]); + expect(presetQueries).toHaveLength(1); + expect(presetQueries[0].method).toBe("GET"); + expect(Object.fromEntries(presetQueries[0].search)).toEqual({ + input_model: "qwen3-8b", + training_type: "efficient_sft", + }); + expect(presetQueries[0].headers.get("authorization")).toBe("Bearer fixture-api-key"); + expect(presetQueries[0].headers.get("X-DashScope-WorkSpace")).toBeNull(); +}); + +test("completes omitted train options from the model defaults", async () => { + const { stdout, exitCode } = await invoke(finetunePresetDatasets, { baseModel: DYNAMIC_MODEL }); + expect(exitCode).toBe(0); + expect(presetQueries[0].search.get("hyper_parameters")).toBe( + JSON.stringify({ modality: "vision", reasoning_mode: "instruct" }), + ); + const parsed = JSON.parse(stdout) as { precheck: unknown }; + expect(parsed.precheck).toEqual({ performed: true, dynamic_options: true }); +}); + +test("sends the version, the mapped training type and the workspace header", async () => { + const { exitCode } = await invoke(finetunePresetDatasets, { + baseModel: "qwen3-8b", + trainingType: "dpo", + modelVersion: "v1", + workspaceId: "ws-123", + }); + expect(exitCode).toBe(0); + expect(Object.fromEntries(presetQueries[0].search)).toEqual({ + input_model: "qwen3-8b", + training_type: "dpo_full", + version: "v1", + }); + expect(presetQueries[0].headers.get("X-DashScope-WorkSpace")).toBe("ws-123"); +}); + +test("rejects a combination outside supportedCombinations before the query", async () => { + const { stderr, exitCode } = await invoke(finetunePresetDatasets, { + baseModel: DYNAMIC_MODEL, + reasoningMode: "thinking", + }); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/Invalid train-options combination|组合不合法/); + expect(presetQueries).toHaveLength(0); +}); + +test("text output prints two lines per dataset", async () => { + const { stdout, exitCode } = await invoke(finetunePresetDatasets, { + baseModel: "qwen3-8b", + output: "text", + }); + expect(exitCode).toBe(0); + expect(stdout.trimEnd().split("\n")).toEqual([ + "mix_V2 Mix v2", + " General mix.", + "bare_Set Bare set", + ]); +}); + +test("an empty list is a success in both output formats", async () => { + serverOutput = []; + const asJson = await invoke(finetunePresetDatasets, { + baseModel: "qwen3-8b", + trainingType: "dpo", + }); + expect(asJson.exitCode).toBe(0); + expect(JSON.parse(asJson.stdout).output).toEqual([]); + + const asText = await invoke(finetunePresetDatasets, { + baseModel: "qwen3-8b", + trainingType: "dpo", + output: "text", + }); + expect(asText.exitCode).toBe(0); + expect(asText.stdout).toMatch(/No preset datasets to mix for qwen3-8b \(dpo_full\)\./); +}); + +test("passes an HTTP error through with the server code, message and request id", async () => { + serverError = { + status: 401, + body: { code: "InvalidApiKey", message: "original server error", request_id: "req-deny" }, + }; + const { stdout, stderr, exitCode } = await invoke(finetunePresetDatasets, { + baseModel: "qwen3-8b", + }); + expect(exitCode).toBe(1); + expect(stdout).toBe(""); + expect(diagnostics(stderr)[0].error).toMatchObject({ + message: "original server error", + request_id: "req-deny", + api_code: "InvalidApiKey", + http_status: 401, + }); +}); + +test("degrades to a warning and passes options through when the console fails", async () => { + consoleFailure = new Error("Console session is not logged in or has expired."); + const { stdout, stderr, exitCode } = await invoke(finetunePresetDatasets, { + baseModel: DYNAMIC_MODEL, + modality: "vision", + reasoningMode: "instruct", + }); + expect(exitCode).toBe(0); + expect(diagnostics(stderr)[0].warning).toMatchObject({ + code: "finetune.train_options_precheck_skipped", + }); + expect(presetQueries[0].search.get("hyper_parameters")).toBe( + JSON.stringify({ modality: "vision", reasoning_mode: "instruct" }), + ); + const parsed = JSON.parse(stdout) as { precheck: unknown }; + expect(parsed.precheck).toEqual({ performed: false, reason: "console-unavailable" }); +}); diff --git a/packages/commands/tests/output/finetune-train-options.test.ts b/packages/commands/tests/output/finetune-train-options.test.ts index c6a5e8ede..559974369 100644 --- a/packages/commands/tests/output/finetune-train-options.test.ts +++ b/packages/commands/tests/output/finetune-train-options.test.ts @@ -6,6 +6,7 @@ import { buildSettings, Client, httpTransport, + MODEL_LIST_API, MODEL_TRAIN_OPTIONS_API, type AnyCommand, type LocalizedText, @@ -35,16 +36,30 @@ const dynamicOptions = { supportedCombinations: [{ modality: "vision", reasoning_mode: "instruct" }], }; +// Trainable-catalog entries. qwen3-8b reports cpt=false here while the training +// API accepts cpt for it, which is why only model existence is ever taken from +// the catalog. +const CATALOG_MODELS = [ + { model: "qwen3-8b", supports: { sft: true, dpo: true, cpt: false } }, + { model: DYNAMIC_MODEL, supports: { sft: true, dpo: true, cpt: true } }, +]; + let isolated: ReturnType; let schemaQueries: URLSearchParams[]; let consoleApis: string[]; let consoleFailure: Error | undefined; +let catalogQueries: string[]; +let catalogAuth: Array; +let catalogFailure: Error | undefined; beforeEach(() => { isolated = enterIsolatedHome(); schemaQueries = []; consoleApis = []; consoleFailure = undefined; + catalogQueries = []; + catalogAuth = []; + catalogFailure = undefined; vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Unexpected unmocked HTTP")); vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input)); @@ -53,13 +68,29 @@ beforeEach(() => { const form = new URLSearchParams(init.body); const params = JSON.parse(form.get("params")!) as { Api: string; - Data: { input?: { models?: string[] } }; + Data: { input?: { models?: string[]; name?: string } }; }; - consoleApis.push(params.Api); if (consoleFailure) throw consoleFailure; + // Public trainable catalog, queried without a console token. + if (params.Api === MODEL_LIST_API) { + const name = params.Data.input?.name ?? ""; + catalogQueries.push(name); + catalogAuth.push(new Headers(init.headers).get("Authorization")); + if (catalogFailure) throw catalogFailure; + const list = CATALOG_MODELS.filter((entry) => entry.model === name); + return Response.json({ + code: "200", + successResponse: true, + data: { + success: true, + DataV2: { ret: ["SUCCESS::ok"], data: { total: list.length, list, success: true } }, + }, + }); + } if (params.Api !== MODEL_TRAIN_OPTIONS_API) { throw new Error(`Unexpected console API: ${params.Api}`); } + consoleApis.push(params.Api); const model = params.Data.input?.models?.[0] ?? ""; const entries = model === DYNAMIC_MODEL ? [{ model, trainingOptions: dynamicOptions }] : []; return Response.json({ @@ -112,11 +143,11 @@ afterEach(() => { async function invoke( command: AnyCommand, flags: Record, - options: { dryRun?: boolean; withConsole?: boolean } = {}, + options: { dryRun?: boolean; withConsole?: boolean; language?: "en-US" | "zh-CN" } = {}, ) { let stdout = ""; let stderr = ""; - const language = "en-US"; + const language = options.language ?? "en-US"; const settings = buildSettings({ flags: { output: "json", dryRun: options.dryRun, ...flags }, file: { language, telemetry: false }, @@ -305,20 +336,94 @@ test("train-options command returns the console configuration verbatim", async ( const parsed = JSON.parse(stdout) as { model: string; training_type: string; + status: string; training_options: { defaults: Record; supportedCombinations: unknown[] }; }; expect(parsed.model).toBe(DYNAMIC_MODEL); expect(parsed.training_type).toBe("cpt"); + expect(parsed.status).toBe("configured"); expect(parsed.training_options.defaults).toEqual({ modality: "vision", reasoning_mode: "instruct", }); expect(parsed.training_options.supportedCombinations).toHaveLength(1); + expect(catalogQueries).toEqual([]); }); -test("train-options command returns null for models without dynamic options", async () => { - const { stdout, exitCode } = await invoke(finetuneTrainOptions, { baseModel: "qwen3-8b" }); +test.each(["sft", "cpt"])( + "train-options command reports not_configured once the catalog confirms the model (%s)", + async (trainingType) => { + const { stdout, exitCode } = await invoke(finetuneTrainOptions, { + baseModel: "qwen3-8b", + trainingType, + }); + expect(exitCode).toBe(0); + expect(consoleApis).toEqual([MODEL_TRAIN_OPTIONS_API]); + // The catalog check runs after the console call and stays anonymous. + expect(catalogQueries).toEqual(["qwen3-8b"]); + expect(catalogAuth).toEqual([null]); + const parsed = JSON.parse(stdout) as { status: string; training_options: unknown }; + expect(parsed.status).toBe("not_configured"); + expect(parsed.training_options).toBeNull(); + }, +); + +test("train-options command fails with a usage error for a model missing from the catalog", async () => { + const { stdout, stderr, exitCode } = await invoke(finetuneTrainOptions, { + baseModel: "qwen3-8b-typo", + }); + expect(exitCode).toBe(2); + expect(stdout).toBe(""); + const parsed = JSON.parse(stderr) as { error: { code: number; message: string; hint: string } }; + expect(parsed.error.code).toBe(2); + expect(parsed.error.message).toBe( + 'No trainable base model named "qwen3-8b-typo" was found in the model catalog, and it has no dynamic train options.', + ); + expect(parsed.error.hint).toBe( + "Check the model id with finetune capability --base-model qwen3-8b-typo.", + ); +}); + +test("train-options command degrades to unverified when the catalog lookup fails", async () => { + catalogFailure = new Error("Console CLI gateway failed: HTTP 503 Service Unavailable"); + const { stdout, stderr, exitCode } = await invoke(finetuneTrainOptions, { + baseModel: "qwen3-8b", + }); expect(exitCode).toBe(0); - const parsed = JSON.parse(stdout) as { training_options: unknown }; + expect(stderr).toMatch(/TRAINING_CAPABILITY_LOOKUP_FAILED/); + expect(stderr).toMatch(/HTTP 503/); + const parsed = JSON.parse(stdout) as { status: string; training_options: unknown }; + expect(parsed.status).toBe("unverified"); expect(parsed.training_options).toBeNull(); + + const localized = await invoke( + finetuneTrainOptions, + { baseModel: "qwen3-8b", output: "text" }, + { language: "zh-CN" }, + ); + expect(localized.exitCode).toBe(0); + expect(localized.stderr).toMatch(/模型目录查询失败/); + expect(localized.stdout).toMatch(/无法在模型目录中确认该模型存在/); }); + +test.each([ + { label: "not_configured", baseModel: "qwen3-8b", exitCode: 0, pattern: /未配置动态训练选项/ }, + { + label: "an unknown model", + baseModel: "qwen3-8b-typo", + exitCode: 2, + pattern: /模型目录中未找到名为 "qwen3-8b-typo"/, + }, +])( + "train-options command localizes the $label text output", + async ({ baseModel, exitCode, pattern }) => { + const { + stdout, + stderr, + exitCode: actual, + } = await invoke(finetuneTrainOptions, { baseModel, output: "text" }, { language: "zh-CN" }); + expect(actual).toBe(exitCode); + // Results go to stdout, errors to stderr. + expect(exitCode === 0 ? stdout : stderr).toMatch(pattern); + }, +); diff --git a/packages/commands/tests/output/fixtures/training-deployment.json b/packages/commands/tests/output/fixtures/training-deployment.json index 6e70eb3d1..28f2fb555 100644 --- a/packages/commands/tests/output/fixtures/training-deployment.json +++ b/packages/commands/tests/output/fixtures/training-deployment.json @@ -744,7 +744,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 }\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}\n", "data": { "action": "finetune.create", "body": { @@ -752,7 +752,8 @@ "training_file_ids": ["file-fixture"], "training_type": "efficient_sft", "hyper_parameters": { - "batch_size": 4 + "batch_size": 4, + "n_epochs": 3 } } }, diff --git a/packages/core/package.json b/packages/core/package.json index 075225ccc..32f474361 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-core", - "version": "2.12.0", + "version": "2.12.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/core/src/client/endpoints.ts b/packages/core/src/client/endpoints.ts index 0b8304f4c..6a1294801 100644 --- a/packages/core/src/client/endpoints.ts +++ b/packages/core/src/client/endpoints.ts @@ -324,6 +324,11 @@ export function finetuneParamsPath(): string { return "/api/v1/fine-tunes/fine-tunes-params"; } +/** GET /api/v1/fine-tunes/preset-datasets — preset datasets available for mixing. */ +export function finetunePresetDatasetsPath(): string { + return "/api/v1/fine-tunes/preset-datasets"; +} + /** GET /api/v1/fine-tunes/{job_id}/basic_metrics — training metrics. */ export function finetuneBasicMetricsPath(jobId: string): string { return `/api/v1/fine-tunes/${encodeURIComponent(jobId)}/basic_metrics`; diff --git a/packages/core/src/finetune/api.ts b/packages/core/src/finetune/api.ts index 32bb6090a..375b6a9a8 100644 --- a/packages/core/src/finetune/api.ts +++ b/packages/core/src/finetune/api.ts @@ -12,6 +12,7 @@ import { finetuneCheckpointsPath, finetuneExportPath, finetuneParamsPath, + finetunePresetDatasetsPath, finetuneBasicMetricsPath, } from "../client/endpoints.ts"; import type { Client } from "../client/client.ts"; @@ -26,6 +27,7 @@ import type { ListCheckpointsResponse, ExportCheckpointResponse, GetFineTuneParamsResponse, + ListPresetDatasetsResponse, ListBasicMetricsResponse, } from "./types.ts"; @@ -201,6 +203,51 @@ export async function getFineTuneParams( }); } +export interface ListPresetDatasetsParams { + /** Base model ID (e.g. qwen3-8b), or a platform fine-tuned model for continued training. */ + inputModel: string; + /** Server training_type: sft | efficient_sft | dpo_full | dpo_lora | cpt. */ + trainingType: string; + /** + * Base-model training config version. Omit for the latest applicable one; for + * continued training the source job's base-model version is reused. + */ + version?: string; + /** + * Training-option context, sent as a single `hyper_parameters` query + * parameter holding the JSON-serialized object. The options narrow the + * candidate list; omit when no extra condition is selected. + */ + trainOptions?: Record; + /** Sent as X-DashScope-WorkSpace; use the job's owning workspace. */ + workspaceId?: string; + signal?: AbortSignal; +} + +/** + * GET /api/v1/fine-tunes/preset-datasets — preset datasets that can be mixed + * into training for a model / training-type combination. An empty `output` + * is a normal result. + */ +export async function listPresetDatasets( + client: Client, + params: ListPresetDatasetsParams, +): Promise { + const qs = new URLSearchParams(); + qs.set("input_model", params.inputModel); + qs.set("training_type", params.trainingType); + if (params.version) qs.set("version", params.version); + if (params.trainOptions && Object.keys(params.trainOptions).length > 0) { + qs.set("hyper_parameters", JSON.stringify(params.trainOptions)); + } + return client.requestJson({ + path: `${finetunePresetDatasetsPath()}?${qs.toString()}`, + method: "GET", + headers: workspaceHeaders(params.workspaceId), + signal: params.signal, + }); +} + export interface ListBasicMetricsParams { pageNo?: number; pageSize?: number; diff --git a/packages/core/src/finetune/index.ts b/packages/core/src/finetune/index.ts index f39b7833b..100680a4a 100644 --- a/packages/core/src/finetune/index.ts +++ b/packages/core/src/finetune/index.ts @@ -6,4 +6,5 @@ export * from "./train-options.ts"; export * from "./preflight.ts"; export * from "./profiles/index.ts"; export * from "./price.ts"; +export * from "./oss-mount.ts"; export * from "./rl/index.ts"; diff --git a/packages/core/src/finetune/oss-mount.ts b/packages/core/src/finetune/oss-mount.ts new file mode 100644 index 000000000..1ae684e25 --- /dev/null +++ b/packages/core/src/finetune/oss-mount.ts @@ -0,0 +1,85 @@ +/** + * OSS-mounted dataset source of `POST /api/v1/fine-tunes`. + * + * A dataset can be read in place from an OSS bucket instead of being uploaded: + * the uncompressed dataset folder is uploaded to OSS as-is (the service cannot + * mount a zip) and the job points at it with `data_source_type: "oss_mount"`. + * Nothing here reaches OSS; a wrong bucket, key or region is judged by the server. + */ +import type { LocalizedText } from "../types/command.ts"; +import type { FineTuneDatasetDescriptor } from "./types.ts"; + +/** Region used for every mount when no region flag is given. */ +export const DEFAULT_OSS_MOUNT_REGION = "cn-beijing"; + +/** Scheme that marks a dataset entry as an OSS mount. */ +const OSS_MOUNT_SCHEME = /^oss:\/\//i; + +export interface OssMountLocation { + bucket: string; + /** Object key; for a multi-file dataset, the path of its data.jsonl. */ + filePath: string; +} + +export type OssMountParse = + | { valid: true; location: OssMountLocation } + | { valid: false; reason: Exclude }; + +/** Whether a dataset entry addresses an OSS mount rather than a file-id or local path. */ +export function isOssMountToken(token: string): boolean { + return OSS_MOUNT_SCHEME.test(token); +} + +/** + * Parse `oss:///` and check its shape. The bucket and key + * cannot be checked from here. + */ +export function parseOssMountUri(token: string): OssMountParse { + const remainder = token.replace(OSS_MOUNT_SCHEME, ""); + const slashIndex = remainder.indexOf("/"); + const bucket = slashIndex === -1 ? remainder : remainder.slice(0, slashIndex); + const filePath = slashIndex === -1 ? "" : remainder.slice(slashIndex + 1); + if (bucket === "") { + return { + valid: false, + reason: { + "en-US": "is missing the bucket; expected oss:///.", + "zh-CN": "缺少 bucket,应形如 oss:///。", + }, + }; + } + if (filePath === "") { + return { + valid: false, + reason: { + "en-US": + "is missing the object key; use oss:/// (for a multi-file dataset, the path of its data.jsonl).", + "zh-CN": + "缺少 object key,应形如 oss:///(多文件数据集指向其 data.jsonl 的路径)。", + }, + }; + } + if (/\.zip$/i.test(filePath)) { + return { + valid: false, + reason: { + "en-US": + "points at a zip file, which cannot be mounted; upload the uncompressed dataset folder and point at its data.jsonl.", + "zh-CN": + "指向 zip 文件,无法挂载;请将未压缩的数据集文件夹上传到 OSS,并指向其中的 data.jsonl。", + }, + }; + } + return { valid: true, location: { bucket, filePath } }; +} + +/** Request entry that mounts a dataset from OSS. */ +export function buildOssMountDataset( + location: OssMountLocation, + region: string, +): FineTuneDatasetDescriptor { + return { + data_source_type: "oss_mount", + mount_storage: { region, bucket: location.bucket, file_path: location.filePath }, + }; +} diff --git a/packages/core/src/finetune/train-options.ts b/packages/core/src/finetune/train-options.ts index 67de0e939..969628ca6 100644 --- a/packages/core/src/finetune/train-options.ts +++ b/packages/core/src/finetune/train-options.ts @@ -1,5 +1,7 @@ import type { ConsoleCall } from "../console/gateway.ts"; import { unwrapResponse } from "../console/models.ts"; +import { BailianError } from "../errors/base.ts"; +import { ExitCode } from "../errors/codes.ts"; /** * Console (zelda) API listing the dynamic train options configured per model. @@ -42,10 +44,29 @@ export async function fetchModelTrainOptions( }); const unwrapped = unwrapResponse(result as Record); // unwrapResponse returns the inner `data`, which is the per-model entries - // array for this API; tolerate an object wrapper as well. - const entries = Array.isArray(unwrapped) - ? (unwrapped as Array>) - : ((unwrapped.data as Array> | undefined) ?? []); + // array for this API (its `data` explicitly null when nothing is configured); + // tolerate an object wrapper as well. Any other shape is reported rather than + // read as "no dynamic options". + const unexpectedShape = () => + new BailianError( + `Console API ${MODEL_TRAIN_OPTIONS_API} returned an unexpected response shape.`, + ExitCode.GENERAL, + undefined, + { rawResponse: JSON.stringify(result).slice(0, 500) }, + ); + let entries: Array>; + if (Array.isArray(unwrapped)) { + entries = unwrapped as Array>; + } else if ( + unwrapped && + typeof unwrapped === "object" && + "data" in unwrapped && + (unwrapped.data === null || Array.isArray(unwrapped.data)) + ) { + entries = (unwrapped.data ?? []) as Array>; + } else { + throw unexpectedShape(); + } const match = entries.find((entry) => entry.model === model); const options = match?.trainingOptions as ModelTrainOptions | undefined; return options?.enabled === true ? options : null; diff --git a/packages/core/src/finetune/types.ts b/packages/core/src/finetune/types.ts index 72738a3c0..91319196a 100644 --- a/packages/core/src/finetune/types.ts +++ b/packages/core/src/finetune/types.ts @@ -20,16 +20,32 @@ export interface FineTuneHyperParameters { [k: string]: unknown; } +/** Dataset read in place from an OSS bucket (`data_source_type: "oss_mount"`). */ +export interface FineTuneOssMountStorage { + /** Region ID of the bucket; whether it can be mounted from is judged by the server. */ + region: string; + bucket: string; + /** Object key; for a multi-file dataset, the path of its data.jsonl. */ + file_path: string; +} + +/** One dataset source: an uploaded file, or an OSS bucket mounted in place. */ +export type FineTuneDatasetSource = + | { data_source_type: "file_id"; file_id: string } + | { data_source_type: "oss_mount"; mount_storage: FineTuneOssMountStorage }; + +/** Which dataset list an entry belongs to. */ +export type FineTuneDatasetSlot = "training" | "validation"; + /** - * Dataset descriptor used by OPD (pg_opd) jobs. The server also accepts the - * flat `training_file_ids` form, but OPD submissions and readbacks use these - * descriptors, so the CLI sends the same shape. + * Entry of `training_datasets` / `validation_datasets`. OPD (pg_opd) submits + * and reads back entries with their slot; the create API takes no slot, so the + * CLI omits it there. The server also accepts the flat `training_file_ids` + * form, but it cannot carry a mount. */ -export interface FineTuneDatasetDescriptor { - type: "training" | "validation"; - data_source_type: "file_id"; - file_id: string; -} +export type FineTuneDatasetDescriptor = FineTuneDatasetSource & { + type?: FineTuneDatasetSlot; +}; /** MTU resource configuration for OPD jobs (kept separate from hyper_parameters). */ export interface FineTuneResourceConfig { @@ -43,7 +59,10 @@ export interface FineTuneResourceConfig { export interface CreateFineTuneRequest { /** Base model ID, or a previously fine-tuned model ID for continued training. */ model: string; - /** Flat file-id form (sft/dpo/cpt). OPD uses training_datasets instead. */ + /** + * Flat file-id form, sent unless a dataset is mounted from OSS. A request + * with a mount sends `training_datasets` instead, which can carry both kinds. + */ training_file_ids?: string[]; /** * Server-supported values: `cpt | sft | efficient_sft | dpo_full | dpo_lora | pg_opd`. @@ -67,9 +86,9 @@ export interface CreateFineTuneRequest { finetuned_output_suffix?: string; /** OPD (pg_opd): platform-registered teacher model ID. */ teacher_model?: string; - /** OPD (pg_opd): training dataset descriptors. */ + /** Dataset entries: OPD jobs, or any job that mounts a dataset from OSS. */ training_datasets?: FineTuneDatasetDescriptor[]; - /** OPD (pg_opd): validation dataset descriptors. */ + /** Validation dataset entries, in the same shape as training_datasets. */ validation_datasets?: FineTuneDatasetDescriptor[]; /** OPD (pg_opd): MTU charge type / spec / capacity. */ resource_config?: FineTuneResourceConfig; @@ -273,6 +292,27 @@ export interface GetFineTuneParamsResponse { [k: string]: unknown; } +/** + * GET /api/v1/fine-tunes/preset-datasets 的 `output[]` 元素。 + * `dataset_code` 区分大小写,是后续使用预置数据集时的标识,原样保留。 + */ +export interface PresetDataset { + dataset_code?: string; + dataset_title?: string; + dataset_desc?: string; + [k: string]: unknown; +} + +/** + * GET /api/v1/fine-tunes/preset-datasets response。 + * 空 `output` 表示当前条件下没有可混入的预置数据集,属于正常结果。 + */ +export interface ListPresetDatasetsResponse { + request_id?: string; + output?: PresetDataset[]; + [k: string]: unknown; +} + /** * GET /api/v1/fine-tunes/{job_id}/basic_metrics 的 `output.metrics[]` 元素。 * 每条指标记录的 JSON 原样返回(step + 动态指标字段),内部 key 不做改名。 diff --git a/packages/core/tests/finetune-oss-mount.test.ts b/packages/core/tests/finetune-oss-mount.test.ts new file mode 100644 index 000000000..5fff21593 --- /dev/null +++ b/packages/core/tests/finetune-oss-mount.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from "vite-plus/test"; +import { buildOssMountDataset, isOssMountToken, parseOssMountUri } from "../src/index.ts"; + +describe("fine-tune OSS mount entry", () => { + test("isOssMountToken only matches the oss scheme", () => { + expect(isOssMountToken("oss://bucket/key.jsonl")).toBe(true); + expect(isOssMountToken("OSS://bucket/key.jsonl")).toBe(true); + expect(isOssMountToken("file-aaa")).toBe(false); + expect(isOssMountToken("./train.jsonl")).toBe(false); + expect(isOssMountToken("https://bucket/key.jsonl")).toBe(false); + }); + + test("parseOssMountUri splits the bucket from the object key at the first slash", () => { + expect(parseOssMountUri("oss://my-bucket/datasets/train/data.jsonl")).toEqual({ + valid: true, + location: { bucket: "my-bucket", filePath: "datasets/train/data.jsonl" }, + }); + // The key is passed through untouched: decoding and existence are the service's call. + expect(parseOssMountUri("oss://my-bucket/a%20b/c.jsonl")).toEqual({ + valid: true, + location: { bucket: "my-bucket", filePath: "a%20b/c.jsonl" }, + }); + expect(parseOssMountUri("oss://my-bucket/data.jsonl")).toEqual({ + valid: true, + location: { bucket: "my-bucket", filePath: "data.jsonl" }, + }); + }); + + test.each([ + ["no bucket", "oss:///data.jsonl", /missing the bucket/], + ["neither bucket nor key", "oss://", /missing the bucket/], + ["no object key", "oss://my-bucket", /missing the object key/], + ["empty object key", "oss://my-bucket/", /missing the object key/], + ["zip cannot be mounted", "oss://my-bucket/train.zip", /zip file/], + ["zip is case-insensitive", "oss://my-bucket/train.ZIP", /zip file/], + ])("parseOssMountUri rejects %s in both languages", (_case, token, english) => { + const parsed = parseOssMountUri(token); + expect(parsed.valid).toBe(false); + if (parsed.valid) throw new Error("expected an invalid entry"); + expect(parsed.reason["en-US"]).toMatch(english); + expect(parsed.reason["zh-CN"]).not.toEqual(parsed.reason["en-US"]); + }); + + test("buildOssMountDataset maps the location onto mount_storage without a slot", () => { + expect( + buildOssMountDataset( + { bucket: "my-bucket", filePath: "datasets/train/data.jsonl" }, + "ap-southeast-1", + ), + ).toEqual({ + data_source_type: "oss_mount", + mount_storage: { + region: "ap-southeast-1", + bucket: "my-bucket", + file_path: "datasets/train/data.jsonl", + }, + }); + }); +}); diff --git a/packages/core/tests/finetune-preset-datasets-api.test.ts b/packages/core/tests/finetune-preset-datasets-api.test.ts new file mode 100644 index 000000000..bfddf8149 --- /dev/null +++ b/packages/core/tests/finetune-preset-datasets-api.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, test, vi } from "vite-plus/test"; +import { listPresetDatasets, type Client } from "../src/index.ts"; + +function mockClient(response: unknown = {}) { + const requestJson = vi.fn().mockResolvedValue(response); + return { client: { requestJson } as unknown as Client, requestJson }; +} + +describe("fine-tune preset datasets API", () => { + test("listPresetDatasets serializes optional params in a fixed order and sends the workspace header", async () => { + const { client, requestJson } = mockClient({ request_id: "req-preset", output: [] }); + const response = await listPresetDatasets(client, { + inputModel: "qwen3-8b", + trainingType: "efficient_sft", + version: "v1", + trainOptions: { modality: "text", reasoning_mode: "thinking" }, + workspaceId: "ws-123", + }); + expect(response).toEqual({ request_id: "req-preset", output: [] }); + expect(requestJson).toHaveBeenCalledWith({ + path: "/api/v1/fine-tunes/preset-datasets?input_model=qwen3-8b&training_type=efficient_sft&version=v1&hyper_parameters=%7B%22modality%22%3A%22text%22%2C%22reasoning_mode%22%3A%22thinking%22%7D", + method: "GET", + headers: { "X-DashScope-WorkSpace": "ws-123" }, + signal: undefined, + }); + }); + + test("listPresetDatasets sends a bare path when no optional params are set", async () => { + const { client, requestJson } = mockClient(); + await listPresetDatasets(client, { inputModel: "qwen3-8b", trainingType: "dpo_full" }); + expect(requestJson).toHaveBeenCalledWith({ + path: "/api/v1/fine-tunes/preset-datasets?input_model=qwen3-8b&training_type=dpo_full", + method: "GET", + headers: undefined, + signal: undefined, + }); + }); + + test("listPresetDatasets omits hyper_parameters for an empty train-options object", async () => { + const { client, requestJson } = mockClient(); + await listPresetDatasets(client, { + inputModel: "qwen3-8b", + trainingType: "efficient_sft", + trainOptions: {}, + }); + expect(requestJson.mock.calls[0]?.[0].path).toBe( + "/api/v1/fine-tunes/preset-datasets?input_model=qwen3-8b&training_type=efficient_sft", + ); + }); +}); diff --git a/packages/core/tests/finetune-train-options.test.ts b/packages/core/tests/finetune-train-options.test.ts index fe6b1038f..fb58ac819 100644 --- a/packages/core/tests/finetune-train-options.test.ts +++ b/packages/core/tests/finetune-train-options.test.ts @@ -29,7 +29,7 @@ function trainOptions(overrides: Partial = {}): ModelTrainOpt }; } -function gatewayEnvelope(entries: unknown[]): unknown { +function gatewayEnvelope(entries: unknown): unknown { return { code: "200", successResponse: true, @@ -98,6 +98,25 @@ describe("fetchModelTrainOptions", () => { ); expect(options?.enabled).toBe(true); }); + + test("returns null when the entries payload is null", async () => { + const options = await fetchModelTrainOptions( + async () => gatewayEnvelope(null), + "qwen3-8b", + "sft", + ); + expect(options).toBeNull(); + }); + + test.each([ + ["a paginated object instead of the entries array", gatewayEnvelope({ list: [], total: 0 })], + ["an empty object", gatewayEnvelope({})], + ["a string payload", gatewayEnvelope("ok")], + ])("rejects %s", async (_label, response) => { + await expect(fetchModelTrainOptions(async () => response, "qwen3-8b", "sft")).rejects.toThrow( + /unexpected response shape/, + ); + }); }); describe("resolveTrainOptions", () => { diff --git a/packages/kscli/package.json b/packages/kscli/package.json index f6cba7c2e..f4d28514b 100644 --- a/packages/kscli/package.json +++ b/packages/kscli/package.json @@ -1,6 +1,6 @@ { "name": "knowledge-studio-cli", - "version": "2.12.0", + "version": "2.12.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 0ab52d15c..2bfbf8c25 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-runtime", - "version": "2.12.0", + "version": "2.12.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 c2ab30c7e..f3a2c0b1c 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-cli metadata: - version: "2.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-finetune/SKILL.md b/skills/bailian-finetune/SKILL.md index 535d0e6fe..7e2597572 100644 --- a/skills/bailian-finetune/SKILL.md +++ b/skills/bailian-finetune/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-finetune metadata: - version: "2.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >- @@ -55,43 +55,45 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-f ## When to use which command -| Intent | Command | -| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| Validate / upload training data | `bl dataset validate` / `upload` (`.jsonl` or `.zip`) | -| Prepare decision training data (split / teacher generate) | `bl dataset split` / `bl dataset generate` (`--schema decision` only today; see below) | -| Dataset list / detail / delete | `bl dataset list` / `get` / `delete` | -| Console dataset groups / discover version and file IDs | `bl dataset groups` → `bl dataset version --dataset-group-id ` (Console auth) | -| Console version detail / import and release state | `bl dataset version --dataset-id ` (Console auth; optional `--include-status`) | -| Console independent deployment services | `bl deploy instances` (Console auth; not capacity instances or replicas) | -| Create a fine-tuning job | `bl finetune text\|audio\|image create` | -| Decision-model fine-tuning (choice/noul/score data) | `bl finetune decision create --base-model decision-model-preview-2026-09-24 --datasets ` (fixed efficient_sft; see below) | -| Job list / detail / follow | `bl finetune list` / `get` / `watch` / `logs` | -| Artifacts and export | `bl finetune checkpoints` / `export` | -| Quantize / compress a full model | `bl finetune compress templates` / `create` / `watch` / `get` / `logs` / `list` | -| Cancel / delete a compression job | `bl finetune compress cancel` / `delete` | -| Cancel / delete a fine-tuning job | `bl finetune cancel` / `delete` | -| Reinforcement-learning (RL) training | `bl finetune rl run` / `get` / `list` / `watch` / `logs` / `cancel` / `delete` (sandbox) | -| RL / OPD authorization check and enablement | `bl finetune rl authorize` / `bl finetune opd authorize` (Console auth; `--authorize` to mutate) | -| OPD distillation training | `bl finetune opd run --teacher-model ` / `get` / `watch` / `logs` / `cancel` / `delete` (OpenAPI; forces `pg_opd`; list via `finetune list`) | -| OPD training / resource parameter query | `bl finetune opd params --base-model [--param-type hyper\|resource]` | -| Prepare / check / clean the RL sandbox runtime | `bl finetune runtime prepare` / `doctor` / `clean` | -| Import an external OSS LoRA model | Hand-off: `bl cmodel import *` — hub-owned commands; see `bailian-cli` reference or `bl cmodel --help` | -| Trainable capability lookup | `bl finetune capability` | -| Dynamic train-option combinations (modality / reasoning-mode) | `bl finetune train-options --base-model ` (Console auth; params/text create precheck against it automatically) | -| Deploy / lifecycle | `bl deploy text\|audio\|image create`, `list` / `get` / `update` / `scale` / `delete` / `models` | -| Query throughput reservations | `bl deploy list --plan ptu` / `bl deploy get` | -| Query capacity instances | `bl deploy capacity list` / `get` | -| Query / wait for a capacity operation | `bl deploy operation get` / `wait` | -| Buy / scale / renew / release capacity | `bl deploy capacity create` / `scale` / `renew` / `delete` | -| Enable / disable automatic renewal | `bl deploy capacity auto-renew enable` / `disable` | -| Unsubscribe a prepaid instance | `bl deploy capacity unsubscribe` (builds the billing console refund link) | -| Configure ModelCode overflow strategy | `bl deploy overflow` | -| List model-routing versions | `bl deploy router versions` | -| Create a model router | `bl deploy router create --name --route-version --strategy --candidates ` | -| List model routers | `bl deploy router list` | -| Get model router detail | `bl deploy router get --deployed-model ` | -| Update selected model router fields | `bl deploy router update --deployed-model [--route-version ] [--strategy ] [--candidates ]` | -| Delete a model router | `bl deploy router delete --deployed-model ` | +| Intent | Command | +| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Validate / upload training data | `bl dataset validate` / `upload` (`.jsonl` or `.zip`) | +| Prepare decision training data (split / teacher generate) | `bl dataset split` / `bl dataset generate` (`--schema decision` only today; see below) | +| Dataset list / detail / delete | `bl dataset list` / `get` / `delete` | +| Console dataset groups / discover version and file IDs | `bl dataset groups` → `bl dataset version --dataset-group-id ` (Console auth) | +| Console version detail / import and release state | `bl dataset version --dataset-id ` (Console auth; optional `--include-status`) | +| Console independent deployment services | `bl deploy instances` (Console auth; not capacity instances or replicas) | +| Create a fine-tuning job | `bl finetune text\|audio\|image create` | +| Mount an OSS dataset into a training job | `bl finetune text create --datasets oss:/// [--oss-region ]` | +| Decision-model fine-tuning (choice/noul/score data) | `bl finetune decision create --base-model decision-model-preview-2026-09-24 --datasets ` (fixed efficient_sft; see below) | +| Job list / detail / follow | `bl finetune list` / `get` / `watch` / `logs` | +| Artifacts and export | `bl finetune checkpoints` / `export` | +| Quantize / compress a full model | `bl finetune compress templates` / `create` / `watch` / `get` / `logs` / `list` | +| Cancel / delete a compression job | `bl finetune compress cancel` / `delete` | +| Cancel / delete a fine-tuning job | `bl finetune cancel` / `delete` | +| Reinforcement-learning (RL) training | `bl finetune rl run` / `get` / `list` / `watch` / `logs` / `cancel` / `delete` (sandbox) | +| RL / OPD authorization check and enablement | `bl finetune rl authorize` / `bl finetune opd authorize` (Console auth; `--authorize` to mutate) | +| OPD distillation training | `bl finetune opd run --teacher-model ` / `get` / `watch` / `logs` / `cancel` / `delete` (OpenAPI; forces `pg_opd`; list via `finetune list`) | +| OPD training / resource parameter query | `bl finetune opd params --base-model [--param-type hyper\|resource]` | +| Prepare / check / clean the RL sandbox runtime | `bl finetune runtime prepare` / `doctor` / `clean` | +| Import an external OSS LoRA model | Hand-off: `bl cmodel import *` — hub-owned commands; see `bailian-cli` reference or `bl cmodel --help` | +| Trainable capability lookup | `bl finetune capability` | +| Dynamic train-option combinations (modality / reasoning-mode) | `bl finetune train-options --base-model ` (Console auth; params / preset-datasets / text create precheck against it automatically) | +| Preset datasets that can be mixed into training | `bl finetune preset-datasets --base-model [--training-type ]` (API key; pass `dataset_code` to `finetune text create --augmentation-types`, lowercased, with `--augmentation-ratio`) | +| Deploy / lifecycle | `bl deploy text\|audio\|image create`, `list` / `get` / `update` / `scale` / `delete` / `models` | +| Query throughput reservations | `bl deploy list --plan ptu` / `bl deploy get` | +| Query capacity instances | `bl deploy capacity list` / `get` | +| Query / wait for a capacity operation | `bl deploy operation get` / `wait` | +| Buy / scale / renew / release capacity | `bl deploy capacity create` / `scale` / `renew` / `delete` | +| Enable / disable automatic renewal | `bl deploy capacity auto-renew enable` / `disable` | +| Unsubscribe a prepaid instance | `bl deploy capacity unsubscribe` (builds the billing console refund link) | +| Configure ModelCode overflow strategy | `bl deploy overflow` | +| List model-routing versions | `bl deploy router versions` | +| Create a model router | `bl deploy router create --name --route-version --strategy --candidates ` | +| List model routers | `bl deploy router list` | +| Get model router detail | `bl deploy router get --deployed-model ` | +| Update selected model router fields | `bl deploy router update --deployed-model [--route-version ] [--strategy ] [--candidates ]` | +| Delete a model router | `bl deploy router delete --deployed-model ` | The `capacity list` / `get`, `operation get` / `wait` and `deploy list` / `get` queries are read-only. Capacity values are kTPM; effective, configured and target capacities are distinct. `deploy list --status` filters only the fetched page locally, with the server total left unfiltered. `operation get` reports status as data; `operation wait` exits non-zero on failure or timeout and refreshes capacity after success. Use IDs returned by the API; waiting never retries a write. diff --git a/skills/bailian-finetune/reference/finetune.md b/skills/bailian-finetune/reference/finetune.md index abc9fd1ae..d99734b2d 100644 --- a/skills/bailian-finetune/reference/finetune.md +++ b/skills/bailian-finetune/reference/finetune.md @@ -38,6 +38,7 @@ Index: [index.md](index.md) | `bl finetune opd run` | API Key | Submit a pure Model OPD distillation job (pg_opd) via the fine-tunes OpenAPI | | `bl finetune opd watch` | API Key | Probe an OPD job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | | `bl finetune params` | API Key | Query the training hyper-parameter configuration for a base model | +| `bl finetune preset-datasets` | API Key | List the preset datasets that can be mixed into a fine-tuning job | | `bl finetune price` | Console | Estimate the training cost for a fine-tune job (token billing) | | `bl finetune rl authorize` | Console | Check and authorize reinforcement-learning access (whitelist, service roles, enablement) | | `bl finetune rl cancel` | API Key | Cancel a running RL job | @@ -1231,6 +1232,58 @@ bl finetune params --base-model qwen3-8b --output json bl finetune params --base-model qwen3-8b --dry-run ``` +### `bl finetune preset-datasets` + +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Name** | `finetune preset-datasets` | +| **Description** | List the preset datasets that can be mixed into a fine-tuning job | +| **Authentication** | API Key | +| **Usage** | `bl finetune preset-datasets --base-model [--training-type ] [--model-version ] [--modality ] [--reasoning-mode ]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------------------------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--base-model ` | string | yes | Base model to list preset datasets for (e.g. qwen3-8b) | +| `--training-type ` | string | no | Training type: sft \| sft-lora \| dpo \| dpo-lora \| cpt (default: sft-lora). Mapped to the server's training_type (e.g. sft-lora -> efficient_sft). | +| `--model-version ` | string | no | Base-model training-config version. Omit to use the latest applicable config (or, when resuming, the source job's version). | +| `--modality ` | string | no | Training modality: text \| vision. Only meaningful for models with dynamic train options; sent as modality inside hyper_parameters. | +| `--reasoning-mode ` | string | no | Reasoning mode: instruct (non-thinking) \| thinking. Only meaningful for models with dynamic train options; sent as reasoning_mode inside hyper_parameters. | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | +| `--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 + +- Queries GET /api/v1/fine-tunes/preset-datasets. Each entry keeps the server field names verbatim (dataset_code, dataset_title, dataset_desc); dataset_code is case-sensitive as returned; finetune text create sends it lowercased as augmentation_types (e.g. mix_V2 -> mix_v2). An empty output (nothing to mix for this model and training type) is a success with exit code 0. +- --modality / --reasoning-mode travel as one hyper_parameters query parameter (JSON). When a console session is available, the combination is prechecked against the model's supported combinations and omitted options are completed from its defaults; invalid combinations fail with a usage error. Without a console session the check is skipped with a warning and the server result is authoritative. + +#### Examples + +```bash +bl finetune preset-datasets --base-model qwen3-8b +``` + +```bash +bl finetune preset-datasets --base-model qwen3-8b --training-type sft-lora --output json +``` + +```bash +bl finetune preset-datasets --base-model qwen3.6-plus-base-2026-04-02 --training-type sft --modality vision --reasoning-mode instruct +``` + +```bash +bl finetune preset-datasets --base-model qwen3-8b --training-type dpo +``` + +```bash +bl finetune preset-datasets --base-model qwen3-8b --dry-run +``` + ### `bl finetune price` | Field | Value | @@ -1705,48 +1758,51 @@ bl finetune runtime prepare --dry-run ### `bl finetune text create` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `finetune text create` | -| **Description** | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | -| **Authentication** | API Key | -| **Usage** | `bl finetune text create --base-model --datasets [--validations ] [--job-name ] [--priority ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ] [--modality ] [--reasoning-mode ]` | +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `finetune text create` | +| **Description** | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | +| **Authentication** | API Key | +| **Usage** | `bl finetune text create --base-model --datasets [--validations ] [--oss-region ] [--job-name ] [--priority ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ] [--data-augmentation ] [--augmentation-types ] [--augmentation-ratio ] [--modality ] [--reasoning-mode ]` | #### 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 | Comma-separated dataset file IDs or local paths (.jsonl for text, .zip for audio/image/video). Local paths are uploaded (validated) first, then their file-ids are used. | -| `--validations ` | string | no | Comma-separated validation dataset file IDs or local paths (auto-uploaded like --datasets). | -| `--model-name ` | string | no | Output model name (after training) | -| `--suffix ` | string | no | Output suffix appended by the platform (finetuned_output_suffix) | -| `--job-name ` | string | no | Training job display name (job_name) | -| `--priority ` | string | no | Requested scheduling priority; verify the service response | -| `--eval-steps ` | number | no | Validation interval in training steps | -| `--lora-alpha ` | number | no | LoRA scaling coefficient | -| `--lora-dropout ` | number | no | LoRA dropout probability | -| `--lora-rank ` | number | no | LoRA matrix rank | -| `--lr-scheduler-type ` | string | no | Learning rate scheduler supported by the selected model | -| `--save-strategy ` | string | no | Checkpoint saving strategy | -| `--save-total-limit ` | number | no | Maximum number of saved checkpoints | -| `--save-steps ` | number | no | Checkpoint saving interval for strategy=steps | -| `--split ` | number | no | Training fraction when no validation dataset is supplied | -| `--max-split-val-dataset-sample ` | number | no | Maximum automatically split validation samples | -| `--data-augmentation ` | string | no | Mix platform training data (true or false) | -| `--training-type ` | string | no | Training type: sft \| sft-lora \| dpo \| dpo-lora \| cpt (default: sft-lora). Mapping to the server happens at the interface boundary (e.g. sft-lora -> efficient_sft, dpo -> dpo_full). | -| `--n-epochs ` | number | no | Number of epochs; valid values are checked against the selected model | -| `--batch-size ` | number | no | Per-device batch size; range and step are checked against the selected model | -| `--learning-rate ` | string | no | Learning rate as a string to preserve precision (e.g. "1.6e-5") | -| `--max-length ` | number | no | Max sequence length | -| `--modality ` | string | no | Training-option modality sent as hyper_parameters.modality (not the dataset format fixed by this subcommand). Only for models with dynamic train options; valid values come from the model's parameter schema. | -| `--reasoning-mode ` | string | no | Reasoning mode sent as hyper_parameters.reasoning_mode. Only for models with dynamic train options; valid values come from the model's parameter schema. | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | -| `--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 | Comma-separated dataset file IDs, local paths (.jsonl) or OSS mounts (oss:///). Local paths are uploaded (validated) first, then their file-ids are used. An OSS mount is read in place by the service, so it is not validated or uploaded here | +| `--validations ` | string | no | Comma-separated validation dataset file IDs, local paths or OSS mounts (oss:///), handled like --datasets | +| `--model-name ` | string | no | Output model name (after training) | +| `--suffix ` | string | no | Output suffix appended by the platform (finetuned_output_suffix) | +| `--oss-region ` | string | no | Region ID of the OSS buckets mounted by the oss:// entries of --datasets / --validations (default: cn-beijing); sent as given, whether the service can mount from it is judged by the service | +| `--job-name ` | string | no | Training job display name (job_name) | +| `--priority ` | string | no | Requested scheduling priority; verify the service response | +| `--eval-steps ` | number | no | Validation interval in training steps | +| `--lora-alpha ` | number | no | LoRA scaling coefficient | +| `--lora-dropout ` | number | no | LoRA dropout probability | +| `--lora-rank ` | number | no | LoRA matrix rank | +| `--lr-scheduler-type ` | string | no | Learning rate scheduler supported by the selected model | +| `--save-strategy ` | string | no | Checkpoint saving strategy | +| `--save-total-limit ` | number | no | Maximum number of saved checkpoints | +| `--save-steps ` | number | no | Checkpoint saving interval for strategy=steps | +| `--split ` | number | no | Training fraction when no validation dataset is supplied | +| `--max-split-val-dataset-sample ` | number | no | Maximum automatically split validation samples | +| `--data-augmentation ` | string | no | Mix platform preset training data into the job (true or false). Only honored for sft and sft-lora; turned on automatically by --augmentation-types | +| `--augmentation-types ` | string | no | Preset datasets to mix in, comma-separated. Codes come from finetune preset-datasets and are sent lowercased (e.g. mix_V2 -> mix_v2). Requires --augmentation-ratio | +| `--augmentation-ratio ` | string | no | Mix ratio per preset dataset, comma-separated and positionally matching --augmentation-types; each is 0.0~2.0 of the training data volume | +| `--training-type ` | string | no | Training type: sft \| sft-lora \| dpo \| dpo-lora \| cpt (default: sft-lora). Mapping to the server happens at the interface boundary (e.g. sft-lora -> efficient_sft, dpo -> dpo_full). | +| `--n-epochs ` | number | no | Number of epochs; valid values are checked against the selected model | +| `--batch-size ` | number | no | Per-device batch size; range and step are checked against the selected model | +| `--learning-rate ` | string | no | Learning rate as a string to preserve precision (e.g. "1.6e-5") | +| `--max-length ` | number | no | Max sequence length | +| `--modality ` | string | no | Training-option modality sent as hyper_parameters.modality (not the dataset format fixed by this subcommand). Only for models with dynamic train options; valid values come from the model's parameter schema. | +| `--reasoning-mode ` | string | no | Reasoning mode sent as hyper_parameters.reasoning_mode. Only for models with dynamic train options; valid values come from the model's parameter schema. | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | +| `--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 @@ -1755,10 +1811,12 @@ 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; omitted values use platform defaults. +- 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. - 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. +- Mixed training: --data-augmentation turns it on; --augmentation-types selects preset datasets (list them with finetune preset-datasets; codes are sent lowercased, e.g. mix_V2 -> mix_v2) and --augmentation-ratio gives one ratio (0.0~2.0) per type, positionally. Passing types turns data_augmentation on. These three are documented on the create API but absent from the model's parameter schema, so they are not part of the schema check; whether the selected model and training type honors them is decided by the server (documented for sft and sft-lora), and mixed data is billed as training tokens. +- OSS mount: an oss:/// entry of --datasets / --validations is read in place, so it skips local validation, upload and the sample-count pre-check. Upload the uncompressed dataset folder to OSS as-is (a zip cannot be mounted) and, for a multi-file dataset, point at its data.jsonl. Every oss:// entry shares --oss-region. A request with an OSS mount sends training_datasets / validation_datasets instead of training_file_ids / validation_file_ids. #### Examples @@ -1786,6 +1844,10 @@ bl finetune text create --base-model qwen3-8b --datasets ./train.jsonl --trainin bl finetune text create --base-model qwen3-8b --datasets ./jev-train.jsonl --job-name jev-train-v1 --priority L0 --lora-rank 8 --lora-alpha 16 --lora-dropout 0.1 --lr-scheduler-type linear --eval-steps 50 --save-strategy epoch --save-total-limit 3 --split 0.9 --max-split-val-dataset-sample 1000 --data-augmentation false --dry-run ``` +```bash +bl finetune text create --base-model qwen3-8b --datasets ./train.jsonl --training-type sft-lora --augmentation-types mix_V2 --augmentation-ratio 0.5 +``` + ```bash bl finetune text create --base-model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4 ``` @@ -1798,6 +1860,10 @@ bl finetune text create --base-model qwen3.6-plus-base-2026-04-02 --datasets fil bl finetune text create --base-model qwen3-8b --datasets file-xxx --output json ``` +```bash +bl finetune text create --base-model qwen3-8b --datasets oss://my-bucket/datasets/train/data.jsonl --oss-region cn-beijing +``` + ```bash bl finetune text create --base-model qwen3-8b --datasets file-xxx --dry-run ``` @@ -1824,9 +1890,9 @@ bl finetune text create --base-model qwen3-8b --datasets file-xxx --dry-run #### Notes -- Calls the console gateway model-train-options API and requires a console login session. The result keeps the server field names verbatim (optionKeys, optionDefinitions, defaults, supportedCombinations). Models without dynamic train options return training_options: null. -- supportedCombinations is the authority for valid option combinations. finetune params and finetune text create call this same API once as a best-effort precheck when a console session is available: omitted options are completed from defaults and invalid combinations are rejected; without a session the check is skipped with a warning. -- Pass the selected options to finetune params / finetune text create via --modality / --reasoning-mode; they travel as hyper_parameters to the training API. +- Calls the console gateway model-train-options API and requires a console login session. The result keeps the server field names verbatim (optionKeys, optionDefinitions, defaults, supportedCombinations) and carries a status: configured (options were returned), not_configured (the model is confirmed in the trainable catalog and has no dynamic options, so training_options is null) or unverified (no options were returned and the catalog lookup failed). A model id that is not a trainable base model fails with an error instead of returning null. +- supportedCombinations is the authority for valid option combinations. finetune params, finetune preset-datasets and finetune text create call this same API once as a best-effort precheck when a console session is available: omitted options are completed from defaults and invalid combinations are rejected; without a session the check is skipped with a warning. +- Pass the selected options to finetune params / finetune preset-datasets / finetune text create via --modality / --reasoning-mode; they travel as hyper_parameters to the training API. #### Examples diff --git a/skills/bailian-finetune/reference/index.md b/skills/bailian-finetune/reference/index.md index d577eb233..c5536339c 100644 --- a/skills/bailian-finetune/reference/index.md +++ b/skills/bailian-finetune/reference/index.md @@ -79,6 +79,7 @@ Use this index for the skill-scoped quick index and global flags. | `bl finetune opd run` | API Key | Submit a pure Model OPD distillation job (pg_opd) via the fine-tunes OpenAPI | [finetune.md](finetune.md) | | `bl finetune opd watch` | API Key | Probe an OPD job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | | `bl finetune params` | API Key | Query the training hyper-parameter configuration for a base model | [finetune.md](finetune.md) | +| `bl finetune preset-datasets` | API Key | List the preset datasets that can be mixed into a fine-tuning job | [finetune.md](finetune.md) | | `bl finetune price` | Console | Estimate the training cost for a fine-tune job (token billing) | [finetune.md](finetune.md) | | `bl finetune rl authorize` | Console | Check and authorize reinforcement-learning access (whitelist, service roles, enablement) | [finetune.md](finetune.md) | | `bl finetune rl cancel` | API Key | Cancel a running RL job | [finetune.md](finetune.md) | @@ -98,11 +99,11 @@ Use this index for the skill-scoped quick index and global flags. ## By group -| Group | Commands | Reference | -| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -| `dataset` | `delete`, `generate`, `get`, `groups`, `list`, `split`, `upload`, `validate`, `version` | [dataset.md](dataset.md) | -| `deploy` | `audio create`, `capacity auto-renew disable`, `capacity auto-renew enable`, `capacity create`, `capacity delete`, `capacity get`, `capacity list`, `capacity renew`, `capacity scale`, `capacity unsubscribe`, `delete`, `get`, `image create`, `instances`, `list`, `models`, `operation get`, `operation wait`, `overflow`, `pause`, `resume`, `router create`, `router delete`, `router get`, `router list`, `router update`, `router versions`, `scale`, `text create`, `update` | [deploy.md](deploy.md) | -| `finetune` | `audio create`, `cancel`, `capability`, `checkpoints`, `compress cancel`, `compress create`, `compress delete`, `compress get`, `compress list`, `compress logs`, `compress templates`, `compress watch`, `decision create`, `delete`, `export`, `get`, `image create`, `list`, `logs`, `metrics`, `opd authorize`, `opd cancel`, `opd delete`, `opd get`, `opd logs`, `opd params`, `opd run`, `opd watch`, `params`, `price`, `rl authorize`, `rl cancel`, `rl delete`, `rl get`, `rl list`, `rl logs`, `rl run`, `rl watch`, `runtime clean`, `runtime doctor`, `runtime prepare`, `text create`, `train-options`, `video create`, `watch` | [finetune.md](finetune.md) | +| Group | Commands | Reference | +| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | +| `dataset` | `delete`, `generate`, `get`, `groups`, `list`, `split`, `upload`, `validate`, `version` | [dataset.md](dataset.md) | +| `deploy` | `audio create`, `capacity auto-renew disable`, `capacity auto-renew enable`, `capacity create`, `capacity delete`, `capacity get`, `capacity list`, `capacity renew`, `capacity scale`, `capacity unsubscribe`, `delete`, `get`, `image create`, `instances`, `list`, `models`, `operation get`, `operation wait`, `overflow`, `pause`, `resume`, `router create`, `router delete`, `router get`, `router list`, `router update`, `router versions`, `scale`, `text create`, `update` | [deploy.md](deploy.md) | +| `finetune` | `audio create`, `cancel`, `capability`, `checkpoints`, `compress cancel`, `compress create`, `compress delete`, `compress get`, `compress list`, `compress logs`, `compress templates`, `compress watch`, `decision create`, `delete`, `export`, `get`, `image create`, `list`, `logs`, `metrics`, `opd authorize`, `opd cancel`, `opd delete`, `opd get`, `opd logs`, `opd params`, `opd run`, `opd watch`, `params`, `preset-datasets`, `price`, `rl authorize`, `rl cancel`, `rl delete`, `rl get`, `rl list`, `rl logs`, `rl run`, `rl watch`, `runtime clean`, `runtime doctor`, `runtime prepare`, `text create`, `train-options`, `video create`, `watch` | [finetune.md](finetune.md) | ## Global flags diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index 29fb8d0c1..8b8095aa2 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-gen metadata: - version: "2.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-knowledge/SKILL.md b/skills/bailian-knowledge/SKILL.md index e3caa87b5..617abf75b 100644 --- a/skills/bailian-knowledge/SKILL.md +++ b/skills/bailian-knowledge/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-knowledge metadata: - version: "2.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-managed-agent/SKILL.md b/skills/bailian-managed-agent/SKILL.md index aefdeb9ff..d905af739 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.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-memory/SKILL.md b/skills/bailian-memory/SKILL.md index 3742db265..83203cae7 100644 --- a/skills/bailian-memory/SKILL.md +++ b/skills/bailian-memory/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-memory metadata: - version: "2.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-opd/SKILL.md b/skills/bailian-opd/SKILL.md index 3e8e8bbce..7ca4d8795 100644 --- a/skills/bailian-opd/SKILL.md +++ b/skills/bailian-opd/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-opd metadata: - version: "2.12.0" + version: "2.12.1" requires: bins: ["bl", "node"] description: >- diff --git a/skills/bailian-protocol/SKILL.md b/skills/bailian-protocol/SKILL.md index 01395fdce..ba1e8393d 100644 --- a/skills/bailian-protocol/SKILL.md +++ b/skills/bailian-protocol/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-protocol metadata: - version: "2.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-sandbox/SKILL.md b/skills/bailian-sandbox/SKILL.md index b496d0e73..851749793 100644 --- a/skills/bailian-sandbox/SKILL.md +++ b/skills/bailian-sandbox/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-sandbox metadata: - version: "2.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-web-search/SKILL.md b/skills/bailian-web-search/SKILL.md index d780bda95..794a84ca4 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.12.0" + version: "2.12.1" requires: bins: ["bl"] description: >-