error-align 0.1.0b9__tar.gz → 0.1.0b11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. error_align-0.1.0b11/.coveragerc +9 -0
  2. error_align-0.1.0b11/.github/assets/logo.svg +54 -0
  3. {error_align-0.1.0b9 → error_align-0.1.0b11}/PKG-INFO +10 -6
  4. {error_align-0.1.0b9 → error_align-0.1.0b11}/README.md +8 -4
  5. error_align-0.1.0b11/benchmarks/bench_error_align.py +309 -0
  6. {error_align-0.1.0b9 → error_align-0.1.0b11}/codecov.yml +1 -1
  7. {error_align-0.1.0b9 → error_align-0.1.0b11}/cpp/beam_search.cpp +49 -27
  8. error_align-0.1.0b11/cpp/edit_distance.cpp +379 -0
  9. {error_align-0.1.0b9 → error_align-0.1.0b11}/poetry.lock +10 -4
  10. {error_align-0.1.0b9 → error_align-0.1.0b11}/pyproject.toml +6 -2
  11. error_align-0.1.0b11/pytest.ini +2 -0
  12. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/backtrace_graph.py +10 -2
  13. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/optimal_word_alignment.py +2 -0
  14. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/edit_distance.py +12 -8
  15. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/error_align.py +50 -5
  16. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/graph_metadata.py +3 -1
  17. {error_align-0.1.0b9 → error_align-0.1.0b11}/tests/test_default.py +126 -4
  18. error_align-0.1.0b11/tests/test_efficiency.py +117 -0
  19. error_align-0.1.0b9/.coveragerc +0 -6
  20. error_align-0.1.0b9/.github/assets/logo.svg +0 -34
  21. error_align-0.1.0b9/cpp/edit_distance.cpp +0 -242
  22. error_align-0.1.0b9/pytest.ini +0 -2
  23. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/CODEOWNERS +0 -0
  24. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/assets/aau.png +0 -0
  25. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/assets/corti.png +0 -0
  26. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/assets/dtu.png +0 -0
  27. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/assets/empty.png +0 -0
  28. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/assets/pcai.png +0 -0
  29. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/assets/ucph.png +0 -0
  30. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/pull_request_template.md +0 -0
  31. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/release_drafter_main_branch.yml +0 -0
  32. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/workflows/build_and_publish.yml +0 -0
  33. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/workflows/build_wheels.yml +0 -0
  34. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/workflows/label_check.yml +0 -0
  35. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/workflows/lint.yml +0 -0
  36. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/workflows/release_draft_main_branch.yml +0 -0
  37. {error_align-0.1.0b9 → error_align-0.1.0b11}/.github/workflows/tests_and_coverage.yml +0 -0
  38. {error_align-0.1.0b9 → error_align-0.1.0b11}/.gitignore +0 -0
  39. {error_align-0.1.0b9 → error_align-0.1.0b11}/.pre-commit-config.yaml +0 -0
  40. {error_align-0.1.0b9 → error_align-0.1.0b11}/.python-version +0 -0
  41. {error_align-0.1.0b9 → error_align-0.1.0b11}/CMakeLists.txt +0 -0
  42. {error_align-0.1.0b9 → error_align-0.1.0b11}/Makefile +0 -0
  43. {error_align-0.1.0b9 → error_align-0.1.0b11}/evaluation/evaluate_dataset.py +0 -0
  44. {error_align-0.1.0b9 → error_align-0.1.0b11}/evaluation/monolingual_eval.sh +0 -0
  45. {error_align-0.1.0b9 → error_align-0.1.0b11}/evaluation/multilingual_eval.sh +0 -0
  46. {error_align-0.1.0b9 → error_align-0.1.0b11}/evaluation/prepare_primock57.py +0 -0
  47. {error_align-0.1.0b9 → error_align-0.1.0b11}/evaluation/transcribe_dataset.py +0 -0
  48. {error_align-0.1.0b9 → error_align-0.1.0b11}/ruff.toml +0 -0
  49. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/__init__.py +0 -0
  50. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/__init__.py +0 -0
  51. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/cmudict.rep.json +0 -0
  52. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/normalize/__init__.py +0 -0
  53. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/normalize/contractions.py +0 -0
  54. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/normalize/normalize.py +0 -0
  55. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/normalize/numbers.py +0 -0
  56. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/power/__init__.py +0 -0
  57. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/power/aligner.py +0 -0
  58. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/power/levenshtein.py +0 -0
  59. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/power/phonemes.py +0 -0
  60. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/power/pronounce.py +0 -0
  61. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/power/punct.py +0 -0
  62. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/power/readers.py +0 -0
  63. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power/power/writers.py +0 -0
  64. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/power_alignment.py +0 -0
  65. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/rapidfuzz_word_alignment.py +0 -0
  66. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/baselines/utils.py +0 -0
  67. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/beam_search.py +0 -0
  68. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/core.py +0 -0
  69. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/path_to_alignment.py +0 -0
  70. {error_align-0.1.0b9 → error_align-0.1.0b11}/src/error_align/utils.py +0 -0
@@ -0,0 +1,9 @@
1
+ [run]
2
+ branch = True
3
+ source = error_align
4
+
5
+ [report]
6
+ # Match both the editable (src/error_align/...) and installed
7
+ # (.../site-packages/error_align/...) layouts so baselines are omitted in
8
+ # both local and CI runs.
9
+ omit = */baselines/*
@@ -0,0 +1,54 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 580 166" role="img" aria-label="ErrorAlign logo">
2
+ <style>
3
+ @import url('https://fonts.googleapis.com/css2?family=Geist:wght@400;500');
4
+ .wordmark {
5
+ font-family: 'Courier New', Courier, monospace;
6
+ font-size: 56px;
7
+ font-weight: normal;
8
+ stroke-width: 3.5px;
9
+ stroke-linejoin: round;
10
+ }
11
+ </style>
12
+
13
+ <defs>
14
+ <linearGradient id="error-gradient" x1="0" y1="0" x2="1" y2="1">
15
+ <stop offset="0%" stop-color="#9e1414"/>
16
+ <stop offset="100%" stop-color="#e0735a"/>
17
+ </linearGradient>
18
+ <linearGradient id="align-gradient" x1="0" y1="0" x2="1" y2="1">
19
+ <stop offset="0%" stop-color="#2d7a0a"/>
20
+ <stop offset="100%" stop-color="#a6c95e"/>
21
+ </linearGradient>
22
+ <!-- Light end at the upper-right corner, fading toward the lower left -->
23
+ <linearGradient id="block-gradient-top" x1="1" y1="0" x2="0" y2="1">
24
+ <stop offset="0%" stop-color="#e0e0e0"/>
25
+ <stop offset="100%" stop-color="#c2c2c2"/>
26
+ </linearGradient>
27
+ <!-- Light end at the lower-left corner, fading toward the upper right -->
28
+ <linearGradient id="block-gradient-bottom" x1="0" y1="1" x2="1" y2="0">
29
+ <stop offset="0%" stop-color="#e0e0e0"/>
30
+ <stop offset="100%" stop-color="#c2c2c2"/>
31
+ </linearGradient>
32
+ </defs>
33
+
34
+ <!-- Centered group: 5 chars + gap + block, 33.6px per char -->
35
+ <g class="wordmark" transform="translate(290, 68)">
36
+ <!-- Line 1: "error" + gap + grey space -->
37
+ <text x="-106" y="-11.7" text-anchor="start" fill="url(#error-gradient)" stroke="url(#error-gradient)">error</text>
38
+ <rect x="72.5" y="-53.7" width="33.6" height="49" rx="2.3" fill="url(#block-gradient-top)"/>
39
+
40
+ <!-- Line 2: grey space + gap + "align" -->
41
+ <rect x="-106.1" y="2.3" width="33.6" height="49" rx="2.3" fill="url(#block-gradient-bottom)"/>
42
+ <text x="-62" y="44.3" text-anchor="start" fill="url(#align-gradient)" stroke="url(#align-gradient)">align</text>
43
+ </g>
44
+
45
+ <text
46
+ x="290" y="150"
47
+ text-anchor="middle"
48
+ font-family="'Geist', system-ui, sans-serif"
49
+ font-size="10"
50
+ font-weight="400"
51
+ letter-spacing="2.5"
52
+ fill="#73726c"
53
+ >A text-to-text alignment algorithm</text>
54
+ </svg>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: error-align
3
- Version: 0.1.0b9
3
+ Version: 0.1.0b11
4
4
  Summary: Text-to-text alignment algorithm for speech recognition error analysis.
5
5
  Keywords: speech-recognition,text-alignment,NLP,evaluation
6
6
  Author-Email: Lasse Borgholt <lb@corti.ai>
@@ -24,8 +24,8 @@ Requires-Python: <3.15,>=3.10
24
24
  Requires-Dist: tqdm>=4.67.1
25
25
  Requires-Dist: unidecode>=1.4.0
26
26
  Requires-Dist: regex>=2025.9.18
27
+ Requires-Dist: rapidfuzz>=3.13.0
27
28
  Provides-Extra: evaluation
28
- Requires-Dist: rapidfuzz>=3.13.0; python_version == "3.12" and extra == "evaluation"
29
29
  Requires-Dist: num2words>=0.5.14; python_version == "3.12" and extra == "evaluation"
30
30
  Requires-Dist: datasets>=3.3.2; python_version == "3.12" and extra == "evaluation"
31
31
  Requires-Dist: soundfile>=0.13.1; python_version == "3.12" and extra == "evaluation"
@@ -62,7 +62,9 @@ Description-Content-Type: text/markdown
62
62
 
63
63
  **Text-to-text alignment algorithm for speech recognition error analysis.** ErrorAlign helps you dig deeper into your speech recognition projects by accurately aligning each word in a reference transcript with the model-generated transcript. Unlike traditional methods, such as Levenshtein-based alignment, it is not restricted to simple one-to-one alignment, but can map a single reference word to multiple words or subwords in the model output. This enables quick and reliable identification of error patterns in rare words, names, or domain-specific terms that matter most for your application.
64
64
 
65
- → **Update [2025-12-10]:** As of version `0.1.0b5`, `error-align` will include a word-level pass to efficiently identify unambiguous matches, along with C++ extensions to accelerate beam search and backtrace construction. The combined speedup is ~15× over the pure-Python implementation ⚡
65
+ → **Update [2026-06-22]:** As of version `0.1.0b10`, the word-level pass defaults to a faster `rapidfuzz`-based method that anchors matches from a single optimal Levenshtein alignment. On longer examples (e.g., Earnings-21), the speedup is expected to be around 30×. The original graph-based pass is still available via `error_align(ref, hyp, word_level_method="unambiguous")`.
66
+
67
+ → **Update [2025-12-10]:** As of version `0.1.0b5`, `error-align` will include a word-level pass to efficiently identify unambiguous matches, along with C++ extensions to accelerate beam search and backtrace construction. The combined speedup is ~15× over the pure-Python implementation.
66
68
 
67
69
  [//]: <> (https://raw.githubusercontent.com/corticph/error-align/refs/heads/main/.github/assets/logo_gpt.svg)
68
70
 
@@ -107,11 +109,13 @@ Alignment(INSERT: "period")
107
109
  ## Citation and Research
108
110
 
109
111
  ```
110
- @article{borgholt2025text,
112
+ @inproceedings{borgholt2026text,
111
113
  title={A Text-To-Text Alignment Algorithm for Better Evaluation of Modern Speech Recognition Systems},
112
114
  author={Borgholt, Lasse and Havtorn, Jakob and Igel, Christian and Maal{\o}e, Lars and Tan, Zheng-Hua},
113
- journal={arXiv preprint arXiv:2509.24478},
114
- year={2025}
115
+ booktitle={ICASSP 2026-2026 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
116
+ pages={3476--3480},
117
+ year={2026},
118
+ organization={IEEE}
115
119
  }
116
120
  ```
117
121
 
@@ -13,7 +13,9 @@
13
13
 
14
14
  **Text-to-text alignment algorithm for speech recognition error analysis.** ErrorAlign helps you dig deeper into your speech recognition projects by accurately aligning each word in a reference transcript with the model-generated transcript. Unlike traditional methods, such as Levenshtein-based alignment, it is not restricted to simple one-to-one alignment, but can map a single reference word to multiple words or subwords in the model output. This enables quick and reliable identification of error patterns in rare words, names, or domain-specific terms that matter most for your application.
15
15
 
16
- → **Update [2025-12-10]:** As of version `0.1.0b5`, `error-align` will include a word-level pass to efficiently identify unambiguous matches, along with C++ extensions to accelerate beam search and backtrace construction. The combined speedup is ~15× over the pure-Python implementation ⚡
16
+ → **Update [2026-06-22]:** As of version `0.1.0b10`, the word-level pass defaults to a faster `rapidfuzz`-based method that anchors matches from a single optimal Levenshtein alignment. On longer examples (e.g., Earnings-21), the speedup is expected to be around 30×. The original graph-based pass is still available via `error_align(ref, hyp, word_level_method="unambiguous")`.
17
+
18
+ → **Update [2025-12-10]:** As of version `0.1.0b5`, `error-align` will include a word-level pass to efficiently identify unambiguous matches, along with C++ extensions to accelerate beam search and backtrace construction. The combined speedup is ~15× over the pure-Python implementation.
17
19
 
18
20
  [//]: <> (https://raw.githubusercontent.com/corticph/error-align/refs/heads/main/.github/assets/logo_gpt.svg)
19
21
 
@@ -58,11 +60,13 @@ Alignment(INSERT: "period")
58
60
  ## Citation and Research
59
61
 
60
62
  ```
61
- @article{borgholt2025text,
63
+ @inproceedings{borgholt2026text,
62
64
  title={A Text-To-Text Alignment Algorithm for Better Evaluation of Modern Speech Recognition Systems},
63
65
  author={Borgholt, Lasse and Havtorn, Jakob and Igel, Christian and Maal{\o}e, Lars and Tan, Zheng-Hua},
64
- journal={arXiv preprint arXiv:2509.24478},
65
- year={2025}
66
+ booktitle={ICASSP 2026-2026 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
67
+ pages={3476--3480},
68
+ year={2026},
69
+ organization={IEEE}
66
70
  }
67
71
  ```
68
72
 
@@ -0,0 +1,309 @@
1
+ """Peak-RSS and wall-time benchmark for error_align().
2
+
3
+ Each (case, run) pair executes in its own subprocess, so the peak RSS is
4
+ attributable to a single error_align() call. Peak RSS is read from
5
+ resource.getrusage(RUSAGE_SELF).ru_maxrss: bytes on macOS, KiB on Linux.
6
+ Wall time is measured around the error_align() call, excluding interpreter
7
+ startup and case generation.
8
+
9
+ Cases (deterministic, seeded):
10
+ identity: hyp == ref, 500 words (sanity).
11
+ realistic: 500 words with every 20th word substituted, ~5% (sanity).
12
+ rewrite: same-length full rewrite, 500 completely different words.
13
+ repeat3x: 3x repeated tokens, 500 -> 1500 tokens from a 5-token cycle.
14
+ garbage3x: 3x unmatchable garbage, 500 -> 1500 distinct tokens.
15
+
16
+ All hypothesis words are disjoint from the reference words, so the word-level
17
+ pass finds no unambiguous matches and the full span reaches the character-level
18
+ beam search. This is the worst-case shape for that path.
19
+
20
+ Usage:
21
+ poetry run python benchmarks/bench_error_align.py --case all --runs 3 \
22
+ --label before --out <dir>
23
+ poetry run python benchmarks/bench_error_align.py --case all --runs 3 \
24
+ --label after --out <dir> --compare <dir>/before
25
+
26
+ The --compare mode asserts that the serialized Alignments are identical to the
27
+ recorded label and exits non-zero on any difference.
28
+
29
+ Results are written to <out>/<label>/<case>.ops.json (serialized Alignments)
30
+ and <out>/<label>/summary.json (per-run measurements and medians).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import hashlib
37
+ import json
38
+ import random
39
+ import resource
40
+ import statistics
41
+ import subprocess
42
+ import sys
43
+ import time
44
+
45
+ CASES = ("identity", "realistic", "rewrite", "repeat3x", "garbage3x")
46
+
47
+ CONSONANTS = "bcdfghklmnprstvz"
48
+ VOWELS = "aeiou"
49
+ RESULT_MARKER = "EA-BENCH-RESULT "
50
+
51
+
52
+ def _pseudo_words(rng: random.Random, count: int, exclude: set[str], min_len: int = 4, max_len: int = 8) -> list[str]:
53
+ """Generate unique pseudo-words of alternating consonants and vowels.
54
+
55
+ The words share the character alphabet with regular text, but never equal
56
+ any word in the exclude set, so word-level matches are absent by design.
57
+ """
58
+ words: list[str] = []
59
+ while len(words) < count:
60
+ length = rng.randint(min_len, max_len)
61
+ word = "".join(rng.choice(CONSONANTS) if i % 2 == 0 else rng.choice(VOWELS) for i in range(length))
62
+ if word not in exclude:
63
+ words.append(word)
64
+ exclude.add(word)
65
+ return words
66
+
67
+
68
+ def make_case(name: str) -> tuple[str, str]:
69
+ """Generate the (ref, hyp) text pair for a benchmark case."""
70
+ rng = random.Random(1234)
71
+ ref_words = _pseudo_words(rng, 500, set())
72
+ ref = " ".join(ref_words)
73
+
74
+ if name == "identity":
75
+ return ref, ref
76
+
77
+ if name == "realistic":
78
+ # Substitute every 20th word: 25 of 500 = ~5% substitutions.
79
+ words = list(ref_words)
80
+ substitutions = _pseudo_words(rng, 25, set(ref_words))
81
+ for i, word in zip(range(0, 500, 20), substitutions, strict=True):
82
+ words[i] = word
83
+ return ref, " ".join(words)
84
+
85
+ if name == "rewrite":
86
+ hyp_words = _pseudo_words(rng, 500, set(ref_words))
87
+ return ref, " ".join(hyp_words)
88
+
89
+ if name == "repeat3x":
90
+ cycle = _pseudo_words(rng, 5, set(ref_words))
91
+ return ref, " ".join(cycle[i % len(cycle)] for i in range(1500))
92
+
93
+ if name == "garbage3x":
94
+ hyp_words = _pseudo_words(rng, 1500, set(ref_words))
95
+ return ref, " ".join(hyp_words)
96
+
97
+ raise ValueError(f"Unknown case: {name}. Valid cases: {CASES}")
98
+
99
+
100
+ def serialize_alignments(alignments) -> list[dict]:
101
+ """Serialize Alignments to a canonical, JSON-compatible representation."""
102
+ return [
103
+ {
104
+ "op_type": alignment.op_type.name,
105
+ "ref_slice": [alignment.ref_slice.start, alignment.ref_slice.stop] if alignment.ref_slice else None,
106
+ "hyp_slice": [alignment.hyp_slice.start, alignment.hyp_slice.stop] if alignment.hyp_slice else None,
107
+ "ref": alignment.ref,
108
+ "hyp": alignment.hyp,
109
+ "left_compound": alignment.left_compound,
110
+ "right_compound": alignment.right_compound,
111
+ }
112
+ for alignment in alignments
113
+ ]
114
+
115
+
116
+ def _ru_maxrss_bytes() -> int:
117
+ """Read the peak RSS of this process in bytes (macOS reports bytes, Linux KiB)."""
118
+ value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
119
+ return value if sys.platform == "darwin" else value * 1024
120
+
121
+
122
+ def run_child(case: str) -> None:
123
+ """Run a single benchmark case in this process and print one result line."""
124
+ import error_align as error_align_pkg
125
+ from error_align import core, error_align
126
+
127
+ ref, hyp = make_case(case)
128
+ baseline_rss = _ru_maxrss_bytes()
129
+
130
+ start = time.perf_counter()
131
+ alignments = error_align(ref, hyp)
132
+ wall_s = time.perf_counter() - start
133
+
134
+ peak_rss = _ru_maxrss_bytes()
135
+ ops = serialize_alignments(alignments)
136
+ ops_json = json.dumps(ops, sort_keys=True)
137
+ result = {
138
+ "case": case,
139
+ "wall_s": round(wall_s, 3),
140
+ "baseline_rss_bytes": baseline_rss,
141
+ "peak_rss_bytes": peak_rss,
142
+ "rss_delta_bytes": peak_rss - baseline_rss,
143
+ "num_alignments": len(alignments),
144
+ "ops_sha256": hashlib.sha256(ops_json.encode()).hexdigest(),
145
+ "using_cpp": core.USING_CPP,
146
+ "package": error_align_pkg.__file__,
147
+ "python": sys.version.split()[0],
148
+ "platform": sys.platform,
149
+ "ops": ops,
150
+ }
151
+ print(RESULT_MARKER + json.dumps(result))
152
+
153
+
154
+ def _fmt_bytes(num_bytes: int) -> str:
155
+ """Format bytes as a decimal MB/GB string."""
156
+ if abs(num_bytes) >= 1_000_000_000:
157
+ return f"{num_bytes / 1_000_000_000:.2f} GB"
158
+ if abs(num_bytes) >= 1_000_000:
159
+ return f"{num_bytes / 1_000_000:.1f} MB"
160
+ return f"{num_bytes / 1_000:.0f} kB"
161
+
162
+
163
+ def _parse_child_result(stdout: str) -> dict:
164
+ """Parse the result line from a child process."""
165
+ for line in reversed(stdout.splitlines()):
166
+ if line.startswith(RESULT_MARKER):
167
+ return json.loads(line[len(RESULT_MARKER) :])
168
+ raise RuntimeError("Child process printed no result line.")
169
+
170
+
171
+ def run_case(case: str, runs: int, label: str, out_dir: str, timeout_s: int) -> dict:
172
+ """Run a case N times in fresh subprocesses and aggregate the medians."""
173
+ runs_data = []
174
+ saved_ops = None
175
+ for run_idx in range(runs):
176
+ try:
177
+ proc = subprocess.run(
178
+ [sys.executable, __file__, "--child", "--case", case],
179
+ capture_output=True,
180
+ text=True,
181
+ timeout=timeout_s or None,
182
+ )
183
+ except subprocess.TimeoutExpired:
184
+ runs_data.append({"case": case, "run": run_idx, "status": f"timeout after {timeout_s}s"})
185
+ break
186
+ if proc.returncode != 0:
187
+ detail = (proc.stderr or "").strip().splitlines()
188
+ reason = detail[-1] if detail else f"exit code {proc.returncode}"
189
+ runs_data.append({"case": case, "run": run_idx, "status": f"failed: {reason}"})
190
+ break
191
+
192
+ payload = _parse_child_result(proc.stdout)
193
+ ops = payload.pop("ops")
194
+ expected_hash = hashlib.sha256(json.dumps(ops, sort_keys=True).encode()).hexdigest()
195
+ if expected_hash != payload["ops_sha256"]:
196
+ raise RuntimeError(f"Hash mismatch between ops payload and hash for case {case}, run {run_idx}.")
197
+ if saved_ops is None:
198
+ saved_ops = ops
199
+ elif ops != saved_ops:
200
+ raise RuntimeError(f"Alignments differ between runs of case {case} (run {run_idx}).")
201
+
202
+ runs_data.append({"case": case, "run": run_idx, "status": "ok", **payload})
203
+
204
+ ok_runs = [r for r in runs_data if r.get("status") == "ok"]
205
+ summary = {
206
+ "case": case,
207
+ "label": label,
208
+ "runs": runs_data,
209
+ "num_ok_runs": len(ok_runs),
210
+ }
211
+ if ok_runs:
212
+ summary["median_wall_s"] = statistics.median(r["wall_s"] for r in ok_runs)
213
+ summary["median_peak_rss_bytes"] = statistics.median(r["peak_rss_bytes"] for r in ok_runs)
214
+ summary["median_baseline_rss_bytes"] = statistics.median(r["baseline_rss_bytes"] for r in ok_runs)
215
+ summary["median_rss_delta_bytes"] = statistics.median(r["rss_delta_bytes"] for r in ok_runs)
216
+ summary["num_alignments"] = ok_runs[0]["num_alignments"]
217
+ summary["ops_sha256"] = ok_runs[0]["ops_sha256"]
218
+ summary["using_cpp"] = ok_runs[0]["using_cpp"]
219
+ if saved_ops is not None:
220
+ with open(f"{out_dir}/{label}/{case}.ops.json", "w") as f:
221
+ json.dump(saved_ops, f, sort_keys=True)
222
+ return summary
223
+
224
+
225
+ def compare_labels(summaries: list[dict], out_dir: str, label: str, compare_dir: str) -> bool:
226
+ """Assert that serialized Alignments are identical between two labels."""
227
+ identical = True
228
+ for summary in summaries:
229
+ case = summary["case"]
230
+ recorded_path = f"{compare_dir}/{case}.ops.json"
231
+ try:
232
+ with open(recorded_path) as f:
233
+ recorded = json.load(f)
234
+ except FileNotFoundError:
235
+ print(f"[compare] {case}: no recorded ops at {recorded_path}, marking comparison as failed")
236
+ identical = False
237
+ continue
238
+ with open(f"{out_dir}/{label}/{case}.ops.json") as f:
239
+ current = json.load(f)
240
+ if current == recorded:
241
+ print(f"[compare] {case}: alignments IDENTICAL to {compare_dir}")
242
+ else:
243
+ print(f"[compare] {case}: alignments DIFFER from {compare_dir}")
244
+ identical = False
245
+ return identical
246
+
247
+
248
+ def run_suite(cases: list[str], runs: int, label: str, out_dir: str, compare_dir: str | None, timeout_s: int) -> int:
249
+ """Run all requested cases and print a summary table."""
250
+ import os
251
+
252
+ os.makedirs(f"{out_dir}/{label}", exist_ok=True)
253
+
254
+ summaries = [run_case(case, runs, label, out_dir, timeout_s) for case in cases]
255
+
256
+ header = f"{'case':<12} {'wall_s':>10} {'peak RSS':>12} {'delta':>12} {'alignments':>11} {'status':>8}"
257
+ print(f"\nlabel={label} runs={runs} (medians of successful runs)\n{header}")
258
+ for summary in summaries:
259
+ if summary.get("num_ok_runs"):
260
+ wall = f"{summary['median_wall_s']:.2f}"
261
+ peak = _fmt_bytes(summary["median_peak_rss_bytes"])
262
+ delta = _fmt_bytes(summary["median_rss_delta_bytes"])
263
+ num = str(summary["num_alignments"])
264
+ status = f"ok x{summary['num_ok_runs']}"
265
+ else:
266
+ wall, peak, delta, num = "-", "-", "-", "-"
267
+ status = summary["runs"][-1]["status"]
268
+ print(f"{summary['case']:<12} {wall:>10} {peak:>12} {delta:>12} {num:>11} {status:>8}")
269
+
270
+ with open(f"{out_dir}/{label}/summary.json", "w") as f:
271
+ json.dump(summaries, f, indent=2, sort_keys=True)
272
+
273
+ if any(summary["num_ok_runs"] == 0 for summary in summaries):
274
+ print("[bench] incomplete runs: some cases had no successful run; not comparing")
275
+ return 3
276
+ if compare_dir:
277
+ return 0 if compare_labels(summaries, out_dir, label, compare_dir) else 2
278
+ return 0
279
+
280
+
281
+ def main() -> None:
282
+ """Parse arguments and dispatch to the child or suite runner."""
283
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
284
+ parser.add_argument("--child", action="store_true", help="Run a single case in-process (internal).")
285
+ parser.add_argument("--case", required=True, help=f"Case name or comma-separated list, or 'all': {CASES}")
286
+ parser.add_argument("--runs", type=int, default=3, help="Runs per case (default: 3)")
287
+ parser.add_argument("--label", default="run", help="Label for this measurement, e.g. 'before' or 'after'")
288
+ parser.add_argument("--out", default="bench_results", help="Output directory for results")
289
+ parser.add_argument("--compare", default=None, help="Directory with recorded ops to compare against")
290
+ parser.add_argument("--timeout-s", type=int, default=3600, help="Per-run subprocess timeout in seconds")
291
+ args = parser.parse_args()
292
+
293
+ if args.child:
294
+ run_child(args.case)
295
+ return
296
+
297
+ if args.case == "all":
298
+ cases = list(CASES)
299
+ else:
300
+ cases = [case.strip() for case in args.case.split(",")]
301
+ for case in cases:
302
+ if case not in CASES:
303
+ parser.error(f"Unknown case: {case}. Valid cases: {CASES}")
304
+
305
+ sys.exit(run_suite(cases, args.runs, args.label, args.out, args.compare, args.timeout_s))
306
+
307
+
308
+ if __name__ == "__main__":
309
+ main()
@@ -1,5 +1,5 @@
1
1
  ignore:
2
- - "src/error_align/baselines/*"
2
+ - "**/baselines/**"
3
3
 
4
4
  coverage:
5
5
  status:
@@ -7,6 +7,8 @@
7
7
  #include <unordered_set>
8
8
  #include <string>
9
9
  #include <limits>
10
+ #include <memory>
11
+ #include <optional>
10
12
  #include <codecvt>
11
13
  #include <locale>
12
14
 
@@ -99,6 +101,9 @@ static inline bool in_unambiguous(const SrcView* s, int hyp, int ref) {
99
101
 
100
102
 
101
103
  // ---------- Path (C++ analog) ----------
104
+
105
+ using EndIndex = std::tuple<int, int, double>;
106
+
102
107
  struct Path {
103
108
  const SrcView* src; // non-owning
104
109
  int ref_idx = -1;
@@ -108,7 +113,11 @@ struct Path {
108
113
  double closed_cost = 0.0;
109
114
  double open_cost = 0.0;
110
115
  bool at_unambiguous_match_node = false;
111
- std::vector<std::tuple<int,int,double>> end_indices;
116
+ // NOTE: Shared, immutable segment history with copy-on-append, like the
117
+ // Python Path, which shares the end_indices tuple between parent and
118
+ // child and builds a new tuple only when a segment ends. This avoids
119
+ // deep-copying the full history on every expansion.
120
+ std::shared_ptr<const std::vector<EndIndex>> end_indices;
112
121
  std::uint64_t sort_id = 0;
113
122
 
114
123
  inline bool at_end() const {
@@ -178,12 +187,20 @@ static inline void reset_segment_variables(Path& p, int hyp_idx, int ref_idx) {
178
187
  p.open_cost = 0.0;
179
188
  }
180
189
 
190
+ // Append to end_indices with copy-on-write semantics: the parent's vector is
191
+ // never mutated, matching the Python tuple-carry-forward behavior.
192
+ static inline void append_end_index(Path& p, int hyp_idx, int ref_idx) {
193
+ auto next = std::make_shared<std::vector<EndIndex>>(*p.end_indices);
194
+ next->emplace_back(hyp_idx, ref_idx, p.open_cost);
195
+ p.end_indices = std::move(next);
196
+ }
197
+
181
198
  static inline void end_insertion_segment(Path& p, int hyp_idx, int ref_idx) {
182
199
  // hyp slice = [last_hyp_idx+1, hyp_idx+1)
183
200
  bool hyp_slice_ok = has_valid_slice_any_nonneg_psum(p.src->hyp_nonneg_psum, p.last_hyp_idx + 1, hyp_idx + 1);
184
201
  bool ref_is_empty = (ref_idx == p.last_ref_idx);
185
202
  if (hyp_slice_ok && ref_is_empty) {
186
- p.end_indices.emplace_back(hyp_idx, ref_idx, p.open_cost);
203
+ append_end_index(p, hyp_idx, ref_idx);
187
204
  reset_segment_variables(p, hyp_idx, ref_idx);
188
205
  }
189
206
  }
@@ -199,7 +216,7 @@ static inline bool end_segment(Path& p) {
199
216
  // hyp side:
200
217
  bool hyp_is_empty = (p.hyp_idx == p.last_hyp_idx);
201
218
  if (hyp_is_empty) {
202
- p.end_indices.emplace_back(p.hyp_idx, p.ref_idx, p.open_cost);
219
+ append_end_index(p, p.hyp_idx, p.ref_idx);
203
220
  } else {
204
221
  bool hyp_slice_ok = has_valid_slice_any_nonneg_psum(p.src->hyp_nonneg_psum, p.last_hyp_idx + 1, p.hyp_idx + 1);
205
222
  if (!hyp_slice_ok) {
@@ -208,7 +225,7 @@ static inline bool end_segment(Path& p) {
208
225
  bool is_match_segment = (p.open_cost == 0.0);
209
226
  p.at_unambiguous_match_node =
210
227
  is_match_segment && in_unambiguous(p.src, p.hyp_idx, p.ref_idx);
211
- p.end_indices.emplace_back(p.hyp_idx, p.ref_idx, p.open_cost);
228
+ append_end_index(p, p.hyp_idx, p.ref_idx);
212
229
  }
213
230
 
214
231
  reset_segment_variables(p, p.hyp_idx, p.ref_idx);
@@ -222,11 +239,10 @@ uint64_t update_hash(uint64_t h, uint64_t t) {
222
239
  }
223
240
 
224
241
  static inline Path transition_to_child_node(const Path& parent, int ref_step, int hyp_step) {
225
- Path child = parent; // shallow copy (we’ll adjust fields)
242
+ Path child = parent; // shallow copy (end_indices is shared, copy-on-append)
226
243
  child.ref_idx = parent.ref_idx + ref_step;
227
244
  child.hyp_idx = parent.hyp_idx + hyp_step;
228
245
  child.at_unambiguous_match_node = false;
229
- // end_indices is copied (like Python’s tuple carry-forward)
230
246
  int transition_value = ref_step * 2 + hyp_step;
231
247
  child.sort_id = update_hash(parent.sort_id, transition_value);
232
248
  return child;
@@ -343,7 +359,7 @@ static py::object to_python_path_like(const Path& p) {
343
359
 
344
360
  // end_indices as tuple of (hyp_idx, ref_idx, open_cost)
345
361
  py::list triples;
346
- for (const auto& t : p.end_indices) {
362
+ for (const auto& t : *p.end_indices) {
347
363
  triples.append(py::make_tuple(std::get<0>(t), std::get<1>(t), std::get<2>(t)));
348
364
  }
349
365
  d["end_indices"] = py::tuple(triples);
@@ -354,12 +370,26 @@ static py::object to_python_path_like(const Path& p) {
354
370
  }
355
371
 
356
372
  // ----------------- Main function -----------------
373
+
374
+ // Strict ordering of finished paths by (cost, sort_id). Replacement under
375
+ // this ordering keeps the first-seen path among exact ties, matching the
376
+ // stable sort of the Python implementation.
377
+ static inline bool ended_less(const Path& a, const Path& b) {
378
+ const double ac = a.cost();
379
+ const double bc = b.cost();
380
+ if (ac < bc) return true;
381
+ if (bc < ac) return false;
382
+ return a.sort_id < b.sort_id;
383
+ }
384
+
357
385
  static py::object error_align_beam_search_cpp(py::object src_obj, int beam_size) {
358
386
  // View over SubgraphMetadata (already initialized on Python side)
359
387
  SrcView src = make_src_view(src_obj);
360
388
 
361
389
  // Initialize beam with root path
362
- Path start; start.src = &src;
390
+ Path start;
391
+ start.src = &src;
392
+ start.end_indices = std::make_shared<const std::vector<EndIndex>>();
363
393
  std::vector<Path> beam;
364
394
  beam.reserve(128);
365
395
  beam.push_back(start);
@@ -367,8 +397,11 @@ static py::object error_align_beam_search_cpp(py::object src_obj, int beam_size)
367
397
  // Prune map: prune_id -> best cost seen so far
368
398
  std::unordered_map<std::size_t, double> prune_map;
369
399
  prune_map.reserve(4096);
370
- std::vector<Path> ended;
371
- ended.reserve(128);
400
+
401
+ // NOTE: Only the best finished path can win the final selection, so only
402
+ // the best finished path is kept. Accumulating every finished path is
403
+ // pure memory overhead on repetition-style content.
404
+ std::optional<Path> ended;
372
405
 
373
406
  while (!beam.empty()) {
374
407
  std::unordered_map<std::size_t, Path> new_beam;
@@ -376,7 +409,8 @@ static py::object error_align_beam_search_cpp(py::object src_obj, int beam_size)
376
409
 
377
410
  for (const Path& path : beam) {
378
411
  if (path.at_end()) {
379
- ended.push_back(path);
412
+ if (!ended || ended_less(path, *ended))
413
+ ended = path;
380
414
  continue;
381
415
  }
382
416
  for (auto& new_path : expand_paths(path)) {
@@ -428,23 +462,10 @@ static py::object error_align_beam_search_cpp(py::object src_obj, int beam_size)
428
462
  }
429
463
  }
430
464
 
431
- if (ended.empty()) {
465
+ if (!ended) {
432
466
  return py::list(); // same as Python: return []
433
467
  }
434
- std::sort(ended.begin(), ended.end(),
435
- [](const Path& a, const Path& b) {
436
-
437
- double ac = a.cost();
438
- double bc = b.cost();
439
-
440
- if (ac < bc) return true;
441
- if (bc < ac) return false;
442
-
443
- // Tie → use deterministic hash tiebreaker
444
- return a.sort_id < b.sort_id;
445
- }
446
- );
447
- return to_python_path_like(ended.front());
468
+ return to_python_path_like(*ended);
448
469
  }
449
470
 
450
471
  // ----------------- Wrapper to expose expand_paths -----------------
@@ -463,7 +484,8 @@ static py::list expand_paths_wrapper(py::object py_path_obj) {
463
484
  p.closed_cost = py::cast<double>(py_path_obj.attr("closed_cost"));
464
485
  p.open_cost = py::cast<double>(py_path_obj.attr("open_cost"));
465
486
  p.at_unambiguous_match_node = py::cast<bool>(py_path_obj.attr("at_unambiguous_match_node"));
466
- p.end_indices = py::cast<std::vector<std::tuple<int,int,double>>>(py_path_obj.attr("end_indices"));
487
+ p.end_indices = std::make_shared<const std::vector<EndIndex>>(
488
+ py::cast<std::vector<EndIndex>>(py_path_obj.attr("end_indices")));
467
489
  p.sort_id = py::cast<std::uint64_t>(py_path_obj.attr("sort_id"));
468
490
 
469
491