|
| 1 | +import keras |
| 2 | + |
| 3 | +from tests.utils import assert_allclose |
| 4 | + |
| 5 | + |
| 6 | +def fn(x): |
| 7 | + return keras.ops.square(x) |
| 8 | + |
| 9 | + |
| 10 | +def test_vjp(): |
| 11 | + from bayesflow.utils import vjp |
| 12 | + |
| 13 | + inputs = keras.random.normal((16, 32)) |
| 14 | + tangents = keras.ops.ones((16, 32)) |
| 15 | + |
| 16 | + vjp_fn = vjp(fn, inputs) |
| 17 | + v = vjp_fn(tangents) |
| 18 | + |
| 19 | + assert keras.ops.shape(v) == (16, 32) |
| 20 | + assert_allclose(v, 2.0 * inputs) |
| 21 | + |
| 22 | + |
| 23 | +def test_jvp(): |
| 24 | + from bayesflow.utils import jvp |
| 25 | + |
| 26 | + inputs = keras.random.normal((16, 32)) |
| 27 | + tangents = keras.ops.ones((16, 32)) |
| 28 | + |
| 29 | + v = jvp(fn, inputs, tangents) |
| 30 | + |
| 31 | + assert keras.ops.shape(v) == (16, 32) |
| 32 | + assert_allclose(v, 2.0 * inputs) |
| 33 | + |
| 34 | + |
| 35 | +def test_jacobian(): |
| 36 | + from bayesflow.utils import jacobian |
| 37 | + |
| 38 | + inputs = keras.random.normal((16, 32)) |
| 39 | + |
| 40 | + j = jacobian(fn, inputs) |
| 41 | + target = 2.0 * keras.ops.tile(keras.ops.expand_dims(inputs, axis=-1), (1, 1, 32)) * keras.ops.eye(32) |
| 42 | + |
| 43 | + assert keras.ops.shape(j) == (16, 32, 32) |
| 44 | + assert_allclose(j, target, atol=0.01, rtol=0.01) |
| 45 | + |
| 46 | + |
| 47 | +def test_jacobian_trace(): |
| 48 | + from bayesflow.utils import jacobian, jacobian_trace |
| 49 | + |
| 50 | + inputs = keras.random.normal((16, 128)) |
| 51 | + |
| 52 | + # deterministic |
| 53 | + j = jacobian(fn, inputs) |
| 54 | + jt = jacobian_trace(fn, inputs) |
| 55 | + |
| 56 | + assert jt.shape == (16,) |
| 57 | + |
| 58 | + jt_target = keras.ops.trace(j, axis1=-2, axis2=-1) |
| 59 | + |
| 60 | + assert_allclose(jt, jt_target) |
| 61 | + |
| 62 | + # too few max_steps, uses the stochastic version |
| 63 | + jt = jacobian_trace(fn, inputs, max_steps=127) |
| 64 | + |
| 65 | + # this check is not reliable enough yet |
| 66 | + # assert_allclose(jt, jt_target, atol=0.01, rtol=0.01) |
0 commit comments