@hviana/sema 0.2.6 → 0.2.8
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/dist/example/demo.d.ts +1 -0
- package/dist/example/demo.js +39 -0
- package/dist/example/train_base.d.ts +87 -0
- package/dist/example/train_base.js +2252 -0
- package/dist/src/alphabet.d.ts +7 -0
- package/dist/src/alphabet.js +33 -0
- package/dist/src/alu/src/alu.d.ts +185 -0
- package/dist/src/alu/src/alu.js +440 -0
- package/dist/src/alu/src/expr.d.ts +61 -0
- package/dist/src/alu/src/expr.js +318 -0
- package/dist/src/alu/src/index.d.ts +11 -0
- package/dist/src/alu/src/index.js +19 -0
- package/dist/src/alu/src/kernel-arith.d.ts +16 -0
- package/dist/src/alu/src/kernel-arith.js +264 -0
- package/dist/src/alu/src/kernel-bits.d.ts +19 -0
- package/dist/src/alu/src/kernel-bits.js +152 -0
- package/dist/src/alu/src/kernel-logic.d.ts +4 -0
- package/dist/src/alu/src/kernel-logic.js +60 -0
- package/dist/src/alu/src/kernel-nd.d.ts +3 -0
- package/dist/src/alu/src/kernel-nd.js +208 -0
- package/dist/src/alu/src/kernel-numeric.d.ts +54 -0
- package/dist/src/alu/src/kernel-numeric.js +366 -0
- package/dist/src/alu/src/operation.d.ts +168 -0
- package/dist/src/alu/src/operation.js +189 -0
- package/dist/src/alu/src/parser.d.ts +221 -0
- package/dist/src/alu/src/parser.js +577 -0
- package/dist/src/alu/src/resonance.d.ts +55 -0
- package/dist/src/alu/src/resonance.js +126 -0
- package/dist/src/alu/src/text.d.ts +31 -0
- package/dist/src/alu/src/text.js +73 -0
- package/dist/src/alu/src/value.d.ts +109 -0
- package/dist/src/alu/src/value.js +300 -0
- package/dist/src/alu/test/alu.test.d.ts +1 -0
- package/dist/src/alu/test/alu.test.js +764 -0
- package/dist/src/bytes.d.ts +14 -0
- package/dist/src/bytes.js +59 -0
- package/dist/src/canon.d.ts +26 -0
- package/dist/src/canon.js +57 -0
- package/dist/src/config.d.ts +111 -0
- package/dist/src/config.js +91 -0
- package/dist/src/derive/src/deduction.d.ts +125 -0
- package/dist/src/derive/src/deduction.js +155 -0
- package/dist/src/derive/src/index.d.ts +7 -0
- package/dist/src/derive/src/index.js +11 -0
- package/dist/src/derive/src/priority-queue.d.ts +20 -0
- package/dist/src/derive/src/priority-queue.js +73 -0
- package/dist/src/derive/src/rewrite.d.ts +56 -0
- package/dist/src/derive/src/rewrite.js +100 -0
- package/dist/src/derive/src/trie.d.ts +90 -0
- package/dist/src/derive/src/trie.js +217 -0
- package/dist/src/derive/test/derive.test.d.ts +1 -0
- package/dist/src/derive/test/derive.test.js +122 -0
- package/dist/src/extension.d.ts +37 -0
- package/dist/src/extension.js +7 -0
- package/dist/src/geometry.d.ts +202 -0
- package/dist/src/geometry.js +575 -0
- package/dist/src/index.d.ts +16 -0
- package/dist/src/index.js +18 -0
- package/dist/src/ingest-cache.d.ts +41 -0
- package/dist/src/ingest-cache.js +161 -0
- package/dist/src/mind/articulation.d.ts +6 -0
- package/dist/src/mind/articulation.js +99 -0
- package/dist/src/mind/attention.d.ts +405 -0
- package/dist/src/mind/attention.js +1829 -0
- package/dist/src/mind/bridge.d.ts +30 -0
- package/dist/src/mind/bridge.js +569 -0
- package/dist/src/mind/canonical.d.ts +29 -0
- package/dist/src/mind/canonical.js +88 -0
- package/dist/src/mind/graph-search.d.ts +285 -0
- package/dist/src/mind/graph-search.js +956 -0
- package/dist/src/mind/index.d.ts +7 -0
- package/dist/src/mind/index.js +5 -0
- package/dist/src/mind/junction.d.ts +124 -0
- package/dist/src/mind/junction.js +317 -0
- package/dist/src/mind/learning.d.ts +47 -0
- package/dist/src/mind/learning.js +248 -0
- package/dist/src/mind/match.d.ts +126 -0
- package/dist/src/mind/match.js +441 -0
- package/dist/src/mind/mechanisms/alu.d.ts +4 -0
- package/dist/src/mind/mechanisms/alu.js +36 -0
- package/dist/src/mind/mechanisms/cast.d.ts +89 -0
- package/dist/src/mind/mechanisms/cast.js +716 -0
- package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
- package/dist/src/mind/mechanisms/confluence.js +225 -0
- package/dist/src/mind/mechanisms/cover.d.ts +6 -0
- package/dist/src/mind/mechanisms/cover.js +203 -0
- package/dist/src/mind/mechanisms/extraction.d.ts +67 -0
- package/dist/src/mind/mechanisms/extraction.js +387 -0
- package/dist/src/mind/mechanisms/recall.d.ts +13 -0
- package/dist/src/mind/mechanisms/recall.js +325 -0
- package/dist/src/mind/mind.d.ts +276 -0
- package/dist/src/mind/mind.js +572 -0
- package/dist/src/mind/pipeline-mechanism.d.ts +142 -0
- package/dist/src/mind/pipeline-mechanism.js +213 -0
- package/dist/src/mind/pipeline.d.ts +20 -0
- package/dist/src/mind/pipeline.js +217 -0
- package/dist/src/mind/primitives.d.ts +70 -0
- package/dist/src/mind/primitives.js +287 -0
- package/dist/src/mind/rationale.d.ts +139 -0
- package/dist/src/mind/rationale.js +163 -0
- package/dist/src/mind/reasoning.d.ts +34 -0
- package/dist/src/mind/reasoning.js +240 -0
- package/dist/src/mind/recognition.d.ts +20 -0
- package/dist/src/mind/recognition.js +390 -0
- package/dist/src/mind/resonance.d.ts +23 -0
- package/dist/src/mind/resonance.js +0 -0
- package/dist/src/mind/trace.d.ts +15 -0
- package/dist/src/mind/trace.js +73 -0
- package/dist/src/mind/traverse.d.ts +113 -0
- package/dist/src/mind/traverse.js +568 -0
- package/dist/src/mind/types.d.ts +289 -0
- package/dist/src/mind/types.js +130 -0
- package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
- package/dist/src/rabitq-ivf/src/database.js +201 -0
- package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
- package/dist/src/rabitq-ivf/src/index.js +4 -0
- package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
- package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
- package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
- package/dist/src/rabitq-ivf/src/prng.js +36 -0
- package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
- package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
- package/dist/src/sema.d.ts +31 -0
- package/dist/src/sema.js +63 -0
- package/dist/src/store-sqlite.d.ts +184 -0
- package/dist/src/store-sqlite.js +942 -0
- package/dist/src/store.d.ts +663 -0
- package/dist/src/store.js +1618 -0
- package/dist/src/vec.d.ts +31 -0
- package/dist/src/vec.js +109 -0
- package/package.json +1 -1
- package/src/mind/attention.ts +178 -63
- package/test/51-structural-resonance-ladder.test.mjs +6 -3
|
@@ -0,0 +1,2252 @@
|
|
|
1
|
+
//This file uses the Google SMOL dataset, made available under the CC BY 4.0 license.
|
|
2
|
+
//This file uses Aya and oasst2 datasets, made available under the apache-2.0 license.
|
|
3
|
+
//This file uses MuskumPillerum/General-Knowledge dataset, made available under the MIT license.
|
|
4
|
+
//This file is a more appropriate training example for Sema.
|
|
5
|
+
//Sema does not learn through repetition;
|
|
6
|
+
//it does not require a massive database.
|
|
7
|
+
//It needs fundamental datasets that teach basic cognitive concepts such as conversation, logic, relationships, behaviors and feelings.
|
|
8
|
+
//The focus is on covering fundamental patterns, not repetition.
|
|
9
|
+
//Tip: ontology-based adapted training datasets could be an interesting path.
|
|
10
|
+
// train_base.ts — streaming trainer for the SmolSent + Aya + oasst2 +
|
|
11
|
+
// General-Knowledge base.
|
|
12
|
+
//
|
|
13
|
+
// Training IS deposition: every source datum is translated into SEMA facts (or,
|
|
14
|
+
// for genuine dialogue, accumulated-context episodes), then stored in one pass.
|
|
15
|
+
// There are no gradients or epochs, and there is no LLM in the loop — the only
|
|
16
|
+
// "model" is the SEMA store itself. The ingestion structures, filtering,
|
|
17
|
+
// checkpointing, cache, and resume model are unchanged from the original LLM-
|
|
18
|
+
// base trainer; only corpus discovery and the row adapters are source-specific.
|
|
19
|
+
//
|
|
20
|
+
// Every source here is commercially licensable (cc-by-4.0 / apache-2.0).
|
|
21
|
+
//
|
|
22
|
+
// The curriculum runs in four stages, into ONE store:
|
|
23
|
+
// 1. SmolSent (google/smol) — sentence-level TRANSLATION pairs across 100+
|
|
24
|
+
// low-resource languages; see §6c. Each pair is "two names for one meaning"
|
|
25
|
+
// → bidirectional translation FACTS, the cross-language concept SEMA fuses
|
|
26
|
+
// (cf. test/05-concepts.test.mjs).
|
|
27
|
+
// 2. Aya Dataset — ~204k human prompt→completion pairs, 70+ languages; see §6d
|
|
28
|
+
// → one (question → answer) FACT each.
|
|
29
|
+
// 3. oasst2 — MULTI-TURN human↔assistant conversation trees; see §6e → the
|
|
30
|
+
// accumulated-context walk (single-turn trees are skipped, by design).
|
|
31
|
+
// 4. General-Knowledge (MuskumPillerum) — ~37.6k {Question, Answer} pairs; see
|
|
32
|
+
// §6f → one (question → answer) FACT each.
|
|
33
|
+
// Each stage runs only after the previous one finishes, and is recorded in the
|
|
34
|
+
// same completed-files set, so a single store resumes the whole curriculum.
|
|
35
|
+
//
|
|
36
|
+
// Every source is DOWNLOADED as a file and streamed from disk (never paged
|
|
37
|
+
// row-by-row over an HTTP API — that was slow and rate-limited): SmolSent as
|
|
38
|
+
// per-pair JSONL, oasst2 as a gzipped JSONL, General-Knowledge as a JSON array,
|
|
39
|
+
// and Aya as Snappy-Parquet read row-group by row-group with hyparquet (the one
|
|
40
|
+
// case the web platform can't decode alone). Resume is per-file: a fully-
|
|
41
|
+
// consumed file is marked complete; an interrupted one re-reads from the top
|
|
42
|
+
// (re-deposition is idempotent). LOCAL_PATH may hold pre-downloaded files.
|
|
43
|
+
//
|
|
44
|
+
// REPRESENTATION POLICY (one datum → one form; no replication):
|
|
45
|
+
// • FACTS are the default. A datum that is a RELATION (translation pair,
|
|
46
|
+
// question → answer) is emitted as a (context → continuation) edge SEMA
|
|
47
|
+
// points at and, by example across the corpus, generalizes from (cf.
|
|
48
|
+
// example/demo.ts). SmolSent emits two facts (both directions); Aya one.
|
|
49
|
+
// • EXPERIENCES (bare statements) are used only when a fact is NOT possible —
|
|
50
|
+
// content with no natural relational split. (No current stage needs this;
|
|
51
|
+
// it stays available for plain-text corpora.)
|
|
52
|
+
// • CUMULATIVE CONTINUOUS CONTEXT is used only when truly necessary — genuine
|
|
53
|
+
// MULTI-TURN dialogue, where a turn follows from the whole conversation so
|
|
54
|
+
// far. Only oasst2 (§6e) uses it; the fact stages do NOT synthesize a multi-
|
|
55
|
+
// turn walk, which would just replicate the facts (repetition SEMA avoids).
|
|
56
|
+
//
|
|
57
|
+
// The store IS the model: memories, training metadata, and the config snapshot
|
|
58
|
+
// all live in {DB_PATH}.sqlite, so a run resumes from the store alone.
|
|
59
|
+
//
|
|
60
|
+
// Built on web standards. All I/O except the durable disk cache uses platform
|
|
61
|
+
// primitives — fetch, WHATWG ReadableStream/WritableStream/TransformStream,
|
|
62
|
+
// DecompressionStream ("gzip" for the oasst2 file), TextDecoderStream, Blob,
|
|
63
|
+
// AbortController. The sole third-party code is hyparquet (+ its Snappy codec),
|
|
64
|
+
// used only to read Aya's Parquet over a web-standard Blob byte source. Node's
|
|
65
|
+
// stdlib is touched only for the filesystem (the cache), which the web platform
|
|
66
|
+
// does not expose. Consistency guarantees:
|
|
67
|
+
// • Resume from the store alone — completed stage-units, example count,
|
|
68
|
+
// learned-content bytes, and processed-byte total are persisted in
|
|
69
|
+
// {DB_PATH}.sqlite and reloaded. API stages persist a page offset; the
|
|
70
|
+
// oasst2 download is atomic (see below).
|
|
71
|
+
// • Atomic cache — a download streams to "<file>.part", is fsync'd, then
|
|
72
|
+
// renamed into place; a file at its final path is, by construction,
|
|
73
|
+
// complete, so an interrupted download can never be mistaken for a cached
|
|
74
|
+
// one.
|
|
75
|
+
// • Bounded cache — a download blocks under the MAX_CACHE_GB ceiling and the
|
|
76
|
+
// fully-processed file is deleted immediately.
|
|
77
|
+
// • Interruptible — Ctrl+C (SIGINT/SIGTERM) aborts in-flight network at once,
|
|
78
|
+
// stops at the next item boundary, writes a final checkpoint, and exits; an
|
|
79
|
+
// un-finished stage-unit is NOT marked complete, so resume re-reads it (re-
|
|
80
|
+
// deposition is idempotent). A second Ctrl+C, or a 60s watchdog, force-exits.
|
|
81
|
+
//
|
|
82
|
+
// Run:
|
|
83
|
+
// npx tsc && node dist/example/train_base.js
|
|
84
|
+
// MAX_MB=500 node dist/example/train_base.js
|
|
85
|
+
// CHECKPOINT_MB=250 node dist/example/train_base.js
|
|
86
|
+
// SMOLSENT_PAIRS=ha_en,zu_en node dist/example/train_base.js # a subset of pairs
|
|
87
|
+
// SMOLSENT=0 node dist/example/train_base.js # skip SmolSent stage
|
|
88
|
+
// AYA=0 node dist/example/train_base.js # skip Aya stage
|
|
89
|
+
// AYA_SPLIT=test node dist/example/train_base.js # small Aya slice
|
|
90
|
+
// OASST=0 node dist/example/train_base.js # skip oasst2 stage
|
|
91
|
+
// OASST_MIN_TURNS=6 node dist/example/train_base.js # deeper multi-turn only
|
|
92
|
+
// GENKNOW=0 node dist/example/train_base.js # skip General-Knowledge
|
|
93
|
+
// LOCAL_PATH=./base node dist/example/train_base.js # offline: *.jsonl/.parquet/.jsonl.gz/.json
|
|
94
|
+
// DB_PATH=./data/sema node dist/example/train_base.js
|
|
95
|
+
import { CachedIngest, Mind, SQliteStore } from "../src/index.js";
|
|
96
|
+
// One Node module — node:fs — and nothing else. Everything else (HTTP, byte
|
|
97
|
+
// streams, (de)compression, text decoding, cancellation) is a web standard:
|
|
98
|
+
// fetch, WHATWG ReadableStream/WritableStream/TransformStream,
|
|
99
|
+
// DecompressionStream, TextDecoderStream, Blob, AbortController. Reading a file
|
|
100
|
+
// goes through openAsBlob, which returns a web Blob (`.stream()` → web streams);
|
|
101
|
+
// writing a file is the single capability the web platform does not expose, so
|
|
102
|
+
// the download sink uses the synchronous fs descriptor calls below. The durable
|
|
103
|
+
// disk cache is therefore the sole, irreducible Node dependency.
|
|
104
|
+
import { closeSync, existsSync, fsyncSync, mkdirSync, openAsBlob, openSync, readdirSync, renameSync, statSync, unlinkSync, writeSync, } from "node:fs";
|
|
105
|
+
import { basename, join } from "node:path";
|
|
106
|
+
// The ONLY third-party dependencies, and only for the one source that ships
|
|
107
|
+
// exclusively as Snappy-compressed Parquet (Aya): hyparquet is a pure-JS,
|
|
108
|
+
// dependency-free Parquet reader driven over a web-standard Blob byte source;
|
|
109
|
+
// hyparquet-compressors supplies the Snappy codec. Every other source is plain
|
|
110
|
+
// JSONL / JSON / gzip and needs no library.
|
|
111
|
+
import { parquetMetadataAsync, parquetReadObjects } from "hyparquet";
|
|
112
|
+
import { compressors } from "hyparquet-compressors";
|
|
113
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
114
|
+
// §1 Configuration (all from the environment)
|
|
115
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
116
|
+
const env = (k, d) => process.env[k] ?? d;
|
|
117
|
+
// ── google/smol · SmolSent (the first training stage) ──
|
|
118
|
+
// SmolSent is Google's sentence-level translation set: ~863 human sentence pairs
|
|
119
|
+
// per language pair across 100+ low-resource languages, cc-by-4.0 (commercial-
|
|
120
|
+
// friendly). Each row is {sl, tl, src, trg, …} — a source sentence and its
|
|
121
|
+
// translation. A pair is "two names for one meaning", which is exactly the
|
|
122
|
+
// cross-language concept SEMA fuses (see test/05-concepts.test.mjs), so each row
|
|
123
|
+
// becomes FACTS that bind the two phrasings as one concept at recall time.
|
|
124
|
+
//
|
|
125
|
+
// The corpus ships as one plain JSONL file PER language pair under smolsent/ in
|
|
126
|
+
// the HF repo (e.g. smolsent/ha_en.jsonl). We DOWNLOAD each file and stream its
|
|
127
|
+
// lines — far faster and free of the rate-limiting that per-row API paging hit.
|
|
128
|
+
// The file list is discovered from the HF repo tree. SMOLSENT=0 disables the
|
|
129
|
+
// stage; SMOLSENT_PAIRS (comma-separated basenames without .jsonl, e.g.
|
|
130
|
+
// "ha_en,zu_en") restricts to a chosen subset.
|
|
131
|
+
const SMOLSENT = env("SMOLSENT", "1") !== "0";
|
|
132
|
+
const SMOLSENT_DATASET = env("SMOLSENT_DATASET", "google/smol");
|
|
133
|
+
const SMOLSENT_PAIRS = (process.env.SMOLSENT_PAIRS ?? "")
|
|
134
|
+
.split(",").map((s) => s.trim()).filter(Boolean);
|
|
135
|
+
// The resume id PREFIX for the SmolSent stage; one completed-files entry per
|
|
136
|
+
// file (e.g. "smolsent::ha_en.jsonl").
|
|
137
|
+
const SMOLSENT_ID = "smolsent";
|
|
138
|
+
// A SmolSent side longer than this is skipped (a sentence pair is short; a huge
|
|
139
|
+
// value is corruption, not a sentence).
|
|
140
|
+
const MAX_SMOLSENT_CHARS = Math.max(2_000, Math.floor(Number(env("MAX_SMOLSENT_KB", "16")) * 1000) || 16_000);
|
|
141
|
+
const DB_PATH = env("DB_PATH", "sema"); // → {DB_PATH}.sqlite
|
|
142
|
+
const D = Number(env("D", "1024"));
|
|
143
|
+
const SEED = Number(env("SEED", "7"));
|
|
144
|
+
// Checkpoint cadence is measured in LEARNED CONTENT, not deposits: a snapshot
|
|
145
|
+
// every CHECKPOINT_MB megabytes of trained UTF-8 content (decimal MB, matching
|
|
146
|
+
// the bytes() helper). A floor of 1 MB: a zero/NaN value must not make every
|
|
147
|
+
// deposit checkpoint, nor silently disable checkpointing. The tail (a run that
|
|
148
|
+
// learns less than one interval, or the remainder past the last interval) is
|
|
149
|
+
// always saved by finish() at exit — a complete point.
|
|
150
|
+
const CHECKPOINT_BYTES = Math.max(1_000_000, Math.floor(Number(env("CHECKPOINT_MB", "100")) * 1_000_000) || 100_000_000);
|
|
151
|
+
const LOCAL_PATH = env("LOCAL_PATH", ""); // train from a local dir of *.zip
|
|
152
|
+
const CACHE_DIR = env("CACHE_DIR", join(process.cwd(), "cache"));
|
|
153
|
+
const MAX_CACHE_BYTES = Number(env("MAX_CACHE_GB", "100")) * 1e9;
|
|
154
|
+
const PROGRESS_MS = Number(env("PROGRESS_MS", "250")); // panel refresh cadence
|
|
155
|
+
// Index maintenance at checkpoints: compact (remove garbage), repair (fill
|
|
156
|
+
// gaps), then refresh the canonical-form index (equivalence-class resolution —
|
|
157
|
+
// src/canon.ts). All three are idempotent batch operations (the canon build is
|
|
158
|
+
// additionally incremental via the store's `canon.upto` cursor);
|
|
159
|
+
// INDEX_MAINTENANCE=0 disables.
|
|
160
|
+
const INDEX_MAINTENANCE = env("INDEX_MAINTENANCE", "1") !== "0";
|
|
161
|
+
const DOWNLOAD_TRIES = 5;
|
|
162
|
+
// In-progress downloads are written to a sibling "<dest>.part" and atomically
|
|
163
|
+
// renamed into place only after the bytes are fully flushed to disk. The cache
|
|
164
|
+
// invariant is therefore absolute: a file at its final path is, by definition,
|
|
165
|
+
// complete. Partial transfers (a crash, a kill, a dropped socket) leave only a
|
|
166
|
+
// .part file, which is swept at startup and never fed to the parser.
|
|
167
|
+
const PART_SUFFIX = ".part";
|
|
168
|
+
// A single process-wide abort signal. SIGINT/SIGTERM aborts it, which cancels
|
|
169
|
+
// every in-flight fetch immediately (instead of waiting out a slow socket), so
|
|
170
|
+
// Ctrl+C is responsive even mid-download. The deposit loop also polls it to
|
|
171
|
+
// stop cleanly at the next item boundary, leaving the store consistent.
|
|
172
|
+
const shutdown = new AbortController();
|
|
173
|
+
// The checkpoint recall is a best-effort diagnostic — it must NEVER stall
|
|
174
|
+
// training. We bound it so a slow/large store cannot freeze the deposit loop.
|
|
175
|
+
const INFER_TIMEOUT_MS = Number(env("INFER_TIMEOUT_MS", "15000"));
|
|
176
|
+
// A module-level hook so the low-level fetch retries can surface a rate-limit
|
|
177
|
+
// WAIT into the live progress log (set once main()'s panel exists). Without it a
|
|
178
|
+
// long 429 back-off would look like a silent hang. Throttled so a storm of 429s
|
|
179
|
+
// logs at most one "waiting" notice every few seconds.
|
|
180
|
+
let onThrottleWait = null;
|
|
181
|
+
let lastThrottleLog = 0;
|
|
182
|
+
// Optional ceiling on how much LEARNED CONTENT to train, in megabytes (decimal,
|
|
183
|
+
// like CHECKPOINT_MB). Default Infinity = unbounded. The cap is checked against
|
|
184
|
+
// trainedContentBytes after each deposit, so a run stops at the first item that
|
|
185
|
+
// carries the running total to/past the ceiling (that item is still counted).
|
|
186
|
+
const MAX_MB = Number(env("MAX_MB", "Infinity"));
|
|
187
|
+
if (isNaN(MAX_MB) || MAX_MB < 0) {
|
|
188
|
+
process.stderr.write(`fatal: MAX_MB must be a non-negative number or "Infinity"\n`);
|
|
189
|
+
process.exit(1);
|
|
190
|
+
}
|
|
191
|
+
const MAX_BYTES = MAX_MB * 1_000_000; // Infinity stays Infinity
|
|
192
|
+
// ── CohereLabs/aya_dataset (the second training stage, after SmolSent) ──
|
|
193
|
+
// The Aya Dataset is ~204k HUMAN-annotated prompt→completion pairs across 70+
|
|
194
|
+
// languages, each a clean (inputs → targets) fact in a named language. It ships
|
|
195
|
+
// ONLY as Snappy-compressed Parquet (no JSONL/CSV). We DOWNLOAD the one train
|
|
196
|
+
// Parquet file and read it row-group by row-group with `hyparquet` (a pure-JS,
|
|
197
|
+
// dependency-free Parquet reader) + `hyparquet-compressors` (Snappy) over a
|
|
198
|
+
// web-standard Blob byte source — no whole-file-in-memory load. AYA=0 disables
|
|
199
|
+
// the stage; AYA_URL overrides the Parquet source.
|
|
200
|
+
const AYA = env("AYA", "1") !== "0";
|
|
201
|
+
const AYA_URL = env("AYA_URL", "https://huggingface.co/datasets/CohereLabs/aya_dataset/resolve/main/data/train-00000-of-00001.parquet");
|
|
202
|
+
// The resume id of the Aya stage, kept in the same completed-files set as the
|
|
203
|
+
// other stages, so one store records the whole curriculum.
|
|
204
|
+
const AYA_ID = "aya::dataset";
|
|
205
|
+
// A single Aya field this many chars or longer is skipped: inputs/targets range
|
|
206
|
+
// up to ~3.3M chars, and a multi-MB "pair" is documentation/dump noise, not a
|
|
207
|
+
// cognitive example.
|
|
208
|
+
const MAX_AYA_FIELD_CHARS = Math.max(10_000, Math.floor(Number(env("MAX_AYA_FIELD_KB", "256")) * 1000) || 256_000);
|
|
209
|
+
// ── OpenAssistant/oasst2 (the fourth training stage, after Aya) ──
|
|
210
|
+
// oasst2 is a corpus of human↔assistant conversation TREES. Its richest, most
|
|
211
|
+
// stream-friendly artifact is "<date>_oasst2_ready.trees.jsonl.gz": one JSON
|
|
212
|
+
// conversation tree PER LINE, gzip-compressed (a web standard — Decompression
|
|
213
|
+
// Stream("gzip")). Each tree is {message_tree_id, prompt:{role,text,replies:[…]}}
|
|
214
|
+
// where `replies` nests recursively and a prompt can have several ranked
|
|
215
|
+
// assistant replies (rank 0 = best). We follow the best-ranked, non-deleted
|
|
216
|
+
// reply at each step to get ONE linear, strictly-alternating conversation per
|
|
217
|
+
// tree, then keep only the MULTI-TURN ones (≥ OASST_MIN_TURNS messages, i.e. at
|
|
218
|
+
// least two full user→assistant exchanges) — single Q→A trees are skipped, by
|
|
219
|
+
// design. OASST=0 disables the stage; OASST_URL overrides the source.
|
|
220
|
+
const OASST = env("OASST", "1") !== "0";
|
|
221
|
+
const OASST_URL = env("OASST_URL", "https://huggingface.co/datasets/OpenAssistant/oasst2/resolve/main/2023-11-05_oasst2_ready.trees.jsonl.gz");
|
|
222
|
+
// The resume id of the oasst2 stage, in the same completed-files set as the
|
|
223
|
+
// other stages, so one store records the whole curriculum.
|
|
224
|
+
const OASST_ID = "oasst2::trees";
|
|
225
|
+
// Multi-turn threshold: a conversation must have at least this many turns to be
|
|
226
|
+
// trained (4 = user→assistant→user→assistant, the smallest real multi-turn).
|
|
227
|
+
const OASST_MIN_TURNS = Math.max(2, Math.floor(Number(env("OASST_MIN_TURNS", "4"))) || 4);
|
|
228
|
+
// Skip a tree whose decoded JSON line exceeds this (a pathological record); the
|
|
229
|
+
// real maximum is far smaller, so this only guards against corruption.
|
|
230
|
+
const MAX_OASST_LINE_CHARS = Math.max(100_000, Math.floor(Number(env("MAX_OASST_LINE_MB", "8")) * 1_000_000) || 8_000_000);
|
|
231
|
+
// ── MuskumPillerum/General-Knowledge (the fourth training stage, after oasst2) ──
|
|
232
|
+
// A ~37.6k-row general-knowledge Q&A set: each row is a single {Question, Answer}
|
|
233
|
+
// pair. A row is a pure RELATION (question → answer), so it becomes exactly ONE
|
|
234
|
+
// FACT, identical in shape to the Aya stage. It ships as a single JSON array
|
|
235
|
+
// file (output.json); we DOWNLOAD it and stream the array. GENKNOW=0 disables
|
|
236
|
+
// the stage; GENKNOW_URL overrides the source.
|
|
237
|
+
const GENKNOW = env("GENKNOW", "1") !== "0";
|
|
238
|
+
const GENKNOW_URL = env("GENKNOW_URL", "https://huggingface.co/datasets/MuskumPillerum/General-Knowledge/resolve/main/output.json");
|
|
239
|
+
// The resume id of the General-Knowledge stage, in the same completed-files set
|
|
240
|
+
// as the other stages, so one store records the whole curriculum.
|
|
241
|
+
const GENKNOW_ID = "genknow::qa";
|
|
242
|
+
// A Question/Answer longer than this is skipped (answers run to a few hundred
|
|
243
|
+
// chars; this only guards against a corrupt/runaway field).
|
|
244
|
+
const MAX_GENKNOW_CHARS = Math.max(4_000, Math.floor(Number(env("MAX_GENKNOW_KB", "64")) * 1000) || 64_000);
|
|
245
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
246
|
+
// §2 Terminal + formatting helpers
|
|
247
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
248
|
+
const CSI = "\x1b[";
|
|
249
|
+
const B = `${CSI}1m`, DIM = `${CSI}2m`, R = `${CSI}0m`;
|
|
250
|
+
const GREY = `${CSI}90m`, CYAN = `${CSI}36m`, GRN = `${CSI}32m`;
|
|
251
|
+
const YEL = `${CSI}33m`, RED = `${CSI}31m`;
|
|
252
|
+
const HIDE = `${CSI}?25l`, SHOW = `${CSI}?25h`;
|
|
253
|
+
/** Sleep `ms`, but wake early if the shutdown signal fires — so a long back-off
|
|
254
|
+
* (e.g. a rate-limit wait) never swallows Ctrl+C. Resolves either way. */
|
|
255
|
+
const waitMs = (ms) => new Promise((resolve) => {
|
|
256
|
+
if (shutdown.signal.aborted)
|
|
257
|
+
return resolve();
|
|
258
|
+
// NOTE: the timer is deliberately NOT unref'd — an unref'd timer does not
|
|
259
|
+
// keep the event loop alive, so a pending wait (e.g. the pace between page
|
|
260
|
+
// requests, or a rate-limit back-off) would let Node exit early and the run
|
|
261
|
+
// would "do nothing and close". The listener lets a shutdown wake it early.
|
|
262
|
+
const t = setTimeout(done, ms);
|
|
263
|
+
function done() {
|
|
264
|
+
clearTimeout(t);
|
|
265
|
+
shutdown.signal.removeEventListener("abort", done);
|
|
266
|
+
resolve();
|
|
267
|
+
}
|
|
268
|
+
shutdown.signal.addEventListener("abort", done, { once: true });
|
|
269
|
+
});
|
|
270
|
+
/** Resolve `p`, but reject with a TimeoutError if it takes longer than `ms`.
|
|
271
|
+
* The underlying promise is left to settle on its own (we just stop waiting),
|
|
272
|
+
* so a slow black-box call can never wedge the caller. */
|
|
273
|
+
function withTimeout(p, ms, label = "operation") {
|
|
274
|
+
return new Promise((resolve, reject) => {
|
|
275
|
+
const t = setTimeout(() => {
|
|
276
|
+
const e = new Error(`${label} timed out after ${ms}ms`);
|
|
277
|
+
e.name = "TimeoutError";
|
|
278
|
+
reject(e);
|
|
279
|
+
}, ms);
|
|
280
|
+
if (typeof t.unref === "function")
|
|
281
|
+
t.unref();
|
|
282
|
+
p.then((v) => {
|
|
283
|
+
clearTimeout(t);
|
|
284
|
+
resolve(v);
|
|
285
|
+
}, (e) => {
|
|
286
|
+
clearTimeout(t);
|
|
287
|
+
reject(e);
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
/** Human-readable duration from seconds. */
|
|
292
|
+
function dur(seconds) {
|
|
293
|
+
if (!isFinite(seconds) || seconds < 0)
|
|
294
|
+
return "--";
|
|
295
|
+
const h = Math.floor(seconds / 3600);
|
|
296
|
+
const m = Math.floor((seconds % 3600) / 60);
|
|
297
|
+
const s = Math.floor(seconds % 60);
|
|
298
|
+
if (h > 0)
|
|
299
|
+
return `${h}h ${m}m ${s}s`;
|
|
300
|
+
if (m > 0)
|
|
301
|
+
return `${m}m ${s}s`;
|
|
302
|
+
return `${s}s`;
|
|
303
|
+
}
|
|
304
|
+
/** Human-readable byte size. */
|
|
305
|
+
function bytes(n) {
|
|
306
|
+
if (!isFinite(n) || n < 0)
|
|
307
|
+
return "--";
|
|
308
|
+
if (n < 1024)
|
|
309
|
+
return `${n} B`;
|
|
310
|
+
if (n < 1e6)
|
|
311
|
+
return `${(n / 1024).toFixed(1)} KB`;
|
|
312
|
+
if (n < 1e9)
|
|
313
|
+
return `${(n / 1e6).toFixed(1)} MB`;
|
|
314
|
+
return `${(n / 1e9).toFixed(2)} GB`;
|
|
315
|
+
}
|
|
316
|
+
/** Short count: 1234567 → "1.23M". */
|
|
317
|
+
function num(n) {
|
|
318
|
+
if (n >= 1e9)
|
|
319
|
+
return `${(n / 1e9).toFixed(2)}B`;
|
|
320
|
+
if (n >= 1e6)
|
|
321
|
+
return `${(n / 1e6).toFixed(2)}M`;
|
|
322
|
+
if (n >= 1e3)
|
|
323
|
+
return `${(n / 1e3).toFixed(1)}K`;
|
|
324
|
+
return String(n);
|
|
325
|
+
}
|
|
326
|
+
const int = (n) => Math.round(n).toLocaleString("en-US");
|
|
327
|
+
const clamp01 = (f) => Math.max(0, Math.min(1, f));
|
|
328
|
+
const pct = (f) => `${(clamp01(f) * 100).toFixed(1)}%`;
|
|
329
|
+
/** A progress bar of width `w` filled to fraction `frac`. */
|
|
330
|
+
function bar(w, frac) {
|
|
331
|
+
const filled = Math.round(clamp01(frac) * w);
|
|
332
|
+
return `${GRN}${"█".repeat(filled)}${GREY}${"░".repeat(w - filled)}${R}`;
|
|
333
|
+
}
|
|
334
|
+
/** Collapse whitespace and clip to `max` chars with an ellipsis. */
|
|
335
|
+
function clip(text, max) {
|
|
336
|
+
const t = text.replace(/\s+/g, " ").trim();
|
|
337
|
+
if (max < 1)
|
|
338
|
+
return "";
|
|
339
|
+
return t.length <= max ? t : t.slice(0, max - 1) + "…";
|
|
340
|
+
}
|
|
341
|
+
/** Retry `fn` with exponential backoff.
|
|
342
|
+
*
|
|
343
|
+
* Three error classes:
|
|
344
|
+
* • `.fatal` / AbortError → rethrown immediately (never retried).
|
|
345
|
+
* • `.throttle` (429/503) → the server is rate-limiting/overloaded. We are
|
|
346
|
+
* NOT failing — we WAIT (honouring Retry-After, else capped exponential
|
|
347
|
+
* back-off with jitter) and retry WITHOUT consuming an attempt, so a
|
|
348
|
+
* throttled request holds on until it succeeds rather than being dropped.
|
|
349
|
+
* Only a shutdown breaks this loop.
|
|
350
|
+
* • anything else → a genuine transient error, retried up to `tries`
|
|
351
|
+
* with exponential back-off before giving up.
|
|
352
|
+
*
|
|
353
|
+
* `onFail` is called after each non-throttle failed attempt; `onThrottle` after
|
|
354
|
+
* each throttle wait (for a "waiting…" notice). */
|
|
355
|
+
async function retry(label, fn, tries, onFail, onThrottle) {
|
|
356
|
+
let wait = 1000, last = "", throttleWait = 1000, throttleHits = 0;
|
|
357
|
+
for (let attempt = 1; attempt <= tries;) {
|
|
358
|
+
if (shutdown.signal.aborted) {
|
|
359
|
+
const e = new Error("aborted");
|
|
360
|
+
e.fatal = true;
|
|
361
|
+
throw e;
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
return await fn();
|
|
365
|
+
}
|
|
366
|
+
catch (e) {
|
|
367
|
+
const err = e;
|
|
368
|
+
if (err.name === "AbortError" || err.fatal)
|
|
369
|
+
throw err;
|
|
370
|
+
// Rate-limited / overloaded: wait it out. Does NOT advance `attempt`, so a
|
|
371
|
+
// busy server can never exhaust the retry budget and drop the request.
|
|
372
|
+
if (err.throttle && !shutdown.signal.aborted) {
|
|
373
|
+
throttleHits++;
|
|
374
|
+
// Honour Retry-After when the server sent one; else exponential back-off
|
|
375
|
+
// with jitter, capped, so a fleet of requests does not resynchronise.
|
|
376
|
+
const base = err.retryAfterMs && err.retryAfterMs > 0
|
|
377
|
+
? err.retryAfterMs
|
|
378
|
+
: throttleWait;
|
|
379
|
+
const ms = Math.min(base, 60_000) +
|
|
380
|
+
Math.floor(base * 0.25 * Math.random());
|
|
381
|
+
onThrottle?.(ms);
|
|
382
|
+
await waitMs(ms);
|
|
383
|
+
throttleWait = Math.min(throttleWait * 2, 60_000);
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
last = err.message;
|
|
387
|
+
onFail?.(attempt, err);
|
|
388
|
+
attempt++;
|
|
389
|
+
if (attempt <= tries) {
|
|
390
|
+
await waitMs(wait);
|
|
391
|
+
wait = Math.min(wait * 2, 30_000);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
throw new Error(`${label} failed after ${tries} attempts: ${last}`);
|
|
396
|
+
}
|
|
397
|
+
/** Classify a non-OK HTTP response into an {@link HttpError} for {@link retry}:
|
|
398
|
+
* • 429 / 503 → THROTTLE (rate-limited / overloaded): retried indefinitely,
|
|
399
|
+
* honouring a Retry-After header (seconds or an HTTP-date) when present.
|
|
400
|
+
* • other 5xx → transient: retried up to the caller's attempt budget.
|
|
401
|
+
* • other 4xx → FATAL: a real client error (404, 401, …) — not retried.
|
|
402
|
+
* Never throttles forever silently: the wait is interruptible by shutdown. */
|
|
403
|
+
function httpError(res) {
|
|
404
|
+
const err = new Error(`HTTP ${res.status}`);
|
|
405
|
+
if (res.status === 429 || res.status === 503) {
|
|
406
|
+
err.throttle = true;
|
|
407
|
+
const ra = res.headers.get("retry-after");
|
|
408
|
+
if (ra) {
|
|
409
|
+
const secs = Number(ra);
|
|
410
|
+
if (Number.isFinite(secs))
|
|
411
|
+
err.retryAfterMs = Math.max(0, secs * 1000);
|
|
412
|
+
else {
|
|
413
|
+
const when = Date.parse(ra);
|
|
414
|
+
if (Number.isFinite(when)) {
|
|
415
|
+
err.retryAfterMs = Math.max(0, when - Date.now());
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
else if (res.status < 500) {
|
|
421
|
+
err.fatal = true; // genuine client error — do not retry
|
|
422
|
+
} // other 5xx: neither fatal nor throttle → ordinary bounded retry
|
|
423
|
+
return err;
|
|
424
|
+
}
|
|
425
|
+
/** GET a URL and parse JSON, with the shared retry policy: rate-limits (429/503)
|
|
426
|
+
* WAIT indefinitely (surfaced to the progress log via onThrottleWait, throttled
|
|
427
|
+
* to one notice every few seconds), other 4xx is fatal, other 5xx retried up to
|
|
428
|
+
* DOWNLOAD_TRIES. Used by every datasets-server API stage so all share the same
|
|
429
|
+
* never-drop-on-throttle behaviour. */
|
|
430
|
+
async function getJson(url, label) {
|
|
431
|
+
return retry(label, async () => {
|
|
432
|
+
const res = await fetch(url, { signal: shutdown.signal });
|
|
433
|
+
if (res.ok)
|
|
434
|
+
return res.json();
|
|
435
|
+
throw httpError(res);
|
|
436
|
+
}, DOWNLOAD_TRIES, undefined, (ms) => {
|
|
437
|
+
const now = Date.now();
|
|
438
|
+
if (onThrottleWait && now - lastThrottleLog > 3000) {
|
|
439
|
+
lastThrottleLog = now;
|
|
440
|
+
onThrottleWait(ms, label);
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
445
|
+
// §3 Cache + download helpers (a downloaded file is bounded by MAX_CACHE_GB)
|
|
446
|
+
//
|
|
447
|
+
// SmolSent and Aya are paged from the datasets-server JSON API (no file to
|
|
448
|
+
// download); oasst2 downloads ONE gzipped file. So only the generic download
|
|
449
|
+
// helpers below survive — there is no per-language ZIP discovery or prefetch.
|
|
450
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
451
|
+
/** A cheap HEAD to learn a download's size (for the cache ceiling and a real
|
|
452
|
+
* ETA). Rate-limits wait; other 4xx is fatal; total failure → 0. */
|
|
453
|
+
async function headSize(url) {
|
|
454
|
+
return retry(`HEAD ${url}`, async () => {
|
|
455
|
+
const res = await fetch(url, { method: "HEAD", signal: shutdown.signal });
|
|
456
|
+
if (res.ok)
|
|
457
|
+
return Number(res.headers.get("content-length")) || 0;
|
|
458
|
+
throw httpError(res);
|
|
459
|
+
}, 4);
|
|
460
|
+
}
|
|
461
|
+
function cacheSize() {
|
|
462
|
+
if (!existsSync(CACHE_DIR))
|
|
463
|
+
return 0;
|
|
464
|
+
let total = 0;
|
|
465
|
+
for (const name of readdirSync(CACHE_DIR)) {
|
|
466
|
+
try {
|
|
467
|
+
total += statSync(join(CACHE_DIR, name)).size;
|
|
468
|
+
}
|
|
469
|
+
catch { /* raced with a delete */ }
|
|
470
|
+
}
|
|
471
|
+
return total;
|
|
472
|
+
}
|
|
473
|
+
/** Block until there is room for a file of `fileBytes` under the ceiling.
|
|
474
|
+
* A single file larger than the whole ceiling can never "fit", so we let it
|
|
475
|
+
* through (it is deleted right after processing) rather than wait forever. */
|
|
476
|
+
async function ensureCacheRoom(fileBytes, warn) {
|
|
477
|
+
mkdirSync(CACHE_DIR, { recursive: true });
|
|
478
|
+
if (fileBytes >= MAX_CACHE_BYTES)
|
|
479
|
+
return;
|
|
480
|
+
let warned = false;
|
|
481
|
+
// Stop waiting the moment a shutdown is requested — the abort signal unblocks
|
|
482
|
+
// a long cache-full wait so Ctrl+C is never swallowed by the ceiling.
|
|
483
|
+
while (!shutdown.signal.aborted && cacheSize() + fileBytes > MAX_CACHE_BYTES) {
|
|
484
|
+
if (!warned) {
|
|
485
|
+
warn?.(`${YEL}⚠${R} cache at ${(MAX_CACHE_BYTES / 1e9).toFixed(0)} GB ceiling — waiting for room…`);
|
|
486
|
+
warned = true;
|
|
487
|
+
}
|
|
488
|
+
await waitMs(5_000);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
492
|
+
// §5 Download (streamed to disk, with retry + cleanup on failure)
|
|
493
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
494
|
+
async function downloadFile(url, destPath, tries = DOWNLOAD_TRIES, onFail, onProgress) {
|
|
495
|
+
const partPath = destPath + PART_SUFFIX;
|
|
496
|
+
await retry(`download ${basename(destPath)}`, async () => {
|
|
497
|
+
// Abort promptly on shutdown rather than waiting out a slow socket.
|
|
498
|
+
if (shutdown.signal.aborted) {
|
|
499
|
+
const e = new Error("aborted");
|
|
500
|
+
e.fatal = true;
|
|
501
|
+
throw e;
|
|
502
|
+
}
|
|
503
|
+
const res = await fetch(url, { signal: shutdown.signal });
|
|
504
|
+
if (!res.ok)
|
|
505
|
+
throw httpError(res);
|
|
506
|
+
if (!res.body)
|
|
507
|
+
throw new Error("empty response body");
|
|
508
|
+
const total = Number(res.headers.get("content-length")) || 0;
|
|
509
|
+
let done = 0;
|
|
510
|
+
// Stream straight to a ".part" sibling using pure WHATWG streams. A
|
|
511
|
+
// TransformStream meters progress; pipeTo into a WritableStream gives REAL
|
|
512
|
+
// backpressure natively — the sink's write() returns a promise the
|
|
513
|
+
// readable side awaits, so a fast server can never outrun the disk (no
|
|
514
|
+
// whole-file heap buffering). The sink wraps a single raw fs descriptor
|
|
515
|
+
// (the one capability the web platform lacks); writing to disk is the only
|
|
516
|
+
// Node operation in the whole pipeline. The final, valid file only ever
|
|
517
|
+
// appears via the atomic rename below, so a crash mid-transfer can never
|
|
518
|
+
// leave a truncated file at the real path.
|
|
519
|
+
const meter = new TransformStream({
|
|
520
|
+
transform(chunk, controller) {
|
|
521
|
+
done += chunk.length;
|
|
522
|
+
onProgress?.(done, total);
|
|
523
|
+
controller.enqueue(chunk);
|
|
524
|
+
},
|
|
525
|
+
});
|
|
526
|
+
const fd = openSync(partPath, "w");
|
|
527
|
+
let closed = false;
|
|
528
|
+
const closeFd = () => {
|
|
529
|
+
if (closed)
|
|
530
|
+
return;
|
|
531
|
+
closed = true;
|
|
532
|
+
try {
|
|
533
|
+
closeSync(fd);
|
|
534
|
+
}
|
|
535
|
+
catch { /* already closed */ }
|
|
536
|
+
};
|
|
537
|
+
const sink = new WritableStream({
|
|
538
|
+
write(chunk) {
|
|
539
|
+
// writeSync drains the whole chunk before returning, so the readable
|
|
540
|
+
// side is paused for exactly as long as the disk needs — backpressure.
|
|
541
|
+
let off = 0;
|
|
542
|
+
while (off < chunk.length) {
|
|
543
|
+
off += writeSync(fd, chunk, off, chunk.length - off);
|
|
544
|
+
}
|
|
545
|
+
},
|
|
546
|
+
close() {
|
|
547
|
+
fsyncSync(fd); // durable bytes before the rename promotes them
|
|
548
|
+
closeFd();
|
|
549
|
+
},
|
|
550
|
+
abort() {
|
|
551
|
+
closeFd();
|
|
552
|
+
},
|
|
553
|
+
});
|
|
554
|
+
try {
|
|
555
|
+
await res.body.pipeThrough(meter).pipeTo(sink, {
|
|
556
|
+
signal: shutdown.signal,
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
catch (e) {
|
|
560
|
+
// pipeTo's abort() ran the sink's abort() (closing the descriptor); if
|
|
561
|
+
// it didn't (a non-abort throw), make sure the descriptor is not leaked.
|
|
562
|
+
closeFd();
|
|
563
|
+
try {
|
|
564
|
+
unlinkSync(partPath);
|
|
565
|
+
}
|
|
566
|
+
catch { /* best effort */ }
|
|
567
|
+
throw e;
|
|
568
|
+
}
|
|
569
|
+
// Optional integrity guard: when the server advertised a size, a complete
|
|
570
|
+
// file must match it. A short read (silent truncation) is retried rather
|
|
571
|
+
// than promoted, so the parser never sees a partial ZIP.
|
|
572
|
+
try {
|
|
573
|
+
const got = statSync(partPath).size;
|
|
574
|
+
if (total > 0 && got !== total) {
|
|
575
|
+
try {
|
|
576
|
+
unlinkSync(partPath);
|
|
577
|
+
}
|
|
578
|
+
catch { /* best effort */ }
|
|
579
|
+
throw new Error(`size mismatch: got ${got}, expected ${total}`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
catch (e) {
|
|
583
|
+
if (e instanceof Error && e.message.startsWith("size mismatch")) {
|
|
584
|
+
throw e;
|
|
585
|
+
}
|
|
586
|
+
// statSync failure is non-fatal here; the rename below will surface it.
|
|
587
|
+
}
|
|
588
|
+
// Atomic publish: rename is atomic within a filesystem, so the final path
|
|
589
|
+
// flips from "absent" to "complete" in one step — never an in-between.
|
|
590
|
+
renameSync(partPath, destPath);
|
|
591
|
+
}, tries, onFail);
|
|
592
|
+
}
|
|
593
|
+
const isEpisode = (it) => typeof it !== "string";
|
|
594
|
+
/** Build the accumulated-context episodes of a turn sequence: each successive
|
|
595
|
+
* turn is the continuation of ALL the turns before it joined together. This is
|
|
596
|
+
* the same cumulative-context shape a multi-turn conversation deposits, so the
|
|
597
|
+
* store learns to continue a growing context. */
|
|
598
|
+
function accumulate(turns) {
|
|
599
|
+
const out = [];
|
|
600
|
+
for (let i = 1; i < turns.length; i++) {
|
|
601
|
+
out.push({ context: turns.slice(0, i).join("\n"), continuation: turns[i] });
|
|
602
|
+
}
|
|
603
|
+
return out;
|
|
604
|
+
}
|
|
605
|
+
/** Dedup + trim a concept's items: drop empty/degenerate pairs and exact
|
|
606
|
+
* repeats so a concept never deposits the same form twice. */
|
|
607
|
+
export function refineItems(items) {
|
|
608
|
+
const out = [];
|
|
609
|
+
const seen = new Set();
|
|
610
|
+
for (const it of items) {
|
|
611
|
+
if (!isEpisode(it)) {
|
|
612
|
+
const exp = it.trim();
|
|
613
|
+
const key = "E:" + exp;
|
|
614
|
+
if (exp && !seen.has(key)) {
|
|
615
|
+
seen.add(key);
|
|
616
|
+
out.push(exp);
|
|
617
|
+
}
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
const ctx = it.context.trim();
|
|
621
|
+
const cont = it.continuation.trim();
|
|
622
|
+
if (!ctx || !cont || ctx === cont)
|
|
623
|
+
continue;
|
|
624
|
+
const key = "P:" + ctx + "\u0000" + cont;
|
|
625
|
+
if (seen.has(key))
|
|
626
|
+
continue;
|
|
627
|
+
seen.add(key);
|
|
628
|
+
out.push({ context: ctx, continuation: cont });
|
|
629
|
+
}
|
|
630
|
+
return out;
|
|
631
|
+
}
|
|
632
|
+
/** Normalize a raw datasets-server row into a SmolSentRow, or null when it lacks
|
|
633
|
+
* both sides or a side is implausibly large (a dump, not a sentence). */
|
|
634
|
+
export function toSmolSentRow(row) {
|
|
635
|
+
if (!row || typeof row !== "object")
|
|
636
|
+
return null;
|
|
637
|
+
const r = row;
|
|
638
|
+
const src = typeof r.src === "string" ? r.src.trim() : "";
|
|
639
|
+
// `trg` is a single string in smolsent; tolerate a list form defensively.
|
|
640
|
+
const trgRaw = Array.isArray(r.trgs) ? r.trgs[0] : r.trg;
|
|
641
|
+
const trg = typeof trgRaw === "string" ? trgRaw.trim() : "";
|
|
642
|
+
if (!src || !trg)
|
|
643
|
+
return null;
|
|
644
|
+
if (src.length > MAX_SMOLSENT_CHARS || trg.length > MAX_SMOLSENT_CHARS)
|
|
645
|
+
return null;
|
|
646
|
+
const sl = typeof r.sl === "string" ? r.sl.trim() : "";
|
|
647
|
+
const tl = typeof r.tl === "string" ? r.tl.trim() : "";
|
|
648
|
+
return { src, trg, sl, tl };
|
|
649
|
+
}
|
|
650
|
+
/** Translate ONE SmolSent pair into SEMA facts: the two sentences are one
|
|
651
|
+
* meaning in two languages, so bind them BOTH ways. refineItems drops the
|
|
652
|
+
* degenerate case where src === trg. */
|
|
653
|
+
export function smolSentRowToItems(row) {
|
|
654
|
+
const { src, trg } = row;
|
|
655
|
+
return refineItems([
|
|
656
|
+
{ context: src, continuation: trg },
|
|
657
|
+
{ context: trg, continuation: src },
|
|
658
|
+
]);
|
|
659
|
+
}
|
|
660
|
+
/** Normalize a raw datasets-server row object into an AyaRow, or null when it
|
|
661
|
+
* lacks a usable prompt/answer or a field is implausibly large (a dump, not a
|
|
662
|
+
* cognitive example). Trims surrounding whitespace; keeps inner text verbatim
|
|
663
|
+
* (human prose, possibly multi-paragraph). */
|
|
664
|
+
export function toAyaRow(row) {
|
|
665
|
+
if (!row || typeof row !== "object")
|
|
666
|
+
return null;
|
|
667
|
+
const r = row;
|
|
668
|
+
const inputs = typeof r.inputs === "string" ? r.inputs.trim() : "";
|
|
669
|
+
const targets = typeof r.targets === "string" ? r.targets.trim() : "";
|
|
670
|
+
if (!inputs || !targets)
|
|
671
|
+
return null;
|
|
672
|
+
if (inputs.length > MAX_AYA_FIELD_CHARS || targets.length > MAX_AYA_FIELD_CHARS)
|
|
673
|
+
return null;
|
|
674
|
+
const language = typeof r.language === "string" ? r.language.trim() : "";
|
|
675
|
+
return { inputs, targets, language };
|
|
676
|
+
}
|
|
677
|
+
/** Translate ONE Aya row into SEMA training items. A row is a single human
|
|
678
|
+
* (question → answer) exchange — exactly one FACT, the (inputs → targets) edge.
|
|
679
|
+
* No standalone-answer experience and no one-exchange "cumulative" walk: a lone
|
|
680
|
+
* Q→A is not multi-turn, and both would only replicate the same edge. */
|
|
681
|
+
export function ayaRowToItems(row) {
|
|
682
|
+
const { inputs, targets } = row;
|
|
683
|
+
return refineItems([{ context: inputs, continuation: targets }]);
|
|
684
|
+
}
|
|
685
|
+
/** Collapse a conversation tree to ONE linear path: at each node, descend into
|
|
686
|
+
* its best-ranked, non-deleted reply (rank 0 preferred; unranked sorts last).
|
|
687
|
+
* Returns the ordered turns (already strictly alternating in this corpus). */
|
|
688
|
+
export function bestOasstPath(root) {
|
|
689
|
+
const turns = [];
|
|
690
|
+
let node = root;
|
|
691
|
+
while (node) {
|
|
692
|
+
const text = typeof node.text === "string" ? node.text.trim() : "";
|
|
693
|
+
if (text)
|
|
694
|
+
turns.push({ role: String(node.role ?? "?"), text });
|
|
695
|
+
const live = (node.replies ?? []).filter((r) => r && !r.deleted && typeof r.text === "string" && r.text.trim() !== "");
|
|
696
|
+
if (live.length === 0)
|
|
697
|
+
break;
|
|
698
|
+
live.sort((a, b) => (a.rank ?? Number.MAX_SAFE_INTEGER) - (b.rank ?? Number.MAX_SAFE_INTEGER));
|
|
699
|
+
node = live[0];
|
|
700
|
+
}
|
|
701
|
+
return turns;
|
|
702
|
+
}
|
|
703
|
+
/** Translate ONE multi-turn oasst2 conversation into SEMA training items.
|
|
704
|
+
*
|
|
705
|
+
* This is the ONE stage where cumulative continuous context is truly necessary:
|
|
706
|
+
* the data is a real multi-turn dialogue, and what must be learned is how each
|
|
707
|
+
* turn follows from the WHOLE conversation so far — not from the previous turn
|
|
708
|
+
* alone. The conversation is emitted ONLY as the accumulated walk; standalone
|
|
709
|
+
* turn experiences and local adjacent-pair facts are NOT emitted (they are
|
|
710
|
+
* subsumed by it and would merely replicate the content).
|
|
711
|
+
*
|
|
712
|
+
* The walk is byte-for-byte the pattern proven in test/13-conversation.test.mjs
|
|
713
|
+
* ("teachConversation"): each turn is the continuation of all prior turns joined
|
|
714
|
+
* by "\n", with BARE turn text — NO "User:/Assistant:" labels. Roles already
|
|
715
|
+
* alternate by position in an oasst2 best-path (the root is a prompter), so a
|
|
716
|
+
* label adds nothing the position does not, while a clean continuation matches
|
|
717
|
+
* the test's recall (predictNext queries bare prior turns) and lets a turn share
|
|
718
|
+
* its gist with the same text elsewhere (e.g. an Aya question stored bare).
|
|
719
|
+
*
|
|
720
|
+
* Returns [] for a conversation below the multi-turn threshold, so callers can
|
|
721
|
+
* simply skip empties. */
|
|
722
|
+
export function oasstConversationToItems(turns) {
|
|
723
|
+
if (turns.length < OASST_MIN_TURNS)
|
|
724
|
+
return []; // not multi-turn — skip
|
|
725
|
+
return refineItems(accumulate(turns.map((t) => t.text)));
|
|
726
|
+
}
|
|
727
|
+
/** Turn a source value into clean prose: decode the literal "\n"/"\t"/"\r"
|
|
728
|
+
* two-character escapes the source JSON left in the text, collapse the runs of
|
|
729
|
+
* whitespace that creates, and trim. */
|
|
730
|
+
function unescapePlain(s) {
|
|
731
|
+
return s
|
|
732
|
+
.replace(/\\r\\n|\\n|\\r/g, "\n")
|
|
733
|
+
.replace(/\\t/g, " ")
|
|
734
|
+
.replace(/[ \t]+/g, " ")
|
|
735
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
736
|
+
.trim();
|
|
737
|
+
}
|
|
738
|
+
/** Normalize a raw datasets-server row into a GenKnowRow, or null when it lacks
|
|
739
|
+
* a usable question/answer or a side is implausibly large (corruption). */
|
|
740
|
+
export function toGenKnowRow(row) {
|
|
741
|
+
if (!row || typeof row !== "object")
|
|
742
|
+
return null;
|
|
743
|
+
const r = row;
|
|
744
|
+
const question = typeof r.Question === "string"
|
|
745
|
+
? unescapePlain(r.Question)
|
|
746
|
+
: "";
|
|
747
|
+
const answer = typeof r.Answer === "string" ? unescapePlain(r.Answer) : "";
|
|
748
|
+
if (!question || !answer)
|
|
749
|
+
return null;
|
|
750
|
+
if (question.length > MAX_GENKNOW_CHARS || answer.length > MAX_GENKNOW_CHARS)
|
|
751
|
+
return null;
|
|
752
|
+
return { question, answer };
|
|
753
|
+
}
|
|
754
|
+
/** Translate ONE General-Knowledge row into SEMA items: exactly one
|
|
755
|
+
* (question → answer) FACT. refineItems drops a degenerate question === answer. */
|
|
756
|
+
export function genKnowRowToItems(row) {
|
|
757
|
+
return refineItems([{ context: row.question, continuation: row.answer }]);
|
|
758
|
+
}
|
|
759
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
760
|
+
// §7 Ingestion
|
|
761
|
+
//
|
|
762
|
+
// Each item is deposited directly: an experience via ingest(text), an episode
|
|
763
|
+
// via ingest(context, continuation). After each, the per-example callback
|
|
764
|
+
// receives the item's UTF-8 content size — the quantity the scaling suite
|
|
765
|
+
// (14-scaling.test.mjs) reports as a constant KB/s — then gates the global
|
|
766
|
+
// example count and checkpointing (returns false to stop). `sample` feeds the
|
|
767
|
+
// reservoir used for the periodic recall box.
|
|
768
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
769
|
+
const ENC = new TextEncoder();
|
|
770
|
+
/** Content size of a training item in UTF-8 bytes — the same quantity the
|
|
771
|
+
* scaling suite (14-scaling.test.mjs) measures as KB/s: for an episode the
|
|
772
|
+
* context plus the continuation, for a bare experience its own text. */
|
|
773
|
+
const itemBytes = (it) => isEpisode(it)
|
|
774
|
+
? ENC.encode(it.context).length + ENC.encode(it.continuation).length
|
|
775
|
+
: ENC.encode(it).length;
|
|
776
|
+
async function ingestItems(ci, items, onItem, sample) {
|
|
777
|
+
for (const it of items) {
|
|
778
|
+
if (isEpisode(it))
|
|
779
|
+
await ci.ingest(it.context, it.continuation);
|
|
780
|
+
else
|
|
781
|
+
await ci.ingest(it);
|
|
782
|
+
sample?.(it);
|
|
783
|
+
if (!(await onItem(itemBytes(it))))
|
|
784
|
+
return false; // stop requested
|
|
785
|
+
}
|
|
786
|
+
return true;
|
|
787
|
+
}
|
|
788
|
+
// ── §7a′ oasst2 — stream the gzipped JSONL of trees and deposit multi-turn ──
|
|
789
|
+
//
|
|
790
|
+
// The file is gzipped JSONL: one conversation tree per line. We inflate with the
|
|
791
|
+
// web-standard DecompressionStream("gzip"), split on newlines without buffering
|
|
792
|
+
// the whole file or an unbounded line, parse each tree, collapse it to its best
|
|
793
|
+
// linear path, and deposit only the multi-turn ones. Robust by construction: a
|
|
794
|
+
// line that fails to parse (or is oversize) is counted skipped and the stream
|
|
795
|
+
// continues; a cap/signal stops cleanly at a conversation boundary.
|
|
796
|
+
async function processOasst(filePath, ci, onExample, sample) {
|
|
797
|
+
const blob = await openAsBlob(filePath);
|
|
798
|
+
const reader = blob.stream()
|
|
799
|
+
.pipeThrough(new DecompressionStream("gzip"))
|
|
800
|
+
.pipeThrough(new TextDecoderStream())
|
|
801
|
+
.getReader();
|
|
802
|
+
let examples = 0;
|
|
803
|
+
let skipped = 0; // malformed/oversize lines
|
|
804
|
+
let multi = 0; // multi-turn conversations deposited
|
|
805
|
+
let leftover = "";
|
|
806
|
+
let droppingLine = false;
|
|
807
|
+
const processLine = async (line) => {
|
|
808
|
+
if (!line.trim())
|
|
809
|
+
return true;
|
|
810
|
+
let tree;
|
|
811
|
+
try {
|
|
812
|
+
tree = JSON.parse(line);
|
|
813
|
+
}
|
|
814
|
+
catch {
|
|
815
|
+
skipped++;
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
if (!tree.prompt)
|
|
819
|
+
return true;
|
|
820
|
+
const turns = bestOasstPath(tree.prompt);
|
|
821
|
+
const items = oasstConversationToItems(turns); // [] when not multi-turn
|
|
822
|
+
if (items.length === 0)
|
|
823
|
+
return true; // single-turn / empty — skipped
|
|
824
|
+
multi++;
|
|
825
|
+
return ingestItems(ci, items, async (contentBytes) => {
|
|
826
|
+
examples++;
|
|
827
|
+
return onExample(contentBytes);
|
|
828
|
+
}, sample);
|
|
829
|
+
};
|
|
830
|
+
try {
|
|
831
|
+
while (true) {
|
|
832
|
+
const { done, value } = await reader.read();
|
|
833
|
+
if (done)
|
|
834
|
+
break;
|
|
835
|
+
let chunk = value;
|
|
836
|
+
for (;;) {
|
|
837
|
+
const nl = chunk.indexOf("\n");
|
|
838
|
+
if (nl < 0) {
|
|
839
|
+
if (!droppingLine) {
|
|
840
|
+
if (leftover.length + chunk.length > MAX_OASST_LINE_CHARS) {
|
|
841
|
+
leftover = "";
|
|
842
|
+
droppingLine = true;
|
|
843
|
+
skipped++;
|
|
844
|
+
}
|
|
845
|
+
else
|
|
846
|
+
leftover += chunk;
|
|
847
|
+
}
|
|
848
|
+
break;
|
|
849
|
+
}
|
|
850
|
+
const part = chunk.slice(0, nl);
|
|
851
|
+
chunk = chunk.slice(nl + 1);
|
|
852
|
+
if (droppingLine) {
|
|
853
|
+
droppingLine = false;
|
|
854
|
+
leftover = "";
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
if (leftover.length + part.length > MAX_OASST_LINE_CHARS) {
|
|
858
|
+
leftover = "";
|
|
859
|
+
skipped++;
|
|
860
|
+
continue;
|
|
861
|
+
}
|
|
862
|
+
const line = leftover + part;
|
|
863
|
+
leftover = "";
|
|
864
|
+
if (!(await processLine(line))) {
|
|
865
|
+
return { examples, stopped: true, skipped, multi };
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
if (!droppingLine && leftover.trim()) {
|
|
870
|
+
if (!(await processLine(leftover))) {
|
|
871
|
+
return { examples, stopped: true, skipped, multi };
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return { examples, stopped: false, skipped, multi };
|
|
875
|
+
}
|
|
876
|
+
finally {
|
|
877
|
+
try {
|
|
878
|
+
reader.releaseLock();
|
|
879
|
+
}
|
|
880
|
+
catch { /* best effort */ }
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
/** Discover the SmolSent per-pair JSONL files from the HF repo tree, restricted
|
|
884
|
+
* to SMOLSENT_PAIRS (basenames without .jsonl) when set. Each entry is the
|
|
885
|
+
* repo-relative path, e.g. "smolsent/ha_en.jsonl". */
|
|
886
|
+
async function listSmolSentFiles() {
|
|
887
|
+
// The dataset id ("owner/name") is a PATH here, so its "/" must not be
|
|
888
|
+
// percent-encoded. `recursive=true` returns every file under smolsent/.
|
|
889
|
+
const url = `https://huggingface.co/api/datasets/${SMOLSENT_DATASET}` +
|
|
890
|
+
`/tree/main/smolsent?recursive=true`;
|
|
891
|
+
const body = await getJson(url, `GET smol tree`);
|
|
892
|
+
const paths = Array.isArray(body)
|
|
893
|
+
? body
|
|
894
|
+
.filter((e) => e?.type === "file" && /\.jsonl$/i.test(e?.path))
|
|
895
|
+
.map((e) => String(e.path))
|
|
896
|
+
: [];
|
|
897
|
+
paths.sort();
|
|
898
|
+
if (!SMOLSENT_PAIRS.length)
|
|
899
|
+
return paths;
|
|
900
|
+
const want = new Set(SMOLSENT_PAIRS.map((p) => p.replace(/\.jsonl$/i, "")));
|
|
901
|
+
return paths.filter((p) => want.has(basename(p).replace(/\.jsonl$/i, "")));
|
|
902
|
+
}
|
|
903
|
+
/** Stream a plain-JSONL file from disk, deposit each parsed row via `toItems`.
|
|
904
|
+
* Lines are split without buffering the whole file; an oversize/malformed line
|
|
905
|
+
* is counted skipped and the stream continues. Shared by SmolSent (and any
|
|
906
|
+
* future JSONL source). */
|
|
907
|
+
async function processJsonl(filePath, toItems, ci, onExample, sample, maxLineChars) {
|
|
908
|
+
const blob = await openAsBlob(filePath);
|
|
909
|
+
const reader = blob.stream().pipeThrough(new TextDecoderStream()).getReader();
|
|
910
|
+
let examples = 0, skipped = 0, leftover = "", dropping = false;
|
|
911
|
+
const processLine = async (line) => {
|
|
912
|
+
if (!line.trim())
|
|
913
|
+
return true;
|
|
914
|
+
let row;
|
|
915
|
+
try {
|
|
916
|
+
row = JSON.parse(line);
|
|
917
|
+
}
|
|
918
|
+
catch {
|
|
919
|
+
skipped++;
|
|
920
|
+
return true;
|
|
921
|
+
}
|
|
922
|
+
const items = toItems(row);
|
|
923
|
+
if (!items || items.length === 0) {
|
|
924
|
+
skipped++;
|
|
925
|
+
return true;
|
|
926
|
+
}
|
|
927
|
+
return ingestItems(ci, items, async (contentBytes) => {
|
|
928
|
+
examples++;
|
|
929
|
+
return onExample(contentBytes);
|
|
930
|
+
}, sample);
|
|
931
|
+
};
|
|
932
|
+
try {
|
|
933
|
+
while (true) {
|
|
934
|
+
const { done, value } = await reader.read();
|
|
935
|
+
if (done)
|
|
936
|
+
break;
|
|
937
|
+
let chunk = value;
|
|
938
|
+
for (;;) {
|
|
939
|
+
const nl = chunk.indexOf("\n");
|
|
940
|
+
if (nl < 0) {
|
|
941
|
+
if (!dropping) {
|
|
942
|
+
if (leftover.length + chunk.length > maxLineChars) {
|
|
943
|
+
leftover = "";
|
|
944
|
+
dropping = true;
|
|
945
|
+
skipped++;
|
|
946
|
+
}
|
|
947
|
+
else
|
|
948
|
+
leftover += chunk;
|
|
949
|
+
}
|
|
950
|
+
break;
|
|
951
|
+
}
|
|
952
|
+
const part = chunk.slice(0, nl);
|
|
953
|
+
chunk = chunk.slice(nl + 1);
|
|
954
|
+
if (dropping) {
|
|
955
|
+
dropping = false;
|
|
956
|
+
leftover = "";
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
if (leftover.length + part.length > maxLineChars) {
|
|
960
|
+
leftover = "";
|
|
961
|
+
skipped++;
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
const line = leftover + part;
|
|
965
|
+
leftover = "";
|
|
966
|
+
if (!(await processLine(line))) {
|
|
967
|
+
return { examples, stopped: true, skipped };
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
if (!dropping && leftover.trim()) {
|
|
972
|
+
if (!(await processLine(leftover))) {
|
|
973
|
+
return { examples, stopped: true, skipped };
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return { examples, stopped: false, skipped };
|
|
977
|
+
}
|
|
978
|
+
finally {
|
|
979
|
+
try {
|
|
980
|
+
reader.releaseLock();
|
|
981
|
+
}
|
|
982
|
+
catch { /* best effort */ }
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
/** Read a downloaded Parquet file row-group by row-group with hyparquet (+Snappy
|
|
986
|
+
* from hyparquet-compressors) over a web-standard Blob byte source, depositing
|
|
987
|
+
* each row via `toItems`. Only one row-group is materialised at a time, so a
|
|
988
|
+
* multi-hundred-MB file never loads whole into memory. */
|
|
989
|
+
async function processParquet(filePath, toItems, ci, onExample, sample) {
|
|
990
|
+
const blob = await openAsBlob(filePath);
|
|
991
|
+
const file = {
|
|
992
|
+
byteLength: blob.size,
|
|
993
|
+
slice: async (start, end) => await blob.slice(start, end ?? blob.size).arrayBuffer(),
|
|
994
|
+
};
|
|
995
|
+
const meta = await parquetMetadataAsync(file);
|
|
996
|
+
let examples = 0, skipped = 0;
|
|
997
|
+
let rowStart = 0;
|
|
998
|
+
for (const rg of meta.row_groups) {
|
|
999
|
+
if (shutdown.signal.aborted)
|
|
1000
|
+
return { examples, stopped: true, skipped };
|
|
1001
|
+
const rgRows = Number(rg.num_rows);
|
|
1002
|
+
const rowEnd = rowStart + rgRows;
|
|
1003
|
+
// Materialise exactly one row-group, then deposit its rows.
|
|
1004
|
+
const rows = await parquetReadObjects({
|
|
1005
|
+
file,
|
|
1006
|
+
compressors,
|
|
1007
|
+
rowStart,
|
|
1008
|
+
rowEnd,
|
|
1009
|
+
});
|
|
1010
|
+
rowStart = rowEnd;
|
|
1011
|
+
for (const row of rows) {
|
|
1012
|
+
const items = toItems(row);
|
|
1013
|
+
if (!items || items.length === 0) {
|
|
1014
|
+
skipped++;
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
const ok = await ingestItems(ci, items, async (contentBytes) => {
|
|
1018
|
+
examples++;
|
|
1019
|
+
return onExample(contentBytes);
|
|
1020
|
+
}, sample);
|
|
1021
|
+
if (!ok)
|
|
1022
|
+
return { examples, stopped: true, skipped };
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
return { examples, stopped: false, skipped };
|
|
1026
|
+
}
|
|
1027
|
+
/** Read a downloaded JSON-array file (General-Knowledge output.json) and deposit
|
|
1028
|
+
* each element via `toItems`. The array is small enough (~16 MB) to parse whole;
|
|
1029
|
+
* a huge file would be rejected by the cache ceiling long before this. */
|
|
1030
|
+
async function processJsonArray(filePath, toItems, ci, onExample, sample) {
|
|
1031
|
+
const blob = await openAsBlob(filePath);
|
|
1032
|
+
let arr;
|
|
1033
|
+
try {
|
|
1034
|
+
arr = JSON.parse(await blob.text());
|
|
1035
|
+
}
|
|
1036
|
+
catch (e) {
|
|
1037
|
+
throw new Error(`invalid JSON: ${e.message}`);
|
|
1038
|
+
}
|
|
1039
|
+
const rows = Array.isArray(arr) ? arr : [];
|
|
1040
|
+
let examples = 0, skipped = 0;
|
|
1041
|
+
for (const row of rows) {
|
|
1042
|
+
if (shutdown.signal.aborted)
|
|
1043
|
+
return { examples, stopped: true, skipped };
|
|
1044
|
+
const items = toItems(row);
|
|
1045
|
+
if (!items || items.length === 0) {
|
|
1046
|
+
skipped++;
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
const ok = await ingestItems(ci, items, async (contentBytes) => {
|
|
1050
|
+
examples++;
|
|
1051
|
+
return onExample(contentBytes);
|
|
1052
|
+
}, sample);
|
|
1053
|
+
if (!ok)
|
|
1054
|
+
return { examples, stopped: true, skipped };
|
|
1055
|
+
}
|
|
1056
|
+
return { examples, stopped: false, skipped };
|
|
1057
|
+
}
|
|
1058
|
+
/** A prompt/expected pair to display for an item. */
|
|
1059
|
+
function promptOf(it) {
|
|
1060
|
+
return isEpisode(it)
|
|
1061
|
+
? { prompt: it.context, expected: it.continuation, kind: "episode" }
|
|
1062
|
+
: { prompt: it.slice(0, 200), expected: null, kind: "experience" };
|
|
1063
|
+
}
|
|
1064
|
+
/** A coarse, honest similarity between an expected continuation and SEMA's
|
|
1065
|
+
* recall. Both are normalized (lowercased, whitespace-collapsed) and compared
|
|
1066
|
+
* by the longest shared leading run plus token overlap, so the verdict is a
|
|
1067
|
+
* heuristic signal of recall quality rather than a brittle fixed-prefix test. */
|
|
1068
|
+
function recallSimilarity(expected, response) {
|
|
1069
|
+
const norm = (s) => s.toLowerCase().replace(/\s+/g, " ").trim();
|
|
1070
|
+
const a = norm(expected), b = norm(response);
|
|
1071
|
+
if (!a || !b)
|
|
1072
|
+
return 0;
|
|
1073
|
+
let lead = 0;
|
|
1074
|
+
const lim = Math.min(a.length, b.length);
|
|
1075
|
+
while (lead < lim && a[lead] === b[lead])
|
|
1076
|
+
lead++;
|
|
1077
|
+
const leadFrac = lead / Math.max(1, Math.min(a.length, b.length));
|
|
1078
|
+
const ta = new Set(a.split(" ")), tb = new Set(b.split(" "));
|
|
1079
|
+
let inter = 0;
|
|
1080
|
+
for (const w of ta)
|
|
1081
|
+
if (tb.has(w))
|
|
1082
|
+
inter++;
|
|
1083
|
+
const jac = inter / Math.max(1, ta.size + tb.size - inter);
|
|
1084
|
+
return Math.max(leadFrac, jac);
|
|
1085
|
+
}
|
|
1086
|
+
/** A framed recall sample. Pinned in the panel on a TTY (so the most recent
|
|
1087
|
+
* example is always on screen) and logged once per checkpoint when piped. */
|
|
1088
|
+
function renderInferenceBox(prompt, expected, response, kind, checkpointN) {
|
|
1089
|
+
const W = 68;
|
|
1090
|
+
const hr = `${DIM}${"─".repeat(W)}${R}`;
|
|
1091
|
+
const title = kind === "episode"
|
|
1092
|
+
? "latest recall"
|
|
1093
|
+
: "latest recall (experience)";
|
|
1094
|
+
const head = `${title} · checkpoint #${checkpointN} `;
|
|
1095
|
+
const shown = response.trim() ? response : "(empty)";
|
|
1096
|
+
const lines = [
|
|
1097
|
+
`${B}╭─ ${head}${"─".repeat(Math.max(0, W - 2 - head.length))}╮${R}`,
|
|
1098
|
+
`${B}│${R} ${hr}`,
|
|
1099
|
+
`${B}│${R} ${CYAN}${B}Context:${R} ${clip(prompt, W - 13)}`,
|
|
1100
|
+
];
|
|
1101
|
+
if (expected) {
|
|
1102
|
+
lines.push(`${B}│${R} ${YEL}${B}Expected:${R} ${clip(expected, W - 13)}`);
|
|
1103
|
+
}
|
|
1104
|
+
lines.push(`${B}│${R} ${GRN}${B}SEMA:${R} ${clip(shown, W - 13)}`);
|
|
1105
|
+
lines.push(`${B}│${R} ${hr}`);
|
|
1106
|
+
let verdict;
|
|
1107
|
+
if (expected) {
|
|
1108
|
+
const sim = recallSimilarity(expected, response);
|
|
1109
|
+
const pctStr = `${Math.round(sim * 100)}%`;
|
|
1110
|
+
verdict = sim >= 0.6
|
|
1111
|
+
? `${GRN}✓${R} recall close to expected ${DIM}(~${pctStr} overlap)${R}`
|
|
1112
|
+
: sim >= 0.25
|
|
1113
|
+
? `${YEL}△${R} partial recall ${DIM}(~${pctStr} overlap)${R}`
|
|
1114
|
+
: `${RED}✗${R} recall diverges ${DIM}(~${pctStr} overlap)${R}`;
|
|
1115
|
+
}
|
|
1116
|
+
else {
|
|
1117
|
+
verdict = `${DIM}·${R} plain experience — no expected answer`;
|
|
1118
|
+
}
|
|
1119
|
+
lines.push(`${B}│${R} ${verdict}`);
|
|
1120
|
+
lines.push(`${B}╰${"─".repeat(W)}╯${R}`);
|
|
1121
|
+
return lines.join("\n");
|
|
1122
|
+
}
|
|
1123
|
+
function renderPanel(s) {
|
|
1124
|
+
const targetKnown = isFinite(s.target);
|
|
1125
|
+
// Primary progress: by learned-content bytes when a MAX_MB target is set,
|
|
1126
|
+
// else by how far we are through the corpus on disk (bytes) — so the default
|
|
1127
|
+
// unbounded run still shows a real fraction and a real ETA.
|
|
1128
|
+
const frac = targetKnown
|
|
1129
|
+
? (s.target > 0 ? s.trainedBytes / s.target : 0)
|
|
1130
|
+
: (s.bytesTotal > 0 ? s.bytesDone / s.bytesTotal : 0);
|
|
1131
|
+
const etaStr = (() => {
|
|
1132
|
+
if (targetKnown) {
|
|
1133
|
+
return s.trainedRate > 0
|
|
1134
|
+
? dur((s.target - s.trainedBytes) / s.trainedRate)
|
|
1135
|
+
: "∞";
|
|
1136
|
+
}
|
|
1137
|
+
if (s.bytesTotal > 0 && s.bytesRate > 0) {
|
|
1138
|
+
return dur((s.bytesTotal - s.bytesDone) / s.bytesRate);
|
|
1139
|
+
}
|
|
1140
|
+
return "∞";
|
|
1141
|
+
})();
|
|
1142
|
+
const fileFrac = s.fileTotal > 0 ? s.fileIndex / s.fileTotal : 0;
|
|
1143
|
+
let actIcon = `${DIM}·${R}`, actText = "waiting…";
|
|
1144
|
+
if (s.activity === "download") {
|
|
1145
|
+
actIcon = `${CYAN}⬇${R}`;
|
|
1146
|
+
const name = s.filePath;
|
|
1147
|
+
const total = s.dlTotal > 0 ? s.dlTotal : s.fileSize;
|
|
1148
|
+
if (total > 0 && s.dlDone > 0) {
|
|
1149
|
+
const dlFrac = clamp01(s.dlDone / total);
|
|
1150
|
+
actText =
|
|
1151
|
+
`downloading ${name} ${bar(18, dlFrac)} ${B}${pct(dlFrac)}${R}` +
|
|
1152
|
+
` ${DIM}${bytes(s.dlDone)}/${bytes(total)}${R}`;
|
|
1153
|
+
if (s.dlSpeed > 0)
|
|
1154
|
+
actText += ` ${DIM}@ ${bytes(s.dlSpeed)}/s${R}`;
|
|
1155
|
+
}
|
|
1156
|
+
else {
|
|
1157
|
+
actText = total > 0
|
|
1158
|
+
? `downloading ${name} · ${bytes(total)}…`
|
|
1159
|
+
: `downloading ${name}…`;
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
else if (s.activity === "process") {
|
|
1163
|
+
actIcon = `${GRN}✓${R}`;
|
|
1164
|
+
actText = `processing ${s.filePath} · ${int(s.fileExamples)} examples so far`;
|
|
1165
|
+
}
|
|
1166
|
+
const targetStr = targetKnown ? bytes(s.target) : "∞";
|
|
1167
|
+
const headExamples = targetKnown
|
|
1168
|
+
? `${CYAN}${bytes(s.trainedBytes)}${R} / ${targetStr} learned ${DIM}·${R} ${int(s.exampleCount)} examples`
|
|
1169
|
+
: `${CYAN}${int(s.exampleCount)}${R} examples`;
|
|
1170
|
+
const corpusInfo = s.bytesTotal > 0
|
|
1171
|
+
? `${B}📦${R} ${bytes(s.bytesDone)}/${bytes(s.bytesTotal)} (${pct(s.bytesDone / s.bytesTotal)})`
|
|
1172
|
+
: `${B}📦${R} ${bytes(s.bytesDone)} processed`;
|
|
1173
|
+
const fileInfo = s.fileTotal > 0
|
|
1174
|
+
? `${B}🌐${R} ${s.fileIndex}/${s.fileTotal} (${pct(fileFrac)})`
|
|
1175
|
+
: `${B}🌐${R} ${s.fileIndex} languages`;
|
|
1176
|
+
const panel = [
|
|
1177
|
+
`${B}╭${R}${B} sema train${R} ${DIM}·${R} SmolSent+Aya+oasst2 ${DIM}·${R} ` +
|
|
1178
|
+
`D=${D} ${DIM}·${R} seed=${SEED} ${DIM}·${R} ` +
|
|
1179
|
+
`store=${basename(DB_PATH)}.sqlite\n${B}╰${R} target=${CYAN}${targetStr}${R} ` +
|
|
1180
|
+
`learned ${DIM}·${R} checkpoint every ${bytes(CHECKPOINT_BYTES)}`,
|
|
1181
|
+
`\n${bar(40, frac)} ${B}${pct(frac)}${R} ${headExamples}`,
|
|
1182
|
+
`\n${B}⚡${R} ${bytes(s.trainedRate)}/s learned ${B}🧠${R} ${bytes(s.trainedBytes)} content ${B}⏱${R} ${dur(s.elapsedS)} elapsed ${B}🕐${R} ${etaStr} ETA`,
|
|
1183
|
+
`${fileInfo} ${corpusInfo} ${B}🗄${R} ${num(s.storeEntries)} entries ` +
|
|
1184
|
+
`${B}💾${R} cache ${bytes(s.cacheBytes)}`,
|
|
1185
|
+
`\n${actIcon} ${actText}`,
|
|
1186
|
+
].join("");
|
|
1187
|
+
return s.lastSample ? `${panel}\n${s.lastSample}` : panel;
|
|
1188
|
+
}
|
|
1189
|
+
/** A live panel pinned to the bottom of stderr. On a TTY it redraws in place,
|
|
1190
|
+
* clearing only its own lines; logs are flushed into the scrollback above it.
|
|
1191
|
+
* Off a TTY (piped/CI) the panel is suppressed and a plain status line is
|
|
1192
|
+
* emitted occasionally, so logs stay clean and parseable. */
|
|
1193
|
+
class Progress {
|
|
1194
|
+
lines = 0; // height of the panel currently on screen
|
|
1195
|
+
lastPaint = 0;
|
|
1196
|
+
lastStatus = 0;
|
|
1197
|
+
last = null;
|
|
1198
|
+
tty = process.stderr.isTTY === true;
|
|
1199
|
+
/** True when attached to an interactive terminal (panel is live). */
|
|
1200
|
+
get interactive() {
|
|
1201
|
+
return this.tty;
|
|
1202
|
+
}
|
|
1203
|
+
/** Cursor sequence that returns to the top of the panel and clears it. */
|
|
1204
|
+
clearPanel() {
|
|
1205
|
+
if (this.lines <= 0)
|
|
1206
|
+
return "";
|
|
1207
|
+
const up = this.lines - 1; // cursor is on the panel's last line
|
|
1208
|
+
return (up > 0 ? `${CSI}${up}F` : "\r") + `${CSI}0J`;
|
|
1209
|
+
}
|
|
1210
|
+
render(s, force = false) {
|
|
1211
|
+
this.last = s;
|
|
1212
|
+
const now = Date.now();
|
|
1213
|
+
if (!force && now - this.lastPaint < PROGRESS_MS)
|
|
1214
|
+
return;
|
|
1215
|
+
this.lastPaint = now;
|
|
1216
|
+
if (!this.tty) {
|
|
1217
|
+
if (force || now - this.lastStatus >= 10_000) {
|
|
1218
|
+
this.lastStatus = now;
|
|
1219
|
+
const targetKnown = isFinite(s.target);
|
|
1220
|
+
const where = s.bytesTotal > 0
|
|
1221
|
+
? ` ${pct(s.bytesDone / s.bytesTotal)} of corpus`
|
|
1222
|
+
: "";
|
|
1223
|
+
process.stderr.write(`[sema] ${bytes(s.trainedBytes)}${targetKnown ? "/" + bytes(s.target) : ""} learned · ${int(s.exampleCount)} examples · ` +
|
|
1224
|
+
`${bytes(s.trainedRate)}/s · lang ${s.fileIndex}/${s.fileTotal}${where} · ` +
|
|
1225
|
+
`${num(s.storeEntries)} entries\n`);
|
|
1226
|
+
}
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
const text = renderPanel(s);
|
|
1230
|
+
process.stderr.write(`${this.clearPanel()}${HIDE}${text}`);
|
|
1231
|
+
this.lines = text.split("\n").length;
|
|
1232
|
+
}
|
|
1233
|
+
/** Emit a line (or block) into the scrollback above the panel; the panel is
|
|
1234
|
+
* redrawn immediately beneath it so it never disappears between frames. */
|
|
1235
|
+
log(msg) {
|
|
1236
|
+
if (!this.tty) {
|
|
1237
|
+
process.stderr.write(`${msg}\n`);
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
let out = `${this.clearPanel()}${msg}\n`;
|
|
1241
|
+
this.lines = 0;
|
|
1242
|
+
if (this.last) {
|
|
1243
|
+
const text = renderPanel(this.last);
|
|
1244
|
+
out += `${HIDE}${text}`;
|
|
1245
|
+
this.lines = text.split("\n").length;
|
|
1246
|
+
}
|
|
1247
|
+
process.stderr.write(out);
|
|
1248
|
+
}
|
|
1249
|
+
dispose() {
|
|
1250
|
+
if (this.tty)
|
|
1251
|
+
process.stderr.write(`${SHOW}\n`);
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
1255
|
+
// §9 Progress persistence (inside the store — resume from the store alone)
|
|
1256
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
1257
|
+
const META_COMPLETED = "train.completedFiles";
|
|
1258
|
+
const META_DEPOSITS = "train.depositCount";
|
|
1259
|
+
const META_TRAINED_BYTES = "train.trainedContentBytes";
|
|
1260
|
+
const META_BYTES = "train.totalBytesProcessed";
|
|
1261
|
+
const META_CORPUS_BYTES = "train.totalCorpusBytes";
|
|
1262
|
+
async function loadProgress(store) {
|
|
1263
|
+
try {
|
|
1264
|
+
const raw = await store.getMeta(META_COMPLETED);
|
|
1265
|
+
const deps = await store.getMeta(META_DEPOSITS);
|
|
1266
|
+
const b = await store.getMeta(META_BYTES);
|
|
1267
|
+
if (raw !== null && deps !== null && b !== null) {
|
|
1268
|
+
const completedFiles = JSON.parse(raw);
|
|
1269
|
+
if (Array.isArray(completedFiles)) {
|
|
1270
|
+
const trained = await store.getMeta(META_TRAINED_BYTES);
|
|
1271
|
+
const corpus = await store.getMeta(META_CORPUS_BYTES);
|
|
1272
|
+
return {
|
|
1273
|
+
completedFiles,
|
|
1274
|
+
depositCount: Number(deps) || 0,
|
|
1275
|
+
trainedContentBytes: Number(trained) || 0,
|
|
1276
|
+
totalBytesProcessed: Number(b) || 0,
|
|
1277
|
+
totalCorpusBytes: Number(corpus) || 0,
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
catch { /* corrupt/missing — start fresh */ }
|
|
1283
|
+
return {
|
|
1284
|
+
completedFiles: [],
|
|
1285
|
+
depositCount: 0,
|
|
1286
|
+
trainedContentBytes: 0,
|
|
1287
|
+
totalBytesProcessed: 0,
|
|
1288
|
+
totalCorpusBytes: 0,
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
async function saveProgress(store, p) {
|
|
1292
|
+
await store.setMeta(META_COMPLETED, JSON.stringify(p.completedFiles));
|
|
1293
|
+
await store.setMeta(META_DEPOSITS, String(p.depositCount));
|
|
1294
|
+
await store.setMeta(META_TRAINED_BYTES, String(p.trainedContentBytes));
|
|
1295
|
+
await store.setMeta(META_BYTES, String(p.totalBytesProcessed));
|
|
1296
|
+
await store.setMeta(META_CORPUS_BYTES, String(p.totalCorpusBytes));
|
|
1297
|
+
await store.setMeta("train.updatedAt", new Date().toISOString());
|
|
1298
|
+
store.commit();
|
|
1299
|
+
}
|
|
1300
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
1301
|
+
// §10 Main
|
|
1302
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
1303
|
+
async function main() {
|
|
1304
|
+
// The vector indices' memory knob (MiB) — each index's SQLite page cache.
|
|
1305
|
+
// The IVF index routes inserts through a RAM-resident pivot table and
|
|
1306
|
+
// appends to chunk blobs, so this cache mostly serves query-time cluster
|
|
1307
|
+
// scans; 256 MiB comfortably covers the probed working set of a trained
|
|
1308
|
+
// store. Override with VECTOR_CACHE_MB (64 is the library default).
|
|
1309
|
+
const VECTOR_CACHE_MB = Math.max(0, Number(env("VECTOR_CACHE_MB", "256")));
|
|
1310
|
+
// Page cache for the MAIN DAG database (node/kid/edge/contain tables).
|
|
1311
|
+
// Training issues millions of content-addressed point probes per session
|
|
1312
|
+
// against a GB-scale file; the library default (64 MiB) is sized for a
|
|
1313
|
+
// small machine — a training box affords more. Override with
|
|
1314
|
+
// SQLITE_CACHE_MB.
|
|
1315
|
+
const SQLITE_CACHE_MB = Math.max(0, Number(env("SQLITE_CACHE_MB", "256")));
|
|
1316
|
+
const store = new SQliteStore({
|
|
1317
|
+
path: DB_PATH,
|
|
1318
|
+
D,
|
|
1319
|
+
vectorCacheMb: VECTOR_CACHE_MB,
|
|
1320
|
+
sqliteCacheMb: SQLITE_CACHE_MB,
|
|
1321
|
+
});
|
|
1322
|
+
// The store IS the model: memories, progress, and metadata all persist in
|
|
1323
|
+
// it, so a resumed run just reopens the same store and continues. Guard
|
|
1324
|
+
// against a changed D/SEED by comparing against what a previous run recorded.
|
|
1325
|
+
const mind = new Mind({ seed: SEED, store });
|
|
1326
|
+
// Pre-fill the vector indices' RAM caches with sequential scans (bounded by
|
|
1327
|
+
// VECTOR_CACHE_MB). A resumed run over a large store otherwise spends its
|
|
1328
|
+
// first minutes warming those caches through random point reads — the
|
|
1329
|
+
// ingest hot path is cache-miss bound until then. Seconds, once, up front.
|
|
1330
|
+
if (VECTOR_CACHE_MB > 0) {
|
|
1331
|
+
const t = Date.now();
|
|
1332
|
+
const warmed = await store.warmVectorCaches();
|
|
1333
|
+
if (warmed > 0) {
|
|
1334
|
+
process.stderr.write(` warmed vector caches: ${num(warmed)} rows in ${dur((Date.now() - t) / 1000)}\n`);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
const ci = new CachedIngest(mind);
|
|
1338
|
+
const prevD = await store.getMeta("train.D");
|
|
1339
|
+
const prevSeed = await store.getMeta("train.seed");
|
|
1340
|
+
if ((prevD && Number(prevD) !== D) || (prevSeed && Number(prevSeed) !== SEED)) {
|
|
1341
|
+
process.stderr.write(`fatal: D/SEED changed (store has D=${prevD} seed=${prevSeed}, ` +
|
|
1342
|
+
`requested D=${D} seed=${SEED}). Delete ${DB_PATH}.sqlite ` +
|
|
1343
|
+
`to start fresh.\n`);
|
|
1344
|
+
process.exit(1);
|
|
1345
|
+
}
|
|
1346
|
+
await store.setMeta("train.dataset", "SmolSent+Aya+oasst2");
|
|
1347
|
+
await store.setMeta("train.D", String(D));
|
|
1348
|
+
await store.setMeta("train.seed", String(SEED));
|
|
1349
|
+
await store.setMeta("train.createdAt", new Date().toISOString());
|
|
1350
|
+
// ── counters & sampling ──
|
|
1351
|
+
let depositCount = 0;
|
|
1352
|
+
let trainedContentBytes = 0;
|
|
1353
|
+
let bytesSinceCkpt = 0;
|
|
1354
|
+
let checkpointNum = 0;
|
|
1355
|
+
let totalBytesProcessed = 0;
|
|
1356
|
+
let totalCorpusBytes = 0;
|
|
1357
|
+
const langTally = {};
|
|
1358
|
+
const t0 = Date.now();
|
|
1359
|
+
// Reservoir sample: one uniformly-random item from the current window, shown
|
|
1360
|
+
// in the recall box at each checkpoint.
|
|
1361
|
+
let sampleItem = null;
|
|
1362
|
+
let seenInWindow = 0;
|
|
1363
|
+
const sample = (it) => {
|
|
1364
|
+
seenInWindow++;
|
|
1365
|
+
if (Math.random() < 1 / seenInWindow)
|
|
1366
|
+
sampleItem = it;
|
|
1367
|
+
};
|
|
1368
|
+
// ── progress panel ──
|
|
1369
|
+
const progress = new Progress();
|
|
1370
|
+
// Surface rate-limit waits from the low-level fetch retries into the live log,
|
|
1371
|
+
// so a 429 back-off reads as "waiting", never a silent hang or a dropped file.
|
|
1372
|
+
onThrottleWait = (ms, label) => {
|
|
1373
|
+
progress.log(` ${YEL}⏳${R} rate-limited (${label}); waiting ${(ms / 1000).toFixed(1)}s and retrying — not skipping`);
|
|
1374
|
+
};
|
|
1375
|
+
const state = {
|
|
1376
|
+
exampleCount: 0,
|
|
1377
|
+
target: MAX_BYTES,
|
|
1378
|
+
elapsedS: 0,
|
|
1379
|
+
trainedBytes: 0,
|
|
1380
|
+
trainedRate: 0,
|
|
1381
|
+
bytesDone: 0,
|
|
1382
|
+
bytesTotal: 0,
|
|
1383
|
+
bytesRate: 0,
|
|
1384
|
+
fileIndex: 0,
|
|
1385
|
+
fileTotal: 0,
|
|
1386
|
+
filePath: "",
|
|
1387
|
+
fileSize: 0,
|
|
1388
|
+
fileExamples: 0,
|
|
1389
|
+
activity: "idle",
|
|
1390
|
+
dlSpeed: 0,
|
|
1391
|
+
dlDone: 0,
|
|
1392
|
+
dlTotal: 0,
|
|
1393
|
+
storeEntries: 0,
|
|
1394
|
+
cacheBytes: 0,
|
|
1395
|
+
lastSample: null,
|
|
1396
|
+
};
|
|
1397
|
+
// store.size() is async; refresh it on a slow cadence so the hot loop and
|
|
1398
|
+
// the repaint never block on a query.
|
|
1399
|
+
let cachedEntries = 0;
|
|
1400
|
+
let sizeInFlight = false;
|
|
1401
|
+
const refreshSize = () => {
|
|
1402
|
+
if (sizeInFlight)
|
|
1403
|
+
return;
|
|
1404
|
+
sizeInFlight = true;
|
|
1405
|
+
void mind.store.size()
|
|
1406
|
+
.then((n) => (cachedEntries = n))
|
|
1407
|
+
.catch(() => undefined)
|
|
1408
|
+
.finally(() => (sizeInFlight = false));
|
|
1409
|
+
};
|
|
1410
|
+
// Cache size changes only at download/delete boundaries — recompute it
|
|
1411
|
+
// lazily rather than statting the dir on every deposit.
|
|
1412
|
+
let cachedCacheBytes = 0;
|
|
1413
|
+
let lastCacheUpdate = 0;
|
|
1414
|
+
// Live download progress for the panel.
|
|
1415
|
+
let dlSlot = null;
|
|
1416
|
+
// Rolling throughput: a short EMA over wall-clock windows, so the headline
|
|
1417
|
+
// figures reflect CURRENT speed rather than a lifetime average diluted by the
|
|
1418
|
+
// listing and download phases (which train nothing).
|
|
1419
|
+
let rateT = t0;
|
|
1420
|
+
let rateTrained = 0;
|
|
1421
|
+
let rateBytes = 0;
|
|
1422
|
+
const syncState = () => {
|
|
1423
|
+
const now = Date.now();
|
|
1424
|
+
state.exampleCount = depositCount;
|
|
1425
|
+
state.trainedBytes = trainedContentBytes;
|
|
1426
|
+
state.elapsedS = (now - t0) / 1000;
|
|
1427
|
+
state.storeEntries = cachedEntries;
|
|
1428
|
+
state.bytesDone = totalBytesProcessed;
|
|
1429
|
+
state.bytesTotal = totalCorpusBytes;
|
|
1430
|
+
if (dlSlot && state.activity === "download") {
|
|
1431
|
+
state.dlDone = dlSlot.done;
|
|
1432
|
+
state.dlTotal = dlSlot.total;
|
|
1433
|
+
const ds = (now - dlSlot.t0) / 1000;
|
|
1434
|
+
state.dlSpeed = ds > 0.2 ? dlSlot.done / ds : 0;
|
|
1435
|
+
}
|
|
1436
|
+
else {
|
|
1437
|
+
state.dlDone = 0;
|
|
1438
|
+
state.dlTotal = 0;
|
|
1439
|
+
}
|
|
1440
|
+
const dt = (now - rateT) / 1000;
|
|
1441
|
+
if (dt >= 0.5) {
|
|
1442
|
+
const instTrained = (trainedContentBytes - rateTrained) / dt;
|
|
1443
|
+
const instByte = (totalBytesProcessed - rateBytes) / dt;
|
|
1444
|
+
const a = 0.3; // EMA weight on the newest sample
|
|
1445
|
+
state.trainedRate = state.trainedRate === 0
|
|
1446
|
+
? instTrained
|
|
1447
|
+
: state.trainedRate * (1 - a) + instTrained * a;
|
|
1448
|
+
state.bytesRate = state.bytesRate === 0
|
|
1449
|
+
? instByte
|
|
1450
|
+
: state.bytesRate * (1 - a) + instByte * a;
|
|
1451
|
+
rateT = now;
|
|
1452
|
+
rateTrained = trainedContentBytes;
|
|
1453
|
+
rateBytes = totalBytesProcessed;
|
|
1454
|
+
}
|
|
1455
|
+
if (now - lastCacheUpdate > 2000) {
|
|
1456
|
+
cachedCacheBytes = cacheSize();
|
|
1457
|
+
lastCacheUpdate = now;
|
|
1458
|
+
}
|
|
1459
|
+
state.cacheBytes = cachedCacheBytes;
|
|
1460
|
+
};
|
|
1461
|
+
const tick = (force = false) => {
|
|
1462
|
+
syncState();
|
|
1463
|
+
progress.render(state, force);
|
|
1464
|
+
};
|
|
1465
|
+
const paintTimer = setInterval(() => {
|
|
1466
|
+
refreshSize();
|
|
1467
|
+
tick(false);
|
|
1468
|
+
}, PROGRESS_MS);
|
|
1469
|
+
if (typeof paintTimer.unref === "function")
|
|
1470
|
+
paintTimer.unref();
|
|
1471
|
+
// ── keep-alive: the process must never exit on its own mid-training ──
|
|
1472
|
+
// The CPU-bound processing phase (perceive + intern + the batched vector-index
|
|
1473
|
+
// writes) hands control back to the event loop between batches via the store's
|
|
1474
|
+
// yieldToEventLoop(), which parks on an UNREF'd setImmediate so the library
|
|
1475
|
+
// never holds a process open by itself. node:sqlite is synchronous and the
|
|
1476
|
+
// vector index is in-memory, so the store's awaits resolve as microtasks with
|
|
1477
|
+
// no I/O handle, and the paint timer above is unref'd too. That leaves a window
|
|
1478
|
+
// — a batch flush that fires while we're processing an in-memory chunk, not
|
|
1479
|
+
// awaiting a disk read — in which the ONLY pending work is that unref'd
|
|
1480
|
+
// setImmediate and NOTHING is ref'd. Node's rule is to exit when only unref'd
|
|
1481
|
+
// handles remain, WITHOUT running them: the yield's continuation never fires,
|
|
1482
|
+
// main() is abandoned, and the process exits 0 silently mid-file — no error for
|
|
1483
|
+
// the fault-tolerance to catch. This one ref'd (NOT unref'd) timer guarantees a
|
|
1484
|
+
// live handle for the whole run, so the loop can never drain from under a
|
|
1485
|
+
// pending yield. Every real exit is an explicit process.exit() (finish(), the
|
|
1486
|
+
// shutdown watchdog, the second-signal path, the fatal catch), so keeping this
|
|
1487
|
+
// handle alive never delays a genuine shutdown; finish() clears it before that
|
|
1488
|
+
// final exit for tidiness. Same lesson as waitMs above (deliberately un-unref'd).
|
|
1489
|
+
const keepAlive = setInterval(() => { }, 1 << 30);
|
|
1490
|
+
const checkpoint = () => mind.save();
|
|
1491
|
+
/** Run index maintenance: compact (remove garbage), repair (fill gaps),
|
|
1492
|
+
* then refresh the canonical-form index (see below). All three are
|
|
1493
|
+
* idempotent — running twice produces the same result as once.
|
|
1494
|
+
* Compaction frees index space first; repair then adds back every
|
|
1495
|
+
* edge/halo-bearing node whose gist was evicted from the pending cache
|
|
1496
|
+
* before it reached the content index, completing the coverage that
|
|
1497
|
+
* incremental promotion alone cannot guarantee.
|
|
1498
|
+
*
|
|
1499
|
+
* repair runs with minParents = 0, NOT the library default of 2. The
|
|
1500
|
+
* default repairs only structural BRIDGES (≥2 parents), but this
|
|
1501
|
+
* trainer's fact deposits also leave answer-side DEPOSIT ROOTS with 0
|
|
1502
|
+
* structural parents ("The capital of France is Paris." as the dst of a
|
|
1503
|
+
* Q→A edge is a root of its own tree, contained in nothing). Those are
|
|
1504
|
+
* resonance targets recall depends on — a trained store shipped without
|
|
1505
|
+
* them cannot ground statement-shaped queries against its own answers
|
|
1506
|
+
* (observed: 33 such roots missing after a full curriculum, including
|
|
1507
|
+
* high-traffic conversation replies). minParents = 0 admits every
|
|
1508
|
+
* edge/halo bearer; the candidate set is still corpus-of-experiences-
|
|
1509
|
+
* sized, so the pass stays cheap.
|
|
1510
|
+
*
|
|
1511
|
+
* Logs the number of entries removed/added so a run that silently degrades
|
|
1512
|
+
* (growing compaction count, or repair never recovering anything) is
|
|
1513
|
+
* visible in the training log. */
|
|
1514
|
+
const runIndexMaintenance = async () => {
|
|
1515
|
+
if (!INDEX_MAINTENANCE)
|
|
1516
|
+
return;
|
|
1517
|
+
try {
|
|
1518
|
+
const removed = await mind.store.compactContentIndex();
|
|
1519
|
+
if (removed > 0) {
|
|
1520
|
+
progress.log(` ${DIM}index compact: removed ${int(removed)} isolated entries${R}`);
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
catch (err) {
|
|
1524
|
+
progress.log(` ${YEL}⚠ index compact failed${R}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1525
|
+
}
|
|
1526
|
+
try {
|
|
1527
|
+
const added = await mind.repairContentIndex(0);
|
|
1528
|
+
if (added > 0) {
|
|
1529
|
+
progress.log(` ${GRN}index repair: added ${int(added)} missing resonance targets${R}`);
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
catch (err) {
|
|
1533
|
+
progress.log(` ${YEL}⚠ index repair failed${R}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1534
|
+
}
|
|
1535
|
+
// Canonical-form index (src/canon.ts): lets resolution find stored forms
|
|
1536
|
+
// across surface variation (case, width, whitespace). Incremental and
|
|
1537
|
+
// idempotent by construction — the `canon.upto` meta cursor scans only
|
|
1538
|
+
// nodes newer than the last pass, and the (h, id) primary key ignores
|
|
1539
|
+
// re-inserted rows — so it composes with the resume model exactly like
|
|
1540
|
+
// compact/repair: every checkpoint (and finish) leaves the index
|
|
1541
|
+
// covering all content trained so far.
|
|
1542
|
+
try {
|
|
1543
|
+
const added = await mind.buildCanonIndex();
|
|
1544
|
+
if (added > 0) {
|
|
1545
|
+
progress.log(` ${GRN}canon index: added ${int(added)} canonical-form entries${R}`);
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
catch (err) {
|
|
1549
|
+
progress.log(` ${YEL}⚠ canon index build failed${R}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
// The checkpoint recall is a best-effort diagnostic. It is time-bounded so a
|
|
1553
|
+
// slow/large store can never freeze the deposit loop, and guarded so a still
|
|
1554
|
+
// running recall is never stacked on top of another.
|
|
1555
|
+
let inferBusy = false;
|
|
1556
|
+
const runRecall = async (item, n) => {
|
|
1557
|
+
if (inferBusy)
|
|
1558
|
+
return;
|
|
1559
|
+
inferBusy = true;
|
|
1560
|
+
try {
|
|
1561
|
+
const info = promptOf(item);
|
|
1562
|
+
const r = await withTimeout(mind.respond(info.prompt), INFER_TIMEOUT_MS, "recall");
|
|
1563
|
+
const resp = new TextDecoder().decode(r.bytes).replace(/\u0000+/g, "");
|
|
1564
|
+
const box = renderInferenceBox(info.prompt, info.expected, resp, info.kind, n);
|
|
1565
|
+
state.lastSample = box;
|
|
1566
|
+
if (!progress.interactive)
|
|
1567
|
+
progress.log(box);
|
|
1568
|
+
tick(true);
|
|
1569
|
+
}
|
|
1570
|
+
catch (err) {
|
|
1571
|
+
progress.log(` ${DIM}· checkpoint #${n} recall skipped: ${err instanceof Error ? err.message : String(err)}${R}`);
|
|
1572
|
+
}
|
|
1573
|
+
finally {
|
|
1574
|
+
inferBusy = false;
|
|
1575
|
+
}
|
|
1576
|
+
};
|
|
1577
|
+
// ── graceful shutdown (always leaves the store consistent) ──
|
|
1578
|
+
let stopRequested = false;
|
|
1579
|
+
let stopReason = "interrupted";
|
|
1580
|
+
let finishing = false;
|
|
1581
|
+
const finish = async (why) => {
|
|
1582
|
+
if (finishing)
|
|
1583
|
+
return;
|
|
1584
|
+
finishing = true;
|
|
1585
|
+
shutdown.abort(); // unblock any straggling fetch/pipeTo
|
|
1586
|
+
tick(true);
|
|
1587
|
+
await store.setMeta("train.completedAt", new Date().toISOString());
|
|
1588
|
+
await store.setMeta("train.totalDeposits", String(depositCount));
|
|
1589
|
+
await store.setMeta("train.totalTrainedBytes", String(trainedContentBytes));
|
|
1590
|
+
await store.setMeta("train.totalBytes", String(totalBytesProcessed));
|
|
1591
|
+
await store.setMeta("train.totalCorpusBytes", String(totalCorpusBytes));
|
|
1592
|
+
await store.setMeta("train.langTally", JSON.stringify(langTally));
|
|
1593
|
+
try {
|
|
1594
|
+
await runIndexMaintenance();
|
|
1595
|
+
await checkpoint();
|
|
1596
|
+
}
|
|
1597
|
+
catch (err) {
|
|
1598
|
+
process.stderr.write(`\n ${YEL}⚠ final checkpoint failed${R}: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
1599
|
+
}
|
|
1600
|
+
clearInterval(paintTimer);
|
|
1601
|
+
clearInterval(keepAlive);
|
|
1602
|
+
progress.dispose();
|
|
1603
|
+
const elapsedS = (Date.now() - t0) / 1000;
|
|
1604
|
+
const elapsed = dur(elapsedS);
|
|
1605
|
+
const avgRate = elapsedS > 0 ? trainedContentBytes / elapsedS : 0;
|
|
1606
|
+
const tally = Object.entries(langTally)
|
|
1607
|
+
.sort((a, b) => b[1] - a[1])
|
|
1608
|
+
.map(([k, v]) => `${k}:${int(v)}`)
|
|
1609
|
+
.join(", ");
|
|
1610
|
+
let entries = depositCount;
|
|
1611
|
+
try {
|
|
1612
|
+
entries = await mind.store.size();
|
|
1613
|
+
}
|
|
1614
|
+
catch { /* best effort */ }
|
|
1615
|
+
console.log(`\n${GRN}✓${R} ${why}. ${basename(DB_PATH)}.sqlite: ` +
|
|
1616
|
+
`${int(entries)} entries, ${int(depositCount)} examples, ` +
|
|
1617
|
+
`${bytes(trainedContentBytes)} content learned ` +
|
|
1618
|
+
`${DIM}(${bytes(avgRate)}/s avg)${R}, ` +
|
|
1619
|
+
`${bytes(totalBytesProcessed)} corpus processed, ${elapsed} elapsed.` +
|
|
1620
|
+
(tally ? `\n ${DIM}per language:${R} ${tally}` : ""));
|
|
1621
|
+
try {
|
|
1622
|
+
await store.close();
|
|
1623
|
+
}
|
|
1624
|
+
catch { /* best effort */ }
|
|
1625
|
+
process.exit(0);
|
|
1626
|
+
};
|
|
1627
|
+
const requestStop = (reason) => {
|
|
1628
|
+
if (stopRequested) {
|
|
1629
|
+
process.stderr.write(`\n${YEL}⚠ second signal — exiting now${R}\n`);
|
|
1630
|
+
process.stderr.write(SHOW);
|
|
1631
|
+
process.exit(130);
|
|
1632
|
+
}
|
|
1633
|
+
stopRequested = true;
|
|
1634
|
+
stopReason = reason;
|
|
1635
|
+
shutdown.abort();
|
|
1636
|
+
progress.log(` ${YEL}⏸${R} ${reason} — finishing current item, saving…`);
|
|
1637
|
+
const watchdog = setTimeout(() => {
|
|
1638
|
+
process.stderr.write(`\n${YEL}⚠ shutdown watchdog fired — forcing exit${R}\n`);
|
|
1639
|
+
process.stderr.write(SHOW);
|
|
1640
|
+
process.exit(130);
|
|
1641
|
+
}, 60_000);
|
|
1642
|
+
if (typeof watchdog.unref === "function")
|
|
1643
|
+
watchdog.unref();
|
|
1644
|
+
};
|
|
1645
|
+
process.on("SIGINT", () => requestStop("interrupted"));
|
|
1646
|
+
process.on("SIGTERM", () => requestStop("terminated"));
|
|
1647
|
+
// ── fail-safe: a dropped connection must never kill a long run ──
|
|
1648
|
+
process.on("unhandledRejection", (reason) => {
|
|
1649
|
+
progress.log(` ${YEL}⚠ unhandled rejection${R}: ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
1650
|
+
});
|
|
1651
|
+
process.on("uncaughtException", (err) => {
|
|
1652
|
+
const code = err?.code ?? err?.cause?.code;
|
|
1653
|
+
if (err.message === "terminated" || code === "UND_ERR_SOCKET") {
|
|
1654
|
+
progress.log(` ${YEL}⚠ connection error (ignored)${R}: ${err.message}`);
|
|
1655
|
+
return;
|
|
1656
|
+
}
|
|
1657
|
+
process.stderr.write(`\n${RED}uncaught exception${R}: ${err.message}\n${err.stack ?? ""}\n`);
|
|
1658
|
+
try {
|
|
1659
|
+
void store.setMeta("train.crashedAt", new Date().toISOString());
|
|
1660
|
+
void store.setMeta("train.crashError", err.message);
|
|
1661
|
+
void store.setMeta("train.totalDeposits", String(depositCount));
|
|
1662
|
+
}
|
|
1663
|
+
catch { /* best effort */ }
|
|
1664
|
+
process.exit(1);
|
|
1665
|
+
});
|
|
1666
|
+
// ── per-example callback: gates MAX_MB, drives checkpoints + samples ──
|
|
1667
|
+
const onDeposit = async (contentBytes) => {
|
|
1668
|
+
depositCount++;
|
|
1669
|
+
trainedContentBytes += contentBytes;
|
|
1670
|
+
bytesSinceCkpt += contentBytes;
|
|
1671
|
+
state.fileExamples++;
|
|
1672
|
+
if (bytesSinceCkpt >= CHECKPOINT_BYTES) {
|
|
1673
|
+
bytesSinceCkpt %= CHECKPOINT_BYTES;
|
|
1674
|
+
const n = ++checkpointNum;
|
|
1675
|
+
const item = sampleItem;
|
|
1676
|
+
sampleItem = null;
|
|
1677
|
+
seenInWindow = 0;
|
|
1678
|
+
if (item)
|
|
1679
|
+
await runRecall(item, n);
|
|
1680
|
+
try {
|
|
1681
|
+
await runIndexMaintenance();
|
|
1682
|
+
await checkpoint();
|
|
1683
|
+
}
|
|
1684
|
+
catch (err) {
|
|
1685
|
+
progress.log(` ${YEL}⚠ checkpoint failed${R}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1686
|
+
}
|
|
1687
|
+
tick(true);
|
|
1688
|
+
}
|
|
1689
|
+
else {
|
|
1690
|
+
tick();
|
|
1691
|
+
}
|
|
1692
|
+
// Stop AFTER the deposit is counted/displayed so the final item is never
|
|
1693
|
+
// lost from the totals. A pending signal stops at this same boundary, so a
|
|
1694
|
+
// clean shutdown and a MAX_MB cap unwind through identical, tested code.
|
|
1695
|
+
return !stopRequested && trainedContentBytes < MAX_BYTES;
|
|
1696
|
+
};
|
|
1697
|
+
const cacheWarn = (m) => progress.log(` ${m}`);
|
|
1698
|
+
/** Acquire a source file: reuse a cached copy, else download `url` into the
|
|
1699
|
+
* cache under `destName` (atomic, retried, rate-limit-tolerant, shows live
|
|
1700
|
+
* byte progress). Returns the local path, or null on a non-abort failure
|
|
1701
|
+
* (logged). `label` names the file in the panel/log. */
|
|
1702
|
+
const acquire = async (url, destName, label) => {
|
|
1703
|
+
const dest = join(CACHE_DIR, destName);
|
|
1704
|
+
if (existsSync(dest)) {
|
|
1705
|
+
progress.log(` ${GRN}✓${R} ${label} ${DIM}(cached)${R}`);
|
|
1706
|
+
return dest;
|
|
1707
|
+
}
|
|
1708
|
+
let size = 0;
|
|
1709
|
+
try {
|
|
1710
|
+
size = await headSize(url);
|
|
1711
|
+
}
|
|
1712
|
+
catch { /* unknown — proceed without a cache-room reservation */ }
|
|
1713
|
+
state.activity = "download";
|
|
1714
|
+
state.filePath = label;
|
|
1715
|
+
state.fileSize = size;
|
|
1716
|
+
const slot = { done: 0, total: size, t0: Date.now() };
|
|
1717
|
+
dlSlot = slot;
|
|
1718
|
+
tick(true);
|
|
1719
|
+
try {
|
|
1720
|
+
await ensureCacheRoom(size, cacheWarn);
|
|
1721
|
+
slot.t0 = Date.now();
|
|
1722
|
+
await downloadFile(url, dest, DOWNLOAD_TRIES, (n, e) => progress.log(` ${YEL}⚠${R} ${label} download attempt ${n}/${DOWNLOAD_TRIES}: ${e.message}`), (done, total) => {
|
|
1723
|
+
slot.done = done;
|
|
1724
|
+
if (total > 0)
|
|
1725
|
+
slot.total = total;
|
|
1726
|
+
});
|
|
1727
|
+
}
|
|
1728
|
+
catch (e) {
|
|
1729
|
+
dlSlot = null;
|
|
1730
|
+
if (stopRequested || e?.name === "AbortError")
|
|
1731
|
+
return null;
|
|
1732
|
+
progress.log(` ${RED}✗${R} ${label} download failed: ${e.message}`);
|
|
1733
|
+
try {
|
|
1734
|
+
unlinkSync(dest);
|
|
1735
|
+
}
|
|
1736
|
+
catch { /* best effort */ }
|
|
1737
|
+
return null;
|
|
1738
|
+
}
|
|
1739
|
+
dlSlot = null;
|
|
1740
|
+
const dlS = Math.max(0.001, (Date.now() - slot.t0) / 1000);
|
|
1741
|
+
const sz = statSync(dest).size;
|
|
1742
|
+
progress.log(` ${CYAN}⬇${R} ${label} ${bytes(sz)} ${DIM}${dur(dlS)} @ ${bytes(sz / dlS)}/s${R}`);
|
|
1743
|
+
return dest;
|
|
1744
|
+
};
|
|
1745
|
+
// ── §10a SmolSent stage (the FIRST stage) ──
|
|
1746
|
+
//
|
|
1747
|
+
// Downloads each SmolSent per-pair JSONL file and streams its lines. Resume is
|
|
1748
|
+
// per-file: a fully-consumed file is recorded in completedFiles
|
|
1749
|
+
// ("smolsent::<name>"); an interrupted file is re-streamed from the top on
|
|
1750
|
+
// resume (re-deposition is idempotent). LOCAL_PATH may hold pre-downloaded
|
|
1751
|
+
// smolsent *.jsonl files.
|
|
1752
|
+
const smolToItems = (row) => {
|
|
1753
|
+
const r = toSmolSentRow(row);
|
|
1754
|
+
return r ? smolSentRowToItems(r) : null;
|
|
1755
|
+
};
|
|
1756
|
+
const trainSmolSent = async () => {
|
|
1757
|
+
if (!SMOLSENT)
|
|
1758
|
+
return;
|
|
1759
|
+
if (trainedContentBytes >= MAX_BYTES || stopRequested)
|
|
1760
|
+
return;
|
|
1761
|
+
// Work-list: local *.jsonl in LOCAL_PATH, else the repo's smolsent/ files.
|
|
1762
|
+
let files;
|
|
1763
|
+
if (LOCAL_PATH) {
|
|
1764
|
+
files = readdirSync(LOCAL_PATH)
|
|
1765
|
+
.filter((f) => /\.jsonl$/i.test(f))
|
|
1766
|
+
.sort()
|
|
1767
|
+
.map((f) => ({
|
|
1768
|
+
id: `${SMOLSENT_ID}::${f}`,
|
|
1769
|
+
name: f,
|
|
1770
|
+
local: join(LOCAL_PATH, f),
|
|
1771
|
+
}));
|
|
1772
|
+
if (SMOLSENT_PAIRS.length) {
|
|
1773
|
+
const want = new Set(SMOLSENT_PAIRS.map((p) => p.replace(/\.jsonl$/i, "")));
|
|
1774
|
+
files = files.filter((f) => want.has(f.name.replace(/\.jsonl$/i, "")));
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
else {
|
|
1778
|
+
let paths;
|
|
1779
|
+
try {
|
|
1780
|
+
paths = await listSmolSentFiles();
|
|
1781
|
+
}
|
|
1782
|
+
catch (e) {
|
|
1783
|
+
if (stopRequested || e?.name === "AbortError")
|
|
1784
|
+
return;
|
|
1785
|
+
progress.log(` ${RED}✗${R} SmolSent file listing failed: ${e.message}`);
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
files = paths.map((path) => ({
|
|
1789
|
+
id: `${SMOLSENT_ID}::${basename(path)}`,
|
|
1790
|
+
name: basename(path),
|
|
1791
|
+
// owner/name and the file path are URL PATH segments — do not encode "/".
|
|
1792
|
+
url: `https://huggingface.co/datasets/${SMOLSENT_DATASET}/resolve/main/${path}`,
|
|
1793
|
+
}));
|
|
1794
|
+
}
|
|
1795
|
+
if (files.length === 0) {
|
|
1796
|
+
progress.log(` ${DIM}· no SmolSent files found — skipping${R}`);
|
|
1797
|
+
return;
|
|
1798
|
+
}
|
|
1799
|
+
const p = await loadProgress(store);
|
|
1800
|
+
const done = new Set(p.completedFiles);
|
|
1801
|
+
const remaining = files.filter((f) => !done.has(f.id));
|
|
1802
|
+
if (remaining.length === 0) {
|
|
1803
|
+
progress.log(` ${DIM}· SmolSent already trained — skipping${R}`);
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
state.fileTotal = files.length;
|
|
1807
|
+
progress.log(` ${GRN}✓${R} SmolSent: ${remaining.length}/${files.length} translation file(s) to train`);
|
|
1808
|
+
let idx = 0;
|
|
1809
|
+
for (const f of files) {
|
|
1810
|
+
if (trainedContentBytes >= MAX_BYTES || stopRequested)
|
|
1811
|
+
break;
|
|
1812
|
+
idx++;
|
|
1813
|
+
if (done.has(f.id))
|
|
1814
|
+
continue;
|
|
1815
|
+
// Acquire (download or reuse), then stream the JSONL.
|
|
1816
|
+
let path = f.local ?? "";
|
|
1817
|
+
let downloaded = false;
|
|
1818
|
+
if (!path) {
|
|
1819
|
+
const got = await acquire(f.url, f.id.replace(/[^A-Za-z0-9._-]+/g, "_"), `SmolSent ${f.name}`);
|
|
1820
|
+
if (!got) {
|
|
1821
|
+
if (stopRequested)
|
|
1822
|
+
break;
|
|
1823
|
+
continue; // a single failed file never aborts the stage
|
|
1824
|
+
}
|
|
1825
|
+
path = got;
|
|
1826
|
+
downloaded = true;
|
|
1827
|
+
}
|
|
1828
|
+
// Accumulate known corpus bytes so the progress bar shows a
|
|
1829
|
+
// meaningful ETA — grows as each file's size is discovered.
|
|
1830
|
+
try {
|
|
1831
|
+
totalCorpusBytes += statSync(path).size;
|
|
1832
|
+
}
|
|
1833
|
+
catch { /* best effort */ }
|
|
1834
|
+
state.activity = "process";
|
|
1835
|
+
state.fileIndex = idx;
|
|
1836
|
+
state.filePath = `SmolSent ${f.name}`;
|
|
1837
|
+
state.fileExamples = 0;
|
|
1838
|
+
tick(true);
|
|
1839
|
+
const p0 = Date.now();
|
|
1840
|
+
let res;
|
|
1841
|
+
try {
|
|
1842
|
+
res = await processJsonl(path, smolToItems, ci, onDeposit, sample, MAX_SMOLSENT_CHARS * 4);
|
|
1843
|
+
}
|
|
1844
|
+
catch (e) {
|
|
1845
|
+
if (stopRequested || e?.name === "AbortError")
|
|
1846
|
+
break;
|
|
1847
|
+
progress.log(` ${RED}✗${R} SmolSent ${f.name} parse failed: ${e.message}`);
|
|
1848
|
+
if (downloaded) {
|
|
1849
|
+
try {
|
|
1850
|
+
unlinkSync(path);
|
|
1851
|
+
}
|
|
1852
|
+
catch { /* best effort */ }
|
|
1853
|
+
}
|
|
1854
|
+
continue;
|
|
1855
|
+
}
|
|
1856
|
+
langTally["smolsent"] = (langTally["smolsent"] ?? 0) + res.examples;
|
|
1857
|
+
progress.log(` ${GRN}✓${R} ${f.name.replace(/\.jsonl$/i, "")} ${DIM}[translation]${R} → ${int(res.examples)} facts ${DIM}in ${dur((Date.now() - p0) / 1000)}${R}` +
|
|
1858
|
+
(res.skipped
|
|
1859
|
+
? ` ${YEL}· ${int(res.skipped)} unusable row(s) skipped${R}`
|
|
1860
|
+
: "") +
|
|
1861
|
+
(res.stopped ? ` ${YEL}(stopped early)${R}` : ""));
|
|
1862
|
+
if (!res.stopped) {
|
|
1863
|
+
try {
|
|
1864
|
+
totalBytesProcessed += statSync(path).size;
|
|
1865
|
+
}
|
|
1866
|
+
catch { /* best effort */ }
|
|
1867
|
+
if (downloaded) {
|
|
1868
|
+
try {
|
|
1869
|
+
unlinkSync(path);
|
|
1870
|
+
}
|
|
1871
|
+
catch { /* best effort */ }
|
|
1872
|
+
}
|
|
1873
|
+
done.add(f.id);
|
|
1874
|
+
p.completedFiles.push(f.id);
|
|
1875
|
+
}
|
|
1876
|
+
try {
|
|
1877
|
+
await saveProgress(store, {
|
|
1878
|
+
completedFiles: p.completedFiles,
|
|
1879
|
+
depositCount,
|
|
1880
|
+
trainedContentBytes,
|
|
1881
|
+
totalBytesProcessed,
|
|
1882
|
+
totalCorpusBytes,
|
|
1883
|
+
});
|
|
1884
|
+
await store.setMeta("train.langTally", JSON.stringify(langTally));
|
|
1885
|
+
}
|
|
1886
|
+
catch { /* best effort — finish() will retry */ }
|
|
1887
|
+
if (res.stopped)
|
|
1888
|
+
break; // cap/signal — leave file un-completed for resume
|
|
1889
|
+
}
|
|
1890
|
+
};
|
|
1891
|
+
// ── §10b Aya Dataset stage (runs AFTER SmolSent) ──
|
|
1892
|
+
//
|
|
1893
|
+
// Downloads the one train Parquet file and reads it row-group by row-group
|
|
1894
|
+
// (hyparquet + Snappy) — one (inputs → targets) fact per row. Marked complete
|
|
1895
|
+
// only when fully consumed; an interrupted run re-reads from the top on resume
|
|
1896
|
+
// (re-deposition is idempotent). LOCAL_PATH may hold a pre-downloaded *.parquet.
|
|
1897
|
+
const ayaToItems = (row) => {
|
|
1898
|
+
const r = toAyaRow(row);
|
|
1899
|
+
return r ? ayaRowToItems(r) : null;
|
|
1900
|
+
};
|
|
1901
|
+
const trainAya = async () => {
|
|
1902
|
+
if (!AYA)
|
|
1903
|
+
return;
|
|
1904
|
+
if (trainedContentBytes >= MAX_BYTES || stopRequested)
|
|
1905
|
+
return;
|
|
1906
|
+
const p = await loadProgress(store);
|
|
1907
|
+
if (p.completedFiles.includes(AYA_ID)) {
|
|
1908
|
+
progress.log(` ${DIM}· Aya Dataset already trained — skipping${R}`);
|
|
1909
|
+
return;
|
|
1910
|
+
}
|
|
1911
|
+
let path = "", downloaded = false;
|
|
1912
|
+
if (LOCAL_PATH) {
|
|
1913
|
+
const hit = readdirSync(LOCAL_PATH).find((f) => /aya.*\.parquet$/i.test(f) || /\.parquet$/i.test(f));
|
|
1914
|
+
if (!hit) {
|
|
1915
|
+
progress.log(` ${DIM}· no Aya *.parquet in ${LOCAL_PATH} — skipping${R}`);
|
|
1916
|
+
return;
|
|
1917
|
+
}
|
|
1918
|
+
path = join(LOCAL_PATH, hit);
|
|
1919
|
+
}
|
|
1920
|
+
else {
|
|
1921
|
+
const got = await acquire(AYA_URL, "aya_train.parquet", "Aya Dataset");
|
|
1922
|
+
if (!got)
|
|
1923
|
+
return;
|
|
1924
|
+
path = got;
|
|
1925
|
+
downloaded = true;
|
|
1926
|
+
}
|
|
1927
|
+
try {
|
|
1928
|
+
totalCorpusBytes += statSync(path).size;
|
|
1929
|
+
}
|
|
1930
|
+
catch { /* best effort */ }
|
|
1931
|
+
state.fileTotal = 1;
|
|
1932
|
+
state.fileIndex = 1;
|
|
1933
|
+
state.activity = "process";
|
|
1934
|
+
state.filePath = "Aya Dataset";
|
|
1935
|
+
state.fileExamples = 0;
|
|
1936
|
+
tick(true);
|
|
1937
|
+
const p0 = Date.now();
|
|
1938
|
+
let res;
|
|
1939
|
+
try {
|
|
1940
|
+
res = await processParquet(path, ayaToItems, ci, onDeposit, sample);
|
|
1941
|
+
}
|
|
1942
|
+
catch (e) {
|
|
1943
|
+
if (stopRequested || e?.name === "AbortError")
|
|
1944
|
+
return;
|
|
1945
|
+
progress.log(` ${RED}✗${R} Aya processing failed: ${e.message}`);
|
|
1946
|
+
return;
|
|
1947
|
+
}
|
|
1948
|
+
langTally["aya"] = (langTally["aya"] ?? 0) + res.examples;
|
|
1949
|
+
progress.log(` ${GRN}✓${R} Aya Dataset ${DIM}[multilingual chat]${R} → ${int(res.examples)} facts ${DIM}in ${dur((Date.now() - p0) / 1000)}${R}` +
|
|
1950
|
+
(res.skipped
|
|
1951
|
+
? ` ${YEL}· ${int(res.skipped)} unusable row(s) skipped${R}`
|
|
1952
|
+
: "") +
|
|
1953
|
+
(res.stopped ? ` ${YEL}(stopped early)${R}` : ""));
|
|
1954
|
+
if (!res.stopped) {
|
|
1955
|
+
try {
|
|
1956
|
+
totalBytesProcessed += statSync(path).size;
|
|
1957
|
+
}
|
|
1958
|
+
catch { /* best effort */ }
|
|
1959
|
+
if (downloaded) {
|
|
1960
|
+
try {
|
|
1961
|
+
unlinkSync(path);
|
|
1962
|
+
}
|
|
1963
|
+
catch { /* best effort */ }
|
|
1964
|
+
}
|
|
1965
|
+
p.completedFiles.push(AYA_ID);
|
|
1966
|
+
}
|
|
1967
|
+
try {
|
|
1968
|
+
await saveProgress(store, {
|
|
1969
|
+
completedFiles: p.completedFiles,
|
|
1970
|
+
depositCount,
|
|
1971
|
+
trainedContentBytes,
|
|
1972
|
+
totalBytesProcessed,
|
|
1973
|
+
totalCorpusBytes,
|
|
1974
|
+
});
|
|
1975
|
+
await store.setMeta("train.langTally", JSON.stringify(langTally));
|
|
1976
|
+
}
|
|
1977
|
+
catch { /* best effort — finish() will retry */ }
|
|
1978
|
+
};
|
|
1979
|
+
// ── §10c oasst2 stage (multi-turn conversations; runs AFTER Aya; both modes) ──
|
|
1980
|
+
//
|
|
1981
|
+
// Resolves the source (a local *trees*.jsonl.gz in
|
|
1982
|
+
// LOCAL_PATH, else the gzip downloaded to the cache), streams it, and marks
|
|
1983
|
+
// OASST_ID complete only when fully consumed (an interrupted run re-streams
|
|
1984
|
+
// from the top; re-deposition is idempotent). Only multi-turn conversations
|
|
1985
|
+
// are deposited — single Q→A trees are skipped inside processOasst.
|
|
1986
|
+
const trainOasst = async () => {
|
|
1987
|
+
if (!OASST)
|
|
1988
|
+
return;
|
|
1989
|
+
if (trainedContentBytes >= MAX_BYTES || stopRequested)
|
|
1990
|
+
return;
|
|
1991
|
+
const p = await loadProgress(store);
|
|
1992
|
+
if (p.completedFiles.includes(OASST_ID)) {
|
|
1993
|
+
progress.log(` ${DIM}· oasst2 already trained — skipping${R}`);
|
|
1994
|
+
return;
|
|
1995
|
+
}
|
|
1996
|
+
let gzPath = "";
|
|
1997
|
+
let downloaded = false;
|
|
1998
|
+
if (LOCAL_PATH) {
|
|
1999
|
+
const hit = readdirSync(LOCAL_PATH).find((f) => /oasst.*trees.*\.jsonl\.gz$/i.test(f) || /oasst.*\.jsonl\.gz$/i.test(f));
|
|
2000
|
+
if (!hit) {
|
|
2001
|
+
progress.log(` ${DIM}· no oasst2 *trees*.jsonl.gz in ${LOCAL_PATH} — skipping${R}`);
|
|
2002
|
+
return;
|
|
2003
|
+
}
|
|
2004
|
+
gzPath = join(LOCAL_PATH, hit);
|
|
2005
|
+
}
|
|
2006
|
+
else {
|
|
2007
|
+
const dest = join(CACHE_DIR, "oasst2_ready.trees.jsonl.gz");
|
|
2008
|
+
if (existsSync(dest)) {
|
|
2009
|
+
gzPath = dest; // reuse a copy left by a previous interrupted run
|
|
2010
|
+
progress.log(` ${GRN}✓${R} oasst2 trees ${DIM}(cached)${R}`);
|
|
2011
|
+
}
|
|
2012
|
+
else {
|
|
2013
|
+
let size = 0;
|
|
2014
|
+
try {
|
|
2015
|
+
size = await headSize(OASST_URL);
|
|
2016
|
+
}
|
|
2017
|
+
catch { /* unknown — proceed without a cache-room reservation */ }
|
|
2018
|
+
state.activity = "download";
|
|
2019
|
+
state.filePath = "oasst2 trees";
|
|
2020
|
+
state.fileSize = size;
|
|
2021
|
+
const slot = { done: 0, total: size, t0: Date.now() };
|
|
2022
|
+
dlSlot = slot;
|
|
2023
|
+
tick(true);
|
|
2024
|
+
try {
|
|
2025
|
+
await ensureCacheRoom(size, cacheWarn);
|
|
2026
|
+
slot.t0 = Date.now();
|
|
2027
|
+
await downloadFile(OASST_URL, dest, DOWNLOAD_TRIES, (n, e) => progress.log(` ${YEL}⚠${R} oasst2 download attempt ${n}/${DOWNLOAD_TRIES}: ${e.message}`), (done, total) => {
|
|
2028
|
+
slot.done = done;
|
|
2029
|
+
if (total > 0)
|
|
2030
|
+
slot.total = total;
|
|
2031
|
+
});
|
|
2032
|
+
}
|
|
2033
|
+
catch (e) {
|
|
2034
|
+
dlSlot = null;
|
|
2035
|
+
if (stopRequested || e?.name === "AbortError")
|
|
2036
|
+
return;
|
|
2037
|
+
progress.log(` ${RED}✗${R} oasst2 download failed: ${e.message}`);
|
|
2038
|
+
try {
|
|
2039
|
+
unlinkSync(dest);
|
|
2040
|
+
}
|
|
2041
|
+
catch { /* best effort */ }
|
|
2042
|
+
return;
|
|
2043
|
+
}
|
|
2044
|
+
dlSlot = null;
|
|
2045
|
+
const dlS = Math.max(0.001, (Date.now() - slot.t0) / 1000);
|
|
2046
|
+
const sz = statSync(dest).size;
|
|
2047
|
+
progress.log(` ${CYAN}⬇${R} oasst2 trees ${bytes(sz)} ` +
|
|
2048
|
+
`${DIM}${dur(dlS)} @ ${bytes(sz / dlS)}/s${R}`);
|
|
2049
|
+
gzPath = dest;
|
|
2050
|
+
downloaded = true;
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
try {
|
|
2054
|
+
totalCorpusBytes += statSync(gzPath).size;
|
|
2055
|
+
}
|
|
2056
|
+
catch { /* best effort */ }
|
|
2057
|
+
state.fileTotal = 1;
|
|
2058
|
+
state.fileIndex = 1;
|
|
2059
|
+
// Stream the trees.
|
|
2060
|
+
state.activity = "process";
|
|
2061
|
+
state.filePath = "oasst2 (multi-turn)";
|
|
2062
|
+
state.fileExamples = 0;
|
|
2063
|
+
tick(true);
|
|
2064
|
+
const p0 = Date.now();
|
|
2065
|
+
let result;
|
|
2066
|
+
try {
|
|
2067
|
+
result = await processOasst(gzPath, ci, onDeposit, sample);
|
|
2068
|
+
}
|
|
2069
|
+
catch (e) {
|
|
2070
|
+
if (stopRequested || e?.name === "AbortError")
|
|
2071
|
+
return;
|
|
2072
|
+
progress.log(` ${RED}✗${R} oasst2 processing failed: ${e.message}`);
|
|
2073
|
+
return;
|
|
2074
|
+
}
|
|
2075
|
+
const { examples, stopped, skipped, multi } = result;
|
|
2076
|
+
langTally["oasst2"] = (langTally["oasst2"] ?? 0) + examples;
|
|
2077
|
+
progress.log(` ${GRN}✓${R} oasst2 ${DIM}[multi-turn chat]${R} → ${int(examples)} examples from ${int(multi)} conversation(s) ${DIM}in ${dur((Date.now() - p0) / 1000)}${R}` +
|
|
2078
|
+
(skipped
|
|
2079
|
+
? ` ${YEL}· ${int(skipped)} malformed line(s) skipped${R}`
|
|
2080
|
+
: "") +
|
|
2081
|
+
(stopped ? ` ${YEL}(stopped early)${R}` : ""));
|
|
2082
|
+
// Only mark complete (and reclaim the cache) when fully consumed.
|
|
2083
|
+
if (!stopped) {
|
|
2084
|
+
try {
|
|
2085
|
+
totalBytesProcessed += statSync(gzPath).size;
|
|
2086
|
+
}
|
|
2087
|
+
catch { /* best effort */ }
|
|
2088
|
+
if (downloaded) {
|
|
2089
|
+
try {
|
|
2090
|
+
unlinkSync(gzPath);
|
|
2091
|
+
}
|
|
2092
|
+
catch { /* best effort */ }
|
|
2093
|
+
}
|
|
2094
|
+
p.completedFiles.push(OASST_ID);
|
|
2095
|
+
}
|
|
2096
|
+
try {
|
|
2097
|
+
await saveProgress(store, {
|
|
2098
|
+
completedFiles: p.completedFiles,
|
|
2099
|
+
depositCount,
|
|
2100
|
+
trainedContentBytes,
|
|
2101
|
+
totalBytesProcessed,
|
|
2102
|
+
totalCorpusBytes,
|
|
2103
|
+
});
|
|
2104
|
+
await store.setMeta("train.langTally", JSON.stringify(langTally));
|
|
2105
|
+
}
|
|
2106
|
+
catch { /* best effort — finish() will retry */ }
|
|
2107
|
+
};
|
|
2108
|
+
// ── §10d General-Knowledge stage (runs AFTER oasst2) ──
|
|
2109
|
+
//
|
|
2110
|
+
// Downloads the single JSON-array file (output.json) and deposits each
|
|
2111
|
+
// {Question, Answer} as one fact. Marked complete only when fully consumed.
|
|
2112
|
+
// LOCAL_PATH may hold a pre-downloaded *.json.
|
|
2113
|
+
const genToItems = (row) => {
|
|
2114
|
+
const r = toGenKnowRow(row);
|
|
2115
|
+
return r ? genKnowRowToItems(r) : null;
|
|
2116
|
+
};
|
|
2117
|
+
const trainGenKnow = async () => {
|
|
2118
|
+
if (!GENKNOW)
|
|
2119
|
+
return;
|
|
2120
|
+
if (trainedContentBytes >= MAX_BYTES || stopRequested)
|
|
2121
|
+
return;
|
|
2122
|
+
const p = await loadProgress(store);
|
|
2123
|
+
if (p.completedFiles.includes(GENKNOW_ID)) {
|
|
2124
|
+
progress.log(` ${DIM}· General-Knowledge already trained — skipping${R}`);
|
|
2125
|
+
return;
|
|
2126
|
+
}
|
|
2127
|
+
let path = "", downloaded = false;
|
|
2128
|
+
if (LOCAL_PATH) {
|
|
2129
|
+
const hit = readdirSync(LOCAL_PATH).find((f) => /general.*knowledge.*\.json$/i.test(f) || /output\.json$/i.test(f));
|
|
2130
|
+
if (!hit) {
|
|
2131
|
+
progress.log(` ${DIM}· no General-Knowledge *.json in ${LOCAL_PATH} — skipping${R}`);
|
|
2132
|
+
return;
|
|
2133
|
+
}
|
|
2134
|
+
path = join(LOCAL_PATH, hit);
|
|
2135
|
+
}
|
|
2136
|
+
else {
|
|
2137
|
+
const got = await acquire(GENKNOW_URL, "general_knowledge.json", "General-Knowledge");
|
|
2138
|
+
if (!got)
|
|
2139
|
+
return;
|
|
2140
|
+
path = got;
|
|
2141
|
+
downloaded = true;
|
|
2142
|
+
}
|
|
2143
|
+
try {
|
|
2144
|
+
totalCorpusBytes += statSync(path).size;
|
|
2145
|
+
}
|
|
2146
|
+
catch { /* best effort */ }
|
|
2147
|
+
state.fileTotal = 1;
|
|
2148
|
+
state.fileIndex = 1;
|
|
2149
|
+
state.activity = "process";
|
|
2150
|
+
state.filePath = "General-Knowledge";
|
|
2151
|
+
state.fileExamples = 0;
|
|
2152
|
+
tick(true);
|
|
2153
|
+
const p0 = Date.now();
|
|
2154
|
+
let res;
|
|
2155
|
+
try {
|
|
2156
|
+
res = await processJsonArray(path, genToItems, ci, onDeposit, sample);
|
|
2157
|
+
}
|
|
2158
|
+
catch (e) {
|
|
2159
|
+
if (stopRequested || e?.name === "AbortError")
|
|
2160
|
+
return;
|
|
2161
|
+
progress.log(` ${RED}✗${R} General-Knowledge processing failed: ${e.message}`);
|
|
2162
|
+
return;
|
|
2163
|
+
}
|
|
2164
|
+
langTally["genknow"] = (langTally["genknow"] ?? 0) + res.examples;
|
|
2165
|
+
progress.log(` ${GRN}✓${R} General-Knowledge ${DIM}[Q&A facts]${R} → ${int(res.examples)} facts ${DIM}in ${dur((Date.now() - p0) / 1000)}${R}` +
|
|
2166
|
+
(res.skipped
|
|
2167
|
+
? ` ${YEL}· ${int(res.skipped)} unusable row(s) skipped${R}`
|
|
2168
|
+
: "") +
|
|
2169
|
+
(res.stopped ? ` ${YEL}(stopped early)${R}` : ""));
|
|
2170
|
+
if (!res.stopped) {
|
|
2171
|
+
try {
|
|
2172
|
+
totalBytesProcessed += statSync(path).size;
|
|
2173
|
+
}
|
|
2174
|
+
catch { /* best effort */ }
|
|
2175
|
+
if (downloaded) {
|
|
2176
|
+
try {
|
|
2177
|
+
unlinkSync(path);
|
|
2178
|
+
}
|
|
2179
|
+
catch { /* best effort */ }
|
|
2180
|
+
}
|
|
2181
|
+
p.completedFiles.push(GENKNOW_ID);
|
|
2182
|
+
}
|
|
2183
|
+
try {
|
|
2184
|
+
await saveProgress(store, {
|
|
2185
|
+
completedFiles: p.completedFiles,
|
|
2186
|
+
depositCount,
|
|
2187
|
+
trainedContentBytes,
|
|
2188
|
+
totalBytesProcessed,
|
|
2189
|
+
totalCorpusBytes,
|
|
2190
|
+
});
|
|
2191
|
+
await store.setMeta("train.langTally", JSON.stringify(langTally));
|
|
2192
|
+
}
|
|
2193
|
+
catch { /* best effort — finish() will retry */ }
|
|
2194
|
+
};
|
|
2195
|
+
// ── §10 Train the curriculum (resume-aware; one store records all stages) ──
|
|
2196
|
+
//
|
|
2197
|
+
// Every source is paged from an HTTP API (SmolSent, Aya) or a single
|
|
2198
|
+
// downloaded file (oasst2) — there is no per-file ZIP loop. Each stage closure
|
|
2199
|
+
// reads the authoritative completed-set from the store, skips itself when
|
|
2200
|
+
// already done, and persists its own progress, so the whole curriculum resumes
|
|
2201
|
+
// from the store alone. LOCAL_PATH lets oasst2 read a local *.jsonl.gz.
|
|
2202
|
+
tick(true);
|
|
2203
|
+
// ── resume — restore counters and the per-source tally from the store ──
|
|
2204
|
+
const prog = await loadProgress(store);
|
|
2205
|
+
depositCount = prog.depositCount;
|
|
2206
|
+
trainedContentBytes = prog.trainedContentBytes;
|
|
2207
|
+
totalBytesProcessed = prog.totalBytesProcessed;
|
|
2208
|
+
totalCorpusBytes = prog.totalCorpusBytes;
|
|
2209
|
+
rateTrained = trainedContentBytes;
|
|
2210
|
+
rateBytes = totalBytesProcessed;
|
|
2211
|
+
try {
|
|
2212
|
+
const t = await store.getMeta("train.langTally");
|
|
2213
|
+
if (t) {
|
|
2214
|
+
const parsed = JSON.parse(t);
|
|
2215
|
+
if (parsed && typeof parsed === "object") {
|
|
2216
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
2217
|
+
langTally[k] = Number(v) || 0;
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
catch { /* fresh tally */ }
|
|
2223
|
+
if (prog.completedFiles.length > 0) {
|
|
2224
|
+
progress.log(` ${CYAN}↻${R} resuming: ${prog.completedFiles.length} stage-unit(s) done, ` +
|
|
2225
|
+
`${int(depositCount)} examples, ${bytes(trainedContentBytes)} learned`);
|
|
2226
|
+
}
|
|
2227
|
+
// Stage 1 (SmolSent translation facts), 2 (Aya multilingual chat), 3 (oasst2
|
|
2228
|
+
// multi-turn), 4 (General-Knowledge Q&A facts). Each is skipped on a resume
|
|
2229
|
+
// that already finished it.
|
|
2230
|
+
if (!stopRequested)
|
|
2231
|
+
await trainSmolSent();
|
|
2232
|
+
if (!stopRequested)
|
|
2233
|
+
await trainAya();
|
|
2234
|
+
if (!stopRequested)
|
|
2235
|
+
await trainOasst();
|
|
2236
|
+
if (!stopRequested)
|
|
2237
|
+
await trainGenKnow();
|
|
2238
|
+
await finish(stopRequested ? stopReason : "done");
|
|
2239
|
+
}
|
|
2240
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
2241
|
+
// §11 Entry point — only run when invoked directly, so importing the parser
|
|
2242
|
+
// functions above (e.g. for tests) never starts training.
|
|
2243
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
2244
|
+
const isMain = import.meta.url === `file://${process.argv[1]}` ||
|
|
2245
|
+
process.argv[1]?.endsWith("train_base.js");
|
|
2246
|
+
if (isMain) {
|
|
2247
|
+
main().catch((e) => {
|
|
2248
|
+
process.stderr.write(SHOW);
|
|
2249
|
+
console.error(`\n${RED}fatal:${R}`, e);
|
|
2250
|
+
process.exit(1);
|
|
2251
|
+
});
|
|
2252
|
+
}
|