harness-everything 1.3.2 → 1.5.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/release.yml +23 -6
- package/CHANGELOG.md +42 -0
- package/RELEASING.md +2 -0
- package/ci/fixtures/system-one-colab-fit-layer-sitecustomize.py +72 -0
- package/ci/mechanism-2x-release-automation.test.js +17 -0
- package/ci/mechanism-system-one-colab.test.js +528 -0
- package/ci/mechanism-system-one-contract.test.js +30 -0
- package/ci/mechanism-system-one-curves.test.js +85 -0
- package/ci/mechanism-system-one-cycle.test.js +344 -34
- package/ci/mechanism-system-one-install.test.js +47 -0
- package/ci/mechanism-system-one-provider.test.js +2 -0
- package/ci/mechanism-system-one-resident.test.js +69 -0
- package/ci/system-one-adapter-test.py +86 -0
- package/ci/system-one-fit-layer-test.py +371 -0
- package/ci/system-one-layer-test.py +122 -0
- package/ci/system-one-train-test.py +26 -0
- package/docs/system-one-cycle.md +10 -0
- package/docs/system-one-training.md +3 -1
- package/harness-everything/SKILL.md +1 -1
- package/harness-everything/scripts/system-one/cua_adapter.py +36 -1
- package/harness-everything/scripts/system-one/install.js +10 -0
- package/harness-everything/scripts/system-one/layer.py +178 -0
- package/harness-everything/scripts/system-one/manifest.js +8 -1
- package/harness-everything/scripts/system-one/provider.js +12 -2
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/plugin.json +1 -1
- package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/cua_adapter.py +36 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/install.js +10 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/layer.py +178 -0
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/manifest.js +8 -1
- package/plugins/harness-everything/skills/harness-everything/scripts/system-one/provider.js +12 -2
- package/sbom.cdx.json +7 -7
- package/scripts/system-one-colab.js +240 -0
- package/scripts/system-one-curves.js +52 -8
- package/scripts/system-one-cycle/evaluate.js +56 -5
- package/scripts/system-one-cycle/package.js +61 -3
- package/scripts/system-one-cycle/score.py +23 -2
- package/scripts/system-one-cycle/train.js +212 -20
- package/scripts/system-one-fit-layer.py +369 -0
- package/scripts/system-one-train.py +36 -9
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const crypto = require('node:crypto');
|
|
3
4
|
const fs = require('node:fs');
|
|
4
5
|
const path = require('node:path');
|
|
5
6
|
const { spawn, spawnSync } = require('node:child_process');
|
|
6
7
|
const { REPO, dataPath, writeJson, runNode, assertPrivateDataDir } = require('./common');
|
|
7
8
|
|
|
8
9
|
const TASKS = ['validity', 'intent', 'tier'];
|
|
10
|
+
const HOLDOUTS = { validity: 'system-one-holdout.json', tier: 'system-one-holdout.json', intent: 'system-one-intent-holdout.json' };
|
|
9
11
|
|
|
10
12
|
function processTreeRssMb(rootPid) {
|
|
11
13
|
if (process.platform === 'win32') {
|
|
@@ -95,10 +97,192 @@ function pythonExecutable() {
|
|
|
95
97
|
return process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
|
|
96
98
|
}
|
|
97
99
|
|
|
100
|
+
function sha256(file) {
|
|
101
|
+
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function reportLabelFile(task, target) {
|
|
105
|
+
return task === 'intent' && target === 'scores' ? 'labels-intent-scores.jsonl'
|
|
106
|
+
: task === 'intent' ? 'labels-intent.jsonl' : 'labels.jsonl';
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function readTrainerReport(runDir, task) {
|
|
110
|
+
try {
|
|
111
|
+
const report = JSON.parse(fs.readFileSync(path.join(runDir, 'train-report.json'), 'utf8'));
|
|
112
|
+
const datasets = report.datasets;
|
|
113
|
+
return report.schemaVersion === 1 && report.task === task
|
|
114
|
+
&& (report.target === 'label' || (task === 'intent' && report.target === 'scores'))
|
|
115
|
+
&& Array.isArray(report.catalog) && report.catalog.length > 0
|
|
116
|
+
&& report.catalog.every(id => typeof id === 'string' && id.length > 0)
|
|
117
|
+
&& new Set(report.catalog).size === report.catalog.length
|
|
118
|
+
&& Number.isInteger(report.counts?.validation) && report.counts.validation > 0
|
|
119
|
+
&& Number.isInteger(report.counts?.train) && report.counts.train > 0
|
|
120
|
+
&& datasets && typeof datasets === 'object' && !Array.isArray(datasets)
|
|
121
|
+
&& Object.keys(datasets).sort().join(',') === ['prompts.jsonl', reportLabelFile(task, report.target)].sort().join(',')
|
|
122
|
+
&& Object.values(datasets).every(hash => /^[a-f0-9]{64}$/.test(hash))
|
|
123
|
+
&& report.config && typeof report.config === 'object' && !Array.isArray(report.config)
|
|
124
|
+
&& Number.isInteger(report.bestEpoch) && report.bestEpoch > 0
|
|
125
|
+
&& Array.isArray(report.history) && typeof report.device === 'string' && typeof report.torch === 'string'
|
|
126
|
+
? report : null;
|
|
127
|
+
} catch { return null; }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function hasTrainerReport(runDir, task) {
|
|
131
|
+
return Boolean(readTrainerReport(runDir, task));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function successfulGuard(runDir) {
|
|
135
|
+
try {
|
|
136
|
+
const guard = JSON.parse(fs.readFileSync(path.join(runDir, 'resource-guard.json'), 'utf8'));
|
|
137
|
+
if (guard.schemaVersion !== 1 || guard.exitCode !== 0 || guard.killedForLimit || guard.monitorFailed) return false;
|
|
138
|
+
if (guard.remote === undefined) return Number.isFinite(guard.peakRssMb) && guard.peakRssMb >= 0
|
|
139
|
+
&& Number.isFinite(guard.maxRssMb) && guard.maxRssMb > 0 && Number.isInteger(guard.threads) && guard.threads > 0;
|
|
140
|
+
const remote = guard.remote;
|
|
141
|
+
if (remote?.provider !== 'colab' || typeof remote.session !== 'string' || !remote.session.length
|
|
142
|
+
|| !(remote.gpu === null || ['T4', 'L4', 'A100'].includes(remote.gpu))
|
|
143
|
+
|| typeof remote.invocationId !== 'string' || !/^[a-f0-9-]{36}$/.test(remote.invocationId)
|
|
144
|
+
|| !/^[a-f0-9]{64}$/.test(remote.manifestSha256 || '') || !remote.files || typeof remote.files !== 'object') return false;
|
|
145
|
+
const required = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json'];
|
|
146
|
+
return required.every(file => /^[a-f0-9]{64}$/.test(remote.files[file] || '')
|
|
147
|
+
&& fs.existsSync(path.join(runDir, file)) && remote.files[file] === sha256(path.join(runDir, file)));
|
|
148
|
+
} catch { return false; }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function validateFitStage({ runDir, task, dataDir, checkpointPath, checkpointConfigPath }) {
|
|
152
|
+
const report = readTrainerReport(runDir, task);
|
|
153
|
+
if (!report) throw new Error(`${task} trainer report is missing or invalid`);
|
|
154
|
+
if (!successfulGuard(runDir)) {
|
|
155
|
+
let detail = 'missing, failed, or lacks verified remote provenance';
|
|
156
|
+
try {
|
|
157
|
+
const guard = JSON.parse(fs.readFileSync(path.join(runDir, 'resource-guard.json'), 'utf8'));
|
|
158
|
+
if (guard.remote?.files) detail = `remote file hash mismatch: ${Object.entries(guard.remote.files)
|
|
159
|
+
.filter(([name, value]) => !fs.existsSync(path.join(runDir, name)) || sha256(path.join(runDir, name)) !== value)
|
|
160
|
+
.map(([name]) => name).join(', ')}`;
|
|
161
|
+
} catch { /* retain generic guard diagnostic */ }
|
|
162
|
+
throw new Error(`${task} training guard is ${detail}`);
|
|
163
|
+
}
|
|
164
|
+
const files = Object.fromEntries(Object.entries(report.datasets).map(([name, expected]) => {
|
|
165
|
+
const file = dataDir && path.join(dataDir, 'training', task === 'validity' ? 'v1-validity' : 'v1', name);
|
|
166
|
+
if (file && (!fs.existsSync(file) || sha256(file) !== expected)) throw new Error(`${task} trainer dataset provenance is stale`);
|
|
167
|
+
return [name, expected];
|
|
168
|
+
}));
|
|
169
|
+
const outcomePath = path.join(runDir, 'layer-outcome.json');
|
|
170
|
+
const calibrationPath = path.join(runDir, 'calibration.json');
|
|
171
|
+
let outcome;
|
|
172
|
+
let calibration;
|
|
173
|
+
try {
|
|
174
|
+
outcome = JSON.parse(fs.readFileSync(outcomePath, 'utf8'));
|
|
175
|
+
calibration = JSON.parse(fs.readFileSync(calibrationPath, 'utf8'));
|
|
176
|
+
} catch { throw new Error(`${task} fit outcome or calibration is missing or invalid`); }
|
|
177
|
+
const checkpoint = checkpointPath || path.join(runDir, 'harness-routing-v1.safetensors');
|
|
178
|
+
const checkpointConfig = checkpointConfigPath || path.join(runDir, 'harness-routing-v1.json');
|
|
179
|
+
const input = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
|
|
180
|
+
const scorePath = path.join(runDir, input);
|
|
181
|
+
const holdoutPath = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
|
|
182
|
+
const hash = file => fs.existsSync(file) ? sha256(file) : null;
|
|
183
|
+
if (outcome.schemaVersion !== 1 || outcome.task !== task || !['layer', 'keep-base'].includes(outcome.outcome)
|
|
184
|
+
|| JSON.stringify(outcome.datasetSha256) !== JSON.stringify(files)
|
|
185
|
+
|| outcome.trainerReportSha256 !== hash(path.join(runDir, 'train-report.json'))
|
|
186
|
+
|| outcome.holdoutSha256 !== hash(holdoutPath)
|
|
187
|
+
|| outcome.checkpointSha256 !== hash(checkpoint)
|
|
188
|
+
|| !/^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
|
|
189
|
+
|| outcome.checkpointConfigSha256 !== hash(checkpointConfig)
|
|
190
|
+
|| outcome.calibrationInput !== input || outcome.calibrationInputSha256 !== hash(scorePath)
|
|
191
|
+
|| outcome.calibrationSha256 !== hash(calibrationPath)) {
|
|
192
|
+
throw new Error(`${task} fit outcome, checkpoint, calibration, or selected score file is stale`);
|
|
193
|
+
}
|
|
194
|
+
if (!calibration.thresholds || Object.keys(calibration.thresholds).sort().join('\0') !== [...report.catalog].sort().join('\0')
|
|
195
|
+
|| Object.values(calibration.thresholds).some(value => value !== null && (!Number.isFinite(value) || value < 0 || value > 1))) {
|
|
196
|
+
throw new Error(`${task} calibration has no finite per-option thresholds matching the trainer catalog`);
|
|
197
|
+
}
|
|
198
|
+
let rows;
|
|
199
|
+
try { rows = fs.readFileSync(scorePath, 'utf8').trim().split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line)); }
|
|
200
|
+
catch { throw new Error(`${task} selected score file is invalid`); }
|
|
201
|
+
const ids = rows.map(row => row.id);
|
|
202
|
+
if (!rows.length || ids.some(id => typeof id !== 'string' || !id) || new Set(ids).size !== ids.length
|
|
203
|
+
|| !Array.isArray(outcome.validationIds) || outcome.validationIds.length !== ids.length
|
|
204
|
+
|| [...outcome.validationIds].sort().join('\0') !== [...ids].sort().join('\0')
|
|
205
|
+
|| rows.some(row => typeof row.gold !== 'string' || !row.scores
|
|
206
|
+
|| Object.keys(row.scores).sort().join('\0') !== [...report.catalog].sort().join('\0')
|
|
207
|
+
|| Object.values(row.scores).some(value => !Number.isFinite(value)))) {
|
|
208
|
+
throw new Error(`${task} selected score file does not match the fit outcome`);
|
|
209
|
+
}
|
|
210
|
+
if (outcome.outcome === 'layer') {
|
|
211
|
+
const layerPath = path.join(runDir, 'layer.json');
|
|
212
|
+
if (outcome.oofScoreSpace !== 'h-transform-v2' || outcome.layerSha256 !== hash(layerPath))
|
|
213
|
+
throw new Error(`${task} layered fit is stale or lacks corrected OOF score-space evidence`);
|
|
214
|
+
const layer = JSON.parse(fs.readFileSync(layerPath, 'utf8'));
|
|
215
|
+
if (layer.stage !== task || layer.kind !== 'echl-h' || layer.fit?.oof !== true
|
|
216
|
+
|| layer.options?.join('\0') !== report.catalog.join('\0')) throw new Error(`${task} layer does not match fit outcome`);
|
|
217
|
+
} else if (outcome.oofScoreSpace !== null || fs.existsSync(path.join(runDir, 'layer.json'))
|
|
218
|
+
|| outcome.calibrationInput !== 'val-scores.jsonl') {
|
|
219
|
+
throw new Error(`${task} keep-base fit outcome is inconsistent`);
|
|
220
|
+
}
|
|
221
|
+
return { report, outcome, calibration, scorePath };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function fitLayerStage({ dataDir, runDir, task }) {
|
|
225
|
+
const fitter = path.join(REPO, 'scripts', 'system-one-fit-layer.py');
|
|
226
|
+
const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
|
|
227
|
+
const bundle = dataPath(dataDir, 'training', task === 'validity' ? 'v1-validity' : 'v1');
|
|
228
|
+
const holdout = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
|
|
229
|
+
const sha256 = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
230
|
+
const outcomeFile = path.join(runDir, 'layer-outcome.json');
|
|
231
|
+
if (fs.existsSync(outcomeFile)) {
|
|
232
|
+
try {
|
|
233
|
+
const outcome = JSON.parse(fs.readFileSync(outcomeFile, 'utf8'));
|
|
234
|
+
const report = readTrainerReport(runDir, task);
|
|
235
|
+
if (!report) throw new Error('invalid trainer report');
|
|
236
|
+
const labelFile = reportLabelFile(task, report.target);
|
|
237
|
+
const datasets = Object.fromEntries(['prompts.jsonl', labelFile].map(file => [file, sha256(path.join(bundle, file))]));
|
|
238
|
+
const holdout = path.join(REPO, 'benchmarks', 'fixtures', HOLDOUTS[task]);
|
|
239
|
+
const input = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
|
|
240
|
+
const layerPath = path.join(runDir, 'layer.json');
|
|
241
|
+
const current = outcome.schemaVersion === 1 && outcome.task === task && ['layer', 'keep-base'].includes(outcome.outcome)
|
|
242
|
+
&& (outcome.outcome === 'layer' ? outcome.oofScoreSpace === 'h-transform-v2' : outcome.oofScoreSpace === null)
|
|
243
|
+
&& JSON.stringify(outcome.datasetSha256) === JSON.stringify(datasets)
|
|
244
|
+
&& outcome.trainerReportSha256 === sha256(path.join(runDir, 'train-report.json'))
|
|
245
|
+
&& outcome.holdoutSha256 === sha256(holdout)
|
|
246
|
+
&& outcome.checkpointSha256 === sha256(path.join(runDir, 'harness-routing-v1.safetensors'))
|
|
247
|
+
&& /^[a-f0-9]{64}$/.test(outcome.checkpointConfigSha256 || '')
|
|
248
|
+
&& outcome.checkpointConfigSha256 === sha256(path.join(runDir, 'harness-routing-v1.json'))
|
|
249
|
+
&& outcome.calibrationInput === input && outcome.calibrationInputSha256 === sha256(path.join(runDir, input))
|
|
250
|
+
&& outcome.calibrationSha256 === sha256(path.join(runDir, 'calibration.json'))
|
|
251
|
+
&& (outcome.outcome === 'layer' ? fs.existsSync(layerPath) && outcome.layerSha256 === sha256(layerPath)
|
|
252
|
+
: !fs.existsSync(layerPath));
|
|
253
|
+
if (current) {
|
|
254
|
+
validateFitStage({ runDir, task, dataDir });
|
|
255
|
+
return outcome;
|
|
256
|
+
}
|
|
257
|
+
} catch { /* Refit incomplete or stale stage artifacts below. */ }
|
|
258
|
+
}
|
|
259
|
+
const result = spawnSync(pythonExecutable(), [fitter, '--run-dir', runDir, '--data-dir', bundle,
|
|
260
|
+
'--task', task, '--holdout', holdout], { cwd: REPO, stdio: 'ignore', windowsHide: true });
|
|
261
|
+
if (result.error || result.status !== 0) throw new Error(`system-one-fit-layer.py failed${result.status === null ? '' : ` (${result.status})`}`);
|
|
262
|
+
const outcome = JSON.parse(fs.readFileSync(outcomeFile, 'utf8'));
|
|
263
|
+
if (!['layer', 'keep-base'].includes(outcome.outcome)) throw new Error(`layer fit for ${task} has no explicit outcome`);
|
|
264
|
+
const scores = outcome.outcome === 'layer' ? 'val-scores-layered.jsonl' : 'val-scores.jsonl';
|
|
265
|
+
if (outcome.outcome === 'layer' && (!fs.existsSync(path.join(runDir, 'layer.json'))
|
|
266
|
+
|| !fs.existsSync(path.join(runDir, scores)))) throw new Error(`layer fit for ${task} is incomplete`);
|
|
267
|
+
runNode(calibrator, [path.join(runDir, scores), path.join(runDir, 'calibration.json'), '--task', task,
|
|
268
|
+
'--catalog', path.join(runDir, 'train-report.json')]);
|
|
269
|
+
if (outcome.outcome === 'layer' && (!fs.existsSync(path.join(runDir, 'layer.json'))
|
|
270
|
+
|| !fs.existsSync(path.join(runDir, 'val-scores-layered.jsonl')))) throw new Error(`layer fit for ${task} is incomplete`);
|
|
271
|
+
outcome.calibrationInput = scores;
|
|
272
|
+
outcome.calibrationInputSha256 = sha256(path.join(runDir, scores));
|
|
273
|
+
outcome.calibrationSha256 = sha256(path.join(runDir, 'calibration.json'));
|
|
274
|
+
if (outcome.outcome === 'layer' && outcome.oofScoreSpace !== 'h-transform-v2')
|
|
275
|
+
throw new Error(`layer fit for ${task} does not prove corrected OOF score space`);
|
|
276
|
+
if (outcome.outcome === 'keep-base' && outcome.oofScoreSpace !== null)
|
|
277
|
+
throw new Error(`layer fit for ${task} has an invalid keep-base score-space marker`);
|
|
278
|
+
writeJson(outcomeFile, outcome);
|
|
279
|
+
validateFitStage({ runDir, task, dataDir });
|
|
280
|
+
return outcome;
|
|
281
|
+
}
|
|
282
|
+
|
|
98
283
|
async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run = runGuarded }) {
|
|
99
284
|
const privateDir = assertPrivateDataDir(dataDir);
|
|
100
285
|
const trainer = path.join(REPO, 'scripts', 'system-one-train.py');
|
|
101
|
-
const calibrator = path.join(REPO, 'scripts', 'system-one-calibrate.js');
|
|
102
286
|
const outputs = [];
|
|
103
287
|
let trained = 0;
|
|
104
288
|
let skipped = 0;
|
|
@@ -107,30 +291,38 @@ async function trainCycle({ dataDir, version, threads = 4, maxRssMb = 6144, run
|
|
|
107
291
|
const source = dataPath(privateDir, 'training', task === 'validity' ? 'v1-validity' : 'v1');
|
|
108
292
|
const out = dataPath(privateDir, 'training', 'runs', version, task);
|
|
109
293
|
fs.mkdirSync(out, { recursive: true, mode: 0o700 });
|
|
110
|
-
const requiredFiles = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json'
|
|
294
|
+
const requiredFiles = ['harness-routing-v1.safetensors', 'harness-routing-v1.json', 'val-scores.jsonl', 'train-report.json'];
|
|
111
295
|
const guardFile = path.join(out, 'resource-guard.json');
|
|
296
|
+
let trainedThisTask = false;
|
|
112
297
|
if (requiredFiles.every(file => fs.existsSync(path.join(out, file)))) {
|
|
113
|
-
|
|
114
|
-
if (priorGuard.exitCode === 0 && !priorGuard.killedForLimit && !priorGuard.monitorFailed) {
|
|
298
|
+
if (successfulGuard(out) && hasTrainerReport(out, task)) {
|
|
115
299
|
skipped++;
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
300
|
+
} else trainedThisTask = true;
|
|
301
|
+
} else trainedThisTask = true;
|
|
302
|
+
if (trainedThisTask) {
|
|
303
|
+
const result = await run(pythonExecutable(), [trainer, '--data-dir', source, '--out', out, '--task', task, '--threads', String(threads)], {
|
|
304
|
+
threads, maxRssMb,
|
|
305
|
+
});
|
|
306
|
+
const guard = { schemaVersion: 1, ...result, createdAt: new Date().toISOString() };
|
|
307
|
+
writeJson(path.join(out, 'resource-guard.json'), guard);
|
|
308
|
+
if (result.killedForLimit) throw new Error(`training ${task} exceeded the ${maxRssMb} MB RSS limit`);
|
|
309
|
+
if (result.monitorFailed) throw new Error(`training ${task} RSS monitoring failed`);
|
|
310
|
+
if (result.exitCode !== 0) throw new Error(`training ${task} failed`);
|
|
311
|
+
if (!hasTrainerReport(out, task)) throw new Error(`training ${task} produced a missing or invalid trainer report`);
|
|
312
|
+
trained++;
|
|
313
|
+
}
|
|
314
|
+
if (!hasTrainerReport(out, task)) throw new Error(`training ${task} has no valid trainer report`);
|
|
315
|
+
const outcome = fitLayerStage({ dataDir: privateDir, runDir: out, task });
|
|
316
|
+
validateFitStage({ runDir: out, task, dataDir: privateDir });
|
|
317
|
+
if (fs.existsSync(guardFile)) outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
|
|
318
|
+
if (outcome) {
|
|
319
|
+
outputs.push(`training/runs/${version}/${task}/calibration.json`, `training/runs/${version}/${task}/layer-outcome.json`);
|
|
320
|
+
if (outcome.outcome === 'layer') outputs.push(`training/runs/${version}/${task}/layer.json`,
|
|
321
|
+
`training/runs/${version}/${task}/val-scores-layered.jsonl`);
|
|
119
322
|
}
|
|
120
|
-
const result = await run(pythonExecutable(), [trainer, '--data-dir', source, '--out', out, '--task', task, '--threads', String(threads)], {
|
|
121
|
-
threads, maxRssMb,
|
|
122
|
-
});
|
|
123
|
-
const guard = { schemaVersion: 1, ...result, createdAt: new Date().toISOString() };
|
|
124
|
-
writeJson(path.join(out, 'resource-guard.json'), guard);
|
|
125
|
-
if (result.killedForLimit) throw new Error(`training ${task} exceeded the ${maxRssMb} MB RSS limit`);
|
|
126
|
-
if (result.monitorFailed) throw new Error(`training ${task} RSS monitoring failed`);
|
|
127
|
-
if (result.exitCode !== 0) throw new Error(`training ${task} failed`);
|
|
128
|
-
runNode(calibrator, [path.join(out, 'val-scores.jsonl'), path.join(out, 'calibration.json'), '--task', task,
|
|
129
|
-
'--catalog', path.join(out, 'train-report.json')]);
|
|
130
|
-
trained++;
|
|
131
|
-
outputs.push(`training/runs/${version}/${task}/resource-guard.json`);
|
|
132
323
|
}
|
|
133
324
|
return { trained, skipped, threads, maxRssMb, outputs };
|
|
134
325
|
}
|
|
135
326
|
|
|
136
|
-
module.exports = { runGuarded, processTreeRssMb, trainCycle,
|
|
327
|
+
module.exports = { runGuarded, processTreeRssMb, trainCycle, fitLayerStage, hasTrainerReport, successfulGuard,
|
|
328
|
+
validateFitStage, TASKS, HOLDOUTS };
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Fit the H layer on validation rows and write deterministic two-fold OOF scores."""
|
|
3
|
+
import argparse
|
|
4
|
+
import hashlib
|
|
5
|
+
import importlib.util
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
sys.dont_write_bytecode = True
|
|
12
|
+
REPO = Path(__file__).resolve().parents[1]
|
|
13
|
+
TASKS = ('validity', 'intent', 'tier')
|
|
14
|
+
CANDIDATES = (('H-temp', True, False), ('H-bias', True, True), ('H-knn', False, False),
|
|
15
|
+
('H-temp+knn', True, False), ('H-bias+knn', True, True))
|
|
16
|
+
ALPHAS = tuple(i / 10 for i in range(11))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def load_module(name, file):
|
|
20
|
+
spec = importlib.util.spec_from_file_location(name, file)
|
|
21
|
+
module = importlib.util.module_from_spec(spec)
|
|
22
|
+
spec.loader.exec_module(module)
|
|
23
|
+
return module
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def load_layer_api():
|
|
27
|
+
return load_module('system_one_layer', REPO / 'harness-everything/scripts/system-one/layer.py')
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def fold_for(row_id):
|
|
31
|
+
return int(hashlib.sha256(row_id.encode('utf-8')).hexdigest(), 16) % 2
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def trainer_targets(row, task, catalog, trainer, target='label', gold_row=None):
|
|
35
|
+
"""Attach the trainer's gold and target vector to one row for every fit consumer."""
|
|
36
|
+
truth = gold_row if gold_row is not None else row
|
|
37
|
+
result = {**row, '_targets': trainer.build_targets(row, catalog, task, target),
|
|
38
|
+
'_trainer_gold': trainer.target_gold(truth, task)}
|
|
39
|
+
if task == 'intent' and truth.get('secondary'):
|
|
40
|
+
result['secondary'] = truth['secondary']
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def positives(row, task):
|
|
45
|
+
targets = row['_targets']
|
|
46
|
+
if task == 'validity':
|
|
47
|
+
return (1,) if targets[0] > 0 else (0,)
|
|
48
|
+
return tuple(index for index, value in enumerate(targets) if value > 0)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def row_nll(rows, predictions, task):
|
|
52
|
+
if not rows:
|
|
53
|
+
raise ValueError('empty-fold')
|
|
54
|
+
loss = 0.0
|
|
55
|
+
for row in rows:
|
|
56
|
+
q = predictions[row['id']]
|
|
57
|
+
loss -= math.log(max(1e-9, max(q[i] for i in positives(row, task))))
|
|
58
|
+
return loss / len(rows)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _layered_scores(logits, row, task, recipe, knn, layer_api, neighbor_distribution=None):
|
|
62
|
+
q = layer_api.transform(logits, task, recipe['temperature'], recipe['bias'])
|
|
63
|
+
if recipe['alpha']:
|
|
64
|
+
distribution = neighbor_distribution if neighbor_distribution is not None else knn.dist(row['text'], len(q))
|
|
65
|
+
q = layer_api.blend(q, distribution, recipe['alpha'])
|
|
66
|
+
return q
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def precompute_knn(rows, task, knn, logits_by_id):
|
|
70
|
+
return {row['id']: knn.dist(row['text'], len(logits_by_id[row['id']]) + (task == 'validity')) for row in rows}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def assert_base_nll_matches(fitter_nll, trainer_nll):
|
|
74
|
+
if not math.isfinite(fitter_nll) or not math.isfinite(trainer_nll) or abs(fitter_nll - trainer_nll) > 1e-3:
|
|
75
|
+
raise ValueError(f'base-nll-mismatch: fitter={fitter_nll:.6f} trainer={trainer_nll:.6f} tolerance=0.001')
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def raw_scores(logits):
|
|
79
|
+
return [1.0 / (1.0 + math.exp(-max(-80.0, min(80.0, value)))) for value in logits]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def oof_score_space(candidate):
|
|
83
|
+
return 'h-transform-v2' if candidate != 'keep-base' else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def select_recipe(rows, logits_by_id, task, knn, layer_api, fit_parameters, neighbor_distributions=None):
|
|
87
|
+
"""Select temp/bias/alpha and keep-base using only the supplied rows."""
|
|
88
|
+
if not rows:
|
|
89
|
+
raise ValueError('empty-fold')
|
|
90
|
+
width = len(logits_by_id[rows[0]['id']])
|
|
91
|
+
base = {row['id']: layer_api.transform(logits_by_id[row['id']], task) for row in rows}
|
|
92
|
+
base_nll = row_nll(rows, base, task)
|
|
93
|
+
best = None
|
|
94
|
+
for name, uses_temp, use_bias in CANDIDATES:
|
|
95
|
+
uses_knn = name in ('H-knn', 'H-temp+knn', 'H-bias+knn')
|
|
96
|
+
temperature, bias = fit_parameters(rows, logits_by_id, task, use_bias) if uses_temp else (1.0, None)
|
|
97
|
+
if not math.isfinite(temperature) or temperature <= 0 or (bias is not None
|
|
98
|
+
and any(not math.isfinite(float(value)) for value in bias)):
|
|
99
|
+
raise ValueError('layer-fit-parameters-invalid')
|
|
100
|
+
recipe = {'candidate': name, 'temperature': temperature, 'bias': bias, 'alpha': 0.0}
|
|
101
|
+
if uses_knn:
|
|
102
|
+
chosen = None
|
|
103
|
+
for alpha in ALPHAS:
|
|
104
|
+
trial = {**recipe, 'alpha': alpha}
|
|
105
|
+
q = {row['id']: _layered_scores(logits_by_id[row['id']], row, task, trial, knn, layer_api,
|
|
106
|
+
(neighbor_distributions or {}).get(row['id']))
|
|
107
|
+
for row in rows}
|
|
108
|
+
nll = row_nll(rows, q, task)
|
|
109
|
+
if chosen is None or nll < chosen['nll']:
|
|
110
|
+
chosen = {'recipe': trial, 'nll': nll}
|
|
111
|
+
recipe = chosen['recipe']
|
|
112
|
+
nll = chosen['nll']
|
|
113
|
+
else:
|
|
114
|
+
q = {row['id']: _layered_scores(logits_by_id[row['id']], row, task, recipe, knn, layer_api,
|
|
115
|
+
(neighbor_distributions or {}).get(row['id']))
|
|
116
|
+
for row in rows}
|
|
117
|
+
nll = row_nll(rows, q, task)
|
|
118
|
+
if best is None or nll < best['nll']:
|
|
119
|
+
best = {'recipe': recipe, 'nll': nll}
|
|
120
|
+
if best['nll'] >= base_nll:
|
|
121
|
+
return {'candidate': 'keep-base', 'temperature': 1.0, 'bias': None, 'alpha': 0.0,
|
|
122
|
+
'nll': base_nll, 'baseNll': base_nll}
|
|
123
|
+
return {**best['recipe'], 'nll': best['nll'], 'baseNll': base_nll}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def cross_fit(rows, logits_by_id, task, knn, layer_api, fit_parameters, neighbor_distributions=None):
|
|
127
|
+
ids = [row['id'] for row in rows]
|
|
128
|
+
if not rows or len(ids) != len(set(ids)) or set(ids) != set(logits_by_id):
|
|
129
|
+
raise ValueError('validation-ids-mismatch')
|
|
130
|
+
folds = [[row for row in rows if fold_for(row['id']) == fold] for fold in (0, 1)]
|
|
131
|
+
if any(not fold for fold in folds):
|
|
132
|
+
raise ValueError('empty-fold')
|
|
133
|
+
predictions = {}
|
|
134
|
+
recipes = []
|
|
135
|
+
for reserved in folds:
|
|
136
|
+
reserved_ids = {row['id'] for row in reserved}
|
|
137
|
+
training = [row for row in rows if row['id'] not in reserved_ids]
|
|
138
|
+
recipe = select_recipe(training, logits_by_id, task, knn, layer_api, fit_parameters, neighbor_distributions)
|
|
139
|
+
recipes.append({'reservedIds': [row['id'] for row in reserved], 'recipe': recipe})
|
|
140
|
+
for row in reserved:
|
|
141
|
+
logits = logits_by_id[row['id']]
|
|
142
|
+
if recipe['candidate'] == 'keep-base':
|
|
143
|
+
if task == 'validity':
|
|
144
|
+
# Validity has one invalid logit; preserve its legacy single-score shape.
|
|
145
|
+
predictions[row['id']] = raw_scores(logits)
|
|
146
|
+
else:
|
|
147
|
+
# This is a fold-local normalized baseline, not the deployed no-layer path.
|
|
148
|
+
# Keep its score space aligned with the H layer used by other folds.
|
|
149
|
+
identity = {'temperature': 1.0, 'bias': None, 'alpha': 0.0}
|
|
150
|
+
scores = _layered_scores(logits, row, task, identity, knn, layer_api,
|
|
151
|
+
(neighbor_distributions or {}).get(row['id']))
|
|
152
|
+
predictions[row['id']] = scores
|
|
153
|
+
else:
|
|
154
|
+
scores = _layered_scores(logits, row, task, recipe, knn, layer_api,
|
|
155
|
+
(neighbor_distributions or {}).get(row['id']))
|
|
156
|
+
predictions[row['id']] = [scores[1]] if task == 'validity' else scores
|
|
157
|
+
if set(predictions) != set(ids) or len(predictions) != len(rows):
|
|
158
|
+
raise ValueError('validation-ids-mismatch')
|
|
159
|
+
return recipes, predictions
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def build_index(prompts, labels, task, catalog, trainer, target='label'):
|
|
163
|
+
joined = trainer.eligible_rows(trainer.join(prompts, labels), task)
|
|
164
|
+
index = []
|
|
165
|
+
for row in joined:
|
|
166
|
+
if row.get('split') != 'train':
|
|
167
|
+
continue
|
|
168
|
+
index.append({'text': row['text'], 'target': trainer_targets(row, task, catalog, trainer, target)['_targets']})
|
|
169
|
+
return index
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def score_rows(rows, options, task, predictions):
|
|
173
|
+
result = []
|
|
174
|
+
for row in rows:
|
|
175
|
+
record = {'id': row['id'], 'gold': row['_trainer_gold'],
|
|
176
|
+
'scores': {option: float(value) for option, value in zip(options, predictions[row['id']], strict=True)}}
|
|
177
|
+
if task == 'intent' and row.get('secondary'):
|
|
178
|
+
record['secondary'] = row['secondary']
|
|
179
|
+
result.append(record)
|
|
180
|
+
return result
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def fit_temp_bias(rows, logits_by_id, task, use_bias):
|
|
184
|
+
import torch
|
|
185
|
+
torch.set_num_threads(1)
|
|
186
|
+
logits = torch.tensor([logits_by_id[row['id']] for row in rows], dtype=torch.float64)
|
|
187
|
+
log_temperature = torch.zeros(1, dtype=torch.float64, requires_grad=True)
|
|
188
|
+
bias = torch.zeros(logits.shape[1], dtype=torch.float64, requires_grad=use_bias)
|
|
189
|
+
parameters = [log_temperature] + ([bias] if use_bias else [])
|
|
190
|
+
optimizer = torch.optim.Adam(parameters, lr=0.05)
|
|
191
|
+
for _ in range(300):
|
|
192
|
+
p = torch.sigmoid(logits / log_temperature.exp() + bias)
|
|
193
|
+
if task == 'validity':
|
|
194
|
+
q = torch.cat([1 - p, p], dim=1)
|
|
195
|
+
else:
|
|
196
|
+
q = p / p.sum(dim=1, keepdim=True).clamp_min(1e-9)
|
|
197
|
+
selected = torch.stack([q[i, list(positives(row, task))].max() for i, row in enumerate(rows)]).clamp_min(1e-9)
|
|
198
|
+
loss = -selected.log().mean()
|
|
199
|
+
optimizer.zero_grad()
|
|
200
|
+
loss.backward()
|
|
201
|
+
optimizer.step()
|
|
202
|
+
return float(log_temperature.detach().exp()), bias.detach().tolist() if use_bias else None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def load_data(data_dir, run_dir, task, holdout, trainer):
|
|
206
|
+
data_dir = Path(data_dir)
|
|
207
|
+
run_dir = Path(run_dir)
|
|
208
|
+
report = json.loads((run_dir / 'train-report.json').read_text(encoding='utf-8'))
|
|
209
|
+
config_bytes = (run_dir / 'harness-routing-v1.json').read_bytes()
|
|
210
|
+
checkpoint_config_sha256 = hashlib.sha256(config_bytes).hexdigest()
|
|
211
|
+
checkpoint = json.loads(config_bytes)
|
|
212
|
+
if not isinstance(checkpoint, dict) or not isinstance(checkpoint.get('config'), dict) \
|
|
213
|
+
or not isinstance(checkpoint.get('metadata'), dict):
|
|
214
|
+
raise ValueError('checkpoint-metadata-mismatch')
|
|
215
|
+
target = report.get('target', 'label')
|
|
216
|
+
label_file = 'labels-intent-scores.jsonl' if task == 'intent' and target == 'scores' else \
|
|
217
|
+
'labels-intent.jsonl' if task == 'intent' else 'labels.jsonl'
|
|
218
|
+
file_names = ('prompts.jsonl', label_file)
|
|
219
|
+
dataset_hashes = {name: trainer.sha256_file(data_dir / name) for name in file_names}
|
|
220
|
+
if report.get('task') != task or report.get('datasets') != dataset_hashes:
|
|
221
|
+
raise ValueError('dataset-identity-mismatch')
|
|
222
|
+
metadata = checkpoint['metadata']
|
|
223
|
+
if metadata.get('task') != task or metadata.get('target') != target \
|
|
224
|
+
or metadata.get('catalog') != report.get('catalog') \
|
|
225
|
+
or metadata.get('datasets') != report.get('datasets') or checkpoint.get('config') != report.get('config'):
|
|
226
|
+
raise ValueError('checkpoint-metadata-mismatch')
|
|
227
|
+
catalog = trainer.catalog_for(task, holdout)
|
|
228
|
+
options = [item['id'] for item in catalog]
|
|
229
|
+
if report.get('catalog') != options:
|
|
230
|
+
raise ValueError('catalog-identity-mismatch')
|
|
231
|
+
prompts = trainer.load_jsonl(data_dir / 'prompts.jsonl')
|
|
232
|
+
labels = trainer.load_jsonl(data_dir / label_file)
|
|
233
|
+
joined = trainer.eligible_rows(trainer.join(prompts, labels), task)
|
|
234
|
+
validation = [row for row in joined if row.get('split') == 'validation']
|
|
235
|
+
if not validation or any(not isinstance(row.get('text'), str) for row in validation):
|
|
236
|
+
raise ValueError('validation-split-empty')
|
|
237
|
+
if report.get('counts', {}).get('validation') != len(validation):
|
|
238
|
+
raise ValueError('validation-count-mismatch')
|
|
239
|
+
intent_truth = {}
|
|
240
|
+
if task == 'intent':
|
|
241
|
+
intent_truth = {row['id']: row for row in trainer.load_jsonl(data_dir / 'labels-intent.jsonl')}
|
|
242
|
+
scores = [json.loads(line) for line in (run_dir / 'val-scores.jsonl').read_text(encoding='utf-8').splitlines() if line.strip()]
|
|
243
|
+
score_ids = [row.get('id') for row in scores]
|
|
244
|
+
validation_ids = [row['id'] for row in validation]
|
|
245
|
+
if len(score_ids) != len(set(score_ids)) or set(score_ids) != set(validation_ids):
|
|
246
|
+
raise ValueError('validation-ids-mismatch')
|
|
247
|
+
score_by_id = {row['id']: row for row in scores}
|
|
248
|
+
for row in validation:
|
|
249
|
+
truth = intent_truth.get(row['id']) if task == 'intent' else row
|
|
250
|
+
if truth is None:
|
|
251
|
+
raise ValueError('validation-label-mismatch')
|
|
252
|
+
score = score_by_id[row['id']]
|
|
253
|
+
targeted = trainer_targets(row, task, catalog, trainer, target, truth)
|
|
254
|
+
if score.get('gold') != targeted['_trainer_gold']:
|
|
255
|
+
raise ValueError('validation-label-mismatch')
|
|
256
|
+
if list(score.get('scores', {})) != options:
|
|
257
|
+
raise ValueError('validation-catalog-mismatch')
|
|
258
|
+
row.update(targeted)
|
|
259
|
+
for row in validation:
|
|
260
|
+
row['options'] = options
|
|
261
|
+
train_rows = [row for row in joined if row.get('split') == 'train']
|
|
262
|
+
if not train_rows or set(row['id'] for row in train_rows) & set(validation_ids):
|
|
263
|
+
raise ValueError('index-split-mismatch')
|
|
264
|
+
index = build_index(prompts, labels, task, catalog, trainer, target)
|
|
265
|
+
if any(not math.isfinite(float(value)) for item in index for value in item['target']):
|
|
266
|
+
raise ValueError('index-target-invalid')
|
|
267
|
+
return report, checkpoint['config'], catalog, validation, index, score_by_id, checkpoint_config_sha256
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def infer_logits(run_dir, rows, catalog, config):
|
|
271
|
+
import torch
|
|
272
|
+
from cua_s1.model import ChoiceExample, load_checkpoint
|
|
273
|
+
torch.set_num_threads(1)
|
|
274
|
+
torch.use_deterministic_algorithms(True)
|
|
275
|
+
checkpoint = Path(run_dir) / 'harness-routing-v1.safetensors'
|
|
276
|
+
model, collator, _ = load_checkpoint(checkpoint, 'cpu')
|
|
277
|
+
model.eval()
|
|
278
|
+
options = tuple(item['text'] for item in catalog)
|
|
279
|
+
logits = {}
|
|
280
|
+
with torch.inference_mode():
|
|
281
|
+
for start in range(0, len(rows), 16):
|
|
282
|
+
batch = rows[start:start + 16]
|
|
283
|
+
examples = [ChoiceExample(context=row['text'], options=options, label=0) for row in batch]
|
|
284
|
+
outputs = model(collator(examples)).float().tolist()
|
|
285
|
+
for row, output in zip(batch, outputs, strict=True):
|
|
286
|
+
if not output or any(not math.isfinite(float(value)) for value in output):
|
|
287
|
+
raise ValueError('checkpoint-logits-invalid')
|
|
288
|
+
logits[row['id']] = [float(value) for value in output]
|
|
289
|
+
return logits
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def write_private(file, text):
|
|
293
|
+
file = Path(file)
|
|
294
|
+
data = text.encode('utf-8')
|
|
295
|
+
if file.name == 'layer.json' and len(data) > 32 * 1024 * 1024:
|
|
296
|
+
raise ValueError('layer-artifact-too-large')
|
|
297
|
+
file.write_text(text, encoding='utf-8')
|
|
298
|
+
if file.stat().st_mode & 0o077:
|
|
299
|
+
file.chmod(0o600)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def fit_layer(run_dir, data_dir, task, holdout):
|
|
303
|
+
trainer = load_module('system_one_train', REPO / 'scripts/system-one-train.py')
|
|
304
|
+
layer_api = load_layer_api()
|
|
305
|
+
report, config, catalog, rows, index, trainer_scores, checkpoint_config_sha256 = load_data(
|
|
306
|
+
data_dir, run_dir, task, holdout, trainer)
|
|
307
|
+
logits_by_id = infer_logits(run_dir, rows, catalog, config)
|
|
308
|
+
if trainer.sha256_file(Path(run_dir) / 'harness-routing-v1.json') != checkpoint_config_sha256:
|
|
309
|
+
raise ValueError('checkpoint-config-changed-during-fit')
|
|
310
|
+
base = {row['id']: layer_api.transform(logits_by_id[row['id']], task) for row in rows}
|
|
311
|
+
trainer_base = {}
|
|
312
|
+
for row in rows:
|
|
313
|
+
values = [float(trainer_scores[row['id']]['scores'][option]) for option in report['catalog']]
|
|
314
|
+
trainer_base[row['id']] = [1.0 - values[0], values[0]] if task == 'validity' else \
|
|
315
|
+
[value / (sum(values) or 1.0) for value in values]
|
|
316
|
+
assert_base_nll_matches(row_nll(rows, base, task), row_nll(rows, trainer_base, task))
|
|
317
|
+
knn = layer_api.KnnIndex(index, task)
|
|
318
|
+
neighbor_distributions = precompute_knn(rows, task, knn, logits_by_id)
|
|
319
|
+
recipes, oof = cross_fit(rows, logits_by_id, task, knn, layer_api, fit_temp_bias, neighbor_distributions)
|
|
320
|
+
final = select_recipe(rows, logits_by_id, task, knn, layer_api, fit_temp_bias, neighbor_distributions)
|
|
321
|
+
output_rows = score_rows(rows, report['catalog'], task, oof)
|
|
322
|
+
output = Path(run_dir)
|
|
323
|
+
write_private(output / 'val-scores-layered.jsonl', ''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in output_rows))
|
|
324
|
+
outcome = {'schemaVersion': 1, 'task': task, 'datasetSha256': report['datasets'],
|
|
325
|
+
'checkpointSha256': trainer.sha256_file(output / 'harness-routing-v1.safetensors'),
|
|
326
|
+
'checkpointConfigSha256': checkpoint_config_sha256,
|
|
327
|
+
'trainerReportSha256': trainer.sha256_file(output / 'train-report.json'),
|
|
328
|
+
'holdoutSha256': trainer.sha256_file(holdout),
|
|
329
|
+
'validationIds': [row['id'] for row in rows], 'folds': recipes,
|
|
330
|
+
'candidate': final['candidate'], 'temperature': final['temperature'], 'alpha': final['alpha'],
|
|
331
|
+
'baseNll': final['baseNll'], 'selectedNll': final['nll'],
|
|
332
|
+
'oofScoreSpace': oof_score_space(final['candidate'])}
|
|
333
|
+
if final['candidate'] == 'keep-base':
|
|
334
|
+
for filename in ('layer.json', 'val-scores-layered.jsonl'):
|
|
335
|
+
if (output / filename).exists() and filename != 'val-scores-layered.jsonl':
|
|
336
|
+
(output / filename).unlink()
|
|
337
|
+
outcome['outcome'] = 'keep-base'
|
|
338
|
+
write_private(output / 'layer-outcome.json', json.dumps(outcome, indent=2) + '\n')
|
|
339
|
+
return outcome
|
|
340
|
+
layer = {'schemaVersion': 1, 'kind': 'echl-h', 'stage': task, 'options': report['catalog'],
|
|
341
|
+
'temperature': final['temperature'], 'bias': final['bias'], 'alpha': final['alpha'],
|
|
342
|
+
'k': 15, 'ngrams': [3, 4, 5], 'maxChars': 2000, 'index': index,
|
|
343
|
+
'fit': {'candidate': final['candidate'], 'heldOutRows': len(rows), 'nll': final['nll'],
|
|
344
|
+
'baseNll': final['baseNll'], 'oof': True}}
|
|
345
|
+
write_private(output / 'layer.json', json.dumps(layer, separators=(',', ':')) + '\n')
|
|
346
|
+
outcome['outcome'] = 'layer'
|
|
347
|
+
outcome['layerSha256'] = trainer.sha256_file(output / 'layer.json')
|
|
348
|
+
write_private(output / 'layer-outcome.json', json.dumps(outcome, indent=2) + '\n')
|
|
349
|
+
return outcome
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def main(argv=None):
|
|
353
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
354
|
+
parser.add_argument('--run-dir', required=True)
|
|
355
|
+
parser.add_argument('--data-dir', required=True)
|
|
356
|
+
parser.add_argument('--task', choices=TASKS, required=True)
|
|
357
|
+
parser.add_argument('--holdout', required=True)
|
|
358
|
+
args = parser.parse_args(argv)
|
|
359
|
+
try:
|
|
360
|
+
result = fit_layer(args.run_dir, args.data_dir, args.task, args.holdout)
|
|
361
|
+
except Exception as error:
|
|
362
|
+
print(f'system-one-fit-layer: {error}', file=sys.stderr)
|
|
363
|
+
return 1
|
|
364
|
+
print(json.dumps({key: value for key, value in result.items() if key not in ('folds', 'validationIds')}))
|
|
365
|
+
return 0
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
if __name__ == '__main__':
|
|
369
|
+
raise SystemExit(main())
|