File size: 8,666 Bytes
36fe364 fac4d07 36fe364 fac4d07 36fe364 fac4d07 36fe364 fac4d07 36fe364 fac4d07 36fe364 fac4d07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | """Maintain historical Python migration references; native training never invokes this script.
The dataset is exported separately from evaluation cases. Gradient references
use the preserved python-reference artifact and disabled dropout to compare
numerical behavior. This developer maintenance command regenerates historical
training/evaluation inputs from the original Python generators; it does not
prepare semantic-training.json, evaluate the current default, or select models.
"""
import copy
import hashlib
import json
from pathlib import Path
import sys
# Permit running this explicit development adapter from the repository root.
ROOT = Path(__file__).resolve().parents[1]
# Numerical witnesses stay tied to the archived Python model after promotion.
REFERENCE_ARTIFACT = ROOT / 'python-reference'
sys.path.insert(0, str(ROOT))
import torch
from safetensors.torch import save_file
from actions import Action, ActionKind, InputError, Program, action_argument
from command_data import calibration_rows, hard_training_rows, training_rows
from compare_models import CORPORA, _cohort, _novel, _seen_inputs
from data_arguments import example_argument, materialize
from hub_model import EmacsCommandModel
from intent_model import collate, encode, make_vocab
from training import rows_sha256
def write_json(path, value):
"""Write deterministic UTF-8 fixtures and create their owned parent directory."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
def digest(path):
"""Identify the exact local input bytes used by the migration reference."""
return hashlib.sha256(path.read_bytes()).hexdigest()
def export_training():
"""Freeze training/calibration text and sampling membership, excluding tests."""
rows = training_rows()
calibration = calibration_rows()
positions = {row: index for index, row in enumerate(rows)}
reference_path = ROOT / 'selection_reference.json'
data = {
'format_version': 1,
'training_rows': rows,
'calibration_rows': calibration,
'calibration_commands': [materialize(text, label) for text, label in calibration],
'hard_training_indices': [positions[row] for row in hard_training_rows()],
'reference': json.loads(reference_path.read_text()),
'selection_reference_json': reference_path.read_text(),
'training_sha256': rows_sha256(rows),
'calibration_sha256': rows_sha256(calibration),
'selection_reference_sha256': digest(reference_path),
}
write_json(ROOT / 'data/training.json', data)
def export_evaluation(bundle):
"""Retain the exact shared cohorts used for the already published comparison."""
seen = _seen_inputs()
vocabulary = set(bundle.vocab)
# The original vocabulary is reproducible from its frozen training rows.
# This also works in the published repository, without private checkpoints.
vocabulary.update(make_vocab(training_rows(False)))
corpora = {}
for name, filename in CORPORA.items():
path = ROOT / filename
corpus = json.loads(path.read_text())
supported, unsupported, positive_sources, negative_sources = _cohort(corpus, seen)
rows = []
for split, cases, sources in [('supported', supported, positive_sources),
('unsupported', unsupported, negative_sources)]:
for (text, expected), source in zip(cases, sources):
rows.append({'input': text, 'expected': expected, 'split': split,
'action': source.get('action'), 'group': source.get('group'),
'novel_to_both': _novel(text, vocabulary)})
corpora[name] = {'sha256': digest(path), 'cases': rows}
write_json(ROOT / 'data/evaluation.json', {
'format_version': 1,
'policy': 'Previously published frozen regression cohorts; never used for Rust checkpoint selection.',
'corpora': corpora,
})
return [row['input'] for corpus in corpora.values() for row in corpus['cases']]
def boundary_examples():
"""Exercise syntax, literal escaping, domain validation and known confusions."""
return [
'', '!!!', '你好', 'do not split right', 'save or close the buffer',
'split right then split right', 'split right then save buffer then undo',
'switch to buffer "中文 Notes"', 'open file "a\\\"b.el"',
'search forward for "a\\nb"', 'new folder in finder "../bad"',
'open url "javascript:alert(1)"', 'open url "https://example.org/a"',
'duplicate the current browser tab', 'close the current browser tab',
'return the active browser tab to the prior page',
'create a sticky note "duplicate the current browser tab"',
'open file "notes.el" then search forward for "TODO"',
]
def export_reference(bundle, commands):
"""Freeze token/logit/decision and deterministic AdamW step parity witnesses."""
fixtures = ROOT / 'tests/fixtures'
phrases = ['save buffer', 'split right', 'open file NAME', 'glide to buffer end',
'duplicate the current browser tab', 'close the current browser tab',
'make finder list its parent directory', 'create a sticky note NAME']
encoded = [encode(text, bundle.vocab, bundle.model.config) for text in phrases]
inputs = collate(encoded, bundle.model.config)
model = copy.deepcopy(bundle.model).eval()
labels = [0, 11, 22, 33, 44, 48, 9, 30]
logits = model(*inputs)
loss = torch.nn.functional.cross_entropy(logits, torch.tensor(labels), label_smoothing=0.05)
optimizer = torch.optim.AdamW(model.parameters(), lr=0.002, weight_decay=0.01)
optimizer.zero_grad()
loss.backward()
fixtures.mkdir(parents=True, exist_ok=True)
save_file({name: parameter.grad.detach().contiguous()
for name, parameter in model.named_parameters()}, fixtures / 'python-gradients.safetensors')
gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
save_file({name: value.detach().contiguous() for name, value in model.state_dict().items()},
fixtures / 'python-adamw-step.safetensors')
decisions = []
for command in dict.fromkeys(commands + boundary_examples()):
try:
actual = bundle.predict(command).to_lisp()
except InputError:
actual = None
decisions.append({'input': command, 'expected': actual})
rendering = []
actions = [Action(kind, example_argument(kind.value, '中文 "sample"\ntext')
if action_argument(kind) else None) for kind in ActionKind
if kind is not ActionKind.FINDER_NEW_FOLDER]
actions.append(Action(ActionKind.FINDER_NEW_FOLDER, 'Notes'))
for first in actions:
rendering.append({'actions': [{'label': first.kind.value, 'argument': first.name}],
'expected': first.to_lisp()})
for second in actions:
if first.kind != second.kind:
rendering.append({'actions': [{'label': item.kind.value, 'argument': item.name}
for item in (first, second)],
'expected': Program((first, second)).to_lisp()})
write_json(fixtures / 'python-reference.json', {
'format_version': 1, 'torch_version': str(torch.__version__),
'weights_sha256': digest(REFERENCE_ARTIFACT / 'model.safetensors'),
'phrases': phrases, 'encoded': [{'word_ids': words, 'char_ids': chars}
for words, chars in encoded],
'logits': logits.detach().tolist(), 'targets': labels,
'loss': float(loss.detach()), 'gradient_norm': float(gradient_norm),
'decisions': decisions, 'rendering': rendering,
'gradients_sha256': digest(fixtures / 'python-gradients.safetensors'),
'adamw_step_sha256': digest(fixtures / 'python-adamw-step.safetensors'),
})
def main():
"""Regenerate historical references without changing any model weights."""
torch.set_num_threads(2)
bundle = EmacsCommandModel.from_pretrained(REFERENCE_ARTIFACT, local_files_only=True)
export_training()
commands = export_evaluation(bundle)
export_reference(bundle, commands)
print(json.dumps({'training_rows': len(training_rows()),
'calibration_rows': len(calibration_rows()),
'evaluation_commands': len(commands),
'torch_version': str(torch.__version__)}, indent=2))
if __name__ == '__main__':
main()
|