lispm-llm / export_hf.py
Ryan.K
Publish open-vocabulary bi-encoder, continual learning, and technical paper
4a54697 unverified
Raw History Blame Contribute Delete
42.9 kB
"""Build a self-contained Hugging Face upload directory from verified artifacts.
Only the explicit release allowlist is copied. Local checkpoints, experiments,
credentials and Git metadata never enter the upload directory. This command
does not contact the Hub, create a remote repository, or upload anything.
"""
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import shutil
import tempfile
from command_data import calibration_rows, training_rows
from hub_model import EmacsCommandModel
# Source tree containing the implementation, corpus generators and reports.
ROOT = Path(__file__).resolve().parent
# Explicit publication boundary; adding a local file cannot silently publish it.
RELEASE_FILES = (
'.gitattributes', '.gitignore', 'LICENSE', 'README.md', 'requirements.txt',
'actions.py', 'intent_model.py', 'lispm.py', 'hub_model.py', 'export_hf.py',
'training.py', 'command_data.py', 'expanded_data.py', 'lispm_data.py',
'data_arguments.py', 'test_actions.py', 'test_lispm.py', 'test_training.py',
'test_evaluation.py', 'test_hub_model.py', 'test_lispm_actions.py',
'expanded_generalization_cases.json', 'lispm_generalization_cases.json',
'lispm_api_catalog.json', 'verify_lispm_api.py', 'evaluation.json',
'inference-evaluation.json', 'docs/huggingface.md', 'docs/lispm-api.md',
'docs/model-details.md',
'contrastive_data.py', 'selection_reference.json', 'compare_models.py',
'robustness_generalization_cases.json', 'comparison-evaluation.json',
'Cargo.toml', 'Cargo.lock', 'build.rs', 'docs/rust.md',
'src/lib.rs', 'src/main.rs', 'src/actions.rs', 'src/actions_tests.rs',
'src/config.rs', 'src/tokenizer.rs', 'src/model.rs', 'src/inference.rs',
'src/training.rs', 'src/metrics.rs', 'src/evaluation.rs',
'scripts/setup-libtorch.sh', 'scripts/export_rust_reference.py',
'data/training.json', 'data/evaluation.json', 'tests/parity.rs',
'tests/fixtures/python-reference.json',
'tests/fixtures/python-boundary-reference.json',
'tests/fixtures/python-gradients.safetensors',
'tests/fixtures/python-adamw-step.safetensors',
'rust-evaluation.json', 'rust-training-evaluation.json',
'rust-migration-validation.json',
'rust-trained/config.json', 'rust-trained/model.safetensors',
'rust-trained/training-report.json',
'skills/lispm-train/SKILL.md', 'skills/lispm-train/agents/openai.yaml',
'emacs/lispm-llm.el', 'emacs/lispm-llm-tests.el', 'docs/emacs.md',
'emacs-module/Cargo.toml', 'emacs-module/build.rs',
'emacs-module/src/lib.rs', 'emacs-module/src/worker.rs',
'emacs-module/src/worker_tests.rs',
'scripts/build-emacs-module.sh',
'src/runtime.rs', 'src/training/control.rs', 'src/training/data.rs',
'src/training/initialization.rs',
'src/training/tests.rs', 'src/dataset.rs', 'src/episodic.rs',
'src/catalog.rs', 'src/biencoder.rs', 'src/engine.rs',
'src/workflow.rs', 'src/workflow_io.rs', 'src/workflow_learn.rs',
'src/workflow_runs.rs', 'src/workflow_types.rs',
'tests/workflow.rs', 'data/example-user-dataset.json',
'native-api/Cargo.toml', 'native-api/build.rs',
'native-api/src/lib.rs', 'native-api/src/protocol.rs',
'native-api/src/jobs.rs', 'native-api/src/jobs/tests.rs',
'native-api/tests/api.rs', 'native-api/include/lispm_llm.h',
'native-api/examples/client.c',
'emacs/lispm-llm-catalog.el',
'emacs/lispm-llm-train.el', 'emacs/lispm-llm-train-tests.el',
'emacs/lispm-llm-learn.el', 'emacs/lispm-llm-learn-tests.el',
'emacs/lispm-llm-0.3.0.tar', 'scripts/package-emacs.sh',
'docs/training-workflow.md',
'src/composition.rs', 'src/workflow_tasks.rs',
'src/task_benchmark.rs', 'src/task_benchmark/types.rs',
'src/task_benchmark/io.rs', 'src/task_benchmark/tests.rs',
'data/benchmark.json', 'data/emacs-tasks.json', 'docs/benchmarks.md',
'emacs/lispm-llm-benchmark.el', 'emacs/lispm-llm-benchmark-tests.el',
'benchmark-evaluation.json', 'benchmark-rust-training-evaluation.json',
'emacs-task-evaluation.json', 'emacs-task-rust-training-evaluation.json',
'python-reference/config.json', 'python-reference/model.safetensors',
'python-reference/benchmark-evaluation.json', 'python-reference/emacs-task-evaluation.json',
'semantic-trained/config.json', 'semantic-trained/model.safetensors',
'semantic-trained/training-report.json',
'semantic-evaluation.json', 'semantic-benchmark-evaluation.json', 'semantic-task-evaluation.json',
'semantic-from-scratch/config.json', 'semantic-from-scratch/model.safetensors',
'semantic-from-scratch/training-report.json',
'semantic-from-scratch-evaluation.json', 'semantic-from-scratch-benchmark-evaluation.json',
'semantic-from-scratch-task-evaluation.json',
'semantic-warm-start/config.json', 'semantic-warm-start/model.safetensors',
'semantic-warm-start/training-report.json',
'semantic-warm-start-evaluation.json', 'semantic-warm-start-benchmark-evaluation.json',
'semantic-warm-start-task-evaluation.json',
'data/semantic-training.json', 'data/semantic-expansion.json',
'data/semantic-authored.json', 'data/semantic-expansion-audit.json',
'data/semantic-expansion-notes.md', 'examples/prepare-training.rs', 'examples/blind-normalize.rs',
'data/nov28-blind.json', 'blind-baseline-evaluation.json', 'blind-semantic-evaluation.json',
'data/nov28-blind-source.json', 'data/nov28-blind-audit.json',
'semantic-scratch-plan.json', 'semantic-warm-start-plan.json', 'semantic-refinement-plan.json',
'data/refined-semantic-training.json', 'data/semantic-contrasts.json',
'data/semantic-contrasts-notes.md', 'data/semantic-contrasts-authored.json',
'data/semantic-contrasts-audit.json', 'semantic-final-selection.json', 'semantic-comparison.json',
'biencoder/config.json', 'biencoder/model.safetensors',
'biencoder/catalog.json', 'biencoder/training-report.json',
'biencoder-benchmark-evaluation.json', 'biencoder-blind-evaluation.json',
'biencoder-task-evaluation.json',
'docs/paper.md', 'paper/lispm-llm.tex', 'paper/lispm-llm.pdf',
)
# Root artifacts are always copied unchanged after their provenance is verified.
ARTIFACT_FILES = ('config.json', 'model.safetensors')
# Counts remain integral; zero-sized cohorts need no special ratio convention.
COMMAND_OUTCOMES = ('correct', 'wrong', 'rejected')
# Every execution result belongs to exactly one task outcome.
TASK_OUTCOMES = ('success', 'wrong_state', 'rejected', 'execution_error', 'blocked_action')
def sha256(path):
"""Return the SHA-256 of a small release file without changing its contents."""
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def validate_counts(counts, outcomes, context):
"""Require a complete nonnegative integer partition, including an empty one."""
if (set(counts) != {'total', *outcomes}
or any(type(value) is not int or value < 0 for value in counts.values())
or sum(counts[name] for name in outcomes) != counts['total']):
raise ValueError(f'{context} outcome partition mismatch')
def verify_command_report(source, directory, report_name, data_file):
"""Bind command metrics and cohort denominators to artifact and dataset bytes."""
source = Path(source)
artifact = source / directory
report = json.loads((source / report_name).read_text())
data = json.loads((source / data_file).read_text())
config = json.loads((artifact / 'config.json').read_text())
expected = {
'weights_sha256': sha256(artifact / 'model.safetensors'),
'config_sha256': sha256(artifact / 'config.json'),
'evaluation_data_sha256': sha256(source / data_file),
'thresholds': config['thresholds'],
}
if any(report.get(field) != value for field, value in expected.items()):
raise ValueError(f'{report_name} artifact, data or threshold mismatch')
if data.get('format_version') != 1 or not data.get('corpora') or set(report['corpora']) != set(data['corpora']):
raise ValueError(f'{report_name} cohort identity mismatch')
for name, corpus in data['corpora'].items():
measured = report['corpora'][name]
cases = corpus['cases']
if measured['source_sha256'] != corpus['sha256']:
raise ValueError(f'{report_name} {name} source corpus mismatch')
if any(case['split'] not in ('supported', 'unsupported')
or (case['expected'] is not None) != (case['split'] == 'supported') for case in cases):
raise ValueError(f'{report_name} {name} invalid source partition')
for partition in ('supported', 'unsupported'):
counts = measured[partition]
validate_counts(counts, COMMAND_OUTCOMES, f'{report_name} {name} {partition}')
if counts['total'] != sum(case['split'] == partition for case in cases):
raise ValueError(f'{report_name} {name} {partition} total mismatch')
if measured['unsupported']['correct'] != 0:
raise ValueError(f'{report_name} {name} unsupported acceptance cannot be correct')
novel = measured['novel_to_both_supported']
validate_counts(novel, COMMAND_OUTCOMES, f'{report_name} {name} novelty')
if novel['total'] != sum(case['split'] == 'supported' and case['novel_to_both'] for case in cases):
raise ValueError(f'{report_name} {name} novelty total mismatch')
groups = Counter(case['group'] for case in cases
if case['split'] == 'unsupported' and case['group'] is not None)
if set(measured['unsupported_groups']) != set(groups):
raise ValueError(f'{report_name} {name} unsupported group identity mismatch')
for group, total in groups.items():
counts = measured['unsupported_groups'][group]
validate_counts(counts, COMMAND_OUTCOMES, f'{report_name} {name} {group}')
if counts['total'] != total or counts['correct'] != 0:
raise ValueError(f'{report_name} {name} unsupported group total mismatch')
return report
def verify_task_counts(report, tasks, context):
"""Recompute overall and grouped task counts from the individual outcomes."""
def counts(results):
"""Reduce one known task subset into the same disjoint outcome schema."""
statuses = Counter(result['status'] for result in results)
if set(statuses) - set(TASK_OUTCOMES):
raise ValueError(f'{context} unknown task status')
return {'total': len(results), **{name: statuses[name] for name in TASK_OUTCOMES}}
results = report['results']
if len(results) != len(tasks):
raise ValueError(f'{context} task result length mismatch')
for result, task in zip(results, tasks):
if any(result[field] != task[field] for field in ('id', 'steps', 'scenario')):
raise ValueError(f'{context} task result identity mismatch')
validate_counts(report['counts'], TASK_OUTCOMES, f'{context} task overall')
if report['counts'] != counts(results):
raise ValueError(f'{context} task outcome counts mismatch')
for field, key in (('by_steps', 'steps'), ('by_scenario', 'scenario')):
for name, grouped in report[field].items():
validate_counts(grouped, TASK_OUTCOMES, f'{context} task {field}/{name}')
expected = {str(value): counts([result for result in results if result[key] == value])
for value in {task[key] for task in tasks}}
if report[field] != expected:
raise ValueError(f'{context} task {field} counts mismatch')
def verify_benchmark_provenance(source=ROOT):
"""Bind expanded command and real-Emacs reports to the published artifacts.
The runtime executable itself is not shipped. Its recorded digest and Emacs
version describe the measured environment, while all portable task inputs
and runner bytes must match the actual payload in this release.
"""
source = Path(source)
task_data = json.loads((source / 'data/emacs-tasks.json').read_text())
task_ids = [task['id'] for task in task_data['tasks']]
reports = (
('.', 'benchmark-evaluation.json', 'emacs-task-evaluation.json'),
('python-reference', 'python-reference/benchmark-evaluation.json',
'python-reference/emacs-task-evaluation.json'),
('rust-trained', 'benchmark-rust-training-evaluation.json',
'emacs-task-rust-training-evaluation.json'),
('semantic-trained', 'semantic-benchmark-evaluation.json', 'semantic-task-evaluation.json'),
('semantic-from-scratch', 'semantic-from-scratch-benchmark-evaluation.json',
'semantic-from-scratch-task-evaluation.json'),
('semantic-warm-start', 'semantic-warm-start-benchmark-evaluation.json',
'semantic-warm-start-task-evaluation.json'),
('biencoder', 'biencoder-benchmark-evaluation.json', 'biencoder-task-evaluation.json'),
)
for directory, command_report, task_report in reports:
artifact = source / directory
commands = verify_command_report(source, directory, command_report, 'data/benchmark.json')
tasks = json.loads((source / task_report).read_text())
expected = {
'weights_sha256': sha256(artifact / 'model.safetensors'),
'config_sha256': sha256(artifact / 'config.json'),
}
for report_name, report in (('commands', commands), ('tasks', tasks)):
for field, digest in expected.items():
if report.get(field) != digest:
raise ValueError(f'{directory} {report_name} report {field} mismatch')
config = json.loads((artifact / 'config.json').read_text())
if commands.get('thresholds') != config['thresholds']:
raise ValueError(f'{directory} expanded benchmark thresholds mismatch')
for field, filename in (
('evaluation_data_sha256', 'data/benchmark.json'),
):
if commands.get(field) != sha256(source / filename):
raise ValueError(f'{directory} expanded benchmark data mismatch')
for field, filename in (
('tasks_sha256', 'data/emacs-tasks.json'),
('runner_sha256', 'emacs/lispm-llm-benchmark.el'),
):
if tasks.get(field) != sha256(source / filename):
raise ValueError(f'{directory} task benchmark {field} mismatch')
if ([result['id'] for result in tasks['results']] != task_ids
or tasks['oracle_checked'] != len(task_ids)
or tasks['counts']['total'] != len(task_ids)
or sum(tasks['counts'][name] for name in TASK_OUTCOMES) != len(task_ids)):
raise ValueError(f'{directory} task benchmark outcome partition mismatch')
verify_task_counts(tasks, task_data['tasks'], directory)
def verify_initialization(source, config, training):
"""Validate optional initialization evidence against the preserved source."""
initialization = training.get('initialization')
if initialization is None:
return # Older native artifacts predate explicit initialization metadata.
expected = {'optimizer_state': 'fresh'}
if initialization.get('mode') == 'from_scratch':
expected.update(mode='from_scratch', vocabulary='training_rows')
elif initialization.get('mode') == 'warm_start':
source = Path(source)
matched = None
for directory in ('python-reference', 'semantic-from-scratch'):
config_hash = sha256(source / directory / 'config.json')
weights_hash = sha256(source / directory / 'model.safetensors')
if (initialization.get('config_sha256') == config_hash
and initialization.get('weights_sha256') == weights_hash):
matched = (directory, config_hash, weights_hash)
break
if matched is None:
raise ValueError('Native initialization source provenance mismatch')
directory, config_hash, weights_hash = matched
reference = json.loads((source / directory / 'config.json').read_text())
expected.update(mode='warm_start', vocabulary='retained', character_features='retained',
config_sha256=config_hash, weights_sha256=weights_hash)
if any(config[field] != reference[field] for field in ('architecture', 'vocab', 'labels')):
raise ValueError('Warm-start architecture, vocabulary or labels differ from its source')
else:
raise ValueError('Unknown native initialization mode')
if initialization != expected:
raise ValueError('Native initialization source provenance mismatch')
updates = training.get('selected_checkpoint_has_updates')
if (type(training['selected_step']) is not int or training['selected_step'] < 0
or type(updates) is not bool or updates != (training['selected_step'] > 0)):
raise ValueError('Selected checkpoint update metadata mismatch')
initial, minimum = training.get('learning_rate_initial'), training.get('learning_rate_minimum')
if (type(initial) not in (int, float) or type(minimum) not in (int, float)
or not 0 < minimum <= initial < float('inf')):
raise ValueError('Invalid native learning-rate metadata')
def verify_native_training(source, directory, data_file):
"""Bind one native artifact to its own immutable dataset and complete report."""
source = Path(source)
artifact = source / directory
candidate = json.loads((artifact / 'config.json').read_text())
training = json.loads((artifact / 'training-report.json').read_text())
data = json.loads((source / data_file).read_text())
# Loading validates every parameter's shape and finite float32 contents.
bundle = EmacsCommandModel.from_pretrained(artifact, local_files_only=True)
checks = {
'source format': (candidate.get('source_checkpoint_format'), 'safetensors'),
'source weights': (candidate['source_checkpoint_sha256'], sha256(artifact / 'model.safetensors')),
'training data': (training['training_data_sha256'], sha256(source / data_file)),
'training rows': (training['training_sha256'], data['training_sha256']),
'calibration rows': (training['calibration_sha256'], data['calibration_sha256']),
'selection reference': (training['selection_reference_sha256'], data['selection_reference_sha256']),
'selected thresholds': (candidate['thresholds'], training['thresholds']),
'calibration eligibility': (training['calibration']['eligible'], True),
'complete training metadata': ({field: candidate['training'].get(field) for field in training}, training),
'trained step metadata': (candidate['training'].get('trained_steps', training['steps']), training['steps']),
'parameter count': (training['parameters'], sum(p.numel() for p in bundle.model.parameters())),
'action count': (training['action_count'], len(candidate['labels']) - 1),
}
mismatches = [name for name, (actual, expected) in checks.items() if actual != expected]
if mismatches:
raise ValueError(f'Stale or inconsistent {directory} inputs: ' + ', '.join(mismatches))
verify_initialization(source, candidate, training)
def verify_semantic_training_contract(source=ROOT, original_file='data/training.json',
expanded_file='data/semantic-training.json'):
"""Require semantic training to append rows while preserving frozen evidence."""
source = Path(source)
original = json.loads((source / original_file).read_text())
expanded = json.loads((source / expanded_file).read_text())
mutable = {'training_rows', 'hard_training_indices', 'training_sha256'}
if (set(original) != set(expanded)
or any(original[field] != expanded[field] for field in original.keys() - mutable)
or expanded['training_rows'][:len(original['training_rows'])] != original['training_rows']
or expanded['hard_training_indices'][:len(original['hard_training_indices'])]
!= original['hard_training_indices']):
raise ValueError('Semantic training changed the original rows or frozen calibration/reference contract.')
def verify_example_authoring(source, audit_file, authored_file, filtered_file,
original_data_file, expanded_data_file):
"""Bind the authored-to-retained example audit to exact ordered source rows."""
source = Path(source)
audit = json.loads((source / audit_file).read_text())
authored = json.loads((source / authored_file).read_text())
filtered = json.loads((source / filtered_file).read_text())
if (audit['authored_sha256'] != sha256(source / authored_file)
or audit['filtered_sha256'] != sha256(source / filtered_file)):
raise ValueError('Semantic authoring audit source hash mismatch')
originals, retained = authored['examples'], filtered['examples']
indices = [row['authored_index'] for row in audit['excluded']]
if (authored['format_version'] != 1 or filtered['format_version'] != 1
or any(type(index) is not int or not 0 <= index < len(originals) for index in indices)
or len(set(indices)) != len(indices)):
raise ValueError('Semantic authoring audit exclusion identity mismatch')
excluded = set(indices)
if [row for index, row in enumerate(originals) if index not in excluded] != retained:
raise ValueError('Semantic authoring audit changed or reordered retained examples')
expected = {'authored_total': len(originals), 'retained_total': len(retained),
'supported': sum(row['label'] != 'reject' for row in retained),
'unsupported': sum(row['label'] == 'reject' for row in retained)}
if any(type(audit[field]) is not int or audit[field] != value for field, value in expected.items()):
raise ValueError('Semantic authoring audit count mismatch')
original_data = json.loads((source / original_data_file).read_text())
expanded_data = json.loads((source / expanded_data_file).read_text())
if len(expanded_data['training_rows']) - len(original_data['training_rows']) != len(retained):
raise ValueError('Semantic training row growth does not match retained authoring examples')
def verify_semantic_authoring(source=ROOT):
"""Verify the first independent example expansion and its materialized growth."""
verify_example_authoring(source, 'data/semantic-expansion-audit.json',
'data/semantic-authored.json', 'data/semantic-expansion.json',
'data/training.json', 'data/semantic-training.json')
def verify_contrast_authoring(source=ROOT):
"""Verify the second contrast import without rebinding the earlier dataset."""
verify_example_authoring(source, 'data/semantic-contrasts-audit.json',
'data/semantic-contrasts-authored.json', 'data/semantic-contrasts.json',
'data/semantic-training.json', 'data/refined-semantic-training.json')
def verify_rust_provenance(source=ROOT):
"""Bind native evaluations, numerical fixtures and retraining to their bytes.
Frozen Python parity uses its archived artifact. Each native training run
retains its own input dataset, independently of the selected default.
"""
source = Path(source)
verify_benchmark_provenance(source)
read = lambda name: json.loads((source / name).read_text())
fixture = read('tests/fixtures/python-reference.json')
validation = read('rust-migration-validation.json')
checks = {
'numerical reference weights': (fixture['weights_sha256'], sha256(source / 'python-reference/model.safetensors')),
'gradient fixture': (fixture['gradients_sha256'], sha256(source / 'tests/fixtures/python-gradients.safetensors')),
'AdamW fixture': (fixture['adamw_step_sha256'], sha256(source / 'tests/fixtures/python-adamw-step.safetensors')),
'validation weights': (validation['weights_sha256'], fixture['weights_sha256']),
'validation fixture': (validation['reference_sha256'], sha256(source / 'tests/fixtures/python-reference.json')),
}
for directory, report_name in (('python-reference', 'rust-evaluation.json'),
('rust-trained', 'rust-training-evaluation.json'),
('semantic-trained', 'semantic-evaluation.json'),
('semantic-from-scratch', 'semantic-from-scratch-evaluation.json'),
('semantic-warm-start', 'semantic-warm-start-evaluation.json')):
artifact = source / directory
config = read(f'{directory}/config.json')
report = verify_command_report(source, directory, report_name, 'data/evaluation.json')
checks.update({
f'{directory} evaluation weights': (report['weights_sha256'], sha256(artifact / 'model.safetensors')),
f'{directory} evaluation config': (report['config_sha256'], sha256(artifact / 'config.json')),
f'{directory} evaluation data': (report['evaluation_data_sha256'], sha256(source / 'data/evaluation.json')),
f'{directory} evaluation thresholds': (report['thresholds'], config['thresholds']),
})
mismatches = [name for name, (actual, expected) in checks.items() if actual != expected]
if mismatches:
raise ValueError('Stale or inconsistent Rust release inputs: ' + ', '.join(mismatches))
verify_native_training(source, 'rust-trained', 'data/training.json')
verify_native_training(source, 'semantic-trained', 'data/refined-semantic-training.json')
verify_native_training(source, 'semantic-from-scratch', 'data/semantic-training.json')
verify_native_training(source, 'semantic-warm-start', 'data/semantic-training.json')
verify_semantic_training_contract(source)
verify_semantic_training_contract(source, 'data/semantic-training.json', 'data/refined-semantic-training.json')
verify_semantic_authoring(source)
verify_contrast_authoring(source)
def verify_python_provenance(bundle, source=ROOT):
"""Verify historical Python evidence against its preserved artifact only.
Reports identify the original torch checkpoint, not its different safe
serialization. Both identities are retained in the release manifest.
"""
source = Path(source)
training = json.loads((source / 'evaluation.json').read_text())
evaluation = json.loads((source / 'inference-evaluation.json').read_text())
comparison = json.loads((source / 'comparison-evaluation.json').read_text())
metadata = bundle.metadata
rows_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()
comparisons = {
'source checkpoint': (metadata['source_checkpoint_sha256'], evaluation['checkpoint_sha256']),
'training data': (rows_hash, metadata['training']['training_sha256']),
'training report': (training['training_sha256'], rows_hash),
'calibration data': (calibration_hash, metadata['training']['calibration_sha256']),
'calibration report': (training['calibration_sha256'], calibration_hash),
'selection reference': (sha256(source / 'selection_reference.json'),
metadata['training']['selection_reference_sha256']),
'selection reference report': (training['selection_reference_sha256'],
metadata['training']['selection_reference_sha256']),
'comparison checkpoint': (comparison['model_checkpoints']['candidate'], metadata['source_checkpoint_sha256']),
'comparison thresholds': (comparison['thresholds']['candidate'], metadata['thresholds']),
'comparison training data': (comparison['training_sha256'], rows_hash),
'comparison calibration data': (comparison['calibration_sha256'], calibration_hash),
'fresh corpus': (sha256(source / 'robustness_generalization_cases.json'),
comparison['corpora']['fresh_robustness']['sha256']),
'comparison Emacs corpus': (sha256(source / 'expanded_generalization_cases.json'),
comparison['corpora']['historical_emacs']['sha256']),
'comparison LispM corpus': (sha256(source / 'lispm_generalization_cases.json'),
comparison['corpora']['historical_lispm']['sha256']),
'selected step': (training['selected_step'], metadata['training']['selected_step']),
'trained steps': (training['steps'], metadata['training']['trained_steps']),
'parameter count': (training['parameters'], sum(p.numel() for p in bundle.model.parameters())),
'action count': (training['action_count'], len(metadata['labels']) - 1),
'evaluation labels': (evaluation['actions'], metadata['labels'][:-1]),
'training thresholds': (training['thresholds'], metadata['thresholds']),
'evaluation thresholds': (evaluation['thresholds'], metadata['thresholds']),
'Emacs corpus': (sha256(source / 'expanded_generalization_cases.json'),
evaluation['frozen_corpus_sha256']),
'LispM corpus': (sha256(source / 'lispm_generalization_cases.json'),
evaluation['lispm_frozen_corpus_sha256']),
}
mismatches = [name for name, (actual, expected) in comparisons.items() if actual != expected]
if mismatches:
raise ValueError('Stale or inconsistent release inputs: ' + ', '.join(mismatches)
+ '. Re-evaluate the selected checkpoint before export.')
def default_artifact(source=ROOT):
"""Identify the root artifact only when both files equal an audited model."""
source = Path(source)
identity = tuple(sha256(source / name) for name in ARTIFACT_FILES)
for directory in ('python-reference', 'semantic-trained'):
expected = tuple(sha256(source / directory / name) for name in ARTIFACT_FILES)
if identity == expected:
return directory
raise ValueError('Default artifact must exactly match python-reference or semantic-trained.')
def require_command_nonregression(baseline, candidate, context):
"""Check every supported, novelty and unsupported-family gate independently."""
old, new = baseline['corpora'], candidate['corpora']
if not old or set(old) != set(new):
raise ValueError(f'{context} promotion cohort identity mismatch')
regressions = []
for name, prior in old.items():
current = new[name]
for partition in ('supported', 'novel_to_both_supported', 'unsupported'):
first, second = prior[partition], current[partition]
validate_counts(first, COMMAND_OUTCOMES, f'{context} baseline {name} {partition}')
validate_counts(second, COMMAND_OUTCOMES, f'{context} candidate {name} {partition}')
if first['total'] != second['total']:
raise ValueError(f'{context} {name} {partition} promotion total mismatch')
if partition == 'unsupported' and (first['correct'] != 0 or second['correct'] != 0):
raise ValueError(f'{context} {name} unsupported acceptance cannot be correct')
failed = second['wrong'] > first['wrong']
if partition != 'unsupported':
failed |= second['correct'] < first['correct'] or second['rejected'] > first['rejected']
if failed:
regressions.append(f'{name}/{partition}')
if set(prior['unsupported_groups']) != set(current['unsupported_groups']):
raise ValueError(f'{context} {name} promotion unsupported group mismatch')
for group, first in prior['unsupported_groups'].items():
second = current['unsupported_groups'][group]
validate_counts(first, COMMAND_OUTCOMES, f'{context} baseline {name} {group}')
validate_counts(second, COMMAND_OUTCOMES, f'{context} candidate {name} {group}')
if first['total'] != second['total']:
raise ValueError(f'{context} {name} {group} promotion total mismatch')
if first['correct'] != 0 or second['correct'] != 0:
raise ValueError(f'{context} {name} {group} unsupported acceptance cannot be correct')
if second['wrong'] > first['wrong']:
regressions.append(f'{name}/{group}')
if regressions:
raise ValueError(f'Default promotion regresses {context}: ' + ', '.join(regressions))
def require_task_nonregression(baseline, candidate):
"""Preserve task success and every failure count overall and in each group."""
pairs = [('overall', baseline['counts'], candidate['counts'])]
for field in ('by_steps', 'by_scenario'):
if set(baseline[field]) != set(candidate[field]):
raise ValueError(f'Task promotion {field} identity mismatch')
pairs.extend((f'{field}/{name}', counts, candidate[field][name])
for name, counts in baseline[field].items())
regressions = []
for name, first, second in pairs:
validate_counts(first, TASK_OUTCOMES, f'baseline task {name}')
validate_counts(second, TASK_OUTCOMES, f'candidate task {name}')
if first['total'] != second['total']:
raise ValueError(f'Task promotion {name} total mismatch')
if (second['success'] < first['success']
or any(second[field] > first[field] for field in TASK_OUTCOMES if field != 'success')):
regressions.append(name)
if regressions:
raise ValueError('Default promotion regresses tasks: ' + ', '.join(regressions))
def verify_blind_audit(source, report):
"""Bind pre-inference audit metadata to source, final data and training bytes."""
source = Path(source)
audit = json.loads((source / 'data/nov28-blind-audit.json').read_text())
expected = {
'format_version': 1, 'protocol_version': 'nov28-blind-v4',
'source_file': 'data/nov28-blind-source.json',
'source_data_sha256': sha256(source / 'data/nov28-blind-source.json'),
'evaluation_file': 'data/nov28-blind.json',
'evaluation_data_sha256': sha256(source / 'data/nov28-blind.json'),
'training_sources': {path: sha256(source / path) for path in
('data/training.json', 'data/semantic-training.json', 'data/refined-semantic-training.json')},
'comparison_training_sources': ['data/training.json', 'data/refined-semantic-training.json'],
}
if any(audit.get(field) != value for field, value in expected.items()):
raise ValueError('Blind audit source, evaluation or training binding mismatch')
exclusions = audit['exclusions']
encoded = json.dumps(exclusions, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode()
if audit['exclusions_sha256'] != hashlib.sha256(encoded).hexdigest():
raise ValueError('Blind audit exclusion digest mismatch')
counts = audit['counts']
if any(type(value) is not int or value < 0 for field, value in counts.items() if field != 'cohorts'):
raise ValueError('Blind audit counts must be nonnegative integers')
cohorts = {name: corpus['supported']['total'] + corpus['unsupported']['total']
for name, corpus in report['corpora'].items()}
categories = Counter(row['category'] for row in exclusions)
totals = {
'cohorts': cohorts, 'final_total': sum(cohorts.values()), 'excluded_total': len(exclusions),
'source_total': sum(cohorts.values()) + len(exclusions),
'overlap_exclusions': categories['training_or_calibration_overlap'],
'semantic_exclusions': categories['independent_semantic_ambiguity'],
}
if (any(counts.get(field) != value for field, value in totals.items())
or set(categories) - {'training_or_calibration_overlap', 'independent_semantic_ambiguity'}):
raise ValueError('Blind audit cohort or exclusion count mismatch')
identities = []
for row in exclusions:
digest = row['input_sha256']
if (row['source_corpus'] not in cohorts or type(row['source_index']) is not int
or not 0 <= row['source_index'] < counts['source_total']
or not isinstance(digest, str) or len(digest) != 64
or any(character not in '0123456789abcdef' for character in digest)):
raise ValueError('Blind audit exclusion identity mismatch')
identities.append((row['source_corpus'], row['source_index']))
if len(set(identities)) != len(identities):
raise ValueError('Blind audit repeats an excluded source row')
def verify_blind_provenance(source=ROOT):
"""Verify both fixed-artifact blind reports without using them for training."""
source = Path(source)
baseline = verify_command_report(source, 'python-reference', 'blind-baseline-evaluation.json',
'data/nov28-blind.json')
candidate = verify_command_report(source, 'semantic-trained', 'blind-semantic-evaluation.json',
'data/nov28-blind.json')
verify_command_report(source, 'biencoder', 'biencoder-blind-evaluation.json',
'data/nov28-blind.json')
verify_blind_audit(source, baseline)
return baseline, candidate
def verify_default_promotion(source=ROOT):
"""Block a new default unless regression, task and blind gates all hold."""
source = Path(source)
# Candidate failures may be published for comparison while the incumbent stays default.
blind_baseline, blind_candidate = verify_blind_provenance(source)
if default_artifact(source) != 'semantic-trained':
return
read = lambda name: json.loads((source / name).read_text())
baseline = read('python-reference/benchmark-evaluation.json')
candidate = read('semantic-benchmark-evaluation.json')
require_command_nonregression(baseline, candidate, 'expanded benchmark')
require_command_nonregression(baseline, read('benchmark-evaluation.json'), 'default benchmark')
require_command_nonregression(read('rust-evaluation.json'), read('semantic-evaluation.json'),
'historical single-action benchmark')
baseline_tasks = read('python-reference/emacs-task-evaluation.json')
require_task_nonregression(baseline_tasks, read('semantic-task-evaluation.json'))
require_task_nonregression(baseline_tasks, read('emacs-task-evaluation.json'))
require_command_nonregression(blind_baseline, blind_candidate, 'blind benchmark')
def verify_provenance(source=ROOT):
"""Verify the default and all archived evidence without reserializing bytes."""
source = Path(source)
default_artifact(source)
historical = EmacsCommandModel.from_pretrained(source / 'python-reference', local_files_only=True)
verify_python_provenance(historical, source)
verify_rust_provenance(source)
verify_default_promotion(source)
def build_release(output):
"""Export one verified model into a new directory and return its manifest.
Existing nonempty destinations are refused rather than merging an older
release with new files. Pass a fresh --output path for a subsequent export.
The final directory appears only after every file has been written.
"""
output = Path(output).expanduser().resolve()
if output == ROOT or output in ROOT.parents:
raise ValueError('The upload directory must be separate from the source tree.')
if output.exists() and (not output.is_dir() or any(output.iterdir())):
raise ValueError(f'Output already exists and is not empty: {output}. Choose a fresh directory.')
missing = [filename for filename in RELEASE_FILES + ARTIFACT_FILES if not (ROOT / filename).is_file()]
if missing:
raise ValueError('Missing release files: ' + ', '.join(missing))
# Snapshot the exact pair before loading to detect source changes mid-export.
identity = {filename: sha256(ROOT / filename) for filename in ARTIFACT_FILES}
# A stale local Python checkpoint can never override the published default.
bundle = EmacsCommandModel.from_pretrained(ROOT, local_files_only=True)
verify_provenance(ROOT)
output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.lispm-release-', dir=output.parent) as temporary:
staged = Path(temporary) / 'model'
staged.mkdir()
for filename in RELEASE_FILES + ARTIFACT_FILES:
destination = staged / filename
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ROOT / filename, destination)
# Preserve native serializer headers and config whitespace: reports bind
# the actual bytes, not merely numerically equivalent model parameters.
verify_provenance(staged)
for filename in ARTIFACT_FILES:
if sha256(staged / filename) != identity[filename] or sha256(ROOT / filename) != identity[filename]:
raise ValueError(f'Default artifact changed while exporting: {filename}')
files = {path.relative_to(staged).as_posix(): {'sha256': sha256(path), 'bytes': path.stat().st_size}
for path in sorted(staged.rglob('*')) if path.is_file()}
manifest = {
'format_version': 1,
'license': 'AGPL-3.0-only',
'source_checkpoint_sha256': bundle.metadata['source_checkpoint_sha256'],
'default_artifact': default_artifact(staged),
'config_sha256': files['config.json']['sha256'],
'weights_sha256': files['model.safetensors']['sha256'],
'files': files,
'note': 'Hashes cover every payload file; the manifest itself is excluded.',
}
(staged / 'release-manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
if output.exists():
output.rmdir() # Only an empty destination reaches this point.
staged.replace(output)
return manifest
def main():
"""Create a local upload folder; printing this result never publishes it."""
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('--output', type=Path, default=ROOT / 'dist' / 'huggingface')
args = cli.parse_args()
try:
manifest = build_release(args.output)
except (OSError, ValueError, KeyError) as error:
cli.error(str(error))
print(json.dumps({'output': str(args.output.resolve()), 'files': len(manifest['files']) + 1,
'weights_sha256': manifest['weights_sha256']}, indent=2))
if __name__ == '__main__':
main()