diff --git a/AGENTS.md b/AGENTS.md index c8b204a..64d866a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -104,6 +104,17 @@ CLI 只为「自己能权威解释的错误」发出语义化信号,服务端的 如果命令调用 Console Gateway,`defineCommand` 必须设置 `auth: "console"`。runtime 会基于 `CONSOLE_AUTH_FLAGS` 自动在 help 中展示 `--console-region`、`--console-site`、`--console-switch-agent`、`--workspace-id`,并由 `authStage` 解析/注入 console credential。命令不要重复声明这些凭证域 flag,也不要手动从 env/config 解析 token。 +### 5. 禁止单字母变量命名 + +所有变量、参数、回调形参必须使用有语义的命名,不允许单字母(如 `i`、`m`、`p`、`t`、`e`、`s`)。具体表现: + +- 回调参数: `.map((m) => ...)` → `.map((model) => ...)`, `.find((t) => ...)` → `.find((template) => ...)` +- catch 变量: `catch (e)` → `catch (error)` +- for-of 循环: `for (const i of items)` → `for (const item of items)` +- 临时变量: `const s = ...` → `const strategy = ...` + +例外: 仅当作用域极小(≤3 行)且语义从上下文完全明确时,可使用 `k`/`v`(Object.entries 的 key/value)。 + ## 完成改动后的快速验证 ```sh diff --git a/README.md b/README.md index 020ae34..68ff687 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Equip your AI Agent out-of-the-box with these capabilities, composable across co - **MCP integration** — Orchestrate Bailian MCP servers: list services, inspect tools, and invoke any tool directly from the terminal - **Web search** — Real-time internet retrieval for up-to-date, accurate answers - **Model recommendation** — Describe your scenario and get best-fit model suggestions; supports scoped search, model comparison, and alternative discovery -- **Fine-tuning & deployment** — Upload datasets, create SFT/LoRA/DPO/CPT jobs (`finetune create`), probe job status non-blockingly (`finetune watch`), query per-model training capability (`finetune capability`), and deploy trained models as endpoints (`deploy create`) +- **Fine-tuning & deployment** — Upload datasets, create text/audio/image fine-tune jobs (`finetune text|audio|image create`; text covers SFT/LoRA/DPO/CPT), probe job status non-blockingly (`finetune watch`), query per-model training capability (`finetune capability`), and deploy trained models as endpoints (`deploy text|audio|image create`) - **Console capabilities** — Browse Bailian apps (`app list`), check free-tier quota (`usage free`), view model usage statistics (`usage stats`), manage workspaces (`workspace list`), and manage rate limits (`quota list/request/check/history`) - **Local file auto-upload** — Every URL parameter accepts a local path; uploaded to free temp storage with 48-hour validity @@ -114,10 +114,10 @@ bl auth login --console # Fine-tune & deploy — a one-shot train-to-serve workflow bl dataset upload --file ./train.jsonl # Upload a .jsonl dataset (validated first) -bl finetune create --model qwen3-8b --datasets ./train.jsonl --training-type sft-lora # Local paths auto-upload +bl finetune text create --model qwen3-8b --datasets ./train.jsonl --training-type sft-lora # Local paths auto-upload bl finetune watch --job-id ft-xxx --output json # Non-blocking status probe (exit 0/1/3 = done/failed/running) bl finetune capability --model qwen3-8b # Which training types a model supports -bl deploy create --model qwen3-8b --name my-svc --plan mu # Deploy the trained model as an endpoint +bl deploy text create --model qwen3-8b --name my-svc --plan mu # Deploy the trained model as an endpoint # Browse apps / free-tier quota / usage statistics / workspaces bl app list diff --git a/README.zh.md b/README.zh.md index 90fa079..eaa27e4 100644 --- a/README.zh.md +++ b/README.zh.md @@ -38,7 +38,7 @@ _专为 AI Agent 打造,每个命令均可作为结构化工具调用。_ - **MCP 集成** — 统一调度百炼 MCP 服务:列出服务、查看工具、直接在终端调用任意工具 - **联网搜索** — 实时互联网信息检索,提升回答准确性及时效性 - **模型推荐** — 描述你的场景,智能推荐最适合的模型;支持限定范围搜索、模型对比和替代发现 -- **微调与部署** — 上传数据集、创建 SFT/LoRA/DPO/CPT 调优任务(`finetune create`)、非阻塞探测任务状态(`finetune watch`)、按模型查训练能力(`finetune capability`),并把训练好的模型部署为推理服务(`deploy create`) +- **微调与部署** — 上传数据集、创建文本/音频/图像调优任务(`finetune text|audio|image create`;文本涵盖 SFT/LoRA/DPO/CPT)、非阻塞探测任务状态(`finetune watch`)、按模型查训练能力(`finetune capability`),并把训练好的模型部署为推理服务(`deploy text|audio|image create`) - **控制台能力** — 浏览百炼应用(`app list`),查询模型免费额度(`usage free`),查看模型用量统计(`usage stats`),管理业务空间(`workspace list`),管理限流与提额(`quota list/request/check/history`) - **本地文件自动上传** — 所有 URL 参数同时支持本地路径,免费临时存储 48 小时 @@ -112,10 +112,10 @@ bl auth login --console # 微调与部署 — 从训练到服务的一站式流程 bl dataset upload --file ./train.jsonl # 上传 .jsonl 数据集(先校验) -bl finetune create --model qwen3-8b --datasets ./train.jsonl --training-type sft-lora # 本地路径自动上传 +bl finetune text create --model qwen3-8b --datasets ./train.jsonl --training-type sft-lora # 本地路径自动上传 bl finetune watch --job-id ft-xxx --output json # 非阻塞状态探测(退出码 0/1/3 = 成功/失败/进行中) bl finetune capability --model qwen3-8b # 查询模型支持哪些训练方式 -bl deploy create --model qwen3-8b --name my-svc --plan mu # 把训练好的模型部署为推理服务 +bl deploy text create --model qwen3-8b --name my-svc --plan mu # 把训练好的模型部署为推理服务 # 浏览应用 / 免费额度 / 用量统计 / 业务空间 bl app list diff --git a/packages/cli/README.md b/packages/cli/README.md index 020ae34..68ff687 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -38,7 +38,7 @@ Equip your AI Agent out-of-the-box with these capabilities, composable across co - **MCP integration** — Orchestrate Bailian MCP servers: list services, inspect tools, and invoke any tool directly from the terminal - **Web search** — Real-time internet retrieval for up-to-date, accurate answers - **Model recommendation** — Describe your scenario and get best-fit model suggestions; supports scoped search, model comparison, and alternative discovery -- **Fine-tuning & deployment** — Upload datasets, create SFT/LoRA/DPO/CPT jobs (`finetune create`), probe job status non-blockingly (`finetune watch`), query per-model training capability (`finetune capability`), and deploy trained models as endpoints (`deploy create`) +- **Fine-tuning & deployment** — Upload datasets, create text/audio/image fine-tune jobs (`finetune text|audio|image create`; text covers SFT/LoRA/DPO/CPT), probe job status non-blockingly (`finetune watch`), query per-model training capability (`finetune capability`), and deploy trained models as endpoints (`deploy text|audio|image create`) - **Console capabilities** — Browse Bailian apps (`app list`), check free-tier quota (`usage free`), view model usage statistics (`usage stats`), manage workspaces (`workspace list`), and manage rate limits (`quota list/request/check/history`) - **Local file auto-upload** — Every URL parameter accepts a local path; uploaded to free temp storage with 48-hour validity @@ -114,10 +114,10 @@ bl auth login --console # Fine-tune & deploy — a one-shot train-to-serve workflow bl dataset upload --file ./train.jsonl # Upload a .jsonl dataset (validated first) -bl finetune create --model qwen3-8b --datasets ./train.jsonl --training-type sft-lora # Local paths auto-upload +bl finetune text create --model qwen3-8b --datasets ./train.jsonl --training-type sft-lora # Local paths auto-upload bl finetune watch --job-id ft-xxx --output json # Non-blocking status probe (exit 0/1/3 = done/failed/running) bl finetune capability --model qwen3-8b # Which training types a model supports -bl deploy create --model qwen3-8b --name my-svc --plan mu # Deploy the trained model as an endpoint +bl deploy text create --model qwen3-8b --name my-svc --plan mu # Deploy the trained model as an endpoint # Browse apps / free-tier quota / usage statistics / workspaces bl app list diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index 90fa079..eaa27e4 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -38,7 +38,7 @@ _专为 AI Agent 打造,每个命令均可作为结构化工具调用。_ - **MCP 集成** — 统一调度百炼 MCP 服务:列出服务、查看工具、直接在终端调用任意工具 - **联网搜索** — 实时互联网信息检索,提升回答准确性及时效性 - **模型推荐** — 描述你的场景,智能推荐最适合的模型;支持限定范围搜索、模型对比和替代发现 -- **微调与部署** — 上传数据集、创建 SFT/LoRA/DPO/CPT 调优任务(`finetune create`)、非阻塞探测任务状态(`finetune watch`)、按模型查训练能力(`finetune capability`),并把训练好的模型部署为推理服务(`deploy create`) +- **微调与部署** — 上传数据集、创建文本/音频/图像调优任务(`finetune text|audio|image create`;文本涵盖 SFT/LoRA/DPO/CPT)、非阻塞探测任务状态(`finetune watch`)、按模型查训练能力(`finetune capability`),并把训练好的模型部署为推理服务(`deploy text|audio|image create`) - **控制台能力** — 浏览百炼应用(`app list`),查询模型免费额度(`usage free`),查看模型用量统计(`usage stats`),管理业务空间(`workspace list`),管理限流与提额(`quota list/request/check/history`) - **本地文件自动上传** — 所有 URL 参数同时支持本地路径,免费临时存储 48 小时 @@ -112,10 +112,10 @@ bl auth login --console # 微调与部署 — 从训练到服务的一站式流程 bl dataset upload --file ./train.jsonl # 上传 .jsonl 数据集(先校验) -bl finetune create --model qwen3-8b --datasets ./train.jsonl --training-type sft-lora # 本地路径自动上传 +bl finetune text create --model qwen3-8b --datasets ./train.jsonl --training-type sft-lora # 本地路径自动上传 bl finetune watch --job-id ft-xxx --output json # 非阻塞状态探测(退出码 0/1/3 = 成功/失败/进行中) bl finetune capability --model qwen3-8b # 查询模型支持哪些训练方式 -bl deploy create --model qwen3-8b --name my-svc --plan mu # 把训练好的模型部署为推理服务 +bl deploy text create --model qwen3-8b --name my-svc --plan mu # 把训练好的模型部署为推理服务 # 浏览应用 / 免费额度 / 用量统计 / 业务空间 bl app list diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 2d3ca54..6957d52 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -52,7 +52,9 @@ import { datasetGet, datasetDelete, datasetValidate, - finetuneCreate, + finetuneTextCreate, + finetuneAudioCreate, + finetuneImageCreate, finetuneList, finetuneGet, finetuneCancel, @@ -62,7 +64,9 @@ import { finetuneExport, finetuneWatch, finetuneCapability, - deployCreate, + deployTextCreate, + deployAudioCreate, + deployImageCreate, deployList, deployGet, deployModels, @@ -133,7 +137,9 @@ export const commands: Record = { "dataset get": datasetGet, "dataset delete": datasetDelete, "dataset validate": datasetValidate, - "finetune create": finetuneCreate, + "finetune text create": finetuneTextCreate, + "finetune audio create": finetuneAudioCreate, + "finetune image create": finetuneImageCreate, "finetune list": finetuneList, "finetune get": finetuneGet, "finetune cancel": finetuneCancel, @@ -143,7 +149,9 @@ export const commands: Record = { "finetune export": finetuneExport, "finetune watch": finetuneWatch, "finetune capability": finetuneCapability, - "deploy create": deployCreate, + "deploy text create": deployTextCreate, + "deploy audio create": deployAudioCreate, + "deploy image create": deployImageCreate, "deploy list": deployList, "deploy get": deployGet, "deploy models": deployModels, diff --git a/packages/cli/tests/e2e/dataset.e2e.test.ts b/packages/cli/tests/e2e/dataset.e2e.test.ts index ef7f08e..2118ff8 100644 --- a/packages/cli/tests/e2e/dataset.e2e.test.ts +++ b/packages/cli/tests/e2e/dataset.e2e.test.ts @@ -214,6 +214,83 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: dataset (offline)", () => { expect(data.action).toBe("dataset.upload"); expect(data.schema).toBe("dpo"); }); + + test("dataset upload --schema image --no-validate --dry-run 采用 1GB 媒体上限", async () => { + // image schema raises the upload cap to 1 GiB (vs 300 MB for text). + // --no-validate keeps this offline (the jsonl fixture is not a real zip). + const file = join(__dirname, ".dataset-valid.jsonl"); + const { stdout, stderr, exitCode } = await runCli([ + "dataset", + "upload", + "--file", + file, + "--schema", + "image", + "--no-validate", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ action: string; schema: string; max_bytes: number }>(stdout); + expect(data.action).toBe("dataset.upload"); + expect(data.schema).toBe("image"); + expect(data.max_bytes).toBe(1024 * 1024 * 1024); + }); + + test.each(["tts", "image"])("dataset upload --dry-run 接受媒体 schema %s", async (schema) => { + const file = join(__dirname, ".dataset-valid.jsonl"); + const { stdout, stderr, exitCode } = await runCli([ + "dataset", + "upload", + "--file", + file, + "--schema", + schema, + "--no-validate", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ action: string; schema: string }>(stdout); + expect(data.action).toBe("dataset.upload"); + expect(data.schema).toBe(schema); + }); + + test("dataset validate --schema video 拒绝(视频生成入口已隐藏)", async () => { + const file = join(__dirname, ".dataset-valid.jsonl"); + const { stdout, stderr, exitCode } = await runCli([ + "dataset", + "validate", + "--file", + file, + "--schema", + "video", + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).not.toBe(0); + expect(`${stdout}\n${stderr}`).toMatch(/--schema video is not supported/); + }); + + test("dataset upload --schema video 拒绝(视频生成入口已隐藏)", async () => { + const file = join(__dirname, ".dataset-valid.jsonl"); + const { stdout, stderr, exitCode } = await runCli([ + "dataset", + "upload", + "--file", + file, + "--schema", + "video", + "--no-validate", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stdout + stderr).not.toBe(0); + expect(`${stdout}\n${stderr}`).toMatch(/--schema video is not supported/); + }); }); describe.skipIf(!isDashScopeE2EReady())("e2e: dataset (DashScope)", () => { diff --git a/packages/cli/tests/e2e/deploy.e2e.test.ts b/packages/cli/tests/e2e/deploy.e2e.test.ts index 5fdcd63..3dc5c55 100644 --- a/packages/cli/tests/e2e/deploy.e2e.test.ts +++ b/packages/cli/tests/e2e/deploy.e2e.test.ts @@ -22,7 +22,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: deploy (offline)", () => { }); test("deploy create --help 正常退出并展示必填项", async () => { - const { stderr, exitCode } = await runCli(["deploy", "create", "--help"]); + const { stderr, exitCode } = await runCli(["deploy", "text", "create", "--help"]); expect(exitCode, stderr).toBe(0); expect(stderr).toMatch(/--model|--name/i); }); @@ -30,6 +30,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: deploy (offline)", () => { test("deploy create --dry-run 构造 lora 部署请求体", async () => { const { stdout, stderr, exitCode } = await runCli([ "deploy", + "text", "create", "--model", "qwen-plus-2025-12-01", @@ -56,6 +57,65 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: deploy (offline)", () => { expect(data.body.capacity).toBe(1); }); + test("deploy create --plan mu --deploy-spec --dry-run 透传 deploy_spec", async () => { + const { stdout, stderr, exitCode } = await runCli([ + "deploy", + "text", + "create", + "--model", + "qwen3-8b", + "--name", + "my-qwen3-mu", + "--plan", + "mu", + "--deploy-spec", + "MU1", + "--capacity", + "2", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + action: string; + body: { plan: string; deploy_spec?: string; capacity?: number }; + }>(stdout); + expect(data.action).toBe("deploy.create"); + expect(data.body.plan).toBe("mu"); + expect(data.body.deploy_spec).toBe("MU1"); + expect(data.body.capacity).toBe(2); + }); + + test("deploy audio create --dry-run 默认 plan=mu(CosyVoice 部署契约)", async () => { + // Audio (CosyVoice TTS) outputs deploy model-unit-billed: the modality fixes + // the default plan to `mu` (text/image stay `lora`). In dry-run the mu + // strategy skips the catalog lookup, so deploy_spec is omitted and capacity + // falls back to 1 with billing_method POST_PAY. + const { stdout, stderr, exitCode } = await runCli([ + "deploy", + "audio", + "create", + "--model", + "my-cosyvoice-ft", + "--name", + "my-tts", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + action: string; + body: { plan: string; name: string; billing_method?: string; capacity?: number }; + }>(stdout); + expect(data.action).toBe("deploy.create"); + expect(data.body.plan).toBe("mu"); + expect(data.body.name).toBe("my-tts"); + expect(data.body.billing_method).toBe("POST_PAY"); + expect(data.body.capacity).toBe(1); + }); + test("deploy scale --dry-run 转发 capacity", async () => { const { stdout, stderr, exitCode } = await runCli([ "deploy", diff --git a/packages/cli/tests/e2e/finetune.e2e.test.ts b/packages/cli/tests/e2e/finetune.e2e.test.ts index 067cf13..8af40f5 100644 --- a/packages/cli/tests/e2e/finetune.e2e.test.ts +++ b/packages/cli/tests/e2e/finetune.e2e.test.ts @@ -23,7 +23,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { }); test("finetune create --help 正常退出并展示必填项", async () => { - const { stderr, exitCode } = await runCli(["finetune", "create", "--help"]); + const { stderr, exitCode } = await runCli(["finetune", "text", "create", "--help"]); expect(exitCode, stderr).toBe(0); expect(stderr).toMatch(/--model|--datasets/i); }); @@ -31,6 +31,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { test("finetune create --dry-run 构造 SFT 默认请求体", async () => { const { stdout, stderr, exitCode } = await runCli([ "finetune", + "text", "create", "--model", "qwen3-8b", @@ -64,6 +65,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { test("finetune create --dry-run 转发训练类型与超参", async () => { const { stdout, stderr, exitCode } = await runCli([ "finetune", + "text", "create", "--model", "qwen3-8b", @@ -114,9 +116,40 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { }); }); + test.each([ + ["sft", "sft"], + ["sft-lora", "efficient_sft"], + ["dpo", "dpo_full"], + ["dpo-lora", "dpo_lora"], + ["cpt", "cpt"], + ])( + "finetune create --training-type %s 经 profile 映射为 server 类型 %s", + async (cliType, serverType) => { + const { stdout, stderr, exitCode } = await runCli([ + "finetune", + "text", + "create", + "--model", + "qwen3-8b", + "--datasets", + "file-aaa", + "--training-type", + cliType, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ action: string; body: { training_type: string } }>(stdout); + expect(data.action).toBe("finetune.create"); + expect(data.body.training_type).toBe(serverType); + }, + ); + test("finetune create --training-type 拒绝不支持的训练类型值", async () => { const { stdout, stderr, exitCode } = await runCli([ "finetune", + "text", "create", "--model", "qwen3-8b", @@ -135,6 +168,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { const localPath = join(cliPackageRoot, "tests", "e2e", ".dataset-valid.jsonl"); const { stdout, stderr, exitCode } = await runCli([ "finetune", + "text", "create", "--model", "qwen3-8b", @@ -165,6 +199,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { test("finetune create --datasets 为空时拒绝", async () => { const { stdout, stderr, exitCode } = await runCli([ "finetune", + "text", "create", "--model", "qwen3-8b", @@ -185,6 +220,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { const localPath = join(cliPackageRoot, "tests", "e2e", ".dataset-valid.jsonl"); const { stdout, stderr, exitCode } = await runCli([ "finetune", + "text", "create", "--model", "qwen3-8b", @@ -206,6 +242,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { const localPath = join(cliPackageRoot, "tests", "e2e", ".dataset-valid.jsonl"); const { stdout, stderr, exitCode } = await runCli([ "finetune", + "text", "create", "--model", "qwen3-8b", @@ -247,6 +284,7 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { test("finetune create --dry-run 解析多 datasets 中的空白", async () => { const { stdout, stderr, exitCode } = await runCli([ "finetune", + "text", "create", "--model", "qwen3-8b", @@ -262,6 +300,60 @@ describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (offline)", () => { }>(stdout); expect(data.body.training_file_ids).toEqual(["file-a", "file-b"]); }); + + test("finetune audio create --dry-run 用 sft-lora 默认 + audio 超参", async () => { + // Audio has no --training-type flag; the command fixes modality=audio and + // defaults to sft-lora (efficient_sft) with the fixed CosyVoice hyper-params. + const { stdout, stderr, exitCode } = await runCli([ + "finetune", + "audio", + "create", + "--model", + "cosyvoice-v3-flash", + "--datasets", + "file-audio", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ + action: string; + body: { training_type: string; hyper_parameters: Record }; + }>(stdout); + expect(data.action).toBe("finetune.create"); + expect(data.body.training_type).toBe("efficient_sft"); + // Audio TTS defaults are fixed (not the text n_epochs/batch_size surface). + expect(data.body.hyper_parameters.lm_max_epoch).toBeDefined(); + }); + + test("finetune audio create --help 不暴露文本超参 flag", async () => { + // Audio models don't consume --training-type / --n-epochs / --batch-size / + // --learning-rate / --max-length, so those flags are not offered. + const { stderr, exitCode } = await runCli(["finetune", "audio", "create", "--help"]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--model|--datasets/i); + expect(stderr).not.toMatch(/--training-type|--n-epochs|--batch-size|--max-length/); + }); + + test("finetune image create --dry-run 用 sft-lora 默认", async () => { + const { stdout, stderr, exitCode } = await runCli([ + "finetune", + "image", + "create", + "--model", + "wan2.7-image-pro", + "--datasets", + "file-image", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ action: string; body: { training_type: string } }>(stdout); + expect(data.action).toBe("finetune.create"); + expect(data.body.training_type).toBe("efficient_sft"); + }); }); describe.skipIf(!isDashScopeE2EReady())("e2e: finetune (DashScope)", () => { diff --git a/packages/commands/src/commands/dataset/upload.ts b/packages/commands/src/commands/dataset/upload.ts index 40e06c8..f7d805b 100644 --- a/packages/commands/src/commands/dataset/upload.ts +++ b/packages/commands/src/commands/dataset/upload.ts @@ -6,6 +6,7 @@ import { parseDatasetSchemaFlag, formatIssue, MAX_DATASET_BYTES, + MAX_MEDIA_ZIP_BYTES, BailianError, ExitCode, type DatasetFile, @@ -17,7 +18,7 @@ const UPLOAD_FLAGS = { file: { type: "string", valueHint: "", - description: "Local .jsonl dataset file (≤300MB)", + description: "Local dataset file (.jsonl or .zip; ≤300MB text, ≤1GB image)", required: true, }, purpose: { @@ -29,7 +30,7 @@ const UPLOAD_FLAGS = { type: "string", valueHint: "", description: - 'Record schema: "chatml" (SFT), "dpo" (chosen/rejected), or "cpt" (raw text). Default auto-detects per record.', + 'Record schema: "chatml" (SFT), "dpo" (chosen/rejected), "cpt" (raw text), "tts" (audio), or "image" (image generation). Default auto-detects per record.', }, noValidate: { type: "switch", @@ -42,42 +43,55 @@ const UPLOAD_FLAGS = { } satisfies FlagsDef; export default defineCommand({ - description: "Upload a dataset file (.jsonl) to Bailian", + description: "Upload a dataset file (.jsonl or .zip) to Bailian", auth: "apiKey", usageArgs: - "--file [--purpose ] [--schema ] [--no-validate] [--full-validate]", + "--file [--purpose ] [--schema ] [--no-validate] [--full-validate]", flags: UPLOAD_FLAGS, exampleArgs: [ "--file train.jsonl", "--file dpo.jsonl --schema dpo", "--file cpt.jsonl --schema cpt", + "--file audio.zip --schema tts", "--file eval.jsonl --purpose evaluation", "--file train.jsonl --full-validate", "--file train.jsonl --no-validate", ], notes: [ - "Only .jsonl is supported in this release. Three record schemas are", - "recognized: chatml = {messages:[...]} (SFT); dpo = {messages:[...],", - "chosen, rejected} where chosen/rejected are single assistant messages;", - 'cpt = {text:"..."} (continual pre-training, raw text). With no --schema,', - "a record carrying chosen/rejected is validated as DPO, one with text (and", - "no messages) as CPT, otherwise as ChatML. Pass --schema dpo / cpt to", - "require that shape on every record, or --schema chatml to ignore the", - "preference / text fields. Other purposes may carry a different schema in", - "the future and would be served by a purpose-specific validator.", - "The dataset upload cap is 300MB per file.", - "Upload uses the OpenAI-compatible /compatible-mode/v1/files endpoint so", - "the purpose tag is persisted (the DashScope-native /api/v1/files drops it).", + "Supports .jsonl (text) and .zip (audio/image archives with a data.jsonl", + "manifest). Five record schemas are recognized: chatml = {messages:[...]}", + '(SFT); dpo = {messages:[...], chosen, rejected}; cpt = {text:"..."}', + '(continual pre-training, raw text); tts = {wav_fn:"train/xxx.wav",', + 'text:"..."} (audio fine-tuning); image = {img_path:"..."} (image', + "generation). With no --schema, a record carrying wav_fn is validated as", + "TTS, img_path as image, chosen/rejected as DPO, text (no messages) as CPT,", + "otherwise ChatML. Upload cap: 300MB text, 1GB image. Upload uses the", + "OpenAI-compatible /compatible-mode/v1/files endpoint so the purpose tag is", + "persisted (the DashScope-native /api/v1/files drops it).", ], async run(ctx) { const { identity, settings, flags } = ctx; const filePath = flags.file; const purpose = flags.purpose || "fine-tune"; const schema = parseDatasetSchemaFlag(flags.schema); + if (schema === "video") { + throw new BailianError( + `--schema video is not supported.`, + ExitCode.USAGE, + `Supported schemas: chatml, dpo, cpt, tts, image.`, + ); + } const format = detectOutputFormat(settings.output); + // Image schema allows larger ZIPs (1 GB vs 300 MB for text). + const isMediaSchema = schema === "image"; if (!flags.noValidate) { - const result = await validateDataset(filePath, { fullValidate: flags.fullValidate, schema }); + const maxBytes = isMediaSchema ? MAX_MEDIA_ZIP_BYTES : MAX_DATASET_BYTES; + const result = await validateDataset(filePath, { + fullValidate: flags.fullValidate, + schema, + maxBytes, + }); if (!result.valid) { const lines = [ `Dataset validation failed for ${filePath}`, @@ -112,7 +126,7 @@ export default defineCommand({ action: "dataset.upload", file: filePath, purpose, - max_bytes: MAX_DATASET_BYTES, + max_bytes: isMediaSchema ? MAX_MEDIA_ZIP_BYTES : MAX_DATASET_BYTES, validate: !flags.noValidate, schema: schema ?? "auto", }, diff --git a/packages/commands/src/commands/dataset/validate.ts b/packages/commands/src/commands/dataset/validate.ts index f8b7f51..8bf0d29 100644 --- a/packages/commands/src/commands/dataset/validate.ts +++ b/packages/commands/src/commands/dataset/validate.ts @@ -25,7 +25,7 @@ const VALIDATE_FLAGS = { file: { type: "string", valueHint: "", - description: "Local .jsonl dataset file", + description: "Local dataset file (.jsonl or .zip)", required: true, }, fullValidate: { @@ -36,20 +36,21 @@ const VALIDATE_FLAGS = { type: "string", valueHint: "", description: - 'Record schema: "chatml" (SFT), "dpo" (chosen/rejected), or "cpt" (raw text). Default auto-detects per record.', + 'Record schema: "chatml" (SFT), "dpo" (chosen/rejected), "cpt" (raw text), "tts" (audio), or "image" (image generation). Default auto-detects per record.', }, } satisfies FlagsDef; export default defineCommand({ - description: "Locally validate a dataset file (.jsonl) without uploading", + description: "Locally validate a dataset file (.jsonl or .zip) without uploading", // 纯本地校验,不触网、不需 API key(与 `pipeline validate` 一致)。 auth: "none", - usageArgs: "--file [--full-validate] [--schema ]", + usageArgs: "--file [--full-validate] [--schema ]", flags: VALIDATE_FLAGS, exampleArgs: [ "--file train.jsonl", "--file dpo.jsonl --schema dpo", "--file cpt.jsonl --schema cpt", + "--file audio.zip --schema tts", "--file eval.jsonl --full-validate", "--file train.jsonl --output json", ], @@ -57,17 +58,27 @@ export default defineCommand({ "Default scan: every line gets a structural check, then ~160 lines (front 50,", "evenly spaced 100, last 10) are JSON.parsed against the active schema.", "Schemas: chatml = {messages:[...]} (SFT); dpo = {messages:[...], chosen,", - "rejected} where chosen/rejected are single assistant messages; cpt =", - '{text:"..."} (continual pre-training, raw text). With no --schema, a', - "record carrying chosen/rejected is validated as DPO, one with text (and no", - "messages) as CPT, otherwise as ChatML. Pass --schema dpo / cpt to require", - "that shape on every record (strict), or --schema chatml to ignore the", - "preference / text fields. Use --full-validate to JSON.parse every line.", + 'rejected}; cpt = {text:"..."} (continual pre-training, raw text);', + 'tts = {wav_fn:"train/xxx.wav", text:"..."} (audio fine-tuning);', + 'image = {img_path:"..."} (image generation). With no --schema, a record', + "carrying wav_fn is validated as TTS, img_path as image, chosen/rejected", + "as DPO, text (no messages) as CPT, otherwise ChatML. Pass --schema to", + "require a specific shape on every record. ZIP archives (.zip) are", + "validated structurally (data.jsonl present, media references resolve) in", + "addition to per-record content checks. Use --full-validate to JSON.parse", + "every line.", ], async run(ctx) { const { settings, flags } = ctx; const filePath = flags.file; const schema = parseDatasetSchemaFlag(flags.schema); + if (schema === "video") { + throw new BailianError( + `--schema video is not supported.`, + ExitCode.USAGE, + `Supported schemas: chatml, dpo, cpt, tts, image.`, + ); + } const format = detectOutputFormat(settings.output); if (settings.dryRun) { diff --git a/packages/commands/src/commands/deploy/create.ts b/packages/commands/src/commands/deploy/create.ts index 376a91c..60e1857 100644 --- a/packages/commands/src/commands/deploy/create.ts +++ b/packages/commands/src/commands/deploy/create.ts @@ -2,11 +2,16 @@ import { defineCommand, detectOutputFormat, createDeployment, + pickPlanStrategy, + STRATEGIES, + defaultDeployPlan, + type DeployModality, type CreateDeploymentRequest, + type CreatePlanFlags, + type CommandContext, type FlagsDef, } from "bailian-cli-core"; import { emitResult, emitBare } from "bailian-cli-runtime"; -import { pickPlanStrategy, STRATEGIES } from "./plans.ts"; const CREATE_FLAGS = { model: { @@ -26,10 +31,10 @@ const CREATE_FLAGS = { valueHint: "", description: "Billing plan: lora (default, Token-billed) | ptu (Token-billed) | mu", }, - templateId: { + deploySpec: { type: "string", valueHint: "", - description: "Template id (only used by plan=mu; auto-picked if omitted)", + description: "Deploy spec (only used by plan=mu; auto-picked if omitted)", }, capacity: { type: "number", @@ -58,104 +63,156 @@ const CREATE_FLAGS = { }, } satisfies FlagsDef; +const CREATE_USAGE = + "--model --name [--plan ] [--deploy-spec ] [--capacity ] [--billing-method ] [--input-tpm ] [--output-tpm ] [--thinking-output-tpm ]"; + +const CREATE_NOTES = [ + "Plan defaults to `lora` (Token-billed) for text/image and `mu` (model-unit-", + "billed) for audio (CosyVoice TTS). Pass --plan to override.", + "For plan=ptu (Token-billed, provisioned throughput), --input-tpm and", + "--output-tpm are required (the platform rejects creation without an", + "explicit ptu_capacity despite the doc listing defaults).", + "For plan=mu, `capacity`, `billing_method` and `deploy_spec` are required.", + "billing_method defaults to POST_PAY (only supported value); deploy_spec", + "and capacity are auto-picked from GET /deployments/models when omitted.", + "Use `bl deploy models --source base` to inspect available templates.", + "After creation, status starts at PENDING and transitions to RUNNING.", + "Invoke the deployed model with: bl text chat --model ", + "WARNING: --model is overloaded across commands and refers to DIFFERENT", + "values. `bl deploy create --model` takes the exported model_name", + "(e.g. `qwen3-8b-ft-...`), but the create response also returns a", + "`deployed_model` field (the deployment instance id, e.g.", + "`qwen3-8b-5ecb5f068d79`). The inference call `bl text chat --model` must use", + "the `deployed_model` from the create response — NOT the `model_name` you", + "passed to `deploy create`. Do not reuse the value across the two", + "commands.", +]; + /** - * `bl deploy create` — create a model deployment. - * - * Plan-specific behaviour (required flags / body assembly / auto-pick) lives - * in `plans.ts` (`PlanStrategy` + `STRATEGIES`). This file only handles the - * shared envelope: flag validation, dispatch, dry-run, and result - * formatting. Adding a new plan = one entry in the strategy table; - * nothing here changes. + * Shared `deploy create` flag validation. Plan support is + * server-catalog-driven, so validation is identical for every modality: resolve + * the effective plan (modality-specific default when --plan is omitted), reject + * an unknown --plan, then defer to the plan strategy's required-flag check. + */ +function validateCreate(modality: DeployModality, flags: CreatePlanFlags): string | undefined { + const plan = flags.plan || defaultDeployPlan(modality); + const strategy = STRATEGIES[plan]; + if (!strategy) { + return `Unsupported plan "${plan}". Supported plans: ${Object.keys(STRATEGIES).join(", ")}.`; + } + return strategy.validateFlags(flags); +} + +/** + * Shared `deploy create` implementation. deploy create takes a model + * by name and a billing plan — it does NOT inspect data modality for the request + * body, so the run logic is identical across text / audio / image. The modality + * only fixes the default plan (audio → mu, text/image → lora) and the command + * path / description / examples. * - * `--model` (model identifier) and `--name` (console display name) are required. + * Plan-specific behaviour (required flags / body assembly / auto-pick) lives in + * core `plans.ts` (`PlanStrategy` + `STRATEGIES`). This file only handles the + * shared envelope: dispatch, dry-run, and result formatting. */ -export default defineCommand({ - description: "Create a model deployment", +async function runCreate( + modality: DeployModality, + ctx: CommandContext, +): Promise { + const { identity, settings, flags } = ctx; + const model = flags.model as string; + const name = flags.name as string; + const plan = (flags.plan as string | undefined) || defaultDeployPlan(modality); + const format = detectOutputFormat(settings.output); + + // Plan-specific behaviour is owned by core `plans.ts`. The strategy resolves + // the plan-specific body fragment (mu may auto-pick a template from the + // deployable-models catalog). Anything outside the strategy table was + // already rejected by `validate` above. + const strategy = pickPlanStrategy(plan); + + const resolved = await strategy.resolve({ + client: ctx.client, + dryRun: settings.dryRun, + binName: identity.binName, + flags: flags as CreatePlanFlags, + model, + name, + }); + const body: Record = { + model_name: model, + name, + plan, + ...resolved.body, + }; + + if (settings.dryRun) { + emitResult({ action: "deploy.create", body }, format); + return; + } + + const response = await createDeployment(ctx.client, body as CreateDeploymentRequest); + const deployment = response.output ?? response.data; + + if (settings.quiet) { + emitBare(deployment?.deployed_model ?? ""); + } else if (format === "text") { + emitBare(`Created deployment.`); + if (deployment?.deployed_model) emitBare(` deployed_model: ${deployment.deployed_model}`); + if (deployment?.status) emitBare(` status: ${deployment.status}`); + if (deployment?.plan) emitBare(` plan: ${deployment.plan}`); + emitBare( + `\nNext: track readiness with: ${identity.binName} deploy get --deployed-model ${deployment?.deployed_model ?? ""}`, + ); + } else { + emitResult(response, format); + } +} + +/** `bl deploy text create` — deploy a text model. */ +export const deployTextCreate = defineCommand({ + description: "Create a text model deployment", auth: "apiKey", - usageArgs: - "--model --name [--plan ] [--template-id ] [--capacity ] [--billing-method ] [--input-tpm ] [--output-tpm ] [--thinking-output-tpm ]", + usageArgs: CREATE_USAGE, flags: CREATE_FLAGS, exampleArgs: [ "--model my-qwen-sft --name my-sft-test", "--model qwen3.6-flash-2026-04-16 --name my-flash --plan ptu --input-tpm 10000 --output-tpm 1000", "--model qwen3-8b --name my-qwen3-mu --plan mu", - "--model qwen3-8b --name my-qwen3 --plan mu --template-id MU1 --capacity 2", - ], - notes: [ - "Plan defaults to `lora` (Token-billed). Pass --plan to override.", - "For plan=ptu (Token-billed, provisioned throughput), --input-tpm and", - "--output-tpm are required (the platform rejects creation without an", - "explicit ptu_capacity despite the doc listing defaults).", - "For plan=mu, `capacity`, `billing_method` and `template_id` are required.", - "billing_method defaults to POST_PAY (only supported value); template_id", - "and capacity are auto-picked from GET /deployments/models when omitted.", - "Use `bl deploy models --source base` to inspect available templates.", - "After creation, status starts at PENDING and transitions to RUNNING.", - "Invoke the deployed model with: bl text chat --model ", - "WARNING: --model is overloaded across commands and refers to DIFFERENT", - "values. `bl deploy create --model` takes the exported model_name (e.g.", - "`qwen3-8b-ft-...`), but the create response also returns a `deployed_model`", - "field (the deployment instance id, e.g. `qwen3-8b-5ecb5f068d79`). The", - "inference call `bl text chat --model` must use the `deployed_model` from", - "the create response — NOT the `model_name` you passed to `deploy create`.", - "Do not reuse the value across the two commands.", + "--model qwen3-8b --name my-qwen3 --plan mu --deploy-spec MU1 --capacity 2", ], - validate: (flags) => { - const plan = flags.plan || "lora"; - const strategy = STRATEGIES[plan]; - if (!strategy) { - return `Unsupported plan "${plan}". Supported plans: ${Object.keys(STRATEGIES).join(", ")}.`; - } - return strategy.validateFlags(flags); - }, - async run(ctx) { - const { identity, settings, flags } = ctx; - const model = flags.model; - const name = flags.name; - const plan = flags.plan || "lora"; - const format = detectOutputFormat(settings.output); - - // Plan-specific behaviour is owned by `plans.ts`. The strategy resolves - // the plan-specific body fragment (mu may auto-pick a template from the - // deployable-models catalog). Anything outside the strategy table was - // already rejected by `validate` above. - const strategy = pickPlanStrategy(plan); - - const resolved = await strategy.resolve({ - client: ctx.client, - dryRun: settings.dryRun, - binName: identity.binName, - flags, - model, - name, - }); - const body: Record = { - model_name: model, - name, - plan, - ...resolved.body, - }; - - if (settings.dryRun) { - emitResult({ action: "deploy.create", body }, format); - return; - } + notes: CREATE_NOTES, + validate: (flags) => validateCreate("text", flags), + run: (ctx) => runCreate("text", ctx), +}); - const response = await createDeployment(ctx.client, body as CreateDeploymentRequest); - const deployment = response.output ?? response.data; +/** `bl deploy audio create` — deploy an audio (TTS) model. Defaults to plan=mu. */ +export const deployAudioCreate = defineCommand({ + description: "Create an audio (TTS) model deployment", + auth: "apiKey", + usageArgs: CREATE_USAGE, + flags: CREATE_FLAGS, + exampleArgs: [ + "--model my-cosyvoice-ft --name my-tts", + "--model my-cosyvoice-ft --name my-tts --deploy-spec dps-xxxx --capacity 1", + "--model my-cosyvoice-ft --name my-tts --dry-run", + ], + notes: CREATE_NOTES, + validate: (flags) => validateCreate("audio", flags), + run: (ctx) => runCreate("audio", ctx), +}); - if (settings.quiet) { - emitBare(deployment?.deployed_model ?? ""); - } else if (format === "text") { - emitBare(`Created deployment.`); - if (deployment?.deployed_model) emitBare(` deployed_model: ${deployment.deployed_model}`); - if (deployment?.status) emitBare(` status: ${deployment.status}`); - if (deployment?.plan) emitBare(` plan: ${deployment.plan}`); - emitBare( - `\nNext: track readiness with: ${identity.binName} deploy get --deployed-model ${deployment?.deployed_model ?? ""}`, - ); - } else { - emitResult(response, format); - } - }, +/** `bl deploy image create` — deploy an image generation model. */ +export const deployImageCreate = defineCommand({ + description: "Create an image generation model deployment", + auth: "apiKey", + usageArgs: CREATE_USAGE, + flags: CREATE_FLAGS, + exampleArgs: [ + "--model my-wan-ft --name my-wan", + "--model my-wan-ft --name my-wan-mu --plan mu", + "--model my-wan-ft --name my-wan --dry-run", + ], + notes: CREATE_NOTES, + validate: (flags) => validateCreate("image", flags), + run: (ctx) => runCreate("image", ctx), }); diff --git a/packages/commands/src/commands/deploy/delete.ts b/packages/commands/src/commands/deploy/delete.ts index 3e8560f..8340d09 100644 --- a/packages/commands/src/commands/deploy/delete.ts +++ b/packages/commands/src/commands/deploy/delete.ts @@ -59,8 +59,8 @@ export default defineCommand({ ExitCode.USAGE, ); } - } catch (e) { - if (e instanceof BailianError) throw e; + } catch (error) { + if (error instanceof BailianError) throw error; // If the get itself failed (e.g. not found), let the DELETE call surface the real error. } } diff --git a/packages/commands/src/commands/deploy/list.ts b/packages/commands/src/commands/deploy/list.ts index a2e9610..d26b4e3 100644 --- a/packages/commands/src/commands/deploy/list.ts +++ b/packages/commands/src/commands/deploy/list.ts @@ -68,13 +68,13 @@ export default defineCommand({ return; } const headers = ["DEPLOYED_MODEL", "MODEL_NAME", "STATUS", "PLAN", "CAPACITY", "CREATED_AT"]; - const rows = items.map((i) => [ - i.deployed_model, - i.model_name, - i.status, - i.plan, - i.capacity, - i.created_at, + const rows = items.map((item) => [ + item.deployed_model, + item.model_name, + item.status, + item.plan, + item.capacity, + item.created_at, ]); for (const line of formatTable(headers, rows)) emitBare(line); if (total !== undefined) emitBare(`\nTotal: ${total}`); diff --git a/packages/commands/src/commands/deploy/models.ts b/packages/commands/src/commands/deploy/models.ts index 1b742b5..6bc8daa 100644 --- a/packages/commands/src/commands/deploy/models.ts +++ b/packages/commands/src/commands/deploy/models.ts @@ -73,47 +73,47 @@ export default defineCommand({ // - custom (fine-tuned): top-level supported_plans: string[] // - base (catalog): plans: [{plan, templates?, cu_specs?}] // For json: surface the deployment-relevant fields preserved as a tree, so - // downstream tooling can drive `bl deploy create --template-id <…>` without - // a second round-trip. For text: keep the compact one-line summary. + // downstream tooling can drive `bl deploy create --deploy-spec <…>` + // without a second round-trip. For text: keep the compact one-line summary. if (format === "json") { - const items = models.map((m) => { + const items = models.map((model) => { const out: Record = { - model_name: m.model_name ?? "", + model_name: model.model_name ?? "", }; - if (m.base_model) out.base_model = m.base_model; - if (m.model_source) out.model_source = m.model_source; - if (m.supported_plans && m.supported_plans.length > 0) { - out.supported_plans = m.supported_plans; + if (model.base_model) out.base_model = model.base_model; + if (model.model_source) out.model_source = model.model_source; + if (model.supported_plans && model.supported_plans.length > 0) { + out.supported_plans = model.supported_plans; } - if (m.plans && m.plans.length > 0) { - out.plans = m.plans.map((p) => { - const planEntry: Record = { plan: p.plan ?? "" }; - if (p.cu_specs && p.cu_specs.length > 0) { - planEntry.cu_specs = p.cu_specs; + if (model.plans && model.plans.length > 0) { + out.plans = model.plans.map((plan) => { + const planEntry: Record = { plan: plan.plan ?? "" }; + if (plan.cu_specs && plan.cu_specs.length > 0) { + planEntry.cu_specs = plan.cu_specs; } - if (p.templates && p.templates.length > 0) { - // Pull the top 6 fields most useful for `bl deploy create`. + if (plan.templates && plan.templates.length > 0) { + // Pull the top 6 fields most useful for `bl deploy create`. // Drop noisy/redundant: template_source, template_type, // template_version, deploy_spec (typically == template_id). - planEntry.templates = p.templates.map((t) => { + planEntry.templates = plan.templates.map((template) => { const tpl: Record = {}; - if (t.template_id) tpl.template_id = t.template_id; - if (t.template_name) tpl.template_name = t.template_name; - if (t.charge_type) tpl.charge_type = t.charge_type; + if (template.template_id) tpl.template_id = template.template_id; + if (template.template_name) tpl.template_name = template.template_name; + if (template.charge_type) tpl.charge_type = template.charge_type; // Flatten roles.unified for the common COUPLED case. - const unified = t.roles?.unified; + const unified = template.roles?.unified; if (unified?.model_unit_spec) tpl.model_unit_spec = unified.model_unit_spec; if (unified?.capacity_unit_per_instance !== undefined) tpl.capacity_unit_per_instance = unified.capacity_unit_per_instance; // Preserve split-role configs (SEPERATED) as-is so callers // can still drive prefill/decode sizing. - if (t.roles?.prefill || t.roles?.decode) { + if (template.roles?.prefill || template.roles?.decode) { tpl.roles = { - prefill: t.roles?.prefill, - decode: t.roles?.decode, + prefill: template.roles?.prefill, + decode: template.roles?.decode, }; } - if (t.template_desc) tpl.template_desc = t.template_desc; + if (template.template_desc) tpl.template_desc = template.template_desc; return tpl; }); } @@ -127,19 +127,19 @@ export default defineCommand({ } // text / quiet — keep the compact single-line summary table. - const textItems = models.map((m) => { + const textItems = models.map((model) => { let plansSummary = ""; - if (m.supported_plans && m.supported_plans.length > 0) { - plansSummary = m.supported_plans.join(","); - } else if (m.plans && m.plans.length > 0) { - plansSummary = m.plans - .map((p) => { - const planName = p.plan ?? "?"; - if (p.templates && p.templates.length > 0) { - return `${planName}(${p.templates.length}t)`; + if (model.supported_plans && model.supported_plans.length > 0) { + plansSummary = model.supported_plans.join(","); + } else if (model.plans && model.plans.length > 0) { + plansSummary = model.plans + .map((plan) => { + const planName = plan.plan ?? "?"; + if (plan.templates && plan.templates.length > 0) { + return `${planName}(${plan.templates.length}t)`; } - if (p.cu_specs && p.cu_specs.length > 0) { - return `${planName}(${p.cu_specs.join("/")})`; + if (plan.cu_specs && plan.cu_specs.length > 0) { + return `${planName}(${plan.cu_specs.join("/")})`; } return planName; }) @@ -148,9 +148,9 @@ export default defineCommand({ plansSummary = "-"; } return { - model_name: m.model_name ?? "", - base_model: m.base_model ?? "", - source: m.model_source ?? "", + model_name: model.model_name ?? "", + base_model: model.base_model ?? "", + source: model.model_source ?? "", plans: plansSummary, }; }); @@ -160,7 +160,12 @@ export default defineCommand({ return; } const headers = ["MODEL_NAME", "BASE_MODEL", "SOURCE", "PLANS"]; - const rows = textItems.map((i) => [i.model_name, i.base_model, i.source, i.plans]); + const rows = textItems.map((item) => [ + item.model_name, + item.base_model, + item.source, + item.plans, + ]); for (const line of formatTable(headers, rows)) emitBare(line); if (total !== undefined) emitBare(`\nTotal: ${total}`); }, diff --git a/packages/commands/src/commands/finetune/create.ts b/packages/commands/src/commands/finetune/create.ts index a843c14..8e72375 100644 --- a/packages/commands/src/commands/finetune/create.ts +++ b/packages/commands/src/commands/finetune/create.ts @@ -4,12 +4,12 @@ import { createFineTune, getDataset, uploadDataset, - validateDataset, + detectModality, + getProfile, fetchModelCapability, listSupportedTrainingTypes, preflightBatchSizeGate, isTrainingTypeCli, - toServerTrainingType, TRAINING_TYPES_CLI, DEFAULT_TRAINING_TYPE, formatIssue, @@ -17,10 +17,12 @@ import { ExitCode, type Client, type Settings, + type CommandContext, type CreateFineTuneRequest, type FineTuneHyperParameters, type DatasetFile, - type DatasetSchema, + type TrainingProfile, + type DataModality, type FlagsDef, } from "bailian-cli-core"; import { existsSync, statSync } from "fs"; @@ -77,7 +79,11 @@ async function analyzeDatasetTokens( binName: string, raw: string, label: string, - schema?: DatasetSchema, + profile: TrainingProfile, + modality: DataModality, + model: string, + /** Pre-detected modality for a known path (avoids re-opening the file). */ + knownModality?: { path: string; modality: DataModality }, ): Promise { const tokens = raw .split(",") @@ -109,11 +115,18 @@ async function analyzeDatasetTokens( if (settings.dryRun) continue; - // Local path → validate (same checks as `dataset upload`). Upload is - // deferred to `uploadResolvedLocal` so the gate can run first. The schema - // (SFT vs DPO) is derived from --training-type so a DPO job validates the - // chosen/rejected preference pairs here, not on the platform. - const result = await validateDataset(token, { schema }); + // The command's modality is authoritative; each local file is validated + // under that modality's schema. Reuse the caller's pre-detected modality + // when available to avoid opening the same file twice (matters for large + // ZIPs). + const tokenModality = + knownModality && knownModality.path === token ? knownModality.modality : modality; + + // Local path → validate through the profile. The profile internally routes + // to the correct validator based on modality. Upload is deferred to + // `uploadResolvedLocal` so the gate can run first. `model` is forwarded for + // schema-agnostic cross-checks. + const result = await profile.validate(token, tokenModality, { model }); if (!result.valid) { const lines = [ `Dataset validation failed for ${token}`, @@ -194,25 +207,33 @@ async function uploadResolvedLocal( return uploaded; } -const CREATE_FLAGS = { +/** The modality a `finetune create` subcommand is bound to. */ +type CommandModality = "text" | "audio" | "image"; + +/** + * Flags shared by every `finetune create` subcommand: what to train + * (model), what data to train on (datasets / validations), and how to name the + * output. Every modality's model consumes these. + */ +const COMMON_FLAGS = { model: { type: "string", valueHint: "", - description: "Base model to fine-tune (e.g. qwen3-8b, qwen3-14b)", + description: "Base model to fine-tune", required: true, }, datasets: { type: "string", valueHint: "", description: - "Comma-separated dataset file IDs or local .jsonl paths. Local paths are uploaded (validated) first, then their file-ids are used.", + "Comma-separated dataset file IDs or local paths (.jsonl for text, .zip for audio/image). Local paths are uploaded (validated) first, then their file-ids are used.", required: true, }, validations: { type: "string", valueHint: "", description: - "Comma-separated validation dataset file IDs or local .jsonl paths (auto-uploaded like --datasets).", + "Comma-separated validation dataset file IDs or local paths (auto-uploaded like --datasets).", }, modelName: { type: "string", @@ -224,6 +245,16 @@ const CREATE_FLAGS = { valueHint: "", description: "Output suffix appended by the platform (finetuned_output_suffix)", }, +} satisfies FlagsDef; + +/** + * Text flags: text models consume the full hyper-parameter surface — training + * type selection plus n_epochs / batch_size / learning_rate / max_length (see + * resolveTextHyperParameters). Only text exposes --training-type because only + * text models support types other than the sft-lora default. + */ +const TEXT_FLAGS = { + ...COMMON_FLAGS, trainingType: { type: "string", valueHint: "", @@ -252,247 +283,413 @@ const CREATE_FLAGS = { }, } satisfies FlagsDef; -export default defineCommand({ - description: "Create a fine-tune job (sft | sft-lora | dpo | dpo-lora | cpt)", - auth: "apiKey", - usageArgs: - "--model --datasets [--validations ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ]", - flags: CREATE_FLAGS, - exampleArgs: [ - "--model qwen3-8b --datasets file-xxx", - "--model qwen3-8b --datasets ./train.jsonl", - "--model qwen3-8b --datasets ./train.jsonl --validations ./eval.jsonl", - "--model qwen3-8b --datasets file-aaa,./extra.jsonl", - "--model qwen3-8b --datasets ./train.jsonl --training-type sft", - '--model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4', - "--model qwen3-8b --datasets file-xxx --output json", - "--model qwen3-8b --datasets file-xxx --dry-run", - ], - notes: [ - "Creating a job uploads any local datasets and consumes training quota.", - "Use --dry-run to preview the request body without submitting.", - "Training-type values use the `` / `-lora` convention:", - "sft (full) | sft-lora (LoRA) | dpo (full) | dpo-lora (LoRA) | cpt. These map", - "to the server's training_type at the interface boundary, so the rest of the", - "CLI never sees the raw server strings.", - "Before submitting (non dry-run) the job, the model's training capability is", - "checked via listFoundationModels (no console login required); an unsupported", - "training type fails fast with the list the model actually supports.", - "n_epochs defaults to 3. Other hyper-parameters are platform defaults unless set.", - "Learning rate is forwarded as a string to avoid JSON-number precision loss.", - "--datasets / --validations accept either file-ids (from `dataset upload`)", - "or local .jsonl paths. Local paths are validated and uploaded first, then", - "their file-ids are submitted — a one-step upload-and-train.", - "Dataset record schema is chosen from --training-type: dpo* → {messages,", - "chosen, rejected}; cpt → {text} (raw pre-training text); else {messages}.", - "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).", - ], - async run(ctx) { - const { identity, settings, flags } = ctx; - const model = flags.model; - const datasetsRaw = flags.datasets; - - // Resolve the training type before analyzing datasets so the validator can - // enforce the right record schema (DPO jobs require chosen/rejected on - // every record). Whitelist is the single source of truth in core - // (TRAINING_TYPES_CLI); any other value is rejected up-front. - const trainingType = flags.trainingType || DEFAULT_TRAINING_TYPE; - if (!isTrainingTypeCli(trainingType)) { +/** + * Audio (CosyVoice TTS) flags: the audio model runs sft-lora with a fully fixed + * hyper-parameter set (AUDIO_HYPER_PARAMS). No --training-type or hyper-parameter + * flag is honored by resolveHyperParameters, so none are exposed. + */ +const AUDIO_FLAGS = { + ...COMMON_FLAGS, +} satisfies FlagsDef; + +/** + * Image (Wan generation) flags: the image model runs sft-lora with fixed + * defaults; resolveHyperParameters only honors learning_rate, so --learning-rate + * is the sole extra numeric knob. --generation-type declares T2I vs I2I + * explicitly (the platform expects generation_type as a request field); it is + * required to reach I2I from a bare file-id or in --dry-run, where the data + * cannot be inspected. + */ +const IMAGE_FLAGS = { + ...COMMON_FLAGS, + generationType: { + type: "string", + choices: ["t2i", "i2i"] as const, + valueHint: "", + description: + "Generation type: t2i (default) | i2i. Sets generation_type/max_pixels. Required to train I2I from a file-id or with --dry-run (local data auto-detects input_img).", + }, + learningRate: { + type: "string", + valueHint: "", + description: 'Learning rate as a string to preserve precision (e.g. "3e-5")', + }, +} satisfies FlagsDef; + +const TEXT_USAGE = + "--model --datasets [--validations ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ]"; + +const AUDIO_USAGE = + "--model --datasets [--validations ] [--model-name ] [--suffix ]"; + +const IMAGE_USAGE = + "--model --datasets [--validations ] [--model-name ] [--suffix ] [--generation-type ] [--learning-rate ]"; + +const COMMON_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.", +]; + +const TEXT_NOTES = [ + ...COMMON_NOTES, + "Training-type values use the `` / `-lora` convention:", + "sft (full) | sft-lora (LoRA) | dpo (full) | dpo-lora (LoRA) | cpt. These map", + "to the server's training_type at the interface boundary, so the rest of the", + "CLI never sees the raw server strings.", + "Before submitting (non dry-run) the job, the model's training capability is", + "checked via listFoundationModels (no console login required); an unsupported", + "training type fails fast with the list the model actually supports.", + "n_epochs defaults to 3. Other hyper-parameters are platform defaults unless set.", + "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).", +]; + +const AUDIO_NOTES = [ + ...COMMON_NOTES, + "Audio TTS training runs sft-lora (efficient_sft) with fixed CosyVoice", + "hyper-parameter defaults; there are no training-type or hyper-parameter", + "knobs to set.", +]; + +const IMAGE_NOTES = [ + ...COMMON_NOTES, + "Image generation training runs sft-lora (efficient_sft) with fixed defaults;", + "only --learning-rate is overridable. T2I vs I2I is declared with", + "--generation-type (default t2i), which sets generation_type/max_pixels. For", + "local data the type is auto-detected (records with input_img train I2I);", + "pass --generation-type explicitly to train I2I from a file-id or in --dry-run.", +]; + +/** + * Shared `finetune create` implementation. The parameter surface and + * run logic are identical to the previous single `finetune create`; the ONLY + * change is that the data modality is fixed by the subcommand instead of being + * detected from data content. This is what lets file-id datasets (which have no + * local file to inspect) train the correct model — the old command silently + * defaulted a file-id to "text". + * + * Image is the only modality with a sub-variant (T2I vs I2I). It is upgraded to + * `image-i2i` only when a local file's first record carries `input_img`; a bare + * file-id defaults to plain "image" (T2I), matching the old detection fallback. + */ +async function runCreate( + commandModality: CommandModality, + ctx: CommandContext, +): Promise { + const { identity, settings } = ctx; + const flags = ctx.flags as Record; + const model = flags.model as string; + const datasetsRaw = flags.datasets as string; + + // CosyVoice audio fine-tuning accepts exactly one training file + // (`training_file_ids` supports a single ID per the speech-synthesis + // contract). Reject a multi-token --datasets up-front so the job isn't + // rejected server-side after an upload. + if (commandModality === "audio") { + const audioTokens = datasetsRaw + .split(",") + .map((token) => token.trim()) + .filter(Boolean); + if (audioTokens.length > 1) { throw new BailianError( - `--training-type "${trainingType}" is not supported.`, + `Audio (TTS) fine-tuning accepts exactly one training file, got ${audioTokens.length}.`, ExitCode.USAGE, - `Supported values: ${TRAINING_TYPES_CLI.join(", ")} (default: ${DEFAULT_TRAINING_TYPE}).`, + "Merge your recordings into a single .zip (or pass one file-id).", ); } - // dpo / dpo-lora → "dpo" schema (strict chosen/rejected); cpt → "cpt" - // (raw {text} records); else ChatML ({messages}). - const datasetSchema: DatasetSchema = trainingType.startsWith("dpo") - ? "dpo" - : trainingType === "cpt" - ? "cpt" - : "chatml"; - - const training = await analyzeDatasetTokens( - settings, - identity.binName, - datasetsRaw, - "datasets", - datasetSchema, + } + + // Resolve the training type before analyzing datasets so the validator can + // enforce the right record schema (DPO jobs require chosen/rejected on + // every record). Whitelist is the single source of truth in core + // (TRAINING_TYPES_CLI); any other value is rejected up-front. + const trainingType = (flags.trainingType as string | undefined) || DEFAULT_TRAINING_TYPE; + if (!isTrainingTypeCli(trainingType)) { + throw new BailianError( + `--training-type "${trainingType}" is not supported.`, + ExitCode.USAGE, + `Supported values: ${TRAINING_TYPES_CLI.join(", ")} (default: ${DEFAULT_TRAINING_TYPE}).`, ); - const trainingFileIds = training.fileIds; - - const validation = flags.validations - ? await analyzeDatasetTokens( - settings, - identity.binName, - flags.validations, - "validations", - datasetSchema, - ) - : undefined; - const validationFileIds = validation?.fileIds; - - const modelName = flags.modelName; - const suffix = flags.suffix; - - // Hyper-parameters: inject n_epochs=3 default unless overridden. - const hp: FineTuneHyperParameters = {}; - hp.n_epochs = flags.nEpochs ?? 3; - if (flags.learningRate !== undefined) hp.learning_rate = flags.learningRate; - if (flags.maxLength !== undefined) hp.max_length = flags.maxLength; - - // batch_size: clamp to [8, 1024] (server hard constraint, undocumented). - // Surface the clamp on stderr instead of silently rewriting the user's - // value — otherwise the submitted body would carry a number the user never - // typed, with no audit trail. (Range observed on common SFT / SFT-LoRA - // training types; some bases like qwen3.6-flash report a wider range, so - // the warning explicitly mentions "server range".) - if (flags.batchSize !== undefined) { - const requested = flags.batchSize; - let batchSize = requested; - if (batchSize < 8) batchSize = 8; - if (batchSize > 1024) batchSize = 1024; - if (batchSize !== requested && !settings.quiet) { - process.stderr.write( - `warning: --batch-size ${requested} clamped to ${batchSize} ` + - `(server range [8, 1024] for the common training types).\n`, - ); - } - hp.batch_size = batchSize; - } + } - // Auto batch_size for small datasets: fetch first training file size. - // With default split=0.9, validation_set = 0.1 * rows. - // Platform default batch_size=16 needs rows > 160; batch_size=8 needs rows > 80. - // Files < 100KB are conservatively estimated to have < 200 rows. - // If the first file was just uploaded we already hold its size; otherwise - // fall back to getDataset. - if (hp.batch_size === undefined && !settings.dryRun) { - let sizeBytes = training.firstSize ?? 0; - if (sizeBytes === 0) { - try { - const fileInfo = await getDataset(ctx.client, trainingFileIds[0]); - sizeBytes = fileInfo.data?.size ?? 0; - } catch { - // If we can't fetch file info, skip auto-adjustment; platform will use default. - } - } - if (sizeBytes > 0 && sizeBytes < 100 * 1024) { - hp.batch_size = 8; - } + // Profile: single source of truth for how this training type behaves + // (validation rules, hyper-parameters, gates, capability check). + const profile = getProfile(trainingType); + + // Modality is fixed by the subcommand (no content-based detection) — this is + // the sole behavioural change of the modality split. Image alone has a T2I/I2I + // sub-variant: an explicit --generation-type is authoritative (the only way to + // reach I2I from a bare file-id or in --dry-run, where data can't be + // inspected); otherwise a local file is probed to upgrade T2I → I2I, and a + // bare file-id stays "image" (T2I). + const firstLocalPath = datasetsRaw + .split(",") + .map((token) => token.trim()) + .find((token) => isLocalPath(token)); + let modality: DataModality = commandModality; + if (commandModality === "image") { + const generationType = flags.generationType as "t2i" | "i2i" | undefined; + if (generationType === "i2i") { + modality = "image-i2i"; + } else if (!generationType && firstLocalPath && !settings.dryRun) { + const detected = await detectModality(firstLocalPath); + if (detected === "image-i2i") modality = "image-i2i"; } + } - // Pre-submit batch-size gate: the platform rejects a job whose number of - // training samples is not greater than batch_size, but only surfaces that - // ~10 minutes into the run (after data processing). Fail fast here, before - // burning quota. `recordCount` is only known when every --datasets token - // was a local file we validated; file-id tokens fall through to the - // platform rather than risk a false positive from an undercount. - // - // The decision lives in core (`preflightBatchSizeGate`) — a structured, - // job-level pre-flight that returns a `ValidationIssue` (same shape / stable - // code as `validateDataset`) so the failure surfaces through the same - // `BailianError` + issue convention used by `dataset upload`/`validate`. - // ExitCode.GENERAL matches the existing validation-failed exit code. - if (!settings.dryRun && training.recordCount !== undefined) { - // 16 is the platform default when neither the user nor the small-file - // auto-adjust set a batch_size (see the auto-adjust comment above). - const effectiveBatchSize = hp.batch_size ?? 16; - const gate = preflightBatchSizeGate({ - recordCount: training.recordCount, - batchSize: effectiveBatchSize, - }); - if (!gate.ok && gate.issue) { - throw new BailianError(gate.issue.message, ExitCode.GENERAL, gate.hint); - } + const training = await analyzeDatasetTokens( + settings, + identity.binName, + datasetsRaw, + "datasets", + profile, + modality, + model, + firstLocalPath ? { path: firstLocalPath, modality } : undefined, + ); + const trainingFileIds = training.fileIds; + + const validation = flags.validations + ? await analyzeDatasetTokens( + settings, + identity.binName, + flags.validations as string, + "validations", + profile, + modality, + model, + ) + : undefined; + const validationFileIds = validation?.fileIds; + + const modelName = flags.modelName as string | undefined; + const suffix = flags.suffix as string | undefined; + + // Hyper-parameters: the profile resolves modality-specific defaults + // (text: n_epochs/batch_size/learning_rate; audio: lm_max_epoch/fm_max_epoch/...). + const hp = profile.resolveHyperParameters( + modality, + flags as Record, + ) as FineTuneHyperParameters; + + // Restore the batch-size clamping warning that was lost when the logic moved + // into profiles. The profile silently clamps to [8, 1024]; surface it here + // so the user has an audit trail. Skip modalities that bypass the batch_size + // gate (image): their batch_size is a fixed model-family default, not a + // clamp of the user's value, so the [8, 1024] "clamped" message would be + // self-contradictory and misleading. + if ( + flags.batchSize !== undefined && + hp.batch_size !== undefined && + !settings.quiet && + !profile.shouldSkipGate("batch_size", modality) + ) { + const requested = flags.batchSize as number; + if (hp.batch_size !== requested) { + process.stderr.write( + `warning: --batch-size ${requested} clamped to ${hp.batch_size} ` + + `(server range [8, 1024] for the common training types).\n`, + ); } + } + // For modalities that skip the batch_size gate, warn the user that their + // explicit --batch-size was discarded (model uses a fixed batch_size). + if ( + flags.batchSize !== undefined && + !settings.quiet && + profile.shouldSkipGate("batch_size", modality) + ) { + const requested = flags.batchSize as number; + if (hp.batch_size !== undefined && hp.batch_size !== requested) { + process.stderr.write( + `warning: --batch-size ${requested} ignored for ${modality} training ` + + `(model uses a fixed batch_size of ${hp.batch_size}).\n`, + ); + } + } - // 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 - // be trained against. listFoundationModels is a public API (no console - // login required); on lookup failure (network / 401 / etc.) we fall back - // to letting the server decide rather than blocking the submit. - if (!settings.dryRun) { - let capability: Awaited> | undefined; + // Auto batch_size for small datasets — only for text data. Audio/image + // profiles already set their own batch parameters. + if (modality === "text" && hp.batch_size === undefined && !settings.dryRun) { + let sizeBytes = training.firstSize ?? 0; + if (sizeBytes === 0) { try { - capability = await fetchModelCapability(settings, model); - } catch (error) { - if (!settings.quiet) { - process.stderr.write( - `warning: model capability lookup failed (${(error as Error).message}); ` + - "proceeding without local pre-flight.\n", - ); - } - } - if (capability && !listSupportedTrainingTypes(capability).includes(trainingType)) { - const supported = listSupportedTrainingTypes(capability); - throw new BailianError( - `Model "${model}" does not support training type "${trainingType}".`, - ExitCode.USAGE, - supported.length - ? `This model supports: ${supported.join(", ")}.` - : "This model reports no supported training types.", - ); + const fileInfo = await getDataset(ctx.client, trainingFileIds[0]); + sizeBytes = fileInfo.data?.size ?? 0; + } catch { + // If we can't fetch file info, skip auto-adjustment; platform will use default. } } + if (sizeBytes > 0 && sizeBytes < 100 * 1024) { + hp.batch_size = 8; + } + } + + // Pre-submit batch-size gate: the platform rejects a job whose number of + // training samples is not greater than batch_size, but only surfaces that + // ~10 minutes into the run (after data processing). Fail fast here, before + // burning quota. `recordCount` is only known when every --datasets token + // was a local file we validated; file-id tokens fall through to the + // platform rather than risk a false positive from an undercount. + if ( + !settings.dryRun && + training.recordCount !== undefined && + !profile.shouldSkipGate("batch_size", modality) + ) { + // 16 is the platform default when neither the user nor the small-file + // auto-adjust set a batch_size (see the auto-adjust comment above). + const effectiveBatchSize = hp.batch_size ?? 16; + const gate = preflightBatchSizeGate({ + recordCount: training.recordCount, + batchSize: effectiveBatchSize, + }); + if (!gate.ok && gate.issue) { + throw new BailianError(gate.issue.message, ExitCode.GENERAL, gate.hint); + } + } - // Upload local paths now that pre-flight (validation, batch-size gate, - // capability check) has cleared them. This swaps the - // placeholder path entries in `training.fileIds` / `validation?.fileIds` - // for real file-ids, so the body below sees ids. - if (!settings.dryRun) { - await uploadResolvedLocal(ctx.client, settings, training, "fine-tune", "datasets"); - if (validation) { - await uploadResolvedLocal(ctx.client, settings, validation, "fine-tune", "validations"); + // 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 + // be trained against. listFoundationModels is a public API (no console + // login required); on lookup failure (network / 401 / etc.) we fall back + // to letting the server decide rather than blocking the submit. + if (!settings.dryRun && !profile.shouldSkipCapabilityCheck(modality)) { + let capability: Awaited> | undefined; + try { + capability = await fetchModelCapability(settings, model); + } catch (error) { + if (!settings.quiet) { + process.stderr.write( + `warning: model capability lookup failed (${(error as Error).message}); ` + + "proceeding without local pre-flight.\n", + ); } } + if (capability && !listSupportedTrainingTypes(capability).includes(trainingType)) { + const supported = listSupportedTrainingTypes(capability); + throw new BailianError( + `Model "${model}" does not support training type "${trainingType}".`, + ExitCode.USAGE, + supported.length + ? `This model supports: ${supported.join(", ")}.` + : "This model reports no supported training types.", + ); + } + } - const body: CreateFineTuneRequest = { - model, - training_file_ids: trainingFileIds, - // Map the CLI training type to the server value at the interface boundary. - training_type: toServerTrainingType(trainingType), - hyper_parameters: hp, - }; - if (validationFileIds && validationFileIds.length > 0) { - body.validation_file_ids = validationFileIds; + // Upload local paths now that pre-flight (validation, batch-size gate, + // capability check) has cleared them. This swaps the placeholder path + // entries in `training.fileIds` / `validation?.fileIds` for real file-ids. + if (!settings.dryRun) { + await uploadResolvedLocal(ctx.client, settings, training, "fine-tune", "datasets"); + if (validation) { + await uploadResolvedLocal(ctx.client, settings, validation, "fine-tune", "validations"); } - if (modelName) body.model_name = modelName; - if (suffix) body.finetuned_output_suffix = suffix; + } - const format = detectOutputFormat(settings.output); + const body: CreateFineTuneRequest = { + model, + training_file_ids: trainingFileIds, + // Profile maps the CLI training type to the server value at the boundary. + training_type: profile.serverTrainingType, + hyper_parameters: hp, + }; + if (validationFileIds && validationFileIds.length > 0) { + body.validation_file_ids = validationFileIds; + } + if (modelName) body.model_name = modelName; + if (suffix) body.finetuned_output_suffix = suffix; - if (settings.dryRun) { - const pending = [ - ...training.localPaths.map((path) => ({ field: "datasets", path })), - ...(validation?.localPaths ?? []).map((path) => ({ field: "validations", path })), - ]; - emitResult( - pending.length > 0 - ? { action: "finetune.create", body, pending_uploads: pending } - : { action: "finetune.create", body }, - format, - ); - return; - } + const format = detectOutputFormat(settings.output); - const response = await createFineTune(ctx.client, body); - const job = response.output ?? response.data; - - if (settings.quiet) { - if (job?.job_id) emitBare(job.job_id); - } else if (format === "text") { - if (job?.job_id) { - emitBare(`Created fine-tune job: ${job.job_id}`); - if (job.status) emitBare(`Status: ${job.status}`); - } else { - emitResult(response, format); - } + if (settings.dryRun) { + const pending = [ + ...training.localPaths.map((path) => ({ field: "datasets", path })), + ...(validation?.localPaths ?? []).map((path) => ({ field: "validations", path })), + ]; + emitResult( + pending.length > 0 + ? { action: "finetune.create", body, pending_uploads: pending } + : { action: "finetune.create", body }, + format, + ); + return; + } + + const response = await createFineTune(ctx.client, body); + const job = response.output ?? response.data; + + if (settings.quiet) { + if (job?.job_id) emitBare(job.job_id); + } else if (format === "text") { + if (job?.job_id) { + emitBare(`Created fine-tune job: ${job.job_id}`); + if (job.status) emitBare(`Status: ${job.status}`); } else { emitResult(response, format); } - }, + } else { + emitResult(response, format); + } +} + +/** `bl finetune text create` — fine-tune a text model. Datasets are `.jsonl`. */ +export const finetuneTextCreate = defineCommand({ + description: "Create a text model fine-tune job (sft | sft-lora | dpo | dpo-lora | cpt)", + auth: "apiKey", + usageArgs: TEXT_USAGE, + flags: TEXT_FLAGS, + exampleArgs: [ + "--model qwen3-8b --datasets file-xxx", + "--model qwen3-8b --datasets ./train.jsonl", + "--model qwen3-8b --datasets ./train.jsonl --validations ./eval.jsonl", + "--model qwen3-8b --datasets file-aaa,./extra.jsonl", + "--model qwen3-8b --datasets ./train.jsonl --training-type sft", + '--model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4', + "--model qwen3-8b --datasets file-xxx --output json", + "--model qwen3-8b --datasets file-xxx --dry-run", + ], + notes: TEXT_NOTES, + run: (ctx) => runCreate("text", ctx), +}); + +/** `bl finetune audio create` — fine-tune an audio TTS model. Datasets are `.zip`. */ +export const finetuneAudioCreate = defineCommand({ + description: "Create an audio TTS model fine-tune job (sft-lora)", + auth: "apiKey", + usageArgs: AUDIO_USAGE, + flags: AUDIO_FLAGS, + exampleArgs: [ + "--model cosyvoice-v3-flash --datasets ./audio.zip", + "--model cosyvoice-v3-flash --datasets file-xxx", + "--model cosyvoice-v3-flash --datasets ./audio.zip --model-name my-tts", + "--model cosyvoice-v3-flash --datasets file-xxx --output json", + "--model cosyvoice-v3-flash --datasets ./audio.zip --dry-run", + ], + notes: AUDIO_NOTES, + run: (ctx) => runCreate("audio", ctx), +}); + +/** `bl finetune image create` — fine-tune an image generation model. Datasets are `.zip`. */ +export const finetuneImageCreate = defineCommand({ + description: "Create an image generation model fine-tune job (sft-lora)", + auth: "apiKey", + usageArgs: IMAGE_USAGE, + flags: IMAGE_FLAGS, + exampleArgs: [ + "--model wan2.7-image-pro --datasets ./images.zip", + "--model wan2.7-image-pro --datasets file-xxx", + "--model wan2.7-image-pro --datasets file-xxx --generation-type i2i", + "--model wan2.7-image-pro --datasets ./images.zip --model-name my-wan", + "--model wan2.7-image-pro --datasets file-xxx --output json", + "--model wan2.7-image-pro --datasets ./images.zip --dry-run", + ], + notes: IMAGE_NOTES, + run: (ctx) => runCreate("image", ctx), }); diff --git a/packages/commands/src/commands/finetune/export.ts b/packages/commands/src/commands/finetune/export.ts index 4131fe6..7f3857e 100644 --- a/packages/commands/src/commands/finetune/export.ts +++ b/packages/commands/src/commands/finetune/export.ts @@ -34,9 +34,9 @@ export default defineCommand({ flags: EXPORT_FLAGS, exampleArgs: ["--job-id ft-xxx --checkpoint ckpt-3 --model-name my-qwen-sft"], notes: [ - "Required before `deploy create` can target a checkpoint. The platform", - "may auto-export the best checkpoint when a job reaches SUCCEEDED — explicit", - "export is the canonical path for non-best checkpoints.", + "Required before `deploy create` can target a checkpoint. The", + "platform may auto-export the best checkpoint when a job reaches SUCCEEDED —", + "explicit export is the canonical path for non-best checkpoints.", ], async run(ctx) { const { identity, settings, flags } = ctx; @@ -66,7 +66,9 @@ export default defineCommand({ emitBare(exported); } else if (format === "text") { emitBare(`Exported ${jobId} / ${checkpoint} → model_name=${exported}`); - emitBare(`Next: ${identity.binName} deploy create --model ${exported} --name `); + emitBare( + `Next: ${identity.binName} deploy text create --model ${exported} --name `, + ); } else { emitResult(response, format); } diff --git a/packages/commands/src/commands/finetune/get.ts b/packages/commands/src/commands/finetune/get.ts index 3bb2d6c..d661c79 100644 --- a/packages/commands/src/commands/finetune/get.ts +++ b/packages/commands/src/commands/finetune/get.ts @@ -71,7 +71,7 @@ export default defineCommand({ if (item.hyper_params) emitBare(`hyper_params: ${item.hyper_params}`); if (item.output_model) emitBare( - `output_model: ${item.output_model} (→ ${identity.binName} deploy create --model)`, + `output_model: ${item.output_model} (→ ${identity.binName} deploy text create --model)`, ); if (item.model_name) emitBare(`model_name: ${item.model_name}`); if (item.created_at) emitBare(`created_at: ${item.created_at}`); diff --git a/packages/commands/src/commands/finetune/list.ts b/packages/commands/src/commands/finetune/list.ts index b42cf4f..d8d822d 100644 --- a/packages/commands/src/commands/finetune/list.ts +++ b/packages/commands/src/commands/finetune/list.ts @@ -75,6 +75,8 @@ export default defineCommand({ ]); for (const line of formatTable(headers, rows)) emitBare(line); if (total !== undefined) emitBare(`\nTotal: ${total}`); - emitBare(`Tip: OUTPUT_MODEL is the input for \`${identity.binName} deploy create --model\``); + emitBare( + `Tip: OUTPUT_MODEL is the input for \`${identity.binName} deploy text create --model\``, + ); }, }); diff --git a/packages/commands/src/commands/finetune/watch.ts b/packages/commands/src/commands/finetune/watch.ts index 9a496f3..1eb589a 100644 --- a/packages/commands/src/commands/finetune/watch.ts +++ b/packages/commands/src/commands/finetune/watch.ts @@ -1,15 +1,16 @@ -import { defineCommand, detectOutputFormat, getFineTune, type FlagsDef } from "bailian-cli-core"; +import { + defineCommand, + detectOutputFormat, + getFineTune, + BailianError, + ExitCode, + type FlagsDef, +} from "bailian-cli-core"; import { emitResult, emitBare } from "bailian-cli-runtime"; const DEFAULT_INTERVAL_SEC = 10; const MIN_INTERVAL_SEC = 1; const TERMINAL_STATUSES = new Set(["SUCCEEDED", "FAILED", "CANCELED"]); -/** SIGINT exit code (128 + signal 2). */ -const EXIT_INTERRUPTED = 130; -const EXIT_FAILED = 1; -const EXIT_TIMEOUT = 2; -/** Non-terminal status: the job is still running. Distinct from failure. */ -const EXIT_RUNNING = 3; function nowStamp(): string { const date = new Date(); @@ -25,18 +26,6 @@ function formatElapsed(milliseconds: number): string { return `${minutes}m ${seconds}s`; } -/** - * Exit code for a status value: - * SUCCEEDED -> 0 - * FAILED / CANCELED -> 1 - * anything else -> 3 (still running) - */ -function exitCodeForStatus(status: string): number { - if (status === "SUCCEEDED") return 0; - if (TERMINAL_STATUSES.has(status)) return EXIT_FAILED; - return EXIT_RUNNING; -} - /** * Resolve after `milliseconds`, rejecting early if `signal` aborts (Ctrl-C). * Cleans up its timer + listener so nothing leaks between polls. @@ -101,9 +90,9 @@ export default defineCommand({ "Default (no --follow) is a NON-BLOCKING single status probe: one fetch, then", "return immediately. This is the mode meant for agents / scripts — the caller", "owns the polling cadence, so the CLI never holds the terminal.", - "Exit codes (both modes): 0 SUCCEEDED | 1 FAILED/CANCELED | 2 --poll-timeout", - "exceeded (--follow) | 3 still running (non-terminal, default mode) | 130", - "interrupted (Ctrl-C).", + "A terminal FAILED/CANCELED status raises a normal CLI error (non-zero exit);", + "a SUCCEEDED or still-running status returns 0. With --follow, exceeding", + "--poll-timeout raises a timeout error.", "Use --follow for the blocking, human-terminal-follow experience; use the", "default mode when driving the loop yourself (e.g. from an agent).", "For per-step training output (not status), use `finetune logs`.", @@ -130,32 +119,34 @@ export default defineCommand({ return; } - // Exit codes here are a public probe contract (0 succeeded / 1 failed / 2 - // timeout / 3 still running / 130 interrupted) — deliberately routed via - // process.exit instead of the central error handler. - // ---- Default: non-blocking single status probe ------------------------- + // A terminal FAILED/CANCELED status is surfaced as a BailianError (the + // central handler prints it and exits non-zero); SUCCEEDED and still-running + // both return normally. No process.exit / custom exit-code contract. if (!follow) { const response = await getFineTune(ctx.client, jobId); const job = response.output ?? response.data; const status = String(job?.status ?? "").toUpperCase(); const terminal = TERMINAL_STATUSES.has(status); - const code = exitCodeForStatus(status); if (settings.quiet) { // Just the status word — ideal for `status=$(... finetune watch ... --quiet)`. emitBare(status || "UNKNOWN"); } else if (format === "text") { emitBare(`${nowStamp()} ${jobId} ${status || "UNKNOWN"}`); - if (terminal) { - const mark = status === "SUCCEEDED" ? "✓" : "✗"; - emitBare(`${mark} ${jobId} ${status}`); - } + if (status === "SUCCEEDED") emitBare(`✓ ${jobId} ${status}`); } else { // json: a compact, purpose-built status probe. emitResult({ job_id: jobId, status: status || "UNKNOWN", terminal }, format); } - process.exit(code); + + if (terminal && status !== "SUCCEEDED") { + throw new BailianError( + `Fine-tune job ${jobId} ended in status ${status}.`, + ExitCode.GENERAL, + ); + } + return; } // ---- --follow: blocking poll loop (legacy behavior) ------------------- @@ -182,28 +173,35 @@ export default defineCommand({ const elapsed = Date.now() - startedAt; if (format !== "text" || settings.quiet) { emitResult(response, format); - } else { - const mark = status === "SUCCEEDED" ? "✓" : "✗"; - emitBare(`\n${mark} ${jobId} ${status} (elapsed ${formatElapsed(elapsed)})`); + } else if (status === "SUCCEEDED") { + emitBare(`\n✓ ${jobId} ${status} (elapsed ${formatElapsed(elapsed)})`); + } + if (status !== "SUCCEEDED") { + throw new BailianError( + `Fine-tune job ${jobId} ended in status ${status} (elapsed ${formatElapsed(elapsed)}).`, + ExitCode.GENERAL, + ); } - process.exit(exitCodeForStatus(status)); + return; } if (pollTimeoutSec !== undefined && (Date.now() - startedAt) / 1000 >= pollTimeoutSec) { - if (format === "text" && !settings.quiet) { - emitBare( - `\n⏼ ${jobId} timed out after ${formatElapsed(Date.now() - startedAt)} (last status: ${status || "UNKNOWN"})`, - ); - } - process.exit(EXIT_TIMEOUT); + throw new BailianError( + `Watching fine-tune job ${jobId} timed out after ` + + `${formatElapsed(Date.now() - startedAt)} (last status: ${status || "UNKNOWN"}).`, + ExitCode.TIMEOUT, + ); } await sleep(intervalSec * 1000, controller.signal); } } catch (error) { + // Ctrl-C aborts the poll loop: report and return normally (no custom code). + // Any other error (including the BailianError thrown above) propagates to + // the central handler. if (controller.signal.aborted) { emitBare("\nInterrupted."); - process.exit(EXIT_INTERRUPTED); + return; } throw error; } finally { diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index d8467a7..c3d857a 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -55,7 +55,11 @@ export { default as datasetList } from "./commands/dataset/list.ts"; export { default as datasetGet } from "./commands/dataset/get.ts"; export { default as datasetDelete } from "./commands/dataset/delete.ts"; export { default as datasetValidate } from "./commands/dataset/validate.ts"; -export { default as finetuneCreate } from "./commands/finetune/create.ts"; +export { + finetuneTextCreate, + finetuneAudioCreate, + finetuneImageCreate, +} from "./commands/finetune/create.ts"; export { default as finetuneList } from "./commands/finetune/list.ts"; export { default as finetuneGet } from "./commands/finetune/get.ts"; export { default as finetuneCancel } from "./commands/finetune/cancel.ts"; @@ -65,7 +69,11 @@ export { default as finetuneCheckpoints } from "./commands/finetune/checkpoints. export { default as finetuneExport } from "./commands/finetune/export.ts"; export { default as finetuneWatch } from "./commands/finetune/watch.ts"; export { default as finetuneCapability } from "./commands/finetune/capability.ts"; -export { default as deployCreate } from "./commands/deploy/create.ts"; +export { + deployTextCreate, + deployAudioCreate, + deployImageCreate, +} from "./commands/deploy/create.ts"; export { default as deployList } from "./commands/deploy/list.ts"; export { default as deployGet } from "./commands/deploy/get.ts"; export { default as deployModels } from "./commands/deploy/models.ts"; diff --git a/packages/core/package.json b/packages/core/package.json index 4db5fa5..41906d3 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -40,10 +40,12 @@ "check": "vp check" }, "dependencies": { - "yaml": "^2.8.3" + "yaml": "^2.8.3", + "yauzl": "catalog:" }, "devDependencies": { "@types/node": "catalog:", + "@types/yauzl": "catalog:", "@typescript/native-preview": "7.0.0-dev.20260328.1", "typescript": "^6.0.2", "vite-plus": "catalog:" diff --git a/packages/core/src/dataset/index.ts b/packages/core/src/dataset/index.ts index d1e73a9..cc605c4 100644 --- a/packages/core/src/dataset/index.ts +++ b/packages/core/src/dataset/index.ts @@ -1,11 +1,13 @@ export * from "./types.ts"; export * from "./api.ts"; +export { detectModality } from "./inspect.ts"; export { validateDataset, pickValidator, registerValidator, listSupportedFormats, MAX_DATASET_BYTES, + MAX_MEDIA_ZIP_BYTES, parseDatasetSchemaFlag, formatIssue, } from "./validate/index.ts"; diff --git a/packages/core/src/dataset/inspect.ts b/packages/core/src/dataset/inspect.ts new file mode 100644 index 0000000..9a556ae --- /dev/null +++ b/packages/core/src/dataset/inspect.ts @@ -0,0 +1,209 @@ +/** + * Data inspector — lightweight content parser that determines the modality + * of a training data file. + * + * The inspector peeks at the first non-blank line of a JSONL file (or the + * `data.jsonl` manifest inside a ZIP) and inspects the record's fields to + * decide whether the data carries text, audio, image, or video samples. + * + * This is intentionally shallow — it reads at most one record — so it stays + * fast even on very large files. The full structural validation is the job + * of the format-specific validator (`jsonl.ts`, `zip.ts`), not this module. + * + * Routing in `create.ts`: + * 1. `--training-type` → Profile (via `getProfile`) + * 2. Profile.acceptedExtensions → match file extension + * 3. `detectModality(filePath)` → "text" | "audio" | "image" | "video" + * 4. Profile validates / resolves hyper-params using detected modality + */ +import { createReadStream } from "fs"; +import { createInterface } from "readline"; +import { extname } from "path"; +import { BailianError } from "../errors/base.ts"; +import { ExitCode } from "../errors/codes.ts"; +import { openZipAndFindEntry } from "./validate/zip.ts"; +import type { DataModality } from "../finetune/profiles/types.ts"; + +/** + * Inspect a file and return its data modality. + * + * `.jsonl` → read the first non-blank line, parse JSON, check fields. + * `.zip` → locate `data.jsonl` inside the archive, read its first line. + * + * Image data returns `"image"` (T2I) or `"image-i2i"` (I2I, first record + * has `input_img`). Callers that don't distinguish can normalise to `"image"`. + * + * Throws USAGE if the file extension is not `.jsonl` or `.zip`, or if the + * content cannot be parsed. + */ +export async function detectModality(filePath: string): Promise { + const ext = extname(filePath).toLowerCase(); + if (ext === ".jsonl") return detectFromJsonl(filePath); + if (ext === ".zip") return detectFromZip(filePath); + throw new BailianError( + `Cannot inspect file with extension "${ext}". Expected .jsonl or .zip.`, + ExitCode.USAGE, + ); +} + +/** + * Read the first non-blank line of a JSONL file and determine the modality. + */ +async function detectFromJsonl(filePath: string): Promise { + const firstLine = await readFirstNonBlankLine(filePath); + if (!firstLine) { + throw new BailianError( + `JSONL file is empty or contains only blank lines: ${filePath}`, + ExitCode.USAGE, + ); + } + const modality = classifyRecord(firstLine); + // JSONL files are always text data (chatml / dpo / cpt). + return modality === "unknown" ? "text" : modality; +} + +/** + * Locate `data.jsonl` inside a ZIP archive, extract its first non-blank line, + * and determine the modality. + * + * Uses `yauzl` for streaming access — only the target entry is read, the rest + * of the archive is skipped. + */ +async function detectFromZip(filePath: string): Promise { + const firstLine = await readFirstLineFromZipEntry(filePath, "data.jsonl"); + if (!firstLine) { + throw new BailianError( + `ZIP archive does not contain "data.jsonl" or it is empty: ${filePath}`, + ExitCode.USAGE, + `Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`, + ); + } + const modality = classifyRecord(firstLine); + if (modality === "unknown") { + throw new BailianError( + `ZIP data.jsonl does not match any supported media format ` + + `(expected wav_fn / img_path / first_frame_path / video_path): ${filePath}`, + ExitCode.USAGE, + `ZIP archives are for audio/image/video training data. ` + + `For text data, use a .jsonl file instead.`, + ); + } + return modality; +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/** Classify a JSON record into a data modality based on its field names. */ +function classifyRecord(line: string): DataModality | "unknown" { + let record: Record; + try { + record = JSON.parse(line); + } catch { + throw new BailianError( + `Failed to parse first JSON record for modality detection: ${line.slice(0, 120)}`, + ExitCode.USAGE, + ); + } + if (typeof record !== "object" || record === null || Array.isArray(record)) { + throw new BailianError( + `Expected a JSON object as the first record, got ${Array.isArray(record) ? "array" : typeof record}.`, + ExitCode.USAGE, + ); + } + if ("wav_fn" in record) return "audio"; + if ("img_path" in record) { + // Image generation: distinguish T2I (no input_img) from I2I (has input_img). + // The subtype drives hyper-parameter defaults (max_pixels 2k vs 1k). + return "input_img" in record ? "image-i2i" : "image"; + } + if ("first_frame_path" in record || "video_path" in record) { + // Video generation (Wan i2v/kf2v): distinguish first-frame-only (i2v) from + // first+last-frame (kf2v, has last_frame_path). The subtype lets the + // profile cross-check the chosen --model against the data shape. + return "last_frame_path" in record ? "video-kf2v" : "video"; + } + // No known media field found — caller decides how to handle. + return "unknown"; +} + +/** Read the first non-blank line from a file using a readline stream. */ +function readFirstNonBlankLine(filePath: string): Promise { + return new Promise((resolve, reject) => { + const stream = createReadStream(filePath, { encoding: "utf8" }); + const rl = createInterface({ input: stream, crlfDelay: Infinity }); + let found = false; + rl.on("line", (line) => { + if (found) return; + const trimmed = line.trim(); + if (trimmed.length === 0) return; + found = true; + rl.close(); + stream.destroy(); + resolve(trimmed); + }); + rl.on("close", () => { + if (!found) resolve(null); + }); + rl.on("error", reject); + stream.on("error", reject); + }); +} + +/** + * Open a ZIP archive, locate the entry with the given name, and return the + * first non-blank line from its content. Returns `null` if the entry is not + * found or is empty. + * + * Delegates ZIP open/locate to the shared `openZipAndFindEntry` helper in + * `validate/zip.ts` — avoids duplicating yauzl boilerplate. + */ +function readFirstLineFromZipEntry(zipPath: string, entryName: string): Promise { + return openZipAndFindEntry(zipPath, entryName) + .then(({ entry, zipfile }) => { + return new Promise((resolve, reject) => { + zipfile.openReadStream(entry, (streamErr, readStream) => { + if (streamErr || !readStream) { + zipfile.close(); + reject( + new BailianError( + `Failed to read "${entryName}" from ZIP: ${streamErr?.message}`, + ExitCode.USAGE, + ), + ); + return; + } + const rl = createInterface({ input: readStream, crlfDelay: Infinity }); + let found = false; + rl.on("line", (line) => { + if (found) return; + const trimmed = line.trim(); + if (trimmed.length === 0) return; + found = true; + rl.close(); + readStream.destroy(); + zipfile.close(); + resolve(trimmed); + }); + rl.on("close", () => { + if (!found) { + zipfile.close(); + resolve(null); + } + }); + rl.on("error", (readError) => { + zipfile.close(); + reject(readError); + }); + }); + }); + }) + .catch((error) => { + // openZipAndFindEntry rejects when the entry is not found — treat as null. + if (error instanceof Error && error.message.includes("not found in ZIP")) { + return null; + } + throw error; + }); +} diff --git a/packages/core/src/dataset/validate/common.ts b/packages/core/src/dataset/validate/common.ts index 26cc964..17bdbad 100644 --- a/packages/core/src/dataset/validate/common.ts +++ b/packages/core/src/dataset/validate/common.ts @@ -18,6 +18,13 @@ import type { DatasetSchema, ValidationIssue, ValidationStats } from "./types.ts */ export const MAX_DATASET_BYTES = 300 * 1024 * 1024; +/** + * Image / video ZIP size cap — 1 GB per the platform docs (vs 300 MB for + * text / audio). Used by `bl dataset upload` for media schemas and by the + * `sft-lora` training profile for image / video validation. + */ +export const MAX_MEDIA_ZIP_BYTES = 1024 * 1024 * 1024; + export interface PreflightResult { bytes: number; ext: string; @@ -75,11 +82,12 @@ export function emptyStats(): ValidationStats { export function parseDatasetSchemaFlag(value: string | undefined): DatasetSchema | undefined { if (value === undefined || value.trim() === "") return undefined; const v = value.trim(); - if (v === "chatml" || v === "dpo" || v === "cpt") return v; + if (v === "chatml" || v === "dpo" || v === "cpt" || v === "tts" || v === "image" || v === "video") + return v; throw new BailianError( - `Unsupported --schema "${value}". Supported: chatml, dpo, cpt.`, + `Unsupported --schema "${value}". Supported: chatml, dpo, cpt, tts, image.`, ExitCode.USAGE, - `Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, else ChatML).`, + `Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`, ); } diff --git a/packages/core/src/dataset/validate/index.ts b/packages/core/src/dataset/validate/index.ts index ce686ee..42df442 100644 --- a/packages/core/src/dataset/validate/index.ts +++ b/packages/core/src/dataset/validate/index.ts @@ -4,7 +4,7 @@ export { registerValidator, listSupportedFormats, } from "./registry.ts"; -export { MAX_DATASET_BYTES, parseDatasetSchemaFlag } from "./common.ts"; +export { MAX_DATASET_BYTES, MAX_MEDIA_ZIP_BYTES, parseDatasetSchemaFlag } from "./common.ts"; export { formatIssue } from "./format.ts"; export type { ValidatorSpec, diff --git a/packages/core/src/dataset/validate/registry.ts b/packages/core/src/dataset/validate/registry.ts index f59d634..1be491a 100644 --- a/packages/core/src/dataset/validate/registry.ts +++ b/packages/core/src/dataset/validate/registry.ts @@ -16,10 +16,11 @@ import { extname } from "path"; import { BailianError } from "../../errors/base.ts"; import { ExitCode } from "../../errors/codes.ts"; import { jsonlValidator } from "./jsonl.ts"; +import { zipValidator } from "./zip.ts"; import { preflight, MAX_DATASET_BYTES } from "./common.ts"; import type { ValidatorSpec, ValidateOpts, ValidationResult } from "./types.ts"; -const REGISTRY: ValidatorSpec[] = [jsonlValidator]; +const REGISTRY: ValidatorSpec[] = [jsonlValidator, zipValidator]; /** Lookup the validator that handles a given file extension. */ export function pickValidator(filePath: string): ValidatorSpec { diff --git a/packages/core/src/dataset/validate/schemas/image.ts b/packages/core/src/dataset/validate/schemas/image.ts new file mode 100644 index 0000000..daef380 --- /dev/null +++ b/packages/core/src/dataset/validate/schemas/image.ts @@ -0,0 +1,177 @@ +/** + * Image generation record schema — Wan2.x fine-tuning. + * + * Two record flavours share the same schema: + * - **Text-to-image (T2I):** `{"prompt": "...", "img_path": "./x.png"}` + * - **Image-to-image (I2I):** `{"prompt": "...", "input_img": "./in.jpg", "img_path": "./out.jpg"}` + * + * The presence of `img_path` is the distinguishing field — auto-detect picks + * this schema before the ChatML fallback. `input_img` is optional (I2I only). + * + * Image data lives in a ZIP with a flat layout (no `train/` subdirectory). + * File names must be ASCII-only per platform requirements. + */ +import { makeIssue } from "../common.ts"; +import type { ValidationIssue } from "../types.ts"; +import type { RecordSchemaSpec } from "./types.ts"; + +/** Accepted image file extensions (lower-case, with dot). */ +export const IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tiff"]); + +/** + * Check that a path string ends with an accepted image extension. + * Returns the extension (lower-case) or an empty string. + */ +function imageExt(path: string): string { + const dot = path.lastIndexOf("."); + return dot >= 0 ? path.slice(dot).toLowerCase() : ""; +} + +/** + * Warn (non-error) when a filename contains non-ASCII characters. + * The platform requires English-only filenames. + */ +function asciiOnly(value: string): boolean { + return /^[\x20-\x7E]+$/.test(value); +} + +function inspectImageRecord(record: Record, lineNo: number): ValidationIssue[] { + const out: ValidationIssue[] = []; + + // --- prompt (required) --- + if (!("prompt" in record)) { + out.push( + makeIssue("error", "MISSING_PROMPT", `Required field "prompt" is missing.`, { + line: lineNo, + path: "prompt", + }), + ); + } else { + const prompt = record.prompt; + if (typeof prompt !== "string") { + out.push( + makeIssue("error", "INVALID_PROMPT", `"prompt" must be a string (got ${typeof prompt}).`, { + line: lineNo, + path: "prompt", + }), + ); + } else if (prompt.trim().length === 0) { + out.push( + makeIssue("error", "EMPTY_PROMPT", `"prompt" must not be empty / whitespace-only.`, { + line: lineNo, + path: "prompt", + }), + ); + } + } + + // --- img_path (required) --- + if (!("img_path" in record)) { + out.push( + makeIssue("error", "MISSING_IMG_PATH", `Required field "img_path" is missing.`, { + line: lineNo, + path: "img_path", + }), + ); + } else { + const imgPath = record.img_path; + if (typeof imgPath !== "string") { + out.push( + makeIssue( + "error", + "INVALID_IMG_PATH", + `"img_path" must be a string (got ${typeof imgPath}).`, + { line: lineNo, path: "img_path" }, + ), + ); + } else if (imgPath.trim().length === 0) { + out.push( + makeIssue("error", "EMPTY_IMG_PATH", `"img_path" must not be empty.`, { + line: lineNo, + path: "img_path", + }), + ); + } else { + const ext = imageExt(imgPath); + if (!IMAGE_EXTENSIONS.has(ext)) { + out.push( + makeIssue( + "warning", + "UNUSUAL_IMAGE_EXT", + `"img_path" points to a non-standard image extension "${ext || "(none)"}". ` + + `Expected one of: ${[...IMAGE_EXTENSIONS].join(", ")}.`, + { line: lineNo, path: "img_path" }, + ), + ); + } + if (!asciiOnly(imgPath)) { + out.push( + makeIssue( + "error", + "NON_ASCII_IMG_PATH", + `"img_path" must contain only ASCII characters (English filenames required). Got: "${imgPath}".`, + { line: lineNo, path: "img_path" }, + ), + ); + } + } + } + + // --- input_img (optional — present only for I2I records) --- + if ("input_img" in record) { + const inputImg = record.input_img; + if (typeof inputImg !== "string") { + out.push( + makeIssue( + "error", + "INVALID_INPUT_IMG", + `"input_img" must be a string (got ${typeof inputImg}).`, + { line: lineNo, path: "input_img" }, + ), + ); + } else if (inputImg.trim().length === 0) { + out.push( + makeIssue("error", "EMPTY_INPUT_IMG", `"input_img" must not be empty.`, { + line: lineNo, + path: "input_img", + }), + ); + } else { + const ext = imageExt(inputImg); + if (!IMAGE_EXTENSIONS.has(ext)) { + out.push( + makeIssue( + "warning", + "UNUSUAL_INPUT_IMG_EXT", + `"input_img" points to a non-standard image extension "${ext || "(none)"}". ` + + `Expected one of: ${[...IMAGE_EXTENSIONS].join(", ")}.`, + { line: lineNo, path: "input_img" }, + ), + ); + } + if (!asciiOnly(inputImg)) { + out.push( + makeIssue( + "error", + "NON_ASCII_INPUT_IMG", + `"input_img" must contain only ASCII characters (English filenames required). Got: "${inputImg}".`, + { line: lineNo, path: "input_img" }, + ), + ); + } + } + } + + return out; +} + +/** + * Image generation schema. Auto-detect: a record matches when it carries + * `img_path`. Placed before ChatML in the registry so image data is never + * misclassified. + */ +export const imageSchema: RecordSchemaSpec = { + name: "image", + detect: (record) => "img_path" in record, + inspect: inspectImageRecord, +}; diff --git a/packages/core/src/dataset/validate/schemas/index.ts b/packages/core/src/dataset/validate/schemas/index.ts index 742815e..19cdeb8 100644 --- a/packages/core/src/dataset/validate/schemas/index.ts +++ b/packages/core/src/dataset/validate/schemas/index.ts @@ -16,11 +16,21 @@ import type { RecordSchemaSpec } from "./types.ts"; import { chatmlSchema } from "./chatml.ts"; import { cptSchema } from "./cpt.ts"; import { dpoSchema } from "./dpo.ts"; +import { ttsSchema } from "./tts.ts"; +import { imageSchema } from "./image.ts"; +import { videoSchema } from "./video.ts"; -// Order matters: DPO (chosen/rejected) and CPT (text) before ChatML (the -// catch-all fallback). Each keys off a distinguishing field so the three -// partition cleanly — DPO never looks like CPT, etc. -export const RECORD_SCHEMAS: RecordSchemaSpec[] = [dpoSchema, cptSchema, chatmlSchema]; +// Order matters: TTS (wav_fn), image (img_path), video (first_frame_path/ +// video_path), DPO (chosen/rejected) and CPT (text) before ChatML (the catch- +// all fallback). Each keys off a distinguishing field so they partition cleanly. +export const RECORD_SCHEMAS: RecordSchemaSpec[] = [ + ttsSchema, + imageSchema, + videoSchema, + dpoSchema, + cptSchema, + chatmlSchema, +]; /** * Pick the right schema for a single parsed record. diff --git a/packages/core/src/dataset/validate/schemas/tts.ts b/packages/core/src/dataset/validate/schemas/tts.ts new file mode 100644 index 0000000..5e6ab6f --- /dev/null +++ b/packages/core/src/dataset/validate/schemas/tts.ts @@ -0,0 +1,117 @@ +/** + * TTS record schema — `{"wav_fn": "train/xxx.wav", "text": "..."}`. + * + * Used for audio fine-tuning (e.g. CosyVoice v3 Flash). Each JSONL record + * inside the training data ZIP's `data.jsonl` maps a `.wav` file path to its + * transcript. The ZIP validator (`../zip.ts`) calls into this schema via the + * standard `jsonlValidator` pipeline — the schema only owns per-record checks, + * the ZIP-level structural validation is separate. + * + * Auto-detect: a record matches when it carries `wav_fn` — this is unique to + * audio training data and will never collide with ChatML/DPO/CPT. + */ +import { makeIssue } from "../common.ts"; +import type { ValidationIssue } from "../types.ts"; +import type { RecordSchemaSpec } from "./types.ts"; + +function inspectTTSRecord(record: Record, lineNo: number): ValidationIssue[] { + const out: ValidationIssue[] = []; + + // --- wav_fn --- + if (!("wav_fn" in record)) { + out.push( + makeIssue("error", "MISSING_WAV_FN", `Required field "wav_fn" is missing.`, { + line: lineNo, + path: "wav_fn", + }), + ); + } else { + const wavFn = record.wav_fn; + if (typeof wavFn !== "string") { + out.push( + makeIssue("error", "INVALID_WAV_FN", `"wav_fn" must be a string (got ${typeof wavFn}).`, { + line: lineNo, + path: "wav_fn", + }), + ); + } else if (wavFn.trim().length === 0) { + out.push( + makeIssue("error", "EMPTY_WAV_FN", `"wav_fn" must not be empty.`, { + line: lineNo, + path: "wav_fn", + }), + ); + } else { + // CosyVoice requires each wav_fn to reference a `.wav` file placed under + // the `train/` directory (matching the expected ZIP layout). Both are + // hard server-side requirements, so they are surfaced as errors — a + // dataset that violates them passes no useful preflight and would be + // rejected on submit. + if (!wavFn.startsWith("train/")) { + out.push( + makeIssue( + "error", + "WAV_FN_PREFIX", + `"wav_fn" must start with "train/" (got "${wavFn}").`, + { + line: lineNo, + path: "wav_fn", + }, + ), + ); + } + const dotIndex = wavFn.lastIndexOf("."); + const ext = dotIndex >= 0 ? wavFn.slice(dotIndex).toLowerCase() : ""; + if (ext !== ".wav") { + out.push( + makeIssue( + "error", + "INVALID_AUDIO_EXT", + `"wav_fn" must reference a .wav file (got "${ext || "(none)"}"). ` + + `CosyVoice training audio must be WAV.`, + { line: lineNo, path: "wav_fn" }, + ), + ); + } + } + } + + // --- text --- + if (!("text" in record)) { + out.push( + makeIssue("error", "MISSING_TEXT", `Required field "text" is missing.`, { + line: lineNo, + path: "text", + }), + ); + } else { + const text = record.text; + if (typeof text !== "string") { + out.push( + makeIssue("error", "INVALID_TEXT", `"text" must be a string (got ${typeof text}).`, { + line: lineNo, + path: "text", + }), + ); + } else if (text.trim().length === 0) { + out.push( + makeIssue("error", "EMPTY_TEXT", `"text" must not be empty / whitespace-only.`, { + line: lineNo, + path: "text", + }), + ); + } + } + + return out; +} + +/** + * TTS schema. Auto-detect: a record is treated as TTS when it carries `wav_fn`. + * Placed first in the registry so audio data is never misclassified as ChatML. + */ +export const ttsSchema: RecordSchemaSpec = { + name: "tts", + detect: (record) => "wav_fn" in record, + inspect: inspectTTSRecord, +}; diff --git a/packages/core/src/dataset/validate/schemas/video.ts b/packages/core/src/dataset/validate/schemas/video.ts new file mode 100644 index 0000000..9495548 --- /dev/null +++ b/packages/core/src/dataset/validate/schemas/video.ts @@ -0,0 +1,158 @@ +/** + * Video generation record schema — Wan i2v / kf2v fine-tuning. + * + * Two record flavours share the same schema: + * - **Image-to-video, first frame (i2v):** + * `{"prompt": "...", "first_frame_path": "image_1.jpg", "video_path": "video_1.mp4"}` + * - **Image-to-video, first+last frame (kf2v):** + * `{"prompt": "...", "first_frame_path": "image/x_first.jpg", + * "last_frame_path": "image/x_last.jpg", "video_path": "video/x.mp4"}` + * + * The presence of `first_frame_path` / `video_path` is the distinguishing + * signal — auto-detect picks this schema before the ChatML fallback. + * + * `video_path` is OPTIONAL: validation-set records omit the target video (the + * platform generates preview videos from the first frame + prompt at each eval + * checkpoint), so the same schema validates both training and validation zips. + * `last_frame_path` is optional (kf2v only). + * + * Video data lives in a ZIP: i2v is flat, kf2v uses `image/` + `video/` + * subfolders. File names should be ASCII-only per platform requirements. + */ +import { makeIssue } from "../common.ts"; +import type { ValidationIssue } from "../types.ts"; +import type { RecordSchemaSpec } from "./types.ts"; + +/** Accepted image (frame) file extensions (lower-case, with dot). */ +export const VIDEO_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".bmp", ".webp"]); + +/** Accepted video file extensions (lower-case, with dot). */ +export const VIDEO_EXTENSIONS = new Set([".mp4", ".mov"]); + +/** Return the lower-case extension of a path (with dot), or "". */ +function pathExt(path: string): string { + const dot = path.lastIndexOf("."); + return dot >= 0 ? path.slice(dot).toLowerCase() : ""; +} + +/** The platform requires English-only (ASCII) file names. */ +function asciiOnly(value: string): boolean { + return /^[\x20-\x7E]+$/.test(value); +} + +/** + * Validate a required string path field, checking its extension against the + * accepted set and warning on non-ASCII names. Pushes issues into `out`. + */ +function checkPathField( + out: ValidationIssue[], + record: Record, + field: string, + required: boolean, + accepted: Set, + lineNo: number, +): void { + if (!(field in record)) { + if (required) { + out.push( + makeIssue("error", "MISSING_FIELD", `Required field "${field}" is missing.`, { + line: lineNo, + path: field, + }), + ); + } + return; + } + const value = record[field]; + if (typeof value !== "string") { + out.push( + makeIssue("error", "INVALID_FIELD", `"${field}" must be a string (got ${typeof value}).`, { + line: lineNo, + path: field, + }), + ); + return; + } + if (value.trim().length === 0) { + out.push( + makeIssue("error", "EMPTY_FIELD", `"${field}" must not be empty.`, { + line: lineNo, + path: field, + }), + ); + return; + } + const ext = pathExt(value); + if (!accepted.has(ext)) { + out.push( + makeIssue( + "warning", + "UNUSUAL_MEDIA_EXT", + `"${field}" points to a non-standard extension "${ext || "(none)"}". ` + + `Expected one of: ${[...accepted].join(", ")}.`, + { line: lineNo, path: field }, + ), + ); + } + if (!asciiOnly(value)) { + out.push( + makeIssue( + "error", + "NON_ASCII_PATH", + `"${field}" must contain only ASCII characters (English filenames required). Got: "${value}".`, + { line: lineNo, path: field }, + ), + ); + } +} + +function inspectVideoRecord(record: Record, lineNo: number): ValidationIssue[] { + const out: ValidationIssue[] = []; + + // --- prompt (required) --- + if (!("prompt" in record)) { + out.push( + makeIssue("error", "MISSING_PROMPT", `Required field "prompt" is missing.`, { + line: lineNo, + path: "prompt", + }), + ); + } else { + const prompt = record.prompt; + if (typeof prompt !== "string") { + out.push( + makeIssue("error", "INVALID_PROMPT", `"prompt" must be a string (got ${typeof prompt}).`, { + line: lineNo, + path: "prompt", + }), + ); + } else if (prompt.trim().length === 0) { + out.push( + makeIssue("error", "EMPTY_PROMPT", `"prompt" must not be empty / whitespace-only.`, { + line: lineNo, + path: "prompt", + }), + ); + } + } + + // --- first_frame_path (required) --- + checkPathField(out, record, "first_frame_path", true, VIDEO_IMAGE_EXTENSIONS, lineNo); + // --- last_frame_path (optional — kf2v only) --- + checkPathField(out, record, "last_frame_path", false, VIDEO_IMAGE_EXTENSIONS, lineNo); + // --- video_path (optional — training only; validation sets omit it) --- + checkPathField(out, record, "video_path", false, VIDEO_EXTENSIONS, lineNo); + + return out; +} + +/** + * Video generation schema. Auto-detect: a record matches when it carries + * `first_frame_path` or `video_path`. Placed before ChatML in the registry so + * video data is never misclassified. Distinct from image (`img_path`). + */ +export const videoSchema: RecordSchemaSpec = { + name: "video", + detect: (record) => "first_frame_path" in record || "video_path" in record, + inspect: inspectVideoRecord, +}; diff --git a/packages/core/src/dataset/validate/types.ts b/packages/core/src/dataset/validate/types.ts index 9f71615..ea8cfce 100644 --- a/packages/core/src/dataset/validate/types.ts +++ b/packages/core/src/dataset/validate/types.ts @@ -32,10 +32,17 @@ export interface ValidateOpts { * platform ten minutes in. */ schema?: DatasetSchema; + + /** + * Model identifier (`--model`) forwarded for schema-agnostic cross-checks — + * e.g. the video validator uses it to verify a `kf2v` model is paired with + * first+last-frame data. Optional: absent for bare file-id flows. + */ + model?: string; } /** The schemas a `.jsonl` record can be validated against. */ -export type DatasetSchema = "chatml" | "dpo" | "cpt"; +export type DatasetSchema = "chatml" | "dpo" | "cpt" | "tts" | "image" | "video"; export type ValidationSeverity = "error" | "warning"; diff --git a/packages/core/src/dataset/validate/zip.ts b/packages/core/src/dataset/validate/zip.ts new file mode 100644 index 0000000..4309133 --- /dev/null +++ b/packages/core/src/dataset/validate/zip.ts @@ -0,0 +1,363 @@ +/** + * ZIP validator — audio / image / video training data archives. + * + * A training data ZIP must have: + * - `data.jsonl` at the root — the manifest mapping media files to labels. + * - A `train/` subfolder (or media files at the root) referenced by the + * manifest entries. + * + * This validator owns the **ZIP-level structural checks** (entries present, + * references resolve). The **per-record JSONL content validation** is delegated + * to the existing `jsonlValidator` — we extract `data.jsonl` to a temp file, + * run the full pipeline (quickScan + deepCheck + schema dispatch), and stitch + * the results together. + * + * The schema for `data.jsonl` records is passed via `opts.schema` (typically + * `"tts"` for audio). The profile layer decides which schema to use based on + * the detected modality — this validator is schema-agnostic. + */ +import { createReadStream, createWriteStream, mkdirSync, rmSync } from "fs"; +import { createInterface } from "readline"; +import { tmpdir } from "os"; +import { join } from "path"; +import { pipeline } from "stream/promises"; +import { randomBytes } from "crypto"; +import * as yauzl from "yauzl"; +import type { ValidatorSpec, ValidateOpts, ValidationResult, ValidationIssue } from "./types.ts"; +import { makeIssue } from "./common.ts"; +import { jsonlValidator } from "./jsonl.ts"; +import { IMAGE_EXTENSIONS } from "./schemas/image.ts"; + +/** + * Open a ZIP archive and locate a specific entry by name. + * Returns the entry and zipfile handle — **caller must close the zipfile**. + * Normalises entry names (backslash → forward-slash) and supports entries + * at the root or inside subdirectories (matches `name === targetName` or + * `name.endsWith("/${targetName}")`). + * + * Shared by `extractZipEntry` (this file) and `readFirstLineFromZipEntry` + * (inspect.ts) to avoid duplicating yauzl open/iterate/locate boilerplate. + */ +export function openZipAndFindEntry( + zipPath: string, + targetName: string, +): Promise<{ entry: yauzl.Entry; zipfile: yauzl.ZipFile }> { + return new Promise((resolve, reject) => { + yauzl.open(zipPath, { lazyEntries: true }, (err, zipfile) => { + if (err || !zipfile) { + reject(new Error(`Failed to open ZIP: ${err?.message ?? "unknown error"}`)); + return; + } + zipfile.readEntry(); + zipfile.on("entry", (entry) => { + const name = entry.fileName.replace(/\\/g, "/"); + if (name === targetName || name.endsWith(`/${targetName}`)) { + resolve({ entry, zipfile }); + } else { + zipfile.readEntry(); + } + }); + zipfile.on("end", () => { + zipfile.close(); + reject(new Error(`Entry "${targetName}" not found in ZIP`)); + }); + zipfile.on("error", reject); + }); + }); +} + +/** + * Collect all entry paths from a ZIP archive using yauzl. + * Returns normalised forward-slash paths. + */ +function collectZipEntries(zipPath: string): Promise { + return new Promise((resolve, reject) => { + yauzl.open(zipPath, { lazyEntries: true }, (err, zipfile) => { + if (err || !zipfile) { + reject(new Error(`Failed to open ZIP: ${err?.message ?? "unknown error"}`)); + return; + } + const entries: string[] = []; + zipfile.readEntry(); + zipfile.on("entry", (entry) => { + entries.push(entry.fileName.replace(/\\/g, "/")); + zipfile.readEntry(); + }); + zipfile.on("end", () => { + zipfile.close(); + resolve(entries); + }); + zipfile.on("error", reject); + }); + }); +} + +/** + * Extract a single entry from a ZIP archive to a destination path. + */ +async function extractZipEntry( + zipPath: string, + entryName: string, + destPath: string, +): Promise { + const { entry, zipfile } = await openZipAndFindEntry(zipPath, entryName); + return new Promise((resolve, reject) => { + zipfile.openReadStream(entry, (streamErr, readStream) => { + if (streamErr || !readStream) { + zipfile.close(); + reject(streamErr ?? new Error("Failed to open entry stream")); + return; + } + const writeStream = createWriteStream(destPath); + pipeline(readStream, writeStream) + .then(() => { + zipfile.close(); + resolve(); + }) + .catch((pipelineError) => { + zipfile.close(); + reject(pipelineError); + }); + }); + }); +} + +/** + * Read media file references from the first N records of a JSONL file to verify + * that referenced files exist inside the ZIP. + * + * Collects from all known schema fields: `wav_fn` (audio), `img_path` + + * `input_img` (image generation), `first_frame_path` / `last_frame_path` / + * `video_path` (video generation), `image_fn` / `video_fn` (legacy). + */ +async function collectMediaRefs( + jsonlPath: string, + maxLines = 100, +): Promise<{ refs: string[]; totalLines: number }> { + const stream = createReadStream(jsonlPath, { encoding: "utf8" }); + const rl = createInterface({ input: stream, crlfDelay: Infinity }); + const refs: string[] = []; + let totalLines = 0; + for await (const raw of rl) { + totalLines++; + if (refs.length >= maxLines) continue; + const line = raw.trim(); + if (line.length === 0) continue; + try { + const obj = JSON.parse(line) as Record; + if (typeof obj.wav_fn === "string") refs.push(obj.wav_fn); + if (typeof obj.img_path === "string") refs.push(obj.img_path); + if (typeof obj.input_img === "string") refs.push(obj.input_img); + if (typeof obj.first_frame_path === "string") refs.push(obj.first_frame_path); + if (typeof obj.last_frame_path === "string") refs.push(obj.last_frame_path); + if (typeof obj.video_path === "string") refs.push(obj.video_path); + if (typeof obj.image_fn === "string") refs.push(obj.image_fn); + if (typeof obj.video_fn === "string") refs.push(obj.video_fn); + } catch { + // Parse errors are reported by the JSONL validator, not here. + } + } + return { refs, totalLines }; +} + +export const zipValidator: ValidatorSpec = { + format: "zip", + extensions: [".zip"], + + async validate(filePath: string, opts: ValidateOpts): Promise { + const start = Date.now(); + const errors: ValidationIssue[] = []; + const warnings: ValidationIssue[] = []; + + // --- 1. Collect ZIP entries --- + let entries: string[]; + try { + entries = await collectZipEntries(filePath); + } catch (openError) { + return { + valid: false, + format: "zip", + filePath, + errors: [ + makeIssue( + "error", + "ZIP_OPEN_FAILED", + `Could not open ZIP archive: ${(openError as Error).message}`, + ), + ], + warnings: [], + stats: { durationMs: Date.now() - start }, + }; + } + + if (entries.length === 0) { + return { + valid: false, + format: "zip", + filePath, + errors: [makeIssue("error", "ZIP_EMPTY", `ZIP archive contains no entries.`)], + warnings: [], + stats: { durationMs: Date.now() - start }, + }; + } + + // --- 2. Check for data.jsonl --- + const hasDataJsonl = entries.some( + (entry) => entry === "data.jsonl" || entry.endsWith("/data.jsonl"), + ); + if (!hasDataJsonl) { + errors.push( + makeIssue( + "error", + "MISSING_DATA_JSONL", + `ZIP archive must contain "data.jsonl" at the root. ` + + `This file maps media files (e.g. .wav) to their labels.`, + ), + ); + } + + // --- 3. Check for train/ directory (modality-aware) --- + // Audio TTS data uses a train/ subdirectory; image and video generation + // data do not (image is flat; video i2v is flat, kf2v uses image//video/). + // Only warn about missing train/ for audio (schema === "tts" or auto-detect + // when we don't know the schema yet). + const isImageSchema = opts.schema === "image"; + const isVideoSchema = opts.schema === "video"; + const hasTrainDir = entries.some((entry) => entry === "train/" || entry.startsWith("train/")); + // The train/ layout is an audio-TTS convention (media referenced as + // "train/xxx.wav"). It is only meaningful when the archive actually contains + // .wav files — image/video ZIPs (flat, or kf2v's image//video/ layout) + // legitimately have no train/ dir. Gating on .wav presence also fixes the + // auto-detect path (opts.schema undefined), where we would otherwise + // false-warn on every image/video archive. + const hasWavFiles = entries.some((entry) => entry.toLowerCase().endsWith(".wav")); + if (!hasTrainDir && !isImageSchema && !isVideoSchema && hasWavFiles) { + warnings.push( + makeIssue( + "warning", + "NO_TRAIN_DIR", + `No "train/" directory found in the ZIP. Media files are typically ` + + `placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`, + ), + ); + } + + // --- 3b. Minimum image count check (image generation only) --- + // The platform requires at least 25 training images (50+ recommended). + if (isImageSchema) { + const MIN_IMAGES = 25; + const imageFiles = entries.filter((entry) => { + if (entry === "data.jsonl" || entry.endsWith("/data.jsonl")) return false; + if (entry.endsWith("/")) return false; // directory entries + const dot = entry.lastIndexOf("."); + const ext = dot >= 0 ? entry.slice(dot).toLowerCase() : ""; + return IMAGE_EXTENSIONS.has(ext); + }); + if (imageFiles.length < MIN_IMAGES) { + errors.push( + makeIssue( + "error", + "INSUFFICIENT_IMAGES", + `Found ${imageFiles.length} image(s) in ZIP, but image generation fine-tuning ` + + `requires at least ${MIN_IMAGES} images (50+ recommended).`, + ), + ); + } + } + + // If data.jsonl is missing, we can't do JSONL content validation. + if (!hasDataJsonl) { + return { + valid: false, + format: "zip", + filePath, + errors, + warnings, + stats: { totalRecords: entries.length, durationMs: Date.now() - start }, + }; + } + + // --- 4. Extract data.jsonl to a temp file and run jsonlValidator --- + const dataJsonlEntry = entries.find( + (entry) => entry === "data.jsonl" || entry.endsWith("/data.jsonl"), + )!; + const tmpDir = join(tmpdir(), `bl-zip-${randomBytes(6).toString("hex")}`); + mkdirSync(tmpDir, { recursive: true }); + const tmpJsonl = join(tmpDir, "data.jsonl"); + + try { + await extractZipEntry(filePath, dataJsonlEntry, tmpJsonl); + } catch (extractError) { + errors.push( + makeIssue( + "error", + "EXTRACT_FAILED", + `Failed to extract "data.jsonl" from ZIP: ${(extractError as Error).message}`, + ), + ); + rmSync(tmpDir, { recursive: true, force: true }); + return { + valid: false, + format: "zip", + filePath, + errors, + warnings, + stats: { durationMs: Date.now() - start }, + }; + } + + // Delegate JSONL content validation. The profile layer passes opts.schema + // (e.g. "tts") so the right record-schema spec is used. + const jsonlResult = await jsonlValidator.validate(tmpJsonl, opts); + errors.push(...jsonlResult.errors); + warnings.push(...jsonlResult.warnings); + + // --- 5. Verify media file references (sample first 100 records) --- + if (jsonlResult.valid) { + const { refs } = await collectMediaRefs(tmpJsonl); + const entrySet = new Set(entries); + // Media paths in data.jsonl are relative to the manifest's location. Many + // official sample archives wrap everything in a single top-level folder + // (e.g. "wan-i2v-valid-dataset/data.jsonl" alongside + // "wan-i2v-valid-dataset/image_1.jpg"), so a bare "image_1.jpg" ref + // resolves against that folder, not the ZIP root. Derive the manifest's + // directory prefix and accept either the wrapped or root-relative form. + const slash = dataJsonlEntry.lastIndexOf("/"); + const baseDir = slash >= 0 ? dataJsonlEntry.slice(0, slash + 1) : ""; + const danglingRefs: string[] = []; + for (const ref of refs) { + // Normalise: some archives use "train/foo.wav", some use "./train/foo.wav". + const normalised = ref.replace(/^\.\//, ""); + if (entrySet.has(normalised) || entrySet.has(baseDir + normalised)) continue; + danglingRefs.push(ref); + } + if (danglingRefs.length > 0) { + const shown = danglingRefs.slice(0, 5).join(", "); + const suffix = danglingRefs.length > 5 ? ` (and ${danglingRefs.length - 5} more)` : ""; + errors.push( + makeIssue( + "error", + "DANGLING_MEDIA_REFS", + `${danglingRefs.length} media file(s) referenced in data.jsonl not found in ZIP: ${shown}${suffix}`, + ), + ); + } + } + + // --- 6. Clean up --- + rmSync(tmpDir, { recursive: true, force: true }); + + return { + valid: errors.length === 0, + format: "zip", + filePath, + errors, + warnings, + stats: { + totalRecords: jsonlResult.stats.totalRecords ?? entries.length, + sampledRecords: jsonlResult.stats.sampledRecords, + durationMs: Date.now() - start, + }, + }; + }, +}; diff --git a/packages/core/src/deploy/constants.ts b/packages/core/src/deploy/constants.ts new file mode 100644 index 0000000..e918145 --- /dev/null +++ b/packages/core/src/deploy/constants.ts @@ -0,0 +1,58 @@ +/** + * Deploy-domain constants — billing plans, billing methods and template + * charge types. Centralised here so no `deploy` command carries a magic + * string for these server-contract values. + */ + +/** Billing plan (`--plan` value, matches the server's deployment plan). */ +export const DEPLOY_PLAN = { + /** Token-billed; the CLI default. */ + LORA: "lora", + /** Token-billed, provisioned throughput. */ + PTU: "ptu", + /** Model-unit-billed. */ + MU: "mu", +} as const; + +export type DeployPlan = (typeof DEPLOY_PLAN)[keyof typeof DEPLOY_PLAN]; + +/** CLI default plan when `--plan` is omitted. */ +export const DEFAULT_DEPLOY_PLAN: DeployPlan = DEPLOY_PLAN.LORA; + +/** Deployment target modality — fixes the default plan when `--plan` is omitted. */ +export type DeployModality = "text" | "audio" | "image"; + +/** + * Default plan per modality when `--plan` is omitted. + * + * The contract differs by modality (verified against the DashScope docs): + * - text / image LoRA outputs deploy Token-billed (`lora`) — the image + * fine-tune guide's deploy example uses `plan: "lora"`. + * - CosyVoice (audio TTS) outputs deploy model-unit-billed (`mu`) — the + * speech-synthesis guide fixes `plan: "mu"` and requires deploy_spec / + * capacity / billing_method (all auto-picked by the mu strategy). + */ +export function defaultDeployPlan(modality: DeployModality): DeployPlan { + return modality === "audio" ? DEPLOY_PLAN.MU : DEFAULT_DEPLOY_PLAN; +} + +/** Billing method (`billing_method`, plan=mu only). */ +export const BILLING_METHOD = { + /** Post-paid (currently the only server-supported value). */ + POST_PAY: "POST_PAY", + /** Pre-paid. */ + PRE_PAY: "PRE_PAY", +} as const; + +export type BillingMethod = (typeof BILLING_METHOD)[keyof typeof BILLING_METHOD]; + +/** Default billing method for plan=mu when `--billing-method` is omitted. */ +export const DEFAULT_BILLING_METHOD: BillingMethod = BILLING_METHOD.POST_PAY; + +/** Template charge type (`charge_type`) returned by the deployable-models catalog. */ +export const CHARGE_TYPE = { + POST_PAID: "post_paid", + PRE_PAID: "pre_paid", +} as const; + +export type ChargeType = (typeof CHARGE_TYPE)[keyof typeof CHARGE_TYPE]; diff --git a/packages/core/src/deploy/index.ts b/packages/core/src/deploy/index.ts index 9811231..e0515c1 100644 --- a/packages/core/src/deploy/index.ts +++ b/packages/core/src/deploy/index.ts @@ -1,2 +1,4 @@ export * from "./api.ts"; export * from "./types.ts"; +export * from "./constants.ts"; +export * from "./plans.ts"; diff --git a/packages/commands/src/commands/deploy/plans.ts b/packages/core/src/deploy/plans.ts similarity index 68% rename from packages/commands/src/commands/deploy/plans.ts rename to packages/core/src/deploy/plans.ts index 02d886b..ab9835c 100644 --- a/packages/commands/src/commands/deploy/plans.ts +++ b/packages/core/src/deploy/plans.ts @@ -1,5 +1,5 @@ /** - * Per-plan strategy table for `bl deploy create`. + * Per-plan strategy table for `deploy create`. * * Each PlanStrategy owns one slice of plan-specific behaviour: * - required-flag checks (returned as validate-style error strings) @@ -7,18 +7,23 @@ * catalog; lora/ptu are pure) * - the plan-specific body fragment for POST /api/v1/deployments * - * The dispatcher in `create.ts` only knows about `STRATEGIES[plan]`. Adding a - * new plan = one new strategy object + one line in `STRATEGIES`. Nothing in - * `create.ts` needs to change. This collapses the places where lora / ptu / - * mu used to be hard-coded (default value list / required-flag checks / - * auto-pick / body assembly) into one strategy entry per plan. + * The dispatcher in the `deploy create` command only knows about + * `STRATEGIES[plan]`. Adding a new plan = one new strategy object + one line in + * `STRATEGIES`. Nothing in the command needs to change. This collapses the + * places where lora / ptu / mu used to be hard-coded (default value list / + * required-flag checks / auto-pick / body assembly) into one strategy entry per + * plan. */ -import { listDeployableModels, BailianError, ExitCode, type Client } from "bailian-cli-core"; +import { listDeployableModels } from "./api.ts"; +import { BailianError } from "../errors/base.ts"; +import { ExitCode } from "../errors/codes.ts"; +import type { Client } from "../client/client.ts"; +import { DEPLOY_PLAN, BILLING_METHOD, CHARGE_TYPE, DEFAULT_BILLING_METHOD } from "./constants.ts"; -/** Plan-relevant subset of `deploy create` flags (parsed flags satisfy this shape). */ +/** Plan-relevant subset of `deploy create` flags (parsed flags satisfy this shape). */ export interface CreatePlanFlags { plan?: string; - templateId?: string; + deploySpec?: string; capacity?: number; billingMethod?: string; inputTpm?: number; @@ -65,7 +70,7 @@ export interface PlanStrategy { * the CLI injects `1` as a placeholder. */ const loraStrategy: PlanStrategy = { - name: "lora", + name: DEPLOY_PLAN.LORA, validateFlags() { return undefined; /* no required flags */ }, @@ -81,7 +86,7 @@ const loraStrategy: PlanStrategy = { * required. */ const ptuStrategy: PlanStrategy = { - name: "ptu", + name: DEPLOY_PLAN.PTU, validateFlags(flags) { if (flags.inputTpm === undefined || flags.outputTpm === undefined) { return "--input-tpm and --output-tpm are required for plan=ptu."; @@ -101,35 +106,35 @@ const ptuStrategy: PlanStrategy = { }; /** - * `mu` (model-unit-billed). `capacity`, `billing_method` and `template_id` are + * `mu` (model-unit-billed). `capacity`, `billing_method` and `deploy_spec` are * all required by the API but every one has a CLI-side default: * - billing_method defaults to POST_PAY (the only supported value). - * - template_id auto-picks from GET /deployments/models — the one whose + * - deploy_spec auto-picks from GET /deployments/models — the one whose * `charge_type` matches `billing_method`, else the first available. * - capacity defaults to the template's `capacity_unit_per_instance` (the * smallest valid multiple of base_capacity). * - * The catalog lookup is skipped when `--template-id` is supplied explicitly: + * The catalog lookup is skipped when `--deploy-spec` is supplied explicitly: * fine-tuned custom models may not appear in the `source=base` catalog, and * forcing the lookup would otherwise raise a spurious "no template" error. * It is also skipped in dry-run mode to keep `--dry-run` side-effect-free. */ const muStrategy: PlanStrategy = { - name: "mu", + name: DEPLOY_PLAN.MU, validateFlags() { return undefined; /* every required field has a default — nothing to assert up-front */ }, async resolve(ctx: PlanContext): Promise { - const billingMethod = ctx.flags.billingMethod || "POST_PAY"; - let templateId = ctx.flags.templateId; + const billingMethod = ctx.flags.billingMethod || DEFAULT_BILLING_METHOD; + let deploySpec = ctx.flags.deploySpec; let capacity = ctx.flags.capacity; - if (!ctx.dryRun && !templateId) { + if (!ctx.dryRun && !deploySpec) { const noTemplateError = () => new BailianError( `No mu-plan template found for model "${ctx.model}". ` + `Run \`${ctx.binName} deploy models --source base\` to inspect available models, ` + - `or pass --template-id explicitly.`, + `or pass --deploy-spec explicitly.`, ExitCode.USAGE, ); try { @@ -139,23 +144,25 @@ const muStrategy: PlanStrategy = { version: "v1.0", }); const payload = resp.output ?? resp.data; - const target = (payload?.models ?? []).find((m) => m.model_name === ctx.model); - const muPlan = target?.plans?.find((p) => p.plan === "mu"); + const target = (payload?.models ?? []).find((model) => model.model_name === ctx.model); + const muPlan = target?.plans?.find(({ plan }) => plan === DEPLOY_PLAN.MU); const templates = muPlan?.templates ?? []; if (templates.length === 0) throw noTemplateError(); // POST_PAY → post_paid template; fall back to the first available. - const wantChargeType = billingMethod === "POST_PAY" ? "post_paid" : "pre_paid"; - const picked = templates.find((t) => t.charge_type === wantChargeType) ?? templates[0]; - if (!picked?.template_id) throw noTemplateError(); - templateId = picked.template_id; + const wantChargeType = + billingMethod === BILLING_METHOD.POST_PAY ? CHARGE_TYPE.POST_PAID : CHARGE_TYPE.PRE_PAID; + const picked = + templates.find((template) => template.charge_type === wantChargeType) ?? templates[0]; + if (!picked?.deploy_spec && !picked?.template_id) throw noTemplateError(); + deploySpec = picked.deploy_spec ?? picked.template_id; if (capacity === undefined) { capacity = picked.roles?.unified?.capacity_unit_per_instance ?? 1; } - } catch (e) { - if (e instanceof BailianError) throw e; + } catch (error) { + if (error instanceof BailianError) throw error; throw new BailianError( - `Failed to auto-pick template for plan=mu: ${(e as Error).message}. ` + - `Pass --template-id explicitly.`, + `Failed to auto-pick template for plan=mu: ${(error as Error).message}. ` + + `Pass --deploy-spec explicitly.`, ExitCode.USAGE, ); } @@ -165,7 +172,7 @@ const muStrategy: PlanStrategy = { capacity: capacity ?? 1, billing_method: billingMethod, }; - if (templateId) body.template_id = templateId; + if (deploySpec) body.deploy_spec = deploySpec; return { body }; }, }; @@ -173,23 +180,23 @@ const muStrategy: PlanStrategy = { /** * Registry of supported plans. Adding a new plan = one entry here. The * catalog lists some additional plan names (e.g. `ptu_v2`) that are NOT - * accepted by the create endpoint, so the dispatcher in `create.ts` will + * accepted by the create endpoint, so the dispatcher in the command will * reject anything outside this table with a clear USAGE error. */ export const STRATEGIES: Record = { - lora: loraStrategy, - ptu: ptuStrategy, - mu: muStrategy, + [DEPLOY_PLAN.LORA]: loraStrategy, + [DEPLOY_PLAN.PTU]: ptuStrategy, + [DEPLOY_PLAN.MU]: muStrategy, }; /** Throws USAGE if `plan` is not in the strategy table. */ export function pickPlanStrategy(plan: string): PlanStrategy { - const s = STRATEGIES[plan]; - if (!s) { + const strategy = STRATEGIES[plan]; + if (!strategy) { throw new BailianError( `Unsupported plan "${plan}". Supported plans: ${Object.keys(STRATEGIES).join(", ")}.`, ExitCode.USAGE, ); } - return s; + return strategy; } diff --git a/packages/core/src/deploy/types.ts b/packages/core/src/deploy/types.ts index f1a2b05..e7927b8 100644 --- a/packages/core/src/deploy/types.ts +++ b/packages/core/src/deploy/types.ts @@ -119,8 +119,8 @@ export interface CreateDeploymentRequest { plan: string; /** Required by API even for token-billed (lora) plans where it is ignored — CLI injects 1. */ capacity?: number; - /** Optional template id for advanced configurations. */ - template_id?: string; + /** Deploy spec id (e.g. "MU1", "dps-..."), sent as `deploy_spec` in POST body. */ + deploy_spec?: string; /** * PTU capacity (provisioned throughput limits). Only effective when * `plan === "ptu"`. The doc says this defaults to 10000/1000 when omitted, @@ -128,10 +128,29 @@ export interface CreateDeploymentRequest { * info"), so the CLI treats it as required for ptu. */ ptu_capacity?: PtuCapacity; + /** + * AIGC generation config for fine-tuned Wan video (i2v/kf2v) LoRA deployments. + * Ignored by non-video plans. See `AigcConfig`. + */ + aigc_config?: AigcConfig; /** Future-compat: arbitrary additional fields are forwarded as-is. */ [k: string]: unknown; } +/** + * AIGC generation config — used when deploying fine-tuned Wan video (i2v/kf2v) + * LoRA models. Controls how prompts are applied at inference time: + * - use_input_prompt=false: ignore the caller's prompt, use the preset + * `prompt` template instead (the common LoRA case). + * - use_input_prompt=true: honor the caller's prompt. + * `lora_prompt_default` is the default trigger-word phrase appended for the LoRA. + */ +export interface AigcConfig { + use_input_prompt?: boolean; + prompt?: string; + lora_prompt_default?: string; +} + /** PTU throughput limits — only used when `plan === "ptu"`. */ export interface PtuCapacity { /** Max input tokens per minute (all models). */ diff --git a/packages/core/src/finetune/api.ts b/packages/core/src/finetune/api.ts index bba820a..1126c9d 100644 --- a/packages/core/src/finetune/api.ts +++ b/packages/core/src/finetune/api.ts @@ -144,7 +144,7 @@ export async function listCheckpoints( * GET /api/v1/fine-tunes/{job_id}/export/{checkpoint}?model_name={name} * * Publishes a training checkpoint as a deployable model — required before - * `bl deploy create` can target it. The platform may auto-export the best + * `deploy create` can target it. The platform may auto-export the best * checkpoint on SUCCEEDED, but explicit export is the canonical path. */ export async function exportCheckpoint( diff --git a/packages/core/src/finetune/capability.ts b/packages/core/src/finetune/capability.ts index f3c0ecc..314bcd1 100644 --- a/packages/core/src/finetune/capability.ts +++ b/packages/core/src/finetune/capability.ts @@ -57,11 +57,6 @@ export function isTrainingTypeCli(value: string): value is TrainingTypeCli { return value in TRAINING_TYPE_MAP; } -/** Map a CLI training type to the server `training_type` for the request body. */ -export function toServerTrainingType(value: TrainingTypeCli): string { - return TRAINING_TYPE_MAP[value].server; -} - /** The (method, variant) pair a CLI training type resolves to. */ export function trainingTypeMethodVariant(value: TrainingTypeCli): { method: string; diff --git a/packages/core/src/finetune/index.ts b/packages/core/src/finetune/index.ts index b162966..e0b064b 100644 --- a/packages/core/src/finetune/index.ts +++ b/packages/core/src/finetune/index.ts @@ -2,3 +2,4 @@ export * from "./types.ts"; export * from "./api.ts"; export * from "./capability.ts"; export * from "./preflight.ts"; +export * from "./profiles/index.ts"; diff --git a/packages/core/src/finetune/profiles/common.ts b/packages/core/src/finetune/profiles/common.ts new file mode 100644 index 0000000..142e0bb --- /dev/null +++ b/packages/core/src/finetune/profiles/common.ts @@ -0,0 +1,79 @@ +/** + * Shared helpers for training profiles. + * + * Most text-based training types (sft, dpo, cpt, and their -lora variants) + * share the same hyper-parameter resolution logic: n_epochs defaults to 3, + * learning_rate and max_length are set only when explicitly provided, and + * batch_size is clamped to the server's [8, 1024] range. Extracting this + * into a single helper prevents drift when defaults or bounds change. + */ +import type { TrainingProfile, DataModality } from "./types.ts"; +import type { ValidateOpts, ValidationResult } from "../../dataset/validate/types.ts"; +import type { DatasetSchema } from "../../dataset/validate/types.ts"; +import { validateDataset } from "../../dataset/validate/registry.ts"; + +/** + * Resolve text-mode hyper-parameters from CLI flags. + * + * Shared by every profile's text branch (and by profiles that only support + * text). The audio branch in `sft-lora` uses its own `AUDIO_HYPER_PARAMS`. + */ +export function resolveTextHyperParameters( + flags: Record, +): Record { + const hp: Record = {}; + hp.n_epochs = flags.nEpochs !== undefined ? (flags.nEpochs as number) : 3; + if (flags.learningRate !== undefined) hp.learning_rate = flags.learningRate as string; + if (flags.maxLength !== undefined) hp.max_length = flags.maxLength as number; + if (flags.batchSize !== undefined) { + const requested = flags.batchSize as number; + let batchSize = requested; + if (batchSize < 8) batchSize = 8; + if (batchSize > 1024) batchSize = 1024; + hp.batch_size = batchSize; + } + return hp; +} + +/** + * Factory for text-only training profiles (sft, dpo, dpo-lora, cpt). + * + * These profiles are structurally identical — they differ only in three + * string constants (CLI name, server name, record schema). Using a factory + * eliminates four near-identical files and prevents drift when the + * TrainingProfile interface changes. + */ +export function textProfile( + clientTrainingType: string, + serverTrainingType: string, + schema: DatasetSchema, +): TrainingProfile { + return { + clientTrainingType, + serverTrainingType, + acceptedExtensions: [".jsonl"], + + async validate( + filePath: string, + _modality: DataModality, + opts: ValidateOpts, + ): Promise { + return validateDataset(filePath, { ...opts, schema }); + }, + + resolveHyperParameters( + _modality: DataModality, + flags: Record, + ): Record { + return resolveTextHyperParameters(flags); + }, + + shouldSkipGate(_gate: string, _modality: DataModality): boolean { + return false; + }, + + shouldSkipCapabilityCheck(_modality: DataModality): boolean { + return false; + }, + }; +} diff --git a/packages/core/src/finetune/profiles/cpt.ts b/packages/core/src/finetune/profiles/cpt.ts new file mode 100644 index 0000000..ab5aba7 --- /dev/null +++ b/packages/core/src/finetune/profiles/cpt.ts @@ -0,0 +1,7 @@ +/** + * `cpt` profile — Continual Pre-Training (full-parameter). + * Maps to the server's `cpt` training type. CPT record schema. + */ +import { textProfile } from "./common.ts"; + +export const cptProfile = textProfile("cpt", "cpt", "cpt"); diff --git a/packages/core/src/finetune/profiles/dpo-lora.ts b/packages/core/src/finetune/profiles/dpo-lora.ts new file mode 100644 index 0000000..820fbd0 --- /dev/null +++ b/packages/core/src/finetune/profiles/dpo-lora.ts @@ -0,0 +1,7 @@ +/** + * `dpo-lora` profile — LoRA variant of Direct Preference Optimization. + * Maps to the server's `dpo_lora` training type. DPO record schema. + */ +import { textProfile } from "./common.ts"; + +export const dpoLoraProfile = textProfile("dpo-lora", "dpo_lora", "dpo"); diff --git a/packages/core/src/finetune/profiles/dpo.ts b/packages/core/src/finetune/profiles/dpo.ts new file mode 100644 index 0000000..d76e040 --- /dev/null +++ b/packages/core/src/finetune/profiles/dpo.ts @@ -0,0 +1,7 @@ +/** + * `dpo` profile — Direct Preference Optimization (full-parameter). + * Maps to the server's `dpo_full` training type. DPO record schema. + */ +import { textProfile } from "./common.ts"; + +export const dpoProfile = textProfile("dpo", "dpo_full", "dpo"); diff --git a/packages/core/src/finetune/profiles/index.ts b/packages/core/src/finetune/profiles/index.ts new file mode 100644 index 0000000..5f1caf7 --- /dev/null +++ b/packages/core/src/finetune/profiles/index.ts @@ -0,0 +1,2 @@ +export type { TrainingProfile, DataModality } from "./types.ts"; +export { getProfile, listTrainingTypes } from "./registry.ts"; diff --git a/packages/core/src/finetune/profiles/registry.ts b/packages/core/src/finetune/profiles/registry.ts new file mode 100644 index 0000000..8d4531c --- /dev/null +++ b/packages/core/src/finetune/profiles/registry.ts @@ -0,0 +1,50 @@ +/** + * Training profile registry — single point of truth for which training types + * the CLI supports. + * + * Routing: `--training-type ` → exact match on `clientTrainingType`. + * Unknown values are rejected with a USAGE error listing all registered types. + * + * Adding a new training type: + * 1. Create `.ts` exporting a `TrainingProfile` constant. + * 2. Import and append to `PROFILES`. + * That's it. `create.ts` never needs to change. + */ +import { BailianError } from "../../errors/base.ts"; +import { ExitCode } from "../../errors/codes.ts"; +import type { TrainingProfile } from "./types.ts"; +import { sftProfile } from "./sft.ts"; +import { sftLoraProfile } from "./sft-lora.ts"; +import { dpoProfile } from "./dpo.ts"; +import { dpoLoraProfile } from "./dpo-lora.ts"; +import { cptProfile } from "./cpt.ts"; + +const PROFILES: TrainingProfile[] = [ + sftProfile, + sftLoraProfile, + dpoProfile, + dpoLoraProfile, + cptProfile, +]; + +/** Look up a profile by its CLI training-type name. Throws USAGE if unknown. */ +export function getProfile(clientTrainingType: string): TrainingProfile { + const p = PROFILES.find((p) => p.clientTrainingType === clientTrainingType); + if (!p) { + const known = PROFILES.map((p) => p.clientTrainingType).join(", "); + throw new BailianError( + `Unknown training type "${clientTrainingType}".`, + ExitCode.USAGE, + `Supported training types: ${known}.`, + ); + } + return p; +} + +/** All registered CLI training-type names (for help text / whitelisting). */ +export function listTrainingTypes(): string[] { + return PROFILES.map((p) => p.clientTrainingType); +} + +export type { TrainingProfile } from "./types.ts"; +export type { DataModality } from "./types.ts"; diff --git a/packages/core/src/finetune/profiles/sft-lora.ts b/packages/core/src/finetune/profiles/sft-lora.ts new file mode 100644 index 0000000..d442dc5 --- /dev/null +++ b/packages/core/src/finetune/profiles/sft-lora.ts @@ -0,0 +1,231 @@ +/** + * `sft-lora` profile — LoRA fine-tuning via the server's `efficient_sft`. + * + * Accepts `.jsonl` (text data with ChatML `{messages}` schema) and `.zip` + * (audio / image data with a `data.jsonl` manifest inside). The data + * inspector detects the modality from file content; this profile routes to the + * correct validator and assembles modality-specific hyper-parameters. + * + * Text, audio, and image all share the same server training type + * (`efficient_sft`) but differ in every other dimension: validation rules, + * hyper-parameters, and pre-flight gates. All branching is internal — + * `create.ts` calls the uniform profile interface without knowing the modality. + */ +import type { TrainingProfile, DataModality } from "./types.ts"; +import type { ValidateOpts, ValidationResult } from "../../dataset/validate/types.ts"; +import { validateDataset } from "../../dataset/validate/registry.ts"; +import { makeIssue, MAX_MEDIA_ZIP_BYTES } from "../../dataset/validate/common.ts"; +import { resolveTextHyperParameters } from "./common.ts"; + +/** Audio TTS hyper-parameter defaults (CosyVoice v3 Flash). */ +const AUDIO_HYPER_PARAMS: Record = { + lm_max_epoch: 60, + lm_step: 5, + lm_num: 3, + lm_batch_size: 1000, + fm_max_epoch: 100, + fm_step: 10, + fm_num: 3, + fm_batch_size: 2000, +}; + +/** + * Image generation hyper-parameter defaults (Wan2.x). + * + * The platform accepts these via `hyper_parameters` in the POST /fine-tunes + * body. `generation_type` controls `max_pixels` and `val_img_size` defaults: + * - t2i: "2k" (2048×2048) + * - i2i: "1k" (1024×1024) + * + * The default is "t2i". The generation type is auto-detected from data + * content: if the first JSONL record has `input_img`, it's I2I; otherwise T2I. + * The inspector returns `"image-i2i"` for I2I data, which this profile uses + * directly to pick the right hyper-parameter set. + * `split` (0.9) auto-splits training data into train/validation when no + * explicit validation_file_ids are provided. + */ +const IMAGE_HYPER_PARAMS_T2I: Record = { + learning_rate: "3e-5", + max_steps: 800, + eval_steps: 200, + max_token_length: "1k", + gradient_clip: 0.5, + weight_decay: 0.02, + max_pixels: "2k", + val_img_size: "2k", + generation_type: "t2i", + lora_rank: 32, + save_total_limit: 10, + split: 0.9, +}; + +const IMAGE_HYPER_PARAMS_I2I: Record = { + ...IMAGE_HYPER_PARAMS_T2I, + max_pixels: "1k", + val_img_size: "1k", + generation_type: "i2i", +}; + +/** + * Image / video ZIP size cap — shared constant from dataset/validate/common.ts. + */ + +/** + * Video generation hyper-parameter defaults (Wan i2v / kf2v). + * + * Shared across all video models; `batch_size` and `max_pixels` differ by model + * family (resolved per model in `resolveHyperParameters`): + * - wan2.5 (e.g. wan2.5-i2v-preview): batch_size 2, max_pixels 36864 + * - wan2.2 (i2v-flash / kf2v-flash): batch_size 4, max_pixels 262144 + * + * `learning_rate` is a string to avoid JSON-number precision loss (consistent + * with the image defaults). `split` (0.9) + `max_split_val_dataset_sample` + * (5) drive the automatic train/validation split when no explicit + * validation_file_ids are provided. + */ +const VIDEO_HYPER_PARAMS_BASE: Record = { + n_epochs: 400, + learning_rate: "2e-5", + split: 0.9, + max_split_val_dataset_sample: 5, + eval_epochs: 50, + save_total_limit: 10, + lora_rank: 32, + lora_alpha: 32, +}; + +/** True for any image modality (base or subtype). */ +function isImage(modality: DataModality): boolean { + return modality === "image" || modality === "image-i2i"; +} + +/** True for any video modality (i2v base or kf2v subtype). */ +function isVideo(modality: DataModality): boolean { + return modality === "video" || modality === "video-kf2v"; +} + +/** wan2.5 family uses smaller batch_size / max_pixels than wan2.2. */ +function isWan25(model: string | undefined): boolean { + return typeof model === "string" && /wan2\.5/i.test(model); +} + +export const sftLoraProfile: TrainingProfile = { + clientTrainingType: "sft-lora", + serverTrainingType: "efficient_sft", + acceptedExtensions: [".jsonl", ".zip"], + + async validate( + filePath: string, + modality: DataModality, + opts: ValidateOpts, + ): Promise { + if (modality === "audio") { + // ZIP validation: structure check + JSONL content via tts schema. + // The zip validator internally calls jsonlValidator for data.jsonl. + return validateDataset(filePath, { ...opts, schema: "tts" }); + } + if (isImage(modality)) { + // Image generation: flat ZIP with data.jsonl + image files. + // The zip validator handles ≥25 image count + flat structure when + // schema is "image". Size cap is 1 GB (vs 300 MB for text/audio). + return validateDataset(filePath, { + ...opts, + schema: "image", + maxBytes: MAX_MEDIA_ZIP_BYTES, + }); + } + if (isVideo(modality)) { + // Video generation (Wan i2v/kf2v): ZIP with data.jsonl + frame images and + // (for training) target videos. i2v is flat; kf2v uses image//video/ + // subfolders. 1 GB cap like image. + const result = await validateDataset(filePath, { + ...opts, + schema: "video", + maxBytes: MAX_MEDIA_ZIP_BYTES, + }); + // Model <-> data cross-check: a kf2v model needs first+last-frame data, + // an i2v model ignores last_frame_path. Only runs when we know the model + // (bare file-id flows pass no model). Detected subtype comes from the + // data inspector (video = i2v, video-kf2v = has last_frame_path). + if (typeof opts.model === "string" && opts.model.length > 0) { + const modelIsKf2v = /kf2v/i.test(opts.model); + const dataIsKf2v = modality === "video-kf2v"; + if (modelIsKf2v && !dataIsKf2v) { + result.errors.push( + makeIssue( + "error", + "KF2V_DATA_MISMATCH", + `Model "${opts.model}" is a first+last-frame (kf2v) model but the data has ` + + `no "last_frame_path". kf2v training data must include a last frame per record.`, + ), + ); + } else if (!modelIsKf2v && dataIsKf2v) { + result.warnings.push( + makeIssue( + "warning", + "I2V_LAST_FRAME_IGNORED", + `Model "${opts.model}" is a first-frame (i2v) model but the data includes ` + + `"last_frame_path"; the last frame will be ignored during training.`, + ), + ); + } + } + result.valid = result.errors.length === 0; + return result; + } + // Text: standard JSONL validation with chatml schema. + return validateDataset(filePath, { ...opts, schema: "chatml" }); + }, + + resolveHyperParameters( + modality: DataModality, + flags: Record, + ): Record { + if (modality === "audio") { + // Audio: use TTS defaults, user flags override (MVP: all hardcoded). + return { ...AUDIO_HYPER_PARAMS }; + } + if (isImage(modality)) { + // Image: modality "image-i2i" (auto-detected from data having input_img) + // uses I2I defaults; plain "image" uses T2I defaults. + const base = modality === "image-i2i" ? IMAGE_HYPER_PARAMS_I2I : IMAGE_HYPER_PARAMS_T2I; + const hp = { ...base }; + if (flags.learningRate !== undefined) hp.learning_rate = flags.learningRate as string; + return hp; + } + if (isVideo(modality)) { + // Video: shared defaults + model-family-specific batch_size / max_pixels. + // wan2.5 uses batch_size 2 / max_pixels 36864; wan2.2 uses 4 / 262144. + const wan25 = isWan25(flags.model as string | undefined); + const hp: Record = { + ...VIDEO_HYPER_PARAMS_BASE, + batch_size: 4, + max_pixels: wan25 ? 36864 : 262144, + }; + // Optional overrides (no clamping — video batch_size is intentionally small). + if (flags.nEpochs !== undefined) hp.n_epochs = flags.nEpochs as number; + if (flags.learningRate !== undefined) hp.learning_rate = flags.learningRate as string; + return hp; + } + // Text: existing hyper-parameter logic (n_epochs, batch_size, etc.). + return resolveTextHyperParameters(flags); + }, + + shouldSkipGate(gate: string, modality: DataModality): boolean { + if (modality === "audio" || isImage(modality) || isVideo(modality)) { + // Audio has no batch_size hyper-parameter; image uses max_steps; video + // datasets are intentionally small (batch_size 2/4). All skip the + // batch-size pre-flight gate to avoid false rejections. + if (gate === "batch_size") return true; + } + return false; + }, + + shouldSkipCapabilityCheck(modality: DataModality): boolean { + // Audio models (e.g. cosyvoice-v3-flash), image models + // (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); + }, +}; diff --git a/packages/core/src/finetune/profiles/sft.ts b/packages/core/src/finetune/profiles/sft.ts new file mode 100644 index 0000000..8dba888 --- /dev/null +++ b/packages/core/src/finetune/profiles/sft.ts @@ -0,0 +1,7 @@ +/** + * `sft` profile — full-parameter Supervised Fine-Tuning. + * Maps to the server's `sft` training type. ChatML record schema. + */ +import { textProfile } from "./common.ts"; + +export const sftProfile = textProfile("sft", "sft", "chatml"); diff --git a/packages/core/src/finetune/profiles/types.ts b/packages/core/src/finetune/profiles/types.ts new file mode 100644 index 0000000..a93ef62 --- /dev/null +++ b/packages/core/src/finetune/profiles/types.ts @@ -0,0 +1,84 @@ +/** + * Training profile — single source of truth for "how a training type behaves". + * + * Each profile encapsulates everything the CLI needs to know about a specific + * `--training-type` value: what file formats it accepts, how to validate data, + * which hyper-parameters to use, which pre-flight gates to run, and whether + * the model-capability check should be skipped. + * + * Profiles are **decoupled from validators**: the profile declares which file + * extensions it accepts, and the data inspector (`dataset/inspect.ts`) detects + * the data modality by parsing the file content. The profile then routes to + * the appropriate validator internally — `create.ts` never sees an if-else + * about modalities or file formats. + * + * Adding a new training type = one new profile file + one line in the registry. + * Nothing in `create.ts` needs to change. + */ +import type { ValidateOpts, ValidationResult } from "../../dataset/validate/types.ts"; + +/** + * Data modality detected by the inspector from file content. + * + * The inspector peeks at the first record of a JSONL or the `data.jsonl` inside + * a ZIP to determine what kind of data the file carries. This is orthogonal to + * the training type — `sft-lora` accepts both `.jsonl` (text) and `.zip` + * (audio / image / video). + * + * `"image-i2i"` is a subtype of `"image"` — the first record contains an + * `input_img` field (image-to-image). `"video-kf2v"` is a subtype of `"video"` + * — the first record contains a `last_frame_path` field (first+last-frame video, + * 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"`. + */ +export type DataModality = "text" | "audio" | "image" | "image-i2i" | "video" | "video-kf2v"; + +/** + * A training profile. One per `--training-type` CLI value. + * + * The profile owns all modality-specific branching internally — callers + * (`create.ts`) interact with it through a uniform interface and never need + * to know whether the data is text, audio, or something else. + */ +export interface TrainingProfile { + /** CLI vocabulary: the value users pass to `--training-type`. */ + clientTrainingType: string; + + /** Server `training_type` for the POST /fine-tunes request body. */ + serverTrainingType: string; + + /** File extensions this profile accepts (lower-case, with dot). */ + acceptedExtensions: string[]; + + /** + * Validate the training data file. The profile internally routes to the + * correct validator based on `modality` (detected by the data inspector). + */ + validate(filePath: string, modality: DataModality, opts: ValidateOpts): Promise; + + /** + * Build the `hyper_parameters` object for the API request. Merges user-supplied + * flags with modality-specific defaults (e.g. audio TTS uses `lm_max_epoch` / + * `fm_max_epoch`, text SFT uses `n_epochs` / `batch_size`). + */ + resolveHyperParameters( + modality: DataModality, + flags: Record, + ): Record; + + /** + * Whether a specific pre-flight gate should be skipped for the given modality. + * Common gates: `"batch_size"` (samples must exceed batch_size), etc. + * Audio TTS skips the batch-size gate (no batch_size hyper-parameter). + */ + shouldSkipGate(gate: string, modality: DataModality): boolean; + + /** + * Whether the model-capability pre-flight check should be skipped. + * Audio models (e.g. cosyvoice-v3-flash) report `supports.sft = false` in + * `listFoundationModels` but the API accepts `efficient_sft` — the check + * would incorrectly block the submission. + */ + shouldSkipCapabilityCheck(modality: DataModality): boolean; +} diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index f580c76..11202f2 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -1,6 +1,7 @@ export type { Command, AnyCommand, + CommandContext, FlagDef, FlagsDef, ParsedFlags, diff --git a/packages/core/tests/dataset-validate.test.ts b/packages/core/tests/dataset-validate.test.ts index 632cade..b4b2b52 100644 --- a/packages/core/tests/dataset-validate.test.ts +++ b/packages/core/tests/dataset-validate.test.ts @@ -169,10 +169,13 @@ describe("parseDatasetSchemaFlag", () => { expect(parseDatasetSchemaFlag(" ")).toBeUndefined(); }); - test("chatml / dpo / cpt pass through", () => { + test("chatml / dpo / cpt / tts / image / video pass through", () => { expect(parseDatasetSchemaFlag("chatml")).toBe("chatml"); expect(parseDatasetSchemaFlag("dpo")).toBe("dpo"); expect(parseDatasetSchemaFlag("cpt")).toBe("cpt"); + expect(parseDatasetSchemaFlag("tts")).toBe("tts"); + expect(parseDatasetSchemaFlag("image")).toBe("image"); + expect(parseDatasetSchemaFlag("video")).toBe("video"); expect(parseDatasetSchemaFlag(" dpo ")).toBe("dpo"); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4b58533..59f01e9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,6 +9,9 @@ catalogs: '@types/node': specifier: ^24 version: 24.12.2 + '@types/yauzl': + specifier: ^3.4.0 + version: 3.4.0 ajv: specifier: ^8.20.0 version: 8.20.0 @@ -30,6 +33,9 @@ catalogs: yaml: specifier: ^2.8.3 version: 2.8.3 + yauzl: + specifier: ^3.4.0 + version: 3.4.0 overrides: vite: npm:@voidzero-dev/vite-plus-core@latest @@ -125,10 +131,16 @@ importers: yaml: specifier: ^2.8.3 version: 2.8.3 + yauzl: + specifier: 'catalog:' + version: 3.4.0 devDependencies: '@types/node': specifier: 'catalog:' version: 24.12.2 + '@types/yauzl': + specifier: 'catalog:' + version: 3.4.0 '@typescript/native-preview': specifier: 7.0.0-dev.20260328.1 version: 7.0.0-dev.20260328.1 @@ -807,6 +819,9 @@ packages: '@types/node@25.6.0': resolution: {integrity: sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==} + '@types/yauzl@3.4.0': + resolution: {integrity: sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw==} + '@typescript/native-preview-darwin-arm64@7.0.0-dev.20260328.1': resolution: {integrity: sha512-BmJGDWC0bSQ2w5O/E+Mw9eTv9RklJ3vjshu7UdD92bUMxc4V4dkBhYj5r0qxbl4f+VFNX7fXvcDDI+9o+Kb6yw==} cpu: [arm64] @@ -1188,6 +1203,9 @@ packages: oxlint-tsgolint: optional: true + pend@1.2.0: + resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -1365,6 +1383,10 @@ packages: engines: {node: '>= 14.6'} hasBin: true + yauzl@3.4.0: + resolution: {integrity: sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==} + engines: {node: '>=12'} + snapshots: '@clack/core@0.3.5': @@ -1693,7 +1715,10 @@ snapshots: '@types/node@25.6.0': dependencies: undici-types: 7.19.2 - optional: true + + '@types/yauzl@3.4.0': + dependencies: + '@types/node': 25.6.0 '@typescript/native-preview-darwin-arm64@7.0.0-dev.20260328.1': optional: true @@ -2064,6 +2089,8 @@ snapshots: '@oxlint/binding-win32-x64-msvc': 1.63.0 oxlint-tsgolint: 0.22.1 + pend@1.2.0: {} + picocolors@1.1.1: {} picomatch@4.0.4: {} @@ -2163,8 +2190,7 @@ snapshots: undici-types@7.16.0: {} - undici-types@7.19.2: - optional: true + undici-types@7.19.2: {} undici@8.4.1: {} @@ -2309,3 +2335,7 @@ snapshots: ws@8.20.0: {} yaml@2.8.3: {} + + yauzl@3.4.0: + dependencies: + pend: 1.2.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index d3544a4..4f3e9e3 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,6 +4,7 @@ packages: catalog: "@types/node": ^24 + "@types/yauzl": ^3.4.0 ajv: ^8.20.0 boxen: ^8.0.1 chalk: ^5.6.2 @@ -14,6 +15,7 @@ catalog: vite-plus: latest vitest: npm:@voidzero-dev/vite-plus-test@latest yaml: ^2.8.3 + yauzl: ^3.4.0 catalogMode: prefer overrides: diff --git a/skills/bailian-cli/reference/dataset.md b/skills/bailian-cli/reference/dataset.md index 65650e9..523a421 100644 --- a/skills/bailian-cli/reference/dataset.md +++ b/skills/bailian-cli/reference/dataset.md @@ -7,13 +7,13 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Description | -| --------------------- | ---------------------------------------------------------- | -| `bl dataset delete` | Delete a dataset file by ID | -| `bl dataset get` | Get details of a single dataset file | -| `bl dataset list` | List uploaded dataset files | -| `bl dataset upload` | Upload a dataset file (.jsonl) to Bailian | -| `bl dataset validate` | Locally validate a dataset file (.jsonl) without uploading | +| Command | Description | +| --------------------- | ------------------------------------------------------------------ | +| `bl dataset delete` | Delete a dataset file by ID | +| `bl dataset get` | Get details of a single dataset file | +| `bl dataset list` | List uploaded dataset files | +| `bl dataset upload` | Upload a dataset file (.jsonl or .zip) to Bailian | +| `bl dataset validate` | Locally validate a dataset file (.jsonl or .zip) without uploading | ## Command details @@ -107,38 +107,36 @@ bl dataset list --output json ### `bl dataset upload` -| Field | Value | -| --------------- | -------------------------------------------------------------------------------------------------------------------- | -| **Name** | `dataset upload` | -| **Description** | Upload a dataset file (.jsonl) to Bailian | -| **Usage** | `bl dataset upload --file [--purpose ] [--schema ] [--no-validate] [--full-validate]` | +| Field | Value | +| --------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `dataset upload` | +| **Description** | Upload a dataset file (.jsonl or .zip) to Bailian | +| **Usage** | `bl dataset upload --file [--purpose ] [--schema ] [--no-validate] [--full-validate]` | #### Flags -| Flag | Type | Required | Description | -| ------------------ | ------ | -------- | ------------------------------------------------------------------------------------------------------------- | -| `--file ` | string | yes | Local .jsonl dataset file (≤300MB) | -| `--purpose ` | string | no | Dataset purpose tag (default: "fine-tune"; e.g. "evaluation") | -| `--schema ` | string | no | Record schema: "chatml" (SFT), "dpo" (chosen/rejected), or "cpt" (raw text). Default auto-detects per record. | -| `--no-validate` | switch | no | Skip the local JSONL pre-flight check (not recommended) | -| `--full-validate` | switch | no | JSON.parse every line instead of sampling (slower) | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| ------------------ | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--file ` | string | yes | Local dataset file (.jsonl or .zip; ≤300MB text, ≤1GB image) | +| `--purpose ` | string | no | Dataset purpose tag (default: "fine-tune"; e.g. "evaluation") | +| `--schema ` | string | no | Record schema: "chatml" (SFT), "dpo" (chosen/rejected), "cpt" (raw text), "tts" (audio), or "image" (image generation). Default auto-detects per record. | +| `--no-validate` | switch | no | Skip the local JSONL pre-flight check (not recommended) | +| `--full-validate` | switch | no | JSON.parse every line instead of sampling (slower) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes -- Only .jsonl is supported in this release. Three record schemas are -- recognized: chatml = {messages:[...]} (SFT); dpo = {messages:[...], -- chosen, rejected} where chosen/rejected are single assistant messages; -- cpt = {text:"..."} (continual pre-training, raw text). With no --schema, -- a record carrying chosen/rejected is validated as DPO, one with text (and -- no messages) as CPT, otherwise as ChatML. Pass --schema dpo / cpt to -- require that shape on every record, or --schema chatml to ignore the -- preference / text fields. Other purposes may carry a different schema in -- the future and would be served by a purpose-specific validator. -- The dataset upload cap is 300MB per file. -- Upload uses the OpenAI-compatible /compatible-mode/v1/files endpoint so -- the purpose tag is persisted (the DashScope-native /api/v1/files drops it). +- Supports .jsonl (text) and .zip (audio/image archives with a data.jsonl +- manifest). Five record schemas are recognized: chatml = {messages:[...]} +- (SFT); dpo = {messages:[...], chosen, rejected}; cpt = {text:"..."} +- (continual pre-training, raw text); tts = {wav_fn:"train/xxx.wav", +- text:"..."} (audio fine-tuning); image = {img_path:"..."} (image +- generation). With no --schema, a record carrying wav_fn is validated as +- TTS, img_path as image, chosen/rejected as DPO, text (no messages) as CPT, +- otherwise ChatML. Upload cap: 300MB text, 1GB image. Upload uses the +- OpenAI-compatible /compatible-mode/v1/files endpoint so the purpose tag is +- persisted (the DashScope-native /api/v1/files drops it). #### Examples @@ -154,6 +152,10 @@ bl dataset upload --file dpo.jsonl --schema dpo bl dataset upload --file cpt.jsonl --schema cpt ``` +```bash +bl dataset upload --file audio.zip --schema tts +``` + ```bash bl dataset upload --file eval.jsonl --purpose evaluation ``` @@ -168,31 +170,34 @@ bl dataset upload --file train.jsonl --no-validate ### `bl dataset validate` -| Field | Value | -| --------------- | ----------------------------------------------------------------------------------- | -| **Name** | `dataset validate` | -| **Description** | Locally validate a dataset file (.jsonl) without uploading | -| **Usage** | `bl dataset validate --file [--full-validate] [--schema ]` | +| Field | Value | +| --------------- | ----------------------------------------------------------------------------------------------- | +| **Name** | `dataset validate` | +| **Description** | Locally validate a dataset file (.jsonl or .zip) without uploading | +| **Usage** | `bl dataset validate --file [--full-validate] [--schema ]` | #### Flags -| Flag | Type | Required | Description | -| ----------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------- | -| `--file ` | string | yes | Local .jsonl dataset file | -| `--full-validate` | switch | no | JSON.parse every line instead of sampling (slower) | -| `--schema ` | string | no | Record schema: "chatml" (SFT), "dpo" (chosen/rejected), or "cpt" (raw text). Default auto-detects per record. | +| Flag | Type | Required | Description | +| ----------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--file ` | string | yes | Local dataset file (.jsonl or .zip) | +| `--full-validate` | switch | no | JSON.parse every line instead of sampling (slower) | +| `--schema ` | string | no | Record schema: "chatml" (SFT), "dpo" (chosen/rejected), "cpt" (raw text), "tts" (audio), or "image" (image generation). Default auto-detects per record. | #### Notes - Default scan: every line gets a structural check, then ~160 lines (front 50, - evenly spaced 100, last 10) are JSON.parsed against the active schema. - Schemas: chatml = {messages:[...]} (SFT); dpo = {messages:[...], chosen, -- rejected} where chosen/rejected are single assistant messages; cpt = -- {text:"..."} (continual pre-training, raw text). With no --schema, a -- record carrying chosen/rejected is validated as DPO, one with text (and no -- messages) as CPT, otherwise as ChatML. Pass --schema dpo / cpt to require -- that shape on every record (strict), or --schema chatml to ignore the -- preference / text fields. Use --full-validate to JSON.parse every line. +- rejected}; cpt = {text:"..."} (continual pre-training, raw text); +- tts = {wav_fn:"train/xxx.wav", text:"..."} (audio fine-tuning); +- image = {img_path:"..."} (image generation). With no --schema, a record +- carrying wav_fn is validated as TTS, img_path as image, chosen/rejected +- as DPO, text (no messages) as CPT, otherwise ChatML. Pass --schema to +- require a specific shape on every record. ZIP archives (.zip) are +- validated structurally (data.jsonl present, media references resolve) in +- addition to per-record content checks. Use --full-validate to JSON.parse +- every line. #### Examples @@ -208,6 +213,10 @@ bl dataset validate --file dpo.jsonl --schema dpo bl dataset validate --file cpt.jsonl --schema cpt ``` +```bash +bl dataset validate --file audio.zip --schema tts +``` + ```bash bl dataset validate --file eval.jsonl --full-validate ``` diff --git a/skills/bailian-cli/reference/deploy.md b/skills/bailian-cli/reference/deploy.md index 99e9a9c..a33d2c5 100644 --- a/skills/bailian-cli/reference/deploy.md +++ b/skills/bailian-cli/reference/deploy.md @@ -7,25 +7,27 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Description | -| ------------------ | --------------------------------------------------------- | -| `bl deploy create` | Create a model deployment | -| `bl deploy delete` | Delete a model deployment (must be STOPPED or FAILED) | -| `bl deploy get` | Get details of a single model deployment | -| `bl deploy list` | List model deployments | -| `bl deploy models` | List models available for deployment | -| `bl deploy scale` | Scale a deployment's capacity | -| `bl deploy update` | Update a deployment's rate limits (rpm_limit / tpm_limit) | +| Command | Description | +| ------------------------ | --------------------------------------------------------- | +| `bl deploy audio create` | Create an audio (TTS) model deployment | +| `bl deploy delete` | Delete a model deployment (must be STOPPED or FAILED) | +| `bl deploy get` | Get details of a single model deployment | +| `bl deploy image create` | Create an image generation model deployment | +| `bl deploy list` | List model deployments | +| `bl deploy models` | List models available for deployment | +| `bl deploy scale` | Scale a deployment's capacity | +| `bl deploy text create` | Create a text model deployment | +| `bl deploy update` | Update a deployment's rate limits (rpm_limit / tpm_limit) | ## Command details -### `bl deploy create` +### `bl deploy audio create` -| Field | Value | -| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `deploy create` | -| **Description** | Create a model deployment | -| **Usage** | `bl deploy create --model --name [--plan ] [--template-id ] [--capacity ] [--billing-method ] [--input-tpm ] [--output-tpm ] [--thinking-output-tpm ]` | +| Field | Value | +| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy audio create` | +| **Description** | Create an audio (TTS) model deployment | +| **Usage** | `bl deploy audio create --model --name [--plan ] [--deploy-spec ] [--capacity ] [--billing-method ] [--input-tpm ] [--output-tpm ] [--thinking-output-tpm ]` | #### Flags @@ -34,7 +36,7 @@ Index: [index.md](index.md) | `--model ` | string | yes | Model name (catalog model or fine-tuned output) (required) | | `--name ` | string | yes | Console display name for the deployment (required) | | `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (Token-billed) \| mu | -| `--template-id ` | string | no | Template id (only used by plan=mu; auto-picked if omitted) | +| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | | `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | | `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | | `--input-tpm ` | number | no | PTU max input tokens/min (required for plan=ptu) | @@ -45,40 +47,38 @@ Index: [index.md](index.md) #### Notes -- Plan defaults to `lora` (Token-billed). Pass --plan to override. +- Plan defaults to `lora` (Token-billed) for text/image and `mu` (model-unit- +- billed) for audio (CosyVoice TTS). Pass --plan to override. - For plan=ptu (Token-billed, provisioned throughput), --input-tpm and - --output-tpm are required (the platform rejects creation without an - explicit ptu_capacity despite the doc listing defaults). -- For plan=mu, `capacity`, `billing_method` and `template_id` are required. -- billing_method defaults to POST_PAY (only supported value); template_id +- For plan=mu, `capacity`, `billing_method` and `deploy_spec` are required. +- billing_method defaults to POST_PAY (only supported value); deploy_spec - and capacity are auto-picked from GET /deployments/models when omitted. - Use `bl deploy models --source base` to inspect available templates. - After creation, status starts at PENDING and transitions to RUNNING. - Invoke the deployed model with: bl text chat --model - WARNING: --model is overloaded across commands and refers to DIFFERENT -- values. `bl deploy create --model` takes the exported model_name (e.g. -- `qwen3-8b-ft-...`), but the create response also returns a `deployed_model` -- field (the deployment instance id, e.g. `qwen3-8b-5ecb5f068d79`). The -- inference call `bl text chat --model` must use the `deployed_model` from -- the create response — NOT the `model_name` you passed to `deploy create`. -- Do not reuse the value across the two commands. +- values. `bl deploy create --model` takes the exported model_name +- (e.g. `qwen3-8b-ft-...`), but the create response also returns a +- `deployed_model` field (the deployment instance id, e.g. +- `qwen3-8b-5ecb5f068d79`). The inference call `bl text chat --model` must use +- the `deployed_model` from the create response — NOT the `model_name` you +- passed to `deploy create`. Do not reuse the value across the two +- commands. #### Examples ```bash -bl deploy create --model my-qwen-sft --name my-sft-test +bl deploy audio create --model my-cosyvoice-ft --name my-tts ``` ```bash -bl deploy create --model qwen3.6-flash-2026-04-16 --name my-flash --plan ptu --input-tpm 10000 --output-tpm 1000 +bl deploy audio create --model my-cosyvoice-ft --name my-tts --deploy-spec dps-xxxx --capacity 1 ``` ```bash -bl deploy create --model qwen3-8b --name my-qwen3-mu --plan mu -``` - -```bash -bl deploy create --model qwen3-8b --name my-qwen3 --plan mu --template-id MU1 --capacity 2 +bl deploy audio create --model my-cosyvoice-ft --name my-tts --dry-run ``` ### `bl deploy delete` @@ -134,6 +134,66 @@ bl deploy get --deployed-model qwen-plus-2025-12-01-b6d61c71 bl deploy get --deployed-model qwen-plus-2025-12-01-b6d61c71 --output json ``` +### `bl deploy image create` + +| Field | Value | +| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy image create` | +| **Description** | Create an image generation model deployment | +| **Usage** | `bl deploy image create --model --name [--plan ] [--deploy-spec ] [--capacity ] [--billing-method ] [--input-tpm ] [--output-tpm ] [--thinking-output-tpm ]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------------- | ------ | -------- | ------------------------------------------------------------------------------- | +| `--model ` | string | yes | Model name (catalog model or fine-tuned output) (required) | +| `--name ` | string | yes | Console display name for the deployment (required) | +| `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (Token-billed) \| mu | +| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | +| `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | +| `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | +| `--input-tpm ` | number | no | PTU max input tokens/min (required for plan=ptu) | +| `--output-tpm ` | number | no | PTU max output tokens/min (required for plan=ptu) | +| `--thinking-output-tpm ` | number | no | PTU max thinking-output tokens/min (optional, some models) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Plan defaults to `lora` (Token-billed) for text/image and `mu` (model-unit- +- billed) for audio (CosyVoice TTS). Pass --plan to override. +- For plan=ptu (Token-billed, provisioned throughput), --input-tpm and +- --output-tpm are required (the platform rejects creation without an +- explicit ptu_capacity despite the doc listing defaults). +- For plan=mu, `capacity`, `billing_method` and `deploy_spec` are required. +- billing_method defaults to POST_PAY (only supported value); deploy_spec +- and capacity are auto-picked from GET /deployments/models when omitted. +- Use `bl deploy models --source base` to inspect available templates. +- After creation, status starts at PENDING and transitions to RUNNING. +- Invoke the deployed model with: bl text chat --model +- WARNING: --model is overloaded across commands and refers to DIFFERENT +- values. `bl deploy create --model` takes the exported model_name +- (e.g. `qwen3-8b-ft-...`), but the create response also returns a +- `deployed_model` field (the deployment instance id, e.g. +- `qwen3-8b-5ecb5f068d79`). The inference call `bl text chat --model` must use +- the `deployed_model` from the create response — NOT the `model_name` you +- passed to `deploy create`. Do not reuse the value across the two +- commands. + +#### Examples + +```bash +bl deploy image create --model my-wan-ft --name my-wan +``` + +```bash +bl deploy image create --model my-wan-ft --name my-wan-mu --plan mu +``` + +```bash +bl deploy image create --model my-wan-ft --name my-wan --dry-run +``` + ### `bl deploy list` | Field | Value | @@ -232,6 +292,70 @@ bl deploy scale --deployed-model qwen-plus-...-b6d61c71 --capacity 8 bl deploy scale --deployed-model dep-... --capacity 2 ``` +### `bl deploy text create` + +| Field | Value | +| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `deploy text create` | +| **Description** | Create a text model deployment | +| **Usage** | `bl deploy text create --model --name [--plan ] [--deploy-spec ] [--capacity ] [--billing-method ] [--input-tpm ] [--output-tpm ] [--thinking-output-tpm ]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------------- | ------ | -------- | ------------------------------------------------------------------------------- | +| `--model ` | string | yes | Model name (catalog model or fine-tuned output) (required) | +| `--name ` | string | yes | Console display name for the deployment (required) | +| `--plan ` | string | no | Billing plan: lora (default, Token-billed) \| ptu (Token-billed) \| mu | +| `--deploy-spec ` | string | no | Deploy spec (only used by plan=mu; auto-picked if omitted) | +| `--capacity ` | number | no | Resource units (plan=mu only; required by API; defaults to the template's unit) | +| `--billing-method ` | string | no | Billing method (plan=mu only; default "POST_PAY", the only supported value) | +| `--input-tpm ` | number | no | PTU max input tokens/min (required for plan=ptu) | +| `--output-tpm ` | number | no | PTU max output tokens/min (required for plan=ptu) | +| `--thinking-output-tpm ` | number | no | PTU max thinking-output tokens/min (optional, some models) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Plan defaults to `lora` (Token-billed) for text/image and `mu` (model-unit- +- billed) for audio (CosyVoice TTS). Pass --plan to override. +- For plan=ptu (Token-billed, provisioned throughput), --input-tpm and +- --output-tpm are required (the platform rejects creation without an +- explicit ptu_capacity despite the doc listing defaults). +- For plan=mu, `capacity`, `billing_method` and `deploy_spec` are required. +- billing_method defaults to POST_PAY (only supported value); deploy_spec +- and capacity are auto-picked from GET /deployments/models when omitted. +- Use `bl deploy models --source base` to inspect available templates. +- After creation, status starts at PENDING and transitions to RUNNING. +- Invoke the deployed model with: bl text chat --model +- WARNING: --model is overloaded across commands and refers to DIFFERENT +- values. `bl deploy create --model` takes the exported model_name +- (e.g. `qwen3-8b-ft-...`), but the create response also returns a +- `deployed_model` field (the deployment instance id, e.g. +- `qwen3-8b-5ecb5f068d79`). The inference call `bl text chat --model` must use +- the `deployed_model` from the create response — NOT the `model_name` you +- passed to `deploy create`. Do not reuse the value across the two +- commands. + +#### Examples + +```bash +bl deploy text create --model my-qwen-sft --name my-sft-test +``` + +```bash +bl deploy text create --model qwen3.6-flash-2026-04-16 --name my-flash --plan ptu --input-tpm 10000 --output-tpm 1000 +``` + +```bash +bl deploy text create --model qwen3-8b --name my-qwen3-mu --plan mu +``` + +```bash +bl deploy text create --model qwen3-8b --name my-qwen3 --plan mu --deploy-spec MU1 --capacity 2 +``` + ### `bl deploy update` | Field | Value | diff --git a/skills/bailian-cli/reference/finetune.md b/skills/bailian-cli/reference/finetune.md index 21511fc..d269dfc 100644 --- a/skills/bailian-cli/reference/finetune.md +++ b/skills/bailian-cli/reference/finetune.md @@ -7,21 +7,76 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Description | -| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -| `bl finetune cancel` | Cancel a running fine-tune job | -| `bl finetune capability` | Query fine-tune training capability — by model (which training types it supports) or by training type (which models support it) | -| `bl finetune checkpoints` | List checkpoints produced by a fine-tune job | -| `bl finetune create` | Create a fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | -| `bl finetune delete` | Delete a fine-tune job record | -| `bl finetune export` | Publish a checkpoint as a deployable model | -| `bl finetune get` | Get details of a single fine-tune job | -| `bl finetune list` | List fine-tune jobs | -| `bl finetune logs` | Fetch training logs for a fine-tune job | -| `bl finetune watch` | Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | +| Command | Description | +| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `bl finetune audio create` | Create an audio TTS model fine-tune job (sft-lora) | +| `bl finetune cancel` | Cancel a running fine-tune job | +| `bl finetune capability` | Query fine-tune training capability — by model (which training types it supports) or by training type (which models support it) | +| `bl finetune checkpoints` | List checkpoints produced by a fine-tune job | +| `bl finetune delete` | Delete a fine-tune job record | +| `bl finetune export` | Publish a checkpoint as a deployable model | +| `bl finetune get` | Get details of a single fine-tune job | +| `bl finetune image create` | Create an image generation model fine-tune job (sft-lora) | +| `bl finetune list` | List fine-tune jobs | +| `bl finetune logs` | Fetch training logs for a fine-tune job | +| `bl finetune text create` | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | +| `bl finetune watch` | Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | ## Command details +### `bl finetune audio create` + +| Field | Value | +| --------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `finetune audio create` | +| **Description** | Create an audio TTS model fine-tune job (sft-lora) | +| **Usage** | `bl finetune audio create --model --datasets [--validations ] [--model-name ] [--suffix ]` | + +#### Flags + +| Flag | Type | Required | Description | +| ---------------------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `--model ` | string | yes | Base model to fine-tune | +| `--datasets ` | string | yes | Comma-separated dataset file IDs or local paths (.jsonl for text, .zip for audio/image). 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) | +| `--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. +- Audio TTS training runs sft-lora (efficient_sft) with fixed CosyVoice +- hyper-parameter defaults; there are no training-type or hyper-parameter +- knobs to set. + +#### Examples + +```bash +bl finetune audio create --model cosyvoice-v3-flash --datasets ./audio.zip +``` + +```bash +bl finetune audio create --model cosyvoice-v3-flash --datasets file-xxx +``` + +```bash +bl finetune audio create --model cosyvoice-v3-flash --datasets ./audio.zip --model-name my-tts +``` + +```bash +bl finetune audio create --model cosyvoice-v3-flash --datasets file-xxx --output json +``` + +```bash +bl finetune audio create --model cosyvoice-v3-flash --datasets ./audio.zip --dry-run +``` + ### `bl finetune cancel` | Field | Value | @@ -124,87 +179,6 @@ bl finetune checkpoints --job-id ft-xxx bl finetune checkpoints --job-id ft-xxx --output json ``` -### `bl finetune create` - -| Field | Value | -| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Name** | `finetune create` | -| **Description** | Create a fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | -| **Usage** | `bl finetune create --model --datasets [--validations ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ]` | - -#### Flags - -| Flag | Type | Required | Description | -| ---------------------------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--model ` | string | yes | Base model to fine-tune (e.g. qwen3-8b, qwen3-14b) | -| `--datasets ` | string | yes | Comma-separated dataset file IDs or local .jsonl paths. Local paths are uploaded (validated) first, then their file-ids are used. | -| `--validations ` | string | no | Comma-separated validation dataset file IDs or local .jsonl 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) | -| `--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 (default: 3) | -| `--batch-size ` | number | no | Per-device batch size (clamped to [8, 1024]). Auto-set to 8 for small datasets (<100KB) | -| `--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 | - -#### Notes - -- Creating a job uploads any local datasets and consumes training quota. -- Use --dry-run to preview the request body without submitting. -- Training-type values use the `` / `-lora` convention: -- sft (full) | sft-lora (LoRA) | dpo (full) | dpo-lora (LoRA) | cpt. These map -- to the server's training_type at the interface boundary, so the rest of the -- CLI never sees the raw server strings. -- Before submitting (non dry-run) the job, the model's training capability is -- checked via listFoundationModels (no console login required); an unsupported -- training type fails fast with the list the model actually supports. -- n_epochs defaults to 3. Other hyper-parameters are platform defaults unless set. -- Learning rate is forwarded as a string to avoid JSON-number precision loss. -- --datasets / --validations accept either file-ids (from `dataset upload`) -- or local .jsonl paths. Local paths are validated and uploaded first, then -- their file-ids are submitted — a one-step upload-and-train. -- Dataset record schema is chosen from --training-type: dpo\* → {messages, -- chosen, rejected}; cpt → {text} (raw pre-training text); else {messages}. -- 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). - -#### Examples - -```bash -bl finetune create --model qwen3-8b --datasets file-xxx -``` - -```bash -bl finetune create --model qwen3-8b --datasets ./train.jsonl -``` - -```bash -bl finetune create --model qwen3-8b --datasets ./train.jsonl --validations ./eval.jsonl -``` - -```bash -bl finetune create --model qwen3-8b --datasets file-aaa,./extra.jsonl -``` - -```bash -bl finetune create --model qwen3-8b --datasets ./train.jsonl --training-type sft -``` - -```bash -bl finetune create --model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4 -``` - -```bash -bl finetune create --model qwen3-8b --datasets file-xxx --output json -``` - -```bash -bl finetune create --model qwen3-8b --datasets file-xxx --dry-run -``` - ### `bl finetune delete` | Field | Value | @@ -256,9 +230,9 @@ bl finetune delete --job-id ft-xxx --dry-run #### Notes -- Required before `deploy create` can target a checkpoint. The platform -- may auto-export the best checkpoint when a job reaches SUCCEEDED — explicit -- export is the canonical path for non-best checkpoints. +- Required before `deploy create` can target a checkpoint. The +- platform may auto-export the best checkpoint when a job reaches SUCCEEDED — +- explicit export is the canonical path for non-best checkpoints. #### Examples @@ -292,6 +266,67 @@ bl finetune get --job-id ft-xxx bl finetune get --job-id ft-xxx --output json ``` +### `bl finetune image create` + +| Field | Value | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Name** | `finetune image create` | +| **Description** | Create an image generation model fine-tune job (sft-lora) | +| **Usage** | `bl finetune image create --model --datasets [--validations ] [--model-name ] [--suffix ] [--generation-type ] [--learning-rate ]` | + +#### Flags + +| Flag | Type | Required | Description | +| ------------------------------ | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--model ` | string | yes | Base model to fine-tune | +| `--datasets ` | string | yes | Comma-separated dataset file IDs or local paths (.jsonl for text, .zip for audio/image). 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) | +| `--generation-type ` | string | no | Generation type: t2i (default) \| i2i. Sets generation_type/max_pixels. Required to train I2I from a file-id or with --dry-run (local data auto-detects input_img). | +| `--learning-rate ` | string | no | Learning rate as a string to preserve precision (e.g. "3e-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. +- Image generation training runs sft-lora (efficient_sft) with fixed defaults; +- only --learning-rate is overridable. T2I vs I2I is declared with +- --generation-type (default t2i), which sets generation_type/max_pixels. For +- local data the type is auto-detected (records with input_img train I2I); +- pass --generation-type explicitly to train I2I from a file-id or in --dry-run. + +#### Examples + +```bash +bl finetune image create --model wan2.7-image-pro --datasets ./images.zip +``` + +```bash +bl finetune image create --model wan2.7-image-pro --datasets file-xxx +``` + +```bash +bl finetune image create --model wan2.7-image-pro --datasets file-xxx --generation-type i2i +``` + +```bash +bl finetune image create --model wan2.7-image-pro --datasets ./images.zip --model-name my-wan +``` + +```bash +bl finetune image create --model wan2.7-image-pro --datasets file-xxx --output json +``` + +```bash +bl finetune image create --model wan2.7-image-pro --datasets ./images.zip --dry-run +``` + ### `bl finetune list` | Field | Value | @@ -370,6 +405,85 @@ bl finetune logs --job-id ft-xxx --tail 20 bl finetune logs --job-id ft-xxx --search checkpoint --tail 5 ``` +### `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) | +| **Usage** | `bl finetune text create --model --datasets [--validations ] [--model-name ] [--suffix ] [--n-epochs ] [--batch-size ] [--learning-rate ] [--max-length ] [--training-type ]` | + +#### Flags + +| Flag | Type | Required | Description | +| ---------------------------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--model ` | string | yes | Base model to fine-tune | +| `--datasets ` | string | yes | Comma-separated dataset file IDs or local paths (.jsonl for text, .zip for audio/image). 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) | +| `--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 (default: 3) | +| `--batch-size ` | number | no | Per-device batch size (clamped to [8, 1024]). Auto-set to 8 for small datasets (<100KB) | +| `--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 | + +#### 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-type values use the `` / `-lora` convention: +- sft (full) | sft-lora (LoRA) | dpo (full) | dpo-lora (LoRA) | cpt. These map +- to the server's training_type at the interface boundary, so the rest of the +- CLI never sees the raw server strings. +- Before submitting (non dry-run) the job, the model's training capability is +- checked via listFoundationModels (no console login required); an unsupported +- training type fails fast with the list the model actually supports. +- n_epochs defaults to 3. Other hyper-parameters are platform defaults unless set. +- 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). + +#### Examples + +```bash +bl finetune text create --model qwen3-8b --datasets file-xxx +``` + +```bash +bl finetune text create --model qwen3-8b --datasets ./train.jsonl +``` + +```bash +bl finetune text create --model qwen3-8b --datasets ./train.jsonl --validations ./eval.jsonl +``` + +```bash +bl finetune text create --model qwen3-8b --datasets file-aaa,./extra.jsonl +``` + +```bash +bl finetune text create --model qwen3-8b --datasets ./train.jsonl --training-type sft +``` + +```bash +bl finetune text create --model qwen3-8b --datasets file-xxx --learning-rate "1.6e-5" --n-epochs 4 +``` + +```bash +bl finetune text create --model qwen3-8b --datasets file-xxx --output json +``` + +```bash +bl finetune text create --model qwen3-8b --datasets file-xxx --dry-run +``` + ### `bl finetune watch` | Field | Value | @@ -394,9 +508,9 @@ bl finetune logs --job-id ft-xxx --search checkpoint --tail 5 - Default (no --follow) is a NON-BLOCKING single status probe: one fetch, then - return immediately. This is the mode meant for agents / scripts — the caller - owns the polling cadence, so the CLI never holds the terminal. -- Exit codes (both modes): 0 SUCCEEDED | 1 FAILED/CANCELED | 2 --poll-timeout -- exceeded (--follow) | 3 still running (non-terminal, default mode) | 130 -- interrupted (Ctrl-C). +- A terminal FAILED/CANCELED status raises a normal CLI error (non-zero exit); +- a SUCCEEDED or still-running status returns 0. With --follow, exceeding +- --poll-timeout raises a timeout error. - Use --follow for the blocking, human-terminal-follow experience; use the - default mode when driving the loop yourself (e.g. from an agent). - For per-step training output (not status), use `finetune logs`. diff --git a/skills/bailian-cli/reference/index.md b/skills/bailian-cli/reference/index.md index 00aef86..d9eaa28 100644 --- a/skills/bailian-cli/reference/index.md +++ b/skills/bailian-cli/reference/index.md @@ -22,25 +22,29 @@ Use this index for the full quick index and global flags. | `bl dataset delete` | Delete a dataset file by ID | [dataset.md](dataset.md) | | `bl dataset get` | Get details of a single dataset file | [dataset.md](dataset.md) | | `bl dataset list` | List uploaded dataset files | [dataset.md](dataset.md) | -| `bl dataset upload` | Upload a dataset file (.jsonl) to Bailian | [dataset.md](dataset.md) | -| `bl dataset validate` | Locally validate a dataset file (.jsonl) without uploading | [dataset.md](dataset.md) | -| `bl deploy create` | Create a model deployment | [deploy.md](deploy.md) | +| `bl dataset upload` | Upload a dataset file (.jsonl or .zip) to Bailian | [dataset.md](dataset.md) | +| `bl dataset validate` | Locally validate a dataset file (.jsonl or .zip) without uploading | [dataset.md](dataset.md) | +| `bl deploy audio create` | Create an audio (TTS) model deployment | [deploy.md](deploy.md) | | `bl deploy delete` | Delete a model deployment (must be STOPPED or FAILED) | [deploy.md](deploy.md) | | `bl deploy get` | Get details of a single model deployment | [deploy.md](deploy.md) | +| `bl deploy image create` | Create an image generation model deployment | [deploy.md](deploy.md) | | `bl deploy list` | List model deployments | [deploy.md](deploy.md) | | `bl deploy models` | List models available for deployment | [deploy.md](deploy.md) | | `bl deploy scale` | Scale a deployment's capacity | [deploy.md](deploy.md) | +| `bl deploy text create` | Create a text model deployment | [deploy.md](deploy.md) | | `bl deploy update` | Update a deployment's rate limits (rpm_limit / tpm_limit) | [deploy.md](deploy.md) | | `bl file upload` | Upload a local file to DashScope temporary storage (48h) | [file.md](file.md) | +| `bl finetune audio create` | Create an audio TTS model fine-tune job (sft-lora) | [finetune.md](finetune.md) | | `bl finetune cancel` | Cancel a running fine-tune job | [finetune.md](finetune.md) | | `bl finetune capability` | 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` | List checkpoints produced by a fine-tune job | [finetune.md](finetune.md) | -| `bl finetune create` | Create a fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | [finetune.md](finetune.md) | | `bl finetune delete` | Delete a fine-tune job record | [finetune.md](finetune.md) | | `bl finetune export` | Publish a checkpoint as a deployable model | [finetune.md](finetune.md) | | `bl finetune get` | Get details of a single fine-tune job | [finetune.md](finetune.md) | +| `bl finetune image create` | Create an image generation model fine-tune job (sft-lora) | [finetune.md](finetune.md) | | `bl finetune list` | List fine-tune jobs | [finetune.md](finetune.md) | | `bl finetune logs` | Fetch training logs for a fine-tune job | [finetune.md](finetune.md) | +| `bl finetune text create` | Create a text model fine-tune job (sft \| sft-lora \| dpo \| dpo-lora \| cpt) | [finetune.md](finetune.md) | | `bl finetune watch` | Probe a fine-tune job's status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [finetune.md](finetune.md) | | `bl image edit` | Edit an existing image with text instructions (Qwen-Image) | [image.md](image.md) | | `bl image generate` | Generate images (Qwen-Image / wan2.x) | [image.md](image.md) | @@ -86,33 +90,33 @@ Use this index for the full quick index and global flags. ## By group -| Group | Commands | Reference | -| ------------ | --------------------------------------------------------------------------------------------------- | ------------------------------ | -| `advisor` | `recommend` | [advisor.md](advisor.md) | -| `app` | `call`, `list` | [app.md](app.md) | -| `auth` | `login`, `logout`, `status` | [auth.md](auth.md) | -| `config` | `set`, `show` | [config.md](config.md) | -| `console` | `call` | [console.md](console.md) | -| `dataset` | `delete`, `get`, `list`, `upload`, `validate` | [dataset.md](dataset.md) | -| `deploy` | `create`, `delete`, `get`, `list`, `models`, `scale`, `update` | [deploy.md](deploy.md) | -| `file` | `upload` | [file.md](file.md) | -| `finetune` | `cancel`, `capability`, `checkpoints`, `create`, `delete`, `export`, `get`, `list`, `logs`, `watch` | [finetune.md](finetune.md) | -| `image` | `edit`, `generate` | [image.md](image.md) | -| `knowledge` | `chat`, `retrieve`, `search` | [knowledge.md](knowledge.md) | -| `mcp` | `call`, `list`, `tools` | [mcp.md](mcp.md) | -| `memory` | `add`, `delete`, `list`, `profile create`, `profile get`, `search`, `update` | [memory.md](memory.md) | -| `omni` | `(root)` | [omni.md](omni.md) | -| `pipeline` | `run`, `validate` | [pipeline.md](pipeline.md) | -| `quota` | `check`, `history`, `list`, `request` | [quota.md](quota.md) | -| `search` | `web` | [search.md](search.md) | -| `speech` | `recognize`, `synthesize` | [speech.md](speech.md) | -| `text` | `chat` | [text.md](text.md) | -| `token-plan` | `add-member`, `assign-seats`, `create-key`, `list-seats` | [token-plan.md](token-plan.md) | -| `update` | `(root)` | [update.md](update.md) | -| `usage` | `free`, `freetier`, `stats` | [usage.md](usage.md) | -| `video` | `download`, `edit`, `generate`, `ref`, `task get` | [video.md](video.md) | -| `vision` | `describe` | [vision.md](vision.md) | -| `workspace` | `list` | [workspace.md](workspace.md) | +| Group | Commands | Reference | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | +| `advisor` | `recommend` | [advisor.md](advisor.md) | +| `app` | `call`, `list` | [app.md](app.md) | +| `auth` | `login`, `logout`, `status` | [auth.md](auth.md) | +| `config` | `set`, `show` | [config.md](config.md) | +| `console` | `call` | [console.md](console.md) | +| `dataset` | `delete`, `get`, `list`, `upload`, `validate` | [dataset.md](dataset.md) | +| `deploy` | `audio create`, `delete`, `get`, `image create`, `list`, `models`, `scale`, `text create`, `update` | [deploy.md](deploy.md) | +| `file` | `upload` | [file.md](file.md) | +| `finetune` | `audio create`, `cancel`, `capability`, `checkpoints`, `delete`, `export`, `get`, `image create`, `list`, `logs`, `text create`, `watch` | [finetune.md](finetune.md) | +| `image` | `edit`, `generate` | [image.md](image.md) | +| `knowledge` | `chat`, `retrieve`, `search` | [knowledge.md](knowledge.md) | +| `mcp` | `call`, `list`, `tools` | [mcp.md](mcp.md) | +| `memory` | `add`, `delete`, `list`, `profile create`, `profile get`, `search`, `update` | [memory.md](memory.md) | +| `omni` | `(root)` | [omni.md](omni.md) | +| `pipeline` | `run`, `validate` | [pipeline.md](pipeline.md) | +| `quota` | `check`, `history`, `list`, `request` | [quota.md](quota.md) | +| `search` | `web` | [search.md](search.md) | +| `speech` | `recognize`, `synthesize` | [speech.md](speech.md) | +| `text` | `chat` | [text.md](text.md) | +| `token-plan` | `add-member`, `assign-seats`, `create-key`, `list-seats` | [token-plan.md](token-plan.md) | +| `update` | `(root)` | [update.md](update.md) | +| `usage` | `free`, `freetier`, `stats` | [usage.md](usage.md) | +| `video` | `download`, `edit`, `generate`, `ref`, `task get` | [video.md](video.md) | +| `vision` | `describe` | [vision.md](vision.md) | +| `workspace` | `list` | [workspace.md](workspace.md) | ## Global flags