File size: 6,266 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 111 112 113 114 115 116 117 118 | import unittest
from dataclasses import replace
import copy
import hashlib
import json
import torch
from initialize_danish import migrate, source_symbols, validate_source_frontend
from tiny_voca.config import CHECKPOINT_FORMAT, Config
from tiny_voca.languages import ENGLISH
from tiny_voca.model import TinyVoca
from tiny_voca.text import FRONTEND_VERSION, ESPEAK_VOICE, SEPARATOR
def signed_identity(identity):
return {**identity, 'fingerprint': hashlib.sha256(
json.dumps(identity, sort_keys=True, ensure_ascii=False).encode()).hexdigest()}
class InitializationTests(unittest.TestCase):
def setUp(self):
settings = dict(channels=16, heads=2, feedforward=32, kernel=3,
encoder_layers=1, prosody_layers=1, acoustic_layers=1,
predictor_channels=16, cep_causal=12, cep_anti=4, noise_cep=8)
self.source_config = Config.for_language('en', ('F2', 'M2'), **settings)
self.target_config = Config.for_language('da', ('DA1',), **settings)
torch.manual_seed(12)
self.source_model = TinyVoca(self.source_config)
self.source = {'format_version': CHECKPOINT_FORMAT,
'config': self.source_config.to_dict(), 'step': 100,
'model': self.source_model.state_dict(),
'frontend': signed_identity({'frontend_version': 4, 'phonemizer': 'dizione',
'symbols': list(ENGLISH.symbols)})}
def test_copies_network_and_both_voice_tables_without_relabeling_ids(self):
target, report = migrate(self.source, self.target_config, 'M2')
state = target.state_dict()
for name in report['copied_tensor_names']:
self.assertTrue(torch.equal(state[name], self.source['model'][name]), name)
for name in ('voices.weight', 'frame_voices.weight'):
self.assertTrue(torch.equal(state[name][0], self.source['model'][name][1]))
source_id = self.source_config.profile.symbol_to_id['ə']
target_id = self.target_config.profile.symbol_to_id['ə']
self.assertTrue(torch.equal(state['tokens.weight'][target_id],
self.source['model']['tokens.weight'][source_id]))
self.assertEqual(report['danish_training_steps'], 0)
self.assertEqual(report['source_frontend_validation']['family'], 'dizione-v4')
self.assertEqual(len(report['token_rows']), self.target_config.vocab_size)
self.assertEqual(target.phone_tokens.shape[0], self.target_config.vocab_size)
def test_target_updates_do_not_mutate_original_weights(self):
target, _ = migrate(self.source, self.target_config, 'M2')
before = self.source['model']['encoder.blocks.0.norm1.weight'].clone()
with torch.no_grad():
target.encoder.blocks[0].norm1.weight.add_(1)
self.assertTrue(torch.equal(before, self.source['model']['encoder.blocks.0.norm1.weight']))
def test_missing_phone_mapping_and_wrong_voice_fail(self):
with self.assertRaisesRegex(ValueError, 'No reviewed'):
source_symbols('unreviewed_phone', ENGLISH)
with self.assertRaisesRegex(ValueError, 'Source voice'):
migrate(self.source, self.target_config, 'missing')
def test_architecture_changes_fail(self):
different = replace(self.target_config, channels=32)
with self.assertRaisesRegex(ValueError, 'Architecture/DSP'):
migrate(self.source, different, 'M2')
class EnglishSourceFrontendGuardTests(unittest.TestCase):
def setUp(self):
self.config = Config.for_language('en', ('F2', 'M2'))
self.identity = {'frontend_version': 4, 'phonemizer': 'dizione', 'symbols': list(ENGLISH.symbols)}
def test_published_dizione_contract_is_accepted_without_loading_dizione(self):
source = {'frontend': signed_identity(self.identity)}
result = validate_source_frontend(source, self.config)
self.assertEqual(result['family'], 'dizione-v4')
self.assertEqual(result['fingerprint'], 'c729f235e10daa1a08ce7711169c1cb93fb552b3c24eecb16527513d7b69d4da')
self.assertEqual(result['symbol_count'], 76)
def test_known_legacy_espeak_contract_is_accepted(self):
identity = {'frontend_version': FRONTEND_VERSION, 'voice': ESPEAK_VOICE, 'separator': SEPARATOR,
'symbols': list(ENGLISH.symbols),
'fallback': {key: list(value) for key, value in sorted(ENGLISH.fallback.items())}}
self.assertEqual(validate_source_frontend({'frontend': signed_identity(identity)}, self.config)['family'], 'espeak-v3')
def test_missing_metadata_is_not_inferred_from_config(self):
for source in ({}, {'frontend': None}, {'frontend': []}):
with self.subTest(source=source), self.assertRaisesRegex(ValueError, 'metadata'):
validate_source_frontend(source, self.config)
def test_tampered_fingerprint_fails(self):
stored = signed_identity(self.identity)
stored['frontend_version'] = 5
with self.assertRaisesRegex(ValueError, 'fingerprint'):
validate_source_frontend({'frontend': stored}, self.config)
def test_same_size_reordered_symbols_fail_even_with_recomputed_fingerprint(self):
identity = copy.deepcopy(self.identity)
identity['symbols'][17], identity['symbols'][18] = identity['symbols'][18], identity['symbols'][17]
with self.assertRaisesRegex(ValueError, 'symbol order'):
validate_source_frontend({'frontend': signed_identity(identity)}, self.config)
def test_self_consistent_unknown_frontend_is_not_assumed_supported(self):
identity = {**self.identity, 'phonemizer': 'another-program'}
with self.assertRaisesRegex(ValueError, 'Unsupported'):
validate_source_frontend({'frontend': signed_identity(identity)}, self.config)
def test_language_metadata_cannot_contradict_english_config(self):
source = {'frontend': signed_identity(self.identity), 'language': {'language': 'da'}}
with self.assertRaisesRegex(ValueError, 'language metadata'):
validate_source_frontend(source, self.config)
if __name__ == '__main__':
unittest.main()
|