Download recipe/kit-v3/alignment_head/test_streaming.py from gowombat/tiny-voca-da: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/kit-v3/alignment_head/test_streaming.py
- Command line
-
hf download hf://gowombat/tiny-voca-da/recipe/kit-v3/alignment_head/test_streaming.py
-
curl -L -o test_streaming.py https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/kit-v3/alignment_head/test_streaming.py
13.1 kB
| """Numerical and integrity regressions for bounded CTC representation loading.""" | |
| import argparse | |
| import copy | |
| import contextlib | |
| import io | |
| import json | |
| from pathlib import Path | |
| import shutil | |
| import tempfile | |
| import unittest | |
| from unittest.mock import patch | |
| import torch | |
| import adapt_head as a | |
| class StreamingTests(unittest.TestCase): | |
| def make_cache(self, root, name, hidden=None): | |
| root.mkdir(parents=True) | |
| if hidden is None: | |
| hidden = torch.arange(80, dtype=torch.float16).reshape(20, 4) / 20 | |
| target = root / f'{name}.pt' | |
| a.atomic_torch_save(target, {'hidden': hidden, 'audio_sha256': name, | |
| 'samples': 512, 'acoustic_frames': 2}) | |
| row = {'id': name, 'audio_sha256': name, 'cache': target.name, | |
| 'cache_sha256': a.sha(target), 'ctc_frames': len(hidden), 'acoustic_frames': 2, | |
| 'split': 'train', 'text': 'fixture'} | |
| (root / 'index.jsonl').write_text(json.dumps(row) + '\n') | |
| identity = {'cache_version': 2, 'model': 'fixture', 'sources': {'fixture_manifest': 'fixture_hash'}} | |
| a.atomic_torch_save(root / 'original_head.pt', { | |
| 'state_dict': {'weight': torch.ones(3, 4), 'bias': torch.zeros(3)}, | |
| 'vocabulary': {'blank': 0, 'a': 1, 'b': 2}, 'blank': 0, 'hidden_size': 4}) | |
| a.dump(root / 'identity.json', {'identity': identity, 'complete': True, 'count': 1, | |
| 'index_sha256': a.sha(root / 'index.jsonl'), | |
| 'original_head_sha256': a.sha(root / 'original_head.pt')}) | |
| return {**row, '_cache_root': str(root), 'targets': torch.tensor([1, 2, 1])} | |
| def test_lazy_batch_has_identical_loss_and_gradients_to_eager(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| descriptor = self.make_cache(Path(temporary) / 'cache', 'one') | |
| eager = a.materialize(descriptor) | |
| self.assertNotIn('hidden', descriptor) | |
| torch.manual_seed(81) | |
| first = torch.nn.Linear(4, 3) | |
| second = copy.deepcopy(first) | |
| lazy_loss = a.batch_loss(first, [descriptor]) | |
| eager_loss = a.batch_loss(second, [eager]) | |
| lazy_loss.backward(); eager_loss.backward() | |
| self.assertTrue(torch.equal(lazy_loss, eager_loss)) | |
| for left, right in zip(first.parameters(), second.parameters()): | |
| self.assertTrue(torch.equal(left.grad, right.grad)) | |
| def test_representations_cannot_change_after_verified_read(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| descriptor = self.make_cache(Path(temporary) / 'cache', 'one') | |
| a.materialize(descriptor) | |
| path = Path(descriptor['_cache_root']) / descriptor['cache'] | |
| path.write_bytes(path.read_bytes() + b'changed') | |
| with self.assertRaisesRegex(ValueError, 'changed during run'): | |
| a.materialize(descriptor) | |
| def test_cache_merge_preserves_bytes_and_rejects_duplicate_ids(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| self.make_cache(root / 'a', 'one') | |
| self.make_cache(root / 'b', 'two') | |
| a.merge_caches(argparse.Namespace(cache=[root / 'a', root / 'b'], output=root / 'merged')) | |
| records = a.rows(root / 'merged/index.jsonl') | |
| self.assertEqual({r['id'] for r in records}, {'one', 'two'}) | |
| for row in records: | |
| self.assertEqual(a.sha(root / 'merged' / row['cache']), row['cache_sha256']) | |
| self.make_cache(root / 'duplicate', 'one') | |
| with self.assertRaisesRegex(ValueError, 'duplicate merged ID'): | |
| a.merge_caches(argparse.Namespace(cache=[root / 'a', root / 'duplicate'], output=root / 'bad-merge')) | |
| def test_interrupted_hardlink_merge_resumes_without_replacing_committed_tensor(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| self.make_cache(root / 'a', 'one') | |
| self.make_cache(root / 'b', 'two') | |
| args = argparse.Namespace(cache=[root / 'a', root / 'b'], output=root / 'merged') | |
| original_link, called = a.os.link, [] | |
| def interrupt_second_link(source, target): | |
| called.append(str(target)) | |
| if len(called) == 2: | |
| raise KeyboardInterrupt('simulated merge interruption') | |
| original_link(source, target) | |
| with patch.object(a.os, 'link', side_effect=interrupt_second_link): | |
| with self.assertRaises(KeyboardInterrupt): | |
| a.merge_caches(args) | |
| committed = root / 'merged/part-000/one.pt' | |
| before = committed.stat().st_ino | |
| a.merge_caches(args) | |
| self.assertEqual(before, committed.stat().st_ino) | |
| self.assertEqual(a.sha(committed), a.sha(root / 'a/one.pt')) | |
| self.assertTrue(json.loads((root / 'merged/identity.json').read_text())['complete']) | |
| self.assertEqual(len(a.rows(root / 'merged/index.jsonl')), 2) | |
| def test_stod_probe_does_not_count_uncontrastable_stops_as_correct(self): | |
| result = a.nst_contrast_counts(['nst:p', 'nst:nˀ', 'nst:uː'], | |
| ['nst:p', 'nst:n', 'nst:u'], | |
| ['nst:p', 'nst:n', 'nst:nˀ', 'nst:u', 'nst:uː', 'nst:uːˀ']) | |
| counts = result['counts'] | |
| self.assertEqual(counts['same_base_and_length_pairs'], 1) | |
| self.assertEqual(counts['same_base_and_length_stod_correct'], 0) | |
| self.assertEqual(counts['stod_only_substitutions'], 1) | |
| self.assertEqual(counts['length_only_substitutions'], 1) | |
| self.assertEqual(counts['edits_without_nst_stod'], 1) | |
| self.assertEqual(counts['edits_without_nst_stod_or_length'], 0) | |
| def test_reuse_rejects_nested_changed_thread_runtime(self): | |
| a.check_representation_threads({'merged_worker_runtimes': [ | |
| {'threads': 2, 'reused_cache_runtimes': [{'runtime': {'threads': 2}}]}, {'threads': 2}]}, 2) | |
| with self.assertRaisesRegex(ValueError, 'thread runtimes differ'): | |
| a.check_representation_threads({'merged_worker_runtimes': [ | |
| {'threads': 2}, {'threads': 3}]}, 2) | |
| def test_completed_shard_recovers_missing_provenance_before_cache_removal(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| self.make_cache(root / 'cache', 'one') | |
| evaluation = root / 'evaluation'; evaluation.mkdir() | |
| metadata = json.loads((root / 'cache/identity.json').read_text()) | |
| # Simulate interruption after summary and the first provenance copy. | |
| a.dump(evaluation / 'summary.json', {'complete': True, 'cache_identity': metadata}) | |
| shutil.copy2(root / 'cache/index.jsonl', evaluation / 'representation_index.jsonl') | |
| a.preserve_representation_evidence(evaluation, root / 'cache', metadata) | |
| self.assertEqual(json.loads((evaluation / 'representation_identity.json').read_text()), metadata) | |
| shutil.rmtree(root / 'cache') | |
| a.preserve_representation_evidence(evaluation, root / 'cache', metadata) | |
| with (evaluation / 'representation_index.jsonl').open('a') as stream: | |
| stream.write('{}\n') | |
| with self.assertRaisesRegex(ValueError, 'index differs'): | |
| a.preserve_representation_evidence(evaluation, root / 'cache', metadata) | |
| def test_export_identity_binds_rejected_decisions_to_split_text_and_samples(self): | |
| feature = {'id': 'clip', 'text': 'Hej.', 'provenance': { | |
| 'waveform_sha256': 'samples', 'source_id': 'mic:1', 'source_revision': 'revision'}} | |
| evaluated = {'id': 'clip', 'text': 'Hej.', 'split': 'train', 'waveform_sha256': 'samples', | |
| 'reasons': ['weak_phone_fraction']} | |
| source = {'id': 'clip', 'text': 'Hej.', 'split': 'train', 'waveform_sha256': 'samples', | |
| 'source_id': 'mic:1', 'source_revision': 'revision'} | |
| a.assert_feature_evaluation_identity(feature, 'train', evaluated, source) | |
| with self.assertRaisesRegex(ValueError, 'split differs'): | |
| a.assert_feature_evaluation_identity(feature, 'test', evaluated, source) | |
| changed = copy.deepcopy(feature); changed['provenance']['waveform_sha256'] = 'changed' | |
| with self.assertRaisesRegex(ValueError, 'waveform differs'): | |
| a.assert_feature_evaluation_identity(changed, 'train', evaluated, source) | |
| with self.assertRaisesRegex(ValueError, 'transcript differs'): | |
| a.assert_feature_evaluation_identity({**feature, 'text': 'Farvel.'}, 'train', evaluated, source) | |
| def test_resume_requires_previously_committed_summary_hash(self): | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary) | |
| report = {'note': 'committed'} | |
| a.dump(root / 'summary.json', report) | |
| committed = a.sha(root / 'summary.json') | |
| a.dump(root / 'summary.json', {'note': 'changed'}) | |
| with self.assertRaisesRegex(ValueError, 'previously committed shard summary changed'): | |
| a.verify_completed_shard(root, report, {}, set(), 'train', committed) | |
| def test_interrupted_epoch_resume_restores_optimizer_and_reproduces_weights(self): | |
| # Synthetic hidden states exercise checkpoint semantics only. No WAV, | |
| # model download, pretrained backbone or deliverable training data used. | |
| with tempfile.TemporaryDirectory() as temporary: | |
| root = Path(temporary); cache = root / 'cache'; cache.mkdir() | |
| config = a.Config.for_language('da', ('DA1',)) | |
| a.dump(root / 'config.json', config.to_dict()) | |
| labels = ['<blank>'] + sorted({config.profile.aligner_label(p) for p in config.profile.phones}) | |
| generator = torch.Generator().manual_seed(872) | |
| original = {'state_dict': {'weight': torch.randn(len(labels), 4, generator=generator), | |
| 'bias': torch.zeros(len(labels))}, | |
| 'vocabulary': dict(zip(labels, range(len(labels)))), 'blank': 0, 'hidden_size': 4} | |
| a.atomic_torch_save(cache / 'original_head.pt', original) | |
| index = [] | |
| for i, text in enumerate(['Hej.', 'Pumpen starter.', 'Ventilen er lukket.', 'Døren er åben.']): | |
| path = cache / f'{i}.pt' | |
| a.atomic_torch_save(path, {'hidden': torch.randn(80, 4, generator=generator).half(), | |
| 'audio_sha256': str(i), 'acoustic_frames': 150, 'samples': 38400}) | |
| index.append({'id': str(i), 'text': text, 'split': 'train' if i < 3 else 'validation', | |
| 'audio_sha256': str(i), 'ctc_frames': 80, 'acoustic_frames': 150, | |
| 'cache': path.name, 'cache_sha256': a.sha(path)}) | |
| (cache / 'index.jsonl').write_text(''.join(json.dumps(row) + '\n' for row in index)) | |
| a.dump(cache / 'identity.json', {'identity': a.representation_identity(config), | |
| 'synthetic_test_only': True, 'complete': True, 'count': len(index), | |
| 'index_sha256': a.sha(cache / 'index.jsonl'), | |
| 'original_head_sha256': a.sha(cache / 'original_head.pt')}) | |
| args = argparse.Namespace(cache=cache, config=root / 'config.json', output=root / 'reference', | |
| seed=53, batch_size=2, learning_rate=0.001, epochs=2, weight_decay=0.01, resume=False) | |
| with contextlib.redirect_stdout(io.StringIO()): | |
| a.fit(args) | |
| args.output = root / 'resumed' | |
| original_save = a.atomic_torch_save | |
| def interrupt_after_checkpoint(path, value): | |
| original_save(path, value) | |
| if Path(path).name == 'last.pt' and value.get('epoch') == 1: | |
| raise KeyboardInterrupt('simulated interruption before metrics commit') | |
| with patch.object(a, 'atomic_torch_save', side_effect=interrupt_after_checkpoint): | |
| with self.assertRaises(KeyboardInterrupt): | |
| a.fit(args) | |
| args.resume = True | |
| a.fit(args) | |
| expected = torch.load(root / 'reference/last.pt', weights_only=True) | |
| actual = torch.load(root / 'resumed/last.pt', weights_only=True) | |
| self.assertEqual(actual['epoch'], 2) | |
| for key, value in expected['state_dict'].items(): | |
| self.assertTrue(torch.equal(value, actual['state_dict'][key])) | |
| for parameter, values in expected['optimizer']['state'].items(): | |
| for name, value in values.items(): | |
| self.assertTrue(torch.equal(value, actual['optimizer']['state'][parameter][name])) | |
| self.assertEqual([row['epoch'] for row in a.rows(root / 'resumed/metrics.jsonl')], [1, 2]) | |
| if __name__ == '__main__': | |
| torch.set_num_threads(1) | |
| unittest.main() | |