"""Train a tiny Transformer and select bounded Emacs actions from English.""" import argparse from dataclasses import dataclass import json import hashlib import math from pathlib import Path import torch from actions import Action, ActionKind, InputError, Program, action_argument, parse_command from intent_model import IntentClassifier, LABELS, ModelConfig, collate, encode, tokenize from data_arguments import example_argument, materialize ROOT = Path(__file__).resolve().parent # Last phrase is held out for evaluation. NAME represents one quoted literal. COMMANDS = [ ("(split-window-right)", ["split right", "split the window to the right", "make a pane on the right", "put a new window on the right"]), ("(split-window-below)", ["split below", "split the window below", "make a pane below", "put a new window below"]), ("(other-window 1)", ["select the next window", "focus the next pane", "move to the next window", "switch focus to the next window"]), ("(delete-other-windows)", ["keep only this window", "close the other panes", "maximize this window", "close every other window"]), ("(balance-windows)", ["balance the windows", "equalize pane sizes", "make all panes equal", "give the windows equal sizes"]), ("(beginning-of-buffer)", ["go to buffer start", "jump to the beginning", "move to the top", "take me to the top of the buffer"]), ("(end-of-buffer)", ["go to buffer end", "jump to the end", "move to the bottom", "take me to the bottom of the buffer"]), ("(switch-to-buffer NAME)", ["switch to buffer NAME", "show buffer NAME", "visit the buffer NAME", "display the buffer named NAME"]), ] def examples(): singles = [] pairs = [] hold = [] paraphrase = [] for i, (form, phrases) in enumerate(COMMANDS): singles.extend((p, form) for p in phrases[:-1]) paraphrase.append((phrases[-1], form)) for j, (second, others) in enumerate(COMMANDS): if i == j: continue dest = hold if j == (i+1) % len(COMMANDS) else pairs for a in phrases[:-1]: for b in others[:-1]: for join in [" then ", " and then "]: dest.append((a + join + b, f"(progn {form} {second})")) return singles + pairs, paraphrase, hold @dataclass(frozen=True) class ActionScore: """An intent score, with None representing the learned reject category.""" kind: ActionKind | None probability: float def score_actions(model, vocab, phrase): """Rank the fixed action labels and rejection; retain unknown-word features.""" word_ids, char_ids = collate([encode(phrase, vocab, model.config)], model.config) with torch.no_grad(): probabilities = model(word_ids, char_ids).softmax(-1)[0].tolist() if not all(math.isfinite(probability) for probability in probabilities): raise InputError('The model could not score this command.') scores = [ActionScore(None if label == 'reject' else ActionKind(label), probability) for label, probability in zip(LABELS, probabilities)] return tuple(sorted(scores, key=lambda score: score.probability, reverse=True)) def infer(model, vocab, command): """Return a validated program, or reject unsupported or uncertain input.""" clauses = parse_command(command) actions = [] for clause in clauses: best, runner_up, *_ = score_actions(model, vocab, clause.text) if best.kind is None: raise InputError('This operation is outside the supported action set.') margin = best.probability - runner_up.probability if (best.probability < model.thresholds['probability'] or margin < model.thresholds['margin']): raise InputError('The model is uncertain; rephrase the requested operation.') needs_name = action_argument(best.kind) is not None if needs_name != (clause.name is not None): raise InputError('A quoted argument must belong to an action that accepts a string.') actions.append(Action(best.kind, clause.name)) return Program(tuple(actions)) def decode(model, vocab, commands): """Render constrained predictions; reject the batch if any input is invalid.""" return [infer(model, vocab, command).to_lisp() for command in commands] def _evaluate_rows(model, vocab, rows): """Count correct accepted commands, mistakes and refusals without conflating them.""" errors, rejected = [], [] correct = oov_total = oov_correct = 0 for phrase, expected in rows: phrase = materialize(phrase) expected = materialize(expected) if expected is not None else None try: normalized_words = {word for clause in parse_command(phrase) for word in tokenize(clause.text)} except InputError: normalized_words = set() novel_words = normalized_words - vocab.keys() oov_total += bool(novel_words) try: actual = infer(model, vocab, phrase).to_lisp() except InputError as error: rejected.append(dict(input=phrase, reason=str(error))) else: if actual == expected: correct += 1 oov_correct += bool(novel_words) else: errors.append(dict(input=phrase, expected=expected, actual=actual)) return dict(total=len(rows), correct=correct, wrong=len(errors), rejected=len(rejected), with_novel_words=oov_total, correct_with_novel_words=oov_correct, errors=errors, refusals=rejected) def _action_form(label, argument='Notes'): kind = ActionKind(label) return Action(kind, argument if action_argument(kind) else None).to_lisp() def _canonical_command(phrase): """Compare the actual normalized model input, with names treated as data.""" try: return tuple(clause.text for clause in parse_command(materialize(phrase))) except InputError: return ('invalid syntax', ' '.join(phrase.lower().split())) def _checkpoint_identity(): """Identify the active local training checkpoint or published safe artifact.""" checkpoint = ROOT / 'model.pt' if checkpoint.is_file(): return {'checkpoint_sha256': hashlib.sha256(checkpoint.read_bytes()).hexdigest()} metadata = json.loads((ROOT / 'config.json').read_text()) return { 'checkpoint_sha256': metadata['source_checkpoint_sha256'], 'weights_sha256': hashlib.sha256((ROOT / 'model.safetensors').read_bytes()).hexdigest(), 'config_sha256': hashlib.sha256((ROOT / 'config.json').read_bytes()).hexdigest(), } def _composition_rows(grouped, cross_domain=False): """Recombine one representative per ordered action pair, keeping literals typed. Cross-domain rows pair an Emacs operation with a LispM operation. They test ordered composition, not independently authored conversational language. """ rows = [] for first_index, (first, phrases) in enumerate(grouped.items()): for second_index, (second, others) in enumerate(grouped.items()): if first == second or not phrases or not others: continue if cross_domain and first.startswith('lispm-') == second.startswith('lispm-'): continue first_arg = example_argument(first, 'first argument') second_arg = example_argument(second, 'second argument') phrase = materialize(phrases[(first_index + second_index) % len(phrases)], first, first_arg) other = materialize(others[(first_index * 3 + second_index) % len(others)], second, second_arg) expected = f'(progn {_action_form(first, first_arg)} {_action_form(second, second_arg)})' rows.append((phrase + ' then ' + other, expected)) return rows def _evaluate_lispm_corpus(model, vocab, seen, original_grouped): """Evaluate the independently authored LispM corpus after model selection. Exact normalized overlap is excluded from both positive and negative rows. Original Emacs phrases are used only for a separate recombination measure. """ corpus_path = ROOT / 'lispm_generalization_cases.json' corpus = json.loads(corpus_path.read_text()) supported = [row for row in corpus['supported'] if _canonical_command(row['input']) not in seen] unsupported = [row for row in corpus['unsupported'] if _canonical_command(row['input']) not in seen] rows = [] for row in supported: argument = row.get('argument', example_argument(row['action'])) rows.append((materialize(row['input'], row['action'], argument), _action_form(row['action'], argument))) negative_rows = [(materialize(row['input'], argument=row.get('argument')), None) for row in unsupported] labels = [label for label in LABELS if label.startswith('lispm-')] grouped = {label: [row['input'] for row in supported if row['action'] == label] for label in labels} per_action = {label: _evaluate_rows(model, vocab, [pair for row, pair in zip(supported, rows) if row['action'] == label]) for label in labels} return { 'lispm_frozen_corpus_sha256': hashlib.sha256(corpus_path.read_bytes()).hexdigest(), 'lispm_excluded_exact_overlap': { 'supported': len(corpus['supported']) - len(supported), 'unsupported': len(corpus['unsupported']) - len(unsupported), 'rows': [row['input'] for row in corpus['supported'] + corpus['unsupported'] if _canonical_command(row['input']) in seen], }, 'lispm_independent_paraphrase': _evaluate_rows(model, vocab, rows), 'lispm_independent_unsupported': _evaluate_rows(model, vocab, negative_rows), 'lispm_independent_composition': _evaluate_rows(model, vocab, _composition_rows(grouped)), 'cross_domain_composition': _evaluate_rows( model, vocab, _composition_rows({**original_grouped, **grouped}, cross_domain=True)), 'lispm_per_action': per_action, } def evaluate(model, vocab): """Evaluate legacy regressions and the independently frozen paraphrase corpus.""" from command_data import calibration_rows, training_rows train_set, para, comp = examples() mixed = [ (a + join + b, f'(progn {first} {second})') for i, (first, phrases) in enumerate(COMMANDS) for j, (second, others) in enumerate(COMMANDS) if i != j for ai, a in enumerate(phrases) for bi, b in enumerate(others) if ai == 3 or bi == 3 for join in [' then '] ] report = { 'decoder': 'word_subword_intent_classifier', 'action_count': len(ActionKind), 'actions': [kind.value for kind in ActionKind], 'thresholds': model.thresholds, **_checkpoint_identity(), 'note': 'Scores are heuristic filters, not a guarantee of correct intent.', } for name, rows in [('legacy_examples', train_set), ('paraphrase', para), ('unseen_ordered_pair', comp), ('composed_paraphrase', mixed)]: report[name] = _evaluate_rows(model, vocab, rows) probes = ['', '!!!', '你好', 'unicorns frobnicate', 'do not split right', 'split right before split below', 'show buffer Notes', 'show buffer "Notes', 'split right "Notes"', 'split right then split below then balance the windows', 'focus right', 'maximize other window'] report['unsupported_probes'] = _evaluate_rows(model, vocab, [(phrase, None) for phrase in probes]) frozen_path = ROOT / 'expanded_generalization_cases.json' frozen = json.loads(frozen_path.read_text()) report['frozen_corpus_sha256'] = hashlib.sha256(frozen_path.read_bytes()).hexdigest() seen = {_canonical_command(phrase) for phrase, _ in training_rows() + calibration_rows()} unseen = [row for row in frozen['supported'] if _canonical_command(row['input']) not in seen] unseen_negative = [row for row in frozen['unsupported'] if _canonical_command(row['input']) not in seen] report['excluded_exact_overlap'] = { 'supported': len(frozen['supported']) - len(unseen), 'unsupported': len(frozen['unsupported']) - len(unseen_negative), 'normalization': 'same clause text after case, whitespace and quoted-name normalization', 'rows': [row['input'] for row in frozen['supported'] + frozen['unsupported'] if _canonical_command(row['input']) in seen], } report['independent_paraphrase'] = _evaluate_rows( model, vocab, [(row['input'], _action_form(row['action'])) for row in unseen]) report['per_action'] = { label: _evaluate_rows(model, vocab, [(row['input'], _action_form(label)) for row in unseen if row['action'] == label]) for label in LABELS if label != 'reject' } report['independent_unsupported'] = _evaluate_rows( model, vocab, [(row['input'], None) for row in unseen_negative]) grouped = {label: [row['input'] for row in unseen if row['action'] == label] for label in LABELS if label != 'reject'} report['independent_composition'] = _evaluate_rows(model, vocab, _composition_rows(grouped)) report['evaluation_scope'] = { 'independent_paraphrase': 'Previously exposed 24-action corpus; regression for this expansion.', 'lispm_independent_paraphrase': 'Previously exposed LispM corpus; regression during robustness tuning.', 'compositions': 'Deterministic recombinations, not independently authored requests.', } report.update(_evaluate_lispm_corpus(model, vocab, seen, {label: phrases for label, phrases in grouped.items() if phrases})) return report def load(): """Load a local training checkpoint, or the published safe artifact. A newly trained model.pt takes precedence so --train never silently leaves inference using older exported weights. Published repositories omit that training file and load config.json plus model.safetensors instead. """ if not (ROOT / 'model.pt').is_file(): from hub_model import EmacsCommandModel bundle = EmacsCommandModel.from_pretrained(ROOT, local_files_only=True) return bundle.model, bundle.vocab state = torch.load(ROOT / 'model.pt', map_location='cpu', weights_only=True) if state.get('format_version') != 3 or state.get('labels') != list(LABELS): raise ValueError('Incompatible checkpoint; train the current model with --train.') model = IntentClassifier(len(state['vocab']), ModelConfig(**state['architecture'])) model.load_state_dict(state['model']) model.thresholds = state['thresholds'] return model.eval(), state['vocab'] def main(): """Expose proposal-only inference and explicit training/evaluation commands.""" cli = argparse.ArgumentParser() mode = cli.add_mutually_exclusive_group() mode.add_argument('--infer', help='English instruction; string arguments use JSON double-quoted strings') mode.add_argument('--train', action='store_true', help='retrain and overwrite model.pt/evaluation.json') mode.add_argument('--evaluate', action='store_true', help='write inference-evaluation.json using current weights') cli.add_argument('--format', choices=('lisp', 'json'), default='lisp', help='inference output format') args = cli.parse_args() torch.manual_seed(42) torch.set_num_threads(2) if args.train: from training import train print(json.dumps(train(ROOT), indent=2)) elif args.evaluate: model, vocab = load() report = evaluate(model, vocab) (ROOT / 'inference-evaluation.json').write_text(json.dumps(report, indent=2) + '\n') print(json.dumps({name: {key: value[key] for key in ('correct', 'wrong', 'rejected', 'total')} for name, value in report.items() if isinstance(value, dict) and 'total' in value}, indent=2)) elif args.infer is not None: model, vocab = load() try: program = infer(model, vocab, args.infer) except InputError as error: cli.error(str(error)) if args.format == 'json': print(json.dumps({'actions': [dict(action=action.kind.value, **({action_argument(action.kind): action.name} if action.name is not None else {})) for action in program.actions]}, ensure_ascii=False)) else: print(program.to_lisp()) else: cli.print_help() if __name__ == '__main__': main()