File size: 6,012 Bytes
2cf4a54 | 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 | #!/usr/bin/env python3
"""Numerical and teacher-forcing checks using small CPU STARFlow models."""
import unittest
import torch
import torch.nn.functional as F
from torch.distributions import Independent, Normal, kl_divergence
from visualize_pie_bench_token_kl import conditional_kl_maps, diagonal_gaussian_kl
from transformer_flow import IdentityBlock, INV_SOFTPLUS_1, KVCache, Model
class ConditionalKLTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
torch.set_num_threads(1)
def test_analytic_kl_matches_distribution_library(self):
torch.manual_seed(12)
ms, mt = torch.randn(2, 7, 4), torch.randn(2, 7, 4)
ss, st = torch.randn(2, 7, 4).exp(), torch.randn(2, 7, 4).exp()
kl, mean, variance = diagonal_gaussian_kl(ms, ss, mt, st)
expected = kl_divergence(Independent(Normal(ms.double(), ss.double()), 1),
Independent(Normal(mt.double(), st.double()), 1))
torch.testing.assert_close(kl, expected, atol=1e-12, rtol=1e-12)
torch.testing.assert_close(kl, mean + variance, atol=0, rtol=0)
self.assertTrue((mean >= 0).all() and (variance >= 0).all())
reverse, _, _ = diagonal_gaussian_kl(mt, st, ms, ss)
self.assertFalse(torch.allclose(kl, reverse))
def test_identical_and_nearly_identical_gaussians(self):
mu, sigma = torch.zeros(1, 4, dtype=torch.float64), torch.ones(1, 4, dtype=torch.float64)
for value in diagonal_gaussian_kl(mu, sigma, mu, sigma):
self.assertEqual(value.count_nonzero(), 0)
kl, mean, variance = diagonal_gaussian_kl(mu, sigma, mu, sigma * (1 + 1e-8))
self.assertEqual(mean.count_nonzero(), 0)
self.assertTrue((kl > 0).all() and (variance > 0).all())
torch.testing.assert_close(kl, torch.full_like(kl, 4e-16), atol=1e-23, rtol=1e-6)
def test_parameters_match_forward_and_autoregressive_prediction(self):
for order, sos, softplus, patch_size, identity in (
('L2R', True, True, 1, False), ('R2L', False, False, 2, True)):
with self.subTest(order=order, sos=sos, patch_size=patch_size):
torch.manual_seed(23)
model = Model(in_channels=4, img_size=4, patch_size=patch_size, channels=32,
num_blocks=3, layers_per_block=[0 if identity else 1, 1, 2],
head_dim=32, rope=True, sos=sos, txt_size=3, txt_dim=8,
cond_top_only=True, use_softplus=softplus, use_final_norm=True,
soft_clip=0.2, seq_order=order).eval().requires_grad_(False)
with torch.no_grad():
for block in model.blocks:
if not isinstance(block, IdentityBlock):
block.proj_out.weight.normal_(std=0.1)
block.proj_out.bias.normal_(std=0.03)
latent, cs, ct = torch.randn(2, 4, 4, 4), torch.randn(2, 3, 8), torch.randn(2, 3, 8)
maps = conditional_kl_maps(model, latent, cs, ct)
identical = conditional_kl_maps(model, latent, cs, cs)
self.assertEqual(identical['kl_source_target'].count_nonzero(), 0)
_, _, states, _ = model(latent, cs)
torch.testing.assert_close(maps['source_state'], states[-2], atol=0, rtol=0)
top = model.blocks[-1]
self.assertFalse(top.proj_out._forward_hooks)
for name, condition in (('source', cs), ('target', ct)):
mu, sigma = maps[f'{name}_mu'], maps[f'{name}_sigma']
actual, _, logdet = top(states[-2], condition, model.feat_rope_gen)
torch.testing.assert_close((states[-2] - mu) / sigma, actual, atol=2e-6, rtol=2e-6)
flat_sigma = sigma.reshape(sigma.shape[0], -1, sigma.shape[-1])
ordered_sigma = top.permutation.permute(flat_sigma, shape=sigma.shape)
torch.testing.assert_close(-ordered_sigma.log(), logdet, atol=2e-6, rtol=2e-6)
freqs = top.get_freqs_cis(states[-2], condition, model.feat_rope_gen)
cache = KVCache()
try:
top.initialize_kv_cache(cache, states[-2], freqs)
top.reverse_step_condition(condition, cache, freqs_cis=freqs)
ordered_state = top.permutation(states[-2])
for step in range(ordered_state.shape[1] if sos else ordered_state.shape[1] - 1):
raw_scale, predicted_mu = top.reverse_step(
ordered_state, step, cache, y=condition, freqs_cis=freqs)
predicted_sigma = (F.softplus(raw_scale.float() + INV_SOFTPLUS_1)
if softplus else raw_scale.float().exp())
slot = step if sos else step + 1
spatial_index = maps['token_index'].reshape(latent.shape[0], -1) == slot
expected_mu = mu.reshape(latent.shape[0], -1, mu.shape[-1])[spatial_index]
expected_sigma = sigma.reshape(latent.shape[0], -1, sigma.shape[-1])[spatial_index]
torch.testing.assert_close(predicted_mu.squeeze(1), expected_mu, atol=2e-6, rtol=2e-6)
torch.testing.assert_close(predicted_sigma.squeeze(1), expected_sigma, atol=2e-6, rtol=2e-6)
finally:
cache.delete()
expected, _, _ = diagonal_gaussian_kl(
maps['source_mu'], maps['source_sigma'], maps['target_mu'], maps['target_sigma'])
torch.testing.assert_close(maps['kl_source_target'], expected, atol=0, rtol=0)
self.assertEqual(maps['source_mu'].shape[-1], 4 * patch_size ** 2)
if __name__ == '__main__':
unittest.main()
|