Download compare_models.py from ElderRyan/lispm-llm: direct link, hf CLI and curl.
- Browser
- Download file 8.27 kB
-
https://huggingface.co/ElderRyan/lispm-llm/resolve/main/compare_models.py
- Command line
-
hf download hf://ElderRyan/lispm-llm/compare_models.py
-
curl -L -o compare_models.py https://huggingface.co/ElderRyan/lispm-llm/resolve/main/compare_models.py
8.27 kB
| """Compare unchanged and retrained models on identical frozen evaluation cohorts. | |
| Historical corpora are development regressions; robustness_generalization_cases | |
| is the fresh blind set. Both models use the union of old/new training and | |
| calibration exclusions, and the same novel-to-both slice. This script does not | |
| train, select a checkpoint, or adjust confidence thresholds. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import torch | |
| from actions import Action, ActionKind, InputError, action_argument, parse_command | |
| from command_data import calibration_rows, training_rows | |
| from data_arguments import example_argument, materialize | |
| from hub_model import EmacsCommandModel | |
| from intent_model import tokenize | |
| from lispm import _canonical_command, _evaluate_rows | |
| # Only these named frozen corpora are evaluated; no glob can silently add data. | |
| ROOT = Path(__file__).resolve().parent | |
| CORPORA = { | |
| 'historical_emacs': 'expanded_generalization_cases.json', | |
| 'historical_lispm': 'lispm_generalization_cases.json', | |
| 'fresh_robustness': 'robustness_generalization_cases.json', | |
| } | |
| def load_bundle(path): | |
| """Load a local .pt checkpoint or a local safe-artifact directory.""" | |
| path = Path(path) | |
| return (EmacsCommandModel.from_checkpoint(path) if path.is_file() | |
| else EmacsCommandModel.from_pretrained(path, local_files_only=True)) | |
| def _seen_inputs(): | |
| """Exclude anything seen by either model, using the actual normalized clauses.""" | |
| rows = (training_rows(False) + calibration_rows(False) | |
| + training_rows() + calibration_rows()) | |
| return {_canonical_command(phrase) for phrase, _ in rows} | |
| def _cohort(corpus, seen): | |
| """Materialize typed arguments and keep source rows aligned with admitted cases.""" | |
| supported, unsupported, source_supported, source_unsupported = [], [], [], [] | |
| for row in corpus['supported']: | |
| if _canonical_command(row['input']) in seen: | |
| continue | |
| kind = ActionKind(row['action']) | |
| argument = row.get('argument', example_argument(kind.value)) | |
| actual_input = materialize(row['input'], kind.value, argument) | |
| expected = Action(kind, argument if action_argument(kind) else None).to_lisp() | |
| supported.append((actual_input, expected)) | |
| source_supported.append(row) | |
| for row in corpus['unsupported']: | |
| if _canonical_command(row['input']) in seen: | |
| continue | |
| unsupported.append((materialize(row['input'], argument=row.get('argument')), None)) | |
| source_unsupported.append(row) | |
| return supported, unsupported, source_supported, source_unsupported | |
| def _novel(phrase, vocabulary): | |
| """Check for command words outside the shared vocabulary, ignoring literal data.""" | |
| try: | |
| words = {word for clause in parse_command(phrase) for word in tokenize(clause.text)} | |
| except InputError: | |
| return False | |
| return bool(words - vocabulary) | |
| def _score(bundle, rows): | |
| """Preserve correct/wrong/refused counts and full failure details.""" | |
| return _evaluate_rows(bundle.model, bundle.vocab, rows) | |
| def compare(candidate, baseline=None): | |
| """Evaluate both models on each identical cohort without inspecting results for selection.""" | |
| training_hash = hashlib.sha256(json.dumps(training_rows(), ensure_ascii=False).encode()).hexdigest() | |
| calibration_hash = hashlib.sha256(json.dumps(calibration_rows(), ensure_ascii=False).encode()).hexdigest() | |
| if (candidate.metadata['training'].get('training_sha256') != training_hash | |
| or candidate.metadata['training'].get('calibration_sha256') != calibration_hash): | |
| raise ValueError('Candidate was not trained/selected on the current documented splits.') | |
| if baseline is not None: | |
| reference = json.loads((ROOT / 'selection_reference.json').read_text()) | |
| original_hash = hashlib.sha256(json.dumps(training_rows(False), ensure_ascii=False).encode()).hexdigest() | |
| if (baseline.metadata['source_checkpoint_sha256'] != reference['checkpoint_sha256'] | |
| or baseline.metadata['training'].get('training_sha256') != original_hash | |
| or baseline.metadata['thresholds'] != reference['thresholds']): | |
| raise ValueError('Baseline does not match the fixed original model and training split.') | |
| bundles = {'candidate': candidate} | |
| if baseline is not None: | |
| bundles['baseline'] = baseline | |
| vocabulary = set().union(*(bundle.vocab.keys() for bundle in bundles.values())) | |
| seen = _seen_inputs() | |
| report = { | |
| 'model_checkpoints': {name: bundle.metadata['source_checkpoint_sha256'] | |
| for name, bundle in bundles.items()}, | |
| 'thresholds': {name: bundle.metadata['thresholds'] for name, bundle in bundles.items()}, | |
| 'training_sha256': training_hash, | |
| 'calibration_sha256': calibration_hash, | |
| 'novelty_policy': 'Use words outside the union of the loaded models vocabularies; identical slice for each model.', | |
| 'cohort_policy': 'Exclude the union of old/new training and calibration; same rows for both models.', | |
| 'selection': 'Fresh corpus evaluated after checkpoint selection; no tuning on these results.', | |
| '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) | |
| novel = [row for row in supported if _novel(row[0], vocabulary)] | |
| groups = sorted({row['group'] for row in negative_sources if 'group' in row}) | |
| results = {} | |
| for model_name, bundle in bundles.items(): | |
| results[model_name] = { | |
| 'supported': _score(bundle, supported), | |
| 'unsupported': _score(bundle, unsupported), | |
| 'novel_to_both_supported': _score(bundle, novel), | |
| 'unsupported_groups': { | |
| group: _score(bundle, [case for source, case in zip(negative_sources, unsupported) | |
| if source.get('group') == group]) | |
| for group in groups | |
| }, | |
| 'per_action': { | |
| kind.value: _score(bundle, [case for source, case in zip(positive_sources, supported) | |
| if source['action'] == kind.value]) | |
| for kind in ActionKind | |
| if any(row['action'] == kind.value for row in positive_sources) | |
| }, | |
| } | |
| report['corpora'][name] = { | |
| 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(), | |
| 'excluded_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], | |
| }, | |
| 'results': results, | |
| } | |
| return report | |
| def main(): | |
| """Write a comparison report; the optional baseline is never downloaded.""" | |
| cli = argparse.ArgumentParser(description=__doc__) | |
| cli.add_argument('--candidate', type=Path, default=ROOT / 'model.pt') | |
| cli.add_argument('--baseline', type=Path, help='archived model.pt or safe artifact directory') | |
| cli.add_argument('--output', type=Path, default=ROOT / 'comparison-evaluation.json') | |
| args = cli.parse_args() | |
| torch.set_num_threads(2) | |
| candidate = load_bundle(args.candidate) | |
| baseline = load_bundle(args.baseline) if args.baseline else None | |
| report = compare(candidate, baseline) | |
| args.output.write_text(json.dumps(report, indent=2, ensure_ascii=False) + '\n') | |
| summary = {corpus: {name: {split: {key: metrics[split][key] | |
| for key in ('total', 'correct', 'wrong', 'rejected')} | |
| for split in ('supported', 'unsupported', 'novel_to_both_supported')} | |
| for name, metrics in data['results'].items()} | |
| for corpus, data in report['corpora'].items()} | |
| print(json.dumps(summary, indent=2)) | |
| if __name__ == '__main__': | |
| main() | |