diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d61113c..ee0d35cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,21 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and [中文版](CHANGELOG.zh.md) · [README](README.md) · [Contributing](CONTRIBUTING.md) +## [2.11.2] - 2026-11-24 + +### Added + +- **Decision-model fine-tuning pipeline**: End-to-end data preparation and training for decision models. + - `bl dataset generate` synthesizes labeled decision training samples from a `workload.json` business config. + - `bl dataset split` splits a labeled JSONL file into training and evaluation sets. + - `bl finetune decision create` submits decision-model fine-tuning (LoRA / efficient_sft); `bl dataset validate` understands the decision sample schema. +- **`bl finetune train-options`**: New command querying a model's dynamic training options (option definitions, defaults, supported combinations) from the Console. `training_options: null` means the model takes no training options. `--training-type` defaults to `sft`. +- **Training-option flags for text fine-tuning**: `bl finetune text create` accepts `--modality` and `--reasoning-mode` for models with dynamic training options (e.g. vision-fixed models). + +### Changed + +- **Fine-tune parameter preflight**: `bl finetune params` and `bl finetune text create` now check the model's dynamic training options once via the Console when a Console session is available — auto-filling option defaults and rejecting unsupported values or combinations locally before submission. Without a Console session they degrade to a warning and pass through to the server. `finetune params` JSON output adds a `precheck` field describing whether the check ran. + ## [2.11.1] - 2026-11-24 ### Fixed diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index a20ebd4f..fec27662 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -6,6 +6,21 @@ [English](CHANGELOG.md) · [README](README.zh.md) · [参与贡献](CONTRIBUTING.zh.md) +## [2.11.2] - 2026-11-24 + +### 新增 + +- **决策模型精调流水线**:决策模型的数据准备与训练全链路。 + - `bl dataset generate` 依据 `workload.json` 业务配置合成带标注的决策训练样本。 + - `bl dataset split` 将已标注 JSONL 切分为训练集与评估集。 + - `bl finetune decision create` 提交决策模型精调(LoRA / efficient_sft);`bl dataset validate` 支持决策样本格式校验。 +- **`bl finetune train-options`**:新命令,从控制台查询模型的动态训练选项(选项定义、默认值、合法组合)。`training_options: null` 表示该模型无需训练选项。`--training-type` 默认 `sft`。 +- **文本精调训练选项 flag**:`bl finetune text create` 新增 `--modality` 与 `--reasoning-mode`,适用于配置了动态训练选项的模型(如 modality 固定 vision 的模型)。 + +### 变更 + +- **精调参数预检**:`bl finetune params` 与 `bl finetune text create` 在控制台登录态可用时会调用一次动态训练选项接口——自动补齐选项默认值,并在提交前本地拦截非法取值或组合;无登录态时降级为 warning 并原样透传服务端。`finetune params` 的 JSON 输出新增 `precheck` 字段说明预检是否执行。 + ## [2.11.1] - 2026-11-24 ### 修复 diff --git a/README.md b/README.md index f8258629..ceb5dc6c 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ _Built for AI Agents. Every command works as a structured tool call._ - **Asset understanding** — Parse and ask questions about images, documents, audio, and long videos - **App orchestration** — Call Managed Agents, agents, and workflows published on Aliyun Model Studio, wired to knowledge bases, memory, web search, and MCP tools; create, update, publish, copy, and delete agents/workflows, and edit workflow canvases from the CLI - **Native MCP setup** — Register Bailian MCP servers in Codex, Claude Code, Cursor, Qoder, Qoder Work, QwenWork (千问办公), Qwen Code, Gemini CLI, or Pi -- **Training & deployment** — Validate and upload datasets, fine-tune models (SFT/DPO/CPT), run reinforcement-learning jobs in an isolated sandbox (macOS/Linux), submit OPD distillation jobs via OpenAPI, deploy dedicated models as endpoints +- **Training & deployment** — Prepare decision training data (local split, teacher-model generation, or fully async offline Batch), validate and upload datasets, fine-tune models (SFT/DPO/CPT), run reinforcement-learning jobs in an isolated sandbox (macOS/Linux), submit OPD distillation jobs via OpenAPI, deploy dedicated models as endpoints - **Batch inference** — Prepare CSV/JSONL, create and follow asynchronous Chat/Embedding tasks, download original results/errors with optional CSV, or send one synchronous Batch Chat request - **Account operations** — Login, UI-based configuration, model marketplace, usage and quota, rate-limit increases, team seat management - **Plan onboarding** — Connect subscription plans such as Token Plan to the CLI and common coding agents in one step diff --git a/README.zh.md b/README.zh.md index eb959b96..54cd161a 100644 --- a/README.zh.md +++ b/README.zh.md @@ -26,7 +26,7 @@ _专为 AI Agent 打造,每个命令均可作为结构化工具调用。_ - **素材理解** — 图像、文档、音频、长视频的解析与问答 - **应用编排** — 调用百炼已发布的 Managed Agent、智能体和工作流,接入知识库、记忆库、联网搜索与 MCP 工具;并可在命令行创建/更新/发布/复制/删除智能体与工作流、编辑工作流画布 - **原生 MCP 接入** — 将百炼 MCP 服务注册到 Codex、Claude Code、Cursor、Qoder、Qoder Work、千问办公(QwenWork)、Qwen Code、Gemini CLI 或 Pi -- **模型训推** — 数据集校验上传、模型精调(SFT/DPO/CPT)、在隔离沙箱内执行强化学习(RL)训练(macOS/Linux)、通过 OpenAPI 提交 OPD 蒸馏训练、专属模型部署上线 +- **模型训推** — 决策训练数据准备(本地切分 / teacher 模型生成 / 全异步离线 Batch)、数据集校验上传、模型精调(SFT/DPO/CPT)、在隔离沙箱内执行强化学习(RL)训练(macOS/Linux)、通过 OpenAPI 提交 OPD 蒸馏训练、专属模型部署上线 - **批量推理** — CSV/JSONL 构造、异步 Chat/Embedding 任务创建与跟踪、原始结果/错误下载及可选 CSV,或同步单请求 Batch Chat - **账号运维** — 授权登录、界面化配置、模型市场、用量与额度、限流提额、团队席位管理 - **套餐接入** — 支持 Token Plan 等订阅计划一键接到 CLI 和常见 Coding Agent diff --git a/packages/bailian-kb-dsh/package.json b/packages/bailian-kb-dsh/package.json index b909db0e..7081c297 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.11.1", + "version": "2.11.2", "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 cb930b8e..89a96ab4 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.11.1", + "version": "2.11.2", "description": "Bailian personal memory for DeepSeek Harness: automatic recall, silent curation, and user-controlled remember/forget.", "keywords": [ "alibaba-cloud", diff --git a/packages/cli/README.md b/packages/cli/README.md index f8258629..ceb5dc6c 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -27,7 +27,7 @@ _Built for AI Agents. Every command works as a structured tool call._ - **Asset understanding** — Parse and ask questions about images, documents, audio, and long videos - **App orchestration** — Call Managed Agents, agents, and workflows published on Aliyun Model Studio, wired to knowledge bases, memory, web search, and MCP tools; create, update, publish, copy, and delete agents/workflows, and edit workflow canvases from the CLI - **Native MCP setup** — Register Bailian MCP servers in Codex, Claude Code, Cursor, Qoder, Qoder Work, QwenWork (千问办公), Qwen Code, Gemini CLI, or Pi -- **Training & deployment** — Validate and upload datasets, fine-tune models (SFT/DPO/CPT), run reinforcement-learning jobs in an isolated sandbox (macOS/Linux), submit OPD distillation jobs via OpenAPI, deploy dedicated models as endpoints +- **Training & deployment** — Prepare decision training data (local split, teacher-model generation, or fully async offline Batch), validate and upload datasets, fine-tune models (SFT/DPO/CPT), run reinforcement-learning jobs in an isolated sandbox (macOS/Linux), submit OPD distillation jobs via OpenAPI, deploy dedicated models as endpoints - **Batch inference** — Prepare CSV/JSONL, create and follow asynchronous Chat/Embedding tasks, download original results/errors with optional CSV, or send one synchronous Batch Chat request - **Account operations** — Login, UI-based configuration, model marketplace, usage and quota, rate-limit increases, team seat management - **Plan onboarding** — Connect subscription plans such as Token Plan to the CLI and common coding agents in one step diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index eb959b96..54cd161a 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -26,7 +26,7 @@ _专为 AI Agent 打造,每个命令均可作为结构化工具调用。_ - **素材理解** — 图像、文档、音频、长视频的解析与问答 - **应用编排** — 调用百炼已发布的 Managed Agent、智能体和工作流,接入知识库、记忆库、联网搜索与 MCP 工具;并可在命令行创建/更新/发布/复制/删除智能体与工作流、编辑工作流画布 - **原生 MCP 接入** — 将百炼 MCP 服务注册到 Codex、Claude Code、Cursor、Qoder、Qoder Work、千问办公(QwenWork)、Qwen Code、Gemini CLI 或 Pi -- **模型训推** — 数据集校验上传、模型精调(SFT/DPO/CPT)、在隔离沙箱内执行强化学习(RL)训练(macOS/Linux)、通过 OpenAPI 提交 OPD 蒸馏训练、专属模型部署上线 +- **模型训推** — 决策训练数据准备(本地切分 / teacher 模型生成 / 全异步离线 Batch)、数据集校验上传、模型精调(SFT/DPO/CPT)、在隔离沙箱内执行强化学习(RL)训练(macOS/Linux)、通过 OpenAPI 提交 OPD 蒸馏训练、专属模型部署上线 - **批量推理** — CSV/JSONL 构造、异步 Chat/Embedding 任务创建与跟踪、原始结果/错误下载及可选 CSV,或同步单请求 Batch Chat - **账号运维** — 授权登录、界面化配置、模型市场、用量与额度、限流提额、团队席位管理 - **套餐接入** — 支持 Token Plan 等订阅计划一键接到 CLI 和常见 Coding Agent diff --git a/packages/cli/package.json b/packages/cli/package.json index 7c375b26..b1c53e81 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli", - "version": "2.11.1", + "version": "2.11.2", "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 0de5e76f..7ce091b3 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -191,10 +191,13 @@ import { datasetGroups, datasetDelete, datasetValidate, + datasetSplit, + datasetGenerate, finetuneTextCreate, finetuneAudioCreate, finetuneImageCreate, finetuneVideoCreate, + finetuneDecisionCreate, finetuneList, finetuneGet, finetuneCancel, @@ -206,6 +209,7 @@ import { finetuneCapability, finetunePrice, finetuneParams, + finetuneTrainOptions, finetuneMetrics, finetuneCompressTemplates, finetuneCompressCreate, @@ -589,10 +593,13 @@ export const commands: Record = { "dataset groups": datasetGroups, "dataset delete": datasetDelete, "dataset validate": datasetValidate, + "dataset split": datasetSplit, + "dataset generate": datasetGenerate, "finetune text create": finetuneTextCreate, "finetune audio create": finetuneAudioCreate, "finetune image create": finetuneImageCreate, "finetune video create": finetuneVideoCreate, + "finetune decision create": finetuneDecisionCreate, "finetune list": finetuneList, "finetune get": finetuneGet, "finetune cancel": finetuneCancel, @@ -604,6 +611,7 @@ export const commands: Record = { "finetune capability": finetuneCapability, "finetune price": finetunePrice, "finetune params": finetuneParams, + "finetune train-options": finetuneTrainOptions, "finetune metrics": finetuneMetrics, "finetune compress templates": finetuneCompressTemplates, "finetune compress create": finetuneCompressCreate, diff --git a/packages/commands/package.json b/packages/commands/package.json index 07f3a3bf..1d15beb9 100644 --- a/packages/commands/package.json +++ b/packages/commands/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-commands", - "version": "2.11.1", + "version": "2.11.2", "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/dataset/generate.ts b/packages/commands/src/commands/dataset/generate.ts new file mode 100644 index 00000000..ab151e9d --- /dev/null +++ b/packages/commands/src/commands/dataset/generate.ts @@ -0,0 +1,678 @@ +import { existsSync, mkdirSync } from "fs"; +import { basename, dirname, join } from "path"; +import { + BailianError, + ExitCode, + buildGenerationMessages, + buildPlans, + buildTeacherMessages, + chatPath, + defineCommand, + loadWorkload, + parseStateItems, + parseTeacherRow, + runWithConcurrency, + stateKey, + toTrainingRecord, + validateWorkload, + workloadIdFields, + type ChatRequest, + type ChatResponse, + type CommandContext, + type FlagsDef, + type GenerationPlan, + type RawLabelRow, + type StateItem, + type UsageSummary, + type WorkloadConfig, +} from "bailian-cli-core"; +import { + appendJsonl, + fileStamp, + finalizeDataset, + isObject, + readObjectRows, + usageError, +} from "./shared.ts"; + +const DEFAULT_MODEL = "qwen3.8-max"; +const CHAT_ATTEMPTS = 4; + +const GENERATE_FLAGS = { + workload: { + type: "string", + valueHint: "", + description: { + "en-US": + "workload.json business config (required). Every field's meaning and format is listed in Notes below.", + "zh-CN": "workload.json 业务配置(必填)。每个字段的含义与写法见下方 Notes 字段速查。", + }, + }, + samples: { + type: "number", + valueHint: "", + description: { + "en-US": "Ordinary samples to generate (default: 200)", + "zh-CN": "生成的普通样本数(默认:200)", + }, + }, + unknowable: { + type: "number", + valueHint: "", + description: { + "en-US": "Extra evidence-free states with uniform targets (default: 0)", + "zh-CN": "额外的信息不足样本数,使用均匀 target(默认:0)", + }, + }, + outDir: { + type: "string", + valueHint: "", + description: { + "en-US": "Output directory (default: data)", + "zh-CN": "输出目录(默认:data)", + }, + }, + prefix: { + type: "string", + valueHint: "", + description: { + "en-US": "Output file name prefix (default: tickets)", + "zh-CN": "输出文件名前缀(默认:tickets)", + }, + }, + model: { + type: "string", + valueHint: "", + description: { + "en-US": `Teacher/generator model (default: ${DEFAULT_MODEL})`, + "zh-CN": `标注与生成使用的模型(默认:${DEFAULT_MODEL})`, + }, + }, + seed: { + type: "number", + valueHint: "", + description: { + "en-US": "Shuffle seed for plans and split (default: 0)", + "zh-CN": "画像与切分的洗牌种子(默认:0)", + }, + }, + batch: { + type: "number", + valueHint: "", + description: { + "en-US": "States per generation call (default: 5)", + "zh-CN": "每次生成调用的样本数(默认:5)", + }, + }, + concurrency: { + type: "number", + valueHint: "", + description: { + "en-US": "Parallel API calls (default: 8)", + "zh-CN": "并行 API 调用数(默认:8)", + }, + }, + targetTemp: { + type: "number", + valueHint: "", + description: { + "en-US": + "Soft-target smoothing temperature; 1.0 keeps the teacher distribution (default: 1.5)", + "zh-CN": "软标签平滑温度;1.0 保持 teacher 原分布(默认:1.5)", + }, + }, + noSoftTarget: { + type: "switch", + description: { + "en-US": "Hard labels only (unknowable rows keep uniform targets)", + "zh-CN": "仅硬标签(unknowable 样本仍保留均匀 target)", + }, + }, + statesOnly: { + type: "switch", + description: { + "en-US": "Stop after generating states; no labelling spend", + "zh-CN": "生成输入后即停止,不产生标注费用", + }, + }, + fromStates: { + type: "string", + valueHint: "", + description: { + "en-US": "Label an existing JSONL of {state, plan?} records instead of generating", + "zh-CN": "改为标注已有的 {state, plan?} JSONL 文件,不再生成", + }, + }, + resumeRaw: { + type: "string", + valueHint: "", + description: { + "en-US": "With --from-states: skip states already labelled in this raw file", + "zh-CN": "配合 --from-states:跳过该 raw 文件中已标注的 state,续跑标注", + }, + }, + fromRaw: { + type: "string", + valueHint: "", + description: { + "en-US": "Zero API calls: re-convert saved teacher labels (e.g. to adjust --target-temp)", + "zh-CN": "零 API 调用:仅重新转换已保存的 teacher 标签(例如调整 --target-temp)", + }, + }, + schema: { + type: "string", + valueHint: "", + choices: ["decision"] as const, + description: { + "en-US": 'Record schema. Only "decision" (state/questions) is supported today.', + "zh-CN": '记录 Schema。当前仅支持 "decision"(state/questions 决策数据)。', + }, + }, +} satisfies FlagsDef; + +function sleep(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +/** 服务端 4xx(含 HTTP 200 业务错码)原样透传终止;429/5xx 与其余错误进入重试/跳过。 */ +function isFatalApiError(error: unknown): error is BailianError { + if (!(error instanceof BailianError)) return false; + const status = error.api?.httpStatus; + return status !== undefined && status !== 429 && status < 500; +} + +/** 429/5xx 退避重试 4 次;网络/解析类错误同样重试;4xx 立即抛出。 */ +async function chatWithRetry( + ctx: CommandContext, + request: ChatRequest, + usage: UsageSummary, +): Promise { + let lastReason = "unknown"; + for (let attempt = 0; attempt < CHAT_ATTEMPTS; attempt++) { + try { + const response = await ctx.client.requestJson({ + path: chatPath(), + method: "POST", + body: request, + }); + usage.calls += 1; + usage.prompt_tokens += response.usage?.prompt_tokens ?? 0; + usage.completion_tokens += response.usage?.completion_tokens ?? 0; + return response.choices?.[0]?.message?.content ?? ""; + } catch (error) { + if (isFatalApiError(error)) throw error; + if (error instanceof Error && error.name === "AbortError") throw error; + lastReason = error instanceof Error ? error.message : String(error); + const status = error instanceof BailianError ? error.api?.httpStatus : undefined; + const throttled = status === 429 || (status !== undefined && status >= 500); + await sleep((throttled ? 2000 : 1500) * (attempt + 1)); + } + } + throw new BailianError( + `chat failed after ${CHAT_ATTEMPTS} attempts: ${lastReason} / 模型调用重试 ${CHAT_ATTEMPTS} 次后仍失败:${lastReason}`, + ExitCode.GENERAL, + ); +} + +/** 批量生成业务输入;坏批跳过,逐批 append states 文件(崩溃只丢一批)。 */ +async function generateStates( + ctx: CommandContext, + workload: WorkloadConfig, + plans: GenerationPlan[], + options: { batch: number; concurrency: number; model: string; statesPath: string }, + usage: UsageSummary, +): Promise { + const groups: GenerationPlan[][] = []; + for (let index = 0; index < plans.length; index += options.batch) { + groups.push(plans.slice(index, index + options.batch)); + } + const schemaFields = Object.keys(workload.state_schema ?? {}); + const out: StateItem[] = []; + const tasks = groups.map((group) => async () => { + let content: string; + try { + content = await chatWithRetry( + ctx, + { + model: options.model, + messages: buildGenerationMessages(workload, group), + temperature: 1.0, + top_p: 0.8, + max_tokens: 4096, + enable_thinking: false, + enable_search: false, + }, + usage, + ); + } catch (error) { + if (isFatalApiError(error)) throw error; + const reason = error instanceof Error ? error.message : String(error); + ctx.output.warning({ + "en-US": `state batch failed: ${reason}`, + "zh-CN": `生成批次失败:${reason}`, + }); + return; + } + const { items: fresh, invalid } = parseStateItems(content, group, schemaFields); + if (invalid) { + ctx.output.warning({ + "en-US": "state batch skipped: invalid JSON or item count (response content omitted)", + "zh-CN": "生成批次已跳过:JSON 无效或条数不符(不展示响应内容)", + }); + return; + } + if (fresh.length > 0) { + appendJsonl( + options.statesPath, + fresh.map((row) => JSON.stringify(row)), + ); + } + out.push(...fresh); + ctx.output.progress({ + "en-US": `states ${out.length}/${plans.length}`, + "zh-CN": `已生成 ${out.length}/${plans.length} 条输入`, + }); + }); + await runWithConcurrency(tasks, options.concurrency); + return out; +} + +/** 逐 state teacher 标注;校验概率分布,逐条 append raw 文件(崩溃只丢一条)。 */ +async function labelStates( + ctx: CommandContext, + workload: WorkloadConfig, + items: StateItem[], + options: { concurrency: number; model: string; rawPath: string }, + usage: UsageSummary, +): Promise { + const labelled: RawLabelRow[] = []; + const tasks = items.map((item) => async () => { + let content: string; + try { + content = await chatWithRetry( + ctx, + { + model: options.model, + messages: buildTeacherMessages(item.state, workload.questions, workload.guidance ?? []), + temperature: 0.2, + top_p: 0.8, + max_tokens: 4096, + enable_thinking: true, + // 强制关闭联网搜索:标注必须只依据 STATE,避免默认联网污染概率分布。 + enable_search: false, + }, + usage, + ); + } catch (error) { + if (isFatalApiError(error)) throw error; + const reason = error instanceof Error ? error.message : String(error); + ctx.output.warning({ + "en-US": `label failed: ${reason}`, + "zh-CN": `标注失败:${reason}`, + }); + return; + } + const { answers, missing } = parseTeacherRow(content, workload.questions); + if (missing.length > 0) { + ctx.output.warning({ + "en-US": `label skipped: invalid probabilities for ${missing.join(", ")}`, + "zh-CN": `标注已跳过:${missing.join(", ")} 的概率分布无效`, + }); + return; + } + const row: RawLabelRow = { ...item, answers, missing: [] }; + appendJsonl(options.rawPath, [JSON.stringify(row)]); + labelled.push(row); + ctx.output.progress({ + "en-US": `labelled ${labelled.length}/${items.length}`, + "zh-CN": `已标注 ${labelled.length}/${items.length} 条`, + }); + }); + await runWithConcurrency(tasks, options.concurrency); + return labelled; +} + +export default defineCommand({ + defaultOutput: "json", + description: { + "en-US": + "Generate decision training data with a teacher model: synthesize states, label probabilities, convert soft targets, split, and write a manifest", + "zh-CN": + "用 teacher 大模型生成决策训练数据:合成输入、标注概率分布、转换软标签、切分并输出 manifest", + }, + auth: "apiKey", + usageArgs: + "--workload [--samples ] [--unknowable ] [--out-dir ] [--prefix ] [--model ] [--seed ] [--batch ] [--concurrency ] [--target-temp ] [--no-soft-target] [--states-only | --from-states [--resume-raw ] | --from-raw ] [--schema decision]", + flags: GENERATE_FLAGS, + exampleArgs: [ + "--workload workload.json --samples 200 --unknowable 20 --out-dir output/demo", + "--workload workload.json --samples 20 --dry-run", + "--workload workload.json --states-only", + "--workload workload.json --from-states data/states.jsonl --resume-raw data/raw/labeled.jsonl", + "--workload workload.json --from-raw data/raw/labeled.jsonl --target-temp 1.0", + ], + notes: [ + { + "en-US": + 'Only decision-model data (state/questions records) is supported today; --schema accepts "decision" only.', + "zh-CN": '当前仅支持决策模型数据(state/questions 记录);--schema 只接受 "decision"。', + }, + { + "en-US": + "Generation and labelling call the teacher model and consume tokens (billing applies). Use --dry-run to preview plans and prompts, --states-only to stop before labelling spend, or --from-raw for a zero-API re-conversion.", + "zh-CN": + "生成与标注会调用 teacher 模型并消耗 token(产生费用)。可先用 --dry-run 预览画像与提示词,用 --states-only 在标注前停止,或用 --from-raw 零 API 重转换。", + }, + { + "en-US": + 'workload.json field reference (meaning + format). Full annotated example: bailian-finetune skill, "workload.json format".', + "zh-CN": + "workload.json 字段速查(含义 + 写法)。完整带注释示例见 bailian-finetune 技能「workload.json format」节。", + }, + { + "en-US": + 'questions (required): the question table, id → {type, criteria, instructions?}. choice: criteria is an object of 1–255 "option name → description"; score: criteria is an array of 2–255 level descriptions ordered low → high; noul: criteria optional, only "true"/"false" keys. instructions is optional free text.', + "zh-CN": + 'questions(必填):问题表,id → {type, criteria, instructions?}。choice:criteria 为 1–255 项「选项名 → 描述」对象;score:criteria 为 2–255 级描述数组(低→高);noul:criteria 可选,仅 "true"/"false" 两键。instructions 为可选自由文本。', + }, + { + "en-US": + "description (required for generation): one sentence describing the input business data; injected into the generation prompt.", + "zh-CN": "description(生成模式必填):一句话描述输入业务数据,注入生成提示词。", + }, + { + "en-US": + "state_schema (required for generation): input field name → non-empty example value; field names appear verbatim in every generated state.", + "zh-CN": + "state_schema(生成模式必填):输入字段名 → 非空示例值;字段名原样进入每条生成的 state。", + }, + { + "en-US": + 'id_fields (optional, default ["ticket_id"]): state key fields used for dedup and resume; values are record ids, not model input.', + "zh-CN": + 'id_fields(可选,默认 ["ticket_id"]):state 主键字段,用于去重与续跑;其值是记录编号,不作为模型输入。', + }, + { + "en-US": + "axes (optional): profile axis name → value list, for balanced generation. An axis named after a question id is the intended answer (score axes use 0-based level indices); axes you omit are randomized.", + "zh-CN": + "axes(可选):画像轴名 → 取值列表,用于均衡生成。与问题 id 同名的轴即期望答案(score 轴用 0 起等级下标);未列出的维度随机。", + }, + { + "en-US": + "guidance (optional): business rules injected into both the generation and labelling prompts.", + "zh-CN": "guidance(可选):业务规则,同时注入生成与标注提示词。", + }, + { + "en-US": + "difficulty_hints (optional): clean / unknowable keys override the built-in generation difficulty hints.", + "zh-CN": "difficulty_hints(可选):clean / unknowable 两键,覆盖内置的生成难度提示。", + }, + { + "en-US": + "Crash resilience: states append per batch and labels append per row; continue labelling with --from-states plus --resume-raw. Raw labels keep teacher probabilities so --from-raw can re-derive targets at a new --target-temp without any API call.", + "zh-CN": + "崩溃韧性:输入逐批 append、标签逐条 append;用 --from-states 配合 --resume-raw 续跑标注。raw 文件保留 teacher 概率,--from-raw 可在不调用 API 的情况下按新 --target-temp 重新派生 target。", + }, + { + "en-US": + "Outputs .train.jsonl / .development.jsonl (15% development), .manifest.json (workload sha256, label balance, generator/teacher agreement, usage), and raw teacher labels under /raw. The state token-budget check is skipped (needs the Python transformers tokenizer).", + "zh-CN": + "输出 .train.jsonl / .development.jsonl(development 占 15%)、.manifest.json(workload sha256、标签均衡、生成意图与 teacher 一致率、用量),以及 /raw 下的 teacher 原始标签。state token 预算检查跳过(依赖 Python transformers 分词器)。", + }, + { + "en-US": + "Labelling forces enable_search=false so probabilities depend only on the STATE. The shuffle PRNG differs from Python random.Random: the same seed reproduces results within this CLI only. Request timeout uses the global --timeout.", + "zh-CN": + "标注强制 enable_search=false,概率只依据 STATE。洗牌随机源与 Python random.Random 不同:同一 seed 仅在本 CLI 内可复现。请求超时使用全局 --timeout。", + }, + ], + validate: (flags) => { + if (!flags.workload) { + return { + "en-US": + 'Missing --workload . Minimal skeleton: {"questions":{"team":{"type":"choice","criteria":{"billing":"Billing issues","technical":"Technical issues"}}},"description":"Support tickets","state_schema":{"ticket_id":"T-1001","content":"Ticket body"},"axes":{"team":["billing","technical"]}}. Every field\'s meaning and format: see the Notes of `dataset generate --help`, or the bailian-finetune skill section "workload.json format".', + "zh-CN": + '缺少 --workload 。最小骨架:{"questions":{"team":{"type":"choice","criteria":{"billing":"账单问题","technical":"技术问题"}}},"description":"客服工单","state_schema":{"ticket_id":"T-1001","content":"工单正文"},"axes":{"team":["billing","technical"]}}。每个字段的含义与写法:见 `dataset generate --help` 的 Notes 字段速查,或 bailian-finetune 技能「workload.json format」节。', + }; + } + for (const [name, value] of [ + ["batch", flags.batch], + ["concurrency", flags.concurrency], + ["target-temp", flags.targetTemp], + ] as const) { + if (value !== undefined && (!Number.isFinite(value) || value <= 0)) { + return { + "en-US": `--${name} must be positive and finite.`, + "zh-CN": `--${name} 必须为正有限数值。`, + }; + } + } + for (const [name, value] of [ + ["samples", flags.samples], + ["unknowable", flags.unknowable], + ] as const) { + if (value !== undefined && (!Number.isInteger(value) || value < 0)) { + return { + "en-US": `--${name} must be a nonnegative integer.`, + "zh-CN": `--${name} 必须是非负整数。`, + }; + } + } + if (flags.fromRaw && (flags.fromStates || flags.resumeRaw || flags.statesOnly)) { + return { + "en-US": "--from-raw cannot be combined with generation/labelling options.", + "zh-CN": "--from-raw 不能与生成/标注选项同时使用。", + }; + } + if (flags.resumeRaw && !flags.fromStates) { + return { + "en-US": "--resume-raw requires --from-states.", + "zh-CN": "--resume-raw 需要配合 --from-states。", + }; + } + if (flags.statesOnly && flags.fromStates) { + return { + "en-US": "--states-only is for generation; omit it when using --from-states.", + "zh-CN": "--states-only 用于生成模式;使用 --from-states 时请去掉。", + }; + } + return undefined; + }, + async run(ctx) { + const { settings, flags } = ctx; + const workloadPath = flags.workload as string; + const workload = loadWorkload(workloadPath); + const mode = flags.fromRaw ? "from_raw" : flags.fromStates ? "from_states" : "generate"; + validateWorkload(workload, mode === "generate"); + + const outDir = flags.outDir ?? "data"; + const prefix = flags.prefix ?? "tickets"; + const model = flags.model ?? DEFAULT_MODEL; + const seed = flags.seed ?? 0; + const count = flags.samples ?? 200; + const unknowable = flags.unknowable ?? 0; + const batch = flags.batch ?? 5; + const concurrency = flags.concurrency ?? 8; + const targetTemp = flags.targetTemp ?? 1.5; + const soft = !flags.noSoftTarget; + const idFields = workloadIdFields(workload); + const rawPath = + flags.fromRaw ?? + flags.resumeRaw ?? + join(outDir, "raw", `labeled-${fileStamp(new Date())}.jsonl`); + const statesPath = join(dirname(rawPath), basename(rawPath).replace("labeled", "states")); + const trainPath = join(outDir, `${prefix}.train.jsonl`); + const developmentPath = join(outDir, `${prefix}.development.jsonl`); + const manifestPath = join(outDir, `${prefix}.manifest.json`); + + if (settings.dryRun) { + const preview: Record = { + action: "dataset.generate", + mode, + schema: flags.schema ?? "decision", + files: { + train: trainPath, + development: developmentPath, + manifest: manifestPath, + raw: rawPath, + }, + }; + if (mode === "from_raw") { + preview.rows = readObjectRows(rawPath).length; + preview.estimated_calls = { generation: 0, labeling: 0 }; + } else if (mode === "from_states") { + const items = readObjectRows(flags.fromStates as string); + preview.states = items.length; + preview.estimated_calls = { generation: 0, labeling: items.length }; + preview.sample = { + teacher_messages: buildTeacherMessages( + items[0]?.state ?? {}, + workload.questions, + workload.guidance ?? [], + ), + }; + } else { + const plans = buildPlans(workload, count, unknowable, seed); + preview.plans = { total: plans.length, unknowable }; + preview.estimated_calls = { + generation: Math.ceil(plans.length / batch), + labeling: plans.length, + }; + preview.files = { ...(preview.files as object), states: statesPath }; + const placeholderState = Object.fromEntries( + Object.keys(workload.state_schema ?? {}).map((field) => [field, "..."]), + ); + preview.sample = { + generation_messages: buildGenerationMessages(workload, plans.slice(0, batch)), + teacher_messages: buildTeacherMessages( + placeholderState, + workload.questions, + workload.guidance ?? [], + ), + }; + } + ctx.output.result( + preview, + settings.output === "text" ? { text: JSON.stringify(preview, null, 2) } : undefined, + ); + return; + } + + mkdirSync(join(outDir, "raw"), { recursive: true }); + const usage: UsageSummary = { calls: 0, prompt_tokens: 0, completion_tokens: 0 }; + const started = Date.now(); + + if (mode !== "from_raw") { + let items: StateItem[]; + if (mode === "from_states") { + const rows = readObjectRows(flags.fromStates as string); + items = rows.map((row) => { + if (!("state" in row)) { + throw usageError( + `${flags.fromStates} records must contain "state".`, + `${flags.fromStates} 的记录必须包含 "state"。`, + ); + } + return { + state: row.state as Record, + plan: isObject(row.plan) ? row.plan : undefined, + }; + }); + ctx.output.info({ + "en-US": `labelling ${items.length} states from ${flags.fromStates}`, + "zh-CN": `开始标注 ${flags.fromStates} 中的 ${items.length} 条输入`, + }); + } else { + const plans = buildPlans(workload, count, unknowable, seed); + ctx.output.info({ + "en-US": `planning ${plans.length} states (${unknowable} evidence-free) on ${model}`, + "zh-CN": `规划 ${plans.length} 条输入(${unknowable} 条信息不足),模型 ${model}`, + }); + items = await generateStates( + ctx, + workload, + plans, + { batch, concurrency, model, statesPath }, + usage, + ); + } + + if (flags.statesOnly) { + if (items.length === 0) { + throw new BailianError( + "no usable states: check the API and skipped-batch messages above. / 没有可用输入:请检查 API 与上方跳过批次的提示。", + ExitCode.GENERAL, + ); + } + const statesResult = { + action: "dataset.generate", + mode, + states_only: true, + files: { states: statesPath }, + counts: { states: items.length }, + usage, + }; + ctx.output.result( + statesResult, + settings.output === "text" ? { text: JSON.stringify(statesResult, null, 2) } : undefined, + ); + return; + } + + // 续跑:raw 文件中已能成功转换的 state 不再重复标注。 + const done = new Set(); + if (flags.resumeRaw && existsSync(rawPath)) { + for (const row of readObjectRows(rawPath)) { + const { record } = toTrainingRecord( + row as unknown as RawLabelRow, + workload, + targetTemp, + soft, + ); + if (record) done.add(stateKey(record.state, idFields)); + } + ctx.output.info({ + "en-US": `resuming: ${done.size} states already labelled`, + "zh-CN": `续跑:${done.size} 条输入已标注`, + }); + } + const seen = new Set(done); + const unique: StateItem[] = []; + for (const item of items) { + const key = stateKey(item.state, idFields); + if (!seen.has(key)) { + seen.add(key); + unique.push(item); + } + } + ctx.output.info({ + "en-US": `${items.length} states in, ${unique.length} to label after dedupe`, + "zh-CN": `${items.length} 条输入,去重后待标注 ${unique.length} 条`, + }); + await labelStates(ctx, workload, unique, { concurrency, model, rawPath }, usage); + } + + // 转换尾段(转换 → 切分 → manifest → 报告),纯本地零 API。 + const result = finalizeDataset(ctx.output, { + workload, + workloadPath, + rawPath, + outDir, + prefix, + seed, + targetTemp, + soft, + mode, + model: mode === "from_raw" ? null : model, + baseUrl: mode === "from_raw" ? null : ctx.client.url(""), + usage: mode === "from_raw" ? null : usage, + started, + schema: flags.schema ?? "decision", + }); + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + }, +}); diff --git a/packages/commands/src/commands/dataset/shared.ts b/packages/commands/src/commands/dataset/shared.ts new file mode 100644 index 00000000..e91fdd18 --- /dev/null +++ b/packages/commands/src/commands/dataset/shared.ts @@ -0,0 +1,305 @@ +/** + * dataset 域共享 helper:JSONL 读写、raw 转换,以及 generate 的转换尾段 + * finalizeDataset(转换 → 切分 → manifest → 报告)。 + * + * 按“新功能不跨命令域收敛”的取舍在域内自实现,batch/shared.ts 零改动。 + */ +import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + BailianError, + ExitCode, + MIN_SPLIT_RECORDS, + agreementRatio, + balanceReport, + buildManifest, + readTextFromPathOrStdin, + sha256Hex, + splitRecords, + stateKey, + toTrainingRecord, + workloadIdFields, + type AgreementTally, + type CommandOutput, + type ManifestInput, + type RawLabelRow, + type TrainingRecord, + type UsageSummary, + type WorkloadConfig, +} from "bailian-cli-core"; + +export function usageError(english: string, chinese: string): BailianError { + return new BailianError(`${english} / ${chinese}`, ExitCode.USAGE); +} + +export function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** 逐行读取 JSONL 对象行;空行跳过,非法行报 USAGE。 */ +export function readObjectRows(path: string): Array> { + const raw = readTextFromPathOrStdin(path); + const rows: Array> = []; + const lines = raw.split("\n"); + for (let index = 0; index < lines.length; index++) { + const line = lines[index].trim(); + if (line.length === 0) continue; + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + throw usageError( + `${path} line ${index + 1} is not valid JSON.`, + `${path} 第 ${index + 1} 行不是合法的 JSON。`, + ); + } + if (!isObject(parsed)) { + throw usageError( + `${path} line ${index + 1} must be a JSON object.`, + `${path} 第 ${index + 1} 行必须是 JSON 对象。`, + ); + } + rows.push(parsed); + } + return rows; +} + +/** 追加 JSONL 行;已有文件末尾缺换行时先补一个,避免手写 resume 文件与新行粘连。 */ +export function appendJsonl(path: string, rows: string[]): void { + if (rows.length === 0) return; + let prefix = ""; + if (existsSync(path)) { + const existing = readFileSync(path); + if (existing.length > 0 && existing[existing.length - 1] !== 0x0a) prefix = "\n"; + } + appendFileSync(path, prefix + rows.join("\n") + "\n"); +} + +export interface ConversionSummary { + records: TrainingRecord[]; + agreement: Record; + unknowableRecords: number; + rejected: number; + duplicates: number; +} + +/** raw 行 → 训练记录:无效计 rejected、重复 state 计 duplicate,统计意图一致率。 */ +export function convertRows( + rows: Array>, + workload: WorkloadConfig, + targetTemp: number, + soft: boolean, +): ConversionSummary { + const idFields = workloadIdFields(workload); + const records: TrainingRecord[] = []; + const agreement: Record = {}; + const seen = new Set(); + let unknowableRecords = 0; + let rejected = 0; + let duplicates = 0; + for (const row of rows) { + const { record, intentMatch } = toTrainingRecord( + row as unknown as RawLabelRow, + workload, + targetTemp, + soft, + ); + if (!record) { + rejected += 1; + continue; + } + const key = stateKey(record.state, idFields); + if (seen.has(key)) { + duplicates += 1; + continue; + } + seen.add(key); + records.push(record); + if (record._meta?.source === "unknowable") unknowableRecords += 1; + for (const [questionId, matched] of Object.entries(intentMatch)) { + const tally = agreement[questionId] ?? (agreement[questionId] = { hit: 0, total: 0 }); + tally.hit += matched ? 1 : 0; + tally.total += 1; + } + } + return { records, agreement, unknowableRecords, rejected, duplicates }; +} + +/** 文件时间戳(对齐脚本 %Y%m%d-%H%M%S-%f 形态)。 */ +export function fileStamp(now: Date): string { + const pad = (value: number, width = 2) => String(value).padStart(width, "0"); + return ( + `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}` + + `-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}` + + `-${pad(now.getMilliseconds(), 3)}000` + ); +} + +export interface FinalizeInput { + workload: WorkloadConfig; + workloadPath: string; + rawPath: string; + outDir: string; + prefix: string; + seed: number; + targetTemp: number; + soft: boolean; + mode: ManifestInput["mode"]; + /** from_raw 模式为 null(无模型调用)。 */ + model: string | null; + baseUrl: string | null; + usage: UsageSummary | null; + /** 命令启动时刻(Date.now()),用于 wall_s。 */ + started: number; + schema?: string; +} + +export interface DatasetFinalResult { + action: "dataset.generate"; + mode: ManifestInput["mode"]; + schema: string; + files: { train: string; development: string; manifest: string; raw: string }; + records: { train: number; development: number }; + unknowable_records: number; + rejected_raw_records: number; + duplicate_raw_records: number; + label_balance: Record>; + generator_teacher_agreement: Record; + usage: UsageSummary | null; +} + +/** + * 转换尾段(generate 专用):读整份 raw → 转换 → 切分 → + * 写 train/dev/manifest → stderr 质量与用量报告;返回结构化 result 由调用方输出。 + * 纯本地,零 API 调用。 + */ +export function finalizeDataset(output: CommandOutput, input: FinalizeInput): DatasetFinalResult { + const { + workload, + workloadPath, + rawPath, + outDir, + prefix, + seed, + targetTemp, + soft, + mode, + model, + baseUrl, + usage, + started, + } = input; + const trainPath = join(outDir, `${prefix}.train.jsonl`); + const developmentPath = join(outDir, `${prefix}.development.jsonl`); + const manifestPath = join(outDir, `${prefix}.manifest.json`); + + // 转换阶段读取整份 raw(续跑时包含历史标签),保证 manifest 统计真实。 + const rows = mode === "from_raw" || existsSync(rawPath) ? readObjectRows(rawPath) : []; + const summary = convertRows(rows, workload, targetTemp, soft); + if (summary.records.length === 0) { + throw new BailianError( + "no usable records: check the API and skipped-batch/label messages above. / 没有可用记录:请检查 API 与上方跳过批次/标注的提示。", + ExitCode.GENERAL, + ); + } + if (summary.records.length < MIN_SPLIT_RECORDS) { + throw new BailianError( + `need at least ${MIN_SPLIT_RECORDS} usable records for nonempty train/development splits, got ${summary.records.length}. / 非空 train/development 切分至少需要 ${MIN_SPLIT_RECORDS} 条可用记录,当前只有 ${summary.records.length} 条。`, + ExitCode.GENERAL, + ); + } + + const parts = splitRecords(summary.records, seed); + mkdirSync(outDir, { recursive: true }); + writeFileSync(trainPath, parts.train.map((record) => JSON.stringify(record)).join("\n") + "\n"); + writeFileSync( + developmentPath, + parts.development.map((record) => JSON.stringify(record)).join("\n") + "\n", + ); + + const balance = balanceReport(summary.records, workload); + const agreement = agreementRatio(summary.agreement); + const wallSeconds = Number(((Date.now() - started) / 1000).toFixed(1)); + const manifest = buildManifest({ + created: new Date().toISOString(), + mode, + workloadPath, + rawPath, + workloadSha256: sha256Hex(readFileSync(workloadPath)), + generator: { + model, + base_url: baseUrl, + seed, + target_temp: targetTemp, + soft_target: soft, + }, + unknowableRecords: summary.unknowableRecords, + rejectedRawRecords: summary.rejected, + duplicateRawRecords: summary.duplicates, + records: { train: parts.train.length, development: parts.development.length }, + labelBalance: balance, + agreement, + wallSeconds, + usage, + }); + writeFileSync(manifestPath, JSON.stringify(manifest, null, 1) + "\n"); + + // 质量与用量报告走 stderr(info/warning),不污染 stdout 的结构化结果。 + const thin: string[] = []; + const balanceLines = Object.entries(balance).map(([questionId, dist]) => { + const total = Object.values(dist).reduce((sum, value) => sum + value, 0); + const cells = Object.entries(dist) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([key, value]) => { + if (total > 0 && value / total < 0.05) thin.push(`${questionId}.${key}`); + return `${key}=${value} (${total > 0 ? Math.round((value / total) * 100) : 0}%)`; + }) + .join(" "); + return ` ${questionId}: ${cells}`; + }); + output.info({ + "en-US": `=== balance (teacher labels) ===\n${balanceLines.join("\n")}`, + "zh-CN": `=== 标签均衡(teacher 硬标签)===\n${balanceLines.join("\n")}`, + }); + if (thin.length > 0) { + output.warning({ + "en-US": `label balance under 5%: ${thin.join(", ")} — consider more samples or adjusted axes.`, + "zh-CN": `标签占比低于 5%:${thin.join(", ")}——建议增加样本或调整 axes。`, + }); + } + if (Object.keys(summary.agreement).length > 0) { + const agreementLines = Object.entries(summary.agreement).map( + ([questionId, tally]) => + ` ${questionId}: ${tally.hit}/${tally.total} = ${Math.round((tally.hit / tally.total) * 100)}%`, + ); + output.info({ + "en-US": `=== generator intent vs teacher label ===\n${agreementLines.join("\n")}`, + "zh-CN": `=== 生成意图与 teacher 标注一致率 ===\n${agreementLines.join("\n")}`, + }); + } + if (usage) { + output.info({ + "en-US": `=== usage: ${usage.calls} calls, ${usage.prompt_tokens} in / ${usage.completion_tokens} out tokens, ${wallSeconds}s ===`, + "zh-CN": `=== 用量:${usage.calls} 次调用,输入 ${usage.prompt_tokens} / 输出 ${usage.completion_tokens} token,耗时 ${wallSeconds}s ===`, + }); + } + + return { + action: "dataset.generate", + mode, + schema: input.schema ?? "decision", + files: { + train: trainPath, + development: developmentPath, + manifest: manifestPath, + raw: rawPath, + }, + records: { train: parts.train.length, development: parts.development.length }, + unknowable_records: summary.unknowableRecords, + rejected_raw_records: summary.rejected, + duplicate_raw_records: summary.duplicates, + label_balance: balance, + generator_teacher_agreement: agreement, + usage, + }; +} diff --git a/packages/commands/src/commands/dataset/split.ts b/packages/commands/src/commands/dataset/split.ts new file mode 100644 index 00000000..1643676d --- /dev/null +++ b/packages/commands/src/commands/dataset/split.ts @@ -0,0 +1,288 @@ +import { mkdirSync, writeFileSync } from "fs"; +import { join } from "path"; +import { + BailianError, + DEFAULT_DEV_RATIO, + ExitCode, + MIN_SPLIT_RECORDS, + defineCommand, + loadWorkload, + readTextFromPathOrStdin, + splitRecords, + stateKey, + validateDataset, + workloadIdFields, + type FlagsDef, +} from "bailian-cli-core"; + +const SPLIT_FLAGS = { + input: { + type: "string", + valueHint: "", + description: { + "en-US": "Labeled JSONL file to split (use - for stdin)", + "zh-CN": "待切分的已标注 JSONL 文件(- 表示 stdin)", + }, + required: true, + }, + outDir: { + type: "string", + valueHint: "", + description: { + "en-US": "Output directory (default: output/custom)", + "zh-CN": "输出目录(默认:output/custom)", + }, + }, + prefix: { + type: "string", + valueHint: "", + description: { + "en-US": "Output file name prefix (default: tickets)", + "zh-CN": "输出文件名前缀(默认:tickets)", + }, + }, + seed: { + type: "number", + valueHint: "", + description: { + "en-US": "Shuffle seed for a reproducible split (default: 0)", + "zh-CN": "洗牌种子,保证切分可复现(默认:0)", + }, + }, + devRatio: { + type: "number", + valueHint: "", + description: { + "en-US": "Development share in (0, 1), floor(n * ratio) records (default: 0.15)", + "zh-CN": "development 占比,取值 (0, 1),按 floor(n * ratio) 取整(默认:0.15)", + }, + }, + workload: { + type: "string", + valueHint: "", + description: { + "en-US": "workload.json used to read id_fields for dedup", + "zh-CN": "用于读取去重忽略字段 id_fields 的 workload.json", + }, + }, + idFields: { + type: "string", + valueHint: "", + description: { + "en-US": "Comma-separated record-id fields ignored by dedup (overrides --workload)", + "zh-CN": "去重时忽略的记录编号字段,逗号分隔(覆盖 --workload 的 id_fields)", + }, + }, + schema: { + type: "string", + valueHint: "", + choices: ["decision"] as const, + description: { + "en-US": 'Record schema. Only "decision" (state/questions) is supported today.', + "zh-CN": '记录 Schema。当前仅支持 "decision"(state/questions 决策数据)。', + }, + }, +} satisfies FlagsDef; + +function usageError(english: string, chinese: string): BailianError { + return new BailianError(`${english} / ${chinese}`, ExitCode.USAGE); +} + +interface LabeledRecord { + state: unknown; + [field: string]: unknown; +} + +/** 逐行解析 JSONL;空行跳过,非法行或非对象记录报 USAGE。 */ +function readRecords(raw: string, inputPath: string): LabeledRecord[] { + const records: LabeledRecord[] = []; + const lines = raw.split("\n"); + for (let index = 0; index < lines.length; index++) { + const line = lines[index].trim(); + if (line.length === 0) continue; + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + throw usageError( + `${inputPath} line ${index + 1} is not valid JSON.`, + `${inputPath} 第 ${index + 1} 行不是合法的 JSON。`, + ); + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw usageError( + `${inputPath} line ${index + 1} must be a JSON object with "state".`, + `${inputPath} 第 ${index + 1} 行必须是含 "state" 的 JSON 对象。`, + ); + } + const record = parsed as LabeledRecord; + if (!("state" in record)) { + throw usageError( + `${inputPath} line ${index + 1} is missing "state".`, + `${inputPath} 第 ${index + 1} 行缺少 "state"。`, + ); + } + records.push(record); + } + return records; +} + +export default defineCommand({ + defaultOutput: "json", + description: { + "en-US": + "Split labeled decision JSONL into train/development files locally (dedup + seeded shuffle, no API calls)", + "zh-CN": + "在本地把已标注的决策 JSONL 切分为 train/development 两份文件(去重 + 种子洗牌,不调用 API)", + }, + // 纯本地切分,零费用、不触网、不需 API key。 + auth: "none", + usageArgs: + "--input [--out-dir ] [--prefix ] [--seed ] [--dev-ratio ] [--workload ] [--id-fields ] [--schema decision]", + flags: SPLIT_FLAGS, + exampleArgs: [ + "--input labeled.jsonl", + "--input labeled.jsonl --out-dir output/custom --prefix tickets", + "--input labeled.jsonl --workload workload.json --seed 42", + "--input labeled.jsonl --dev-ratio 0.2 --dry-run", + ], + notes: [ + { + "en-US": + 'Only decision-model data (state/questions records) is supported today; --schema accepts "decision" only.', + "zh-CN": '当前仅支持决策模型数据(state/questions 记录);--schema 只接受 "decision"。', + }, + { + "en-US": + "Dedup compares states ignoring record-id fields (id_fields from --workload, default ticket_id, or --id-fields); any duplicate state aborts with a usage error.", + "zh-CN": + "去重按忽略记录编号字段后的 state 比对(编号字段取 --workload 的 id_fields,默认 ticket_id,或用 --id-fields 覆盖);发现重复 state 即以用法错误终止。", + }, + { + "en-US": `At least ${MIN_SPLIT_RECORDS} records are required so both output files are non-empty.`, + "zh-CN": `至少需要 ${MIN_SPLIT_RECORDS} 条记录,保证两份输出文件都非空。`, + }, + { + "en-US": + "development takes floor(n * --dev-ratio) records after a seeded shuffle; the rest go to train. The PRNG differs from Python random.Random, so the same seed reproduces splits within this CLI only.", + "zh-CN": + "种子洗牌后 development 取 floor(n * --dev-ratio) 条,其余为 train。随机源与 Python random.Random 不同,同一 seed 仅在本 CLI 内可复现。", + }, + { + "en-US": + "Outputs .train.jsonl and .development.jsonl under --out-dir, then self-checks them with the decision training schema; --dry-run previews counts without writing.", + "zh-CN": + "在 --out-dir 下输出 .train.jsonl 与 .development.jsonl,并按决策训练 Schema 自检;--dry-run 仅预览计数,不写文件。", + }, + ], + async run(ctx) { + const { settings, flags } = ctx; + const inputPath = flags.input; + const outDir = flags.outDir ?? "output/custom"; + const prefix = flags.prefix ?? "tickets"; + const seed = flags.seed ?? 0; + const devRatio = flags.devRatio ?? DEFAULT_DEV_RATIO; + if (!Number.isFinite(devRatio) || devRatio <= 0 || devRatio >= 1) { + throw usageError( + "--dev-ratio must be a finite number in (0, 1).", + "--dev-ratio 必须是 (0, 1) 内的有限数值。", + ); + } + if (!Number.isFinite(seed)) { + throw usageError("--seed must be a finite number.", "--seed 必须是有限数值。"); + } + const idFields = flags.idFields + ? flags.idFields + .split(",") + .map((field) => field.trim()) + .filter((field) => field.length > 0) + : flags.workload + ? workloadIdFields(loadWorkload(flags.workload)) + : ["ticket_id"]; + + const records = readRecords(readTextFromPathOrStdin(inputPath), inputPath); + const seen = new Set(); + for (const record of records) { + const key = stateKey(record.state, idFields); + if (seen.has(key)) { + throw usageError( + `Duplicate state detected (ignoring id fields: ${idFields.join(", ")}). Deduplicate the input first.`, + `检测到重复 state(已忽略编号字段:${idFields.join(", ")})。请先对输入去重。`, + ); + } + seen.add(key); + } + if (records.length < MIN_SPLIT_RECORDS) { + throw usageError( + `Need at least ${MIN_SPLIT_RECORDS} records to split, got ${records.length}.`, + `切分至少需要 ${MIN_SPLIT_RECORDS} 条记录,当前只有 ${records.length} 条。`, + ); + } + const parts = splitRecords(records, seed, devRatio); + if (parts.development.length === 0 || parts.train.length === 0) { + throw usageError( + "--dev-ratio leaves one split empty; adjust it so both files are non-empty.", + "--dev-ratio 导致某一份为空;请调整比例使两份文件都非空。", + ); + } + const trainPath = join(outDir, `${prefix}.train.jsonl`); + const developmentPath = join(outDir, `${prefix}.development.jsonl`); + const counts = { + total: records.length, + train: parts.train.length, + development: parts.development.length, + }; + + if (settings.dryRun) { + const preview = { + action: "dataset.split", + input: inputPath, + schema: flags.schema ?? "decision", + seed, + dev_ratio: devRatio, + id_fields: idFields, + counts, + files: { train: trainPath, development: developmentPath }, + }; + ctx.output.result( + preview, + settings.output === "text" ? { text: JSON.stringify(preview, null, 2) } : undefined, + ); + return; + } + + mkdirSync(outDir, { recursive: true }); + writeFileSync(trainPath, parts.train.map((record) => JSON.stringify(record)).join("\n") + "\n"); + writeFileSync( + developmentPath, + parts.development.map((record) => JSON.stringify(record)).join("\n") + "\n", + ); + + // 产物按训练侧同一套 decision 规则自检,问题以警告透出(切分本身已完成)。 + const validation = await validateDataset(trainPath, { schema: "decision", fullValidate: true }); + const result = { + action: "dataset.split", + input: inputPath, + schema: flags.schema ?? "decision", + seed, + dev_ratio: devRatio, + counts, + files: { train: trainPath, development: developmentPath }, + validation: { + valid: validation.valid, + errors: validation.errors.length, + warnings: validation.warnings.length, + }, + }; + ctx.output.result( + result, + settings.output === "text" ? { text: JSON.stringify(result, null, 2) } : undefined, + ); + if (!validation.valid) { + ctx.output.warning({ + "en-US": `Split files written, but the train file failed decision-schema self-check (${validation.errors.length} error(s)); run "bl dataset validate --file ${trainPath} --schema decision" for details.`, + "zh-CN": `切分文件已写出,但 train 文件未通过决策 Schema 自检(${validation.errors.length} 个错误);可运行 "bl dataset validate --file ${trainPath} --schema decision" 查看详情。`, + }); + } + }, +}); diff --git a/packages/commands/src/commands/finetune/create.ts b/packages/commands/src/commands/finetune/create.ts index 1a0cb960..7c18652a 100644 --- a/packages/commands/src/commands/finetune/create.ts +++ b/packages/commands/src/commands/finetune/create.ts @@ -12,6 +12,9 @@ import { isTrainingTypeCli, TRAINING_TYPES_CLI, DEFAULT_TRAINING_TYPE, + preflightDecisionSampleGate, + readDecisionQuestionSignature, + compareDecisionQuestionTables, BailianError, ExitCode, type HttpDeps, @@ -23,9 +26,10 @@ import { type FlagsDef, } from "bailian-cli-core"; import { analyzeDatasetTokens, isLocalPath, uploadResolvedLocal } from "./dataset-input.ts"; +import { preflightTrainOptions } from "./train-options-shared.ts"; /** The modality a `finetune create` subcommand is bound to. */ -type CommandModality = "text" | "audio" | "image" | "video"; +type CommandModality = "text" | "audio" | "image" | "video" | "decision"; function explicitHyperParameterOverrides( commandModality: CommandModality, @@ -37,6 +41,8 @@ function explicitHyperParameterOverrides( batchSize: "batch_size", learningRate: "learning_rate", maxLength: "max_length", + modality: "modality", + reasoningMode: "reasoning_mode", evalSteps: "eval_steps", loraAlpha: "lora_alpha", loraDropout: "lora_dropout", @@ -55,6 +61,11 @@ function explicitHyperParameterOverrides( batchSize: "batch_size", learningRate: "learning_rate", }, + decision: { + nEpochs: "n_epochs", + batchSize: "batch_size", + learningRate: "learning_rate", + }, }; if (commandModality === "audio") return {}; @@ -297,6 +308,28 @@ const TEXT_FLAGS = { valueHint: "", description: { "en-US": "Max sequence length", "zh-CN": "最大序列长度" }, }, + modality: { + type: "string", + valueHint: "", + description: { + "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: { + "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; /** @@ -340,7 +373,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 ]"; + "--base-model --datasets [--validations ] [--job-name ] [--priority ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ] [--modality ] [--reasoning-mode ]"; const AUDIO_USAGE = "--base-model --datasets [--validations ] [--model-name ] [--suffix ]"; @@ -382,6 +415,51 @@ const VIDEO_FLAGS = { const VIDEO_USAGE = "--base-model --datasets [--validations ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ]"; +/** + * Decision flags: the decision model only supports efficient_sft (LoRA + * high-efficiency training) and exactly three hyper-parameters. No + * --training-type is exposed (the method is fixed); defaults and valid ranges + * come from the platform parameter schema, so the flags carry no local clamps. + */ +const DECISION_FLAGS = { + ...COMMON_FLAGS, + jobName: { + type: "string", + valueHint: "", + description: { + "en-US": "Training job display name (job_name)", + "zh-CN": "训练任务显示名称(job_name)", + }, + }, + nEpochs: { + type: "number", + valueHint: "", + description: { + "en-US": "Number of epochs (default: 2)", + "zh-CN": "训练轮数(默认:2)", + }, + }, + batchSize: { + type: "number", + valueHint: "", + description: { + "en-US": "Samples per training batch (default: 1)", + "zh-CN": "每个训练批次的样本数(默认:1)", + }, + }, + learningRate: { + type: "string", + valueHint: "", + description: { + "en-US": 'Learning rate as a string to preserve precision (default: "2e-5")', + "zh-CN": '以字符串形式指定学习率以保留精度(默认:"2e-5")', + }, + }, +} satisfies FlagsDef; + +const DECISION_USAGE = + "--base-model --datasets [--validations ] [--job-name ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ]"; + const COMMON_NOTES = [ { "en-US": "Creating a job uploads any local datasets and consumes training quota.", @@ -429,6 +507,12 @@ const TEXT_NOTES = [ "zh-CN": "提交前检查:如果训练数据集的样本数不大于 batch_size,会在上传或消耗额度前拒绝任务(否则平台会在数据处理约 10 分钟后才失败)。", }, + { + "en-US": + "--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.", + "zh-CN": + "--modality / --reasoning-mode 是训练选项,作为 hyper_parameters 条目发送,与子命令固定的数据格式无关。配置了动态训练选项的模型需要它们才能解析参数配置(例如仅支持视觉训练的 CPT 基座需要 --modality vision);未配置动态选项的模型会拒绝这两个 flag。非法组合由服务端拒绝并原样透传错误。", + }, ]; const AUDIO_NOTES = [ @@ -570,6 +654,8 @@ async function runCreate( if (commandModality === "text") { const extraParameters: Record = { + modality: "modality", + reasoningMode: "reasoning_mode", evalSteps: "eval_steps", loraAlpha: "lora_alpha", loraDropout: "lora_dropout", @@ -639,10 +725,37 @@ async function runCreate( } } + // Best-effort console precheck for dynamic train options: validate the + // combination and complete omitted options from the model defaults, so + // dynamic-option models work even without explicit flags. A missing console + // session degrades to a warning and leaves the user options unchanged. + if (commandModality === "text") { + const userTrainOptions: Record = {}; + if (typeof hp.modality === "string") userTrainOptions.modality = hp.modality; + if (typeof hp.reasoning_mode === "string") userTrainOptions.reasoning_mode = hp.reasoning_mode; + const resolved = await preflightTrainOptions( + ctx, + model, + profile.serverTrainingType, + userTrainOptions, + ); + for (const [optionName, optionValue] of Object.entries(resolved.context)) { + hp[optionName] = optionValue; + } + } + + // Dynamic train options (modality / reasoning_mode) double as the schema + // query context: models with dynamic options return an empty schema unless + // hyper_parameters carries the selected options. + const trainOptions: Record = {}; + if (typeof hp.modality === "string") trainOptions.modality = hp.modality; + if (typeof hp.reasoning_mode === "string") trainOptions.reasoning_mode = hp.reasoning_mode; + const parameterResponse = await getFineTuneParams(ctx.client, { inputModel: model, trainingType: profile.serverTrainingType, paramType: "hyper", + trainOptions, workspaceId: settings.workspaceId, }); const parameterSchema = parameterResponse.output?.hyper_params; @@ -654,8 +767,10 @@ async function runCreate( }), ExitCode.GENERAL, ctx.localize({ - "en-US": "The dataset was not uploaded and the training job was not submitted.", - "zh-CN": "数据集未上传,训练任务未提交。", + "en-US": + "The dataset was not uploaded and the training job was not submitted. If this model has dynamic train options, pass --modality / --reasoning-mode (query valid values with the finetune params command first).", + "zh-CN": + "数据集未上传,训练任务未提交。若该模型配置了动态训练选项,请传入 --modality / --reasoning-mode(合法值可先用 finetune params 命令查询)。", }), ); } @@ -695,6 +810,50 @@ async function runCreate( } } + // Decision-specific pre-flight: the sample-count rule (train/val each ≥ + // batch_size with a separate validation set, otherwise train ≥ batch_size × + // 10) replaces the generic gate above, and the training/validation question + // definitions must match. Both only run on local data outside dry-run; bare + // file-id counts are unknown and fall through to the platform. + if (commandModality === "decision" && !settings.dryRun) { + if (training.recordCount !== undefined || validation?.recordCount !== undefined) { + const effectiveBatchSize = + typeof hp.batch_size === "number" + ? hp.batch_size + : getFineTuneHyperParameterDefaultNumber(parameterSchema, "batch_size"); + if (effectiveBatchSize !== undefined) { + const gate = preflightDecisionSampleGate({ + hasValidation: Boolean(flags.validations), + trainingRecordCount: training.recordCount, + validationRecordCount: validation?.recordCount, + batchSize: effectiveBatchSize, + }); + if (!gate.ok && gate.issue) { + throw new BailianError(gate.issue.message, ExitCode.GENERAL, gate.hint); + } + } + } + const trainingPath = training.localPaths[0]; + const validationPath = validation?.localPaths[0]; + if (trainingPath && validationPath) { + const trainingSignature = await readDecisionQuestionSignature(trainingPath); + const validationSignature = await readDecisionQuestionSignature(validationPath); + if (trainingSignature && validationSignature) { + const driftedIds = compareDecisionQuestionTables(trainingSignature, validationSignature); + if (driftedIds.length > 0) { + ctx.output.warning({ + code: "DECISION_QUESTION_DEFINITION_MISMATCH", + message: { + "en-US": `Training and validation question definitions differ (IDs: ${driftedIds.join(", ")}). Keep question ID, type, instructions and criteria identical across training, evaluation and online requests; changing them requires regenerating data and retraining.`, + "zh-CN": `训练集与验证集的问题定义不一致(ID:${driftedIds.join(", ")})。训练、评估与线上请求的问题 ID、类型、instructions、criteria 必须保持一致;修改定义须重新准备数据并重训。`, + }, + details: { questions: driftedIds }, + }); + } + } + } + } + // Pre-flight capability check: confirm the model actually supports the // requested training type BEFORE any upload, so a wrong --model / // --training-type combo doesn't burn storage on datasets that will never @@ -784,6 +943,7 @@ export const finetuneTextCreate = defineCommand({ "zh-CN": "创建文本模型微调任务(sft | sft-lora | dpo | dpo-lora | cpt)", }, auth: "apiKey", + optionalConsole: true, usageArgs: TEXT_USAGE, flags: TEXT_FLAGS, exampleArgs: [ @@ -794,6 +954,7 @@ export const finetuneTextCreate = defineCommand({ "--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 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 file-xxx --dry-run", ], @@ -881,3 +1042,65 @@ export const finetuneVideoCreate = defineCommand({ notes: VIDEO_NOTES, run: (ctx) => runCreate("video", ctx), }); + +const DECISION_NOTES = [ + ...COMMON_NOTES, + { + "en-US": + "Training data is JSONL: each record carries an input state and a question table. Every question needs a hard label (choice: an option name; noul: true/false; score: a 0-based level index) and may carry a target soft-label distribution covering all options, with probabilities in [0, 1] summing to 1.", + "zh-CN": + "训练数据为 JSONL:每条记录包含输入 state 与问题表 questions。每个问题必填硬标签 label(choice:选项名;noul:true/false;score:从 0 开始的档位下标),可选软标签 target 须覆盖全部选项、概率在 [0, 1] 之间且合计为 1。", + }, + { + "en-US": + 'Decision fine-tuning always runs efficient_sft (LoRA high-efficiency training); full-parameter training is not available. Only n_epochs / batch_size / learning_rate are overridable; omitted values are sent with the documented defaults (2 / 1 / "2e-5") because the API requires them in the request body.', + "zh-CN": + '决策模型微调固定使用 efficient_sft(LoRA 高效训练),不支持全参训练。仅 n_epochs / batch_size / learning_rate 可覆盖;未指定项按文档默认值(2 / 1 / "2e-5")显式发送——API 要求请求体必须携带这些超参。', + }, + { + "en-US": + "Sample-count rule: with a separate validation dataset, train and validation samples must each be at least batch_size; with training data only, samples must be at least batch_size × 10. Hundreds of samples are recommended.", + "zh-CN": + "样本数规则:单独上传验证集时,训练集与验证集样本数均不小于 batch_size;仅上传训练集时,样本数不少于 batch_size × 10。推荐准备上百条样本。", + }, + { + "en-US": + "Keep question definitions (ID, type, instructions, criteria) identical across training, evaluation and online requests; changing them shifts the distribution and requires regenerating data and retraining. The CLI warns on cross-record and train/validation definition drift.", + "zh-CN": + "训练、评估与线上请求的问题定义(ID、类型、instructions、criteria)必须保持一致;修改定义会造成分布漂移,须重新准备数据并重训。CLI 会对跨记录及训练/验证集的定义漂移发出警告。", + }, + { + "en-US": + "--suffix is limited to 8 characters. After training, deploy the output model and invoke it with the decision command (--model ); training-only fields label/target are stripped automatically when reusing a training sample as a request file.", + "zh-CN": + "--suffix 最多 8 个字符。训练完成后部署产出模型,再用决策调用命令(--model )调用;复用训练样本作为请求文件时会自动剥离训练专用字段 label/target。", + }, +]; + +/** `bl finetune decision create` — fine-tune the decision model. Datasets are `.jsonl`. */ +export const finetuneDecisionCreate = defineCommand({ + defaultOutput: "json", + description: { + "en-US": + "Create a decision model fine-tune job (efficient_sft; choice/noul/score training data)", + "zh-CN": "创建决策模型微调任务(efficient_sft 高效训练;choice/noul/score 训练数据)", + }, + auth: "apiKey", + usageArgs: DECISION_USAGE, + flags: DECISION_FLAGS, + exampleArgs: [ + "--base-model decision-model-preview-2026-09-24 --datasets ./tickets.train.jsonl --validations ./tickets.development.jsonl", + "--base-model decision-model-preview-2026-09-24 --datasets file-xxx", + '--base-model decision-model-preview-2026-09-24 --datasets ./tickets.train.jsonl --n-epochs 3 --batch-size 4 --learning-rate "2e-5" --suffix mytune', + "--base-model decision-model-preview-2026-09-24 --datasets ./tickets.train.jsonl --dry-run", + ], + notes: DECISION_NOTES, + validate: (flags) => { + const suffix = flags.suffix as string | undefined; + if (suffix !== undefined && suffix.length > 8) { + return "--suffix must be at most 8 characters for the decision model. / 决策模型的 --suffix 最多 8 个字符。"; + } + return undefined; + }, + run: (ctx) => runCreate("decision", ctx), +}); diff --git a/packages/commands/src/commands/finetune/params.ts b/packages/commands/src/commands/finetune/params.ts index ab4952e2..d5ae1853 100644 --- a/packages/commands/src/commands/finetune/params.ts +++ b/packages/commands/src/commands/finetune/params.ts @@ -9,6 +9,7 @@ import { 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 @@ -91,15 +92,6 @@ const PARAMS_FLAGS = { "zh-CN": "服务端展示文案的语言(例如 en、zh)。不传由服务端决定。", }, }, - workspaceId: { - type: "string", - valueHint: "", - description: { - "en-US": - "Workspace ID sent as X-DashScope-WorkSpace; omit when your API key is already workspace-bound.", - "zh-CN": "以 X-DashScope-WorkSpace 头发送的业务空间 ID;API Key 已绑定空间时可省略。", - }, - }, } satisfies FlagsDef; export default defineCommand({ @@ -109,8 +101,9 @@ export default defineCommand({ "zh-CN": "查询基础模型的训练超参配置", }, auth: "apiKey", + optionalConsole: true, usageArgs: - "--base-model [--training-type ] [--param-type ] [--mtu-spec-code ] [--modality ] [--reasoning-mode ] [--lang ] [--workspace-id ]", + "--base-model [--training-type ] [--param-type ] [--mtu-spec-code ] [--modality ] [--reasoning-mode ] [--lang ]", flags: PARAMS_FLAGS, exampleArgs: [ "--base-model qwen3-8b", @@ -130,9 +123,9 @@ export default defineCommand({ }, { "en-US": - "--modality / --reasoning-mode travel as one hyper_parameters query parameter (JSON). Supported values and combinations vary per model; invalid combinations are rejected by the server and surfaced as-is. Models without dynamic train options ignore these flags.", + "--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)发送。各模型支持的取值与组合不同;非法组合由服务端拒绝并原样透传错误。未配置动态训练选项的模型可忽略这两个 flag。", + "--modality / --reasoning-mode 会合并为单个 hyper_parameters query 参数(JSON)发送。控制台会话可用时,会按模型支持的组合预检,并从默认值补齐未传的选项;非法组合报用法错误。无控制台会话时跳过预检并输出警告,以服务端结果为准。", }, { "en-US": @@ -152,7 +145,7 @@ export default defineCommand({ ); } const trainingType = TRAINING_TYPE_MAP[trainingTypeCli].server; - const trainOptions = buildTrainOptions(flags.modality, flags.reasoningMode); + let trainOptions = buildTrainOptions(flags.modality, flags.reasoningMode); if (settings.dryRun) { const resultData = { @@ -165,7 +158,7 @@ export default defineCommand({ ? { hyper_parameters: JSON.stringify(trainOptions) } : {}), ...(flags.lang ? { lang: flags.lang } : {}), - ...(flags.workspaceId ? { workspace_id: flags.workspaceId } : {}), + ...(settings.workspaceId ? { workspace_id: settings.workspaceId } : {}), }; ctx.output.result( resultData, @@ -174,6 +167,13 @@ export default defineCommand({ return; } + // Best-effort console precheck: validate the combination against the + // model's supportedCombinations and complete omitted options from its + // defaults. Skipped offline in dry-run; 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 getFineTuneParams(ctx.client, { inputModel: flags.baseModel, trainingType, @@ -181,11 +181,12 @@ export default defineCommand({ paramType: flags.paramType || undefined, trainOptions, lang: flags.lang || undefined, - workspaceId: flags.workspaceId || undefined, + workspaceId: settings.workspaceId, }); + const payload = { ...response, precheck: resolved.precheck }; ctx.output.result( - response, + payload, ctx.settings.output === "text" ? { text: JSON.stringify(response, null, 2) } : undefined, ); }, diff --git a/packages/commands/src/commands/finetune/train-options-shared.ts b/packages/commands/src/commands/finetune/train-options-shared.ts new file mode 100644 index 00000000..eeb1302f --- /dev/null +++ b/packages/commands/src/commands/finetune/train-options-shared.ts @@ -0,0 +1,74 @@ +import { + fetchModelTrainOptions, + resolveTrainOptions, + UsageError, + type CommandContext, + type TrainOptionsIssue, +} from "bailian-cli-core"; + +export interface TrainOptionsPreflight { + /** Validated options with omitted values completed from the model defaults. */ + context: Record; + precheck: Record; +} + +function formatIssue(issue: TrainOptionsIssue, model: string): string { + switch (issue.code) { + case "not_configured": + return `Model ${model} has no dynamic train options; remove --modality / --reasoning-mode. / 模型 ${model} 未配置动态训练选项,请移除 --modality / --reasoning-mode。`; + case "unsupported_value": + return `Unsupported value "${issue.value}" for train option "${issue.key}". Supported values: ${(issue.expected ?? []).join(", ")}. / 训练选项 "${issue.key}" 的值 "${issue.value}" 不受支持。合法值:${(issue.expected ?? []).join("、")}。`; + case "invalid_combination": { + const combinations = (issue.combinations ?? []) + .map((combination) => + Object.entries(combination) + .map(([key, value]) => `${key}=${value}`) + .join("+"), + ) + .join("; "); + return `Invalid train-options combination for ${model}. Supported combinations: ${combinations}. / 模型 ${model} 的训练选项组合不合法。合法组合:${combinations}。`; + } + } +} + +/** + * Best-effort console precheck for dynamic train options (modality / + * reasoning_mode): validates the user's combination against the console + * configuration and completes omitted options from the model defaults. + * + * Follows the cmodel import contract: usage issues fail fast; a missing or + * expired console session skips the check with a warning and passes the user + * options through unchanged — the training API's final result stays + * authoritative. + */ +export async function preflightTrainOptions( + ctx: CommandContext, + model: string, + serverTrainingType: string, + userOptions: Record, +): Promise { + try { + const options = await fetchModelTrainOptions( + ctx.client.console.bind(ctx.client), + model, + serverTrainingType, + ); + const { context, issues } = resolveTrainOptions(options, userOptions); + if (issues.length > 0) { + throw new UsageError(issues.map((issue) => formatIssue(issue, model)).join("\n")); + } + return { context, precheck: { performed: true, dynamic_options: options !== null } }; + } catch (error) { + if (error instanceof UsageError) throw error; + ctx.output.warning({ + code: "finetune.train_options_precheck_skipped", + message: { + "en-US": + "Train-options precheck skipped (console session unavailable or expired). The training API's final result is authoritative.", + "zh-CN": "已跳过训练选项预检(控制台会话不可用或已过期)。以训练接口的最终结果为准。", + }, + details: { message: error instanceof Error ? error.message : String(error) }, + }); + return { context: userOptions, precheck: { performed: false, reason: "console-unavailable" } }; + } +} diff --git a/packages/commands/src/commands/finetune/train-options.ts b/packages/commands/src/commands/finetune/train-options.ts new file mode 100644 index 00000000..191236f0 --- /dev/null +++ b/packages/commands/src/commands/finetune/train-options.ts @@ -0,0 +1,137 @@ +import { + defineCommand, + fetchModelTrainOptions, + MODEL_TRAIN_OPTIONS_API, + isTrainingTypeCli, + TRAINING_TYPES_CLI, + TRAINING_TYPE_MAP, + BailianError, + ExitCode, + type FlagsDef, +} from "bailian-cli-core"; + +const TRAIN_OPTIONS_FLAGS = { + baseModel: { + type: "string", + valueHint: "", + description: { + "en-US": "Base model to query dynamic train options for (e.g. qwen3.6-plus-base-2026-04-02)", + "zh-CN": "要查询动态训练选项的基础模型(例如 qwen3.6-plus-base-2026-04-02)", + }, + 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)。`, + }, + }, +} satisfies FlagsDef; + +export default defineCommand({ + defaultOutput: "json", + description: { + "en-US": "Query a base model's dynamic train options (modality / reasoning-mode combinations)", + "zh-CN": "查询基础模型的动态训练选项(modality / reasoning-mode 合法组合)", + }, + auth: "console", + usageArgs: "--base-model [--training-type ]", + flags: TRAIN_OPTIONS_FLAGS, + exampleArgs: [ + "--base-model qwen3.6-plus-base-2026-04-02", + "--base-model qwen3.6-plus-base-2026-04-02 --training-type cpt", + "--base-model qwen3-8b", + "--base-model qwen3-8b --dry-run", + ], + 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.", + "zh-CN": + "调用控制台网关 model-train-options 接口,需要控制台登录态。结果原样保留服务端字段名(optionKeys、optionDefinitions、defaults、supportedCombinations)。未配置动态训练选项的模型返回 training_options: 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.", + "zh-CN": + "supportedCombinations 是选项组合合法性的唯一权威。finetune params 与 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.", + "zh-CN": + "选定的选项通过 --modality / --reasoning-mode 传给 finetune params / 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 trainingType = TRAINING_TYPE_MAP[trainingTypeCli].server; + + if (settings.dryRun) { + const resultData = { + action: "finetune.train-options", + api: MODEL_TRAIN_OPTIONS_API, + input: { models: [flags.baseModel], trainingType }, + }; + ctx.output.result( + resultData, + ctx.settings.output === "text" ? { text: JSON.stringify(resultData, null, 2) } : undefined, + ); + return; + } + + const options = await fetchModelTrainOptions( + ctx.client.console.bind(ctx.client), + flags.baseModel, + trainingType, + ); + const result = { + model: flags.baseModel, + training_type: trainingType, + training_options: options, + }; + + if (settings.output === "text") { + const lines: string[] = []; + if (!options) { + lines.push(`No dynamic train options configured for ${flags.baseModel} (${trainingType}).`); + } else { + for (const definition of options.optionDefinitions ?? []) { + const values = (definition.supportValues ?? []).join(" | "); + const required = definition.required ? ", required" : ""; + const recommended = definition.recommendValue + ? `, recommend=${definition.recommendValue}` + : ""; + lines.push(`${definition.name}: ${values}${required}${recommended}`); + } + const defaults = Object.entries(options.defaults ?? {}) + .map(([key, value]) => `${key}=${value}`) + .join(", "); + if (defaults) lines.push(`defaults: ${defaults}`); + const combinations = (options.supportedCombinations ?? []) + .map((combination) => + Object.entries(combination) + .map(([key, value]) => `${key}=${value}`) + .join("+"), + ) + .join("; "); + if (combinations) lines.push(`supported combinations: ${combinations}`); + } + ctx.output.result(result, { text: lines.join("\n") }); + return; + } + + ctx.output.result(result); + }, +}); diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index e6f26885..15bb281d 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -191,11 +191,14 @@ export { default as datasetVersion } from "./commands/dataset/version.ts"; export { default as datasetGroups } from "./commands/dataset/groups.ts"; export { default as datasetDelete } from "./commands/dataset/delete.ts"; export { default as datasetValidate } from "./commands/dataset/validate.ts"; +export { default as datasetSplit } from "./commands/dataset/split.ts"; +export { default as datasetGenerate } from "./commands/dataset/generate.ts"; export { finetuneTextCreate, finetuneAudioCreate, finetuneImageCreate, finetuneVideoCreate, + finetuneDecisionCreate, } from "./commands/finetune/create.ts"; export { default as finetuneList } from "./commands/finetune/list.ts"; export { default as finetuneGet } from "./commands/finetune/get.ts"; @@ -208,6 +211,7 @@ export { default as finetuneWatch } from "./commands/finetune/watch.ts"; 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 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/dataset-prepare.e2e.test.ts b/packages/commands/tests/e2e/dataset-prepare.e2e.test.ts new file mode 100644 index 00000000..f6dd4a88 --- /dev/null +++ b/packages/commands/tests/e2e/dataset-prepare.e2e.test.ts @@ -0,0 +1,973 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, test } from "vite-plus/test"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createServer, type Server, type ServerResponse } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { parseStdoutJson, runCommandHelp, runCommandInProcess } from "./helpers.ts"; +import { DATASET_ROUTES } from "./topic-routes.ts"; + +/** + * Decision data preparation E2E (offline). + * + * `dataset split` is keyless and purely local; `dataset generate` local modes + * (--from-raw / --dry-run) never touch the network, and its API pipeline is + * exercised against a loopback chat/completions mock. No real credentials or + * endpoints are used anywhere in this file. + */ + +let fixtureDir = ""; + +function decisionRecord(index: number, overrides?: { label?: string }): string { + return JSON.stringify({ + state: { ticket_id: `T-${index}`, content: `客户反馈问题描述 ${index}` }, + questions: { + team: { + type: "choice", + instructions: "应该由哪个团队处理?", + criteria: { billing: "账单与支付问题", technical: "产品故障问题" }, + label: overrides?.label ?? "billing", + }, + }, + }); +} + +function decisionLines(count: number): string[] { + return Array.from({ length: count }, (_line, index) => decisionRecord(index)); +} + +const WORKLOAD = { + name: "cloud-support-zh", + description: "客服工单分流", + state_schema: { ticket_id: "工单编号", content: "工单正文" }, + id_fields: ["case_id"], + questions: { + team: { + type: "choice", + instructions: "应该由哪个团队处理?", + criteria: { billing: "账单与支付问题", technical: "产品故障问题" }, + }, + }, +}; + +beforeAll(() => { + fixtureDir = mkdtempSync(join(tmpdir(), "bl-dataset-prepare-e2e-")); + writeFileSync(join(fixtureDir, "labeled-20.jsonl"), decisionLines(20).join("\n")); + writeFileSync(join(fixtureDir, "labeled-6.jsonl"), decisionLines(6).join("\n")); + writeFileSync(join(fixtureDir, "workload.json"), JSON.stringify(WORKLOAD)); + // 两条记录 content 相同、ticket_id 不同:默认忽略 ticket_id 后应判重。 + writeFileSync( + join(fixtureDir, "duplicate.jsonl"), + [decisionRecord(1), decisionRecord(2)].join("\n").replace("问题描述 2", "问题描述 1"), + ); + // 编号字段为 case_id 的重复对:默认 ticket_id 规则判不出,--workload 才能判出。 + const caseLines = [1, 2].map((index) => + JSON.stringify({ + state: { case_id: `C-${index}`, content: "同一份工单正文" }, + questions: { + team: { + type: "choice", + instructions: "哪个团队?", + criteria: { billing: "账单", technical: "技术" }, + label: "billing", + }, + }, + }), + ); + writeFileSync(join(fixtureDir, "case-duplicate.jsonl"), caseLines.join("\n")); + writeFileSync(join(fixtureDir, "bad-label.jsonl"), decisionRecord(1, { label: "sales" })); + writeFileSync(join(fixtureDir, "broken.jsonl"), "{not json}\n"); +}); + +afterAll(() => rmSync(fixtureDir, { recursive: true, force: true })); + +function runSplit(args: string[]) { + return runCommandInProcess(DATASET_ROUTES, ["dataset", "split", ...args]); +} + +interface SplitResult { + action: string; + counts: { total: number; train: number; development: number }; + files: { train: string; development: string }; + validation?: { valid: boolean; errors: number }; +} + +describe("e2e: dataset split (offline)", () => { + test("split --help 展示切分 flag 且标明仅 decision", async () => { + const { stderr, exitCode } = await runCommandHelp(DATASET_ROUTES, [ + "dataset", + "split", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--input/); + expect(stderr).toMatch(/--dev-ratio/); + expect(stderr).toMatch(/--seed/); + expect(stderr).toMatch(/decision/i); + }); + + test("split 缺少 --input 退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSplit(["--quiet"]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--input|Missing required/i); + }); + + test("split 按 15% 切分并写出两份文件", async () => { + const outDir = join(fixtureDir, "out-default"); + const { stdout, stderr, exitCode } = await runSplit([ + "--input", + join(fixtureDir, "labeled-20.jsonl"), + "--out-dir", + outDir, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson(stdout); + expect(data.action).toBe("dataset.split"); + expect(data.counts).toEqual({ total: 20, train: 17, development: 3 }); + expect(data.validation?.valid).toBe(true); + const trainLines = readFileSync(join(outDir, "tickets.train.jsonl"), "utf8").trim().split("\n"); + const devLines = readFileSync(join(outDir, "tickets.development.jsonl"), "utf8") + .trim() + .split("\n"); + expect(trainLines).toHaveLength(17); + expect(devLines).toHaveLength(3); + }); + + test("split 同 seed 两次切分结果逐字节一致", async () => { + const firstDir = join(fixtureDir, "out-seed-a"); + const secondDir = join(fixtureDir, "out-seed-b"); + const input = join(fixtureDir, "labeled-20.jsonl"); + const first = await runSplit(["--input", input, "--out-dir", firstDir, "--seed", "42"]); + const second = await runSplit(["--input", input, "--out-dir", secondDir, "--seed", "42"]); + expect(first.exitCode, first.stderr).toBe(0); + expect(second.exitCode, second.stderr).toBe(0); + expect(readFileSync(join(firstDir, "tickets.train.jsonl"), "utf8")).toBe( + readFileSync(join(secondDir, "tickets.train.jsonl"), "utf8"), + ); + }); + + test("split --dev-ratio 0.5 --prefix cases 自定义比例与文件名", async () => { + const outDir = join(fixtureDir, "out-half"); + const { stdout, stderr, exitCode } = await runSplit([ + "--input", + join(fixtureDir, "labeled-20.jsonl"), + "--out-dir", + outDir, + "--prefix", + "cases", + "--dev-ratio", + "0.5", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson(stdout); + expect(data.counts.train).toBe(10); + expect(data.counts.development).toBe(10); + expect(existsSync(join(outDir, "cases.train.jsonl"))).toBe(true); + expect(existsSync(join(outDir, "cases.development.jsonl"))).toBe(true); + }); + + test("split 重复 state(忽略 ticket_id)退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSplit([ + "--input", + join(fixtureDir, "duplicate.jsonl"), + "--out-dir", + join(fixtureDir, "out-dup"), + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/重复|Duplicate/i); + }); + + test("split --workload 用 id_fields 判重,--id-fields 可覆盖", async () => { + const input = join(fixtureDir, "case-duplicate.jsonl"); + // 仅两条记录:先绕过最少记录数限制不现实,这里直接断言判重先于数量校验。 + const viaWorkload = await runSplit([ + "--input", + input, + "--workload", + join(fixtureDir, "workload.json"), + ]); + expect(viaWorkload.exitCode).toBe(2); + expect(viaWorkload.stderr).toMatch(/重复|Duplicate/i); + // 覆盖为不忽略任何编号字段后,两条 state 不再重复,转而触发最少记录数校验。 + const viaOverride = await runSplit(["--input", input, "--id-fields", "none"]); + expect(viaOverride.exitCode).toBe(2); + expect(viaOverride.stderr).toMatch(/至少|at least/i); + }); + + test("split 少于 7 条退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSplit([ + "--input", + join(fixtureDir, "labeled-6.jsonl"), + "--out-dir", + join(fixtureDir, "out-few"), + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/至少|at least/i); + }); + + test("split 非法 JSON 行退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSplit(["--input", join(fixtureDir, "broken.jsonl")]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/JSON/i); + }); + + test.each(["0", "1", "abc"])("split --dev-ratio %s 拒绝", async (ratio) => { + const { stderr, exitCode } = await runSplit([ + "--input", + join(fixtureDir, "labeled-20.jsonl"), + "--dev-ratio", + ratio, + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/dev-ratio/i); + }); + + test("split --schema 拒绝非 decision 值", async () => { + const { stderr, exitCode } = await runSplit([ + "--input", + join(fixtureDir, "labeled-20.jsonl"), + "--schema", + "chatml", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/schema|decision/i); + }); + + test("split --dry-run 预览计数且不写文件", async () => { + const outDir = join(fixtureDir, "out-dry"); + const { stdout, stderr, exitCode } = await runSplit([ + "--input", + join(fixtureDir, "labeled-20.jsonl"), + "--out-dir", + outDir, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson(stdout); + expect(data.counts).toEqual({ total: 20, train: 17, development: 3 }); + expect(existsSync(outDir)).toBe(false); + }); + + test("split 产物自检失败时仍写文件并以警告透出", async () => { + const outDir = join(fixtureDir, "out-bad-label"); + // 7 条全部坏标签:无论洗牌结果如何,train 文件自检必失败。 + const mixed = join(fixtureDir, "mixed-label.jsonl"); + writeFileSync( + mixed, + Array.from({ length: 7 }, (_line, index) => decisionRecord(index, { label: "sales" })).join( + "\n", + ), + ); + const { stdout, stderr, exitCode } = await runSplit([ + "--input", + mixed, + "--out-dir", + outDir, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson(stdout); + expect(data.validation?.valid).toBe(false); + expect(stderr).toMatch(/自检|self-check/i); + expect(existsSync(data.files.train)).toBe(true); + }); +}); + +// ---- dataset generate:本地模式(--from-raw / --dry-run)与参数闸门 ---- + +const GENERATE_WORKLOAD = { + name: "cloud-support-zh", + description: "客服工单分流", + state_schema: { ticket_id: "工单编号", content: "工单正文" }, + questions: { + team: { + type: "choice", + instructions: "应该由哪个团队处理?", + criteria: { billing: "账单与支付问题", technical: "产品故障问题" }, + }, + }, + guidance: ["涉及退款一律升级"], + axes: { team: ["billing", "technical"] }, +}; + +function rawRow( + index: number, + overrides?: { difficulty?: string; content?: string; probabilities?: Record }, +): string { + return JSON.stringify({ + state: { ticket_id: `T-${index}`, content: overrides?.content ?? `工单正文 ${index}` }, + plan: { difficulty: overrides?.difficulty ?? "clean", team: "billing", index }, + answers: { + team: { + type: "choice", + probabilities: overrides?.probabilities ?? { billing: 0.9, technical: 0.1 }, + }, + }, + missing: [], + }); +} + +interface GenerateResult { + action: string; + mode: string; + records: { train: number; development: number }; + unknowable_records: number; + rejected_raw_records: number; + duplicate_raw_records: number; + files: { train: string; development: string; manifest: string; raw: string }; + generator_teacher_agreement?: Record; + usage: { calls: number } | null; +} + +describe("e2e: dataset generate local modes (offline)", () => { + let genServer: Server; + let genOrigin = ""; + let genRequests = 0; + let genDir = ""; + let workloadPath = ""; + let raw10 = ""; + let rawMixed = ""; + let rawFew = ""; + + function runGenerate(args: string[], env: NodeJS.ProcessEnv = {}) { + return runCommandInProcess(DATASET_ROUTES, ["dataset", "generate", ...args], { + DASHSCOPE_API_KEY: "offline-test-only", + DASHSCOPE_BASE_URL: genOrigin, + BAILIAN_WORKSPACE_ID: "", + NODE_OPTIONS: "", + HTTP_PROXY: "", + HTTPS_PROXY: "", + ALL_PROXY: "", + NO_PROXY: "", + http_proxy: "", + https_proxy: "", + all_proxy: "", + no_proxy: "", + NODE_USE_ENV_PROXY: "", + ...env, + }); + } + + beforeAll(async () => { + genDir = mkdtempSync(join(tmpdir(), "bl-dataset-generate-e2e-")); + workloadPath = join(genDir, "workload.json"); + writeFileSync(workloadPath, JSON.stringify(GENERATE_WORKLOAD)); + raw10 = join(genDir, "raw-10.jsonl"); + writeFileSync(raw10, Array.from({ length: 10 }, (_line, index) => rawRow(index)).join("\n")); + // 10 clean + 2 unknowable + 1 重复 state + 1 missing → 12 条可用记录。 + rawMixed = join(genDir, "raw-mixed.jsonl"); + writeFileSync( + rawMixed, + [ + ...Array.from({ length: 10 }, (_line, index) => rawRow(index)), + rawRow(20, { difficulty: "unknowable" }), + rawRow(21, { difficulty: "unknowable" }), + rawRow(22, { content: "工单正文 0" }), + JSON.stringify({ + state: { ticket_id: "T-23", content: "缺标注的工单" }, + plan: { difficulty: "clean", index: 23 }, + answers: {}, + missing: ["team"], + }), + ].join("\n"), + ); + rawFew = join(genDir, "raw-few.jsonl"); + writeFileSync(rawFew, Array.from({ length: 3 }, (_line, index) => rawRow(index)).join("\n")); + // 本地模式不应触网:任何请求都计数并返回 500,便于断言零调用。 + genServer = createServer((_request, response) => { + genRequests += 1; + response.statusCode = 500; + response.setHeader("content-type", "application/json"); + response.end('{"message":"local mode must not call the API"}'); + }); + await new Promise((resolve, reject) => { + genServer.once("error", reject); + genServer.listen(0, "127.0.0.1", resolve); + }); + const address = genServer.address(); + if (!address || typeof address === "string") throw new Error("Expected a local TCP server."); + genOrigin = `http://127.0.0.1:${address.port}`; + }); + + afterAll(async () => { + genServer.closeAllConnections(); + await new Promise((resolve) => genServer.close(() => resolve())); + rmSync(genDir, { recursive: true, force: true }); + }); + + test("generate --help 展示全模式 flag 且标明仅 decision", async () => { + const { stderr, exitCode } = await runCommandHelp(DATASET_ROUTES, [ + "dataset", + "generate", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--workload/); + expect(stderr).toMatch(/--from-raw/); + expect(stderr).toMatch(/--from-states/); + expect(stderr).toMatch(/--resume-raw/); + expect(stderr).toMatch(/--states-only/); + expect(stderr).toMatch(/--target-temp/); + expect(stderr).toMatch(/decision/i); + }); + + test("generate 缺少 --workload 退出为用法错误 (2),并给出骨架与字段速查指引", async () => { + const { stderr, exitCode } = await runGenerate(["--quiet"]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--workload/); + // 报错现场即给出最小骨架(questions 键)与字段写法出处(--help Notes)。 + expect(stderr).toMatch(/questions/); + expect(stderr).toMatch(/--help/); + }); + + test("generate --from-raw 零网络转换并写出产物与 manifest", async () => { + const outDir = join(genDir, "out-from-raw"); + const { stdout, stderr, exitCode } = await runGenerate([ + "--workload", + workloadPath, + "--from-raw", + rawMixed, + "--out-dir", + outDir, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(genRequests).toBe(0); + const data = parseStdoutJson(stdout); + expect(data.action).toBe("dataset.generate"); + expect(data.mode).toBe("from_raw"); + expect(data.records).toEqual({ train: 11, development: 1 }); + expect(data.unknowable_records).toBe(2); + expect(data.duplicate_raw_records).toBe(1); + expect(data.rejected_raw_records).toBe(1); + expect(data.usage).toBeNull(); + const manifest = JSON.parse(readFileSync(data.files.manifest, "utf8")) as Record< + string, + unknown + >; + expect(manifest.mode).toBe("from_raw"); + expect(manifest.usage).toBeNull(); + expect((manifest.generator as Record).model).toBeNull(); + expect(typeof manifest.workload_sha256).toBe("string"); + expect((manifest.state_token_check as Record).status).toBe("skipped"); + // unknowable 记录保留均匀 target 与 _meta.source。 + const allLines = [ + ...readFileSync(data.files.train, "utf8").trim().split("\n"), + ...readFileSync(data.files.development, "utf8").trim().split("\n"), + ].map( + (line) => + JSON.parse(line) as { + _meta?: { source: string }; + questions: Record }>; + }, + ); + const unknowable = allLines.filter((record) => record._meta?.source === "unknowable"); + expect(unknowable).toHaveLength(2); + expect(unknowable[0].questions.team.target).toEqual({ billing: 0.5, technical: 0.5 }); + }); + + test("generate --from-raw --target-temp 1.0 保留 teacher 原分布", async () => { + const outDir = join(genDir, "out-temp1"); + const { stderr, exitCode } = await runGenerate([ + "--workload", + workloadPath, + "--from-raw", + raw10, + "--target-temp", + "1.0", + "--out-dir", + outDir, + ]); + expect(exitCode, stderr).toBe(0); + expect(genRequests).toBe(0); + const lines = readFileSync(join(outDir, "tickets.train.jsonl"), "utf8").trim().split("\n"); + for (const line of lines) { + const record = JSON.parse(line) as { + questions: { team: { target: Record } }; + }; + expect(record.questions.team.target.billing).toBeCloseTo(0.9, 5); + expect(record.questions.team.target.technical).toBeCloseTo(0.1, 5); + } + }); + + test("generate --from-raw --no-soft-target 仅硬标签", async () => { + const outDir = join(genDir, "out-no-soft"); + const { stderr, exitCode } = await runGenerate([ + "--workload", + workloadPath, + "--from-raw", + raw10, + "--no-soft-target", + "--out-dir", + outDir, + ]); + expect(exitCode, stderr).toBe(0); + const lines = readFileSync(join(outDir, "tickets.train.jsonl"), "utf8").trim().split("\n"); + for (const line of lines) { + const record = JSON.parse(line) as { + questions: { team: { label: string; target?: unknown } }; + }; + expect(record.questions.team.label).toBe("billing"); + expect(record.questions.team.target).toBeUndefined(); + } + }); + + test("generate --from-raw 可用记录不足 7 条以非零码退出", async () => { + const { stderr, exitCode } = await runGenerate([ + "--workload", + workloadPath, + "--from-raw", + rawFew, + "--out-dir", + join(genDir, "out-few"), + ]); + expect(exitCode).toBe(1); + expect(stderr).toMatch(/至少|at least/i); + expect(genRequests).toBe(0); + }); + + test("generate --dry-run 预览画像与调用数,零网络零写入", async () => { + const outDir = join(genDir, "out-dry-gen"); + const { stdout, stderr, exitCode } = await runGenerate([ + "--workload", + workloadPath, + "--samples", + "12", + "--unknowable", + "2", + "--batch", + "5", + "--out-dir", + outDir, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(genRequests).toBe(0); + expect(existsSync(outDir)).toBe(false); + const data = parseStdoutJson<{ + mode: string; + plans: { total: number; unknowable: number }; + estimated_calls: { generation: number; labeling: number }; + sample: { generation_messages: unknown[]; teacher_messages: unknown[] }; + }>(stdout); + expect(data.mode).toBe("generate"); + expect(data.plans).toEqual({ total: 14, unknowable: 2 }); + expect(data.estimated_calls).toEqual({ generation: 3, labeling: 14 }); + expect(data.sample.generation_messages).toHaveLength(2); + expect(data.sample.teacher_messages).toHaveLength(2); + }); + + test("generate --from-raw --dry-run 预览行数且不转换不写文件", async () => { + const outDir = join(genDir, "out-dry-raw"); + const { stdout, stderr, exitCode } = await runGenerate([ + "--workload", + workloadPath, + "--from-raw", + raw10, + "--out-dir", + outDir, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(genRequests).toBe(0); + expect(existsSync(outDir)).toBe(false); + const data = parseStdoutJson<{ + mode: string; + rows: number; + estimated_calls: { generation: number; labeling: number }; + }>(stdout); + expect(data.mode).toBe("from_raw"); + expect(data.rows).toBe(10); + expect(data.estimated_calls).toEqual({ generation: 0, labeling: 0 }); + }); + + test("generate 生成模式缺少 state_schema 退出为用法错误 (2)", async () => { + const bare = join(genDir, "workload-bare.json"); + writeFileSync( + bare, + JSON.stringify({ description: "客服工单分流", questions: GENERATE_WORKLOAD.questions }), + ); + const { stderr, exitCode } = await runGenerate(["--workload", bare, "--dry-run"]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/state_schema/); + }); + + test.each([ + ["--from-raw 与 --states-only 互斥", ["--from-raw", "x.jsonl", "--states-only"]], + ["--from-raw 与 --from-states 互斥", ["--from-raw", "x.jsonl", "--from-states", "y.jsonl"]], + ["--resume-raw 需要 --from-states", ["--resume-raw", "x.jsonl"]], + ["--states-only 与 --from-states 互斥", ["--states-only", "--from-states", "y.jsonl"]], + ["--batch 必须为正", ["--batch", "0"]], + ["--samples 必须非负", ["--samples", "-1"]], + ["--target-temp 必须为正", ["--target-temp", "0"]], + ])("generate %s 退出为用法错误 (2)", async (_label, extraArgs) => { + const { stderr, exitCode } = await runGenerate(["--workload", workloadPath, ...extraArgs]); + expect(exitCode).toBe(2); + expect(stderr.length).toBeGreaterThan(0); + expect(genRequests).toBe(0); + }); +}); + +// ---- dataset generate:API 管线(loopback mock chat/completions,零真实网络) ---- + +// 单轴 billing:生成意图与 teacher 硬标签一致率应为 1,technical 占比 0 触发 <5% 警告。 +const PIPELINE_WORKLOAD = { ...GENERATE_WORKLOAD, axes: { team: ["billing"] } }; + +interface ChatBody { + model?: string; + temperature?: number; + enable_thinking?: boolean; + enable_search?: boolean; + messages?: Array<{ role: string; content: string }>; + [key: string]: unknown; +} + +function chatResponse(content: string): Record { + return { + id: "chatcmpl-mock", + object: "chat.completion", + created: 0, + model: "mock", + choices: [{ index: 0, message: { role: "assistant", content }, finish_reason: "stop" }], + usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 }, + }; +} + +function respondJson(response: ServerResponse, status: number, payload: unknown): void { + response.statusCode = status; + response.setHeader("content-type", "application/json"); + response.end(JSON.stringify(payload)); +} + +function generationSamples(count: number, offset: number): string { + return JSON.stringify({ + samples: Array.from({ length: count }, (_item, index) => ({ + ticket_id: `T-${offset + index}`, + content: `生成工单 ${offset + index}`, + })), + }); +} + +const TEACHER_DISTRIBUTION = JSON.stringify({ team: { billing: 0.9, technical: 0.1 } }); + +function generationBatchSize(body: ChatBody): number { + const user = body.messages?.[1]?.content ?? ""; + const match = /数组长度为 (\d+)/.exec(user); + return match ? Number(match[1]) : 0; +} + +describe("e2e: dataset generate API pipeline (loopback)", () => { + let pipeServer: Server; + let pipeOrigin = ""; + let pipeDir = ""; + let pipeWorkloadPath = ""; + const requests: ChatBody[] = []; + let stateCounter = 0; + let handler: (body: ChatBody, response: ServerResponse) => void = defaultHandler; + + function defaultHandler(body: ChatBody, response: ServerResponse): void { + if (body.enable_thinking === false) { + const count = generationBatchSize(body); + const offset = stateCounter; + stateCounter += count; + respondJson(response, 200, chatResponse(generationSamples(count, offset))); + } else { + respondJson(response, 200, chatResponse(TEACHER_DISTRIBUTION)); + } + } + + function runPipeline(args: string[]) { + return runCommandInProcess(DATASET_ROUTES, ["dataset", "generate", ...args], { + DASHSCOPE_API_KEY: "offline-test-only", + DASHSCOPE_BASE_URL: pipeOrigin, + BAILIAN_WORKSPACE_ID: "", + NODE_OPTIONS: "", + HTTP_PROXY: "", + HTTPS_PROXY: "", + ALL_PROXY: "", + NO_PROXY: "", + http_proxy: "", + https_proxy: "", + all_proxy: "", + no_proxy: "", + NODE_USE_ENV_PROXY: "", + }); + } + + beforeAll(async () => { + pipeDir = mkdtempSync(join(tmpdir(), "bl-dataset-pipeline-e2e-")); + pipeWorkloadPath = join(pipeDir, "workload.json"); + writeFileSync(pipeWorkloadPath, JSON.stringify(PIPELINE_WORKLOAD)); + pipeServer = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + let body: ChatBody = {}; + try { + body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as ChatBody; + } catch { + // 保留空 body,交由 handler 处理。 + } + requests.push(body); + handler(body, response); + }); + }); + await new Promise((resolve, reject) => { + pipeServer.once("error", reject); + pipeServer.listen(0, "127.0.0.1", resolve); + }); + const address = pipeServer.address(); + if (!address || typeof address === "string") throw new Error("Expected a local TCP server."); + pipeOrigin = `http://127.0.0.1:${address.port}`; + }); + + beforeEach(() => { + requests.length = 0; + stateCounter = 0; + handler = defaultHandler; + }); + + afterAll(async () => { + pipeServer.closeAllConnections(); + await new Promise((resolve) => pipeServer.close(() => resolve())); + rmSync(pipeDir, { recursive: true, force: true }); + }); + + test("generate 完整管线:生成 + 标注 + 切分 + manifest 用量", async () => { + const outDir = join(pipeDir, "out-full"); + const { stdout, stderr, exitCode } = await runPipeline([ + "--workload", + pipeWorkloadPath, + "--samples", + "10", + "--batch", + "5", + "--concurrency", + "4", + "--out-dir", + outDir, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson(stdout); + expect(data.mode).toBe("generate"); + expect(data.records).toEqual({ train: 9, development: 1 }); + expect(data.usage?.calls).toBe(12); + const generationCalls = requests.filter((call) => call.enable_thinking === false); + const teacherCalls = requests.filter((call) => call.enable_thinking === true); + expect(generationCalls).toHaveLength(2); + expect(teacherCalls).toHaveLength(10); + for (const call of generationCalls) { + expect(call.temperature).toBe(1.0); + expect(call.enable_search).toBe(false); + } + for (const call of teacherCalls) { + expect(call.temperature).toBe(0.2); + expect(call.enable_search).toBe(false); + } + const statesPath = data.files.raw.replace("labeled", "states"); + expect(readFileSync(statesPath, "utf8").trim().split("\n")).toHaveLength(10); + const manifest = JSON.parse(readFileSync(data.files.manifest, "utf8")) as Record< + string, + unknown + >; + expect(manifest.usage).toEqual({ calls: 12, prompt_tokens: 120, completion_tokens: 60 }); + expect((manifest.generator as Record).model).toBe("qwen3.8-max"); + expect(data.generator_teacher_agreement).toEqual({ team: 1 }); + // technical 硬标签占比 0,应透出 <5% 均衡警告。 + expect(stderr).toMatch(/5%/); + }); + + test("generate --states-only 生成后停止,不产生标注调用", async () => { + const outDir = join(pipeDir, "out-states-only"); + const { stdout, stderr, exitCode } = await runPipeline([ + "--workload", + pipeWorkloadPath, + "--samples", + "5", + "--states-only", + "--out-dir", + outDir, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + states_only: boolean; + counts: { states: number }; + files: { states: string }; + usage: { calls: number }; + }>(stdout); + expect(data.states_only).toBe(true); + expect(data.counts.states).toBe(5); + expect(data.usage.calls).toBe(1); + expect(requests.filter((call) => call.enable_thinking === true)).toHaveLength(0); + expect(readFileSync(data.files.states, "utf8").trim().split("\n")).toHaveLength(5); + expect(existsSync(join(outDir, "tickets.train.jsonl"))).toBe(false); + }); + + test("generate --from-states + --resume-raw 跳过已标注 state 续跑", async () => { + const statesFile = join(pipeDir, "states-10.jsonl"); + writeFileSync( + statesFile, + Array.from({ length: 10 }, (_line, index) => + JSON.stringify({ + state: { ticket_id: `T-${index}`, content: `工单正文 ${index}` }, + plan: { difficulty: "clean", team: "billing", index }, + }), + ).join("\n"), + ); + const resumeFile = join(pipeDir, "resume-raw.jsonl"); + writeFileSync( + resumeFile, + Array.from({ length: 4 }, (_line, index) => rawRow(index)).join("\n"), + ); + const outDir = join(pipeDir, "out-resume"); + const { stdout, stderr, exitCode } = await runPipeline([ + "--workload", + pipeWorkloadPath, + "--from-states", + statesFile, + "--resume-raw", + resumeFile, + "--out-dir", + outDir, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(requests).toHaveLength(6); + expect(requests.every((call) => call.enable_thinking === true)).toBe(true); + const data = parseStdoutJson(stdout); + expect(data.mode).toBe("from_states"); + expect(data.records).toEqual({ train: 9, development: 1 }); + expect(data.files.raw).toBe(resumeFile); + // 历史 4 条 + 新标注 6 条全部保留在同一 raw 文件。 + expect(readFileSync(resumeFile, "utf8").trim().split("\n")).toHaveLength(10); + }); + + test("generate 坏批(条数不符)跳过,其余批次照常完成", async () => { + let generationSeen = 0; + handler = (body, response) => { + if (body.enable_thinking === false) { + generationSeen += 1; + if (generationSeen === 1) { + const offset = stateCounter; + stateCounter += 3; + respondJson(response, 200, chatResponse(generationSamples(3, offset))); + return; + } + } + defaultHandler(body, response); + }; + const outDir = join(pipeDir, "out-bad-batch"); + const { stdout, stderr, exitCode } = await runPipeline([ + "--workload", + pipeWorkloadPath, + "--samples", + "15", + "--batch", + "5", + "--concurrency", + "2", + "--out-dir", + outDir, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/跳过|skipped/i); + const data = parseStdoutJson(stdout); + expect(data.records).toEqual({ train: 9, development: 1 }); + expect(data.usage?.calls).toBe(13); + const statesPath = data.files.raw.replace("labeled", "states"); + expect(readFileSync(statesPath, "utf8").trim().split("\n")).toHaveLength(10); + }); + + test("generate 服务端 4xx 原样透传且不重试", async () => { + handler = (_body, response) => { + respondJson(response, 400, { message: "Invalid API key provided" }); + }; + const { stderr, exitCode } = await runPipeline([ + "--workload", + pipeWorkloadPath, + "--samples", + "5", + "--out-dir", + join(pipeDir, "out-4xx"), + ]); + expect(exitCode).toBe(1); + expect(stderr).toContain("Invalid API key provided"); + expect(requests).toHaveLength(1); + }); + + test("generate 429 退避重试后成功", async () => { + let seen = 0; + handler = (body, response) => { + seen += 1; + if (seen === 1) { + respondJson(response, 429, { message: "throttled" }); + return; + } + defaultHandler(body, response); + }; + const outDir = join(pipeDir, "out-429"); + const { stdout, stderr, exitCode } = await runPipeline([ + "--workload", + pipeWorkloadPath, + "--samples", + "10", + "--batch", + "5", + "--concurrency", + "1", + "--out-dir", + outDir, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + // 1 次 429 + 2 次生成 + 10 次标注;usage 只计成功调用。 + expect(requests).toHaveLength(13); + const data = parseStdoutJson(stdout); + expect(data.usage?.calls).toBe(12); + expect(data.records).toEqual({ train: 9, development: 1 }); + }, 20000); + + test("generate teacher 分布非法时整行跳过,无可用记录以非零码退出", async () => { + handler = (body, response) => { + if (body.enable_thinking === false) { + defaultHandler(body, response); + return; + } + respondJson( + response, + 200, + chatResponse(JSON.stringify({ team: { billing: 2, technical: 0.1 } })), + ); + }; + const { stderr, exitCode } = await runPipeline([ + "--workload", + pipeWorkloadPath, + "--samples", + "10", + "--out-dir", + join(pipeDir, "out-bad-label"), + ]); + expect(exitCode).toBe(1); + expect(stderr).toMatch(/没有可用记录|no usable records/i); + expect(stderr).toMatch(/跳过|skipped/i); + }); +}); diff --git a/packages/commands/tests/e2e/finetune.e2e.test.ts b/packages/commands/tests/e2e/finetune.e2e.test.ts index c4f950cd..b86ab8c4 100644 --- a/packages/commands/tests/e2e/finetune.e2e.test.ts +++ b/packages/commands/tests/e2e/finetune.e2e.test.ts @@ -1,5 +1,7 @@ import { afterAll, beforeAll, describe, expect, test } from "vite-plus/test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { createServer, type Server } from "node:http"; +import { tmpdir } from "node:os"; import { join } from "path"; import { isDashScopeE2EReady, @@ -13,8 +15,69 @@ import { FINETUNE_ROUTES } from "./topic-routes.ts"; let schemaServer: Server; let schemaOrigin = ""; +/** Query of the most recent schema request, for protocol assertions. */ +let lastSchemaQuery: URLSearchParams | null = null; -function parameterSchema(inputModel: string): Array> { +/** Vision-only dynamic-option base mirroring qwen3.6-plus-base-2026-04-02. */ +const DYNAMIC_OPTION_MODEL = "qwen3.6-plus-base-2026-04-02"; + +function parameterSchema( + inputModel: string, + hyperParametersRaw: string | null, +): Array> { + if (inputModel === DYNAMIC_OPTION_MODEL) { + // Mirror the platform: dynamic-option models return an empty schema unless + // hyper_parameters carries a legal option context (modality fixed vision). + let options: Record = {}; + try { + options = hyperParametersRaw ? JSON.parse(hyperParametersRaw) : {}; + } catch { + options = {}; + } + if (options.modality !== "vision") return []; + return [ + { + name: "batch_size", + type: "number", + data_range: ["8", "8192"], + step: 8, + editable: true, + defaultValue: "8", + }, + { name: "n_epochs", type: "number", data_range: ["1", "200"], step: 1, editable: true }, + { name: "learning_rate", type: "input", editable: true }, + { name: "modality", type: "select", support_values: ["vision"], editable: true }, + { + name: "reasoning_mode", + type: "select", + support_values: ["instruct", "thinking"], + editable: true, + }, + ]; + } + if (inputModel.startsWith("decision-model")) { + // Decision preview model: only the three documented knobs; batch_size + // defaults to 1 within [1, 1024], n_epochs to 2 within [1, 200]. + return [ + { + name: "batch_size", + type: "number", + data_range: ["1", "1024"], + step: 1, + editable: true, + defaultValue: "1", + }, + { + name: "n_epochs", + type: "number", + data_range: ["1", "200"], + step: 1, + editable: true, + defaultValue: "2", + }, + { name: "learning_rate", type: "input", editable: true }, + ]; + } const videoModel = inputModel.startsWith("wan"); return [ { @@ -122,10 +185,14 @@ beforeAll(async () => { response.end('{"message":"unexpected path"}'); return; } + lastSchemaQuery = url.searchParams; response.end( JSON.stringify({ output: { - hyper_params: parameterSchema(url.searchParams.get("input_model") ?? ""), + hyper_params: parameterSchema( + url.searchParams.get("input_model") ?? "", + url.searchParams.get("hyper_parameters"), + ), }, }), ); @@ -325,6 +392,136 @@ describe("e2e: finetune (schema-gated)", () => { expect(exitCode, stdout + stderr).not.toBe(0); }); + test("finetune text create --help 展示训练选项 flag", async () => { + const { stderr, exitCode } = await runCommandHelp(FINETUNE_ROUTES, [ + "finetune", + "text", + "create", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--modality/); + expect(stderr).toMatch(/--reasoning-mode/); + }); + + test("finetune create --dry-run 动态选项模型透传 modality/reasoning_mode 并作为 schema 查询上下文", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + DYNAMIC_OPTION_MODEL, + "--datasets", + "file-aaa", + "--training-type", + "cpt", + "--modality", + "vision", + "--reasoning-mode", + "instruct", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + body: { + training_type: string; + hyper_parameters: { modality: string; reasoning_mode: string }; + }; + }>(stdout); + expect(data.body.training_type).toBe("cpt"); + expect(data.body.hyper_parameters.modality).toBe("vision"); + expect(data.body.hyper_parameters.reasoning_mode).toBe("instruct"); + // The schema query must carry the same options as hyper_parameters JSON. + expect(lastSchemaQuery).not.toBeNull(); + expect(lastSchemaQuery?.get("training_type")).toBe("cpt"); + expect(lastSchemaQuery?.get("hyper_parameters")).toBe( + JSON.stringify({ modality: "vision", reasoning_mode: "instruct" }), + ); + }); + + test("finetune create 动态选项模型缺 modality 时空 schema 闸门给出训练选项提示", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + DYNAMIC_OPTION_MODEL, + "--datasets", + "file-aaa", + "--training-type", + "cpt", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode).toBe(1); + expect(stderr).toMatch(/--modality/); + expect(stderr).toMatch(/dynamic train options|动态训练选项/i); + }); + + test("finetune create 动态选项模型拒绝 schema 外的 modality 值", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + DYNAMIC_OPTION_MODEL, + "--datasets", + "file-aaa", + "--training-type", + "cpt", + "--modality", + "text", + "--dry-run", + "--output", + "json", + ]); + // Empty schema (illegal context) hits the gate before override validation. + expect(exitCode).toBe(1); + expect(stderr).toMatch(/--modality/); + }); + + test("finetune create 无动态选项模型拒绝 --modality(schema unsupported)", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + "qwen3-8b", + "--datasets", + "file-aaa", + "--modality", + "vision", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/modality/); + expect(stderr).toMatch(/not supported|不支持/i); + }); + + test("finetune create --modality 拒绝枚举外的值 (2)", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "text", + "create", + "--base-model", + "qwen3-8b", + "--datasets", + "file-aaa", + "--modality", + "audio", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--modality/); + }); + test("finetune create --dry-run 把本地路径标记为 pending 且不上传数据", async () => { const localPath = join(e2eFixturesDir, ".dataset-valid.jsonl"); const { stdout, stderr, exitCode } = await runSchemaCommand([ @@ -539,6 +736,72 @@ describe("e2e: finetune (schema-gated)", () => { expect(stderr).toMatch(/--base-model|Missing required argument/i); }); + test("finetune train-options --help 展示必填项与 console 凭证域 flag", async () => { + const { stderr, exitCode } = await runSchemaCommand(["finetune", "train-options", "--help"]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--base-model/); + expect(stderr).toMatch(/--console-region/); + }); + + test("finetune train-options --dry-run 离线预览接口与映射后的训练类型", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "train-options", + "--base-model", + DYNAMIC_OPTION_MODEL, + "--training-type", + "sft-lora", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + action: string; + api: string; + input: { models: string[]; trainingType: string }; + }>(stdout); + expect(data.action).toBe("finetune.train-options"); + expect(data.api).toContain("model-train-options"); + expect(data.input.models).toEqual([DYNAMIC_OPTION_MODEL]); + expect(data.input.trainingType).toBe("efficient_sft"); + }); + + test("finetune train-options 不传 --training-type 时默认 sft", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "train-options", + "--base-model", + DYNAMIC_OPTION_MODEL, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ input: { trainingType: string } }>(stdout); + expect(data.input.trainingType).toBe("sft"); + }); + + test("finetune train-options 非法训练类型退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "train-options", + "--base-model", + "qwen3-8b", + "--training-type", + "nope", + "--dry-run", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--training-type|nope/); + }); + + test("finetune train-options 缺少 --base-model 时退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSchemaCommand(["finetune", "train-options", "--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. @@ -775,6 +1038,405 @@ describe("e2e: finetune (schema-gated)", () => { }); }); +describe("e2e: finetune decision create (offline)", () => { + const decisionModel = "decision-model-preview-2026-09-24"; + let fixtureDir = ""; + let train3 = ""; + let train10 = ""; + let val10 = ""; + let val10Drift = ""; + let badLabel = ""; + let fakeZip = ""; + + function decisionRecord(overrides?: { instructions?: string; label?: string }): string { + return JSON.stringify({ + state: "Customer complains the invoice title is wrong.", + questions: { + team: { + type: "choice", + instructions: overrides?.instructions ?? "Which team should handle this?", + criteria: { billing: "Payment and billing issues", technical: "Product fault issues" }, + label: overrides?.label ?? "billing", + }, + }, + }); + } + + function decisionLines(count: number, overrides?: { instructions?: string }): string[] { + return Array.from({ length: count }, () => decisionRecord(overrides)); + } + + beforeAll(() => { + fixtureDir = mkdtempSync(join(tmpdir(), "bl-finetune-decision-e2e-")); + train3 = join(fixtureDir, "train-3.jsonl"); + train10 = join(fixtureDir, "train-10.jsonl"); + val10 = join(fixtureDir, "val-10.jsonl"); + val10Drift = join(fixtureDir, "val-10-drift.jsonl"); + badLabel = join(fixtureDir, "bad-label.jsonl"); + fakeZip = join(fixtureDir, "data.zip"); + writeFileSync(train3, decisionLines(3).join("\n")); + writeFileSync(train10, decisionLines(10).join("\n")); + writeFileSync(val10, decisionLines(10).join("\n")); + writeFileSync( + val10Drift, + decisionLines(10, { instructions: "A different wording?" }).join("\n"), + ); + writeFileSync(badLabel, decisionRecord({ label: "sales" })); + writeFileSync(fakeZip, "not-a-real-zip"); + }); + + afterAll(() => rmSync(fixtureDir, { recursive: true, force: true })); + + test("decision create --help 展示三个超参且不暴露文本专属 flag", async () => { + const { stderr, exitCode } = await runCommandHelp(FINETUNE_ROUTES, [ + "finetune", + "decision", + "create", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--base-model/); + expect(stderr).toMatch(/--datasets/); + expect(stderr).toMatch(/--n-epochs/); + expect(stderr).toMatch(/--batch-size/); + expect(stderr).toMatch(/--learning-rate/); + expect(stderr).not.toMatch(/--training-type|--max-length|--lora-rank|--split/); + }); + + test("decision create 缺少 --datasets 时退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--quiet", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--datasets|Missing required/i); + }); + + test("decision create 缺少 --base-model 时退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--datasets", + "file-aaa", + "--quiet", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--base-model|Missing required/i); + }); + + test("decision create --suffix 超过 8 字符时退出为用法错误 (2)", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + "file-aaa", + "--suffix", + "waytoolong", + "--dry-run", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/suffix/i); + }); + + test("decision create --dry-run 构造 efficient_sft 默认请求体", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + "file-aaa,file-bbb", + "--validations", + "file-ccc", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + action: string; + body: { + model: string; + training_file_ids: string[]; + validation_file_ids: string[]; + training_type: string; + hyper_parameters: Record; + }; + }>(stdout); + expect(data.action).toBe("finetune.create"); + expect(data.body.model).toBe(decisionModel); + 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"); + // The API requires hyper_parameters in the body; omitted knobs are sent + // with the documented defaults. + expect(data.body.hyper_parameters).toEqual({ + n_epochs: 2, + batch_size: 1, + learning_rate: "2e-5", + }); + }); + + test("decision create --dry-run 仅透传三个超参与命名 flag", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + "file-aaa", + "--n-epochs", + "3", + "--batch-size", + "4", + "--learning-rate", + "2e-5", + "--job-name", + "decision-job", + "--model-name", + "decision-model", + "--suffix", + "mytune", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + body: { + job_name: string; + model_name: string; + finetuned_output_suffix: string; + hyper_parameters: Record; + }; + }>(stdout); + expect(data.body.job_name).toBe("decision-job"); + expect(data.body.model_name).toBe("decision-model"); + expect(data.body.finetuned_output_suffix).toBe("mytune"); + expect(data.body.hyper_parameters).toEqual({ + n_epochs: 3, + batch_size: 4, + learning_rate: "2e-5", + }); + }); + + test("decision create --dry-run 本地路径标记 pending 且不校验不上传", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + train3, + "--validations", + val10, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + body: { training_file_ids: string[]; validation_file_ids: string[] }; + pending_uploads: { field: string; path: string }[]; + }>(stdout); + expect(data.body.training_file_ids).toEqual([train3]); + expect(data.body.validation_file_ids).toEqual([val10]); + expect(data.pending_uploads.map((pending) => pending.field).sort()).toEqual([ + "datasets", + "validations", + ]); + }); + + test.each([ + ["--batch-size", "2000"], + ["--n-epochs", "0"], + ])("decision create 按平台参数 schema 拒绝非法 %s=%s", async (flagName, invalidValue) => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + "file-aaa", + flagName, + invalidValue, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/batch_size|n_epochs/); + }); + + test("decision create 本地数据校验失败时不上传", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + badLabel, + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).not.toBe(0); + const combined = `${stdout}\n${stderr}`; + expect(combined).toMatch(/DECISION_INVALID_CHOICE_LABEL/); + expect(combined).not.toMatch(/Uploaded .* → file-/); + }); + + test("decision create 拒绝非 .jsonl 数据文件", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + fakeZip, + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).not.toBe(0); + expect(`${stdout}\n${stderr}`).toMatch(/DECISION_UNSUPPORTED_FORMAT/); + }); + + test("decision create 仅训练集时样本数 < batch_size×10 提交前失败", async () => { + // Default batch_size=1 → training-only minimum is 10; 3 records fail. + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + train3, + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).not.toBe(0); + const combined = `${stdout}\n${stderr}`; + expect(combined).toMatch(/requires at least 10/); + expect(combined).toMatch(/INSUFFICIENT_DECISION_SAMPLES|样本数检查未通过/); + expect(combined).not.toMatch(/Uploaded .* → file-/); + }); + + test("decision create 显式 --batch-size 放大训练集门槛", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + train3, + "--batch-size", + "4", + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).not.toBe(0); + expect(`${stdout}\n${stderr}`).toMatch(/requires at least 40/); + }); + + test("decision create 有验证集时训练集门槛降为 batch_size 且验证集同检", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + train3, + "--validations", + val10, + "--batch-size", + "4", + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).not.toBe(0); + const combined = `${stdout}\n${stderr}`; + expect(combined).toMatch(/training dataset has 3 sample\(s\), requires at least 4/); + expect(combined).not.toMatch(/validation dataset has/); + expect(combined).not.toMatch(/Uploaded .* → file-/); + }); + + test("decision create 样本数达标时通过 gate(后续上传命中 mock 404)", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + train10, + "--output", + "json", + ]); + // The gate passes at the ≥10 boundary; the upload then hits the loopback + // 404 (no real network), proving the failure is no longer the sample gate. + expect(exitCode, stdout + stderr).not.toBe(0); + const combined = `${stdout}\n${stderr}`; + expect(combined).not.toMatch(/sample-count check failed|样本数检查未通过/); + expect(combined).toMatch(/unexpected path/); + }); + + test("decision create 训练/验证问题定义漂移发出 warning 后继续", async () => { + const { stdout, stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + train10, + "--validations", + val10Drift, + "--output", + "json", + ]); + // Warning only (not blocking): the flow proceeds to the upload, which + // fails on the loopback 404. + expect(exitCode, stdout + stderr).not.toBe(0); + expect(stderr).toMatch(/DECISION_QUESTION_DEFINITION_MISMATCH/); + expect(stderr).toMatch(/team/); + expect(stderr).toMatch(/unexpected path/); + }); + + test("decision create 训练/验证定义一致时不发漂移 warning", async () => { + const { stderr, exitCode } = await runSchemaCommand([ + "finetune", + "decision", + "create", + "--base-model", + decisionModel, + "--datasets", + train10, + "--validations", + val10, + "--output", + "json", + ]); + expect(exitCode).not.toBe(0); + expect(stderr).not.toMatch(/DECISION_QUESTION_DEFINITION_MISMATCH/); + expect(stderr).toMatch(/unexpected path/); + }); +}); + describe("e2e: finetune high-risk confirmation", () => { test("finetune delete --help 展示 runtime 注入的 --yes", async () => { const { stderr, exitCode } = await runSchemaCommand(["finetune", "delete", "--help"]); diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index a70c8e6e..271ac472 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -367,6 +367,8 @@ export const DATASET_ROUTES: E2eRouteExports = { "dataset get": "datasetGet", "dataset delete": "datasetDelete", "dataset validate": "datasetValidate", + "dataset split": "datasetSplit", + "dataset generate": "datasetGenerate", }; export const FINETUNE_ROUTES: E2eRouteExports = { @@ -374,6 +376,7 @@ export const FINETUNE_ROUTES: E2eRouteExports = { "finetune audio create": "finetuneAudioCreate", "finetune image create": "finetuneImageCreate", "finetune video create": "finetuneVideoCreate", + "finetune decision create": "finetuneDecisionCreate", "finetune list": "finetuneList", "finetune get": "finetuneGet", "finetune cancel": "finetuneCancel", @@ -384,6 +387,7 @@ export const FINETUNE_ROUTES: E2eRouteExports = { "finetune watch": "finetuneWatch", "finetune capability": "finetuneCapability", "finetune params": "finetuneParams", + "finetune train-options": "finetuneTrainOptions", "finetune metrics": "finetuneMetrics", "finetune compress templates": "finetuneCompressTemplates", "finetune compress create": "finetuneCompressCreate", diff --git a/packages/commands/tests/output/finetune-train-options.test.ts b/packages/commands/tests/output/finetune-train-options.test.ts new file mode 100644 index 00000000..c6a5e8ed --- /dev/null +++ b/packages/commands/tests/output/finetune-train-options.test.ts @@ -0,0 +1,324 @@ +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +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 finetuneParams from "../../src/commands/finetune/params.ts"; +import finetuneTrainOptions from "../../src/commands/finetune/train-options.ts"; +import { finetuneTextCreate } from "../../src/commands/finetune/create.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" }], +}; + +let isolated: ReturnType; +let schemaQueries: URLSearchParams[]; +let consoleApis: string[]; +let consoleFailure: Error | undefined; + +beforeEach(() => { + isolated = enterIsolatedHome(); + schemaQueries = []; + consoleApis = []; + 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 hyper-parameter schema GET. + if (url.pathname === "/api/v1/fine-tunes/fine-tunes-params") { + schemaQueries.push(url.searchParams); + return Response.json({ + output: { + hyper_params: [ + { + name: "batch_size", + type: "int", + recommend_value: "32", + range: [1, 512], + step: 1, + editable: true, + }, + { name: "modality", type: "string", support_values: ["vision"], editable: true }, + { + name: "reasoning_mode", + type: "string", + support_values: ["instruct", "thinking"], + editable: true, + }, + ], + }, + }); + } + 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, + options: { dryRun?: boolean; withConsole?: boolean } = {}, +) { + let stdout = ""; + let stderr = ""; + const language = "en-US"; + const settings = buildSettings({ + flags: { output: "json", dryRun: options.dryRun, ...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, + }, + ...(options.withConsole === false + ? {} + : { + 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 }; +} + +function datasetPath(): string { + const dir = mkdtempSync(join(tmpdir(), "bl-train-options-")); + const path = join(dir, "train.jsonl"); + writeFileSync( + path, + `${JSON.stringify({ + messages: [ + { role: "user", content: "问" }, + { role: "assistant", content: "答" }, + ], + })}\n`, + ); + return path; +} + +test("params completes omitted train options from the model defaults", async () => { + const { stdout, exitCode } = await invoke(finetuneParams, { baseModel: DYNAMIC_MODEL }); + expect(exitCode).toBe(0); + expect(consoleApis).toEqual([MODEL_TRAIN_OPTIONS_API]); + expect(schemaQueries).toHaveLength(1); + expect(schemaQueries[0].get("hyper_parameters")).toBe( + JSON.stringify({ modality: "vision", reasoning_mode: "instruct" }), + ); + const parsed = JSON.parse(stdout) as { precheck: { performed: boolean } }; + expect(parsed.precheck.performed).toBe(true); +}); + +test("params rejects an unsupported train-option value before the schema query", async () => { + const { stderr, exitCode } = await invoke(finetuneParams, { + baseModel: DYNAMIC_MODEL, + modality: "text", + }); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/Unsupported value|不受支持/); + expect(schemaQueries).toHaveLength(0); +}); + +test("params rejects a combination outside supportedCombinations", async () => { + const { stderr, exitCode } = await invoke(finetuneParams, { + baseModel: DYNAMIC_MODEL, + reasoningMode: "thinking", + }); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/Invalid train-options combination|组合不合法/); + expect(stderr).toMatch(/modality=vision\+reasoning_mode=instruct/); + expect(schemaQueries).toHaveLength(0); +}); + +test("params rejects train-option flags on a model without dynamic options", async () => { + const { stderr, exitCode } = await invoke(finetuneParams, { + baseModel: "qwen3-8b", + modality: "vision", + }); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/no dynamic train options|未配置动态训练选项/); + expect(schemaQueries).toHaveLength(0); +}); + +test("params 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(finetuneParams, { + baseModel: DYNAMIC_MODEL, + modality: "vision", + reasoningMode: "instruct", + }); + expect(exitCode).toBe(0); + expect(stderr).toMatch(/finetune\.train_options_precheck_skipped/); + expect(schemaQueries[0].get("hyper_parameters")).toBe( + JSON.stringify({ modality: "vision", reasoning_mode: "instruct" }), + ); + const parsed = JSON.parse(stdout) as { precheck: { performed: boolean; reason: string } }; + expect(parsed.precheck).toEqual({ performed: false, reason: "console-unavailable" }); +}); + +test("create dry-run completes defaults so dynamic-option models work without flags", async () => { + const { stdout, exitCode } = await invoke( + finetuneTextCreate, + { baseModel: DYNAMIC_MODEL, datasets: datasetPath(), trainingType: "cpt" }, + { dryRun: true }, + ); + expect(exitCode).toBe(0); + const parsed = JSON.parse(stdout) as { + body: { hyper_parameters: Record }; + }; + expect(parsed.body.hyper_parameters.modality).toBe("vision"); + expect(parsed.body.hyper_parameters.reasoning_mode).toBe("instruct"); + expect(schemaQueries[0].get("hyper_parameters")).toBe( + JSON.stringify({ modality: "vision", reasoning_mode: "instruct" }), + ); +}); + +test("create rejects an invalid combination before the schema query", async () => { + const { stderr, exitCode } = await invoke( + finetuneTextCreate, + { + baseModel: DYNAMIC_MODEL, + datasets: datasetPath(), + trainingType: "cpt", + reasoningMode: "thinking", + }, + { dryRun: true }, + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/Invalid train-options combination|组合不合法/); + expect(schemaQueries).toHaveLength(0); +}); + +test("create degrades silently to the hyper-parameter channel without a console session", async () => { + const { stdout, exitCode } = await invoke( + finetuneTextCreate, + { + baseModel: DYNAMIC_MODEL, + datasets: datasetPath(), + trainingType: "cpt", + modality: "vision", + reasoningMode: "instruct", + }, + { dryRun: true, withConsole: false }, + ); + expect(exitCode).toBe(0); + expect(consoleApis).toHaveLength(0); + const parsed = JSON.parse(stdout) as { + body: { hyper_parameters: Record }; + }; + expect(parsed.body.hyper_parameters.modality).toBe("vision"); +}); + +test("train-options command returns the console configuration verbatim", async () => { + const { stdout, exitCode } = await invoke(finetuneTrainOptions, { + baseModel: DYNAMIC_MODEL, + trainingType: "cpt", + }); + expect(exitCode).toBe(0); + expect(consoleApis).toEqual([MODEL_TRAIN_OPTIONS_API]); + const parsed = JSON.parse(stdout) as { + model: string; + training_type: string; + training_options: { defaults: Record; supportedCombinations: unknown[] }; + }; + expect(parsed.model).toBe(DYNAMIC_MODEL); + expect(parsed.training_type).toBe("cpt"); + expect(parsed.training_options.defaults).toEqual({ + modality: "vision", + reasoning_mode: "instruct", + }); + expect(parsed.training_options.supportedCombinations).toHaveLength(1); +}); + +test("train-options command returns null for models without dynamic options", async () => { + const { stdout, exitCode } = await invoke(finetuneTrainOptions, { baseModel: "qwen3-8b" }); + expect(exitCode).toBe(0); + const parsed = JSON.parse(stdout) as { training_options: unknown }; + expect(parsed.training_options).toBeNull(); +}); diff --git a/packages/core/package.json b/packages/core/package.json index 3953dba3..fa9b3cde 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-core", - "version": "2.11.1", + "version": "2.11.2", "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/dataset/index.ts b/packages/core/src/dataset/index.ts index 14c76b70..a7796d7e 100644 --- a/packages/core/src/dataset/index.ts +++ b/packages/core/src/dataset/index.ts @@ -1,6 +1,7 @@ export * from "./types.ts"; export * from "./api.ts"; export * from "./console.ts"; +export * from "./prepare/index.ts"; export { detectModality } from "./inspect.ts"; export { validateDataset, diff --git a/packages/core/src/dataset/prepare/index.ts b/packages/core/src/dataset/prepare/index.ts new file mode 100644 index 00000000..851ad98e --- /dev/null +++ b/packages/core/src/dataset/prepare/index.ts @@ -0,0 +1,8 @@ +export * from "./workload.ts"; +export * from "./rng.ts"; +export * from "./plan.ts"; +export * from "./prompt.ts"; +export * from "./parse.ts"; +export * from "./label.ts"; +export * from "./split.ts"; +export * from "./report.ts"; diff --git a/packages/core/src/dataset/prepare/label.ts b/packages/core/src/dataset/prepare/label.ts new file mode 100644 index 00000000..c0d87270 --- /dev/null +++ b/packages/core/src/dataset/prepare/label.ts @@ -0,0 +1,181 @@ +/** + * teacher 原始标注 → 训练记录的转换。 + * + * 硬标签 label 取概率最大的选项(noul 以 P(true)≥0.5 判真,score 取档位下标); + * 软标签 target 可选,由 teacher 分布经温度平滑得到(temp 越大越平滑、越保留不确定 + * 性);unknowable(信息不足)样本改用均匀分布 target,专门降低过度自信。转换前要求 + * teacher 分布键完整、概率有限且落在 [0,1]、总和为正,并归一化消除舍入漂移。 + */ +import { isDecisionObject } from "../../decision/questions.ts"; +import type { DecisionQuestion } from "../../decision/request.ts"; +import { extractJson } from "./parse.ts"; +import { questionOptions } from "./prompt.ts"; +import type { WorkloadConfig } from "./workload.ts"; + +export interface RawAnswer { + type?: string; + probabilities?: Record; + noul?: number; +} + +/** 标注阶段落盘的原始行:state + 画像 + teacher 概率(label/target 在转换时派生)。 */ +export interface RawLabelRow { + state: unknown; + plan?: Record; + answers?: Record; + missing?: string[]; +} + +export interface TrainingQuestion extends DecisionQuestion { + label: string | boolean | number; + target?: Record; +} + +export interface TrainingRecord { + state: unknown; + questions: Record; + _meta?: { source: string }; +} + +export interface ConversionResult { + record: TrainingRecord | null; + /** 生成意图(画像)与 teacher 硬标签是否一致,按问题 ID 统计。 */ + intentMatch: Record; +} + +/** 概率保留 4 位小数,消除浮点尾差。 */ +export function round4(value: number): number { + return Number(value.toFixed(4)); +} + +export interface TeacherParseResult { + answers: Record; + missing: string[]; +} + +/** + * 解析 teacher 回复为逐问题概率分布:键集校验 + 归一化 + round4;noul 额外存 + * P(true)。任一问题无效即记入 missing(调用方据此跳过整行),同步与离线共用。 + */ +export function parseTeacherRow( + content: string, + questions: Record, +): TeacherParseResult { + const parsed = extractJson(content); + const answers: Record = {}; + const missing: string[] = []; + for (const [questionId, spec] of Object.entries(questions)) { + try { + const keys = Object.keys(questionOptions(spec)); + const raw = isDecisionObject(parsed) ? parsed[questionId] : undefined; + const values = alignRow(raw, keys); + const answer: RawAnswer = { + type: spec.type, + probabilities: Object.fromEntries(keys.map((key, index) => [key, round4(values[index])])), + }; + if (spec.type === "noul") answer.noul = round4(values[1]); + answers[questionId] = answer; + } catch { + missing.push(questionId); + } + } + return { answers, missing }; +} + +/** 要求完整有效的 teacher 分布,再归一化消除舍入漂移;非法抛错(调用方跳过该记录)。 */ +export function alignRow(raw: unknown, answerKeys: string[]): number[] { + if (!isDecisionObject(raw)) { + throw new Error("teacher probability keys do not match the question"); + } + const rawKeys = Object.keys(raw); + if ( + rawKeys.length !== answerKeys.length || + !answerKeys.every((key) => Object.prototype.hasOwnProperty.call(raw, key)) + ) { + throw new Error("teacher probability keys do not match the question"); + } + const values = answerKeys.map((key) => { + const rawValue = raw[key]; + return typeof rawValue === "number" + ? rawValue + : typeof rawValue === "string" + ? Number(rawValue) + : NaN; + }); + if (values.some((value) => !Number.isFinite(value) || value < 0 || value > 1)) { + throw new Error("teacher probabilities must be finite and in [0, 1]"); + } + const total = values.reduce((sum, value) => sum + value, 0); + if (total <= 0) throw new Error("teacher probabilities sum to zero"); + return values.map((value) => value / total); +} + +/** 温度平滑:p^(1/temp) 后重归一;temp=1 保持原分布,越大越平滑。 */ +export function smooth(probs: Record, temp: number): Record { + const raised = Object.fromEntries( + Object.entries(probs).map(([key, value]) => [key, value ** (1 / temp)]), + ); + const total = Object.values(raised).reduce((sum, value) => sum + value, 0); + return total + ? Object.fromEntries(Object.entries(raised).map(([key, value]) => [key, value / total])) + : probs; +} + +function copyQuestionDefinition( + spec: DecisionQuestion, +): Pick { + const question: Pick = { + type: spec.type, + }; + if (spec.instructions !== undefined) question.instructions = spec.instructions; + if (spec.criteria !== undefined) question.criteria = spec.criteria; + return question; +} + +/** 一条原始行 → 一条训练记录(硬标签必有,软标签可选);无效行返回 null。 */ +export function toTrainingRecord( + row: RawLabelRow, + workload: WorkloadConfig, + targetTemp: number, + soft: boolean, +): ConversionResult { + if (row.missing && row.missing.length > 0) return { record: null, intentMatch: {} }; + const plan = row.plan ?? {}; + const unknowable = plan.difficulty === "unknowable"; + const record: TrainingRecord = { state: row.state, questions: {} }; + if (unknowable) record._meta = { source: "unknowable" }; + const intentMatch: Record = {}; + + for (const [questionId, spec] of Object.entries(workload.questions)) { + const definition = copyQuestionDefinition(spec); + let probs: Record; + let keys: string[]; + try { + const answer = row.answers?.[questionId]; + if (!answer) throw new Error("missing teacher answer"); + keys = Object.keys(questionOptions(spec)); + const raw = + spec.type === "noul" + ? { true: Number(answer.noul), false: 1 - Number(answer.noul) } + : answer.probabilities; + const values = alignRow(raw, keys); + probs = Object.fromEntries(keys.map((key, index) => [key, values[index]])); + } catch { + return { record: null, intentMatch: {} }; + } + const best = keys.reduce((bestKey, key) => (probs[key] > probs[bestKey] ? key : bestKey)); + const label = + spec.type === "noul" ? probs.true >= 0.5 : spec.type === "score" ? Number(best) : best; + const question: TrainingQuestion = { ...definition, label }; + if (unknowable) { + question.target = Object.fromEntries(keys.map((key) => [key, 1 / keys.length])); + } else if (soft) { + question.target = smooth(probs, targetTemp); + } + record.questions[questionId] = question; + if (Object.prototype.hasOwnProperty.call(plan, questionId)) { + intentMatch[questionId] = String(label) === String(plan[questionId]); + } + } + return { record, intentMatch }; +} diff --git a/packages/core/src/dataset/prepare/parse.ts b/packages/core/src/dataset/prepare/parse.ts new file mode 100644 index 00000000..656db005 --- /dev/null +++ b/packages/core/src/dataset/prepare/parse.ts @@ -0,0 +1,137 @@ +/** + * 数据准备用的 JSON 工具:规范化渲染与从模型回复中抽取 JSON。 + * + * teacher / 生成模型的回复可能带 markdown 代码块或前导说明文字,需要稳健地取出 + * 第一个 JSON 对象/数组;state 去重键则要求与书写顺序无关的规范化序列化。 + */ +import { isDecisionObject } from "../../decision/questions.ts"; +import type { GenerationPlan } from "./plan.ts"; + +/** 递归按对象键排序,使序列化与键书写顺序无关(对齐 Python json sort_keys=True)。 */ +function canonicalize(value: unknown): unknown { + if (Array.isArray(value)) return value.map(canonicalize); + if (isDecisionObject(value)) { + return Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => [key, canonicalize(value[key])]), + ); + } + return value; +} + +/** 字符串原样返回;其他值规范化(键排序)后 JSON 序列化。 */ +export function renderValue(value: unknown): string { + return typeof value === "string" ? value : JSON.stringify(canonicalize(value)); +} + +const FENCE_PATTERN = /```(?:json)?\s*([\s\S]*?)```/g; + +/** + * 从 start 处的 `[` / `{` 起扫描配对的闭括号(跳过字符串与转义),截取第一个完整 + * JSON 值解析;等价于 Python json.JSONDecoder().raw_decode 忽略尾部多余内容。 + */ +function rawDecode(text: string, start: number): unknown { + const opener = text[start]; + const closer = opener === "[" ? "]" : "}"; + let depth = 0; + let inString = false; + let escaped = false; + for (let index = start; index < text.length; index++) { + const character = text[index]; + if (inString) { + if (escaped) escaped = false; + else if (character === "\\") escaped = true; + else if (character === '"') inString = false; + continue; + } + if (character === '"') inString = true; + else if (character === opener) depth++; + else if (character === closer) { + depth--; + if (depth === 0) { + try { + return JSON.parse(text.slice(start, index + 1)); + } catch { + return undefined; + } + } + } + } + return undefined; +} + +/** 读取 JSON 对象/数组:先试整体与代码块,再扫描前导 prose 后的第一个 JSON 值。 */ +export function extractJson(text: string): unknown { + if (!text) return undefined; + const fenced = [...text.matchAll(FENCE_PATTERN)].map((match) => match[1]); + for (const candidate of [text.trim(), ...fenced]) { + try { + const value: unknown = JSON.parse(candidate); + if (isDecisionObject(value) || Array.isArray(value)) return value; + } catch { + // try next candidate + } + } + for (const match of text.matchAll(/[[{]/g)) { + const value = rawDecode(text, match.index ?? 0); + if (value !== undefined) return value; + } + return undefined; +} + +/** 接受包裹列表({"samples":[...]} 等)或裸数组;对象无数组值时回落为单元素。 */ +export function extractItems(content: string): unknown[] | undefined { + const parsed = extractJson(content); + if (isDecisionObject(parsed)) { + const found = Object.values(parsed).find((value) => Array.isArray(value)); + return found !== undefined ? (found as unknown[]) : [parsed]; + } + return Array.isArray(parsed) ? parsed : undefined; +} + +/** 生成阶段落盘的输入行:state + 可选画像(画像用于事后统计生成意图一致率)。 */ +export interface StateItem { + state: Record; + plan?: Record; +} + +export interface StateParseResult { + items: StateItem[]; + /** JSON 无效或条数与画像不符(整批跳过);个别字段缺失不算 invalid。 */ + invalid: boolean; +} + +/** + * 解析生成回复为 StateItem:条数须与画像一致,逐条要求 schema 字段非空; + * 缺字段的个别条目静默跳过。同步与离线共用。 + */ +export function parseStateItems( + content: string, + group: GenerationPlan[], + schemaFields: string[], +): StateParseResult { + const items = extractItems(content); + if (!items || items.length !== group.length) return { items: [], invalid: true }; + const fresh: StateItem[] = []; + for (let index = 0; index < group.length; index++) { + const item = items[index]; + if (!isDecisionObject(item)) continue; + const state: Record = {}; + let complete = true; + for (const field of schemaFields) { + const value = item[field]; + if ( + value === undefined || + value === null || + (typeof value === "string" && value.trim().length === 0) + ) { + complete = false; + break; + } + state[field] = value; + } + if (complete) fresh.push({ state, plan: group[index] }); + } + return { items: fresh, invalid: false }; +} diff --git a/packages/core/src/dataset/prepare/plan.ts b/packages/core/src/dataset/prepare/plan.ts new file mode 100644 index 00000000..55307787 --- /dev/null +++ b/packages/core/src/dataset/prepare/plan.ts @@ -0,0 +1,56 @@ +/** + * 生成画像规划:把 workload.axes 的笛卡尔积均衡地循环到 n 条普通样本,再追加 + * unknowable(信息不足)样本,最后整体洗牌。画像中与问题 ID 同名的字段表示期望 + * 答案,用于事后统计生成意图与 teacher 标注的一致率。 + */ +import { BailianError } from "../../errors/base.ts"; +import { ExitCode } from "../../errors/codes.ts"; +import { mulberry32, shuffleWithRandom } from "./rng.ts"; +import type { WorkloadConfig } from "./workload.ts"; + +export interface GenerationPlan { + difficulty: string; + index: number; + [axis: string]: unknown; +} + +/** axes 笛卡尔积;任一轴为空即报错(与脚本 build_plans 一致)。 */ +function axesGrid(axes: Record): Array> { + let grid: Array> = [{}]; + for (const [axisName, values] of Object.entries(axes)) { + if (!Array.isArray(values) || values.length === 0) { + throw new BailianError( + `each axis must contain at least one value (axis "${axisName}" is empty). / 每个 axis 至少要有一个取值(axis "${axisName}" 为空)。`, + ExitCode.USAGE, + ); + } + const next: Array> = []; + for (const combination of grid) { + for (const value of values) next.push({ ...combination, [axisName]: value }); + } + grid = next; + } + return grid; +} + +/** + * 构造 n 条普通画像 + unknowable 条信息不足画像。grid 与 plans 共用一个确定性 + * 随机源(对齐脚本单 rng 实例两次 shuffle 的语义);同 seed 在 CLI 内可复现。 + */ +export function buildPlans( + workload: WorkloadConfig, + count: number, + unknowable: number, + seed: number, +): GenerationPlan[] { + const random = mulberry32(seed); + const grid = shuffleWithRandom(axesGrid(workload.axes ?? {}), random); + const plans: GenerationPlan[] = []; + for (let index = 0; index < count; index++) { + plans.push({ difficulty: "clean", ...grid[index % grid.length], index }); + } + for (let offset = 0; offset < unknowable; offset++) { + plans.push({ difficulty: "unknowable", index: count + offset }); + } + return shuffleWithRandom(plans, random); +} diff --git a/packages/core/src/dataset/prepare/prompt.ts b/packages/core/src/dataset/prepare/prompt.ts new file mode 100644 index 00000000..6fb3bfeb --- /dev/null +++ b/packages/core/src/dataset/prepare/prompt.ts @@ -0,0 +1,170 @@ +/** + * 数据合成的提示词构造(teacher 标注 / 业务输入生成)。 + * + * 提示词正文沿用示例脚本:teacher 被要求对每个问题输出概率分布(和为 1),生成 + * 模型按 state_schema 与画像构造原始输入。这些是发给模型的 prompt 内容,不是 CLI + * 用户面文案。问题选项键的顺序(choice 按 criteria、score 按档位下标、noul 按 + * false/true)与训练记录 / 推理 API 保持一致。 + */ +import { + MAX_DECISION_CHOICE_OPTIONS, + MAX_DECISION_SCORE_LEVELS, + MIN_DECISION_SCORE_LEVELS, + isDecisionObject, +} from "../../decision/questions.ts"; +import type { DecisionQuestion } from "../../decision/request.ts"; +import type { ChatMessage } from "../../types/api.ts"; +import { renderValue } from "./parse.ts"; +import type { GenerationPlan } from "./plan.ts"; +import type { WorkloadConfig } from "./workload.ts"; + +export const TEACHER_SYSTEM_PROMPT = + "You are a precise, deterministic decision engine that answers structured " + + "questions about a given STATE. For every question you receive, you must produce a " + + "probability distribution over that question's candidate answer keys.\n\n" + + "Rules:\n" + + "1. Base every probability only on evidence in the STATE. Read it literally and carefully; " + + "extract exact facts (numbers, ids, names, dates, amounts) when asked.\n" + + "2. Each question is independent. Judge it on its own; do not let other questions bias it.\n" + + "3. Output a distribution per question whose probabilities sum to 1.0.\n" + + "4. Represent uncertainty faithfully: when the STATE clearly determines the answer, put >=0.9 on it; when " + + "evidence is genuinely ambiguous or conflicting, spread the mass honestly instead of " + + "guessing with false confidence. Distinguish what is stated from what is merely implied.\n" + + "5. For ordinal score levels, prefer adjacent levels when uncertain (do not jump from " + + "lowest to highest without strong evidence).\n" + + "6. When the instructions state an explicit policy, rule, or ONLY-if condition, apply it " + + "literally and exclusively: the answer is decided solely by whether the rule's stated " + + "conditions are present in the STATE. Do not introduce rules from other business domains. " + + "Use tone or wording only when relevant to the question and supplied business rules.\n" + + "7. When asked to select an exact value (id, amount, phone, date, name) from the STATE, " + + "copy it verbatim and prefer the candidate whose text matches the STATE exactly.\n" + + "8. Think privately and thoroughly first. Your final message must be ONLY a JSON object, " + + "with no prose, no markdown fences, no commentary."; + +const GENERATION_SYSTEM_PROMPT = + "你在按给定业务配置构造训练样本,只生成模型需要判断的原始输入。\n" + + "要求:\n" + + "1. 遵循业务场景、字段说明和业务规则,每条输入独立、自然,符合实际使用场景。\n" + + "2. 覆盖不同内容和表达,避免只替换编号或名称的重复样本。\n" + + "3. 用具体事实体现生成画像,不把答案、标签或分析写进输入。\n" + + "4. 只输出 JSON,不要 markdown 代码块,不要任何解释。"; + +const DEFAULT_DIFFICULTY_HINTS: Record = { + clean: "信息完整,判断依据明确。", + hard: "包含干扰信息或边界情况,但保留足够的判断依据。", + unknowable: "缺少作出判断所需的信息,不补充可推断答案的事实。", +}; + +/** 校验单个问题并返回有序答案键 → 描述;非法定义抛错(调用方捕获后跳过该记录)。 */ +export function questionOptions(spec: DecisionQuestion): Record { + const kind = spec.type; + const criteria = spec.criteria; + if (kind === "choice" && isDecisionObject(criteria)) { + const optionCount = Object.keys(criteria).length; + if (optionCount >= 1 && optionCount <= MAX_DECISION_CHOICE_OPTIONS) { + return criteria as Record; + } + } else if (kind === "score" && Array.isArray(criteria)) { + if ( + criteria.length >= MIN_DECISION_SCORE_LEVELS && + criteria.length <= MAX_DECISION_SCORE_LEVELS + ) { + return Object.fromEntries(criteria.map((level, index) => [String(index), String(level)])); + } + } else if (kind === "noul") { + if (criteria === undefined) return { false: "No", true: "Yes" }; + if ( + isDecisionObject(criteria) && + Object.keys(criteria).length === 2 && + "false" in criteria && + "true" in criteria + ) { + return { false: String(criteria.false), true: String(criteria.true) }; + } + } + throw new Error("expected choice (1..255 options), score (2..255 levels), or noul"); +} + +const QUESTION_HEADINGS: Record = { + choice: " candidate answer keys => description:", + score: " ordinal levels, lowest to highest (key = level position):", + noul: " candidate answer keys (assign one distribution over BOTH):", +}; + +/** + * 构造 teacher 标注消息:逐问题列出指令与候选键,要求只输出概率分布 JSON。 + * guidance 作为业务规则附在 system 提示词末尾(对齐脚本 label_states)。 + */ +export function buildTeacherMessages( + state: unknown, + questions: Record, + guidance: string[] = [], +): ChatMessage[] { + const blocks: string[] = []; + const skeleton: Record> = {}; + for (const [questionId, spec] of Object.entries(questions)) { + const kind = spec.type; + let questionText = renderValue(spec.instructions ?? ""); + let options = questionOptions(spec); + skeleton[questionId] = Object.fromEntries(Object.keys(options).map((key) => [key, 0])); + if (kind === "noul") { + if (spec.criteria !== undefined) { + questionText += `\nYes means: ${renderValue(options.true)}\nNo means: ${renderValue(options.false)}`; + } + options = { false: "the answer is No", true: "the answer is Yes" }; + } + const lines = [ + `QUESTION id="${questionId}" type=${kind}`, + ` instructions: ${questionText}`, + QUESTION_HEADINGS[kind], + ]; + for (const [key, value] of Object.entries(options)) { + let description = renderValue(value); + if (kind === "choice") description = value === null ? key : `${key}: ${description}`; + const label = kind === "noul" ? `"${key}"`.padEnd(7) : `"${key}"`; + lines.push(` ${label} => ${description}`); + } + blocks.push(lines.join("\n")); + } + const user = + `STATE:\n${renderValue(state)}\n\n` + + `Answer ALL ${Object.keys(questions).length} question(s) below about this STATE.\n\n` + + `${blocks.join("\n\n")}\n\n` + + "OUTPUT FORMAT — return ONLY this JSON object (keys exactly as shown, floats summing " + + "to 1.0 within each question):\n" + + JSON.stringify(skeleton); + const system = + TEACHER_SYSTEM_PROMPT + + (guidance.length > 0 ? `\n\nBusiness rules:\n${renderValue(guidance)}` : ""); + return [ + { role: "system", content: system }, + { role: "user", content: user }, + ]; +} + +/** 构造业务输入生成消息:按 state_schema 与画像批量生成原始输入(不含答案)。 */ +export function buildGenerationMessages( + workload: WorkloadConfig, + plans: GenerationPlan[], +): ChatMessage[] { + const schema = Object.entries(workload.state_schema ?? {}) + .map(([fieldName, requirement]) => ` "${fieldName}": ${requirement}`) + .join("\n"); + const hints = { ...DEFAULT_DIFFICULTY_HINTS, ...workload.difficulty_hints }; + const lines = plans.map((plan, index) => { + const profile = Object.fromEntries(Object.entries(plan).filter(([key]) => key !== "index")); + return ` [${index}] ${renderValue(profile)}\n ${hints[plan.difficulty] ?? ""}`; + }); + const user = + `业务场景:${workload.description ?? ""}\n\n` + + `需要判断的问题:${renderValue(workload.questions)}\n\n` + + `业务规则:${renderValue(workload.guidance ?? [])}\n\n` + + `每条输入是一个 JSON 对象,必须包含以下字段,字段名保持一致:\n${schema}\n\n` + + "画像中与问题 ID 同名的字段表示期望答案;score 使用从 0 开始的档位下标。\n" + + `按下面 ${plans.length} 个画像各写一条,顺序对应输出数组的下标:\n${lines.join("\n")}\n\n` + + `输出格式:{"samples": [...]},数组长度为 ${plans.length},元素为上述对象。`; + return [ + { role: "system", content: GENERATION_SYSTEM_PROMPT }, + { role: "user", content: user }, + ]; +} diff --git a/packages/core/src/dataset/prepare/report.ts b/packages/core/src/dataset/prepare/report.ts new file mode 100644 index 00000000..02408b8a --- /dev/null +++ b/packages/core/src/dataset/prepare/report.ts @@ -0,0 +1,106 @@ +/** + * 数据准备的质量与用量报告:标签均衡、生成意图与 teacher 标注一致率、manifest。 + * + * manifest 用 workload 文件的 SHA256 钉住“是哪一版问题定义产出了这批标签”——若它 + * 与线上 workload.json 不再匹配,说明数据与服务的问题定义已经漂移。token 预算检查 + * 依赖 Python transformers 分词器,CLI 无对应依赖,标记 skipped 并注明原因,不做 + * 臆造的 token 计数。 + */ +import type { TrainingRecord } from "./label.ts"; +import type { WorkloadConfig } from "./workload.ts"; + +/** 每个问题的硬标签分布(选项 → 计数)。 */ +export function balanceReport( + records: readonly TrainingRecord[], + workload: WorkloadConfig, +): Record> { + const counts: Record> = {}; + for (const [questionId, spec] of Object.entries(workload.questions)) { + const keys = + spec.type === "choice" + ? Object.keys((spec.criteria ?? {}) as Record) + : spec.type === "score" + ? Array.from({ length: (spec.criteria as unknown[]).length }, (_level, index) => + String(index), + ) + : ["false", "true"]; + counts[questionId] = Object.fromEntries(keys.map((key) => [key, 0])); + } + for (const record of records) { + for (const [questionId, question] of Object.entries(record.questions)) { + const key = String(question.label); + const bucket = counts[questionId] ?? (counts[questionId] = {}); + bucket[key] = (bucket[key] ?? 0) + 1; + } + } + return counts; +} + +export interface AgreementTally { + hit: number; + total: number; +} + +/** 生成意图与 teacher 硬标签的一致率(保留 4 位小数)。 */ +export function agreementRatio(agreement: Record): Record { + return Object.fromEntries( + Object.entries(agreement).map(([questionId, tally]) => [ + questionId, + tally.total > 0 ? Number((tally.hit / tally.total).toFixed(4)) : 0, + ]), + ); +} + +export interface UsageSummary { + calls: number; + prompt_tokens: number; + completion_tokens: number; +} + +export interface ManifestInput { + created: string; + mode: "generate" | "from_states" | "from_raw"; + workloadPath: string; + rawPath: string; + workloadSha256: string; + generator: { + model: string | null; + base_url: string | null; + seed: number; + target_temp: number; + soft_target: boolean; + }; + unknowableRecords: number; + rejectedRawRecords: number; + duplicateRawRecords: number; + records: { train: number; development: number }; + labelBalance: Record>; + agreement: Record; + wallSeconds: number; + usage: UsageSummary | null; +} + +/** 组装 manifest(结构对齐示例脚本;token 检查标记 skipped)。 */ +export function buildManifest(input: ManifestInput): Record { + return { + created: input.created, + mode: input.mode, + workload: input.workloadPath, + raw: input.rawPath, + workload_sha256: input.workloadSha256, + generator: input.generator, + unknowable_records: input.unknowableRecords, + rejected_raw_records: input.rejectedRawRecords, + duplicate_raw_records: input.duplicateRawRecords, + state_token_check: { + status: "skipped", + reason: + "State token-budget check needs the Python transformers tokenizer, which the CLI does not bundle.", + }, + records: input.records, + label_balance: input.labelBalance, + generator_teacher_agreement: input.agreement, + wall_s: input.wallSeconds, + usage: input.usage, + }; +} diff --git a/packages/core/src/dataset/prepare/rng.ts b/packages/core/src/dataset/prepare/rng.ts new file mode 100644 index 00000000..3ec50037 --- /dev/null +++ b/packages/core/src/dataset/prepare/rng.ts @@ -0,0 +1,38 @@ +/** + * 确定性伪随机数与洗牌。 + * + * 数据准备(画像规划、train/development 切分)需要可复现的随机顺序:同一 seed + * 在 CLI 内产出一致结果。这里用 mulberry32 + Fisher–Yates,刻意不依赖运行时随机源。 + * + * 注意:PRNG 与示例脚本的 Python `random.Random` 不同,洗牌顺序不逐位一致; + * 同 seed 仅在 CLI 内确定,不承诺与脚本跨工具复现同一 split。 + */ + +/** mulberry32:以 32 位整数为状态的小型确定性 PRNG,返回 [0, 1) 浮点。 */ +export function mulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let mixed = state; + mixed = Math.imul(mixed ^ (mixed >>> 15), mixed | 1); + mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61); + return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296; + }; +} + +/** 用给定随机源做 Fisher–Yates 洗牌,返回新数组,不修改入参。 */ +export function shuffleWithRandom(items: readonly T[], random: () => number): T[] { + const result = [...items]; + for (let index = result.length - 1; index > 0; index--) { + const swapIndex = Math.floor(random() * (index + 1)); + const temporary = result[index]; + result[index] = result[swapIndex]; + result[swapIndex] = temporary; + } + return result; +} + +/** 以 seed 构造确定性随机源并洗牌。 */ +export function seededShuffle(items: readonly T[], seed: number): T[] { + return shuffleWithRandom(items, mulberry32(seed)); +} diff --git a/packages/core/src/dataset/prepare/split.ts b/packages/core/src/dataset/prepare/split.ts new file mode 100644 index 00000000..1f409521 --- /dev/null +++ b/packages/core/src/dataset/prepare/split.ts @@ -0,0 +1,63 @@ +/** + * 已标注 JSONL 的去重与 train/development 切分(纯本地,不调用 API)。 + * + * 去重键忽略 workload.id_fields 里的记录编号,只保留决策相关字段,规范化序列化后 + * 比对——同一输入不应在训练集与评估集里重复出现。切分用确定性种子洗牌后按比例取 + * development,其余为 train。 + */ +import { isDecisionObject } from "../../decision/questions.ts"; +import { renderValue } from "./parse.ts"; +import { seededShuffle } from "./rng.ts"; + +/** 切出两份非空文件所需的最少记录数(与脚本一致)。 */ +export const MIN_SPLIT_RECORDS = 7; + +/** 默认 development 占比(脚本固定 0.15)。 */ +export const DEFAULT_DEV_RATIO = 0.15; + +/** 忽略记录编号字段后的规范化 state 键,用于跨记录去重。 */ +export function stateKey(state: unknown, idFields: string[]): string { + let normalized = state; + if (isDecisionObject(state)) { + normalized = Object.fromEntries( + Object.entries(state).filter(([fieldName]) => !idFields.includes(fieldName)), + ); + } + return renderValue(normalized); +} + +export interface SplitParts { + train: T[]; + development: T[]; +} + +/** 种子洗牌后按 devRatio 取整切分:前 devCount 条为 development,其余为 train。 */ +export function splitRecords( + records: readonly T[], + seed: number, + devRatio: number = DEFAULT_DEV_RATIO, +): SplitParts { + const shuffled = seededShuffle(records, seed); + const devCount = Math.floor(shuffled.length * devRatio); + return { development: shuffled.slice(0, devCount), train: shuffled.slice(devCount) }; +} + +/** 按 state 去重,保留首次出现;返回去重结果与重复计数(generate 转换阶段用)。 */ +export function dedupByState( + records: readonly T[], + idFields: string[], +): { unique: T[]; duplicateCount: number } { + const seen = new Set(); + const unique: T[] = []; + let duplicateCount = 0; + for (const record of records) { + const key = stateKey(record.state, idFields); + if (seen.has(key)) { + duplicateCount++; + continue; + } + seen.add(key); + unique.push(record); + } + return { unique, duplicateCount }; +} diff --git a/packages/core/src/dataset/prepare/workload.ts b/packages/core/src/dataset/prepare/workload.ts new file mode 100644 index 00000000..2b501c5e --- /dev/null +++ b/packages/core/src/dataset/prepare/workload.ts @@ -0,0 +1,132 @@ +/** + * 决策数据合成的工作负载配置(workload.json)。 + * + * 换业务只需改这份配置:`description` 写业务与判断目标,`state_schema` 写输入字段 + * 及内容要求,`questions` 定义问题与答案选项,`guidance` 补充判断规则;`axes` / + * `difficulty_hints` 用于均衡生成画像,可省略。问题定义的结构规则与推理 / 训练校验 + * 共用 `decision/questions.ts`,保证合成数据与线上请求的问题定义一致。 + */ +import { BailianError } from "../../errors/base.ts"; +import { ExitCode } from "../../errors/codes.ts"; +import { inspectDecisionQuestions, isDecisionObject } from "../../decision/questions.ts"; +import type { DecisionQuestion } from "../../decision/request.ts"; +import { readTextFromPathOrStdin } from "../../utils/fs.ts"; + +export interface WorkloadConfig { + name?: string; + language?: string; + description?: string; + state_schema?: Record; + id_fields?: string[]; + questions: Record; + guidance?: string[]; + axes?: Record; + difficulty_hints?: Record; +} + +/** 记录编号字段(去重时忽略);未配置时沿用示例默认的 ticket_id。 */ +export function workloadIdFields(workload: WorkloadConfig): string[] { + return workload.id_fields ?? ["ticket_id"]; +} + +function usageError(english: string, chinese: string): BailianError { + return new BailianError(`${english} / ${chinese}`, ExitCode.USAGE); +} + +/** 结构解析:必须是对象且含非空问题表;其余字段按类型收取,非法即 USAGE。 */ +export function parseWorkload(parsed: unknown): WorkloadConfig { + if (!isDecisionObject(parsed)) { + throw usageError("workload must be a JSON object.", "workload 必须是 JSON 对象。"); + } + if (!isDecisionObject(parsed.questions) || Object.keys(parsed.questions).length === 0) { + throw usageError( + 'workload must define a non-empty "questions" object.', + 'workload 必须定义非空的 "questions" 对象。', + ); + } + const workload: WorkloadConfig = { + questions: parsed.questions as Record, + }; + if (typeof parsed.name === "string") workload.name = parsed.name; + if (typeof parsed.language === "string") workload.language = parsed.language; + if (typeof parsed.description === "string") workload.description = parsed.description; + if (isDecisionObject(parsed.state_schema)) { + workload.state_schema = parsed.state_schema as Record; + } + if (Array.isArray(parsed.id_fields)) { + workload.id_fields = parsed.id_fields.filter( + (field): field is string => typeof field === "string", + ); + } + if (Array.isArray(parsed.guidance)) { + workload.guidance = parsed.guidance.filter((rule): rule is string => typeof rule === "string"); + } + if (isDecisionObject(parsed.axes)) workload.axes = parsed.axes as Record; + if (isDecisionObject(parsed.difficulty_hints)) { + workload.difficulty_hints = parsed.difficulty_hints as Record; + } + return workload; +} + +/** 读取并解析 workload 文件(`-` 表示 stdin)。 */ +export function loadWorkload(path: string): WorkloadConfig { + const raw = readTextFromPathOrStdin(path); + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw usageError( + `workload is not valid JSON: ${reason}`, + `workload 不是合法的 JSON:${reason}`, + ); + } + return parseWorkload(parsed); +} + +/** + * 语义校验:问题定义复用决策共享规则;生成模式额外要求 description、 + * 非空 state_schema,以及(若提供)每个 axis 至少一个取值。校验在调用 API 前执行。 + */ +export function validateWorkload(workload: WorkloadConfig, forGeneration: boolean): void { + const questionIssues = inspectDecisionQuestions(workload.questions); + if (questionIssues.length > 0) { + throw usageError( + `Invalid workload questions:\n${questionIssues.map((issue) => `- ${issue.message["en-US"]}`).join("\n")}`, + `workload 问题定义不合法:\n${questionIssues.map((issue) => `- ${issue.message["zh-CN"]}`).join("\n")}`, + ); + } + if (!forGeneration) return; + + if (typeof workload.description !== "string" || workload.description.trim().length === 0) { + throw usageError( + 'workload needs a non-empty "description" for generation.', + '生成模式需要非空的 "description"。', + ); + } + const schema = workload.state_schema; + if (!isDecisionObject(schema) || Object.keys(schema).length === 0) { + throw usageError( + 'workload must define at least one input field in "state_schema" for generation.', + '生成模式必须在 "state_schema" 中定义至少一个输入字段。', + ); + } + for (const [fieldName, requirement] of Object.entries(schema)) { + if (typeof requirement !== "string" || requirement.trim().length === 0) { + throw usageError( + `state_schema["${fieldName}"] must be a non-empty content requirement string.`, + `state_schema["${fieldName}"] 必须是非空的内容要求字符串。`, + ); + } + } + if (workload.axes) { + for (const [axisName, values] of Object.entries(workload.axes)) { + if (!Array.isArray(values) || values.length === 0) { + throw usageError( + `each axis must contain at least one value (axis "${axisName}" is empty).`, + `每个 axis 至少要有一个取值(axis "${axisName}" 为空)。`, + ); + } + } + } +} diff --git a/packages/core/src/dataset/validate/jsonl.ts b/packages/core/src/dataset/validate/jsonl.ts index 3e6a312f..dffa4d00 100644 --- a/packages/core/src/dataset/validate/jsonl.ts +++ b/packages/core/src/dataset/validate/jsonl.ts @@ -27,6 +27,7 @@ import type { } from "./types.ts"; import { makeIssue, pickSampleLines } from "./common.ts"; import { pickRecordSchema } from "./schemas/index.ts"; +import type { RecordSchemaSession } from "./schemas/types.ts"; interface QuickScanResult { totalLines: number; @@ -74,6 +75,16 @@ interface DeepCheckResult { issues: ValidationIssue[]; } +/** + * Mutable holder for the cross-record session of the first schema that + * provides one. Records picking a different schema still go through the + * stateless per-record dispatch. + */ +interface SessionState { + schemaName?: DatasetSchema; + session?: RecordSchemaSession; +} + async function deepCheck( filePath: string, totalLines: number, @@ -86,6 +97,7 @@ async function deepCheck( const issues: ValidationIssue[] = []; let sampled = 0; const MAX_ISSUES = 30; + const sessionState: SessionState = {}; const stream = createReadStream(filePath, { encoding: "utf8" }); const rl = createInterface({ input: stream, crlfDelay: Infinity }); @@ -111,7 +123,7 @@ async function deepCheck( continue; } - issues.push(...inspectRecord(obj, lineNo, schema)); + issues.push(...inspectRecord(obj, lineNo, schema, sessionState)); } return { sampled, issues }; } @@ -121,8 +133,18 @@ async function deepCheck( * The registry decides whether the record is DPO, ChatML, or some future * shape — this function only owns the "is this even an object?" guard so the * downstream specs can assume a real object. + * + * When a session holder is given, the first record whose schema provides a + * `createSession` starts a cross-record session (e.g. decision question + * definition consistency); later records of that same schema are inspected + * through the session instead of the stateless spec. */ -function inspectRecord(obj: unknown, lineNo: number, schema?: DatasetSchema): ValidationIssue[] { +function inspectRecord( + obj: unknown, + lineNo: number, + schema?: DatasetSchema, + sessionState?: SessionState, +): ValidationIssue[] { if (obj === null || typeof obj !== "object" || Array.isArray(obj)) { return [ makeIssue( @@ -135,6 +157,15 @@ function inspectRecord(obj: unknown, lineNo: number, schema?: DatasetSchema): Va } const record = obj as Record; const spec = pickRecordSchema(record, schema); + if (sessionState) { + if (!sessionState.session && spec.createSession) { + sessionState.schemaName = spec.name; + sessionState.session = spec.createSession(); + } + if (sessionState.session && sessionState.schemaName === spec.name) { + return sessionState.session.inspect(record, lineNo); + } + } return spec.inspect(record, lineNo); } diff --git a/packages/core/src/dataset/validate/schemas/decision.ts b/packages/core/src/dataset/validate/schemas/decision.ts index 04934ad2..b713c277 100644 --- a/packages/core/src/dataset/validate/schemas/decision.ts +++ b/packages/core/src/dataset/validate/schemas/decision.ts @@ -10,6 +10,8 @@ * 训练侧额外要求 `label` 硬标签,`target` 是可选软标签概率分布。 */ import { + compareDecisionQuestionTables, + decisionQuestionTableSignature, inspectDecisionQuestion, inspectDecisionQuestionId, inspectDecisionQuestionTable, @@ -19,7 +21,7 @@ import { } from "../../../decision/questions.ts"; import { makeIssue } from "../common.ts"; import type { ValidationIssue } from "../types.ts"; -import type { RecordSchemaSpec } from "./types.ts"; +import type { RecordSchemaSession, RecordSchemaSpec } from "./types.ts"; const TARGET_SUM_TOLERANCE = 1e-6; @@ -224,4 +226,45 @@ export const decisionSchema: RecordSchemaSpec = { name: "decision", detect: (record) => !("messages" in record) && ("questions" in record || "state" in record), inspect: inspectDecisionRecord, + createSession: createDecisionSession, }; + +/** + * 跨记录一致性检查:微调学的是“输入 + 问题定义 → 答案”的映射,同一文件内 + * 问题 ID、类型、instructions、criteria 必须保持一致,否则分布漂移、准确率下降、 + * 校准失效。以首条有效记录的问题定义为基线,后续不一致报 warning(不阻断: + * 平台是否硬拒未实证,且采样校验可能漏检)。 + */ +function createDecisionSession(): RecordSchemaSession { + let baseline: Map | undefined; + let baselineLine = 0; + return { + inspect(record: Record, lineNo: number): ValidationIssue[] { + const issues = inspectDecisionRecord(record, lineNo); + const signatures = decisionQuestionTableSignature(record.questions); + if (!signatures) return issues; + if (!baseline) { + baseline = signatures; + baselineLine = lineNo; + return issues; + } + const driftedIds = compareDecisionQuestionTables(baseline, signatures); + if (driftedIds.length > 0) { + issues.push( + makeIssue( + "warning", + "DECISION_QUESTION_DRIFT", + `Question definitions differ from line ${baselineLine} (IDs: ${driftedIds.join(", ")}). ` + + `Training, evaluation and online requests must keep question ID, type, instructions and criteria identical; ` + + `changing them requires regenerating data and retraining. / ` + + `问题定义与第 ${baselineLine} 行不一致(ID:${driftedIds.join(", ")})。` + + `训练、评估与线上请求的问题 ID、类型、instructions、criteria 必须保持一致;` + + `修改定义须重新准备数据并重训。`, + { line: lineNo, path: "questions" }, + ), + ); + } + return issues; + }, + }; +} diff --git a/packages/core/src/dataset/validate/schemas/types.ts b/packages/core/src/dataset/validate/schemas/types.ts index d80dc21f..ff8133fb 100644 --- a/packages/core/src/dataset/validate/schemas/types.ts +++ b/packages/core/src/dataset/validate/schemas/types.ts @@ -16,6 +16,16 @@ */ import type { DatasetSchema, ValidationIssue } from "../types.ts"; +/** + * Stateful per-file inspector. A schema whose rules span records (e.g. the + * decision model requires identical question definitions across the whole + * training file) creates one session per validation run; the first inspected + * record establishes the baseline and later records are compared against it. + */ +export interface RecordSchemaSession { + inspect(record: Record, lineNo: number): ValidationIssue[]; +} + export interface RecordSchemaSpec { /** Schema id — must match a value in the `DatasetSchema` union. */ name: DatasetSchema; @@ -27,4 +37,11 @@ export interface RecordSchemaSpec { detect(record: Record): boolean; /** Run schema-specific structural checks on the parsed record. */ inspect(record: Record, lineNo: number): ValidationIssue[]; + /** + * Optional cross-record session factory. When present, the JSONL validator + * instantiates one session from the first sampled record that picks this + * schema and routes subsequent same-schema records through it (memory stays + * bounded by the sampling cap). Schemas without cross-record rules omit it. + */ + createSession?(): RecordSchemaSession; } diff --git a/packages/core/src/decision/index.ts b/packages/core/src/decision/index.ts index 51d3f7ce..4ebba617 100644 --- a/packages/core/src/decision/index.ts +++ b/packages/core/src/decision/index.ts @@ -1,2 +1,3 @@ export * from "./questions.ts"; export * from "./request.ts"; +export * from "./training-data.ts"; diff --git a/packages/core/src/decision/questions.ts b/packages/core/src/decision/questions.ts index 29e83e84..6586e797 100644 --- a/packages/core/src/decision/questions.ts +++ b/packages/core/src/decision/questions.ts @@ -230,3 +230,55 @@ export function inspectDecisionQuestions(questions: unknown, path = "questions") } return issues; } + +/** + * 问题定义的规范化签名:type + instructions + criteria(对象键排序,与书写顺序无关)。 + * 微调学的是“输入 + 问题定义 → 答案”的映射,同一任务的训练、评估与线上请求 + * 必须保持问题 ID、类型、instructions、criteria 一致;签名用于跨记录 / 跨文件比对。 + * 训练专用的 label / target 不参与签名。非对象问题返回 undefined。 + */ +export function decisionQuestionSignature(question: unknown): string | undefined { + if (!isDecisionObject(question)) return undefined; + const criteria = question.criteria; + let normalizedCriteria: unknown; + if (Array.isArray(criteria)) { + normalizedCriteria = criteria; + } else if (isDecisionObject(criteria)) { + normalizedCriteria = Object.fromEntries( + Object.keys(criteria) + .sort() + .map((optionName) => [optionName, criteria[optionName]]), + ); + } else { + normalizedCriteria = criteria ?? null; + } + return JSON.stringify([question.type ?? null, question.instructions ?? null, normalizedCriteria]); +} + +/** 问题表签名:问题 ID → 定义签名。非对象问题表返回 undefined;非对象问题跳过。 */ +export function decisionQuestionTableSignature( + questions: unknown, +): Map | undefined { + if (!isDecisionObject(questions)) return undefined; + const signatures = new Map(); + for (const [questionId, question] of Object.entries(questions)) { + const signature = decisionQuestionSignature(question); + if (signature !== undefined) signatures.set(questionId, signature); + } + return signatures; +} + +/** 比对两份问题表签名,返回新增 / 缺失 / 定义变化的问题 ID(排序后)。 */ +export function compareDecisionQuestionTables( + baseline: Map, + other: Map, +): string[] { + const driftedIds = new Set(); + for (const [questionId, signature] of baseline) { + if (other.get(questionId) !== signature) driftedIds.add(questionId); + } + for (const questionId of other.keys()) { + if (!baseline.has(questionId)) driftedIds.add(questionId); + } + return [...driftedIds].sort(); +} diff --git a/packages/core/src/decision/training-data.ts b/packages/core/src/decision/training-data.ts new file mode 100644 index 00000000..fcf51dfa --- /dev/null +++ b/packages/core/src/decision/training-data.ts @@ -0,0 +1,40 @@ +/** + * 决策训练数据文件的问题定义签名读取。 + * + * 只读首条非空记录的问题表(ID、类型、instructions、criteria),用于训练集与 + * 验证集之间的跨文件一致性比对——同一任务两侧的问题定义必须一致,否则分布漂移。 + * 文件不可读、首行不是 JSON 对象或问题表缺失时返回 undefined,调用方据此跳过比对 + * (结构问题由 dataset validate 的逐记录校验负责报告)。 + */ +import { createReadStream } from "fs"; +import { createInterface } from "readline"; +import { decisionQuestionTableSignature, isDecisionObject } from "./questions.ts"; + +export async function readDecisionQuestionSignature( + filePath: string, +): Promise | undefined> { + const stream = createReadStream(filePath, { encoding: "utf8" }); + const reader = createInterface({ input: stream, crlfDelay: Infinity }); + try { + for await (const raw of reader) { + const line = raw.trim(); + if (line.length === 0) continue; + let record: unknown; + try { + record = JSON.parse(line); + } catch { + return undefined; + } + if (!isDecisionObject(record)) return undefined; + return decisionQuestionTableSignature(record.questions); + } + return undefined; + } catch { + // Unreadable file (ENOENT/EACCES/...): skip the comparison; dataset + // validation owns reporting file-level problems. + return undefined; + } finally { + reader.close(); + stream.destroy(); + } +} diff --git a/packages/core/src/finetune/index.ts b/packages/core/src/finetune/index.ts index 19297eff..f39b7833 100644 --- a/packages/core/src/finetune/index.ts +++ b/packages/core/src/finetune/index.ts @@ -2,6 +2,7 @@ export * from "./types.ts"; export * from "./api.ts"; export * from "./compress.ts"; export * from "./capability.ts"; +export * from "./train-options.ts"; export * from "./preflight.ts"; export * from "./profiles/index.ts"; export * from "./price.ts"; diff --git a/packages/core/src/finetune/preflight.ts b/packages/core/src/finetune/preflight.ts index 5ab435d5..e03a77b3 100644 --- a/packages/core/src/finetune/preflight.ts +++ b/packages/core/src/finetune/preflight.ts @@ -75,6 +75,73 @@ export function preflightBatchSizeGate(input: BatchSizeGateInput): BatchSizeGate }; } +/** Stable issue code for the decision-model sample-count rule. */ +export const INSUFFICIENT_DECISION_SAMPLES_CODE = "INSUFFICIENT_DECISION_SAMPLES"; + +export interface DecisionSampleGateInput { + /** Whether a separate validation dataset was supplied (`--validations`). */ + hasValidation: boolean; + /** + * Training-sample count, when known (every `--datasets` token was a local + * file). Undefined for bare file-id flows — that part of the check is then + * left to the platform. + */ + trainingRecordCount?: number; + /** Validation-sample count, when known. Same fall-through as training. */ + validationRecordCount?: number; + /** Effective batch_size from the user override or the service default. */ + batchSize: number; +} + +/** + * Pre-flight the decision model's sample-count rule (documented FAQ): + * - with a separate validation dataset: train ≥ batch_size AND val ≥ batch_size; + * - training only: train ≥ batch_size × 10. + * + * Unlike the generic text gate this is a "≥" rule and covers the validation + * set too. Conservative by design: each part only fires when its record count + * is known (local files, non dry-run); bare file-id tokens fall through to the + * platform rather than risk a false positive. + */ +export function preflightDecisionSampleGate(input: DecisionSampleGateInput): BatchSizeGateResult { + const { hasValidation, trainingRecordCount, validationRecordCount, batchSize } = input; + const trainingMinimum = hasValidation ? batchSize : batchSize * 10; + const failuresEnglish: string[] = []; + const failuresChinese: string[] = []; + + if (trainingRecordCount !== undefined && trainingRecordCount < trainingMinimum) { + failuresEnglish.push( + `training dataset has ${trainingRecordCount} sample(s), requires at least ${trainingMinimum}`, + ); + failuresChinese.push(`训练集仅 ${trainingRecordCount} 条样本,至少需要 ${trainingMinimum} 条`); + } + if (hasValidation && validationRecordCount !== undefined && validationRecordCount < batchSize) { + failuresEnglish.push( + `validation dataset has ${validationRecordCount} sample(s), requires at least ${batchSize}`, + ); + failuresChinese.push(`验证集仅 ${validationRecordCount} 条样本,至少需要 ${batchSize} 条`); + } + + if (failuresEnglish.length === 0) return { ok: true }; + return { + ok: false, + issue: { + severity: "error", + code: INSUFFICIENT_DECISION_SAMPLES_CODE, + message: `Decision model sample-count check failed: ${failuresEnglish.join("; ")}. / 决策模型样本数检查未通过:${failuresChinese.join(";")}。`, + }, + hint: [ + "The decision model requires: with a separate validation dataset, both train and validation", + "samples ≥ batch_size; with training data only, samples ≥ batch_size × 10.", + "Options:", + " • add more data (recommended: hundreds of samples),", + " • lower --batch-size within the range published for this model.", + "决策模型要求:单独上传验证集时,训练集与验证集样本数均不小于 batch_size;仅上传训练集时,", + "样本数不少于 batch_size × 10。建议补充数据(推荐上百条)或在模型允许范围内调低 --batch-size。", + ].join("\n"), + }; +} + export type FineTuneHyperParameterIssueCode = | "unsupported" | "not_editable" diff --git a/packages/core/src/finetune/profiles/sft-lora.ts b/packages/core/src/finetune/profiles/sft-lora.ts index 538543bf..c7953841 100644 --- a/packages/core/src/finetune/profiles/sft-lora.ts +++ b/packages/core/src/finetune/profiles/sft-lora.ts @@ -11,6 +11,7 @@ * hyper-parameters, and pre-flight gates. All branching is internal — * `create.ts` calls the uniform profile interface without knowing the modality. */ +import { extname } from "path"; import type { TrainingProfile, DataModality } from "./types.ts"; import type { ValidateOpts, ValidationResult } from "../../dataset/validate/types.ts"; import { validateDataset } from "../../dataset/validate/registry.ts"; @@ -128,6 +129,27 @@ export const sftLoraProfile: TrainingProfile = { modality: DataModality, opts: ValidateOpts, ): Promise { + if (modality === "decision") { + // Decision training data is plain JSONL ({state, questions, label, + // optional target}); ZIP archives belong to the media modalities. + if (extname(filePath).toLowerCase() !== ".jsonl") { + return { + valid: false, + format: "jsonl", + filePath, + errors: [ + makeIssue( + "error", + "DECISION_UNSUPPORTED_FORMAT", + `Decision model training data must be a .jsonl file (got "${extname(filePath) || "(none)"}"). / 决策模型训练数据必须是 .jsonl 文件(当前为 "${extname(filePath) || "(none)"}")。`, + ), + ], + warnings: [], + stats: {}, + }; + } + return validateDataset(filePath, { ...opts, schema: "decision" }); + } if (modality === "audio") { // ZIP validation: structure check + JSONL content via tts schema. // The zip validator internally calls jsonlValidator for data.jsonl. @@ -190,6 +212,22 @@ export const sftLoraProfile: TrainingProfile = { modality: DataModality, flags: Record, ): Record { + if (modality === "decision") { + // Decision: only the three documented knobs (n_epochs / batch_size / + // learning_rate). The API rejects an empty hyper_parameters block + // ("n_epochs is required"), so the documented defaults are always sent; + // valid ranges still come from the platform parameter schema (explicit + // overrides only, no local clamping). + const hp: Record = { + n_epochs: 2, + batch_size: 1, + learning_rate: "2e-5", + }; + if (flags.nEpochs !== undefined) hp.n_epochs = flags.nEpochs as number; + if (flags.batchSize !== undefined) hp.batch_size = flags.batchSize as number; + if (flags.learningRate !== undefined) hp.learning_rate = flags.learningRate as string; + return hp; + } if (modality === "audio") { // Audio: use TTS defaults, user flags override (MVP: all hardcoded). return { ...AUDIO_HYPER_PARAMS }; @@ -230,6 +268,12 @@ export const sftLoraProfile: TrainingProfile = { // batch-size pre-flight gate to avoid false rejections. if (gate === "batch_size") return true; } + if (modality === "decision" && gate === "batch_size") { + // Decision has its own sample-count rule (train/val each ≥ batch_size, + // or train ≥ batch_size × 10 without validation), enforced by + // preflightDecisionSampleGate in `finetune decision create`. + return true; + } return false; }, @@ -238,6 +282,11 @@ export const sftLoraProfile: TrainingProfile = { // (e.g. wan2.7-image-pro) and video models (e.g. wan2.5-i2v-preview) report // supports.sft=false in listFoundationModels but the API accepts // efficient_sft — skip to avoid false blocking. - return modality === "audio" || isImage(modality) || isVideo(modality); + // The decision preview model likewise reports fineTune/sft=false in the + // public catalog while training access is account-gated (whitelist); the + // server is the authority on whether the job is accepted. + return ( + modality === "audio" || isImage(modality) || isVideo(modality) || modality === "decision" + ); }, }; diff --git a/packages/core/src/finetune/profiles/types.ts b/packages/core/src/finetune/profiles/types.ts index a93ef62d..0d05f1e8 100644 --- a/packages/core/src/finetune/profiles/types.ts +++ b/packages/core/src/finetune/profiles/types.ts @@ -31,8 +31,20 @@ import type { ValidateOpts, ValidationResult } from "../../dataset/validate/type * Wan kf2v). Profiles can branch on subtypes to adjust hyper-parameter defaults * or cross-check the chosen `--model`. Callers that don't care about a subtype * can normalise `"image-i2i"` → `"image"` and `"video-kf2v"` → `"video"`. + * + * `"decision"` is the decision-model training data (`{state, questions}` JSONL + * with `label` / optional `target`). Like text it is plain `.jsonl`, but the + * record schema and sample-count rules differ, so it is a distinct modality + * fixed by the `finetune decision create` subcommand. */ -export type DataModality = "text" | "audio" | "image" | "image-i2i" | "video" | "video-kf2v"; +export type DataModality = + | "text" + | "audio" + | "image" + | "image-i2i" + | "video" + | "video-kf2v" + | "decision"; /** * A training profile. One per `--training-type` CLI value. diff --git a/packages/core/src/finetune/train-options.ts b/packages/core/src/finetune/train-options.ts new file mode 100644 index 00000000..67de0e93 --- /dev/null +++ b/packages/core/src/finetune/train-options.ts @@ -0,0 +1,108 @@ +import type { ConsoleCall } from "../console/gateway.ts"; +import { unwrapResponse } from "../console/models.ts"; + +/** + * Console (zelda) API listing the dynamic train options configured per model. + * Requires a Console login session — anonymous calls are rejected. Models + * without dynamic train options are simply absent from the response. + */ +export const MODEL_TRAIN_OPTIONS_API = + "zeldaHttp.dashscopeFinetune./zelda/api/v1/finetune/model-train-options"; + +export interface TrainOptionDefinition { + name?: string; + supportValues?: string[]; + required?: boolean; + editable?: boolean; + recommendValue?: string; + [key: string]: unknown; +} + +export interface ModelTrainOptions { + enabled?: boolean; + optionKeys?: string[]; + optionDefinitions?: TrainOptionDefinition[]; + defaults?: Record; + supportedCombinations?: Array>; + [key: string]: unknown; +} + +/** + * Fetch the dynamic train options for one model + server-side training type. + * Returns null when the model has no dynamic options (absent from the list or + * `enabled !== true`), so callers never need a hardcoded model allowlist. + */ +export async function fetchModelTrainOptions( + call: ConsoleCall, + model: string, + serverTrainingType: string, +): Promise { + const result = await call(MODEL_TRAIN_OPTIONS_API, { + input: { models: [model], trainingType: serverTrainingType }, + }); + 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) ?? []); + const match = entries.find((entry) => entry.model === model); + const options = match?.trainingOptions as ModelTrainOptions | undefined; + return options?.enabled === true ? options : null; +} + +export type TrainOptionsIssueCode = "not_configured" | "unsupported_value" | "invalid_combination"; + +export interface TrainOptionsIssue { + code: TrainOptionsIssueCode; + key?: string; + value?: string; + expected?: string[]; + combinations?: Array>; +} + +/** + * Validate user-supplied train options against the console configuration and + * complete omitted options from `defaults`. Pure: callers format the issues. + * + * Combination authority is `supportedCombinations` only — the `editable` flag + * disagrees between this API and the fine-tunes-params schema, so it is never + * consulted here. + */ +export function resolveTrainOptions( + options: ModelTrainOptions | null, + userOptions: Record, +): { context: Record; issues: TrainOptionsIssue[] } { + const issues: TrainOptionsIssue[] = []; + if (!options) { + if (Object.keys(userOptions).length > 0) issues.push({ code: "not_configured" }); + return { context: {}, issues }; + } + + const definitions = new Map( + (options.optionDefinitions ?? []).map((definition) => [definition.name, definition]), + ); + const merged: Record = { ...options.defaults, ...userOptions }; + for (const [key, value] of Object.entries(userOptions)) { + const definition = definitions.get(key); + const supportValues = definition?.supportValues; + if (!definition || (supportValues && !supportValues.includes(value))) { + issues.push({ + code: "unsupported_value", + key, + value, + expected: supportValues ?? options.optionKeys ?? [], + }); + } + } + + const combinations = options.supportedCombinations ?? []; + if (issues.length === 0 && combinations.length > 0) { + const matched = combinations.some((combination) => + Object.entries(merged).every(([key, value]) => combination[key] === value), + ); + if (!matched) issues.push({ code: "invalid_combination", combinations }); + } + + return { context: issues.length === 0 ? merged : {}, issues }; +} diff --git a/packages/core/tests/dataset-prepare.test.ts b/packages/core/tests/dataset-prepare.test.ts new file mode 100644 index 00000000..3611102c --- /dev/null +++ b/packages/core/tests/dataset-prepare.test.ts @@ -0,0 +1,523 @@ +import { afterAll, describe, expect, test } from "vite-plus/test"; +import { mkdirSync, rmSync, writeFileSync } from "fs"; +import { join } from "path"; +import { tmpdir } from "os"; +import { + BailianError, + ExitCode, + MIN_SPLIT_RECORDS, + TEACHER_SYSTEM_PROMPT, + agreementRatio, + alignRow, + balanceReport, + buildGenerationMessages, + buildManifest, + buildPlans, + buildTeacherMessages, + dedupByState, + extractItems, + extractJson, + loadWorkload, + parseStateItems, + parseTeacherRow, + parseWorkload, + questionOptions, + renderValue, + seededShuffle, + smooth, + splitRecords, + stateKey, + toTrainingRecord, + validateWorkload, + workloadIdFields, + type GenerationPlan, + type RawLabelRow, + type WorkloadConfig, +} from "../src/index.ts"; + +const tmp = join(tmpdir(), `bl-dataset-prepare-test-${process.pid}`); +mkdirSync(tmp, { recursive: true }); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +function file(name: string, content: string): string { + const filePath = join(tmp, name); + writeFileSync(filePath, content); + return filePath; +} + +function expectUsage(run: () => unknown): void { + try { + run(); + throw new Error("expected a USAGE BailianError"); + } catch (error) { + expect(error).toBeInstanceOf(BailianError); + expect((error as BailianError).exitCode).toBe(ExitCode.USAGE); + } +} + +const WORKLOAD: WorkloadConfig = { + description: "客服工单分流与升级判断", + state_schema: { ticket_id: "工单编号", content: "工单正文" }, + questions: { + department: { + type: "choice", + instructions: "应该由哪个部门处理?", + criteria: { billing: "账单与支付问题", technical: "产品故障问题" }, + }, + escalate: { type: "noul", instructions: "是否需要升级处理?" }, + severity: { + type: "score", + instructions: "严重程度档位?", + criteria: ["低", "中", "高", "紧急"], + }, + }, + guidance: ["涉及退款一律升级"], + axes: { department: ["billing", "technical"], severity: [0, 1, 2, 3] }, +}; + +const RAW_ROW: RawLabelRow = { + state: { ticket_id: "T-1", content: "发票金额开错了,要求退款" }, + plan: { difficulty: "clean", department: "billing", escalate: false, severity: 1, index: 0 }, + answers: { + department: { probabilities: { billing: 0.9, technical: 0.1 } }, + escalate: { noul: 0.8 }, + severity: { probabilities: { "0": 0.1, "1": 0.7, "2": 0.2, "3": 0 } }, + }, +}; + +describe("workload — parse / load / validate", () => { + test("parseWorkload keeps typed fields and drops non-string entries", () => { + const parsed = parseWorkload({ + ...WORKLOAD, + name: "cloud-support", + id_fields: ["ticket_id", 42], + guidance: ["规则一", 7], + }); + expect(parsed.name).toBe("cloud-support"); + expect(parsed.id_fields).toEqual(["ticket_id"]); + expect(parsed.guidance).toEqual(["规则一"]); + expect(Object.keys(parsed.questions)).toEqual(["department", "escalate", "severity"]); + }); + + test("parseWorkload rejects non-object and empty questions", () => { + expectUsage(() => parseWorkload(null)); + expectUsage(() => parseWorkload([])); + expectUsage(() => parseWorkload({ questions: {} })); + expectUsage(() => parseWorkload({ description: "x" })); + }); + + test("loadWorkload reads a file and reports invalid JSON as USAGE", () => { + const good = file("workload.json", JSON.stringify(WORKLOAD)); + expect(loadWorkload(good).description).toBe(WORKLOAD.description); + const bad = file("workload-bad.json", "{not json"); + expectUsage(() => loadWorkload(bad)); + }); + + test("workloadIdFields defaults to ticket_id", () => { + expect(workloadIdFields(WORKLOAD)).toEqual(["ticket_id"]); + expect(workloadIdFields({ ...WORKLOAD, id_fields: ["case_id"] })).toEqual(["case_id"]); + }); + + test("validateWorkload rejects invalid question definitions", () => { + const broken: WorkloadConfig = { + questions: { department: { type: "choice", criteria: {} } }, + }; + expectUsage(() => validateWorkload(broken, false)); + }); + + test("validateWorkload in generation mode requires description and state_schema", () => { + expectUsage(() => validateWorkload({ questions: WORKLOAD.questions }, true)); + expectUsage(() => validateWorkload({ ...WORKLOAD, description: " " }, true)); + expectUsage(() => validateWorkload({ ...WORKLOAD, state_schema: {} }, true)); + expectUsage(() => validateWorkload({ ...WORKLOAD, state_schema: { content: "" } }, true)); + expectUsage(() => validateWorkload({ ...WORKLOAD, axes: { department: [] } }, true)); + // 非生成模式不要求 description / state_schema。 + expect(() => validateWorkload({ questions: WORKLOAD.questions }, false)).not.toThrow(); + expect(() => validateWorkload(WORKLOAD, true)).not.toThrow(); + }); +}); + +describe("rng / plan — determinism and balance", () => { + test("seededShuffle is deterministic, permutes, and does not mutate input", () => { + const items = Array.from({ length: 50 }, (_item, index) => index); + const first = seededShuffle(items, 42); + const second = seededShuffle(items, 42); + expect(first).toEqual(second); + expect(first).not.toEqual(items); + expect([...first].sort((left, right) => left - right)).toEqual(items); + expect(items).toEqual(Array.from({ length: 50 }, (_item, index) => index)); + expect(seededShuffle(items, 43)).not.toEqual(first); + }); + + test("buildPlans cycles the axes grid evenly and appends unknowable plans", () => { + const plans = buildPlans(WORKLOAD, 20, 3, 7); + expect(plans).toHaveLength(23); + const normal = plans.filter((plan) => plan.difficulty !== "unknowable"); + const unknowable = plans.filter((plan) => plan.difficulty === "unknowable"); + expect(normal).toHaveLength(20); + expect(unknowable).toHaveLength(3); + // 8 种组合循环 20 次:每种组合出现 2 或 3 次。 + const comboCounts = new Map(); + for (const plan of normal) { + const key = `${plan.department}/${plan.severity}`; + comboCounts.set(key, (comboCounts.get(key) ?? 0) + 1); + } + expect(comboCounts.size).toBe(8); + for (const count of comboCounts.values()) { + expect(count === 2 || count === 3).toBe(true); + } + expect(new Set(plans.map((plan) => plan.index)).size).toBe(23); + }); + + test("buildPlans is reproducible for the same seed and rejects empty axes", () => { + expect(buildPlans(WORKLOAD, 12, 2, 9)).toEqual(buildPlans(WORKLOAD, 12, 2, 9)); + expectUsage(() => buildPlans({ ...WORKLOAD, axes: { department: [] } }, 5, 0, 0)); + }); +}); + +describe("prompt — question options and message construction", () => { + test("questionOptions keeps ordered keys for choice / score / noul", () => { + const choice = questionOptions(WORKLOAD.questions.department); + expect(Object.keys(choice)).toEqual(["billing", "technical"]); + const score = questionOptions(WORKLOAD.questions.severity); + expect(Object.keys(score)).toEqual(["0", "1", "2", "3"]); + expect(score["2"]).toBe("高"); + const noul = questionOptions(WORKLOAD.questions.escalate); + expect(Object.keys(noul)).toEqual(["false", "true"]); + const described = questionOptions({ + type: "noul", + instructions: "x", + criteria: { false: "无需升级", true: "需要升级" }, + }); + expect(described).toEqual({ false: "无需升级", true: "需要升级" }); + }); + + test("questionOptions rejects malformed definitions", () => { + expect(() => questionOptions({ type: "choice", instructions: "x" })).toThrow(); + expect(() => + questionOptions({ type: "score", instructions: "x", criteria: ["只有一档"] }), + ).toThrow(); + expect(() => + questionOptions({ type: "noul", instructions: "x", criteria: { yes: "是" } }), + ).toThrow(); + }); + + test("buildTeacherMessages emits system + user with skeleton and guidance", () => { + const messages = buildTeacherMessages(RAW_ROW.state, WORKLOAD.questions, WORKLOAD.guidance); + expect(messages.map((message) => message.role)).toEqual(["system", "user"]); + const system = String(messages[0].content); + const user = String(messages[1].content); + expect(system.startsWith(TEACHER_SYSTEM_PROMPT)).toBe(true); + expect(system).toContain("Business rules:"); + expect(system).toContain("涉及退款一律升级"); + expect(user).toContain('QUESTION id="department" type=choice'); + expect(user).toContain("billing: 账单与支付问题"); + expect(user).toContain('"severity"'); + expect(user).toContain('{"department":{"billing":0,"technical":0}'); + expect(user).toContain("发票金额开错了"); + const withoutGuidance = buildTeacherMessages(RAW_ROW.state, WORKLOAD.questions); + expect(String(withoutGuidance[0].content)).not.toContain("Business rules:"); + }); + + test("buildGenerationMessages lists schema fields and profiles without index", () => { + const plans = buildPlans(WORKLOAD, 3, 1, 5); + const messages = buildGenerationMessages(WORKLOAD, plans); + const user = String(messages[1].content); + expect(user).toContain('"ticket_id": 工单编号'); + expect(user).toContain('"content": 工单正文'); + expect(user).toContain("客服工单分流与升级判断"); + expect(user).toContain('输出格式:{"samples": [...]},数组长度为 4'); + expect(user).not.toContain('"index"'); + expect(user).toContain("缺少作出判断所需的信息"); + }); +}); + +describe("parse — JSON extraction from model replies", () => { + test("extractJson handles bare, fenced, and prose-prefixed payloads", () => { + expect(extractJson('{"a":1}')).toEqual({ a: 1 }); + expect(extractJson('```json\n{"a":1}\n```')).toEqual({ a: 1 }); + expect(extractJson('好的,结果如下:\n{"a":1}\n以上。')).toEqual({ a: 1 }); + expect(extractJson("[1,2,3]")).toEqual([1, 2, 3]); + expect(extractJson('前缀 [{"a":1}] 后缀')).toEqual([{ a: 1 }]); + expect(extractJson("没有 JSON")).toBeUndefined(); + expect(extractJson("")).toBeUndefined(); + }); + + test("extractItems accepts wrapped lists, bare arrays, and single objects", () => { + expect(extractItems('{"samples":[{"x":1},{"x":2}]}')).toEqual([{ x: 1 }, { x: 2 }]); + expect(extractItems('[{"x":1}]')).toEqual([{ x: 1 }]); + expect(extractItems('{"x":1}')).toEqual([{ x: 1 }]); + expect(extractItems("纯文本")).toBeUndefined(); + }); + + test("renderValue is key-order independent for objects", () => { + expect(renderValue({ b: 2, a: { d: 4, c: 3 } })).toBe(renderValue({ a: { c: 3, d: 4 }, b: 2 })); + expect(renderValue("原样")).toBe("原样"); + }); +}); + +describe("label — alignment, smoothing, and training records", () => { + test("alignRow validates keys, range, sum, and normalizes", () => { + expect(alignRow({ a: 0.5, b: 0.5 }, ["a", "b"])).toEqual([0.5, 0.5]); + expect(alignRow({ a: "0.2", b: "0.2" }, ["a", "b"])).toEqual([0.5, 0.5]); + expect(() => alignRow({ a: 1 }, ["a", "b"])).toThrow(); + expect(() => alignRow({ a: 0.5, c: 0.5 }, ["a", "b"])).toThrow(); + expect(() => alignRow({ a: 1.2, b: 0 }, ["a", "b"])).toThrow(); + expect(() => alignRow({ a: -0.1, b: 0.5 }, ["a", "b"])).toThrow(); + expect(() => alignRow({ a: 0, b: 0 }, ["a", "b"])).toThrow(); + expect(() => alignRow(null, ["a"])).toThrow(); + }); + + test("smooth keeps distribution at temp 1 and flattens above 1", () => { + const probs = { a: 0.9, b: 0.1 }; + expect(smooth(probs, 1)).toEqual(probs); + const flattened = smooth(probs, 1.5); + expect(flattened.a).toBeLessThan(0.9); + expect(flattened.b).toBeGreaterThan(0.1); + expect(flattened.a + flattened.b).toBeCloseTo(1, 10); + }); + + test("toTrainingRecord derives hard labels by question type", () => { + const { record, intentMatch } = toTrainingRecord(RAW_ROW, WORKLOAD, 1.5, true); + expect(record).not.toBeNull(); + const questions = record!.questions; + expect(questions.department.label).toBe("billing"); + expect(questions.escalate.label).toBe(true); + expect(questions.severity.label).toBe(1); + // 软标签保留问题定义且概率和为 1。 + expect(questions.department.criteria).toEqual(WORKLOAD.questions.department.criteria); + for (const question of Object.values(questions)) { + const total = Object.values(question.target ?? {}).reduce((sum, value) => sum + value, 0); + expect(total).toBeCloseTo(1, 10); + } + expect(intentMatch).toEqual({ department: true, escalate: false, severity: true }); + expect(record!._meta).toBeUndefined(); + }); + + test("noul boundary 0.5 counts as true; no-soft omits targets", () => { + const boundary: RawLabelRow = { + ...RAW_ROW, + answers: { ...RAW_ROW.answers, escalate: { noul: 0.5 } }, + }; + const { record } = toTrainingRecord(boundary, WORKLOAD, 1.5, false); + expect(record!.questions.escalate.label).toBe(true); + expect(record!.questions.department.target).toBeUndefined(); + }); + + test("unknowable plans get uniform targets and _meta.source", () => { + const unknowable: RawLabelRow = { + ...RAW_ROW, + plan: { difficulty: "unknowable", index: 3 }, + }; + const { record, intentMatch } = toTrainingRecord(unknowable, WORKLOAD, 1.5, true); + expect(record!._meta).toEqual({ source: "unknowable" }); + expect(record!.questions.department.target).toEqual({ billing: 0.5, technical: 0.5 }); + expect(record!.questions.severity.target).toEqual({ + "0": 0.25, + "1": 0.25, + "2": 0.25, + "3": 0.25, + }); + expect(intentMatch).toEqual({}); + }); + + test("invalid or missing teacher answers reject the whole row", () => { + expect( + toTrainingRecord({ ...RAW_ROW, missing: ["department"] }, WORKLOAD, 1.5, true).record, + ).toBeNull(); + const broken: RawLabelRow = { + ...RAW_ROW, + answers: { ...RAW_ROW.answers, department: { probabilities: { billing: 2 } } }, + }; + expect(toTrainingRecord(broken, WORKLOAD, 1.5, true).record).toBeNull(); + const absent: RawLabelRow = { ...RAW_ROW, answers: {} }; + expect(toTrainingRecord(absent, WORKLOAD, 1.5, true).record).toBeNull(); + }); +}); + +describe("split — dedup key and deterministic split", () => { + test("stateKey ignores id fields and key order", () => { + const left = stateKey({ ticket_id: "T-1", content: "x", meta: { b: 2, a: 1 } }, ["ticket_id"]); + const right = stateKey({ content: "x", meta: { a: 1, b: 2 }, ticket_id: "T-2" }, ["ticket_id"]); + expect(left).toBe(right); + expect(stateKey({ content: "y" }, ["ticket_id"])).not.toBe(left); + }); + + test("dedupByState keeps first occurrences and counts duplicates", () => { + const records = [ + { state: { ticket_id: "T-1", content: "x" } }, + { state: { ticket_id: "T-2", content: "x" } }, + { state: { ticket_id: "T-3", content: "y" } }, + ]; + const { unique, duplicateCount } = dedupByState(records, ["ticket_id"]); + expect(duplicateCount).toBe(1); + expect(unique).toHaveLength(2); + expect(unique[0]).toBe(records[0]); + }); + + test("splitRecords uses floor(n * ratio) for development and is deterministic", () => { + expect(MIN_SPLIT_RECORDS).toBe(7); + const records = Array.from({ length: 20 }, (_item, index) => ({ id: index })); + const parts = splitRecords(records, 3); + expect(parts.development).toHaveLength(3); + expect(parts.train).toHaveLength(17); + expect(splitRecords(records, 3)).toEqual(parts); + const merged = [...parts.development, ...parts.train]; + expect(merged.map((record) => record.id).sort((left, right) => left - right)).toEqual( + records.map((record) => record.id), + ); + expect(splitRecords(records, 3, 0.5).development).toHaveLength(10); + }); +}); + +describe("report — balance, agreement, manifest", () => { + test("balanceReport counts hard labels per option", () => { + const first = toTrainingRecord(RAW_ROW, WORKLOAD, 1.5, true).record!; + const second = toTrainingRecord( + { + ...RAW_ROW, + plan: { difficulty: "clean", department: "technical", index: 1 }, + answers: { + ...RAW_ROW.answers, + department: { probabilities: { billing: 0.1, technical: 0.9 } }, + }, + }, + WORKLOAD, + 1.5, + true, + ).record!; + const balance = balanceReport([first, second], WORKLOAD); + expect(balance.department).toEqual({ billing: 1, technical: 1 }); + expect(balance.escalate).toEqual({ false: 0, true: 2 }); + expect(balance.severity).toEqual({ "0": 0, "1": 2, "2": 0, "3": 0 }); + }); + + test("agreementRatio rounds to 4 decimals and guards zero totals", () => { + expect( + agreementRatio({ department: { hit: 2, total: 3 }, escalate: { hit: 0, total: 0 } }), + ).toEqual({ department: 0.6667, escalate: 0 }); + }); + + test("buildManifest mirrors the script structure with skipped token check", () => { + const manifest = buildManifest({ + created: "2026-01-01T00:00:00Z", + mode: "generate", + workloadPath: "workload.json", + rawPath: "raw/labeled.jsonl", + workloadSha256: "abc123", + generator: { + model: "qwen3.8-max", + base_url: "https://example.com/compatible-mode/v1", + seed: 0, + target_temp: 1.5, + soft_target: true, + }, + unknowableRecords: 1, + rejectedRawRecords: 2, + duplicateRawRecords: 3, + records: { train: 17, development: 3 }, + labelBalance: { department: { billing: 10, technical: 10 } }, + agreement: { department: 0.9 }, + wallSeconds: 12.5, + usage: { calls: 25, prompt_tokens: 1000, completion_tokens: 500 }, + }); + expect(manifest.workload_sha256).toBe("abc123"); + expect(manifest.mode).toBe("generate"); + expect(manifest.state_token_check).toEqual({ + status: "skipped", + reason: expect.stringContaining("transformers"), + }); + expect(manifest.records).toEqual({ train: 17, development: 3 }); + expect(manifest.usage).toEqual({ calls: 25, prompt_tokens: 1000, completion_tokens: 500 }); + expect(manifest.generator_teacher_agreement).toEqual({ department: 0.9 }); + expect(manifest.wall_s).toBe(12.5); + }); +}); + +const GROUP: GenerationPlan[] = [ + { difficulty: "clean", department: "billing", severity: 1, index: 0 }, + { difficulty: "clean", department: "technical", severity: 2, index: 1 }, +]; +const SCHEMA_FIELDS = ["ticket_id", "content"]; +const STATE: Record = { ticket_id: "T-1", content: "发票金额开错了,要求退款" }; +const GEN_CONTENT = JSON.stringify({ + samples: [STATE, { ticket_id: "T-2", content: "产品无法开机" }], +}); +const TEACHER_CONTENT = JSON.stringify({ + department: { billing: 0.9, technical: 0.1 }, + escalate: { false: 0.2, true: 0.8 }, + severity: { "0": 0.1, "1": 0.7, "2": 0.2, "3": 0 }, +}); + +describe("label — parseTeacherRow", () => { + test("parses a full teacher reply into normalized answers", () => { + const { answers, missing } = parseTeacherRow(TEACHER_CONTENT, WORKLOAD.questions); + expect(missing).toEqual([]); + expect(answers.department.probabilities).toEqual({ billing: 0.9, technical: 0.1 }); + expect(answers.escalate.noul).toBe(0.8); + expect(answers.escalate.probabilities).toEqual({ false: 0.2, true: 0.8 }); + expect(answers.severity.probabilities).toEqual({ "0": 0.1, "1": 0.7, "2": 0.2, "3": 0 }); + }); + + test("normalizes unnormalized weights and rounds to 4 decimals", () => { + const content = JSON.stringify({ + department: { billing: 0.4, technical: 0.4 }, + escalate: { false: 0.1, true: 0.3 }, + severity: { "0": 0.3, "1": 0.3, "2": 0.3, "3": 0 }, + }); + const { answers, missing } = parseTeacherRow(content, WORKLOAD.questions); + expect(missing).toEqual([]); + expect(answers.department.probabilities).toEqual({ billing: 0.5, technical: 0.5 }); + expect(answers.escalate.noul).toBe(0.75); + expect(answers.severity.probabilities).toEqual({ + "0": 0.3333, + "1": 0.3333, + "2": 0.3333, + "3": 0, + }); + }); + + test("non-JSON reply marks every question missing", () => { + const { answers, missing } = parseTeacherRow("没有 JSON", WORKLOAD.questions); + expect(answers).toEqual({}); + expect(missing).toEqual(["department", "escalate", "severity"]); + }); + + test("one invalid distribution only marks that question missing", () => { + const content = JSON.stringify({ + department: { billing: 1.2, technical: 0 }, + escalate: { false: 0.2, true: 0.8 }, + severity: { "0": 0.1, "1": 0.7, "2": 0.2, "3": 0 }, + }); + const { answers, missing } = parseTeacherRow(content, WORKLOAD.questions); + expect(missing).toEqual(["department"]); + expect(answers.department).toBeUndefined(); + expect(answers.escalate.noul).toBe(0.8); + }); +}); + +describe("parse — parseStateItems", () => { + test("keeps schema-complete items and attaches the matching plan", () => { + const { items, invalid } = parseStateItems(GEN_CONTENT, GROUP, SCHEMA_FIELDS); + expect(invalid).toBe(false); + expect(items).toHaveLength(2); + expect(items[0]).toEqual({ state: STATE, plan: GROUP[0] }); + expect(items[1].plan).toBe(GROUP[1]); + }); + + test("count mismatch or non-JSON marks the whole batch invalid", () => { + const short = JSON.stringify({ samples: [STATE] }); + expect(parseStateItems(short, GROUP, SCHEMA_FIELDS)).toEqual({ items: [], invalid: true }); + expect(parseStateItems("纯文本", GROUP, SCHEMA_FIELDS)).toEqual({ items: [], invalid: true }); + }); + + test("items missing schema fields are skipped individually, not invalid", () => { + const content = JSON.stringify({ + samples: [STATE, { ticket_id: "T-2", content: " " }], + }); + const { items, invalid } = parseStateItems(content, GROUP, SCHEMA_FIELDS); + expect(invalid).toBe(false); + expect(items).toHaveLength(1); + expect(items[0].state).toEqual(STATE); + }); +}); diff --git a/packages/core/tests/dataset-validate.test.ts b/packages/core/tests/dataset-validate.test.ts index 5a3f3c29..ac66a3b2 100644 --- a/packages/core/tests/dataset-validate.test.ts +++ b/packages/core/tests/dataset-validate.test.ts @@ -332,6 +332,81 @@ describe("validateDataset — decision schema", () => { expect(result.valid).toBe(true); expect(codes(result).errors).not.toContain("DECISION_INVALID_QUESTIONS"); }); + + const decisionBaseline = JSON.parse(DECISION_OK) as { + state: unknown; + questions: Record>; + }; + + function decisionVariant(questions: Record>): string { + return JSON.stringify({ state: decisionBaseline.state, questions }); + } + + test("repeated identical decision records produce no drift warning", async () => { + const datasetPath = file("decision_consistent.jsonl", [DECISION_OK, DECISION_OK, DECISION_OK]); + const result = await validateDataset(datasetPath, { fullValidate: true }); + expect(result.valid).toBe(true); + expect(codes(result).warnings).not.toContain("DECISION_QUESTION_DRIFT"); + }); + + test("changed instructions on a later record warn DECISION_QUESTION_DRIFT (not an error)", async () => { + const drifted = decisionVariant({ + ...decisionBaseline.questions, + department: { ...decisionBaseline.questions.department, instructions: "换了一个问法?" }, + }); + const datasetPath = file("decision_drift.jsonl", [DECISION_OK, drifted]); + const result = await validateDataset(datasetPath, { fullValidate: true }); + expect(result.valid).toBe(true); + const driftWarnings = result.warnings.filter( + (warning) => warning.code === "DECISION_QUESTION_DRIFT", + ); + expect(driftWarnings).toHaveLength(1); + expect(driftWarnings[0].message).toContain("department"); + expect(driftWarnings[0].message).toContain("重新准备数据并重训"); + expect(driftWarnings[0]).toMatchObject({ line: 2, path: "questions" }); + }); + + test("criteria key order does not count as drift", async () => { + const reordered = decisionVariant({ + ...decisionBaseline.questions, + department: { + ...decisionBaseline.questions.department, + criteria: { technical: "产品故障问题", billing: "支付和账单问题" }, + label: "technical", + target: { technical: 0.9, billing: 0.1 }, + }, + }); + const datasetPath = file("decision_reordered.jsonl", [DECISION_OK, reordered]); + const result = await validateDataset(datasetPath, { fullValidate: true }); + expect(result.valid).toBe(true); + expect(codes(result).warnings).not.toContain("DECISION_QUESTION_DRIFT"); + }); + + test("a missing question ID on a later record is reported as drift", async () => { + const subset = decisionVariant({ + escalate: decisionBaseline.questions.escalate, + severity: decisionBaseline.questions.severity, + }); + const datasetPath = file("decision_subset.jsonl", [DECISION_OK, subset]); + const result = await validateDataset(datasetPath, { fullValidate: true }); + expect(result.valid).toBe(true); + const driftWarnings = result.warnings.filter( + (warning) => warning.code === "DECISION_QUESTION_DRIFT", + ); + expect(driftWarnings).toHaveLength(1); + expect(driftWarnings[0].message).toContain("department"); + }); + + test("mixed ChatML + decision file: session survives other-schema records", async () => { + const drifted = decisionVariant({ + ...decisionBaseline.questions, + escalate: { ...decisionBaseline.questions.escalate, instructions: "另一个问法?" }, + }); + const datasetPath = file("decision_mixed.jsonl", [DECISION_OK, SFT_OK, drifted]); + const result = await validateDataset(datasetPath, { fullValidate: true }); + expect(result.valid).toBe(true); + expect(codes(result).warnings).toContain("DECISION_QUESTION_DRIFT"); + }); }); describe("validateDataset — CPT schema", () => { diff --git a/packages/core/tests/finetune-preflight.test.ts b/packages/core/tests/finetune-preflight.test.ts index dd1580b1..2e31ca7b 100644 --- a/packages/core/tests/finetune-preflight.test.ts +++ b/packages/core/tests/finetune-preflight.test.ts @@ -1,8 +1,10 @@ import { describe, expect, test } from "vite-plus/test"; import { getFineTuneHyperParameterDefaultNumber, + INSUFFICIENT_DECISION_SAMPLES_CODE, INSUFFICIENT_SAMPLES_CODE, preflightBatchSizeGate, + preflightDecisionSampleGate, validateFineTuneHyperParameterOverrides, type FineTuneParamHyperParam, } from "../src/index.ts"; @@ -52,6 +54,100 @@ describe("preflightBatchSizeGate", () => { }); }); +describe("preflightDecisionSampleGate", () => { + test("with validation: train and val each at batch_size pass (>= rule)", () => { + const result = preflightDecisionSampleGate({ + hasValidation: true, + trainingRecordCount: 8, + validationRecordCount: 8, + batchSize: 8, + }); + expect(result.ok).toBe(true); + expect(result.issue).toBeUndefined(); + expect(result.hint).toBeUndefined(); + }); + + test("with validation: a short validation set fails even when train is large", () => { + const result = preflightDecisionSampleGate({ + hasValidation: true, + trainingRecordCount: 1000, + validationRecordCount: 7, + batchSize: 8, + }); + expect(result.ok).toBe(false); + expect(result.issue!.severity).toBe("error"); + expect(result.issue!.code).toBe(INSUFFICIENT_DECISION_SAMPLES_CODE); + expect(result.issue!.message).toMatch( + /validation dataset has 7 sample\(s\), requires at least 8/, + ); + expect(result.issue!.message).toMatch(/验证集仅 7 条样本/); + }); + + test("with validation: training minimum is batch_size, not batch_size x 10", () => { + const result = preflightDecisionSampleGate({ + hasValidation: true, + trainingRecordCount: 7, + validationRecordCount: 8, + batchSize: 8, + }); + expect(result.ok).toBe(false); + expect(result.issue!.message).toMatch( + /training dataset has 7 sample\(s\), requires at least 8/, + ); + }); + + test("training only: passes at the batch_size x 10 boundary", () => { + expect( + preflightDecisionSampleGate({ + hasValidation: false, + trainingRecordCount: 80, + batchSize: 8, + }).ok, + ).toBe(true); + }); + + test("training only: one sample below batch_size x 10 fails", () => { + const result = preflightDecisionSampleGate({ + hasValidation: false, + trainingRecordCount: 79, + batchSize: 8, + }); + expect(result.ok).toBe(false); + expect(result.issue!.message).toMatch(/requires at least 80/); + expect(result.issue!.message).toMatch(/至少需要 80 条/); + expect(result.hint).toMatch(/batch_size × 10/); + expect(result.hint).toMatch(/决策模型要求/); + }); + + test("unknown counts fall through to the platform (bare file-id flows)", () => { + expect(preflightDecisionSampleGate({ hasValidation: true, batchSize: 8 }).ok).toBe(true); + expect(preflightDecisionSampleGate({ hasValidation: false, batchSize: 8 }).ok).toBe(true); + // Only the known part is checked: unknown train count + short val set. + const result = preflightDecisionSampleGate({ + hasValidation: true, + validationRecordCount: 3, + batchSize: 8, + }); + expect(result.ok).toBe(false); + expect(result.issue!.message).toMatch(/validation dataset/); + expect(result.issue!.message).not.toMatch(/training dataset/); + }); + + test("reports both failing parts in one bilingual issue", () => { + const result = preflightDecisionSampleGate({ + hasValidation: true, + trainingRecordCount: 2, + validationRecordCount: 3, + batchSize: 8, + }); + expect(result.ok).toBe(false); + expect(result.issue!.message).toMatch(/training dataset has 2/); + expect(result.issue!.message).toMatch(/validation dataset has 3/); + expect(result.issue!.message).toMatch(/训练集仅 2 条样本/); + expect(result.issue!.message).toMatch(/验证集仅 3 条样本/); + }); +}); + const schema: FineTuneParamHyperParam[] = [ { name: "batch_size", diff --git a/packages/core/tests/finetune-profile-decision.test.ts b/packages/core/tests/finetune-profile-decision.test.ts new file mode 100644 index 00000000..7688bd01 --- /dev/null +++ b/packages/core/tests/finetune-profile-decision.test.ts @@ -0,0 +1,184 @@ +import { afterAll, describe, expect, test } from "vite-plus/test"; +import { mkdirSync, rmSync, writeFileSync } from "fs"; +import { join } from "path"; +import { tmpdir } from "os"; +import { + compareDecisionQuestionTables, + decisionQuestionSignature, + decisionQuestionTableSignature, + getProfile, + readDecisionQuestionSignature, +} from "../src/index.ts"; + +const tmp = join(tmpdir(), `bl-decision-profile-test-${process.pid}`); +mkdirSync(tmp, { recursive: true }); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +function file(name: string, lines: string[]): string { + const filePath = join(tmp, name); + writeFileSync(filePath, lines.join("\n")); + return filePath; +} + +const profile = getProfile("sft-lora"); + +const DECISION_RECORD = JSON.stringify({ + state: "客户投诉发票抬头写错了。", + questions: { + team: { + type: "choice", + instructions: "应该由哪个团队处理?", + criteria: { billing: "支付和账单问题", technical: "产品故障问题" }, + label: "billing", + }, + }, +}); + +describe("sft-lora profile — decision modality", () => { + test("server training type stays efficient_sft", () => { + expect(profile.serverTrainingType).toBe("efficient_sft"); + }); + + test("validate routes .jsonl through the decision schema", async () => { + const validPath = file("decision_valid.jsonl", [DECISION_RECORD]); + const validResult = await profile.validate(validPath, "decision", { fullValidate: true }); + expect(validResult.valid).toBe(true); + + // A bad choice label is a decision-schema error — proves the routing did + // not fall through to ChatML (which would report missing messages). + const invalidPath = file("decision_invalid_label.jsonl", [ + JSON.stringify({ + state: "x", + questions: { + team: { + type: "choice", + instructions: "team?", + criteria: { billing: "账单", technical: "技术" }, + label: "sales", + }, + }, + }), + ]); + const invalidResult = await profile.validate(invalidPath, "decision", { fullValidate: true }); + expect(invalidResult.valid).toBe(false); + expect(invalidResult.errors.map((issue) => issue.code)).toContain( + "DECISION_INVALID_CHOICE_LABEL", + ); + }); + + test("non-.jsonl files are rejected with DECISION_UNSUPPORTED_FORMAT", async () => { + const result = await profile.validate(join(tmp, "decision.zip"), "decision", {}); + expect(result.valid).toBe(false); + expect(result.errors).toHaveLength(1); + expect(result.errors[0].code).toBe("DECISION_UNSUPPORTED_FORMAT"); + expect(result.errors[0].message).toContain(".jsonl"); + }); + + test("resolveHyperParameters sends documented defaults and honors the three decision knobs", () => { + // The API requires hyper_parameters in the request body ("n_epochs is + // required"), so omitted knobs are filled with the documented defaults. + expect(profile.resolveHyperParameters("decision", {})).toEqual({ + n_epochs: 2, + batch_size: 1, + learning_rate: "2e-5", + }); + expect( + profile.resolveHyperParameters("decision", { + nEpochs: 3, + batchSize: 2, + learningRate: "1e-4", + }), + ).toEqual({ n_epochs: 3, batch_size: 2, learning_rate: "1e-4" }); + // Text-only knobs must not leak into the decision request body. + expect( + profile.resolveHyperParameters("decision", { loraRank: 16, split: 0.9, evalSteps: 50 }), + ).toEqual({ n_epochs: 2, batch_size: 1, learning_rate: "2e-5" }); + }); + + test("skips the generic batch-size gate and the capability check", () => { + expect(profile.shouldSkipGate("batch_size", "decision")).toBe(true); + expect(profile.shouldSkipGate("batch_size", "text")).toBe(false); + expect(profile.shouldSkipCapabilityCheck("decision")).toBe(true); + expect(profile.shouldSkipCapabilityCheck("text")).toBe(false); + }); +}); + +describe("decision question signatures", () => { + const baseQuestion = { + type: "choice", + instructions: "哪个团队?", + criteria: { billing: "账单", technical: "技术" }, + label: "billing", + target: { billing: 0.9, technical: 0.1 }, + }; + + test("label/target and criteria key order do not affect the signature", () => { + const variant = { + criteria: { technical: "技术", billing: "账单" }, + instructions: "哪个团队?", + type: "choice", + label: "technical", + }; + expect(decisionQuestionSignature(variant)).toBe(decisionQuestionSignature(baseQuestion)); + }); + + test("type, instructions and criteria changes all change the signature", () => { + const baseline = decisionQuestionSignature(baseQuestion); + expect(decisionQuestionSignature({ ...baseQuestion, type: "noul" })).not.toBe(baseline); + expect(decisionQuestionSignature({ ...baseQuestion, instructions: "换个问法" })).not.toBe( + baseline, + ); + expect(decisionQuestionSignature({ ...baseQuestion, criteria: { billing: "账单" } })).not.toBe( + baseline, + ); + }); + + test("non-object questions and tables yield undefined; non-object entries are skipped", () => { + expect(decisionQuestionSignature("nope")).toBeUndefined(); + expect(decisionQuestionTableSignature([1, 2])).toBeUndefined(); + const table = decisionQuestionTableSignature({ team: baseQuestion, broken: "nope" }); + expect(table).toBeDefined(); + expect([...table!.keys()]).toEqual(["team"]); + }); + + test("compare reports added, missing and changed IDs, sorted", () => { + const baseline = decisionQuestionTableSignature({ + alpha: baseQuestion, + beta: baseQuestion, + gamma: baseQuestion, + })!; + const other = decisionQuestionTableSignature({ + beta: { ...baseQuestion, instructions: "改了" }, + gamma: baseQuestion, + delta: baseQuestion, + })!; + expect(compareDecisionQuestionTables(baseline, other)).toEqual(["alpha", "beta", "delta"]); + expect(compareDecisionQuestionTables(baseline, baseline)).toEqual([]); + }); +}); + +describe("readDecisionQuestionSignature", () => { + test("reads the first non-blank record's question table", async () => { + const filePath = file("signature_ok.jsonl", ["", DECISION_RECORD, DECISION_RECORD]); + const signature = await readDecisionQuestionSignature(filePath); + const expected = decisionQuestionTableSignature(JSON.parse(DECISION_RECORD).questions); + expect(signature).toEqual(expected); + }); + + test("returns undefined for malformed JSON, non-decision records and empty files", async () => { + expect( + await readDecisionQuestionSignature(file("signature_bad_json.jsonl", ["{oops"])), + ).toBeUndefined(); + const chatmlPath = file("signature_chatml.jsonl", [ + '{"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"}]}', + ]); + expect(await readDecisionQuestionSignature(chatmlPath)).toBeUndefined(); + expect( + await readDecisionQuestionSignature(file("signature_empty.jsonl", ["", ""])), + ).toBeUndefined(); + }); + + test("returns undefined for an unreadable file instead of throwing", async () => { + expect(await readDecisionQuestionSignature(join(tmp, "does-not-exist.jsonl"))).toBeUndefined(); + }); +}); diff --git a/packages/core/tests/finetune-train-options.test.ts b/packages/core/tests/finetune-train-options.test.ts new file mode 100644 index 00000000..fe6b1038 --- /dev/null +++ b/packages/core/tests/finetune-train-options.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, test } from "vite-plus/test"; +import { + fetchModelTrainOptions, + MODEL_TRAIN_OPTIONS_API, + resolveTrainOptions, + type ModelTrainOptions, +} from "../src/index.ts"; + +const DYNAMIC_MODEL = "qwen3.6-plus-base-2026-04-02"; + +function trainOptions(overrides: Partial = {}): ModelTrainOptions { + return { + enabled: true, + optionKeys: ["modality", "reasoning_mode"], + optionDefinitions: [ + // editable=false mirrors the console contract; combination authority is + // supportedCombinations, so passing a supported value must still pass. + { 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" }], + ...overrides, + }; +} + +function gatewayEnvelope(entries: unknown[]): unknown { + return { + code: "200", + successResponse: true, + data: { + success: true, + DataV2: { + ret: ["SUCCESS::ok"], + data: { code: "200", data: entries, success: true }, + }, + }, + }; +} + +describe("fetchModelTrainOptions", () => { + test("requests the console API with the model and server training type", async () => { + const calls: Array<{ api: string; data: Record }> = []; + const options = await fetchModelTrainOptions( + async (api, data) => { + calls.push({ api, data }); + return gatewayEnvelope([{ model: DYNAMIC_MODEL, trainingOptions: trainOptions() }]); + }, + DYNAMIC_MODEL, + "cpt", + ); + expect(calls).toEqual([ + { + api: MODEL_TRAIN_OPTIONS_API, + data: { input: { models: [DYNAMIC_MODEL], trainingType: "cpt" } }, + }, + ]); + expect(options?.defaults).toEqual({ modality: "vision", reasoning_mode: "instruct" }); + }); + + test("returns null when the model is absent (no dynamic options)", async () => { + const options = await fetchModelTrainOptions( + async () => gatewayEnvelope([]), + "qwen3-8b", + "sft", + ); + expect(options).toBeNull(); + }); + + test("returns null when trainingOptions.enabled is not true", async () => { + const options = await fetchModelTrainOptions( + async () => + gatewayEnvelope([ + { model: DYNAMIC_MODEL, trainingOptions: trainOptions({ enabled: false }) }, + ]), + DYNAMIC_MODEL, + "cpt", + ); + expect(options).toBeNull(); + }); + + test("tolerates an object wrapper around the entries array", async () => { + const options = await fetchModelTrainOptions( + async () => ({ + data: { + DataV2: { + data: { data: { data: [{ model: DYNAMIC_MODEL, trainingOptions: trainOptions() }] } }, + }, + }, + }), + DYNAMIC_MODEL, + "cpt", + ); + expect(options?.enabled).toBe(true); + }); +}); + +describe("resolveTrainOptions", () => { + test("no options and no user flags yields an empty context", () => { + expect(resolveTrainOptions(null, {})).toEqual({ context: {}, issues: [] }); + }); + + test("user flags on a model without dynamic options are not_configured", () => { + const { context, issues } = resolveTrainOptions(null, { modality: "vision" }); + expect(context).toEqual({}); + expect(issues).toEqual([{ code: "not_configured" }]); + }); + + test("omitted options are completed from the model defaults", () => { + const { context, issues } = resolveTrainOptions(trainOptions(), {}); + expect(issues).toEqual([]); + expect(context).toEqual({ modality: "vision", reasoning_mode: "instruct" }); + }); + + test("a partial user selection merges with defaults", () => { + const options = trainOptions({ + supportedCombinations: [ + { modality: "vision", reasoning_mode: "instruct" }, + { modality: "vision", reasoning_mode: "thinking" }, + ], + }); + const { context, issues } = resolveTrainOptions(options, { reasoning_mode: "thinking" }); + expect(issues).toEqual([]); + expect(context).toEqual({ modality: "vision", reasoning_mode: "thinking" }); + }); + + test("a value outside supportValues is unsupported_value", () => { + const { issues } = resolveTrainOptions(trainOptions(), { modality: "text" }); + expect(issues).toEqual([ + { code: "unsupported_value", key: "modality", value: "text", expected: ["vision"] }, + ]); + }); + + test("an unknown option key is unsupported_value", () => { + const { issues } = resolveTrainOptions(trainOptions(), { audio: "x" }); + expect(issues[0]?.code).toBe("unsupported_value"); + expect(issues[0]?.key).toBe("audio"); + }); + + test("a supported value outside supportedCombinations is invalid_combination", () => { + const options = trainOptions({ + optionDefinitions: [ + { name: "modality", supportValues: ["vision"] }, + { name: "reasoning_mode", supportValues: ["instruct", "thinking"] }, + ], + }); + const { context, issues } = resolveTrainOptions(options, { reasoning_mode: "thinking" }); + expect(context).toEqual({}); + expect(issues).toEqual([ + { + code: "invalid_combination", + combinations: [{ modality: "vision", reasoning_mode: "instruct" }], + }, + ]); + }); + + test("editable=false does not block a supported value (combinations are authoritative)", () => { + const { context, issues } = resolveTrainOptions(trainOptions(), { modality: "vision" }); + expect(issues).toEqual([]); + expect(context.modality).toBe("vision"); + }); +}); diff --git a/packages/kscli/package.json b/packages/kscli/package.json index bb59f73a..ed406e44 100644 --- a/packages/kscli/package.json +++ b/packages/kscli/package.json @@ -1,6 +1,6 @@ { "name": "knowledge-studio-cli", - "version": "2.11.1", + "version": "2.11.2", "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 821d8dba..83e7443c 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-runtime", - "version": "2.11.1", + "version": "2.11.2", "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 5f707b45..9bcddca7 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-cli metadata: - version: "2.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-finetune/SKILL.md b/skills/bailian-finetune/SKILL.md index ebc97c73..963665a3 100644 --- a/skills/bailian-finetune/SKILL.md +++ b/skills/bailian-finetune/SKILL.md @@ -1,15 +1,16 @@ --- name: bailian-finetune metadata: - version: "2.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >- 阿里云百炼模型精调训练入口:用户要精调、微调、训练自己的模型(fine-tune,支持 SFT / SFT-LoRA / DPO / DPO-LoRA / CPT, - 覆盖文本、语音、图像)、校验或上传训练数据集、看训练进度和日志、挑 checkpoint、导出精调产物、 + 覆盖文本、语音、图像、决策模型)、校验或上传训练数据集、看训练进度和日志、挑 checkpoint、导出精调产物、 把专属模型部署成服务时使用 `bl dataset` / `bl finetune` / `bl deploy`。链路是 validate 校验数据 → upload 拿 file-id → finetune create 建任务 → watch 看进度 → export 导出 → 可选 compress 量化压缩 → deploy 上线,需要 API key; Console 版本状态与独立部署服务查询使用 Console 鉴权。 + 决策模型微调(choice/noul/score 决策数据,state+questions+label)走 `bl finetune decision create`,固定 efficient_sft。 百炼模型智能路由(智能选模、smart routing / model routing)的路由版本查询、服务创建、配置更新与服务删除也由本 skill 承接,不要求先精调。 百炼吞吐预留(PTU)、ModelCode 容量购买、扩缩容、续费、释放、退订与溢出策略也由本 skill 承接,不要求先精调。 强化学习(RL)训练走 `bl finetune rl`,在隔离沙箱内执行,需先 `bl finetune runtime prepare` 准备运行时(沙箱仅支持 macOS / Linux); @@ -35,7 +36,7 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-f ## End-to-end workflow (follow in order) ``` -1. Validate data bl dataset validate --file train.jsonl [--schema chatml|dpo|cpt|tts|image] +1. Validate data bl dataset validate --file train.jsonl [--schema chatml|dpo|cpt|decision|tts|image] 2. Upload data bl dataset upload --file train.jsonl # returns a file-id 3. Create job bl finetune text|audio|image create --base-model --datasets 4. Watch progress bl finetune watch --job-id ft-xxx # or get / logs @@ -54,40 +55,43 @@ 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`) | -| 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` | -| 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` | -| 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` | +| 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 ` | 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. @@ -97,6 +101,82 @@ Console reads are separate from API-key file/deployment queries; the API Key / ` Flags, usage, and examples: see [`reference/`](reference/index.md) or `bl --help` — do not guess flags. +## Decision data preparation + +`bl dataset split` and `bl dataset generate` prepare decision-model training data (`--schema decision` only today; future modalities extend the same commands). Chain: `dataset generate` (or `split` on already-labelled data) → `dataset validate --schema decision` → `finetune decision create`. + +- `bl dataset split --input labeled.jsonl [--out-dir ] [--prefix tickets] [--seed 0] [--dev-ratio 0.15] [--workload workload.json | --id-fields a,b]` — keyless, zero cost: dedupes states (ignoring `id_fields`, default `ticket_id`), requires ≥7 records, seeded shuffle, writes `.train.jsonl` / `.development.jsonl` and self-checks the train split. Duplicate states or too few records are usage errors; `--dry-run` previews counts without writing. +- `bl dataset generate --workload workload.json [--samples 200] [--unknowable 0] [--model qwen3.8-max] [--batch 5] [--concurrency 8] [--target-temp 1.5] [--out-dir data]` — teacher pipeline: balanced state synthesis → per-state probability labelling → hard labels + smoothed soft targets (`--no-soft-target` for hard only) → 15% development split → manifest (workload sha256, label balance, generator/teacher agreement, usage). Generation and labelling call the teacher model and consume tokens (billing applies); preview plans and prompts with `--dry-run` (zero network). + - Modes: `--states-only` stops after synthesis (no labelling spend); `--from-states ` labels existing `{state, plan?}` JSONL; `--from-states` + `--resume-raw ` skips already-labelled states to continue an interrupted run; `--from-raw ` re-converts saved teacher labels with zero API calls (e.g. to adjust `--target-temp`). + - workload.json: field rules and a complete three-question example — see [workload.json format](#workloadjson-format) below. + - Crash resilience: states append per batch, labels per row; bad batches and invalid teacher distributions are skipped with warnings. Labelling forces `enable_search=false`. The shuffle PRNG differs from Python `random.Random` — the same seed reproduces results within this CLI only. The state token-budget check is skipped (needs the Python transformers tokenizer). +- Flags, usage, and examples: see [`reference/dataset.md`](reference/dataset.md) or `bl dataset split --help` / `bl dataset generate --help`. + +### workload.json format + +Complete example (one question of each type; copy and adapt to your business — field names are free to rename): + +```json +{ + "name": "cloud-support-zh", + "description": "客服工单分流:判断处理团队、是否升级、严重程度", + "state_schema": { + "ticket_id": "工单编号", + "content": "工单正文,包含客户问题与关键事实" + }, + "id_fields": ["ticket_id"], + "questions": { + "team": { + "type": "choice", + "instructions": "应该由哪个团队处理?", + "criteria": { "billing": "账单与支付问题", "technical": "产品故障问题" } + }, + "escalate": { + "type": "noul", + "instructions": "是否需要升级处理?", + "criteria": { "false": "常规流程可解决", "true": "涉及退款或投诉,需升级" } + }, + "severity": { + "type": "score", + "instructions": "问题严重程度", + "criteria": ["轻微", "一般", "严重", "紧急"] + } + }, + "guidance": ["涉及退款一律升级"], + "axes": { "team": ["billing", "technical"], "severity": [0, 1, 2, 3] }, + "difficulty_hints": { "clean": "信息完整,判断依据明确。" } +} +``` + +| Field | Required | Rules | +| ------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `questions` | yes | Non-empty object keyed by question ID. Same definition format as training records and online `bl decision` requests — keep ID / type / instructions / criteria identical across train, eval and serving. | +| `description` | generation mode | Non-empty business goal; tells the generator what to synthesize. | +| `state_schema` | generation mode | At least one input field; each value is a non-empty content-requirement string. Generated states carry exactly these fields. | +| `name` / `language` | no | Free-form metadata. | +| `id_fields` | no | Record-id fields ignored by dedup; default `["ticket_id"]`; set `[]` when states have no ids. | +| `guidance` | no | String array of business rules appended to the teacher prompt. | +| `axes` | no | Axis → non-empty value array; the balanced cross product is cycled to `--samples`. A profile field named after a question ID is the expected answer (score: 0-based level index). | +| `difficulty_hints` | no | Overrides the built-in generation hints for `clean` / `unknowable` profiles. | + +Question types (`instructions` is an optional string for all three): + +- `choice`: `criteria` is an option-name → description object, 1–255 options, names and descriptions non-empty strings; hard label = option name. +- `noul`: `criteria` optional; when provided, an object with only `"true"` / `"false"` string descriptions; hard label = true/false. +- `score`: `criteria` is an array of 2–255 non-empty level descriptions, low → high; hard label = 0-based level index. + +`--unknowable` appends evidence-free states (no axis fields) whose targets stay uniform. All workload validation runs before any API call and reports bilingual usage errors; preview the resulting plans and prompts with `--dry-run`. + +## Decision-model fine-tuning + +`bl finetune decision create` trains the decision model (`decision-model-preview-2026-09-24`, account-whitelisted preview) with fixed `efficient_sft` (LoRA high-efficiency training; no full-parameter option). Only `--n-epochs` / `--batch-size` / `--learning-rate` are overridable; omitted values are sent with the documented defaults (2 / 1 / "2e-5"), which the API requires in the request body. `--suffix` is limited to 8 characters. + +- Data: JSONL, each record `{state, questions}`. Every question needs a hard `label` (choice: an option name; noul: true/false; score: a 0-based level index) and may carry a `target` soft-label distribution covering all options, probabilities in [0, 1] summing to 1. Validate with `bl dataset validate --file train.jsonl --schema decision` (auto-detect also works). +- Sample-count rule (CLI fails fast before upload): with a separate `--validations` set, train and validation samples must each be ≥ batch_size; with training data only, samples ≥ batch_size × 10. Hundreds of samples are recommended. +- Keep question definitions (ID, type, instructions, criteria) identical across training, evaluation and online requests — changing them shifts the distribution and requires regenerating data and retraining. The CLI warns on cross-record drift (`DECISION_QUESTION_DRIFT`) and train/validation mismatch (`DECISION_QUESTION_DEFINITION_MISMATCH`); warnings do not block. +- After training: `bl finetune watch` / `checkpoints` / `export` as usual, then deploy with `bl deploy text create --model-name --display-name --plan mu --capacity 1` (MU spec auto-picked; high-risk — preview with `--dry-run`, then confirm per protocol), and invoke with `bl decision --model ` (owned by `bailian-cli`; `--request-file` reuses a training sample and strips label/target automatically). +- Flags, usage, and examples: see [`reference/finetune.md`](reference/finetune.md) or `bl finetune decision create --help`. + ## RL sandbox / OPD distillation training `bl finetune rl` submits reinforcement-learning jobs with the DashScope SDK inside an isolated sandbox (credential deny-read, home redirect, whitelist proxy), so the host Python environment is never used. The sandbox is a local black box: on first run it downloads and verifies a fixed CPython + dashscope runtime from a bundled reviewed manifest, caches it, and reuses the cache afterwards. diff --git a/skills/bailian-finetune/reference/dataset.md b/skills/bailian-finetune/reference/dataset.md index 5424c46c..061bd6d6 100644 --- a/skills/bailian-finetune/reference/dataset.md +++ b/skills/bailian-finetune/reference/dataset.md @@ -7,15 +7,17 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Authentication | Description | -| --------------------- | -------------- | ------------------------------------------------------------------ | -| `bl dataset delete` | API Key | Delete a dataset file by ID | -| `bl dataset get` | API Key | Get details of a single dataset file | -| `bl dataset groups` | Console | List Console dataset groups | -| `bl dataset list` | API Key | List uploaded dataset files | -| `bl dataset upload` | API Key | Upload a dataset file (.jsonl or .zip) to Bailian | -| `bl dataset validate` | No Auth | Locally validate a dataset file (.jsonl or .zip) without uploading | -| `bl dataset version` | Console | List Console dataset versions by group or get one version by ID | +| Command | Authentication | Description | +| --------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `bl dataset delete` | API Key | Delete a dataset file by ID | +| `bl dataset generate` | API Key | Generate decision training data with a teacher model: synthesize states, label probabilities, convert soft targets, split, and write a manifest | +| `bl dataset get` | API Key | Get details of a single dataset file | +| `bl dataset groups` | Console | List Console dataset groups | +| `bl dataset list` | API Key | List uploaded dataset files | +| `bl dataset split` | No Auth | Split labeled decision JSONL into train/development files locally (dedup + seeded shuffle, no API calls) | +| `bl dataset upload` | API Key | Upload a dataset file (.jsonl or .zip) to Bailian | +| `bl dataset validate` | No Auth | Locally validate a dataset file (.jsonl or .zip) without uploading | +| `bl dataset version` | Console | List Console dataset versions by group or get one version by ID | ## Command details @@ -56,6 +58,76 @@ bl dataset delete --file-id file-id-xxx --dry-run bl dataset delete --file-id file-id-xxx --yes ``` +### `bl dataset generate` + +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `dataset generate` | +| **Description** | Generate decision training data with a teacher model: synthesize states, label probabilities, convert soft targets, split, and write a manifest | +| **Authentication** | API Key | +| **Usage** | `bl dataset generate --workload [--samples ] [--unknowable ] [--out-dir ] [--prefix ] [--model ] [--seed ] [--batch ] [--concurrency ] [--target-temp ] [--no-soft-target] [--states-only \| --from-states [--resume-raw ] \| --from-raw ] [--schema decision]` | + +#### Flags + +| Flag | Type | Required | Description | +| ---------------------- | ------ | -------- | ---------------------------------------------------------------------------------------------------- | +| `--workload ` | string | no | workload.json business config (required). Every field's meaning and format is listed in Notes below. | +| `--samples ` | number | no | Ordinary samples to generate (default: 200) | +| `--unknowable ` | number | no | Extra evidence-free states with uniform targets (default: 0) | +| `--out-dir ` | string | no | Output directory (default: data) | +| `--prefix ` | string | no | Output file name prefix (default: tickets) | +| `--model ` | string | no | Teacher/generator model (default: qwen3.8-max) | +| `--seed ` | number | no | Shuffle seed for plans and split (default: 0) | +| `--batch ` | number | no | States per generation call (default: 5) | +| `--concurrency ` | number | no | Parallel API calls (default: 8) | +| `--target-temp ` | number | no | Soft-target smoothing temperature; 1.0 keeps the teacher distribution (default: 1.5) | +| `--no-soft-target` | switch | no | Hard labels only (unknowable rows keep uniform targets) | +| `--states-only` | switch | no | Stop after generating states; no labelling spend | +| `--from-states ` | string | no | Label an existing JSONL of {state, plan?} records instead of generating | +| `--resume-raw ` | string | no | With --from-states: skip states already labelled in this raw file | +| `--from-raw ` | string | no | Zero API calls: re-convert saved teacher labels (e.g. to adjust --target-temp) | +| `--schema ` | string | no | Record schema. Only "decision" (state/questions) is supported today. | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Only decision-model data (state/questions records) is supported today; --schema accepts "decision" only. +- Generation and labelling call the teacher model and consume tokens (billing applies). Use --dry-run to preview plans and prompts, --states-only to stop before labelling spend, or --from-raw for a zero-API re-conversion. +- workload.json field reference (meaning + format). Full annotated example: bailian-finetune skill, "workload.json format". +- questions (required): the question table, id → {type, criteria, instructions?}. choice: criteria is an object of 1–255 "option name → description"; score: criteria is an array of 2–255 level descriptions ordered low → high; noul: criteria optional, only "true"/"false" keys. instructions is optional free text. +- description (required for generation): one sentence describing the input business data; injected into the generation prompt. +- state_schema (required for generation): input field name → non-empty example value; field names appear verbatim in every generated state. +- id_fields (optional, default ["ticket_id"]): state key fields used for dedup and resume; values are record ids, not model input. +- axes (optional): profile axis name → value list, for balanced generation. An axis named after a question id is the intended answer (score axes use 0-based level indices); axes you omit are randomized. +- guidance (optional): business rules injected into both the generation and labelling prompts. +- difficulty_hints (optional): clean / unknowable keys override the built-in generation difficulty hints. +- Crash resilience: states append per batch and labels append per row; continue labelling with --from-states plus --resume-raw. Raw labels keep teacher probabilities so --from-raw can re-derive targets at a new --target-temp without any API call. +- Outputs .train.jsonl / .development.jsonl (15% development), .manifest.json (workload sha256, label balance, generator/teacher agreement, usage), and raw teacher labels under /raw. The state token-budget check is skipped (needs the Python transformers tokenizer). +- Labelling forces enable_search=false so probabilities depend only on the STATE. The shuffle PRNG differs from Python random.Random: the same seed reproduces results within this CLI only. Request timeout uses the global --timeout. + +#### Examples + +```bash +bl dataset generate --workload workload.json --samples 200 --unknowable 20 --out-dir output/demo +``` + +```bash +bl dataset generate --workload workload.json --samples 20 --dry-run +``` + +```bash +bl dataset generate --workload workload.json --states-only +``` + +```bash +bl dataset generate --workload workload.json --from-states data/states.jsonl --resume-raw data/raw/labeled.jsonl +``` + +```bash +bl dataset generate --workload workload.json --from-raw data/raw/labeled.jsonl --target-temp 1.0 +``` + ### `bl dataset get` | Field | Value | @@ -163,6 +235,54 @@ bl dataset list --page-size 20 bl dataset list --output json ``` +### `bl dataset split` + +| Field | Value | +| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `dataset split` | +| **Description** | Split labeled decision JSONL into train/development files locally (dedup + seeded shuffle, no API calls) | +| **Authentication** | No Auth | +| **Usage** | `bl dataset split --input [--out-dir ] [--prefix ] [--seed ] [--dev-ratio ] [--workload ] [--id-fields ] [--schema decision]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------- | ------ | -------- | ------------------------------------------------------------------------ | +| `--input ` | string | yes | Labeled JSONL file to split (use - for stdin) | +| `--out-dir ` | string | no | Output directory (default: output/custom) | +| `--prefix ` | string | no | Output file name prefix (default: tickets) | +| `--seed ` | number | no | Shuffle seed for a reproducible split (default: 0) | +| `--dev-ratio ` | number | no | Development share in (0, 1), floor(n * ratio) records (default: 0.15) | +| `--workload ` | string | no | workload.json used to read id_fields for dedup | +| `--id-fields ` | string | no | Comma-separated record-id fields ignored by dedup (overrides --workload) | +| `--schema ` | string | no | Record schema. Only "decision" (state/questions) is supported today. | + +#### Notes + +- Only decision-model data (state/questions records) is supported today; --schema accepts "decision" only. +- Dedup compares states ignoring record-id fields (id_fields from --workload, default ticket_id, or --id-fields); any duplicate state aborts with a usage error. +- At least 7 records are required so both output files are non-empty. +- development takes floor(n * --dev-ratio) records after a seeded shuffle; the rest go to train. The PRNG differs from Python random.Random, so the same seed reproduces splits within this CLI only. +- Outputs .train.jsonl and .development.jsonl under --out-dir, then self-checks them with the decision training schema; --dry-run previews counts without writing. + +#### Examples + +```bash +bl dataset split --input labeled.jsonl +``` + +```bash +bl dataset split --input labeled.jsonl --out-dir output/custom --prefix tickets +``` + +```bash +bl dataset split --input labeled.jsonl --workload workload.json --seed 42 +``` + +```bash +bl dataset split --input labeled.jsonl --dev-ratio 0.2 --dry-run +``` + ### `bl dataset upload` | Field | Value | diff --git a/skills/bailian-finetune/reference/finetune.md b/skills/bailian-finetune/reference/finetune.md index 5ded1589..abc9fd1a 100644 --- a/skills/bailian-finetune/reference/finetune.md +++ b/skills/bailian-finetune/reference/finetune.md @@ -21,6 +21,7 @@ Index: [index.md](index.md) | `bl finetune compress logs` | API Key | Get compression job logs | | `bl finetune compress templates` | API Key | List quantizable models and their compression templates | | `bl finetune compress watch` | API Key | Probe or follow a compression job's status | +| `bl finetune decision create` | API Key | Create a decision model fine-tune job (efficient_sft; choice/noul/score training data) | | `bl finetune delete` | API Key | Delete a fine-tune job record | | `bl finetune export` | API Key | Publish a checkpoint as a deployable model | | `bl finetune get` | API Key | Get details of a single fine-tune job | @@ -50,6 +51,7 @@ Index: [index.md](index.md) | `bl finetune runtime doctor` | No Auth | Check the RL runtime and sandbox isolation (credential deny, home redirect, SDK import) | | `bl finetune runtime prepare` | No Auth | Prepare the managed Python/SDK runtime used by RL and OPD jobs | | `bl finetune text create` | API Key | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | +| `bl finetune train-options` | Console | Query a base model's dynamic train options (modality / reasoning-mode combinations) | | `bl finetune video create` | API Key | Create a video generation model fine-tune job (Wan i2v/kf2v, efficient_sft) | | `bl finetune watch` | API Key | Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | @@ -494,6 +496,60 @@ bl finetune compress watch --job-id quant-xxx --follow bl finetune compress watch --job-id quant-xxx --follow --interval 30 --poll-timeout 7200 ``` +### `bl finetune decision create` + +| Field | Value | +| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `finetune decision create` | +| **Description** | Create a decision model fine-tune job (efficient_sft; choice/noul/score training data) | +| **Authentication** | API Key | +| **Usage** | `bl finetune decision create --base-model --datasets [--validations ] [--job-name ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ]` | + +#### 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) | +| `--n-epochs ` | number | no | Number of epochs (default: 2) | +| `--batch-size ` | number | no | Samples per training batch (default: 1) | +| `--learning-rate ` | string | no | Learning rate as a string to preserve precision (default: "2e-5") | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Creating a job uploads any local datasets and consumes training quota. +- Use --dry-run to preview the request body without submitting. +- --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 data is JSONL: each record carries an input state and a question table. Every question needs a hard label (choice: an option name; noul: true/false; score: a 0-based level index) and may carry a target soft-label distribution covering all options, with probabilities in [0, 1] summing to 1. +- Decision fine-tuning always runs efficient_sft (LoRA high-efficiency training); full-parameter training is not available. Only n_epochs / batch_size / learning_rate are overridable; omitted values are sent with the documented defaults (2 / 1 / "2e-5") because the API requires them in the request body. +- Sample-count rule: with a separate validation dataset, train and validation samples must each be at least batch_size; with training data only, samples must be at least batch_size × 10. Hundreds of samples are recommended. +- Keep question definitions (ID, type, instructions, criteria) identical across training, evaluation and online requests; changing them shifts the distribution and requires regenerating data and retraining. The CLI warns on cross-record and train/validation definition drift. +- --suffix is limited to 8 characters. After training, deploy the output model and invoke it with the decision command (--model ); training-only fields label/target are stripped automatically when reusing a training sample as a request file. + +#### Examples + +```bash +bl finetune decision create --base-model decision-model-preview-2026-09-24 --datasets ./tickets.train.jsonl --validations ./tickets.development.jsonl +``` + +```bash +bl finetune decision create --base-model decision-model-preview-2026-09-24 --datasets file-xxx +``` + +```bash +bl finetune decision create --base-model decision-model-preview-2026-09-24 --datasets ./tickets.train.jsonl --n-epochs 3 --batch-size 4 --learning-rate "2e-5" --suffix mytune +``` + +```bash +bl finetune decision create --base-model decision-model-preview-2026-09-24 --datasets ./tickets.train.jsonl --dry-run +``` + ### `bl finetune delete` | Field | Value | @@ -1114,12 +1170,12 @@ bl finetune opd watch --job-id ft-xxx --follow --poll-timeout 3600 ### `bl finetune params` -| Field | Value | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `finetune params` | -| **Description** | Query the training hyper-parameter configuration for a base model | -| **Authentication** | API Key | -| **Usage** | `bl finetune params --base-model [--training-type ] [--param-type ] [--mtu-spec-code ] [--modality ] [--reasoning-mode ] [--lang ] [--workspace-id ]` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `finetune params` | +| **Description** | Query the training hyper-parameter configuration for a base model | +| **Authentication** | API Key | +| **Usage** | `bl finetune params --base-model [--training-type ] [--param-type ] [--mtu-spec-code ] [--modality ] [--reasoning-mode ] [--lang ]` | #### Flags @@ -1132,14 +1188,17 @@ bl finetune opd watch --job-id ft-xxx --follow --poll-timeout 3600 | `--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. | | `--lang ` | string | no | Locale for server-side display text (e.g. en, zh). Omit for the server default. | -| `--workspace-id ` | string | no | Workspace ID sent as X-DashScope-WorkSpace; omit when your API key is already workspace-bound. | | `--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/fine-tunes-params. Each hyper_params entry keeps server field names verbatim (recommend_value, defaultValue, is_advanced_parameter, ...). -- --modality / --reasoning-mode travel as one hyper_parameters query parameter (JSON). Supported values and combinations vary per model; invalid combinations are rejected by the server and surfaced as-is. Models without dynamic train options ignore these flags. +- --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. - resume_from_checkpoint in the output reports whether the training type supports resuming training. #### Examples @@ -1646,42 +1705,48 @@ 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 ]` | +| 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 ]` | #### 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 | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| 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) | #### Notes @@ -1693,6 +1758,7 @@ bl finetune runtime prepare --dry-run - 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. - 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. #### Examples @@ -1724,6 +1790,10 @@ bl finetune text create --base-model qwen3-8b --datasets ./jev-train.jsonl --job bl finetune text create --base-model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4 ``` +```bash +bl finetune text create --base-model qwen3.6-plus-base-2026-04-02 --datasets file-xxx --training-type cpt --modality vision --reasoning-mode instruct +``` + ```bash bl finetune text create --base-model qwen3-8b --datasets file-xxx --output json ``` @@ -1732,6 +1802,50 @@ bl finetune text create --base-model qwen3-8b --datasets file-xxx --output json bl finetune text create --base-model qwen3-8b --datasets file-xxx --dry-run ``` +### `bl finetune train-options` + +| Field | Value | +| ------------------ | ----------------------------------------------------------------------------------- | +| **Name** | `finetune train-options` | +| **Description** | Query a base model's dynamic train options (modality / reasoning-mode combinations) | +| **Authentication** | Console | +| **Usage** | `bl finetune train-options --base-model [--training-type ]` | + +#### Flags + +| Flag | Type | Required | Description | +| ------------------------------ | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `--base-model ` | string | yes | Base model to query dynamic train options for (e.g. qwen3.6-plus-base-2026-04-02) | +| `--training-type ` | string | no | Training type: sft \| sft-lora \| dpo \| dpo-lora \| cpt (default: sft). Mapped to the server's training_type (e.g. sft-lora -> efficient_sft). | +| `--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 + +- 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. + +#### Examples + +```bash +bl finetune train-options --base-model qwen3.6-plus-base-2026-04-02 +``` + +```bash +bl finetune train-options --base-model qwen3.6-plus-base-2026-04-02 --training-type cpt +``` + +```bash +bl finetune train-options --base-model qwen3-8b +``` + +```bash +bl finetune train-options --base-model qwen3-8b --dry-run +``` + ### `bl finetune video create` | Field | Value | diff --git a/skills/bailian-finetune/reference/index.md b/skills/bailian-finetune/reference/index.md index e5f2c124..d577eb23 100644 --- a/skills/bailian-finetune/reference/index.md +++ b/skills/bailian-finetune/reference/index.md @@ -9,96 +9,100 @@ Use this index for the skill-scoped quick index and global flags. ## Quick index -| Command | Authentication | Description | Detail | -| --------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -| `bl dataset delete` | API Key | Delete a dataset file by ID | [dataset.md](dataset.md) | -| `bl dataset get` | API Key | Get details of a single dataset file | [dataset.md](dataset.md) | -| `bl dataset groups` | Console | List Console dataset groups | [dataset.md](dataset.md) | -| `bl dataset list` | API Key | List uploaded dataset files | [dataset.md](dataset.md) | -| `bl dataset upload` | API Key | Upload a dataset file (.jsonl or .zip) to Bailian | [dataset.md](dataset.md) | -| `bl dataset validate` | No Auth | Locally validate a dataset file (.jsonl or .zip) without uploading | [dataset.md](dataset.md) | -| `bl dataset version` | Console | List Console dataset versions by group or get one version by ID | [dataset.md](dataset.md) | -| `bl deploy audio create` | API Key | Create an audio (TTS) model deployment | [deploy.md](deploy.md) | -| `bl deploy capacity auto-renew disable` | API Key | Disable automatic renewal for one prepaid capacity instance | [deploy.md](deploy.md) | -| `bl deploy capacity auto-renew enable` | API Key | Enable automatic renewal for one prepaid capacity instance | [deploy.md](deploy.md) | -| `bl deploy capacity create` | API Key | Purchase an additional capacity instance for a ModelCode | [deploy.md](deploy.md) | -| `bl deploy capacity delete` | API Key | Release a capacity instance without deleting its ModelCode | [deploy.md](deploy.md) | -| `bl deploy capacity get` | API Key | Get a throughput reservation capacity instance | [deploy.md](deploy.md) | -| `bl deploy capacity list` | API Key | List throughput reservation capacity instances | [deploy.md](deploy.md) | -| `bl deploy capacity renew` | API Key | Renew a prepaid capacity instance, optionally changing capacity | [deploy.md](deploy.md) | -| `bl deploy capacity scale` | API Key | Scale the absolute capacity of one reservation instance | [deploy.md](deploy.md) | -| `bl deploy capacity unsubscribe` | No Auth | Build the Aliyun billing console unsubscribe link for a prepaid capacity instance | [deploy.md](deploy.md) | -| `bl deploy delete` | API Key | Delete a model deployment (PTU must be STOPPED with all capacity released) | [deploy.md](deploy.md) | -| `bl deploy get` | API Key | Get details of a single model deployment | [deploy.md](deploy.md) | -| `bl deploy image create` | API Key | Create an image generation model deployment | [deploy.md](deploy.md) | -| `bl deploy instances` | Console | List Console independent deployment services | [deploy.md](deploy.md) | -| `bl deploy list` | API Key | List model deployments and throughput reservations | [deploy.md](deploy.md) | -| `bl deploy models` | API Key | List models available for deployment | [deploy.md](deploy.md) | -| `bl deploy operation get` | API Key | Query a throughput reservation capacity operation once | [deploy.md](deploy.md) | -| `bl deploy operation wait` | API Key | Wait for a capacity operation and refresh confirmed capacity | [deploy.md](deploy.md) | -| `bl deploy overflow` | API Key | Set the overflow strategy for a throughput reservation ModelCode | [deploy.md](deploy.md) | -| `bl deploy pause` | Console | Pause a running model deployment (stops billing for mu/ptu) | [deploy.md](deploy.md) | -| `bl deploy resume` | Console | Resume a paused model deployment (brings service back online) | [deploy.md](deploy.md) | -| `bl deploy router create` | API Key | Create a postpaid model router | [deploy.md](deploy.md) | -| `bl deploy router delete` | API Key | Delete a model router | [deploy.md](deploy.md) | -| `bl deploy router get` | API Key | Get model router details | [deploy.md](deploy.md) | -| `bl deploy router list` | API Key | List model routers | [deploy.md](deploy.md) | -| `bl deploy router update` | API Key | Update selected fields of a running model router configuration | [deploy.md](deploy.md) | -| `bl deploy router versions` | API Key | List available model-routing versions and candidates | [deploy.md](deploy.md) | -| `bl deploy scale` | API Key | Scale a deployment's capacity | [deploy.md](deploy.md) | -| `bl deploy text create` | API Key | Create a text model deployment | [deploy.md](deploy.md) | -| `bl deploy update` | API Key | Update a deployment's rate limits (rpm_limit / tpm_limit) | [deploy.md](deploy.md) | -| `bl finetune audio create` | API Key | Create an audio TTS model fine-tune job (sft-lora) | [finetune.md](finetune.md) | -| `bl finetune cancel` | API Key | Cancel a running fine-tune job | [finetune.md](finetune.md) | -| `bl finetune capability` | No Auth | Query fine-tune training capability — by model (which training types it supports) or by training type (which models support it) | [finetune.md](finetune.md) | -| `bl finetune checkpoints` | API Key | List checkpoints produced by a fine-tune job | [finetune.md](finetune.md) | -| `bl finetune compress cancel` | API Key | Cancel a compression job | [finetune.md](finetune.md) | -| `bl finetune compress create` | API Key | Create a model compression job | [finetune.md](finetune.md) | -| `bl finetune compress delete` | API Key | Delete a compression job record | [finetune.md](finetune.md) | -| `bl finetune compress get` | API Key | Get a compression job | [finetune.md](finetune.md) | -| `bl finetune compress list` | API Key | List model compression jobs | [finetune.md](finetune.md) | -| `bl finetune compress logs` | API Key | Get compression job logs | [finetune.md](finetune.md) | -| `bl finetune compress templates` | API Key | List quantizable models and their compression templates | [finetune.md](finetune.md) | -| `bl finetune compress watch` | API Key | Probe or follow a compression job's status | [finetune.md](finetune.md) | -| `bl finetune delete` | API Key | Delete a fine-tune job record | [finetune.md](finetune.md) | -| `bl finetune export` | API Key | Publish a checkpoint as a deployable model | [finetune.md](finetune.md) | -| `bl finetune get` | API Key | Get details of a single fine-tune job | [finetune.md](finetune.md) | -| `bl finetune image create` | API Key | Create an image generation model fine-tune job (sft-lora) | [finetune.md](finetune.md) | -| `bl finetune list` | API Key | List fine-tune jobs | [finetune.md](finetune.md) | -| `bl finetune logs` | API Key | Fetch training logs for a fine-tune job | [finetune.md](finetune.md) | -| `bl finetune metrics` | API Key | Query the training metrics of a fine-tune job | [finetune.md](finetune.md) | -| `bl finetune opd authorize` | Console | Check and authorize OPD distillation access (whitelist, service roles, enablement) | [finetune.md](finetune.md) | -| `bl finetune opd cancel` | API Key | Cancel a running OPD job | [finetune.md](finetune.md) | -| `bl finetune opd delete` | API Key | Delete an OPD job record | [finetune.md](finetune.md) | -| `bl finetune opd get` | API Key | Get an OPD job | [finetune.md](finetune.md) | -| `bl finetune opd logs` | API Key | Fetch OPD job logs | [finetune.md](finetune.md) | -| `bl finetune opd params` | API Key | Query OPD (pg_opd) training / resource parameter configuration for a student model | [finetune.md](finetune.md) | -| `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 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) | -| `bl finetune rl delete` | API Key | Delete an RL job record | [finetune.md](finetune.md) | -| `bl finetune rl get` | API Key | Get an RL job | [finetune.md](finetune.md) | -| `bl finetune rl list` | API Key | List RL jobs | [finetune.md](finetune.md) | -| `bl finetune rl logs` | API Key | Fetch RL job logs | [finetune.md](finetune.md) | -| `bl finetune rl run` | API Key | Submit a reinforcement-learning training job | [finetune.md](finetune.md) | -| `bl finetune rl watch` | API Key | Probe an RL job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | -| `bl finetune runtime clean` | No Auth | Reclaim orphaned sandbox run directories and superseded runtime versions | [finetune.md](finetune.md) | -| `bl finetune runtime doctor` | No Auth | Check the RL runtime and sandbox isolation (credential deny, home redirect, SDK import) | [finetune.md](finetune.md) | -| `bl finetune runtime prepare` | No Auth | Prepare the managed Python/SDK runtime used by RL and OPD jobs | [finetune.md](finetune.md) | -| `bl finetune text create` | API Key | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | [finetune.md](finetune.md) | -| `bl finetune video create` | API Key | Create a video generation model fine-tune job (Wan i2v/kf2v, efficient_sft) | [finetune.md](finetune.md) | -| `bl finetune watch` | API Key | Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | +| Command | Authentication | Description | Detail | +| --------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | +| `bl dataset delete` | API Key | Delete a dataset file by ID | [dataset.md](dataset.md) | +| `bl dataset generate` | API Key | Generate decision training data with a teacher model: synthesize states, label probabilities, convert soft targets, split, and write a manifest | [dataset.md](dataset.md) | +| `bl dataset get` | API Key | Get details of a single dataset file | [dataset.md](dataset.md) | +| `bl dataset groups` | Console | List Console dataset groups | [dataset.md](dataset.md) | +| `bl dataset list` | API Key | List uploaded dataset files | [dataset.md](dataset.md) | +| `bl dataset split` | No Auth | Split labeled decision JSONL into train/development files locally (dedup + seeded shuffle, no API calls) | [dataset.md](dataset.md) | +| `bl dataset upload` | API Key | Upload a dataset file (.jsonl or .zip) to Bailian | [dataset.md](dataset.md) | +| `bl dataset validate` | No Auth | Locally validate a dataset file (.jsonl or .zip) without uploading | [dataset.md](dataset.md) | +| `bl dataset version` | Console | List Console dataset versions by group or get one version by ID | [dataset.md](dataset.md) | +| `bl deploy audio create` | API Key | Create an audio (TTS) model deployment | [deploy.md](deploy.md) | +| `bl deploy capacity auto-renew disable` | API Key | Disable automatic renewal for one prepaid capacity instance | [deploy.md](deploy.md) | +| `bl deploy capacity auto-renew enable` | API Key | Enable automatic renewal for one prepaid capacity instance | [deploy.md](deploy.md) | +| `bl deploy capacity create` | API Key | Purchase an additional capacity instance for a ModelCode | [deploy.md](deploy.md) | +| `bl deploy capacity delete` | API Key | Release a capacity instance without deleting its ModelCode | [deploy.md](deploy.md) | +| `bl deploy capacity get` | API Key | Get a throughput reservation capacity instance | [deploy.md](deploy.md) | +| `bl deploy capacity list` | API Key | List throughput reservation capacity instances | [deploy.md](deploy.md) | +| `bl deploy capacity renew` | API Key | Renew a prepaid capacity instance, optionally changing capacity | [deploy.md](deploy.md) | +| `bl deploy capacity scale` | API Key | Scale the absolute capacity of one reservation instance | [deploy.md](deploy.md) | +| `bl deploy capacity unsubscribe` | No Auth | Build the Aliyun billing console unsubscribe link for a prepaid capacity instance | [deploy.md](deploy.md) | +| `bl deploy delete` | API Key | Delete a model deployment (PTU must be STOPPED with all capacity released) | [deploy.md](deploy.md) | +| `bl deploy get` | API Key | Get details of a single model deployment | [deploy.md](deploy.md) | +| `bl deploy image create` | API Key | Create an image generation model deployment | [deploy.md](deploy.md) | +| `bl deploy instances` | Console | List Console independent deployment services | [deploy.md](deploy.md) | +| `bl deploy list` | API Key | List model deployments and throughput reservations | [deploy.md](deploy.md) | +| `bl deploy models` | API Key | List models available for deployment | [deploy.md](deploy.md) | +| `bl deploy operation get` | API Key | Query a throughput reservation capacity operation once | [deploy.md](deploy.md) | +| `bl deploy operation wait` | API Key | Wait for a capacity operation and refresh confirmed capacity | [deploy.md](deploy.md) | +| `bl deploy overflow` | API Key | Set the overflow strategy for a throughput reservation ModelCode | [deploy.md](deploy.md) | +| `bl deploy pause` | Console | Pause a running model deployment (stops billing for mu/ptu) | [deploy.md](deploy.md) | +| `bl deploy resume` | Console | Resume a paused model deployment (brings service back online) | [deploy.md](deploy.md) | +| `bl deploy router create` | API Key | Create a postpaid model router | [deploy.md](deploy.md) | +| `bl deploy router delete` | API Key | Delete a model router | [deploy.md](deploy.md) | +| `bl deploy router get` | API Key | Get model router details | [deploy.md](deploy.md) | +| `bl deploy router list` | API Key | List model routers | [deploy.md](deploy.md) | +| `bl deploy router update` | API Key | Update selected fields of a running model router configuration | [deploy.md](deploy.md) | +| `bl deploy router versions` | API Key | List available model-routing versions and candidates | [deploy.md](deploy.md) | +| `bl deploy scale` | API Key | Scale a deployment's capacity | [deploy.md](deploy.md) | +| `bl deploy text create` | API Key | Create a text model deployment | [deploy.md](deploy.md) | +| `bl deploy update` | API Key | Update a deployment's rate limits (rpm_limit / tpm_limit) | [deploy.md](deploy.md) | +| `bl finetune audio create` | API Key | Create an audio TTS model fine-tune job (sft-lora) | [finetune.md](finetune.md) | +| `bl finetune cancel` | API Key | Cancel a running fine-tune job | [finetune.md](finetune.md) | +| `bl finetune capability` | No Auth | Query fine-tune training capability — by model (which training types it supports) or by training type (which models support it) | [finetune.md](finetune.md) | +| `bl finetune checkpoints` | API Key | List checkpoints produced by a fine-tune job | [finetune.md](finetune.md) | +| `bl finetune compress cancel` | API Key | Cancel a compression job | [finetune.md](finetune.md) | +| `bl finetune compress create` | API Key | Create a model compression job | [finetune.md](finetune.md) | +| `bl finetune compress delete` | API Key | Delete a compression job record | [finetune.md](finetune.md) | +| `bl finetune compress get` | API Key | Get a compression job | [finetune.md](finetune.md) | +| `bl finetune compress list` | API Key | List model compression jobs | [finetune.md](finetune.md) | +| `bl finetune compress logs` | API Key | Get compression job logs | [finetune.md](finetune.md) | +| `bl finetune compress templates` | API Key | List quantizable models and their compression templates | [finetune.md](finetune.md) | +| `bl finetune compress watch` | API Key | Probe or follow a compression job's status | [finetune.md](finetune.md) | +| `bl finetune decision create` | API Key | Create a decision model fine-tune job (efficient_sft; choice/noul/score training data) | [finetune.md](finetune.md) | +| `bl finetune delete` | API Key | Delete a fine-tune job record | [finetune.md](finetune.md) | +| `bl finetune export` | API Key | Publish a checkpoint as a deployable model | [finetune.md](finetune.md) | +| `bl finetune get` | API Key | Get details of a single fine-tune job | [finetune.md](finetune.md) | +| `bl finetune image create` | API Key | Create an image generation model fine-tune job (sft-lora) | [finetune.md](finetune.md) | +| `bl finetune list` | API Key | List fine-tune jobs | [finetune.md](finetune.md) | +| `bl finetune logs` | API Key | Fetch training logs for a fine-tune job | [finetune.md](finetune.md) | +| `bl finetune metrics` | API Key | Query the training metrics of a fine-tune job | [finetune.md](finetune.md) | +| `bl finetune opd authorize` | Console | Check and authorize OPD distillation access (whitelist, service roles, enablement) | [finetune.md](finetune.md) | +| `bl finetune opd cancel` | API Key | Cancel a running OPD job | [finetune.md](finetune.md) | +| `bl finetune opd delete` | API Key | Delete an OPD job record | [finetune.md](finetune.md) | +| `bl finetune opd get` | API Key | Get an OPD job | [finetune.md](finetune.md) | +| `bl finetune opd logs` | API Key | Fetch OPD job logs | [finetune.md](finetune.md) | +| `bl finetune opd params` | API Key | Query OPD (pg_opd) training / resource parameter configuration for a student model | [finetune.md](finetune.md) | +| `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 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) | +| `bl finetune rl delete` | API Key | Delete an RL job record | [finetune.md](finetune.md) | +| `bl finetune rl get` | API Key | Get an RL job | [finetune.md](finetune.md) | +| `bl finetune rl list` | API Key | List RL jobs | [finetune.md](finetune.md) | +| `bl finetune rl logs` | API Key | Fetch RL job logs | [finetune.md](finetune.md) | +| `bl finetune rl run` | API Key | Submit a reinforcement-learning training job | [finetune.md](finetune.md) | +| `bl finetune rl watch` | API Key | Probe an RL job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | +| `bl finetune runtime clean` | No Auth | Reclaim orphaned sandbox run directories and superseded runtime versions | [finetune.md](finetune.md) | +| `bl finetune runtime doctor` | No Auth | Check the RL runtime and sandbox isolation (credential deny, home redirect, SDK import) | [finetune.md](finetune.md) | +| `bl finetune runtime prepare` | No Auth | Prepare the managed Python/SDK runtime used by RL and OPD jobs | [finetune.md](finetune.md) | +| `bl finetune text create` | API Key | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | [finetune.md](finetune.md) | +| `bl finetune train-options` | Console | Query a base model's dynamic train options (modality / reasoning-mode combinations) | [finetune.md](finetune.md) | +| `bl finetune video create` | API Key | Create a video generation model fine-tune job (Wan i2v/kf2v, efficient_sft) | [finetune.md](finetune.md) | +| `bl finetune watch` | API Key | Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | ## By group -| Group | Commands | Reference | -| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -| `dataset` | `delete`, `get`, `groups`, `list`, `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`, `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`, `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`, `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 495af140..168ddcd0 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-gen metadata: - version: "2.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-knowledge/SKILL.md b/skills/bailian-knowledge/SKILL.md index f1b5e7e9..7b54f27e 100644 --- a/skills/bailian-knowledge/SKILL.md +++ b/skills/bailian-knowledge/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-knowledge metadata: - version: "2.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-managed-agent/SKILL.md b/skills/bailian-managed-agent/SKILL.md index 9957d1ec..46fe9079 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.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-memory/SKILL.md b/skills/bailian-memory/SKILL.md index 56bc0466..3d95eed2 100644 --- a/skills/bailian-memory/SKILL.md +++ b/skills/bailian-memory/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-memory metadata: - version: "2.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-opd/SKILL.md b/skills/bailian-opd/SKILL.md index 6912c5e2..9ea4d841 100644 --- a/skills/bailian-opd/SKILL.md +++ b/skills/bailian-opd/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-opd metadata: - version: "2.11.1" + version: "2.11.2" requires: bins: ["bl", "node"] description: >- diff --git a/skills/bailian-protocol/SKILL.md b/skills/bailian-protocol/SKILL.md index 3213faf0..08123d2d 100644 --- a/skills/bailian-protocol/SKILL.md +++ b/skills/bailian-protocol/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-protocol metadata: - version: "2.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-sandbox/SKILL.md b/skills/bailian-sandbox/SKILL.md index 0cb8d894..75720d6c 100644 --- a/skills/bailian-sandbox/SKILL.md +++ b/skills/bailian-sandbox/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-sandbox metadata: - version: "2.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-web-search/SKILL.md b/skills/bailian-web-search/SKILL.md index 52d8d82b..a1083eb4 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.11.1" + version: "2.11.2" requires: bins: ["bl"] description: >-