import math, unittest from copy import deepcopy import numpy as np from model import ( initialize, features, fnv, normalized, batch_loss_grad, one_forward, probabilities, nll, Adam, portable, decode_portable, ) class ModelTests(unittest.TestCase): def test_all_parameter_finite_difference(self): p = initialize(8, 3, 2, seed=9, std=0.2) xs = [ (np.array([1, 3, 5]), np.array([0.2, 0.5, 0.7])), (np.array([0, 3]), np.array([0.8, 0.6])), ] ys = [0, 1] l2 = 0.04 loss, ce, g = batch_loss_grad(xs, ys, p, l2) maxerror = 0 for key in p: for index in np.ndindex(p[key].shape): old = p[key][index] eps = 1e-6 p[key][index] = old + eps plus = batch_loss_grad(xs, ys, p, l2)[0] p[key][index] = old - eps minus = batch_loss_grad(xs, ys, p, l2)[0] p[key][index] = old expected = (plus - minus) / (2 * eps) maxerror = max(maxerror, abs(expected - g[key][index])) self.assertAlmostEqual(expected, g[key][index], delta=2e-8) self.assertLess(maxerror, 2e-8) def test_hand_forward_and_uniform(self): p = { "E": np.array([[0.2, -0.1], [0.6, 0.4]]), "W": np.array([[0.2, -0.3], [-0.5, 0.1]]), "bh": np.array([0.1, 0.2]), "bo": np.array([0.3, -0.2]), } h, z = one_forward((np.array([0, 1]), np.array([0.6, 0.8])), p) a = math.tanh(0.6 * 0.2 + 0.8 * 0.6 + 0.1) b = math.tanh(0.6 * -0.1 + 0.8 * 0.4 + 0.2) np.testing.assert_allclose( z, [a * 0.2 - b * 0.5 + 0.3, a * -0.3 + b * 0.1 - 0.2], atol=1e-15 ) self.assertAlmostEqual( float(nll(np.zeros((1, 77)), np.array([0]))[0]), math.log(77) ) np.testing.assert_allclose(probabilities(np.array([10000.0, 9999.0])).sum(), 1) def test_adam_scalar(self): p = {"x": np.array([2.0, -3.0])} g = {"x": np.array([0.4, -0.2])} a = Adam(p, lr=0.003) a.update(p, g) np.testing.assert_allclose( p["x"], np.array([2.0, -3.0]) - 0.003 * np.array([0.4, -0.2]) / (np.abs([0.4, -0.2]) + 1e-8), atol=1e-15, ) self.assertEqual(a.step, 1) def test_features_unicode_and_limits(self): self.assertEqual(fnv("hello"), 0x4F9F2CAB) self.assertEqual(normalized(" Cafe\u0301\u0085 NOTE "), "café note") ids, v = features("😀a") self.assertAlmostEqual(float(v @ v), 1) self.assertEqual(len(ids), len(set(ids))) for s in ["", " ", chr(0xD800), "x" * 2049]: with self.assertRaises(ValueError): features(s) def test_zero_feature_vector(self): p = initialize(8, 3, 2) h, z = one_forward((np.array([], dtype=np.int64), np.array([])), p) np.testing.assert_array_equal(z, np.zeros(2)) def test_quantization_shape_error_bounds(self): p = initialize(8, 3, 2, seed=19) m = portable(p, ["a", "b"], 1.25) q = decode_portable(m) for i, scale in enumerate(m["embedding_scales"]): self.assertLessEqual( float(np.max(np.abs(q["E"][i] - p["E"][i]))), scale * 0.50000001 ) for j, scale in enumerate(m["output_scales"]): self.assertLessEqual( float(np.max(np.abs(q["W"][:, j] - p["W"][:, j]))), scale * 0.50000001 ) m["embedding_scales"][0] = -1 with self.assertRaises(ValueError): decode_portable(m) if __name__ == "__main__": unittest.main(verbosity=2)