File size: 13,778 Bytes
2d13eb2 | 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 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | import unittest
import inspect
from unittest.mock import patch
import jax
import jax.numpy as jnp
import jax.random as jrandom
import jax.tree_util as jtu
import numpy as np
# Import algorithm helpers to patch gen_basis and for LeafTuple typing
import algorithm
# Canonical impls
from canonical import nf_relu as canonical_nf_relu
from canonical import UNFSequential as CanonicalUNFSequential
from canonical import UNFLayer as CanonicalUNFLayer
from canonical import BatchUNFLayer as CanonicalBatchUNFLayer
# Generated impls
from layers import nf_relu as generated_nf_relu
from layers import UNFSequential as GeneratedUNFSequential
from layers import UNFLayer as GeneratedUNFLayer
from layers import BatchUNFLayer as GeneratedBatchUNFLayer
# --------------------------
# Helpers
# --------------------------
def _same_structure_and_shapes(a, b):
"""Assert two pytrees share identical structure and leaf shapes."""
assert jtu.tree_structure(a) == jtu.tree_structure(b), "Tree structures differ"
for x, y in zip(jtu.tree_leaves(a), jtu.tree_leaves(b)):
assert hasattr(x, "shape") and hasattr(y, "shape")
assert x.shape == y.shape, f"Leaf shape mismatch: {x.shape} != {y.shape}"
def _copy_params(src_vars, dst_vars):
"""Copy params from src flax variables to dst (matching tree structure)."""
return jax.tree.map(lambda s, _: s, src_vars, dst_vars)
# Deterministic mock for algorithm.gen_basis that works with both modules.
# Signature expected by canonical code (and generated code) is:
# gen_basis(out_spec, in_spec, out_shape, in_param_slice)
# We vmapped over the last axis of input param (c_in), out_axes=-1.
# This returns a tensor with shape `out_shape[:-1]` per input channel,
# which vmap stacks into `out_shape[:-1] + (c_in,)`, enabling `@` with
# a (c_in, c_out) theta.
def _mock_gen_basis(out_spec, in_spec, out_shape, in_slice):
# Use the mean of the input slice so the result isn't trivial
# Shape: out_shape[:-1]
scale = jnp.asarray(jnp.mean(in_slice))
return jnp.ones(out_shape[:-1]) * scale
# --------------------------
# Tests
# --------------------------
class TestNFReLUEquivalence(unittest.TestCase):
"""Existing nf_relu tests + a few extras."""
def setUp(self):
self.key = jrandom.PRNGKey(42)
self.c_in = 4
self.params = {
'weight1': jrandom.normal(self.key, (3, 4, self.c_in)),
'weight2': jrandom.normal(jrandom.fold_in(self.key, 1), (5, 2, self.c_in))
}
def test_nf_relu_output_structure(self):
canonical_output = canonical_nf_relu(self.params)
generated_output = generated_nf_relu(self.params)
self.assertEqual(
jtu.tree_structure(canonical_output),
jtu.tree_structure(generated_output),
)
self.assertEqual(
jtu.tree_structure(self.params),
jtu.tree_structure(canonical_output),
)
def test_nf_relu_shape_preservation(self):
canonical_output = canonical_nf_relu(self.params)
generated_output = generated_nf_relu(self.params)
for c_leaf, g_leaf, in_leaf in zip(
jtu.tree_leaves(canonical_output),
jtu.tree_leaves(generated_output),
jtu.tree_leaves(self.params),
):
self.assertEqual(c_leaf.shape, g_leaf.shape)
self.assertEqual(c_leaf.shape, in_leaf.shape)
def test_nf_relu_numerical_equivalence(self):
canonical_output = canonical_nf_relu(self.params)
generated_output = generated_nf_relu(self.params)
for c_leaf, g_leaf in zip(jtu.tree_leaves(canonical_output),
jtu.tree_leaves(generated_output)):
np.testing.assert_allclose(c_leaf, g_leaf, rtol=1e-5, atol=1e-8)
def test_nf_relu_negative_values(self):
negative_params = jtu.tree_map(lambda x: x - 0.5, self.params)
canonical_output = canonical_nf_relu(negative_params)
generated_output = generated_nf_relu(negative_params)
for c_leaf, g_leaf in zip(jtu.tree_leaves(canonical_output),
jtu.tree_leaves(generated_output)):
np.testing.assert_allclose(c_leaf, g_leaf, rtol=1e-5, atol=1e-8)
for leaf in jtu.tree_leaves(canonical_output):
self.assertTrue((leaf >= 0).all())
for leaf in jtu.tree_leaves(generated_output):
self.assertTrue((leaf >= 0).all())
def test_nf_relu_mixed_values(self):
mixed_params = jtu.tree_map(
lambda x: x * jrandom.normal(jrandom.fold_in(self.key, 10), x.shape),
self.params
)
canonical_output = canonical_nf_relu(mixed_params)
generated_output = generated_nf_relu(mixed_params)
for c_leaf, g_leaf in zip(jtu.tree_leaves(canonical_output),
jtu.tree_leaves(generated_output)):
np.testing.assert_allclose(c_leaf, g_leaf, rtol=1e-5, atol=1e-8)
for leaf in jtu.tree_leaves(canonical_output):
self.assertTrue((leaf >= 0).all())
found_zeros = False
for in_leaf, out_leaf in zip(jtu.tree_leaves(mixed_params),
jtu.tree_leaves(canonical_output)):
if ((in_leaf < 0) & (out_leaf == 0)).any():
found_zeros = True
break
self.assertTrue(found_zeros, "ReLU did not zero any negatives")
def test_nf_relu_dtype_preservation(self):
fp16_params = jtu.tree_map(lambda x: jnp.asarray(x, jnp.float16), self.params)
c_out = canonical_nf_relu(fp16_params)
g_out = generated_nf_relu(fp16_params)
for c_leaf, g_leaf in zip(jtu.tree_leaves(c_out), jtu.tree_leaves(g_out)):
self.assertEqual(c_leaf.dtype, jnp.float16)
self.assertEqual(g_leaf.dtype, jnp.float16)
class TestStructureCornerCases(unittest.TestCase):
def setUp(self):
self.key = jrandom.PRNGKey(0)
self.c_in = 3
def test_empty_structure(self):
empty = {}
self.assertEqual(canonical_nf_relu(empty), generated_nf_relu(empty))
self.assertEqual(empty, canonical_nf_relu(empty))
def test_zero_sized_arrays(self):
zero_params = {
'w1': jnp.zeros((0, 2, self.c_in)),
'w2': jnp.zeros((2, 0, self.c_in)),
}
c = canonical_nf_relu(zero_params)
g = generated_nf_relu(zero_params)
_same_structure_and_shapes(c, g)
_same_structure_and_shapes(zero_params, c)
def test_nested_mixed_types(self):
mixed = {
'w': jrandom.normal(self.key, (2, 2, self.c_in)),
'scalar': 3.14,
'nested': {'v': 2.71}
}
wrapped = jtu.tree_map(lambda x: jnp.array([x]) if isinstance(x, (int, float)) else x, mixed)
try:
c = canonical_nf_relu(wrapped)
g = generated_nf_relu(wrapped)
for cl, gl in zip(jtu.tree_leaves(c), jtu.tree_leaves(g)):
np.testing.assert_allclose(cl, gl, rtol=1e-5, atol=1e-8)
except Exception:
self.skipTest("Mixed scalar handling unsupported; parity preserved")
def _make_params_and_spec(key, c_in):
params = {
'a': jrandom.normal(jrandom.fold_in(key, 1), (2, 2, c_in)),
'b': jrandom.normal(jrandom.fold_in(key, 2), (3, 1, c_in)),
}
perm_spec = {
'a': (0, 1, None),
'b': (1, 0, None),
}
return params, perm_spec
class TestUNFLayerAndSequential(unittest.TestCase):
# leave any other tests in this class as they are
def test_unflayer_shapes_and_forward_equivalence(self):
key = jrandom.PRNGKey(123)
c_in, c_out = 3, 4
params, perm_spec = _make_params_and_spec(key, c_in)
with patch('canonical.gen_basis', side_effect=_mock_gen_basis), \
patch('layers.gen_basis', side_effect=_mock_gen_basis):
c_mod = CanonicalUNFLayer(c_out=c_out, c_in=c_in)
g_mod = GeneratedUNFLayer(c_out=c_out, c_in=c_in)
c_vars = c_mod.init(key, params, perm_spec)
g_vars = g_mod.init(key, params, perm_spec)
_same_structure_and_shapes(c_vars['params'], g_vars['params'])
g_vars_synced = {'params': _copy_params(c_vars['params'], g_vars['params'])}
c_out_tree = c_mod.apply(c_vars, params, perm_spec)
g_out_tree = g_mod.apply(g_vars_synced, params, perm_spec)
_same_structure_and_shapes(c_out_tree, g_out_tree)
for cl, gl in zip(jtu.tree_leaves(c_out_tree), jtu.tree_leaves(g_out_tree)):
np.testing.assert_allclose(cl, gl, rtol=1e-5, atol=1e-8)
def test_unflayer_param_shapes_and_bias_broadcast(self):
key = jrandom.PRNGKey(123)
c_in, c_out = 3, 4
params, perm_spec = _make_params_and_spec(key, c_in)
with patch('canonical.gen_basis', side_effect=_mock_gen_basis), \
patch('layers.gen_basis', side_effect=_mock_gen_basis):
mod = CanonicalUNFLayer(c_out=c_out, c_in=c_in)
vars_ = mod.init(key, params, perm_spec)
flat_params = jtu.tree_leaves(vars_['params'])
# At least one param leaf should end with c_out (theta[..., c_out])
self.assertTrue(any(p.shape and p.shape[-1] == c_out for p in flat_params))
# At least one 1-D bias of length c_out
self.assertTrue(any((p.ndim == 1 and p.shape[0] == c_out) for p in flat_params))
def test_unfsequential_end_to_end(self):
key = jrandom.PRNGKey(123)
c_in, c_out = 3, 4
params, perm_spec = _make_params_and_spec(key, c_in)
with patch('canonical.gen_basis', side_effect=_mock_gen_basis), \
patch('layers.gen_basis', side_effect=_mock_gen_basis):
c_seq = CanonicalUNFSequential(layers=[
CanonicalUNFLayer(c_out=c_out, c_in=c_in),
canonical_nf_relu,
])
g_seq = GeneratedUNFSequential(layers=[
GeneratedUNFLayer(c_out=c_out, c_in=c_in),
generated_nf_relu,
])
c_vars = c_seq.init(key, params, perm_spec)
g_vars = g_seq.init(key, params, perm_spec)
g_vars_synced = {'params': _copy_params(c_vars['params'], g_vars['params'])}
c_out_tree = c_seq.apply(c_vars, params, perm_spec)
g_out_tree = g_seq.apply(g_vars_synced, params, perm_spec)
_same_structure_and_shapes(c_out_tree, g_out_tree)
for cl, gl in zip(jtu.tree_leaves(c_out_tree), jtu.tree_leaves(g_out_tree)):
np.testing.assert_allclose(cl, gl, rtol=1e-5, atol=1e-8)
for leaf in jtu.tree_leaves(c_out_tree):
self.assertTrue((leaf >= 0).all())
def test_batchunflayer_matches_unbatched(self):
key = jrandom.PRNGKey(123)
c_in, c_out = 3, 4
params, perm_spec = _make_params_and_spec(key, c_in)
with patch('canonical.gen_basis', side_effect=_mock_gen_basis), \
patch('layers.gen_basis', side_effect=_mock_gen_basis):
batch_size = 5
batched_params = jax.tree.map(
lambda x: jnp.stack([x + 0.01 * i for i in range(batch_size)], axis=0),
params
)
c_unf = CanonicalUNFLayer(c_out=c_out, c_in=c_in)
c_batch = CanonicalBatchUNFLayer(c_out=c_out, c_in=c_in)
# Initialize unbatched once; BatchUNFLayer shares params across batch
c_vars = c_unf.init(key, params, perm_spec)
def single_forward(p):
return c_unf.apply(c_vars, p, perm_spec)
manual_batched = jax.vmap(single_forward, in_axes=0, out_axes=0)(batched_params)
# Pass shared params collection explicitly
c_batch_out = c_batch.apply({'params': c_vars['params']}, batched_params, perm_spec)
_same_structure_and_shapes(manual_batched, c_batch_out)
for ml, bl in zip(jtu.tree_leaves(manual_batched), jtu.tree_leaves(c_batch_out)):
np.testing.assert_allclose(ml, bl, rtol=1e-5, atol=1e-8)
# Keep your original TestUNFSequentialBehavior mock test to validate routing logic
class TestUNFSequentialBehavior(unittest.TestCase):
def setUp(self):
self.key = jrandom.PRNGKey(42)
self.c_in = 3
self.params = {'weight': jrandom.normal(self.key, (2, 2, self.c_in))}
self.perm_spec = {'weight': (0, 1, None)}
def test_sequential_layer_routing(self):
class MockUNFLayer:
def __init__(self):
self.called_with_spec = False
def __call__(self, params, spec):
self.called_with_spec = True
return jtu.tree_map(lambda x: x + 1.0, params)
class MockPointwise:
def __init__(self):
self.called = False
def __call__(self, params):
self.called = True
return jtu.tree_map(lambda x: x * 2.0, params)
unf = MockUNFLayer()
pw = MockPointwise()
def run_seq(layers, params, spec):
out = params
for layer in layers:
if isinstance(layer, MockUNFLayer):
out = layer(out, spec)
else:
out = layer(out)
return out
out = run_seq([unf, pw], self.params, self.perm_spec)
self.assertTrue(unf.called_with_spec)
self.assertTrue(pw.called)
expected = jtu.tree_map(lambda x: (x + 1.0) * 2.0, self.params)
for a, b in zip(jtu.tree_leaves(out), jtu.tree_leaves(expected)):
np.testing.assert_array_equal(a, b)
if __name__ == "__main__":
unittest.main()
|