@claude-flow/cli 3.18.2 → 3.20.0

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.
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Native training via @ruvector/ruvllm's TrainingPipeline (#2549 follow-up).
3
+ *
4
+ * `neural train` historically trained only on the RuVector WASM path
5
+ * (MicroLoRA + InfoNCE) and its "checkpoint" was a freshly-constructed
6
+ * adapter's weights — the native TrainingPipeline (real epochs, loss
7
+ * history, early stopping, EWC registration, disk checkpoints since
8
+ * ruvllm 2.5.7) was never exercised. This service routes the LoRA
9
+ * training leg through it.
10
+ *
11
+ * Batch formulation: pattern-alignment pairs — input = embedding[i],
12
+ * target = embedding[i+1 mod n], quality 1.0 — the MSE analogue of the
13
+ * WASM path's anchor→positive contrastive objective (adjacent training
14
+ * items belong to the same pattern family by construction).
15
+ *
16
+ * Graceful: returns null when @ruvector/ruvllm is absent or anything
17
+ * throws — callers fall back to the WASM path.
18
+ */
19
+ export interface NativeTrainingResult {
20
+ epochs: number;
21
+ steps: number;
22
+ finalLoss: number;
23
+ bestValLoss: number | null;
24
+ durationMs: number;
25
+ earlyStopped: boolean;
26
+ checkpointPath?: string;
27
+ checkpointBytes?: number;
28
+ /** True when training resumed from a --resume checkpoint. */
29
+ resumed?: boolean;
30
+ /**
31
+ * How the resume happened: 'resumeFrom' (ruvllm >=2.6.0 — restores epoch
32
+ * position + optimizer state) or 'loadCheckpoint' (2.5.7 fallback —
33
+ * weights only, training restarts from epoch 0).
34
+ */
35
+ resumeMode?: 'resumeFrom' | 'loadCheckpoint';
36
+ }
37
+ export interface NativeTrainingOptions {
38
+ embeddings: Float32Array[];
39
+ epochs: number;
40
+ batchSize: number;
41
+ learningRate: number;
42
+ dim: number;
43
+ /**
44
+ * Validation holdout fraction (0..1). >0 makes the pipeline report
45
+ * bestValLoss + early-stopping; 0 (or omitted) disables validation.
46
+ * validationSplit exists in ruvllm 2.5.7 — no version gate needed.
47
+ */
48
+ validationSplit?: number;
49
+ /**
50
+ * Resume weights (and, on >=2.6.0, epoch position) from this checkpoint
51
+ * BEFORE training. A missing/invalid path throws ResumeFailedError — an
52
+ * explicit --resume must fail loudly, never silently fresh-train.
53
+ */
54
+ resumeFrom?: string;
55
+ /** When set, the TRAINED pipeline checkpoints here (ruvllm >=2.5.7). */
56
+ checkpointPath?: string;
57
+ }
58
+ /**
59
+ * Thrown when an explicit --resume checkpoint cannot be found or loaded.
60
+ * Distinct from the generic "native unavailable → null" degradation so the
61
+ * caller can surface a loud, exit-1 failure rather than fresh training.
62
+ */
63
+ export declare class ResumeFailedError extends Error {
64
+ constructor(message: string);
65
+ }
66
+ export declare function nativeTrainingAvailable(): boolean;
67
+ export declare function runNativeTraining(opts: NativeTrainingOptions): Promise<NativeTrainingResult | null>;
68
+ //# sourceMappingURL=native-training.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-training.d.ts","sourceRoot":"","sources":["../../../src/services/native-training.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAMH,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,OAAO,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,6DAA6D;IAC7D,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;OAIG;IACH,UAAU,CAAC,EAAE,YAAY,GAAG,gBAAgB,CAAC;CAC9C;AAED,MAAM,WAAW,qBAAqB;IACpC,UAAU,EAAE,YAAY,EAAE,CAAC;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,wEAAwE;IACxE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;gBAC9B,OAAO,EAAE,MAAM;CAI5B;AAED,wBAAgB,uBAAuB,IAAI,OAAO,CAOjD;AAED,wBAAsB,iBAAiB,CACrC,IAAI,EAAE,qBAAqB,GAC1B,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAsGtC"}
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Native training via @ruvector/ruvllm's TrainingPipeline (#2549 follow-up).
3
+ *
4
+ * `neural train` historically trained only on the RuVector WASM path
5
+ * (MicroLoRA + InfoNCE) and its "checkpoint" was a freshly-constructed
6
+ * adapter's weights — the native TrainingPipeline (real epochs, loss
7
+ * history, early stopping, EWC registration, disk checkpoints since
8
+ * ruvllm 2.5.7) was never exercised. This service routes the LoRA
9
+ * training leg through it.
10
+ *
11
+ * Batch formulation: pattern-alignment pairs — input = embedding[i],
12
+ * target = embedding[i+1 mod n], quality 1.0 — the MSE analogue of the
13
+ * WASM path's anchor→positive contrastive objective (adjacent training
14
+ * items belong to the same pattern family by construction).
15
+ *
16
+ * Graceful: returns null when @ruvector/ruvllm is absent or anything
17
+ * throws — callers fall back to the WASM path.
18
+ */
19
+ import { createRequire } from 'module';
20
+ import { mkdirSync, existsSync } from 'fs';
21
+ import { dirname } from 'path';
22
+ /**
23
+ * Thrown when an explicit --resume checkpoint cannot be found or loaded.
24
+ * Distinct from the generic "native unavailable → null" degradation so the
25
+ * caller can surface a loud, exit-1 failure rather than fresh training.
26
+ */
27
+ export class ResumeFailedError extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = 'ResumeFailedError';
31
+ }
32
+ }
33
+ export function nativeTrainingAvailable() {
34
+ try {
35
+ createRequire(import.meta.url).resolve('@ruvector/ruvllm');
36
+ return true;
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ export async function runNativeTraining(opts) {
43
+ const { embeddings, epochs, batchSize, learningRate, dim, validationSplit, resumeFrom, checkpointPath } = opts;
44
+ if (embeddings.length < 2)
45
+ return null;
46
+ try {
47
+ const req = createRequire(import.meta.url);
48
+ const ruvllm = req('@ruvector/ruvllm');
49
+ const pipelineConfig = {
50
+ learningRate,
51
+ batchSize,
52
+ epochs,
53
+ inputDim: dim,
54
+ outputDim: dim,
55
+ };
56
+ // 0 (or omitted) disables validation; only pass a real holdout through.
57
+ if (typeof validationSplit === 'number' && validationSplit > 0) {
58
+ pipelineConfig.validationSplit = validationSplit;
59
+ }
60
+ const pipeline = new ruvllm.TrainingPipeline(pipelineConfig);
61
+ // Resume BEFORE training. Prefer resumeFrom() (2.6.0 — epoch position +
62
+ // optimizer state); fall back to loadCheckpoint() (2.5.7 — weights only).
63
+ // Any failure with an explicit --resume is loud (ResumeFailedError),
64
+ // never silent fresh training.
65
+ let resumed = false;
66
+ let resumeMode;
67
+ if (resumeFrom) {
68
+ if (!existsSync(resumeFrom)) {
69
+ throw new ResumeFailedError(`--resume checkpoint not found: ${resumeFrom}`);
70
+ }
71
+ try {
72
+ if (typeof pipeline.resumeFrom === 'function') {
73
+ pipeline.resumeFrom(resumeFrom);
74
+ resumeMode = 'resumeFrom';
75
+ }
76
+ else {
77
+ const ok = pipeline.loadCheckpoint(resumeFrom);
78
+ if (ok === false)
79
+ throw new Error('loadCheckpoint returned false');
80
+ resumeMode = 'loadCheckpoint';
81
+ }
82
+ resumed = true;
83
+ }
84
+ catch (e) {
85
+ if (e instanceof ResumeFailedError)
86
+ throw e;
87
+ throw new ResumeFailedError(`--resume failed to load checkpoint ${resumeFrom}: ${e.message}`);
88
+ }
89
+ }
90
+ // Pattern-alignment pairs, chunked into pipeline batches.
91
+ const inputs = [];
92
+ const targets = [];
93
+ const qualities = [];
94
+ for (let i = 0; i < embeddings.length; i++) {
95
+ inputs.push(Array.from(embeddings[i]));
96
+ targets.push(Array.from(embeddings[(i + 1) % embeddings.length]));
97
+ qualities.push(1.0);
98
+ }
99
+ for (let i = 0; i < inputs.length; i += batchSize) {
100
+ pipeline.addBatch(inputs.slice(i, i + batchSize), targets.slice(i, i + batchSize), qualities.slice(i, i + batchSize));
101
+ }
102
+ const r = pipeline.train();
103
+ // When validation is disabled the pipeline reports Infinity for
104
+ // bestValLoss — normalize any non-finite value to null so downstream
105
+ // "bestValLoss !== null ⇒ validation ran" holds for the results table.
106
+ const bestValLoss = typeof r.bestValLoss === 'number' && Number.isFinite(r.bestValLoss)
107
+ ? r.bestValLoss
108
+ : null;
109
+ const result = {
110
+ epochs: r.epochs,
111
+ steps: r.steps,
112
+ finalLoss: r.finalLoss,
113
+ bestValLoss,
114
+ durationMs: r.durationMs,
115
+ earlyStopped: !!r.earlyStopped,
116
+ resumed,
117
+ resumeMode,
118
+ };
119
+ if (checkpointPath) {
120
+ try {
121
+ mkdirSync(dirname(checkpointPath), { recursive: true });
122
+ const saved = pipeline.saveCheckpoint(checkpointPath);
123
+ // <2.5.7 returns undefined and writes nothing — verify on disk.
124
+ if (existsSync(checkpointPath)) {
125
+ result.checkpointPath = checkpointPath;
126
+ result.checkpointBytes = saved?.bytes;
127
+ }
128
+ }
129
+ catch { /* checkpoint is best-effort; training result stands */ }
130
+ }
131
+ return result;
132
+ }
133
+ catch (err) {
134
+ // An explicit --resume failure must propagate as a loud error; every
135
+ // other failure degrades to null so callers fall back to the WASM path.
136
+ if (err instanceof ResumeFailedError)
137
+ throw err;
138
+ return null;
139
+ }
140
+ }
141
+ //# sourceMappingURL=native-training.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-training.js","sourceRoot":"","sources":["../../../src/services/native-training.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,Q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