File size: 5,829 Bytes
adabee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score a trained Danish G2P run on its held-out NST words and package it for frontend v4.

    TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1 python scripts/g2p_package.py --run work/g2p-nst-v1 \
        --report checks/g2p-nst-v1-eval.json [--package kit-v4-resources/]

Scoring: word error rate (exact (phone, stress) sequence), phoneme error rate (edit distance
over (phone, stress) units), the same without stress, and stød recall/precision (phones ending
in ˀ), on the 2% of single-word NST entries held out by scripts/g2p_train.py.

Packaging writes the shipped files: `da_g2p_nst_v1.pt` holds only the weights and the
DeepPhonemizer config, so the frontend loads it with weights_only=True; the symbol table; and
`danish_g2p_data.py` (G2P_METADATA with both SHA-256s, the training identity and the scores).
"""
import argparse
import hashlib
import json
import shutil
from pathlib import Path

import torch
from dp.model.model import ModelType, create_model
from dp.model.predictor import Predictor
from dp.preprocessing.text import Preprocessor

NAME = "da_g2p_nst_v1"


def edit_distance(a, b):
    row = list(range(len(b) + 1))
    for i, x in enumerate(a, 1):
        previous, row[0] = row[0], i
        for j, y in enumerate(b, 1):
            previous, row[j] = row[j], min(row[j] + 1, row[j - 1] + 1, previous + (x != y))
    return row[-1]


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--run", type=Path, required=True)
    p.add_argument("--checkpoint", default="best_model.pt")
    p.add_argument("--report", type=Path, required=True)
    p.add_argument("--package", type=Path, help="directory for the shipped resource files")
    args = p.parse_args()

    checkpoint = torch.load(args.run / "checkpoints" / args.checkpoint, map_location="cpu", weights_only=False)
    config = checkpoint["config"]
    model = create_model(ModelType(config["model"]["type"]), config=config)
    model.load_state_dict(checkpoint["model"])
    model.eval()
    predictor = Predictor(model=model, preprocessor=Preprocessor.from_config(config))
    symbols = json.loads((args.run / "symbols.json").read_text(encoding="utf-8"))
    decode = {char: (phone, stress) for phone, stress, char in symbols["pairs"]}
    rows = [json.loads(x) for x in (args.run / "validation.jsonl").read_text(encoding="utf-8").splitlines()]

    torch.set_num_threads(8)
    with torch.inference_mode():
        predictions = predictor([w for w, _ in rows], lang="da", batch_size=256)
    words = errors = edits = edits_ns = units = stod_ref = stod_hit = stod_pred = 0
    examples = []
    for (word, target), prediction in zip(rows, predictions):
        ref = [decode[c] for c in target]
        hyp = [decode[c] for c in prediction.phonemes if c in decode]
        words += 1
        units += len(ref)
        wrong = ref != hyp
        errors += wrong
        edits += edit_distance(ref, hyp)
        edits_ns += edit_distance([x[0] for x in ref], [x[0] for x in hyp])
        ref_stod = {i for i, (ph, _) in enumerate(ref) if ph.endswith("ˀ")}
        hyp_stod = {i for i, (ph, _) in enumerate(hyp) if ph.endswith("ˀ")}
        stod_ref += len(ref_stod)
        stod_pred += len(hyp_stod)
        stod_hit += len(ref_stod & hyp_stod) if len(ref) == len(hyp) else 0
        if wrong and len(examples) < 40:
            examples.append({"word": word, "nst": " ".join(f"{a}{'¹²'[b-1] if b else ''}" for a, b in ref),
                             "g2p": " ".join(f"{a}{'¹²'[b-1] if b else ''}" for a, b in hyp)})
    report = {"run": str(args.run), "checkpoint": args.checkpoint, "step": checkpoint.get("step"),
              "model": config["model"], "words": words, "wer": errors / words, "per": edits / units,
              "per_without_stress": edits_ns / units,
              "stød_recall_same_length": stod_hit / max(stod_ref, 1),
              "stød_predicted_vs_reference": [stod_pred, stod_ref], "examples": examples}
    args.report.parent.mkdir(parents=True, exist_ok=True)
    args.report.write_text(json.dumps(report, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({k: v for k, v in report.items() if k != "examples"}, ensure_ascii=False))

    if args.package:
        args.package.mkdir(parents=True, exist_ok=True)
        weights = args.package / f"{NAME}.pt"
        torch.save({"model": {k: v.contiguous() for k, v in model.state_dict().items()}, "config": config}, weights)
        torch.load(weights, map_location="cpu", weights_only=True)   # must load without pickled objects
        table = args.package / f"{NAME}.symbols.json"
        shutil.copyfile(args.run / "symbols.json", table)
        sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
        from tiny_voca.danish_nst_data import LEXICON_METADATA
        metadata = {"resource": weights.name, "sha256": sha(weights), "symbols": table.name, "symbols_sha256": sha(table),
                    "version": "nst-g2p-v1", "library": "deep-phonemizer==0.0.19", "model_type": config["model"]["type"],
                    "d_model": config["model"]["d_model"], "layers": config["model"]["layers"], "step": checkpoint.get("step"),
                    "trained_on": {"nst_content_sha256": LEXICON_METADATA["content_sha256"],
                                   "entries": "single-word, casefolded, 2% held out (seed 1234)"},
                    "validation": {k: round(report[k], 5) for k in ("wer", "per", "per_without_stress")},
                    "device": "cpu"}
        (args.package / "danish_g2p_data.py").write_text(
            '"""Generated by scripts/g2p_package.py; do not edit by hand."""\n\nG2P_METADATA = '
            + repr(metadata) + "\n", encoding="utf-8")
        print("packaged", weights, f"{weights.stat().st_size / 1e6:.1f} MB")


if __name__ == "__main__":
    main()