mlx-bun 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +362 -0
  3. package/THIRD_PARTY_LICENSES.md +41 -0
  4. package/bin/mlx-bun.mjs +32 -0
  5. package/docs/curve-designer.html +303 -0
  6. package/docs/design/adapters-end-to-end.md +201 -0
  7. package/docs/design/compat-cli-surface-design.md +227 -0
  8. package/docs/design/docs-reorg-plan.md +152 -0
  9. package/docs/design/hlg-sampling.md +340 -0
  10. package/docs/design/memory-system.md +339 -0
  11. package/docs/design/optimization_plan.md +344 -0
  12. package/docs/design/parallel-slots.md +515 -0
  13. package/docs/design/runtime-isolation.md +247 -0
  14. package/docs/design/segmented-backward-training.md +508 -0
  15. package/docs/investigations/chunk-finetune-experiment.md +84 -0
  16. package/docs/investigations/curve-bisector-routing.md +123 -0
  17. package/docs/investigations/curve-runs/bisector-route.json +98 -0
  18. package/docs/investigations/curve-runs/bisector-trace.json +1393 -0
  19. package/docs/investigations/curve-runs/curve-terrain.json +1179 -0
  20. package/docs/investigations/curve-runs/curve-terrain.svg +42 -0
  21. package/docs/investigations/curve-terrain.html +105 -0
  22. package/docs/investigations/expert-offload-single-user-moe.md +292 -0
  23. package/docs/investigations/hlg-ab.html +34 -0
  24. package/docs/investigations/hlg-explorer.html +238 -0
  25. package/docs/investigations/hlg-figs/cliff.svg +1 -0
  26. package/docs/investigations/hlg-figs/cross.svg +1 -0
  27. package/docs/investigations/hlg-figs/edges.svg +1 -0
  28. package/docs/investigations/hlg-figs/k20-grids.svg +1 -0
  29. package/docs/investigations/hlg-figs/k20-peaks.svg +1 -0
  30. package/docs/investigations/hlg-figs/lw-curve.svg +1 -0
  31. package/docs/investigations/hlg-figs/terrain.svg +1 -0
  32. package/docs/investigations/hlg-report.html +262 -0
  33. package/docs/investigations/hlg-runs/hlg-ab.json +149 -0
  34. package/docs/investigations/hlg-runs/hlg-blind-prompts.md +87 -0
  35. package/docs/investigations/hlg-runs/hlg-blind.json +107 -0
  36. package/docs/investigations/hlg-runs/hlg-cliff.json +197 -0
  37. package/docs/investigations/hlg-runs/hlg-cross.json +505 -0
  38. package/docs/investigations/hlg-runs/hlg-edge.json +388 -0
  39. package/docs/investigations/hlg-runs/hlg-eval1.json +25 -0
  40. package/docs/investigations/hlg-runs/hlg-frontier.json +86 -0
  41. package/docs/investigations/hlg-runs/hlg-grid.json +242 -0
  42. package/docs/investigations/hlg-runs/hlg-grid2.json +343 -0
  43. package/docs/investigations/hlg-runs/hlg-lw-coarse.json +110 -0
  44. package/docs/investigations/hlg-runs/hlg-map.json +383 -0
  45. package/docs/investigations/hlg-runs/run0-original.log +159 -0
  46. package/docs/investigations/hlg-runs/runA-recommended.log +131 -0
  47. package/docs/investigations/hlg-runs/runAA-cliff-cpm5.log +26 -0
  48. package/docs/investigations/hlg-runs/runAB-grid2-e4b.log +18 -0
  49. package/docs/investigations/hlg-runs/runAC-peak-e4b-partial.log +25 -0
  50. package/docs/investigations/hlg-runs/runAD-ab-samples.log +8 -0
  51. package/docs/investigations/hlg-runs/runAE-edge-e4b.log +51 -0
  52. package/docs/investigations/hlg-runs/runAF-logit-calibration.log +10 -0
  53. package/docs/investigations/hlg-runs/runAG-eval-config2.log +16 -0
  54. package/docs/investigations/hlg-runs/runB-gain-variants.log +192 -0
  55. package/docs/investigations/hlg-runs/runC-pivots.log +162 -0
  56. package/docs/investigations/hlg-runs/runD-oetf.log +132 -0
  57. package/docs/investigations/hlg-runs/runE-eotf.log +162 -0
  58. package/docs/investigations/hlg-runs/runF-shaper-working.log +86 -0
  59. package/docs/investigations/hlg-runs/runG-shaper-sweep.log +101 -0
  60. package/docs/investigations/hlg-runs/runH-wsweep.log +176 -0
  61. package/docs/investigations/hlg-runs/runI-asweep.log +176 -0
  62. package/docs/investigations/hlg-runs/runJ-knobmap.log +49 -0
  63. package/docs/investigations/hlg-runs/runK-frontier.log +19 -0
  64. package/docs/investigations/hlg-runs/runL-widemap.log +65 -0
  65. package/docs/investigations/hlg-runs/runM-frontier-emb.log +15 -0
  66. package/docs/investigations/hlg-runs/runN-verify.log +116 -0
  67. package/docs/investigations/hlg-runs/runO-frontier-seed5000.log +15 -0
  68. package/docs/investigations/hlg-runs/runP-grid-AxSm.log +15 -0
  69. package/docs/investigations/hlg-runs/runQ-grid-tgW.log +15 -0
  70. package/docs/investigations/hlg-runs/runR-blind-transcript.log +79 -0
  71. package/docs/investigations/hlg-runs/runS-cross-coherence.log +33 -0
  72. package/docs/investigations/hlg-runs/runT-cross-cpm5.log +33 -0
  73. package/docs/investigations/hlg-runs/runU-cross-12b.log +33 -0
  74. package/docs/investigations/hlg-runs/runV-lw-e4b.log +22 -0
  75. package/docs/investigations/hlg-runs/runW-lw-12b.log +22 -0
  76. package/docs/investigations/hlg-runs/runX-lw-cpm5.log +22 -0
  77. package/docs/investigations/hlg-runs/runY-cliff-e4b.log +26 -0
  78. package/docs/investigations/hlg-runs/runZ-cliff-12b.log +26 -0
  79. package/docs/investigations/hlg-sampling-investigation.md +970 -0
  80. package/docs/investigations/lab-build-journal.md +157 -0
  81. package/docs/investigations/pi-builtin-investigation.md +308 -0
  82. package/docs/investigations/starter-model-port-handoff.md +323 -0
  83. package/docs/planning/IDEAS.md +26 -0
  84. package/docs/planning/PRODUCT_ROADMAP.md +426 -0
  85. package/docs/planning/ResearchTopics.md +119 -0
  86. package/docs/planning/chunk-task-roadmap.md +77 -0
  87. package/docs/planning/journal.md +155 -0
  88. package/docs/reference/distribution.md +121 -0
  89. package/docs/reference/embedding.md +168 -0
  90. package/docs/reference/library-api.md +153 -0
  91. package/docs/reference/server-api.md +224 -0
  92. package/docs/reference/server-config.md +243 -0
  93. package/docs/segmented-backward-handoff.md +148 -0
  94. package/package.json +68 -0
  95. package/src/anthropic.ts +491 -0
  96. package/src/chat-template.ts +186 -0
  97. package/src/cli.ts +1075 -0
  98. package/src/config.ts +229 -0
  99. package/src/curve-sampler.ts +122 -0
  100. package/src/dataset/generators.ts +1087 -0
  101. package/src/dataset/index.ts +12 -0
  102. package/src/dataset/job.ts +81 -0
  103. package/src/dataset/llm.ts +71 -0
  104. package/src/dataset/registry.ts +528 -0
  105. package/src/download.ts +283 -0
  106. package/src/eval/README.md +86 -0
  107. package/src/eval/kl-prompts.ts +29 -0
  108. package/src/eval/kl.ts +294 -0
  109. package/src/eval/quality-db.ts +92 -0
  110. package/src/eval/runner.ts +102 -0
  111. package/src/eval/score.ts +49 -0
  112. package/src/eval/tasks/bfcl.ts +500 -0
  113. package/src/eval/tasks/gsm8k.ts +85 -0
  114. package/src/eval/tasks/hashhop.ts +109 -0
  115. package/src/eval/tasks/humaneval.ts +252 -0
  116. package/src/eval/tasks/ifeval.ts +354 -0
  117. package/src/eval/tasks/mmlu.ts +145 -0
  118. package/src/evaldb.ts +199 -0
  119. package/src/expert-offload-build.ts +77 -0
  120. package/src/expert-offload.ts +61 -0
  121. package/src/expert-trace.ts +67 -0
  122. package/src/fit.ts +254 -0
  123. package/src/generate.ts +451 -0
  124. package/src/harness-pi.ts +177 -0
  125. package/src/hf-push.ts +628 -0
  126. package/src/index.ts +22 -0
  127. package/src/jobs/db.ts +139 -0
  128. package/src/jobs/index.ts +29 -0
  129. package/src/jobs/job-entry.ts +106 -0
  130. package/src/jobs/runner.ts +304 -0
  131. package/src/jobs/sse.ts +114 -0
  132. package/src/jobs/types.ts +58 -0
  133. package/src/kv-store.ts +185 -0
  134. package/src/lora.ts +314 -0
  135. package/src/md-modules.d.ts +7 -0
  136. package/src/mlx/array.ts +237 -0
  137. package/src/mlx/autograd.ts +267 -0
  138. package/src/mlx/checkpoint.ts +116 -0
  139. package/src/mlx/compile.ts +158 -0
  140. package/src/mlx/custom-vjp.ts +140 -0
  141. package/src/mlx/ffi.ts +433 -0
  142. package/src/mlx/metal-kernel.ts +130 -0
  143. package/src/mlx/ops.ts +707 -0
  144. package/src/mmap.ts +90 -0
  145. package/src/model/batched-mask.ts +204 -0
  146. package/src/model/batched-rotating.ts +300 -0
  147. package/src/model/compiled-decode.ts +681 -0
  148. package/src/model/factory.ts +27 -0
  149. package/src/model/fingerprint.ts +33 -0
  150. package/src/model/flash-attention.ts +674 -0
  151. package/src/model/fused-decode-kernel.ts +305 -0
  152. package/src/model/fused-geglu-kernel.ts +87 -0
  153. package/src/model/gemma4-base.ts +1616 -0
  154. package/src/model/gemma4.ts +1012 -0
  155. package/src/model/generated/gemma4-12b.ts +526 -0
  156. package/src/model/generated/gemma4-26b.ts +500 -0
  157. package/src/model/generated/gemma4-e4b.ts +757 -0
  158. package/src/model/generated/index.ts +18 -0
  159. package/src/model/minicpm5.ts +278 -0
  160. package/src/model/qwen3-delta.ts +224 -0
  161. package/src/model/qwen3_5.ts +429 -0
  162. package/src/model/support.ts +46 -0
  163. package/src/native-pack.ts +152 -0
  164. package/src/pi-provider.ts +95 -0
  165. package/src/pi-terminal.ts +264 -0
  166. package/src/pi-web.ts +924 -0
  167. package/src/preflight.ts +123 -0
  168. package/src/prompt-cache.ts +113 -0
  169. package/src/quantize/allocator.ts +627 -0
  170. package/src/quantize/calibration.ts +180 -0
  171. package/src/quantize/config-writer.ts +132 -0
  172. package/src/quantize/index.ts +57 -0
  173. package/src/quantize/job.ts +136 -0
  174. package/src/quantize/quantizer.ts +462 -0
  175. package/src/quantize/safetensors-writer.ts +171 -0
  176. package/src/quantize/sensitivity.ts +234 -0
  177. package/src/registry.ts +336 -0
  178. package/src/responses.ts +774 -0
  179. package/src/safetensors.ts +158 -0
  180. package/src/sampler.ts +517 -0
  181. package/src/serve/batch-scheduler.ts +362 -0
  182. package/src/serve/generation-gateway.ts +160 -0
  183. package/src/server.ts +1891 -0
  184. package/src/spec/drafter.ts +261 -0
  185. package/src/spec/generate.ts +221 -0
  186. package/src/status-page.html +497 -0
  187. package/src/tokenizer.ts +38 -0
  188. package/src/tool-call.ts +242 -0
  189. package/src/train/dataset.ts +461 -0
  190. package/src/train/export.ts +32 -0
  191. package/src/train/forward.ts +229 -0
  192. package/src/train/index.ts +43 -0
  193. package/src/train/job.ts +148 -0
  194. package/src/train/lora-params.ts +194 -0
  195. package/src/train/loss.ts +342 -0
  196. package/src/train/merge.ts +195 -0
  197. package/src/train/optimizer.ts +176 -0
  198. package/src/train/rank.ts +101 -0
  199. package/src/train/segmented.ts +520 -0
  200. package/src/train/trainer.ts +600 -0
  201. package/src/tui.ts +161 -0
  202. package/src/vision/embedder.ts +168 -0
  203. package/src/vision/preprocess.ts +247 -0
  204. package/src/vision/prompt.ts +158 -0
  205. package/src/vision/siglip.ts +599 -0
  206. package/src/web/app.html +2471 -0
  207. package/src/web/skills/web-research/SKILL.md +44 -0
  208. package/src/web/skills.ts +59 -0
  209. package/src/web-tools.ts +426 -0
  210. package/src/weights.ts +91 -0
@@ -0,0 +1,12 @@
1
+ // Public barrel for the native dataset-building engine: a TypeScript port of
2
+ // optiq lab's 13 dataset templates. Wizards/server routes import from here.
3
+
4
+ export { TEMPLATES, getTemplate, generate } from "./registry";
5
+ export type { TemplateDef, TemplateField, GenerateResult } from "./registry";
6
+
7
+ export { datasetRunner, registerDatasetRunner } from "./job";
8
+
9
+ export { makeLlmClient } from "./llm";
10
+ export type { LlmClient, ChatMessage, ChatOpts } from "./llm";
11
+
12
+ export type { Row } from "./generators";
@@ -0,0 +1,81 @@
1
+ // The dataset JobRunner: wires a submitted dataset job to generate(). Speaks
2
+ // the shared src/jobs/types.ts contract. The submit config carries the
3
+ // template id, user inputs, output dir, the server's own loopback API base,
4
+ // and an optional model name.
5
+
6
+ import type { JobRunner } from "../jobs/types";
7
+ import { makeLlmClient } from "./llm";
8
+ import { generate } from "./registry";
9
+
10
+ export const datasetRunner: JobRunner = async (emit, config) => {
11
+ const template_id = String(config.template_id ?? "");
12
+ const inputs = (config.inputs as Record<string, unknown>) ?? {};
13
+ const output_dir = String(config.output_dir ?? "");
14
+ const api_url = String(config.api_url ?? "");
15
+ const model_name = (config.model_name as string | undefined) ?? "local";
16
+
17
+ if (!template_id) throw new Error("dataset job: missing template_id");
18
+ if (!output_dir) throw new Error("dataset job: missing output_dir");
19
+
20
+ emit({
21
+ type: "stage",
22
+ stage: "starting",
23
+ progress: 0.05,
24
+ message: `Starting template ${template_id}…`,
25
+ });
26
+
27
+ const llm = api_url ? makeLlmClient(api_url, model_name) : undefined;
28
+ const r = await generate(template_id, inputs, output_dir, emit, llm);
29
+ return { outputPath: r.output_dir };
30
+ };
31
+
32
+ function applyRegister(mod: any): boolean {
33
+ const register =
34
+ mod?.registerRunner ?? mod?.register ?? mod?.default?.registerRunner ?? mod?.default?.register;
35
+ if (typeof register === "function") {
36
+ register("dataset", datasetRunner); // idempotent: registry is a Map by kind
37
+ return true;
38
+ }
39
+ return false;
40
+ }
41
+
42
+ /**
43
+ * Best-effort self-registration with the jobs runner registry. Registers the
44
+ * "dataset" kind so both submitInProcess (server path) and the subprocess
45
+ * job-entry resolver can find this runner. Tries a synchronous require first
46
+ * (so registration completes before any submit on the same tick — the
47
+ * convention quantize/finetune use), then an async import as a fallback.
48
+ * Wrapped in try/catch so importing job.ts never fails in tests or standalone
49
+ * use where ../jobs/runner isn't present. Returns true if registration
50
+ * succeeded synchronously; an async fallback may still complete shortly after.
51
+ *
52
+ * job-entry.ts's KIND_MODULES can map `dataset → ../dataset/job.ts` and rely on
53
+ * the top-level call below; the server orchestrator can alternatively await
54
+ * this explicitly at bootstrap.
55
+ */
56
+ export function registerDatasetRunner(): boolean {
57
+ // 1. Synchronous require — Bun supports import.meta.require for ESM. This is
58
+ // the path that matters for in-process submit on the same tick.
59
+ try {
60
+ const req = (import.meta as any).require ?? (globalThis as any).require;
61
+ if (typeof req === "function") {
62
+ if (applyRegister(req("../jobs/runner"))) return true;
63
+ }
64
+ } catch {
65
+ // fall through to async
66
+ }
67
+ // 2. Async fallback — completes on a later microtask. The orchestrator that
68
+ // needs guaranteed timing should call/await the runner module directly.
69
+ void (async () => {
70
+ try {
71
+ applyRegister(await import("../jobs/runner"));
72
+ } catch {
73
+ // runner module not present — orchestrator will wire registration.
74
+ }
75
+ })();
76
+ return false;
77
+ }
78
+
79
+ // Self-register on import so `kind: "dataset"` resolves wherever this module is
80
+ // loaded (mirrors quantize/finetune's top-level registration on import).
81
+ registerDatasetRunner();
@@ -0,0 +1,71 @@
1
+ // Loopback chat client for LLM-driven dataset templates. Posts to the
2
+ // mlx-bun server's own /v1/chat/completions endpoint (OpenAI shape, with
3
+ // tool calling). Ports the _llm_call / _llm_chat / _llm_chat_raw helpers
4
+ // from optiq's dataset_templates.py.
5
+
6
+ export interface ChatMessage {
7
+ role: string;
8
+ content: string;
9
+ // Tool-call traces carry extra fields (tool_calls, tool_call_id, name).
10
+ [k: string]: unknown;
11
+ }
12
+
13
+ export interface ChatOpts {
14
+ maxTokens?: number;
15
+ temperature?: number;
16
+ /** Defaults to false: dataset generators need `content`, not a hidden
17
+ * `<think>` channel that eats the whole token budget. */
18
+ enableThinking?: boolean;
19
+ /** OpenAI tools array, forwarded for tool-use traces. */
20
+ tools?: unknown[];
21
+ }
22
+
23
+ export interface LlmClient {
24
+ /** One-shot/multi-turn chat; returns the assistant content string. */
25
+ chat(messages: ChatMessage[], opts?: ChatOpts): Promise<string>;
26
+ /** Non-streaming chat returning the full JSON body (for tool_calls). */
27
+ chatRaw(messages: ChatMessage[], opts?: ChatOpts): Promise<any>;
28
+ }
29
+
30
+ const LOOPBACK_TOKEN = "sk-mlx-bun-local";
31
+
32
+ /**
33
+ * Build a loopback chat client targeting `apiUrl` (the server's own base,
34
+ * e.g. http://127.0.0.1:8080). `model` defaults to "local", the stable id
35
+ * mlx-bun advertises for its served model.
36
+ */
37
+ export function makeLlmClient(apiUrl: string, model = "local"): LlmClient {
38
+ const base = apiUrl.replace(/\/+$/, "");
39
+
40
+ async function chatRaw(messages: ChatMessage[], opts: ChatOpts = {}): Promise<any> {
41
+ const body: Record<string, unknown> = {
42
+ model,
43
+ messages,
44
+ max_tokens: opts.maxTokens ?? 512,
45
+ temperature: opts.temperature ?? 0.7,
46
+ chat_template_kwargs: { enable_thinking: opts.enableThinking ?? false },
47
+ };
48
+ if (opts.tools && opts.tools.length) body.tools = opts.tools;
49
+
50
+ const resp = await fetch(`${base}/v1/chat/completions`, {
51
+ method: "POST",
52
+ headers: {
53
+ "Content-Type": "application/json",
54
+ Authorization: `Bearer ${LOOPBACK_TOKEN}`,
55
+ },
56
+ body: JSON.stringify(body),
57
+ });
58
+ if (!resp.ok) {
59
+ const detail = await resp.text().catch(() => "");
60
+ throw new Error(`chat/completions ${resp.status}: ${detail.slice(0, 400)}`);
61
+ }
62
+ return resp.json();
63
+ }
64
+
65
+ async function chat(messages: ChatMessage[], opts?: ChatOpts): Promise<string> {
66
+ const data = await chatRaw(messages, opts);
67
+ return data?.choices?.[0]?.message?.content ?? "";
68
+ }
69
+
70
+ return { chat, chatRaw };
71
+ }
@@ -0,0 +1,528 @@
1
+ // Dataset-template registry: the 13 TemplateDefs ported field-for-field from
2
+ // optiq lab's dataset_templates.py. This file is pure metadata (the UI renders
3
+ // forms from it) plus the generate() dispatcher that does the 90/10 split and
4
+ // JSONL writing exactly like the Python reference.
5
+
6
+ import type { Emit } from "../jobs/types";
7
+ import type { LlmClient } from "./llm";
8
+ import {
9
+ genCodeCompletion,
10
+ genCotSynthesis,
11
+ genDpoPairs,
12
+ genFormatConversion,
13
+ genHfDatasetImport,
14
+ genMultiTurnChat,
15
+ genPromptReconstruction,
16
+ genRagQa,
17
+ genSelfInstruct,
18
+ genSftQa,
19
+ genStyleTransfer,
20
+ genToolUseTraces,
21
+ genVerifiedCode,
22
+ type Row,
23
+ } from "./generators";
24
+
25
+ /** A single user-facing form field. UI forms are built from these. */
26
+ export interface TemplateField {
27
+ name: string;
28
+ type: "text" | "textarea" | "number";
29
+ label: string;
30
+ hint?: string;
31
+ required?: boolean;
32
+ default?: string | number;
33
+ }
34
+
35
+ /** Metadata for one dataset-building template. */
36
+ export interface TemplateDef {
37
+ id: string;
38
+ label: string;
39
+ description: string;
40
+ output_format: "messages" | "prompt_completion" | "dpo" | "text";
41
+ needs_llm: boolean;
42
+ fields: TemplateField[];
43
+ }
44
+
45
+ export const TEMPLATES: TemplateDef[] = [
46
+ // ---- non-LLM templates (fast, local) ----
47
+ {
48
+ id: "sft_qa_pairs",
49
+ label: "SFT from QA pairs",
50
+ description:
51
+ "Paste Q/A pairs or upload a .txt with `Q: …\\nA: …` blocks. Produces chat-format JSONL.",
52
+ output_format: "messages",
53
+ needs_llm: false,
54
+ fields: [
55
+ {
56
+ name: "pairs_text",
57
+ type: "textarea",
58
+ label: "Pairs (Q: / A: blocks)",
59
+ hint: "Q: What is OptIQ?\\nA: A mixed-precision quantizer …",
60
+ required: true,
61
+ },
62
+ ],
63
+ },
64
+ {
65
+ id: "dpo_pref_pairs",
66
+ label: "DPO from preference pairs",
67
+ description: "Upload CSV with columns `prompt,chosen,rejected`. Emits DPO JSONL.",
68
+ output_format: "dpo",
69
+ needs_llm: false,
70
+ fields: [
71
+ {
72
+ name: "csv_text",
73
+ type: "textarea",
74
+ label: "CSV (header `prompt,chosen,rejected`)",
75
+ required: true,
76
+ },
77
+ ],
78
+ },
79
+ {
80
+ id: "code_completion",
81
+ label: "Code completion",
82
+ description:
83
+ "Walks a directory's .py files, splits each function at a random midpoint into prompt/completion pairs.",
84
+ output_format: "prompt_completion",
85
+ needs_llm: false,
86
+ fields: [
87
+ {
88
+ name: "src_dir",
89
+ type: "text",
90
+ label: "Source directory (containing .py files)",
91
+ required: true,
92
+ },
93
+ {
94
+ name: "max_pairs",
95
+ type: "number",
96
+ label: "Max pairs to produce",
97
+ default: 500,
98
+ },
99
+ ],
100
+ },
101
+ {
102
+ id: "hf_dataset_import",
103
+ label: "Hugging Face dataset import",
104
+ description:
105
+ "Pull a public dataset from the Hugging Face Hub by id, optionally " +
106
+ "filter rows by a column value, slice to a row cap, and emit the " +
107
+ "chosen output format. Stand-alone (no LLM call) and idempotent — " +
108
+ "use it as the first step of any pipeline that starts from a " +
109
+ "published corpus (EditLens, no_robots, dolly, your own dataset).",
110
+ output_format: "text",
111
+ needs_llm: false,
112
+ fields: [
113
+ {
114
+ name: "hf_id",
115
+ type: "text",
116
+ label: "Dataset id",
117
+ hint: "e.g. pangram/editlens_iclr or HuggingFaceH4/no_robots",
118
+ required: true,
119
+ },
120
+ {
121
+ name: "config",
122
+ type: "text",
123
+ label: "Config / subset (optional)",
124
+ hint: "Some datasets have multiple configs (e.g. wikitext-2-raw-v1).",
125
+ },
126
+ {
127
+ name: "split",
128
+ type: "text",
129
+ label: "Split",
130
+ default: "train",
131
+ },
132
+ {
133
+ name: "text_column",
134
+ type: "text",
135
+ label: "Text column",
136
+ hint: "Field on each row that holds the body text.",
137
+ default: "text",
138
+ },
139
+ {
140
+ name: "label_column",
141
+ type: "text",
142
+ label: "Filter column (optional)",
143
+ hint: "e.g. text_type for EditLens. Leave blank for no filter.",
144
+ },
145
+ {
146
+ name: "label_filter",
147
+ type: "text",
148
+ label: "Filter value (optional)",
149
+ hint: "Keep only rows where filter-column == this value. e.g. human_written.",
150
+ },
151
+ {
152
+ name: "max_rows",
153
+ type: "number",
154
+ label: "Row cap (0 = no cap)",
155
+ default: 1000,
156
+ },
157
+ {
158
+ name: "min_chars",
159
+ type: "number",
160
+ label: "Drop rows shorter than this many chars",
161
+ default: 200,
162
+ },
163
+ {
164
+ name: "output_format",
165
+ type: "text",
166
+ label: "Output format",
167
+ hint:
168
+ "One of: text | messages_user_only | prompt_completion. " +
169
+ "'text' writes {\"text\": ...}; 'messages_user_only' writes a " +
170
+ "messages row with the text as the user turn (downstream " +
171
+ "templates can read either).",
172
+ default: "text",
173
+ },
174
+ ],
175
+ },
176
+ {
177
+ id: "format_conversion",
178
+ label: "Format conversion",
179
+ description:
180
+ "Upload existing JSONL in any shape + a key mapping. Emits OptIQ-expected JSONL.",
181
+ output_format: "messages",
182
+ needs_llm: false,
183
+ fields: [
184
+ {
185
+ name: "input_jsonl",
186
+ type: "textarea",
187
+ label: "Existing JSONL",
188
+ required: true,
189
+ },
190
+ { name: "user_key", type: "text", label: "user field", default: "input" },
191
+ { name: "assistant_key", type: "text", label: "assistant field", default: "output" },
192
+ ],
193
+ },
194
+ // ---- LLM-driven templates (need a served model) ----
195
+ {
196
+ id: "style_transfer",
197
+ label: "Style transfer",
198
+ description:
199
+ "Provide reference samples and raw text. Uses the served model to rewrite in the reference style.",
200
+ output_format: "prompt_completion",
201
+ needs_llm: true,
202
+ fields: [
203
+ {
204
+ name: "reference_samples",
205
+ type: "textarea",
206
+ label: "Reference style samples (separated by ---)",
207
+ required: true,
208
+ },
209
+ {
210
+ name: "raw_text",
211
+ type: "textarea",
212
+ label: "Raw text to rewrite (one paragraph per row)",
213
+ required: true,
214
+ },
215
+ ],
216
+ },
217
+ {
218
+ id: "self_instruct",
219
+ label: "Self-instruct expansion",
220
+ description:
221
+ "Upload seed instructions; uses the served model (via data-designer when available) to generate K variants per seed.",
222
+ output_format: "messages",
223
+ needs_llm: true,
224
+ fields: [
225
+ {
226
+ name: "seeds",
227
+ type: "textarea",
228
+ label: "Seed instructions (one per line)",
229
+ required: true,
230
+ },
231
+ {
232
+ name: "variants_per_seed",
233
+ type: "number",
234
+ label: "Variants per seed",
235
+ default: 5,
236
+ },
237
+ ],
238
+ },
239
+ {
240
+ id: "prompt_reconstruction",
241
+ label: "Prompt reconstruction",
242
+ description:
243
+ "Build (AI draft → target) training pairs by working backwards: " +
244
+ "for each target paragraph the served model infers a likely prompt " +
245
+ "and writes a generic AI draft. The assistant target is the original " +
246
+ "paragraph verbatim, so facts and formatting are preserved by construction.",
247
+ output_format: "messages",
248
+ needs_llm: true,
249
+ fields: [
250
+ {
251
+ name: "target_text",
252
+ type: "textarea",
253
+ label: "Target paragraphs (separated by blank lines)",
254
+ hint:
255
+ "Paste the text you want the model to learn to produce. " +
256
+ "Posts, memos, brand-voice samples, edited drafts, etc.",
257
+ required: true,
258
+ },
259
+ {
260
+ name: "style",
261
+ type: "text",
262
+ label: "Style label",
263
+ hint: "Free text, surfaced in the system prompt.",
264
+ default: "direct technical blog",
265
+ },
266
+ {
267
+ name: "tone",
268
+ type: "text",
269
+ label: "Tone",
270
+ default: "analytical, clear, non-corporate",
271
+ },
272
+ {
273
+ name: "preserve",
274
+ type: "text",
275
+ label: "Things to preserve (comma-separated)",
276
+ default: "facts, names, numbers, URLs, citations, code blocks, quotes",
277
+ },
278
+ {
279
+ name: "avoid",
280
+ type: "text",
281
+ label: "Things to avoid (comma-separated)",
282
+ default: "em dashes, generic transitions, marketing language",
283
+ },
284
+ ],
285
+ },
286
+ {
287
+ id: "multi_turn_chat",
288
+ label: "Multi-turn chat synthesis",
289
+ description:
290
+ "Take seed user prompts and a persona; expand each into an " +
291
+ "N-turn synthetic user/assistant conversation by alternating " +
292
+ "model-as-assistant and model-as-followup-user calls.",
293
+ output_format: "messages",
294
+ needs_llm: true,
295
+ fields: [
296
+ {
297
+ name: "seeds",
298
+ type: "textarea",
299
+ label: "Seed user prompts (one per line)",
300
+ required: true,
301
+ },
302
+ {
303
+ name: "turns",
304
+ type: "number",
305
+ label: "Total turns per conversation (user + assistant pairs)",
306
+ default: 4,
307
+ },
308
+ {
309
+ name: "persona",
310
+ type: "text",
311
+ label: "Assistant persona (system prompt)",
312
+ default: "You are a helpful, concise assistant.",
313
+ },
314
+ {
315
+ name: "user_persona",
316
+ type: "text",
317
+ label: "Followup-user persona",
318
+ hint: "How follow-up questions should sound.",
319
+ default: "a curious developer probing for specifics",
320
+ },
321
+ ],
322
+ },
323
+ {
324
+ id: "tool_use_traces",
325
+ label: "Tool-use traces",
326
+ description:
327
+ "Generate (user, tool_call, tool_result, final) training traces " +
328
+ "in OpenAI tool-call shape. Provide a list of tool schemas plus " +
329
+ "scenario prompts; the model picks a tool, you supply a mocked " +
330
+ "result, the model writes the final answer.",
331
+ output_format: "messages",
332
+ needs_llm: true,
333
+ fields: [
334
+ {
335
+ name: "tools_json",
336
+ type: "textarea",
337
+ label: "Tool schemas (OpenAI tools format, JSON array)",
338
+ hint: "Paste a JSON array of {type, function:{name,description,parameters}}.",
339
+ required: true,
340
+ },
341
+ {
342
+ name: "scenarios",
343
+ type: "textarea",
344
+ label: "User scenarios (one per line)",
345
+ required: true,
346
+ },
347
+ {
348
+ name: "mock_results",
349
+ type: "textarea",
350
+ label: "Mocked tool results (one per line, matches scenarios order)",
351
+ hint: "Free text; gets passed back as the tool_result content.",
352
+ required: true,
353
+ },
354
+ ],
355
+ },
356
+ {
357
+ id: "rag_qa",
358
+ label: "RAG Q/A from documents",
359
+ description:
360
+ "Chunk pasted text into passages; for each passage the model " +
361
+ "writes a question whose answer is grounded in that passage and " +
362
+ "then writes the grounded answer. Outputs messages-format rows " +
363
+ "where the passage is in a system message and the question/answer " +
364
+ "in user/assistant turns.",
365
+ output_format: "messages",
366
+ needs_llm: true,
367
+ fields: [
368
+ {
369
+ name: "documents",
370
+ type: "textarea",
371
+ label: "Source documents (paragraphs separated by blank lines)",
372
+ required: true,
373
+ },
374
+ {
375
+ name: "questions_per_chunk",
376
+ type: "number",
377
+ label: "Questions per chunk",
378
+ default: 2,
379
+ },
380
+ {
381
+ name: "min_chunk_chars",
382
+ type: "number",
383
+ label: "Min chunk size (chars)",
384
+ default: 200,
385
+ },
386
+ ],
387
+ },
388
+ {
389
+ id: "cot_synthesis",
390
+ label: "Reasoning trace (CoT) synthesis",
391
+ description:
392
+ "For each question, the served model emits a step-by-step " +
393
+ "<think> trace followed by the final answer. Output is messages-" +
394
+ "format with the reasoning preserved inside the assistant content " +
395
+ "as a `<think>...</think>` block, matching the Qwen3 / GPT-OSS " +
396
+ "reasoning convention.",
397
+ output_format: "messages",
398
+ needs_llm: true,
399
+ fields: [
400
+ {
401
+ name: "questions",
402
+ type: "textarea",
403
+ label: "Questions (one per line)",
404
+ required: true,
405
+ },
406
+ {
407
+ name: "category",
408
+ type: "text",
409
+ label: "Domain hint",
410
+ default: "math, logic, planning, technical analysis",
411
+ },
412
+ ],
413
+ },
414
+ {
415
+ id: "verified_code",
416
+ label: "Verified code generation",
417
+ description:
418
+ "For each natural-language spec, the served model writes Python " +
419
+ "code AND a set of `assert` checks. We run the assertions in the " +
420
+ "sandbox and keep only the pairs that pass. Output is messages-" +
421
+ "format; failed pairs are dropped before writing the JSONL.",
422
+ output_format: "messages",
423
+ needs_llm: true,
424
+ fields: [
425
+ {
426
+ name: "specs",
427
+ type: "textarea",
428
+ label: "Natural-language specs (one per line)",
429
+ hint: "e.g. `write a function that returns the n-th Fibonacci number`",
430
+ required: true,
431
+ },
432
+ {
433
+ name: "language",
434
+ type: "text",
435
+ label: "Language",
436
+ default: "python",
437
+ },
438
+ ],
439
+ },
440
+ ];
441
+
442
+ export function getTemplate(id: string): TemplateDef | undefined {
443
+ return TEMPLATES.find((t) => t.id === id);
444
+ }
445
+
446
+ /** Result of a successful generate() run. */
447
+ export interface GenerateResult {
448
+ n_train: number;
449
+ n_valid: number;
450
+ output_dir: string;
451
+ }
452
+
453
+ type Inputs = Record<string, unknown>;
454
+
455
+ /** Dispatch table: template id → generator function. */
456
+ const GENERATORS: Record<
457
+ string,
458
+ (inputs: Inputs, emit: Emit, llm?: LlmClient) => Promise<Row[]>
459
+ > = {
460
+ sft_qa_pairs: genSftQa,
461
+ dpo_pref_pairs: genDpoPairs,
462
+ code_completion: genCodeCompletion,
463
+ format_conversion: genFormatConversion,
464
+ hf_dataset_import: genHfDatasetImport,
465
+ style_transfer: genStyleTransfer,
466
+ self_instruct: genSelfInstruct,
467
+ prompt_reconstruction: genPromptReconstruction,
468
+ multi_turn_chat: genMultiTurnChat,
469
+ tool_use_traces: genToolUseTraces,
470
+ rag_qa: genRagQa,
471
+ cot_synthesis: genCotSynthesis,
472
+ verified_code: genVerifiedCode,
473
+ };
474
+
475
+ /**
476
+ * Run the named template with `inputs`, write `train.jsonl` + `valid.jsonl`
477
+ * into `outputDir`, and emit progress events. Mirrors the Python reference:
478
+ * 90/10 split with `split_idx = max(1, floor(n * 0.9))`, valid = remainder
479
+ * (or the last row if the remainder is empty).
480
+ */
481
+ export async function generate(
482
+ id: string,
483
+ inputs: Inputs,
484
+ outputDir: string,
485
+ emit: Emit,
486
+ llm?: LlmClient,
487
+ ): Promise<GenerateResult> {
488
+ const gen = GENERATORS[id];
489
+ if (!gen) throw new Error(`unknown template ${JSON.stringify(id)}`);
490
+
491
+ // mkdir -p
492
+ const { mkdir } = await import("node:fs/promises");
493
+ await mkdir(outputDir, { recursive: true });
494
+
495
+ const rows = await gen(inputs, emit, llm);
496
+ const n = rows.length;
497
+ if (n === 0) {
498
+ throw new Error("generator produced 0 rows — check your inputs");
499
+ }
500
+
501
+ // 90/10 split (matches dataset_templates.py exactly).
502
+ const splitIdx = Math.max(1, Math.floor(n * 0.9));
503
+ const trainRows = rows.slice(0, splitIdx);
504
+ let validRows = rows.slice(splitIdx);
505
+ if (validRows.length === 0) validRows = rows.slice(-1); // last row fallback
506
+
507
+ const sep = outputDir.endsWith("/") ? "" : "/";
508
+ const trainPath = `${outputDir}${sep}train.jsonl`;
509
+ const validPath = `${outputDir}${sep}valid.jsonl`;
510
+
511
+ await Bun.write(trainPath, trainRows.map((r) => JSON.stringify(r)).join("\n") + "\n");
512
+ await Bun.write(validPath, validRows.map((r) => JSON.stringify(r)).join("\n") + "\n");
513
+
514
+ const nTrain = splitIdx;
515
+ const nValid = Math.max(1, n - splitIdx);
516
+
517
+ emit({
518
+ type: "stage",
519
+ stage: "done",
520
+ progress: 1.0,
521
+ message: `Wrote ${n} rows.`,
522
+ output_dir: outputDir,
523
+ n_train: nTrain,
524
+ n_valid: nValid,
525
+ });
526
+
527
+ return { n_train: nTrain, n_valid: nValid, output_dir: outputDir };
528
+ }