Spaces:
Sleeping
Sleeping
File size: 6,441 Bytes
8648e23 | 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 | #!/usr/bin/env python
"""
backend/scripts/evaluate_transformer.py
CLI evaluation script for the Music Transformer.
Run locally after training with caffeinate.
Usage:
uv run python scripts/evaluate_transformer.py \\
--checkpoint checkpoints/transformer-v1/best.pt \\
--data-dir data/encoded \\
--n-samples 50 \\
--output-report reports/evaluation_v1.json
Options:
--checkpoint Path to best.pt checkpoint (required)
--data-dir Directory containing vocab.json, encoded_sequences.jsonl,
transition_matrix.json (default: data/encoded)
--n-samples Number of sequences to generate for grammar evaluation
(default: 50)
--key-mode "minor" or "major" (default: minor)
--output-report Path for JSON report output (default: reports/evaluation.json)
--device Override device: mps / cuda / cpu (default: auto)
--batch-size Batch size for perplexity computation (default: 32)
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
# Make sure backend/src is importable when run from backend/
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Evaluate Music Transformer")
p.add_argument("--checkpoint", required=True,
help="Path to best.pt")
p.add_argument("--data-dir", default="data/encoded",
help="Directory with vocab.json etc.")
p.add_argument("--n-samples", type=int, default=50,
help="Sequences to generate for grammar evaluation")
p.add_argument("--key-mode", default="minor",
choices=["minor", "major"],
help="Key mode for generation")
p.add_argument("--output-report", default="reports/evaluation.json",
help="Output JSON report path")
p.add_argument("--device", default="auto",
help="Device override: mps / cuda / cpu / auto")
p.add_argument("--batch-size", type=int, default=32,
help="Batch size for perplexity computation")
return p.parse_args()
def main() -> None:
args = parse_args()
data_dir = Path(args.data_dir)
vocab_path = str(data_dir / "vocab.json")
matrix_path = str(data_dir / "transition_matrix.json")
jsonl_path = str(data_dir / "encoded_sequences.jsonl")
# ββ Validate inputs βββββββββββββββββββββββββββββββββββββββββββββββββββ
for p in (args.checkpoint, vocab_path, matrix_path, jsonl_path):
if not Path(p).exists():
print(f"ERROR: Required file not found: {p}", file=sys.stderr)
sys.exit(1)
print(f"Loading checkpoint: {args.checkpoint}")
print(f"Data directory: {args.data_dir}")
print(f"Key mode: {args.key_mode}")
print(f"Samples: {args.n_samples}")
print()
# ββ Resolve device ββββββββββββββββββββββββββββββββββββββββββββββββββββ
import torch
if args.device == "auto":
if torch.backends.mps.is_available():
device = torch.device("mps")
elif torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
else:
device = torch.device(args.device)
print(f"Device: {device}")
# ββ Load generator ββββββββββββββββββββββββββββββββββββββββββββββββββββ
from src.models.generator import MusicGenerator
print("Loading generator from checkpointβ¦")
generator = MusicGenerator.from_checkpoint(
checkpoint_path=args.checkpoint,
vocab_path=vocab_path,
transition_matrix_path=matrix_path,
device=str(device),
)
print("Generator loaded.\n")
# ββ Compute transformer perplexity ββββββββββββββββββββββββββββββββββββ
from src.data.transformer_dataset import HarmonicSequenceDataset
from src.models.music_transformer import MusicTransformer
from src.evaluation.transformer_metrics import (
compute_transformer_perplexity,
compute_baseline_perplexity,
evaluate_generator,
)
print("Computing perplexity on test setβ¦")
test_dataset = HarmonicSequenceDataset(
jsonl_path=jsonl_path,
vocab_path=vocab_path,
split="test",
window_size=128,
stride=64,
)
model, _ = MusicTransformer.load_checkpoint(args.checkpoint, device=str(device))
ppl = compute_transformer_perplexity(model, test_dataset, device, args.batch_size)
print(f"Transformer perplexity: {ppl:.2f}")
# ββ Baseline perplexity βββββββββββββββββββββββββββββββββββββββββββββββ
print("Computing baseline perplexityβ¦")
baseline_ppl = compute_baseline_perplexity(jsonl_path, vocab_path, device)
print(f"Baseline perplexity: {baseline_ppl:.2f}")
# ββ Grammar evaluation ββββββββββββββββββββββββββββββββββββββββββββββββ
print(f"\nGenerating {args.n_samples} sequences for grammar evaluationβ¦")
report = evaluate_generator(
generator=generator,
n_samples=args.n_samples,
key_mode=args.key_mode,
checkpoint_path=args.checkpoint,
)
# Fill in the perplexity values computed above
import dataclasses
report = dataclasses.replace(
report,
perplexity=ppl,
baseline_perplexity=baseline_ppl,
improvement_over_baseline=(
(baseline_ppl - ppl) / baseline_ppl if ppl > 0 else 0.0
),
)
# ββ Print and save ββββββββββββββββββββββββββββββββββββββββββββββββββββ
report.print_summary()
report.to_json(args.output_report)
if __name__ == "__main__":
main() |