harness-everything 1.4.0 → 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 +16 -5
- package/CHANGELOG.md +25 -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 +83 -5
- 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/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 +6 -4
- 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
|
@@ -17,6 +17,7 @@ from unittest.mock import patch
|
|
|
17
17
|
|
|
18
18
|
sys.dont_write_bytecode = True # never leave __pycache__ in the source tree that packaging copies
|
|
19
19
|
path = Path(__file__).resolve().parents[1] / 'harness-everything/scripts/system-one/cua_adapter.py'
|
|
20
|
+
sys.path.insert(0, str(path.parent))
|
|
20
21
|
spec = importlib.util.spec_from_file_location('adapter', path)
|
|
21
22
|
adapter = importlib.util.module_from_spec(spec)
|
|
22
23
|
spec.loader.exec_module(adapter)
|
|
@@ -74,6 +75,86 @@ class RequestSocket:
|
|
|
74
75
|
|
|
75
76
|
|
|
76
77
|
class AdapterTests(unittest.TestCase):
|
|
78
|
+
def test_active_layer_is_verified_and_passed_to_the_scorer_without_changing_legacy_shape(self):
|
|
79
|
+
with tempfile.TemporaryDirectory() as root:
|
|
80
|
+
pointer = write_active_fixture(root)
|
|
81
|
+
version_dir = pointer.parent / 'v1'
|
|
82
|
+
manifest_path = version_dir / 'manifest.json'
|
|
83
|
+
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
|
|
84
|
+
stage = manifest['stages']['tier']
|
|
85
|
+
payload = {
|
|
86
|
+
'schemaVersion': 1, 'kind': 'echl-h', 'stage': 'tier', 'options': ACTIVE_OPTIONS['tier'],
|
|
87
|
+
'temperature': 1.0, 'bias': None, 'alpha': 1.0, 'k': 1, 'ngrams': [3], 'maxChars': 2000,
|
|
88
|
+
'index': [{'text': 'fixture prompt', 'target': [0.0, 1.0, 0.0]}],
|
|
89
|
+
'fit': {'candidate': 'H-knn', 'heldOutRows': 1, 'nll': 0.1, 'baseNll': 0.2, 'oof': True},
|
|
90
|
+
}
|
|
91
|
+
layer_path = version_dir / 'tier.layer.json'
|
|
92
|
+
raw = json.dumps(payload).encode()
|
|
93
|
+
layer_path.write_bytes(raw)
|
|
94
|
+
stage.update({'layer': layer_path.name, 'layerSha256': hashlib.sha256(raw).hexdigest()})
|
|
95
|
+
manifest_path.write_text(json.dumps(manifest), encoding='utf-8')
|
|
96
|
+
loaded = []
|
|
97
|
+
|
|
98
|
+
def fake_loader(weights, stage_manifest):
|
|
99
|
+
loaded.append(stage_manifest)
|
|
100
|
+
return (lambda _request: []), {'context_tokens': 8, 'option_tokens': 8}
|
|
101
|
+
|
|
102
|
+
bundle = adapter.load_active_bundle(pointer, scorer_loader=fake_loader)
|
|
103
|
+
self.assertEqual(loaded[-1]['layerPath'], str(layer_path))
|
|
104
|
+
self.assertEqual(bundle['scorers']['tier']['layer']['stage'], 'tier')
|
|
105
|
+
self.assertFalse(bundle['scorers']['validity'].get('layer'))
|
|
106
|
+
raw = layer_path.read_bytes() + b' '
|
|
107
|
+
layer_path.write_bytes(raw)
|
|
108
|
+
self.assertFalse(adapter._active_unchanged(bundle, bundle['stamp']))
|
|
109
|
+
with self.assertRaisesRegex(ValueError, 'artifact-hash'):
|
|
110
|
+
adapter.load_active_bundle(pointer, scorer_loader=fake_loader)
|
|
111
|
+
|
|
112
|
+
def test_scorer_applies_layer_to_raw_logits(self):
|
|
113
|
+
class Logits:
|
|
114
|
+
def __getitem__(self, _index):
|
|
115
|
+
class Row:
|
|
116
|
+
def tolist(self):
|
|
117
|
+
return [0.0, 0.0, 0.0]
|
|
118
|
+
return Row()
|
|
119
|
+
|
|
120
|
+
def sigmoid(self):
|
|
121
|
+
raise AssertionError('layer requires raw logits')
|
|
122
|
+
|
|
123
|
+
class FakeModel:
|
|
124
|
+
def __call__(self, _batch):
|
|
125
|
+
return Logits()
|
|
126
|
+
|
|
127
|
+
torch = ModuleType('torch')
|
|
128
|
+
torch.set_num_threads = lambda _count: None
|
|
129
|
+
torch.use_deterministic_algorithms = lambda _enabled: None
|
|
130
|
+
torch.inference_mode = nullcontext
|
|
131
|
+
cua_s1 = ModuleType('cua_s1')
|
|
132
|
+
model = ModuleType('cua_s1.model')
|
|
133
|
+
model.ChoiceExample = lambda **values: values
|
|
134
|
+
model.load_checkpoint = lambda _weights, _device: (FakeModel(), lambda examples: examples, {})
|
|
135
|
+
with tempfile.TemporaryDirectory() as root:
|
|
136
|
+
weights = Path(root) / 'unused.safetensors'
|
|
137
|
+
weights.with_suffix('.json').write_text(json.dumps({'metadata': {
|
|
138
|
+
'domain': 'harness-routing-v1', 'task': 'tier', 'loss': 'binary_cross_entropy',
|
|
139
|
+
}}), encoding='utf-8')
|
|
140
|
+
layer_value = {
|
|
141
|
+
'schemaVersion': 1, 'kind': 'echl-h', 'stage': 'tier', 'options': ['a', 'b', 'c'],
|
|
142
|
+
'temperature': 1.0, 'bias': None, 'alpha': 1.0, 'k': 1, 'ngrams': [3], 'maxChars': 2000,
|
|
143
|
+
'index': [{'text': 'fixture', 'target': [0.0, 1.0, 0.0]}],
|
|
144
|
+
'fit': {'candidate': 'H-knn', 'heldOutRows': 1, 'nll': 0.1, 'baseNll': 0.2, 'oof': True},
|
|
145
|
+
}
|
|
146
|
+
layer_path = Path(root) / 'tier.layer.json'
|
|
147
|
+
raw = json.dumps(layer_value).encode()
|
|
148
|
+
layer_path.write_bytes(raw)
|
|
149
|
+
manifest = {'modelId': 'fixture-v1', 'domain': 'harness-routing-v1',
|
|
150
|
+
'layerPath': str(layer_path), 'layerSha256': hashlib.sha256(raw).hexdigest(),
|
|
151
|
+
'options': ['a', 'b', 'c']}
|
|
152
|
+
with patch.dict(sys.modules, {'torch': torch, 'cua_s1': cua_s1, 'cua_s1.model': model}):
|
|
153
|
+
score, _config = adapter.load_scorer(weights, manifest)
|
|
154
|
+
result = score({'task': 'tier', 'context': 'fixture', 'options': [
|
|
155
|
+
{'text': 'one'}, {'text': 'two'}, {'text': 'three'}]})
|
|
156
|
+
self.assertEqual(result, [0.0, 1.0, 0.0])
|
|
157
|
+
|
|
77
158
|
def test_active_pointer_loads_all_stage_checkpoints_from_separate_files(self):
|
|
78
159
|
with tempfile.TemporaryDirectory() as root:
|
|
79
160
|
pointer = write_active_fixture(root)
|
|
@@ -87,6 +168,11 @@ class AdapterTests(unittest.TestCase):
|
|
|
87
168
|
self.assertEqual(bundle['version'], 'v1')
|
|
88
169
|
self.assertEqual(list(bundle['scorers']), ['validity', 'intent', 'tier'])
|
|
89
170
|
self.assertEqual(bundle['scorers']['intent']['referenceOnly'], ['fix'])
|
|
171
|
+
legacy_parts = ['v1', str(pointer.parent / 'v1')]
|
|
172
|
+
for stage in adapter.ACTIVE_STAGES:
|
|
173
|
+
entry = bundle['scorers'][stage]
|
|
174
|
+
legacy_parts.extend((stage, entry['sha256'], entry['manifest']['configSha256']))
|
|
175
|
+
self.assertEqual(bundle['fingerprint'], hashlib.sha256('\0'.join(legacy_parts).encode()).hexdigest())
|
|
90
176
|
self.assertEqual(loaded, [(f'{stage}-weights.safetensors', f'{stage}-config.json') for stage in ('validity', 'intent', 'tier')])
|
|
91
177
|
|
|
92
178
|
def test_active_manifest_uses_shared_reference_only_validation(self):
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Synthetic tests for the System One H fitting pipeline; no private inputs or torch required."""
|
|
3
|
+
import importlib.util
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import subprocess
|
|
8
|
+
import tempfile
|
|
9
|
+
import unittest
|
|
10
|
+
import sys
|
|
11
|
+
from unittest.mock import patch
|
|
12
|
+
|
|
13
|
+
sys.dont_write_bytecode = True # keep __pycache__ out of the shipped tree (installer stale-tree check)
|
|
14
|
+
|
|
15
|
+
SCRIPT = Path(__file__).resolve().parents[1] / 'scripts' / 'system-one-fit-layer.py'
|
|
16
|
+
SPEC = importlib.util.spec_from_file_location('system_one_fit_layer', SCRIPT)
|
|
17
|
+
FIT = importlib.util.module_from_spec(SPEC)
|
|
18
|
+
SPEC.loader.exec_module(FIT)
|
|
19
|
+
SCORE_SPEC = importlib.util.spec_from_file_location(
|
|
20
|
+
'system_one_cycle_score', Path(__file__).resolve().parents[1] / 'scripts/system-one-cycle/score.py')
|
|
21
|
+
SCORE = importlib.util.module_from_spec(SCORE_SPEC)
|
|
22
|
+
SCORE_SPEC.loader.exec_module(SCORE)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class LayerApi:
|
|
26
|
+
@staticmethod
|
|
27
|
+
def transform(logits, task, temperature=1.0, bias=None):
|
|
28
|
+
values = [value / temperature + (bias[i] if bias else 0.0) for i, value in enumerate(logits)]
|
|
29
|
+
if task == 'validity':
|
|
30
|
+
p = 1 / (1 + __import__('math').exp(-values[0]))
|
|
31
|
+
return [1 - p, p]
|
|
32
|
+
exps = [__import__('math').exp(value) for value in values]
|
|
33
|
+
return [value / sum(exps) for value in exps]
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def blend(q, d, alpha):
|
|
37
|
+
values = [(1 - alpha) * a + alpha * b for a, b in zip(q, d)]
|
|
38
|
+
total = sum(values)
|
|
39
|
+
return [value / total for value in values]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Knn:
|
|
43
|
+
@staticmethod
|
|
44
|
+
def dist(_text, width):
|
|
45
|
+
return [1 / width] * width
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def fake_fit(rows, _logits, _task, use_bias):
|
|
49
|
+
if not use_bias:
|
|
50
|
+
return 1.0, None
|
|
51
|
+
if _task == 'validity':
|
|
52
|
+
return 1.0, [2.0 if all(row['gold'] == 'invalid' for row in rows) else -2.0]
|
|
53
|
+
first = sum(row['gold'] == row['options'][0] for row in rows)
|
|
54
|
+
second = len(rows) - first
|
|
55
|
+
return 1.0, ([2.0, -2.0] if first >= second else [-2.0, 2.0])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def rows_for_folds():
|
|
59
|
+
rows = []
|
|
60
|
+
for fold in (0, 1):
|
|
61
|
+
number = 0
|
|
62
|
+
while len([row for row in rows if FIT.fold_for(row['id']) == fold]) < 2:
|
|
63
|
+
row_id = f'fold-{fold}-row-{number}'
|
|
64
|
+
number += 1
|
|
65
|
+
if FIT.fold_for(row_id) != fold:
|
|
66
|
+
continue
|
|
67
|
+
rows.append({'id': row_id, 'text': row_id, 'gold': 'a', 'options': ['a', 'b'], '_targets': [1.0, 0.0]})
|
|
68
|
+
return rows
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class FitLayerTest(unittest.TestCase):
|
|
72
|
+
def test_two_fold_crossfit_selects_inside_each_fold_and_covers_every_id_once(self):
|
|
73
|
+
rows = rows_for_folds()
|
|
74
|
+
logits = {row['id']: [0.0, 0.0] for row in rows}
|
|
75
|
+
recipes, predictions = FIT.cross_fit(rows, logits, 'tier', Knn(), LayerApi, fake_fit)
|
|
76
|
+
self.assertEqual(len(recipes), 2)
|
|
77
|
+
self.assertEqual(len(predictions), len(rows))
|
|
78
|
+
self.assertEqual(set(predictions), {row['id'] for row in rows})
|
|
79
|
+
for fold in (0, 1):
|
|
80
|
+
item = next(recipe for recipe in recipes if FIT.fold_for(recipe['reservedIds'][0]) == fold)
|
|
81
|
+
self.assertEqual({FIT.fold_for(row_id) for row_id in item['reservedIds']}, {fold})
|
|
82
|
+
|
|
83
|
+
def test_changing_reserved_fold_gold_does_not_change_its_recipe_or_scores(self):
|
|
84
|
+
rows = rows_for_folds()
|
|
85
|
+
logits = {row['id']: [0.0, 0.0] for row in rows}
|
|
86
|
+
recipes_a, scores_a = FIT.cross_fit(rows, logits, 'tier', Knn(), LayerApi, fake_fit)
|
|
87
|
+
changed = [dict(row, gold='b') if FIT.fold_for(row['id']) == 1 else row for row in rows]
|
|
88
|
+
recipes_b, scores_b = FIT.cross_fit(changed, logits, 'tier', Knn(), LayerApi, fake_fit)
|
|
89
|
+
fold_a = next(item for item in recipes_a if FIT.fold_for(item['reservedIds'][0]) == 1)
|
|
90
|
+
fold_b = next(item for item in recipes_b if FIT.fold_for(item['reservedIds'][0]) == 1)
|
|
91
|
+
self.assertEqual(fold_a['recipe'], fold_b['recipe'])
|
|
92
|
+
for row_id in fold_a['reservedIds']:
|
|
93
|
+
self.assertEqual(scores_a[row_id], scores_b[row_id])
|
|
94
|
+
|
|
95
|
+
def test_mixed_fold_baselines_share_h_normalization_for_tier_and_intent(self):
|
|
96
|
+
layer_api = FIT.load_layer_api()
|
|
97
|
+
for task in ('tier', 'intent'):
|
|
98
|
+
with self.subTest(task=task):
|
|
99
|
+
rows = []
|
|
100
|
+
for fold, labels in ((0, ['a', 'a']), (1, ['a', 'b'])):
|
|
101
|
+
found = 0
|
|
102
|
+
number = 0
|
|
103
|
+
while found < len(labels):
|
|
104
|
+
row_id = f'{task}-mixed-{fold}-{number}'
|
|
105
|
+
number += 1
|
|
106
|
+
if FIT.fold_for(row_id) != fold:
|
|
107
|
+
continue
|
|
108
|
+
label = labels[found]
|
|
109
|
+
rows.append({'id': row_id, 'text': row_id, 'gold': label,
|
|
110
|
+
'_targets': [1.0 if option == label else 0.0 for option in ('a', 'b', 'c')]})
|
|
111
|
+
found += 1
|
|
112
|
+
logits = {row['id']: [0.0, 0.0, 0.0] for row in rows}
|
|
113
|
+
|
|
114
|
+
def select_from_training(training, *_args, **_kwargs):
|
|
115
|
+
# Select by the training fold identity only, never reserved-row labels.
|
|
116
|
+
if len(training) == len(rows):
|
|
117
|
+
return {'candidate': 'H-temp', 'temperature': 1.0, 'bias': None, 'alpha': 0.0}
|
|
118
|
+
training_fold = FIT.fold_for(training[0]['id'])
|
|
119
|
+
if training_fold == 1:
|
|
120
|
+
return {'candidate': 'keep-base', 'temperature': 1.0, 'bias': None, 'alpha': 0.0}
|
|
121
|
+
return {'candidate': 'H-temp', 'temperature': 1.0, 'bias': None, 'alpha': 0.0}
|
|
122
|
+
|
|
123
|
+
with patch.object(FIT, 'select_recipe', side_effect=select_from_training):
|
|
124
|
+
recipes, scores = FIT.cross_fit(rows, logits, task, Knn(), layer_api, fake_fit)
|
|
125
|
+
by_reserved_fold = {FIT.fold_for(item['reservedIds'][0]): item['recipe']['candidate']
|
|
126
|
+
for item in recipes}
|
|
127
|
+
self.assertEqual(by_reserved_fold, {0: 'keep-base', 1: 'H-temp'})
|
|
128
|
+
with patch.object(FIT, 'select_recipe', side_effect=select_from_training):
|
|
129
|
+
final = FIT.select_recipe(rows, logits, task, Knn(), layer_api, fake_fit)
|
|
130
|
+
self.assertEqual(final['candidate'], 'H-temp')
|
|
131
|
+
self.assertEqual(FIT.oof_score_space(final['candidate']), 'h-transform-v2')
|
|
132
|
+
self.assertIsNone(FIT.oof_score_space('keep-base'))
|
|
133
|
+
self.assertEqual(set(scores), {row['id'] for row in rows})
|
|
134
|
+
self.assertEqual(len(scores), len(rows))
|
|
135
|
+
self.assertTrue(all(len(score) == 3 and abs(sum(score) - 1.0) < 1e-12
|
|
136
|
+
for score in scores.values()))
|
|
137
|
+
self.assertTrue(all(score == [1 / 3, 1 / 3, 1 / 3] for score in scores.values()))
|
|
138
|
+
|
|
139
|
+
changed_reserved = [dict(row, gold='c', _targets=[0.0, 0.0, 1.0])
|
|
140
|
+
if FIT.fold_for(row['id']) == 0 else row for row in rows]
|
|
141
|
+
with patch.object(FIT, 'select_recipe', side_effect=select_from_training):
|
|
142
|
+
changed_recipes, changed_scores = FIT.cross_fit(changed_reserved, logits, task, Knn(),
|
|
143
|
+
layer_api, fake_fit)
|
|
144
|
+
original = next(item for item in recipes if FIT.fold_for(item['reservedIds'][0]) == 0)
|
|
145
|
+
changed = next(item for item in changed_recipes if FIT.fold_for(item['reservedIds'][0]) == 0)
|
|
146
|
+
self.assertEqual(original, changed)
|
|
147
|
+
for row_id in original['reservedIds']:
|
|
148
|
+
self.assertEqual(scores[row_id], changed_scores[row_id])
|
|
149
|
+
|
|
150
|
+
def test_changing_other_fold_gold_can_change_the_reserved_fold_recipe(self):
|
|
151
|
+
rows = rows_for_folds()
|
|
152
|
+
logits = {row['id']: [0.0, 0.0] for row in rows}
|
|
153
|
+
recipes_a, _ = FIT.cross_fit(rows, logits, 'tier', Knn(), LayerApi, fake_fit)
|
|
154
|
+
changed = [dict(row, gold='b') if FIT.fold_for(row['id']) == 0 else row for row in rows]
|
|
155
|
+
recipes_b, _ = FIT.cross_fit(changed, logits, 'tier', Knn(), LayerApi, fake_fit)
|
|
156
|
+
fold_a = next(item for item in recipes_a if FIT.fold_for(item['reservedIds'][0]) == 1)
|
|
157
|
+
fold_b = next(item for item in recipes_b if FIT.fold_for(item['reservedIds'][0]) == 1)
|
|
158
|
+
self.assertNotEqual(fold_a['recipe']['bias'], fold_b['recipe']['bias'])
|
|
159
|
+
|
|
160
|
+
def test_empty_fold_is_rejected(self):
|
|
161
|
+
rows = [{'id': 'only-row', 'text': 'only-row', 'gold': 'a', 'options': ['a', 'b']}]
|
|
162
|
+
with self.assertRaisesRegex(ValueError, 'empty-fold'):
|
|
163
|
+
FIT.cross_fit(rows, {'only-row': [0.0, 0.0]}, 'tier', Knn(), LayerApi, fake_fit)
|
|
164
|
+
|
|
165
|
+
def test_validity_oof_rows_keep_the_single_invalid_score_shape(self):
|
|
166
|
+
rows = []
|
|
167
|
+
for fold in (0, 1):
|
|
168
|
+
number = 0
|
|
169
|
+
while len([row for row in rows if FIT.fold_for(row['id']) == fold]) < 2:
|
|
170
|
+
row_id = f'validity-{fold}-{number}'
|
|
171
|
+
number += 1
|
|
172
|
+
if FIT.fold_for(row_id) == fold:
|
|
173
|
+
rows.append({'id': row_id, 'text': row_id, 'gold': 'invalid', '_trainer_gold': 'invalid',
|
|
174
|
+
'options': ['invalid'], '_targets': [1.0]})
|
|
175
|
+
logits = {row['id']: [0.0] for row in rows}
|
|
176
|
+
_recipes, predictions = FIT.cross_fit(rows, logits, 'validity', Knn(), LayerApi, fake_fit)
|
|
177
|
+
self.assertTrue(all(len(scores) == 1 for scores in predictions.values()))
|
|
178
|
+
self.assertEqual(FIT.score_rows(rows, ['invalid'], 'validity', predictions)[0]['scores'].keys(), {'invalid'})
|
|
179
|
+
|
|
180
|
+
def test_alpha_is_selected_inside_the_candidate_comparison(self):
|
|
181
|
+
row = {'id': 'wrong-base', 'text': 'synthetic', 'gold': 'b', 'options': ['a', 'b'], '_targets': [0.0, 1.0]}
|
|
182
|
+
|
|
183
|
+
class Neighbor:
|
|
184
|
+
@staticmethod
|
|
185
|
+
def dist(_text, _width):
|
|
186
|
+
return [0.0, 1.0]
|
|
187
|
+
|
|
188
|
+
recipe = FIT.select_recipe([row], {row['id']: [6.0, -6.0]}, 'tier', Neighbor(), LayerApi,
|
|
189
|
+
lambda *_args: (1.0, None))
|
|
190
|
+
self.assertEqual(recipe['candidate'], 'H-knn')
|
|
191
|
+
self.assertEqual(recipe['alpha'], 1.0)
|
|
192
|
+
|
|
193
|
+
def test_keep_base_is_an_explicit_selection_result(self):
|
|
194
|
+
row = {'id': 'base', 'text': 'synthetic', 'gold': 'a', 'options': ['a', 'b'], '_targets': [1.0, 0.0]}
|
|
195
|
+
recipe = FIT.select_recipe([row], {row['id']: [0.0, 0.0]}, 'tier', Knn(), LayerApi,
|
|
196
|
+
lambda *_args: (1.0, None))
|
|
197
|
+
self.assertEqual(recipe['candidate'], 'keep-base')
|
|
198
|
+
|
|
199
|
+
def test_train_index_excludes_validation_ids(self):
|
|
200
|
+
class Trainer:
|
|
201
|
+
@staticmethod
|
|
202
|
+
def join(prompts, labels):
|
|
203
|
+
label_by_id = {row['id']: row for row in labels}
|
|
204
|
+
return [{**prompt, **label_by_id[prompt['id']]} for prompt in prompts]
|
|
205
|
+
|
|
206
|
+
@staticmethod
|
|
207
|
+
def eligible_rows(rows, _task):
|
|
208
|
+
return rows
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def build_targets(row, catalog, task, _target):
|
|
212
|
+
return [float(option == row['gold']) for option in catalog]
|
|
213
|
+
|
|
214
|
+
@staticmethod
|
|
215
|
+
def target_gold(row, _task):
|
|
216
|
+
return row['gold']
|
|
217
|
+
|
|
218
|
+
prompts = [{'id': 'train', 'text': 'train prompt', 'split': 'train'},
|
|
219
|
+
{'id': 'validation', 'text': 'validation prompt', 'split': 'validation'}]
|
|
220
|
+
labels = [{'id': 'train', 'gold': 'tier1'}, {'id': 'validation', 'gold': 'tier2'}]
|
|
221
|
+
index = FIT.build_index(prompts, labels, 'tier', ['tier1', 'tier2'], Trainer)
|
|
222
|
+
self.assertEqual(index, [{'text': 'train prompt', 'target': [1.0, 0.0]}])
|
|
223
|
+
|
|
224
|
+
def test_load_data_audits_metadata_and_uses_only_training_prompts_for_index(self):
|
|
225
|
+
trainer = FIT.load_module('system_one_fit_layer_test_trainer', FIT.REPO / 'scripts/system-one-train.py')
|
|
226
|
+
catalog = trainer.catalog_for('tier', Path(__file__).resolve().parents[1] / 'benchmarks/fixtures/system-one-holdout.json')
|
|
227
|
+
options = [item['id'] for item in catalog]
|
|
228
|
+
with tempfile.TemporaryDirectory(prefix='system-one-layer-input-') as temporary:
|
|
229
|
+
root = Path(temporary)
|
|
230
|
+
bundle, run = root / 'bundle', root / 'run'
|
|
231
|
+
bundle.mkdir()
|
|
232
|
+
run.mkdir()
|
|
233
|
+
prompts = [{'id': 'train-row', 'text': 'train-only prompt', 'split': 'train'},
|
|
234
|
+
{'id': 'validation-row', 'text': 'validation-only prompt', 'split': 'validation'}]
|
|
235
|
+
labels = [{'id': 'train-row', 'gold': options[0]}, {'id': 'validation-row', 'gold': options[0]}]
|
|
236
|
+
(bundle / 'prompts.jsonl').write_text(''.join(json.dumps(row) + '\n' for row in prompts), encoding='utf-8')
|
|
237
|
+
(bundle / 'labels.jsonl').write_text(''.join(json.dumps(row) + '\n' for row in labels), encoding='utf-8')
|
|
238
|
+
datasets = {name: trainer.sha256_file(bundle / name) for name in ('prompts.jsonl', 'labels.jsonl')}
|
|
239
|
+
report = {'task': 'tier', 'target': 'label', 'catalog': options, 'datasets': datasets,
|
|
240
|
+
'counts': {'train': 1, 'validation': 1}, 'config': {'context_tokens': 1024}}
|
|
241
|
+
(run / 'train-report.json').write_text(json.dumps(report), encoding='utf-8')
|
|
242
|
+
checkpoint = {'config': report['config'], 'metadata': {'task': 'tier', 'target': 'label',
|
|
243
|
+
'catalog': options, 'datasets': datasets}}
|
|
244
|
+
(run / 'harness-routing-v1.json').write_text(json.dumps(checkpoint), encoding='utf-8')
|
|
245
|
+
(run / 'val-scores.jsonl').write_text(json.dumps({'id': 'validation-row', 'gold': options[0],
|
|
246
|
+
'scores': {option: 1 / len(options) for option in options}}) + '\n', encoding='utf-8')
|
|
247
|
+
loaded_report, _, _, validation, index, _scores, config_hash = FIT.load_data(bundle, run, 'tier',
|
|
248
|
+
Path(__file__).resolve().parents[1] / 'benchmarks/fixtures/system-one-holdout.json', trainer)
|
|
249
|
+
self.assertEqual(loaded_report, report)
|
|
250
|
+
self.assertEqual(config_hash, hashlib.sha256((run / 'harness-routing-v1.json').read_bytes()).hexdigest())
|
|
251
|
+
self.assertEqual([row['id'] for row in validation], ['validation-row'])
|
|
252
|
+
self.assertEqual([row['text'] for row in index], ['train-only prompt'])
|
|
253
|
+
|
|
254
|
+
checkpoint['metadata']['datasets']['labels.jsonl'] = '0' * 64
|
|
255
|
+
(run / 'harness-routing-v1.json').write_text(json.dumps(checkpoint), encoding='utf-8')
|
|
256
|
+
with self.assertRaisesRegex(ValueError, 'checkpoint-metadata-mismatch'):
|
|
257
|
+
FIT.load_data(bundle, run, 'tier',
|
|
258
|
+
Path(__file__).resolve().parents[1] / 'benchmarks/fixtures/system-one-holdout.json', trainer)
|
|
259
|
+
|
|
260
|
+
def test_fit_fails_if_checkpoint_config_changes_during_inference(self):
|
|
261
|
+
with tempfile.TemporaryDirectory(prefix='system-one-layer-config-race-') as temporary:
|
|
262
|
+
run = Path(temporary)
|
|
263
|
+
config = run / 'harness-routing-v1.json'
|
|
264
|
+
original = b'{"config":{},"metadata":{}}\n'
|
|
265
|
+
config.write_bytes(original)
|
|
266
|
+
trainer = type('Trainer', (), {'sha256_file': staticmethod(lambda file: hashlib.sha256(Path(file).read_bytes()).hexdigest())})
|
|
267
|
+
|
|
268
|
+
def inference(*_args):
|
|
269
|
+
config.write_bytes(b'{"config":{"changed":true},"metadata":{}}\n')
|
|
270
|
+
return {}
|
|
271
|
+
|
|
272
|
+
with patch.object(FIT, 'load_module', return_value=trainer), \
|
|
273
|
+
patch.object(FIT, 'load_layer_api', return_value=object()), \
|
|
274
|
+
patch.object(FIT, 'load_data', return_value=({}, {}, [], [], [], {}, hashlib.sha256(original).hexdigest())), \
|
|
275
|
+
patch.object(FIT, 'infer_logits', side_effect=inference):
|
|
276
|
+
with self.assertRaisesRegex(ValueError, 'checkpoint-config-changed-during-fit'):
|
|
277
|
+
FIT.fit_layer(run, run, 'tier', run / 'holdout.json')
|
|
278
|
+
|
|
279
|
+
def test_intent_oof_rows_preserve_secondary_positives(self):
|
|
280
|
+
source = [{'id': 'intent-1', 'gold': 'primary', '_trainer_gold': 'primary', 'secondary': ['secondary']}]
|
|
281
|
+
result = FIT.score_rows(source, ['primary', 'secondary'], 'intent', {'intent-1': [0.8, 0.2]})
|
|
282
|
+
self.assertEqual(result[0]['secondary'], ['secondary'])
|
|
283
|
+
|
|
284
|
+
def test_holdout_consumer_loads_and_applies_the_manifest_layer(self):
|
|
285
|
+
with tempfile.TemporaryDirectory(prefix='system-one-layer-score-') as temporary:
|
|
286
|
+
directory = Path(temporary)
|
|
287
|
+
options = ['tier1', 'tier2']
|
|
288
|
+
layer = {'schemaVersion': 1, 'kind': 'echl-h', 'stage': 'tier', 'options': options,
|
|
289
|
+
'temperature': 1.0, 'bias': None, 'alpha': 1.0, 'k': 1, 'ngrams': [3],
|
|
290
|
+
'maxChars': 200, 'index': [{'text': 'abc', 'target': [1.0, 0.0]}],
|
|
291
|
+
'fit': {'candidate': 'H-knn', 'heldOutRows': 2, 'nll': 0.1,
|
|
292
|
+
'baseNll': 0.5, 'oof': True}}
|
|
293
|
+
layer_path = directory / 'tier.layer.json'
|
|
294
|
+
layer_path.write_text(json.dumps(layer), encoding='utf-8')
|
|
295
|
+
weights = directory / 'tier.safetensors'
|
|
296
|
+
weights.write_bytes(b'weights')
|
|
297
|
+
digest = hashlib.sha256(layer_path.read_bytes()).hexdigest()
|
|
298
|
+
stage = {'weights': 'tier.safetensors', 'config': 'tier.json', 'sha256': '0' * 64,
|
|
299
|
+
'options': options, 'thresholds': {'tier1': 0.5, 'tier2': 0.5},
|
|
300
|
+
'layer': 'tier.layer.json', 'layerSha256': digest}
|
|
301
|
+
(directory / 'manifest.json').write_text(json.dumps({'stages': {'tier': stage}}), encoding='utf-8')
|
|
302
|
+
layer_api, loaded = SCORE.layer_for(weights, 'tier', options)
|
|
303
|
+
self.assertEqual(layer_api.apply_layer(loaded, [0.0, 0.0], 'abc'), [1.0, 0.0])
|
|
304
|
+
|
|
305
|
+
def test_trainer_targets_drive_real_shaped_gold_and_calibrator_rows(self):
|
|
306
|
+
trainer = FIT.load_module('system_one_fit_layer_real_shape_trainer', FIT.REPO / 'scripts/system-one-train.py')
|
|
307
|
+
holdout = Path(__file__).resolve().parents[1] / 'benchmarks/fixtures/system-one-holdout.json'
|
|
308
|
+
validity_catalog = trainer.catalog_for('validity', holdout)
|
|
309
|
+
raw = [
|
|
310
|
+
{'id': 'valid-null', 'text': 'invalid example', 'gold': None, 'options': ['invalid']},
|
|
311
|
+
{'id': 'valid-tier', 'text': 'actionable example', 'gold': 'tier2', 'options': ['invalid']},
|
|
312
|
+
]
|
|
313
|
+
validity = [FIT.trainer_targets(row, 'validity', validity_catalog, trainer) for row in raw]
|
|
314
|
+
self.assertEqual([row['_trainer_gold'] for row in validity], ['invalid', 'actionable'])
|
|
315
|
+
self.assertEqual([FIT.positives(row, 'validity') for row in validity], [(1,), (0,)])
|
|
316
|
+
layered = FIT.score_rows(validity, ['invalid'], 'validity', {'valid-null': [0.95], 'valid-tier': [0.05]})
|
|
317
|
+
self.assertEqual([row['gold'] for row in layered], ['invalid', 'actionable'])
|
|
318
|
+
with tempfile.TemporaryDirectory(prefix='system-one-layer-calibrate-') as temporary:
|
|
319
|
+
input_file, output_file = Path(temporary) / 'layered.jsonl', Path(temporary) / 'calibration.json'
|
|
320
|
+
input_file.write_text(''.join(json.dumps(row) + '\n' for row in layered), encoding='utf-8')
|
|
321
|
+
result = subprocess.run(['node', str(FIT.REPO / 'scripts/system-one-calibrate.js'), str(input_file),
|
|
322
|
+
str(output_file), '--task', 'validity'], capture_output=True, text=True, check=False)
|
|
323
|
+
self.assertEqual(result.returncode, 0, result.stderr)
|
|
324
|
+
self.assertEqual(json.loads(output_file.read_text(encoding='utf-8'))['rows'], 2)
|
|
325
|
+
|
|
326
|
+
intent_catalog = trainer.catalog_for('intent', holdout)
|
|
327
|
+
intent_ids = [item['id'] for item in intent_catalog]
|
|
328
|
+
intent = FIT.trainer_targets({'id': 'intent-secondary', 'text': 'intent', 'gold': intent_ids[0],
|
|
329
|
+
'secondary': [intent_ids[1]], 'options': intent_ids}, 'intent', intent_catalog, trainer)
|
|
330
|
+
self.assertEqual(FIT.positives(intent, 'intent'), (0, 1))
|
|
331
|
+
tier_catalog = trainer.catalog_for('tier', holdout)
|
|
332
|
+
tier_ids = [item['id'] for item in tier_catalog]
|
|
333
|
+
tier = FIT.trainer_targets({'id': 'tier-row', 'text': 'tier', 'gold': 'tier2', 'options': tier_ids},
|
|
334
|
+
'tier', tier_catalog, trainer)
|
|
335
|
+
self.assertEqual(FIT.positives(tier, 'tier'), (1,))
|
|
336
|
+
|
|
337
|
+
def test_base_nll_guard_rejects_trainer_mismatch(self):
|
|
338
|
+
FIT.assert_base_nll_matches(0.1291, 0.1290)
|
|
339
|
+
with self.assertRaisesRegex(ValueError, 'base-nll-mismatch'):
|
|
340
|
+
FIT.assert_base_nll_matches(4.81, 0.129)
|
|
341
|
+
|
|
342
|
+
def test_precomputed_knn_distributions_preserve_fit_outputs(self):
|
|
343
|
+
rows = rows_for_folds()
|
|
344
|
+
logits = {row['id']: [0.0, 0.0] for row in rows}
|
|
345
|
+
|
|
346
|
+
class CountingKnn:
|
|
347
|
+
def __init__(self):
|
|
348
|
+
self.calls = 0
|
|
349
|
+
|
|
350
|
+
def dist(self, text, width):
|
|
351
|
+
self.calls += 1
|
|
352
|
+
return [1 / width] * width
|
|
353
|
+
|
|
354
|
+
uncached_knn = CountingKnn()
|
|
355
|
+
old_recipes, old_predictions = FIT.cross_fit(rows, logits, 'tier', uncached_knn, LayerApi, fake_fit)
|
|
356
|
+
old_final = FIT.select_recipe(rows, logits, 'tier', uncached_knn, LayerApi, fake_fit)
|
|
357
|
+
cached_knn = CountingKnn()
|
|
358
|
+
distributions = FIT.precompute_knn(rows, 'tier', cached_knn, logits)
|
|
359
|
+
new_recipes, new_predictions = FIT.cross_fit(rows, logits, 'tier', cached_knn, LayerApi, fake_fit,
|
|
360
|
+
distributions)
|
|
361
|
+
new_final = FIT.select_recipe(rows, logits, 'tier', cached_knn, LayerApi, fake_fit, distributions)
|
|
362
|
+
self.assertEqual((new_recipes, new_predictions), (old_recipes, old_predictions))
|
|
363
|
+
self.assertEqual(new_final, old_final)
|
|
364
|
+
self.assertGreater(uncached_knn.calls, len(rows))
|
|
365
|
+
self.assertEqual(cached_knn.calls, len(rows))
|
|
366
|
+
with self.assertRaisesRegex(ValueError, 'base-nll-mismatch'):
|
|
367
|
+
FIT.assert_base_nll_matches(0.129, 0.129 + 0.0011)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
if __name__ == '__main__':
|
|
371
|
+
unittest.main()
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import importlib.util
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import tempfile
|
|
6
|
+
import sys
|
|
7
|
+
import unittest
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
sys.dont_write_bytecode = True
|
|
11
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
12
|
+
MODULE = ROOT / 'harness-everything' / 'scripts' / 'system-one' / 'layer.py'
|
|
13
|
+
spec = importlib.util.spec_from_file_location('system_one_layer', MODULE)
|
|
14
|
+
layer = importlib.util.module_from_spec(spec)
|
|
15
|
+
spec.loader.exec_module(layer)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class LayerTest(unittest.TestCase):
|
|
19
|
+
def valid(self, stage='tier', options=None, **changes):
|
|
20
|
+
options = options or (['invalid'] if stage == 'validity' else ['a', 'b'])
|
|
21
|
+
return {
|
|
22
|
+
'schemaVersion': 1, 'kind': 'echl-h', 'stage': stage, 'options': options,
|
|
23
|
+
'temperature': 1.0, 'bias': None, 'alpha': 0.0, 'k': 15,
|
|
24
|
+
'ngrams': [3, 4, 5], 'maxChars': 2000, 'index': [],
|
|
25
|
+
'fit': {'candidate': 'H-temp', 'heldOutRows': 1, 'nll': 0.1, 'baseNll': 0.2, 'oof': True},
|
|
26
|
+
**changes,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
def test_legacy_transform_and_validity_shapes(self):
|
|
30
|
+
logits = [0.25, -0.5, 1.0]
|
|
31
|
+
raw = [1 / (1 + math.exp(-value)) for value in logits]
|
|
32
|
+
for actual, expected in zip(layer.transform(logits, 'intent'), [value / sum(raw) for value in raw]):
|
|
33
|
+
self.assertAlmostEqual(actual, expected, places=15)
|
|
34
|
+
p = 1 / (1 + math.exp(-0.25))
|
|
35
|
+
self.assertEqual(layer.transform([0.25], 'validity'), [1 - p, p])
|
|
36
|
+
self.assertEqual(layer.apply_layer(self.valid(options=['a', 'b', 'c']), logits, 'ignored'),
|
|
37
|
+
layer.transform(logits, 'tier'))
|
|
38
|
+
|
|
39
|
+
def test_tie_order_matches_experiment_counter_first_encounter(self):
|
|
40
|
+
index = layer.KnnIndex([
|
|
41
|
+
{'text': 'abc', 'target': [1, 0]}, {'text': 'xyz', 'target': [0, 1]},
|
|
42
|
+
], 'tier', k=1)
|
|
43
|
+
# For xyz abc, xyz grams are encountered first and select row 1 on the tie.
|
|
44
|
+
self.assertEqual(index.dist('xyz abc', 2), [0.0, 1.0])
|
|
45
|
+
control = layer.KnnIndex([
|
|
46
|
+
{'text': 'xyz', 'target': [1, 0]}, {'text': 'abc', 'target': [0, 1]},
|
|
47
|
+
], 'tier', k=1)
|
|
48
|
+
self.assertEqual(control.dist('xyz abc', 2), [1.0, 0.0])
|
|
49
|
+
|
|
50
|
+
def test_apply_matches_temperature_bias_and_neighbor_blend(self):
|
|
51
|
+
data = self.valid(alpha=0.6, k=1, ngrams=[3], maxChars=2000,
|
|
52
|
+
index=[{'text': 'small change', 'target': [0, 1]}])
|
|
53
|
+
logits = [0.0, 0.0]
|
|
54
|
+
result = layer.apply_layer(data, logits, 'small change')
|
|
55
|
+
self.assertEqual(result, [0.2, 0.8])
|
|
56
|
+
self.assertEqual(layer.apply_layer({**data, 'alpha': 0.0}, logits, 'small change'), [0.5, 0.5])
|
|
57
|
+
|
|
58
|
+
def test_intent_soft_targets_and_temperature_bias_match_shared_transform(self):
|
|
59
|
+
data = self.valid(stage='intent', temperature=2.0, bias=[math.log(3), 0.0],
|
|
60
|
+
alpha=1.0, index=[{'text': 'multi label', 'target': [0.25, 0.75]}])
|
|
61
|
+
for actual, expected in zip(layer.apply_layer(data, [0.0, 0.0], 'multi label'), [0.25, 0.75]):
|
|
62
|
+
self.assertAlmostEqual(actual, expected)
|
|
63
|
+
fitted = layer.transform([0.0, 0.0], 'intent', 2.0, [math.log(3), 0.0])
|
|
64
|
+
self.assertAlmostEqual(fitted[0], 0.6)
|
|
65
|
+
self.assertAlmostEqual(fitted[1], 0.4)
|
|
66
|
+
self.assertEqual(layer.apply_layer({**data, 'alpha': 0.0, 'index': []}, [0, 0], 'multi label'),
|
|
67
|
+
fitted)
|
|
68
|
+
|
|
69
|
+
def test_validity_neighbors_convert_binary_target_to_two_classes(self):
|
|
70
|
+
data = self.valid('validity', alpha=1.0, index=[{'text': 'bad request', 'target': [0.8]}])
|
|
71
|
+
self.assertEqual(layer.apply_layer(data, [0.0], 'bad request'), [0.8])
|
|
72
|
+
|
|
73
|
+
def test_load_builds_the_knn_index_once_and_requests_reuse_it(self):
|
|
74
|
+
index = [{'text': 'fix the login test', 'target': [1.0, 0.0]}, {'text': 'plan the release', 'target': [0.0, 1.0]}]
|
|
75
|
+
with tempfile.TemporaryDirectory() as temp:
|
|
76
|
+
file = Path(temp) / 'tier.layer.json'
|
|
77
|
+
payload = json.dumps(self.valid(alpha=0.5, index=index)).encode()
|
|
78
|
+
file.write_bytes(payload)
|
|
79
|
+
loaded = layer.load_layer(file, hashlib.sha256(payload).hexdigest(), 'tier', ['a', 'b'])
|
|
80
|
+
built = loaded['_knn']
|
|
81
|
+
reference = layer.apply_layer(dict(self.valid(alpha=0.5, index=index)), [0.2, -0.1], 'fix the login')
|
|
82
|
+
self.assertEqual(layer.apply_layer(loaded, [0.2, -0.1], 'fix the login'), reference)
|
|
83
|
+
self.assertIs(loaded['_knn'], built)
|
|
84
|
+
|
|
85
|
+
def test_load_checks_hash_then_schema_and_stage_option_order(self):
|
|
86
|
+
with tempfile.TemporaryDirectory() as temp:
|
|
87
|
+
file = Path(temp) / 'tier.layer.json'
|
|
88
|
+
payload = json.dumps(self.valid()).encode()
|
|
89
|
+
file.write_bytes(payload)
|
|
90
|
+
digest = hashlib.sha256(payload).hexdigest()
|
|
91
|
+
self.assertEqual(layer.load_layer(file, digest, 'tier', ['a', 'b'])['stage'], 'tier')
|
|
92
|
+
with self.assertRaisesRegex(ValueError, 'artifact-hash'):
|
|
93
|
+
layer.load_layer(file, '0' * 64, 'tier', ['a', 'b'])
|
|
94
|
+
with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
|
|
95
|
+
layer.load_layer(file, digest, 'intent', ['a', 'b'])
|
|
96
|
+
with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
|
|
97
|
+
layer.load_layer(file, digest, 'tier', ['b', 'a'])
|
|
98
|
+
|
|
99
|
+
def test_rejects_nonfinite_values_and_malformed_pairs(self):
|
|
100
|
+
for changes in (
|
|
101
|
+
{'temperature': float('nan')}, {'temperature': 0}, {'alpha': float('inf')},
|
|
102
|
+
{'bias': [float('nan'), 0]}, {'index': [{'text': 'x', 'target': [0, float('nan')]}]},
|
|
103
|
+
{'k': True}, {'ngrams': [0]}, {'maxChars': True},
|
|
104
|
+
):
|
|
105
|
+
with self.subTest(changes=changes), tempfile.TemporaryDirectory() as temp:
|
|
106
|
+
file = Path(temp) / 'layer.json'
|
|
107
|
+
raw = json.dumps(self.valid(**changes)).encode()
|
|
108
|
+
file.write_bytes(raw)
|
|
109
|
+
with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
|
|
110
|
+
layer.load_layer(file, hashlib.sha256(raw).hexdigest(), 'tier', ['a', 'b'])
|
|
111
|
+
|
|
112
|
+
def test_file_size_limit_is_checked_before_read(self):
|
|
113
|
+
with tempfile.TemporaryDirectory() as temp:
|
|
114
|
+
file = Path(temp) / 'large.layer.json'
|
|
115
|
+
with file.open('wb') as handle:
|
|
116
|
+
handle.truncate(32 * 1024 * 1024 + 1)
|
|
117
|
+
with self.assertRaisesRegex(ValueError, 'checkpoint-format'):
|
|
118
|
+
layer.load_layer(file, '0' * 64, 'tier', ['a', 'b'])
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == '__main__':
|
|
122
|
+
unittest.main()
|