def main(unused_argv):
  key1, key2, key3 = random.split(random.PRNGKey(1), 3)
  x1 = random.normal(key1, (2, 8, 8, 3))
  x2 = random.normal(key2, (3, 8, 8, 3))

  # A vanilla CNN.
  init_fn, f, _ = stax.serial(
      stax.Conv(8, (3, 3)),
      stax.Relu(),
      stax.Conv(8, (3, 3)),
      stax.Relu(),
      stax.Conv(8, (3, 3)),
      stax.Flatten(),
      stax.Dense(10)
  )

  _, params = init_fn(key3, x1.shape)
  kwargs = dict(
      f=f,
      trace_axes=(),
      vmap_axes=0,
  )

  # Default, baseline Jacobian contraction.
  jacobian_contraction = nt.empirical_ntk_fn(
      **kwargs,
      implementation=nt.NtkImplementation.JACOBIAN_CONTRACTION)

  # (6, 3, 10, 10) full `np.ndarray` test-train NTK
  ntk_jc = jacobian_contraction(x2, x1, params)

  # NTK-vector products-based implementation.
  ntk_vector_products = nt.empirical_ntk_fn(
      **kwargs,
      implementation=nt.NtkImplementation.NTK_VECTOR_PRODUCTS)

  ntk_vp = ntk_vector_products(x2, x1, params)

  # Structured derivatives-based implementation.
  structured_derivatives = nt.empirical_ntk_fn(
      **kwargs,
      implementation=nt.NtkImplementation.STRUCTURED_DERIVATIVES)

  ntk_sd = structured_derivatives(x2, x1, params)

  # Auto-FLOPs-selecting implementation. Doesn't work correctly on CPU/GPU.
  auto = nt.empirical_ntk_fn(
      **kwargs,
      implementation=nt.NtkImplementation.AUTO)

  ntk_auto = auto(x2, x1, params)

  # Check that implementations match
  for ntk1 in [ntk_jc, ntk_vp, ntk_sd, ntk_auto]:
    for ntk2 in [ntk_jc, ntk_vp, ntk_sd, ntk_auto]:
      diff = np.max(np.abs(ntk1 - ntk2))
      print(f'NTK implementation diff {diff}.')
      assert diff < (1e-4 if jax.default_backend() != 'tpu' else 0.1), diff

  print('All NTK implementations match.')
def _kernel_fns(key,
                input_shape,
                network,
                out_logits,
                diagonal_axes,
                trace_axes,
                vmap_axes=None):
    init_fn, f, _ = _build_network(input_shape, network, out_logits)
    _, params = init_fn(key, (-1, ) + input_shape)
    implicit_kernel_fn = jit(
        nt.empirical_ntk_fn(f,
                            trace_axes,
                            diagonal_axes,
                            vmap_axes,
                            implementation=2))
    direct_kernel_fn = jit(
        nt.empirical_ntk_fn(f,
                            trace_axes,
                            diagonal_axes,
                            vmap_axes,
                            implementation=1))

    nngp_kernel_fn = jit(nt.empirical_nngp_fn(f, trace_axes, diagonal_axes))

    return (partial(implicit_kernel_fn,
                    params=params), partial(direct_kernel_fn, params=params),
            partial(nngp_kernel_fn, params=params))
    def test_parallel_nested(self, same_inputs):
        rng = random.PRNGKey(0)
        input_key1, input_key2, net_key = random.split(rng, 3)

        x1_1, x1_2, x1_3 = np.split(random.normal(input_key1, (3, 33)),
                                    (10, 21),
                                    axis=1)
        x2_1, x2_2, x2_3 = np.split(random.normal(input_key2, (4, 33)),
                                    (10, 21),
                                    axis=1)

        x1 = ([x1_1, x1_2], x1_3)
        x2 = ([x2_1, x2_2], x2_3) if not same_inputs else None

        def layer(N_out):
            return stax.parallel(
                stax.parallel(stax.Dense(N_out), stax.Dense(N_out + 1)),
                stax.Dense(N_out + 2))

        init_fn, apply_fn, _ = stax.serial(layer(1024), layer(1))

        _, params = init_fn(net_key, tree_map(np.shape, x1))
        implicit_kernel_fn = jit(
            nt.empirical_ntk_fn(apply_fn, implementation=2))
        direct_kernel_fn = jit(nt.empirical_ntk_fn(apply_fn, implementation=1))

        implicit_batched_kernel_fn = jit(
            nt.empirical_ntk_fn(apply_fn,
                                vmap_axes=([0, 0], 0),
                                implementation=2))
        direct_batched_kernel_fn = jit(
            nt.empirical_ntk_fn(apply_fn,
                                vmap_axes=([0, 0], 0),
                                implementation=1))

        k_direct = direct_kernel_fn(x1, x2, params)

        self.assertAllClose(k_direct, implicit_kernel_fn(x1, x2, params))
        self.assertAllClose(k_direct, direct_batched_kernel_fn(x1, x2, params))
        self.assertAllClose(k_direct,
                            implicit_batched_kernel_fn(x1, x2, params))

        nngp_kernel_fn = jit(nt.empirical_nngp_fn(apply_fn))
        nngp = nngp_kernel_fn(x1, x2, params)

        self.assertEqual(len(nngp), 2)
        nngp_shape = (3, 3 if same_inputs else 4)
        self.assertEqual(nngp[0][0].shape, nngp_shape)
        self.assertEqual(nngp[0][1].shape, nngp_shape)
        self.assertEqual(nngp[1].shape, nngp_shape)
Exemple #4
0
def _empirical_kernel(key, input_shape, network, out_logits, use_dropout):
    init_fn, f, _ = _build_network(input_shape, network, out_logits,
                                   use_dropout)
    key, split = random.split(key)
    _, params = init_fn(key, (-1, ) + input_shape)
    kernel_fn = jit(nt.empirical_ntk_fn(f))
    return partial(kernel_fn, params=params, keys=split)
Exemple #5
0
    def test_empirical_ntk_diagonal_outputs(self, same_inputs, device_count,
                                            trace_axes, diagonal_axes):
        test_utils.stub_out_pmap(batching, 2)
        rng = random.PRNGKey(0)

        input_key1, input_key2, net_key = random.split(rng, 3)

        init_fn, apply_fn, _ = stax.serial(stax.Dense(5), stax.Relu(),
                                           stax.Dense(3))

        test_x1 = random.normal(input_key1, (12, 4, 4))
        test_x2 = None
        if same_inputs:
            test_x2 = random.normal(input_key2, (9, 4, 4))

        kernel_fn = nt.empirical_ntk_fn(apply_fn,
                                        trace_axes=trace_axes,
                                        diagonal_axes=diagonal_axes,
                                        vmap_axes=0,
                                        implementation=2)

        _, params = init_fn(net_key, test_x1.shape)

        true_kernel = kernel_fn(test_x1, test_x2, params)
        batched_fn = batching.batch(kernel_fn,
                                    device_count=device_count,
                                    batch_size=3)
        batch_kernel = batched_fn(test_x1, test_x2, params)
        self.assertAllClose(true_kernel, batch_kernel)
def main(unused_argv):

    train_size = FLAGS.train_size
    x_train, y_train, x_test, y_test = pickle.load(
        open("data_" + str(train_size) + ".p", "rb"))
    print("Got data")
    sys.stdout.flush()

    # Build the network
    init_fn, apply_fn, _ = stax.serial(
        stax.Dense(2048, 1., 0.05),
        # stax.Erf(),
        stax.Relu(),
        stax.Dense(1, 1., 0.05))

    # initialize the network first time, to compute NTK
    randnnn = numpy.random.random_integers(np.iinfo(np.int32).min,
                                           high=np.iinfo(np.int32).max,
                                           size=2)[0]
    key = random.PRNGKey(randnnn)
    _, params = init_fn(key, (-1, 784))

    # Create an MSE predictor to solve the NTK equation in function space.
    # we assume that the NTK is approximately the same for any sample of parameters (true in the limit of infinite width)

    print("Making NTK")
    sys.stdout.flush()
    ntk = nt.batch(nt.empirical_ntk_fn(apply_fn), batch_size=4, device_count=1)
    g_dd = ntk(x_train, None, params)
    pickle.dump(g_dd, open("ntk_train_" + str(FLAGS.train_size) + ".p", "wb"))
    g_td = ntk(x_test, x_train, params)
    pickle.dump(g_td,
                open("ntk_train_test_" + str(FLAGS.train_size) + ".p", "wb"))
    predictor = nt.predict.gradient_descent_mse(g_dd, y_train, g_td)
def main(unused_argv):
  # Build data pipelines.
  print('Loading data.')
  x_train, y_train, x_test, y_test = \
      datasets.get_dataset('mnist', FLAGS.train_size, FLAGS.test_size)

  # Build the network
  init_fn, apply_fn, _ = stax.serial(
      stax.Dense(512, 1., 0.05),
      stax.Erf(),
      stax.Dense(10, 1., 0.05))

  key = random.PRNGKey(0)
  _, params = init_fn(key, (-1, 784))

  # Create and initialize an optimizer.
  opt_init, opt_apply, get_params = optimizers.sgd(FLAGS.learning_rate)
  state = opt_init(params)

  # Create an mse loss function and a gradient function.
  loss = lambda fx, y_hat: 0.5 * np.mean((fx - y_hat) ** 2)
  grad_loss = jit(grad(lambda params, x, y: loss(apply_fn(params, x), y)))

  # Create an MSE predictor to solve the NTK equation in function space.
  ntk = nt.batch(nt.empirical_ntk_fn(apply_fn, vmap_axes=0),
                 batch_size=4, device_count=0)
  g_dd = ntk(x_train, None, params)
  g_td = ntk(x_test, x_train, params)
  predictor = nt.predict.gradient_descent_mse(g_dd, y_train)

  # Get initial values of the network in function space.
  fx_train = apply_fn(params, x_train)
  fx_test = apply_fn(params, x_test)

  # Train the network.
  train_steps = int(FLAGS.train_time // FLAGS.learning_rate)
  print('Training for {} steps'.format(train_steps))

  for i in range(train_steps):
    params = get_params(state)
    state = opt_apply(i, grad_loss(params, x_train, y_train), state)

  # Get predictions from analytic computation.
  print('Computing analytic prediction.')
  fx_train, fx_test = predictor(FLAGS.train_time, fx_train, fx_test, g_td)

  # Print out summary data comparing the linear / nonlinear model.
  util.print_summary('train', y_train, apply_fn(params, x_train), fx_train,
                     loss)
  util.print_summary('test', y_test, apply_fn(params, x_test), fx_test,
                     loss)
Exemple #8
0
    def test_parallel_in_out_empirical(self, same_inputs):
        test_utils.stub_out_pmap(batching, 2)
        rng = random.PRNGKey(0)
        input_key1, input_key2, net_key = random.split(rng, 3)

        x1_1, x1_2, x1_3 = random.normal(input_key1, (3, 4, 1))
        x1 = (x1_1, (x1_2, x1_3))

        if same_inputs:
            x2 = None
        else:
            x2_1, x2_2, x2_3 = random.normal(input_key2, (3, 8, 1))
            x2 = (x2_1, (x2_2, x2_3))

        def net(N_out):
            return stax.parallel(
                stax.Dense(N_out),
                stax.parallel(stax.Dense(N_out + 1), stax.Dense(N_out + 2)))

        # Check NNGP.
        init_fn, apply_fn, _ = net(WIDTH)
        _, params = init_fn(net_key, ((-1, 1), ((-1, 1), (-1, 1))))

        kernel_fn = jit(nt.empirical_nngp_fn(apply_fn))
        batch_kernel_fn = jit(batching.batch(kernel_fn, 2))

        test_utils.assert_close_matrices(self, kernel_fn(x1, x2, params),
                                         batch_kernel_fn(x1, x2, params), RTOL)

        # Check NTK.
        init_fn, apply_fn, _ = stax.serial(net(WIDTH), net(1))
        _, params = init_fn(net_key, ((-1, 1), ((-1, 1), (-1, 1))))

        kernel_fn = jit(nt.empirical_ntk_fn(apply_fn))
        batch_kernel_fn = jit(batching.batch(kernel_fn, 2))

        test_utils.assert_close_matrices(self, kernel_fn(x1, x2, params),
                                         batch_kernel_fn(x1, x2, params), RTOL)
  return jax.device_put(X), jax.device_put(y)

X, Y = make_dataset(points_per_class=N, classes=C)

### Defining the Neural Network ###

init_fn, apply_fn, kernel_fn = stax.serial(
                                           stax.Dense(NN_width, parameterization='standard'), 
                                           stax.Relu(), 
                                           stax.Dense(3, parameterization='standard')
                                           )

key = random.PRNGKey(0)

# NTK computation
ntk_fn = jit(nt.empirical_ntk_fn(apply_fn))
@jit
def ntk_evals(params, X):
  ntk = ntk_fn(X, X, params)
  evals, _ = jnp.linalg.eigh(ntk)
  return evals

# Weights for the loss function
def c_fn(t,i,w_max):
  slope = 2 * (w_max - 1) / T 
  w_main_class = jnp.where(t < T / 2., 1+ t * slope, 2 * w_max - t * slope - 1)
  res = jnp.ones(C) +  (w_main_class-1) * jnp.eye(C)[i]
  res = res / jnp.sum(res) * C
  return res

# Dynamical loss function
def main(unused_argv):
    # Build data pipelines.
    print('Loading data.')
    x_train, y_train, x_test, y_test = \
        datasets.get_dataset('mnist', FLAGS.train_size, FLAGS.test_size)

    # Build the network
    init_fn, apply_fn, _ = stax.serial(
      stax.Dense(2048, 1., 0.05),
      # stax.Erf(),
      stax.Relu(),
      stax.Dense(2048, 1., 0.05),
      # stax.Erf(),
      stax.Relu(),
      stax.Dense(10, 1., 0.05))

    key = random.PRNGKey(0)
    _, params = init_fn(key, (-1, 784))

    # params

    # Create and initialize an optimizer.
    opt_init, opt_apply, get_params = optimizers.sgd(FLAGS.learning_rate)
    state = opt_init(params)
    # state


    # Create an mse loss function and a gradient function.
    loss = lambda fx, y_hat: 0.5 * np.mean((fx - y_hat) ** 2)
    grad_loss = jit(grad(lambda params, x, y: loss(apply_fn(params, x), y)))

    # Create an MSE predictor to solve the NTK equation in function space.
    ntk = nt.batch(nt.empirical_ntk_fn(apply_fn), batch_size=4, device_count=0)
    g_dd = ntk(x_train, None, params)
    g_td = ntk(x_test, x_train, params)
    predictor = nt.predict.gradient_descent_mse(g_dd, y_train, g_td)
    # g_dd.shape

    m = FLAGS.train_size
    print(m)
    n = m*10
    m_test = FLAGS.test_size
    n_test = m_test*10
    # g_td.shape
    # predictor
    # g_dd
    # type(g_dd)
    # g_dd.shape
    theta = g_dd.transpose((0,2,1,3)).reshape(n,n)
    theta_test = ntk(x_test, None, params).transpose((0,2,1,3)).reshape(n_test,n_test)
    theta_tilde = g_td.transpose((0,2,1,3)).reshape(n_test,n)
    #NNGP
    K = nt.empirical_nngp_fn(apply_fn)(x_train,None,params)
    K = np.kron(theta,np.eye(10))
    K_test = nt.empirical_nngp_fn(apply_fn)(x_test,None,params)
    K_test = np.kron(theta_test,np.eye(10))
    K_tilde = nt.empirical_nngp_fn(apply_fn)(x_test,x_train,params)
    K_tilde = np.kron(theta_tilde,np.eye(10))

    decay_matrix = np.eye(n)-scipy.linalg.expm(-t*theta)
    Sigma = K + np.matmul(decay_matrix, np.matmul(K, np.matmul(np.linalg.inv(theta), np.matmul(decay_matrix, theta))) - 2*K)

    # K.shape
    theta
    # alpha = np.matmul(np.linalg.inv(K),np.matmul(theta,np.linalg.inv(theta)))
    # y_train
    # alpha = np.matmul(np.linalg.inv(K), y_train.reshape(1280))
    # Sigma = K + np.matmul()
    # K = theta
    sigma_noise = 1.0
    Y = y_train.reshape(n)
    alpha = np.matmul(np.linalg.inv(np.eye(n)*(sigma_noise**2)+K),Y)
    # cov = np.linalg.inv(np.linalg.inv(K)+np.eye(n)/(sigma_noise**2))
    # covi = np.linalg.inv(cov)
    # covi = np.linalg.inv(K)+np.eye(n)/(sigma_noise**2)
    # print(covi)
    # np.linalg.det(K)
    eigs = np.linalg.eigh(K)[0]
    logdetcoviK = np.sum(np.log((eigs+sigma_noise**2) /sigma_noise**2))
    # coviK = np.matmul(covi,K)
    # coviK = np.eye(n) + K/(sigma_noise**2)
    # coviK
    # covi
    # np.linalg.det()
    # KL = 0.5*np.log(np.linalg.det(coviK)) + 0.5*np.trace(np.linalg.inv(coviK)) + 0.5*np.matmul(alpha.T,np.matmul(K,alpha)) - n/2
    KL = 0.5*logdetcoviK + 0.5*np.trace(np.linalg.inv(coviK)) + 0.5*np.matmul(alpha.T,np.matmul(K,alpha)) - n/2
    print(KL)

    delta = 2**-10
    bound = (KL+2*np.log(m)+1-np.log(delta))/m
    bound = 1-np.exp(-bound)
    bound
    print("bound", bound)

    import numpy
    bigK = numpy.zeros((n+n_test,n+n_test))
    bigK
    bigK[0:n,0:n] = K
    bigK[0:n,n:] = theta_tilde.T
    bigK[n:,0:n] = theta_tilde
    bigK[n:,n:] = theta_test
    init_ntk_f = numpy.random.multivariate_normal(np.zeros(n+n_test),bigK)
    fx_train = init_ntk_f[:n].reshape(m,10)
    fx_test = init_ntk_f[n:].reshape(m_test,10)

    # Get initial values of the network in function space.
    # fx_train = apply_fn(params, x_train)
    # fx_test = apply_fn(params, x_test)

    # Train the network.
    train_steps = int(FLAGS.train_time // FLAGS.learning_rate)
    print('Training for {} steps'.format(train_steps))

    for i in range(train_steps):
        params = get_params(state)
        state = opt_apply(i, grad_loss(params, x_train, y_train), state)

    # Get predictions from analytic computation.
    print('Computing analytic prediction.')
    # fx_train, fx_test = predictor(FLAGS.train_time, fx_train, fx_test)
    fx_train, fx_test = predictor(FLAGS.train_time, fx_train, fx_test)

    # Print out summary data comparing the linear / nonlinear model.
    util.print_summary('train', y_train, apply_fn(params, x_train), fx_train, loss)
    util.print_summary('test', y_test, apply_fn(params, x_test), fx_test, loss)
Exemple #11
0
    def _compare_ntks(self, f, f_jax, params, trace_axes, diagonal_axes,
                      vmap_axes):
        if any(i == j for i in trace_axes for j in diagonal_axes):
            raise absltest.SkipTest('Overlapping trace and diagonal axes.')

        kwargs = dict(
            trace_axes=trace_axes,
            diagonal_axes=diagonal_axes,
        )

        jax_ntk_fns = [
            jax.jit(
                nt.empirical_ntk_fn(**kwargs,
                                    f=f_jax,
                                    implementation=i,
                                    vmap_axes=v)) for i in nt.NtkImplementation
            for v in vmap_axes if v not in trace_axes + diagonal_axes
        ]

        ntk_fns = [
            experimental.empirical_ntk_fn_tf(**kwargs,
                                             f=f,
                                             implementation=i,
                                             vmap_axes=v)
            for i in nt.NtkImplementation for v in vmap_axes
            if v not in trace_axes + diagonal_axes
        ]

        x_shape = (f.input_shape[1:] if isinstance(f, tf.Module) else
                   f.input_signature[1].shape[1:])

        x1 = tf.random.normal((2, ) + x_shape, seed=2) / onp.prod(x_shape)**0.5
        x2 = tf.random.normal((3, ) + x_shape, seed=3) / onp.prod(x_shape)**0.5

        x1_jax = np.array(x1)
        x2_jax = np.array(x2)
        params_jax = jax.tree_map(lambda x: np.array(x), params)

        jax_ntks = [
            ntk_fn_i(x1_jax, x2_jax, params_jax) for ntk_fn_i in jax_ntk_fns
        ]

        ntks = list(
            enumerate([ntk_fn_i(x1, x2, params) for ntk_fn_i in ntk_fns]))

        if len(tf.config.list_physical_devices()) > 1:  # TPU
            atol = 0.
            rtol = 5e-3
            atol_jax = 0.4
            rtol_jax = 0.15  # TODO(romann): revisit poor TPU agreement.
        else:
            atol = 1e-5
            rtol = 5e-5
            atol_jax = 0.
            rtol_jax = 5e-5

        for i1, ntk1 in ntks:
            for i2, ntk2 in ntks[i1 + 1:]:
                # Compare different implementation
                onp.testing.assert_allclose(ntk1, ntk2, rtol=rtol, atol=atol)
                # Compare against the JAX version (without calling `jax2tf`).
                onp.testing.assert_allclose(ntk1,
                                            jax_ntks[i1],
                                            rtol=rtol_jax,
                                            atol=atol_jax)
    def test_vmap_axes(self, same_inputs):
        n1, n2 = 3, 4
        c1, c2, c3 = 9, 5, 7
        h2, h3, w3 = 6, 8, 2

        def get_x(n, k):
            k1, k2, k3 = random.split(k, 3)
            x1 = random.normal(k1, (n, c1))
            x2 = random.normal(k2, (h2, n, c2))
            x3 = random.normal(k3, (c3, w3, n, h3))
            x = [(x1, x2), x3]
            return x

        x1 = get_x(n1, random.PRNGKey(1))
        x2 = get_x(n2, random.PRNGKey(2)) if not same_inputs else None

        p1 = random.normal(random.PRNGKey(5), (n1, h2, h2))
        p2 = None if same_inputs else random.normal(random.PRNGKey(6),
                                                    (n2, h2, h2))

        init_fn, apply_fn, _ = stax.serial(
            stax.parallel(
                stax.parallel(
                    stax.serial(stax.Dense(4, 2., 0.1), stax.Relu(),
                                stax.Dense(3, 1., 0.15)),  # 1
                    stax.serial(
                        stax.Conv(7, (2, ),
                                  padding='SAME',
                                  dimension_numbers=('HNC', 'OIH', 'NHC')),
                        stax.Erf(), stax.Aggregate(1, 0, -1),
                        stax.GlobalAvgPool(), stax.Dense(3, 0.5, 0.2)),  # 2
                ),
                stax.serial(
                    stax.Conv(5, (2, 3),
                              padding='SAME',
                              dimension_numbers=('CWNH', 'IOHW', 'HWCN')),
                    stax.Sin(),
                )  # 3
            ),
            stax.parallel(
                stax.FanInSum(),
                stax.Conv(2, (2, 1),
                          dimension_numbers=('HWCN', 'OIHW', 'HNWC'))))

        _, params = init_fn(random.PRNGKey(3), tree_map(np.shape, x1))
        implicit = jit(nt.empirical_ntk_fn(apply_fn, implementation=2))
        direct = jit(nt.empirical_ntk_fn(apply_fn, implementation=1))

        implicit_batched = jit(
            nt.empirical_ntk_fn(apply_fn,
                                vmap_axes=([(0, 1), 2], [-2,
                                                         -3], dict(pattern=0)),
                                implementation=2))
        direct_batched = jit(
            nt.empirical_ntk_fn(apply_fn,
                                vmap_axes=([(-2, -2),
                                            -2], [0, 1], dict(pattern=-3)),
                                implementation=1))

        k = direct(x1, x2, params, pattern=(p1, p2))

        self.assertAllClose(k, implicit(x1, x2, params, pattern=(p1, p2)))
        self.assertAllClose(k, direct_batched(x1, x2, params,
                                              pattern=(p1, p2)))
        self.assertAllClose(k,
                            implicit_batched(x1, x2, params, pattern=(p1, p2)))
Exemple #13
0
# params

# Create and initialize an optimizer.
opt_init, opt_apply, get_params = optimizers.sgd(FLAGS.learning_rate)
state = opt_init(params)
# state
#%%


# Create an mse loss function and a gradient function.
loss = lambda fx, y_hat: 0.5 * np.mean((fx - y_hat) ** 2)
grad_loss = jit(grad(lambda params, x, y: loss(apply_fn(params, x), y)))

# Create an MSE predictor to solve the NTK equation in function space.
ntk = nt.batch(nt.empirical_ntk_fn(apply_fn), batch_size=4, device_count=0)
g_dd = ntk(x_train, None, params)
g_td = ntk(x_test, x_train, params)
predictor = nt.predict.gradient_descent_mse(g_dd, y_train, g_td)
#%%

m = FLAGS.train_size
n = m*10
m_test = FLAGS.test_size
n_test = m_test*10
# g_td.shape
# predictor
# g_dd
# type(g_dd)
# g_dd.shape
theta = g_dd.transpose((0,2,1,3)).reshape(n,n)
Exemple #14
0
def main(unused_argv):
    # Build data pipelines.
    print('Loading data.')
    x_train, y_train, x_test, y_test = \
      datasets.mnist(FLAGS.train_size, FLAGS.test_size)

    # x_train
    import numpy
    # numpy.argmax(y_train,1)%2
    # y_train_tmp = numpy.zeros((y_train.shape[0],2))
    # y_train_tmp[np.arange(y_train.shape[0]),numpy.argmax(y_train,1)%2] = 1
    # y_train = y_train_tmp
    # y_test_tmp = numpy.zeros((y_test.shape[0],2))
    # y_test_tmp[np.arange(y_train.shape[0]),numpy.argmax(y_test,1)%2] = 1
    # y_test = y_test_tmp

    y_train_tmp = numpy.argmax(y_train, 1) % 2
    y_train = np.expand_dims(y_train_tmp, 1)
    y_test_tmp = numpy.argmax(y_test, 1) % 2
    y_test = np.expand_dims(y_test_tmp, 1)
    # print(y_train)
    # Build the network
    # init_fn, apply_fn, _ = stax.serial(
    #   stax.Dense(2048, 1., 0.05),
    #   # stax.Erf(),
    #   stax.Relu(),
    #   stax.Dense(2048, 1., 0.05),
    #   # stax.Erf(),
    #   stax.Relu(),
    #   stax.Dense(10, 1., 0.05))
    init_fn, apply_fn, _ = stax.serial(stax.Dense(2048, 1., 0.05), stax.Erf(),
                                       stax.Dense(1, 1., 0.05))

    # key = random.PRNGKey(0)
    randnnn = numpy.random.random_integers(np.iinfo(np.int32).min,
                                           high=np.iinfo(np.int32).max,
                                           size=2)[0]
    key = random.PRNGKey(randnnn)
    _, params = init_fn(key, (-1, 784))

    # params

    # Create and initialize an optimizer.
    opt_init, opt_apply, get_params = optimizers.sgd(FLAGS.learning_rate)
    state = opt_init(params)
    # state

    # Create an mse loss function and a gradient function.
    loss = lambda fx, y_hat: 0.5 * np.mean((fx - y_hat)**2)
    grad_loss = jit(grad(lambda params, x, y: loss(apply_fn(params, x), y)))

    # Create an MSE predictor to solve the NTK equation in function space.
    ntk = nt.batch(nt.empirical_ntk_fn(apply_fn), batch_size=4, device_count=0)
    g_dd = ntk(x_train, None, params)
    g_td = ntk(x_test, x_train, params)
    predictor = nt.predict.gradient_descent_mse(g_dd, y_train, g_td)
    # g_dd.shape

    # Get initial values of the network in function space.
    fx_train = apply_fn(params, x_train)
    fx_test = apply_fn(params, x_test)

    # Train the network.
    train_steps = int(FLAGS.train_time // FLAGS.learning_rate)
    print('Training for {} steps'.format(train_steps))

    for i in range(train_steps):
        params = get_params(state)
        state = opt_apply(i, grad_loss(params, x_train, y_train), state)

    # Get predictions from analytic computation.
    print('Computing analytic prediction.')
    # fx_train, fx_test = predictor(FLAGS.train_time, fx_train, fx_test)
    fx_train, fx_test = predictor(FLAGS.train_time, fx_train, fx_test)

    # Print out summary data comparing the linear / nonlinear model.
    util.print_summary('train', y_train, apply_fn(params, x_train), fx_train,
                       loss)
    util.print_summary('test', y_test, apply_fn(params, x_test), fx_test, loss)
Exemple #15
0
def empirical_ntk_fn_tf(
    f: Union[tf.Module, tf.types.experimental.GenericFunction],
    trace_axes: Axes = (-1,),
    diagonal_axes: Axes = (),
    vmap_axes: VMapAxes = None,
    implementation: Union[
        nt.NtkImplementation, int] = DEFAULT_NTK_IMPLEMENTATION,
    _j_rules: bool = _DEFAULT_NTK_J_RULES,
    _s_rules: bool = _DEFAULT_NTK_S_RULES,
    _fwd: Optional[bool] = _DEFAULT_NTK_FWD,
) -> Callable[..., NTTree[tf.Tensor]]:
  r"""Returns a function to draw a single sample the NTK of a given network `f`.

  This function follows the API of :obj:`neural_tangents.empirical_ntk_fn`, but
  is applicable to Tensorflow :class:`tf.Module`, :class:`tf.keras.Model`, or
  :obj:`tf.function`, via a TF->JAX->TF roundtrip using `tf2jax` and `jax2tf`.
  Docstring below adapted from :obj:`neural_tangents.empirical_ntk_fn`.

  .. warning::
    This function is highly experimental and risks returning wrong
    results or performing slowly. It is intended to demonstrate the usage of
    :obj:`neural_tangents.empirical_ntk_fn` in Tensorflow, but has not been
    extensively tested.

  TODO(romann): support proper division between trainable and non-trainable
    variables.

  TODO(romann): investigate slow compile times.

  Args:
    f:
      :class:`tf.Module` or :obj:`tf.function` whose NTK we are computing. Must
      satisfy the following:

        - if a :obj:`tf.function`, must have the signature of `f(params, x)`.

        - if a :class:`tf.Module`, must be either a :class:`tf.keras.Model`, or
          be callable.

        - input signature (`f.input_shape` for :class:`tf.Module` or
          :class:`tf.keras.Model`, or `f.input_signature` for `tf.function`)
          must be known.

    trace_axes:
      output axes to trace the output kernel over, i.e. compute only the trace
      of the covariance along the respective pair of axes (one pair for each
      axis in `trace_axes`). This allows to save space and compute if you are
      only interested in the respective trace, but also improve approximation
      accuracy if you know that covariance along these pairs of axes converges
      to a `constant * identity matrix` in the limit of interest (e.g.
      infinite width or infinite `n_samples`). A common use case is the channel
      / feature / logit axis, since activation slices along such axis are i.i.d.
      and the respective covariance along the respective pair of axes indeed
      converges to a constant-diagonal matrix in the infinite width or infinite
      `n_samples` limit.
      Also related to "contracting dimensions" in XLA terms.
      (https://www.tensorflow.org/xla/operation_semantics#dotgeneral)

    diagonal_axes:
      output axes to diagonalize the output kernel over, i.e. compute only the
      diagonal of the covariance along the respective pair of axes (one pair for
      each axis in `diagonal_axes`). This allows to save space and compute, if
      off-diagonal values along these axes are not needed, but also improve
      approximation accuracy if their limiting value is known theoretically,
      e.g. if they vanish in the limit of interest (e.g. infinite
      width or infinite `n_samples`). If you further know that on-diagonal
      values converge to the same constant in your limit of interest, you should
      specify these axes in `trace_axes` instead, to save even more compute and
      gain even more accuracy. A common use case is computing the variance
      (instead of covariance) along certain axes.
      Also related to "batch dimensions" in XLA terms.
      (https://www.tensorflow.org/xla/operation_semantics#dotgeneral)

    vmap_axes:
      A triple of `(in_axes, out_axes, kwargs_axes)`
      passed to `vmap` to evaluate the empirical NTK in parallel ove these axes.
      Precisely, providing this argument implies that `f.call(x, **kwargs)`
      equals to a concatenation along `out_axes` of `f` applied to slices of
      `x` and `**kwargs` along `in_axes` and `kwargs_axes`. In other words, it
      certifies that `f` can be evaluated as a `vmap` with `out_axes=out_axes`
      over `x` (along `in_axes`) and those arguments in `**kwargs` that are
      present in `kwargs_axes.keys()` (along `kwargs_axes.values()`).

      This allows us to evaluate Jacobians much more
      efficiently. If `vmap_axes` is not a triple, it is interpreted as
      `in_axes = out_axes = vmap_axes, kwargs_axes = {}`. For example a very
      common use case is `vmap_axes=0` for a neural network with leading (`0`)
      batch dimension, both for inputs and outputs, and no interactions between
      different elements of the batch (e.g. no BatchNorm, and, in the case of
      `nt.stax`, also no Dropout). However, if there is interaction between
      batch elements or no concept of a batch axis at all, `vmap_axes` must be
      set to `None`, to avoid wrong (and potentially silent) results.

    implementation:
      An :class:`~neural_tangents.NtkImplementation` value (or an :class:`int` 
      `0`, `1`, `2`, or `3`). See the
      :class:`~neural_tangents.NtkImplementation` docstring for details.

    _j_rules:
      Internal debugging parameter, applicable only when
      `implementation` is
      :attr:`~neural_tangents.NtkImplementation.STRUCTURED_DERIVATIVES`
      (`3`) or :attr:`~neural_tangents.NtkImplementation.AUTO` (`0`). Set to
      `True` to allow custom Jacobian rules for intermediary primitive `dy/dw`
      computations for MJJMPs (matrix-Jacobian-Jacobian-matrix products). Set
      to `False` to use JVPs or VJPs, via JAX's :obj:`jax.jacfwd` or
      :obj:`jax.jacrev`. Custom Jacobian rules (`True`) are expected to be not
      worse, and sometimes better than automated alternatives, but in case of a
      suboptimal implementation setting it to `False` could improve performance.

    _s_rules:
      Internal debugging parameter, applicable only when `implementation` is
      :attr:`~neural_tangents.NtkImplementation.STRUCTURED_DERIVATIVES` (`3`)
      or :attr:`~neural_tangents.NtkImplementation.AUTO` (`0`). Set to `True`
      to allow efficient MJJMp rules for structured `dy/dw` primitive Jacobians.
      In practice should be set to `True`, and setting it to `False` can lead to
      dramatic deterioration of performance.

    _fwd:
      Internal debugging parameter, applicable only when `implementation` is
      :attr:`~neural_tangents.NtkImplementation.STRUCTURED_DERIVATIVES` (`3`)
      or :attr:`~neural_tangents.NtkImplementation.AUTO` (`0`). Set to `True`
      to allow :obj:`jax.jvp` in intermediary primitive Jacobian `dy/dw`
      computations, `False` to always use :obj:`jax.vjp`. `None` to decide
      automatically based on input/output sizes. Applicable when
      `_j_rules=False`, or when a primitive does not have a Jacobian rule.
      Should be set to `None` for best performance.

  Returns:
    A function `ntk_fn` that computes the empirical ntk.
  """
  warnings.warn('This function is an early proof-of-concept.')

  kwargs = dict(
      trace_axes=trace_axes,
      diagonal_axes=diagonal_axes,
      vmap_axes=vmap_axes,
      implementation=implementation,
      _j_rules=_j_rules,
      _s_rules=_s_rules,
      _fwd=_fwd,
  )
  if isinstance(f, tf.Module):
    apply_fn, _ = get_apply_fn_and_params(f)

  elif isinstance(f, tf.types.experimental.GenericFunction):
    apply_fn = tf2jax.convert_functional(f, *f.input_signature)

  else:
    raise NotImplementedError(f'Got `f={f}` of unsupported type {type(f)}, '
                              f'please file a bug at '
                              f'https://github.com/google/neural-tangents.')

  ntk_fn = nt.empirical_ntk_fn(apply_fn, **kwargs)
  ntk_fn = jax2tf.convert(ntk_fn)
  ntk_fn = tf.function(ntk_fn, jit_compile=True, autograph=False)
  return ntk_fn