taskforce-model-foundry 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/tmf.mjs +353 -0
- package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
- package/docs/acceptance/r1-r7-reconciliation.md +185 -0
- package/docs/integration.md +227 -0
- package/docs/tutorial.md +336 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
- package/integrations/hermes-plugin/tests/test_register.py +230 -0
- package/integrations/openclaw-plugin/index.mjs +27 -0
- package/integrations/openclaw-plugin/tools.mjs +70 -0
- package/openclaw.plugin.json +24 -0
- package/package.json +70 -4
- package/scripts/e2e-demo.sh +56 -0
- package/src/api.mjs +341 -0
- package/src/config.mjs +342 -0
- package/src/core/autograd.mjs +451 -0
- package/src/core/fsx.mjs +65 -0
- package/src/core/hash.mjs +47 -0
- package/src/core/rng.mjs +70 -0
- package/src/data/clean.mjs +115 -0
- package/src/data/dedupe.mjs +125 -0
- package/src/data/ingest.mjs +184 -0
- package/src/data/pii.mjs +142 -0
- package/src/data/pipeline.mjs +183 -0
- package/src/data/provenance.mjs +88 -0
- package/src/data/split.mjs +193 -0
- package/src/data/synth.mjs +198 -0
- package/src/eval/evaluator.mjs +124 -0
- package/src/eval/gates.mjs +114 -0
- package/src/eval/metrics.mjs +90 -0
- package/src/export/package.mjs +365 -0
- package/src/index.mjs +26 -0
- package/src/integrations/hermes.mjs +177 -0
- package/src/integrations/openclaw.mjs +154 -0
- package/src/jobs/evaluate.mjs +164 -0
- package/src/jobs/runner.mjs +323 -0
- package/src/jobs/train.mjs +303 -0
- package/src/model/lora.mjs +53 -0
- package/src/model/tokenizer.mjs +73 -0
- package/src/model/transformer.mjs +276 -0
- package/src/train/backends/builtin-js.mjs +367 -0
- package/src/train/backends/hf-peft.mjs +549 -0
- package/src/train/backends/hf_peft_runner.py +326 -0
- package/src/train/backends/index.mjs +92 -0
- package/src/train/dataset.mjs +56 -0
- package/src/train/optimizer.mjs +99 -0
- package/src/version.mjs +5 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Data pipeline: ingest -> clean -> sensitive-info policy -> quality -> dedupe
|
|
2
|
+
// -> provenance -> split -> leakage check -> report.
|
|
3
|
+
//
|
|
4
|
+
// Two rules shape the output. First, the report records counts and reasons but
|
|
5
|
+
// never the offending text, so an audit trail can be shared without re-leaking
|
|
6
|
+
// the data it is auditing. Second, the stage order puts redaction before
|
|
7
|
+
// dedupe and splitting, so a secret cannot survive by hiding in a duplicate.
|
|
8
|
+
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { sha256Json } from '../core/hash.mjs';
|
|
11
|
+
import { writeJsonl, writeJson, ensureDir } from '../core/fsx.mjs';
|
|
12
|
+
import { ingestAll } from './ingest.mjs';
|
|
13
|
+
import { cleanText, qualityReport, canonicalKey, DEFAULT_CLEAN_CONFIG, DEFAULT_QUALITY_CONFIG } from './clean.mjs';
|
|
14
|
+
import { applyPiiPolicy } from './pii.mjs';
|
|
15
|
+
import { NearDuplicateIndex, DEFAULT_DEDUPE_CONFIG, exactKey } from './dedupe.mjs';
|
|
16
|
+
import { summarizeProvenance, assertTrainableClassification, DEFAULT_TRAINABLE_CLASSIFICATIONS } from './provenance.mjs';
|
|
17
|
+
import { splitRecords, checkLeakage, DEFAULT_SPLIT_CONFIG, SPLIT_NAMES } from './split.mjs';
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_PIPELINE_CONFIG = {
|
|
20
|
+
clean: DEFAULT_CLEAN_CONFIG,
|
|
21
|
+
quality: DEFAULT_QUALITY_CONFIG,
|
|
22
|
+
dedupe: DEFAULT_DEDUPE_CONFIG,
|
|
23
|
+
split: DEFAULT_SPLIT_CONFIG,
|
|
24
|
+
pii: { policy: 'redact', blockSeverity: 'critical' },
|
|
25
|
+
allowedClassifications: DEFAULT_TRAINABLE_CLASSIFICATIONS,
|
|
26
|
+
failOnLeakage: true,
|
|
27
|
+
maxRecords: null,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function bump(map, key) {
|
|
31
|
+
map.set(key, (map.get(key) ?? 0) + 1);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function mapToObject(map) {
|
|
35
|
+
return Object.fromEntries([...map.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function runDataPipeline({ datasets, outDir, baseDir = process.cwd(), config = {}, onProgress } = {}) {
|
|
39
|
+
const cfg = {
|
|
40
|
+
...DEFAULT_PIPELINE_CONFIG,
|
|
41
|
+
...config,
|
|
42
|
+
clean: { ...DEFAULT_CLEAN_CONFIG, ...(config.clean ?? {}) },
|
|
43
|
+
quality: { ...DEFAULT_QUALITY_CONFIG, ...(config.quality ?? {}) },
|
|
44
|
+
dedupe: { ...DEFAULT_DEDUPE_CONFIG, ...(config.dedupe ?? {}) },
|
|
45
|
+
split: { ...DEFAULT_SPLIT_CONFIG, ...(config.split ?? {}) },
|
|
46
|
+
pii: { ...DEFAULT_PIPELINE_CONFIG.pii, ...(config.pii ?? {}) },
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const ingested = await ingestAll(datasets, { baseDir });
|
|
50
|
+
onProgress?.({ stage: 'ingest', records: ingested.records.length, errors: ingested.errors.length });
|
|
51
|
+
|
|
52
|
+
const stageCounts = { ingested: ingested.records.length, cleaned: 0, piiRedacted: 0, piiDropped: 0, qualityDropped: 0, exactDuplicates: 0, nearDuplicates: 0, accepted: 0 };
|
|
53
|
+
const dropReasons = new Map();
|
|
54
|
+
const piiKinds = new Map();
|
|
55
|
+
const piiSeverities = new Map();
|
|
56
|
+
const cleanOps = new Map();
|
|
57
|
+
|
|
58
|
+
const accepted = [];
|
|
59
|
+
const seenExact = new Map();
|
|
60
|
+
const nearIndex = cfg.dedupe.nearDuplicates ? new NearDuplicateIndex(cfg.dedupe) : null;
|
|
61
|
+
|
|
62
|
+
for (const record of ingested.records) {
|
|
63
|
+
if (cfg.maxRecords && accepted.length >= cfg.maxRecords) break;
|
|
64
|
+
|
|
65
|
+
const cleanedPrompt = record.prompt === null ? null : cleanText(record.prompt, cfg.clean);
|
|
66
|
+
const cleanedCompletion = record.completion === null ? null : cleanText(record.completion, { ...cfg.clean, trim: false });
|
|
67
|
+
const cleanedText = cleanText(record.text, cfg.clean);
|
|
68
|
+
for (const op of new Set([...(cleanedPrompt?.applied ?? []), ...(cleanedCompletion?.applied ?? []), ...cleanedText.applied])) bump(cleanOps, op);
|
|
69
|
+
stageCounts.cleaned += 1;
|
|
70
|
+
|
|
71
|
+
// Sensitive-info policy runs on the full record text so a secret split
|
|
72
|
+
// across prompt and completion is still caught.
|
|
73
|
+
let pii;
|
|
74
|
+
try {
|
|
75
|
+
pii = applyPiiPolicy(cleanedText.text, cfg.pii);
|
|
76
|
+
} catch (err) {
|
|
77
|
+
// policy: 'fail' aborts the job; surface which record without the content.
|
|
78
|
+
err.recordId = record.id;
|
|
79
|
+
err.source = record.source;
|
|
80
|
+
throw err;
|
|
81
|
+
}
|
|
82
|
+
for (const finding of pii.findings) {
|
|
83
|
+
bump(piiKinds, finding.kind);
|
|
84
|
+
bump(piiSeverities, finding.severity);
|
|
85
|
+
}
|
|
86
|
+
if (pii.action === 'drop') {
|
|
87
|
+
stageCounts.piiDropped += 1;
|
|
88
|
+
bump(dropReasons, `pii_${pii.worst}`);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let prompt = cleanedPrompt?.text ?? null;
|
|
93
|
+
let completion = cleanedCompletion?.text ?? null;
|
|
94
|
+
let text = cleanedText.text;
|
|
95
|
+
if (pii.action === 'redact' && pii.findings.length > 0) {
|
|
96
|
+
stageCounts.piiRedacted += 1;
|
|
97
|
+
text = pii.text;
|
|
98
|
+
if (prompt !== null) prompt = applyPiiPolicy(prompt, cfg.pii).text;
|
|
99
|
+
if (completion !== null) completion = applyPiiPolicy(completion, cfg.pii).text;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const quality = qualityReport(text, cfg.quality);
|
|
103
|
+
if (!quality.ok) {
|
|
104
|
+
stageCounts.qualityDropped += 1;
|
|
105
|
+
for (const reason of quality.reasons) bump(dropReasons, `quality_${reason.split('(')[0]}`);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const key = exactKey(text);
|
|
110
|
+
if (seenExact.has(key)) {
|
|
111
|
+
stageCounts.exactDuplicates += 1;
|
|
112
|
+
bump(dropReasons, 'exact_duplicate');
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (nearIndex) {
|
|
117
|
+
const { signature, match } = nearIndex.query(text);
|
|
118
|
+
if (match) {
|
|
119
|
+
stageCounts.nearDuplicates += 1;
|
|
120
|
+
bump(dropReasons, 'near_duplicate');
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
nearIndex.add(record.id, text, signature);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
seenExact.set(key, record.id);
|
|
127
|
+
accepted.push({
|
|
128
|
+
id: record.id,
|
|
129
|
+
prompt,
|
|
130
|
+
completion,
|
|
131
|
+
text,
|
|
132
|
+
source: record.source,
|
|
133
|
+
quality: { score: quality.score, chars: quality.metrics.chars },
|
|
134
|
+
piiRedacted: pii.action === 'redact' && pii.findings.length > 0,
|
|
135
|
+
canonicalPreviewHash: sha256Json({ key: canonicalKey(text) }).slice(0, 16),
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
stageCounts.accepted = accepted.length;
|
|
139
|
+
onProgress?.({ stage: 'filter', accepted: accepted.length });
|
|
140
|
+
|
|
141
|
+
assertTrainableClassification(accepted, cfg.allowedClassifications);
|
|
142
|
+
|
|
143
|
+
const splits = splitRecords(accepted, cfg.split);
|
|
144
|
+
const leakage = checkLeakage(splits, { dedupe: cfg.dedupe });
|
|
145
|
+
onProgress?.({ stage: 'split', sizes: Object.fromEntries(SPLIT_NAMES.map((n) => [n, splits[n].length])) });
|
|
146
|
+
|
|
147
|
+
if (cfg.failOnLeakage && !leakage.ok) {
|
|
148
|
+
const err = new Error(
|
|
149
|
+
`data pipeline aborted: leakage check failed (${leakage.counts.exact} exact, ${leakage.counts.near} near-duplicate across splits)`,
|
|
150
|
+
);
|
|
151
|
+
err.leakage = leakage;
|
|
152
|
+
throw err;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const provenance = summarizeProvenance(accepted);
|
|
156
|
+
const report = {
|
|
157
|
+
version: 1,
|
|
158
|
+
generatedAt: new Date().toISOString(),
|
|
159
|
+
configDigest: sha256Json(cfg),
|
|
160
|
+
datasets: ingested.datasets,
|
|
161
|
+
ingestErrors: ingested.errors.length,
|
|
162
|
+
ingestErrorSamples: ingested.errors.slice(0, 5).map((e) => ({ file: e.file, line: e.line, reason: e.reason })),
|
|
163
|
+
stageCounts,
|
|
164
|
+
dropReasons: mapToObject(dropReasons),
|
|
165
|
+
cleanOperations: mapToObject(cleanOps),
|
|
166
|
+
// Counts only: the matched values are never written to disk.
|
|
167
|
+
sensitiveInfo: { byKind: mapToObject(piiKinds), bySeverity: mapToObject(piiSeverities), policy: cfg.pii.policy },
|
|
168
|
+
provenance,
|
|
169
|
+
splits: Object.fromEntries(SPLIT_NAMES.map((n) => [n, splits[n].length])),
|
|
170
|
+
splitConfig: cfg.split,
|
|
171
|
+
leakage,
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
if (outDir) {
|
|
175
|
+
await ensureDir(outDir);
|
|
176
|
+
for (const name of SPLIT_NAMES) {
|
|
177
|
+
await writeJsonl(path.join(outDir, `${name}.jsonl`), splits[name]);
|
|
178
|
+
}
|
|
179
|
+
await writeJson(path.join(outDir, 'data-report.json'), report);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return { report, splits, provenance, accepted, config: cfg };
|
|
183
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Source and licence bookkeeping.
|
|
2
|
+
//
|
|
3
|
+
// Every accepted record carries the dataset it came from, the file and line it
|
|
4
|
+
// was read from, the declared licence and data classification, and a digest of
|
|
5
|
+
// the raw bytes. That record is what makes the exported lineage auditable: a
|
|
6
|
+
// reviewer can trace any trained adapter back to the exact inputs.
|
|
7
|
+
|
|
8
|
+
export const ALLOWED_CLASSIFICATIONS = ['public', 'internal', 'confidential', 'restricted'];
|
|
9
|
+
export const DEFAULT_TRAINABLE_CLASSIFICATIONS = ['public', 'internal', 'confidential'];
|
|
10
|
+
|
|
11
|
+
export function normalizeDatasetDescriptor(descriptor, index = 0) {
|
|
12
|
+
const name = descriptor.name ?? `dataset_${index}`;
|
|
13
|
+
if (!descriptor.path) throw new Error(`dataset "${name}" is missing a path`);
|
|
14
|
+
if (!descriptor.license) throw new Error(`dataset "${name}" is missing a license; provenance requires one`);
|
|
15
|
+
const classification = descriptor.classification ?? 'internal';
|
|
16
|
+
if (!ALLOWED_CLASSIFICATIONS.includes(classification)) {
|
|
17
|
+
throw new Error(`dataset "${name}" has unknown classification "${classification}"; allowed: ${ALLOWED_CLASSIFICATIONS.join(', ')}`);
|
|
18
|
+
}
|
|
19
|
+
return {
|
|
20
|
+
name,
|
|
21
|
+
path: descriptor.path,
|
|
22
|
+
format: descriptor.format ?? 'auto',
|
|
23
|
+
license: descriptor.license,
|
|
24
|
+
licenseUrl: descriptor.licenseUrl ?? null,
|
|
25
|
+
owner: descriptor.owner ?? null,
|
|
26
|
+
classification,
|
|
27
|
+
collectedAt: descriptor.collectedAt ?? null,
|
|
28
|
+
consentRef: descriptor.consentRef ?? null,
|
|
29
|
+
promptField: descriptor.promptField ?? 'prompt',
|
|
30
|
+
completionField: descriptor.completionField ?? 'completion',
|
|
31
|
+
textField: descriptor.textField ?? 'text',
|
|
32
|
+
tags: descriptor.tags ?? [],
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function sourceRecord(dataset, { file, line, rawSha256 }) {
|
|
37
|
+
return {
|
|
38
|
+
dataset: dataset.name,
|
|
39
|
+
file,
|
|
40
|
+
line,
|
|
41
|
+
rawSha256,
|
|
42
|
+
license: dataset.license,
|
|
43
|
+
licenseUrl: dataset.licenseUrl,
|
|
44
|
+
owner: dataset.owner,
|
|
45
|
+
classification: dataset.classification,
|
|
46
|
+
collectedAt: dataset.collectedAt,
|
|
47
|
+
consentRef: dataset.consentRef,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Aggregated licence/classification view for the model card and lineage file.
|
|
52
|
+
export function summarizeProvenance(records) {
|
|
53
|
+
const byDataset = new Map();
|
|
54
|
+
for (const record of records) {
|
|
55
|
+
const key = record.source.dataset;
|
|
56
|
+
if (!byDataset.has(key)) {
|
|
57
|
+
byDataset.set(key, {
|
|
58
|
+
dataset: key,
|
|
59
|
+
license: record.source.license,
|
|
60
|
+
licenseUrl: record.source.licenseUrl,
|
|
61
|
+
owner: record.source.owner,
|
|
62
|
+
classification: record.source.classification,
|
|
63
|
+
consentRef: record.source.consentRef,
|
|
64
|
+
records: 0,
|
|
65
|
+
files: new Set(),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const entry = byDataset.get(key);
|
|
69
|
+
entry.records += 1;
|
|
70
|
+
entry.files.add(record.source.file);
|
|
71
|
+
}
|
|
72
|
+
const datasets = [...byDataset.values()]
|
|
73
|
+
.map((e) => ({ ...e, files: [...e.files].sort() }))
|
|
74
|
+
.sort((a, b) => (a.dataset < b.dataset ? -1 : 1));
|
|
75
|
+
const licenses = [...new Set(datasets.map((d) => d.license))].sort();
|
|
76
|
+
const classifications = [...new Set(datasets.map((d) => d.classification))].sort();
|
|
77
|
+
return { datasets, licenses, classifications, totalRecords: records.length };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function assertTrainableClassification(records, allowed = DEFAULT_TRAINABLE_CLASSIFICATIONS) {
|
|
81
|
+
const violations = records.filter((r) => !allowed.includes(r.source.classification));
|
|
82
|
+
if (violations.length > 0) {
|
|
83
|
+
const kinds = [...new Set(violations.map((r) => r.source.classification))].join(', ');
|
|
84
|
+
throw new Error(
|
|
85
|
+
`${violations.length} record(s) carry a classification not permitted for training (${kinds}); allowed: ${allowed.join(', ')}`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Deterministic splitting plus leakage detection.
|
|
2
|
+
//
|
|
3
|
+
// Assignment is a hash of the record's canonical key, not its position, so the
|
|
4
|
+
// same record always lands in the same split no matter what order it was
|
|
5
|
+
// ingested in. That is what makes a re-run reproducible and makes "the holdout
|
|
6
|
+
// set never saw training" checkable rather than assumed.
|
|
7
|
+
|
|
8
|
+
import { sha256 } from '../core/hash.mjs';
|
|
9
|
+
import { canonicalKey } from './clean.mjs';
|
|
10
|
+
import { NearDuplicateIndex, DEFAULT_DEDUPE_CONFIG } from './dedupe.mjs';
|
|
11
|
+
|
|
12
|
+
export const SPLIT_NAMES = ['train', 'validation', 'holdout'];
|
|
13
|
+
|
|
14
|
+
// Kept equal to eval's MIN_EXACT_MATCH_SAMPLES on purpose: the data stage must
|
|
15
|
+
// not hand evaluation a holdout that evaluation will refuse to score.
|
|
16
|
+
export const MIN_SCORABLE_HOLDOUT = 10;
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_SPLIT_CONFIG = {
|
|
19
|
+
train: 0.7,
|
|
20
|
+
validation: 0.15,
|
|
21
|
+
holdout: 0.15,
|
|
22
|
+
seed: 'tmf-split-v1',
|
|
23
|
+
requireNonEmptyHoldout: true,
|
|
24
|
+
// A corpus mixes supervised pairs with plain documents, and only the pairs
|
|
25
|
+
// can be greedy-decoded and scored for exact match. Bucketing the mixed
|
|
26
|
+
// population by hash alone let the pairs land almost entirely in train:
|
|
27
|
+
// train-ws-full put 2 of ~40 pairs in a 25-record holdout, so exact match
|
|
28
|
+
// was an estimate over two samples. Strata are split independently and
|
|
29
|
+
// proportionally instead, so every holdout keeps its share of pairs.
|
|
30
|
+
stratify: true,
|
|
31
|
+
requireScorableHoldout: true,
|
|
32
|
+
// Stratification keeps the share, but a share of too few pairs is still too
|
|
33
|
+
// few: an exact-match rate over 2 samples is noise. This is the data-side
|
|
34
|
+
// half of eval's MIN_EXACT_MATCH_SAMPLES -- a corpus that cannot fill a
|
|
35
|
+
// scorable holdout fails here, while the job is cheap, instead of producing
|
|
36
|
+
// an unusable estimate after training. Unit fixtures that only exercise
|
|
37
|
+
// assignment pass 0 explicitly.
|
|
38
|
+
minScorableHoldout: MIN_SCORABLE_HOLDOUT,
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
function bucket(text, seed) {
|
|
42
|
+
// 32-bit prefix of the digest, mapped to [0,1).
|
|
43
|
+
const digest = sha256(`${seed}:${canonicalKey(text)}`);
|
|
44
|
+
return parseInt(digest.slice(0, 8), 16) / 0x100000000;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// A record is scorable when it carries a supervised pair; text-only rows can
|
|
48
|
+
// contribute loss but never exact match. This mirrors eval's isScorableRecord.
|
|
49
|
+
export function splitStratum(record) {
|
|
50
|
+
return typeof record?.prompt === 'string' && typeof record?.completion === 'string' ? 'pair' : 'text';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function assignByRatio(fraction, cfg) {
|
|
54
|
+
if (fraction < cfg.train) return 'train';
|
|
55
|
+
if (fraction < cfg.train + cfg.validation) return 'validation';
|
|
56
|
+
return 'holdout';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Proportional allocation inside one stratum. The hash still decides which
|
|
60
|
+
// record goes where -- records are ranked by their bucket value, not by input
|
|
61
|
+
// position -- but the rank, rather than the raw value, is compared against the
|
|
62
|
+
// ratios. That makes the per-stratum counts exact instead of binomial, which
|
|
63
|
+
// is what keeps a small pair population represented in holdout.
|
|
64
|
+
function assignStratum(records, cfg) {
|
|
65
|
+
const ranked = records
|
|
66
|
+
.map((record) => ({ record, b: bucket(record.text, cfg.seed), key: canonicalKey(record.text) }))
|
|
67
|
+
.sort((a, b) => (a.b - b.b) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
68
|
+
return ranked.map((entry, index) => ({
|
|
69
|
+
record: entry.record,
|
|
70
|
+
name: assignByRatio((index + 0.5) / ranked.length, cfg),
|
|
71
|
+
}));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function splitRecords(records, config = {}) {
|
|
75
|
+
const cfg = { ...DEFAULT_SPLIT_CONFIG, ...config };
|
|
76
|
+
const total = cfg.train + cfg.validation + cfg.holdout;
|
|
77
|
+
if (Math.abs(total - 1) > 1e-6) {
|
|
78
|
+
throw new Error(`split ratios must sum to 1, got ${total} (train=${cfg.train}, validation=${cfg.validation}, holdout=${cfg.holdout})`);
|
|
79
|
+
}
|
|
80
|
+
for (const name of SPLIT_NAMES) {
|
|
81
|
+
if (cfg[name] < 0) throw new Error(`split ratio "${name}" must not be negative`);
|
|
82
|
+
}
|
|
83
|
+
const splits = { train: [], validation: [], holdout: [] };
|
|
84
|
+
if (cfg.stratify) {
|
|
85
|
+
const strata = new Map();
|
|
86
|
+
for (const record of records) {
|
|
87
|
+
const stratum = splitStratum(record);
|
|
88
|
+
if (!strata.has(stratum)) strata.set(stratum, []);
|
|
89
|
+
strata.get(stratum).push(record);
|
|
90
|
+
}
|
|
91
|
+
for (const stratum of [...strata.keys()].sort()) {
|
|
92
|
+
for (const { record, name } of assignStratum(strata.get(stratum), cfg)) {
|
|
93
|
+
splits[name].push({ ...record, split: name, stratum });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
} else {
|
|
97
|
+
for (const record of records) {
|
|
98
|
+
const name = assignByRatio(bucket(record.text, cfg.seed), cfg);
|
|
99
|
+
splits[name].push({ ...record, split: name, stratum: splitStratum(record) });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (cfg.requireNonEmptyHoldout && splits.holdout.length === 0) {
|
|
103
|
+
throw new Error('holdout split is empty; evaluation would have nothing independent to measure against');
|
|
104
|
+
}
|
|
105
|
+
// A holdout with no supervised pair cannot produce an exact-match number at
|
|
106
|
+
// all, which is a silent hole in evaluation rather than a bad score.
|
|
107
|
+
if (cfg.requireScorableHoldout && cfg.holdout > 0) {
|
|
108
|
+
const pairsAvailable = records.some((r) => splitStratum(r) === 'pair');
|
|
109
|
+
const pairsHeldOut = splits.holdout.some((r) => splitStratum(r) === 'pair');
|
|
110
|
+
if (pairsAvailable && !pairsHeldOut) {
|
|
111
|
+
throw new Error('holdout split contains no supervised pair; exact match would have nothing to score');
|
|
112
|
+
}
|
|
113
|
+
const minScorable = cfg.minScorableHoldout ?? 0;
|
|
114
|
+
const scorable = splits.holdout.filter((r) => splitStratum(r) === 'pair').length;
|
|
115
|
+
if (pairsAvailable && scorable < minScorable) {
|
|
116
|
+
const pairs = records.filter((r) => splitStratum(r) === 'pair').length;
|
|
117
|
+
const needed = Math.ceil(minScorable / cfg.holdout);
|
|
118
|
+
throw new Error(
|
|
119
|
+
`holdout has ${scorable} scorable pair(s), below the minimum ${minScorable}: `
|
|
120
|
+
+ `the corpus carries ${pairs} supervised pair(s) and a ${cfg.holdout} holdout share, `
|
|
121
|
+
+ `so exact match would be an estimate over too few samples. `
|
|
122
|
+
+ `Supply at least ${needed} supervised pair(s), or set split.minScorableHoldout explicitly to accept the smaller sample.`,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return splits;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Cross-split contamination check. Exact matches are canonical-key collisions;
|
|
130
|
+
// near matches are MinHash/Jaccard hits above the dedupe threshold.
|
|
131
|
+
export function checkLeakage(splits, { dedupe = {}, checkNear = true } = {}) {
|
|
132
|
+
const cfg = { ...DEFAULT_DEDUPE_CONFIG, ...dedupe };
|
|
133
|
+
const exact = [];
|
|
134
|
+
const near = [];
|
|
135
|
+
|
|
136
|
+
const keyIndex = new Map();
|
|
137
|
+
for (const name of SPLIT_NAMES) {
|
|
138
|
+
for (const record of splits[name] ?? []) {
|
|
139
|
+
const key = canonicalKey(record.text);
|
|
140
|
+
if (!keyIndex.has(key)) keyIndex.set(key, []);
|
|
141
|
+
keyIndex.get(key).push({ split: name, id: record.id });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const [key, hits] of keyIndex) {
|
|
145
|
+
const splitsSeen = [...new Set(hits.map((h) => h.split))];
|
|
146
|
+
if (splitsSeen.length > 1) {
|
|
147
|
+
exact.push({ kind: 'exact', splits: splitsSeen.sort(), ids: hits.map((h) => h.id), keyPreview: key.slice(0, 48) });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (checkNear) {
|
|
152
|
+
// Index train+validation, then probe the holdout against it: the direction
|
|
153
|
+
// that matters is "did anything the model trained on reappear in holdout".
|
|
154
|
+
const index = new NearDuplicateIndex(cfg);
|
|
155
|
+
for (const name of ['train', 'validation']) {
|
|
156
|
+
for (const record of splits[name] ?? []) index.add(`${name}:${record.id}`, record.text);
|
|
157
|
+
}
|
|
158
|
+
for (const record of splits.holdout ?? []) {
|
|
159
|
+
const { match } = index.query(record.text);
|
|
160
|
+
if (match) {
|
|
161
|
+
near.push({
|
|
162
|
+
kind: 'near',
|
|
163
|
+
holdoutId: record.id,
|
|
164
|
+
matchedId: match.id,
|
|
165
|
+
similarity: Number(match.similarity.toFixed(4)),
|
|
166
|
+
threshold: cfg.threshold,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const findings = [...exact, ...near];
|
|
173
|
+
return {
|
|
174
|
+
ok: findings.length === 0,
|
|
175
|
+
exact,
|
|
176
|
+
near,
|
|
177
|
+
counts: { exact: exact.length, near: near.length },
|
|
178
|
+
checked: { train: splits.train?.length ?? 0, validation: splits.validation?.length ?? 0, holdout: splits.holdout?.length ?? 0 },
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function assertNoLeakage(splits, options = {}) {
|
|
183
|
+
const result = checkLeakage(splits, options);
|
|
184
|
+
if (!result.ok) {
|
|
185
|
+
const parts = [];
|
|
186
|
+
if (result.exact.length) parts.push(`${result.exact.length} exact overlap(s) across splits`);
|
|
187
|
+
if (result.near.length) parts.push(`${result.near.length} near-duplicate holdout record(s)`);
|
|
188
|
+
const err = new Error(`split leakage check failed: ${parts.join('; ')}`);
|
|
189
|
+
err.leakage = result;
|
|
190
|
+
throw err;
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// Synthetic corpus generator.
|
|
2
|
+
//
|
|
3
|
+
// Two corpora are produced from one seed:
|
|
4
|
+
//
|
|
5
|
+
// * a pretraining corpus of generic enterprise prose, used to fit the base
|
|
6
|
+
// model, and
|
|
7
|
+
// * a task corpus in an instruction format the base model has never seen,
|
|
8
|
+
// used for adapter post-training.
|
|
9
|
+
//
|
|
10
|
+
// Keeping the task format out of the pretraining distribution is deliberate:
|
|
11
|
+
// the gap between the two is what makes the post-training improvement real and
|
|
12
|
+
// measurable on a holdout set instead of a restatement of what the base already
|
|
13
|
+
// knew. Optional noise injection (duplicates, PII, junk records) exercises the
|
|
14
|
+
// data pipeline on inputs that actually need cleaning.
|
|
15
|
+
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { Rng } from '../core/rng.mjs';
|
|
18
|
+
import { writeJsonl, ensureDir } from '../core/fsx.mjs';
|
|
19
|
+
|
|
20
|
+
export const ROUTING_RULES = [
|
|
21
|
+
{ trigger: 'billing', queue: 'finance' },
|
|
22
|
+
{ trigger: 'outage', queue: 'platform' },
|
|
23
|
+
{ trigger: 'access', queue: 'security' },
|
|
24
|
+
{ trigger: 'hiring', queue: 'people' },
|
|
25
|
+
{ trigger: 'legal', queue: 'compliance' },
|
|
26
|
+
{ trigger: 'shipping', queue: 'logistics' },
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
export const PRIORITY_RULES = [
|
|
30
|
+
{ qualifier: 'critical', priority: 'p1' },
|
|
31
|
+
{ qualifier: 'urgent', priority: 'p1' },
|
|
32
|
+
{ qualifier: 'soon', priority: 'p2' },
|
|
33
|
+
{ qualifier: 'routine', priority: 'p3' },
|
|
34
|
+
{ qualifier: 'later', priority: 'p3' },
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
const NOUNS = ['refund', 'invoice', 'request', 'ticket', 'incident', 'review', 'renewal', 'audit', 'handoff', 'escalation'];
|
|
38
|
+
const TEAMS = ['finance', 'platform', 'security', 'people', 'compliance', 'logistics'];
|
|
39
|
+
const VERBS = ['reviewed', 'approved', 'escalated', 'closed', 'reopened', 'documented'];
|
|
40
|
+
const PERIODS = ['this week', 'last quarter', 'on monday', 'after standup', 'before the audit'];
|
|
41
|
+
|
|
42
|
+
export const TASK_PROMPT_HEADER = 'route\nsubject: ';
|
|
43
|
+
export const TASK_COMPLETION_PREFIX = '\nqueue=';
|
|
44
|
+
|
|
45
|
+
export function renderTaskPrompt(subject) {
|
|
46
|
+
return `${TASK_PROMPT_HEADER}${subject}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function renderTaskCompletion(queue, priority) {
|
|
50
|
+
return `${TASK_COMPLETION_PREFIX}${queue}\npriority=${priority}\n`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function expectedRouting(subject) {
|
|
54
|
+
const words = subject.trim().split(/\s+/);
|
|
55
|
+
const rule = ROUTING_RULES.find((r) => r.trigger === words[0]);
|
|
56
|
+
const priorityRule = PRIORITY_RULES.find((p) => words.includes(p.qualifier));
|
|
57
|
+
return {
|
|
58
|
+
queue: rule ? rule.queue : null,
|
|
59
|
+
priority: priorityRule ? priorityRule.priority : 'p3',
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function generateTaskRecords(count, seed = 'tmf-task') {
|
|
64
|
+
const rng = new Rng(seed);
|
|
65
|
+
const seen = new Set();
|
|
66
|
+
const out = [];
|
|
67
|
+
let guard = 0;
|
|
68
|
+
while (out.length < count && guard < count * 50) {
|
|
69
|
+
guard += 1;
|
|
70
|
+
const rule = rng.pick(ROUTING_RULES);
|
|
71
|
+
const priorityRule = rng.pick(PRIORITY_RULES);
|
|
72
|
+
const noun = rng.pick(NOUNS);
|
|
73
|
+
const extra = rng.pick(NOUNS);
|
|
74
|
+
const subject = `${rule.trigger} ${noun} ${priorityRule.qualifier} ${extra}`;
|
|
75
|
+
if (seen.has(subject)) continue;
|
|
76
|
+
seen.add(subject);
|
|
77
|
+
out.push({
|
|
78
|
+
prompt: renderTaskPrompt(subject),
|
|
79
|
+
completion: renderTaskCompletion(rule.queue, priorityRule.priority),
|
|
80
|
+
meta: { subject, queue: rule.queue, priority: priorityRule.priority },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function generatePretrainDocs(count, seed = 'tmf-pretrain') {
|
|
87
|
+
const rng = new Rng(seed);
|
|
88
|
+
const out = [];
|
|
89
|
+
for (let i = 0; i < count; i += 1) {
|
|
90
|
+
const sentences = [];
|
|
91
|
+
const n = 2 + rng.int(2);
|
|
92
|
+
for (let s = 0; s < n; s += 1) {
|
|
93
|
+
const team = rng.pick(TEAMS);
|
|
94
|
+
const noun = rng.pick(NOUNS);
|
|
95
|
+
const verb = rng.pick(VERBS);
|
|
96
|
+
const trigger = rng.pick(ROUTING_RULES).trigger;
|
|
97
|
+
const period = rng.pick(PERIODS);
|
|
98
|
+
sentences.push(`the ${team} team ${verb} the ${trigger} ${noun} ${period}.`);
|
|
99
|
+
}
|
|
100
|
+
out.push({ text: sentences.join(' ') });
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Records that must be caught by the pipeline rather than trained on.
|
|
106
|
+
export function generateNoisyRecords(taskRecords, seed = 'tmf-noise') {
|
|
107
|
+
const rng = new Rng(seed);
|
|
108
|
+
const out = [];
|
|
109
|
+
const pick = (i) => taskRecords[i % taskRecords.length];
|
|
110
|
+
|
|
111
|
+
// Exact duplicates.
|
|
112
|
+
for (let i = 0; i < 6; i += 1) {
|
|
113
|
+
const base = pick(i * 3);
|
|
114
|
+
out.push({ ...base, meta: { ...base.meta, injected: 'exact_duplicate' } });
|
|
115
|
+
}
|
|
116
|
+
// Cosmetic re-submissions: different casing and spacing, identical content.
|
|
117
|
+
// These collapse onto the same canonical key, so the exact path catches them.
|
|
118
|
+
for (let i = 0; i < 4; i += 1) {
|
|
119
|
+
const base = pick(i * 5 + 1);
|
|
120
|
+
out.push({
|
|
121
|
+
prompt: base.prompt.replace('subject: ', 'subject: ').toUpperCase(),
|
|
122
|
+
completion: base.completion,
|
|
123
|
+
meta: { ...base.meta, injected: 'cosmetic_duplicate' },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
// A long record re-submitted with a typo. The canonical keys differ, so only
|
|
127
|
+
// the MinHash/Jaccard path can catch this one.
|
|
128
|
+
const longRecord =
|
|
129
|
+
'the finance team reviewed the billing refund escalation this week and the '
|
|
130
|
+
+ 'compliance team documented the legal audit before the renewal handoff';
|
|
131
|
+
out.push({ text: longRecord, meta: { injected: 'long_record' } });
|
|
132
|
+
out.push({ text: longRecord.replace('documented', 'documentd'), meta: { injected: 'near_duplicate' } });
|
|
133
|
+
// Records carrying sensitive data.
|
|
134
|
+
const piiSamples = [
|
|
135
|
+
'reach the owner at ops.lead@contoso.example for the billing refund urgent case',
|
|
136
|
+
'customer phone 13800138000 asked about the shipping invoice routine handoff',
|
|
137
|
+
'service token sk-abcdefghijklmnopqrstuvwx must be rotated before the access audit soon',
|
|
138
|
+
'card 4111111111111111 was declined during the billing renewal critical escalation',
|
|
139
|
+
];
|
|
140
|
+
for (const sample of piiSamples) {
|
|
141
|
+
out.push({ prompt: renderTaskPrompt(sample), completion: renderTaskCompletion('finance', 'p3'), meta: { injected: 'pii' } });
|
|
142
|
+
}
|
|
143
|
+
// Junk records: too short, repetitive, placeholder.
|
|
144
|
+
out.push({ text: 'ok', meta: { injected: 'too_short' } });
|
|
145
|
+
out.push({ text: 'ab'.repeat(40), meta: { injected: 'repetitive' } });
|
|
146
|
+
out.push({ text: 'lorem ipsum dolor sit amet placeholder body', meta: { injected: 'placeholder' } });
|
|
147
|
+
return rng.shuffled(out);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function writeSyntheticCorpus(dir, options = {}) {
|
|
151
|
+
const {
|
|
152
|
+
taskCount = 240,
|
|
153
|
+
pretrainCount = 160,
|
|
154
|
+
seed = 'tmf-demo',
|
|
155
|
+
includeNoise = true,
|
|
156
|
+
} = options;
|
|
157
|
+
await ensureDir(dir);
|
|
158
|
+
const task = generateTaskRecords(taskCount, `${seed}:task`);
|
|
159
|
+
const pretrain = generatePretrainDocs(pretrainCount, `${seed}:pretrain`);
|
|
160
|
+
const noise = includeNoise ? generateNoisyRecords(task, `${seed}:noise`) : [];
|
|
161
|
+
|
|
162
|
+
const taskFile = path.join(dir, 'tickets.jsonl');
|
|
163
|
+
const pretrainFile = path.join(dir, 'corpus.jsonl');
|
|
164
|
+
await writeJsonl(taskFile, [...task, ...noise]);
|
|
165
|
+
await writeJsonl(pretrainFile, pretrain);
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
dir,
|
|
169
|
+
seed,
|
|
170
|
+
files: { task: taskFile, pretrain: pretrainFile },
|
|
171
|
+
counts: { task: task.length, pretrain: pretrain.length, noise: noise.length },
|
|
172
|
+
datasets: [
|
|
173
|
+
{
|
|
174
|
+
name: 'support-tickets-synthetic',
|
|
175
|
+
path: taskFile,
|
|
176
|
+
format: 'jsonl',
|
|
177
|
+
license: 'CC0-1.0',
|
|
178
|
+
owner: 'taskforce-model-foundry/synthetic',
|
|
179
|
+
classification: 'internal',
|
|
180
|
+
collectedAt: null,
|
|
181
|
+
consentRef: 'synthetic-no-consent-required',
|
|
182
|
+
tags: ['synthetic', 'routing'],
|
|
183
|
+
},
|
|
184
|
+
],
|
|
185
|
+
pretrainDatasets: [
|
|
186
|
+
{
|
|
187
|
+
name: 'enterprise-prose-synthetic',
|
|
188
|
+
path: pretrainFile,
|
|
189
|
+
format: 'jsonl',
|
|
190
|
+
license: 'CC0-1.0',
|
|
191
|
+
owner: 'taskforce-model-foundry/synthetic',
|
|
192
|
+
classification: 'internal',
|
|
193
|
+
consentRef: 'synthetic-no-consent-required',
|
|
194
|
+
tags: ['synthetic', 'pretrain'],
|
|
195
|
+
},
|
|
196
|
+
],
|
|
197
|
+
};
|
|
198
|
+
}
|