Download annotations/annotation_22/test.py from mcy98/RECODE-H: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_22/test.py
- Command line
-
hf download hf://datasets/mcy98/RECODE-H/annotations/annotation_22/test.py
-
curl -L -o test.py https://huggingface.co/datasets/mcy98/RECODE-H/resolve/main/annotations/annotation_22/test.py
13.8 kB
| 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() | |