Repository navigation
Expand file tree
/
Copy pathevaluate.py
More file actions
378 lines (333 loc) · 12 KB
/
Copy pathevaluate.py
File metadata and controls
378 lines (333 loc) · 12 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import json
import pathlib
import click
from lib import logging
from lib.cli import DefaultGroup, csv_list, csv_set
from lib.config.io import load_raw_config
from lib.config.schema import ConfigurationScope
def shared_input_options(func):
options = [
click.option(
"--dataset", "-d", required=True,
type=click.Path(exists=True, dir_okay=True, file_okay=False, path_type=pathlib.Path),
help="Path to the binarized dataset directory.",
),
click.option(
"--model", "-m", required=True,
type=click.Path(exists=True, dir_okay=False, file_okay=True, path_type=pathlib.Path),
help="Path to model checkpoint.",
),
click.option(
"--prefix", default="valid", show_default=True,
help="Dataset prefix (e.g. valid, train).",
),
]
for option in options[::-1]:
func = option(func)
return func
def shared_output_options(func):
options = [
click.option(
"--output-dir", "-o", required=True,
type=click.Path(file_okay=False, writable=True, path_type=pathlib.Path),
help="Directory to save evaluation results.",
),
click.option(
"--plot", is_flag=True,
help="Save per-sample plots.",
),
]
for option in options[::-1]:
func = option(func)
return func
def shared_trainer_options(func):
options = [
click.option(
"--skip-penalty", type=float, default=0.5, show_default=True,
help="Raw cosine-score cost per skipped phoneme during online alignment.",
),
click.option(
"--batch-size", type=int, default=4, show_default=True,
help="Batch size for evaluation.",
),
click.option(
"--concat-size", type=int, default=None,
help="Concatenate up to N samples per item to test context length.",
),
click.option(
"--concat-deterministic", is_flag=True, default=False,
help="Use deterministic grouping for sample concatenation.",
),
click.option(
"--num-workers", type=int, default=0, show_default=True,
help="Number of dataloader worker processes.",
),
click.option(
"--precision", default="32-true", show_default=True,
help="Precision for evaluation.",
),
]
for option in options[::-1]:
func = option(func)
return func
def shared_metric_options(func=None, *, unit="ms"):
if unit == "ms":
ber_opt = click.option(
"--ber-tols-ms", "ber_tols", default="50", show_default=True,
callback=csv_list(int),
help="Comma-separated BER tolerances in milliseconds.",
)
elif unit == "frame":
ber_opt = click.option(
"--ber-tols", "ber_tols", default="5", show_default=True,
callback=csv_list(int),
help="Comma-separated BER tolerances in frames.",
)
else:
raise ValueError(f"Unknown metric unit: {unit}")
options = [
ber_opt,
click.option(
"--token-topk", default="20", show_default=True,
callback=csv_list(int),
help="Comma-separated worst-k values for per-token metrics.",
),
click.option(
"--pair-topk", default="20", show_default=True,
callback=csv_list(int),
help="Comma-separated worst-k values for pair conjunction metrics.",
),
click.option(
"--determinacy-power", default=2.0, show_default=True,
type=float,
help="Activation power for Determinacy metric.",
),
click.option(
"--determinacy-width", default=5, show_default=True,
type=int,
help="Neighborhood half-width in tokens for Determinacy metric."
" set to negative for unlimited (all tokens).",
),
click.option(
"--monotonicity-power", default=2.0, show_default=True,
type=float,
help="Activation power for Monotonicity metric.",
),
click.option(
"--monotonicity-width", default=-1, show_default=True,
type=int,
help="Neighborhood half-width in tokens for Monotonicity metric."
" set to negative for unlimited (global monotonicity).",
),
]
def decorator(f):
for option in reversed(options):
f = option(f)
return f
if func is None:
return decorator
return decorator(func)
def _check_file_and_config(file: pathlib.Path, expected):
actual = load_raw_config(file, inherit=False, overrides=None)
if actual != expected:
raise RuntimeError(
f"Contents of '{file}' do not match the model configuration. "
f"The dataset was binarized with different parameters. "
f"Please re-binarize."
)
def _check_vocabulary(checkpoint_dir: pathlib.Path, dataset_dir: pathlib.Path):
ckpt_vocab_path = checkpoint_dir / "vocabulary.json"
dataset_vocab_path = dataset_dir / "vocabulary.json"
if not ckpt_vocab_path.is_file():
raise FileNotFoundError(f"Vocabulary not found at {ckpt_vocab_path}")
if not dataset_vocab_path.is_file():
raise FileNotFoundError(f"Vocabulary not found at {dataset_vocab_path}")
with open(ckpt_vocab_path, "r", encoding="utf8") as f:
ckpt_vocab = json.load(f)["symbols"]
with open(dataset_vocab_path, "r", encoding="utf8") as f:
dataset_vocab = json.load(f)["symbols"]
if ckpt_vocab != dataset_vocab:
raise RuntimeError(
"Vocabulary mismatch between checkpoint and dataset. "
"The dataset was binarized with a different vocabulary "
"than the model was trained with."
)
def _run_online_evaluation(
scope: int,
dataset: pathlib.Path,
model: pathlib.Path,
prefix: str,
output_dir: pathlib.Path,
batch_size: int,
concat_size: int,
concat_deterministic: bool,
num_workers: int,
precision: str,
ber_tols: list[int],
token_topk: list[int],
pair_topk: list[int],
plot: bool,
skip_penalty: float = 0.5,
determinacy_power: float = 2.0,
determinacy_width: int = 5,
monotonicity_power: float = 2.0,
monotonicity_width: int = -1,
):
if determinacy_width < 0:
determinacy_width = None
if monotonicity_width < 0:
monotonicity_width = None
from lightning_utilities.core.rank_zero import rank_zero_info
from inference.api import (
load_inference_model,
run_inference,
)
from inference.callbacks import StatisticsCallback, EvaluationMetricsCallback, SavePlotCallback
from training.data import PhonemeTimingDataset
backend, vocabulary, inference_config = load_inference_model(model, scope=scope)
_check_file_and_config(
dataset / "feature.yaml", inference_config.features.model_dump()
)
_check_vocabulary(model.parent, dataset)
ds = PhonemeTimingDataset(
data_dir=dataset,
prefix=prefix,
max_concat_size=concat_size,
concat_deterministic=concat_deterministic,
concat_dynamic_size=False,
augmentation_config=None,
)
output_dir.mkdir(parents=True, exist_ok=True)
save_path = output_dir / "summary.json"
item_paths = [ds.get_metadata("item_paths", i) for i in range(len(ds))]
callbacks = [
EvaluationMetricsCallback(
unit="frame",
vocab=vocabulary,
save_path=save_path,
ber_tols=ber_tols,
token_topk=token_topk,
pair_topk=pair_topk,
determinacy_power=determinacy_power,
determinacy_width=determinacy_width,
monotonicity_power=monotonicity_power,
monotonicity_width=monotonicity_width,
),
StatisticsCallback(
save_dir=output_dir / "statistics",
determinacy_power=determinacy_power,
determinacy_width=determinacy_width,
monotonicity_power=monotonicity_power,
monotonicity_width=monotonicity_width,
identifiers=item_paths,
),
]
if plot:
callbacks.append(
SavePlotCallback(
output_dir=output_dir / "plots",
vocab=vocabulary,
identifiers=item_paths,
)
)
run_inference(
backend=backend,
dataset=ds,
callbacks=callbacks,
batch_size=batch_size,
num_workers=num_workers,
precision=precision,
skip_penalty=skip_penalty,
mode="evaluate",
)
logging.success("Online evaluation completed.", callback=rank_zero_info)
def _run_offline_evaluation(
pred_dir: pathlib.Path,
gt_dir: pathlib.Path,
tier_name: str,
stop_symbols: set[str],
mismatch_handling: str,
output_dir: pathlib.Path,
ber_tols: list[int],
token_topk: list[int],
pair_topk: list[int],
**kwargs,
):
from lightning_utilities.core.rank_zero import rank_zero_info
from inference.api import evaluate_offline
from inference.callbacks import EvaluationMetricsCallback, StatisticsCallback
from inference.data import PairedDataset, TextGridDataset
pred_ds = TextGridDataset(pred_dir, tier_name=tier_name, stop_symbols=stop_symbols)
gt_ds = TextGridDataset(gt_dir, tier_name=tier_name, stop_symbols=stop_symbols)
paired = PairedDataset(
pred_dataset=pred_ds,
gt_dataset=gt_ds,
mismatch_handling=mismatch_handling,
)
output_dir.mkdir(parents=True, exist_ok=True)
save_path = output_dir / "summary.json"
statistic_callback = StatisticsCallback(
save_dir=output_dir / "statistics",
unit_factor=1000.0,
)
metric_callback = EvaluationMetricsCallback(
unit="ms",
vocab=paired.vocab,
save_path=save_path,
ber_tols=ber_tols,
token_topk=token_topk,
pair_topk=pair_topk,
)
evaluate_offline(dataset=paired, callbacks=[statistic_callback, metric_callback])
logging.success("Offline evaluation completed.", callback=rank_zero_info)
@click.group(cls=DefaultGroup, help="Evaluate a model or compare TextGrids.")
def main():
pass
@main.default_command()
@shared_input_options
@shared_output_options
@shared_trainer_options
@shared_metric_options(unit="frame")
def supervised(**kwargs):
"""Supervised online evaluation on a binarized dataset."""
_run_online_evaluation(scope=ConfigurationScope.FA, **kwargs)
# @main.command(name="ssl")
# @shared_input_options
# @shared_output_options
# @shared_trainer_options
# @shared_metric_options(unit="frame")
def ssl(**kwargs):
"""Self-supervised online evaluation."""
_run_online_evaluation(scope=ConfigurationScope.FA_SSL, **kwargs)
@main.command(name="offline")
@click.option(
"--pred", "pred_dir", required=True,
type=click.Path(exists=True, dir_okay=True, file_okay=False, path_type=pathlib.Path),
help="Directory of predicted TextGrid files.",
)
@click.option(
"--gt", "gt_dir", required=True,
type=click.Path(exists=True, dir_okay=True, file_okay=False, path_type=pathlib.Path),
help="Directory of ground truth TextGrid files.",
)
@click.option(
"--tier-name", default="phones", show_default=True,
help="TextGrid tier name to extract.",
)
@click.option(
"--stop-symbols", default="AP,SP,EP,GS,sil,br,pau", show_default=True,
callback=csv_set(str),
help="Comma-separated stop symbols to filter from TextGrid intervals.",
)
@click.option(
"--mismatch-handling", default="raise",
type=click.Choice(["raise", "skip"]), show_default=True,
help="How to handle label mismatches: raise or skip.",
)
@shared_output_options
@shared_metric_options(unit="ms")
def offline(**kwargs):
"""Offline evaluation comparing two sets of TextGrid files."""
_run_offline_evaluation(**kwargs)
if __name__ == "__main__":
main()