@orkestrel/train 0.0.0-stage → 0.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Orkestrel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # @orkestrel/train
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > A host-agnostic TypeScript trainer that fits and calibrates frozen-feature decision heads over
4
+ > the features of an `@orkestrel/infer` backbone, offline and in batch, and writes the GGUF head
5
+ > files its judge loads.
6
+
7
+ The package trains and exports both frozen-feature linear decision heads (`Trainer`) and full LoRA /
8
+ surgical LISA section adaptations (`Finetuner`, using `@orkestrel/infer`'s `BackwardInterface`) over
9
+ Llama and Qwen3.5 backbones in pure TypeScript without Python. For decision heads, it imports NDJSON
10
+ or CSV (`readTrainerCSV`) training rows, preserves `group` identifiers across cross-validation folds,
11
+ calibrates on held folds, and writes `orkestrel.*` GGUF head files. For model adaptation, it trains
12
+ GGUF LoRA adapters (`mode: 'adapter'`) and full-rank `Section` patches (`mode: 'section'` with LISA
13
+ block rotation), converts adapters to and from Hugging Face PEFT safetensors (`ggufToPEFT` /
14
+ `peftToGGUF`), streams merged checkpoints (`mergeGGUF` `Q8_0`/`Q4_K`/`BF16`/`F32` and
15
+ `mergeSafetensors`), provides resumable GGUF v3 checkpoints (`FileCheckpointStore` and
16
+ `IndexedDBCheckpointStore`), traces head errors, rankable sections, and negative flips (`traceHead` /
17
+ `traceSections` / `countFlips`), refits heads (`refitTracedHead`), calibrates adapter scales (`calibrateAdapter`),
18
+ combines adapters (`combineAdapters`), and diffs weights (`diffWeights`). `@orkestrel/train` runs on
19
+ any host, `@orkestrel/train/server` adds Node worker fitting and file checkpointing/merges, and
20
+ `@orkestrel/train/browser` adds Chromium WebGPU `GraphicsBackward` training, IndexedDB checkpoints,
21
+ and `Blob`/`File` streaming; `createTrainQueue` schedules background jobs over `@orkestrel/worker`.
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ npm install @orkestrel/train
27
+ ```
28
+
29
+ ## Guide
30
+
31
+ See [the `@orkestrel/train` guide](guides/train.md) for the training law, the faces, the method,
32
+ the measured costs, and every export.
33
+
34
+ ## Development
35
+
36
+ ```sh
37
+ npm install
38
+ npm test
39
+ ```
@@ -0,0 +1,378 @@
1
+ import type { Checkpoint } from '@orkestrel/train';
2
+ import type { CheckpointEntry } from '@orkestrel/train';
3
+ import type { CheckpointReadOptions } from '@orkestrel/train';
4
+ import type { CheckpointStoreInterface } from '@orkestrel/train';
5
+ import type { MergeGGUFOptions } from '@orkestrel/train';
6
+ import type { MergeSafetensorsOptions } from '@orkestrel/train';
7
+ import type { TrainerRow } from '@orkestrel/train';
8
+
9
+ /**
10
+ * Wraps an async iterable of byte chunks as a pull-driven browser `ReadableStream`.
11
+ *
12
+ * @remarks
13
+ * Pulls one chunk at a time from the underlying async iterator so streaming merges remain bounded
14
+ * in memory, and calls `iterator.return()` when the stream is cancelled.
15
+ *
16
+ * @param chunks - The async iterable of byte chunks
17
+ * @returns A pull-driven `ReadableStream`
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const stream = buildByteStream(mergeGGUF({ source, adapter }))
22
+ * ```
23
+ */
24
+ export declare function buildByteStream(chunks: AsyncIterable<Uint8Array<ArrayBuffer>>): ReadableStream<Uint8Array<ArrayBuffer>>;
25
+
26
+ /**
27
+ * Builds the `File` a page hands back for a checkpoint GGUF file, named by an explicit identifier
28
+ * or its SHA-256 content digest.
29
+ *
30
+ * @remarks
31
+ * When `id` is supplied, validates it against `CHECKPOINT_ID_PATTERN` and names the file
32
+ * `<id>.gguf`; otherwise computes `<sha256>.gguf`. Uses `CHECKPOINT_FILE_TYPE`.
33
+ *
34
+ * @param bytes - The serialized GGUF v3 checkpoint bytes
35
+ * @param id - Optional validated checkpoint identifier for the filename stem
36
+ * @returns The browser `File`
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const file = await buildCheckpointFile(bytes, 'step-10')
41
+ * file.name // 'step-10.gguf'
42
+ * ```
43
+ */
44
+ export declare function buildCheckpointFile(bytes: Uint8Array<ArrayBuffer>, id?: string): Promise<File>;
45
+
46
+ /**
47
+ * Builds the `File` a page hands back for a head file, named by its content.
48
+ *
49
+ * @remarks
50
+ * The name is `computeHeadName` of the bytes, the digest `@orkestrel/infer`'s head reports, and the type is
51
+ * `HEAD_FILE_TYPE`. A page can store it or offer it for download through an object URL.
52
+ *
53
+ * @param bytes - The head file's bytes
54
+ * @returns The file
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * const file = await buildHeadFile(result.bytes)
59
+ * file.name // '3f2a…9c.gguf'
60
+ * ```
61
+ */
62
+ export declare function buildHeadFile(bytes: Uint8Array<ArrayBuffer>): Promise<File>;
63
+
64
+ /**
65
+ * Builds a browser `File` containing adapter- or section-merged safetensors bytes assembled from
66
+ * `mergeSafetensors`.
67
+ *
68
+ * @remarks
69
+ * Collects streamed chunks into a `File` with media type `SAFETENSORS_FILE_TYPE` and filename
70
+ * `name` (defaulting to `SAFETENSORS_FILE_NAME`).
71
+ *
72
+ * @param options - The streaming safetensors merge options
73
+ * @param name - Optional filename for the returned `File`. Default: `SAFETENSORS_FILE_NAME`
74
+ * @returns The assembled browser `File`
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const file = await buildMergedSafetensorsFile({ source, adapter, architecture })
79
+ * file.name // 'model.safetensors'
80
+ * ```
81
+ */
82
+ export declare function buildMergedSafetensorsFile(options: MergeSafetensorsOptions, name?: string): Promise<File>;
83
+
84
+ /**
85
+ * Holds the default IndexedDB database name used by `IndexedDBCheckpointStore`.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * CHECKPOINT_DATABASE_NAME // 'orkestrel-train-checkpoints'
90
+ * ```
91
+ */
92
+ export declare const CHECKPOINT_DATABASE_NAME = "orkestrel-train-checkpoints";
93
+
94
+ /**
95
+ * Holds the media type of a checkpoint file a page receives.
96
+ *
97
+ * @remarks
98
+ * GGUF has no registered media type, so a checkpoint file is opaque bytes to the page.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * CHECKPOINT_FILE_TYPE // 'application/octet-stream'
103
+ * ```
104
+ */
105
+ export declare const CHECKPOINT_FILE_TYPE = "application/octet-stream";
106
+
107
+ /**
108
+ * Holds the IndexedDB object store name holding checkpoint records.
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * CHECKPOINT_STORE_NAME // 'checkpoints'
113
+ * ```
114
+ */
115
+ export declare const CHECKPOINT_STORE_NAME = "checkpoints";
116
+
117
+ /**
118
+ * Holds the `@orkestrel/indexeddb` store schema for browser checkpoint persistence.
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * CHECKPOINT_STORES.checkpoints.path // 'id'
123
+ * ```
124
+ */
125
+ export declare const CHECKPOINT_STORES: Readonly<{
126
+ checkpoints: Readonly<{
127
+ path: "id";
128
+ }>;
129
+ }>;
130
+
131
+ /**
132
+ * Creates an IndexedDB-backed checkpoint store for browser persistence.
133
+ *
134
+ * @param options - Optional IndexedDB database name
135
+ * @returns A {@link CheckpointStoreInterface} backed by `@orkestrel/indexeddb`
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * const store = createIndexedDBCheckpointStore({ name: 'checkpoints' })
140
+ * await store.list() // []
141
+ * ```
142
+ */
143
+ export declare function createIndexedDBCheckpointStore(options?: IndexedDBCheckpointStoreOptions): CheckpointStoreInterface;
144
+
145
+ /**
146
+ * Holds the media type of a head file a page receives.
147
+ *
148
+ * @remarks
149
+ * GGUF has no registered media type, so a head file is opaque bytes to the page.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * HEAD_FILE_TYPE // 'application/octet-stream'
154
+ * ```
155
+ */
156
+ export declare const HEAD_FILE_TYPE = "application/octet-stream";
157
+
158
+ /**
159
+ * Persists training checkpoints in browser IndexedDB through `@orkestrel/indexeddb`.
160
+ *
161
+ * @remarks
162
+ * Refuses construction with the `HOST` code when the page provides no `indexedDB` capability.
163
+ * Validates every checkpoint identifier against `CHECKPOINT_ID_PATTERN` before issuing database
164
+ * requests, and surfaces IndexedDB faults as `InferError` (`SOURCE` code) or `ABORT` when
165
+ * cancelled.
166
+ *
167
+ * @example
168
+ * ```ts
169
+ * import { createIndexedDBCheckpointStore } from '@orkestrel/train/browser'
170
+ *
171
+ * const store = createIndexedDBCheckpointStore({ name: 'checkpoints' })
172
+ * await store.save({ id: 'step-10', bytes })
173
+ * await store.has('step-10') // true
174
+ * ```
175
+ */
176
+ export declare class IndexedDBCheckpointStore implements CheckpointStoreInterface {
177
+ #private;
178
+ /**
179
+ * Creates an IndexedDB-backed checkpoint store over the named database.
180
+ *
181
+ * @param options - Optional IndexedDB database name
182
+ */
183
+ constructor(options?: IndexedDBCheckpointStoreOptions);
184
+ /**
185
+ * Writes a checkpoint entry into IndexedDB under its validated identifier.
186
+ *
187
+ * @param entry - The identifier and serialized GGUF v3 checkpoint bytes
188
+ * @param signal - Cancels the write before committing to IndexedDB
189
+ */
190
+ save(entry: CheckpointEntry, signal?: AbortSignal): Promise<void>;
191
+ /**
192
+ * Loads a stored checkpoint entry by identifier, or `undefined` when absent.
193
+ *
194
+ * @param id - The validated checkpoint identifier
195
+ * @param signal - Cancels the read
196
+ * @returns The stored entry, or `undefined` when missing
197
+ */
198
+ load(id: string, signal?: AbortSignal): Promise<CheckpointEntry | undefined>;
199
+ /**
200
+ * Checks whether a checkpoint identifier is present in the store.
201
+ *
202
+ * @param id - The validated checkpoint identifier
203
+ * @param signal - Cancels the presence check
204
+ * @returns True if the checkpoint exists; false otherwise
205
+ */
206
+ has(id: string, signal?: AbortSignal): Promise<boolean>;
207
+ /**
208
+ * Lists the stored checkpoint identifiers in ascending order.
209
+ *
210
+ * @param signal - Cancels the key listing
211
+ * @returns The sorted checkpoint identifiers
212
+ */
213
+ list(signal?: AbortSignal): Promise<readonly string[]>;
214
+ /**
215
+ * Deletes a stored checkpoint by identifier; a missing identifier is a no-op.
216
+ *
217
+ * @param id - The validated checkpoint identifier
218
+ * @param signal - Cancels the removal
219
+ */
220
+ remove(id: string, signal?: AbortSignal): Promise<void>;
221
+ /**
222
+ * Deletes every stored checkpoint from IndexedDB.
223
+ *
224
+ * @param signal - Cancels the clear operation
225
+ */
226
+ clear(signal?: AbortSignal): Promise<void>;
227
+ }
228
+
229
+ /**
230
+ * Configures an IndexedDB-backed checkpoint store.
231
+ *
232
+ * @example
233
+ * ```ts
234
+ * const options: IndexedDBCheckpointStoreOptions = { name: 'my-checkpoints' }
235
+ * ```
236
+ */
237
+ export declare interface IndexedDBCheckpointStoreOptions {
238
+ /** Holds the IndexedDB database name. Default: `CHECKPOINT_DATABASE_NAME`. */
239
+ readonly name?: string;
240
+ }
241
+
242
+ /**
243
+ * Reads and validates a GGUF v3 training checkpoint from a browser `Blob`, `File`, or
244
+ * `ReadableStream`.
245
+ *
246
+ * @remarks
247
+ * Reads the stream bytes through `readStreamBytes` and parses them through `readCheckpointGGUF`,
248
+ * enforcing format, tensor triple, finite value, and optional binding checks.
249
+ *
250
+ * @param source - The checkpoint `Blob`, `File`, or byte stream
251
+ * @param options - Optional expected bindings and abort signal
252
+ * @returns The decoded and validated checkpoint
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * const checkpoint = await readCheckpointStream(file, { base: backbone.digest })
257
+ * checkpoint.mode // 'adapter'
258
+ * ```
259
+ */
260
+ export declare function readCheckpointStream(source: Blob | ReadableStream<Uint8Array>, options?: CheckpointReadOptions): Promise<Checkpoint>;
261
+
262
+ /**
263
+ * Reads training rows from NDJSON bytes a page holds: a `Blob`, such as a `File` from an input, or a
264
+ * byte stream, such as a fetch body.
265
+ *
266
+ * @remarks
267
+ * Decodes the bytes with `readStreamText` and reads the text with `readTrainerRows`, rejecting as each
268
+ * states.
269
+ *
270
+ * @param source - The NDJSON bytes
271
+ * @param signal - Cancels the read; it then rejects with the `ABORT` code
272
+ * @returns The rows, in line order
273
+ *
274
+ * @example
275
+ * ```ts
276
+ * const rows = await readRowStream(input.files[0])
277
+ * const result = await trainer.execute(rows)
278
+ * ```
279
+ */
280
+ export declare function readRowStream(source: Blob | ReadableStream<Uint8Array>, signal?: AbortSignal): Promise<readonly TrainerRow[]>;
281
+
282
+ /**
283
+ * Reads a byte stream to the end as raw bytes.
284
+ *
285
+ * @remarks
286
+ * With a signal, pipes the stream through a pass-through transform under it so an abort cancels the
287
+ * read mid-stream and rejects with the `ABORT` code.
288
+ *
289
+ * @param stream - The byte stream
290
+ * @param signal - Cancels the read
291
+ * @returns The collected bytes
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * await readStreamBytes(new Blob([Uint8Array.of(1, 2)]).stream()) // Uint8Array [1, 2]
296
+ * ```
297
+ */
298
+ export declare function readStreamBytes(stream: ReadableStream<Uint8Array>, signal?: AbortSignal): Promise<Uint8Array<ArrayBuffer>>;
299
+
300
+ /**
301
+ * Reads a byte stream to the end as UTF-8 text.
302
+ *
303
+ * @remarks
304
+ * Decodes through a `Response`, which strips a byte order mark. With a signal, the stream is piped
305
+ * through a pass-through transform under it, so an abort cancels the read mid-stream and rejects
306
+ * with the `ABORT` code; a stream that fails otherwise rejects with its own error.
307
+ *
308
+ * @param stream - The bytes
309
+ * @param signal - Cancels the read
310
+ * @returns The text
311
+ *
312
+ * @example
313
+ * ```ts
314
+ * await readStreamText(new Blob(['{"state":"user: hi","label":"chatter"}\n']).stream())
315
+ * ```
316
+ */
317
+ export declare function readStreamText(stream: ReadableStream<Uint8Array>, signal?: AbortSignal): Promise<string>;
318
+
319
+ /**
320
+ * Holds the default file name assigned by `buildMergedSafetensorsFile` when no name is supplied.
321
+ *
322
+ * @example
323
+ * ```ts
324
+ * SAFETENSORS_FILE_NAME // 'model.safetensors'
325
+ * ```
326
+ */
327
+ export declare const SAFETENSORS_FILE_NAME = "model.safetensors";
328
+
329
+ /**
330
+ * Holds the media type of a merged safetensors file a page receives.
331
+ *
332
+ * @remarks
333
+ * Safetensors has no registered media type, so the file is opaque bytes to the page.
334
+ *
335
+ * @example
336
+ * ```ts
337
+ * SAFETENSORS_FILE_TYPE // 'application/octet-stream'
338
+ * ```
339
+ */
340
+ export declare const SAFETENSORS_FILE_TYPE = "application/octet-stream";
341
+
342
+ /**
343
+ * Streams an adapter- or section-merged GGUF v3 file in the browser as a pull-driven
344
+ * `ReadableStream`.
345
+ *
346
+ * @remarks
347
+ * Delegates to `mergeGGUF` and `buildByteStream`, pulling bounded slices without holding the full
348
+ * base checkpoint in memory, supporting `F32`, `BF16`, `Q8_0`, and `Q4_K` targeted tensor formats.
349
+ *
350
+ * @param options - The streaming GGUF merge options
351
+ * @returns A `ReadableStream` yielding merged GGUF v3 bytes
352
+ *
353
+ * @example
354
+ * ```ts
355
+ * const stream = streamMergedGGUF({ source, adapter, format: 'F32' })
356
+ * ```
357
+ */
358
+ export declare function streamMergedGGUF(options: MergeGGUFOptions): ReadableStream<Uint8Array<ArrayBuffer>>;
359
+
360
+ /**
361
+ * Streams an adapter- or section-merged safetensors file in the browser as a pull-driven
362
+ * `ReadableStream`.
363
+ *
364
+ * @remarks
365
+ * Delegates to `mergeSafetensors` and `buildByteStream`, pulling bounded slices without holding the
366
+ * full base checkpoint in memory.
367
+ *
368
+ * @param options - The streaming safetensors merge options
369
+ * @returns A `ReadableStream` yielding merged safetensors bytes
370
+ *
371
+ * @example
372
+ * ```ts
373
+ * const stream = streamMergedSafetensors({ source, adapter, architecture })
374
+ * ```
375
+ */
376
+ export declare function streamMergedSafetensors(options: MergeSafetensorsOptions): ReadableStream<Uint8Array<ArrayBuffer>>;
377
+
378
+ export { }