import pytest import torch from photontts.conditioning.score_clock import NONE, REST, Note, Score, ScoreClockEmbed, frame_features from photontts.conditioning.speaker_encoder import SpeakerEncoder from photontts.config import SpeakerConfig def test_score_frames_and_onsets(): s = Score([Note(0.0, 0.5, 60, syllable=0), Note(0.51, 0.49, 64, slur=True, syllable=1)], tempo_bpm=120) midi, cont = frame_features(25, s) assert midi[0] == 60 and midi[11] == 60 assert midi[13] == 64 and midi[24] == 64 assert cont[0, 2] == 1.0 and cont[0, 3] == 0.0 # onset at frame 0 assert cont[12, 2] == 1.0 # 0.51 s * 25 = 12.75 -> onset in frame 12 assert abs(cont[12, 3].item() - 0.75) < 1e-4 # sub-frame offset assert cont[13, 0] == 1.0 # slur assert cont[:, 6].eq(1.0).all() # has_beat assert 0 < cont[5, 1] < cont[10, 1] < 1 # note position fraction increases def test_rests_vs_none(): midi, _ = frame_features(10, Score([Note(0.2, 0.1, 70)])) assert midi[0] == REST and midi[5] == 70 midi, cont = frame_features(10, None) assert midi.eq(NONE).all() and cont.abs().sum() == 0 def test_transpose(): s = Score([Note(0, 1, 60), Note(1, 1, REST)]).transpose(3) assert s.notes[0].midi == 63 and s.notes[1].midi == REST def test_f0_and_progress_features(): f0 = torch.tensor([0.0, 200.0, 400.0, 0.0]) _, cont = frame_features(4, f0=f0, total_duration=0.16) assert cont[:, 9].eq(1).all() and cont[0, 8] == 0 and cont[1, 8] == 1 assert abs(cont[1, 7].item()) < 1e-5 # log(200/200) = 0 assert cont[0, 10] < cont[3, 10] <= 1.0 def test_clock_embed_shapes_and_init_noop(): emb = ScoreClockEmbed(32, 128, 2) midi, cont = frame_features(10, Score([Note(0, 0.4, 60)])) frame, patch = emb(midi[None], cont[None], lag=torch.zeros(1, 5, dtype=torch.long)) assert frame.shape == (1, 10, 32) and patch.shape == (1, 5, 128) assert patch.abs().max() == 0 # zero-init: does not perturb a pretrained LLM at start def test_speaker_encoder_mask_invariance(): torch.manual_seed(0) enc = SpeakerEncoder(SpeakerConfig(n_tokens=4, dim=64, layers=2, heads=4), 64, 128).eval() ref = torch.randn(1, 50, 64) a, _ = enc(ref, torch.ones(1, 50, dtype=torch.bool)) padded = torch.cat([ref, torch.randn(1, 20, 64) * 100], 1) mask = torch.cat([torch.ones(1, 50), torch.zeros(1, 20)], 1).bool() b, _ = enc(padded, mask) assert a.shape == (1, 4, 128) assert torch.allclose(a, b, atol=1e-4) def test_speaker_emotion_adversary_reverses_grad(): enc = SpeakerEncoder(SpeakerConfig(n_tokens=4, dim=32, layers=2, heads=4, n_emotions=5), 64, 64) ref = torch.randn(2, 30, 64, requires_grad=True) _, emo = enc(ref, torch.ones(2, 30, dtype=torch.bool)) assert emo.shape == (2, 5) emo.sum().backward() assert enc.emotion_head.weight.grad is not None